1 //===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "GDBRemoteCommunicationClient.h"
20 // Other libraries and framework includes
21 #include "lldb/Core/DataBufferHeap.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Core/State.h"
25 #include "lldb/Core/StreamGDBRemote.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Host/HostInfo.h"
28 #include "lldb/Host/StringConvert.h"
29 #include "lldb/Interpreter/Args.h"
30 #include "lldb/Symbol/Symbol.h"
31 #include "lldb/Target/MemoryRegionInfo.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/UnixSignals.h"
34 #include "lldb/Utility/JSON.h"
35 #include "lldb/Utility/LLDBAssert.h"
38 #include "ProcessGDBRemote.h"
39 #include "ProcessGDBRemoteLog.h"
40 #include "Utility/StringExtractorGDBRemote.h"
41 #include "lldb/Host/Config.h"
43 #include "llvm/ADT/StringSwitch.h"
45 #if defined(HAVE_LIBCOMPRESSION)
46 #include <compression.h>
50 using namespace lldb_private;
51 using namespace lldb_private::process_gdb_remote;
52 using namespace std::chrono;
54 //----------------------------------------------------------------------
55 // GDBRemoteCommunicationClient constructor
56 //----------------------------------------------------------------------
57 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
58 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
59 m_supports_not_sending_acks(eLazyBoolCalculate),
60 m_supports_thread_suffix(eLazyBoolCalculate),
61 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
62 m_supports_vCont_all(eLazyBoolCalculate),
63 m_supports_vCont_any(eLazyBoolCalculate),
64 m_supports_vCont_c(eLazyBoolCalculate),
65 m_supports_vCont_C(eLazyBoolCalculate),
66 m_supports_vCont_s(eLazyBoolCalculate),
67 m_supports_vCont_S(eLazyBoolCalculate),
68 m_qHostInfo_is_valid(eLazyBoolCalculate),
69 m_curr_pid_is_valid(eLazyBoolCalculate),
70 m_qProcessInfo_is_valid(eLazyBoolCalculate),
71 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
72 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
73 m_supports_memory_region_info(eLazyBoolCalculate),
74 m_supports_watchpoint_support_info(eLazyBoolCalculate),
75 m_supports_detach_stay_stopped(eLazyBoolCalculate),
76 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
77 m_attach_or_wait_reply(eLazyBoolCalculate),
78 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
79 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
80 m_avoid_g_packets(eLazyBoolCalculate),
81 m_supports_QSaveRegisterState(eLazyBoolCalculate),
82 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
83 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
84 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
85 m_supports_qXfer_features_read(eLazyBoolCalculate),
86 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
87 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
88 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
89 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
90 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
91 m_supports_qUserName(true), m_supports_qGroupName(true),
92 m_supports_qThreadStopInfo(true), m_supports_z0(true),
93 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
94 m_supports_z4(true), m_supports_QEnvironment(true),
95 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
96 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
97 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
98 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
99 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
100 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
101 m_os_version_major(UINT32_MAX), m_os_version_minor(UINT32_MAX),
102 m_os_version_update(UINT32_MAX), m_os_build(), m_os_kernel(),
103 m_hostname(), m_gdb_server_name(), m_gdb_server_version(UINT32_MAX),
104 m_default_packet_timeout(0), m_max_packet_size(0),
105 m_qSupported_response(), m_supported_async_json_packets_is_valid(false),
106 m_supported_async_json_packets_sp() {}
108 //----------------------------------------------------------------------
110 //----------------------------------------------------------------------
111 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
116 bool GDBRemoteCommunicationClient::HandshakeWithServer(Error *error_ptr) {
117 ResetDiscoverableSettings(false);
119 // Start the read thread after we send the handshake ack since if we
120 // fail to send the handshake ack, there is no reason to continue...
122 // Wait for any responses that might have been queued up in the remote
123 // GDB server and flush them all
124 StringExtractorGDBRemote response;
125 PacketResult packet_result = PacketResult::Success;
126 while (packet_result == PacketResult::Success)
127 packet_result = ReadPacket(response, milliseconds(10), false);
129 // The return value from QueryNoAckModeSupported() is true if the packet
130 // was sent and _any_ response (including UNIMPLEMENTED) was received),
131 // or false if no response was received. This quickly tells us if we have
132 // a live connection to a remote GDB server...
133 if (QueryNoAckModeSupported()) {
137 error_ptr->SetErrorString("failed to get reply to handshake packet");
141 error_ptr->SetErrorString("failed to send the handshake ack");
146 bool GDBRemoteCommunicationClient::GetEchoSupported() {
147 if (m_supports_qEcho == eLazyBoolCalculate) {
148 GetRemoteQSupported();
150 return m_supports_qEcho == 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 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
189 if (m_max_packet_size == 0) {
190 GetRemoteQSupported();
192 return m_max_packet_size;
195 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
196 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
198 m_supports_not_sending_acks = eLazyBoolNo;
200 // This is the first real packet that we'll send in a debug session and it
202 // longer than normal to receive a reply. Wait at least 6 seconds for a
203 // reply to this packet.
205 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
207 StringExtractorGDBRemote response;
208 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
209 PacketResult::Success) {
210 if (response.IsOKResponse()) {
212 m_supports_not_sending_acks = eLazyBoolYes;
220 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
221 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
222 m_supports_threads_in_stop_reply = eLazyBoolNo;
224 StringExtractorGDBRemote response;
225 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
226 false) == PacketResult::Success) {
227 if (response.IsOKResponse())
228 m_supports_threads_in_stop_reply = eLazyBoolYes;
233 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
234 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
235 m_attach_or_wait_reply = eLazyBoolNo;
237 StringExtractorGDBRemote response;
238 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
239 false) == PacketResult::Success) {
240 if (response.IsOKResponse())
241 m_attach_or_wait_reply = eLazyBoolYes;
244 if (m_attach_or_wait_reply == eLazyBoolYes)
250 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
251 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
252 m_prepare_for_reg_writing_reply = eLazyBoolNo;
254 StringExtractorGDBRemote response;
255 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
256 false) == PacketResult::Success) {
257 if (response.IsOKResponse())
258 m_prepare_for_reg_writing_reply = eLazyBoolYes;
261 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
267 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
268 if (did_exec == false) {
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_augmented_libraries_svr4_read = eLazyBoolCalculate;
293 m_supports_qProcessInfoPID = true;
294 m_supports_qfProcessInfo = true;
295 m_supports_qUserName = true;
296 m_supports_qGroupName = true;
297 m_supports_qThreadStopInfo = true;
298 m_supports_z0 = true;
299 m_supports_z1 = true;
300 m_supports_z2 = true;
301 m_supports_z3 = true;
302 m_supports_z4 = true;
303 m_supports_QEnvironment = true;
304 m_supports_QEnvironmentHexEncoded = true;
305 m_supports_qSymbol = true;
306 m_qSymbol_requests_done = false;
307 m_supports_qModuleInfo = true;
309 m_os_version_major = UINT32_MAX;
310 m_os_version_minor = UINT32_MAX;
311 m_os_version_update = UINT32_MAX;
315 m_gdb_server_name.clear();
316 m_gdb_server_version = UINT32_MAX;
317 m_default_packet_timeout = seconds(0);
318 m_max_packet_size = 0;
319 m_qSupported_response.clear();
320 m_supported_async_json_packets_is_valid = false;
321 m_supported_async_json_packets_sp.reset();
322 m_supports_jModulesInfo = true;
325 // These flags should be reset when we first connect to a GDB server
326 // and when our inferior process execs
327 m_qProcessInfo_is_valid = eLazyBoolCalculate;
328 m_process_arch.Clear();
331 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
332 // Clear out any capabilities we expect to see in the qSupported response
333 m_supports_qXfer_auxv_read = eLazyBoolNo;
334 m_supports_qXfer_libraries_read = eLazyBoolNo;
335 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
336 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
337 m_supports_qXfer_features_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"};
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().c_str();
356 // Hang on to the qSupported packet, so that platforms can do custom
357 // configuration of the transport before attaching/launching the
359 m_qSupported_response = response_cstr;
361 if (::strstr(response_cstr, "qXfer:auxv:read+"))
362 m_supports_qXfer_auxv_read = eLazyBoolYes;
363 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
364 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
365 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
366 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
367 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
369 if (::strstr(response_cstr, "qXfer:libraries:read+"))
370 m_supports_qXfer_libraries_read = eLazyBoolYes;
371 if (::strstr(response_cstr, "qXfer:features:read+"))
372 m_supports_qXfer_features_read = eLazyBoolYes;
374 // Look for a list of compressions in the features list e.g.
375 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
376 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
378 const char *compressions =
379 ::strstr(features_list, "SupportedCompressions=");
381 std::vector<std::string> supported_compressions;
382 compressions += sizeof("SupportedCompressions=") - 1;
383 const char *end_of_compressions = strchr(compressions, ';');
384 if (end_of_compressions == NULL) {
385 end_of_compressions = strchr(compressions, '\0');
387 const char *current_compression = compressions;
388 while (current_compression < end_of_compressions) {
389 const char *next_compression_name = strchr(current_compression, ',');
390 const char *end_of_this_word = next_compression_name;
391 if (next_compression_name == NULL ||
392 end_of_compressions < next_compression_name) {
393 end_of_this_word = end_of_compressions;
396 if (end_of_this_word) {
397 if (end_of_this_word == current_compression) {
398 current_compression++;
400 std::string this_compression(
401 current_compression, end_of_this_word - current_compression);
402 supported_compressions.push_back(this_compression);
403 current_compression = end_of_this_word + 1;
406 supported_compressions.push_back(current_compression);
407 current_compression = end_of_compressions;
411 if (supported_compressions.size() > 0) {
412 MaybeEnableCompression(supported_compressions);
417 if (::strstr(response_cstr, "qEcho"))
418 m_supports_qEcho = eLazyBoolYes;
420 m_supports_qEcho = eLazyBoolNo;
422 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
423 if (packet_size_str) {
424 StringExtractorGDBRemote packet_response(packet_size_str +
425 strlen("PacketSize="));
427 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
428 if (m_max_packet_size == 0) {
429 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
431 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
433 log->Printf("Garbled PacketSize spec in qSupported response");
439 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
440 if (m_supports_thread_suffix == eLazyBoolCalculate) {
441 StringExtractorGDBRemote response;
442 m_supports_thread_suffix = eLazyBoolNo;
443 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
444 false) == PacketResult::Success) {
445 if (response.IsOKResponse())
446 m_supports_thread_suffix = eLazyBoolYes;
449 return m_supports_thread_suffix;
451 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
452 if (m_supports_vCont_c == eLazyBoolCalculate) {
453 StringExtractorGDBRemote response;
454 m_supports_vCont_any = eLazyBoolNo;
455 m_supports_vCont_all = eLazyBoolNo;
456 m_supports_vCont_c = eLazyBoolNo;
457 m_supports_vCont_C = eLazyBoolNo;
458 m_supports_vCont_s = eLazyBoolNo;
459 m_supports_vCont_S = eLazyBoolNo;
460 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
461 PacketResult::Success) {
462 const char *response_cstr = response.GetStringRef().c_str();
463 if (::strstr(response_cstr, ";c"))
464 m_supports_vCont_c = eLazyBoolYes;
466 if (::strstr(response_cstr, ";C"))
467 m_supports_vCont_C = eLazyBoolYes;
469 if (::strstr(response_cstr, ";s"))
470 m_supports_vCont_s = eLazyBoolYes;
472 if (::strstr(response_cstr, ";S"))
473 m_supports_vCont_S = eLazyBoolYes;
475 if (m_supports_vCont_c == eLazyBoolYes &&
476 m_supports_vCont_C == eLazyBoolYes &&
477 m_supports_vCont_s == eLazyBoolYes &&
478 m_supports_vCont_S == eLazyBoolYes) {
479 m_supports_vCont_all = eLazyBoolYes;
482 if (m_supports_vCont_c == eLazyBoolYes ||
483 m_supports_vCont_C == eLazyBoolYes ||
484 m_supports_vCont_s == eLazyBoolYes ||
485 m_supports_vCont_S == eLazyBoolYes) {
486 m_supports_vCont_any = eLazyBoolYes;
493 return m_supports_vCont_any;
495 return m_supports_vCont_all;
497 return m_supports_vCont_c;
499 return m_supports_vCont_C;
501 return m_supports_vCont_s;
503 return m_supports_vCont_S;
510 GDBRemoteCommunication::PacketResult
511 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
512 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
514 Lock lock(*this, send_async);
516 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
517 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
518 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
520 __FUNCTION__, payload.GetData());
521 return PacketResult::ErrorNoSequenceLock;
524 if (GetThreadSuffixSupported())
525 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
527 if (!SetCurrentThread(tid))
528 return PacketResult::ErrorSendFailed;
531 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
534 // Check if the target supports 'p' packet. It sends out a 'p'
535 // packet and checks the response. A normal packet will tell us
536 // that support is available.
538 // Takes a valid thread ID because p needs to apply to a thread.
539 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
540 if (m_supports_p == eLazyBoolCalculate) {
541 m_supports_p = eLazyBoolNo;
542 StreamString payload;
543 payload.PutCString("p0");
544 StringExtractorGDBRemote response;
545 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
547 PacketResult::Success &&
548 response.IsNormalResponse()) {
549 m_supports_p = eLazyBoolYes;
555 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
556 // Get information on all threads at one using the "jThreadsInfo" packet
557 StructuredData::ObjectSP object_sp;
559 if (m_supports_jThreadsInfo) {
560 StringExtractorGDBRemote response;
561 response.SetResponseValidatorToJSON();
562 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
563 PacketResult::Success) {
564 if (response.IsUnsupportedResponse()) {
565 m_supports_jThreadsInfo = false;
566 } else if (!response.Empty()) {
567 object_sp = StructuredData::ParseJSON(response.GetStringRef());
574 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
575 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
576 StringExtractorGDBRemote response;
577 m_supports_jThreadExtendedInfo = eLazyBoolNo;
578 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
579 PacketResult::Success) {
580 if (response.IsOKResponse()) {
581 m_supports_jThreadExtendedInfo = eLazyBoolYes;
585 return m_supports_jThreadExtendedInfo;
588 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
589 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
590 StringExtractorGDBRemote response;
591 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
592 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
594 false) == PacketResult::Success) {
595 if (response.IsOKResponse()) {
596 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
600 return m_supports_jLoadedDynamicLibrariesInfos;
603 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
604 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
605 StringExtractorGDBRemote response;
606 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
607 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
608 PacketResult::Success) {
609 if (response.IsOKResponse()) {
610 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
614 return m_supports_jGetSharedCacheInfo;
617 bool GDBRemoteCommunicationClient::GetxPacketSupported() {
618 if (m_supports_x == eLazyBoolCalculate) {
619 StringExtractorGDBRemote response;
620 m_supports_x = eLazyBoolNo;
622 snprintf(packet, sizeof(packet), "x0,0");
623 if (SendPacketAndWaitForResponse(packet, response, false) ==
624 PacketResult::Success) {
625 if (response.IsOKResponse())
626 m_supports_x = eLazyBoolYes;
632 GDBRemoteCommunicationClient::PacketResult
633 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
634 const char *payload_prefix, std::string &response_string) {
635 Lock lock(*this, false);
637 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
640 log->Printf("error: failed to get packet sequence mutex, not sending "
641 "packets with prefix '%s'",
643 return PacketResult::ErrorNoSequenceLock;
646 response_string = "";
647 std::string payload_prefix_str(payload_prefix);
648 unsigned int response_size = 0x1000;
649 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
650 response_size = GetRemoteMaxPacketSize();
653 for (unsigned int offset = 0; true; offset += response_size) {
654 StringExtractorGDBRemote this_response;
656 char sizeDescriptor[128];
657 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
659 PacketResult result = SendPacketAndWaitForResponseNoLock(
660 payload_prefix_str + sizeDescriptor, this_response);
661 if (result != PacketResult::Success)
664 const std::string &this_string = this_response.GetStringRef();
666 // Check for m or l as first character; l seems to mean this is the last
668 char first_char = *this_string.c_str();
669 if (first_char != 'm' && first_char != 'l') {
670 return PacketResult::ErrorReplyInvalid;
672 // Concatenate the result so far (skipping 'm' or 'l')
673 response_string.append(this_string, 1, std::string::npos);
674 if (first_char == 'l')
676 return PacketResult::Success;
680 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
681 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
684 // First try to retrieve the pid via the qProcessInfo request.
685 GetCurrentProcessInfo(allow_lazy);
686 if (m_curr_pid_is_valid == eLazyBoolYes) {
690 // If we don't get a response for qProcessInfo, check if $qC gives us a
692 // $qC only returns a real process id on older debugserver and lldb-platform
694 // The gdb remote protocol documents $qC as returning the thread id, which
696 // debugserver and lldb-gdbserver stubs return correctly.
697 StringExtractorGDBRemote response;
698 if (SendPacketAndWaitForResponse("qC", response, false) ==
699 PacketResult::Success) {
700 if (response.GetChar() == 'Q') {
701 if (response.GetChar() == 'C') {
702 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
703 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
704 m_curr_pid_is_valid = eLazyBoolYes;
711 // If we don't get a response for $qC, check if $qfThreadID gives us a
713 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
714 std::vector<lldb::tid_t> thread_ids;
715 bool sequence_mutex_unavailable;
717 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
718 if (size && sequence_mutex_unavailable == false) {
719 m_curr_pid = thread_ids.front();
720 m_curr_pid_is_valid = eLazyBoolYes;
726 return LLDB_INVALID_PROCESS_ID;
729 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
731 StringExtractorGDBRemote response;
732 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
733 PacketResult::Success) {
734 if (response.IsOKResponse())
736 if (response.GetChar() == 'E') {
737 // A string the describes what failed when launching...
738 error_str = response.GetStringRef().substr(1);
740 error_str.assign("unknown error occurred launching process");
743 error_str.assign("timed out waiting for app to launch");
748 int GDBRemoteCommunicationClient::SendArgumentsPacket(
749 const ProcessLaunchInfo &launch_info) {
750 // Since we don't get the send argv0 separate from the executable path, we
752 // make sure to use the actual executable path found in the launch_info...
753 std::vector<const char *> argv;
754 FileSpec exe_file = launch_info.GetExecutableFile();
755 std::string exe_path;
756 const char *arg = NULL;
757 const Args &launch_args = launch_info.GetArguments();
759 exe_path = exe_file.GetPath(false);
761 arg = launch_args.GetArgumentAtIndex(0);
765 if (!exe_path.empty()) {
766 argv.push_back(exe_path.c_str());
767 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
776 for (size_t i = 0, n = argv.size(); i < n; ++i) {
778 const int arg_len = strlen(arg);
781 packet.Printf("%i,%i,", arg_len * 2, (int)i);
782 packet.PutBytesAsRawHex8(arg, arg_len);
785 StringExtractorGDBRemote response;
786 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
787 PacketResult::Success) {
788 if (response.IsOKResponse())
790 uint8_t error = response.GetError();
798 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
799 char const *name_equal_value) {
800 if (name_equal_value && name_equal_value[0]) {
802 bool send_hex_encoding = false;
803 for (const char *p = name_equal_value;
804 *p != '\0' && send_hex_encoding == false; ++p) {
811 send_hex_encoding = true;
817 // We have non printable characters, lets hex encode this...
818 send_hex_encoding = true;
822 StringExtractorGDBRemote response;
823 if (send_hex_encoding) {
824 if (m_supports_QEnvironmentHexEncoded) {
825 packet.PutCString("QEnvironmentHexEncoded:");
826 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
827 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
828 PacketResult::Success) {
829 if (response.IsOKResponse())
831 uint8_t error = response.GetError();
834 if (response.IsUnsupportedResponse())
835 m_supports_QEnvironmentHexEncoded = false;
839 } else if (m_supports_QEnvironment) {
840 packet.Printf("QEnvironment:%s", name_equal_value);
841 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
842 PacketResult::Success) {
843 if (response.IsOKResponse())
845 uint8_t error = response.GetError();
848 if (response.IsUnsupportedResponse())
849 m_supports_QEnvironment = false;
856 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
857 if (arch && arch[0]) {
859 packet.Printf("QLaunchArch:%s", arch);
860 StringExtractorGDBRemote response;
861 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
862 PacketResult::Success) {
863 if (response.IsOKResponse())
865 uint8_t error = response.GetError();
873 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
874 char const *data, bool *was_supported) {
875 if (data && *data != '\0') {
877 packet.Printf("QSetProcessEvent:%s", data);
878 StringExtractorGDBRemote response;
879 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
880 PacketResult::Success) {
881 if (response.IsOKResponse()) {
883 *was_supported = true;
885 } else if (response.IsUnsupportedResponse()) {
887 *was_supported = false;
890 uint8_t error = response.GetError();
892 *was_supported = true;
901 bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
905 if (m_os_version_major != UINT32_MAX) {
906 major = m_os_version_major;
907 minor = m_os_version_minor;
908 update = m_os_version_update;
915 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
917 if (!m_os_build.empty()) {
926 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
928 if (!m_os_kernel.empty()) {
937 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
939 if (!m_hostname.empty()) {
948 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
954 const lldb_private::ArchSpec &
955 GDBRemoteCommunicationClient::GetProcessArchitecture() {
956 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
957 GetCurrentProcessInfo();
958 return m_process_arch;
961 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
962 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
963 m_gdb_server_name.clear();
964 m_gdb_server_version = 0;
965 m_qGDBServerVersion_is_valid = eLazyBoolNo;
967 StringExtractorGDBRemote response;
968 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
969 PacketResult::Success) {
970 if (response.IsNormalResponse()) {
971 llvm::StringRef name, value;
972 bool success = false;
973 while (response.GetNameColonValue(name, value)) {
974 if (name.equals("name")) {
976 m_gdb_server_name = value;
977 } else if (name.equals("version")) {
978 llvm::StringRef major, minor;
979 std::tie(major, minor) = value.split('.');
980 if (!major.getAsInteger(0, m_gdb_server_version))
985 m_qGDBServerVersion_is_valid = eLazyBoolYes;
989 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
992 void GDBRemoteCommunicationClient::MaybeEnableCompression(
993 std::vector<std::string> supported_compressions) {
994 CompressionType avail_type = CompressionType::None;
995 std::string avail_name;
997 #if defined(HAVE_LIBCOMPRESSION)
998 // libcompression is weak linked so test if compression_decode_buffer() is
1000 if (compression_decode_buffer != NULL &&
1001 avail_type == CompressionType::None) {
1002 for (auto compression : supported_compressions) {
1003 if (compression == "lzfse") {
1004 avail_type = CompressionType::LZFSE;
1005 avail_name = compression;
1012 #if defined(HAVE_LIBCOMPRESSION)
1013 // libcompression is weak linked so test if compression_decode_buffer() is
1015 if (compression_decode_buffer != NULL &&
1016 avail_type == CompressionType::None) {
1017 for (auto compression : supported_compressions) {
1018 if (compression == "zlib-deflate") {
1019 avail_type = CompressionType::ZlibDeflate;
1020 avail_name = compression;
1027 #if defined(HAVE_LIBZ)
1028 if (avail_type == CompressionType::None) {
1029 for (auto compression : supported_compressions) {
1030 if (compression == "zlib-deflate") {
1031 avail_type = CompressionType::ZlibDeflate;
1032 avail_name = compression;
1039 #if defined(HAVE_LIBCOMPRESSION)
1040 // libcompression is weak linked so test if compression_decode_buffer() is
1042 if (compression_decode_buffer != NULL &&
1043 avail_type == CompressionType::None) {
1044 for (auto compression : supported_compressions) {
1045 if (compression == "lz4") {
1046 avail_type = CompressionType::LZ4;
1047 avail_name = compression;
1054 #if defined(HAVE_LIBCOMPRESSION)
1055 // libcompression is weak linked so test if compression_decode_buffer() is
1057 if (compression_decode_buffer != NULL &&
1058 avail_type == CompressionType::None) {
1059 for (auto compression : supported_compressions) {
1060 if (compression == "lzma") {
1061 avail_type = CompressionType::LZMA;
1062 avail_name = compression;
1069 if (avail_type != CompressionType::None) {
1070 StringExtractorGDBRemote response;
1071 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1072 if (SendPacketAndWaitForResponse(packet, response, false) !=
1073 PacketResult::Success)
1076 if (response.IsOKResponse()) {
1077 m_compression_type = avail_type;
1082 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1083 if (GetGDBServerVersion()) {
1084 if (!m_gdb_server_name.empty())
1085 return m_gdb_server_name.c_str();
1090 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1091 if (GetGDBServerVersion())
1092 return m_gdb_server_version;
1096 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1097 StringExtractorGDBRemote response;
1098 if (SendPacketAndWaitForResponse("qC", response, false) !=
1099 PacketResult::Success)
1102 if (!response.IsNormalResponse())
1105 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1106 tid = response.GetHexMaxU32(true, -1);
1111 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1112 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1114 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1115 m_qHostInfo_is_valid = eLazyBoolNo;
1116 StringExtractorGDBRemote response;
1117 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1118 PacketResult::Success) {
1119 if (response.IsNormalResponse()) {
1120 llvm::StringRef name;
1121 llvm::StringRef value;
1122 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1124 std::string arch_name;
1125 std::string os_name;
1126 std::string vendor_name;
1128 std::string distribution_id;
1129 uint32_t pointer_byte_size = 0;
1130 ByteOrder byte_order = eByteOrderInvalid;
1131 uint32_t num_keys_decoded = 0;
1132 while (response.GetNameColonValue(name, value)) {
1133 if (name.equals("cputype")) {
1134 // exception type in big endian hex
1135 if (!value.getAsInteger(0, cpu))
1137 } else if (name.equals("cpusubtype")) {
1138 // exception count in big endian hex
1139 if (!value.getAsInteger(0, sub))
1141 } else if (name.equals("arch")) {
1144 } else if (name.equals("triple")) {
1145 StringExtractor extractor(value);
1146 extractor.GetHexByteString(triple);
1148 } else if (name.equals("distribution_id")) {
1149 StringExtractor extractor(value);
1150 extractor.GetHexByteString(distribution_id);
1152 } else if (name.equals("os_build")) {
1153 StringExtractor extractor(value);
1154 extractor.GetHexByteString(m_os_build);
1156 } else if (name.equals("hostname")) {
1157 StringExtractor extractor(value);
1158 extractor.GetHexByteString(m_hostname);
1160 } else if (name.equals("os_kernel")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(m_os_kernel);
1164 } else if (name.equals("ostype")) {
1167 } else if (name.equals("vendor")) {
1168 vendor_name = value;
1170 } else if (name.equals("endian")) {
1171 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1172 .Case("little", eByteOrderLittle)
1173 .Case("big", eByteOrderBig)
1174 .Case("pdp", eByteOrderPDP)
1175 .Default(eByteOrderInvalid);
1176 if (byte_order != eByteOrderInvalid)
1178 } else if (name.equals("ptrsize")) {
1179 if (!value.getAsInteger(0, pointer_byte_size))
1181 } else if (name.equals("os_version") ||
1183 "version")) // Older debugserver binaries used the
1184 // "version" key instead of
1187 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1188 m_os_version_update);
1189 if (m_os_version_major != UINT32_MAX)
1191 } else if (name.equals("watchpoint_exceptions_received")) {
1192 m_watchpoints_trigger_after_instruction =
1193 llvm::StringSwitch<LazyBool>(value)
1194 .Case("before", eLazyBoolNo)
1195 .Case("after", eLazyBoolYes)
1196 .Default(eLazyBoolCalculate);
1197 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1199 } else if (name.equals("default_packet_timeout")) {
1200 uint32_t timeout_seconds;
1201 if (!value.getAsInteger(0, timeout_seconds)) {
1202 m_default_packet_timeout = seconds(timeout_seconds);
1203 SetPacketTimeout(m_default_packet_timeout);
1209 if (num_keys_decoded > 0)
1210 m_qHostInfo_is_valid = eLazyBoolYes;
1212 if (triple.empty()) {
1213 if (arch_name.empty()) {
1214 if (cpu != LLDB_INVALID_CPUTYPE) {
1215 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1216 if (pointer_byte_size) {
1217 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1219 if (byte_order != eByteOrderInvalid) {
1220 assert(byte_order == m_host_arch.GetByteOrder());
1223 if (!vendor_name.empty())
1224 m_host_arch.GetTriple().setVendorName(
1225 llvm::StringRef(vendor_name));
1226 if (!os_name.empty())
1227 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1231 triple += arch_name;
1232 if (!vendor_name.empty() || !os_name.empty()) {
1234 if (vendor_name.empty())
1235 triple += "unknown";
1237 triple += vendor_name;
1239 if (os_name.empty())
1240 triple += "unknown";
1244 m_host_arch.SetTriple(triple.c_str());
1246 llvm::Triple &host_triple = m_host_arch.GetTriple();
1247 if (host_triple.getVendor() == llvm::Triple::Apple &&
1248 host_triple.getOS() == llvm::Triple::Darwin) {
1249 switch (m_host_arch.GetMachine()) {
1250 case llvm::Triple::aarch64:
1251 case llvm::Triple::arm:
1252 case llvm::Triple::thumb:
1253 host_triple.setOS(llvm::Triple::IOS);
1256 host_triple.setOS(llvm::Triple::MacOSX);
1260 if (pointer_byte_size) {
1261 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1263 if (byte_order != eByteOrderInvalid) {
1264 assert(byte_order == m_host_arch.GetByteOrder());
1268 m_host_arch.SetTriple(triple.c_str());
1269 if (pointer_byte_size) {
1270 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1272 if (byte_order != eByteOrderInvalid) {
1273 assert(byte_order == m_host_arch.GetByteOrder());
1277 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1278 "architecture as %s, triple as %s from triple text %s",
1279 __FUNCTION__, m_host_arch.GetArchitectureName()
1280 ? m_host_arch.GetArchitectureName()
1281 : "<null-arch-name>",
1282 m_host_arch.GetTriple().getTriple().c_str(),
1285 if (!distribution_id.empty())
1286 m_host_arch.SetDistributionId(distribution_id.c_str());
1290 return m_qHostInfo_is_valid == eLazyBoolYes;
1293 int GDBRemoteCommunicationClient::SendAttach(
1294 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1295 if (pid != LLDB_INVALID_PROCESS_ID) {
1297 const int packet_len =
1298 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1299 UNUSED_IF_ASSERT_DISABLED(packet_len);
1300 assert(packet_len < (int)sizeof(packet));
1301 if (SendPacketAndWaitForResponse(packet, response, false) ==
1302 PacketResult::Success) {
1303 if (response.IsErrorResponse())
1304 return response.GetError();
1311 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1313 StreamString packet;
1314 packet.PutCString("I");
1315 packet.PutBytesAsRawHex8(data, data_len);
1316 StringExtractorGDBRemote response;
1317 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1318 PacketResult::Success) {
1321 return response.GetError();
1324 const lldb_private::ArchSpec &
1325 GDBRemoteCommunicationClient::GetHostArchitecture() {
1326 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1331 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1332 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1334 return m_default_packet_timeout;
1337 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1338 uint32_t permissions) {
1339 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1340 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1342 const int packet_len = ::snprintf(
1343 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1344 permissions & lldb::ePermissionsReadable ? "r" : "",
1345 permissions & lldb::ePermissionsWritable ? "w" : "",
1346 permissions & lldb::ePermissionsExecutable ? "x" : "");
1347 assert(packet_len < (int)sizeof(packet));
1348 UNUSED_IF_ASSERT_DISABLED(packet_len);
1349 StringExtractorGDBRemote response;
1350 if (SendPacketAndWaitForResponse(packet, response, false) ==
1351 PacketResult::Success) {
1352 if (response.IsUnsupportedResponse())
1353 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1354 else if (!response.IsErrorResponse())
1355 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1357 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1360 return LLDB_INVALID_ADDRESS;
1363 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1364 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1365 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1367 const int packet_len =
1368 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1369 assert(packet_len < (int)sizeof(packet));
1370 UNUSED_IF_ASSERT_DISABLED(packet_len);
1371 StringExtractorGDBRemote response;
1372 if (SendPacketAndWaitForResponse(packet, response, false) ==
1373 PacketResult::Success) {
1374 if (response.IsUnsupportedResponse())
1375 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1376 else if (response.IsOKResponse())
1379 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1385 Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1389 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1391 const int packet_len =
1392 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1393 assert(packet_len < (int)sizeof(packet));
1394 UNUSED_IF_ASSERT_DISABLED(packet_len);
1395 StringExtractorGDBRemote response;
1396 if (SendPacketAndWaitForResponse(packet, response, false) ==
1397 PacketResult::Success &&
1398 response.IsOKResponse()) {
1399 m_supports_detach_stay_stopped = eLazyBoolYes;
1401 m_supports_detach_stay_stopped = eLazyBoolNo;
1405 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1406 error.SetErrorString("Stays stopped not supported by this target.");
1409 StringExtractorGDBRemote response;
1410 PacketResult packet_result =
1411 SendPacketAndWaitForResponse("D1", response, false);
1412 if (packet_result != PacketResult::Success)
1413 error.SetErrorString("Sending extended disconnect packet failed.");
1416 StringExtractorGDBRemote response;
1417 PacketResult packet_result =
1418 SendPacketAndWaitForResponse("D", response, false);
1419 if (packet_result != PacketResult::Success)
1420 error.SetErrorString("Sending disconnect packet failed.");
1425 Error GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1426 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1428 region_info.Clear();
1430 if (m_supports_memory_region_info != eLazyBoolNo) {
1431 m_supports_memory_region_info = eLazyBoolYes;
1433 const int packet_len = ::snprintf(
1434 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1435 assert(packet_len < (int)sizeof(packet));
1436 UNUSED_IF_ASSERT_DISABLED(packet_len);
1437 StringExtractorGDBRemote response;
1438 if (SendPacketAndWaitForResponse(packet, response, false) ==
1439 PacketResult::Success) {
1440 llvm::StringRef name;
1441 llvm::StringRef value;
1442 addr_t addr_value = LLDB_INVALID_ADDRESS;
1443 bool success = true;
1444 bool saw_permissions = false;
1445 while (success && response.GetNameColonValue(name, value)) {
1446 if (name.equals("start")) {
1447 if (!value.getAsInteger(16, addr_value))
1448 region_info.GetRange().SetRangeBase(addr_value);
1449 } else if (name.equals("size")) {
1450 if (!value.getAsInteger(16, addr_value))
1451 region_info.GetRange().SetByteSize(addr_value);
1452 } else if (name.equals("permissions") &&
1453 region_info.GetRange().IsValid()) {
1454 saw_permissions = true;
1455 if (region_info.GetRange().Contains(addr)) {
1456 if (value.find('r') != llvm::StringRef::npos)
1457 region_info.SetReadable(MemoryRegionInfo::eYes);
1459 region_info.SetReadable(MemoryRegionInfo::eNo);
1461 if (value.find('w') != llvm::StringRef::npos)
1462 region_info.SetWritable(MemoryRegionInfo::eYes);
1464 region_info.SetWritable(MemoryRegionInfo::eNo);
1466 if (value.find('x') != llvm::StringRef::npos)
1467 region_info.SetExecutable(MemoryRegionInfo::eYes);
1469 region_info.SetExecutable(MemoryRegionInfo::eNo);
1471 region_info.SetMapped(MemoryRegionInfo::eYes);
1473 // The reported region does not contain this address -- we're
1474 // looking at an unmapped page
1475 region_info.SetReadable(MemoryRegionInfo::eNo);
1476 region_info.SetWritable(MemoryRegionInfo::eNo);
1477 region_info.SetExecutable(MemoryRegionInfo::eNo);
1478 region_info.SetMapped(MemoryRegionInfo::eNo);
1480 } else if (name.equals("name")) {
1481 StringExtractorGDBRemote name_extractor(value);
1483 name_extractor.GetHexByteString(name);
1484 region_info.SetName(name.c_str());
1485 } else if (name.equals("error")) {
1486 StringExtractorGDBRemote error_extractor(value);
1487 std::string error_string;
1488 // Now convert the HEX bytes into a string value
1489 error_extractor.GetHexByteString(error_string);
1490 error.SetErrorString(error_string.c_str());
1494 // We got a valid address range back but no permissions -- which means
1495 // this is an unmapped page
1496 if (region_info.GetRange().IsValid() && saw_permissions == false) {
1497 region_info.SetReadable(MemoryRegionInfo::eNo);
1498 region_info.SetWritable(MemoryRegionInfo::eNo);
1499 region_info.SetExecutable(MemoryRegionInfo::eNo);
1500 region_info.SetMapped(MemoryRegionInfo::eNo);
1503 m_supports_memory_region_info = eLazyBoolNo;
1507 if (m_supports_memory_region_info == eLazyBoolNo) {
1508 error.SetErrorString("qMemoryRegionInfo is not supported");
1511 region_info.Clear();
1515 Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1518 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1519 num = m_num_supported_hardware_watchpoints;
1523 // Set num to 0 first.
1525 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1527 const int packet_len =
1528 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1529 assert(packet_len < (int)sizeof(packet));
1530 UNUSED_IF_ASSERT_DISABLED(packet_len);
1531 StringExtractorGDBRemote response;
1532 if (SendPacketAndWaitForResponse(packet, response, false) ==
1533 PacketResult::Success) {
1534 m_supports_watchpoint_support_info = eLazyBoolYes;
1535 llvm::StringRef name;
1536 llvm::StringRef value;
1537 while (response.GetNameColonValue(name, value)) {
1538 if (name.equals("num")) {
1539 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1540 num = m_num_supported_hardware_watchpoints;
1544 m_supports_watchpoint_support_info = eLazyBoolNo;
1548 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1549 error.SetErrorString("qWatchpointSupportInfo is not supported");
1554 lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1555 uint32_t &num, bool &after, const ArchSpec &arch) {
1556 Error error(GetWatchpointSupportInfo(num));
1557 if (error.Success())
1558 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1563 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1564 bool &after, const ArchSpec &arch) {
1566 llvm::Triple::ArchType atype = arch.GetMachine();
1568 // we assume watchpoints will happen after running the relevant opcode
1569 // and we only want to override this behavior if we have explicitly
1570 // received a qHostInfo telling us otherwise
1571 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1572 // On targets like MIPS, watchpoint exceptions are always generated
1573 // before the instruction is executed. The connected target may not
1574 // support qHostInfo or qWatchpointSupportInfo packets.
1575 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1576 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1581 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1582 // if it is not calculated before.
1583 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1584 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1585 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1586 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1588 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1593 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1595 std::string path{file_spec.GetPath(false)};
1596 StreamString packet;
1597 packet.PutCString("QSetSTDIN:");
1598 packet.PutCStringAsRawHex8(path.c_str());
1600 StringExtractorGDBRemote response;
1601 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1602 PacketResult::Success) {
1603 if (response.IsOKResponse())
1605 uint8_t error = response.GetError();
1613 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1615 std::string path{file_spec.GetPath(false)};
1616 StreamString packet;
1617 packet.PutCString("QSetSTDOUT:");
1618 packet.PutCStringAsRawHex8(path.c_str());
1620 StringExtractorGDBRemote response;
1621 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1622 PacketResult::Success) {
1623 if (response.IsOKResponse())
1625 uint8_t error = response.GetError();
1633 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1635 std::string path{file_spec.GetPath(false)};
1636 StreamString packet;
1637 packet.PutCString("QSetSTDERR:");
1638 packet.PutCStringAsRawHex8(path.c_str());
1640 StringExtractorGDBRemote response;
1641 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1642 PacketResult::Success) {
1643 if (response.IsOKResponse())
1645 uint8_t error = response.GetError();
1653 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1654 StringExtractorGDBRemote response;
1655 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1656 PacketResult::Success) {
1657 if (response.IsUnsupportedResponse())
1659 if (response.IsErrorResponse())
1662 response.GetHexByteString(cwd);
1663 working_dir.SetFile(cwd, false, GetHostArchitecture());
1664 return !cwd.empty();
1669 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1671 std::string path{working_dir.GetPath(false)};
1672 StreamString packet;
1673 packet.PutCString("QSetWorkingDir:");
1674 packet.PutCStringAsRawHex8(path.c_str());
1676 StringExtractorGDBRemote response;
1677 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1678 PacketResult::Success) {
1679 if (response.IsOKResponse())
1681 uint8_t error = response.GetError();
1689 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1691 const int packet_len =
1692 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1693 assert(packet_len < (int)sizeof(packet));
1694 UNUSED_IF_ASSERT_DISABLED(packet_len);
1695 StringExtractorGDBRemote response;
1696 if (SendPacketAndWaitForResponse(packet, response, false) ==
1697 PacketResult::Success) {
1698 if (response.IsOKResponse())
1700 uint8_t error = response.GetError();
1707 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1709 const int packet_len = ::snprintf(packet, sizeof(packet),
1710 "QSetDetachOnError:%i", enable ? 1 : 0);
1711 assert(packet_len < (int)sizeof(packet));
1712 UNUSED_IF_ASSERT_DISABLED(packet_len);
1713 StringExtractorGDBRemote response;
1714 if (SendPacketAndWaitForResponse(packet, response, false) ==
1715 PacketResult::Success) {
1716 if (response.IsOKResponse())
1718 uint8_t error = response.GetError();
1725 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1726 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1727 if (response.IsNormalResponse()) {
1728 llvm::StringRef name;
1729 llvm::StringRef value;
1730 StringExtractor extractor;
1732 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1735 std::string os_type;
1737 while (response.GetNameColonValue(name, value)) {
1738 if (name.equals("pid")) {
1739 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1740 value.getAsInteger(0, pid);
1741 process_info.SetProcessID(pid);
1742 } else if (name.equals("ppid")) {
1743 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1744 value.getAsInteger(0, pid);
1745 process_info.SetParentProcessID(pid);
1746 } else if (name.equals("uid")) {
1747 uint32_t uid = UINT32_MAX;
1748 value.getAsInteger(0, uid);
1749 process_info.SetUserID(uid);
1750 } else if (name.equals("euid")) {
1751 uint32_t uid = UINT32_MAX;
1752 value.getAsInteger(0, uid);
1753 process_info.SetEffectiveGroupID(uid);
1754 } else if (name.equals("gid")) {
1755 uint32_t gid = UINT32_MAX;
1756 value.getAsInteger(0, gid);
1757 process_info.SetGroupID(gid);
1758 } else if (name.equals("egid")) {
1759 uint32_t gid = UINT32_MAX;
1760 value.getAsInteger(0, gid);
1761 process_info.SetEffectiveGroupID(gid);
1762 } else if (name.equals("triple")) {
1763 StringExtractor extractor(value);
1765 extractor.GetHexByteString(triple);
1766 process_info.GetArchitecture().SetTriple(triple.c_str());
1767 } else if (name.equals("name")) {
1768 StringExtractor extractor(value);
1769 // The process name from ASCII hex bytes since we can't
1770 // control the characters in a process name
1772 extractor.GetHexByteString(name);
1773 process_info.GetExecutableFile().SetFile(name, false);
1774 } else if (name.equals("cputype")) {
1775 value.getAsInteger(0, cpu);
1776 } else if (name.equals("cpusubtype")) {
1777 value.getAsInteger(0, sub);
1778 } else if (name.equals("vendor")) {
1780 } else if (name.equals("ostype")) {
1785 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1786 if (vendor == "apple") {
1787 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1789 process_info.GetArchitecture().GetTriple().setVendorName(
1790 llvm::StringRef(vendor));
1791 process_info.GetArchitecture().GetTriple().setOSName(
1792 llvm::StringRef(os_type));
1796 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1802 bool GDBRemoteCommunicationClient::GetProcessInfo(
1803 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1804 process_info.Clear();
1806 if (m_supports_qProcessInfoPID) {
1808 const int packet_len =
1809 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1810 assert(packet_len < (int)sizeof(packet));
1811 UNUSED_IF_ASSERT_DISABLED(packet_len);
1812 StringExtractorGDBRemote response;
1813 if (SendPacketAndWaitForResponse(packet, response, false) ==
1814 PacketResult::Success) {
1815 return DecodeProcessInfoResponse(response, process_info);
1817 m_supports_qProcessInfoPID = false;
1824 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1825 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1829 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1831 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1837 StringExtractorGDBRemote response;
1838 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1839 PacketResult::Success) {
1840 if (response.IsNormalResponse()) {
1841 llvm::StringRef name;
1842 llvm::StringRef value;
1843 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1845 std::string arch_name;
1846 std::string os_name;
1847 std::string vendor_name;
1849 std::string elf_abi;
1850 uint32_t pointer_byte_size = 0;
1851 StringExtractor extractor;
1852 ByteOrder byte_order = eByteOrderInvalid;
1853 uint32_t num_keys_decoded = 0;
1854 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1855 while (response.GetNameColonValue(name, value)) {
1856 if (name.equals("cputype")) {
1857 if (!value.getAsInteger(16, cpu))
1859 } else if (name.equals("cpusubtype")) {
1860 if (!value.getAsInteger(16, sub))
1862 } else if (name.equals("triple")) {
1863 StringExtractor extractor(value);
1864 extractor.GetHexByteString(triple);
1866 } else if (name.equals("ostype")) {
1869 } else if (name.equals("vendor")) {
1870 vendor_name = value;
1872 } else if (name.equals("endian")) {
1873 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1874 .Case("little", eByteOrderLittle)
1875 .Case("big", eByteOrderBig)
1876 .Case("pdp", eByteOrderPDP)
1877 .Default(eByteOrderInvalid);
1878 if (byte_order != eByteOrderInvalid)
1880 } else if (name.equals("ptrsize")) {
1881 if (!value.getAsInteger(16, pointer_byte_size))
1883 } else if (name.equals("pid")) {
1884 if (!value.getAsInteger(16, pid))
1886 } else if (name.equals("elf_abi")) {
1891 if (num_keys_decoded > 0)
1892 m_qProcessInfo_is_valid = eLazyBoolYes;
1893 if (pid != LLDB_INVALID_PROCESS_ID) {
1894 m_curr_pid_is_valid = eLazyBoolYes;
1898 // Set the ArchSpec from the triple if we have it.
1899 if (!triple.empty()) {
1900 m_process_arch.SetTriple(triple.c_str());
1901 m_process_arch.SetFlags(elf_abi);
1902 if (pointer_byte_size) {
1903 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1905 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1906 !vendor_name.empty()) {
1907 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1909 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
1910 switch (triple.getObjectFormat()) {
1911 case llvm::Triple::MachO:
1912 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1914 case llvm::Triple::ELF:
1915 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1917 case llvm::Triple::COFF:
1918 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1920 case llvm::Triple::UnknownObjectFormat:
1922 log->Printf("error: failed to determine target architecture");
1926 if (pointer_byte_size) {
1927 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1929 if (byte_order != eByteOrderInvalid) {
1930 assert(byte_order == m_process_arch.GetByteOrder());
1932 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1933 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1934 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1935 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1940 m_qProcessInfo_is_valid = eLazyBoolNo;
1946 uint32_t GDBRemoteCommunicationClient::FindProcesses(
1947 const ProcessInstanceInfoMatch &match_info,
1948 ProcessInstanceInfoList &process_infos) {
1949 process_infos.Clear();
1951 if (m_supports_qfProcessInfo) {
1952 StreamString packet;
1953 packet.PutCString("qfProcessInfo");
1954 if (!match_info.MatchAllProcesses()) {
1955 packet.PutChar(':');
1956 const char *name = match_info.GetProcessInfo().GetName();
1957 bool has_name_match = false;
1958 if (name && name[0]) {
1959 has_name_match = true;
1960 NameMatchType name_match_type = match_info.GetNameMatchType();
1961 switch (name_match_type) {
1962 case eNameMatchIgnore:
1963 has_name_match = false;
1966 case eNameMatchEquals:
1967 packet.PutCString("name_match:equals;");
1970 case eNameMatchContains:
1971 packet.PutCString("name_match:contains;");
1974 case eNameMatchStartsWith:
1975 packet.PutCString("name_match:starts_with;");
1978 case eNameMatchEndsWith:
1979 packet.PutCString("name_match:ends_with;");
1982 case eNameMatchRegularExpression:
1983 packet.PutCString("name_match:regex;");
1986 if (has_name_match) {
1987 packet.PutCString("name:");
1988 packet.PutBytesAsRawHex8(name, ::strlen(name));
1989 packet.PutChar(';');
1993 if (match_info.GetProcessInfo().ProcessIDIsValid())
1994 packet.Printf("pid:%" PRIu64 ";",
1995 match_info.GetProcessInfo().GetProcessID());
1996 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1997 packet.Printf("parent_pid:%" PRIu64 ";",
1998 match_info.GetProcessInfo().GetParentProcessID());
1999 if (match_info.GetProcessInfo().UserIDIsValid())
2000 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2001 if (match_info.GetProcessInfo().GroupIDIsValid())
2002 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2003 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2004 packet.Printf("euid:%u;",
2005 match_info.GetProcessInfo().GetEffectiveUserID());
2006 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2007 packet.Printf("egid:%u;",
2008 match_info.GetProcessInfo().GetEffectiveGroupID());
2009 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2010 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2011 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2012 const ArchSpec &match_arch =
2013 match_info.GetProcessInfo().GetArchitecture();
2014 const llvm::Triple &triple = match_arch.GetTriple();
2015 packet.PutCString("triple:");
2016 packet.PutCString(triple.getTriple());
2017 packet.PutChar(';');
2020 StringExtractorGDBRemote response;
2021 // Increase timeout as the first qfProcessInfo packet takes a long time
2022 // on Android. The value of 1min was arrived at empirically.
2023 ScopedTimeout timeout(*this, minutes(1));
2024 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2025 PacketResult::Success) {
2027 ProcessInstanceInfo process_info;
2028 if (!DecodeProcessInfoResponse(response, process_info))
2030 process_infos.Append(process_info);
2031 response.GetStringRef().clear();
2032 response.SetFilePos(0);
2033 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2034 PacketResult::Success);
2036 m_supports_qfProcessInfo = false;
2040 return process_infos.GetSize();
2043 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2044 std::string &name) {
2045 if (m_supports_qUserName) {
2047 const int packet_len =
2048 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2049 assert(packet_len < (int)sizeof(packet));
2050 UNUSED_IF_ASSERT_DISABLED(packet_len);
2051 StringExtractorGDBRemote response;
2052 if (SendPacketAndWaitForResponse(packet, response, false) ==
2053 PacketResult::Success) {
2054 if (response.IsNormalResponse()) {
2055 // Make sure we parsed the right number of characters. The response is
2056 // the hex encoded user name and should make up the entire packet.
2057 // If there are any non-hex ASCII bytes, the length won't match below..
2058 if (response.GetHexByteString(name) * 2 ==
2059 response.GetStringRef().size())
2063 m_supports_qUserName = false;
2070 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2071 std::string &name) {
2072 if (m_supports_qGroupName) {
2074 const int packet_len =
2075 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2076 assert(packet_len < (int)sizeof(packet));
2077 UNUSED_IF_ASSERT_DISABLED(packet_len);
2078 StringExtractorGDBRemote response;
2079 if (SendPacketAndWaitForResponse(packet, response, false) ==
2080 PacketResult::Success) {
2081 if (response.IsNormalResponse()) {
2082 // Make sure we parsed the right number of characters. The response is
2083 // the hex encoded group name and should make up the entire packet.
2084 // If there are any non-hex ASCII bytes, the length won't match below..
2085 if (response.GetHexByteString(name) * 2 ==
2086 response.GetStringRef().size())
2090 m_supports_qGroupName = false;
2097 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2098 // Form non-stop packet request
2100 const int packet_len =
2101 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2102 assert(packet_len < (int)sizeof(packet));
2103 UNUSED_IF_ASSERT_DISABLED(packet_len);
2105 StringExtractorGDBRemote response;
2107 if (SendPacketAndWaitForResponse(packet, response, false) ==
2108 PacketResult::Success)
2109 if (response.IsOKResponse())
2112 // Failed or not supported
2116 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2117 uint32_t recv_size) {
2119 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2120 uint32_t bytes_left = send_size;
2121 while (bytes_left > 0) {
2122 if (bytes_left >= 26) {
2123 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2126 packet.Printf("%*.*s;", bytes_left, bytes_left,
2127 "abcdefghijklmnopqrstuvwxyz");
2134 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2135 using Dur = duration<float>;
2136 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2137 Dur mean = sum / v.size();
2140 float delta = (d - mean).count();
2141 accum += delta * delta;
2144 return Dur(sqrtf(accum / (v.size() - 1)));
2147 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2150 uint64_t recv_amount,
2151 bool json, Stream &strm) {
2153 if (SendSpeedTestPacket(0, 0)) {
2154 StreamString packet;
2156 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2160 strm.Printf("Testing sending %u packets of various sizes:\n",
2164 uint32_t result_idx = 0;
2166 std::vector<duration<float>> packet_times;
2168 for (send_size = 0; send_size <= max_send;
2169 send_size ? send_size *= 2 : send_size = 4) {
2170 for (uint32_t recv_size = 0; recv_size <= max_recv;
2171 recv_size ? recv_size *= 2 : recv_size = 4) {
2172 MakeSpeedTestPacket(packet, send_size, recv_size);
2174 packet_times.clear();
2175 // Test how long it takes to send 'num_packets' packets
2176 const auto start_time = steady_clock::now();
2177 for (i = 0; i < num_packets; ++i) {
2178 const auto packet_start_time = steady_clock::now();
2179 StringExtractorGDBRemote response;
2180 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2181 const auto packet_end_time = steady_clock::now();
2182 packet_times.push_back(packet_end_time - packet_start_time);
2184 const auto end_time = steady_clock::now();
2185 const auto total_time = end_time - start_time;
2187 float packets_per_second =
2188 ((float)num_packets) / duration<float>(total_time).count();
2189 auto average_per_packet = total_time / num_packets;
2190 const duration<float> standard_deviation =
2191 calculate_standard_deviation(packet_times);
2193 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2194 ", \"recv_size\" : %6" PRIu32
2195 ", \"total_time_nsec\" : %12" PRIu64
2196 ", \"standard_deviation_nsec\" : %9" PRIu64 " }",
2197 result_idx > 0 ? "," : "", send_size, recv_size,
2198 duration_cast<nanoseconds>(total_time).count(),
2199 duration_cast<nanoseconds>(standard_deviation).count());
2203 "qSpeedTest(send=%-7u, recv=%-7u) in %.9f"
2204 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard "
2205 "deviation of %10.6f ms\n",
2206 send_size, recv_size, duration<float>(total_time).count(),
2208 duration<float, std::milli>(average_per_packet).count(),
2209 duration<float, std::milli>(standard_deviation).count());
2215 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2217 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2218 ": %" PRIu64 ",\n \"results\" : [",
2221 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2227 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2228 MakeSpeedTestPacket(packet, send_size, recv_size);
2230 // If we have a receive size, test how long it takes to receive 4MB of
2232 if (recv_size > 0) {
2233 const auto start_time = steady_clock::now();
2234 uint32_t bytes_read = 0;
2235 uint32_t packet_count = 0;
2236 while (bytes_read < recv_amount) {
2237 StringExtractorGDBRemote response;
2238 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2239 bytes_read += recv_size;
2242 const auto end_time = steady_clock::now();
2243 const auto total_time = end_time - start_time;
2244 float mb_second = ((float)recv_amount) /
2245 duration<float>(total_time).count() /
2247 float packets_per_second =
2248 ((float)packet_count) / duration<float>(total_time).count();
2249 const auto average_per_packet = total_time / packet_count;
2252 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2253 ", \"recv_size\" : %6" PRIu32
2254 ", \"total_time_nsec\" : %12" PRIu64 " }",
2255 result_idx > 0 ? "," : "", send_size, recv_size,
2256 duration_cast<nanoseconds>(total_time).count());
2259 strm.Printf("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to "
2260 "receive %2.1fMB in %.9f"
2261 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per "
2263 send_size, recv_size, packet_count, k_recv_amount_mb,
2264 duration<float>(total_time).count(), mb_second,
2266 duration<float, std::milli>(average_per_packet).count());
2272 strm.Printf("\n ]\n }\n}\n");
2278 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2279 uint32_t recv_size) {
2280 StreamString packet;
2281 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2282 uint32_t bytes_left = send_size;
2283 while (bytes_left > 0) {
2284 if (bytes_left >= 26) {
2285 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2288 packet.Printf("%*.*s;", bytes_left, bytes_left,
2289 "abcdefghijklmnopqrstuvwxyz");
2294 StringExtractorGDBRemote response;
2295 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2296 PacketResult::Success;
2299 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2300 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2301 std::string &socket_name) {
2302 pid = LLDB_INVALID_PROCESS_ID;
2304 socket_name.clear();
2306 StringExtractorGDBRemote response;
2307 StreamString stream;
2308 stream.PutCString("qLaunchGDBServer;");
2309 std::string hostname;
2310 if (remote_accept_hostname && remote_accept_hostname[0])
2311 hostname = remote_accept_hostname;
2313 if (HostInfo::GetHostname(hostname)) {
2314 // Make the GDB server we launch only accept connections from this host
2315 stream.Printf("host:%s;", hostname.c_str());
2317 // Make the GDB server we launch accept connections from any host since we
2318 // can't figure out the hostname
2319 stream.Printf("host:*;");
2322 // give the process a few seconds to startup
2323 ScopedTimeout timeout(*this, seconds(10));
2325 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2326 PacketResult::Success) {
2327 llvm::StringRef name;
2328 llvm::StringRef value;
2329 while (response.GetNameColonValue(name, value)) {
2330 if (name.equals("port"))
2331 value.getAsInteger(0, port);
2332 else if (name.equals("pid"))
2333 value.getAsInteger(0, pid);
2334 else if (name.compare("socket_name") == 0) {
2335 StringExtractor extractor(value);
2336 extractor.GetHexByteString(socket_name);
2344 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2345 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2346 connection_urls.clear();
2348 StringExtractorGDBRemote response;
2349 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2350 PacketResult::Success)
2353 StructuredData::ObjectSP data =
2354 StructuredData::ParseJSON(response.GetStringRef());
2358 StructuredData::Array *array = data->GetAsArray();
2362 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2363 StructuredData::Dictionary *element = nullptr;
2364 if (!array->GetItemAtIndexAsDictionary(i, element))
2368 if (StructuredData::ObjectSP port_osp =
2369 element->GetValueForKey(llvm::StringRef("port")))
2370 port = port_osp->GetIntegerValue(0);
2372 std::string socket_name;
2373 if (StructuredData::ObjectSP socket_name_osp =
2374 element->GetValueForKey(llvm::StringRef("socket_name")))
2375 socket_name = socket_name_osp->GetStringValue();
2377 if (port != 0 || !socket_name.empty())
2378 connection_urls.emplace_back(port, socket_name);
2380 return connection_urls.size();
2383 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2384 StreamString stream;
2385 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2387 StringExtractorGDBRemote response;
2388 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2389 PacketResult::Success) {
2390 if (response.IsOKResponse())
2396 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2397 if (m_curr_tid == tid)
2402 if (tid == UINT64_MAX)
2403 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2405 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2406 assert(packet_len + 1 < (int)sizeof(packet));
2407 UNUSED_IF_ASSERT_DISABLED(packet_len);
2408 StringExtractorGDBRemote response;
2409 if (SendPacketAndWaitForResponse(packet, response, false) ==
2410 PacketResult::Success) {
2411 if (response.IsOKResponse()) {
2417 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2419 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2421 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2423 if (response.IsUnsupportedResponse() && IsConnected()) {
2431 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2432 if (m_curr_tid_run == tid)
2437 if (tid == UINT64_MAX)
2438 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2440 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2442 assert(packet_len + 1 < (int)sizeof(packet));
2443 UNUSED_IF_ASSERT_DISABLED(packet_len);
2444 StringExtractorGDBRemote response;
2445 if (SendPacketAndWaitForResponse(packet, response, false) ==
2446 PacketResult::Success) {
2447 if (response.IsOKResponse()) {
2448 m_curr_tid_run = tid;
2453 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2455 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2457 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2459 if (response.IsUnsupportedResponse() && IsConnected()) {
2467 bool GDBRemoteCommunicationClient::GetStopReply(
2468 StringExtractorGDBRemote &response) {
2469 if (SendPacketAndWaitForResponse("?", response, false) ==
2470 PacketResult::Success)
2471 return response.IsNormalResponse();
2475 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2476 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2477 if (m_supports_qThreadStopInfo) {
2480 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2481 assert(packet_len < (int)sizeof(packet));
2482 UNUSED_IF_ASSERT_DISABLED(packet_len);
2483 if (SendPacketAndWaitForResponse(packet, response, false) ==
2484 PacketResult::Success) {
2485 if (response.IsUnsupportedResponse())
2486 m_supports_qThreadStopInfo = false;
2487 else if (response.IsNormalResponse())
2492 m_supports_qThreadStopInfo = false;
2498 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2499 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2500 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2502 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2503 __FUNCTION__, insert ? "add" : "remove", addr);
2505 // Check if the stub is known not to support this breakpoint type
2506 if (!SupportsGDBStoppointPacket(type))
2508 // Construct the breakpoint packet
2510 const int packet_len =
2511 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2512 insert ? 'Z' : 'z', type, addr, length);
2513 // Check we haven't overwritten the end of the packet buffer
2514 assert(packet_len + 1 < (int)sizeof(packet));
2515 UNUSED_IF_ASSERT_DISABLED(packet_len);
2516 StringExtractorGDBRemote response;
2517 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2518 // or "" (unsupported)
2519 response.SetResponseValidatorToOKErrorNotSupported();
2520 // Try to send the breakpoint packet, and check that it was correctly sent
2521 if (SendPacketAndWaitForResponse(packet, response, true) ==
2522 PacketResult::Success) {
2523 // Receive and OK packet when the breakpoint successfully placed
2524 if (response.IsOKResponse())
2527 // Error while setting breakpoint, send back specific error
2528 if (response.IsErrorResponse())
2529 return response.GetError();
2531 // Empty packet informs us that breakpoint is not supported
2532 if (response.IsUnsupportedResponse()) {
2533 // Disable this breakpoint type since it is unsupported
2535 case eBreakpointSoftware:
2536 m_supports_z0 = false;
2538 case eBreakpointHardware:
2539 m_supports_z1 = false;
2541 case eWatchpointWrite:
2542 m_supports_z2 = false;
2544 case eWatchpointRead:
2545 m_supports_z3 = false;
2547 case eWatchpointReadWrite:
2548 m_supports_z4 = false;
2550 case eStoppointInvalid:
2555 // Signal generic failure
2559 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2560 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2563 Lock lock(*this, false);
2565 sequence_mutex_unavailable = false;
2566 StringExtractorGDBRemote response;
2568 PacketResult packet_result;
2569 for (packet_result =
2570 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2571 packet_result == PacketResult::Success && response.IsNormalResponse();
2573 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2574 char ch = response.GetChar();
2579 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2581 if (tid != LLDB_INVALID_THREAD_ID) {
2582 thread_ids.push_back(tid);
2584 ch = response.GetChar(); // Skip the command separator
2585 } while (ch == ','); // Make sure we got a comma separator
2590 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2591 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2593 * be as simple as 'S05'. There is no packet which can give us pid and/or
2595 * Assume pid=tid=1 in such cases.
2597 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2599 thread_ids.push_back(1);
2602 #if defined(LLDB_CONFIGURATION_DEBUG)
2603 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the
2604 // sequence mutex");
2606 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2609 log->Printf("error: failed to get packet sequence mutex, not sending "
2610 "packet 'qfThreadInfo'");
2612 sequence_mutex_unavailable = true;
2614 return thread_ids.size();
2617 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2618 StringExtractorGDBRemote response;
2619 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2620 PacketResult::Success ||
2621 !response.IsNormalResponse())
2622 return LLDB_INVALID_ADDRESS;
2623 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2626 lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2627 const char *command, // Shouldn't be NULL
2629 working_dir, // Pass empty FileSpec to use the current working directory
2630 int *status_ptr, // Pass NULL if you don't want the process exit status
2631 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2634 *command_output, // Pass NULL if you don't want the command output
2636 timeout_sec) // Timeout in seconds to wait for shell program to finish
2638 lldb_private::StreamString stream;
2639 stream.PutCString("qPlatform_shell:");
2640 stream.PutBytesAsRawHex8(command, strlen(command));
2641 stream.PutChar(',');
2642 stream.PutHex32(timeout_sec);
2644 std::string path{working_dir.GetPath(false)};
2645 stream.PutChar(',');
2646 stream.PutCStringAsRawHex8(path.c_str());
2648 StringExtractorGDBRemote response;
2649 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2650 PacketResult::Success) {
2651 if (response.GetChar() != 'F')
2652 return Error("malformed reply");
2653 if (response.GetChar() != ',')
2654 return Error("malformed reply");
2655 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2656 if (exitcode == UINT32_MAX)
2657 return Error("unable to run remote process");
2658 else if (status_ptr)
2659 *status_ptr = exitcode;
2660 if (response.GetChar() != ',')
2661 return Error("malformed reply");
2662 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2665 if (response.GetChar() != ',')
2666 return Error("malformed reply");
2668 response.GetEscapedBinaryData(output);
2670 command_output->assign(output);
2673 return Error("unable to send packet");
2676 Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2677 uint32_t file_permissions) {
2678 std::string path{file_spec.GetPath(false)};
2679 lldb_private::StreamString stream;
2680 stream.PutCString("qPlatform_mkdir:");
2681 stream.PutHex32(file_permissions);
2682 stream.PutChar(',');
2683 stream.PutCStringAsRawHex8(path.c_str());
2684 llvm::StringRef packet = stream.GetString();
2685 StringExtractorGDBRemote response;
2687 if (SendPacketAndWaitForResponse(packet, response, false) !=
2688 PacketResult::Success)
2689 return Error("failed to send '%s' packet", packet.str().c_str());
2691 if (response.GetChar() != 'F')
2692 return Error("invalid response to '%s' packet", packet.str().c_str());
2694 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2697 Error GDBRemoteCommunicationClient::SetFilePermissions(
2698 const FileSpec &file_spec, uint32_t file_permissions) {
2699 std::string path{file_spec.GetPath(false)};
2700 lldb_private::StreamString stream;
2701 stream.PutCString("qPlatform_chmod:");
2702 stream.PutHex32(file_permissions);
2703 stream.PutChar(',');
2704 stream.PutCStringAsRawHex8(path.c_str());
2705 llvm::StringRef packet = stream.GetString();
2706 StringExtractorGDBRemote response;
2708 if (SendPacketAndWaitForResponse(packet, response, false) !=
2709 PacketResult::Success)
2710 return Error("failed to send '%s' packet", stream.GetData());
2712 if (response.GetChar() != 'F')
2713 return Error("invalid response to '%s' packet", stream.GetData());
2715 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2718 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2719 uint64_t fail_result, Error &error) {
2720 response.SetFilePos(0);
2721 if (response.GetChar() != 'F')
2723 int32_t result = response.GetS32(-2);
2726 if (response.GetChar() == ',') {
2727 int result_errno = response.GetS32(-2);
2728 if (result_errno != -2)
2729 error.SetError(result_errno, eErrorTypePOSIX);
2731 error.SetError(-1, eErrorTypeGeneric);
2737 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2738 uint32_t flags, mode_t mode,
2740 std::string path(file_spec.GetPath(false));
2741 lldb_private::StreamString stream;
2742 stream.PutCString("vFile:open:");
2745 stream.PutCStringAsRawHex8(path.c_str());
2746 stream.PutChar(',');
2747 stream.PutHex32(flags);
2748 stream.PutChar(',');
2749 stream.PutHex32(mode);
2750 StringExtractorGDBRemote response;
2751 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2752 PacketResult::Success) {
2753 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2758 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2759 lldb_private::StreamString stream;
2760 stream.Printf("vFile:close:%i", (int)fd);
2761 StringExtractorGDBRemote response;
2762 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2763 PacketResult::Success) {
2764 return ParseHostIOPacketResponse(response, -1, error) == 0;
2769 // Extension of host I/O packets to get the file size.
2770 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2771 const lldb_private::FileSpec &file_spec) {
2772 std::string path(file_spec.GetPath(false));
2773 lldb_private::StreamString stream;
2774 stream.PutCString("vFile:size:");
2775 stream.PutCStringAsRawHex8(path.c_str());
2776 StringExtractorGDBRemote response;
2777 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2778 PacketResult::Success) {
2779 if (response.GetChar() != 'F')
2781 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2787 Error GDBRemoteCommunicationClient::GetFilePermissions(
2788 const FileSpec &file_spec, uint32_t &file_permissions) {
2789 std::string path{file_spec.GetPath(false)};
2791 lldb_private::StreamString stream;
2792 stream.PutCString("vFile:mode:");
2793 stream.PutCStringAsRawHex8(path.c_str());
2794 StringExtractorGDBRemote response;
2795 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2796 PacketResult::Success) {
2797 if (response.GetChar() != 'F') {
2798 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2801 const uint32_t mode = response.GetS32(-1);
2802 if (static_cast<int32_t>(mode) == -1) {
2803 if (response.GetChar() == ',') {
2804 int response_errno = response.GetS32(-1);
2805 if (response_errno > 0)
2806 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2808 error.SetErrorToGenericError();
2810 error.SetErrorToGenericError();
2812 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2816 error.SetErrorStringWithFormat("failed to send '%s' packet",
2822 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2823 uint64_t offset, void *dst,
2826 lldb_private::StreamString stream;
2827 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2829 StringExtractorGDBRemote response;
2830 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2831 PacketResult::Success) {
2832 if (response.GetChar() != 'F')
2834 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2835 if (retcode == UINT32_MAX)
2837 const char next = (response.Peek() ? *response.Peek() : 0);
2841 response.GetChar(); // skip the semicolon
2843 if (response.GetEscapedBinaryData(buffer)) {
2844 const uint64_t data_to_write =
2845 std::min<uint64_t>(dst_len, buffer.size());
2846 if (data_to_write > 0)
2847 memcpy(dst, &buffer[0], data_to_write);
2848 return data_to_write;
2855 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2860 lldb_private::StreamGDBRemote stream;
2861 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2862 stream.PutEscapedBytes(src, src_len);
2863 StringExtractorGDBRemote response;
2864 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2865 PacketResult::Success) {
2866 if (response.GetChar() != 'F') {
2867 error.SetErrorStringWithFormat("write file failed");
2870 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2871 if (bytes_written == UINT64_MAX) {
2872 error.SetErrorToGenericError();
2873 if (response.GetChar() == ',') {
2874 int response_errno = response.GetS32(-1);
2875 if (response_errno > 0)
2876 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2880 return bytes_written;
2882 error.SetErrorString("failed to send vFile:pwrite packet");
2887 Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2888 const FileSpec &dst) {
2889 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2891 lldb_private::StreamGDBRemote stream;
2892 stream.PutCString("vFile:symlink:");
2893 // the unix symlink() command reverses its parameters where the dst if first,
2894 // so we follow suit here
2895 stream.PutCStringAsRawHex8(dst_path.c_str());
2896 stream.PutChar(',');
2897 stream.PutCStringAsRawHex8(src_path.c_str());
2898 StringExtractorGDBRemote response;
2899 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2900 PacketResult::Success) {
2901 if (response.GetChar() == 'F') {
2902 uint32_t result = response.GetU32(UINT32_MAX);
2904 error.SetErrorToGenericError();
2905 if (response.GetChar() == ',') {
2906 int response_errno = response.GetS32(-1);
2907 if (response_errno > 0)
2908 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2912 // Should have returned with 'F<result>[,<errno>]'
2913 error.SetErrorStringWithFormat("symlink failed");
2916 error.SetErrorString("failed to send vFile:symlink packet");
2921 Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2922 std::string path{file_spec.GetPath(false)};
2924 lldb_private::StreamGDBRemote stream;
2925 stream.PutCString("vFile:unlink:");
2926 // the unix symlink() command reverses its parameters where the dst if first,
2927 // so we follow suit here
2928 stream.PutCStringAsRawHex8(path.c_str());
2929 StringExtractorGDBRemote response;
2930 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2931 PacketResult::Success) {
2932 if (response.GetChar() == 'F') {
2933 uint32_t result = response.GetU32(UINT32_MAX);
2935 error.SetErrorToGenericError();
2936 if (response.GetChar() == ',') {
2937 int response_errno = response.GetS32(-1);
2938 if (response_errno > 0)
2939 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2943 // Should have returned with 'F<result>[,<errno>]'
2944 error.SetErrorStringWithFormat("unlink failed");
2947 error.SetErrorString("failed to send vFile:unlink packet");
2952 // Extension of host I/O packets to get whether a file exists.
2953 bool GDBRemoteCommunicationClient::GetFileExists(
2954 const lldb_private::FileSpec &file_spec) {
2955 std::string path(file_spec.GetPath(false));
2956 lldb_private::StreamString stream;
2957 stream.PutCString("vFile:exists:");
2958 stream.PutCStringAsRawHex8(path.c_str());
2959 StringExtractorGDBRemote response;
2960 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2961 PacketResult::Success) {
2962 if (response.GetChar() != 'F')
2964 if (response.GetChar() != ',')
2966 bool retcode = (response.GetChar() != '0');
2972 bool GDBRemoteCommunicationClient::CalculateMD5(
2973 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2974 std::string path(file_spec.GetPath(false));
2975 lldb_private::StreamString stream;
2976 stream.PutCString("vFile:MD5:");
2977 stream.PutCStringAsRawHex8(path.c_str());
2978 StringExtractorGDBRemote response;
2979 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2980 PacketResult::Success) {
2981 if (response.GetChar() != 'F')
2983 if (response.GetChar() != ',')
2985 if (response.Peek() && *response.Peek() == 'x')
2987 low = response.GetHexMaxU64(false, UINT64_MAX);
2988 high = response.GetHexMaxU64(false, UINT64_MAX);
2994 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
2995 // Some targets have issues with g/G packets and we need to avoid using them
2996 if (m_avoid_g_packets == eLazyBoolCalculate) {
2998 m_avoid_g_packets = eLazyBoolNo;
2999 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3000 if (arch.IsValid() &&
3001 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3002 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3003 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3004 m_avoid_g_packets = eLazyBoolYes;
3005 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3006 if (gdb_server_version != 0) {
3007 const char *gdb_server_name = GetGDBServerProgramName();
3008 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3009 if (gdb_server_version >= 310)
3010 m_avoid_g_packets = eLazyBoolNo;
3016 return m_avoid_g_packets == eLazyBoolYes;
3019 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3021 StreamString payload;
3022 payload.Printf("p%x", reg);
3023 StringExtractorGDBRemote response;
3024 if (SendThreadSpecificPacketAndWaitForResponse(
3025 tid, std::move(payload), response, false) != PacketResult::Success ||
3026 !response.IsNormalResponse())
3029 DataBufferSP buffer_sp(
3030 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3031 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3035 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3036 StreamString payload;
3037 payload.PutChar('g');
3038 StringExtractorGDBRemote response;
3039 if (SendThreadSpecificPacketAndWaitForResponse(
3040 tid, std::move(payload), response, false) != PacketResult::Success ||
3041 !response.IsNormalResponse())
3044 DataBufferSP buffer_sp(
3045 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3046 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3050 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3052 llvm::ArrayRef<uint8_t> data) {
3053 StreamString payload;
3054 payload.Printf("P%x=", reg_num);
3055 payload.PutBytesAsRawHex8(data.data(), data.size(),
3056 endian::InlHostByteOrder(),
3057 endian::InlHostByteOrder());
3058 StringExtractorGDBRemote response;
3059 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3061 PacketResult::Success &&
3062 response.IsOKResponse();
3065 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3066 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3067 StreamString payload;
3068 payload.PutChar('G');
3069 payload.PutBytesAsRawHex8(data.data(), data.size(),
3070 endian::InlHostByteOrder(),
3071 endian::InlHostByteOrder());
3072 StringExtractorGDBRemote response;
3073 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3075 PacketResult::Success &&
3076 response.IsOKResponse();
3079 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3080 uint32_t &save_id) {
3081 save_id = 0; // Set to invalid save ID
3082 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3085 m_supports_QSaveRegisterState = eLazyBoolYes;
3086 StreamString payload;
3087 payload.PutCString("QSaveRegisterState");
3088 StringExtractorGDBRemote response;
3089 if (SendThreadSpecificPacketAndWaitForResponse(
3090 tid, std::move(payload), response, false) != PacketResult::Success)
3093 if (response.IsUnsupportedResponse())
3094 m_supports_QSaveRegisterState = eLazyBoolNo;
3096 const uint32_t response_save_id = response.GetU32(0);
3097 if (response_save_id == 0)
3100 save_id = response_save_id;
3104 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3106 // We use the "m_supports_QSaveRegisterState" variable here because the
3107 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3109 // order to be useful
3110 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3113 StreamString payload;
3114 payload.Printf("QRestoreRegisterState:%u", save_id);
3115 StringExtractorGDBRemote response;
3116 if (SendThreadSpecificPacketAndWaitForResponse(
3117 tid, std::move(payload), response, false) != PacketResult::Success)
3120 if (response.IsOKResponse())
3123 if (response.IsUnsupportedResponse())
3124 m_supports_QSaveRegisterState = eLazyBoolNo;
3128 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3129 if (!GetSyncThreadStateSupported())
3132 StreamString packet;
3133 StringExtractorGDBRemote response;
3134 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3135 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3136 GDBRemoteCommunication::PacketResult::Success &&
3137 response.IsOKResponse();
3140 bool GDBRemoteCommunicationClient::GetModuleInfo(
3141 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3142 ModuleSpec &module_spec) {
3143 if (!m_supports_qModuleInfo)
3146 std::string module_path = module_file_spec.GetPath(false);
3147 if (module_path.empty())
3150 StreamString packet;
3151 packet.PutCString("qModuleInfo:");
3152 packet.PutCStringAsRawHex8(module_path.c_str());
3153 packet.PutCString(";");
3154 const auto &triple = arch_spec.GetTriple().getTriple();
3155 packet.PutCStringAsRawHex8(triple.c_str());
3157 StringExtractorGDBRemote response;
3158 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3159 PacketResult::Success)
3162 if (response.IsErrorResponse())
3165 if (response.IsUnsupportedResponse()) {
3166 m_supports_qModuleInfo = false;
3170 llvm::StringRef name;
3171 llvm::StringRef value;
3173 module_spec.Clear();
3174 module_spec.GetFileSpec() = module_file_spec;
3176 while (response.GetNameColonValue(name, value)) {
3177 if (name == "uuid" || name == "md5") {
3178 StringExtractor extractor(value);
3180 extractor.GetHexByteString(uuid);
3181 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3182 } else if (name == "triple") {
3183 StringExtractor extractor(value);
3185 extractor.GetHexByteString(triple);
3186 module_spec.GetArchitecture().SetTriple(triple.c_str());
3187 } else if (name == "file_offset") {
3189 if (!value.getAsInteger(16, ival))
3190 module_spec.SetObjectOffset(ival);
3191 } else if (name == "file_size") {
3193 if (!value.getAsInteger(16, ival))
3194 module_spec.SetObjectSize(ival);
3195 } else if (name == "file_path") {
3196 StringExtractor extractor(value);
3198 extractor.GetHexByteString(path);
3199 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec);
3206 static llvm::Optional<ModuleSpec>
3207 ParseModuleSpec(StructuredData::Dictionary *dict) {
3215 if (!dict->GetValueForKeyAsString("uuid", string))
3217 result.GetUUID().SetFromCString(string.c_str(), string.size());
3219 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3221 result.SetObjectOffset(integer);
3223 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3225 result.SetObjectSize(integer);
3227 if (!dict->GetValueForKeyAsString("triple", string))
3229 result.GetArchitecture().SetTriple(string.c_str());
3231 if (!dict->GetValueForKeyAsString("file_path", string))
3233 result.GetFileSpec() = FileSpec(string, false, result.GetArchitecture());
3238 llvm::Optional<std::vector<ModuleSpec>>
3239 GDBRemoteCommunicationClient::GetModulesInfo(
3240 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3241 if (!m_supports_jModulesInfo)
3244 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3245 for (const FileSpec &module_file_spec : module_file_specs) {
3246 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3247 module_array_sp->AppendObject(module_sp);
3248 module_sp->SetObject(
3249 "file", std::make_shared<JSONString>(module_file_spec.GetPath()));
3250 module_sp->SetObject("triple",
3251 std::make_shared<JSONString>(triple.getTriple()));
3253 StreamString unescaped_payload;
3254 unescaped_payload.PutCString("jModulesInfo:");
3255 module_array_sp->Write(unescaped_payload);
3256 StreamGDBRemote payload;
3257 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3258 unescaped_payload.GetSize());
3260 StringExtractorGDBRemote response;
3261 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3262 PacketResult::Success ||
3263 response.IsErrorResponse())
3266 if (response.IsUnsupportedResponse()) {
3267 m_supports_jModulesInfo = false;
3271 StructuredData::ObjectSP response_object_sp =
3272 StructuredData::ParseJSON(response.GetStringRef());
3273 if (!response_object_sp)
3276 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3277 if (!response_array)
3280 std::vector<ModuleSpec> result;
3281 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3282 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3283 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3284 result.push_back(*module_spec);
3290 // query the target remote for extended information using the qXfer packet
3292 // example: object='features', annex='target.xml', out=<xml output>
3293 // return: 'true' on success
3294 // 'false' on failure (err set)
3295 bool GDBRemoteCommunicationClient::ReadExtFeature(
3296 const lldb_private::ConstString object,
3297 const lldb_private::ConstString annex, std::string &out,
3298 lldb_private::Error &err) {
3300 std::stringstream output;
3301 StringExtractorGDBRemote chunk;
3303 uint64_t size = GetRemoteMaxPacketSize();
3306 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3310 // loop until all data has been read
3313 // send query extended feature packet
3314 std::stringstream packet;
3315 packet << "qXfer:" << object.AsCString("")
3316 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3317 << "," << std::hex << size;
3319 GDBRemoteCommunication::PacketResult res =
3320 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3322 if (res != GDBRemoteCommunication::PacketResult::Success) {
3323 err.SetErrorString("Error sending $qXfer packet");
3327 const std::string &str = chunk.GetStringRef();
3328 if (str.length() == 0) {
3329 // should have some data in chunk
3330 err.SetErrorString("Empty response from $qXfer packet");
3334 // check packet code
3343 if (str.length() > 1)
3350 err.SetErrorString("Invalid continuation code from $qXfer packet");
3360 // Notify the target that gdb is prepared to serve symbol lookup requests.
3361 // packet: "qSymbol::"
3363 // OK The target does not need to look up any (more) symbols.
3364 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3366 // LLDB may provide the value by sending another qSymbol
3368 // in the form of"qSymbol:<sym_value>:<sym_name>".
3372 // lldb sends: qSymbol::
3373 // lldb receives: OK
3374 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3376 // need to ask again in this session.
3378 // lldb sends: qSymbol::
3379 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3380 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3381 // lldb receives: OK
3382 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3384 // the address at this time. lldb needs to send qSymbol:: again when it has
3388 // lldb sends: qSymbol::
3389 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3390 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3391 // lldb receives: OK
3392 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3394 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3396 // need any more symbols. lldb does not need to ask again in this session.
3398 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3399 lldb_private::Process *process) {
3400 // Set to true once we've resolved a symbol to an address for the remote stub.
3401 // If we get an 'OK' response after this, the remote stub doesn't need any
3403 // symbols and we can stop asking.
3404 bool symbol_response_provided = false;
3406 // Is this the initial qSymbol:: packet?
3407 bool first_qsymbol_query = true;
3409 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3410 Lock lock(*this, false);
3412 StreamString packet;
3413 packet.PutCString("qSymbol::");
3414 StringExtractorGDBRemote response;
3415 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3416 PacketResult::Success) {
3417 if (response.IsOKResponse()) {
3418 if (symbol_response_provided || first_qsymbol_query) {
3419 m_qSymbol_requests_done = true;
3422 // We are done serving symbols requests
3425 first_qsymbol_query = false;
3427 if (response.IsUnsupportedResponse()) {
3428 // qSymbol is not supported by the current GDB server we are connected
3430 m_supports_qSymbol = false;
3433 llvm::StringRef response_str(response.GetStringRef());
3434 if (response_str.startswith("qSymbol:")) {
3435 response.SetFilePos(strlen("qSymbol:"));
3436 std::string symbol_name;
3437 if (response.GetHexByteString(symbol_name)) {
3438 if (symbol_name.empty())
3441 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3442 lldb_private::SymbolContextList sc_list;
3443 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3444 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3445 const size_t num_scs = sc_list.GetSize();
3446 for (size_t sc_idx = 0;
3448 symbol_load_addr == LLDB_INVALID_ADDRESS;
3451 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3453 switch (sc.symbol->GetType()) {
3454 case eSymbolTypeInvalid:
3455 case eSymbolTypeAbsolute:
3456 case eSymbolTypeUndefined:
3457 case eSymbolTypeSourceFile:
3458 case eSymbolTypeHeaderFile:
3459 case eSymbolTypeObjectFile:
3460 case eSymbolTypeCommonBlock:
3461 case eSymbolTypeBlock:
3462 case eSymbolTypeLocal:
3463 case eSymbolTypeParam:
3464 case eSymbolTypeVariable:
3465 case eSymbolTypeVariableType:
3466 case eSymbolTypeLineEntry:
3467 case eSymbolTypeLineHeader:
3468 case eSymbolTypeScopeBegin:
3469 case eSymbolTypeScopeEnd:
3470 case eSymbolTypeAdditional:
3471 case eSymbolTypeCompiler:
3472 case eSymbolTypeInstrumentation:
3473 case eSymbolTypeTrampoline:
3476 case eSymbolTypeCode:
3477 case eSymbolTypeResolver:
3478 case eSymbolTypeData:
3479 case eSymbolTypeRuntime:
3480 case eSymbolTypeException:
3481 case eSymbolTypeObjCClass:
3482 case eSymbolTypeObjCMetaClass:
3483 case eSymbolTypeObjCIVar:
3484 case eSymbolTypeReExported:
3486 sc.symbol->GetLoadAddress(&process->GetTarget());
3493 // This is the normal path where our symbol lookup was successful
3495 // to send a packet with the new symbol value and see if another
3496 // lookup needs to be
3499 // Change "packet" to contain the requested symbol value and name
3501 packet.PutCString("qSymbol:");
3502 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3503 packet.Printf("%" PRIx64, symbol_load_addr);
3504 symbol_response_provided = true;
3506 symbol_response_provided = false;
3508 packet.PutCString(":");
3509 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3510 continue; // go back to the while loop and send "packet" and wait
3511 // for another response
3516 // If we make it here, the symbol request packet response wasn't valid or
3517 // our symbol lookup failed so we must abort
3520 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3521 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3523 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3529 StructuredData::Array *
3530 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3531 if (!m_supported_async_json_packets_is_valid) {
3532 // Query the server for the array of supported asynchronous JSON
3534 m_supported_async_json_packets_is_valid = true;
3536 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3539 StringExtractorGDBRemote response;
3540 const bool send_async = false;
3541 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3542 send_async) == PacketResult::Success) {
3543 m_supported_async_json_packets_sp =
3544 StructuredData::ParseJSON(response.GetStringRef());
3545 if (m_supported_async_json_packets_sp &&
3546 !m_supported_async_json_packets_sp->GetAsArray()) {
3547 // We were returned something other than a JSON array. This
3548 // is invalid. Clear it out.
3550 log->Printf("GDBRemoteCommunicationClient::%s(): "
3551 "QSupportedAsyncJSONPackets returned invalid "
3553 __FUNCTION__, response.GetStringRef().c_str());
3554 m_supported_async_json_packets_sp.reset();
3558 log->Printf("GDBRemoteCommunicationClient::%s(): "
3559 "QSupportedAsyncJSONPackets unsupported",
3563 if (log && m_supported_async_json_packets_sp) {
3564 StreamString stream;
3565 m_supported_async_json_packets_sp->Dump(stream);
3566 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3568 __FUNCTION__, stream.GetData());
3572 return m_supported_async_json_packets_sp
3573 ? m_supported_async_json_packets_sp->GetAsArray()
3577 Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3578 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3581 if (type_name.GetLength() == 0) {
3582 error.SetErrorString("invalid type_name argument");
3586 // Build command: Configure{type_name}: serialized config
3588 StreamGDBRemote stream;
3589 stream.PutCString("QConfigure");
3590 stream.PutCString(type_name.AsCString());
3591 stream.PutChar(':');
3593 // Gather the plain-text version of the configuration data.
3594 StreamString unescaped_stream;
3595 config_sp->Dump(unescaped_stream);
3596 unescaped_stream.Flush();
3598 // Add it to the stream in escaped fashion.
3599 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
3600 unescaped_stream.GetSize());
3605 const bool send_async = false;
3606 StringExtractorGDBRemote response;
3608 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
3609 if (result == PacketResult::Success) {
3610 // We failed if the config result comes back other than OK.
3611 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3615 error.SetErrorStringWithFormat("configuring StructuredData feature "
3616 "%s failed with error %s",
3617 type_name.AsCString(),
3618 response.GetStringRef().c_str());
3621 // Can we get more data here on the failure?
3622 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3623 "failed when sending packet: "
3625 type_name.AsCString(), (int)result);
3630 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3631 GDBRemoteClientBase::OnRunPacketSent(first);
3632 m_curr_tid = LLDB_INVALID_THREAD_ID;