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