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