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_
19 // Other libraries and framework includes
21 #include "lldb/lldb-private.h"
22 #include "lldb/Core/Broadcaster.h"
23 #include "lldb/Core/Error.h"
24 #include "lldb/Host/HostThread.h"
25 #include "lldb/lldb-private.h"
27 namespace lldb_private {
29 //----------------------------------------------------------------------
30 /// @class Communication Communication.h "lldb/Core/Communication.h"
31 /// @brief An abstract communications class.
33 /// Communication is an class that handles data communication
34 /// between two data sources. It uses a Connection class to do the
35 /// real communication. This approach has a couple of advantages: it
36 /// allows a single instance of this class to be used even though its
37 /// connection can change. Connections could negotiate for different
38 /// connections based on abilities like starting with Bluetooth and
39 /// negotiating up to WiFi if available. It also allows this class to be
40 /// subclassed by any interfaces that don't want to give bytes but want
41 /// to validate and give out packets. This can be done by overriding:
43 /// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
45 /// Communication inherits from Broadcaster which means it can be
46 /// used in conjunction with Listener to wait for multiple broadcaster
47 /// objects and multiple events from each of those objects.
48 /// Communication defines a set of pre-defined event bits (see
49 /// enumerations definitions that start with "eBroadcastBit" below).
51 /// There are two modes in which communications can occur:
52 /// @li single-threaded
53 /// @li multi-threaded
55 /// In single-threaded mode, all reads and writes happen synchronously
56 /// on the calling thread.
58 /// In multi-threaded mode, a read thread is spawned that continually
59 /// reads data and caches any received bytes. To start the read thread
62 /// bool Communication::StartReadThread (Error *);
64 /// If true is returned a read thread has been spawned that will
65 /// continually execute a call to the pure virtual DoRead function:
67 /// size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
69 /// When bytes are received the data gets cached in \a m_bytes and this
70 /// class will broadcast a \b eBroadcastBitReadThreadGotBytes event.
71 /// Clients that want packet based communication should override
72 /// AppendBytesToCache. The subclasses can choose to call the
73 /// built in AppendBytesToCache with the \a broadcast parameter set to
74 /// false. This will cause the \b eBroadcastBitReadThreadGotBytes event
75 /// not get broadcast, and then the subclass can post a \b
76 /// eBroadcastBitPacketAvailable event when a full packet of data has
79 /// If the connection is disconnected a \b eBroadcastBitDisconnected
80 /// event gets broadcast. If the read thread exits a \b
81 /// eBroadcastBitReadThreadDidExit event will be broadcast. Clients
82 /// can also post a \b eBroadcastBitReadThreadShouldExit event to this
83 /// object which will cause the read thread to exit.
84 //----------------------------------------------------------------------
85 class Communication : public Broadcaster
88 FLAGS_ANONYMOUS_ENUM()
90 eBroadcastBitDisconnected = (1u << 0), ///< Sent when the communications connection is lost.
91 eBroadcastBitReadThreadGotBytes = (1u << 1), ///< Sent by the read thread when bytes become available.
92 eBroadcastBitReadThreadDidExit = (1u << 2), ///< Sent by the read thread when it exits to inform clients.
93 eBroadcastBitReadThreadShouldExit = (1u << 3), ///< Sent by clients that need to cancel the read thread.
94 eBroadcastBitPacketAvailable = (1u << 4), ///< Sent when data received makes a complete packet.
95 eBroadcastBitNoMorePendingInput = (1u << 5), ///< Sent by the read thread to indicate all pending input has been processed.
96 kLoUserBroadcastBit = (1u << 16),///< Subclasses can used bits 31:16 for any needed events.
97 kHiUserBroadcastBit = (1u << 31),
98 eAllEventBits = 0xffffffff
101 typedef void (*ReadThreadBytesReceived) (void *baton, const void *src, size_t src_len);
103 //------------------------------------------------------------------
104 /// Construct the Communication object with the specified name for
105 /// the Broadcaster that this object inherits from.
107 /// @param[in] broadcaster_name
108 /// The name of the broadcaster object. This name should be as
109 /// complete as possible to uniquely identify this object. The
110 /// broadcaster name can be updated after the connect function
112 //------------------------------------------------------------------
113 Communication(const char * broadcaster_name);
115 //------------------------------------------------------------------
118 /// The destructor is virtual since this class gets subclassed.
119 //------------------------------------------------------------------
120 ~Communication() override;
125 //------------------------------------------------------------------
126 /// Connect using the current connection by passing \a url to its
127 /// connect function.
131 /// A string that contains all information needed by the
132 /// subclass to connect to another client.
135 /// \b True if the connect succeeded, \b false otherwise. The
136 /// internal error object should be filled in with an
137 /// appropriate value based on the result of this function.
139 /// @see Error& Communication::GetError ();
140 /// @see bool Connection::Connect (const char *url);
141 //------------------------------------------------------------------
142 lldb::ConnectionStatus
143 Connect (const char *url, Error *error_ptr);
145 //------------------------------------------------------------------
146 /// Disconnect the communications connection if one is currently
150 /// \b True if the disconnect succeeded, \b false otherwise. The
151 /// internal error object should be filled in with an
152 /// appropriate value based on the result of this function.
154 /// @see Error& Communication::GetError ();
155 /// @see bool Connection::Disconnect ();
156 //------------------------------------------------------------------
157 lldb::ConnectionStatus
158 Disconnect(Error *error_ptr = nullptr);
160 //------------------------------------------------------------------
161 /// Check if the connection is valid.
164 /// \b True if this object is currently connected, \b false
166 //------------------------------------------------------------------
168 IsConnected () const;
171 HasConnection () const;
173 lldb_private::Connection *
176 return m_connection_sp.get();
179 //------------------------------------------------------------------
180 /// Read bytes from the current connection.
182 /// If no read thread is running, this function call the
183 /// connection's Connection::Read(...) function to get any available.
185 /// If a read thread has been started, this function will check for
186 /// any cached bytes that have already been read and return any
187 /// currently available bytes. If no bytes are cached, it will wait
188 /// for the bytes to become available by listening for the \a
189 /// eBroadcastBitReadThreadGotBytes event. If this function consumes
190 /// all of the bytes in the cache, it will reset the
191 /// \a eBroadcastBitReadThreadGotBytes event bit.
194 /// A destination buffer that must be at least \a dst_len bytes
197 /// @param[in] dst_len
198 /// The number of bytes to attempt to read, and also the max
199 /// number of bytes that can be placed into \a dst.
201 /// @param[in] timeout_usec
202 /// A timeout value in micro-seconds.
205 /// The number of bytes actually read.
207 /// @see size_t Connection::Read (void *, size_t);
208 //------------------------------------------------------------------
212 uint32_t timeout_usec,
213 lldb::ConnectionStatus &status,
216 //------------------------------------------------------------------
217 /// The actual write function that attempts to write to the
218 /// communications protocol.
220 /// Subclasses must override this function.
223 /// A source buffer that must be at least \a src_len bytes
226 /// @param[in] src_len
227 /// The number of bytes to attempt to write, and also the
228 /// number of bytes are currently available in \a src.
231 /// The number of bytes actually Written.
232 //------------------------------------------------------------------
234 Write (const void *src,
236 lldb::ConnectionStatus &status,
239 //------------------------------------------------------------------
240 /// Sets the connection that it to be used by this class.
242 /// By making a communication class that uses different connections
243 /// it allows a single communication interface to negotiate and
244 /// change its connection without any interruption to the client.
245 /// It also allows the Communication class to be subclassed for
246 /// packet based communication.
248 /// @param[in] connection
249 /// A connection that this class will own and destroy.
253 //------------------------------------------------------------------
255 SetConnection (Connection *connection);
257 //------------------------------------------------------------------
258 /// Starts a read thread whose sole purpose it to read bytes from
259 /// the current connection. This function will call connection's
262 /// size_t Connection::Read (void *, size_t);
264 /// When bytes are read and cached, this function will call:
266 /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast);
268 /// Subclasses should override this function if they wish to override
269 /// the default action of caching the bytes and broadcasting a \b
270 /// eBroadcastBitReadThreadGotBytes event.
273 /// \b True if the read thread was successfully started, \b
276 /// @see size_t Connection::Read (void *, size_t);
277 /// @see void Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast);
278 //------------------------------------------------------------------
280 StartReadThread(Error *error_ptr = nullptr);
282 //------------------------------------------------------------------
283 /// Stops the read thread by cancelling it.
286 /// \b True if the read thread was successfully canceled, \b
288 //------------------------------------------------------------------
290 StopReadThread(Error *error_ptr = nullptr);
293 JoinReadThread(Error *error_ptr = nullptr);
294 //------------------------------------------------------------------
295 /// Checks if there is a currently running read thread.
298 /// \b True if the read thread is running, \b false otherwise.
299 //------------------------------------------------------------------
301 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
319 ReadThread (lldb::thread_arg_t comm_ptr);
322 SetReadThreadBytesReceivedCallback (ReadThreadBytesReceived callback,
323 void *callback_baton);
325 //------------------------------------------------------------------
326 /// Wait for the read thread to process all outstanding data.
328 /// After this function returns, the read thread has processed all data that
329 /// has been waiting in the Connection queue.
331 //------------------------------------------------------------------
332 void SynchronizeWithReadThread ();
335 ConnectionStatusAsCString (lldb::ConnectionStatus status);
338 GetCloseOnEOF () const
340 return m_close_on_eof;
344 SetCloseOnEOF (bool b)
349 static ConstString &GetStaticBroadcasterClass ();
351 ConstString &GetBroadcasterClass() const override
353 return GetStaticBroadcasterClass();
357 lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use by this communications class.
358 HostThread m_read_thread; ///< The read thread handle in case we need to cancel the thread.
359 std::atomic<bool> m_read_thread_enabled;
360 std::atomic<bool> m_read_thread_did_exit;
361 std::string m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
362 std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded access to the cached bytes.
363 std::mutex m_write_mutex; ///< Don't let multiple threads write at the same time...
364 std::mutex m_synchronize_mutex;
365 ReadThreadBytesReceived m_callback;
366 void *m_callback_baton;
370 ReadFromConnection (void *dst,
372 uint32_t timeout_usec,
373 lldb::ConnectionStatus &status,
376 //------------------------------------------------------------------
377 /// Append new bytes that get read from the read thread into the
378 /// internal object byte cache. This will cause a \b
379 /// eBroadcastBitReadThreadGotBytes event to be broadcast if \a
380 /// broadcast is true.
382 /// Subclasses can override this function in order to inspect the
383 /// received data and check if a packet is available.
385 /// Subclasses can also still call this function from the
386 /// overridden method to allow the caching to correctly happen and
387 /// suppress the broadcasting of the \a eBroadcastBitReadThreadGotBytes
388 /// event by setting \a broadcast to false.
391 /// A source buffer that must be at least \a src_len bytes
394 /// @param[in] src_len
395 /// The number of bytes to append to the cache.
396 //------------------------------------------------------------------
398 AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast, lldb::ConnectionStatus status);
400 //------------------------------------------------------------------
401 /// Get any available bytes from our data cache. If this call
402 /// empties the data cache, the \b eBroadcastBitReadThreadGotBytes event
403 /// will be reset to signify no more bytes are available.
406 /// A destination buffer that must be at least \a dst_len bytes
409 /// @param[in] dst_len
410 /// The number of bytes to attempt to read from the cache,
411 /// and also the max number of bytes that can be placed into
415 /// The number of bytes extracted from the data cache.
416 //------------------------------------------------------------------
418 GetCachedBytes (void *dst, size_t dst_len);
421 DISALLOW_COPY_AND_ASSIGN (Communication);
424 } // namespace lldb_private
426 #endif // liblldb_Communication_h_