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