blob: c82e2fe93681ff868ac345e6f35cffccf989a310 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Eugene Zelenko896ddd02016-03-02 01:09:03 +000012#include <cstring>
13
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014// Other libraries and framework includes
15// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include "lldb/Core/Communication.h"
17#include "lldb/Core/Connection.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include "lldb/Core/Event.h"
Jim Ingham583bbb12016-03-07 21:50:25 +000019#include "lldb/Core/Listener.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/Timer.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000022#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000023#include "lldb/Host/HostThread.h"
24#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025
26using namespace lldb;
27using namespace lldb_private;
28
Kate Stoneb9c1b512016-09-06 20:57:50 +000029ConstString &Communication::GetStaticBroadcasterClass() {
30 static ConstString class_name("lldb.communication");
31 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000032}
33
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000034Communication::Communication(const char *name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000035 : 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)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039
40{
Kate Stoneb9c1b512016-09-06 20:57:50 +000041 lldb_private::LogIfAnyCategoriesSet(
42 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
43 "%p Communication::Communication (name = %s)", this, name);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000044
Kate Stoneb9c1b512016-09-06 20:57:50 +000045 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");
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000051
Kate Stoneb9c1b512016-09-06 20:57:50 +000052 CheckInWithManager();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053}
54
Kate Stoneb9c1b512016-09-06 20:57:50 +000055Communication::~Communication() {
56 lldb_private::LogIfAnyCategoriesSet(
57 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
58 "%p Communication::~Communication (name = %s)", this,
59 GetBroadcasterName().AsCString());
60 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061}
62
Kate Stoneb9c1b512016-09-06 20:57:50 +000063void Communication::Clear() {
64 SetReadThreadBytesReceivedCallback(nullptr, nullptr);
65 Disconnect(nullptr);
66 StopReadThread(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067}
68
Kate Stoneb9c1b512016-09-06 20:57:50 +000069ConnectionStatus Communication::Connect(const char *url, Error *error_ptr) {
70 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
Kate Stoneb9c1b512016-09-06 20:57:50 +000072 lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
73 "%p Communication::Connect (url = %s)",
74 this, url);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 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
84ConnectionStatus 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
106bool Communication::IsConnected() const {
107 lldb::ConnectionSP connection_sp(m_connection_sp);
108 return (connection_sp ? connection_sp->IsConnected() : false);
109}
110
111bool Communication::HasConnection() const {
112 return m_connection_sp.get() != nullptr;
113}
114
Pavel Labathc4063ee2016-11-25 11:58:44 +0000115size_t Communication::Read(void *dst, size_t dst_len,
116 const Timeout<std::micro> &timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 ConnectionStatus &status, Error *error_ptr) {
Pavel Labath3043fd82016-11-25 12:15:17 +0000118 using std::chrono::microseconds;
119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 lldb_private::LogIfAnyCategoriesSet(
121 LIBLLDB_LOG_COMMUNICATION,
122 "%p Communication::Read (dst = %p, dst_len = %" PRIu64
123 ", timeout = %u usec) connection = %p",
Pavel Labathc4063ee2016-11-25 11:58:44 +0000124 this, dst, (uint64_t)dst_len, timeout ? timeout->count() : -1,
125 m_connection_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126
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);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000130 if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 status = eConnectionStatusSuccess;
132 return cached_bytes;
133 }
134
135 if (!m_connection_sp) {
136 if (error_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137 error_ptr->SetErrorString("Invalid connection.");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 status = eConnectionStatusNoConnection;
139 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000140 }
141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
143 listener_sp->StartListeningForEvents(
144 this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
Pavel Labath3f5df532015-03-12 10:12:41 +0000145 EventSP event_sp;
Pavel Labath3043fd82016-11-25 12:15:17 +0000146 microseconds listener_timeout =
147 timeout ? microseconds(*timeout) : microseconds(0);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000148 while (listener_sp->WaitForEvent(listener_timeout, event_sp)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 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.
Pavel Labathc4063ee2016-11-25 11:58:44 +0000165 return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
Pavel Labath3f5df532015-03-12 10:12:41 +0000166}
167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168size_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
188bool 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
211bool 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
228bool 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
236size_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
254void 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
276size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
Pavel Labathc4063ee2016-11-25 11:58:44 +0000277 const Timeout<std::micro> &timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278 ConnectionStatus &status,
279 Error *error_ptr) {
280 lldb::ConnectionSP connection_sp(m_connection_sp);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000281 if (connection_sp) {
282 return connection_sp->Read(dst, dst_len,
283 timeout ? timeout->count() : UINT32_MAX, status,
284 error_ptr);
285 }
286
287 if (error_ptr)
288 error_ptr->SetErrorString("Invalid connection.");
289 status = eConnectionStatusNoConnection;
290 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291}
292
293bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
294
295lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) {
296 Communication *comm = (Communication *)p;
297
298 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
299
300 if (log)
301 log->Printf("%p Communication::ReadThread () thread starting...", p);
302
303 uint8_t buf[1024];
304
305 Error error;
306 ConnectionStatus status = eConnectionStatusSuccess;
307 bool done = false;
308 while (!done && comm->m_read_thread_enabled) {
309 size_t bytes_read = comm->ReadFromConnection(
Pavel Labathc4063ee2016-11-25 11:58:44 +0000310 buf, sizeof(buf), std::chrono::seconds(5), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 if (bytes_read > 0)
312 comm->AppendBytesToCache(buf, bytes_read, true, status);
313 else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) {
314 if (comm->GetCloseOnEOF())
315 comm->Disconnect();
316 comm->AppendBytesToCache(buf, bytes_read, true, status);
317 }
318
319 switch (status) {
320 case eConnectionStatusSuccess:
321 break;
322
323 case eConnectionStatusEndOfFile:
324 done = true;
325 break;
326 case eConnectionStatusError: // Check GetError() for details
327 if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
328 // EIO on a pipe is usually caused by remote shutdown
329 comm->Disconnect();
330 done = true;
331 }
332 if (log)
333 error.LogIfError(
334 log, "%p Communication::ReadFromConnection () => status = %s", p,
335 Communication::ConnectionStatusAsCString(status));
336 break;
337 case eConnectionStatusInterrupted: // Synchronization signal from
338 // SynchronizeWithReadThread()
339 // The connection returns eConnectionStatusInterrupted only when there is
340 // no
341 // input pending to be read, so we can signal that.
342 comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
343 break;
344 case eConnectionStatusNoConnection: // No connection
345 case eConnectionStatusLostConnection: // Lost connection while connected to
346 // a valid connection
347 done = true;
348 LLVM_FALLTHROUGH;
349 case eConnectionStatusTimedOut: // Request timed out
350 if (log)
351 error.LogIfError(
352 log, "%p Communication::ReadFromConnection () => status = %s", p,
353 Communication::ConnectionStatusAsCString(status));
354 break;
355 }
356 }
357 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
358 if (log)
359 log->Printf("%p Communication::ReadThread () thread exiting...", p);
360
361 comm->m_read_thread_did_exit = true;
362 // Let clients know that this thread is exiting
363 comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
364 comm->BroadcastEvent(eBroadcastBitReadThreadDidExit);
365 return NULL;
366}
367
368void Communication::SetReadThreadBytesReceivedCallback(
369 ReadThreadBytesReceived callback, void *callback_baton) {
370 m_callback = callback;
371 m_callback_baton = callback_baton;
372}
373
374void Communication::SynchronizeWithReadThread() {
375 // Only one thread can do the synchronization dance at a time.
376 std::lock_guard<std::mutex> guard(m_synchronize_mutex);
377
378 // First start listening for the synchronization event.
379 ListenerSP listener_sp(
380 Listener::MakeListener("Communication::SyncronizeWithReadThread"));
381 listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
382
383 // If the thread is not running, there is no point in synchronizing.
384 if (!m_read_thread_enabled || m_read_thread_did_exit)
385 return;
386
387 // Notify the read thread.
388 m_connection_sp->InterruptRead();
389
390 // Wait for the synchronization event.
391 EventSP event_sp;
392 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
393}
394
395void Communication::SetConnection(Connection *connection) {
396 Disconnect(nullptr);
397 StopReadThread(nullptr);
398 m_connection_sp.reset(connection);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399}
Caroline Ticeceb6b132010-10-26 03:11:13 +0000400
401const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402Communication::ConnectionStatusAsCString(lldb::ConnectionStatus status) {
403 switch (status) {
404 case eConnectionStatusSuccess:
405 return "success";
406 case eConnectionStatusError:
407 return "error";
408 case eConnectionStatusTimedOut:
409 return "timed out";
410 case eConnectionStatusNoConnection:
411 return "no connection";
412 case eConnectionStatusLostConnection:
413 return "lost connection";
414 case eConnectionStatusEndOfFile:
415 return "end of file";
416 case eConnectionStatusInterrupted:
417 return "interrupted";
418 }
Caroline Ticeceb6b132010-10-26 03:11:13 +0000419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 static char unknown_state_string[64];
421 snprintf(unknown_state_string, sizeof(unknown_state_string),
422 "ConnectionStatus = %i", status);
423 return unknown_state_string;
Caroline Ticeceb6b132010-10-26 03:11:13 +0000424}