1 //===-- Communication.h -----------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef liblldb_Communication_h_
10 #define liblldb_Communication_h_
12 #include "lldb/Host/HostThread.h"
13 #include "lldb/Utility/Broadcaster.h"
14 #include "lldb/Utility/Timeout.h"
15 #include "lldb/lldb-defines.h"
16 #include "lldb/lldb-enumerations.h"
17 #include "lldb/lldb-forward.h"
18 #include "lldb/lldb-types.h"
28 namespace lldb_private {
33 /// \class Communication Communication.h "lldb/Core/Communication.h" An
34 /// abstract communications class.
36 /// Communication is an class that handles data communication between two data
37 /// sources. It uses a Connection class to do the real communication. This
38 /// approach has a couple of advantages: it allows a single instance of this
39 /// class to be used even though its connection can change. Connections could
40 /// negotiate for different connections based on abilities like starting with
41 /// Bluetooth and negotiating up to WiFi if available. It also allows this
42 /// class to be subclassed by any interfaces that don't want to give bytes but
43 /// want to validate and give out packets. This can be done by overriding:
45 /// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
47 /// Communication inherits from Broadcaster which means it can be used in
48 /// conjunction with Listener to wait for multiple broadcaster objects and
49 /// multiple events from each of those objects. Communication defines a set of
50 /// pre-defined event bits (see enumerations definitions that start with
51 /// "eBroadcastBit" below).
53 /// There are two modes in which communications can occur:
54 /// \li single-threaded
55 /// \li multi-threaded
57 /// In single-threaded mode, all reads and writes happen synchronously on the
60 /// In multi-threaded mode, a read thread is spawned that continually reads
61 /// data and caches any received bytes. To start the read thread clients call:
63 /// bool Communication::StartReadThread (Status *);
65 /// If true is returned a read thread has been spawned that will continually
66 /// execute a call to the pure virtual DoRead function:
68 /// size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
70 /// When bytes are received the data gets cached in \a m_bytes and this class
71 /// will broadcast a \b eBroadcastBitReadThreadGotBytes event. Clients that
72 /// want packet based communication should override AppendBytesToCache. The
73 /// subclasses can choose to call the built in AppendBytesToCache with the \a
74 /// broadcast parameter set to false. This will cause the \b
75 /// eBroadcastBitReadThreadGotBytes event not get broadcast, and then the
76 /// subclass can post a \b eBroadcastBitPacketAvailable event when a full
77 /// packet of data has been received.
79 /// If the connection is disconnected a \b eBroadcastBitDisconnected event
80 /// gets broadcast. If the read thread exits a \b
81 /// eBroadcastBitReadThreadDidExit event will be broadcast. Clients can also
82 /// post a \b eBroadcastBitReadThreadShouldExit event to this object which
83 /// will cause the read thread to exit.
84 class Communication : public Broadcaster {
86 FLAGS_ANONYMOUS_ENUM(){
87 eBroadcastBitDisconnected =
88 (1u << 0), ///< Sent when the communications connection is lost.
89 eBroadcastBitReadThreadGotBytes =
90 (1u << 1), ///< Sent by the read thread when bytes become available.
91 eBroadcastBitReadThreadDidExit =
93 << 2), ///< Sent by the read thread when it exits to inform clients.
94 eBroadcastBitReadThreadShouldExit =
95 (1u << 3), ///< Sent by clients that need to cancel the read thread.
96 eBroadcastBitPacketAvailable =
97 (1u << 4), ///< Sent when data received makes a complete packet.
98 eBroadcastBitNoMorePendingInput = (1u << 5), ///< Sent by the read thread
99 ///to indicate all pending
100 ///input has been processed.
101 kLoUserBroadcastBit =
102 (1u << 16), ///< Subclasses can used bits 31:16 for any needed events.
103 kHiUserBroadcastBit = (1u << 31),
104 eAllEventBits = 0xffffffff};
106 typedef void (*ReadThreadBytesReceived)(void *baton, const void *src,
109 /// Construct the Communication object with the specified name for the
110 /// Broadcaster that this object inherits from.
112 /// \param[in] broadcaster_name
113 /// The name of the broadcaster object. This name should be as
114 /// complete as possible to uniquely identify this object. The
115 /// broadcaster name can be updated after the connect function
117 Communication(const char *broadcaster_name);
121 /// The destructor is virtual since this class gets subclassed.
122 ~Communication() override;
126 /// Connect using the current connection by passing \a url to its connect
127 /// function. string.
130 /// A string that contains all information needed by the
131 /// subclass to connect to another client.
134 /// \b True if the connect succeeded, \b false otherwise. The
135 /// internal error object should be filled in with an
136 /// appropriate value based on the result of this function.
138 /// \see Status& Communication::GetError ();
139 /// \see bool Connection::Connect (const char *url);
140 lldb::ConnectionStatus Connect(const char *url, Status *error_ptr);
142 /// Disconnect the communications connection if one is currently connected.
145 /// \b True if the disconnect succeeded, \b false otherwise. The
146 /// internal error object should be filled in with an
147 /// appropriate value based on the result of this function.
149 /// \see Status& Communication::GetError ();
150 /// \see bool Connection::Disconnect ();
151 lldb::ConnectionStatus Disconnect(Status *error_ptr = nullptr);
153 /// Check if the connection is valid.
156 /// \b True if this object is currently connected, \b false
158 bool IsConnected() const;
160 bool HasConnection() const;
162 lldb_private::Connection *GetConnection() { return m_connection_sp.get(); }
164 /// Read bytes from the current connection.
166 /// If no read thread is running, this function call the connection's
167 /// Connection::Read(...) function to get any available.
169 /// If a read thread has been started, this function will check for any
170 /// cached bytes that have already been read and return any currently
171 /// available bytes. If no bytes are cached, it will wait for the bytes to
172 /// become available by listening for the \a eBroadcastBitReadThreadGotBytes
173 /// event. If this function consumes all of the bytes in the cache, it will
174 /// reset the \a eBroadcastBitReadThreadGotBytes event bit.
177 /// A destination buffer that must be at least \a dst_len bytes
180 /// \param[in] dst_len
181 /// The number of bytes to attempt to read, and also the max
182 /// number of bytes that can be placed into \a dst.
184 /// \param[in] timeout
185 /// A timeout value or llvm::None for no timeout.
188 /// The number of bytes actually read.
190 /// \see size_t Connection::Read (void *, size_t);
191 size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout,
192 lldb::ConnectionStatus &status, Status *error_ptr);
194 /// The actual write function that attempts to write to the communications
197 /// Subclasses must override this function.
200 /// A source buffer that must be at least \a src_len bytes
203 /// \param[in] src_len
204 /// The number of bytes to attempt to write, and also the
205 /// number of bytes are currently available in \a src.
208 /// The number of bytes actually Written.
209 size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status,
212 /// Sets the connection that it to be used by this class.
214 /// By making a communication class that uses different connections it
215 /// allows a single communication interface to negotiate and change its
216 /// connection without any interruption to the client. It also allows the
217 /// Communication class to be subclassed for packet based communication.
219 /// \param[in] connection
220 /// A connection that this class will own and destroy.
224 void SetConnection(Connection *connection);
226 /// Starts a read thread whose sole purpose it to read bytes from the
227 /// current connection. This function will call connection's read function:
229 /// size_t Connection::Read (void *, size_t);
231 /// When bytes are read and cached, this function will call:
233 /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len,
237 /// Subclasses should override this function if they wish to override the
238 /// default action of caching the bytes and broadcasting a \b
239 /// eBroadcastBitReadThreadGotBytes event.
242 /// \b True if the read thread was successfully started, \b
245 /// \see size_t Connection::Read (void *, size_t);
246 /// \see void Communication::AppendBytesToCache (const uint8_t * bytes,
247 /// size_t len, bool broadcast);
248 virtual bool StartReadThread(Status *error_ptr = nullptr);
250 /// Stops the read thread by cancelling it.
253 /// \b True if the read thread was successfully canceled, \b
255 virtual bool StopReadThread(Status *error_ptr = nullptr);
257 virtual bool JoinReadThread(Status *error_ptr = nullptr);
258 /// Checks if there is a currently running read thread.
261 /// \b True if the read thread is running, \b false otherwise.
262 bool ReadThreadIsRunning();
264 /// The static read thread function. This function will call the "DoRead"
265 /// function continuously and wait for data to become available. When data
266 /// is received it will append the available data to the internal cache and
267 /// broadcast a \b eBroadcastBitReadThreadGotBytes event.
269 /// \param[in] comm_ptr
270 /// A pointer to an instance of this class.
275 /// \see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
276 static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr);
278 void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,
279 void *callback_baton);
281 /// Wait for the read thread to process all outstanding data.
283 /// After this function returns, the read thread has processed all data that
284 /// has been waiting in the Connection queue.
286 void SynchronizeWithReadThread();
288 static const char *ConnectionStatusAsCString(lldb::ConnectionStatus status);
290 bool GetCloseOnEOF() const { return m_close_on_eof; }
292 void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
294 static ConstString &GetStaticBroadcasterClass();
296 ConstString &GetBroadcasterClass() const override {
297 return GetStaticBroadcasterClass();
301 lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use
302 ///by this communications class.
303 HostThread m_read_thread; ///< The read thread handle in case we need to
304 ///cancel the thread.
305 std::atomic<bool> m_read_thread_enabled;
306 std::atomic<bool> m_read_thread_did_exit;
308 m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
309 std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded
310 ///access to the cached bytes.
312 m_write_mutex; ///< Don't let multiple threads write at the same time...
313 std::mutex m_synchronize_mutex;
314 ReadThreadBytesReceived m_callback;
315 void *m_callback_baton;
318 size_t ReadFromConnection(void *dst, size_t dst_len,
319 const Timeout<std::micro> &timeout,
320 lldb::ConnectionStatus &status, Status *error_ptr);
322 /// Append new bytes that get read from the read thread into the internal
323 /// object byte cache. This will cause a \b eBroadcastBitReadThreadGotBytes
324 /// event to be broadcast if \a broadcast is true.
326 /// Subclasses can override this function in order to inspect the received
327 /// data and check if a packet is available.
329 /// Subclasses can also still call this function from the overridden method
330 /// to allow the caching to correctly happen and suppress the broadcasting
331 /// of the \a eBroadcastBitReadThreadGotBytes event by setting \a broadcast
335 /// A source buffer that must be at least \a src_len bytes
338 /// \param[in] src_len
339 /// The number of bytes to append to the cache.
340 virtual void AppendBytesToCache(const uint8_t *src, size_t src_len,
342 lldb::ConnectionStatus status);
344 /// Get any available bytes from our data cache. If this call empties the
345 /// data cache, the \b eBroadcastBitReadThreadGotBytes event will be reset
346 /// to signify no more bytes are available.
349 /// A destination buffer that must be at least \a dst_len bytes
352 /// \param[in] dst_len
353 /// The number of bytes to attempt to read from the cache,
354 /// and also the max number of bytes that can be placed into
358 /// The number of bytes extracted from the data cache.
359 size_t GetCachedBytes(void *dst, size_t dst_len);
362 DISALLOW_COPY_AND_ASSIGN(Communication);
365 } // namespace lldb_private
367 #endif // liblldb_Communication_h_