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"
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"
19
20#include <atomic>
21#include <mutex>
22#include <ratio>
23#include <string>
24
25#include <stddef.h>
26#include <stdint.h>
27
28namespace lldb_private {
29class Connection;
30class ConstString;
31class 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.
84class Communication : public Broadcaster {
85public:
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 =
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
162 lldb_private::Connection *GetConnection() { return m_connection_sp.get(); }
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);
276 static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr);
277
278 void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,
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 ///
286 void SynchronizeWithReadThread();
287
288 static std::string ConnectionStatusAsString(lldb::ConnectionStatus status);
289
290 bool GetCloseOnEOF() const { return m_close_on_eof; }
291
292 void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
293
294 static ConstString &GetStaticBroadcasterClass();
295
296 ConstString &GetBroadcasterClass() const override {
297 return GetStaticBroadcasterClass();
298 }
299
300protected:
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;
307 std::string
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...
313 std::mutex m_synchronize_mutex;
314 ReadThreadBytesReceived m_callback;
315 void *m_callback_baton;
316 bool m_close_on_eof;
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
361private:
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
369