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 <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:
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   /// Repeatedly attempt writing until either \a src_len bytes are written
213   /// or a permanent failure occurs.
214   ///
215   /// \param[in] src
216   ///     A source buffer that must be at least \a src_len bytes
217   ///     long.
218   ///
219   /// \param[in] src_len
220   ///     The number of bytes to attempt to write, and also the
221   ///     number of bytes are currently available in \a src.
222   ///
223   /// \return
224   ///     The number of bytes actually Written.
225   size_t WriteAll(const void *src, size_t src_len,
226                   lldb::ConnectionStatus &status, Status *error_ptr);
227 
228   /// Sets the connection that it to be used by this class.
229   ///
230   /// By making a communication class that uses different connections it
231   /// allows a single communication interface to negotiate and change its
232   /// connection without any interruption to the client. It also allows the
233   /// Communication class to be subclassed for packet based communication.
234   ///
235   /// \param[in] connection
236   ///     A connection that this class will own and destroy.
237   ///
238   /// \see
239   ///     class Connection
240   void SetConnection(std::unique_ptr<Connection> connection);
241 
242   /// Starts a read thread whose sole purpose it to read bytes from the
243   /// current connection. This function will call connection's read function:
244   ///
245   /// size_t Connection::Read (void *, size_t);
246   ///
247   /// When bytes are read and cached, this function will call:
248   ///
249   /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len,
250   /// bool
251   /// broadcast);
252   ///
253   /// Subclasses should override this function if they wish to override the
254   /// default action of caching the bytes and broadcasting a \b
255   /// eBroadcastBitReadThreadGotBytes event.
256   ///
257   /// \return
258   ///     \b True if the read thread was successfully started, \b
259   ///     false otherwise.
260   ///
261   /// \see size_t Connection::Read (void *, size_t);
262   /// \see void Communication::AppendBytesToCache (const uint8_t * bytes,
263   ///                                              size_t len, bool broadcast);
264   virtual bool StartReadThread(Status *error_ptr = nullptr);
265 
266   /// Stops the read thread by cancelling it.
267   ///
268   /// \return
269   ///     \b True if the read thread was successfully canceled, \b
270   ///     false otherwise.
271   virtual bool StopReadThread(Status *error_ptr = nullptr);
272 
273   virtual bool JoinReadThread(Status *error_ptr = nullptr);
274   /// Checks if there is a currently running read thread.
275   ///
276   /// \return
277   ///     \b True if the read thread is running, \b false otherwise.
278   bool ReadThreadIsRunning();
279 
280   /// The read thread function. This function will call the "DoRead"
281   /// function continuously and wait for data to become available. When data
282   /// is received it will append the available data to the internal cache and
283   /// broadcast a \b eBroadcastBitReadThreadGotBytes event.
284   ///
285   /// \param[in] comm_ptr
286   ///     A pointer to an instance of this class.
287   ///
288   /// \return
289   ///     \b NULL.
290   ///
291   /// \see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
292   lldb::thread_result_t ReadThread();
293 
294   void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,
295                                           void *callback_baton);
296 
297   /// Wait for the read thread to process all outstanding data.
298   ///
299   /// After this function returns, the read thread has processed all data that
300   /// has been waiting in the Connection queue.
301   ///
302   void SynchronizeWithReadThread();
303 
304   static std::string ConnectionStatusAsString(lldb::ConnectionStatus status);
305 
306   bool GetCloseOnEOF() const { return m_close_on_eof; }
307 
308   void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
309 
310   static ConstString &GetStaticBroadcasterClass();
311 
312   ConstString &GetBroadcasterClass() const override {
313     return GetStaticBroadcasterClass();
314   }
315 
316 protected:
317   lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use
318                                       ///by this communications class.
319   HostThread m_read_thread; ///< The read thread handle in case we need to
320                             ///cancel the thread.
321   std::atomic<bool> m_read_thread_enabled;
322   std::atomic<bool> m_read_thread_did_exit;
323   std::string
324       m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
325   std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded
326                                       ///access to the cached bytes.
327   std::mutex
328       m_write_mutex; ///< Don't let multiple threads write at the same time...
329   std::mutex m_synchronize_mutex;
330   ReadThreadBytesReceived m_callback;
331   void *m_callback_baton;
332   bool m_close_on_eof;
333 
334   size_t ReadFromConnection(void *dst, size_t dst_len,
335                             const Timeout<std::micro> &timeout,
336                             lldb::ConnectionStatus &status, Status *error_ptr);
337 
338   /// Append new bytes that get read from the read thread into the internal
339   /// object byte cache. This will cause a \b eBroadcastBitReadThreadGotBytes
340   /// event to be broadcast if \a broadcast is true.
341   ///
342   /// Subclasses can override this function in order to inspect the received
343   /// data and check if a packet is available.
344   ///
345   /// Subclasses can also still call this function from the overridden method
346   /// to allow the caching to correctly happen and suppress the broadcasting
347   /// of the \a eBroadcastBitReadThreadGotBytes event by setting \a broadcast
348   /// to false.
349   ///
350   /// \param[in] src
351   ///     A source buffer that must be at least \a src_len bytes
352   ///     long.
353   ///
354   /// \param[in] src_len
355   ///     The number of bytes to append to the cache.
356   virtual void AppendBytesToCache(const uint8_t *src, size_t src_len,
357                                   bool broadcast,
358                                   lldb::ConnectionStatus status);
359 
360   /// Get any available bytes from our data cache. If this call empties the
361   /// data cache, the \b eBroadcastBitReadThreadGotBytes event will be reset
362   /// to signify no more bytes are available.
363   ///
364   /// \param[in] dst
365   ///     A destination buffer that must be at least \a dst_len bytes
366   ///     long.
367   ///
368   /// \param[in] dst_len
369   ///     The number of bytes to attempt to read from the cache,
370   ///     and also the max number of bytes that can be placed into
371   ///     \a dst.
372   ///
373   /// \return
374   ///     The number of bytes extracted from the data cache.
375   size_t GetCachedBytes(void *dst, size_t dst_len);
376 
377 private:
378   Communication(const Communication &) = delete;
379   const Communication &operator=(const Communication &) = delete;
380 };
381 
382 } // namespace lldb_private
383 
384 #endif // LLDB_CORE_COMMUNICATION_H
385