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/LLDBAssert.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/State.h"
29 #include "lldb/Utility/StreamString.h"
31 #include "ProcessGDBRemote.h"
32 #include "ProcessGDBRemoteLog.h"
33 #include "lldb/Host/Config.h"
34 #include "lldb/Utility/StringExtractorGDBRemote.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/Support/JSON.h"
39 #if defined(HAVE_LIBCOMPRESSION)
40 #include <compression.h>
44 using namespace lldb_private::process_gdb_remote;
45 using namespace lldb_private;
46 using namespace std::chrono;
48 // GDBRemoteCommunicationClient constructor
49 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
50 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
51 m_supports_not_sending_acks(eLazyBoolCalculate),
52 m_supports_thread_suffix(eLazyBoolCalculate),
53 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
54 m_supports_vCont_all(eLazyBoolCalculate),
55 m_supports_vCont_any(eLazyBoolCalculate),
56 m_supports_vCont_c(eLazyBoolCalculate),
57 m_supports_vCont_C(eLazyBoolCalculate),
58 m_supports_vCont_s(eLazyBoolCalculate),
59 m_supports_vCont_S(eLazyBoolCalculate),
60 m_qHostInfo_is_valid(eLazyBoolCalculate),
61 m_curr_pid_is_valid(eLazyBoolCalculate),
62 m_qProcessInfo_is_valid(eLazyBoolCalculate),
63 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
64 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
65 m_supports_memory_region_info(eLazyBoolCalculate),
66 m_supports_watchpoint_support_info(eLazyBoolCalculate),
67 m_supports_detach_stay_stopped(eLazyBoolCalculate),
68 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
69 m_attach_or_wait_reply(eLazyBoolCalculate),
70 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
71 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
72 m_avoid_g_packets(eLazyBoolCalculate),
73 m_supports_QSaveRegisterState(eLazyBoolCalculate),
74 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
75 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
76 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
77 m_supports_qXfer_features_read(eLazyBoolCalculate),
78 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
79 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
80 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
81 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
82 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
83 m_supports_QPassSignals(eLazyBoolCalculate),
84 m_supports_error_string_reply(eLazyBoolCalculate),
85 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
86 m_supports_qUserName(true), m_supports_qGroupName(true),
87 m_supports_qThreadStopInfo(true), m_supports_z0(true),
88 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
89 m_supports_z4(true), m_supports_QEnvironment(true),
90 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
91 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
92 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
93 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
94 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
95 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
96 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
97 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
98 m_max_packet_size(0), m_qSupported_response(),
99 m_supported_async_json_packets_is_valid(false),
100 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
101 m_qXfer_memory_map_loaded(false) {}
104 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
109 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
110 ResetDiscoverableSettings(false);
112 // Start the read thread after we send the handshake ack since if we fail to
113 // send the handshake ack, there is no reason to continue...
115 // Wait for any responses that might have been queued up in the remote
116 // GDB server and flush them all
117 StringExtractorGDBRemote response;
118 PacketResult packet_result = PacketResult::Success;
119 while (packet_result == PacketResult::Success)
120 packet_result = ReadPacket(response, milliseconds(10), false);
122 // The return value from QueryNoAckModeSupported() is true if the packet
123 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
124 // false if no response was received. This quickly tells us if we have a
125 // live connection to a remote GDB server...
126 if (QueryNoAckModeSupported()) {
130 error_ptr->SetErrorString("failed to get reply to handshake packet");
134 error_ptr->SetErrorString("failed to send the handshake ack");
139 bool GDBRemoteCommunicationClient::GetEchoSupported() {
140 if (m_supports_qEcho == eLazyBoolCalculate) {
141 GetRemoteQSupported();
143 return m_supports_qEcho == eLazyBoolYes;
146 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
147 if (m_supports_QPassSignals == eLazyBoolCalculate) {
148 GetRemoteQSupported();
150 return m_supports_QPassSignals == eLazyBoolYes;
153 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
154 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
155 GetRemoteQSupported();
157 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
160 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
161 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
164 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
167 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
168 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
171 return m_supports_qXfer_libraries_read == eLazyBoolYes;
174 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
175 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
178 return m_supports_qXfer_auxv_read == eLazyBoolYes;
181 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
182 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
185 return m_supports_qXfer_features_read == eLazyBoolYes;
188 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
189 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
190 GetRemoteQSupported();
192 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
195 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
196 if (m_max_packet_size == 0) {
197 GetRemoteQSupported();
199 return m_max_packet_size;
202 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
203 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
205 m_supports_not_sending_acks = eLazyBoolNo;
207 // This is the first real packet that we'll send in a debug session and it
208 // may take a little longer than normal to receive a reply. Wait at least
209 // 6 seconds for a reply to this packet.
211 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
213 StringExtractorGDBRemote response;
214 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
215 PacketResult::Success) {
216 if (response.IsOKResponse()) {
218 m_supports_not_sending_acks = eLazyBoolYes;
226 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
227 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
228 m_supports_threads_in_stop_reply = eLazyBoolNo;
230 StringExtractorGDBRemote response;
231 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
232 false) == PacketResult::Success) {
233 if (response.IsOKResponse())
234 m_supports_threads_in_stop_reply = eLazyBoolYes;
239 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
240 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
241 m_attach_or_wait_reply = eLazyBoolNo;
243 StringExtractorGDBRemote response;
244 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
245 false) == PacketResult::Success) {
246 if (response.IsOKResponse())
247 m_attach_or_wait_reply = eLazyBoolYes;
250 return m_attach_or_wait_reply == eLazyBoolYes;
253 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
254 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
255 m_prepare_for_reg_writing_reply = eLazyBoolNo;
257 StringExtractorGDBRemote response;
258 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
259 false) == PacketResult::Success) {
260 if (response.IsOKResponse())
261 m_prepare_for_reg_writing_reply = eLazyBoolYes;
264 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
267 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
269 // Hard reset everything, this is when we first connect to a GDB server
270 m_supports_not_sending_acks = eLazyBoolCalculate;
271 m_supports_thread_suffix = eLazyBoolCalculate;
272 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
273 m_supports_vCont_c = eLazyBoolCalculate;
274 m_supports_vCont_C = eLazyBoolCalculate;
275 m_supports_vCont_s = eLazyBoolCalculate;
276 m_supports_vCont_S = eLazyBoolCalculate;
277 m_supports_p = eLazyBoolCalculate;
278 m_supports_x = eLazyBoolCalculate;
279 m_supports_QSaveRegisterState = eLazyBoolCalculate;
280 m_qHostInfo_is_valid = eLazyBoolCalculate;
281 m_curr_pid_is_valid = eLazyBoolCalculate;
282 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
283 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
284 m_supports_memory_region_info = eLazyBoolCalculate;
285 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
286 m_attach_or_wait_reply = eLazyBoolCalculate;
287 m_avoid_g_packets = eLazyBoolCalculate;
288 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
289 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
290 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
291 m_supports_qXfer_features_read = eLazyBoolCalculate;
292 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
293 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_qProcessInfoPID = true;
295 m_supports_qfProcessInfo = true;
296 m_supports_qUserName = true;
297 m_supports_qGroupName = true;
298 m_supports_qThreadStopInfo = true;
299 m_supports_z0 = true;
300 m_supports_z1 = true;
301 m_supports_z2 = true;
302 m_supports_z3 = true;
303 m_supports_z4 = true;
304 m_supports_QEnvironment = true;
305 m_supports_QEnvironmentHexEncoded = true;
306 m_supports_qSymbol = true;
307 m_qSymbol_requests_done = false;
308 m_supports_qModuleInfo = true;
310 m_os_version = llvm::VersionTuple();
314 m_gdb_server_name.clear();
315 m_gdb_server_version = UINT32_MAX;
316 m_default_packet_timeout = seconds(0);
317 m_max_packet_size = 0;
318 m_qSupported_response.clear();
319 m_supported_async_json_packets_is_valid = false;
320 m_supported_async_json_packets_sp.reset();
321 m_supports_jModulesInfo = true;
324 // These flags should be reset when we first connect to a GDB server and when
325 // our inferior process execs
326 m_qProcessInfo_is_valid = eLazyBoolCalculate;
327 m_process_arch.Clear();
330 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
331 // Clear out any capabilities we expect to see in the qSupported response
332 m_supports_qXfer_auxv_read = eLazyBoolNo;
333 m_supports_qXfer_libraries_read = eLazyBoolNo;
334 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
335 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
336 m_supports_qXfer_features_read = eLazyBoolNo;
337 m_supports_qXfer_memory_map_read = eLazyBoolNo;
338 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
339 // not, we assume no limit
341 // build the qSupported packet
342 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc"};
344 packet.PutCString("qSupported");
345 for (uint32_t i = 0; i < features.size(); ++i) {
346 packet.PutCString(i == 0 ? ":" : ";");
347 packet.PutCString(features[i]);
350 StringExtractorGDBRemote response;
351 if (SendPacketAndWaitForResponse(packet.GetString(), response,
352 /*send_async=*/false) ==
353 PacketResult::Success) {
354 const char *response_cstr = response.GetStringRef().data();
356 // Hang on to the qSupported packet, so that platforms can do custom
357 // configuration of the transport before attaching/launching the process.
358 m_qSupported_response = response_cstr;
360 if (::strstr(response_cstr, "qXfer:auxv:read+"))
361 m_supports_qXfer_auxv_read = eLazyBoolYes;
362 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
363 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
364 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
365 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
366 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
368 if (::strstr(response_cstr, "qXfer:libraries:read+"))
369 m_supports_qXfer_libraries_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "qXfer:features:read+"))
371 m_supports_qXfer_features_read = eLazyBoolYes;
372 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
373 m_supports_qXfer_memory_map_read = eLazyBoolYes;
375 // Look for a list of compressions in the features list e.g.
376 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
378 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
380 const char *compressions =
381 ::strstr(features_list, "SupportedCompressions=");
383 std::vector<std::string> supported_compressions;
384 compressions += sizeof("SupportedCompressions=") - 1;
385 const char *end_of_compressions = strchr(compressions, ';');
386 if (end_of_compressions == nullptr) {
387 end_of_compressions = strchr(compressions, '\0');
389 const char *current_compression = compressions;
390 while (current_compression < end_of_compressions) {
391 const char *next_compression_name = strchr(current_compression, ',');
392 const char *end_of_this_word = next_compression_name;
393 if (next_compression_name == nullptr ||
394 end_of_compressions < next_compression_name) {
395 end_of_this_word = end_of_compressions;
398 if (end_of_this_word) {
399 if (end_of_this_word == current_compression) {
400 current_compression++;
402 std::string this_compression(
403 current_compression, end_of_this_word - current_compression);
404 supported_compressions.push_back(this_compression);
405 current_compression = end_of_this_word + 1;
408 supported_compressions.push_back(current_compression);
409 current_compression = end_of_compressions;
413 if (supported_compressions.size() > 0) {
414 MaybeEnableCompression(supported_compressions);
419 if (::strstr(response_cstr, "qEcho"))
420 m_supports_qEcho = eLazyBoolYes;
422 m_supports_qEcho = eLazyBoolNo;
424 if (::strstr(response_cstr, "QPassSignals+"))
425 m_supports_QPassSignals = eLazyBoolYes;
427 m_supports_QPassSignals = eLazyBoolNo;
429 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
430 if (packet_size_str) {
431 StringExtractorGDBRemote packet_response(packet_size_str +
432 strlen("PacketSize="));
434 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
435 if (m_max_packet_size == 0) {
436 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
438 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
439 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
445 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
446 if (m_supports_thread_suffix == eLazyBoolCalculate) {
447 StringExtractorGDBRemote response;
448 m_supports_thread_suffix = eLazyBoolNo;
449 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
450 false) == PacketResult::Success) {
451 if (response.IsOKResponse())
452 m_supports_thread_suffix = eLazyBoolYes;
455 return m_supports_thread_suffix;
457 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
458 if (m_supports_vCont_c == eLazyBoolCalculate) {
459 StringExtractorGDBRemote response;
460 m_supports_vCont_any = eLazyBoolNo;
461 m_supports_vCont_all = eLazyBoolNo;
462 m_supports_vCont_c = eLazyBoolNo;
463 m_supports_vCont_C = eLazyBoolNo;
464 m_supports_vCont_s = eLazyBoolNo;
465 m_supports_vCont_S = eLazyBoolNo;
466 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
467 PacketResult::Success) {
468 const char *response_cstr = response.GetStringRef().data();
469 if (::strstr(response_cstr, ";c"))
470 m_supports_vCont_c = eLazyBoolYes;
472 if (::strstr(response_cstr, ";C"))
473 m_supports_vCont_C = eLazyBoolYes;
475 if (::strstr(response_cstr, ";s"))
476 m_supports_vCont_s = eLazyBoolYes;
478 if (::strstr(response_cstr, ";S"))
479 m_supports_vCont_S = eLazyBoolYes;
481 if (m_supports_vCont_c == eLazyBoolYes &&
482 m_supports_vCont_C == eLazyBoolYes &&
483 m_supports_vCont_s == eLazyBoolYes &&
484 m_supports_vCont_S == eLazyBoolYes) {
485 m_supports_vCont_all = eLazyBoolYes;
488 if (m_supports_vCont_c == eLazyBoolYes ||
489 m_supports_vCont_C == eLazyBoolYes ||
490 m_supports_vCont_s == eLazyBoolYes ||
491 m_supports_vCont_S == eLazyBoolYes) {
492 m_supports_vCont_any = eLazyBoolYes;
499 return m_supports_vCont_any;
501 return m_supports_vCont_all;
503 return m_supports_vCont_c;
505 return m_supports_vCont_C;
507 return m_supports_vCont_s;
509 return m_supports_vCont_S;
516 GDBRemoteCommunication::PacketResult
517 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
518 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
520 Lock lock(*this, send_async);
522 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
523 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
525 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
527 __FUNCTION__, payload.GetData());
528 return PacketResult::ErrorNoSequenceLock;
531 if (GetThreadSuffixSupported())
532 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
534 if (!SetCurrentThread(tid))
535 return PacketResult::ErrorSendFailed;
538 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
541 // Check if the target supports 'p' packet. It sends out a 'p' packet and
542 // checks the response. A normal packet will tell us that support is available.
544 // Takes a valid thread ID because p needs to apply to a thread.
545 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
546 if (m_supports_p == eLazyBoolCalculate)
547 m_supports_p = GetThreadPacketSupported(tid, "p0");
551 LazyBool GDBRemoteCommunicationClient::GetThreadPacketSupported(
552 lldb::tid_t tid, llvm::StringRef packetStr) {
553 StreamString payload;
554 payload.PutCString(packetStr);
555 StringExtractorGDBRemote response;
556 if (SendThreadSpecificPacketAndWaitForResponse(
557 tid, std::move(payload), response, false) == PacketResult::Success &&
558 response.IsNormalResponse()) {
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 "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 llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() {
939 return m_maccatalyst_version;
942 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
944 if (!m_os_build.empty()) {
953 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
955 if (!m_os_kernel.empty()) {
964 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
966 if (!m_hostname.empty()) {
975 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
981 const lldb_private::ArchSpec &
982 GDBRemoteCommunicationClient::GetProcessArchitecture() {
983 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
984 GetCurrentProcessInfo();
985 return m_process_arch;
988 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
989 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
990 m_gdb_server_name.clear();
991 m_gdb_server_version = 0;
992 m_qGDBServerVersion_is_valid = eLazyBoolNo;
994 StringExtractorGDBRemote response;
995 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
996 PacketResult::Success) {
997 if (response.IsNormalResponse()) {
998 llvm::StringRef name, value;
999 bool success = false;
1000 while (response.GetNameColonValue(name, value)) {
1001 if (name.equals("name")) {
1003 m_gdb_server_name = value;
1004 } else if (name.equals("version")) {
1005 llvm::StringRef major, minor;
1006 std::tie(major, minor) = value.split('.');
1007 if (!major.getAsInteger(0, m_gdb_server_version))
1012 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1016 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1019 void GDBRemoteCommunicationClient::MaybeEnableCompression(
1020 std::vector<std::string> supported_compressions) {
1021 CompressionType avail_type = CompressionType::None;
1022 std::string avail_name;
1024 #if defined(HAVE_LIBCOMPRESSION)
1025 if (avail_type == CompressionType::None) {
1026 for (auto compression : supported_compressions) {
1027 if (compression == "lzfse") {
1028 avail_type = CompressionType::LZFSE;
1029 avail_name = compression;
1036 #if defined(HAVE_LIBCOMPRESSION)
1037 if (avail_type == CompressionType::None) {
1038 for (auto compression : supported_compressions) {
1039 if (compression == "zlib-deflate") {
1040 avail_type = CompressionType::ZlibDeflate;
1041 avail_name = compression;
1048 #if defined(HAVE_LIBZ)
1049 if (avail_type == CompressionType::None) {
1050 for (auto compression : supported_compressions) {
1051 if (compression == "zlib-deflate") {
1052 avail_type = CompressionType::ZlibDeflate;
1053 avail_name = compression;
1060 #if defined(HAVE_LIBCOMPRESSION)
1061 if (avail_type == CompressionType::None) {
1062 for (auto compression : supported_compressions) {
1063 if (compression == "lz4") {
1064 avail_type = CompressionType::LZ4;
1065 avail_name = compression;
1072 #if defined(HAVE_LIBCOMPRESSION)
1073 if (avail_type == CompressionType::None) {
1074 for (auto compression : supported_compressions) {
1075 if (compression == "lzma") {
1076 avail_type = CompressionType::LZMA;
1077 avail_name = compression;
1084 if (avail_type != CompressionType::None) {
1085 StringExtractorGDBRemote response;
1086 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1087 if (SendPacketAndWaitForResponse(packet, response, false) !=
1088 PacketResult::Success)
1091 if (response.IsOKResponse()) {
1092 m_compression_type = avail_type;
1097 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1098 if (GetGDBServerVersion()) {
1099 if (!m_gdb_server_name.empty())
1100 return m_gdb_server_name.c_str();
1105 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1106 if (GetGDBServerVersion())
1107 return m_gdb_server_version;
1111 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1112 StringExtractorGDBRemote response;
1113 if (SendPacketAndWaitForResponse("qC", response, false) !=
1114 PacketResult::Success)
1117 if (!response.IsNormalResponse())
1120 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1121 tid = response.GetHexMaxU32(true, -1);
1126 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1127 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1129 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1130 // host info computation can require DNS traffic and shelling out to external processes.
1131 // Increase the timeout to account for that.
1132 ScopedTimeout timeout(*this, seconds(10));
1133 m_qHostInfo_is_valid = eLazyBoolNo;
1134 StringExtractorGDBRemote response;
1135 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1136 PacketResult::Success) {
1137 if (response.IsNormalResponse()) {
1138 llvm::StringRef name;
1139 llvm::StringRef value;
1140 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1142 std::string arch_name;
1143 std::string os_name;
1144 std::string environment;
1145 std::string vendor_name;
1147 std::string distribution_id;
1148 uint32_t pointer_byte_size = 0;
1149 ByteOrder byte_order = eByteOrderInvalid;
1150 uint32_t num_keys_decoded = 0;
1151 while (response.GetNameColonValue(name, value)) {
1152 if (name.equals("cputype")) {
1153 // exception type in big endian hex
1154 if (!value.getAsInteger(0, cpu))
1156 } else if (name.equals("cpusubtype")) {
1157 // exception count in big endian hex
1158 if (!value.getAsInteger(0, sub))
1160 } else if (name.equals("arch")) {
1163 } else if (name.equals("triple")) {
1164 StringExtractor extractor(value);
1165 extractor.GetHexByteString(triple);
1167 } else if (name.equals("distribution_id")) {
1168 StringExtractor extractor(value);
1169 extractor.GetHexByteString(distribution_id);
1171 } else if (name.equals("os_build")) {
1172 StringExtractor extractor(value);
1173 extractor.GetHexByteString(m_os_build);
1175 } else if (name.equals("hostname")) {
1176 StringExtractor extractor(value);
1177 extractor.GetHexByteString(m_hostname);
1179 } else if (name.equals("os_kernel")) {
1180 StringExtractor extractor(value);
1181 extractor.GetHexByteString(m_os_kernel);
1183 } else if (name.equals("ostype")) {
1184 if (value.equals("maccatalyst")) {
1186 environment = "macabi";
1190 } else if (name.equals("vendor")) {
1191 vendor_name = value;
1193 } else if (name.equals("endian")) {
1194 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1195 .Case("little", eByteOrderLittle)
1196 .Case("big", eByteOrderBig)
1197 .Case("pdp", eByteOrderPDP)
1198 .Default(eByteOrderInvalid);
1199 if (byte_order != eByteOrderInvalid)
1201 } else if (name.equals("ptrsize")) {
1202 if (!value.getAsInteger(0, pointer_byte_size))
1204 } else if (name.equals("os_version") ||
1206 "version")) // Older debugserver binaries used the
1207 // "version" key instead of
1210 if (!m_os_version.tryParse(value))
1212 } else if (name.equals("maccatalyst_version")) {
1213 if (!m_maccatalyst_version.tryParse(value))
1215 } else if (name.equals("watchpoint_exceptions_received")) {
1216 m_watchpoints_trigger_after_instruction =
1217 llvm::StringSwitch<LazyBool>(value)
1218 .Case("before", eLazyBoolNo)
1219 .Case("after", eLazyBoolYes)
1220 .Default(eLazyBoolCalculate);
1221 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1223 } else if (name.equals("default_packet_timeout")) {
1224 uint32_t timeout_seconds;
1225 if (!value.getAsInteger(0, timeout_seconds)) {
1226 m_default_packet_timeout = seconds(timeout_seconds);
1227 SetPacketTimeout(m_default_packet_timeout);
1233 if (num_keys_decoded > 0)
1234 m_qHostInfo_is_valid = eLazyBoolYes;
1236 if (triple.empty()) {
1237 if (arch_name.empty()) {
1238 if (cpu != LLDB_INVALID_CPUTYPE) {
1239 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1240 if (pointer_byte_size) {
1241 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1243 if (byte_order != eByteOrderInvalid) {
1244 assert(byte_order == m_host_arch.GetByteOrder());
1247 if (!vendor_name.empty())
1248 m_host_arch.GetTriple().setVendorName(
1249 llvm::StringRef(vendor_name));
1250 if (!os_name.empty())
1251 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1252 if (!environment.empty())
1253 m_host_arch.GetTriple().setEnvironmentName(environment);
1257 triple += arch_name;
1258 if (!vendor_name.empty() || !os_name.empty()) {
1260 if (vendor_name.empty())
1261 triple += "unknown";
1263 triple += vendor_name;
1265 if (os_name.empty())
1266 triple += "unknown";
1270 m_host_arch.SetTriple(triple.c_str());
1272 llvm::Triple &host_triple = m_host_arch.GetTriple();
1273 if (host_triple.getVendor() == llvm::Triple::Apple &&
1274 host_triple.getOS() == llvm::Triple::Darwin) {
1275 switch (m_host_arch.GetMachine()) {
1276 case llvm::Triple::aarch64:
1277 case llvm::Triple::aarch64_32:
1278 case llvm::Triple::arm:
1279 case llvm::Triple::thumb:
1280 host_triple.setOS(llvm::Triple::IOS);
1283 host_triple.setOS(llvm::Triple::MacOSX);
1287 if (pointer_byte_size) {
1288 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1290 if (byte_order != eByteOrderInvalid) {
1291 assert(byte_order == m_host_arch.GetByteOrder());
1295 m_host_arch.SetTriple(triple.c_str());
1296 if (pointer_byte_size) {
1297 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1299 if (byte_order != eByteOrderInvalid) {
1300 assert(byte_order == m_host_arch.GetByteOrder());
1304 "GDBRemoteCommunicationClient::%s parsed host "
1305 "architecture as %s, triple as %s from triple text %s",
1307 m_host_arch.GetArchitectureName()
1308 ? m_host_arch.GetArchitectureName()
1309 : "<null-arch-name>",
1310 m_host_arch.GetTriple().getTriple().c_str(),
1313 if (!distribution_id.empty())
1314 m_host_arch.SetDistributionId(distribution_id.c_str());
1318 return m_qHostInfo_is_valid == eLazyBoolYes;
1321 int GDBRemoteCommunicationClient::SendAttach(
1322 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1323 if (pid != LLDB_INVALID_PROCESS_ID) {
1325 const int packet_len =
1326 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1327 UNUSED_IF_ASSERT_DISABLED(packet_len);
1328 assert(packet_len < (int)sizeof(packet));
1329 if (SendPacketAndWaitForResponse(packet, response, false) ==
1330 PacketResult::Success) {
1331 if (response.IsErrorResponse())
1332 return response.GetError();
1339 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1341 StreamString packet;
1342 packet.PutCString("I");
1343 packet.PutBytesAsRawHex8(data, data_len);
1344 StringExtractorGDBRemote response;
1345 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1346 PacketResult::Success) {
1349 return response.GetError();
1352 const lldb_private::ArchSpec &
1353 GDBRemoteCommunicationClient::GetHostArchitecture() {
1354 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1359 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1360 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1362 return m_default_packet_timeout;
1365 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1366 uint32_t permissions) {
1367 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1368 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1370 const int packet_len = ::snprintf(
1371 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1372 permissions & lldb::ePermissionsReadable ? "r" : "",
1373 permissions & lldb::ePermissionsWritable ? "w" : "",
1374 permissions & lldb::ePermissionsExecutable ? "x" : "");
1375 assert(packet_len < (int)sizeof(packet));
1376 UNUSED_IF_ASSERT_DISABLED(packet_len);
1377 StringExtractorGDBRemote response;
1378 if (SendPacketAndWaitForResponse(packet, response, false) ==
1379 PacketResult::Success) {
1380 if (response.IsUnsupportedResponse())
1381 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1382 else if (!response.IsErrorResponse())
1383 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1385 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1388 return LLDB_INVALID_ADDRESS;
1391 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1392 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1393 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1395 const int packet_len =
1396 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1397 assert(packet_len < (int)sizeof(packet));
1398 UNUSED_IF_ASSERT_DISABLED(packet_len);
1399 StringExtractorGDBRemote response;
1400 if (SendPacketAndWaitForResponse(packet, response, false) ==
1401 PacketResult::Success) {
1402 if (response.IsUnsupportedResponse())
1403 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1404 else if (response.IsOKResponse())
1407 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1413 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1417 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1419 const int packet_len =
1420 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1421 assert(packet_len < (int)sizeof(packet));
1422 UNUSED_IF_ASSERT_DISABLED(packet_len);
1423 StringExtractorGDBRemote response;
1424 if (SendPacketAndWaitForResponse(packet, response, false) ==
1425 PacketResult::Success &&
1426 response.IsOKResponse()) {
1427 m_supports_detach_stay_stopped = eLazyBoolYes;
1429 m_supports_detach_stay_stopped = eLazyBoolNo;
1433 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1434 error.SetErrorString("Stays stopped not supported by this target.");
1437 StringExtractorGDBRemote response;
1438 PacketResult packet_result =
1439 SendPacketAndWaitForResponse("D1", response, false);
1440 if (packet_result != PacketResult::Success)
1441 error.SetErrorString("Sending extended disconnect packet failed.");
1444 StringExtractorGDBRemote response;
1445 PacketResult packet_result =
1446 SendPacketAndWaitForResponse("D", response, false);
1447 if (packet_result != PacketResult::Success)
1448 error.SetErrorString("Sending disconnect packet failed.");
1453 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1454 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1456 region_info.Clear();
1458 if (m_supports_memory_region_info != eLazyBoolNo) {
1459 m_supports_memory_region_info = eLazyBoolYes;
1461 const int packet_len = ::snprintf(
1462 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1463 assert(packet_len < (int)sizeof(packet));
1464 UNUSED_IF_ASSERT_DISABLED(packet_len);
1465 StringExtractorGDBRemote response;
1466 if (SendPacketAndWaitForResponse(packet, response, false) ==
1467 PacketResult::Success &&
1468 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
1469 llvm::StringRef name;
1470 llvm::StringRef value;
1471 addr_t addr_value = LLDB_INVALID_ADDRESS;
1472 bool success = true;
1473 bool saw_permissions = false;
1474 while (success && response.GetNameColonValue(name, value)) {
1475 if (name.equals("start")) {
1476 if (!value.getAsInteger(16, addr_value))
1477 region_info.GetRange().SetRangeBase(addr_value);
1478 } else if (name.equals("size")) {
1479 if (!value.getAsInteger(16, addr_value))
1480 region_info.GetRange().SetByteSize(addr_value);
1481 } else if (name.equals("permissions") &&
1482 region_info.GetRange().IsValid()) {
1483 saw_permissions = true;
1484 if (region_info.GetRange().Contains(addr)) {
1485 if (value.find('r') != llvm::StringRef::npos)
1486 region_info.SetReadable(MemoryRegionInfo::eYes);
1488 region_info.SetReadable(MemoryRegionInfo::eNo);
1490 if (value.find('w') != llvm::StringRef::npos)
1491 region_info.SetWritable(MemoryRegionInfo::eYes);
1493 region_info.SetWritable(MemoryRegionInfo::eNo);
1495 if (value.find('x') != llvm::StringRef::npos)
1496 region_info.SetExecutable(MemoryRegionInfo::eYes);
1498 region_info.SetExecutable(MemoryRegionInfo::eNo);
1500 region_info.SetMapped(MemoryRegionInfo::eYes);
1502 // The reported region does not contain this address -- we're
1503 // looking at an unmapped page
1504 region_info.SetReadable(MemoryRegionInfo::eNo);
1505 region_info.SetWritable(MemoryRegionInfo::eNo);
1506 region_info.SetExecutable(MemoryRegionInfo::eNo);
1507 region_info.SetMapped(MemoryRegionInfo::eNo);
1509 } else if (name.equals("name")) {
1510 StringExtractorGDBRemote name_extractor(value);
1512 name_extractor.GetHexByteString(name);
1513 region_info.SetName(name.c_str());
1514 } else if (name.equals("error")) {
1515 StringExtractorGDBRemote error_extractor(value);
1516 std::string error_string;
1517 // Now convert the HEX bytes into a string value
1518 error_extractor.GetHexByteString(error_string);
1519 error.SetErrorString(error_string.c_str());
1523 if (region_info.GetRange().IsValid()) {
1524 // We got a valid address range back but no permissions -- which means
1525 // this is an unmapped page
1526 if (!saw_permissions) {
1527 region_info.SetReadable(MemoryRegionInfo::eNo);
1528 region_info.SetWritable(MemoryRegionInfo::eNo);
1529 region_info.SetExecutable(MemoryRegionInfo::eNo);
1530 region_info.SetMapped(MemoryRegionInfo::eNo);
1533 // We got an invalid address range back
1534 error.SetErrorString("Server returned invalid range");
1537 m_supports_memory_region_info = eLazyBoolNo;
1541 if (m_supports_memory_region_info == eLazyBoolNo) {
1542 error.SetErrorString("qMemoryRegionInfo is not supported");
1545 // Try qXfer:memory-map:read to get region information not included in
1546 // qMemoryRegionInfo
1547 MemoryRegionInfo qXfer_region_info;
1548 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1551 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1552 // the qXfer result as a fallback
1553 if (qXfer_error.Success()) {
1554 region_info = qXfer_region_info;
1557 region_info.Clear();
1559 } else if (qXfer_error.Success()) {
1560 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1561 // both regions are the same range, update the result to include the flash-
1562 // memory information that is specific to the qXfer result.
1563 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1564 region_info.SetFlash(qXfer_region_info.GetFlash());
1565 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1571 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1572 lldb::addr_t addr, MemoryRegionInfo ®ion) {
1573 Status error = LoadQXferMemoryMap();
1574 if (!error.Success())
1576 for (const auto &map_region : m_qXfer_memory_map) {
1577 if (map_region.GetRange().Contains(addr)) {
1578 region = map_region;
1582 error.SetErrorString("Region not found");
1586 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1590 if (m_qXfer_memory_map_loaded)
1591 // Already loaded, return success
1594 if (!XMLDocument::XMLEnabled()) {
1595 error.SetErrorString("XML is not supported");
1599 if (!GetQXferMemoryMapReadSupported()) {
1600 error.SetErrorString("Memory map is not supported");
1605 lldb_private::Status lldberr;
1606 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1608 error.SetErrorString("Failed to read memory map");
1612 XMLDocument xml_document;
1614 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1615 error.SetErrorString("Failed to parse memory map xml");
1619 XMLNode map_node = xml_document.GetRootElement("memory-map");
1621 error.SetErrorString("Invalid root node in memory map xml");
1625 m_qXfer_memory_map.clear();
1627 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1628 if (!memory_node.IsElement())
1630 if (memory_node.GetName() != "memory")
1632 auto type = memory_node.GetAttributeValue("type", "");
1635 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1637 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1639 MemoryRegionInfo region;
1640 region.GetRange().SetRangeBase(start);
1641 region.GetRange().SetByteSize(length);
1642 if (type == "rom") {
1643 region.SetReadable(MemoryRegionInfo::eYes);
1644 this->m_qXfer_memory_map.push_back(region);
1645 } else if (type == "ram") {
1646 region.SetReadable(MemoryRegionInfo::eYes);
1647 region.SetWritable(MemoryRegionInfo::eYes);
1648 this->m_qXfer_memory_map.push_back(region);
1649 } else if (type == "flash") {
1650 region.SetFlash(MemoryRegionInfo::eYes);
1651 memory_node.ForEachChildElement(
1652 [®ion](const XMLNode &prop_node) -> bool {
1653 if (!prop_node.IsElement())
1655 if (prop_node.GetName() != "property")
1657 auto propname = prop_node.GetAttributeValue("name", "");
1658 if (propname == "blocksize") {
1660 if (prop_node.GetElementTextAsUnsigned(blocksize))
1661 region.SetBlocksize(blocksize);
1665 this->m_qXfer_memory_map.push_back(region);
1670 m_qXfer_memory_map_loaded = true;
1675 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1678 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1679 num = m_num_supported_hardware_watchpoints;
1683 // Set num to 0 first.
1685 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1687 const int packet_len =
1688 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1689 assert(packet_len < (int)sizeof(packet));
1690 UNUSED_IF_ASSERT_DISABLED(packet_len);
1691 StringExtractorGDBRemote response;
1692 if (SendPacketAndWaitForResponse(packet, response, false) ==
1693 PacketResult::Success) {
1694 m_supports_watchpoint_support_info = eLazyBoolYes;
1695 llvm::StringRef name;
1696 llvm::StringRef value;
1697 bool found_num_field = false;
1698 while (response.GetNameColonValue(name, value)) {
1699 if (name.equals("num")) {
1700 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1701 num = m_num_supported_hardware_watchpoints;
1702 found_num_field = true;
1705 if (!found_num_field) {
1706 m_supports_watchpoint_support_info = eLazyBoolNo;
1709 m_supports_watchpoint_support_info = eLazyBoolNo;
1713 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1714 error.SetErrorString("qWatchpointSupportInfo is not supported");
1719 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1720 uint32_t &num, bool &after, const ArchSpec &arch) {
1721 Status error(GetWatchpointSupportInfo(num));
1722 if (error.Success())
1723 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1727 lldb_private::Status
1728 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1729 bool &after, const ArchSpec &arch) {
1731 llvm::Triple triple = arch.GetTriple();
1733 // we assume watchpoints will happen after running the relevant opcode and we
1734 // only want to override this behavior if we have explicitly received a
1735 // qHostInfo telling us otherwise
1736 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1737 // On targets like MIPS and ppc64, watchpoint exceptions are always
1738 // generated before the instruction is executed. The connected target may
1739 // not support qHostInfo or qWatchpointSupportInfo packets.
1740 after = !(triple.isMIPS() || triple.isPPC64());
1742 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
1743 // eLazyBoolNo if it is not calculated before.
1744 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1745 (triple.isMIPS() || triple.isPPC64()))
1746 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1748 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1753 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1755 std::string path{file_spec.GetPath(false)};
1756 StreamString packet;
1757 packet.PutCString("QSetSTDIN:");
1758 packet.PutStringAsRawHex8(path);
1760 StringExtractorGDBRemote response;
1761 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1762 PacketResult::Success) {
1763 if (response.IsOKResponse())
1765 uint8_t error = response.GetError();
1773 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1775 std::string path{file_spec.GetPath(false)};
1776 StreamString packet;
1777 packet.PutCString("QSetSTDOUT:");
1778 packet.PutStringAsRawHex8(path);
1780 StringExtractorGDBRemote response;
1781 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1782 PacketResult::Success) {
1783 if (response.IsOKResponse())
1785 uint8_t error = response.GetError();
1793 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1795 std::string path{file_spec.GetPath(false)};
1796 StreamString packet;
1797 packet.PutCString("QSetSTDERR:");
1798 packet.PutStringAsRawHex8(path);
1800 StringExtractorGDBRemote response;
1801 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1802 PacketResult::Success) {
1803 if (response.IsOKResponse())
1805 uint8_t error = response.GetError();
1813 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1814 StringExtractorGDBRemote response;
1815 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1816 PacketResult::Success) {
1817 if (response.IsUnsupportedResponse())
1819 if (response.IsErrorResponse())
1822 response.GetHexByteString(cwd);
1823 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1824 return !cwd.empty();
1829 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1831 std::string path{working_dir.GetPath(false)};
1832 StreamString packet;
1833 packet.PutCString("QSetWorkingDir:");
1834 packet.PutStringAsRawHex8(path);
1836 StringExtractorGDBRemote response;
1837 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1838 PacketResult::Success) {
1839 if (response.IsOKResponse())
1841 uint8_t error = response.GetError();
1849 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1851 const int packet_len =
1852 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1853 assert(packet_len < (int)sizeof(packet));
1854 UNUSED_IF_ASSERT_DISABLED(packet_len);
1855 StringExtractorGDBRemote response;
1856 if (SendPacketAndWaitForResponse(packet, response, false) ==
1857 PacketResult::Success) {
1858 if (response.IsOKResponse())
1860 uint8_t error = response.GetError();
1867 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1869 const int packet_len = ::snprintf(packet, sizeof(packet),
1870 "QSetDetachOnError:%i", enable ? 1 : 0);
1871 assert(packet_len < (int)sizeof(packet));
1872 UNUSED_IF_ASSERT_DISABLED(packet_len);
1873 StringExtractorGDBRemote response;
1874 if (SendPacketAndWaitForResponse(packet, response, false) ==
1875 PacketResult::Success) {
1876 if (response.IsOKResponse())
1878 uint8_t error = response.GetError();
1885 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1886 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1887 if (response.IsNormalResponse()) {
1888 llvm::StringRef name;
1889 llvm::StringRef value;
1890 StringExtractor extractor;
1892 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1895 std::string os_type;
1897 while (response.GetNameColonValue(name, value)) {
1898 if (name.equals("pid")) {
1899 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1900 value.getAsInteger(0, pid);
1901 process_info.SetProcessID(pid);
1902 } else if (name.equals("ppid")) {
1903 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1904 value.getAsInteger(0, pid);
1905 process_info.SetParentProcessID(pid);
1906 } else if (name.equals("uid")) {
1907 uint32_t uid = UINT32_MAX;
1908 value.getAsInteger(0, uid);
1909 process_info.SetUserID(uid);
1910 } else if (name.equals("euid")) {
1911 uint32_t uid = UINT32_MAX;
1912 value.getAsInteger(0, uid);
1913 process_info.SetEffectiveUserID(uid);
1914 } else if (name.equals("gid")) {
1915 uint32_t gid = UINT32_MAX;
1916 value.getAsInteger(0, gid);
1917 process_info.SetGroupID(gid);
1918 } else if (name.equals("egid")) {
1919 uint32_t gid = UINT32_MAX;
1920 value.getAsInteger(0, gid);
1921 process_info.SetEffectiveGroupID(gid);
1922 } else if (name.equals("triple")) {
1923 StringExtractor extractor(value);
1925 extractor.GetHexByteString(triple);
1926 process_info.GetArchitecture().SetTriple(triple.c_str());
1927 } else if (name.equals("name")) {
1928 StringExtractor extractor(value);
1929 // The process name from ASCII hex bytes since we can't control the
1930 // characters in a process name
1932 extractor.GetHexByteString(name);
1933 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
1934 } else if (name.equals("args")) {
1935 llvm::StringRef encoded_args(value), hex_arg;
1937 bool is_arg0 = true;
1938 while (!encoded_args.empty()) {
1939 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
1941 StringExtractor extractor(hex_arg);
1942 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
1943 // In case of wrong encoding, we discard all the arguments
1944 process_info.GetArguments().Clear();
1945 process_info.SetArg0("");
1949 process_info.SetArg0(arg);
1951 process_info.GetArguments().AppendArgument(arg);
1954 } else if (name.equals("cputype")) {
1955 value.getAsInteger(0, cpu);
1956 } else if (name.equals("cpusubtype")) {
1957 value.getAsInteger(0, sub);
1958 } else if (name.equals("vendor")) {
1960 } else if (name.equals("ostype")) {
1965 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1966 if (vendor == "apple") {
1967 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1969 process_info.GetArchitecture().GetTriple().setVendorName(
1970 llvm::StringRef(vendor));
1971 process_info.GetArchitecture().GetTriple().setOSName(
1972 llvm::StringRef(os_type));
1976 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1982 bool GDBRemoteCommunicationClient::GetProcessInfo(
1983 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1984 process_info.Clear();
1986 if (m_supports_qProcessInfoPID) {
1988 const int packet_len =
1989 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1990 assert(packet_len < (int)sizeof(packet));
1991 UNUSED_IF_ASSERT_DISABLED(packet_len);
1992 StringExtractorGDBRemote response;
1993 if (SendPacketAndWaitForResponse(packet, response, false) ==
1994 PacketResult::Success) {
1995 return DecodeProcessInfoResponse(response, process_info);
1997 m_supports_qProcessInfoPID = false;
2004 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
2005 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2009 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2011 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2017 StringExtractorGDBRemote response;
2018 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
2019 PacketResult::Success) {
2020 if (response.IsNormalResponse()) {
2021 llvm::StringRef name;
2022 llvm::StringRef value;
2023 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2025 std::string arch_name;
2026 std::string os_name;
2027 std::string environment;
2028 std::string vendor_name;
2030 std::string elf_abi;
2031 uint32_t pointer_byte_size = 0;
2032 StringExtractor extractor;
2033 ByteOrder byte_order = eByteOrderInvalid;
2034 uint32_t num_keys_decoded = 0;
2035 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2036 while (response.GetNameColonValue(name, value)) {
2037 if (name.equals("cputype")) {
2038 if (!value.getAsInteger(16, cpu))
2040 } else if (name.equals("cpusubtype")) {
2041 if (!value.getAsInteger(16, sub))
2043 } else if (name.equals("triple")) {
2044 StringExtractor extractor(value);
2045 extractor.GetHexByteString(triple);
2047 } else if (name.equals("ostype")) {
2048 if (value.equals("maccatalyst")) {
2050 environment = "macabi";
2054 } else if (name.equals("vendor")) {
2055 vendor_name = value;
2057 } else if (name.equals("endian")) {
2058 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2059 .Case("little", eByteOrderLittle)
2060 .Case("big", eByteOrderBig)
2061 .Case("pdp", eByteOrderPDP)
2062 .Default(eByteOrderInvalid);
2063 if (byte_order != eByteOrderInvalid)
2065 } else if (name.equals("ptrsize")) {
2066 if (!value.getAsInteger(16, pointer_byte_size))
2068 } else if (name.equals("pid")) {
2069 if (!value.getAsInteger(16, pid))
2071 } else if (name.equals("elf_abi")) {
2076 if (num_keys_decoded > 0)
2077 m_qProcessInfo_is_valid = eLazyBoolYes;
2078 if (pid != LLDB_INVALID_PROCESS_ID) {
2079 m_curr_pid_is_valid = eLazyBoolYes;
2083 // Set the ArchSpec from the triple if we have it.
2084 if (!triple.empty()) {
2085 m_process_arch.SetTriple(triple.c_str());
2086 m_process_arch.SetFlags(elf_abi);
2087 if (pointer_byte_size) {
2088 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2090 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2091 !vendor_name.empty()) {
2092 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2093 if (!environment.empty())
2094 triple.setEnvironmentName(environment);
2096 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2097 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2098 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2099 switch (triple.getObjectFormat()) {
2100 case llvm::Triple::MachO:
2101 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2103 case llvm::Triple::ELF:
2104 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2106 case llvm::Triple::COFF:
2107 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2109 case llvm::Triple::Wasm:
2110 case llvm::Triple::XCOFF:
2111 LLDB_LOGF(log, "error: not supported target architecture");
2113 case llvm::Triple::UnknownObjectFormat:
2114 LLDB_LOGF(log, "error: failed to determine target architecture");
2118 if (pointer_byte_size) {
2119 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2121 if (byte_order != eByteOrderInvalid) {
2122 assert(byte_order == m_process_arch.GetByteOrder());
2124 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2125 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2126 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2127 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2128 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2129 m_host_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2134 m_qProcessInfo_is_valid = eLazyBoolNo;
2140 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2141 const ProcessInstanceInfoMatch &match_info,
2142 ProcessInstanceInfoList &process_infos) {
2143 process_infos.Clear();
2145 if (m_supports_qfProcessInfo) {
2146 StreamString packet;
2147 packet.PutCString("qfProcessInfo");
2148 if (!match_info.MatchAllProcesses()) {
2149 packet.PutChar(':');
2150 const char *name = match_info.GetProcessInfo().GetName();
2151 bool has_name_match = false;
2152 if (name && name[0]) {
2153 has_name_match = true;
2154 NameMatch name_match_type = match_info.GetNameMatchType();
2155 switch (name_match_type) {
2156 case NameMatch::Ignore:
2157 has_name_match = false;
2160 case NameMatch::Equals:
2161 packet.PutCString("name_match:equals;");
2164 case NameMatch::Contains:
2165 packet.PutCString("name_match:contains;");
2168 case NameMatch::StartsWith:
2169 packet.PutCString("name_match:starts_with;");
2172 case NameMatch::EndsWith:
2173 packet.PutCString("name_match:ends_with;");
2176 case NameMatch::RegularExpression:
2177 packet.PutCString("name_match:regex;");
2180 if (has_name_match) {
2181 packet.PutCString("name:");
2182 packet.PutBytesAsRawHex8(name, ::strlen(name));
2183 packet.PutChar(';');
2187 if (match_info.GetProcessInfo().ProcessIDIsValid())
2188 packet.Printf("pid:%" PRIu64 ";",
2189 match_info.GetProcessInfo().GetProcessID());
2190 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2191 packet.Printf("parent_pid:%" PRIu64 ";",
2192 match_info.GetProcessInfo().GetParentProcessID());
2193 if (match_info.GetProcessInfo().UserIDIsValid())
2194 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2195 if (match_info.GetProcessInfo().GroupIDIsValid())
2196 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2197 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2198 packet.Printf("euid:%u;",
2199 match_info.GetProcessInfo().GetEffectiveUserID());
2200 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2201 packet.Printf("egid:%u;",
2202 match_info.GetProcessInfo().GetEffectiveGroupID());
2203 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2204 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2205 const ArchSpec &match_arch =
2206 match_info.GetProcessInfo().GetArchitecture();
2207 const llvm::Triple &triple = match_arch.GetTriple();
2208 packet.PutCString("triple:");
2209 packet.PutCString(triple.getTriple());
2210 packet.PutChar(';');
2213 StringExtractorGDBRemote response;
2214 // Increase timeout as the first qfProcessInfo packet takes a long time on
2215 // Android. The value of 1min was arrived at empirically.
2216 ScopedTimeout timeout(*this, minutes(1));
2217 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2218 PacketResult::Success) {
2220 ProcessInstanceInfo process_info;
2221 if (!DecodeProcessInfoResponse(response, process_info))
2223 process_infos.Append(process_info);
2224 response = StringExtractorGDBRemote();
2225 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2226 PacketResult::Success);
2228 m_supports_qfProcessInfo = false;
2232 return process_infos.GetSize();
2235 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2236 std::string &name) {
2237 if (m_supports_qUserName) {
2239 const int packet_len =
2240 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2241 assert(packet_len < (int)sizeof(packet));
2242 UNUSED_IF_ASSERT_DISABLED(packet_len);
2243 StringExtractorGDBRemote response;
2244 if (SendPacketAndWaitForResponse(packet, response, false) ==
2245 PacketResult::Success) {
2246 if (response.IsNormalResponse()) {
2247 // Make sure we parsed the right number of characters. The response is
2248 // the hex encoded user name and should make up the entire packet. If
2249 // there are any non-hex ASCII bytes, the length won't match below..
2250 if (response.GetHexByteString(name) * 2 ==
2251 response.GetStringRef().size())
2255 m_supports_qUserName = false;
2262 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2263 std::string &name) {
2264 if (m_supports_qGroupName) {
2266 const int packet_len =
2267 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2268 assert(packet_len < (int)sizeof(packet));
2269 UNUSED_IF_ASSERT_DISABLED(packet_len);
2270 StringExtractorGDBRemote response;
2271 if (SendPacketAndWaitForResponse(packet, response, false) ==
2272 PacketResult::Success) {
2273 if (response.IsNormalResponse()) {
2274 // Make sure we parsed the right number of characters. The response is
2275 // the hex encoded group name and should make up the entire packet. If
2276 // there are any non-hex ASCII bytes, the length won't match below..
2277 if (response.GetHexByteString(name) * 2 ==
2278 response.GetStringRef().size())
2282 m_supports_qGroupName = false;
2289 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2290 // Form non-stop packet request
2292 const int packet_len =
2293 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2294 assert(packet_len < (int)sizeof(packet));
2295 UNUSED_IF_ASSERT_DISABLED(packet_len);
2297 StringExtractorGDBRemote response;
2299 if (SendPacketAndWaitForResponse(packet, response, false) ==
2300 PacketResult::Success)
2301 if (response.IsOKResponse())
2304 // Failed or not supported
2308 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2309 uint32_t recv_size) {
2311 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2312 uint32_t bytes_left = send_size;
2313 while (bytes_left > 0) {
2314 if (bytes_left >= 26) {
2315 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2318 packet.Printf("%*.*s;", bytes_left, bytes_left,
2319 "abcdefghijklmnopqrstuvwxyz");
2326 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2327 using Dur = duration<float>;
2328 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2329 Dur mean = sum / v.size();
2332 float delta = (d - mean).count();
2333 accum += delta * delta;
2336 return Dur(sqrtf(accum / (v.size() - 1)));
2339 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2342 uint64_t recv_amount,
2343 bool json, Stream &strm) {
2345 if (SendSpeedTestPacket(0, 0)) {
2346 StreamString packet;
2348 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2352 strm.Printf("Testing sending %u packets of various sizes:\n",
2356 uint32_t result_idx = 0;
2358 std::vector<duration<float>> packet_times;
2360 for (send_size = 0; send_size <= max_send;
2361 send_size ? send_size *= 2 : send_size = 4) {
2362 for (uint32_t recv_size = 0; recv_size <= max_recv;
2363 recv_size ? recv_size *= 2 : recv_size = 4) {
2364 MakeSpeedTestPacket(packet, send_size, recv_size);
2366 packet_times.clear();
2367 // Test how long it takes to send 'num_packets' packets
2368 const auto start_time = steady_clock::now();
2369 for (i = 0; i < num_packets; ++i) {
2370 const auto packet_start_time = steady_clock::now();
2371 StringExtractorGDBRemote response;
2372 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2373 const auto packet_end_time = steady_clock::now();
2374 packet_times.push_back(packet_end_time - packet_start_time);
2376 const auto end_time = steady_clock::now();
2377 const auto total_time = end_time - start_time;
2379 float packets_per_second =
2380 ((float)num_packets) / duration<float>(total_time).count();
2381 auto average_per_packet = total_time / num_packets;
2382 const duration<float> standard_deviation =
2383 calculate_standard_deviation(packet_times);
2385 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2386 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2387 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2388 result_idx > 0 ? "," : "", send_size, recv_size,
2389 total_time, standard_deviation);
2392 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2393 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2394 "standard deviation of {5,10:ms+f6}\n",
2395 send_size, recv_size, duration<float>(total_time),
2396 packets_per_second, duration<float>(average_per_packet),
2397 standard_deviation);
2403 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2405 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2406 ": %" PRIu64 ",\n \"results\" : [",
2409 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2415 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2416 MakeSpeedTestPacket(packet, send_size, recv_size);
2418 // If we have a receive size, test how long it takes to receive 4MB of
2420 if (recv_size > 0) {
2421 const auto start_time = steady_clock::now();
2422 uint32_t bytes_read = 0;
2423 uint32_t packet_count = 0;
2424 while (bytes_read < recv_amount) {
2425 StringExtractorGDBRemote response;
2426 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2427 bytes_read += recv_size;
2430 const auto end_time = steady_clock::now();
2431 const auto total_time = end_time - start_time;
2432 float mb_second = ((float)recv_amount) /
2433 duration<float>(total_time).count() /
2435 float packets_per_second =
2436 ((float)packet_count) / duration<float>(total_time).count();
2437 const auto average_per_packet = total_time / packet_count;
2440 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2441 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2442 result_idx > 0 ? "," : "", send_size, recv_size,
2446 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2447 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2448 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2449 send_size, recv_size, packet_count, k_recv_amount_mb,
2450 duration<float>(total_time), mb_second,
2451 packets_per_second, duration<float>(average_per_packet));
2457 strm.Printf("\n ]\n }\n}\n");
2463 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2464 uint32_t recv_size) {
2465 StreamString packet;
2466 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2467 uint32_t bytes_left = send_size;
2468 while (bytes_left > 0) {
2469 if (bytes_left >= 26) {
2470 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2473 packet.Printf("%*.*s;", bytes_left, bytes_left,
2474 "abcdefghijklmnopqrstuvwxyz");
2479 StringExtractorGDBRemote response;
2480 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2481 PacketResult::Success;
2484 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2485 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2486 std::string &socket_name) {
2487 pid = LLDB_INVALID_PROCESS_ID;
2489 socket_name.clear();
2491 StringExtractorGDBRemote response;
2492 StreamString stream;
2493 stream.PutCString("qLaunchGDBServer;");
2494 std::string hostname;
2495 if (remote_accept_hostname && remote_accept_hostname[0])
2496 hostname = remote_accept_hostname;
2498 if (HostInfo::GetHostname(hostname)) {
2499 // Make the GDB server we launch only accept connections from this host
2500 stream.Printf("host:%s;", hostname.c_str());
2502 // Make the GDB server we launch accept connections from any host since
2503 // we can't figure out the hostname
2504 stream.Printf("host:*;");
2507 // give the process a few seconds to startup
2508 ScopedTimeout timeout(*this, seconds(10));
2510 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2511 PacketResult::Success) {
2512 llvm::StringRef name;
2513 llvm::StringRef value;
2514 while (response.GetNameColonValue(name, value)) {
2515 if (name.equals("port"))
2516 value.getAsInteger(0, port);
2517 else if (name.equals("pid"))
2518 value.getAsInteger(0, pid);
2519 else if (name.compare("socket_name") == 0) {
2520 StringExtractor extractor(value);
2521 extractor.GetHexByteString(socket_name);
2529 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2530 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2531 connection_urls.clear();
2533 StringExtractorGDBRemote response;
2534 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2535 PacketResult::Success)
2538 StructuredData::ObjectSP data =
2539 StructuredData::ParseJSON(response.GetStringRef());
2543 StructuredData::Array *array = data->GetAsArray();
2547 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2548 StructuredData::Dictionary *element = nullptr;
2549 if (!array->GetItemAtIndexAsDictionary(i, element))
2553 if (StructuredData::ObjectSP port_osp =
2554 element->GetValueForKey(llvm::StringRef("port")))
2555 port = port_osp->GetIntegerValue(0);
2557 std::string socket_name;
2558 if (StructuredData::ObjectSP socket_name_osp =
2559 element->GetValueForKey(llvm::StringRef("socket_name")))
2560 socket_name = socket_name_osp->GetStringValue();
2562 if (port != 0 || !socket_name.empty())
2563 connection_urls.emplace_back(port, socket_name);
2565 return connection_urls.size();
2568 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2569 StreamString stream;
2570 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2572 StringExtractorGDBRemote response;
2573 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2574 PacketResult::Success) {
2575 if (response.IsOKResponse())
2581 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2582 if (m_curr_tid == tid)
2587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2590 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2591 assert(packet_len + 1 < (int)sizeof(packet));
2592 UNUSED_IF_ASSERT_DISABLED(packet_len);
2593 StringExtractorGDBRemote response;
2594 if (SendPacketAndWaitForResponse(packet, response, false) ==
2595 PacketResult::Success) {
2596 if (response.IsOKResponse()) {
2602 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2604 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2606 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2608 if (response.IsUnsupportedResponse() && IsConnected()) {
2616 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2617 if (m_curr_tid_run == tid)
2622 if (tid == UINT64_MAX)
2623 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2625 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2627 assert(packet_len + 1 < (int)sizeof(packet));
2628 UNUSED_IF_ASSERT_DISABLED(packet_len);
2629 StringExtractorGDBRemote response;
2630 if (SendPacketAndWaitForResponse(packet, response, false) ==
2631 PacketResult::Success) {
2632 if (response.IsOKResponse()) {
2633 m_curr_tid_run = tid;
2638 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2640 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2642 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2644 if (response.IsUnsupportedResponse() && IsConnected()) {
2652 bool GDBRemoteCommunicationClient::GetStopReply(
2653 StringExtractorGDBRemote &response) {
2654 if (SendPacketAndWaitForResponse("?", response, false) ==
2655 PacketResult::Success)
2656 return response.IsNormalResponse();
2660 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2661 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2662 if (m_supports_qThreadStopInfo) {
2665 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2666 assert(packet_len < (int)sizeof(packet));
2667 UNUSED_IF_ASSERT_DISABLED(packet_len);
2668 if (SendPacketAndWaitForResponse(packet, response, false) ==
2669 PacketResult::Success) {
2670 if (response.IsUnsupportedResponse())
2671 m_supports_qThreadStopInfo = false;
2672 else if (response.IsNormalResponse())
2677 m_supports_qThreadStopInfo = false;
2683 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2684 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2685 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2686 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2687 __FUNCTION__, insert ? "add" : "remove", addr);
2689 // Check if the stub is known not to support this breakpoint type
2690 if (!SupportsGDBStoppointPacket(type))
2692 // Construct the breakpoint packet
2694 const int packet_len =
2695 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2696 insert ? 'Z' : 'z', type, addr, length);
2697 // Check we haven't overwritten the end of the packet buffer
2698 assert(packet_len + 1 < (int)sizeof(packet));
2699 UNUSED_IF_ASSERT_DISABLED(packet_len);
2700 StringExtractorGDBRemote response;
2701 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2702 // or "" (unsupported)
2703 response.SetResponseValidatorToOKErrorNotSupported();
2704 // Try to send the breakpoint packet, and check that it was correctly sent
2705 if (SendPacketAndWaitForResponse(packet, response, true) ==
2706 PacketResult::Success) {
2707 // Receive and OK packet when the breakpoint successfully placed
2708 if (response.IsOKResponse())
2711 // Status while setting breakpoint, send back specific error
2712 if (response.IsErrorResponse())
2713 return response.GetError();
2715 // Empty packet informs us that breakpoint is not supported
2716 if (response.IsUnsupportedResponse()) {
2717 // Disable this breakpoint type since it is unsupported
2719 case eBreakpointSoftware:
2720 m_supports_z0 = false;
2722 case eBreakpointHardware:
2723 m_supports_z1 = false;
2725 case eWatchpointWrite:
2726 m_supports_z2 = false;
2728 case eWatchpointRead:
2729 m_supports_z3 = false;
2731 case eWatchpointReadWrite:
2732 m_supports_z4 = false;
2734 case eStoppointInvalid:
2739 // Signal generic failure
2743 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2744 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2747 Lock lock(*this, false);
2749 sequence_mutex_unavailable = false;
2750 StringExtractorGDBRemote response;
2752 PacketResult packet_result;
2753 for (packet_result =
2754 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2755 packet_result == PacketResult::Success && response.IsNormalResponse();
2757 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2758 char ch = response.GetChar();
2763 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2765 if (tid != LLDB_INVALID_THREAD_ID) {
2766 thread_ids.push_back(tid);
2768 ch = response.GetChar(); // Skip the command separator
2769 } while (ch == ','); // Make sure we got a comma separator
2774 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2775 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2777 * be as simple as 'S05'. There is no packet which can give us pid and/or
2779 * Assume pid=tid=1 in such cases.
2781 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2782 thread_ids.size() == 0 && IsConnected()) {
2783 thread_ids.push_back(1);
2786 #if !defined(LLDB_CONFIGURATION_DEBUG)
2787 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2789 LLDB_LOGF(log, "error: failed to get packet sequence mutex, not sending "
2790 "packet 'qfThreadInfo'");
2792 sequence_mutex_unavailable = true;
2794 return thread_ids.size();
2797 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2798 StringExtractorGDBRemote response;
2799 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2800 PacketResult::Success ||
2801 !response.IsNormalResponse())
2802 return LLDB_INVALID_ADDRESS;
2803 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2806 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2807 const char *command, // Shouldn't be NULL
2809 working_dir, // Pass empty FileSpec to use the current working directory
2810 int *status_ptr, // Pass NULL if you don't want the process exit status
2811 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2814 *command_output, // Pass NULL if you don't want the command output
2815 const Timeout<std::micro> &timeout) {
2816 lldb_private::StreamString stream;
2817 stream.PutCString("qPlatform_shell:");
2818 stream.PutBytesAsRawHex8(command, strlen(command));
2819 stream.PutChar(',');
2820 uint32_t timeout_sec = UINT32_MAX;
2822 // TODO: Use chrono version of std::ceil once c++17 is available.
2823 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2825 stream.PutHex32(timeout_sec);
2827 std::string path{working_dir.GetPath(false)};
2828 stream.PutChar(',');
2829 stream.PutStringAsRawHex8(path);
2831 StringExtractorGDBRemote response;
2832 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2833 PacketResult::Success) {
2834 if (response.GetChar() != 'F')
2835 return Status("malformed reply");
2836 if (response.GetChar() != ',')
2837 return Status("malformed reply");
2838 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2839 if (exitcode == UINT32_MAX)
2840 return Status("unable to run remote process");
2841 else if (status_ptr)
2842 *status_ptr = exitcode;
2843 if (response.GetChar() != ',')
2844 return Status("malformed reply");
2845 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2848 if (response.GetChar() != ',')
2849 return Status("malformed reply");
2851 response.GetEscapedBinaryData(output);
2853 command_output->assign(output);
2856 return Status("unable to send packet");
2859 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2860 uint32_t file_permissions) {
2861 std::string path{file_spec.GetPath(false)};
2862 lldb_private::StreamString stream;
2863 stream.PutCString("qPlatform_mkdir:");
2864 stream.PutHex32(file_permissions);
2865 stream.PutChar(',');
2866 stream.PutStringAsRawHex8(path);
2867 llvm::StringRef packet = stream.GetString();
2868 StringExtractorGDBRemote response;
2870 if (SendPacketAndWaitForResponse(packet, response, false) !=
2871 PacketResult::Success)
2872 return Status("failed to send '%s' packet", packet.str().c_str());
2874 if (response.GetChar() != 'F')
2875 return Status("invalid response to '%s' packet", packet.str().c_str());
2877 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2881 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2882 uint32_t file_permissions) {
2883 std::string path{file_spec.GetPath(false)};
2884 lldb_private::StreamString stream;
2885 stream.PutCString("qPlatform_chmod:");
2886 stream.PutHex32(file_permissions);
2887 stream.PutChar(',');
2888 stream.PutStringAsRawHex8(path);
2889 llvm::StringRef packet = stream.GetString();
2890 StringExtractorGDBRemote response;
2892 if (SendPacketAndWaitForResponse(packet, response, false) !=
2893 PacketResult::Success)
2894 return Status("failed to send '%s' packet", stream.GetData());
2896 if (response.GetChar() != 'F')
2897 return Status("invalid response to '%s' packet", stream.GetData());
2899 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2902 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2903 uint64_t fail_result, Status &error) {
2904 response.SetFilePos(0);
2905 if (response.GetChar() != 'F')
2907 int32_t result = response.GetS32(-2);
2910 if (response.GetChar() == ',') {
2911 int result_errno = response.GetS32(-2);
2912 if (result_errno != -2)
2913 error.SetError(result_errno, eErrorTypePOSIX);
2915 error.SetError(-1, eErrorTypeGeneric);
2921 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2922 File::OpenOptions flags, mode_t mode,
2924 std::string path(file_spec.GetPath(false));
2925 lldb_private::StreamString stream;
2926 stream.PutCString("vFile:open:");
2929 stream.PutStringAsRawHex8(path);
2930 stream.PutChar(',');
2931 stream.PutHex32(flags);
2932 stream.PutChar(',');
2933 stream.PutHex32(mode);
2934 StringExtractorGDBRemote response;
2935 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2936 PacketResult::Success) {
2937 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2942 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2944 lldb_private::StreamString stream;
2945 stream.Printf("vFile:close:%i", (int)fd);
2946 StringExtractorGDBRemote response;
2947 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2948 PacketResult::Success) {
2949 return ParseHostIOPacketResponse(response, -1, error) == 0;
2954 // Extension of host I/O packets to get the file size.
2955 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2956 const lldb_private::FileSpec &file_spec) {
2957 std::string path(file_spec.GetPath(false));
2958 lldb_private::StreamString stream;
2959 stream.PutCString("vFile:size:");
2960 stream.PutStringAsRawHex8(path);
2961 StringExtractorGDBRemote response;
2962 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2963 PacketResult::Success) {
2964 if (response.GetChar() != 'F')
2966 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2973 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2974 uint32_t &file_permissions) {
2975 std::string path{file_spec.GetPath(false)};
2977 lldb_private::StreamString stream;
2978 stream.PutCString("vFile:mode:");
2979 stream.PutStringAsRawHex8(path);
2980 StringExtractorGDBRemote response;
2981 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2982 PacketResult::Success) {
2983 if (response.GetChar() != 'F') {
2984 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2987 const uint32_t mode = response.GetS32(-1);
2988 if (static_cast<int32_t>(mode) == -1) {
2989 if (response.GetChar() == ',') {
2990 int response_errno = response.GetS32(-1);
2991 if (response_errno > 0)
2992 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2994 error.SetErrorToGenericError();
2996 error.SetErrorToGenericError();
2998 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3002 error.SetErrorStringWithFormat("failed to send '%s' packet",
3008 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
3009 uint64_t offset, void *dst,
3012 lldb_private::StreamString stream;
3013 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
3015 StringExtractorGDBRemote response;
3016 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3017 PacketResult::Success) {
3018 if (response.GetChar() != 'F')
3020 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3021 if (retcode == UINT32_MAX)
3023 const char next = (response.Peek() ? *response.Peek() : 0);
3027 response.GetChar(); // skip the semicolon
3029 if (response.GetEscapedBinaryData(buffer)) {
3030 const uint64_t data_to_write =
3031 std::min<uint64_t>(dst_len, buffer.size());
3032 if (data_to_write > 0)
3033 memcpy(dst, &buffer[0], data_to_write);
3034 return data_to_write;
3041 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3046 lldb_private::StreamGDBRemote stream;
3047 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3048 stream.PutEscapedBytes(src, src_len);
3049 StringExtractorGDBRemote response;
3050 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3051 PacketResult::Success) {
3052 if (response.GetChar() != 'F') {
3053 error.SetErrorStringWithFormat("write file failed");
3056 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3057 if (bytes_written == UINT64_MAX) {
3058 error.SetErrorToGenericError();
3059 if (response.GetChar() == ',') {
3060 int response_errno = response.GetS32(-1);
3061 if (response_errno > 0)
3062 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3066 return bytes_written;
3068 error.SetErrorString("failed to send vFile:pwrite packet");
3073 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3074 const FileSpec &dst) {
3075 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3077 lldb_private::StreamGDBRemote stream;
3078 stream.PutCString("vFile:symlink:");
3079 // the unix symlink() command reverses its parameters where the dst if first,
3080 // so we follow suit here
3081 stream.PutStringAsRawHex8(dst_path);
3082 stream.PutChar(',');
3083 stream.PutStringAsRawHex8(src_path);
3084 StringExtractorGDBRemote response;
3085 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3086 PacketResult::Success) {
3087 if (response.GetChar() == 'F') {
3088 uint32_t result = response.GetU32(UINT32_MAX);
3090 error.SetErrorToGenericError();
3091 if (response.GetChar() == ',') {
3092 int response_errno = response.GetS32(-1);
3093 if (response_errno > 0)
3094 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3098 // Should have returned with 'F<result>[,<errno>]'
3099 error.SetErrorStringWithFormat("symlink failed");
3102 error.SetErrorString("failed to send vFile:symlink packet");
3107 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3108 std::string path{file_spec.GetPath(false)};
3110 lldb_private::StreamGDBRemote stream;
3111 stream.PutCString("vFile:unlink:");
3112 // the unix symlink() command reverses its parameters where the dst if first,
3113 // so we follow suit here
3114 stream.PutStringAsRawHex8(path);
3115 StringExtractorGDBRemote response;
3116 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3117 PacketResult::Success) {
3118 if (response.GetChar() == 'F') {
3119 uint32_t result = response.GetU32(UINT32_MAX);
3121 error.SetErrorToGenericError();
3122 if (response.GetChar() == ',') {
3123 int response_errno = response.GetS32(-1);
3124 if (response_errno > 0)
3125 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3129 // Should have returned with 'F<result>[,<errno>]'
3130 error.SetErrorStringWithFormat("unlink failed");
3133 error.SetErrorString("failed to send vFile:unlink packet");
3138 // Extension of host I/O packets to get whether a file exists.
3139 bool GDBRemoteCommunicationClient::GetFileExists(
3140 const lldb_private::FileSpec &file_spec) {
3141 std::string path(file_spec.GetPath(false));
3142 lldb_private::StreamString stream;
3143 stream.PutCString("vFile:exists:");
3144 stream.PutStringAsRawHex8(path);
3145 StringExtractorGDBRemote response;
3146 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3147 PacketResult::Success) {
3148 if (response.GetChar() != 'F')
3150 if (response.GetChar() != ',')
3152 bool retcode = (response.GetChar() != '0');
3158 bool GDBRemoteCommunicationClient::CalculateMD5(
3159 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3160 std::string path(file_spec.GetPath(false));
3161 lldb_private::StreamString stream;
3162 stream.PutCString("vFile:MD5:");
3163 stream.PutStringAsRawHex8(path);
3164 StringExtractorGDBRemote response;
3165 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3166 PacketResult::Success) {
3167 if (response.GetChar() != 'F')
3169 if (response.GetChar() != ',')
3171 if (response.Peek() && *response.Peek() == 'x')
3173 low = response.GetHexMaxU64(false, UINT64_MAX);
3174 high = response.GetHexMaxU64(false, UINT64_MAX);
3180 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3181 // Some targets have issues with g/G packets and we need to avoid using them
3182 if (m_avoid_g_packets == eLazyBoolCalculate) {
3184 m_avoid_g_packets = eLazyBoolNo;
3185 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3186 if (arch.IsValid() &&
3187 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3188 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3189 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3190 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3191 m_avoid_g_packets = eLazyBoolYes;
3192 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3193 if (gdb_server_version != 0) {
3194 const char *gdb_server_name = GetGDBServerProgramName();
3195 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3196 if (gdb_server_version >= 310)
3197 m_avoid_g_packets = eLazyBoolNo;
3203 return m_avoid_g_packets == eLazyBoolYes;
3206 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3208 StreamString payload;
3209 payload.Printf("p%x", reg);
3210 StringExtractorGDBRemote response;
3211 if (SendThreadSpecificPacketAndWaitForResponse(
3212 tid, std::move(payload), response, false) != PacketResult::Success ||
3213 !response.IsNormalResponse())
3216 DataBufferSP buffer_sp(
3217 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3218 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3222 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3223 StreamString payload;
3224 payload.PutChar('g');
3225 StringExtractorGDBRemote response;
3226 if (SendThreadSpecificPacketAndWaitForResponse(
3227 tid, std::move(payload), response, false) != PacketResult::Success ||
3228 !response.IsNormalResponse())
3231 DataBufferSP buffer_sp(
3232 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3233 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3237 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3239 llvm::ArrayRef<uint8_t> data) {
3240 StreamString payload;
3241 payload.Printf("P%x=", reg_num);
3242 payload.PutBytesAsRawHex8(data.data(), data.size(),
3243 endian::InlHostByteOrder(),
3244 endian::InlHostByteOrder());
3245 StringExtractorGDBRemote response;
3246 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3248 PacketResult::Success &&
3249 response.IsOKResponse();
3252 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3253 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3254 StreamString payload;
3255 payload.PutChar('G');
3256 payload.PutBytesAsRawHex8(data.data(), data.size(),
3257 endian::InlHostByteOrder(),
3258 endian::InlHostByteOrder());
3259 StringExtractorGDBRemote response;
3260 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3262 PacketResult::Success &&
3263 response.IsOKResponse();
3266 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3267 uint32_t &save_id) {
3268 save_id = 0; // Set to invalid save ID
3269 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3272 m_supports_QSaveRegisterState = eLazyBoolYes;
3273 StreamString payload;
3274 payload.PutCString("QSaveRegisterState");
3275 StringExtractorGDBRemote response;
3276 if (SendThreadSpecificPacketAndWaitForResponse(
3277 tid, std::move(payload), response, false) != PacketResult::Success)
3280 if (response.IsUnsupportedResponse())
3281 m_supports_QSaveRegisterState = eLazyBoolNo;
3283 const uint32_t response_save_id = response.GetU32(0);
3284 if (response_save_id == 0)
3287 save_id = response_save_id;
3291 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3293 // We use the "m_supports_QSaveRegisterState" variable here because the
3294 // QSaveRegisterState and QRestoreRegisterState packets must both be
3295 // supported in order to be useful
3296 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3299 StreamString payload;
3300 payload.Printf("QRestoreRegisterState:%u", save_id);
3301 StringExtractorGDBRemote response;
3302 if (SendThreadSpecificPacketAndWaitForResponse(
3303 tid, std::move(payload), response, false) != PacketResult::Success)
3306 if (response.IsOKResponse())
3309 if (response.IsUnsupportedResponse())
3310 m_supports_QSaveRegisterState = eLazyBoolNo;
3314 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3315 if (!GetSyncThreadStateSupported())
3318 StreamString packet;
3319 StringExtractorGDBRemote response;
3320 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3321 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3322 GDBRemoteCommunication::PacketResult::Success &&
3323 response.IsOKResponse();
3327 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3329 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3330 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3332 StreamGDBRemote escaped_packet;
3333 escaped_packet.PutCString("jTraceStart:");
3335 StructuredData::Dictionary json_packet;
3336 json_packet.AddIntegerItem("type", options.getType());
3337 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3338 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3340 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3341 json_packet.AddIntegerItem("threadid", options.getThreadID());
3343 StructuredData::DictionarySP custom_params = options.getTraceParams();
3345 json_packet.AddItem("params", custom_params);
3347 StreamString json_string;
3348 json_packet.Dump(json_string, false);
3349 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3351 StringExtractorGDBRemote response;
3352 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3354 GDBRemoteCommunication::PacketResult::Success) {
3355 if (!response.IsNormalResponse()) {
3356 error = response.GetStatus();
3357 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
3359 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3362 LLDB_LOG(log, "failed to send packet");
3363 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3364 escaped_packet.GetData());
3370 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3371 lldb::tid_t thread_id) {
3372 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3373 StringExtractorGDBRemote response;
3376 StructuredData::Dictionary json_packet;
3377 StreamGDBRemote escaped_packet;
3378 StreamString json_string;
3379 escaped_packet.PutCString("jTraceStop:");
3381 json_packet.AddIntegerItem("traceid", uid);
3383 if (thread_id != LLDB_INVALID_THREAD_ID)
3384 json_packet.AddIntegerItem("threadid", thread_id);
3386 json_packet.Dump(json_string, false);
3388 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3390 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3392 GDBRemoteCommunication::PacketResult::Success) {
3393 if (!response.IsOKResponse()) {
3394 error = response.GetStatus();
3395 LLDB_LOG(log, "stop tracing failed");
3398 LLDB_LOG(log, "failed to send packet");
3399 error.SetErrorStringWithFormat(
3400 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3401 response.GetError());
3406 Status GDBRemoteCommunicationClient::SendGetDataPacket(
3407 lldb::user_id_t uid, lldb::tid_t thread_id,
3408 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3410 StreamGDBRemote escaped_packet;
3411 escaped_packet.PutCString("jTraceBufferRead:");
3412 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3415 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3416 lldb::user_id_t uid, lldb::tid_t thread_id,
3417 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3419 StreamGDBRemote escaped_packet;
3420 escaped_packet.PutCString("jTraceMetaRead:");
3421 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3425 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3426 TraceOptions &options) {
3427 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3428 StringExtractorGDBRemote response;
3431 StreamString json_string;
3432 StreamGDBRemote escaped_packet;
3433 escaped_packet.PutCString("jTraceConfigRead:");
3435 StructuredData::Dictionary json_packet;
3436 json_packet.AddIntegerItem("traceid", uid);
3438 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3439 json_packet.AddIntegerItem("threadid", options.getThreadID());
3441 json_packet.Dump(json_string, false);
3442 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3444 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3446 GDBRemoteCommunication::PacketResult::Success) {
3447 if (response.IsNormalResponse()) {
3448 uint64_t type = std::numeric_limits<uint64_t>::max();
3449 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3450 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3452 auto json_object = StructuredData::ParseJSON(response.Peek());
3455 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
3456 error.SetErrorString("Invalid Configuration obtained");
3460 auto json_dict = json_object->GetAsDictionary();
3462 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3464 options.setMetaDataBufferSize(metabuffersize);
3466 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3467 options.setTraceBufferSize(buffersize);
3469 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3470 options.setType(static_cast<lldb::TraceType>(type));
3472 StructuredData::ObjectSP custom_params_sp =
3473 json_dict->GetValueForKey("params");
3474 if (custom_params_sp) {
3475 if (custom_params_sp->GetType() !=
3476 lldb::eStructuredDataTypeDictionary) {
3477 error.SetErrorString("Invalid Configuration obtained");
3480 options.setTraceParams(
3481 static_pointer_cast<StructuredData::Dictionary>(
3485 error = response.GetStatus();
3488 LLDB_LOG(log, "failed to send packet");
3489 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3490 escaped_packet.GetData());
3495 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3496 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3497 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3498 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3501 StructuredData::Dictionary json_packet;
3503 json_packet.AddIntegerItem("traceid", uid);
3504 json_packet.AddIntegerItem("offset", offset);
3505 json_packet.AddIntegerItem("buffersize", buffer.size());
3507 if (thread_id != LLDB_INVALID_THREAD_ID)
3508 json_packet.AddIntegerItem("threadid", thread_id);
3510 StreamString json_string;
3511 json_packet.Dump(json_string, false);
3513 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3514 StringExtractorGDBRemote response;
3515 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3516 GDBRemoteCommunication::PacketResult::Success) {
3517 if (response.IsNormalResponse()) {
3518 size_t filled_size = response.GetHexBytesAvail(buffer);
3519 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3521 error = response.GetStatus();
3522 buffer = buffer.slice(buffer.size());
3525 LLDB_LOG(log, "failed to send packet");
3526 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3528 buffer = buffer.slice(buffer.size());
3533 bool GDBRemoteCommunicationClient::GetModuleInfo(
3534 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3535 ModuleSpec &module_spec) {
3536 if (!m_supports_qModuleInfo)
3539 std::string module_path = module_file_spec.GetPath(false);
3540 if (module_path.empty())
3543 StreamString packet;
3544 packet.PutCString("qModuleInfo:");
3545 packet.PutStringAsRawHex8(module_path);
3546 packet.PutCString(";");
3547 const auto &triple = arch_spec.GetTriple().getTriple();
3548 packet.PutStringAsRawHex8(triple);
3550 StringExtractorGDBRemote response;
3551 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3552 PacketResult::Success)
3555 if (response.IsErrorResponse())
3558 if (response.IsUnsupportedResponse()) {
3559 m_supports_qModuleInfo = false;
3563 llvm::StringRef name;
3564 llvm::StringRef value;
3566 module_spec.Clear();
3567 module_spec.GetFileSpec() = module_file_spec;
3569 while (response.GetNameColonValue(name, value)) {
3570 if (name == "uuid" || name == "md5") {
3571 StringExtractor extractor(value);
3573 extractor.GetHexByteString(uuid);
3574 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
3575 } else if (name == "triple") {
3576 StringExtractor extractor(value);
3578 extractor.GetHexByteString(triple);
3579 module_spec.GetArchitecture().SetTriple(triple.c_str());
3580 } else if (name == "file_offset") {
3582 if (!value.getAsInteger(16, ival))
3583 module_spec.SetObjectOffset(ival);
3584 } else if (name == "file_size") {
3586 if (!value.getAsInteger(16, ival))
3587 module_spec.SetObjectSize(ival);
3588 } else if (name == "file_path") {
3589 StringExtractor extractor(value);
3591 extractor.GetHexByteString(path);
3592 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3599 static llvm::Optional<ModuleSpec>
3600 ParseModuleSpec(StructuredData::Dictionary *dict) {
3605 llvm::StringRef string;
3608 if (!dict->GetValueForKeyAsString("uuid", string))
3610 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3614 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3616 result.SetObjectOffset(integer);
3618 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3620 result.SetObjectSize(integer);
3622 if (!dict->GetValueForKeyAsString("triple", string))
3624 result.GetArchitecture().SetTriple(string);
3626 if (!dict->GetValueForKeyAsString("file_path", string))
3628 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3633 llvm::Optional<std::vector<ModuleSpec>>
3634 GDBRemoteCommunicationClient::GetModulesInfo(
3635 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3636 namespace json = llvm::json;
3638 if (!m_supports_jModulesInfo)
3641 json::Array module_array;
3642 for (const FileSpec &module_file_spec : module_file_specs) {
3643 module_array.push_back(
3644 json::Object{{"file", module_file_spec.GetPath(false)},
3645 {"triple", triple.getTriple()}});
3647 StreamString unescaped_payload;
3648 unescaped_payload.PutCString("jModulesInfo:");
3649 unescaped_payload.AsRawOstream() << std::move(module_array);
3651 StreamGDBRemote payload;
3652 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3653 unescaped_payload.GetSize());
3655 // Increase the timeout for jModulesInfo since this packet can take longer.
3656 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3658 StringExtractorGDBRemote response;
3659 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3660 PacketResult::Success ||
3661 response.IsErrorResponse())
3664 if (response.IsUnsupportedResponse()) {
3665 m_supports_jModulesInfo = false;
3669 StructuredData::ObjectSP response_object_sp =
3670 StructuredData::ParseJSON(response.GetStringRef());
3671 if (!response_object_sp)
3674 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3675 if (!response_array)
3678 std::vector<ModuleSpec> result;
3679 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3680 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3681 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3682 result.push_back(*module_spec);
3688 // query the target remote for extended information using the qXfer packet
3690 // example: object='features', annex='target.xml', out=<xml output> return:
3691 // 'true' on success
3692 // 'false' on failure (err set)
3693 bool GDBRemoteCommunicationClient::ReadExtFeature(
3694 const lldb_private::ConstString object,
3695 const lldb_private::ConstString annex, std::string &out,
3696 lldb_private::Status &err) {
3698 std::stringstream output;
3699 StringExtractorGDBRemote chunk;
3701 uint64_t size = GetRemoteMaxPacketSize();
3704 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3708 // loop until all data has been read
3711 // send query extended feature packet
3712 std::stringstream packet;
3713 packet << "qXfer:" << object.AsCString("")
3714 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3715 << "," << std::hex << size;
3717 GDBRemoteCommunication::PacketResult res =
3718 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3720 if (res != GDBRemoteCommunication::PacketResult::Success) {
3721 err.SetErrorString("Error sending $qXfer packet");
3725 const std::string &str = chunk.GetStringRef();
3726 if (str.length() == 0) {
3727 // should have some data in chunk
3728 err.SetErrorString("Empty response from $qXfer packet");
3732 // check packet code
3741 if (str.length() > 1)
3743 offset += str.length() - 1;
3748 err.SetErrorString("Invalid continuation code from $qXfer packet");
3758 // Notify the target that gdb is prepared to serve symbol lookup requests.
3759 // packet: "qSymbol::"
3761 // OK The target does not need to look up any (more) symbols.
3762 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3764 // LLDB may provide the value by sending another qSymbol
3766 // in the form of"qSymbol:<sym_value>:<sym_name>".
3770 // lldb sends: qSymbol::
3771 // lldb receives: OK
3772 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3774 // need to ask again in this session.
3776 // lldb sends: qSymbol::
3777 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3778 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3779 // lldb receives: OK
3780 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3782 // the address at this time. lldb needs to send qSymbol:: again when it has
3786 // lldb sends: qSymbol::
3787 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3788 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3789 // lldb receives: OK
3790 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3792 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3794 // need any more symbols. lldb does not need to ask again in this session.
3796 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3797 lldb_private::Process *process) {
3798 // Set to true once we've resolved a symbol to an address for the remote
3799 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3800 // any more symbols and we can stop asking.
3801 bool symbol_response_provided = false;
3803 // Is this the initial qSymbol:: packet?
3804 bool first_qsymbol_query = true;
3806 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
3807 Lock lock(*this, false);
3809 StreamString packet;
3810 packet.PutCString("qSymbol::");
3811 StringExtractorGDBRemote response;
3812 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3813 PacketResult::Success) {
3814 if (response.IsOKResponse()) {
3815 if (symbol_response_provided || first_qsymbol_query) {
3816 m_qSymbol_requests_done = true;
3819 // We are done serving symbols requests
3822 first_qsymbol_query = false;
3824 if (response.IsUnsupportedResponse()) {
3825 // qSymbol is not supported by the current GDB server we are
3827 m_supports_qSymbol = false;
3830 llvm::StringRef response_str(response.GetStringRef());
3831 if (response_str.startswith("qSymbol:")) {
3832 response.SetFilePos(strlen("qSymbol:"));
3833 std::string symbol_name;
3834 if (response.GetHexByteString(symbol_name)) {
3835 if (symbol_name.empty())
3838 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3839 lldb_private::SymbolContextList sc_list;
3840 process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3841 ConstString(symbol_name), eSymbolTypeAny, sc_list);
3842 if (!sc_list.IsEmpty()) {
3843 const size_t num_scs = sc_list.GetSize();
3844 for (size_t sc_idx = 0;
3846 symbol_load_addr == LLDB_INVALID_ADDRESS;
3849 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3851 switch (sc.symbol->GetType()) {
3852 case eSymbolTypeInvalid:
3853 case eSymbolTypeAbsolute:
3854 case eSymbolTypeUndefined:
3855 case eSymbolTypeSourceFile:
3856 case eSymbolTypeHeaderFile:
3857 case eSymbolTypeObjectFile:
3858 case eSymbolTypeCommonBlock:
3859 case eSymbolTypeBlock:
3860 case eSymbolTypeLocal:
3861 case eSymbolTypeParam:
3862 case eSymbolTypeVariable:
3863 case eSymbolTypeVariableType:
3864 case eSymbolTypeLineEntry:
3865 case eSymbolTypeLineHeader:
3866 case eSymbolTypeScopeBegin:
3867 case eSymbolTypeScopeEnd:
3868 case eSymbolTypeAdditional:
3869 case eSymbolTypeCompiler:
3870 case eSymbolTypeInstrumentation:
3871 case eSymbolTypeTrampoline:
3874 case eSymbolTypeCode:
3875 case eSymbolTypeResolver:
3876 case eSymbolTypeData:
3877 case eSymbolTypeRuntime:
3878 case eSymbolTypeException:
3879 case eSymbolTypeObjCClass:
3880 case eSymbolTypeObjCMetaClass:
3881 case eSymbolTypeObjCIVar:
3882 case eSymbolTypeReExported:
3884 sc.symbol->GetLoadAddress(&process->GetTarget());
3891 // This is the normal path where our symbol lookup was successful
3892 // and we want to send a packet with the new symbol value and see
3893 // if another lookup needs to be done.
3895 // Change "packet" to contain the requested symbol value and name
3897 packet.PutCString("qSymbol:");
3898 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3899 packet.Printf("%" PRIx64, symbol_load_addr);
3900 symbol_response_provided = true;
3902 symbol_response_provided = false;
3904 packet.PutCString(":");
3905 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3906 continue; // go back to the while loop and send "packet" and wait
3907 // for another response
3912 // If we make it here, the symbol request packet response wasn't valid or
3913 // our symbol lookup failed so we must abort
3916 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3917 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3919 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3925 StructuredData::Array *
3926 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3927 if (!m_supported_async_json_packets_is_valid) {
3928 // Query the server for the array of supported asynchronous JSON packets.
3929 m_supported_async_json_packets_is_valid = true;
3931 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3934 StringExtractorGDBRemote response;
3935 const bool send_async = false;
3936 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3937 send_async) == PacketResult::Success) {
3938 m_supported_async_json_packets_sp =
3939 StructuredData::ParseJSON(response.GetStringRef());
3940 if (m_supported_async_json_packets_sp &&
3941 !m_supported_async_json_packets_sp->GetAsArray()) {
3942 // We were returned something other than a JSON array. This is
3943 // invalid. Clear it out.
3945 "GDBRemoteCommunicationClient::%s(): "
3946 "QSupportedAsyncJSONPackets returned invalid "
3948 __FUNCTION__, response.GetStringRef().data());
3949 m_supported_async_json_packets_sp.reset();
3953 "GDBRemoteCommunicationClient::%s(): "
3954 "QSupportedAsyncJSONPackets unsupported",
3958 if (log && m_supported_async_json_packets_sp) {
3959 StreamString stream;
3960 m_supported_async_json_packets_sp->Dump(stream);
3962 "GDBRemoteCommunicationClient::%s(): supported async "
3964 __FUNCTION__, stream.GetData());
3968 return m_supported_async_json_packets_sp
3969 ? m_supported_async_json_packets_sp->GetAsArray()
3973 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
3974 llvm::ArrayRef<int32_t> signals) {
3976 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3977 auto range = llvm::make_range(signals.begin(), signals.end());
3978 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3980 StringExtractorGDBRemote response;
3981 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3983 if (send_status != GDBRemoteCommunication::PacketResult::Success)
3984 return Status("Sending QPassSignals packet failed");
3986 if (response.IsOKResponse()) {
3989 return Status("Unknown error happened during sending QPassSignals packet.");
3993 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3994 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3997 if (type_name.GetLength() == 0) {
3998 error.SetErrorString("invalid type_name argument");
4002 // Build command: Configure{type_name}: serialized config data.
4003 StreamGDBRemote stream;
4004 stream.PutCString("QConfigure");
4005 stream.PutCString(type_name.AsCString());
4006 stream.PutChar(':');
4008 // Gather the plain-text version of the configuration data.
4009 StreamString unescaped_stream;
4010 config_sp->Dump(unescaped_stream);
4011 unescaped_stream.Flush();
4013 // Add it to the stream in escaped fashion.
4014 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4015 unescaped_stream.GetSize());
4020 const bool send_async = false;
4021 StringExtractorGDBRemote response;
4023 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
4024 if (result == PacketResult::Success) {
4025 // We failed if the config result comes back other than OK.
4026 if (strcmp(response.GetStringRef().data(), "OK") == 0) {
4030 error.SetErrorStringWithFormat("configuring StructuredData feature "
4031 "%s failed with error %s",
4032 type_name.AsCString(),
4033 response.GetStringRef().data());
4036 // Can we get more data here on the failure?
4037 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4038 "failed when sending packet: "
4040 type_name.AsCString(), (int)result);
4045 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4046 GDBRemoteClientBase::OnRunPacketSent(first);
4047 m_curr_tid = LLDB_INVALID_THREAD_ID;