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