1254721Semaste//===-- Communication.h -----------------------------------------*- C++ -*-===//
2254721Semaste//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6254721Semaste//
7254721Semaste//===----------------------------------------------------------------------===//
8254721Semaste
9254721Semaste#ifndef liblldb_Communication_h_
10254721Semaste#define liblldb_Communication_h_
11254721Semaste
12321369Sdim#include "lldb/Host/HostThread.h"
13344779Sdim#include "lldb/Utility/Broadcaster.h"
14321369Sdim#include "lldb/Utility/Timeout.h"
15344779Sdim#include "lldb/lldb-defines.h"
16344779Sdim#include "lldb/lldb-enumerations.h"
17344779Sdim#include "lldb/lldb-forward.h"
18344779Sdim#include "lldb/lldb-types.h"
19321369Sdim
20280031Sdim#include <atomic>
21309124Sdim#include <mutex>
22344779Sdim#include <ratio>
23254721Semaste#include <string>
24254721Semaste
25344779Sdim#include <stddef.h>
26344779Sdim#include <stdint.h>
27254721Semaste
28254721Semastenamespace lldb_private {
29321369Sdimclass Connection;
30321369Sdimclass ConstString;
31321369Sdimclass Status;
32254721Semaste
33353358Sdim/// \class Communication Communication.h "lldb/Core/Communication.h" An
34341825Sdim/// abstract communications class.
35254721Semaste///
36341825Sdim/// Communication is an class that handles data communication between two data
37341825Sdim/// sources. It uses a Connection class to do the real communication. This
38341825Sdim/// approach has a couple of advantages: it allows a single instance of this
39341825Sdim/// class to be used even though its connection can change. Connections could
40341825Sdim/// negotiate for different connections based on abilities like starting with
41341825Sdim/// Bluetooth and negotiating up to WiFi if available. It also allows this
42341825Sdim/// class to be subclassed by any interfaces that don't want to give bytes but
43341825Sdim/// want to validate and give out packets. This can be done by overriding:
44254721Semaste///
45254721Semaste/// AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast);
46254721Semaste///
47341825Sdim/// Communication inherits from Broadcaster which means it can be used in
48341825Sdim/// conjunction with Listener to wait for multiple broadcaster objects and
49341825Sdim/// multiple events from each of those objects. Communication defines a set of
50341825Sdim/// pre-defined event bits (see enumerations definitions that start with
51341825Sdim/// "eBroadcastBit" below).
52254721Semaste///
53254721Semaste/// There are two modes in which communications can occur:
54353358Sdim///     \li single-threaded
55353358Sdim///     \li multi-threaded
56254721Semaste///
57341825Sdim/// In single-threaded mode, all reads and writes happen synchronously on the
58341825Sdim/// calling thread.
59254721Semaste///
60341825Sdim/// In multi-threaded mode, a read thread is spawned that continually reads
61341825Sdim/// data and caches any received bytes. To start the read thread clients call:
62254721Semaste///
63321369Sdim///     bool Communication::StartReadThread (Status *);
64254721Semaste///
65341825Sdim/// If true is returned a read thread has been spawned that will continually
66341825Sdim/// execute a call to the pure virtual DoRead function:
67254721Semaste///
68254721Semaste///     size_t Communication::ReadFromConnection (void *, size_t, uint32_t);
69254721Semaste///
70341825Sdim/// When bytes are received the data gets cached in \a m_bytes and this class
71341825Sdim/// will broadcast a \b eBroadcastBitReadThreadGotBytes event. Clients that
72341825Sdim/// want packet based communication should override AppendBytesToCache. The
73341825Sdim/// subclasses can choose to call the built in AppendBytesToCache with the \a
74341825Sdim/// broadcast parameter set to false. This will cause the \b
75341825Sdim/// eBroadcastBitReadThreadGotBytes event not get broadcast, and then the
76341825Sdim/// subclass can post a \b eBroadcastBitPacketAvailable event when a full
77341825Sdim/// packet of data has been received.
78254721Semaste///
79341825Sdim/// If the connection is disconnected a \b eBroadcastBitDisconnected event
80341825Sdim/// gets broadcast. If the read thread exits a \b
81341825Sdim/// eBroadcastBitReadThreadDidExit event will be broadcast. Clients can also
82341825Sdim/// post a \b eBroadcastBitReadThreadShouldExit event to this object which
83341825Sdim/// will cause the read thread to exit.
84314564Sdimclass Communication : public Broadcaster {
85254721Semastepublic:
86314564Sdim  FLAGS_ANONYMOUS_ENUM(){
87314564Sdim      eBroadcastBitDisconnected =
88314564Sdim          (1u << 0), ///< Sent when the communications connection is lost.
89314564Sdim      eBroadcastBitReadThreadGotBytes =
90314564Sdim          (1u << 1), ///< Sent by the read thread when bytes become available.
91314564Sdim      eBroadcastBitReadThreadDidExit =
92314564Sdim          (1u
93314564Sdim           << 2), ///< Sent by the read thread when it exits to inform clients.
94314564Sdim      eBroadcastBitReadThreadShouldExit =
95314564Sdim          (1u << 3), ///< Sent by clients that need to cancel the read thread.
96314564Sdim      eBroadcastBitPacketAvailable =
97314564Sdim          (1u << 4), ///< Sent when data received makes a complete packet.
98314564Sdim      eBroadcastBitNoMorePendingInput = (1u << 5), ///< Sent by the read thread
99314564Sdim                                                   ///to indicate all pending
100314564Sdim                                                   ///input has been processed.
101314564Sdim      kLoUserBroadcastBit =
102314564Sdim          (1u << 16), ///< Subclasses can used bits 31:16 for any needed events.
103314564Sdim      kHiUserBroadcastBit = (1u << 31),
104314564Sdim      eAllEventBits = 0xffffffff};
105254721Semaste
106314564Sdim  typedef void (*ReadThreadBytesReceived)(void *baton, const void *src,
107314564Sdim                                          size_t src_len);
108254721Semaste
109341825Sdim  /// Construct the Communication object with the specified name for the
110341825Sdim  /// Broadcaster that this object inherits from.
111314564Sdim  ///
112353358Sdim  /// \param[in] broadcaster_name
113314564Sdim  ///     The name of the broadcaster object.  This name should be as
114314564Sdim  ///     complete as possible to uniquely identify this object. The
115314564Sdim  ///     broadcaster name can be updated after the connect function
116314564Sdim  ///     is called.
117314564Sdim  Communication(const char *broadcaster_name);
118254721Semaste
119314564Sdim  /// Destructor.
120314564Sdim  ///
121314564Sdim  /// The destructor is virtual since this class gets subclassed.
122314564Sdim  ~Communication() override;
123254721Semaste
124314564Sdim  void Clear();
125254721Semaste
126341825Sdim  /// Connect using the current connection by passing \a url to its connect
127341825Sdim  /// function. string.
128314564Sdim  ///
129353358Sdim  /// \param[in] url
130314564Sdim  ///     A string that contains all information needed by the
131314564Sdim  ///     subclass to connect to another client.
132314564Sdim  ///
133353358Sdim  /// \return
134314564Sdim  ///     \b True if the connect succeeded, \b false otherwise. The
135314564Sdim  ///     internal error object should be filled in with an
136314564Sdim  ///     appropriate value based on the result of this function.
137314564Sdim  ///
138353358Sdim  /// \see Status& Communication::GetError ();
139353358Sdim  /// \see bool Connection::Connect (const char *url);
140321369Sdim  lldb::ConnectionStatus Connect(const char *url, Status *error_ptr);
141254721Semaste
142341825Sdim  /// Disconnect the communications connection if one is currently connected.
143314564Sdim  ///
144353358Sdim  /// \return
145314564Sdim  ///     \b True if the disconnect succeeded, \b false otherwise. The
146314564Sdim  ///     internal error object should be filled in with an
147314564Sdim  ///     appropriate value based on the result of this function.
148314564Sdim  ///
149353358Sdim  /// \see Status& Communication::GetError ();
150353358Sdim  /// \see bool Connection::Disconnect ();
151321369Sdim  lldb::ConnectionStatus Disconnect(Status *error_ptr = nullptr);
152254721Semaste
153314564Sdim  /// Check if the connection is valid.
154314564Sdim  ///
155353358Sdim  /// \return
156314564Sdim  ///     \b True if this object is currently connected, \b false
157314564Sdim  ///     otherwise.
158314564Sdim  bool IsConnected() const;
159254721Semaste
160314564Sdim  bool HasConnection() const;
161296417Sdim
162314564Sdim  lldb_private::Connection *GetConnection() { return m_connection_sp.get(); }
163254721Semaste
164314564Sdim  /// Read bytes from the current connection.
165314564Sdim  ///
166341825Sdim  /// If no read thread is running, this function call the connection's
167341825Sdim  /// Connection::Read(...) function to get any available.
168314564Sdim  ///
169341825Sdim  /// If a read thread has been started, this function will check for any
170341825Sdim  /// cached bytes that have already been read and return any currently
171341825Sdim  /// available bytes. If no bytes are cached, it will wait for the bytes to
172341825Sdim  /// become available by listening for the \a eBroadcastBitReadThreadGotBytes
173341825Sdim  /// event. If this function consumes all of the bytes in the cache, it will
174341825Sdim  /// reset the \a eBroadcastBitReadThreadGotBytes event bit.
175314564Sdim  ///
176353358Sdim  /// \param[in] dst
177314564Sdim  ///     A destination buffer that must be at least \a dst_len bytes
178314564Sdim  ///     long.
179314564Sdim  ///
180353358Sdim  /// \param[in] dst_len
181314564Sdim  ///     The number of bytes to attempt to read, and also the max
182314564Sdim  ///     number of bytes that can be placed into \a dst.
183314564Sdim  ///
184353358Sdim  /// \param[in] timeout
185314564Sdim  ///     A timeout value or llvm::None for no timeout.
186314564Sdim  ///
187353358Sdim  /// \return
188314564Sdim  ///     The number of bytes actually read.
189314564Sdim  ///
190353358Sdim  /// \see size_t Connection::Read (void *, size_t);
191314564Sdim  size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout,
192321369Sdim              lldb::ConnectionStatus &status, Status *error_ptr);
193254721Semaste
194341825Sdim  /// The actual write function that attempts to write to the communications
195341825Sdim  /// protocol.
196314564Sdim  ///
197314564Sdim  /// Subclasses must override this function.
198314564Sdim  ///
199353358Sdim  /// \param[in] src
200314564Sdim  ///     A source buffer that must be at least \a src_len bytes
201314564Sdim  ///     long.
202314564Sdim  ///
203353358Sdim  /// \param[in] src_len
204314564Sdim  ///     The number of bytes to attempt to write, and also the
205314564Sdim  ///     number of bytes are currently available in \a src.
206314564Sdim  ///
207353358Sdim  /// \return
208314564Sdim  ///     The number of bytes actually Written.
209314564Sdim  size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status,
210321369Sdim               Status *error_ptr);
211254721Semaste
212314564Sdim  /// Sets the connection that it to be used by this class.
213314564Sdim  ///
214341825Sdim  /// By making a communication class that uses different connections it
215341825Sdim  /// allows a single communication interface to negotiate and change its
216341825Sdim  /// connection without any interruption to the client. It also allows the
217341825Sdim  /// Communication class to be subclassed for packet based communication.
218314564Sdim  ///
219353358Sdim  /// \param[in] connection
220314564Sdim  ///     A connection that this class will own and destroy.
221314564Sdim  ///
222353358Sdim  /// \see
223314564Sdim  ///     class Connection
224314564Sdim  void SetConnection(Connection *connection);
225254721Semaste
226341825Sdim  /// Starts a read thread whose sole purpose it to read bytes from the
227341825Sdim  /// current connection. This function will call connection's read function:
228314564Sdim  ///
229314564Sdim  /// size_t Connection::Read (void *, size_t);
230314564Sdim  ///
231314564Sdim  /// When bytes are read and cached, this function will call:
232314564Sdim  ///
233341825Sdim  /// Communication::AppendBytesToCache (const uint8_t * bytes, size_t len,
234341825Sdim  /// bool
235314564Sdim  /// broadcast);
236314564Sdim  ///
237341825Sdim  /// Subclasses should override this function if they wish to override the
238341825Sdim  /// default action of caching the bytes and broadcasting a \b
239314564Sdim  /// eBroadcastBitReadThreadGotBytes event.
240314564Sdim  ///
241353358Sdim  /// \return
242314564Sdim  ///     \b True if the read thread was successfully started, \b
243314564Sdim  ///     false otherwise.
244314564Sdim  ///
245353358Sdim  /// \see size_t Connection::Read (void *, size_t);
246353358Sdim  /// \see void Communication::AppendBytesToCache (const uint8_t * bytes,
247341825Sdim  ///                                              size_t len, bool broadcast);
248321369Sdim  virtual bool StartReadThread(Status *error_ptr = nullptr);
249254721Semaste
250314564Sdim  /// Stops the read thread by cancelling it.
251314564Sdim  ///
252353358Sdim  /// \return
253314564Sdim  ///     \b True if the read thread was successfully canceled, \b
254314564Sdim  ///     false otherwise.
255321369Sdim  virtual bool StopReadThread(Status *error_ptr = nullptr);
256254721Semaste
257321369Sdim  virtual bool JoinReadThread(Status *error_ptr = nullptr);
258314564Sdim  /// Checks if there is a currently running read thread.
259314564Sdim  ///
260353358Sdim  /// \return
261314564Sdim  ///     \b True if the read thread is running, \b false otherwise.
262314564Sdim  bool ReadThreadIsRunning();
263288943Sdim
264341825Sdim  /// The static read thread function. This function will call the "DoRead"
265341825Sdim  /// function continuously and wait for data to become available. When data
266341825Sdim  /// is received it will append the available data to the internal cache and
267341825Sdim  /// broadcast a \b eBroadcastBitReadThreadGotBytes event.
268314564Sdim  ///
269353358Sdim  /// \param[in] comm_ptr
270314564Sdim  ///     A pointer to an instance of this class.
271314564Sdim  ///
272353358Sdim  /// \return
273314564Sdim  ///     \b NULL.
274314564Sdim  ///
275353358Sdim  /// \see void Communication::ReadThreadGotBytes (const uint8_t *, size_t);
276314564Sdim  static lldb::thread_result_t ReadThread(lldb::thread_arg_t comm_ptr);
277254721Semaste
278314564Sdim  void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,
279314564Sdim                                          void *callback_baton);
280254721Semaste
281314564Sdim  /// Wait for the read thread to process all outstanding data.
282314564Sdim  ///
283314564Sdim  /// After this function returns, the read thread has processed all data that
284314564Sdim  /// has been waiting in the Connection queue.
285314564Sdim  ///
286314564Sdim  void SynchronizeWithReadThread();
287254721Semaste
288314564Sdim  static const char *ConnectionStatusAsCString(lldb::ConnectionStatus status);
289254721Semaste
290314564Sdim  bool GetCloseOnEOF() const { return m_close_on_eof; }
291254721Semaste
292314564Sdim  void SetCloseOnEOF(bool b) { m_close_on_eof = b; }
293314564Sdim
294314564Sdim  static ConstString &GetStaticBroadcasterClass();
295314564Sdim
296314564Sdim  ConstString &GetBroadcasterClass() const override {
297314564Sdim    return GetStaticBroadcasterClass();
298314564Sdim  }
299314564Sdim
300254721Semasteprotected:
301314564Sdim  lldb::ConnectionSP m_connection_sp; ///< The connection that is current in use
302314564Sdim                                      ///by this communications class.
303314564Sdim  HostThread m_read_thread; ///< The read thread handle in case we need to
304314564Sdim                            ///cancel the thread.
305314564Sdim  std::atomic<bool> m_read_thread_enabled;
306314564Sdim  std::atomic<bool> m_read_thread_did_exit;
307314564Sdim  std::string
308314564Sdim      m_bytes; ///< A buffer to cache bytes read in the ReadThread function.
309314564Sdim  std::recursive_mutex m_bytes_mutex; ///< A mutex to protect multi-threaded
310314564Sdim                                      ///access to the cached bytes.
311314564Sdim  std::mutex
312314564Sdim      m_write_mutex; ///< Don't let multiple threads write at the same time...
313314564Sdim  std::mutex m_synchronize_mutex;
314314564Sdim  ReadThreadBytesReceived m_callback;
315314564Sdim  void *m_callback_baton;
316314564Sdim  bool m_close_on_eof;
317254721Semaste
318314564Sdim  size_t ReadFromConnection(void *dst, size_t dst_len,
319314564Sdim                            const Timeout<std::micro> &timeout,
320321369Sdim                            lldb::ConnectionStatus &status, Status *error_ptr);
321296417Sdim
322341825Sdim  /// Append new bytes that get read from the read thread into the internal
323341825Sdim  /// object byte cache. This will cause a \b eBroadcastBitReadThreadGotBytes
324341825Sdim  /// event to be broadcast if \a broadcast is true.
325314564Sdim  ///
326341825Sdim  /// Subclasses can override this function in order to inspect the received
327341825Sdim  /// data and check if a packet is available.
328314564Sdim  ///
329341825Sdim  /// Subclasses can also still call this function from the overridden method
330341825Sdim  /// to allow the caching to correctly happen and suppress the broadcasting
331341825Sdim  /// of the \a eBroadcastBitReadThreadGotBytes event by setting \a broadcast
332341825Sdim  /// to false.
333314564Sdim  ///
334353358Sdim  /// \param[in] src
335314564Sdim  ///     A source buffer that must be at least \a src_len bytes
336314564Sdim  ///     long.
337314564Sdim  ///
338353358Sdim  /// \param[in] src_len
339314564Sdim  ///     The number of bytes to append to the cache.
340314564Sdim  virtual void AppendBytesToCache(const uint8_t *src, size_t src_len,
341314564Sdim                                  bool broadcast,
342314564Sdim                                  lldb::ConnectionStatus status);
343254721Semaste
344341825Sdim  /// Get any available bytes from our data cache. If this call empties the
345341825Sdim  /// data cache, the \b eBroadcastBitReadThreadGotBytes event will be reset
346341825Sdim  /// to signify no more bytes are available.
347314564Sdim  ///
348353358Sdim  /// \param[in] dst
349314564Sdim  ///     A destination buffer that must be at least \a dst_len bytes
350314564Sdim  ///     long.
351314564Sdim  ///
352353358Sdim  /// \param[in] dst_len
353314564Sdim  ///     The number of bytes to attempt to read from the cache,
354314564Sdim  ///     and also the max number of bytes that can be placed into
355314564Sdim  ///     \a dst.
356314564Sdim  ///
357353358Sdim  /// \return
358314564Sdim  ///     The number of bytes extracted from the data cache.
359314564Sdim  size_t GetCachedBytes(void *dst, size_t dst_len);
360296417Sdim
361296417Sdimprivate:
362314564Sdim  DISALLOW_COPY_AND_ASSIGN(Communication);
363254721Semaste};
364254721Semaste
365254721Semaste} // namespace lldb_private
366254721Semaste
367296417Sdim#endif // liblldb_Communication_h_
368