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/Timer.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Host/HostThread.h"
23 #include "lldb/Host/ThreadLauncher.h"
24 #include "lldb/Utility/Log.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   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
119   LLDB_LOG(
120       log,
121       "this = {0}, dst = {1}, dst_len = {2}, timeout = {3}, connection = {4}",
122       this, dst, dst_len, timeout, m_connection_sp.get());
123 
124   if (m_read_thread_enabled) {
125     // We have a dedicated read thread that is getting data for us
126     size_t cached_bytes = GetCachedBytes(dst, dst_len);
127     if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
128       status = eConnectionStatusSuccess;
129       return cached_bytes;
130     }
131 
132     if (!m_connection_sp) {
133       if (error_ptr)
134         error_ptr->SetErrorString("Invalid connection.");
135       status = eConnectionStatusNoConnection;
136       return 0;
137     }
138 
139     ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
140     listener_sp->StartListeningForEvents(
141         this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
142     EventSP event_sp;
143     while (listener_sp->GetEvent(event_sp, timeout)) {
144       const uint32_t event_type = event_sp->GetType();
145       if (event_type & eBroadcastBitReadThreadGotBytes) {
146         return GetCachedBytes(dst, dst_len);
147       }
148 
149       if (event_type & eBroadcastBitReadThreadDidExit) {
150         if (GetCloseOnEOF())
151           Disconnect(nullptr);
152         break;
153       }
154     }
155     return 0;
156   }
157 
158   // We aren't using a read thread, just read the data synchronously in this
159   // thread.
160   return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
161 }
162 
163 size_t Communication::Write(const void *src, size_t src_len,
164                             ConnectionStatus &status, Error *error_ptr) {
165   lldb::ConnectionSP connection_sp(m_connection_sp);
166 
167   std::lock_guard<std::mutex> guard(m_write_mutex);
168   lldb_private::LogIfAnyCategoriesSet(
169       LIBLLDB_LOG_COMMUNICATION,
170       "%p Communication::Write (src = %p, src_len = %" PRIu64
171       ") connection = %p",
172       this, src, (uint64_t)src_len, connection_sp.get());
173 
174   if (connection_sp)
175     return connection_sp->Write(src, src_len, status, error_ptr);
176 
177   if (error_ptr)
178     error_ptr->SetErrorString("Invalid connection.");
179   status = eConnectionStatusNoConnection;
180   return 0;
181 }
182 
183 bool Communication::StartReadThread(Error *error_ptr) {
184   if (error_ptr)
185     error_ptr->Clear();
186 
187   if (m_read_thread.IsJoinable())
188     return true;
189 
190   lldb_private::LogIfAnyCategoriesSet(
191       LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this);
192 
193   char thread_name[1024];
194   snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>",
195            GetBroadcasterName().AsCString());
196 
197   m_read_thread_enabled = true;
198   m_read_thread_did_exit = false;
199   m_read_thread = ThreadLauncher::LaunchThread(
200       thread_name, Communication::ReadThread, this, error_ptr);
201   if (!m_read_thread.IsJoinable())
202     m_read_thread_enabled = false;
203   return m_read_thread_enabled;
204 }
205 
206 bool Communication::StopReadThread(Error *error_ptr) {
207   if (!m_read_thread.IsJoinable())
208     return true;
209 
210   lldb_private::LogIfAnyCategoriesSet(
211       LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this);
212 
213   m_read_thread_enabled = false;
214 
215   BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
216 
217   // error = m_read_thread.Cancel();
218 
219   Error error = m_read_thread.Join(nullptr);
220   return error.Success();
221 }
222 
223 bool Communication::JoinReadThread(Error *error_ptr) {
224   if (!m_read_thread.IsJoinable())
225     return true;
226 
227   Error error = m_read_thread.Join(nullptr);
228   return error.Success();
229 }
230 
231 size_t Communication::GetCachedBytes(void *dst, size_t dst_len) {
232   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
233   if (!m_bytes.empty()) {
234     // If DST is nullptr and we have a thread, then return the number
235     // of bytes that are available so the caller can call again
236     if (dst == nullptr)
237       return m_bytes.size();
238 
239     const size_t len = std::min<size_t>(dst_len, m_bytes.size());
240 
241     ::memcpy(dst, m_bytes.c_str(), len);
242     m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
243 
244     return len;
245   }
246   return 0;
247 }
248 
249 void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len,
250                                        bool broadcast,
251                                        ConnectionStatus status) {
252   lldb_private::LogIfAnyCategoriesSet(
253       LIBLLDB_LOG_COMMUNICATION,
254       "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64
255       ", broadcast = %i)",
256       this, bytes, (uint64_t)len, broadcast);
257   if ((bytes == nullptr || len == 0) &&
258       (status != lldb::eConnectionStatusEndOfFile))
259     return;
260   if (m_callback) {
261     // If the user registered a callback, then call it and do not broadcast
262     m_callback(m_callback_baton, bytes, len);
263   } else if (bytes != nullptr && len > 0) {
264     std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
265     m_bytes.append((const char *)bytes, len);
266     if (broadcast)
267       BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
268   }
269 }
270 
271 size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
272                                          const Timeout<std::micro> &timeout,
273                                          ConnectionStatus &status,
274                                          Error *error_ptr) {
275   lldb::ConnectionSP connection_sp(m_connection_sp);
276   if (connection_sp)
277     return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
278 
279   if (error_ptr)
280     error_ptr->SetErrorString("Invalid connection.");
281   status = eConnectionStatusNoConnection;
282   return 0;
283 }
284 
285 bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
286 
287 lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) {
288   Communication *comm = (Communication *)p;
289 
290   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
291 
292   if (log)
293     log->Printf("%p Communication::ReadThread () thread starting...", p);
294 
295   uint8_t buf[1024];
296 
297   Error error;
298   ConnectionStatus status = eConnectionStatusSuccess;
299   bool done = false;
300   while (!done && comm->m_read_thread_enabled) {
301     size_t bytes_read = comm->ReadFromConnection(
302         buf, sizeof(buf), std::chrono::seconds(5), status, &error);
303     if (bytes_read > 0)
304       comm->AppendBytesToCache(buf, bytes_read, true, status);
305     else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) {
306       if (comm->GetCloseOnEOF())
307         comm->Disconnect();
308       comm->AppendBytesToCache(buf, bytes_read, true, status);
309     }
310 
311     switch (status) {
312     case eConnectionStatusSuccess:
313       break;
314 
315     case eConnectionStatusEndOfFile:
316       done = true;
317       break;
318     case eConnectionStatusError: // Check GetError() for details
319       if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
320         // EIO on a pipe is usually caused by remote shutdown
321         comm->Disconnect();
322         done = true;
323       }
324       if (error.Fail())
325         LLDB_LOG(log, "error: {0}, status = {1}", error,
326                  Communication::ConnectionStatusAsCString(status));
327       break;
328     case eConnectionStatusInterrupted: // Synchronization signal from
329                                        // SynchronizeWithReadThread()
330       // The connection returns eConnectionStatusInterrupted only when there is
331       // no
332       // input pending to be read, so we can signal that.
333       comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
334       break;
335     case eConnectionStatusNoConnection:   // No connection
336     case eConnectionStatusLostConnection: // Lost connection while connected to
337                                           // a valid connection
338       done = true;
339       LLVM_FALLTHROUGH;
340     case eConnectionStatusTimedOut: // Request timed out
341       if (error.Fail())
342         LLDB_LOG(log, "error: {0}, status = {1}", error,
343                  Communication::ConnectionStatusAsCString(status));
344       break;
345     }
346   }
347   log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
348   if (log)
349     log->Printf("%p Communication::ReadThread () thread exiting...", p);
350 
351   comm->m_read_thread_did_exit = true;
352   // Let clients know that this thread is exiting
353   comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
354   comm->BroadcastEvent(eBroadcastBitReadThreadDidExit);
355   return NULL;
356 }
357 
358 void Communication::SetReadThreadBytesReceivedCallback(
359     ReadThreadBytesReceived callback, void *callback_baton) {
360   m_callback = callback;
361   m_callback_baton = callback_baton;
362 }
363 
364 void Communication::SynchronizeWithReadThread() {
365   // Only one thread can do the synchronization dance at a time.
366   std::lock_guard<std::mutex> guard(m_synchronize_mutex);
367 
368   // First start listening for the synchronization event.
369   ListenerSP listener_sp(
370       Listener::MakeListener("Communication::SyncronizeWithReadThread"));
371   listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
372 
373   // If the thread is not running, there is no point in synchronizing.
374   if (!m_read_thread_enabled || m_read_thread_did_exit)
375     return;
376 
377   // Notify the read thread.
378   m_connection_sp->InterruptRead();
379 
380   // Wait for the synchronization event.
381   EventSP event_sp;
382   listener_sp->GetEvent(event_sp, llvm::None);
383 }
384 
385 void Communication::SetConnection(Connection *connection) {
386   Disconnect(nullptr);
387   StopReadThread(nullptr);
388   m_connection_sp.reset(connection);
389 }
390 
391 const char *
392 Communication::ConnectionStatusAsCString(lldb::ConnectionStatus status) {
393   switch (status) {
394   case eConnectionStatusSuccess:
395     return "success";
396   case eConnectionStatusError:
397     return "error";
398   case eConnectionStatusTimedOut:
399     return "timed out";
400   case eConnectionStatusNoConnection:
401     return "no connection";
402   case eConnectionStatusLostConnection:
403     return "lost connection";
404   case eConnectionStatusEndOfFile:
405     return "end of file";
406   case eConnectionStatusInterrupted:
407     return "interrupted";
408   }
409 
410   static char unknown_state_string[64];
411   snprintf(unknown_state_string, sizeof(unknown_state_string),
412            "ConnectionStatus = %i", status);
413   return unknown_state_string;
414 }
415