LLDB  mainline
Communication.cpp
Go to the documentation of this file.
1 //===-- Communication.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 
11 #include "lldb/Host/HostThread.h"
15 #include "lldb/Utility/Event.h"
16 #include "lldb/Utility/LLDBLog.h"
17 #include "lldb/Utility/Listener.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/Status.h"
20 
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/Support/Compiler.h"
24 
25 #include <algorithm>
26 #include <chrono>
27 #include <cstring>
28 #include <memory>
29 
30 #include <cerrno>
31 #include <cinttypes>
32 #include <cstdio>
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 
37 ConstString &Communication::GetStaticBroadcasterClass() {
38  static ConstString class_name("lldb.communication");
39  return class_name;
40 }
41 
42 Communication::Communication(const char *name)
43  : Broadcaster(nullptr, name), m_connection_sp(),
44  m_read_thread_enabled(false), m_read_thread_did_exit(false), m_bytes(),
45  m_bytes_mutex(), m_write_mutex(), m_synchronize_mutex(),
46  m_callback(nullptr), m_callback_baton(nullptr), m_close_on_eof(true)
47 
48 {
49 
51  "{0} Communication::Communication (name = {1})", this, name);
52 
53  SetEventName(eBroadcastBitDisconnected, "disconnected");
54  SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes");
55  SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit");
56  SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit");
57  SetEventName(eBroadcastBitPacketAvailable, "packet available");
58  SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input");
59 
61 }
62 
65  "{0} Communication::~Communication (name = {1})", this,
66  GetBroadcasterName().AsCString());
67  Clear();
68 }
69 
71  SetReadThreadBytesReceivedCallback(nullptr, nullptr);
72  StopReadThread(nullptr);
73  Disconnect(nullptr);
74 }
75 
76 ConnectionStatus Communication::Connect(const char *url, Status *error_ptr) {
77  Clear();
78 
80  "{0} Communication::Connect (url = {1})", this, url);
81 
82  lldb::ConnectionSP connection_sp(m_connection_sp);
83  if (connection_sp)
84  return connection_sp->Connect(url, error_ptr);
85  if (error_ptr)
86  error_ptr->SetErrorString("Invalid connection.");
88 }
89 
91  LLDB_LOG(GetLog(LLDBLog::Communication), "{0} Communication::Disconnect ()",
92  this);
93 
95  "Disconnecting while the read thread is running is racy!");
96  lldb::ConnectionSP connection_sp(m_connection_sp);
97  if (connection_sp) {
98  ConnectionStatus status = connection_sp->Disconnect(error_ptr);
99  // We currently don't protect connection_sp with any mutex for multi-
100  // threaded environments. So lets not nuke our connection class without
101  // putting some multi-threaded protections in. We also probably don't want
102  // to pay for the overhead it might cause if every time we access the
103  // connection we have to take a lock.
104  //
105  // This unique pointer will cleanup after itself when this object goes
106  // away, so there is no need to currently have it destroy itself
107  // immediately upon disconnect.
108  // connection_sp.reset();
109  return status;
110  }
112 }
113 
115  lldb::ConnectionSP connection_sp(m_connection_sp);
116  return (connection_sp ? connection_sp->IsConnected() : false);
117 }
118 
120  return m_connection_sp.get() != nullptr;
121 }
122 
123 size_t Communication::Read(void *dst, size_t dst_len,
124  const Timeout<std::micro> &timeout,
125  ConnectionStatus &status, Status *error_ptr) {
127  LLDB_LOG(
128  log,
129  "this = {0}, dst = {1}, dst_len = {2}, timeout = {3}, connection = {4}",
130  this, dst, dst_len, timeout, m_connection_sp.get());
131 
132  if (m_read_thread_enabled) {
133  // We have a dedicated read thread that is getting data for us
134  size_t cached_bytes = GetCachedBytes(dst, dst_len);
135  if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
136  status = eConnectionStatusSuccess;
137  return cached_bytes;
138  }
139 
140  if (!m_connection_sp) {
141  if (error_ptr)
142  error_ptr->SetErrorString("Invalid connection.");
144  return 0;
145  }
146 
147  ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
148  listener_sp->StartListeningForEvents(
149  this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
150  EventSP event_sp;
151  while (listener_sp->GetEvent(event_sp, timeout)) {
152  const uint32_t event_type = event_sp->GetType();
153  if (event_type & eBroadcastBitReadThreadGotBytes) {
154  return GetCachedBytes(dst, dst_len);
155  }
156 
157  if (event_type & eBroadcastBitReadThreadDidExit) {
158  if (GetCloseOnEOF())
159  Disconnect(nullptr);
160  break;
161  }
162  }
163  return 0;
164  }
165 
166  // We aren't using a read thread, just read the data synchronously in this
167  // thread.
168  return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
169 }
170 
171 size_t Communication::Write(const void *src, size_t src_len,
172  ConnectionStatus &status, Status *error_ptr) {
173  lldb::ConnectionSP connection_sp(m_connection_sp);
174 
175  std::lock_guard<std::mutex> guard(m_write_mutex);
177  "{0} Communication::Write (src = {1}, src_len = {2}"
178  ") connection = {3}",
179  this, src, (uint64_t)src_len, connection_sp.get());
180 
181  if (connection_sp)
182  return connection_sp->Write(src, src_len, status, error_ptr);
183 
184  if (error_ptr)
185  error_ptr->SetErrorString("Invalid connection.");
187  return 0;
188 }
189 
190 size_t Communication::WriteAll(const void *src, size_t src_len,
191  ConnectionStatus &status, Status *error_ptr) {
192  size_t total_written = 0;
193  do
194  total_written += Write(static_cast<const char *>(src) + total_written,
195  src_len - total_written, status, error_ptr);
196  while (status == eConnectionStatusSuccess && total_written < src_len);
197  return total_written;
198 }
199 
201  if (error_ptr)
202  error_ptr->Clear();
203 
205  return true;
206 
208  "{0} Communication::StartReadThread ()", this);
209 
210  const std::string thread_name =
211  llvm::formatv("<lldb.comm.{0}>", GetBroadcasterName());
212 
213  m_read_thread_enabled = true;
214  m_read_thread_did_exit = false;
215  auto maybe_thread = ThreadLauncher::LaunchThread(
216  thread_name, [this] { return ReadThread(); });
217  if (maybe_thread) {
218  m_read_thread = *maybe_thread;
219  } else {
220  if (error_ptr)
221  *error_ptr = Status(maybe_thread.takeError());
222  else {
223  LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}",
224  llvm::toString(maybe_thread.takeError()));
225  }
226  }
227 
228  if (!m_read_thread.IsJoinable())
229  m_read_thread_enabled = false;
230 
231  return m_read_thread_enabled;
232 }
233 
235  if (!m_read_thread.IsJoinable())
236  return true;
237 
239  "{0} Communication::StopReadThread ()", this);
240 
241  m_read_thread_enabled = false;
242 
243  BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
244 
245  // error = m_read_thread.Cancel();
246 
247  Status error = m_read_thread.Join(nullptr);
248  return error.Success();
249 }
250 
252  if (!m_read_thread.IsJoinable())
253  return true;
254 
255  Status error = m_read_thread.Join(nullptr);
256  return error.Success();
257 }
258 
259 size_t Communication::GetCachedBytes(void *dst, size_t dst_len) {
260  std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
261  if (!m_bytes.empty()) {
262  // If DST is nullptr and we have a thread, then return the number of bytes
263  // that are available so the caller can call again
264  if (dst == nullptr)
265  return m_bytes.size();
266 
267  const size_t len = std::min<size_t>(dst_len, m_bytes.size());
268 
269  ::memcpy(dst, m_bytes.c_str(), len);
270  m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
271 
272  return len;
273  }
274  return 0;
275 }
276 
277 void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len,
278  bool broadcast,
279  ConnectionStatus status) {
281  "{0} Communication::AppendBytesToCache (src = {1}, src_len = {2}, "
282  "broadcast = {3})",
283  this, bytes, (uint64_t)len, broadcast);
284  if ((bytes == nullptr || len == 0) &&
286  return;
287  if (m_callback) {
288  // If the user registered a callback, then call it and do not broadcast
289  m_callback(m_callback_baton, bytes, len);
290  } else if (bytes != nullptr && len > 0) {
291  std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
292  m_bytes.append((const char *)bytes, len);
293  if (broadcast)
294  BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
295  }
296 }
297 
298 size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
299  const Timeout<std::micro> &timeout,
300  ConnectionStatus &status,
301  Status *error_ptr) {
302  lldb::ConnectionSP connection_sp(m_connection_sp);
303  if (connection_sp)
304  return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
305 
306  if (error_ptr)
307  error_ptr->SetErrorString("Invalid connection.");
309  return 0;
310 }
311 
313 
316 
317  LLDB_LOG(log, "Communication({0}) thread starting...", this);
318 
319  uint8_t buf[1024];
320 
321  Status error;
323  bool done = false;
324  bool disconnect = false;
325  while (!done && m_read_thread_enabled) {
326  size_t bytes_read = ReadFromConnection(
327  buf, sizeof(buf), std::chrono::seconds(5), status, &error);
328  if (bytes_read > 0 || status == eConnectionStatusEndOfFile)
329  AppendBytesToCache(buf, bytes_read, true, status);
330 
331  switch (status) {
333  break;
334 
336  done = true;
337  disconnect = GetCloseOnEOF();
338  break;
339  case eConnectionStatusError: // Check GetError() for details
340  if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
341  // EIO on a pipe is usually caused by remote shutdown
342  disconnect = GetCloseOnEOF();
343  done = true;
344  }
345  if (error.Fail())
346  LLDB_LOG(log, "error: {0}, status = {1}", error,
348  break;
349  case eConnectionStatusInterrupted: // Synchronization signal from
350  // SynchronizeWithReadThread()
351  // The connection returns eConnectionStatusInterrupted only when there is
352  // no input pending to be read, so we can signal that.
353  BroadcastEvent(eBroadcastBitNoMorePendingInput);
354  break;
355  case eConnectionStatusNoConnection: // No connection
356  case eConnectionStatusLostConnection: // Lost connection while connected to
357  // a valid connection
358  done = true;
359  LLVM_FALLTHROUGH;
360  case eConnectionStatusTimedOut: // Request timed out
361  if (error.Fail())
362  LLDB_LOG(log, "error: {0}, status = {1}", error,
364  break;
365  }
366  }
368  LLDB_LOG(log, "Communication({0}) thread exiting...", this);
369 
370  // Handle threads wishing to synchronize with us.
371  {
372  // Prevent new ones from showing up.
373  m_read_thread_did_exit = true;
374 
375  // Unblock any existing thread waiting for the synchronization signal.
376  BroadcastEvent(eBroadcastBitNoMorePendingInput);
377 
378  // Wait for the thread to finish...
379  std::lock_guard<std::mutex> guard(m_synchronize_mutex);
380  // ... and disconnect.
381  if (disconnect)
382  Disconnect();
383  }
384 
385  // Let clients know that this thread is exiting
386  BroadcastEvent(eBroadcastBitReadThreadDidExit);
387  return {};
388 }
389 
391  ReadThreadBytesReceived callback, void *callback_baton) {
392  m_callback = callback;
393  m_callback_baton = callback_baton;
394 }
395 
397  // Only one thread can do the synchronization dance at a time.
398  std::lock_guard<std::mutex> guard(m_synchronize_mutex);
399 
400  // First start listening for the synchronization event.
401  ListenerSP listener_sp(
402  Listener::MakeListener("Communication::SyncronizeWithReadThread"));
403  listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
404 
405  // If the thread is not running, there is no point in synchronizing.
407  return;
408 
409  // Notify the read thread.
410  m_connection_sp->InterruptRead();
411 
412  // Wait for the synchronization event.
413  EventSP event_sp;
414  listener_sp->GetEvent(event_sp, llvm::None);
415 }
416 
417 void Communication::SetConnection(std::unique_ptr<Connection> connection) {
418  Disconnect(nullptr);
419  StopReadThread(nullptr);
420  m_connection_sp = std::move(connection);
421 }
422 
425  switch (status) {
427  return "success";
429  return "error";
431  return "timed out";
433  return "no connection";
435  return "lost connection";
437  return "end of file";
439  return "interrupted";
440  }
441 
442  return "@" + std::to_string(status);
443 }
lldb_private::toString
const char * toString(AppleArm64ExceptionClass EC)
Definition: AppleArm64ExceptionClass.h:38
lldb_private::Broadcaster::CheckInWithManager
void CheckInWithManager()
Definition: Broadcaster.cpp:46
lldb_private::Communication::SynchronizeWithReadThread
void SynchronizeWithReadThread()
Wait for the read thread to process all outstanding data.
Definition: Communication.cpp:396
lldb_private::Communication::ReadThreadIsRunning
bool ReadThreadIsRunning()
Checks if there is a currently running read thread.
Definition: Communication.cpp:312
lldb_private::ThreadLauncher::LaunchThread
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
Definition: ThreadLauncher.cpp:25
lldb_private::Communication::AppendBytesToCache
virtual void AppendBytesToCache(const uint8_t *src, size_t src_len, bool broadcast, lldb::ConnectionStatus status)
Append new bytes that get read from the read thread into the internal object byte cache.
Definition: Communication.cpp:277
lldb_private::Communication::m_callback
ReadThreadBytesReceived m_callback
Definition: Communication.h:330
lldb_private::Communication::ConnectionStatusAsString
static std::string ConnectionStatusAsString(lldb::ConnectionStatus status)
Definition: Communication.cpp:424
lldb_private::Communication::GetCachedBytes
size_t GetCachedBytes(void *dst, size_t dst_len)
Get any available bytes from our data cache.
Definition: Communication.cpp:259
lldb_private::Communication::m_write_mutex
std::mutex m_write_mutex
Don't let multiple threads write at the same time...
Definition: Communication.h:328
lldb_private::Broadcaster::SetEventName
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
Definition: Broadcaster.h:337
ReadThreadBytesReceived
static void ReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition: ScriptInterpreter.cpp:139
lldb_private::LLDBLog::Host
@ Host
lldb_private::Communication::m_connection_sp
lldb::ConnectionSP m_connection_sp
The connection that is current in use by this communications class.
Definition: Communication.h:317
lldb::eConnectionStatusNoConnection
@ eConnectionStatusNoConnection
No connection.
Definition: lldb-enumerations.h:300
Listener.h
ThreadLauncher.h
lldb::eConnectionStatusEndOfFile
@ eConnectionStatusEndOfFile
End-of-file encountered.
Definition: lldb-enumerations.h:297
lldb_private::Communication::m_callback_baton
void * m_callback_baton
Definition: Communication.h:331
lldb::eErrorTypePOSIX
@ eErrorTypePOSIX
POSIX error codes.
Definition: lldb-enumerations.h:310
lldb_private::Communication::~Communication
~Communication() override
Destructor.
Definition: Communication.cpp:63
lldb_private::Communication::SetConnection
void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
Definition: Communication.cpp:417
lldb_private::Communication::WriteAll
size_t WriteAll(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
Repeatedly attempt writing until either src_len bytes are written or a permanent failure occurs.
Definition: Communication.cpp:190
lldb_private::Communication::m_read_thread
HostThread m_read_thread
The read thread handle in case we need to cancel the thread.
Definition: Communication.h:319
error
static llvm::raw_ostream & error(Stream &strm)
Definition: CommandReturnObject.cpp:17
HostThread.h
lldb_private::Communication::ReadFromConnection
size_t ReadFromConnection(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Definition: Communication.cpp:298
lldb_private::Communication::m_read_thread_did_exit
std::atomic< bool > m_read_thread_did_exit
Definition: Communication.h:322
Log.h
lldb_private::Communication::ReadThread
lldb::thread_result_t ReadThread()
The read thread function.
Definition: Communication.cpp:314
lldb_private::Communication::Clear
void Clear()
Definition: Communication.cpp:70
lldb_private::Broadcaster::BroadcastEventIfUnique
void BroadcastEventIfUnique(lldb::EventSP &event_sp)
Definition: Broadcaster.h:266
lldb_private::ConstString
Definition: ConstString.h:40
lldb_private::Communication::StartReadThread
virtual bool StartReadThread(Status *error_ptr=nullptr)
Starts a read thread whose sole purpose it to read bytes from the current connection.
Definition: Communication.cpp:200
lldb::eConnectionStatusTimedOut
@ eConnectionStatusTimedOut
Request timed out.
Definition: lldb-enumerations.h:299
lldb::ConnectionStatus
ConnectionStatus
Connection Status Types.
Definition: lldb-enumerations.h:295
lldb_private::Communication::SetReadThreadBytesReceivedCallback
void SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback, void *callback_baton)
Definition: Communication.cpp:390
lldb::eConnectionStatusInterrupted
@ eConnectionStatusInterrupted
Interrupted read.
Definition: lldb-enumerations.h:303
lldb_private::Communication::StopReadThread
virtual bool StopReadThread(Status *error_ptr=nullptr)
Stops the read thread by cancelling it.
Definition: Communication.cpp:234
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:40
Communication.h
lldb_private::Communication::Write
size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
The actual write function that attempts to write to the communications protocol.
Definition: Communication.cpp:171
lldb_private::Communication::m_synchronize_mutex
std::mutex m_synchronize_mutex
Definition: Communication.h:329
Event.h
Connection.h
lldb_private::Broadcaster::BroadcastEvent
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
Definition: Broadcaster.h:262
lldb_private::LLDBLog::Communication
@ Communication
lldb_private::Communication::Disconnect
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
Definition: Communication.cpp:90
lldb_private::HostThread::Join
Status Join(lldb::thread_result_t *result)
Definition: HostThread.cpp:20
lldb_private::Communication::HasConnection
bool HasConnection() const
Definition: Communication.cpp:119
lldb_private::Status
Definition: Status.h:44
lldb_private::Timeout< std::micro >
lldb_private::Communication::Read
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
Definition: Communication.cpp:123
uint32_t
lldb::thread_result_t
void * thread_result_t
Definition: lldb-types.h:62
lldb::eConnectionStatusError
@ eConnectionStatusError
Check GetError() for details.
Definition: lldb-enumerations.h:298
lldb_private::LLDBLog::Object
@ Object
lldb_private::Status::SetErrorString
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
lldb_private::Communication::IsConnected
bool IsConnected() const
Check if the connection is valid.
Definition: Communication.cpp:114
lldb_private::Communication::GetCloseOnEOF
bool GetCloseOnEOF() const
Definition: Communication.h:306
LLDB_LOG
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:336
lldb::eConnectionStatusSuccess
@ eConnectionStatusSuccess
Success.
Definition: lldb-enumerations.h:296
Status.h
lldb_private::Broadcaster::GetBroadcasterName
ConstString GetBroadcasterName()
Get the NULL terminated C string name of this Broadcaster object.
Definition: Broadcaster.h:317
lldb_private::HostThread::IsJoinable
bool IsJoinable() const
Definition: HostThread.cpp:30
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::Status::Clear
void Clear()
Clear the object state.
Definition: Status.cpp:167
ConstString.h
lldb::eConnectionStatusLostConnection
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
Definition: lldb-enumerations.h:301
lldb_private::Log
Definition: Log.h:115
lldb_private::Listener::MakeListener
static lldb::ListenerSP MakeListener(const char *name)
Definition: Listener.cpp:461
lldb_private::Communication::m_read_thread_enabled
std::atomic< bool > m_read_thread_enabled
Definition: Communication.h:321
lldb_private::GetLog
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:308
lldb_private::Broadcaster
Definition: Broadcaster.h:242
lldb
Definition: SBAddress.h:15
lldb_private::Communication::JoinReadThread
virtual bool JoinReadThread(Status *error_ptr=nullptr)
Definition: Communication.cpp:251
lldb_private::Communication::m_bytes
std::string m_bytes
A buffer to cache bytes read in the ReadThread function.
Definition: Communication.h:324
LLDBLog.h
lldb_private::Communication::m_bytes_mutex
std::recursive_mutex m_bytes_mutex
A mutex to protect multi-threaded access to the cached bytes.
Definition: Communication.h:325
lldb_private::Communication::Connect
lldb::ConnectionStatus Connect(const char *url, Status *error_ptr)
Connect using the current connection by passing url to its connect function.
Definition: Communication.cpp:76