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