1 //===-- Communication.h -----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_Communication_h_
11 #define liblldb_Communication_h_
13 #include "lldb/Core/Broadcaster.h"
14 #include "lldb/Host/HostThread.h"
15 #include "lldb/Utility/Timeout.h"
16 #include "lldb/lldb-defines.h" // for DISALLOW_COPY_AND_ASSIGN
17 #include "lldb/lldb-enumerations.h" // for ConnectionStatus, FLAGS_ANONYMOU...
18 #include "lldb/lldb-forward.h" // for ConnectionSP
19 #include "lldb/lldb-types.h" // for thread_arg_t, thread_result_t
23 #include <ratio> // for micro
26 #include <stddef.h> // for size_t
27 #include <stdint.h> // for uint8_t
29 namespace lldb_private {
32 namespace lldb_private {
35 namespace lldb_private {
39 namespace lldb_private {
41 //----------------------------------------------------------------------
42 /// @class Communication Communication.h "lldb/Core/Communication.h"
43 /// @brief An abstract communications class.
45 /// Communication is an class that handles data communication
46 /// between two data sources. It uses a Connection class to do the
47 /// real communication. This approach has a couple of advantages: it
48 /// allows a single instance of this class to be used even though its
49 /// connection can change. Connections could negotiate for different
50 /// connections based on abilities like starting with Bluetooth and
51 /// negotiating up to WiFi if available. It also allows this class to be
52 /// subclassed by any interfaces that don't want to give bytes but want
53 /// to validate and give out packets. This can be done by overriding:
55 /// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
57 /// Communication inherits from Broadcaster which means it can be
58 /// used in conjunction with Listener to wait for multiple broadcaster
59 /// objects and multiple events from each of those objects.
60 /// Communication defines a set of pre-defined event bits (see
61 /// enumerations definitions that start with "eBroadcastBit" below).
63 /// There are two modes in which communications can occur:
64 /// @li single-threaded
65 /// @li multi-threaded
67 /// In single-threaded mode, all reads and writes happen synchronously
68 /// on the calling thread.
70 /// In multi-threaded mode, a read thread is spawned that continually
71 /// reads data and caches any received bytes. To start the read thread
74 /// bool Communication::StartReadThread (Error *);
76 /// If true is returned a read thread has been spawned that will
77 /// continually execute a call to the pure virtual DoRead function:
79 /// size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
81 /// When bytes are received the data gets cached in \a m_bytes and this
82 /// class will broadcast a \b eBroadcastBitReadThreadGotBytes event.
83 /// Clients that want packet based communication should override
84 /// AppendBytesToCache. The subclasses can choose to call the
85 /// built in AppendBytesToCache with the \a broadcast parameter set to
86 /// false. This will cause the \b eBroadcastBitReadThreadGotBytes event
87 /// not get broadcast, and then the subclass can post a \b
88 /// eBroadcastBitPacketAvailable event when a full packet of data has
91 /// If the connection is disconnected a \b eBroadcastBitDisconnected
92 /// event gets broadcast. If the read thread exits a \b
93 /// eBroadcastBitReadThreadDidExit event will be broadcast. Clients
94 /// can also post a \b eBroadcastBitReadThreadShouldExit event to this
95 /// object which will cause the read thread to exit.
96 //----------------------------------------------------------------------
97 class Communication : public Broadcaster {
99 FLAGS_ANONYMOUS_ENUM(){
100 eBroadcastBitDisconnected =
101 (1u << 0), ///< Sent when the communications connection is lost.
102 eBroadcastBitReadThreadGotBytes =
103 (1u << 1), ///< Sent by the read thread when bytes become available.
104 eBroadcastBitReadThreadDidExit =
106 << 2), ///< Sent by the read thread when it exits to inform clients.
107 eBroadcastBitReadThreadShouldExit =
108 (1u << 3), ///< Sent by clients that need to cancel the read thread.
109 eBroadcastBitPacketAvailable =
110 (1u << 4), ///< Sent when data received makes a complete packet.
111 eBroadcastBitNoMorePendingInput = (1u << 5), ///< Sent by the read thread
112 ///to indicate all pending
113 ///input has been processed.
114 kLoUserBroadcastBit =
115 (1u << 16), ///< Subclasses can used bits 31:16 for any needed events.
116 kHiUserBroadcastBit = (1u << 31),
117 eAllEventBits = 0xffffffff};
119 typedef void (*ReadThreadBytesReceived)(void *baton, const void *src,
122 //------------------------------------------------------------------
123 /// Construct the Communication object with the specified name for
124 /// the Broadcaster that this object inherits from.
126 /// @param[in] broadcaster_name
127 /// The name of the broadcaster object. This name should be as
128 /// complete as possible to uniquely identify this object. The
129 /// broadcaster name can be updated after the connect function
131 //------------------------------------------------------------------
132 Communication(const char *broadcaster_name);
134 //------------------------------------------------------------------
137 /// The destructor is virtual since this class gets subclassed.
138 //------------------------------------------------------------------
139 ~Communication() override;
143 //------------------------------------------------------------------
144 /// Connect using the current connection by passing \a url to its
145 /// connect function.
149 /// A string that contains all information needed by the
150 /// subclass to connect to another client.
153 /// \b True if the connect succeeded, \b false otherwise. The
154 /// internal error object should be filled in with an
155 /// appropriate value based on the result of this function.
157 /// @see Error& Communication::GetError ();
158 /// @see bool Connection::Connect (const char *url);
159 //------------------------------------------------------------------
160 lldb::ConnectionStatus Connect(const char *url, Error *error_ptr);
162 //------------------------------------------------------------------
163 /// Disconnect the communications connection if one is currently
167 /// \b True if the disconnect succeeded, \b false otherwise. The
168 /// internal error object should be filled in with an
169 /// appropriate value based on the result of this function.
171 /// @see Error& Communication::GetError ();
172 /// @see bool Connection::Disconnect ();
173 //------------------------------------------------------------------
174 lldb::ConnectionStatus Disconnect(Error *error_ptr = nullptr);
176 //------------------------------------------------------------------
177 /// Check if the connection is valid.
180 /// \b True if this object is currently connected, \b false
182 //------------------------------------------------------------------
183 bool IsConnected() const;
185 bool HasConnection() const;
187 lldb_private::Connection *GetConnection() { return m_connection_sp.get(); }
189 //------------------------------------------------------------------
190 /// Read bytes from the current connection.
192 /// If no read thread is running, this function call the
193 /// connection's Connection::Read(...) function to get any available.
195 /// If a read thread has been started, this function will check for
196 /// any cached bytes that have already been read and return any
197 /// currently available bytes. If no bytes are cached, it will wait
198 /// for the bytes to become available by listening for the \a
199 /// eBroadcastBitReadThreadGotBytes event. If this function consumes
200 /// all of the bytes in the cache, it will reset the
201 /// \a eBroadcastBitReadThreadGotBytes event bit.
204 /// A destination buffer that must be at least \a dst_len bytes
207 /// @param[in] dst_len
208 /// The number of bytes to attempt to read, and also the max
209 /// number of bytes that can be placed into \a dst.
211 /// @param[in] timeout
212 /// A timeout value or llvm::None for no timeout.
215 /// The number of bytes actually read.
217 /// @see size_t Connection::Read (void *, size_t);
218 //------------------------------------------------------------------
219 size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout,
220 lldb::ConnectionStatus &status, Error *error_ptr);
222 //------------------------------------------------------------------
223 /// The actual write function that attempts to write to the
224 /// communications protocol.
226 /// Subclasses must override this function.
229 /// A source buffer that must be at least \a src_len bytes
232 /// @param[in] src_len
233 /// The number of bytes to attempt to write, and also the
234 /// number of bytes are currently available in \a src.
237 /// The number of bytes actually Written.
238 //------------------------------------------------------------------
239 size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status,
242 //------------------------------------------------------------------
243 /// Sets the connection that it to be used by this class.
245 /// By making a communication class that uses different connections
246 /// it allows a single communication interface to negotiate and
247 /// change its connection without any interruption to the client.
248 /// It also allows the Communication class to be subclassed for
249 /// packet based communication.
251 /// @param[in] connection
252 /// A connection that this class will own and destroy.
256 //------------------------------------------------------------------
257 void SetConnection(Connection *connection);
259 //------------------------------------------------------------------
260 /// Starts a read thread whose sole purpose it to read bytes from
261 /// the current connection. This function will call connection's
264 /// size_t Connection::Read (void *, size_t);
266 /// When bytes are read and cached, this function will call:
268 /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool
271 /// Subclasses should override this function if they wish to override
272 /// the default action of caching the bytes and broadcasting a \b
273 /// eBroadcastBitReadThreadGotBytes event.
276 /// \b True if the read thread was successfully started, \b
279 /// @see size_t Connection::Read (void *, size_t);
280 /// @see void Communication::AppendBytesToCache (const uint8_t * bytes, size_t
281 /// len, bool broadcast);
282 //------------------------------------------------------------------
283 virtual bool StartReadThread(Error *error_ptr = nullptr);
285 //------------------------------------------------------------------
286 /// Stops the read thread by cancelling it.
289 /// \b True if the read thread was successfully canceled, \b
291 //------------------------------------------------------------------
292 virtual bool StopReadThread(Error *error_ptr = nullptr);
294 virtual bool JoinReadThread(Error *error_ptr = nullptr);
295 //------------------------------------------------------------------
296 /// Checks if there is a currently running read thread.
299 /// \b True if the read thread is running, \b false otherwise.
300 //------------------------------------------------------------------
301 bool ReadThreadIsRunning();
303 //------------------------------------------------------------------
304 /// The static read thread function. This function will call
305 /// the "DoRead" function continuously and wait for data to become
306 /// available. When data is received it will append the available
307 /// data to the internal cache and broadcast a
308 /// \b eBroadcastBitReadThreadGotBytes event.
310 /// @param[in] comm_ptr
311 /// A pointer to an instance of this class.
316 /// @see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
317 //------------------------------------------------------------------
318 static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr);
320 void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,
321 void *callback_baton);
323 //------------------------------------------------------------------
324 /// Wait for the read thread to process all outstanding data.
326 /// After this function returns, the read thread has processed all data that
327 /// has been waiting in the Connection queue.
329 //------------------------------------------------------------------
330 void SynchronizeWithReadThread();
332 static const char *ConnectionStatusAsCString(lldb::ConnectionStatus status);
334 bool GetCloseOnEOF() const { return m_close_on_eof; }
336 void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
338 static ConstString &GetStaticBroadcasterClass();
340 ConstString &GetBroadcasterClass() const override {
341 return GetStaticBroadcasterClass();
345 lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use
346 ///by this communications class.
347 HostThread m_read_thread; ///< The read thread handle in case we need to
348 ///cancel the thread.
349 std::atomic<bool> m_read_thread_enabled;
350 std::atomic<bool> m_read_thread_did_exit;
352 m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
353 std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded
354 ///access to the cached bytes.
356 m_write_mutex; ///< Don't let multiple threads write at the same time...
357 std::mutex m_synchronize_mutex;
358 ReadThreadBytesReceived m_callback;
359 void *m_callback_baton;
362 size_t ReadFromConnection(void *dst, size_t dst_len,
363 const Timeout<std::micro> &timeout,
364 lldb::ConnectionStatus &status, Error *error_ptr);
366 //------------------------------------------------------------------
367 /// Append new bytes that get read from the read thread into the
368 /// internal object byte cache. This will cause a \b
369 /// eBroadcastBitReadThreadGotBytes event to be broadcast if \a
370 /// broadcast is true.
372 /// Subclasses can override this function in order to inspect the
373 /// received data and check if a packet is available.
375 /// Subclasses can also still call this function from the
376 /// overridden method to allow the caching to correctly happen and
377 /// suppress the broadcasting of the \a eBroadcastBitReadThreadGotBytes
378 /// event by setting \a broadcast to false.
381 /// A source buffer that must be at least \a src_len bytes
384 /// @param[in] src_len
385 /// The number of bytes to append to the cache.
386 //------------------------------------------------------------------
387 virtual void AppendBytesToCache(const uint8_t *src, size_t src_len,
389 lldb::ConnectionStatus status);
391 //------------------------------------------------------------------
392 /// Get any available bytes from our data cache. If this call
393 /// empties the data cache, the \b eBroadcastBitReadThreadGotBytes event
394 /// will be reset to signify no more bytes are available.
397 /// A destination buffer that must be at least \a dst_len bytes
400 /// @param[in] dst_len
401 /// The number of bytes to attempt to read from the cache,
402 /// and also the max number of bytes that can be placed into
406 /// The number of bytes extracted from the data cache.
407 //------------------------------------------------------------------
408 size_t GetCachedBytes(void *dst, size_t dst_len);
411 DISALLOW_COPY_AND_ASSIGN(Communication);
414 } // namespace lldb_private
416 #endif // liblldb_Communication_h_