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 LLDB_CORE_COMMUNICATION_H
10 #define LLDB_CORE_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 <cstddef>
26 #include <cstdint>
27 
28 namespace lldb_private {
29 class Connection;
30 class ConstString;
31 class Status;
32 
33 /// \class Communication Communication.h "lldb/Core/Communication.h" An
34 /// abstract communications class.
35 ///
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:
44 ///
45 /// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
46 ///
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).
52 ///
53 /// There are two modes in which communications can occur:
54 /// \li single-threaded
55 /// \li multi-threaded
56 ///
57 /// In single-threaded mode, all reads and writes happen synchronously on the
58 /// calling thread.
59 ///
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:
62 ///
63 /// bool Communication::StartReadThread (Status *);
64 ///
65 /// If true is returned a read thread has been spawned that will continually
66 /// execute a call to the pure virtual DoRead function:
67 ///
68 /// size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
69 ///
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.
78 ///
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 {
85 public:
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 =
92  (1u
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};
105 
106  typedef void (*ReadThreadBytesReceived)(void *baton, const void *src,
107  size_t src_len);
108 
109  /// Construct the Communication object with the specified name for the
110  /// Broadcaster that this object inherits from.
111  ///
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
116  /// is called.
117  Communication(const char *broadcaster_name);
118 
119  /// Destructor.
120  ///
121  /// The destructor is virtual since this class gets subclassed.
122  ~Communication() override;
123 
124  void Clear();
125 
126  /// Connect using the current connection by passing \a url to its connect
127  /// function. string.
128  ///
129  /// \param[in] url
130  /// A string that contains all information needed by the
131  /// subclass to connect to another client.
132  ///
133  /// \return
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.
137  ///
138  /// \see Status& Communication::GetError ();
139  /// \see bool Connection::Connect (const char *url);
140  lldb::ConnectionStatus Connect(const char *url, Status *error_ptr);
141 
142  /// Disconnect the communications connection if one is currently connected.
143  ///
144  /// \return
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.
148  ///
149  /// \see Status& Communication::GetError ();
150  /// \see bool Connection::Disconnect ();
151  lldb::ConnectionStatus Disconnect(Status *error_ptr = nullptr);
152 
153  /// Check if the connection is valid.
154  ///
155  /// \return
156  /// \b True if this object is currently connected, \b false
157  /// otherwise.
158  bool IsConnected() const;
159 
160  bool HasConnection() const;
161 
163 
164  /// Read bytes from the current connection.
165  ///
166  /// If no read thread is running, this function call the connection's
167  /// Connection::Read(...) function to get any available.
168  ///
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.
175  ///
176  /// \param[in] dst
177  /// A destination buffer that must be at least \a dst_len bytes
178  /// long.
179  ///
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.
183  ///
184  /// \param[in] timeout
185  /// A timeout value or llvm::None for no timeout.
186  ///
187  /// \return
188  /// The number of bytes actually read.
189  ///
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);
193 
194  /// The actual write function that attempts to write to the communications
195  /// protocol.
196  ///
197  /// Subclasses must override this function.
198  ///
199  /// \param[in] src
200  /// A source buffer that must be at least \a src_len bytes
201  /// long.
202  ///
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.
206  ///
207  /// \return
208  /// The number of bytes actually Written.
209  size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status,
210  Status *error_ptr);
211 
212  /// Sets the connection that it to be used by this class.
213  ///
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.
218  ///
219  /// \param[in] connection
220  /// A connection that this class will own and destroy.
221  ///
222  /// \see
223  /// class Connection
224  void SetConnection(std::unique_ptr<Connection> connection);
225 
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:
228  ///
229  /// size_t Connection::Read (void *, size_t);
230  ///
231  /// When bytes are read and cached, this function will call:
232  ///
233  /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len,
234  /// bool
235  /// broadcast);
236  ///
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.
240  ///
241  /// \return
242  /// \b True if the read thread was successfully started, \b
243  /// false otherwise.
244  ///
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);
249 
250  /// Stops the read thread by cancelling it.
251  ///
252  /// \return
253  /// \b True if the read thread was successfully canceled, \b
254  /// false otherwise.
255  virtual bool StopReadThread(Status *error_ptr = nullptr);
256 
257  virtual bool JoinReadThread(Status *error_ptr = nullptr);
258  /// Checks if there is a currently running read thread.
259  ///
260  /// \return
261  /// \b True if the read thread is running, \b false otherwise.
262  bool ReadThreadIsRunning();
263 
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.
268  ///
269  /// \param[in] comm_ptr
270  /// A pointer to an instance of this class.
271  ///
272  /// \return
273  /// \b NULL.
274  ///
275  /// \see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
277 
279  void *callback_baton);
280 
281  /// Wait for the read thread to process all outstanding data.
282  ///
283  /// After this function returns, the read thread has processed all data that
284  /// has been waiting in the Connection queue.
285  ///
287 
289 
290  bool GetCloseOnEOF() const { return m_close_on_eof; }
291 
292  void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
293 
295 
296  ConstString &GetBroadcasterClass() const override {
297  return GetStaticBroadcasterClass();
298  }
299 
300 protected:
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.
311  std::mutex
312  m_write_mutex; ///< Don't let multiple threads write at the same time...
317 
318  size_t ReadFromConnection(void *dst, size_t dst_len,
319  const Timeout<std::micro> &timeout,
320  lldb::ConnectionStatus &status, Status *error_ptr);
321 
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.
325  ///
326  /// Subclasses can override this function in order to inspect the received
327  /// data and check if a packet is available.
328  ///
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
332  /// to false.
333  ///
334  /// \param[in] src
335  /// A source buffer that must be at least \a src_len bytes
336  /// long.
337  ///
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,
341  bool broadcast,
342  lldb::ConnectionStatus status);
343 
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.
347  ///
348  /// \param[in] dst
349  /// A destination buffer that must be at least \a dst_len bytes
350  /// long.
351  ///
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
355  /// \a dst.
356  ///
357  /// \return
358  /// The number of bytes extracted from the data cache.
359  size_t GetCachedBytes(void *dst, size_t dst_len);
360 
361 private:
362  Communication(const Communication &) = delete;
363  const Communication &operator=(const Communication &) = delete;
364 };
365 
366 } // namespace lldb_private
367 
368 #endif // LLDB_CORE_COMMUNICATION_H
lldb_private::Connection
Definition: Connection.h:41
lldb_private::Communication::FLAGS_ANONYMOUS_ENUM
FLAGS_ANONYMOUS_ENUM()
Definition: Communication.h:86
lldb_private::Communication::SynchronizeWithReadThread
void SynchronizeWithReadThread()
Wait for the read thread to process all outstanding data.
Definition: Communication.cpp:392
lldb_private::Communication::ReadThreadIsRunning
bool ReadThreadIsRunning()
Checks if there is a currently running read thread.
Definition: Communication.cpp:305
lldb_private::Communication::SetCloseOnEOF
void SetCloseOnEOF(bool b)
Definition: Communication.h:292
lldb_private::HostThread
Definition: HostThread.h:29
lldb_private::Communication::AppendBytesToCache
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.
Definition: Communication.cpp:270
lldb_private::Communication::m_callback
ReadThreadBytesReceived m_callback
Definition: Communication.h:314
lldb-defines.h
lldb_private::Communication::ConnectionStatusAsString
static std::string ConnectionStatusAsString(lldb::ConnectionStatus status)
Definition: Communication.cpp:420
lldb_private::Communication::GetCachedBytes
size_t GetCachedBytes(void *dst, size_t dst_len)
Get any available bytes from our data cache.
Definition: Communication.cpp:252
lldb_private::Communication::m_write_mutex
std::mutex m_write_mutex
Don't let multiple threads write at the same time...
Definition: Communication.h:312
lldb_private::Communication::Communication
Communication(const char *broadcaster_name)
Construct the Communication object with the specified name for the Broadcaster that this object inher...
Definition: Communication.cpp:42
lldb_private::Communication::m_connection_sp
lldb::ConnectionSP m_connection_sp
The connection that is current in use by this communications class.
Definition: Communication.h:301
lldb_private::Communication::m_callback_baton
void * m_callback_baton
Definition: Communication.h:315
lldb_private::Communication::~Communication
~Communication() override
Destructor.
Definition: Communication.cpp:64
Broadcaster.h
lldb_private::Communication::SetConnection
void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
Definition: Communication.cpp:413
lldb_private::Communication
Definition: Communication.h:84
lldb_private::Communication::m_read_thread
HostThread m_read_thread
The read thread handle in case we need to cancel the thread.
Definition: Communication.h:303
HostThread.h
lldb_private::Communication::ReadFromConnection
size_t ReadFromConnection(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Definition: Communication.cpp:291
lldb_private::Communication::m_read_thread_did_exit
std::atomic< bool > m_read_thread_did_exit
Definition: Communication.h:306
lldb_private::Communication::GetStaticBroadcasterClass
static ConstString & GetStaticBroadcasterClass()
Definition: Communication.cpp:37
lldb_private::Communication::Clear
void Clear()
Definition: Communication.cpp:72
lldb_private::Communication::GetBroadcasterClass
ConstString & GetBroadcasterClass() const override
This needs to be filled in if you are going to register the broadcaster with the broadcaster manager ...
Definition: Communication.h:296
lldb_private::ConstString
Definition: ConstString.h:40
lldb-enumerations.h
lldb_private::Communication::StartReadThread
virtual bool StartReadThread(Status *error_ptr=nullptr)
Starts a read thread whose sole purpose it to read bytes from the current connection.
Definition: Communication.cpp:192
lldb::ConnectionStatus
ConnectionStatus
Connection Status Types.
Definition: lldb-enumerations.h:295
lldb_private::Communication::SetReadThreadBytesReceivedCallback
void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback, void *callback_baton)
Definition: Communication.cpp:386
lldb_private::Communication::ReadThread
static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr)
The static read thread function.
Definition: Communication.cpp:307
lldb_private::Communication::StopReadThread
virtual bool StopReadThread(Status *error_ptr=nullptr)
Stops the read thread by cancelling it.
Definition: Communication.cpp:227
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:40
lldb::thread_arg_t
void * thread_arg_t
Definition: lldb-types.h:61
lldb_private::Communication::Write
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.
Definition: Communication.cpp:173
lldb_private::Communication::m_synchronize_mutex
std::mutex m_synchronize_mutex
Definition: Communication.h:313
lldb_private::Communication::operator=
const Communication & operator=(const Communication &)=delete
lldb-types.h
lldb_private::Communication::Disconnect
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
Definition: Communication.cpp:92
lldb_private::Communication::HasConnection
bool HasConnection() const
Definition: Communication.cpp:121
lldb_private::Status
Definition: Status.h:44
lldb_private::Timeout< std::micro >
lldb_private::Communication::Read
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.
Definition: Communication.cpp:125
lldb::thread_result_t
void * thread_result_t
Definition: lldb-types.h:62
Timeout.h
lldb_private::Communication::IsConnected
bool IsConnected() const
Check if the connection is valid.
Definition: Communication.cpp:116
lldb_private::Communication::GetCloseOnEOF
bool GetCloseOnEOF() const
Definition: Communication.h:290
lldb-forward.h
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::Communication::GetConnection
lldb_private::Connection * GetConnection()
Definition: Communication.h:162
lldb_private::Communication::ReadThreadBytesReceived
void(* ReadThreadBytesReceived)(void *baton, const void *src, size_t src_len)
Definition: Communication.h:106
lldb_private::Communication::m_read_thread_enabled
std::atomic< bool > m_read_thread_enabled
Definition: Communication.h:305
lldb_private::Broadcaster
Definition: Broadcaster.h:242
lldb_private::LineStatus::Status
@ Status
lldb_private::Communication::m_close_on_eof
bool m_close_on_eof
Definition: Communication.h:316
lldb_private::Communication::JoinReadThread
virtual bool JoinReadThread(Status *error_ptr=nullptr)
Definition: Communication.cpp:244
lldb_private::Communication::m_bytes
std::string m_bytes
A buffer to cache bytes read in the ReadThread function.
Definition: Communication.h:308
lldb_private::Communication::m_bytes_mutex
std::recursive_mutex m_bytes_mutex
A mutex to protect multi-threaded access to the cached bytes.
Definition: Communication.h:309
lldb_private::Communication::Connect
lldb::ConnectionStatus Connect(const char *url, Status *error_ptr)
Connect using the current connection by passing url to its connect function.
Definition: Communication.cpp:78