xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp (revision 446b61cff4ea0cb7e7fcc5e0fec7bc749d379b08)
1 //===-- GDBRemoteClientBase.cpp -------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "GDBRemoteClientBase.h"
10 
11 #include "llvm/ADT/StringExtras.h"
12 
13 #include "lldb/Target/UnixSignals.h"
14 #include "lldb/Utility/Connection.h"
15 #include "lldb/Utility/LLDBAssert.h"
16 
17 #include "ProcessGDBRemoteLog.h"
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 using namespace lldb_private::process_gdb_remote;
22 using namespace std::chrono;
23 
24 // When we've sent a continue packet and are waiting for the target to stop,
25 // we wake up the wait with this interval to make sure the stub hasn't gone
26 // away while we were waiting.
27 static const seconds kWakeupInterval(5);
28 
29 /////////////////////////
30 // GDBRemoteClientBase //
31 /////////////////////////
32 
33 GDBRemoteClientBase::ContinueDelegate::~ContinueDelegate() = default;
34 
35 GDBRemoteClientBase::GDBRemoteClientBase(const char *comm_name,
36                                          const char *listener_name)
37     : GDBRemoteCommunication(comm_name, listener_name), m_async_count(0),
38       m_is_running(false), m_should_stop(false) {}
39 
40 StateType GDBRemoteClientBase::SendContinuePacketAndWaitForResponse(
41     ContinueDelegate &delegate, const UnixSignals &signals,
42     llvm::StringRef payload, std::chrono::seconds interrupt_timeout,
43     StringExtractorGDBRemote &response) {
44   Log *log = GetLog(GDBRLog::Process);
45   response.Clear();
46 
47   {
48     std::lock_guard<std::mutex> lock(m_mutex);
49     m_continue_packet = std::string(payload);
50     m_should_stop = false;
51   }
52   ContinueLock cont_lock(*this);
53   if (!cont_lock)
54     return eStateInvalid;
55   OnRunPacketSent(true);
56   // The main ReadPacket loop wakes up at computed_timeout intervals, just to
57   // check that the connection hasn't dropped.  When we wake up we also check
58   // whether there is an interrupt request that has reached its endpoint.
59   // If we want a shorter interrupt timeout that kWakeupInterval, we need to
60   // choose the shorter interval for the wake up as well.
61   std::chrono::seconds computed_timeout =
62       std::min(interrupt_timeout, kWakeupInterval);
63   std::chrono::time_point<std::chrono::steady_clock> interrupt_endpoint;
64   bool interrupt_sent = false;
65   for (;;) {
66     PacketResult read_result = ReadPacket(response, computed_timeout, false);
67     // Reset the computed_timeout to the default value in case we are going
68     // round again.
69     computed_timeout = std::min(interrupt_timeout, kWakeupInterval);
70     switch (read_result) {
71     case PacketResult::ErrorReplyTimeout: {
72       std::lock_guard<std::mutex> lock(m_mutex);
73       if (m_async_count == 0) {
74         continue;
75       }
76       if (!interrupt_sent) {
77         const char ctrl_c = '\x03';
78         ConnectionStatus status = eConnectionStatusSuccess;
79         size_t bytes_written = Write(&ctrl_c, 1, status, nullptr);
80         if (bytes_written == 0) {
81           LLDB_LOG(log, "failed to send interrupt packet");
82           return eStateInvalid;
83         }
84         interrupt_endpoint = steady_clock::now() + interrupt_timeout;
85         if (log)
86           log->PutCString(
87               "GDBRemoteClientBase::SendContinuePacketAndWaitForResponse sent "
88               "packet: \\x03");
89 
90         interrupt_sent = true;
91         continue;
92       }
93 
94       auto cur_time = steady_clock::now();
95       if (cur_time >= interrupt_endpoint)
96         return eStateInvalid;
97       else {
98         // We woke up and found an interrupt is in flight, but we haven't
99         // exceeded the interrupt wait time.  So reset the wait time to the
100         // time left till the interrupt timeout.  But don't wait longer
101         // than our wakeup timeout.
102         auto new_wait = interrupt_endpoint - cur_time;
103         computed_timeout = std::min(
104             kWakeupInterval,
105             std::chrono::duration_cast<std::chrono::seconds>(new_wait));
106         continue;
107       }
108       break;
109     }
110     case PacketResult::Success:
111       break;
112     default:
113       LLDB_LOGF(log, "GDBRemoteClientBase::%s () ReadPacket(...) => false",
114                 __FUNCTION__);
115       return eStateInvalid;
116     }
117     if (response.Empty())
118       return eStateInvalid;
119 
120     const char stop_type = response.GetChar();
121     LLDB_LOGF(log, "GDBRemoteClientBase::%s () got packet: %s", __FUNCTION__,
122               response.GetStringRef().data());
123 
124     switch (stop_type) {
125     case 'W':
126     case 'X':
127       return eStateExited;
128     case 'E':
129       // ERROR
130       return eStateInvalid;
131     default:
132       LLDB_LOGF(log, "GDBRemoteClientBase::%s () unrecognized async packet",
133                 __FUNCTION__);
134       return eStateInvalid;
135     case 'O': {
136       std::string inferior_stdout;
137       response.GetHexByteString(inferior_stdout);
138       delegate.HandleAsyncStdout(inferior_stdout);
139       break;
140     }
141     case 'A':
142       delegate.HandleAsyncMisc(
143           llvm::StringRef(response.GetStringRef()).substr(1));
144       break;
145     case 'J':
146       delegate.HandleAsyncStructuredDataPacket(response.GetStringRef());
147       break;
148     case 'T':
149     case 'S':
150       // Do this with the continue lock held.
151       const bool should_stop = ShouldStop(signals, response);
152       response.SetFilePos(0);
153 
154       // The packet we should resume with. In the future we should check our
155       // thread list and "do the right thing" for new threads that show up
156       // while we stop and run async packets. Setting the packet to 'c' to
157       // continue all threads is the right thing to do 99.99% of the time
158       // because if a thread was single stepping, and we sent an interrupt, we
159       // will notice above that we didn't stop due to an interrupt but stopped
160       // due to stepping and we would _not_ continue. This packet may get
161       // modified by the async actions (e.g. to send a signal).
162       m_continue_packet = 'c';
163       cont_lock.unlock();
164 
165       delegate.HandleStopReply();
166       if (should_stop)
167         return eStateStopped;
168 
169       switch (cont_lock.lock()) {
170       case ContinueLock::LockResult::Success:
171         break;
172       case ContinueLock::LockResult::Failed:
173         return eStateInvalid;
174       case ContinueLock::LockResult::Cancelled:
175         return eStateStopped;
176       }
177       OnRunPacketSent(false);
178       break;
179     }
180   }
181 }
182 
183 bool GDBRemoteClientBase::SendAsyncSignal(
184     int signo, std::chrono::seconds interrupt_timeout) {
185   Lock lock(*this, interrupt_timeout);
186   if (!lock || !lock.DidInterrupt())
187     return false;
188 
189   m_continue_packet = 'C';
190   m_continue_packet += llvm::hexdigit((signo / 16) % 16);
191   m_continue_packet += llvm::hexdigit(signo % 16);
192   return true;
193 }
194 
195 bool GDBRemoteClientBase::Interrupt(std::chrono::seconds interrupt_timeout) {
196   Lock lock(*this, interrupt_timeout);
197   if (!lock.DidInterrupt())
198     return false;
199   m_should_stop = true;
200   return true;
201 }
202 
203 GDBRemoteCommunication::PacketResult
204 GDBRemoteClientBase::SendPacketAndWaitForResponse(
205     llvm::StringRef payload, StringExtractorGDBRemote &response,
206     std::chrono::seconds interrupt_timeout) {
207   Lock lock(*this, interrupt_timeout);
208   if (!lock) {
209     if (Log *log = GetLog(GDBRLog::Process))
210       LLDB_LOGF(log,
211                 "GDBRemoteClientBase::%s failed to get mutex, not sending "
212                 "packet '%.*s'",
213                 __FUNCTION__, int(payload.size()), payload.data());
214     return PacketResult::ErrorSendFailed;
215   }
216 
217   return SendPacketAndWaitForResponseNoLock(payload, response);
218 }
219 
220 GDBRemoteCommunication::PacketResult
221 GDBRemoteClientBase::SendPacketAndReceiveResponseWithOutputSupport(
222     llvm::StringRef payload, StringExtractorGDBRemote &response,
223     std::chrono::seconds interrupt_timeout,
224     llvm::function_ref<void(llvm::StringRef)> output_callback) {
225   Lock lock(*this, interrupt_timeout);
226   if (!lock) {
227     if (Log *log = GetLog(GDBRLog::Process))
228       LLDB_LOGF(log,
229                 "GDBRemoteClientBase::%s failed to get mutex, not sending "
230                 "packet '%.*s'",
231                 __FUNCTION__, int(payload.size()), payload.data());
232     return PacketResult::ErrorSendFailed;
233   }
234 
235   PacketResult packet_result = SendPacketNoLock(payload);
236   if (packet_result != PacketResult::Success)
237     return packet_result;
238 
239   return ReadPacketWithOutputSupport(response, GetPacketTimeout(), true,
240                                      output_callback);
241 }
242 
243 GDBRemoteCommunication::PacketResult
244 GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(
245     llvm::StringRef payload, StringExtractorGDBRemote &response) {
246   PacketResult packet_result = SendPacketNoLock(payload);
247   if (packet_result != PacketResult::Success)
248     return packet_result;
249 
250   const size_t max_response_retries = 3;
251   for (size_t i = 0; i < max_response_retries; ++i) {
252     packet_result = ReadPacket(response, GetPacketTimeout(), true);
253     // Make sure we received a response
254     if (packet_result != PacketResult::Success)
255       return packet_result;
256     // Make sure our response is valid for the payload that was sent
257     if (response.ValidateResponse())
258       return packet_result;
259     // Response says it wasn't valid
260     Log *log = GetLog(GDBRLog::Packets);
261     LLDB_LOGF(
262         log,
263         "error: packet with payload \"%.*s\" got invalid response \"%s\": %s",
264         int(payload.size()), payload.data(), response.GetStringRef().data(),
265         (i == (max_response_retries - 1))
266             ? "using invalid response and giving up"
267             : "ignoring response and waiting for another");
268   }
269   return packet_result;
270 }
271 
272 bool GDBRemoteClientBase::ShouldStop(const UnixSignals &signals,
273                                      StringExtractorGDBRemote &response) {
274   std::lock_guard<std::mutex> lock(m_mutex);
275 
276   if (m_async_count == 0)
277     return true; // We were not interrupted. The process stopped on its own.
278 
279   // Older debugserver stubs (before April 2016) can return two stop-reply
280   // packets in response to a ^C packet. Additionally, all debugservers still
281   // return two stop replies if the inferior stops due to some other reason
282   // before the remote stub manages to interrupt it. We need to wait for this
283   // additional packet to make sure the packet sequence does not get skewed.
284   StringExtractorGDBRemote extra_stop_reply_packet;
285   ReadPacket(extra_stop_reply_packet, milliseconds(100), false);
286 
287   // Interrupting is typically done using SIGSTOP or SIGINT, so if the process
288   // stops with some other signal, we definitely want to stop.
289   const uint8_t signo = response.GetHexU8(UINT8_MAX);
290   if (signo != signals.GetSignalNumberFromName("SIGSTOP") &&
291       signo != signals.GetSignalNumberFromName("SIGINT"))
292     return true;
293 
294   // We probably only stopped to perform some async processing, so continue
295   // after that is done.
296   // TODO: This is not 100% correct, as the process may have been stopped with
297   // SIGINT or SIGSTOP that was not caused by us (e.g. raise(SIGINT)). This will
298   // normally cause a stop, but if it's done concurrently with a async
299   // interrupt, that stop will get eaten (llvm.org/pr20231).
300   return false;
301 }
302 
303 void GDBRemoteClientBase::OnRunPacketSent(bool first) {
304   if (first)
305     BroadcastEvent(eBroadcastBitRunPacketSent, nullptr);
306 }
307 
308 ///////////////////////////////////////
309 // GDBRemoteClientBase::ContinueLock //
310 ///////////////////////////////////////
311 
312 GDBRemoteClientBase::ContinueLock::ContinueLock(GDBRemoteClientBase &comm)
313     : m_comm(comm), m_acquired(false) {
314   lock();
315 }
316 
317 GDBRemoteClientBase::ContinueLock::~ContinueLock() {
318   if (m_acquired)
319     unlock();
320 }
321 
322 void GDBRemoteClientBase::ContinueLock::unlock() {
323   lldbassert(m_acquired);
324   {
325     std::unique_lock<std::mutex> lock(m_comm.m_mutex);
326     m_comm.m_is_running = false;
327   }
328   m_comm.m_cv.notify_all();
329   m_acquired = false;
330 }
331 
332 GDBRemoteClientBase::ContinueLock::LockResult
333 GDBRemoteClientBase::ContinueLock::lock() {
334   Log *log = GetLog(GDBRLog::Process);
335   LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() resuming with %s",
336             __FUNCTION__, m_comm.m_continue_packet.c_str());
337 
338   lldbassert(!m_acquired);
339   std::unique_lock<std::mutex> lock(m_comm.m_mutex);
340   m_comm.m_cv.wait(lock, [this] { return m_comm.m_async_count == 0; });
341   if (m_comm.m_should_stop) {
342     m_comm.m_should_stop = false;
343     LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() cancelled",
344               __FUNCTION__);
345     return LockResult::Cancelled;
346   }
347   if (m_comm.SendPacketNoLock(m_comm.m_continue_packet) !=
348       PacketResult::Success)
349     return LockResult::Failed;
350 
351   lldbassert(!m_comm.m_is_running);
352   m_comm.m_is_running = true;
353   m_acquired = true;
354   return LockResult::Success;
355 }
356 
357 ///////////////////////////////
358 // GDBRemoteClientBase::Lock //
359 ///////////////////////////////
360 
361 GDBRemoteClientBase::Lock::Lock(GDBRemoteClientBase &comm,
362                                 std::chrono::seconds interrupt_timeout)
363     : m_async_lock(comm.m_async_mutex, std::defer_lock), m_comm(comm),
364       m_interrupt_timeout(interrupt_timeout), m_acquired(false),
365       m_did_interrupt(false) {
366   SyncWithContinueThread();
367   if (m_acquired)
368     m_async_lock.lock();
369 }
370 
371 void GDBRemoteClientBase::Lock::SyncWithContinueThread() {
372   std::unique_lock<std::mutex> lock(m_comm.m_mutex);
373   if (m_comm.m_is_running && m_interrupt_timeout == std::chrono::seconds(0))
374     return; // We were asked to avoid interrupting the sender. Lock is not
375             // acquired.
376 
377   ++m_comm.m_async_count;
378   if (m_comm.m_is_running) {
379     // SendContinuePacketAndWaitForResponse() takes care of sending
380     // the actual interrupt packet since we've increased m_async_count.
381     // Interrupt the ReadPacket() call to avoid having to wait for
382     // the interrupt timeout.
383     m_comm.GetConnection()->InterruptRead();
384     m_comm.m_cv.wait(lock, [this] { return !m_comm.m_is_running; });
385     m_did_interrupt = true;
386   }
387   m_acquired = true;
388 }
389 
390 GDBRemoteClientBase::Lock::~Lock() {
391   if (!m_acquired)
392     return;
393   {
394     std::unique_lock<std::mutex> lock(m_comm.m_mutex);
395     --m_comm.m_async_count;
396   }
397   m_comm.m_cv.notify_one();
398 }
399