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