1 //===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "GDBRemoteCommunicationClient.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Host/HostInfo.h"
19 #include "lldb/Host/XML.h"
20 #include "lldb/Symbol/Symbol.h"
21 #include "lldb/Target/MemoryRegionInfo.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/UnixSignals.h"
24 #include "lldb/Utility/Args.h"
25 #include "lldb/Utility/DataBufferHeap.h"
26 #include "lldb/Utility/JSON.h"
27 #include "lldb/Utility/LLDBAssert.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/State.h"
30 #include "lldb/Utility/StreamString.h"
32 #include "ProcessGDBRemote.h"
33 #include "ProcessGDBRemoteLog.h"
34 #include "lldb/Host/Config.h"
35 #include "lldb/Utility/StringExtractorGDBRemote.h"
37 #include "llvm/ADT/StringSwitch.h"
39 #if defined(__APPLE__)
40 #ifndef HAVE_LIBCOMPRESSION
41 #define HAVE_LIBCOMPRESSION
43 #include <compression.h>
47 using namespace lldb_private;
48 using namespace lldb_private::process_gdb_remote;
49 using namespace std::chrono;
51 // GDBRemoteCommunicationClient constructor
52 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
53 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
54 m_supports_not_sending_acks(eLazyBoolCalculate),
55 m_supports_thread_suffix(eLazyBoolCalculate),
56 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
57 m_supports_vCont_all(eLazyBoolCalculate),
58 m_supports_vCont_any(eLazyBoolCalculate),
59 m_supports_vCont_c(eLazyBoolCalculate),
60 m_supports_vCont_C(eLazyBoolCalculate),
61 m_supports_vCont_s(eLazyBoolCalculate),
62 m_supports_vCont_S(eLazyBoolCalculate),
63 m_qHostInfo_is_valid(eLazyBoolCalculate),
64 m_curr_pid_is_valid(eLazyBoolCalculate),
65 m_qProcessInfo_is_valid(eLazyBoolCalculate),
66 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
67 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
68 m_supports_memory_region_info(eLazyBoolCalculate),
69 m_supports_watchpoint_support_info(eLazyBoolCalculate),
70 m_supports_detach_stay_stopped(eLazyBoolCalculate),
71 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
72 m_attach_or_wait_reply(eLazyBoolCalculate),
73 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
74 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
75 m_avoid_g_packets(eLazyBoolCalculate),
76 m_supports_QSaveRegisterState(eLazyBoolCalculate),
77 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
78 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
80 m_supports_qXfer_features_read(eLazyBoolCalculate),
81 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
82 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
83 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
84 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
85 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
86 m_supports_QPassSignals(eLazyBoolCalculate),
87 m_supports_error_string_reply(eLazyBoolCalculate),
88 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
89 m_supports_qUserName(true), m_supports_qGroupName(true),
90 m_supports_qThreadStopInfo(true), m_supports_z0(true),
91 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
92 m_supports_z4(true), m_supports_QEnvironment(true),
93 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
94 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
95 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
96 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
97 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
98 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
99 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
100 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
101 m_max_packet_size(0), m_qSupported_response(),
102 m_supported_async_json_packets_is_valid(false),
103 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
104 m_qXfer_memory_map_loaded(false) {}
107 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
112 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
113 ResetDiscoverableSettings(false);
115 // Start the read thread after we send the handshake ack since if we fail to
116 // send the handshake ack, there is no reason to continue...
118 // Wait for any responses that might have been queued up in the remote
119 // GDB server and flush them all
120 StringExtractorGDBRemote response;
121 PacketResult packet_result = PacketResult::Success;
122 while (packet_result == PacketResult::Success)
123 packet_result = ReadPacket(response, milliseconds(10), false);
125 // The return value from QueryNoAckModeSupported() is true if the packet
126 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
127 // false if no response was received. This quickly tells us if we have a
128 // live connection to a remote GDB server...
129 if (QueryNoAckModeSupported()) {
133 error_ptr->SetErrorString("failed to get reply to handshake packet");
137 error_ptr->SetErrorString("failed to send the handshake ack");
142 bool GDBRemoteCommunicationClient::GetEchoSupported() {
143 if (m_supports_qEcho == eLazyBoolCalculate) {
144 GetRemoteQSupported();
146 return m_supports_qEcho == eLazyBoolYes;
149 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
150 if (m_supports_QPassSignals == eLazyBoolCalculate) {
151 GetRemoteQSupported();
153 return m_supports_QPassSignals == eLazyBoolYes;
156 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
157 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
158 GetRemoteQSupported();
160 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
163 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
164 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
165 GetRemoteQSupported();
167 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
170 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
171 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
172 GetRemoteQSupported();
174 return m_supports_qXfer_libraries_read == eLazyBoolYes;
177 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
178 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
179 GetRemoteQSupported();
181 return m_supports_qXfer_auxv_read == eLazyBoolYes;
184 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
185 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
186 GetRemoteQSupported();
188 return m_supports_qXfer_features_read == eLazyBoolYes;
191 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
192 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
193 GetRemoteQSupported();
195 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
198 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
199 if (m_max_packet_size == 0) {
200 GetRemoteQSupported();
202 return m_max_packet_size;
205 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
206 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
208 m_supports_not_sending_acks = eLazyBoolNo;
210 // This is the first real packet that we'll send in a debug session and it
211 // may take a little longer than normal to receive a reply. Wait at least
212 // 6 seconds for a reply to this packet.
214 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
216 StringExtractorGDBRemote response;
217 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
218 PacketResult::Success) {
219 if (response.IsOKResponse()) {
221 m_supports_not_sending_acks = eLazyBoolYes;
229 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
230 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
231 m_supports_threads_in_stop_reply = eLazyBoolNo;
233 StringExtractorGDBRemote response;
234 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
235 false) == PacketResult::Success) {
236 if (response.IsOKResponse())
237 m_supports_threads_in_stop_reply = eLazyBoolYes;
242 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
243 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
244 m_attach_or_wait_reply = eLazyBoolNo;
246 StringExtractorGDBRemote response;
247 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
248 false) == PacketResult::Success) {
249 if (response.IsOKResponse())
250 m_attach_or_wait_reply = eLazyBoolYes;
253 return m_attach_or_wait_reply == eLazyBoolYes;
256 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
257 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
258 m_prepare_for_reg_writing_reply = eLazyBoolNo;
260 StringExtractorGDBRemote response;
261 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
262 false) == PacketResult::Success) {
263 if (response.IsOKResponse())
264 m_prepare_for_reg_writing_reply = eLazyBoolYes;
267 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
270 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
272 // Hard reset everything, this is when we first connect to a GDB server
273 m_supports_not_sending_acks = eLazyBoolCalculate;
274 m_supports_thread_suffix = eLazyBoolCalculate;
275 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
276 m_supports_vCont_c = eLazyBoolCalculate;
277 m_supports_vCont_C = eLazyBoolCalculate;
278 m_supports_vCont_s = eLazyBoolCalculate;
279 m_supports_vCont_S = eLazyBoolCalculate;
280 m_supports_p = eLazyBoolCalculate;
281 m_supports_x = eLazyBoolCalculate;
282 m_supports_QSaveRegisterState = eLazyBoolCalculate;
283 m_qHostInfo_is_valid = eLazyBoolCalculate;
284 m_curr_pid_is_valid = eLazyBoolCalculate;
285 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
286 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
287 m_supports_memory_region_info = eLazyBoolCalculate;
288 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
289 m_attach_or_wait_reply = eLazyBoolCalculate;
290 m_avoid_g_packets = eLazyBoolCalculate;
291 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
292 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
293 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_qXfer_features_read = eLazyBoolCalculate;
295 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
296 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qProcessInfoPID = true;
298 m_supports_qfProcessInfo = true;
299 m_supports_qUserName = true;
300 m_supports_qGroupName = true;
301 m_supports_qThreadStopInfo = true;
302 m_supports_z0 = true;
303 m_supports_z1 = true;
304 m_supports_z2 = true;
305 m_supports_z3 = true;
306 m_supports_z4 = true;
307 m_supports_QEnvironment = true;
308 m_supports_QEnvironmentHexEncoded = true;
309 m_supports_qSymbol = true;
310 m_qSymbol_requests_done = false;
311 m_supports_qModuleInfo = true;
313 m_os_version = llvm::VersionTuple();
317 m_gdb_server_name.clear();
318 m_gdb_server_version = UINT32_MAX;
319 m_default_packet_timeout = seconds(0);
320 m_max_packet_size = 0;
321 m_qSupported_response.clear();
322 m_supported_async_json_packets_is_valid = false;
323 m_supported_async_json_packets_sp.reset();
324 m_supports_jModulesInfo = true;
327 // These flags should be reset when we first connect to a GDB server and when
328 // our inferior process execs
329 m_qProcessInfo_is_valid = eLazyBoolCalculate;
330 m_process_arch.Clear();
333 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
334 // Clear out any capabilities we expect to see in the qSupported response
335 m_supports_qXfer_auxv_read = eLazyBoolNo;
336 m_supports_qXfer_libraries_read = eLazyBoolNo;
337 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
338 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
339 m_supports_qXfer_features_read = eLazyBoolNo;
340 m_supports_qXfer_memory_map_read = eLazyBoolNo;
341 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
342 // not, we assume no limit
344 // build the qSupported packet
345 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
347 packet.PutCString("qSupported");
348 for (uint32_t i = 0; i < features.size(); ++i) {
349 packet.PutCString(i == 0 ? ":" : ";");
350 packet.PutCString(features[i]);
353 StringExtractorGDBRemote response;
354 if (SendPacketAndWaitForResponse(packet.GetString(), response,
355 /*send_async=*/false) ==
356 PacketResult::Success) {
357 const char *response_cstr = response.GetStringRef().c_str();
359 // Hang on to the qSupported packet, so that platforms can do custom
360 // configuration of the transport before attaching/launching the process.
361 m_qSupported_response = response_cstr;
363 if (::strstr(response_cstr, "qXfer:auxv:read+"))
364 m_supports_qXfer_auxv_read = eLazyBoolYes;
365 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
366 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
367 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
368 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
369 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
371 if (::strstr(response_cstr, "qXfer:libraries:read+"))
372 m_supports_qXfer_libraries_read = eLazyBoolYes;
373 if (::strstr(response_cstr, "qXfer:features:read+"))
374 m_supports_qXfer_features_read = eLazyBoolYes;
375 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
376 m_supports_qXfer_memory_map_read = eLazyBoolYes;
378 // Look for a list of compressions in the features list e.g.
379 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
381 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
383 const char *compressions =
384 ::strstr(features_list, "SupportedCompressions=");
386 std::vector<std::string> supported_compressions;
387 compressions += sizeof("SupportedCompressions=") - 1;
388 const char *end_of_compressions = strchr(compressions, ';');
389 if (end_of_compressions == nullptr) {
390 end_of_compressions = strchr(compressions, '\0');
392 const char *current_compression = compressions;
393 while (current_compression < end_of_compressions) {
394 const char *next_compression_name = strchr(current_compression, ',');
395 const char *end_of_this_word = next_compression_name;
396 if (next_compression_name == nullptr ||
397 end_of_compressions < next_compression_name) {
398 end_of_this_word = end_of_compressions;
401 if (end_of_this_word) {
402 if (end_of_this_word == current_compression) {
403 current_compression++;
405 std::string this_compression(
406 current_compression, end_of_this_word - current_compression);
407 supported_compressions.push_back(this_compression);
408 current_compression = end_of_this_word + 1;
411 supported_compressions.push_back(current_compression);
412 current_compression = end_of_compressions;
416 if (supported_compressions.size() > 0) {
417 MaybeEnableCompression(supported_compressions);
422 if (::strstr(response_cstr, "qEcho"))
423 m_supports_qEcho = eLazyBoolYes;
425 m_supports_qEcho = eLazyBoolNo;
427 if (::strstr(response_cstr, "QPassSignals+"))
428 m_supports_QPassSignals = eLazyBoolYes;
430 m_supports_QPassSignals = eLazyBoolNo;
432 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
433 if (packet_size_str) {
434 StringExtractorGDBRemote packet_response(packet_size_str +
435 strlen("PacketSize="));
437 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
438 if (m_max_packet_size == 0) {
439 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
441 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
443 log->Printf("Garbled PacketSize spec in qSupported response");
449 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
450 if (m_supports_thread_suffix == eLazyBoolCalculate) {
451 StringExtractorGDBRemote response;
452 m_supports_thread_suffix = eLazyBoolNo;
453 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
454 false) == PacketResult::Success) {
455 if (response.IsOKResponse())
456 m_supports_thread_suffix = eLazyBoolYes;
459 return m_supports_thread_suffix;
461 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
462 if (m_supports_vCont_c == eLazyBoolCalculate) {
463 StringExtractorGDBRemote response;
464 m_supports_vCont_any = eLazyBoolNo;
465 m_supports_vCont_all = eLazyBoolNo;
466 m_supports_vCont_c = eLazyBoolNo;
467 m_supports_vCont_C = eLazyBoolNo;
468 m_supports_vCont_s = eLazyBoolNo;
469 m_supports_vCont_S = eLazyBoolNo;
470 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
471 PacketResult::Success) {
472 const char *response_cstr = response.GetStringRef().c_str();
473 if (::strstr(response_cstr, ";c"))
474 m_supports_vCont_c = eLazyBoolYes;
476 if (::strstr(response_cstr, ";C"))
477 m_supports_vCont_C = eLazyBoolYes;
479 if (::strstr(response_cstr, ";s"))
480 m_supports_vCont_s = eLazyBoolYes;
482 if (::strstr(response_cstr, ";S"))
483 m_supports_vCont_S = eLazyBoolYes;
485 if (m_supports_vCont_c == eLazyBoolYes &&
486 m_supports_vCont_C == eLazyBoolYes &&
487 m_supports_vCont_s == eLazyBoolYes &&
488 m_supports_vCont_S == eLazyBoolYes) {
489 m_supports_vCont_all = eLazyBoolYes;
492 if (m_supports_vCont_c == eLazyBoolYes ||
493 m_supports_vCont_C == eLazyBoolYes ||
494 m_supports_vCont_s == eLazyBoolYes ||
495 m_supports_vCont_S == eLazyBoolYes) {
496 m_supports_vCont_any = eLazyBoolYes;
503 return m_supports_vCont_any;
505 return m_supports_vCont_all;
507 return m_supports_vCont_c;
509 return m_supports_vCont_C;
511 return m_supports_vCont_s;
513 return m_supports_vCont_S;
520 GDBRemoteCommunication::PacketResult
521 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
522 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
524 Lock lock(*this, send_async);
526 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
527 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
528 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
530 __FUNCTION__, payload.GetData());
531 return PacketResult::ErrorNoSequenceLock;
534 if (GetThreadSuffixSupported())
535 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
537 if (!SetCurrentThread(tid))
538 return PacketResult::ErrorSendFailed;
541 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
544 // Check if the target supports 'p' packet. It sends out a 'p' packet and
545 // checks the response. A normal packet will tell us that support is available.
547 // Takes a valid thread ID because p needs to apply to a thread.
548 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
549 if (m_supports_p == eLazyBoolCalculate) {
550 m_supports_p = eLazyBoolNo;
551 StreamString payload;
552 payload.PutCString("p0");
553 StringExtractorGDBRemote response;
554 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
556 PacketResult::Success &&
557 response.IsNormalResponse()) {
558 m_supports_p = eLazyBoolYes;
564 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
565 // Get information on all threads at one using the "jThreadsInfo" packet
566 StructuredData::ObjectSP object_sp;
568 if (m_supports_jThreadsInfo) {
569 StringExtractorGDBRemote response;
570 response.SetResponseValidatorToJSON();
571 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
572 PacketResult::Success) {
573 if (response.IsUnsupportedResponse()) {
574 m_supports_jThreadsInfo = false;
575 } else if (!response.Empty()) {
576 object_sp = StructuredData::ParseJSON(response.GetStringRef());
583 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
584 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
585 StringExtractorGDBRemote response;
586 m_supports_jThreadExtendedInfo = eLazyBoolNo;
587 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
588 PacketResult::Success) {
589 if (response.IsOKResponse()) {
590 m_supports_jThreadExtendedInfo = eLazyBoolYes;
594 return m_supports_jThreadExtendedInfo;
597 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
598 if (m_supports_error_string_reply == eLazyBoolCalculate) {
599 StringExtractorGDBRemote response;
600 // We try to enable error strings in remote packets but if we fail, we just
601 // work in the older way.
602 m_supports_error_string_reply = eLazyBoolNo;
603 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
604 PacketResult::Success) {
605 if (response.IsOKResponse()) {
606 m_supports_error_string_reply = eLazyBoolYes;
612 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
613 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
614 StringExtractorGDBRemote response;
615 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
616 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
618 false) == PacketResult::Success) {
619 if (response.IsOKResponse()) {
620 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
624 return m_supports_jLoadedDynamicLibrariesInfos;
627 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
628 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
629 StringExtractorGDBRemote response;
630 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
631 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
632 PacketResult::Success) {
633 if (response.IsOKResponse()) {
634 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
638 return m_supports_jGetSharedCacheInfo;
641 bool GDBRemoteCommunicationClient::GetxPacketSupported() {
642 if (m_supports_x == eLazyBoolCalculate) {
643 StringExtractorGDBRemote response;
644 m_supports_x = eLazyBoolNo;
646 snprintf(packet, sizeof(packet), "x0,0");
647 if (SendPacketAndWaitForResponse(packet, response, false) ==
648 PacketResult::Success) {
649 if (response.IsOKResponse())
650 m_supports_x = eLazyBoolYes;
656 GDBRemoteCommunicationClient::PacketResult
657 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
658 const char *payload_prefix, std::string &response_string) {
659 Lock lock(*this, false);
661 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
664 log->Printf("error: failed to get packet sequence mutex, not sending "
665 "packets with prefix '%s'",
667 return PacketResult::ErrorNoSequenceLock;
670 response_string = "";
671 std::string payload_prefix_str(payload_prefix);
672 unsigned int response_size = 0x1000;
673 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
674 response_size = GetRemoteMaxPacketSize();
677 for (unsigned int offset = 0; true; offset += response_size) {
678 StringExtractorGDBRemote this_response;
680 char sizeDescriptor[128];
681 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
683 PacketResult result = SendPacketAndWaitForResponseNoLock(
684 payload_prefix_str + sizeDescriptor, this_response);
685 if (result != PacketResult::Success)
688 const std::string &this_string = this_response.GetStringRef();
690 // Check for m or l as first character; l seems to mean this is the last
692 char first_char = *this_string.c_str();
693 if (first_char != 'm' && first_char != 'l') {
694 return PacketResult::ErrorReplyInvalid;
696 // Concatenate the result so far (skipping 'm' or 'l')
697 response_string.append(this_string, 1, std::string::npos);
698 if (first_char == 'l')
700 return PacketResult::Success;
704 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
705 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
708 // First try to retrieve the pid via the qProcessInfo request.
709 GetCurrentProcessInfo(allow_lazy);
710 if (m_curr_pid_is_valid == eLazyBoolYes) {
714 // If we don't get a response for qProcessInfo, check if $qC gives us a
715 // result. $qC only returns a real process id on older debugserver and
716 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
717 // the thread id, which newer debugserver and lldb-gdbserver stubs return
719 StringExtractorGDBRemote response;
720 if (SendPacketAndWaitForResponse("qC", response, false) ==
721 PacketResult::Success) {
722 if (response.GetChar() == 'Q') {
723 if (response.GetChar() == 'C') {
724 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
725 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
726 m_curr_pid_is_valid = eLazyBoolYes;
733 // If we don't get a response for $qC, check if $qfThreadID gives us a
735 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
736 std::vector<lldb::tid_t> thread_ids;
737 bool sequence_mutex_unavailable;
739 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
740 if (size && !sequence_mutex_unavailable) {
741 m_curr_pid = thread_ids.front();
742 m_curr_pid_is_valid = eLazyBoolYes;
748 return LLDB_INVALID_PROCESS_ID;
751 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
753 StringExtractorGDBRemote response;
754 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
755 PacketResult::Success) {
756 if (response.IsOKResponse())
758 if (response.GetChar() == 'E') {
759 // A string the describes what failed when launching...
760 error_str = response.GetStringRef().substr(1);
762 error_str.assign("unknown error occurred launching process");
765 error_str.assign("timed out waiting for app to launch");
770 int GDBRemoteCommunicationClient::SendArgumentsPacket(
771 const ProcessLaunchInfo &launch_info) {
772 // Since we don't get the send argv0 separate from the executable path, we
773 // need to make sure to use the actual executable path found in the
775 std::vector<const char *> argv;
776 FileSpec exe_file = launch_info.GetExecutableFile();
777 std::string exe_path;
778 const char *arg = nullptr;
779 const Args &launch_args = launch_info.GetArguments();
781 exe_path = exe_file.GetPath(false);
783 arg = launch_args.GetArgumentAtIndex(0);
787 if (!exe_path.empty()) {
788 argv.push_back(exe_path.c_str());
789 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != nullptr;
798 for (size_t i = 0, n = argv.size(); i < n; ++i) {
800 const int arg_len = strlen(arg);
803 packet.Printf("%i,%i,", arg_len * 2, (int)i);
804 packet.PutBytesAsRawHex8(arg, arg_len);
807 StringExtractorGDBRemote response;
808 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
809 PacketResult::Success) {
810 if (response.IsOKResponse())
812 uint8_t error = response.GetError();
820 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
821 for (const auto &KV : env) {
822 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
829 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
830 char const *name_equal_value) {
831 if (name_equal_value && name_equal_value[0]) {
833 bool send_hex_encoding = false;
834 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
842 send_hex_encoding = true;
848 // We have non printable characters, lets hex encode this...
849 send_hex_encoding = true;
853 StringExtractorGDBRemote response;
854 if (send_hex_encoding) {
855 if (m_supports_QEnvironmentHexEncoded) {
856 packet.PutCString("QEnvironmentHexEncoded:");
857 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
858 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
859 PacketResult::Success) {
860 if (response.IsOKResponse())
862 uint8_t error = response.GetError();
865 if (response.IsUnsupportedResponse())
866 m_supports_QEnvironmentHexEncoded = false;
870 } else if (m_supports_QEnvironment) {
871 packet.Printf("QEnvironment:%s", name_equal_value);
872 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
873 PacketResult::Success) {
874 if (response.IsOKResponse())
876 uint8_t error = response.GetError();
879 if (response.IsUnsupportedResponse())
880 m_supports_QEnvironment = false;
887 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
888 if (arch && arch[0]) {
890 packet.Printf("QLaunchArch:%s", arch);
891 StringExtractorGDBRemote response;
892 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
893 PacketResult::Success) {
894 if (response.IsOKResponse())
896 uint8_t error = response.GetError();
904 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
905 char const *data, bool *was_supported) {
906 if (data && *data != '\0') {
908 packet.Printf("QSetProcessEvent:%s", data);
909 StringExtractorGDBRemote response;
910 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
911 PacketResult::Success) {
912 if (response.IsOKResponse()) {
914 *was_supported = true;
916 } else if (response.IsUnsupportedResponse()) {
918 *was_supported = false;
921 uint8_t error = response.GetError();
923 *was_supported = true;
932 llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
937 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
939 if (!m_os_build.empty()) {
948 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
950 if (!m_os_kernel.empty()) {
959 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
961 if (!m_hostname.empty()) {
970 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
976 const lldb_private::ArchSpec &
977 GDBRemoteCommunicationClient::GetProcessArchitecture() {
978 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
979 GetCurrentProcessInfo();
980 return m_process_arch;
983 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
984 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
985 m_gdb_server_name.clear();
986 m_gdb_server_version = 0;
987 m_qGDBServerVersion_is_valid = eLazyBoolNo;
989 StringExtractorGDBRemote response;
990 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
991 PacketResult::Success) {
992 if (response.IsNormalResponse()) {
993 llvm::StringRef name, value;
994 bool success = false;
995 while (response.GetNameColonValue(name, value)) {
996 if (name.equals("name")) {
998 m_gdb_server_name = value;
999 } else if (name.equals("version")) {
1000 llvm::StringRef major, minor;
1001 std::tie(major, minor) = value.split('.');
1002 if (!major.getAsInteger(0, m_gdb_server_version))
1007 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1011 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1014 void GDBRemoteCommunicationClient::MaybeEnableCompression(
1015 std::vector<std::string> supported_compressions) {
1016 CompressionType avail_type = CompressionType::None;
1017 std::string avail_name;
1019 #if defined(HAVE_LIBCOMPRESSION)
1020 if (avail_type == CompressionType::None) {
1021 for (auto compression : supported_compressions) {
1022 if (compression == "lzfse") {
1023 avail_type = CompressionType::LZFSE;
1024 avail_name = compression;
1031 #if defined(HAVE_LIBCOMPRESSION)
1032 if (avail_type == CompressionType::None) {
1033 for (auto compression : supported_compressions) {
1034 if (compression == "zlib-deflate") {
1035 avail_type = CompressionType::ZlibDeflate;
1036 avail_name = compression;
1043 #if defined(HAVE_LIBZ)
1044 if (avail_type == CompressionType::None) {
1045 for (auto compression : supported_compressions) {
1046 if (compression == "zlib-deflate") {
1047 avail_type = CompressionType::ZlibDeflate;
1048 avail_name = compression;
1055 #if defined(HAVE_LIBCOMPRESSION)
1056 if (avail_type == CompressionType::None) {
1057 for (auto compression : supported_compressions) {
1058 if (compression == "lz4") {
1059 avail_type = CompressionType::LZ4;
1060 avail_name = compression;
1067 #if defined(HAVE_LIBCOMPRESSION)
1068 if (avail_type == CompressionType::None) {
1069 for (auto compression : supported_compressions) {
1070 if (compression == "lzma") {
1071 avail_type = CompressionType::LZMA;
1072 avail_name = compression;
1079 if (avail_type != CompressionType::None) {
1080 StringExtractorGDBRemote response;
1081 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1082 if (SendPacketAndWaitForResponse(packet, response, false) !=
1083 PacketResult::Success)
1086 if (response.IsOKResponse()) {
1087 m_compression_type = avail_type;
1092 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1093 if (GetGDBServerVersion()) {
1094 if (!m_gdb_server_name.empty())
1095 return m_gdb_server_name.c_str();
1100 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1101 if (GetGDBServerVersion())
1102 return m_gdb_server_version;
1106 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1107 StringExtractorGDBRemote response;
1108 if (SendPacketAndWaitForResponse("qC", response, false) !=
1109 PacketResult::Success)
1112 if (!response.IsNormalResponse())
1115 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1116 tid = response.GetHexMaxU32(true, -1);
1121 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1122 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1124 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1125 // host info computation can require DNS traffic and shelling out to external processes.
1126 // Increase the timeout to account for that.
1127 ScopedTimeout timeout(*this, seconds(10));
1128 m_qHostInfo_is_valid = eLazyBoolNo;
1129 StringExtractorGDBRemote response;
1130 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1131 PacketResult::Success) {
1132 if (response.IsNormalResponse()) {
1133 llvm::StringRef name;
1134 llvm::StringRef value;
1135 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1137 std::string arch_name;
1138 std::string os_name;
1139 std::string vendor_name;
1141 std::string distribution_id;
1142 uint32_t pointer_byte_size = 0;
1143 ByteOrder byte_order = eByteOrderInvalid;
1144 uint32_t num_keys_decoded = 0;
1145 while (response.GetNameColonValue(name, value)) {
1146 if (name.equals("cputype")) {
1147 // exception type in big endian hex
1148 if (!value.getAsInteger(0, cpu))
1150 } else if (name.equals("cpusubtype")) {
1151 // exception count in big endian hex
1152 if (!value.getAsInteger(0, sub))
1154 } else if (name.equals("arch")) {
1157 } else if (name.equals("triple")) {
1158 StringExtractor extractor(value);
1159 extractor.GetHexByteString(triple);
1161 } else if (name.equals("distribution_id")) {
1162 StringExtractor extractor(value);
1163 extractor.GetHexByteString(distribution_id);
1165 } else if (name.equals("os_build")) {
1166 StringExtractor extractor(value);
1167 extractor.GetHexByteString(m_os_build);
1169 } else if (name.equals("hostname")) {
1170 StringExtractor extractor(value);
1171 extractor.GetHexByteString(m_hostname);
1173 } else if (name.equals("os_kernel")) {
1174 StringExtractor extractor(value);
1175 extractor.GetHexByteString(m_os_kernel);
1177 } else if (name.equals("ostype")) {
1180 } else if (name.equals("vendor")) {
1181 vendor_name = value;
1183 } else if (name.equals("endian")) {
1184 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1185 .Case("little", eByteOrderLittle)
1186 .Case("big", eByteOrderBig)
1187 .Case("pdp", eByteOrderPDP)
1188 .Default(eByteOrderInvalid);
1189 if (byte_order != eByteOrderInvalid)
1191 } else if (name.equals("ptrsize")) {
1192 if (!value.getAsInteger(0, pointer_byte_size))
1194 } else if (name.equals("os_version") ||
1196 "version")) // Older debugserver binaries used the
1197 // "version" key instead of
1200 if (!m_os_version.tryParse(value))
1202 } else if (name.equals("watchpoint_exceptions_received")) {
1203 m_watchpoints_trigger_after_instruction =
1204 llvm::StringSwitch<LazyBool>(value)
1205 .Case("before", eLazyBoolNo)
1206 .Case("after", eLazyBoolYes)
1207 .Default(eLazyBoolCalculate);
1208 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1210 } else if (name.equals("default_packet_timeout")) {
1211 uint32_t timeout_seconds;
1212 if (!value.getAsInteger(0, timeout_seconds)) {
1213 m_default_packet_timeout = seconds(timeout_seconds);
1214 SetPacketTimeout(m_default_packet_timeout);
1220 if (num_keys_decoded > 0)
1221 m_qHostInfo_is_valid = eLazyBoolYes;
1223 if (triple.empty()) {
1224 if (arch_name.empty()) {
1225 if (cpu != LLDB_INVALID_CPUTYPE) {
1226 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1227 if (pointer_byte_size) {
1228 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1230 if (byte_order != eByteOrderInvalid) {
1231 assert(byte_order == m_host_arch.GetByteOrder());
1234 if (!vendor_name.empty())
1235 m_host_arch.GetTriple().setVendorName(
1236 llvm::StringRef(vendor_name));
1237 if (!os_name.empty())
1238 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1242 triple += arch_name;
1243 if (!vendor_name.empty() || !os_name.empty()) {
1245 if (vendor_name.empty())
1246 triple += "unknown";
1248 triple += vendor_name;
1250 if (os_name.empty())
1251 triple += "unknown";
1255 m_host_arch.SetTriple(triple.c_str());
1257 llvm::Triple &host_triple = m_host_arch.GetTriple();
1258 if (host_triple.getVendor() == llvm::Triple::Apple &&
1259 host_triple.getOS() == llvm::Triple::Darwin) {
1260 switch (m_host_arch.GetMachine()) {
1261 case llvm::Triple::aarch64:
1262 case llvm::Triple::arm:
1263 case llvm::Triple::thumb:
1264 host_triple.setOS(llvm::Triple::IOS);
1267 host_triple.setOS(llvm::Triple::MacOSX);
1271 if (pointer_byte_size) {
1272 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1274 if (byte_order != eByteOrderInvalid) {
1275 assert(byte_order == m_host_arch.GetByteOrder());
1279 m_host_arch.SetTriple(triple.c_str());
1280 if (pointer_byte_size) {
1281 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1283 if (byte_order != eByteOrderInvalid) {
1284 assert(byte_order == m_host_arch.GetByteOrder());
1288 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1289 "architecture as %s, triple as %s from triple text %s",
1290 __FUNCTION__, m_host_arch.GetArchitectureName()
1291 ? m_host_arch.GetArchitectureName()
1292 : "<null-arch-name>",
1293 m_host_arch.GetTriple().getTriple().c_str(),
1296 if (!distribution_id.empty())
1297 m_host_arch.SetDistributionId(distribution_id.c_str());
1301 return m_qHostInfo_is_valid == eLazyBoolYes;
1304 int GDBRemoteCommunicationClient::SendAttach(
1305 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1306 if (pid != LLDB_INVALID_PROCESS_ID) {
1308 const int packet_len =
1309 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1310 UNUSED_IF_ASSERT_DISABLED(packet_len);
1311 assert(packet_len < (int)sizeof(packet));
1312 if (SendPacketAndWaitForResponse(packet, response, false) ==
1313 PacketResult::Success) {
1314 if (response.IsErrorResponse())
1315 return response.GetError();
1322 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1324 StreamString packet;
1325 packet.PutCString("I");
1326 packet.PutBytesAsRawHex8(data, data_len);
1327 StringExtractorGDBRemote response;
1328 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1329 PacketResult::Success) {
1332 return response.GetError();
1335 const lldb_private::ArchSpec &
1336 GDBRemoteCommunicationClient::GetHostArchitecture() {
1337 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1342 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1343 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1345 return m_default_packet_timeout;
1348 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1349 uint32_t permissions) {
1350 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1351 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1353 const int packet_len = ::snprintf(
1354 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1355 permissions & lldb::ePermissionsReadable ? "r" : "",
1356 permissions & lldb::ePermissionsWritable ? "w" : "",
1357 permissions & lldb::ePermissionsExecutable ? "x" : "");
1358 assert(packet_len < (int)sizeof(packet));
1359 UNUSED_IF_ASSERT_DISABLED(packet_len);
1360 StringExtractorGDBRemote response;
1361 if (SendPacketAndWaitForResponse(packet, response, false) ==
1362 PacketResult::Success) {
1363 if (response.IsUnsupportedResponse())
1364 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1365 else if (!response.IsErrorResponse())
1366 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1368 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1371 return LLDB_INVALID_ADDRESS;
1374 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1375 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1376 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1378 const int packet_len =
1379 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1380 assert(packet_len < (int)sizeof(packet));
1381 UNUSED_IF_ASSERT_DISABLED(packet_len);
1382 StringExtractorGDBRemote response;
1383 if (SendPacketAndWaitForResponse(packet, response, false) ==
1384 PacketResult::Success) {
1385 if (response.IsUnsupportedResponse())
1386 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1387 else if (response.IsOKResponse())
1390 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1396 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1400 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1402 const int packet_len =
1403 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1404 assert(packet_len < (int)sizeof(packet));
1405 UNUSED_IF_ASSERT_DISABLED(packet_len);
1406 StringExtractorGDBRemote response;
1407 if (SendPacketAndWaitForResponse(packet, response, false) ==
1408 PacketResult::Success &&
1409 response.IsOKResponse()) {
1410 m_supports_detach_stay_stopped = eLazyBoolYes;
1412 m_supports_detach_stay_stopped = eLazyBoolNo;
1416 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1417 error.SetErrorString("Stays stopped not supported by this target.");
1420 StringExtractorGDBRemote response;
1421 PacketResult packet_result =
1422 SendPacketAndWaitForResponse("D1", response, false);
1423 if (packet_result != PacketResult::Success)
1424 error.SetErrorString("Sending extended disconnect packet failed.");
1427 StringExtractorGDBRemote response;
1428 PacketResult packet_result =
1429 SendPacketAndWaitForResponse("D", response, false);
1430 if (packet_result != PacketResult::Success)
1431 error.SetErrorString("Sending disconnect packet failed.");
1436 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1437 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1439 region_info.Clear();
1441 if (m_supports_memory_region_info != eLazyBoolNo) {
1442 m_supports_memory_region_info = eLazyBoolYes;
1444 const int packet_len = ::snprintf(
1445 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1446 assert(packet_len < (int)sizeof(packet));
1447 UNUSED_IF_ASSERT_DISABLED(packet_len);
1448 StringExtractorGDBRemote response;
1449 if (SendPacketAndWaitForResponse(packet, response, false) ==
1450 PacketResult::Success &&
1451 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
1452 llvm::StringRef name;
1453 llvm::StringRef value;
1454 addr_t addr_value = LLDB_INVALID_ADDRESS;
1455 bool success = true;
1456 bool saw_permissions = false;
1457 while (success && response.GetNameColonValue(name, value)) {
1458 if (name.equals("start")) {
1459 if (!value.getAsInteger(16, addr_value))
1460 region_info.GetRange().SetRangeBase(addr_value);
1461 } else if (name.equals("size")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetByteSize(addr_value);
1464 } else if (name.equals("permissions") &&
1465 region_info.GetRange().IsValid()) {
1466 saw_permissions = true;
1467 if (region_info.GetRange().Contains(addr)) {
1468 if (value.find('r') != llvm::StringRef::npos)
1469 region_info.SetReadable(MemoryRegionInfo::eYes);
1471 region_info.SetReadable(MemoryRegionInfo::eNo);
1473 if (value.find('w') != llvm::StringRef::npos)
1474 region_info.SetWritable(MemoryRegionInfo::eYes);
1476 region_info.SetWritable(MemoryRegionInfo::eNo);
1478 if (value.find('x') != llvm::StringRef::npos)
1479 region_info.SetExecutable(MemoryRegionInfo::eYes);
1481 region_info.SetExecutable(MemoryRegionInfo::eNo);
1483 region_info.SetMapped(MemoryRegionInfo::eYes);
1485 // The reported region does not contain this address -- we're
1486 // looking at an unmapped page
1487 region_info.SetReadable(MemoryRegionInfo::eNo);
1488 region_info.SetWritable(MemoryRegionInfo::eNo);
1489 region_info.SetExecutable(MemoryRegionInfo::eNo);
1490 region_info.SetMapped(MemoryRegionInfo::eNo);
1492 } else if (name.equals("name")) {
1493 StringExtractorGDBRemote name_extractor(value);
1495 name_extractor.GetHexByteString(name);
1496 region_info.SetName(name.c_str());
1497 } else if (name.equals("error")) {
1498 StringExtractorGDBRemote error_extractor(value);
1499 std::string error_string;
1500 // Now convert the HEX bytes into a string value
1501 error_extractor.GetHexByteString(error_string);
1502 error.SetErrorString(error_string.c_str());
1506 if (region_info.GetRange().IsValid()) {
1507 // We got a valid address range back but no permissions -- which means
1508 // this is an unmapped page
1509 if (!saw_permissions) {
1510 region_info.SetReadable(MemoryRegionInfo::eNo);
1511 region_info.SetWritable(MemoryRegionInfo::eNo);
1512 region_info.SetExecutable(MemoryRegionInfo::eNo);
1513 region_info.SetMapped(MemoryRegionInfo::eNo);
1516 // We got an invalid address range back
1517 error.SetErrorString("Server returned invalid range");
1520 m_supports_memory_region_info = eLazyBoolNo;
1524 if (m_supports_memory_region_info == eLazyBoolNo) {
1525 error.SetErrorString("qMemoryRegionInfo is not supported");
1528 // Try qXfer:memory-map:read to get region information not included in
1529 // qMemoryRegionInfo
1530 MemoryRegionInfo qXfer_region_info;
1531 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1534 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1535 // the qXfer result as a fallback
1536 if (qXfer_error.Success()) {
1537 region_info = qXfer_region_info;
1540 region_info.Clear();
1542 } else if (qXfer_error.Success()) {
1543 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1544 // both regions are the same range, update the result to include the flash-
1545 // memory information that is specific to the qXfer result.
1546 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1547 region_info.SetFlash(qXfer_region_info.GetFlash());
1548 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1554 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1555 lldb::addr_t addr, MemoryRegionInfo ®ion) {
1556 Status error = LoadQXferMemoryMap();
1557 if (!error.Success())
1559 for (const auto &map_region : m_qXfer_memory_map) {
1560 if (map_region.GetRange().Contains(addr)) {
1561 region = map_region;
1565 error.SetErrorString("Region not found");
1569 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1573 if (m_qXfer_memory_map_loaded)
1574 // Already loaded, return success
1577 if (!XMLDocument::XMLEnabled()) {
1578 error.SetErrorString("XML is not supported");
1582 if (!GetQXferMemoryMapReadSupported()) {
1583 error.SetErrorString("Memory map is not supported");
1588 lldb_private::Status lldberr;
1589 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1591 error.SetErrorString("Failed to read memory map");
1595 XMLDocument xml_document;
1597 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1598 error.SetErrorString("Failed to parse memory map xml");
1602 XMLNode map_node = xml_document.GetRootElement("memory-map");
1604 error.SetErrorString("Invalid root node in memory map xml");
1608 m_qXfer_memory_map.clear();
1610 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1611 if (!memory_node.IsElement())
1613 if (memory_node.GetName() != "memory")
1615 auto type = memory_node.GetAttributeValue("type", "");
1618 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1620 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1622 MemoryRegionInfo region;
1623 region.GetRange().SetRangeBase(start);
1624 region.GetRange().SetByteSize(length);
1625 if (type == "rom") {
1626 region.SetReadable(MemoryRegionInfo::eYes);
1627 this->m_qXfer_memory_map.push_back(region);
1628 } else if (type == "ram") {
1629 region.SetReadable(MemoryRegionInfo::eYes);
1630 region.SetWritable(MemoryRegionInfo::eYes);
1631 this->m_qXfer_memory_map.push_back(region);
1632 } else if (type == "flash") {
1633 region.SetFlash(MemoryRegionInfo::eYes);
1634 memory_node.ForEachChildElement(
1635 [®ion](const XMLNode &prop_node) -> bool {
1636 if (!prop_node.IsElement())
1638 if (prop_node.GetName() != "property")
1640 auto propname = prop_node.GetAttributeValue("name", "");
1641 if (propname == "blocksize") {
1643 if (prop_node.GetElementTextAsUnsigned(blocksize))
1644 region.SetBlocksize(blocksize);
1648 this->m_qXfer_memory_map.push_back(region);
1653 m_qXfer_memory_map_loaded = true;
1658 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1661 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1662 num = m_num_supported_hardware_watchpoints;
1666 // Set num to 0 first.
1668 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1670 const int packet_len =
1671 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1672 assert(packet_len < (int)sizeof(packet));
1673 UNUSED_IF_ASSERT_DISABLED(packet_len);
1674 StringExtractorGDBRemote response;
1675 if (SendPacketAndWaitForResponse(packet, response, false) ==
1676 PacketResult::Success) {
1677 m_supports_watchpoint_support_info = eLazyBoolYes;
1678 llvm::StringRef name;
1679 llvm::StringRef value;
1680 bool found_num_field = false;
1681 while (response.GetNameColonValue(name, value)) {
1682 if (name.equals("num")) {
1683 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1684 num = m_num_supported_hardware_watchpoints;
1685 found_num_field = true;
1688 if (!found_num_field) {
1689 m_supports_watchpoint_support_info = eLazyBoolNo;
1692 m_supports_watchpoint_support_info = eLazyBoolNo;
1696 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1697 error.SetErrorString("qWatchpointSupportInfo is not supported");
1702 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1703 uint32_t &num, bool &after, const ArchSpec &arch) {
1704 Status error(GetWatchpointSupportInfo(num));
1705 if (error.Success())
1706 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1710 lldb_private::Status
1711 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1712 bool &after, const ArchSpec &arch) {
1714 llvm::Triple triple = arch.GetTriple();
1716 // we assume watchpoints will happen after running the relevant opcode and we
1717 // only want to override this behavior if we have explicitly received a
1718 // qHostInfo telling us otherwise
1719 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1720 // On targets like MIPS and ppc64, watchpoint exceptions are always
1721 // generated before the instruction is executed. The connected target may
1722 // not support qHostInfo or qWatchpointSupportInfo packets.
1723 after = !(triple.isMIPS() || triple.isPPC64());
1725 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
1726 // eLazyBoolNo if it is not calculated before.
1727 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1728 (triple.isMIPS() || triple.isPPC64()))
1729 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1731 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1736 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1738 std::string path{file_spec.GetPath(false)};
1739 StreamString packet;
1740 packet.PutCString("QSetSTDIN:");
1741 packet.PutStringAsRawHex8(path);
1743 StringExtractorGDBRemote response;
1744 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1745 PacketResult::Success) {
1746 if (response.IsOKResponse())
1748 uint8_t error = response.GetError();
1756 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1758 std::string path{file_spec.GetPath(false)};
1759 StreamString packet;
1760 packet.PutCString("QSetSTDOUT:");
1761 packet.PutStringAsRawHex8(path);
1763 StringExtractorGDBRemote response;
1764 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1765 PacketResult::Success) {
1766 if (response.IsOKResponse())
1768 uint8_t error = response.GetError();
1776 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1778 std::string path{file_spec.GetPath(false)};
1779 StreamString packet;
1780 packet.PutCString("QSetSTDERR:");
1781 packet.PutStringAsRawHex8(path);
1783 StringExtractorGDBRemote response;
1784 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1785 PacketResult::Success) {
1786 if (response.IsOKResponse())
1788 uint8_t error = response.GetError();
1796 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1797 StringExtractorGDBRemote response;
1798 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1799 PacketResult::Success) {
1800 if (response.IsUnsupportedResponse())
1802 if (response.IsErrorResponse())
1805 response.GetHexByteString(cwd);
1806 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1807 return !cwd.empty();
1812 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1814 std::string path{working_dir.GetPath(false)};
1815 StreamString packet;
1816 packet.PutCString("QSetWorkingDir:");
1817 packet.PutStringAsRawHex8(path);
1819 StringExtractorGDBRemote response;
1820 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1821 PacketResult::Success) {
1822 if (response.IsOKResponse())
1824 uint8_t error = response.GetError();
1832 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1834 const int packet_len =
1835 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1836 assert(packet_len < (int)sizeof(packet));
1837 UNUSED_IF_ASSERT_DISABLED(packet_len);
1838 StringExtractorGDBRemote response;
1839 if (SendPacketAndWaitForResponse(packet, response, false) ==
1840 PacketResult::Success) {
1841 if (response.IsOKResponse())
1843 uint8_t error = response.GetError();
1850 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1852 const int packet_len = ::snprintf(packet, sizeof(packet),
1853 "QSetDetachOnError:%i", enable ? 1 : 0);
1854 assert(packet_len < (int)sizeof(packet));
1855 UNUSED_IF_ASSERT_DISABLED(packet_len);
1856 StringExtractorGDBRemote response;
1857 if (SendPacketAndWaitForResponse(packet, response, false) ==
1858 PacketResult::Success) {
1859 if (response.IsOKResponse())
1861 uint8_t error = response.GetError();
1868 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1869 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1870 if (response.IsNormalResponse()) {
1871 llvm::StringRef name;
1872 llvm::StringRef value;
1873 StringExtractor extractor;
1875 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1878 std::string os_type;
1880 while (response.GetNameColonValue(name, value)) {
1881 if (name.equals("pid")) {
1882 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1883 value.getAsInteger(0, pid);
1884 process_info.SetProcessID(pid);
1885 } else if (name.equals("ppid")) {
1886 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1887 value.getAsInteger(0, pid);
1888 process_info.SetParentProcessID(pid);
1889 } else if (name.equals("uid")) {
1890 uint32_t uid = UINT32_MAX;
1891 value.getAsInteger(0, uid);
1892 process_info.SetUserID(uid);
1893 } else if (name.equals("euid")) {
1894 uint32_t uid = UINT32_MAX;
1895 value.getAsInteger(0, uid);
1896 process_info.SetEffectiveGroupID(uid);
1897 } else if (name.equals("gid")) {
1898 uint32_t gid = UINT32_MAX;
1899 value.getAsInteger(0, gid);
1900 process_info.SetGroupID(gid);
1901 } else if (name.equals("egid")) {
1902 uint32_t gid = UINT32_MAX;
1903 value.getAsInteger(0, gid);
1904 process_info.SetEffectiveGroupID(gid);
1905 } else if (name.equals("triple")) {
1906 StringExtractor extractor(value);
1908 extractor.GetHexByteString(triple);
1909 process_info.GetArchitecture().SetTriple(triple.c_str());
1910 } else if (name.equals("name")) {
1911 StringExtractor extractor(value);
1912 // The process name from ASCII hex bytes since we can't control the
1913 // characters in a process name
1915 extractor.GetHexByteString(name);
1916 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
1917 } else if (name.equals("cputype")) {
1918 value.getAsInteger(0, cpu);
1919 } else if (name.equals("cpusubtype")) {
1920 value.getAsInteger(0, sub);
1921 } else if (name.equals("vendor")) {
1923 } else if (name.equals("ostype")) {
1928 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1929 if (vendor == "apple") {
1930 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1932 process_info.GetArchitecture().GetTriple().setVendorName(
1933 llvm::StringRef(vendor));
1934 process_info.GetArchitecture().GetTriple().setOSName(
1935 llvm::StringRef(os_type));
1939 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1945 bool GDBRemoteCommunicationClient::GetProcessInfo(
1946 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1947 process_info.Clear();
1949 if (m_supports_qProcessInfoPID) {
1951 const int packet_len =
1952 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1953 assert(packet_len < (int)sizeof(packet));
1954 UNUSED_IF_ASSERT_DISABLED(packet_len);
1955 StringExtractorGDBRemote response;
1956 if (SendPacketAndWaitForResponse(packet, response, false) ==
1957 PacketResult::Success) {
1958 return DecodeProcessInfoResponse(response, process_info);
1960 m_supports_qProcessInfoPID = false;
1967 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1968 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1972 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1974 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1980 StringExtractorGDBRemote response;
1981 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1982 PacketResult::Success) {
1983 if (response.IsNormalResponse()) {
1984 llvm::StringRef name;
1985 llvm::StringRef value;
1986 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1988 std::string arch_name;
1989 std::string os_name;
1990 std::string vendor_name;
1992 std::string elf_abi;
1993 uint32_t pointer_byte_size = 0;
1994 StringExtractor extractor;
1995 ByteOrder byte_order = eByteOrderInvalid;
1996 uint32_t num_keys_decoded = 0;
1997 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1998 while (response.GetNameColonValue(name, value)) {
1999 if (name.equals("cputype")) {
2000 if (!value.getAsInteger(16, cpu))
2002 } else if (name.equals("cpusubtype")) {
2003 if (!value.getAsInteger(16, sub))
2005 } else if (name.equals("triple")) {
2006 StringExtractor extractor(value);
2007 extractor.GetHexByteString(triple);
2009 } else if (name.equals("ostype")) {
2012 } else if (name.equals("vendor")) {
2013 vendor_name = value;
2015 } else if (name.equals("endian")) {
2016 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2017 .Case("little", eByteOrderLittle)
2018 .Case("big", eByteOrderBig)
2019 .Case("pdp", eByteOrderPDP)
2020 .Default(eByteOrderInvalid);
2021 if (byte_order != eByteOrderInvalid)
2023 } else if (name.equals("ptrsize")) {
2024 if (!value.getAsInteger(16, pointer_byte_size))
2026 } else if (name.equals("pid")) {
2027 if (!value.getAsInteger(16, pid))
2029 } else if (name.equals("elf_abi")) {
2034 if (num_keys_decoded > 0)
2035 m_qProcessInfo_is_valid = eLazyBoolYes;
2036 if (pid != LLDB_INVALID_PROCESS_ID) {
2037 m_curr_pid_is_valid = eLazyBoolYes;
2041 // Set the ArchSpec from the triple if we have it.
2042 if (!triple.empty()) {
2043 m_process_arch.SetTriple(triple.c_str());
2044 m_process_arch.SetFlags(elf_abi);
2045 if (pointer_byte_size) {
2046 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2048 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2049 !vendor_name.empty()) {
2050 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2052 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2053 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2054 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2055 switch (triple.getObjectFormat()) {
2056 case llvm::Triple::MachO:
2057 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2059 case llvm::Triple::ELF:
2060 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2062 case llvm::Triple::COFF:
2063 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2065 case llvm::Triple::Wasm:
2066 case llvm::Triple::XCOFF:
2068 log->Printf("error: not supported target architecture");
2070 case llvm::Triple::UnknownObjectFormat:
2072 log->Printf("error: failed to determine target architecture");
2076 if (pointer_byte_size) {
2077 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2079 if (byte_order != eByteOrderInvalid) {
2080 assert(byte_order == m_process_arch.GetByteOrder());
2082 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2083 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2084 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2085 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2090 m_qProcessInfo_is_valid = eLazyBoolNo;
2096 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2097 const ProcessInstanceInfoMatch &match_info,
2098 ProcessInstanceInfoList &process_infos) {
2099 process_infos.Clear();
2101 if (m_supports_qfProcessInfo) {
2102 StreamString packet;
2103 packet.PutCString("qfProcessInfo");
2104 if (!match_info.MatchAllProcesses()) {
2105 packet.PutChar(':');
2106 const char *name = match_info.GetProcessInfo().GetName();
2107 bool has_name_match = false;
2108 if (name && name[0]) {
2109 has_name_match = true;
2110 NameMatch name_match_type = match_info.GetNameMatchType();
2111 switch (name_match_type) {
2112 case NameMatch::Ignore:
2113 has_name_match = false;
2116 case NameMatch::Equals:
2117 packet.PutCString("name_match:equals;");
2120 case NameMatch::Contains:
2121 packet.PutCString("name_match:contains;");
2124 case NameMatch::StartsWith:
2125 packet.PutCString("name_match:starts_with;");
2128 case NameMatch::EndsWith:
2129 packet.PutCString("name_match:ends_with;");
2132 case NameMatch::RegularExpression:
2133 packet.PutCString("name_match:regex;");
2136 if (has_name_match) {
2137 packet.PutCString("name:");
2138 packet.PutBytesAsRawHex8(name, ::strlen(name));
2139 packet.PutChar(';');
2143 if (match_info.GetProcessInfo().ProcessIDIsValid())
2144 packet.Printf("pid:%" PRIu64 ";",
2145 match_info.GetProcessInfo().GetProcessID());
2146 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2147 packet.Printf("parent_pid:%" PRIu64 ";",
2148 match_info.GetProcessInfo().GetParentProcessID());
2149 if (match_info.GetProcessInfo().UserIDIsValid())
2150 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2151 if (match_info.GetProcessInfo().GroupIDIsValid())
2152 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2153 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2154 packet.Printf("euid:%u;",
2155 match_info.GetProcessInfo().GetEffectiveUserID());
2156 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2157 packet.Printf("egid:%u;",
2158 match_info.GetProcessInfo().GetEffectiveGroupID());
2159 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2160 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2161 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2162 const ArchSpec &match_arch =
2163 match_info.GetProcessInfo().GetArchitecture();
2164 const llvm::Triple &triple = match_arch.GetTriple();
2165 packet.PutCString("triple:");
2166 packet.PutCString(triple.getTriple());
2167 packet.PutChar(';');
2170 StringExtractorGDBRemote response;
2171 // Increase timeout as the first qfProcessInfo packet takes a long time on
2172 // Android. The value of 1min was arrived at empirically.
2173 ScopedTimeout timeout(*this, minutes(1));
2174 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2175 PacketResult::Success) {
2177 ProcessInstanceInfo process_info;
2178 if (!DecodeProcessInfoResponse(response, process_info))
2180 process_infos.Append(process_info);
2181 response.GetStringRef().clear();
2182 response.SetFilePos(0);
2183 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2184 PacketResult::Success);
2186 m_supports_qfProcessInfo = false;
2190 return process_infos.GetSize();
2193 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2194 std::string &name) {
2195 if (m_supports_qUserName) {
2197 const int packet_len =
2198 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2199 assert(packet_len < (int)sizeof(packet));
2200 UNUSED_IF_ASSERT_DISABLED(packet_len);
2201 StringExtractorGDBRemote response;
2202 if (SendPacketAndWaitForResponse(packet, response, false) ==
2203 PacketResult::Success) {
2204 if (response.IsNormalResponse()) {
2205 // Make sure we parsed the right number of characters. The response is
2206 // the hex encoded user name and should make up the entire packet. If
2207 // there are any non-hex ASCII bytes, the length won't match below..
2208 if (response.GetHexByteString(name) * 2 ==
2209 response.GetStringRef().size())
2213 m_supports_qUserName = false;
2220 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2221 std::string &name) {
2222 if (m_supports_qGroupName) {
2224 const int packet_len =
2225 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2226 assert(packet_len < (int)sizeof(packet));
2227 UNUSED_IF_ASSERT_DISABLED(packet_len);
2228 StringExtractorGDBRemote response;
2229 if (SendPacketAndWaitForResponse(packet, response, false) ==
2230 PacketResult::Success) {
2231 if (response.IsNormalResponse()) {
2232 // Make sure we parsed the right number of characters. The response is
2233 // the hex encoded group name and should make up the entire packet. If
2234 // there are any non-hex ASCII bytes, the length won't match below..
2235 if (response.GetHexByteString(name) * 2 ==
2236 response.GetStringRef().size())
2240 m_supports_qGroupName = false;
2247 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2248 // Form non-stop packet request
2250 const int packet_len =
2251 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2252 assert(packet_len < (int)sizeof(packet));
2253 UNUSED_IF_ASSERT_DISABLED(packet_len);
2255 StringExtractorGDBRemote response;
2257 if (SendPacketAndWaitForResponse(packet, response, false) ==
2258 PacketResult::Success)
2259 if (response.IsOKResponse())
2262 // Failed or not supported
2266 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2267 uint32_t recv_size) {
2269 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2270 uint32_t bytes_left = send_size;
2271 while (bytes_left > 0) {
2272 if (bytes_left >= 26) {
2273 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2276 packet.Printf("%*.*s;", bytes_left, bytes_left,
2277 "abcdefghijklmnopqrstuvwxyz");
2284 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2285 using Dur = duration<float>;
2286 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2287 Dur mean = sum / v.size();
2290 float delta = (d - mean).count();
2291 accum += delta * delta;
2294 return Dur(sqrtf(accum / (v.size() - 1)));
2297 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2300 uint64_t recv_amount,
2301 bool json, Stream &strm) {
2303 if (SendSpeedTestPacket(0, 0)) {
2304 StreamString packet;
2306 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2310 strm.Printf("Testing sending %u packets of various sizes:\n",
2314 uint32_t result_idx = 0;
2316 std::vector<duration<float>> packet_times;
2318 for (send_size = 0; send_size <= max_send;
2319 send_size ? send_size *= 2 : send_size = 4) {
2320 for (uint32_t recv_size = 0; recv_size <= max_recv;
2321 recv_size ? recv_size *= 2 : recv_size = 4) {
2322 MakeSpeedTestPacket(packet, send_size, recv_size);
2324 packet_times.clear();
2325 // Test how long it takes to send 'num_packets' packets
2326 const auto start_time = steady_clock::now();
2327 for (i = 0; i < num_packets; ++i) {
2328 const auto packet_start_time = steady_clock::now();
2329 StringExtractorGDBRemote response;
2330 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2331 const auto packet_end_time = steady_clock::now();
2332 packet_times.push_back(packet_end_time - packet_start_time);
2334 const auto end_time = steady_clock::now();
2335 const auto total_time = end_time - start_time;
2337 float packets_per_second =
2338 ((float)num_packets) / duration<float>(total_time).count();
2339 auto average_per_packet = total_time / num_packets;
2340 const duration<float> standard_deviation =
2341 calculate_standard_deviation(packet_times);
2343 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2344 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2345 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2346 result_idx > 0 ? "," : "", send_size, recv_size,
2347 total_time, standard_deviation);
2350 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2351 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2352 "standard deviation of {5,10:ms+f6}\n",
2353 send_size, recv_size, duration<float>(total_time),
2354 packets_per_second, duration<float>(average_per_packet),
2355 standard_deviation);
2361 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2363 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2364 ": %" PRIu64 ",\n \"results\" : [",
2367 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2373 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2374 MakeSpeedTestPacket(packet, send_size, recv_size);
2376 // If we have a receive size, test how long it takes to receive 4MB of
2378 if (recv_size > 0) {
2379 const auto start_time = steady_clock::now();
2380 uint32_t bytes_read = 0;
2381 uint32_t packet_count = 0;
2382 while (bytes_read < recv_amount) {
2383 StringExtractorGDBRemote response;
2384 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2385 bytes_read += recv_size;
2388 const auto end_time = steady_clock::now();
2389 const auto total_time = end_time - start_time;
2390 float mb_second = ((float)recv_amount) /
2391 duration<float>(total_time).count() /
2393 float packets_per_second =
2394 ((float)packet_count) / duration<float>(total_time).count();
2395 const auto average_per_packet = total_time / packet_count;
2398 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2399 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2400 result_idx > 0 ? "," : "", send_size, recv_size,
2404 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2405 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2406 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2407 send_size, recv_size, packet_count, k_recv_amount_mb,
2408 duration<float>(total_time), mb_second,
2409 packets_per_second, duration<float>(average_per_packet));
2415 strm.Printf("\n ]\n }\n}\n");
2421 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2422 uint32_t recv_size) {
2423 StreamString packet;
2424 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2425 uint32_t bytes_left = send_size;
2426 while (bytes_left > 0) {
2427 if (bytes_left >= 26) {
2428 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2431 packet.Printf("%*.*s;", bytes_left, bytes_left,
2432 "abcdefghijklmnopqrstuvwxyz");
2437 StringExtractorGDBRemote response;
2438 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2439 PacketResult::Success;
2442 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2443 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2444 std::string &socket_name) {
2445 pid = LLDB_INVALID_PROCESS_ID;
2447 socket_name.clear();
2449 StringExtractorGDBRemote response;
2450 StreamString stream;
2451 stream.PutCString("qLaunchGDBServer;");
2452 std::string hostname;
2453 if (remote_accept_hostname && remote_accept_hostname[0])
2454 hostname = remote_accept_hostname;
2456 if (HostInfo::GetHostname(hostname)) {
2457 // Make the GDB server we launch only accept connections from this host
2458 stream.Printf("host:%s;", hostname.c_str());
2460 // Make the GDB server we launch accept connections from any host since
2461 // we can't figure out the hostname
2462 stream.Printf("host:*;");
2465 // give the process a few seconds to startup
2466 ScopedTimeout timeout(*this, seconds(10));
2468 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2469 PacketResult::Success) {
2470 llvm::StringRef name;
2471 llvm::StringRef value;
2472 while (response.GetNameColonValue(name, value)) {
2473 if (name.equals("port"))
2474 value.getAsInteger(0, port);
2475 else if (name.equals("pid"))
2476 value.getAsInteger(0, pid);
2477 else if (name.compare("socket_name") == 0) {
2478 StringExtractor extractor(value);
2479 extractor.GetHexByteString(socket_name);
2487 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2488 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2489 connection_urls.clear();
2491 StringExtractorGDBRemote response;
2492 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2493 PacketResult::Success)
2496 StructuredData::ObjectSP data =
2497 StructuredData::ParseJSON(response.GetStringRef());
2501 StructuredData::Array *array = data->GetAsArray();
2505 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2506 StructuredData::Dictionary *element = nullptr;
2507 if (!array->GetItemAtIndexAsDictionary(i, element))
2511 if (StructuredData::ObjectSP port_osp =
2512 element->GetValueForKey(llvm::StringRef("port")))
2513 port = port_osp->GetIntegerValue(0);
2515 std::string socket_name;
2516 if (StructuredData::ObjectSP socket_name_osp =
2517 element->GetValueForKey(llvm::StringRef("socket_name")))
2518 socket_name = socket_name_osp->GetStringValue();
2520 if (port != 0 || !socket_name.empty())
2521 connection_urls.emplace_back(port, socket_name);
2523 return connection_urls.size();
2526 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2527 StreamString stream;
2528 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2530 StringExtractorGDBRemote response;
2531 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2532 PacketResult::Success) {
2533 if (response.IsOKResponse())
2539 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2540 if (m_curr_tid == tid)
2545 if (tid == UINT64_MAX)
2546 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2548 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2549 assert(packet_len + 1 < (int)sizeof(packet));
2550 UNUSED_IF_ASSERT_DISABLED(packet_len);
2551 StringExtractorGDBRemote response;
2552 if (SendPacketAndWaitForResponse(packet, response, false) ==
2553 PacketResult::Success) {
2554 if (response.IsOKResponse()) {
2560 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2562 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2564 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2566 if (response.IsUnsupportedResponse() && IsConnected()) {
2574 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2575 if (m_curr_tid_run == tid)
2580 if (tid == UINT64_MAX)
2581 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2583 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2585 assert(packet_len + 1 < (int)sizeof(packet));
2586 UNUSED_IF_ASSERT_DISABLED(packet_len);
2587 StringExtractorGDBRemote response;
2588 if (SendPacketAndWaitForResponse(packet, response, false) ==
2589 PacketResult::Success) {
2590 if (response.IsOKResponse()) {
2591 m_curr_tid_run = tid;
2596 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2598 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2600 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2602 if (response.IsUnsupportedResponse() && IsConnected()) {
2610 bool GDBRemoteCommunicationClient::GetStopReply(
2611 StringExtractorGDBRemote &response) {
2612 if (SendPacketAndWaitForResponse("?", response, false) ==
2613 PacketResult::Success)
2614 return response.IsNormalResponse();
2618 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2619 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2620 if (m_supports_qThreadStopInfo) {
2623 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2624 assert(packet_len < (int)sizeof(packet));
2625 UNUSED_IF_ASSERT_DISABLED(packet_len);
2626 if (SendPacketAndWaitForResponse(packet, response, false) ==
2627 PacketResult::Success) {
2628 if (response.IsUnsupportedResponse())
2629 m_supports_qThreadStopInfo = false;
2630 else if (response.IsNormalResponse())
2635 m_supports_qThreadStopInfo = false;
2641 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2642 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2643 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2645 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2646 __FUNCTION__, insert ? "add" : "remove", addr);
2648 // Check if the stub is known not to support this breakpoint type
2649 if (!SupportsGDBStoppointPacket(type))
2651 // Construct the breakpoint packet
2653 const int packet_len =
2654 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2655 insert ? 'Z' : 'z', type, addr, length);
2656 // Check we haven't overwritten the end of the packet buffer
2657 assert(packet_len + 1 < (int)sizeof(packet));
2658 UNUSED_IF_ASSERT_DISABLED(packet_len);
2659 StringExtractorGDBRemote response;
2660 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2661 // or "" (unsupported)
2662 response.SetResponseValidatorToOKErrorNotSupported();
2663 // Try to send the breakpoint packet, and check that it was correctly sent
2664 if (SendPacketAndWaitForResponse(packet, response, true) ==
2665 PacketResult::Success) {
2666 // Receive and OK packet when the breakpoint successfully placed
2667 if (response.IsOKResponse())
2670 // Status while setting breakpoint, send back specific error
2671 if (response.IsErrorResponse())
2672 return response.GetError();
2674 // Empty packet informs us that breakpoint is not supported
2675 if (response.IsUnsupportedResponse()) {
2676 // Disable this breakpoint type since it is unsupported
2678 case eBreakpointSoftware:
2679 m_supports_z0 = false;
2681 case eBreakpointHardware:
2682 m_supports_z1 = false;
2684 case eWatchpointWrite:
2685 m_supports_z2 = false;
2687 case eWatchpointRead:
2688 m_supports_z3 = false;
2690 case eWatchpointReadWrite:
2691 m_supports_z4 = false;
2693 case eStoppointInvalid:
2698 // Signal generic failure
2702 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2703 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2706 Lock lock(*this, false);
2708 sequence_mutex_unavailable = false;
2709 StringExtractorGDBRemote response;
2711 PacketResult packet_result;
2712 for (packet_result =
2713 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2714 packet_result == PacketResult::Success && response.IsNormalResponse();
2716 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2717 char ch = response.GetChar();
2722 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2724 if (tid != LLDB_INVALID_THREAD_ID) {
2725 thread_ids.push_back(tid);
2727 ch = response.GetChar(); // Skip the command separator
2728 } while (ch == ','); // Make sure we got a comma separator
2733 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2734 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2736 * be as simple as 'S05'. There is no packet which can give us pid and/or
2738 * Assume pid=tid=1 in such cases.
2740 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2741 thread_ids.size() == 0 && IsConnected()) {
2742 thread_ids.push_back(1);
2745 #if !defined(LLDB_CONFIGURATION_DEBUG)
2746 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2749 log->Printf("error: failed to get packet sequence mutex, not sending "
2750 "packet 'qfThreadInfo'");
2752 sequence_mutex_unavailable = true;
2754 return thread_ids.size();
2757 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2758 StringExtractorGDBRemote response;
2759 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2760 PacketResult::Success ||
2761 !response.IsNormalResponse())
2762 return LLDB_INVALID_ADDRESS;
2763 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2766 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2767 const char *command, // Shouldn't be NULL
2769 working_dir, // Pass empty FileSpec to use the current working directory
2770 int *status_ptr, // Pass NULL if you don't want the process exit status
2771 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2774 *command_output, // Pass NULL if you don't want the command output
2775 const Timeout<std::micro> &timeout) {
2776 lldb_private::StreamString stream;
2777 stream.PutCString("qPlatform_shell:");
2778 stream.PutBytesAsRawHex8(command, strlen(command));
2779 stream.PutChar(',');
2780 uint32_t timeout_sec = UINT32_MAX;
2782 // TODO: Use chrono version of std::ceil once c++17 is available.
2783 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2785 stream.PutHex32(timeout_sec);
2787 std::string path{working_dir.GetPath(false)};
2788 stream.PutChar(',');
2789 stream.PutStringAsRawHex8(path);
2791 StringExtractorGDBRemote response;
2792 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2793 PacketResult::Success) {
2794 if (response.GetChar() != 'F')
2795 return Status("malformed reply");
2796 if (response.GetChar() != ',')
2797 return Status("malformed reply");
2798 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2799 if (exitcode == UINT32_MAX)
2800 return Status("unable to run remote process");
2801 else if (status_ptr)
2802 *status_ptr = exitcode;
2803 if (response.GetChar() != ',')
2804 return Status("malformed reply");
2805 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2808 if (response.GetChar() != ',')
2809 return Status("malformed reply");
2811 response.GetEscapedBinaryData(output);
2813 command_output->assign(output);
2816 return Status("unable to send packet");
2819 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2820 uint32_t file_permissions) {
2821 std::string path{file_spec.GetPath(false)};
2822 lldb_private::StreamString stream;
2823 stream.PutCString("qPlatform_mkdir:");
2824 stream.PutHex32(file_permissions);
2825 stream.PutChar(',');
2826 stream.PutStringAsRawHex8(path);
2827 llvm::StringRef packet = stream.GetString();
2828 StringExtractorGDBRemote response;
2830 if (SendPacketAndWaitForResponse(packet, response, false) !=
2831 PacketResult::Success)
2832 return Status("failed to send '%s' packet", packet.str().c_str());
2834 if (response.GetChar() != 'F')
2835 return Status("invalid response to '%s' packet", packet.str().c_str());
2837 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2841 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2842 uint32_t file_permissions) {
2843 std::string path{file_spec.GetPath(false)};
2844 lldb_private::StreamString stream;
2845 stream.PutCString("qPlatform_chmod:");
2846 stream.PutHex32(file_permissions);
2847 stream.PutChar(',');
2848 stream.PutStringAsRawHex8(path);
2849 llvm::StringRef packet = stream.GetString();
2850 StringExtractorGDBRemote response;
2852 if (SendPacketAndWaitForResponse(packet, response, false) !=
2853 PacketResult::Success)
2854 return Status("failed to send '%s' packet", stream.GetData());
2856 if (response.GetChar() != 'F')
2857 return Status("invalid response to '%s' packet", stream.GetData());
2859 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2862 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2863 uint64_t fail_result, Status &error) {
2864 response.SetFilePos(0);
2865 if (response.GetChar() != 'F')
2867 int32_t result = response.GetS32(-2);
2870 if (response.GetChar() == ',') {
2871 int result_errno = response.GetS32(-2);
2872 if (result_errno != -2)
2873 error.SetError(result_errno, eErrorTypePOSIX);
2875 error.SetError(-1, eErrorTypeGeneric);
2881 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2882 uint32_t flags, mode_t mode,
2884 std::string path(file_spec.GetPath(false));
2885 lldb_private::StreamString stream;
2886 stream.PutCString("vFile:open:");
2889 stream.PutStringAsRawHex8(path);
2890 stream.PutChar(',');
2891 stream.PutHex32(flags);
2892 stream.PutChar(',');
2893 stream.PutHex32(mode);
2894 StringExtractorGDBRemote response;
2895 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2896 PacketResult::Success) {
2897 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2902 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2904 lldb_private::StreamString stream;
2905 stream.Printf("vFile:close:%i", (int)fd);
2906 StringExtractorGDBRemote response;
2907 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2908 PacketResult::Success) {
2909 return ParseHostIOPacketResponse(response, -1, error) == 0;
2914 // Extension of host I/O packets to get the file size.
2915 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2916 const lldb_private::FileSpec &file_spec) {
2917 std::string path(file_spec.GetPath(false));
2918 lldb_private::StreamString stream;
2919 stream.PutCString("vFile:size:");
2920 stream.PutStringAsRawHex8(path);
2921 StringExtractorGDBRemote response;
2922 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2923 PacketResult::Success) {
2924 if (response.GetChar() != 'F')
2926 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2933 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2934 uint32_t &file_permissions) {
2935 std::string path{file_spec.GetPath(false)};
2937 lldb_private::StreamString stream;
2938 stream.PutCString("vFile:mode:");
2939 stream.PutStringAsRawHex8(path);
2940 StringExtractorGDBRemote response;
2941 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2942 PacketResult::Success) {
2943 if (response.GetChar() != 'F') {
2944 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2947 const uint32_t mode = response.GetS32(-1);
2948 if (static_cast<int32_t>(mode) == -1) {
2949 if (response.GetChar() == ',') {
2950 int response_errno = response.GetS32(-1);
2951 if (response_errno > 0)
2952 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2954 error.SetErrorToGenericError();
2956 error.SetErrorToGenericError();
2958 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2962 error.SetErrorStringWithFormat("failed to send '%s' packet",
2968 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2969 uint64_t offset, void *dst,
2972 lldb_private::StreamString stream;
2973 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2975 StringExtractorGDBRemote response;
2976 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2977 PacketResult::Success) {
2978 if (response.GetChar() != 'F')
2980 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2981 if (retcode == UINT32_MAX)
2983 const char next = (response.Peek() ? *response.Peek() : 0);
2987 response.GetChar(); // skip the semicolon
2989 if (response.GetEscapedBinaryData(buffer)) {
2990 const uint64_t data_to_write =
2991 std::min<uint64_t>(dst_len, buffer.size());
2992 if (data_to_write > 0)
2993 memcpy(dst, &buffer[0], data_to_write);
2994 return data_to_write;
3001 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3006 lldb_private::StreamGDBRemote stream;
3007 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3008 stream.PutEscapedBytes(src, src_len);
3009 StringExtractorGDBRemote response;
3010 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3011 PacketResult::Success) {
3012 if (response.GetChar() != 'F') {
3013 error.SetErrorStringWithFormat("write file failed");
3016 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3017 if (bytes_written == UINT64_MAX) {
3018 error.SetErrorToGenericError();
3019 if (response.GetChar() == ',') {
3020 int response_errno = response.GetS32(-1);
3021 if (response_errno > 0)
3022 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3026 return bytes_written;
3028 error.SetErrorString("failed to send vFile:pwrite packet");
3033 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3034 const FileSpec &dst) {
3035 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3037 lldb_private::StreamGDBRemote stream;
3038 stream.PutCString("vFile:symlink:");
3039 // the unix symlink() command reverses its parameters where the dst if first,
3040 // so we follow suit here
3041 stream.PutStringAsRawHex8(dst_path);
3042 stream.PutChar(',');
3043 stream.PutStringAsRawHex8(src_path);
3044 StringExtractorGDBRemote response;
3045 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3046 PacketResult::Success) {
3047 if (response.GetChar() == 'F') {
3048 uint32_t result = response.GetU32(UINT32_MAX);
3050 error.SetErrorToGenericError();
3051 if (response.GetChar() == ',') {
3052 int response_errno = response.GetS32(-1);
3053 if (response_errno > 0)
3054 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3058 // Should have returned with 'F<result>[,<errno>]'
3059 error.SetErrorStringWithFormat("symlink failed");
3062 error.SetErrorString("failed to send vFile:symlink packet");
3067 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3068 std::string path{file_spec.GetPath(false)};
3070 lldb_private::StreamGDBRemote stream;
3071 stream.PutCString("vFile:unlink:");
3072 // the unix symlink() command reverses its parameters where the dst if first,
3073 // so we follow suit here
3074 stream.PutStringAsRawHex8(path);
3075 StringExtractorGDBRemote response;
3076 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3077 PacketResult::Success) {
3078 if (response.GetChar() == 'F') {
3079 uint32_t result = response.GetU32(UINT32_MAX);
3081 error.SetErrorToGenericError();
3082 if (response.GetChar() == ',') {
3083 int response_errno = response.GetS32(-1);
3084 if (response_errno > 0)
3085 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3089 // Should have returned with 'F<result>[,<errno>]'
3090 error.SetErrorStringWithFormat("unlink failed");
3093 error.SetErrorString("failed to send vFile:unlink packet");
3098 // Extension of host I/O packets to get whether a file exists.
3099 bool GDBRemoteCommunicationClient::GetFileExists(
3100 const lldb_private::FileSpec &file_spec) {
3101 std::string path(file_spec.GetPath(false));
3102 lldb_private::StreamString stream;
3103 stream.PutCString("vFile:exists:");
3104 stream.PutStringAsRawHex8(path);
3105 StringExtractorGDBRemote response;
3106 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3107 PacketResult::Success) {
3108 if (response.GetChar() != 'F')
3110 if (response.GetChar() != ',')
3112 bool retcode = (response.GetChar() != '0');
3118 bool GDBRemoteCommunicationClient::CalculateMD5(
3119 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3120 std::string path(file_spec.GetPath(false));
3121 lldb_private::StreamString stream;
3122 stream.PutCString("vFile:MD5:");
3123 stream.PutStringAsRawHex8(path);
3124 StringExtractorGDBRemote response;
3125 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3126 PacketResult::Success) {
3127 if (response.GetChar() != 'F')
3129 if (response.GetChar() != ',')
3131 if (response.Peek() && *response.Peek() == 'x')
3133 low = response.GetHexMaxU64(false, UINT64_MAX);
3134 high = response.GetHexMaxU64(false, UINT64_MAX);
3140 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3141 // Some targets have issues with g/G packets and we need to avoid using them
3142 if (m_avoid_g_packets == eLazyBoolCalculate) {
3144 m_avoid_g_packets = eLazyBoolNo;
3145 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3146 if (arch.IsValid() &&
3147 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3148 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3149 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3150 m_avoid_g_packets = eLazyBoolYes;
3151 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3152 if (gdb_server_version != 0) {
3153 const char *gdb_server_name = GetGDBServerProgramName();
3154 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3155 if (gdb_server_version >= 310)
3156 m_avoid_g_packets = eLazyBoolNo;
3162 return m_avoid_g_packets == eLazyBoolYes;
3165 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3167 StreamString payload;
3168 payload.Printf("p%x", reg);
3169 StringExtractorGDBRemote response;
3170 if (SendThreadSpecificPacketAndWaitForResponse(
3171 tid, std::move(payload), response, false) != PacketResult::Success ||
3172 !response.IsNormalResponse())
3175 DataBufferSP buffer_sp(
3176 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3177 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3181 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3182 StreamString payload;
3183 payload.PutChar('g');
3184 StringExtractorGDBRemote response;
3185 if (SendThreadSpecificPacketAndWaitForResponse(
3186 tid, std::move(payload), response, false) != PacketResult::Success ||
3187 !response.IsNormalResponse())
3190 DataBufferSP buffer_sp(
3191 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3192 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3196 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3198 llvm::ArrayRef<uint8_t> data) {
3199 StreamString payload;
3200 payload.Printf("P%x=", reg_num);
3201 payload.PutBytesAsRawHex8(data.data(), data.size(),
3202 endian::InlHostByteOrder(),
3203 endian::InlHostByteOrder());
3204 StringExtractorGDBRemote response;
3205 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3207 PacketResult::Success &&
3208 response.IsOKResponse();
3211 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3212 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3213 StreamString payload;
3214 payload.PutChar('G');
3215 payload.PutBytesAsRawHex8(data.data(), data.size(),
3216 endian::InlHostByteOrder(),
3217 endian::InlHostByteOrder());
3218 StringExtractorGDBRemote response;
3219 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3221 PacketResult::Success &&
3222 response.IsOKResponse();
3225 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3226 uint32_t &save_id) {
3227 save_id = 0; // Set to invalid save ID
3228 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3231 m_supports_QSaveRegisterState = eLazyBoolYes;
3232 StreamString payload;
3233 payload.PutCString("QSaveRegisterState");
3234 StringExtractorGDBRemote response;
3235 if (SendThreadSpecificPacketAndWaitForResponse(
3236 tid, std::move(payload), response, false) != PacketResult::Success)
3239 if (response.IsUnsupportedResponse())
3240 m_supports_QSaveRegisterState = eLazyBoolNo;
3242 const uint32_t response_save_id = response.GetU32(0);
3243 if (response_save_id == 0)
3246 save_id = response_save_id;
3250 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3252 // We use the "m_supports_QSaveRegisterState" variable here because the
3253 // QSaveRegisterState and QRestoreRegisterState packets must both be
3254 // supported in order to be useful
3255 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3258 StreamString payload;
3259 payload.Printf("QRestoreRegisterState:%u", save_id);
3260 StringExtractorGDBRemote response;
3261 if (SendThreadSpecificPacketAndWaitForResponse(
3262 tid, std::move(payload), response, false) != PacketResult::Success)
3265 if (response.IsOKResponse())
3268 if (response.IsUnsupportedResponse())
3269 m_supports_QSaveRegisterState = eLazyBoolNo;
3273 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3274 if (!GetSyncThreadStateSupported())
3277 StreamString packet;
3278 StringExtractorGDBRemote response;
3279 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3280 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3281 GDBRemoteCommunication::PacketResult::Success &&
3282 response.IsOKResponse();
3286 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3288 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3289 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3291 StreamGDBRemote escaped_packet;
3292 escaped_packet.PutCString("jTraceStart:");
3294 StructuredData::Dictionary json_packet;
3295 json_packet.AddIntegerItem("type", options.getType());
3296 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3297 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3299 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3300 json_packet.AddIntegerItem("threadid", options.getThreadID());
3302 StructuredData::DictionarySP custom_params = options.getTraceParams();
3304 json_packet.AddItem("params", custom_params);
3306 StreamString json_string;
3307 json_packet.Dump(json_string, false);
3308 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3310 StringExtractorGDBRemote response;
3311 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3313 GDBRemoteCommunication::PacketResult::Success) {
3314 if (!response.IsNormalResponse()) {
3315 error = response.GetStatus();
3316 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
3318 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3321 LLDB_LOG(log, "failed to send packet");
3322 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3323 escaped_packet.GetData());
3329 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3330 lldb::tid_t thread_id) {
3331 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3332 StringExtractorGDBRemote response;
3335 StructuredData::Dictionary json_packet;
3336 StreamGDBRemote escaped_packet;
3337 StreamString json_string;
3338 escaped_packet.PutCString("jTraceStop:");
3340 json_packet.AddIntegerItem("traceid", uid);
3342 if (thread_id != LLDB_INVALID_THREAD_ID)
3343 json_packet.AddIntegerItem("threadid", thread_id);
3345 json_packet.Dump(json_string, false);
3347 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3349 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3351 GDBRemoteCommunication::PacketResult::Success) {
3352 if (!response.IsOKResponse()) {
3353 error = response.GetStatus();
3354 LLDB_LOG(log, "stop tracing failed");
3357 LLDB_LOG(log, "failed to send packet");
3358 error.SetErrorStringWithFormat(
3359 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3360 response.GetError());
3365 Status GDBRemoteCommunicationClient::SendGetDataPacket(
3366 lldb::user_id_t uid, lldb::tid_t thread_id,
3367 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3369 StreamGDBRemote escaped_packet;
3370 escaped_packet.PutCString("jTraceBufferRead:");
3371 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3374 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3375 lldb::user_id_t uid, lldb::tid_t thread_id,
3376 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3378 StreamGDBRemote escaped_packet;
3379 escaped_packet.PutCString("jTraceMetaRead:");
3380 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3384 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3385 TraceOptions &options) {
3386 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3387 StringExtractorGDBRemote response;
3390 StreamString json_string;
3391 StreamGDBRemote escaped_packet;
3392 escaped_packet.PutCString("jTraceConfigRead:");
3394 StructuredData::Dictionary json_packet;
3395 json_packet.AddIntegerItem("traceid", uid);
3397 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3398 json_packet.AddIntegerItem("threadid", options.getThreadID());
3400 json_packet.Dump(json_string, false);
3401 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3403 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3405 GDBRemoteCommunication::PacketResult::Success) {
3406 if (response.IsNormalResponse()) {
3407 uint64_t type = std::numeric_limits<uint64_t>::max();
3408 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3409 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3411 auto json_object = StructuredData::ParseJSON(response.Peek());
3414 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
3415 error.SetErrorString("Invalid Configuration obtained");
3419 auto json_dict = json_object->GetAsDictionary();
3421 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3423 options.setMetaDataBufferSize(metabuffersize);
3425 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3426 options.setTraceBufferSize(buffersize);
3428 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3429 options.setType(static_cast<lldb::TraceType>(type));
3431 StructuredData::ObjectSP custom_params_sp =
3432 json_dict->GetValueForKey("params");
3433 if (custom_params_sp) {
3434 if (custom_params_sp->GetType() !=
3435 lldb::eStructuredDataTypeDictionary) {
3436 error.SetErrorString("Invalid Configuration obtained");
3439 options.setTraceParams(
3440 static_pointer_cast<StructuredData::Dictionary>(
3444 error = response.GetStatus();
3447 LLDB_LOG(log, "failed to send packet");
3448 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3449 escaped_packet.GetData());
3454 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3455 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3456 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3457 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3460 StructuredData::Dictionary json_packet;
3462 json_packet.AddIntegerItem("traceid", uid);
3463 json_packet.AddIntegerItem("offset", offset);
3464 json_packet.AddIntegerItem("buffersize", buffer.size());
3466 if (thread_id != LLDB_INVALID_THREAD_ID)
3467 json_packet.AddIntegerItem("threadid", thread_id);
3469 StreamString json_string;
3470 json_packet.Dump(json_string, false);
3472 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3473 StringExtractorGDBRemote response;
3474 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3475 GDBRemoteCommunication::PacketResult::Success) {
3476 if (response.IsNormalResponse()) {
3477 size_t filled_size = response.GetHexBytesAvail(buffer);
3478 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3480 error = response.GetStatus();
3481 buffer = buffer.slice(buffer.size());
3484 LLDB_LOG(log, "failed to send packet");
3485 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3487 buffer = buffer.slice(buffer.size());
3492 bool GDBRemoteCommunicationClient::GetModuleInfo(
3493 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3494 ModuleSpec &module_spec) {
3495 if (!m_supports_qModuleInfo)
3498 std::string module_path = module_file_spec.GetPath(false);
3499 if (module_path.empty())
3502 StreamString packet;
3503 packet.PutCString("qModuleInfo:");
3504 packet.PutStringAsRawHex8(module_path);
3505 packet.PutCString(";");
3506 const auto &triple = arch_spec.GetTriple().getTriple();
3507 packet.PutStringAsRawHex8(triple);
3509 StringExtractorGDBRemote response;
3510 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3511 PacketResult::Success)
3514 if (response.IsErrorResponse())
3517 if (response.IsUnsupportedResponse()) {
3518 m_supports_qModuleInfo = false;
3522 llvm::StringRef name;
3523 llvm::StringRef value;
3525 module_spec.Clear();
3526 module_spec.GetFileSpec() = module_file_spec;
3528 while (response.GetNameColonValue(name, value)) {
3529 if (name == "uuid" || name == "md5") {
3530 StringExtractor extractor(value);
3532 extractor.GetHexByteString(uuid);
3533 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
3534 } else if (name == "triple") {
3535 StringExtractor extractor(value);
3537 extractor.GetHexByteString(triple);
3538 module_spec.GetArchitecture().SetTriple(triple.c_str());
3539 } else if (name == "file_offset") {
3541 if (!value.getAsInteger(16, ival))
3542 module_spec.SetObjectOffset(ival);
3543 } else if (name == "file_size") {
3545 if (!value.getAsInteger(16, ival))
3546 module_spec.SetObjectSize(ival);
3547 } else if (name == "file_path") {
3548 StringExtractor extractor(value);
3550 extractor.GetHexByteString(path);
3551 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3558 static llvm::Optional<ModuleSpec>
3559 ParseModuleSpec(StructuredData::Dictionary *dict) {
3564 llvm::StringRef string;
3567 if (!dict->GetValueForKeyAsString("uuid", string))
3569 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3573 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3575 result.SetObjectOffset(integer);
3577 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3579 result.SetObjectSize(integer);
3581 if (!dict->GetValueForKeyAsString("triple", string))
3583 result.GetArchitecture().SetTriple(string);
3585 if (!dict->GetValueForKeyAsString("file_path", string))
3587 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3592 llvm::Optional<std::vector<ModuleSpec>>
3593 GDBRemoteCommunicationClient::GetModulesInfo(
3594 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3595 if (!m_supports_jModulesInfo)
3598 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3599 for (const FileSpec &module_file_spec : module_file_specs) {
3600 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3601 module_array_sp->AppendObject(module_sp);
3602 module_sp->SetObject(
3603 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
3604 module_sp->SetObject("triple",
3605 std::make_shared<JSONString>(triple.getTriple()));
3607 StreamString unescaped_payload;
3608 unescaped_payload.PutCString("jModulesInfo:");
3609 module_array_sp->Write(unescaped_payload);
3610 StreamGDBRemote payload;
3611 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3612 unescaped_payload.GetSize());
3614 // Increase the timeout for jModulesInfo since this packet can take longer.
3615 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3617 StringExtractorGDBRemote response;
3618 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3619 PacketResult::Success ||
3620 response.IsErrorResponse())
3623 if (response.IsUnsupportedResponse()) {
3624 m_supports_jModulesInfo = false;
3628 StructuredData::ObjectSP response_object_sp =
3629 StructuredData::ParseJSON(response.GetStringRef());
3630 if (!response_object_sp)
3633 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3634 if (!response_array)
3637 std::vector<ModuleSpec> result;
3638 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3639 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3640 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3641 result.push_back(*module_spec);
3647 // query the target remote for extended information using the qXfer packet
3649 // example: object='features', annex='target.xml', out=<xml output> return:
3650 // 'true' on success
3651 // 'false' on failure (err set)
3652 bool GDBRemoteCommunicationClient::ReadExtFeature(
3653 const lldb_private::ConstString object,
3654 const lldb_private::ConstString annex, std::string &out,
3655 lldb_private::Status &err) {
3657 std::stringstream output;
3658 StringExtractorGDBRemote chunk;
3660 uint64_t size = GetRemoteMaxPacketSize();
3663 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3667 // loop until all data has been read
3670 // send query extended feature packet
3671 std::stringstream packet;
3672 packet << "qXfer:" << object.AsCString("")
3673 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3674 << "," << std::hex << size;
3676 GDBRemoteCommunication::PacketResult res =
3677 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3679 if (res != GDBRemoteCommunication::PacketResult::Success) {
3680 err.SetErrorString("Error sending $qXfer packet");
3684 const std::string &str = chunk.GetStringRef();
3685 if (str.length() == 0) {
3686 // should have some data in chunk
3687 err.SetErrorString("Empty response from $qXfer packet");
3691 // check packet code
3700 if (str.length() > 1)
3707 err.SetErrorString("Invalid continuation code from $qXfer packet");
3717 // Notify the target that gdb is prepared to serve symbol lookup requests.
3718 // packet: "qSymbol::"
3720 // OK The target does not need to look up any (more) symbols.
3721 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3723 // LLDB may provide the value by sending another qSymbol
3725 // in the form of"qSymbol:<sym_value>:<sym_name>".
3729 // lldb sends: qSymbol::
3730 // lldb receives: OK
3731 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3733 // need to ask again in this session.
3735 // lldb sends: qSymbol::
3736 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3737 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3738 // lldb receives: OK
3739 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3741 // the address at this time. lldb needs to send qSymbol:: again when it has
3745 // lldb sends: qSymbol::
3746 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3747 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3748 // lldb receives: OK
3749 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3751 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3753 // need any more symbols. lldb does not need to ask again in this session.
3755 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3756 lldb_private::Process *process) {
3757 // Set to true once we've resolved a symbol to an address for the remote
3758 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3759 // any more symbols and we can stop asking.
3760 bool symbol_response_provided = false;
3762 // Is this the initial qSymbol:: packet?
3763 bool first_qsymbol_query = true;
3765 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
3766 Lock lock(*this, false);
3768 StreamString packet;
3769 packet.PutCString("qSymbol::");
3770 StringExtractorGDBRemote response;
3771 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3772 PacketResult::Success) {
3773 if (response.IsOKResponse()) {
3774 if (symbol_response_provided || first_qsymbol_query) {
3775 m_qSymbol_requests_done = true;
3778 // We are done serving symbols requests
3781 first_qsymbol_query = false;
3783 if (response.IsUnsupportedResponse()) {
3784 // qSymbol is not supported by the current GDB server we are
3786 m_supports_qSymbol = false;
3789 llvm::StringRef response_str(response.GetStringRef());
3790 if (response_str.startswith("qSymbol:")) {
3791 response.SetFilePos(strlen("qSymbol:"));
3792 std::string symbol_name;
3793 if (response.GetHexByteString(symbol_name)) {
3794 if (symbol_name.empty())
3797 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3798 lldb_private::SymbolContextList sc_list;
3799 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3800 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3801 const size_t num_scs = sc_list.GetSize();
3802 for (size_t sc_idx = 0;
3804 symbol_load_addr == LLDB_INVALID_ADDRESS;
3807 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3809 switch (sc.symbol->GetType()) {
3810 case eSymbolTypeInvalid:
3811 case eSymbolTypeAbsolute:
3812 case eSymbolTypeUndefined:
3813 case eSymbolTypeSourceFile:
3814 case eSymbolTypeHeaderFile:
3815 case eSymbolTypeObjectFile:
3816 case eSymbolTypeCommonBlock:
3817 case eSymbolTypeBlock:
3818 case eSymbolTypeLocal:
3819 case eSymbolTypeParam:
3820 case eSymbolTypeVariable:
3821 case eSymbolTypeVariableType:
3822 case eSymbolTypeLineEntry:
3823 case eSymbolTypeLineHeader:
3824 case eSymbolTypeScopeBegin:
3825 case eSymbolTypeScopeEnd:
3826 case eSymbolTypeAdditional:
3827 case eSymbolTypeCompiler:
3828 case eSymbolTypeInstrumentation:
3829 case eSymbolTypeTrampoline:
3832 case eSymbolTypeCode:
3833 case eSymbolTypeResolver:
3834 case eSymbolTypeData:
3835 case eSymbolTypeRuntime:
3836 case eSymbolTypeException:
3837 case eSymbolTypeObjCClass:
3838 case eSymbolTypeObjCMetaClass:
3839 case eSymbolTypeObjCIVar:
3840 case eSymbolTypeReExported:
3842 sc.symbol->GetLoadAddress(&process->GetTarget());
3849 // This is the normal path where our symbol lookup was successful
3850 // and we want to send a packet with the new symbol value and see
3851 // if another lookup needs to be done.
3853 // Change "packet" to contain the requested symbol value and name
3855 packet.PutCString("qSymbol:");
3856 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3857 packet.Printf("%" PRIx64, symbol_load_addr);
3858 symbol_response_provided = true;
3860 symbol_response_provided = false;
3862 packet.PutCString(":");
3863 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3864 continue; // go back to the while loop and send "packet" and wait
3865 // for another response
3870 // If we make it here, the symbol request packet response wasn't valid or
3871 // our symbol lookup failed so we must abort
3874 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3875 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3877 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3883 StructuredData::Array *
3884 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3885 if (!m_supported_async_json_packets_is_valid) {
3886 // Query the server for the array of supported asynchronous JSON packets.
3887 m_supported_async_json_packets_is_valid = true;
3889 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3892 StringExtractorGDBRemote response;
3893 const bool send_async = false;
3894 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3895 send_async) == PacketResult::Success) {
3896 m_supported_async_json_packets_sp =
3897 StructuredData::ParseJSON(response.GetStringRef());
3898 if (m_supported_async_json_packets_sp &&
3899 !m_supported_async_json_packets_sp->GetAsArray()) {
3900 // We were returned something other than a JSON array. This is
3901 // invalid. Clear it out.
3903 log->Printf("GDBRemoteCommunicationClient::%s(): "
3904 "QSupportedAsyncJSONPackets returned invalid "
3906 __FUNCTION__, response.GetStringRef().c_str());
3907 m_supported_async_json_packets_sp.reset();
3911 log->Printf("GDBRemoteCommunicationClient::%s(): "
3912 "QSupportedAsyncJSONPackets unsupported",
3916 if (log && m_supported_async_json_packets_sp) {
3917 StreamString stream;
3918 m_supported_async_json_packets_sp->Dump(stream);
3919 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3921 __FUNCTION__, stream.GetData());
3925 return m_supported_async_json_packets_sp
3926 ? m_supported_async_json_packets_sp->GetAsArray()
3930 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
3931 llvm::ArrayRef<int32_t> signals) {
3933 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3934 auto range = llvm::make_range(signals.begin(), signals.end());
3935 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3937 StringExtractorGDBRemote response;
3938 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3940 if (send_status != GDBRemoteCommunication::PacketResult::Success)
3941 return Status("Sending QPassSignals packet failed");
3943 if (response.IsOKResponse()) {
3946 return Status("Unknown error happened during sending QPassSignals packet.");
3950 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3951 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3954 if (type_name.GetLength() == 0) {
3955 error.SetErrorString("invalid type_name argument");
3959 // Build command: Configure{type_name}: serialized config data.
3960 StreamGDBRemote stream;
3961 stream.PutCString("QConfigure");
3962 stream.PutCString(type_name.AsCString());
3963 stream.PutChar(':');
3965 // Gather the plain-text version of the configuration data.
3966 StreamString unescaped_stream;
3967 config_sp->Dump(unescaped_stream);
3968 unescaped_stream.Flush();
3970 // Add it to the stream in escaped fashion.
3971 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
3972 unescaped_stream.GetSize());
3977 const bool send_async = false;
3978 StringExtractorGDBRemote response;
3980 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
3981 if (result == PacketResult::Success) {
3982 // We failed if the config result comes back other than OK.
3983 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3987 error.SetErrorStringWithFormat("configuring StructuredData feature "
3988 "%s failed with error %s",
3989 type_name.AsCString(),
3990 response.GetStringRef().c_str());
3993 // Can we get more data here on the failure?
3994 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3995 "failed when sending packet: "
3997 type_name.AsCString(), (int)result);
4002 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4003 GDBRemoteClientBase::OnRunPacketSent(first);
4004 m_curr_tid = LLDB_INVALID_THREAD_ID;