1 //===-- Communication.cpp ---------------------------------------*- 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 // C Includes
11 // C++ Includes
12 #include <cstring>
13 
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Core/Communication.h"
17 #include "lldb/Core/Connection.h"
18 #include "lldb/Core/Event.h"
19 #include "lldb/Core/Listener.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/Timer.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Host/HostThread.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 ConstString &Communication::GetStaticBroadcasterClass() {
30   static ConstString class_name("lldb.communication");
31   return class_name;
32 }
33 
34 Communication::Communication(const char *name)
35     : Broadcaster(nullptr, name), m_connection_sp(),
36       m_read_thread_enabled(false), m_read_thread_did_exit(false), m_bytes(),
37       m_bytes_mutex(), m_write_mutex(), m_synchronize_mutex(),
38       m_callback(nullptr), m_callback_baton(nullptr), m_close_on_eof(true)
39 
40 {
41   lldb_private::LogIfAnyCategoriesSet(
42       LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
43       "%p Communication::Communication (name = %s)", this, name);
44 
45   SetEventName(eBroadcastBitDisconnected, "disconnected");
46   SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes");
47   SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit");
48   SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit");
49   SetEventName(eBroadcastBitPacketAvailable, "packet available");
50   SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input");
51 
52   CheckInWithManager();
53 }
54 
55 Communication::~Communication() {
56   lldb_private::LogIfAnyCategoriesSet(
57       LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
58       "%p Communication::~Communication (name = %s)", this,
59       GetBroadcasterName().AsCString());
60   Clear();
61 }
62 
63 void Communication::Clear() {
64   SetReadThreadBytesReceivedCallback(nullptr, nullptr);
65   Disconnect(nullptr);
66   StopReadThread(nullptr);
67 }
68 
69 ConnectionStatus Communication::Connect(const char *url, Error *error_ptr) {
70   Clear();
71 
72   lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
73                                       "%p Communication::Connect (url = %s)",
74                                       this, url);
75 
76   lldb::ConnectionSP connection_sp(m_connection_sp);
77   if (connection_sp)
78     return connection_sp->Connect(url, error_ptr);
79   if (error_ptr)
80     error_ptr->SetErrorString("Invalid connection.");
81   return eConnectionStatusNoConnection;
82 }
83 
84 ConnectionStatus Communication::Disconnect(Error *error_ptr) {
85   lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
86                                       "%p Communication::Disconnect ()", this);
87 
88   lldb::ConnectionSP connection_sp(m_connection_sp);
89   if (connection_sp) {
90     ConnectionStatus status = connection_sp->Disconnect(error_ptr);
91     // We currently don't protect connection_sp with any mutex for
92     // multi-threaded environments. So lets not nuke our connection class
93     // without putting some multi-threaded protections in. We also probably
94     // don't want to pay for the overhead it might cause if every time we
95     // access the connection we have to take a lock.
96     //
97     // This unique pointer will cleanup after itself when this object goes away,
98     // so there is no need to currently have it destroy itself immediately
99     // upon disconnnect.
100     // connection_sp.reset();
101     return status;
102   }
103   return eConnectionStatusNoConnection;
104 }
105 
106 bool Communication::IsConnected() const {
107   lldb::ConnectionSP connection_sp(m_connection_sp);
108   return (connection_sp ? connection_sp->IsConnected() : false);
109 }
110 
111 bool Communication::HasConnection() const {
112   return m_connection_sp.get() != nullptr;
113 }
114 
115 size_t Communication::Read(void *dst, size_t dst_len,
116                            const Timeout<std::micro> &timeout,
117                            ConnectionStatus &status, Error *error_ptr) {
118   using std::chrono::microseconds;
119 
120   lldb_private::LogIfAnyCategoriesSet(
121       LIBLLDB_LOG_COMMUNICATION,
122       "%p Communication::Read (dst = %p, dst_len = %" PRIu64
123       ", timeout = %u usec) connection = %p",
124       this, dst, (uint64_t)dst_len, timeout ? timeout->count() : -1,
125       m_connection_sp.get());
126 
127   if (m_read_thread_enabled) {
128     // We have a dedicated read thread that is getting data for us
129     size_t cached_bytes = GetCachedBytes(dst, dst_len);
130     if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
131       status = eConnectionStatusSuccess;
132       return cached_bytes;
133     }
134 
135     if (!m_connection_sp) {
136       if (error_ptr)
137         error_ptr->SetErrorString("Invalid connection.");
138       status = eConnectionStatusNoConnection;
139       return 0;
140     }
141 
142     ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
143     listener_sp->StartListeningForEvents(
144         this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
145     EventSP event_sp;
146     microseconds listener_timeout =
147         timeout ? microseconds(*timeout) : microseconds(0);
148     while (listener_sp->WaitForEvent(listener_timeout, event_sp)) {
149       const uint32_t event_type = event_sp->GetType();
150       if (event_type & eBroadcastBitReadThreadGotBytes) {
151         return GetCachedBytes(dst, dst_len);
152       }
153 
154       if (event_type & eBroadcastBitReadThreadDidExit) {
155         if (GetCloseOnEOF())
156           Disconnect(nullptr);
157         break;
158       }
159     }
160     return 0;
161   }
162 
163   // We aren't using a read thread, just read the data synchronously in this
164   // thread.
165   return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
166 }
167 
168 size_t Communication::Write(const void *src, size_t src_len,
169                             ConnectionStatus &status, Error *error_ptr) {
170   lldb::ConnectionSP connection_sp(m_connection_sp);
171 
172   std::lock_guard<std::mutex> guard(m_write_mutex);
173   lldb_private::LogIfAnyCategoriesSet(
174       LIBLLDB_LOG_COMMUNICATION,
175       "%p Communication::Write (src = %p, src_len = %" PRIu64
176       ") connection = %p",
177       this, src, (uint64_t)src_len, connection_sp.get());
178 
179   if (connection_sp)
180     return connection_sp->Write(src, src_len, status, error_ptr);
181 
182   if (error_ptr)
183     error_ptr->SetErrorString("Invalid connection.");
184   status = eConnectionStatusNoConnection;
185   return 0;
186 }
187 
188 bool Communication::StartReadThread(Error *error_ptr) {
189   if (error_ptr)
190     error_ptr->Clear();
191 
192   if (m_read_thread.IsJoinable())
193     return true;
194 
195   lldb_private::LogIfAnyCategoriesSet(
196       LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this);
197 
198   char thread_name[1024];
199   snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>",
200            GetBroadcasterName().AsCString());
201 
202   m_read_thread_enabled = true;
203   m_read_thread_did_exit = false;
204   m_read_thread = ThreadLauncher::LaunchThread(
205       thread_name, Communication::ReadThread, this, error_ptr);
206   if (!m_read_thread.IsJoinable())
207     m_read_thread_enabled = false;
208   return m_read_thread_enabled;
209 }
210 
211 bool Communication::StopReadThread(Error *error_ptr) {
212   if (!m_read_thread.IsJoinable())
213     return true;
214 
215   lldb_private::LogIfAnyCategoriesSet(
216       LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this);
217 
218   m_read_thread_enabled = false;
219 
220   BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
221 
222   // error = m_read_thread.Cancel();
223 
224   Error error = m_read_thread.Join(nullptr);
225   return error.Success();
226 }
227 
228 bool Communication::JoinReadThread(Error *error_ptr) {
229   if (!m_read_thread.IsJoinable())
230     return true;
231 
232   Error error = m_read_thread.Join(nullptr);
233   return error.Success();
234 }
235 
236 size_t Communication::GetCachedBytes(void *dst, size_t dst_len) {
237   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
238   if (!m_bytes.empty()) {
239     // If DST is nullptr and we have a thread, then return the number
240     // of bytes that are available so the caller can call again
241     if (dst == nullptr)
242       return m_bytes.size();
243 
244     const size_t len = std::min<size_t>(dst_len, m_bytes.size());
245 
246     ::memcpy(dst, m_bytes.c_str(), len);
247     m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
248 
249     return len;
250   }
251   return 0;
252 }
253 
254 void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len,
255                                        bool broadcast,
256                                        ConnectionStatus status) {
257   lldb_private::LogIfAnyCategoriesSet(
258       LIBLLDB_LOG_COMMUNICATION,
259       "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64
260       ", broadcast = %i)",
261       this, bytes, (uint64_t)len, broadcast);
262   if ((bytes == nullptr || len == 0) &&
263       (status != lldb::eConnectionStatusEndOfFile))
264     return;
265   if (m_callback) {
266     // If the user registered a callback, then call it and do not broadcast
267     m_callback(m_callback_baton, bytes, len);
268   } else if (bytes != nullptr && len > 0) {
269     std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
270     m_bytes.append((const char *)bytes, len);
271     if (broadcast)
272       BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
273   }
274 }
275 
276 size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
277                                          const Timeout<std::micro> &timeout,
278                                          ConnectionStatus &status,
279                                          Error *error_ptr) {
280   lldb::ConnectionSP connection_sp(m_connection_sp);
281   if (connection_sp)
282     return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
283 
284   if (error_ptr)
285     error_ptr->SetErrorString("Invalid connection.");
286   status = eConnectionStatusNoConnection;
287   return 0;
288 }
289 
290 bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
291 
292 lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) {
293   Communication *comm = (Communication *)p;
294 
295   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
296 
297   if (log)
298     log->Printf("%p Communication::ReadThread () thread starting...", p);
299 
300   uint8_t buf[1024];
301 
302   Error error;
303   ConnectionStatus status = eConnectionStatusSuccess;
304   bool done = false;
305   while (!done && comm->m_read_thread_enabled) {
306     size_t bytes_read = comm->ReadFromConnection(
307         buf, sizeof(buf), std::chrono::seconds(5), status, &error);
308     if (bytes_read > 0)
309       comm->AppendBytesToCache(buf, bytes_read, true, status);
310     else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) {
311       if (comm->GetCloseOnEOF())
312         comm->Disconnect();
313       comm->AppendBytesToCache(buf, bytes_read, true, status);
314     }
315 
316     switch (status) {
317     case eConnectionStatusSuccess:
318       break;
319 
320     case eConnectionStatusEndOfFile:
321       done = true;
322       break;
323     case eConnectionStatusError: // Check GetError() for details
324       if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
325         // EIO on a pipe is usually caused by remote shutdown
326         comm->Disconnect();
327         done = true;
328       }
329       if (log)
330         error.LogIfError(
331             log, "%p Communication::ReadFromConnection () => status = %s", p,
332             Communication::ConnectionStatusAsCString(status));
333       break;
334     case eConnectionStatusInterrupted: // Synchronization signal from
335                                        // SynchronizeWithReadThread()
336       // The connection returns eConnectionStatusInterrupted only when there is
337       // no
338       // input pending to be read, so we can signal that.
339       comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
340       break;
341     case eConnectionStatusNoConnection:   // No connection
342     case eConnectionStatusLostConnection: // Lost connection while connected to
343                                           // a valid connection
344       done = true;
345       LLVM_FALLTHROUGH;
346     case eConnectionStatusTimedOut: // Request timed out
347       if (log)
348         error.LogIfError(
349             log, "%p Communication::ReadFromConnection () => status = %s", p,
350             Communication::ConnectionStatusAsCString(status));
351       break;
352     }
353   }
354   log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
355   if (log)
356     log->Printf("%p Communication::ReadThread () thread exiting...", p);
357 
358   comm->m_read_thread_did_exit = true;
359   // Let clients know that this thread is exiting
360   comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
361   comm->BroadcastEvent(eBroadcastBitReadThreadDidExit);
362   return NULL;
363 }
364 
365 void Communication::SetReadThreadBytesReceivedCallback(
366     ReadThreadBytesReceived callback, void *callback_baton) {
367   m_callback = callback;
368   m_callback_baton = callback_baton;
369 }
370 
371 void Communication::SynchronizeWithReadThread() {
372   // Only one thread can do the synchronization dance at a time.
373   std::lock_guard<std::mutex> guard(m_synchronize_mutex);
374 
375   // First start listening for the synchronization event.
376   ListenerSP listener_sp(
377       Listener::MakeListener("Communication::SyncronizeWithReadThread"));
378   listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
379 
380   // If the thread is not running, there is no point in synchronizing.
381   if (!m_read_thread_enabled || m_read_thread_did_exit)
382     return;
383 
384   // Notify the read thread.
385   m_connection_sp->InterruptRead();
386 
387   // Wait for the synchronization event.
388   EventSP event_sp;
389   listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
390 }
391 
392 void Communication::SetConnection(Connection *connection) {
393   Disconnect(nullptr);
394   StopReadThread(nullptr);
395   m_connection_sp.reset(connection);
396 }
397 
398 const char *
399 Communication::ConnectionStatusAsCString(lldb::ConnectionStatus status) {
400   switch (status) {
401   case eConnectionStatusSuccess:
402     return "success";
403   case eConnectionStatusError:
404     return "error";
405   case eConnectionStatusTimedOut:
406     return "timed out";
407   case eConnectionStatusNoConnection:
408     return "no connection";
409   case eConnectionStatusLostConnection:
410     return "lost connection";
411   case eConnectionStatusEndOfFile:
412     return "end of file";
413   case eConnectionStatusInterrupted:
414     return "interrupted";
415   }
416 
417   static char unknown_state_string[64];
418   snprintf(unknown_state_string, sizeof(unknown_state_string),
419            "ConnectionStatus = %i", status);
420   return unknown_state_string;
421 }
422