LLDB  mainline
Communication.h
Go to the documentation of this file.
1 //===-- Communication.h -----------------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_Communication_h_
10 #define liblldb_Communication_h_
11 
12 #include "lldb/Host/HostThread.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"
19 
20 #include <atomic>
21 #include <mutex>
22 #include <ratio>
23 #include <string>
24 
25 #include <stddef.h>
26 #include <stdint.h>
27 
28 namespace lldb_private {
29 class Connection;
30 }
31 namespace lldb_private {
32 class ConstString;
33 }
34 namespace lldb_private {
35 class Status;
36 }
37 
38 namespace lldb_private {
39 
40 /// \class Communication Communication.h "lldb/Core/Communication.h" An
41 /// abstract communications class.
42 ///
43 /// Communication is an class that handles data communication between two data
44 /// sources. It uses a Connection class to do the real communication. This
45 /// approach has a couple of advantages: it allows a single instance of this
46 /// class to be used even though its connection can change. Connections could
47 /// negotiate for different connections based on abilities like starting with
48 /// Bluetooth and negotiating up to WiFi if available. It also allows this
49 /// class to be subclassed by any interfaces that don't want to give bytes but
50 /// want to validate and give out packets. This can be done by overriding:
51 ///
52 /// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
53 ///
54 /// Communication inherits from Broadcaster which means it can be used in
55 /// conjunction with Listener to wait for multiple broadcaster objects and
56 /// multiple events from each of those objects. Communication defines a set of
57 /// pre-defined event bits (see enumerations definitions that start with
58 /// "eBroadcastBit" below).
59 ///
60 /// There are two modes in which communications can occur:
61 /// \li single-threaded
62 /// \li multi-threaded
63 ///
64 /// In single-threaded mode, all reads and writes happen synchronously on the
65 /// calling thread.
66 ///
67 /// In multi-threaded mode, a read thread is spawned that continually reads
68 /// data and caches any received bytes. To start the read thread clients call:
69 ///
70 /// bool Communication::StartReadThread (Status *);
71 ///
72 /// If true is returned a read thread has been spawned that will continually
73 /// execute a call to the pure virtual DoRead function:
74 ///
75 /// size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
76 ///
77 /// When bytes are received the data gets cached in \a m_bytes and this class
78 /// will broadcast a \b eBroadcastBitReadThreadGotBytes event. Clients that
79 /// want packet based communication should override AppendBytesToCache. The
80 /// subclasses can choose to call the built in AppendBytesToCache with the \a
81 /// broadcast parameter set to false. This will cause the \b
82 /// eBroadcastBitReadThreadGotBytes event not get broadcast, and then the
83 /// subclass can post a \b eBroadcastBitPacketAvailable event when a full
84 /// packet of data has been received.
85 ///
86 /// If the connection is disconnected a \b eBroadcastBitDisconnected event
87 /// gets broadcast. If the read thread exits a \b
88 /// eBroadcastBitReadThreadDidExit event will be broadcast. Clients can also
89 /// post a \b eBroadcastBitReadThreadShouldExit event to this object which
90 /// will cause the read thread to exit.
91 class Communication : public Broadcaster {
92 public:
94  eBroadcastBitDisconnected =
95  (1u << 0), ///< Sent when the communications connection is lost.
96  eBroadcastBitReadThreadGotBytes =
97  (1u << 1), ///< Sent by the read thread when bytes become available.
98  eBroadcastBitReadThreadDidExit =
99  (1u
100  << 2), ///< Sent by the read thread when it exits to inform clients.
101  eBroadcastBitReadThreadShouldExit =
102  (1u << 3), ///< Sent by clients that need to cancel the read thread.
103  eBroadcastBitPacketAvailable =
104  (1u << 4), ///< Sent when data received makes a complete packet.
105  eBroadcastBitNoMorePendingInput = (1u << 5), ///< Sent by the read thread
106  ///to indicate all pending
107  ///input has been processed.
108  kLoUserBroadcastBit =
109  (1u << 16), ///< Subclasses can used bits 31:16 for any needed events.
110  kHiUserBroadcastBit = (1u << 31),
111  eAllEventBits = 0xffffffff};
112 
113  typedef void (*ReadThreadBytesReceived)(void *baton, const void *src,
114  size_t src_len);
115 
116  /// Construct the Communication object with the specified name for the
117  /// Broadcaster that this object inherits from.
118  ///
119  /// \param[in] broadcaster_name
120  /// The name of the broadcaster object. This name should be as
121  /// complete as possible to uniquely identify this object. The
122  /// broadcaster name can be updated after the connect function
123  /// is called.
124  Communication(const char *broadcaster_name);
125 
126  /// Destructor.
127  ///
128  /// The destructor is virtual since this class gets subclassed.
129  ~Communication() override;
130 
131  void Clear();
132 
133  /// Connect using the current connection by passing \a url to its connect
134  /// function. string.
135  ///
136  /// \param[in] url
137  /// A string that contains all information needed by the
138  /// subclass to connect to another client.
139  ///
140  /// \return
141  /// \b True if the connect succeeded, \b false otherwise. The
142  /// internal error object should be filled in with an
143  /// appropriate value based on the result of this function.
144  ///
145  /// \see Status& Communication::GetError ();
146  /// \see bool Connection::Connect (const char *url);
147  lldb::ConnectionStatus Connect(const char *url, Status *error_ptr);
148 
149  /// Disconnect the communications connection if one is currently connected.
150  ///
151  /// \return
152  /// \b True if the disconnect succeeded, \b false otherwise. The
153  /// internal error object should be filled in with an
154  /// appropriate value based on the result of this function.
155  ///
156  /// \see Status& Communication::GetError ();
157  /// \see bool Connection::Disconnect ();
158  lldb::ConnectionStatus Disconnect(Status *error_ptr = nullptr);
159 
160  /// Check if the connection is valid.
161  ///
162  /// \return
163  /// \b True if this object is currently connected, \b false
164  /// otherwise.
165  bool IsConnected() const;
166 
167  bool HasConnection() const;
168 
170 
171  /// Read bytes from the current connection.
172  ///
173  /// If no read thread is running, this function call the connection's
174  /// Connection::Read(...) function to get any available.
175  ///
176  /// If a read thread has been started, this function will check for any
177  /// cached bytes that have already been read and return any currently
178  /// available bytes. If no bytes are cached, it will wait for the bytes to
179  /// become available by listening for the \a eBroadcastBitReadThreadGotBytes
180  /// event. If this function consumes all of the bytes in the cache, it will
181  /// reset the \a eBroadcastBitReadThreadGotBytes event bit.
182  ///
183  /// \param[in] dst
184  /// A destination buffer that must be at least \a dst_len bytes
185  /// long.
186  ///
187  /// \param[in] dst_len
188  /// The number of bytes to attempt to read, and also the max
189  /// number of bytes that can be placed into \a dst.
190  ///
191  /// \param[in] timeout
192  /// A timeout value or llvm::None for no timeout.
193  ///
194  /// \return
195  /// The number of bytes actually read.
196  ///
197  /// \see size_t Connection::Read (void *, size_t);
198  size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout,
199  lldb::ConnectionStatus &status, Status *error_ptr);
200 
201  /// The actual write function that attempts to write to the communications
202  /// protocol.
203  ///
204  /// Subclasses must override this function.
205  ///
206  /// \param[in] src
207  /// A source buffer that must be at least \a src_len bytes
208  /// long.
209  ///
210  /// \param[in] src_len
211  /// The number of bytes to attempt to write, and also the
212  /// number of bytes are currently available in \a src.
213  ///
214  /// \return
215  /// The number of bytes actually Written.
216  size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status,
217  Status *error_ptr);
218 
219  /// Sets the connection that it to be used by this class.
220  ///
221  /// By making a communication class that uses different connections it
222  /// allows a single communication interface to negotiate and change its
223  /// connection without any interruption to the client. It also allows the
224  /// Communication class to be subclassed for packet based communication.
225  ///
226  /// \param[in] connection
227  /// A connection that this class will own and destroy.
228  ///
229  /// \see
230  /// class Connection
231  void SetConnection(Connection *connection);
232 
233  /// Starts a read thread whose sole purpose it to read bytes from the
234  /// current connection. This function will call connection's read function:
235  ///
236  /// size_t Connection::Read (void *, size_t);
237  ///
238  /// When bytes are read and cached, this function will call:
239  ///
240  /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len,
241  /// bool
242  /// broadcast);
243  ///
244  /// Subclasses should override this function if they wish to override the
245  /// default action of caching the bytes and broadcasting a \b
246  /// eBroadcastBitReadThreadGotBytes event.
247  ///
248  /// \return
249  /// \b True if the read thread was successfully started, \b
250  /// false otherwise.
251  ///
252  /// \see size_t Connection::Read (void *, size_t);
253  /// \see void Communication::AppendBytesToCache (const uint8_t * bytes,
254  /// size_t len, bool broadcast);
255  virtual bool StartReadThread(Status *error_ptr = nullptr);
256 
257  /// Stops the read thread by cancelling it.
258  ///
259  /// \return
260  /// \b True if the read thread was successfully canceled, \b
261  /// false otherwise.
262  virtual bool StopReadThread(Status *error_ptr = nullptr);
263 
264  virtual bool JoinReadThread(Status *error_ptr = nullptr);
265  /// Checks if there is a currently running read thread.
266  ///
267  /// \return
268  /// \b True if the read thread is running, \b false otherwise.
269  bool ReadThreadIsRunning();
270 
271  /// The static read thread function. This function will call the "DoRead"
272  /// function continuously and wait for data to become available. When data
273  /// is received it will append the available data to the internal cache and
274  /// broadcast a \b eBroadcastBitReadThreadGotBytes event.
275  ///
276  /// \param[in] comm_ptr
277  /// A pointer to an instance of this class.
278  ///
279  /// \return
280  /// \b NULL.
281  ///
282  /// \see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
284 
286  void *callback_baton);
287 
288  /// Wait for the read thread to process all outstanding data.
289  ///
290  /// After this function returns, the read thread has processed all data that
291  /// has been waiting in the Connection queue.
292  ///
294 
295  static const char *ConnectionStatusAsCString(lldb::ConnectionStatus status);
296 
297  bool GetCloseOnEOF() const { return m_close_on_eof; }
298 
299  void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
300 
302 
303  ConstString &GetBroadcasterClass() const override {
304  return GetStaticBroadcasterClass();
305  }
306 
307 protected:
308  lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use
309  ///by this communications class.
310  HostThread m_read_thread; ///< The read thread handle in case we need to
311  ///cancel the thread.
312  std::atomic<bool> m_read_thread_enabled;
313  std::atomic<bool> m_read_thread_did_exit;
314  std::string
315  m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
316  std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded
317  ///access to the cached bytes.
318  std::mutex
319  m_write_mutex; ///< Don't let multiple threads write at the same time...
324 
325  size_t ReadFromConnection(void *dst, size_t dst_len,
326  const Timeout<std::micro> &timeout,
327  lldb::ConnectionStatus &status, Status *error_ptr);
328 
329  /// Append new bytes that get read from the read thread into the internal
330  /// object byte cache. This will cause a \b eBroadcastBitReadThreadGotBytes
331  /// event to be broadcast if \a broadcast is true.
332  ///
333  /// Subclasses can override this function in order to inspect the received
334  /// data and check if a packet is available.
335  ///
336  /// Subclasses can also still call this function from the overridden method
337  /// to allow the caching to correctly happen and suppress the broadcasting
338  /// of the \a eBroadcastBitReadThreadGotBytes event by setting \a broadcast
339  /// to false.
340  ///
341  /// \param[in] src
342  /// A source buffer that must be at least \a src_len bytes
343  /// long.
344  ///
345  /// \param[in] src_len
346  /// The number of bytes to append to the cache.
347  virtual void AppendBytesToCache(const uint8_t *src, size_t src_len,
348  bool broadcast,
349  lldb::ConnectionStatus status);
350 
351  /// Get any available bytes from our data cache. If this call empties the
352  /// data cache, the \b eBroadcastBitReadThreadGotBytes event will be reset
353  /// to signify no more bytes are available.
354  ///
355  /// \param[in] dst
356  /// A destination buffer that must be at least \a dst_len bytes
357  /// long.
358  ///
359  /// \param[in] dst_len
360  /// The number of bytes to attempt to read from the cache,
361  /// and also the max number of bytes that can be placed into
362  /// \a dst.
363  ///
364  /// \return
365  /// The number of bytes extracted from the data cache.
366  size_t GetCachedBytes(void *dst, size_t dst_len);
367 
368 private:
369  DISALLOW_COPY_AND_ASSIGN(Communication);
370 };
371 
372 } // namespace lldb_private
373 
374 #endif // liblldb_Communication_h_
ConstString & GetBroadcasterClass() const override
void SynchronizeWithReadThread()
Wait for the read thread to process all outstanding data.
void * thread_arg_t
Definition: lldb-types.h:61
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
virtual bool StopReadThread(Status *error_ptr=nullptr)
Stops the read thread by cancelling it.
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
virtual bool StartReadThread(Status *error_ptr=nullptr)
Starts a read thread whose sole purpose it to read bytes from the current connection.
std::mutex m_write_mutex
Don&#39;t let multiple threads write at the same time...
void SetConnection(Connection *connection)
Sets the connection that it to be used by this class.
HostThread m_read_thread
The read thread handle in case we need to cancel the thread.
void(* ReadThreadBytesReceived)(void *baton, const void *src, size_t src_len)
Communication(const char *broadcaster_name)
Construct the Communication object with the specified name for the Broadcaster that this object inher...
lldb::ConnectionSP m_connection_sp
The connection that is current in use by this communications class.
An event broadcasting class.
Definition: Broadcaster.h:250
virtual bool JoinReadThread(Status *error_ptr=nullptr)
virtual void AppendBytesToCache(const uint8_t *src, size_t src_len, bool broadcast, lldb::ConnectionStatus status)
Append new bytes that get read from the read thread into the internal object byte cache...
lldb_private::Connection * GetConnection()
static ConstString & GetStaticBroadcasterClass()
ReadThreadBytesReceived m_callback
A communication connection class.
Definition: Connection.h:43
static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr)
The static read thread function.
std::atomic< bool > m_read_thread_did_exit
~Communication() override
Destructor.
std::atomic< bool > m_read_thread_enabled
void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback, void *callback_baton)
bool IsConnected() const
Check if the connection is valid.
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
An abstract communications class.
Definition: Communication.h:91
A uniqued constant string class.
Definition: ConstString.h:38
size_t ReadFromConnection(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
size_t GetCachedBytes(void *dst, size_t dst_len)
Get any available bytes from our data cache.
std::string m_bytes
A buffer to cache bytes read in the ReadThread function.
bool ReadThreadIsRunning()
Checks if there is a currently running read thread.
std::recursive_mutex m_bytes_mutex
A mutex to protect multi-threaded access to the cached bytes.
lldb::ConnectionStatus Connect(const char *url, Status *error_ptr)
Connect using the current connection by passing url to its connect function.
static const char * ConnectionStatusAsCString(lldb::ConnectionStatus status)
An error handling class.
Definition: Status.h:44
void * thread_result_t
Definition: lldb-types.h:62
size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
The actual write function that attempts to write to the communications protocol.