1 //===-- GDBRemoteClientBase.cpp ---------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "GDBRemoteClientBase.h"
11 #include "llvm/ADT/StringExtras.h"
13 #include "lldb/Target/UnixSignals.h"
14 #include "lldb/Utility/LLDBAssert.h"
16 #include "ProcessGDBRemoteLog.h"
19 using namespace lldb_private;
20 using namespace lldb_private::process_gdb_remote;
21 using namespace std::chrono;
23 static const seconds kInterruptTimeout(5);
25 /////////////////////////
26 // GDBRemoteClientBase //
27 /////////////////////////
29 GDBRemoteClientBase::ContinueDelegate::~ContinueDelegate() = default;
31 GDBRemoteClientBase::GDBRemoteClientBase(const char *comm_name,
32 const char *listener_name)
33 : GDBRemoteCommunication(comm_name, listener_name), m_async_count(0),
34 m_is_running(false), m_should_stop(false) {}
36 StateType GDBRemoteClientBase::SendContinuePacketAndWaitForResponse(
37 ContinueDelegate &delegate, const UnixSignals &signals,
38 llvm::StringRef payload, StringExtractorGDBRemote &response) {
39 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
43 std::lock_guard<std::mutex> lock(m_mutex);
44 m_continue_packet = payload;
45 m_should_stop = false;
47 ContinueLock cont_lock(*this);
50 OnRunPacketSent(true);
53 PacketResult read_result = ReadPacket(response, kInterruptTimeout, false);
54 switch (read_result) {
55 case PacketResult::ErrorReplyTimeout: {
56 std::lock_guard<std::mutex> lock(m_mutex);
57 if (m_async_count == 0)
59 if (steady_clock::now() >= m_interrupt_time + kInterruptTimeout)
63 case PacketResult::Success:
67 log->Printf("GDBRemoteClientBase::%s () ReadPacket(...) => false",
74 const char stop_type = response.GetChar();
76 log->Printf("GDBRemoteClientBase::%s () got packet: %s", __FUNCTION__,
77 response.GetStringRef().c_str());
88 log->Printf("GDBRemoteClientBase::%s () unrecognized async packet",
92 std::string inferior_stdout;
93 response.GetHexByteString(inferior_stdout);
94 delegate.HandleAsyncStdout(inferior_stdout);
98 delegate.HandleAsyncMisc(
99 llvm::StringRef(response.GetStringRef()).substr(1));
102 delegate.HandleAsyncStructuredDataPacket(response.GetStringRef());
106 // Do this with the continue lock held.
107 const bool should_stop = ShouldStop(signals, response);
108 response.SetFilePos(0);
110 // The packet we should resume with. In the future we should check our
111 // thread list and "do the right thing" for new threads that show up
112 // while we stop and run async packets. Setting the packet to 'c' to
113 // continue all threads is the right thing to do 99.99% of the time
114 // because if a thread was single stepping, and we sent an interrupt, we
115 // will notice above that we didn't stop due to an interrupt but stopped
116 // due to stepping and we would _not_ continue. This packet may get
117 // modified by the async actions (e.g. to send a signal).
118 m_continue_packet = 'c';
121 delegate.HandleStopReply();
123 return eStateStopped;
125 switch (cont_lock.lock()) {
126 case ContinueLock::LockResult::Success:
128 case ContinueLock::LockResult::Failed:
129 return eStateInvalid;
130 case ContinueLock::LockResult::Cancelled:
131 return eStateStopped;
133 OnRunPacketSent(false);
139 bool GDBRemoteClientBase::SendAsyncSignal(int signo) {
140 Lock lock(*this, true);
141 if (!lock || !lock.DidInterrupt())
144 m_continue_packet = 'C';
145 m_continue_packet += llvm::hexdigit((signo / 16) % 16);
146 m_continue_packet += llvm::hexdigit(signo % 16);
150 bool GDBRemoteClientBase::Interrupt() {
151 Lock lock(*this, true);
152 if (!lock.DidInterrupt())
154 m_should_stop = true;
157 GDBRemoteCommunication::PacketResult
158 GDBRemoteClientBase::SendPacketAndWaitForResponse(
159 llvm::StringRef payload, StringExtractorGDBRemote &response,
161 Lock lock(*this, send_async);
164 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS))
165 log->Printf("GDBRemoteClientBase::%s failed to get mutex, not sending "
166 "packet '%.*s' (send_async=%d)",
167 __FUNCTION__, int(payload.size()), payload.data(),
169 return PacketResult::ErrorSendFailed;
172 return SendPacketAndWaitForResponseNoLock(payload, response);
175 GDBRemoteCommunication::PacketResult
176 GDBRemoteClientBase::SendPacketAndReceiveResponseWithOutputSupport(
177 llvm::StringRef payload, StringExtractorGDBRemote &response,
179 llvm::function_ref<void(llvm::StringRef)> output_callback) {
180 Lock lock(*this, send_async);
183 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS))
184 log->Printf("GDBRemoteClientBase::%s failed to get mutex, not sending "
185 "packet '%.*s' (send_async=%d)",
186 __FUNCTION__, int(payload.size()), payload.data(),
188 return PacketResult::ErrorSendFailed;
191 PacketResult packet_result = SendPacketNoLock(payload);
192 if (packet_result != PacketResult::Success)
193 return packet_result;
195 return ReadPacketWithOutputSupport(response, GetPacketTimeout(), true,
199 GDBRemoteCommunication::PacketResult
200 GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(
201 llvm::StringRef payload, StringExtractorGDBRemote &response) {
202 PacketResult packet_result = SendPacketNoLock(payload);
203 if (packet_result != PacketResult::Success)
204 return packet_result;
206 const size_t max_response_retries = 3;
207 for (size_t i = 0; i < max_response_retries; ++i) {
208 packet_result = ReadPacket(response, GetPacketTimeout(), true);
209 // Make sure we received a response
210 if (packet_result != PacketResult::Success)
211 return packet_result;
212 // Make sure our response is valid for the payload that was sent
213 if (response.ValidateResponse())
214 return packet_result;
215 // Response says it wasn't valid
216 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS);
219 "error: packet with payload \"%.*s\" got invalid response \"%s\": %s",
220 int(payload.size()), payload.data(), response.GetStringRef().c_str(),
221 (i == (max_response_retries - 1))
222 ? "using invalid response and giving up"
223 : "ignoring response and waiting for another");
225 return packet_result;
228 bool GDBRemoteClientBase::SendvContPacket(llvm::StringRef payload,
229 StringExtractorGDBRemote &response) {
230 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
232 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
234 // we want to lock down packet sending while we continue
235 Lock lock(*this, true);
239 "GDBRemoteCommunicationClient::%s () sending vCont packet: %.*s",
240 __FUNCTION__, int(payload.size()), payload.data());
242 if (SendPacketNoLock(payload) != PacketResult::Success)
245 OnRunPacketSent(true);
247 // wait for the response to the vCont
248 if (ReadPacket(response, llvm::None, false) == PacketResult::Success) {
249 if (response.IsOKResponse())
255 bool GDBRemoteClientBase::ShouldStop(const UnixSignals &signals,
256 StringExtractorGDBRemote &response) {
257 std::lock_guard<std::mutex> lock(m_mutex);
259 if (m_async_count == 0)
260 return true; // We were not interrupted. The process stopped on its own.
262 // Older debugserver stubs (before April 2016) can return two stop-reply
263 // packets in response to a ^C packet. Additionally, all debugservers still
264 // return two stop replies if the inferior stops due to some other reason
265 // before the remote stub manages to interrupt it. We need to wait for this
266 // additional packet to make sure the packet sequence does not get skewed.
267 StringExtractorGDBRemote extra_stop_reply_packet;
268 ReadPacket(extra_stop_reply_packet, milliseconds(100), false);
270 // Interrupting is typically done using SIGSTOP or SIGINT, so if the process
271 // stops with some other signal, we definitely want to stop.
272 const uint8_t signo = response.GetHexU8(UINT8_MAX);
273 if (signo != signals.GetSignalNumberFromName("SIGSTOP") &&
274 signo != signals.GetSignalNumberFromName("SIGINT"))
277 // We probably only stopped to perform some async processing, so continue
278 // after that is done.
279 // TODO: This is not 100% correct, as the process may have been stopped with
280 // SIGINT or SIGSTOP that was not caused by us (e.g. raise(SIGINT)). This will
281 // normally cause a stop, but if it's done concurrently with a async
282 // interrupt, that stop will get eaten (llvm.org/pr20231).
286 void GDBRemoteClientBase::OnRunPacketSent(bool first) {
288 BroadcastEvent(eBroadcastBitRunPacketSent, nullptr);
291 ///////////////////////////////////////
292 // GDBRemoteClientBase::ContinueLock //
293 ///////////////////////////////////////
295 GDBRemoteClientBase::ContinueLock::ContinueLock(GDBRemoteClientBase &comm)
296 : m_comm(comm), m_acquired(false) {
300 GDBRemoteClientBase::ContinueLock::~ContinueLock() {
305 void GDBRemoteClientBase::ContinueLock::unlock() {
306 lldbassert(m_acquired);
308 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
309 m_comm.m_is_running = false;
311 m_comm.m_cv.notify_all();
315 GDBRemoteClientBase::ContinueLock::LockResult
316 GDBRemoteClientBase::ContinueLock::lock() {
317 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
319 log->Printf("GDBRemoteClientBase::ContinueLock::%s() resuming with %s",
320 __FUNCTION__, m_comm.m_continue_packet.c_str());
322 lldbassert(!m_acquired);
323 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
324 m_comm.m_cv.wait(lock, [this] { return m_comm.m_async_count == 0; });
325 if (m_comm.m_should_stop) {
326 m_comm.m_should_stop = false;
328 log->Printf("GDBRemoteClientBase::ContinueLock::%s() cancelled",
330 return LockResult::Cancelled;
332 if (m_comm.SendPacketNoLock(m_comm.m_continue_packet) !=
333 PacketResult::Success)
334 return LockResult::Failed;
336 lldbassert(!m_comm.m_is_running);
337 m_comm.m_is_running = true;
339 return LockResult::Success;
342 ///////////////////////////////
343 // GDBRemoteClientBase::Lock //
344 ///////////////////////////////
346 GDBRemoteClientBase::Lock::Lock(GDBRemoteClientBase &comm, bool interrupt)
347 : m_async_lock(comm.m_async_mutex, std::defer_lock), m_comm(comm),
348 m_acquired(false), m_did_interrupt(false) {
349 SyncWithContinueThread(interrupt);
354 void GDBRemoteClientBase::Lock::SyncWithContinueThread(bool interrupt) {
355 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
356 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
357 if (m_comm.m_is_running && !interrupt)
358 return; // We were asked to avoid interrupting the sender. Lock is not
361 ++m_comm.m_async_count;
362 if (m_comm.m_is_running) {
363 if (m_comm.m_async_count == 1) {
364 // The sender has sent the continue packet and we are the first async
365 // packet. Let's interrupt it.
366 const char ctrl_c = '\x03';
367 ConnectionStatus status = eConnectionStatusSuccess;
368 size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, nullptr);
369 if (bytes_written == 0) {
370 --m_comm.m_async_count;
372 log->Printf("GDBRemoteClientBase::Lock::Lock failed to send "
377 log->PutCString("GDBRemoteClientBase::Lock::Lock sent packet: \\x03");
378 m_comm.m_interrupt_time = steady_clock::now();
380 m_comm.m_cv.wait(lock, [this] { return !m_comm.m_is_running; });
381 m_did_interrupt = true;
386 GDBRemoteClientBase::Lock::~Lock() {
390 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
391 --m_comm.m_async_count;
393 m_comm.m_cv.notify_one();