blob: 5ca338639de05f879ef300bcfa87a8aa0d5c442c [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010#include "lldb/Core/Communication.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000011
Kate Stoneb9c1b512016-09-06 20:57:50 +000012#include "lldb/Core/Event.h"
Jim Ingham583bbb12016-03-07 21:50:25 +000013#include "lldb/Core/Listener.h"
Zachary Turner39de3112014-09-09 20:54:56 +000014#include "lldb/Host/HostThread.h"
15#include "lldb/Host/ThreadLauncher.h"
Pavel Labath4ccd9952017-06-27 10:33:14 +000016#include "lldb/Utility/Connection.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000017#include "lldb/Utility/ConstString.h" // for ConstString
Zachary Turner6f9e6902017-03-03 20:56:28 +000018#include "lldb/Utility/Log.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000019#include "lldb/Utility/Logging.h" // for LogIfAnyCategoriesSet, LIBLLDB...
Zachary Turner97206d52017-05-12 04:51:55 +000020#include "lldb/Utility/Status.h" // for Status
Zachary Turner2f3df612017-04-06 21:28:29 +000021
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
25
26#include <algorithm> // for min
27#include <chrono> // for duration, seconds
28#include <cstring>
29#include <memory> // for shared_ptr
30
31#include <errno.h> // for EIO
32#include <inttypes.h> // for PRIu64
33#include <stdio.h> // for snprintf
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034
35using namespace lldb;
36using namespace lldb_private;
37
Kate Stoneb9c1b512016-09-06 20:57:50 +000038ConstString &Communication::GetStaticBroadcasterClass() {
39 static ConstString class_name("lldb.communication");
40 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000041}
42
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000043Communication::Communication(const char *name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000044 : 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)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048
49{
Kate Stoneb9c1b512016-09-06 20:57:50 +000050 lldb_private::LogIfAnyCategoriesSet(
51 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
52 "%p Communication::Communication (name = %s)", this, name);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 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");
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000060
Kate Stoneb9c1b512016-09-06 20:57:50 +000061 CheckInWithManager();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062}
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064Communication::~Communication() {
65 lldb_private::LogIfAnyCategoriesSet(
66 LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION,
67 "%p Communication::~Communication (name = %s)", this,
68 GetBroadcasterName().AsCString());
69 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070}
71
Kate Stoneb9c1b512016-09-06 20:57:50 +000072void Communication::Clear() {
73 SetReadThreadBytesReceivedCallback(nullptr, nullptr);
74 Disconnect(nullptr);
75 StopReadThread(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076}
77
Zachary Turner97206d52017-05-12 04:51:55 +000078ConnectionStatus Communication::Connect(const char *url, Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
82 "%p Communication::Connect (url = %s)",
83 this, url);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000084
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 lldb::ConnectionSP connection_sp(m_connection_sp);
86 if (connection_sp)
87 return connection_sp->Connect(url, error_ptr);
88 if (error_ptr)
89 error_ptr->SetErrorString("Invalid connection.");
90 return eConnectionStatusNoConnection;
91}
92
Zachary Turner97206d52017-05-12 04:51:55 +000093ConnectionStatus Communication::Disconnect(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION,
95 "%p Communication::Disconnect ()", this);
96
97 lldb::ConnectionSP connection_sp(m_connection_sp);
98 if (connection_sp) {
99 ConnectionStatus status = connection_sp->Disconnect(error_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +0000100 // 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.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 //
Adrian Prantl05097242018-04-30 16:49:04 +0000106 // This unique pointer will cleanup after itself when this object goes
107 // away, so there is no need to currently have it destroy itself
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000108 // immediately upon disconnect.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 // connection_sp.reset();
110 return status;
111 }
112 return eConnectionStatusNoConnection;
113}
114
115bool Communication::IsConnected() const {
116 lldb::ConnectionSP connection_sp(m_connection_sp);
117 return (connection_sp ? connection_sp->IsConnected() : false);
118}
119
120bool Communication::HasConnection() const {
121 return m_connection_sp.get() != nullptr;
122}
123
Pavel Labathc4063ee2016-11-25 11:58:44 +0000124size_t Communication::Read(void *dst, size_t dst_len,
125 const Timeout<std::micro> &timeout,
Zachary Turner97206d52017-05-12 04:51:55 +0000126 ConnectionStatus &status, Status *error_ptr) {
Pavel Labathd02b1c82017-02-10 11:49:33 +0000127 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION);
128 LLDB_LOG(
129 log,
130 "this = {0}, dst = {1}, dst_len = {2}, timeout = {3}, connection = {4}",
131 this, dst, dst_len, timeout, m_connection_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132
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);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000136 if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 status = eConnectionStatusSuccess;
138 return cached_bytes;
139 }
140
141 if (!m_connection_sp) {
142 if (error_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143 error_ptr->SetErrorString("Invalid connection.");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 status = eConnectionStatusNoConnection;
145 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000146 }
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
149 listener_sp->StartListeningForEvents(
150 this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
Pavel Labath3f5df532015-03-12 10:12:41 +0000151 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +0000152 while (listener_sp->GetEvent(event_sp, timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 const uint32_t event_type = event_sp->GetType();
154 if (event_type & eBroadcastBitReadThreadGotBytes) {
155 return GetCachedBytes(dst, dst_len);
156 }
157
158 if (event_type & eBroadcastBitReadThreadDidExit) {
159 if (GetCloseOnEOF())
160 Disconnect(nullptr);
161 break;
162 }
163 }
164 return 0;
165 }
166
167 // We aren't using a read thread, just read the data synchronously in this
168 // thread.
Pavel Labathc4063ee2016-11-25 11:58:44 +0000169 return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
Pavel Labath3f5df532015-03-12 10:12:41 +0000170}
171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172size_t Communication::Write(const void *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +0000173 ConnectionStatus &status, Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 lldb::ConnectionSP connection_sp(m_connection_sp);
175
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
180 ") connection = %p",
181 this, src, (uint64_t)src_len, connection_sp.get());
182
183 if (connection_sp)
184 return connection_sp->Write(src, src_len, status, error_ptr);
185
186 if (error_ptr)
187 error_ptr->SetErrorString("Invalid connection.");
188 status = eConnectionStatusNoConnection;
189 return 0;
190}
191
Zachary Turner97206d52017-05-12 04:51:55 +0000192bool Communication::StartReadThread(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 if (error_ptr)
194 error_ptr->Clear();
195
196 if (m_read_thread.IsJoinable())
197 return true;
198
199 lldb_private::LogIfAnyCategoriesSet(
200 LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this);
201
202 char thread_name[1024];
203 snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>",
204 GetBroadcasterName().AsCString());
205
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;
213}
214
Zachary Turner97206d52017-05-12 04:51:55 +0000215bool Communication::StopReadThread(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 if (!m_read_thread.IsJoinable())
217 return true;
218
219 lldb_private::LogIfAnyCategoriesSet(
220 LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this);
221
222 m_read_thread_enabled = false;
223
224 BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
225
226 // error = m_read_thread.Cancel();
227
Zachary Turner97206d52017-05-12 04:51:55 +0000228 Status error = m_read_thread.Join(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 return error.Success();
230}
231
Zachary Turner97206d52017-05-12 04:51:55 +0000232bool Communication::JoinReadThread(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 if (!m_read_thread.IsJoinable())
234 return true;
235
Zachary Turner97206d52017-05-12 04:51:55 +0000236 Status error = m_read_thread.Join(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 return error.Success();
238}
239
240size_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()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000243 // 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 if (dst == nullptr)
246 return m_bytes.size();
247
248 const size_t len = std::min<size_t>(dst_len, m_bytes.size());
249
250 ::memcpy(dst, m_bytes.c_str(), len);
251 m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
252
253 return len;
254 }
255 return 0;
256}
257
258void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len,
259 bool broadcast,
260 ConnectionStatus status) {
261 lldb_private::LogIfAnyCategoriesSet(
262 LIBLLDB_LOG_COMMUNICATION,
263 "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64
264 ", broadcast = %i)",
265 this, bytes, (uint64_t)len, broadcast);
266 if ((bytes == nullptr || len == 0) &&
267 (status != lldb::eConnectionStatusEndOfFile))
268 return;
269 if (m_callback) {
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);
275 if (broadcast)
276 BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
277 }
278}
279
280size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
Pavel Labathc4063ee2016-11-25 11:58:44 +0000281 const Timeout<std::micro> &timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 ConnectionStatus &status,
Zachary Turner97206d52017-05-12 04:51:55 +0000283 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284 lldb::ConnectionSP connection_sp(m_connection_sp);
Pavel Labath2f159a52016-11-25 12:22:32 +0000285 if (connection_sp)
286 return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000287
288 if (error_ptr)
289 error_ptr->SetErrorString("Invalid connection.");
290 status = eConnectionStatusNoConnection;
291 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292}
293
294bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
295
296lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) {
297 Communication *comm = (Communication *)p;
298
299 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
300
301 if (log)
302 log->Printf("%p Communication::ReadThread () thread starting...", p);
303
304 uint8_t buf[1024];
305
Zachary Turner97206d52017-05-12 04:51:55 +0000306 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 ConnectionStatus status = eConnectionStatusSuccess;
308 bool done = false;
309 while (!done && comm->m_read_thread_enabled) {
310 size_t bytes_read = comm->ReadFromConnection(
Pavel Labathc4063ee2016-11-25 11:58:44 +0000311 buf, sizeof(buf), std::chrono::seconds(5), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 if (bytes_read > 0)
313 comm->AppendBytesToCache(buf, bytes_read, true, status);
314 else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) {
315 if (comm->GetCloseOnEOF())
316 comm->Disconnect();
317 comm->AppendBytesToCache(buf, bytes_read, true, status);
318 }
319
320 switch (status) {
321 case eConnectionStatusSuccess:
322 break;
323
324 case eConnectionStatusEndOfFile:
325 done = true;
326 break;
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
330 comm->Disconnect();
331 done = true;
332 }
Zachary Turner33aba3c2017-02-06 18:31:44 +0000333 if (error.Fail())
334 LLDB_LOG(log, "error: {0}, status = {1}", error,
335 Communication::ConnectionStatusAsCString(status));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 break;
337 case eConnectionStatusInterrupted: // Synchronization signal from
338 // SynchronizeWithReadThread()
339 // The connection returns eConnectionStatusInterrupted only when there is
Adrian Prantl05097242018-04-30 16:49:04 +0000340 // no input pending to be read, so we can signal that.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 comm->BroadcastEvent(eBroadcastBitNoMorePendingInput);
342 break;
343 case eConnectionStatusNoConnection: // No connection
344 case eConnectionStatusLostConnection: // Lost connection while connected to
345 // a valid connection
346 done = true;
347 LLVM_FALLTHROUGH;
348 case eConnectionStatusTimedOut: // Request timed out
Zachary Turner33aba3c2017-02-06 18:31:44 +0000349 if (error.Fail())
350 LLDB_LOG(log, "error: {0}, status = {1}", error,
351 Communication::ConnectionStatusAsCString(status));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 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;
Pavel Labathd35031e12016-11-30 10:41:42 +0000390 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391}
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}