blob: 10362b656a6bbd0e8c6a99bc22088a35f63f4dfe [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- GDBRemoteClientBase.cpp -------------------------------------------===//
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00006//
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
18using namespace lldb;
19using namespace lldb_private;
20using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000021using namespace std::chrono;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000022
Pavel Labath1eff73c2016-11-24 10:54:49 +000023static const seconds kInterruptTimeout(5);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000024
25/////////////////////////
26// GDBRemoteClientBase //
27/////////////////////////
28
29GDBRemoteClientBase::ContinueDelegate::~ContinueDelegate() = default;
30
Kate Stoneb9c1b512016-09-06 20:57:50 +000031GDBRemoteClientBase::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) {}
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000035
Kate Stoneb9c1b512016-09-06 20:57:50 +000036StateType 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();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000041
Kate Stoneb9c1b512016-09-06 20:57:50 +000042 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000043 std::lock_guard<std::mutex> lock(m_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +000044 m_continue_packet = payload;
45 m_should_stop = false;
46 }
47 ContinueLock cont_lock(*this);
48 if (!cont_lock)
49 return eStateInvalid;
50 OnRunPacketSent(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000051
Kate Stoneb9c1b512016-09-06 20:57:50 +000052 for (;;) {
Pavel Labath1eff73c2016-11-24 10:54:49 +000053 PacketResult read_result = ReadPacket(response, kInterruptTimeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 switch (read_result) {
55 case PacketResult::ErrorReplyTimeout: {
56 std::lock_guard<std::mutex> lock(m_mutex);
57 if (m_async_count == 0)
58 continue;
Pavel Labath1eff73c2016-11-24 10:54:49 +000059 if (steady_clock::now() >= m_interrupt_time + kInterruptTimeout)
Kate Stoneb9c1b512016-09-06 20:57:50 +000060 return eStateInvalid;
Adrian Prantla01e0242017-12-19 22:54:37 +000061 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +000062 }
63 case PacketResult::Success:
64 break;
65 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +000066 LLDB_LOGF(log, "GDBRemoteClientBase::%s () ReadPacket(...) => false",
67 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 return eStateInvalid;
69 }
70 if (response.Empty())
71 return eStateInvalid;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073 const char stop_type = response.GetChar();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +000074 LLDB_LOGF(log, "GDBRemoteClientBase::%s () got packet: %s", __FUNCTION__,
Jonas Devlieghered35b42f2019-08-21 04:55:56 +000075 response.GetStringRef().data());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000076
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 switch (stop_type) {
78 case 'W':
79 case 'X':
80 return eStateExited;
81 case 'E':
82 // ERROR
83 return eStateInvalid;
84 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +000085 LLDB_LOGF(log, "GDBRemoteClientBase::%s () unrecognized async packet",
86 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 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;
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 case 'J':
Todd Fialafcdb1af2016-09-10 00:06:29 +000099 delegate.HandleAsyncStructuredDataPacket(response.GetStringRef());
100 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 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
Adrian Prantl05097242018-04-30 16:49:04 +0000107 // 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).
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 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 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000134}
135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136bool 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
147bool GDBRemoteClientBase::Interrupt() {
148 Lock lock(*this, true);
149 if (!lock.DidInterrupt())
150 return false;
151 m_should_stop = true;
152 return true;
153}
154GDBRemoteCommunication::PacketResult
155GDBRemoteClientBase::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))
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000162 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);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 return PacketResult::ErrorSendFailed;
167 }
168
169 return SendPacketAndWaitForResponseNoLock(payload, response);
170}
171
172GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000173GDBRemoteClientBase::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))
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000181 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);
Pavel Labath7da84752018-01-10 14:39:08 +0000185 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
196GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197GDBRemoteClientBase::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) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000205 packet_result = ReadPacket(response, GetPacketTimeout(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 // 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);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000214 LLDB_LOGF(
215 log,
216 "error: packet with payload \"%.*s\" got invalid response \"%s\": %s",
Jonas Devlieghered35b42f2019-08-21 04:55:56 +0000217 int(payload.size()), payload.data(), response.GetStringRef().data(),
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000218 (i == (max_response_retries - 1))
219 ? "using invalid response and giving up"
220 : "ignoring response and waiting for another");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 }
222 return packet_result;
223}
224
225bool GDBRemoteClientBase::SendvContPacket(llvm::StringRef payload,
226 StringExtractorGDBRemote &response) {
227 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000228 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229
230 // we want to lock down packet sending while we continue
231 Lock lock(*this, true);
232
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000233 LLDB_LOGF(log,
234 "GDBRemoteCommunicationClient::%s () sending vCont packet: %.*s",
235 __FUNCTION__, int(payload.size()), payload.data());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236
237 if (SendPacketNoLock(payload) != PacketResult::Success)
238 return false;
239
240 OnRunPacketSent(true);
241
242 // wait for the response to the vCont
Pavel Labath1eff73c2016-11-24 10:54:49 +0000243 if (ReadPacket(response, llvm::None, false) == PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 if (response.IsOKResponse())
245 return true;
246 }
247
248 return false;
249}
250bool 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
Adrian Prantl05097242018-04-30 16:49:04 +0000257 // 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.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 StringExtractorGDBRemote extra_stop_reply_packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000263 ReadPacket(extra_stop_reply_packet, milliseconds(100), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264
Adrian Prantl05097242018-04-30 16:49:04 +0000265 // Interrupting is typically done using SIGSTOP or SIGINT, so if the process
266 // stops with some other signal, we definitely want to stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 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
Pavel Labath1eff73c2016-11-24 10:54:49 +0000275 // 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).
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278 return false;
279}
280
281void GDBRemoteClientBase::OnRunPacketSent(bool first) {
282 if (first)
Konrad Kleine248a1302019-05-23 11:14:47 +0000283 BroadcastEvent(eBroadcastBitRunPacketSent, nullptr);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000284}
285
286///////////////////////////////////////
287// GDBRemoteClientBase::ContinueLock //
288///////////////////////////////////////
289
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290GDBRemoteClientBase::ContinueLock::ContinueLock(GDBRemoteClientBase &comm)
291 : m_comm(comm), m_acquired(false) {
292 lock();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000293}
294
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295GDBRemoteClientBase::ContinueLock::~ContinueLock() {
296 if (m_acquired)
297 unlock();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000298}
299
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300void 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;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000308}
309
310GDBRemoteClientBase::ContinueLock::LockResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311GDBRemoteClientBase::ContinueLock::lock() {
312 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000313 LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() resuming with %s",
314 __FUNCTION__, m_comm.m_continue_packet.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315
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;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000321 LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() cancelled",
322 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 return LockResult::Cancelled;
324 }
325 if (m_comm.SendPacketNoLock(m_comm.m_continue_packet) !=
326 PacketResult::Success)
327 return LockResult::Failed;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 lldbassert(!m_comm.m_is_running);
330 m_comm.m_is_running = true;
331 m_acquired = true;
332 return LockResult::Success;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000333}
334
335///////////////////////////////
336// GDBRemoteClientBase::Lock //
337///////////////////////////////
338
339GDBRemoteClientBase::Lock::Lock(GDBRemoteClientBase &comm, bool interrupt)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 : 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();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000345}
346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347void 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.
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 ++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;
Konrad Kleine248a1302019-05-23 11:14:47 +0000361 size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 if (bytes_written == 0) {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000363 --m_comm.m_async_count;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000364 LLDB_LOGF(log, "GDBRemoteClientBase::Lock::Lock failed to send "
365 "interrupt packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 return;
367 }
368 if (log)
369 log->PutCString("GDBRemoteClientBase::Lock::Lock sent packet: \\x03");
Pavel Labath1eff73c2016-11-24 10:54:49 +0000370 m_comm.m_interrupt_time = steady_clock::now();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000371 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000372 m_comm.m_cv.wait(lock, [this] { return !m_comm.m_is_running; });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 m_did_interrupt = true;
374 }
375 m_acquired = true;
376}
377
378GDBRemoteClientBase::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();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000386}