xref: /src/contrib/llvm-project/lldb/source/Core/ThreadedCommunication.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e3b55780SDimitry Andric //===-- ThreadedCommunication.cpp -----------------------------------------===//
2e3b55780SDimitry Andric //
3e3b55780SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e3b55780SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e3b55780SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e3b55780SDimitry Andric //
7e3b55780SDimitry Andric //===----------------------------------------------------------------------===//
8e3b55780SDimitry Andric 
9e3b55780SDimitry Andric #include "lldb/Core/ThreadedCommunication.h"
10e3b55780SDimitry Andric 
11e3b55780SDimitry Andric #include "lldb/Host/ThreadLauncher.h"
12e3b55780SDimitry Andric #include "lldb/Utility/Connection.h"
13e3b55780SDimitry Andric #include "lldb/Utility/ConstString.h"
14e3b55780SDimitry Andric #include "lldb/Utility/Event.h"
15e3b55780SDimitry Andric #include "lldb/Utility/LLDBLog.h"
16e3b55780SDimitry Andric #include "lldb/Utility/Listener.h"
17e3b55780SDimitry Andric #include "lldb/Utility/Log.h"
18e3b55780SDimitry Andric #include "lldb/Utility/Status.h"
19e3b55780SDimitry Andric 
20e3b55780SDimitry Andric #include "llvm/Support/Compiler.h"
21e3b55780SDimitry Andric 
22e3b55780SDimitry Andric #include <algorithm>
23e3b55780SDimitry Andric #include <chrono>
24e3b55780SDimitry Andric #include <cstring>
25e3b55780SDimitry Andric #include <memory>
26b1c73532SDimitry Andric #include <shared_mutex>
27e3b55780SDimitry Andric 
28e3b55780SDimitry Andric #include <cerrno>
29e3b55780SDimitry Andric #include <cinttypes>
30e3b55780SDimitry Andric #include <cstdio>
31e3b55780SDimitry Andric 
32e3b55780SDimitry Andric using namespace lldb;
33e3b55780SDimitry Andric using namespace lldb_private;
34e3b55780SDimitry Andric 
GetStaticBroadcasterClass()35ac9a064cSDimitry Andric llvm::StringRef ThreadedCommunication::GetStaticBroadcasterClass() {
36ac9a064cSDimitry Andric   static constexpr llvm::StringLiteral class_name("lldb.communication");
37e3b55780SDimitry Andric   return class_name;
38e3b55780SDimitry Andric }
39e3b55780SDimitry Andric 
ThreadedCommunication(const char * name)40e3b55780SDimitry Andric ThreadedCommunication::ThreadedCommunication(const char *name)
41e3b55780SDimitry Andric     : Communication(), Broadcaster(nullptr, name), m_read_thread_enabled(false),
42e3b55780SDimitry Andric       m_read_thread_did_exit(false), m_bytes(), m_bytes_mutex(),
43e3b55780SDimitry Andric       m_synchronize_mutex(), m_callback(nullptr), m_callback_baton(nullptr) {
44e3b55780SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Object | LLDBLog::Communication),
45e3b55780SDimitry Andric            "{0} ThreadedCommunication::ThreadedCommunication (name = {1})",
46e3b55780SDimitry Andric            this, name);
47e3b55780SDimitry Andric 
48e3b55780SDimitry Andric   SetEventName(eBroadcastBitDisconnected, "disconnected");
49e3b55780SDimitry Andric   SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes");
50e3b55780SDimitry Andric   SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit");
51e3b55780SDimitry Andric   SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit");
52e3b55780SDimitry Andric   SetEventName(eBroadcastBitPacketAvailable, "packet available");
53e3b55780SDimitry Andric   SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input");
54e3b55780SDimitry Andric 
55e3b55780SDimitry Andric   CheckInWithManager();
56e3b55780SDimitry Andric }
57e3b55780SDimitry Andric 
~ThreadedCommunication()58e3b55780SDimitry Andric ThreadedCommunication::~ThreadedCommunication() {
59e3b55780SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Object | LLDBLog::Communication),
60e3b55780SDimitry Andric            "{0} ThreadedCommunication::~ThreadedCommunication (name = {1})",
617fa27ce4SDimitry Andric            this, GetBroadcasterName());
62e3b55780SDimitry Andric }
63e3b55780SDimitry Andric 
Clear()64e3b55780SDimitry Andric void ThreadedCommunication::Clear() {
65e3b55780SDimitry Andric   SetReadThreadBytesReceivedCallback(nullptr, nullptr);
66e3b55780SDimitry Andric   StopReadThread(nullptr);
67e3b55780SDimitry Andric   Communication::Clear();
68e3b55780SDimitry Andric }
69e3b55780SDimitry Andric 
Disconnect(Status * error_ptr)70e3b55780SDimitry Andric ConnectionStatus ThreadedCommunication::Disconnect(Status *error_ptr) {
71e3b55780SDimitry Andric   assert((!m_read_thread_enabled || m_read_thread_did_exit) &&
72e3b55780SDimitry Andric          "Disconnecting while the read thread is running is racy!");
73e3b55780SDimitry Andric   return Communication::Disconnect(error_ptr);
74e3b55780SDimitry Andric }
75e3b55780SDimitry Andric 
Read(void * dst,size_t dst_len,const Timeout<std::micro> & timeout,ConnectionStatus & status,Status * error_ptr)76e3b55780SDimitry Andric size_t ThreadedCommunication::Read(void *dst, size_t dst_len,
77e3b55780SDimitry Andric                                    const Timeout<std::micro> &timeout,
78e3b55780SDimitry Andric                                    ConnectionStatus &status,
79e3b55780SDimitry Andric                                    Status *error_ptr) {
80e3b55780SDimitry Andric   Log *log = GetLog(LLDBLog::Communication);
81e3b55780SDimitry Andric   LLDB_LOG(
82e3b55780SDimitry Andric       log,
83e3b55780SDimitry Andric       "this = {0}, dst = {1}, dst_len = {2}, timeout = {3}, connection = {4}",
84e3b55780SDimitry Andric       this, dst, dst_len, timeout, m_connection_sp.get());
85e3b55780SDimitry Andric 
86e3b55780SDimitry Andric   if (m_read_thread_enabled) {
87e3b55780SDimitry Andric     // We have a dedicated read thread that is getting data for us
88e3b55780SDimitry Andric     size_t cached_bytes = GetCachedBytes(dst, dst_len);
89e3b55780SDimitry Andric     if (cached_bytes > 0) {
90e3b55780SDimitry Andric       status = eConnectionStatusSuccess;
91e3b55780SDimitry Andric       return cached_bytes;
92e3b55780SDimitry Andric     }
93e3b55780SDimitry Andric     if (timeout && timeout->count() == 0) {
94e3b55780SDimitry Andric       if (error_ptr)
95e3b55780SDimitry Andric         error_ptr->SetErrorString("Timed out.");
96e3b55780SDimitry Andric       status = eConnectionStatusTimedOut;
97e3b55780SDimitry Andric       return 0;
98e3b55780SDimitry Andric     }
99e3b55780SDimitry Andric 
100e3b55780SDimitry Andric     if (!m_connection_sp) {
101e3b55780SDimitry Andric       if (error_ptr)
102e3b55780SDimitry Andric         error_ptr->SetErrorString("Invalid connection.");
103e3b55780SDimitry Andric       status = eConnectionStatusNoConnection;
104e3b55780SDimitry Andric       return 0;
105e3b55780SDimitry Andric     }
106e3b55780SDimitry Andric 
107e3b55780SDimitry Andric     // No data yet, we have to start listening.
108e3b55780SDimitry Andric     ListenerSP listener_sp(
109e3b55780SDimitry Andric         Listener::MakeListener("ThreadedCommunication::Read"));
110e3b55780SDimitry Andric     listener_sp->StartListeningForEvents(
111e3b55780SDimitry Andric         this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit);
112e3b55780SDimitry Andric 
113e3b55780SDimitry Andric     // Re-check for data, as it might have arrived while we were setting up our
114e3b55780SDimitry Andric     // listener.
115e3b55780SDimitry Andric     cached_bytes = GetCachedBytes(dst, dst_len);
116e3b55780SDimitry Andric     if (cached_bytes > 0) {
117e3b55780SDimitry Andric       status = eConnectionStatusSuccess;
118e3b55780SDimitry Andric       return cached_bytes;
119e3b55780SDimitry Andric     }
120e3b55780SDimitry Andric 
121e3b55780SDimitry Andric     EventSP event_sp;
122e3b55780SDimitry Andric     // Explicitly check for the thread exit, for the same reason.
123e3b55780SDimitry Andric     if (m_read_thread_did_exit) {
124e3b55780SDimitry Andric       // We've missed the event, lets just conjure one up.
125e3b55780SDimitry Andric       event_sp = std::make_shared<Event>(eBroadcastBitReadThreadDidExit);
126e3b55780SDimitry Andric     } else {
127e3b55780SDimitry Andric       if (!listener_sp->GetEvent(event_sp, timeout)) {
128e3b55780SDimitry Andric         if (error_ptr)
129e3b55780SDimitry Andric           error_ptr->SetErrorString("Timed out.");
130e3b55780SDimitry Andric         status = eConnectionStatusTimedOut;
131e3b55780SDimitry Andric         return 0;
132e3b55780SDimitry Andric       }
133e3b55780SDimitry Andric     }
134e3b55780SDimitry Andric     const uint32_t event_type = event_sp->GetType();
135e3b55780SDimitry Andric     if (event_type & eBroadcastBitReadThreadGotBytes) {
136e3b55780SDimitry Andric       return GetCachedBytes(dst, dst_len);
137e3b55780SDimitry Andric     }
138e3b55780SDimitry Andric 
139e3b55780SDimitry Andric     if (event_type & eBroadcastBitReadThreadDidExit) {
140e3b55780SDimitry Andric       // If the thread exited of its own accord, it either means it
141e3b55780SDimitry Andric       // hit an end-of-file condition or an error.
142e3b55780SDimitry Andric       status = m_pass_status;
143e3b55780SDimitry Andric       if (error_ptr)
144e3b55780SDimitry Andric         *error_ptr = std::move(m_pass_error);
145e3b55780SDimitry Andric 
146e3b55780SDimitry Andric       if (GetCloseOnEOF())
147e3b55780SDimitry Andric         Disconnect(nullptr);
148e3b55780SDimitry Andric       return 0;
149e3b55780SDimitry Andric     }
150e3b55780SDimitry Andric     llvm_unreachable("Got unexpected event type!");
151e3b55780SDimitry Andric   }
152e3b55780SDimitry Andric 
153e3b55780SDimitry Andric   // We aren't using a read thread, just read the data synchronously in this
154e3b55780SDimitry Andric   // thread.
155e3b55780SDimitry Andric   return Communication::Read(dst, dst_len, timeout, status, error_ptr);
156e3b55780SDimitry Andric }
157e3b55780SDimitry Andric 
StartReadThread(Status * error_ptr)158e3b55780SDimitry Andric bool ThreadedCommunication::StartReadThread(Status *error_ptr) {
159b1c73532SDimitry Andric   std::lock_guard<std::mutex> lock(m_read_thread_mutex);
160b1c73532SDimitry Andric 
161e3b55780SDimitry Andric   if (error_ptr)
162e3b55780SDimitry Andric     error_ptr->Clear();
163e3b55780SDimitry Andric 
164e3b55780SDimitry Andric   if (m_read_thread.IsJoinable())
165e3b55780SDimitry Andric     return true;
166e3b55780SDimitry Andric 
167e3b55780SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Communication),
168e3b55780SDimitry Andric            "{0} ThreadedCommunication::StartReadThread ()", this);
169e3b55780SDimitry Andric 
170e3b55780SDimitry Andric   const std::string thread_name =
171e3b55780SDimitry Andric       llvm::formatv("<lldb.comm.{0}>", GetBroadcasterName());
172e3b55780SDimitry Andric 
173e3b55780SDimitry Andric   m_read_thread_enabled = true;
174e3b55780SDimitry Andric   m_read_thread_did_exit = false;
175e3b55780SDimitry Andric   auto maybe_thread = ThreadLauncher::LaunchThread(
176e3b55780SDimitry Andric       thread_name, [this] { return ReadThread(); });
177e3b55780SDimitry Andric   if (maybe_thread) {
178e3b55780SDimitry Andric     m_read_thread = *maybe_thread;
179e3b55780SDimitry Andric   } else {
180e3b55780SDimitry Andric     if (error_ptr)
181e3b55780SDimitry Andric       *error_ptr = Status(maybe_thread.takeError());
182e3b55780SDimitry Andric     else {
1837fa27ce4SDimitry Andric       LLDB_LOG_ERROR(GetLog(LLDBLog::Host), maybe_thread.takeError(),
1847fa27ce4SDimitry Andric                      "failed to launch host thread: {0}");
185e3b55780SDimitry Andric     }
186e3b55780SDimitry Andric   }
187e3b55780SDimitry Andric 
188e3b55780SDimitry Andric   if (!m_read_thread.IsJoinable())
189e3b55780SDimitry Andric     m_read_thread_enabled = false;
190e3b55780SDimitry Andric 
191e3b55780SDimitry Andric   return m_read_thread_enabled;
192e3b55780SDimitry Andric }
193e3b55780SDimitry Andric 
StopReadThread(Status * error_ptr)194e3b55780SDimitry Andric bool ThreadedCommunication::StopReadThread(Status *error_ptr) {
195b1c73532SDimitry Andric   std::lock_guard<std::mutex> lock(m_read_thread_mutex);
196b1c73532SDimitry Andric 
197e3b55780SDimitry Andric   if (!m_read_thread.IsJoinable())
198e3b55780SDimitry Andric     return true;
199e3b55780SDimitry Andric 
200e3b55780SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Communication),
201e3b55780SDimitry Andric            "{0} ThreadedCommunication::StopReadThread ()", this);
202e3b55780SDimitry Andric 
203e3b55780SDimitry Andric   m_read_thread_enabled = false;
204e3b55780SDimitry Andric 
205e3b55780SDimitry Andric   BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr);
206e3b55780SDimitry Andric 
207e3b55780SDimitry Andric   Status error = m_read_thread.Join(nullptr);
208e3b55780SDimitry Andric   return error.Success();
209e3b55780SDimitry Andric }
210e3b55780SDimitry Andric 
JoinReadThread(Status * error_ptr)211e3b55780SDimitry Andric bool ThreadedCommunication::JoinReadThread(Status *error_ptr) {
212b1c73532SDimitry Andric   std::lock_guard<std::mutex> lock(m_read_thread_mutex);
213b1c73532SDimitry Andric 
214e3b55780SDimitry Andric   if (!m_read_thread.IsJoinable())
215e3b55780SDimitry Andric     return true;
216e3b55780SDimitry Andric 
217e3b55780SDimitry Andric   Status error = m_read_thread.Join(nullptr);
218e3b55780SDimitry Andric   return error.Success();
219e3b55780SDimitry Andric }
220e3b55780SDimitry Andric 
GetCachedBytes(void * dst,size_t dst_len)221e3b55780SDimitry Andric size_t ThreadedCommunication::GetCachedBytes(void *dst, size_t dst_len) {
222e3b55780SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
223e3b55780SDimitry Andric   if (!m_bytes.empty()) {
224e3b55780SDimitry Andric     // If DST is nullptr and we have a thread, then return the number of bytes
225e3b55780SDimitry Andric     // that are available so the caller can call again
226e3b55780SDimitry Andric     if (dst == nullptr)
227e3b55780SDimitry Andric       return m_bytes.size();
228e3b55780SDimitry Andric 
229e3b55780SDimitry Andric     const size_t len = std::min<size_t>(dst_len, m_bytes.size());
230e3b55780SDimitry Andric 
231e3b55780SDimitry Andric     ::memcpy(dst, m_bytes.c_str(), len);
232e3b55780SDimitry Andric     m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len);
233e3b55780SDimitry Andric 
234e3b55780SDimitry Andric     return len;
235e3b55780SDimitry Andric   }
236e3b55780SDimitry Andric   return 0;
237e3b55780SDimitry Andric }
238e3b55780SDimitry Andric 
AppendBytesToCache(const uint8_t * bytes,size_t len,bool broadcast,ConnectionStatus status)239e3b55780SDimitry Andric void ThreadedCommunication::AppendBytesToCache(const uint8_t *bytes, size_t len,
240e3b55780SDimitry Andric                                                bool broadcast,
241e3b55780SDimitry Andric                                                ConnectionStatus status) {
242e3b55780SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Communication),
243e3b55780SDimitry Andric            "{0} ThreadedCommunication::AppendBytesToCache (src = {1}, src_len "
244e3b55780SDimitry Andric            "= {2}, "
245e3b55780SDimitry Andric            "broadcast = {3})",
246e3b55780SDimitry Andric            this, bytes, (uint64_t)len, broadcast);
247e3b55780SDimitry Andric   if ((bytes == nullptr || len == 0) &&
248e3b55780SDimitry Andric       (status != lldb::eConnectionStatusEndOfFile))
249e3b55780SDimitry Andric     return;
250e3b55780SDimitry Andric   if (m_callback) {
251e3b55780SDimitry Andric     // If the user registered a callback, then call it and do not broadcast
252e3b55780SDimitry Andric     m_callback(m_callback_baton, bytes, len);
253e3b55780SDimitry Andric   } else if (bytes != nullptr && len > 0) {
254e3b55780SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
255e3b55780SDimitry Andric     m_bytes.append((const char *)bytes, len);
256e3b55780SDimitry Andric     if (broadcast)
257e3b55780SDimitry Andric       BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes);
258e3b55780SDimitry Andric   }
259e3b55780SDimitry Andric }
260e3b55780SDimitry Andric 
ReadThreadIsRunning()261e3b55780SDimitry Andric bool ThreadedCommunication::ReadThreadIsRunning() {
262e3b55780SDimitry Andric   return m_read_thread_enabled;
263e3b55780SDimitry Andric }
264e3b55780SDimitry Andric 
ReadThread()265e3b55780SDimitry Andric lldb::thread_result_t ThreadedCommunication::ReadThread() {
266e3b55780SDimitry Andric   Log *log = GetLog(LLDBLog::Communication);
267e3b55780SDimitry Andric 
268e3b55780SDimitry Andric   LLDB_LOG(log, "Communication({0}) thread starting...", this);
269e3b55780SDimitry Andric 
270e3b55780SDimitry Andric   uint8_t buf[1024];
271e3b55780SDimitry Andric 
272e3b55780SDimitry Andric   Status error;
273e3b55780SDimitry Andric   ConnectionStatus status = eConnectionStatusSuccess;
274e3b55780SDimitry Andric   bool done = false;
275e3b55780SDimitry Andric   bool disconnect = false;
276e3b55780SDimitry Andric   while (!done && m_read_thread_enabled) {
277e3b55780SDimitry Andric     size_t bytes_read = ReadFromConnection(
278e3b55780SDimitry Andric         buf, sizeof(buf), std::chrono::seconds(5), status, &error);
279e3b55780SDimitry Andric     if (bytes_read > 0 || status == eConnectionStatusEndOfFile)
280e3b55780SDimitry Andric       AppendBytesToCache(buf, bytes_read, true, status);
281e3b55780SDimitry Andric 
282e3b55780SDimitry Andric     switch (status) {
283e3b55780SDimitry Andric     case eConnectionStatusSuccess:
284e3b55780SDimitry Andric       break;
285e3b55780SDimitry Andric 
286e3b55780SDimitry Andric     case eConnectionStatusEndOfFile:
287e3b55780SDimitry Andric       done = true;
288e3b55780SDimitry Andric       disconnect = GetCloseOnEOF();
289e3b55780SDimitry Andric       break;
290e3b55780SDimitry Andric     case eConnectionStatusError: // Check GetError() for details
291e3b55780SDimitry Andric       if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) {
292e3b55780SDimitry Andric         // EIO on a pipe is usually caused by remote shutdown
293e3b55780SDimitry Andric         disconnect = GetCloseOnEOF();
294e3b55780SDimitry Andric         done = true;
295e3b55780SDimitry Andric       }
296e3b55780SDimitry Andric       if (error.Fail())
297e3b55780SDimitry Andric         LLDB_LOG(log, "error: {0}, status = {1}", error,
298e3b55780SDimitry Andric                  ThreadedCommunication::ConnectionStatusAsString(status));
299e3b55780SDimitry Andric       break;
300e3b55780SDimitry Andric     case eConnectionStatusInterrupted: // Synchronization signal from
301e3b55780SDimitry Andric                                        // SynchronizeWithReadThread()
302e3b55780SDimitry Andric       // The connection returns eConnectionStatusInterrupted only when there is
303e3b55780SDimitry Andric       // no input pending to be read, so we can signal that.
304e3b55780SDimitry Andric       BroadcastEvent(eBroadcastBitNoMorePendingInput);
305e3b55780SDimitry Andric       break;
306e3b55780SDimitry Andric     case eConnectionStatusNoConnection:   // No connection
307e3b55780SDimitry Andric     case eConnectionStatusLostConnection: // Lost connection while connected to
308e3b55780SDimitry Andric                                           // a valid connection
309e3b55780SDimitry Andric       done = true;
310e3b55780SDimitry Andric       [[fallthrough]];
311e3b55780SDimitry Andric     case eConnectionStatusTimedOut: // Request timed out
312e3b55780SDimitry Andric       if (error.Fail())
313e3b55780SDimitry Andric         LLDB_LOG(log, "error: {0}, status = {1}", error,
314e3b55780SDimitry Andric                  ThreadedCommunication::ConnectionStatusAsString(status));
315e3b55780SDimitry Andric       break;
316e3b55780SDimitry Andric     }
317e3b55780SDimitry Andric   }
318e3b55780SDimitry Andric   m_pass_status = status;
319e3b55780SDimitry Andric   m_pass_error = std::move(error);
320e3b55780SDimitry Andric   LLDB_LOG(log, "Communication({0}) thread exiting...", this);
321e3b55780SDimitry Andric 
322e3b55780SDimitry Andric   // Start shutting down. We need to do this in a very specific order to ensure
323e3b55780SDimitry Andric   // we don't race with threads wanting to read/synchronize with us.
324e3b55780SDimitry Andric 
325e3b55780SDimitry Andric   // First, we signal our intent to exit. This ensures no new thread start
326e3b55780SDimitry Andric   // waiting on events from us.
327e3b55780SDimitry Andric   m_read_thread_did_exit = true;
328e3b55780SDimitry Andric 
329e3b55780SDimitry Andric   // Unblock any existing thread waiting for the synchronization signal.
330e3b55780SDimitry Andric   BroadcastEvent(eBroadcastBitNoMorePendingInput);
331e3b55780SDimitry Andric 
332e3b55780SDimitry Andric   {
333e3b55780SDimitry Andric     // Wait for the synchronization thread to finish...
334e3b55780SDimitry Andric     std::lock_guard<std::mutex> guard(m_synchronize_mutex);
335e3b55780SDimitry Andric     // ... and disconnect.
336e3b55780SDimitry Andric     if (disconnect)
337e3b55780SDimitry Andric       Disconnect();
338e3b55780SDimitry Andric   }
339e3b55780SDimitry Andric 
340e3b55780SDimitry Andric   // Finally, unblock any readers waiting for us to exit.
341e3b55780SDimitry Andric   BroadcastEvent(eBroadcastBitReadThreadDidExit);
342e3b55780SDimitry Andric   return {};
343e3b55780SDimitry Andric }
344e3b55780SDimitry Andric 
SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback,void * callback_baton)345e3b55780SDimitry Andric void ThreadedCommunication::SetReadThreadBytesReceivedCallback(
346e3b55780SDimitry Andric     ReadThreadBytesReceived callback, void *callback_baton) {
347e3b55780SDimitry Andric   m_callback = callback;
348e3b55780SDimitry Andric   m_callback_baton = callback_baton;
349e3b55780SDimitry Andric }
350e3b55780SDimitry Andric 
SynchronizeWithReadThread()351e3b55780SDimitry Andric void ThreadedCommunication::SynchronizeWithReadThread() {
352e3b55780SDimitry Andric   // Only one thread can do the synchronization dance at a time.
353e3b55780SDimitry Andric   std::lock_guard<std::mutex> guard(m_synchronize_mutex);
354e3b55780SDimitry Andric 
355e3b55780SDimitry Andric   // First start listening for the synchronization event.
356e3b55780SDimitry Andric   ListenerSP listener_sp(Listener::MakeListener(
357e3b55780SDimitry Andric       "ThreadedCommunication::SyncronizeWithReadThread"));
358e3b55780SDimitry Andric   listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput);
359e3b55780SDimitry Andric 
360e3b55780SDimitry Andric   // If the thread is not running, there is no point in synchronizing.
361e3b55780SDimitry Andric   if (!m_read_thread_enabled || m_read_thread_did_exit)
362e3b55780SDimitry Andric     return;
363e3b55780SDimitry Andric 
364e3b55780SDimitry Andric   // Notify the read thread.
365e3b55780SDimitry Andric   m_connection_sp->InterruptRead();
366e3b55780SDimitry Andric 
367e3b55780SDimitry Andric   // Wait for the synchronization event.
368e3b55780SDimitry Andric   EventSP event_sp;
369e3b55780SDimitry Andric   listener_sp->GetEvent(event_sp, std::nullopt);
370e3b55780SDimitry Andric }
371e3b55780SDimitry Andric 
SetConnection(std::unique_ptr<Connection> connection)372e3b55780SDimitry Andric void ThreadedCommunication::SetConnection(
373e3b55780SDimitry Andric     std::unique_ptr<Connection> connection) {
374e3b55780SDimitry Andric   StopReadThread(nullptr);
375e3b55780SDimitry Andric   Communication::SetConnection(std::move(connection));
376e3b55780SDimitry Andric }
377