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