1 //===-- Communication.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/Communication.h"
12 #include "lldb/Core/Event.h"
13 #include "lldb/Core/Listener.h"
14 #include "lldb/Host/HostThread.h"
15 #include "lldb/Host/ThreadLauncher.h"
16 #include "lldb/Utility/Connection.h"
17 #include "lldb/Utility/ConstString.h" // for ConstString
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/Logging.h" // for LogIfAnyCategoriesSet, LIBLLDB...
20 #include "lldb/Utility/Status.h" // for Status
22 #include "llvm/ADT/None.h" // for None
23 #include "llvm/ADT/Optional.h" // for Optional
24 #include "llvm/Support/Compiler.h" // for LLVM_FALLTHROUGH
26 #include <algorithm> // for min
27 #include <chrono> // for duration, seconds
29 #include <memory> // for shared_ptr
31 #include <errno.h> // for EIO
32 #include <inttypes.h> // for PRIu64
33 #include <stdio.h> // for snprintf
36 using namespace lldb_private;
38 ConstString &Communication::GetStaticBroadcasterClass() {
39 static ConstString class_name("lldb.communication");
43 Communication::Communication(const char *name)
44 : Broadcaster(nullptr, name), m_connection_sp(),
45 m_read_thread_enabled(false), m_read_thread_did_exit(false), m_bytes(),
46 m_bytes_mutex(), m_write_mutex(), m_synchronize_mutex(),
47 m_callback(nullptr), m_callback_baton(nullptr), m_close_on_eof(true)
50 lldb_private::LogIfAnyCategoriesSet(
51 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
52 "%p Communication::Communication (name = %s)", this, name);
54 SetEventName(eBroadcastBitDisconnected, "disconnected");
55 SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes");
56 SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit");
57 SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit");
58 SetEventName(eBroadcastBitPacketAvailable, "packet available");
59 SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input");
64 Communication::~Communication() {
65 lldb_private::LogIfAnyCategoriesSet(
66 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
67 "%p Communication::~Communication (name = %s)", this,
68 GetBroadcasterName().AsCString());
72 void Communication::Clear() {
73 SetReadThreadBytesReceivedCallback(nullptr, nullptr);
75 StopReadThread(nullptr);
78 ConnectionStatus Communication::Connect(const char *url, Status *error_ptr) {
81 lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
82 "%p Communication::Connect (url = %s)",
85 lldb::ConnectionSP connection_sp(m_connection_sp);
87 return connection_sp->Connect(url, error_ptr);
89 error_ptr->SetErrorString("Invalid connection.");
90 return eConnectionStatusNoConnection;
93 ConnectionStatus Communication::Disconnect(Status *error_ptr) {
94 lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
95 "%p Communication::Disconnect ()", this);
97 lldb::ConnectionSP connection_sp(m_connection_sp);
99 ConnectionStatus status = connection_sp->Disconnect(error_ptr);
100 // We currently don't protect connection_sp with any mutex for multi-
101 // threaded environments. So lets not nuke our connection class without
102 // putting some multi-threaded protections in. We also probably don't want
103 // to pay for the overhead it might cause if every time we access the
104 // connection we have to take a lock.
106 // This unique pointer will cleanup after itself when this object goes
107 // away, so there is no need to currently have it destroy itself
108 // immediately upon disconnect.
109 // connection_sp.reset();
112 return eConnectionStatusNoConnection;
115 bool Communication::IsConnected() const {
116 lldb::ConnectionSP connection_sp(m_connection_sp);
117 return (connection_sp ? connection_sp->IsConnected() : false);
120 bool Communication::HasConnection() const {
121 return m_connection_sp.get() != nullptr;
124 size_t Communication::Read(void *dst, size_t dst_len,
125 const Timeout<std::micro> &timeout,
126 ConnectionStatus &status, Status *error_ptr) {
127 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
130 "this = {0}, dst = {1}, dst_len = {2}, timeout = {3}, connection = {4}",
131 this, dst, dst_len, timeout, m_connection_sp.get());
133 if (m_read_thread_enabled) {
134 // We have a dedicated read thread that is getting data for us
135 size_t cached_bytes = GetCachedBytes(dst, dst_len);
136 if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
137 status = eConnectionStatusSuccess;
141 if (!m_connection_sp) {
143 error_ptr->SetErrorString("Invalid connection.");
144 status = eConnectionStatusNoConnection;
148 ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
149 listener_sp->StartListeningForEvents(
150 this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
152 while (listener_sp->GetEvent(event_sp, timeout)) {
153 const uint32_t event_type = event_sp->GetType();
154 if (event_type & eBroadcastBitReadThreadGotBytes) {
155 return GetCachedBytes(dst, dst_len);
158 if (event_type & eBroadcastBitReadThreadDidExit) {
167 // We aren't using a read thread, just read the data synchronously in this
169 return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
172 size_t Communication::Write(const void *src, size_t src_len,
173 ConnectionStatus &status, Status *error_ptr) {
174 lldb::ConnectionSP connection_sp(m_connection_sp);
176 std::lock_guard<std::mutex> guard(m_write_mutex);
177 lldb_private::LogIfAnyCategoriesSet(
178 LIBLLDB_LOG_COMMUNICATION,
179 "%p Communication::Write (src = %p, src_len = %" PRIu64
181 this, src, (uint64_t)src_len, connection_sp.get());
184 return connection_sp->Write(src, src_len, status, error_ptr);
187 error_ptr->SetErrorString("Invalid connection.");
188 status = eConnectionStatusNoConnection;
192 bool Communication::StartReadThread(Status *error_ptr) {
196 if (m_read_thread.IsJoinable())
199 lldb_private::LogIfAnyCategoriesSet(
200 LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this);
202 char thread_name[1024];
203 snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>",
204 GetBroadcasterName().AsCString());
206 m_read_thread_enabled = true;
207 m_read_thread_did_exit = false;
208 m_read_thread = ThreadLauncher::LaunchThread(
209 thread_name, Communication::ReadThread, this, error_ptr);
210 if (!m_read_thread.IsJoinable())
211 m_read_thread_enabled = false;
212 return m_read_thread_enabled;
215 bool Communication::StopReadThread(Status *error_ptr) {
216 if (!m_read_thread.IsJoinable())
219 lldb_private::LogIfAnyCategoriesSet(
220 LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this);
222 m_read_thread_enabled = false;
224 BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
226 // error = m_read_thread.Cancel();
228 Status error = m_read_thread.Join(nullptr);
229 return error.Success();
232 bool Communication::JoinReadThread(Status *error_ptr) {
233 if (!m_read_thread.IsJoinable())
236 Status error = m_read_thread.Join(nullptr);
237 return error.Success();
240 size_t Communication::GetCachedBytes(void *dst, size_t dst_len) {
241 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
242 if (!m_bytes.empty()) {
243 // If DST is nullptr and we have a thread, then return the number of bytes
244 // that are available so the caller can call again
246 return m_bytes.size();
248 const size_t len = std::min<size_t>(dst_len, m_bytes.size());
250 ::memcpy(dst, m_bytes.c_str(), len);
251 m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
258 void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len,
260 ConnectionStatus status) {
261 lldb_private::LogIfAnyCategoriesSet(
262 LIBLLDB_LOG_COMMUNICATION,
263 "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64
265 this, bytes, (uint64_t)len, broadcast);
266 if ((bytes == nullptr || len == 0) &&
267 (status != lldb::eConnectionStatusEndOfFile))
270 // If the user registered a callback, then call it and do not broadcast
271 m_callback(m_callback_baton, bytes, len);
272 } else if (bytes != nullptr && len > 0) {
273 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
274 m_bytes.append((const char *)bytes, len);
276 BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
280 size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
281 const Timeout<std::micro> &timeout,
282 ConnectionStatus &status,
284 lldb::ConnectionSP connection_sp(m_connection_sp);
286 return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
289 error_ptr->SetErrorString("Invalid connection.");
290 status = eConnectionStatusNoConnection;
294 bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
296 lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) {
297 Communication *comm = (Communication *)p;
299 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
302 log->Printf("%p Communication::ReadThread () thread starting...", p);
307 ConnectionStatus status = eConnectionStatusSuccess;
309 while (!done && comm->m_read_thread_enabled) {
310 size_t bytes_read = comm->ReadFromConnection(
311 buf, sizeof(buf), std::chrono::seconds(5), status, &error);
313 comm->AppendBytesToCache(buf, bytes_read, true, status);
314 else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) {
315 if (comm->GetCloseOnEOF())
317 comm->AppendBytesToCache(buf, bytes_read, true, status);
321 case eConnectionStatusSuccess:
324 case eConnectionStatusEndOfFile:
327 case eConnectionStatusError: // Check GetError() for details
328 if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
329 // EIO on a pipe is usually caused by remote shutdown
334 LLDB_LOG(log, "error: {0}, status = {1}", error,
335 Communication::ConnectionStatusAsCString(status));
337 case eConnectionStatusInterrupted: // Synchronization signal from
338 // SynchronizeWithReadThread()
339 // The connection returns eConnectionStatusInterrupted only when there is
340 // no input pending to be read, so we can signal that.
341 comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
343 case eConnectionStatusNoConnection: // No connection
344 case eConnectionStatusLostConnection: // Lost connection while connected to
345 // a valid connection
348 case eConnectionStatusTimedOut: // Request timed out
350 LLDB_LOG(log, "error: {0}, status = {1}", error,
351 Communication::ConnectionStatusAsCString(status));
355 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
357 log->Printf("%p Communication::ReadThread () thread exiting...", p);
359 comm->m_read_thread_did_exit = true;
360 // Let clients know that this thread is exiting
361 comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
362 comm->BroadcastEvent(eBroadcastBitReadThreadDidExit);
366 void Communication::SetReadThreadBytesReceivedCallback(
367 ReadThreadBytesReceived callback, void *callback_baton) {
368 m_callback = callback;
369 m_callback_baton = callback_baton;
372 void Communication::SynchronizeWithReadThread() {
373 // Only one thread can do the synchronization dance at a time.
374 std::lock_guard<std::mutex> guard(m_synchronize_mutex);
376 // First start listening for the synchronization event.
377 ListenerSP listener_sp(
378 Listener::MakeListener("Communication::SyncronizeWithReadThread"));
379 listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
381 // If the thread is not running, there is no point in synchronizing.
382 if (!m_read_thread_enabled || m_read_thread_did_exit)
385 // Notify the read thread.
386 m_connection_sp->InterruptRead();
388 // Wait for the synchronization event.
390 listener_sp->GetEvent(event_sp, llvm::None);
393 void Communication::SetConnection(Connection *connection) {
395 StopReadThread(nullptr);
396 m_connection_sp.reset(connection);
400 Communication::ConnectionStatusAsCString(lldb::ConnectionStatus status) {
402 case eConnectionStatusSuccess:
404 case eConnectionStatusError:
406 case eConnectionStatusTimedOut:
408 case eConnectionStatusNoConnection:
409 return "no connection";
410 case eConnectionStatusLostConnection:
411 return "lost connection";
412 case eConnectionStatusEndOfFile:
413 return "end of file";
414 case eConnectionStatusInterrupted:
415 return "interrupted";
418 static char unknown_state_string[64];
419 snprintf(unknown_state_string, sizeof(unknown_state_string),
420 "ConnectionStatus = %i", status);
421 return unknown_state_string;