blob: 5db62ba51576b49035e42ef61f9e6061689f298d [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/Timer.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000021#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000022#include "lldb/Host/HostThread.h"
23#include "lldb/Host/ThreadLauncher.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000024#include "lldb/Utility/Log.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 Labathd02b1c82017-02-10 11:49:33 +0000118 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());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123
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);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000127 if (cached_bytes > 0 || (timeout && timeout->count() == 0)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 status = eConnectionStatusSuccess;
129 return cached_bytes;
130 }
131
132 if (!m_connection_sp) {
133 if (error_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000134 error_ptr->SetErrorString("Invalid connection.");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 status = eConnectionStatusNoConnection;
136 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137 }
138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 ListenerSP listener_sp(Listener::MakeListener("Communication::Read"));
140 listener_sp->StartListeningForEvents(
141 this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
Pavel Labath3f5df532015-03-12 10:12:41 +0000142 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +0000143 while (listener_sp->GetEvent(event_sp, timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 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.
Pavel Labathc4063ee2016-11-25 11:58:44 +0000160 return ReadFromConnection(dst, dst_len, timeout, status, error_ptr);
Pavel Labath3f5df532015-03-12 10:12:41 +0000161}
162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163size_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
183bool 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
206bool 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
223bool 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
231size_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
249void 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
271size_t Communication::ReadFromConnection(void *dst, size_t dst_len,
Pavel Labathc4063ee2016-11-25 11:58:44 +0000272 const Timeout<std::micro> &timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 ConnectionStatus &status,
274 Error *error_ptr) {
275 lldb::ConnectionSP connection_sp(m_connection_sp);
Pavel Labath2f159a52016-11-25 12:22:32 +0000276 if (connection_sp)
277 return connection_sp->Read(dst, dst_len, timeout, status, error_ptr);
Pavel Labathc4063ee2016-11-25 11:58:44 +0000278
279 if (error_ptr)
280 error_ptr->SetErrorString("Invalid connection.");
281 status = eConnectionStatusNoConnection;
282 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283}
284
285bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; }
286
287lldb::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(
Pavel Labathc4063ee2016-11-25 11:58:44 +0000302 buf, sizeof(buf), std::chrono::seconds(5), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 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 }
Zachary Turner33aba3c2017-02-06 18:31:44 +0000324 if (error.Fail())
325 LLDB_LOG(log, "error: {0}, status = {1}", error,
326 Communication::ConnectionStatusAsCString(status));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 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
Zachary Turner33aba3c2017-02-06 18:31:44 +0000341 if (error.Fail())
342 LLDB_LOG(log, "error: {0}, status = {1}", error,
343 Communication::ConnectionStatusAsCString(status));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 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
358void Communication::SetReadThreadBytesReceivedCallback(
359 ReadThreadBytesReceived callback, void *callback_baton) {
360 m_callback = callback;
361 m_callback_baton = callback_baton;
362}
363
364void 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;
Pavel Labathd35031e12016-11-30 10:41:42 +0000382 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383}
384
385void Communication::SetConnection(Connection *connection) {
386 Disconnect(nullptr);
387 StopReadThread(nullptr);
388 m_connection_sp.reset(connection);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389}
Caroline Ticeceb6b132010-10-26 03:11:13 +0000390
391const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392Communication::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 }
Caroline Ticeceb6b132010-10-26 03:11:13 +0000409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 static char unknown_state_string[64];
411 snprintf(unknown_state_string, sizeof(unknown_state_string),
412 "ConnectionStatus = %i", status);
413 return unknown_state_string;
Caroline Ticeceb6b132010-10-26 03:11:13 +0000414}