1 //===-- GDBRemoteClientBase.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "GDBRemoteClientBase.h"
12 #include "llvm/ADT/StringExtras.h"
14 #include "lldb/Target/Process.h"
15 #include "lldb/Target/UnixSignals.h"
16 #include "lldb/Utility/LLDBAssert.h"
18 #include "ProcessGDBRemoteLog.h"
21 using namespace lldb_private;
22 using namespace lldb_private::process_gdb_remote;
23 using namespace std::chrono;
25 static const seconds kInterruptTimeout(5);
27 /////////////////////////
28 // GDBRemoteClientBase //
29 /////////////////////////
31 GDBRemoteClientBase::ContinueDelegate::~ContinueDelegate() = default;
33 GDBRemoteClientBase::GDBRemoteClientBase(const char *comm_name,
34 const char *listener_name)
35 : GDBRemoteCommunication(comm_name, listener_name), m_async_count(0),
36 m_is_running(false), m_should_stop(false) {}
38 StateType GDBRemoteClientBase::SendContinuePacketAndWaitForResponse(
39 ContinueDelegate &delegate, const UnixSignals &signals,
40 llvm::StringRef payload, StringExtractorGDBRemote &response) {
41 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
45 std::lock_guard<std::mutex> lock(m_mutex);
46 m_continue_packet = payload;
47 m_should_stop = false;
49 ContinueLock cont_lock(*this);
52 OnRunPacketSent(true);
55 PacketResult read_result = ReadPacket(response, kInterruptTimeout, false);
56 switch (read_result) {
57 case PacketResult::ErrorReplyTimeout: {
58 std::lock_guard<std::mutex> lock(m_mutex);
59 if (m_async_count == 0)
61 if (steady_clock::now() >= m_interrupt_time + kInterruptTimeout)
65 case PacketResult::Success:
69 log->Printf("GDBRemoteClientBase::%s () ReadPacket(...) => false",
76 const char stop_type = response.GetChar();
78 log->Printf("GDBRemoteClientBase::%s () got packet: %s", __FUNCTION__,
79 response.GetStringRef().c_str());
90 log->Printf("GDBRemoteClientBase::%s () unrecognized async packet",
94 std::string inferior_stdout;
95 response.GetHexByteString(inferior_stdout);
96 delegate.HandleAsyncStdout(inferior_stdout);
100 delegate.HandleAsyncMisc(
101 llvm::StringRef(response.GetStringRef()).substr(1));
104 delegate.HandleAsyncStructuredDataPacket(response.GetStringRef());
108 // Do this with the continue lock held.
109 const bool should_stop = ShouldStop(signals, response);
110 response.SetFilePos(0);
112 // The packet we should resume with. In the future
113 // we should check our thread list and "do the right thing"
114 // for new threads that show up while we stop and run async
115 // packets. Setting the packet to 'c' to continue all threads
116 // is the right thing to do 99.99% of the time because if a
117 // thread was single stepping, and we sent an interrupt, we
118 // will notice above that we didn't stop due to an interrupt
119 // but stopped due to stepping and we would _not_ continue.
120 // This packet may get modified by the async actions (e.g. to send a
122 m_continue_packet = 'c';
125 delegate.HandleStopReply();
127 return eStateStopped;
129 switch (cont_lock.lock()) {
130 case ContinueLock::LockResult::Success:
132 case ContinueLock::LockResult::Failed:
133 return eStateInvalid;
134 case ContinueLock::LockResult::Cancelled:
135 return eStateStopped;
137 OnRunPacketSent(false);
143 bool GDBRemoteClientBase::SendAsyncSignal(int signo) {
144 Lock lock(*this, true);
145 if (!lock || !lock.DidInterrupt())
148 m_continue_packet = 'C';
149 m_continue_packet += llvm::hexdigit((signo / 16) % 16);
150 m_continue_packet += llvm::hexdigit(signo % 16);
154 bool GDBRemoteClientBase::Interrupt() {
155 Lock lock(*this, true);
156 if (!lock.DidInterrupt())
158 m_should_stop = true;
161 GDBRemoteCommunication::PacketResult
162 GDBRemoteClientBase::SendPacketAndWaitForResponse(
163 llvm::StringRef payload, StringExtractorGDBRemote &response,
165 Lock lock(*this, send_async);
168 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS))
169 log->Printf("GDBRemoteClientBase::%s failed to get mutex, not sending "
170 "packet '%.*s' (send_async=%d)",
171 __FUNCTION__, int(payload.size()), payload.data(),
173 return PacketResult::ErrorSendFailed;
176 return SendPacketAndWaitForResponseNoLock(payload, response);
179 GDBRemoteCommunication::PacketResult
180 GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(
181 llvm::StringRef payload, StringExtractorGDBRemote &response) {
182 PacketResult packet_result = SendPacketNoLock(payload);
183 if (packet_result != PacketResult::Success)
184 return packet_result;
186 const size_t max_response_retries = 3;
187 for (size_t i = 0; i < max_response_retries; ++i) {
188 packet_result = ReadPacket(response, GetPacketTimeout(), true);
189 // Make sure we received a response
190 if (packet_result != PacketResult::Success)
191 return packet_result;
192 // Make sure our response is valid for the payload that was sent
193 if (response.ValidateResponse())
194 return packet_result;
195 // Response says it wasn't valid
196 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS);
199 "error: packet with payload \"%.*s\" got invalid response \"%s\": %s",
200 int(payload.size()), payload.data(), response.GetStringRef().c_str(),
201 (i == (max_response_retries - 1))
202 ? "using invalid response and giving up"
203 : "ignoring response and waiting for another");
205 return packet_result;
208 bool GDBRemoteClientBase::SendvContPacket(llvm::StringRef payload,
209 StringExtractorGDBRemote &response) {
210 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
212 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
214 // we want to lock down packet sending while we continue
215 Lock lock(*this, true);
219 "GDBRemoteCommunicationClient::%s () sending vCont packet: %.*s",
220 __FUNCTION__, int(payload.size()), payload.data());
222 if (SendPacketNoLock(payload) != PacketResult::Success)
225 OnRunPacketSent(true);
227 // wait for the response to the vCont
228 if (ReadPacket(response, llvm::None, false) == PacketResult::Success) {
229 if (response.IsOKResponse())
235 bool GDBRemoteClientBase::ShouldStop(const UnixSignals &signals,
236 StringExtractorGDBRemote &response) {
237 std::lock_guard<std::mutex> lock(m_mutex);
239 if (m_async_count == 0)
240 return true; // We were not interrupted. The process stopped on its own.
242 // Older debugserver stubs (before April 2016) can return two
243 // stop-reply packets in response to a ^C packet.
244 // Additionally, all debugservers still return two stop replies if
245 // the inferior stops due to some other reason before the remote
246 // stub manages to interrupt it. We need to wait for this
247 // additional packet to make sure the packet sequence does not get
249 StringExtractorGDBRemote extra_stop_reply_packet;
250 ReadPacket(extra_stop_reply_packet, milliseconds(100), false);
252 // Interrupting is typically done using SIGSTOP or SIGINT, so if
253 // the process stops with some other signal, we definitely want to
255 const uint8_t signo = response.GetHexU8(UINT8_MAX);
256 if (signo != signals.GetSignalNumberFromName("SIGSTOP") &&
257 signo != signals.GetSignalNumberFromName("SIGINT"))
260 // We probably only stopped to perform some async processing, so continue
261 // after that is done.
262 // TODO: This is not 100% correct, as the process may have been stopped with
263 // SIGINT or SIGSTOP that was not caused by us (e.g. raise(SIGINT)). This will
264 // normally cause a stop, but if it's done concurrently with a async
265 // interrupt, that stop will get eaten (llvm.org/pr20231).
269 void GDBRemoteClientBase::OnRunPacketSent(bool first) {
271 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
274 ///////////////////////////////////////
275 // GDBRemoteClientBase::ContinueLock //
276 ///////////////////////////////////////
278 GDBRemoteClientBase::ContinueLock::ContinueLock(GDBRemoteClientBase &comm)
279 : m_comm(comm), m_acquired(false) {
283 GDBRemoteClientBase::ContinueLock::~ContinueLock() {
288 void GDBRemoteClientBase::ContinueLock::unlock() {
289 lldbassert(m_acquired);
291 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
292 m_comm.m_is_running = false;
294 m_comm.m_cv.notify_all();
298 GDBRemoteClientBase::ContinueLock::LockResult
299 GDBRemoteClientBase::ContinueLock::lock() {
300 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
302 log->Printf("GDBRemoteClientBase::ContinueLock::%s() resuming with %s",
303 __FUNCTION__, m_comm.m_continue_packet.c_str());
305 lldbassert(!m_acquired);
306 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
307 m_comm.m_cv.wait(lock, [this] { return m_comm.m_async_count == 0; });
308 if (m_comm.m_should_stop) {
309 m_comm.m_should_stop = false;
311 log->Printf("GDBRemoteClientBase::ContinueLock::%s() cancelled",
313 return LockResult::Cancelled;
315 if (m_comm.SendPacketNoLock(m_comm.m_continue_packet) !=
316 PacketResult::Success)
317 return LockResult::Failed;
319 lldbassert(!m_comm.m_is_running);
320 m_comm.m_is_running = true;
322 return LockResult::Success;
325 ///////////////////////////////
326 // GDBRemoteClientBase::Lock //
327 ///////////////////////////////
329 GDBRemoteClientBase::Lock::Lock(GDBRemoteClientBase &comm, bool interrupt)
330 : m_async_lock(comm.m_async_mutex, std::defer_lock), m_comm(comm),
331 m_acquired(false), m_did_interrupt(false) {
332 SyncWithContinueThread(interrupt);
337 void GDBRemoteClientBase::Lock::SyncWithContinueThread(bool interrupt) {
338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
339 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
340 if (m_comm.m_is_running && !interrupt)
341 return; // We were asked to avoid interrupting the sender. Lock is not
344 ++m_comm.m_async_count;
345 if (m_comm.m_is_running) {
346 if (m_comm.m_async_count == 1) {
347 // The sender has sent the continue packet and we are the first async
348 // packet. Let's interrupt it.
349 const char ctrl_c = '\x03';
350 ConnectionStatus status = eConnectionStatusSuccess;
351 size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, NULL);
352 if (bytes_written == 0) {
353 --m_comm.m_async_count;
355 log->Printf("GDBRemoteClientBase::Lock::Lock failed to send "
360 log->PutCString("GDBRemoteClientBase::Lock::Lock sent packet: \\x03");
361 m_comm.m_interrupt_time = steady_clock::now();
363 m_comm.m_cv.wait(lock, [this] { return m_comm.m_is_running == false; });
364 m_did_interrupt = true;
369 GDBRemoteClientBase::Lock::~Lock() {
373 std::unique_lock<std::mutex> lock(m_comm.m_mutex);
374 --m_comm.m_async_count;
376 m_comm.m_cv.notify_one();