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