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"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Host/HostInfo.h"
20 #include "lldb/Host/XML.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Target/MemoryRegionInfo.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/UnixSignals.h"
25 #include "lldb/Utility/Args.h"
26 #include "lldb/Utility/DataBufferHeap.h"
27 #include "lldb/Utility/JSON.h"
28 #include "lldb/Utility/LLDBAssert.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/State.h"
31 #include "lldb/Utility/StreamString.h"
33 #include "ProcessGDBRemote.h"
34 #include "ProcessGDBRemoteLog.h"
35 #include "lldb/Host/Config.h"
36 #include "lldb/Utility/StringExtractorGDBRemote.h"
38 #include "llvm/ADT/StringSwitch.h"
40 #if defined(__APPLE__)
41 #define HAVE_LIBCOMPRESSION
42 #include <compression.h>
46 using namespace lldb_private;
47 using namespace lldb_private::process_gdb_remote;
48 using namespace std::chrono;
50 //----------------------------------------------------------------------
51 // GDBRemoteCommunicationClient constructor
52 //----------------------------------------------------------------------
53 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
54 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
55 m_supports_not_sending_acks(eLazyBoolCalculate),
56 m_supports_thread_suffix(eLazyBoolCalculate),
57 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
58 m_supports_vCont_all(eLazyBoolCalculate),
59 m_supports_vCont_any(eLazyBoolCalculate),
60 m_supports_vCont_c(eLazyBoolCalculate),
61 m_supports_vCont_C(eLazyBoolCalculate),
62 m_supports_vCont_s(eLazyBoolCalculate),
63 m_supports_vCont_S(eLazyBoolCalculate),
64 m_qHostInfo_is_valid(eLazyBoolCalculate),
65 m_curr_pid_is_valid(eLazyBoolCalculate),
66 m_qProcessInfo_is_valid(eLazyBoolCalculate),
67 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
68 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
69 m_supports_memory_region_info(eLazyBoolCalculate),
70 m_supports_watchpoint_support_info(eLazyBoolCalculate),
71 m_supports_detach_stay_stopped(eLazyBoolCalculate),
72 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
73 m_attach_or_wait_reply(eLazyBoolCalculate),
74 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
75 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
76 m_avoid_g_packets(eLazyBoolCalculate),
77 m_supports_QSaveRegisterState(eLazyBoolCalculate),
78 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
80 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
81 m_supports_qXfer_features_read(eLazyBoolCalculate),
82 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
83 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
85 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
86 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
87 m_supports_QPassSignals(eLazyBoolCalculate),
88 m_supports_error_string_reply(eLazyBoolCalculate),
89 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
90 m_supports_qUserName(true), m_supports_qGroupName(true),
91 m_supports_qThreadStopInfo(true), m_supports_z0(true),
92 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
93 m_supports_z4(true), m_supports_QEnvironment(true),
94 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
95 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
96 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
97 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
98 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
99 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
100 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
101 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
102 m_max_packet_size(0), m_qSupported_response(),
103 m_supported_async_json_packets_is_valid(false),
104 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
105 m_qXfer_memory_map_loaded(false) {}
107 //----------------------------------------------------------------------
109 //----------------------------------------------------------------------
110 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
115 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
116 ResetDiscoverableSettings(false);
118 // Start the read thread after we send the handshake ack since if we fail to
119 // send the handshake ack, there is no reason to continue...
121 // Wait for any responses that might have been queued up in the remote
122 // GDB server and flush them all
123 StringExtractorGDBRemote response;
124 PacketResult packet_result = PacketResult::Success;
125 while (packet_result == PacketResult::Success)
126 packet_result = ReadPacket(response, milliseconds(10), false);
128 // The return value from QueryNoAckModeSupported() is true if the packet
129 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
130 // false if no response was received. This quickly tells us if we have a
131 // live connection to a remote GDB server...
132 if (QueryNoAckModeSupported()) {
136 error_ptr->SetErrorString("failed to get reply to handshake packet");
140 error_ptr->SetErrorString("failed to send the handshake ack");
145 bool GDBRemoteCommunicationClient::GetEchoSupported() {
146 if (m_supports_qEcho == eLazyBoolCalculate) {
147 GetRemoteQSupported();
149 return m_supports_qEcho == eLazyBoolYes;
152 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
153 if (m_supports_QPassSignals == eLazyBoolCalculate) {
154 GetRemoteQSupported();
156 return m_supports_QPassSignals == eLazyBoolYes;
159 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
160 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
161 GetRemoteQSupported();
163 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
166 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
167 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
168 GetRemoteQSupported();
170 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
173 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
174 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
175 GetRemoteQSupported();
177 return m_supports_qXfer_libraries_read == eLazyBoolYes;
180 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
181 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
182 GetRemoteQSupported();
184 return m_supports_qXfer_auxv_read == eLazyBoolYes;
187 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
188 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
189 GetRemoteQSupported();
191 return m_supports_qXfer_features_read == eLazyBoolYes;
194 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
195 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
196 GetRemoteQSupported();
198 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
201 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
202 if (m_max_packet_size == 0) {
203 GetRemoteQSupported();
205 return m_max_packet_size;
208 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
209 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
211 m_supports_not_sending_acks = eLazyBoolNo;
213 // This is the first real packet that we'll send in a debug session and it
214 // may take a little longer than normal to receive a reply. Wait at least
215 // 6 seconds for a reply to this packet.
217 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
219 StringExtractorGDBRemote response;
220 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
221 PacketResult::Success) {
222 if (response.IsOKResponse()) {
224 m_supports_not_sending_acks = eLazyBoolYes;
232 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
233 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
234 m_supports_threads_in_stop_reply = eLazyBoolNo;
236 StringExtractorGDBRemote response;
237 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
238 false) == PacketResult::Success) {
239 if (response.IsOKResponse())
240 m_supports_threads_in_stop_reply = eLazyBoolYes;
245 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
246 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
247 m_attach_or_wait_reply = eLazyBoolNo;
249 StringExtractorGDBRemote response;
250 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
251 false) == PacketResult::Success) {
252 if (response.IsOKResponse())
253 m_attach_or_wait_reply = eLazyBoolYes;
256 return m_attach_or_wait_reply == eLazyBoolYes;
259 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
260 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
261 m_prepare_for_reg_writing_reply = eLazyBoolNo;
263 StringExtractorGDBRemote response;
264 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
265 false) == PacketResult::Success) {
266 if (response.IsOKResponse())
267 m_prepare_for_reg_writing_reply = eLazyBoolYes;
270 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
273 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
275 // Hard reset everything, this is when we first connect to a GDB server
276 m_supports_not_sending_acks = eLazyBoolCalculate;
277 m_supports_thread_suffix = eLazyBoolCalculate;
278 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
279 m_supports_vCont_c = eLazyBoolCalculate;
280 m_supports_vCont_C = eLazyBoolCalculate;
281 m_supports_vCont_s = eLazyBoolCalculate;
282 m_supports_vCont_S = eLazyBoolCalculate;
283 m_supports_p = eLazyBoolCalculate;
284 m_supports_x = eLazyBoolCalculate;
285 m_supports_QSaveRegisterState = eLazyBoolCalculate;
286 m_qHostInfo_is_valid = eLazyBoolCalculate;
287 m_curr_pid_is_valid = eLazyBoolCalculate;
288 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
289 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
290 m_supports_memory_region_info = eLazyBoolCalculate;
291 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
292 m_attach_or_wait_reply = eLazyBoolCalculate;
293 m_avoid_g_packets = eLazyBoolCalculate;
294 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
295 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qXfer_features_read = eLazyBoolCalculate;
298 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
300 m_supports_qProcessInfoPID = true;
301 m_supports_qfProcessInfo = true;
302 m_supports_qUserName = true;
303 m_supports_qGroupName = true;
304 m_supports_qThreadStopInfo = true;
305 m_supports_z0 = true;
306 m_supports_z1 = true;
307 m_supports_z2 = true;
308 m_supports_z3 = true;
309 m_supports_z4 = true;
310 m_supports_QEnvironment = true;
311 m_supports_QEnvironmentHexEncoded = true;
312 m_supports_qSymbol = true;
313 m_qSymbol_requests_done = false;
314 m_supports_qModuleInfo = true;
316 m_os_version = llvm::VersionTuple();
320 m_gdb_server_name.clear();
321 m_gdb_server_version = UINT32_MAX;
322 m_default_packet_timeout = seconds(0);
323 m_max_packet_size = 0;
324 m_qSupported_response.clear();
325 m_supported_async_json_packets_is_valid = false;
326 m_supported_async_json_packets_sp.reset();
327 m_supports_jModulesInfo = true;
330 // These flags should be reset when we first connect to a GDB server and when
331 // our inferior process execs
332 m_qProcessInfo_is_valid = eLazyBoolCalculate;
333 m_process_arch.Clear();
336 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
337 // Clear out any capabilities we expect to see in the qSupported response
338 m_supports_qXfer_auxv_read = eLazyBoolNo;
339 m_supports_qXfer_libraries_read = eLazyBoolNo;
340 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
341 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
342 m_supports_qXfer_features_read = eLazyBoolNo;
343 m_supports_qXfer_memory_map_read = eLazyBoolNo;
344 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
345 // not, we assume no limit
347 // build the qSupported packet
348 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
350 packet.PutCString("qSupported");
351 for (uint32_t i = 0; i < features.size(); ++i) {
352 packet.PutCString(i == 0 ? ":" : ";");
353 packet.PutCString(features[i]);
356 StringExtractorGDBRemote response;
357 if (SendPacketAndWaitForResponse(packet.GetString(), response,
358 /*send_async=*/false) ==
359 PacketResult::Success) {
360 const char *response_cstr = response.GetStringRef().c_str();
362 // Hang on to the qSupported packet, so that platforms can do custom
363 // configuration of the transport before attaching/launching the process.
364 m_qSupported_response = response_cstr;
366 if (::strstr(response_cstr, "qXfer:auxv:read+"))
367 m_supports_qXfer_auxv_read = eLazyBoolYes;
368 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
369 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
372 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
374 if (::strstr(response_cstr, "qXfer:libraries:read+"))
375 m_supports_qXfer_libraries_read = eLazyBoolYes;
376 if (::strstr(response_cstr, "qXfer:features:read+"))
377 m_supports_qXfer_features_read = eLazyBoolYes;
378 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
379 m_supports_qXfer_memory_map_read = eLazyBoolYes;
381 // Look for a list of compressions in the features list e.g.
382 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
384 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
386 const char *compressions =
387 ::strstr(features_list, "SupportedCompressions=");
389 std::vector<std::string> supported_compressions;
390 compressions += sizeof("SupportedCompressions=") - 1;
391 const char *end_of_compressions = strchr(compressions, ';');
392 if (end_of_compressions == NULL) {
393 end_of_compressions = strchr(compressions, '\0');
395 const char *current_compression = compressions;
396 while (current_compression < end_of_compressions) {
397 const char *next_compression_name = strchr(current_compression, ',');
398 const char *end_of_this_word = next_compression_name;
399 if (next_compression_name == NULL ||
400 end_of_compressions < next_compression_name) {
401 end_of_this_word = end_of_compressions;
404 if (end_of_this_word) {
405 if (end_of_this_word == current_compression) {
406 current_compression++;
408 std::string this_compression(
409 current_compression, end_of_this_word - current_compression);
410 supported_compressions.push_back(this_compression);
411 current_compression = end_of_this_word + 1;
414 supported_compressions.push_back(current_compression);
415 current_compression = end_of_compressions;
419 if (supported_compressions.size() > 0) {
420 MaybeEnableCompression(supported_compressions);
425 if (::strstr(response_cstr, "qEcho"))
426 m_supports_qEcho = eLazyBoolYes;
428 m_supports_qEcho = eLazyBoolNo;
430 if (::strstr(response_cstr, "QPassSignals+"))
431 m_supports_QPassSignals = eLazyBoolYes;
433 m_supports_QPassSignals = eLazyBoolNo;
435 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
436 if (packet_size_str) {
437 StringExtractorGDBRemote packet_response(packet_size_str +
438 strlen("PacketSize="));
440 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
441 if (m_max_packet_size == 0) {
442 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
444 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
446 log->Printf("Garbled PacketSize spec in qSupported response");
452 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
453 if (m_supports_thread_suffix == eLazyBoolCalculate) {
454 StringExtractorGDBRemote response;
455 m_supports_thread_suffix = eLazyBoolNo;
456 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
457 false) == PacketResult::Success) {
458 if (response.IsOKResponse())
459 m_supports_thread_suffix = eLazyBoolYes;
462 return m_supports_thread_suffix;
464 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
465 if (m_supports_vCont_c == eLazyBoolCalculate) {
466 StringExtractorGDBRemote response;
467 m_supports_vCont_any = eLazyBoolNo;
468 m_supports_vCont_all = eLazyBoolNo;
469 m_supports_vCont_c = eLazyBoolNo;
470 m_supports_vCont_C = eLazyBoolNo;
471 m_supports_vCont_s = eLazyBoolNo;
472 m_supports_vCont_S = eLazyBoolNo;
473 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
474 PacketResult::Success) {
475 const char *response_cstr = response.GetStringRef().c_str();
476 if (::strstr(response_cstr, ";c"))
477 m_supports_vCont_c = eLazyBoolYes;
479 if (::strstr(response_cstr, ";C"))
480 m_supports_vCont_C = eLazyBoolYes;
482 if (::strstr(response_cstr, ";s"))
483 m_supports_vCont_s = eLazyBoolYes;
485 if (::strstr(response_cstr, ";S"))
486 m_supports_vCont_S = eLazyBoolYes;
488 if (m_supports_vCont_c == eLazyBoolYes &&
489 m_supports_vCont_C == eLazyBoolYes &&
490 m_supports_vCont_s == eLazyBoolYes &&
491 m_supports_vCont_S == eLazyBoolYes) {
492 m_supports_vCont_all = eLazyBoolYes;
495 if (m_supports_vCont_c == eLazyBoolYes ||
496 m_supports_vCont_C == eLazyBoolYes ||
497 m_supports_vCont_s == eLazyBoolYes ||
498 m_supports_vCont_S == eLazyBoolYes) {
499 m_supports_vCont_any = eLazyBoolYes;
506 return m_supports_vCont_any;
508 return m_supports_vCont_all;
510 return m_supports_vCont_c;
512 return m_supports_vCont_C;
514 return m_supports_vCont_s;
516 return m_supports_vCont_S;
523 GDBRemoteCommunication::PacketResult
524 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
525 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
527 Lock lock(*this, send_async);
529 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
530 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
531 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
533 __FUNCTION__, payload.GetData());
534 return PacketResult::ErrorNoSequenceLock;
537 if (GetThreadSuffixSupported())
538 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
540 if (!SetCurrentThread(tid))
541 return PacketResult::ErrorSendFailed;
544 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
547 // Check if the target supports 'p' packet. It sends out a 'p' packet and
548 // checks the response. A normal packet will tell us that support is available.
550 // Takes a valid thread ID because p needs to apply to a thread.
551 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
552 if (m_supports_p == eLazyBoolCalculate) {
553 m_supports_p = eLazyBoolNo;
554 StreamString payload;
555 payload.PutCString("p0");
556 StringExtractorGDBRemote response;
557 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
559 PacketResult::Success &&
560 response.IsNormalResponse()) {
561 m_supports_p = eLazyBoolYes;
567 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
568 // Get information on all threads at one using the "jThreadsInfo" packet
569 StructuredData::ObjectSP object_sp;
571 if (m_supports_jThreadsInfo) {
572 StringExtractorGDBRemote response;
573 response.SetResponseValidatorToJSON();
574 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
575 PacketResult::Success) {
576 if (response.IsUnsupportedResponse()) {
577 m_supports_jThreadsInfo = false;
578 } else if (!response.Empty()) {
579 object_sp = StructuredData::ParseJSON(response.GetStringRef());
586 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
587 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
588 StringExtractorGDBRemote response;
589 m_supports_jThreadExtendedInfo = eLazyBoolNo;
590 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
591 PacketResult::Success) {
592 if (response.IsOKResponse()) {
593 m_supports_jThreadExtendedInfo = eLazyBoolYes;
597 return m_supports_jThreadExtendedInfo;
600 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
601 if (m_supports_error_string_reply == eLazyBoolCalculate) {
602 StringExtractorGDBRemote response;
603 // We try to enable error strings in remote packets but if we fail, we just
604 // work in the older way.
605 m_supports_error_string_reply = eLazyBoolNo;
606 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
607 PacketResult::Success) {
608 if (response.IsOKResponse()) {
609 m_supports_error_string_reply = eLazyBoolYes;
615 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
616 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
617 StringExtractorGDBRemote response;
618 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
619 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
621 false) == PacketResult::Success) {
622 if (response.IsOKResponse()) {
623 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
627 return m_supports_jLoadedDynamicLibrariesInfos;
630 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
631 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
632 StringExtractorGDBRemote response;
633 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
634 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
635 PacketResult::Success) {
636 if (response.IsOKResponse()) {
637 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
641 return m_supports_jGetSharedCacheInfo;
644 bool GDBRemoteCommunicationClient::GetxPacketSupported() {
645 if (m_supports_x == eLazyBoolCalculate) {
646 StringExtractorGDBRemote response;
647 m_supports_x = eLazyBoolNo;
649 snprintf(packet, sizeof(packet), "x0,0");
650 if (SendPacketAndWaitForResponse(packet, response, false) ==
651 PacketResult::Success) {
652 if (response.IsOKResponse())
653 m_supports_x = eLazyBoolYes;
659 GDBRemoteCommunicationClient::PacketResult
660 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
661 const char *payload_prefix, std::string &response_string) {
662 Lock lock(*this, false);
664 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
667 log->Printf("error: failed to get packet sequence mutex, not sending "
668 "packets with prefix '%s'",
670 return PacketResult::ErrorNoSequenceLock;
673 response_string = "";
674 std::string payload_prefix_str(payload_prefix);
675 unsigned int response_size = 0x1000;
676 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
677 response_size = GetRemoteMaxPacketSize();
680 for (unsigned int offset = 0; true; offset += response_size) {
681 StringExtractorGDBRemote this_response;
683 char sizeDescriptor[128];
684 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
686 PacketResult result = SendPacketAndWaitForResponseNoLock(
687 payload_prefix_str + sizeDescriptor, this_response);
688 if (result != PacketResult::Success)
691 const std::string &this_string = this_response.GetStringRef();
693 // Check for m or l as first character; l seems to mean this is the last
695 char first_char = *this_string.c_str();
696 if (first_char != 'm' && first_char != 'l') {
697 return PacketResult::ErrorReplyInvalid;
699 // Concatenate the result so far (skipping 'm' or 'l')
700 response_string.append(this_string, 1, std::string::npos);
701 if (first_char == 'l')
703 return PacketResult::Success;
707 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
708 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
711 // First try to retrieve the pid via the qProcessInfo request.
712 GetCurrentProcessInfo(allow_lazy);
713 if (m_curr_pid_is_valid == eLazyBoolYes) {
717 // If we don't get a response for qProcessInfo, check if $qC gives us a
718 // result. $qC only returns a real process id on older debugserver and
719 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
720 // the thread id, which newer debugserver and lldb-gdbserver stubs return
722 StringExtractorGDBRemote response;
723 if (SendPacketAndWaitForResponse("qC", response, false) ==
724 PacketResult::Success) {
725 if (response.GetChar() == 'Q') {
726 if (response.GetChar() == 'C') {
727 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
728 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
729 m_curr_pid_is_valid = eLazyBoolYes;
736 // If we don't get a response for $qC, check if $qfThreadID gives us a
738 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
739 std::vector<lldb::tid_t> thread_ids;
740 bool sequence_mutex_unavailable;
742 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
743 if (size && !sequence_mutex_unavailable) {
744 m_curr_pid = thread_ids.front();
745 m_curr_pid_is_valid = eLazyBoolYes;
751 return LLDB_INVALID_PROCESS_ID;
754 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
756 StringExtractorGDBRemote response;
757 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
758 PacketResult::Success) {
759 if (response.IsOKResponse())
761 if (response.GetChar() == 'E') {
762 // A string the describes what failed when launching...
763 error_str = response.GetStringRef().substr(1);
765 error_str.assign("unknown error occurred launching process");
768 error_str.assign("timed out waiting for app to launch");
773 int GDBRemoteCommunicationClient::SendArgumentsPacket(
774 const ProcessLaunchInfo &launch_info) {
775 // Since we don't get the send argv0 separate from the executable path, we
776 // need to make sure to use the actual executable path found in the
778 std::vector<const char *> argv;
779 FileSpec exe_file = launch_info.GetExecutableFile();
780 std::string exe_path;
781 const char *arg = NULL;
782 const Args &launch_args = launch_info.GetArguments();
784 exe_path = exe_file.GetPath(false);
786 arg = launch_args.GetArgumentAtIndex(0);
790 if (!exe_path.empty()) {
791 argv.push_back(exe_path.c_str());
792 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
801 for (size_t i = 0, n = argv.size(); i < n; ++i) {
803 const int arg_len = strlen(arg);
806 packet.Printf("%i,%i,", arg_len * 2, (int)i);
807 packet.PutBytesAsRawHex8(arg, arg_len);
810 StringExtractorGDBRemote response;
811 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
812 PacketResult::Success) {
813 if (response.IsOKResponse())
815 uint8_t error = response.GetError();
823 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
824 for (const auto &KV : env) {
825 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
832 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
833 char const *name_equal_value) {
834 if (name_equal_value && name_equal_value[0]) {
836 bool send_hex_encoding = false;
837 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
845 send_hex_encoding = true;
851 // We have non printable characters, lets hex encode this...
852 send_hex_encoding = true;
856 StringExtractorGDBRemote response;
857 if (send_hex_encoding) {
858 if (m_supports_QEnvironmentHexEncoded) {
859 packet.PutCString("QEnvironmentHexEncoded:");
860 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
861 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
862 PacketResult::Success) {
863 if (response.IsOKResponse())
865 uint8_t error = response.GetError();
868 if (response.IsUnsupportedResponse())
869 m_supports_QEnvironmentHexEncoded = false;
873 } else if (m_supports_QEnvironment) {
874 packet.Printf("QEnvironment:%s", name_equal_value);
875 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
876 PacketResult::Success) {
877 if (response.IsOKResponse())
879 uint8_t error = response.GetError();
882 if (response.IsUnsupportedResponse())
883 m_supports_QEnvironment = false;
890 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
891 if (arch && arch[0]) {
893 packet.Printf("QLaunchArch:%s", arch);
894 StringExtractorGDBRemote response;
895 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
896 PacketResult::Success) {
897 if (response.IsOKResponse())
899 uint8_t error = response.GetError();
907 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
908 char const *data, bool *was_supported) {
909 if (data && *data != '\0') {
911 packet.Printf("QSetProcessEvent:%s", data);
912 StringExtractorGDBRemote response;
913 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
914 PacketResult::Success) {
915 if (response.IsOKResponse()) {
917 *was_supported = true;
919 } else if (response.IsUnsupportedResponse()) {
921 *was_supported = false;
924 uint8_t error = response.GetError();
926 *was_supported = true;
935 llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
940 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
942 if (!m_os_build.empty()) {
951 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
953 if (!m_os_kernel.empty()) {
962 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
964 if (!m_hostname.empty()) {
973 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
979 const lldb_private::ArchSpec &
980 GDBRemoteCommunicationClient::GetProcessArchitecture() {
981 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
982 GetCurrentProcessInfo();
983 return m_process_arch;
986 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
987 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
988 m_gdb_server_name.clear();
989 m_gdb_server_version = 0;
990 m_qGDBServerVersion_is_valid = eLazyBoolNo;
992 StringExtractorGDBRemote response;
993 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
994 PacketResult::Success) {
995 if (response.IsNormalResponse()) {
996 llvm::StringRef name, value;
997 bool success = false;
998 while (response.GetNameColonValue(name, value)) {
999 if (name.equals("name")) {
1001 m_gdb_server_name = value;
1002 } else if (name.equals("version")) {
1003 llvm::StringRef major, minor;
1004 std::tie(major, minor) = value.split('.');
1005 if (!major.getAsInteger(0, m_gdb_server_version))
1010 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1014 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1017 void GDBRemoteCommunicationClient::MaybeEnableCompression(
1018 std::vector<std::string> supported_compressions) {
1019 CompressionType avail_type = CompressionType::None;
1020 std::string avail_name;
1022 #if defined(HAVE_LIBCOMPRESSION)
1023 if (avail_type == CompressionType::None) {
1024 for (auto compression : supported_compressions) {
1025 if (compression == "lzfse") {
1026 avail_type = CompressionType::LZFSE;
1027 avail_name = compression;
1034 #if defined(HAVE_LIBCOMPRESSION)
1035 if (avail_type == CompressionType::None) {
1036 for (auto compression : supported_compressions) {
1037 if (compression == "zlib-deflate") {
1038 avail_type = CompressionType::ZlibDeflate;
1039 avail_name = compression;
1046 #if defined(HAVE_LIBZ)
1047 if (avail_type == CompressionType::None) {
1048 for (auto compression : supported_compressions) {
1049 if (compression == "zlib-deflate") {
1050 avail_type = CompressionType::ZlibDeflate;
1051 avail_name = compression;
1058 #if defined(HAVE_LIBCOMPRESSION)
1059 if (avail_type == CompressionType::None) {
1060 for (auto compression : supported_compressions) {
1061 if (compression == "lz4") {
1062 avail_type = CompressionType::LZ4;
1063 avail_name = compression;
1070 #if defined(HAVE_LIBCOMPRESSION)
1071 if (avail_type == CompressionType::None) {
1072 for (auto compression : supported_compressions) {
1073 if (compression == "lzma") {
1074 avail_type = CompressionType::LZMA;
1075 avail_name = compression;
1082 if (avail_type != CompressionType::None) {
1083 StringExtractorGDBRemote response;
1084 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1085 if (SendPacketAndWaitForResponse(packet, response, false) !=
1086 PacketResult::Success)
1089 if (response.IsOKResponse()) {
1090 m_compression_type = avail_type;
1095 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1096 if (GetGDBServerVersion()) {
1097 if (!m_gdb_server_name.empty())
1098 return m_gdb_server_name.c_str();
1103 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1104 if (GetGDBServerVersion())
1105 return m_gdb_server_version;
1109 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1110 StringExtractorGDBRemote response;
1111 if (SendPacketAndWaitForResponse("qC", response, false) !=
1112 PacketResult::Success)
1115 if (!response.IsNormalResponse())
1118 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1119 tid = response.GetHexMaxU32(true, -1);
1124 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1125 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1127 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1128 // host info computation can require DNS traffic and shelling out to external processes.
1129 // Increase the timeout to account for that.
1130 ScopedTimeout timeout(*this, seconds(10));
1131 m_qHostInfo_is_valid = eLazyBoolNo;
1132 StringExtractorGDBRemote response;
1133 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1134 PacketResult::Success) {
1135 if (response.IsNormalResponse()) {
1136 llvm::StringRef name;
1137 llvm::StringRef value;
1138 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1140 std::string arch_name;
1141 std::string os_name;
1142 std::string vendor_name;
1144 std::string distribution_id;
1145 uint32_t pointer_byte_size = 0;
1146 ByteOrder byte_order = eByteOrderInvalid;
1147 uint32_t num_keys_decoded = 0;
1148 while (response.GetNameColonValue(name, value)) {
1149 if (name.equals("cputype")) {
1150 // exception type in big endian hex
1151 if (!value.getAsInteger(0, cpu))
1153 } else if (name.equals("cpusubtype")) {
1154 // exception count in big endian hex
1155 if (!value.getAsInteger(0, sub))
1157 } else if (name.equals("arch")) {
1160 } else if (name.equals("triple")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(triple);
1164 } else if (name.equals("distribution_id")) {
1165 StringExtractor extractor(value);
1166 extractor.GetHexByteString(distribution_id);
1168 } else if (name.equals("os_build")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(m_os_build);
1172 } else if (name.equals("hostname")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(m_hostname);
1176 } else if (name.equals("os_kernel")) {
1177 StringExtractor extractor(value);
1178 extractor.GetHexByteString(m_os_kernel);
1180 } else if (name.equals("ostype")) {
1183 } else if (name.equals("vendor")) {
1184 vendor_name = value;
1186 } else if (name.equals("endian")) {
1187 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1188 .Case("little", eByteOrderLittle)
1189 .Case("big", eByteOrderBig)
1190 .Case("pdp", eByteOrderPDP)
1191 .Default(eByteOrderInvalid);
1192 if (byte_order != eByteOrderInvalid)
1194 } else if (name.equals("ptrsize")) {
1195 if (!value.getAsInteger(0, pointer_byte_size))
1197 } else if (name.equals("os_version") ||
1199 "version")) // Older debugserver binaries used the
1200 // "version" key instead of
1203 if (!m_os_version.tryParse(value))
1205 } else if (name.equals("watchpoint_exceptions_received")) {
1206 m_watchpoints_trigger_after_instruction =
1207 llvm::StringSwitch<LazyBool>(value)
1208 .Case("before", eLazyBoolNo)
1209 .Case("after", eLazyBoolYes)
1210 .Default(eLazyBoolCalculate);
1211 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1213 } else if (name.equals("default_packet_timeout")) {
1214 uint32_t timeout_seconds;
1215 if (!value.getAsInteger(0, timeout_seconds)) {
1216 m_default_packet_timeout = seconds(timeout_seconds);
1217 SetPacketTimeout(m_default_packet_timeout);
1223 if (num_keys_decoded > 0)
1224 m_qHostInfo_is_valid = eLazyBoolYes;
1226 if (triple.empty()) {
1227 if (arch_name.empty()) {
1228 if (cpu != LLDB_INVALID_CPUTYPE) {
1229 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1230 if (pointer_byte_size) {
1231 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1233 if (byte_order != eByteOrderInvalid) {
1234 assert(byte_order == m_host_arch.GetByteOrder());
1237 if (!vendor_name.empty())
1238 m_host_arch.GetTriple().setVendorName(
1239 llvm::StringRef(vendor_name));
1240 if (!os_name.empty())
1241 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1245 triple += arch_name;
1246 if (!vendor_name.empty() || !os_name.empty()) {
1248 if (vendor_name.empty())
1249 triple += "unknown";
1251 triple += vendor_name;
1253 if (os_name.empty())
1254 triple += "unknown";
1258 m_host_arch.SetTriple(triple.c_str());
1260 llvm::Triple &host_triple = m_host_arch.GetTriple();
1261 if (host_triple.getVendor() == llvm::Triple::Apple &&
1262 host_triple.getOS() == llvm::Triple::Darwin) {
1263 switch (m_host_arch.GetMachine()) {
1264 case llvm::Triple::aarch64:
1265 case llvm::Triple::arm:
1266 case llvm::Triple::thumb:
1267 host_triple.setOS(llvm::Triple::IOS);
1270 host_triple.setOS(llvm::Triple::MacOSX);
1274 if (pointer_byte_size) {
1275 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1277 if (byte_order != eByteOrderInvalid) {
1278 assert(byte_order == m_host_arch.GetByteOrder());
1282 m_host_arch.SetTriple(triple.c_str());
1283 if (pointer_byte_size) {
1284 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1286 if (byte_order != eByteOrderInvalid) {
1287 assert(byte_order == m_host_arch.GetByteOrder());
1291 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1292 "architecture as %s, triple as %s from triple text %s",
1293 __FUNCTION__, m_host_arch.GetArchitectureName()
1294 ? m_host_arch.GetArchitectureName()
1295 : "<null-arch-name>",
1296 m_host_arch.GetTriple().getTriple().c_str(),
1299 if (!distribution_id.empty())
1300 m_host_arch.SetDistributionId(distribution_id.c_str());
1304 return m_qHostInfo_is_valid == eLazyBoolYes;
1307 int GDBRemoteCommunicationClient::SendAttach(
1308 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1309 if (pid != LLDB_INVALID_PROCESS_ID) {
1311 const int packet_len =
1312 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1313 UNUSED_IF_ASSERT_DISABLED(packet_len);
1314 assert(packet_len < (int)sizeof(packet));
1315 if (SendPacketAndWaitForResponse(packet, response, false) ==
1316 PacketResult::Success) {
1317 if (response.IsErrorResponse())
1318 return response.GetError();
1325 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1327 StreamString packet;
1328 packet.PutCString("I");
1329 packet.PutBytesAsRawHex8(data, data_len);
1330 StringExtractorGDBRemote response;
1331 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1332 PacketResult::Success) {
1335 return response.GetError();
1338 const lldb_private::ArchSpec &
1339 GDBRemoteCommunicationClient::GetHostArchitecture() {
1340 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1345 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1346 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1348 return m_default_packet_timeout;
1351 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1352 uint32_t permissions) {
1353 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1354 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1356 const int packet_len = ::snprintf(
1357 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1358 permissions & lldb::ePermissionsReadable ? "r" : "",
1359 permissions & lldb::ePermissionsWritable ? "w" : "",
1360 permissions & lldb::ePermissionsExecutable ? "x" : "");
1361 assert(packet_len < (int)sizeof(packet));
1362 UNUSED_IF_ASSERT_DISABLED(packet_len);
1363 StringExtractorGDBRemote response;
1364 if (SendPacketAndWaitForResponse(packet, response, false) ==
1365 PacketResult::Success) {
1366 if (response.IsUnsupportedResponse())
1367 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1368 else if (!response.IsErrorResponse())
1369 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1371 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1374 return LLDB_INVALID_ADDRESS;
1377 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1378 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1379 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1381 const int packet_len =
1382 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1383 assert(packet_len < (int)sizeof(packet));
1384 UNUSED_IF_ASSERT_DISABLED(packet_len);
1385 StringExtractorGDBRemote response;
1386 if (SendPacketAndWaitForResponse(packet, response, false) ==
1387 PacketResult::Success) {
1388 if (response.IsUnsupportedResponse())
1389 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1390 else if (response.IsOKResponse())
1393 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1399 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1403 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1405 const int packet_len =
1406 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1407 assert(packet_len < (int)sizeof(packet));
1408 UNUSED_IF_ASSERT_DISABLED(packet_len);
1409 StringExtractorGDBRemote response;
1410 if (SendPacketAndWaitForResponse(packet, response, false) ==
1411 PacketResult::Success &&
1412 response.IsOKResponse()) {
1413 m_supports_detach_stay_stopped = eLazyBoolYes;
1415 m_supports_detach_stay_stopped = eLazyBoolNo;
1419 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1420 error.SetErrorString("Stays stopped not supported by this target.");
1423 StringExtractorGDBRemote response;
1424 PacketResult packet_result =
1425 SendPacketAndWaitForResponse("D1", response, false);
1426 if (packet_result != PacketResult::Success)
1427 error.SetErrorString("Sending extended disconnect packet failed.");
1430 StringExtractorGDBRemote response;
1431 PacketResult packet_result =
1432 SendPacketAndWaitForResponse("D", response, false);
1433 if (packet_result != PacketResult::Success)
1434 error.SetErrorString("Sending disconnect packet failed.");
1439 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1440 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1442 region_info.Clear();
1444 if (m_supports_memory_region_info != eLazyBoolNo) {
1445 m_supports_memory_region_info = eLazyBoolYes;
1447 const int packet_len = ::snprintf(
1448 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1449 assert(packet_len < (int)sizeof(packet));
1450 UNUSED_IF_ASSERT_DISABLED(packet_len);
1451 StringExtractorGDBRemote response;
1452 if (SendPacketAndWaitForResponse(packet, response, false) ==
1453 PacketResult::Success &&
1454 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
1455 llvm::StringRef name;
1456 llvm::StringRef value;
1457 addr_t addr_value = LLDB_INVALID_ADDRESS;
1458 bool success = true;
1459 bool saw_permissions = false;
1460 while (success && response.GetNameColonValue(name, value)) {
1461 if (name.equals("start")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetRangeBase(addr_value);
1464 } else if (name.equals("size")) {
1465 if (!value.getAsInteger(16, addr_value))
1466 region_info.GetRange().SetByteSize(addr_value);
1467 } else if (name.equals("permissions") &&
1468 region_info.GetRange().IsValid()) {
1469 saw_permissions = true;
1470 if (region_info.GetRange().Contains(addr)) {
1471 if (value.find('r') != llvm::StringRef::npos)
1472 region_info.SetReadable(MemoryRegionInfo::eYes);
1474 region_info.SetReadable(MemoryRegionInfo::eNo);
1476 if (value.find('w') != llvm::StringRef::npos)
1477 region_info.SetWritable(MemoryRegionInfo::eYes);
1479 region_info.SetWritable(MemoryRegionInfo::eNo);
1481 if (value.find('x') != llvm::StringRef::npos)
1482 region_info.SetExecutable(MemoryRegionInfo::eYes);
1484 region_info.SetExecutable(MemoryRegionInfo::eNo);
1486 region_info.SetMapped(MemoryRegionInfo::eYes);
1488 // The reported region does not contain this address -- we're
1489 // looking at an unmapped page
1490 region_info.SetReadable(MemoryRegionInfo::eNo);
1491 region_info.SetWritable(MemoryRegionInfo::eNo);
1492 region_info.SetExecutable(MemoryRegionInfo::eNo);
1493 region_info.SetMapped(MemoryRegionInfo::eNo);
1495 } else if (name.equals("name")) {
1496 StringExtractorGDBRemote name_extractor(value);
1498 name_extractor.GetHexByteString(name);
1499 region_info.SetName(name.c_str());
1500 } else if (name.equals("error")) {
1501 StringExtractorGDBRemote error_extractor(value);
1502 std::string error_string;
1503 // Now convert the HEX bytes into a string value
1504 error_extractor.GetHexByteString(error_string);
1505 error.SetErrorString(error_string.c_str());
1509 if (region_info.GetRange().IsValid()) {
1510 // We got a valid address range back but no permissions -- which means
1511 // this is an unmapped page
1512 if (!saw_permissions) {
1513 region_info.SetReadable(MemoryRegionInfo::eNo);
1514 region_info.SetWritable(MemoryRegionInfo::eNo);
1515 region_info.SetExecutable(MemoryRegionInfo::eNo);
1516 region_info.SetMapped(MemoryRegionInfo::eNo);
1519 // We got an invalid address range back
1520 error.SetErrorString("Server returned invalid range");
1523 m_supports_memory_region_info = eLazyBoolNo;
1527 if (m_supports_memory_region_info == eLazyBoolNo) {
1528 error.SetErrorString("qMemoryRegionInfo is not supported");
1531 // Try qXfer:memory-map:read to get region information not included in
1532 // qMemoryRegionInfo
1533 MemoryRegionInfo qXfer_region_info;
1534 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1537 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1538 // the qXfer result as a fallback
1539 if (qXfer_error.Success()) {
1540 region_info = qXfer_region_info;
1543 region_info.Clear();
1545 } else if (qXfer_error.Success()) {
1546 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1547 // both regions are the same range, update the result to include the flash-
1548 // memory information that is specific to the qXfer result.
1549 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1550 region_info.SetFlash(qXfer_region_info.GetFlash());
1551 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1557 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1558 lldb::addr_t addr, MemoryRegionInfo ®ion) {
1559 Status error = LoadQXferMemoryMap();
1560 if (!error.Success())
1562 for (const auto &map_region : m_qXfer_memory_map) {
1563 if (map_region.GetRange().Contains(addr)) {
1564 region = map_region;
1568 error.SetErrorString("Region not found");
1572 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1576 if (m_qXfer_memory_map_loaded)
1577 // Already loaded, return success
1580 if (!XMLDocument::XMLEnabled()) {
1581 error.SetErrorString("XML is not supported");
1585 if (!GetQXferMemoryMapReadSupported()) {
1586 error.SetErrorString("Memory map is not supported");
1591 lldb_private::Status lldberr;
1592 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1594 error.SetErrorString("Failed to read memory map");
1598 XMLDocument xml_document;
1600 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1601 error.SetErrorString("Failed to parse memory map xml");
1605 XMLNode map_node = xml_document.GetRootElement("memory-map");
1607 error.SetErrorString("Invalid root node in memory map xml");
1611 m_qXfer_memory_map.clear();
1613 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1614 if (!memory_node.IsElement())
1616 if (memory_node.GetName() != "memory")
1618 auto type = memory_node.GetAttributeValue("type", "");
1621 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1623 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1625 MemoryRegionInfo region;
1626 region.GetRange().SetRangeBase(start);
1627 region.GetRange().SetByteSize(length);
1628 if (type == "rom") {
1629 region.SetReadable(MemoryRegionInfo::eYes);
1630 this->m_qXfer_memory_map.push_back(region);
1631 } else if (type == "ram") {
1632 region.SetReadable(MemoryRegionInfo::eYes);
1633 region.SetWritable(MemoryRegionInfo::eYes);
1634 this->m_qXfer_memory_map.push_back(region);
1635 } else if (type == "flash") {
1636 region.SetFlash(MemoryRegionInfo::eYes);
1637 memory_node.ForEachChildElement(
1638 [®ion](const XMLNode &prop_node) -> bool {
1639 if (!prop_node.IsElement())
1641 if (prop_node.GetName() != "property")
1643 auto propname = prop_node.GetAttributeValue("name", "");
1644 if (propname == "blocksize") {
1646 if (prop_node.GetElementTextAsUnsigned(blocksize))
1647 region.SetBlocksize(blocksize);
1651 this->m_qXfer_memory_map.push_back(region);
1656 m_qXfer_memory_map_loaded = true;
1661 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1664 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1665 num = m_num_supported_hardware_watchpoints;
1669 // Set num to 0 first.
1671 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1673 const int packet_len =
1674 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1675 assert(packet_len < (int)sizeof(packet));
1676 UNUSED_IF_ASSERT_DISABLED(packet_len);
1677 StringExtractorGDBRemote response;
1678 if (SendPacketAndWaitForResponse(packet, response, false) ==
1679 PacketResult::Success) {
1680 m_supports_watchpoint_support_info = eLazyBoolYes;
1681 llvm::StringRef name;
1682 llvm::StringRef value;
1683 bool found_num_field = false;
1684 while (response.GetNameColonValue(name, value)) {
1685 if (name.equals("num")) {
1686 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1687 num = m_num_supported_hardware_watchpoints;
1688 found_num_field = true;
1691 if (!found_num_field) {
1692 m_supports_watchpoint_support_info = eLazyBoolNo;
1695 m_supports_watchpoint_support_info = eLazyBoolNo;
1699 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1700 error.SetErrorString("qWatchpointSupportInfo is not supported");
1705 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1706 uint32_t &num, bool &after, const ArchSpec &arch) {
1707 Status error(GetWatchpointSupportInfo(num));
1708 if (error.Success())
1709 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1713 lldb_private::Status
1714 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1715 bool &after, const ArchSpec &arch) {
1717 llvm::Triple::ArchType atype = arch.GetMachine();
1719 // we assume watchpoints will happen after running the relevant opcode and we
1720 // only want to override this behavior if we have explicitly received a
1721 // qHostInfo telling us otherwise
1722 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1723 // On targets like MIPS and ppc64le, watchpoint exceptions are always
1724 // generated before the instruction is executed. The connected target may
1725 // not support qHostInfo or qWatchpointSupportInfo packets.
1727 !(atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1728 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1729 atype == llvm::Triple::ppc64le);
1731 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1732 // eLazyBoolNo if it is not calculated before.
1733 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1734 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1735 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1736 atype == llvm::Triple::ppc64le) {
1737 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1740 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1745 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1747 std::string path{file_spec.GetPath(false)};
1748 StreamString packet;
1749 packet.PutCString("QSetSTDIN:");
1750 packet.PutCStringAsRawHex8(path.c_str());
1752 StringExtractorGDBRemote response;
1753 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1754 PacketResult::Success) {
1755 if (response.IsOKResponse())
1757 uint8_t error = response.GetError();
1765 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1767 std::string path{file_spec.GetPath(false)};
1768 StreamString packet;
1769 packet.PutCString("QSetSTDOUT:");
1770 packet.PutCStringAsRawHex8(path.c_str());
1772 StringExtractorGDBRemote response;
1773 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1774 PacketResult::Success) {
1775 if (response.IsOKResponse())
1777 uint8_t error = response.GetError();
1785 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1787 std::string path{file_spec.GetPath(false)};
1788 StreamString packet;
1789 packet.PutCString("QSetSTDERR:");
1790 packet.PutCStringAsRawHex8(path.c_str());
1792 StringExtractorGDBRemote response;
1793 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1794 PacketResult::Success) {
1795 if (response.IsOKResponse())
1797 uint8_t error = response.GetError();
1805 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1806 StringExtractorGDBRemote response;
1807 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1808 PacketResult::Success) {
1809 if (response.IsUnsupportedResponse())
1811 if (response.IsErrorResponse())
1814 response.GetHexByteString(cwd);
1815 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1816 return !cwd.empty();
1821 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1823 std::string path{working_dir.GetPath(false)};
1824 StreamString packet;
1825 packet.PutCString("QSetWorkingDir:");
1826 packet.PutCStringAsRawHex8(path.c_str());
1828 StringExtractorGDBRemote response;
1829 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1830 PacketResult::Success) {
1831 if (response.IsOKResponse())
1833 uint8_t error = response.GetError();
1841 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1843 const int packet_len =
1844 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1845 assert(packet_len < (int)sizeof(packet));
1846 UNUSED_IF_ASSERT_DISABLED(packet_len);
1847 StringExtractorGDBRemote response;
1848 if (SendPacketAndWaitForResponse(packet, response, false) ==
1849 PacketResult::Success) {
1850 if (response.IsOKResponse())
1852 uint8_t error = response.GetError();
1859 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1861 const int packet_len = ::snprintf(packet, sizeof(packet),
1862 "QSetDetachOnError:%i", enable ? 1 : 0);
1863 assert(packet_len < (int)sizeof(packet));
1864 UNUSED_IF_ASSERT_DISABLED(packet_len);
1865 StringExtractorGDBRemote response;
1866 if (SendPacketAndWaitForResponse(packet, response, false) ==
1867 PacketResult::Success) {
1868 if (response.IsOKResponse())
1870 uint8_t error = response.GetError();
1877 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1878 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1879 if (response.IsNormalResponse()) {
1880 llvm::StringRef name;
1881 llvm::StringRef value;
1882 StringExtractor extractor;
1884 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1887 std::string os_type;
1889 while (response.GetNameColonValue(name, value)) {
1890 if (name.equals("pid")) {
1891 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1892 value.getAsInteger(0, pid);
1893 process_info.SetProcessID(pid);
1894 } else if (name.equals("ppid")) {
1895 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1896 value.getAsInteger(0, pid);
1897 process_info.SetParentProcessID(pid);
1898 } else if (name.equals("uid")) {
1899 uint32_t uid = UINT32_MAX;
1900 value.getAsInteger(0, uid);
1901 process_info.SetUserID(uid);
1902 } else if (name.equals("euid")) {
1903 uint32_t uid = UINT32_MAX;
1904 value.getAsInteger(0, uid);
1905 process_info.SetEffectiveGroupID(uid);
1906 } else if (name.equals("gid")) {
1907 uint32_t gid = UINT32_MAX;
1908 value.getAsInteger(0, gid);
1909 process_info.SetGroupID(gid);
1910 } else if (name.equals("egid")) {
1911 uint32_t gid = UINT32_MAX;
1912 value.getAsInteger(0, gid);
1913 process_info.SetEffectiveGroupID(gid);
1914 } else if (name.equals("triple")) {
1915 StringExtractor extractor(value);
1917 extractor.GetHexByteString(triple);
1918 process_info.GetArchitecture().SetTriple(triple.c_str());
1919 } else if (name.equals("name")) {
1920 StringExtractor extractor(value);
1921 // The process name from ASCII hex bytes since we can't control the
1922 // characters in a process name
1924 extractor.GetHexByteString(name);
1925 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
1926 } else if (name.equals("cputype")) {
1927 value.getAsInteger(0, cpu);
1928 } else if (name.equals("cpusubtype")) {
1929 value.getAsInteger(0, sub);
1930 } else if (name.equals("vendor")) {
1932 } else if (name.equals("ostype")) {
1937 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1938 if (vendor == "apple") {
1939 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1941 process_info.GetArchitecture().GetTriple().setVendorName(
1942 llvm::StringRef(vendor));
1943 process_info.GetArchitecture().GetTriple().setOSName(
1944 llvm::StringRef(os_type));
1948 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1954 bool GDBRemoteCommunicationClient::GetProcessInfo(
1955 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1956 process_info.Clear();
1958 if (m_supports_qProcessInfoPID) {
1960 const int packet_len =
1961 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1962 assert(packet_len < (int)sizeof(packet));
1963 UNUSED_IF_ASSERT_DISABLED(packet_len);
1964 StringExtractorGDBRemote response;
1965 if (SendPacketAndWaitForResponse(packet, response, false) ==
1966 PacketResult::Success) {
1967 return DecodeProcessInfoResponse(response, process_info);
1969 m_supports_qProcessInfoPID = false;
1976 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1977 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1981 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1983 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1989 StringExtractorGDBRemote response;
1990 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1991 PacketResult::Success) {
1992 if (response.IsNormalResponse()) {
1993 llvm::StringRef name;
1994 llvm::StringRef value;
1995 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1997 std::string arch_name;
1998 std::string os_name;
1999 std::string vendor_name;
2001 std::string elf_abi;
2002 uint32_t pointer_byte_size = 0;
2003 StringExtractor extractor;
2004 ByteOrder byte_order = eByteOrderInvalid;
2005 uint32_t num_keys_decoded = 0;
2006 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2007 while (response.GetNameColonValue(name, value)) {
2008 if (name.equals("cputype")) {
2009 if (!value.getAsInteger(16, cpu))
2011 } else if (name.equals("cpusubtype")) {
2012 if (!value.getAsInteger(16, sub))
2014 } else if (name.equals("triple")) {
2015 StringExtractor extractor(value);
2016 extractor.GetHexByteString(triple);
2018 } else if (name.equals("ostype")) {
2021 } else if (name.equals("vendor")) {
2022 vendor_name = value;
2024 } else if (name.equals("endian")) {
2025 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2026 .Case("little", eByteOrderLittle)
2027 .Case("big", eByteOrderBig)
2028 .Case("pdp", eByteOrderPDP)
2029 .Default(eByteOrderInvalid);
2030 if (byte_order != eByteOrderInvalid)
2032 } else if (name.equals("ptrsize")) {
2033 if (!value.getAsInteger(16, pointer_byte_size))
2035 } else if (name.equals("pid")) {
2036 if (!value.getAsInteger(16, pid))
2038 } else if (name.equals("elf_abi")) {
2043 if (num_keys_decoded > 0)
2044 m_qProcessInfo_is_valid = eLazyBoolYes;
2045 if (pid != LLDB_INVALID_PROCESS_ID) {
2046 m_curr_pid_is_valid = eLazyBoolYes;
2050 // Set the ArchSpec from the triple if we have it.
2051 if (!triple.empty()) {
2052 m_process_arch.SetTriple(triple.c_str());
2053 m_process_arch.SetFlags(elf_abi);
2054 if (pointer_byte_size) {
2055 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2057 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2058 !vendor_name.empty()) {
2059 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2061 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2062 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2063 switch (triple.getObjectFormat()) {
2064 case llvm::Triple::MachO:
2065 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2067 case llvm::Triple::ELF:
2068 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2070 case llvm::Triple::COFF:
2071 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2073 case llvm::Triple::Wasm:
2075 log->Printf("error: not supported target architecture");
2077 case llvm::Triple::UnknownObjectFormat:
2079 log->Printf("error: failed to determine target architecture");
2083 if (pointer_byte_size) {
2084 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2086 if (byte_order != eByteOrderInvalid) {
2087 assert(byte_order == m_process_arch.GetByteOrder());
2089 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2090 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2091 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2092 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2097 m_qProcessInfo_is_valid = eLazyBoolNo;
2103 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2104 const ProcessInstanceInfoMatch &match_info,
2105 ProcessInstanceInfoList &process_infos) {
2106 process_infos.Clear();
2108 if (m_supports_qfProcessInfo) {
2109 StreamString packet;
2110 packet.PutCString("qfProcessInfo");
2111 if (!match_info.MatchAllProcesses()) {
2112 packet.PutChar(':');
2113 const char *name = match_info.GetProcessInfo().GetName();
2114 bool has_name_match = false;
2115 if (name && name[0]) {
2116 has_name_match = true;
2117 NameMatch name_match_type = match_info.GetNameMatchType();
2118 switch (name_match_type) {
2119 case NameMatch::Ignore:
2120 has_name_match = false;
2123 case NameMatch::Equals:
2124 packet.PutCString("name_match:equals;");
2127 case NameMatch::Contains:
2128 packet.PutCString("name_match:contains;");
2131 case NameMatch::StartsWith:
2132 packet.PutCString("name_match:starts_with;");
2135 case NameMatch::EndsWith:
2136 packet.PutCString("name_match:ends_with;");
2139 case NameMatch::RegularExpression:
2140 packet.PutCString("name_match:regex;");
2143 if (has_name_match) {
2144 packet.PutCString("name:");
2145 packet.PutBytesAsRawHex8(name, ::strlen(name));
2146 packet.PutChar(';');
2150 if (match_info.GetProcessInfo().ProcessIDIsValid())
2151 packet.Printf("pid:%" PRIu64 ";",
2152 match_info.GetProcessInfo().GetProcessID());
2153 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2154 packet.Printf("parent_pid:%" PRIu64 ";",
2155 match_info.GetProcessInfo().GetParentProcessID());
2156 if (match_info.GetProcessInfo().UserIDIsValid())
2157 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2158 if (match_info.GetProcessInfo().GroupIDIsValid())
2159 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2160 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2161 packet.Printf("euid:%u;",
2162 match_info.GetProcessInfo().GetEffectiveUserID());
2163 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2164 packet.Printf("egid:%u;",
2165 match_info.GetProcessInfo().GetEffectiveGroupID());
2166 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2167 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2168 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2169 const ArchSpec &match_arch =
2170 match_info.GetProcessInfo().GetArchitecture();
2171 const llvm::Triple &triple = match_arch.GetTriple();
2172 packet.PutCString("triple:");
2173 packet.PutCString(triple.getTriple());
2174 packet.PutChar(';');
2177 StringExtractorGDBRemote response;
2178 // Increase timeout as the first qfProcessInfo packet takes a long time on
2179 // Android. The value of 1min was arrived at empirically.
2180 ScopedTimeout timeout(*this, minutes(1));
2181 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2182 PacketResult::Success) {
2184 ProcessInstanceInfo process_info;
2185 if (!DecodeProcessInfoResponse(response, process_info))
2187 process_infos.Append(process_info);
2188 response.GetStringRef().clear();
2189 response.SetFilePos(0);
2190 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2191 PacketResult::Success);
2193 m_supports_qfProcessInfo = false;
2197 return process_infos.GetSize();
2200 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2201 std::string &name) {
2202 if (m_supports_qUserName) {
2204 const int packet_len =
2205 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2206 assert(packet_len < (int)sizeof(packet));
2207 UNUSED_IF_ASSERT_DISABLED(packet_len);
2208 StringExtractorGDBRemote response;
2209 if (SendPacketAndWaitForResponse(packet, response, false) ==
2210 PacketResult::Success) {
2211 if (response.IsNormalResponse()) {
2212 // Make sure we parsed the right number of characters. The response is
2213 // the hex encoded user name and should make up the entire packet. If
2214 // there are any non-hex ASCII bytes, the length won't match below..
2215 if (response.GetHexByteString(name) * 2 ==
2216 response.GetStringRef().size())
2220 m_supports_qUserName = false;
2227 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2228 std::string &name) {
2229 if (m_supports_qGroupName) {
2231 const int packet_len =
2232 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2233 assert(packet_len < (int)sizeof(packet));
2234 UNUSED_IF_ASSERT_DISABLED(packet_len);
2235 StringExtractorGDBRemote response;
2236 if (SendPacketAndWaitForResponse(packet, response, false) ==
2237 PacketResult::Success) {
2238 if (response.IsNormalResponse()) {
2239 // Make sure we parsed the right number of characters. The response is
2240 // the hex encoded group name and should make up the entire packet. If
2241 // there are any non-hex ASCII bytes, the length won't match below..
2242 if (response.GetHexByteString(name) * 2 ==
2243 response.GetStringRef().size())
2247 m_supports_qGroupName = false;
2254 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2255 // Form non-stop packet request
2257 const int packet_len =
2258 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2259 assert(packet_len < (int)sizeof(packet));
2260 UNUSED_IF_ASSERT_DISABLED(packet_len);
2262 StringExtractorGDBRemote response;
2264 if (SendPacketAndWaitForResponse(packet, response, false) ==
2265 PacketResult::Success)
2266 if (response.IsOKResponse())
2269 // Failed or not supported
2273 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2274 uint32_t recv_size) {
2276 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2277 uint32_t bytes_left = send_size;
2278 while (bytes_left > 0) {
2279 if (bytes_left >= 26) {
2280 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2283 packet.Printf("%*.*s;", bytes_left, bytes_left,
2284 "abcdefghijklmnopqrstuvwxyz");
2291 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2292 using Dur = duration<float>;
2293 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2294 Dur mean = sum / v.size();
2297 float delta = (d - mean).count();
2298 accum += delta * delta;
2301 return Dur(sqrtf(accum / (v.size() - 1)));
2304 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2307 uint64_t recv_amount,
2308 bool json, Stream &strm) {
2310 if (SendSpeedTestPacket(0, 0)) {
2311 StreamString packet;
2313 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2317 strm.Printf("Testing sending %u packets of various sizes:\n",
2321 uint32_t result_idx = 0;
2323 std::vector<duration<float>> packet_times;
2325 for (send_size = 0; send_size <= max_send;
2326 send_size ? send_size *= 2 : send_size = 4) {
2327 for (uint32_t recv_size = 0; recv_size <= max_recv;
2328 recv_size ? recv_size *= 2 : recv_size = 4) {
2329 MakeSpeedTestPacket(packet, send_size, recv_size);
2331 packet_times.clear();
2332 // Test how long it takes to send 'num_packets' packets
2333 const auto start_time = steady_clock::now();
2334 for (i = 0; i < num_packets; ++i) {
2335 const auto packet_start_time = steady_clock::now();
2336 StringExtractorGDBRemote response;
2337 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2338 const auto packet_end_time = steady_clock::now();
2339 packet_times.push_back(packet_end_time - packet_start_time);
2341 const auto end_time = steady_clock::now();
2342 const auto total_time = end_time - start_time;
2344 float packets_per_second =
2345 ((float)num_packets) / duration<float>(total_time).count();
2346 auto average_per_packet = total_time / num_packets;
2347 const duration<float> standard_deviation =
2348 calculate_standard_deviation(packet_times);
2350 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2351 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2352 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2353 result_idx > 0 ? "," : "", send_size, recv_size,
2354 total_time, standard_deviation);
2357 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2358 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2359 "standard deviation of {5,10:ms+f6}\n",
2360 send_size, recv_size, duration<float>(total_time),
2361 packets_per_second, duration<float>(average_per_packet),
2362 standard_deviation);
2368 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2370 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2371 ": %" PRIu64 ",\n \"results\" : [",
2374 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2380 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2381 MakeSpeedTestPacket(packet, send_size, recv_size);
2383 // If we have a receive size, test how long it takes to receive 4MB of
2385 if (recv_size > 0) {
2386 const auto start_time = steady_clock::now();
2387 uint32_t bytes_read = 0;
2388 uint32_t packet_count = 0;
2389 while (bytes_read < recv_amount) {
2390 StringExtractorGDBRemote response;
2391 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2392 bytes_read += recv_size;
2395 const auto end_time = steady_clock::now();
2396 const auto total_time = end_time - start_time;
2397 float mb_second = ((float)recv_amount) /
2398 duration<float>(total_time).count() /
2400 float packets_per_second =
2401 ((float)packet_count) / duration<float>(total_time).count();
2402 const auto average_per_packet = total_time / packet_count;
2405 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2406 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2407 result_idx > 0 ? "," : "", send_size, recv_size,
2411 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2412 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2413 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2414 send_size, recv_size, packet_count, k_recv_amount_mb,
2415 duration<float>(total_time), mb_second,
2416 packets_per_second, duration<float>(average_per_packet));
2422 strm.Printf("\n ]\n }\n}\n");
2428 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2429 uint32_t recv_size) {
2430 StreamString packet;
2431 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2432 uint32_t bytes_left = send_size;
2433 while (bytes_left > 0) {
2434 if (bytes_left >= 26) {
2435 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2438 packet.Printf("%*.*s;", bytes_left, bytes_left,
2439 "abcdefghijklmnopqrstuvwxyz");
2444 StringExtractorGDBRemote response;
2445 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2446 PacketResult::Success;
2449 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2450 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2451 std::string &socket_name) {
2452 pid = LLDB_INVALID_PROCESS_ID;
2454 socket_name.clear();
2456 StringExtractorGDBRemote response;
2457 StreamString stream;
2458 stream.PutCString("qLaunchGDBServer;");
2459 std::string hostname;
2460 if (remote_accept_hostname && remote_accept_hostname[0])
2461 hostname = remote_accept_hostname;
2463 if (HostInfo::GetHostname(hostname)) {
2464 // Make the GDB server we launch only accept connections from this host
2465 stream.Printf("host:%s;", hostname.c_str());
2467 // Make the GDB server we launch accept connections from any host since
2468 // we can't figure out the hostname
2469 stream.Printf("host:*;");
2472 // give the process a few seconds to startup
2473 ScopedTimeout timeout(*this, seconds(10));
2475 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2476 PacketResult::Success) {
2477 llvm::StringRef name;
2478 llvm::StringRef value;
2479 while (response.GetNameColonValue(name, value)) {
2480 if (name.equals("port"))
2481 value.getAsInteger(0, port);
2482 else if (name.equals("pid"))
2483 value.getAsInteger(0, pid);
2484 else if (name.compare("socket_name") == 0) {
2485 StringExtractor extractor(value);
2486 extractor.GetHexByteString(socket_name);
2494 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2495 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2496 connection_urls.clear();
2498 StringExtractorGDBRemote response;
2499 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2500 PacketResult::Success)
2503 StructuredData::ObjectSP data =
2504 StructuredData::ParseJSON(response.GetStringRef());
2508 StructuredData::Array *array = data->GetAsArray();
2512 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2513 StructuredData::Dictionary *element = nullptr;
2514 if (!array->GetItemAtIndexAsDictionary(i, element))
2518 if (StructuredData::ObjectSP port_osp =
2519 element->GetValueForKey(llvm::StringRef("port")))
2520 port = port_osp->GetIntegerValue(0);
2522 std::string socket_name;
2523 if (StructuredData::ObjectSP socket_name_osp =
2524 element->GetValueForKey(llvm::StringRef("socket_name")))
2525 socket_name = socket_name_osp->GetStringValue();
2527 if (port != 0 || !socket_name.empty())
2528 connection_urls.emplace_back(port, socket_name);
2530 return connection_urls.size();
2533 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2534 StreamString stream;
2535 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2537 StringExtractorGDBRemote response;
2538 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2539 PacketResult::Success) {
2540 if (response.IsOKResponse())
2546 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2547 if (m_curr_tid == tid)
2552 if (tid == UINT64_MAX)
2553 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2555 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2556 assert(packet_len + 1 < (int)sizeof(packet));
2557 UNUSED_IF_ASSERT_DISABLED(packet_len);
2558 StringExtractorGDBRemote response;
2559 if (SendPacketAndWaitForResponse(packet, response, false) ==
2560 PacketResult::Success) {
2561 if (response.IsOKResponse()) {
2567 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2569 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2571 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2573 if (response.IsUnsupportedResponse() && IsConnected()) {
2581 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2582 if (m_curr_tid_run == tid)
2587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2590 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2592 assert(packet_len + 1 < (int)sizeof(packet));
2593 UNUSED_IF_ASSERT_DISABLED(packet_len);
2594 StringExtractorGDBRemote response;
2595 if (SendPacketAndWaitForResponse(packet, response, false) ==
2596 PacketResult::Success) {
2597 if (response.IsOKResponse()) {
2598 m_curr_tid_run = tid;
2603 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2605 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2607 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2609 if (response.IsUnsupportedResponse() && IsConnected()) {
2617 bool GDBRemoteCommunicationClient::GetStopReply(
2618 StringExtractorGDBRemote &response) {
2619 if (SendPacketAndWaitForResponse("?", response, false) ==
2620 PacketResult::Success)
2621 return response.IsNormalResponse();
2625 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2626 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2627 if (m_supports_qThreadStopInfo) {
2630 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2631 assert(packet_len < (int)sizeof(packet));
2632 UNUSED_IF_ASSERT_DISABLED(packet_len);
2633 if (SendPacketAndWaitForResponse(packet, response, false) ==
2634 PacketResult::Success) {
2635 if (response.IsUnsupportedResponse())
2636 m_supports_qThreadStopInfo = false;
2637 else if (response.IsNormalResponse())
2642 m_supports_qThreadStopInfo = false;
2648 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2649 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2652 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2653 __FUNCTION__, insert ? "add" : "remove", addr);
2655 // Check if the stub is known not to support this breakpoint type
2656 if (!SupportsGDBStoppointPacket(type))
2658 // Construct the breakpoint packet
2660 const int packet_len =
2661 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2662 insert ? 'Z' : 'z', type, addr, length);
2663 // Check we haven't overwritten the end of the packet buffer
2664 assert(packet_len + 1 < (int)sizeof(packet));
2665 UNUSED_IF_ASSERT_DISABLED(packet_len);
2666 StringExtractorGDBRemote response;
2667 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2668 // or "" (unsupported)
2669 response.SetResponseValidatorToOKErrorNotSupported();
2670 // Try to send the breakpoint packet, and check that it was correctly sent
2671 if (SendPacketAndWaitForResponse(packet, response, true) ==
2672 PacketResult::Success) {
2673 // Receive and OK packet when the breakpoint successfully placed
2674 if (response.IsOKResponse())
2677 // Status while setting breakpoint, send back specific error
2678 if (response.IsErrorResponse())
2679 return response.GetError();
2681 // Empty packet informs us that breakpoint is not supported
2682 if (response.IsUnsupportedResponse()) {
2683 // Disable this breakpoint type since it is unsupported
2685 case eBreakpointSoftware:
2686 m_supports_z0 = false;
2688 case eBreakpointHardware:
2689 m_supports_z1 = false;
2691 case eWatchpointWrite:
2692 m_supports_z2 = false;
2694 case eWatchpointRead:
2695 m_supports_z3 = false;
2697 case eWatchpointReadWrite:
2698 m_supports_z4 = false;
2700 case eStoppointInvalid:
2705 // Signal generic failure
2709 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2710 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2713 Lock lock(*this, false);
2715 sequence_mutex_unavailable = false;
2716 StringExtractorGDBRemote response;
2718 PacketResult packet_result;
2719 for (packet_result =
2720 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2721 packet_result == PacketResult::Success && response.IsNormalResponse();
2723 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2724 char ch = response.GetChar();
2729 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2731 if (tid != LLDB_INVALID_THREAD_ID) {
2732 thread_ids.push_back(tid);
2734 ch = response.GetChar(); // Skip the command separator
2735 } while (ch == ','); // Make sure we got a comma separator
2740 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2741 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2743 * be as simple as 'S05'. There is no packet which can give us pid and/or
2745 * Assume pid=tid=1 in such cases.
2747 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2748 thread_ids.size() == 0 && IsConnected()) {
2749 thread_ids.push_back(1);
2752 #if !defined(LLDB_CONFIGURATION_DEBUG)
2753 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2756 log->Printf("error: failed to get packet sequence mutex, not sending "
2757 "packet 'qfThreadInfo'");
2759 sequence_mutex_unavailable = true;
2761 return thread_ids.size();
2764 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2765 StringExtractorGDBRemote response;
2766 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2767 PacketResult::Success ||
2768 !response.IsNormalResponse())
2769 return LLDB_INVALID_ADDRESS;
2770 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2773 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2774 const char *command, // Shouldn't be NULL
2776 working_dir, // Pass empty FileSpec to use the current working directory
2777 int *status_ptr, // Pass NULL if you don't want the process exit status
2778 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2781 *command_output, // Pass NULL if you don't want the command output
2782 const Timeout<std::micro> &timeout) {
2783 lldb_private::StreamString stream;
2784 stream.PutCString("qPlatform_shell:");
2785 stream.PutBytesAsRawHex8(command, strlen(command));
2786 stream.PutChar(',');
2787 uint32_t timeout_sec = UINT32_MAX;
2789 // TODO: Use chrono version of std::ceil once c++17 is available.
2790 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2792 stream.PutHex32(timeout_sec);
2794 std::string path{working_dir.GetPath(false)};
2795 stream.PutChar(',');
2796 stream.PutCStringAsRawHex8(path.c_str());
2798 StringExtractorGDBRemote response;
2799 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2800 PacketResult::Success) {
2801 if (response.GetChar() != 'F')
2802 return Status("malformed reply");
2803 if (response.GetChar() != ',')
2804 return Status("malformed reply");
2805 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2806 if (exitcode == UINT32_MAX)
2807 return Status("unable to run remote process");
2808 else if (status_ptr)
2809 *status_ptr = exitcode;
2810 if (response.GetChar() != ',')
2811 return Status("malformed reply");
2812 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2815 if (response.GetChar() != ',')
2816 return Status("malformed reply");
2818 response.GetEscapedBinaryData(output);
2820 command_output->assign(output);
2823 return Status("unable to send packet");
2826 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2827 uint32_t file_permissions) {
2828 std::string path{file_spec.GetPath(false)};
2829 lldb_private::StreamString stream;
2830 stream.PutCString("qPlatform_mkdir:");
2831 stream.PutHex32(file_permissions);
2832 stream.PutChar(',');
2833 stream.PutCStringAsRawHex8(path.c_str());
2834 llvm::StringRef packet = stream.GetString();
2835 StringExtractorGDBRemote response;
2837 if (SendPacketAndWaitForResponse(packet, response, false) !=
2838 PacketResult::Success)
2839 return Status("failed to send '%s' packet", packet.str().c_str());
2841 if (response.GetChar() != 'F')
2842 return Status("invalid response to '%s' packet", packet.str().c_str());
2844 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2848 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2849 uint32_t file_permissions) {
2850 std::string path{file_spec.GetPath(false)};
2851 lldb_private::StreamString stream;
2852 stream.PutCString("qPlatform_chmod:");
2853 stream.PutHex32(file_permissions);
2854 stream.PutChar(',');
2855 stream.PutCStringAsRawHex8(path.c_str());
2856 llvm::StringRef packet = stream.GetString();
2857 StringExtractorGDBRemote response;
2859 if (SendPacketAndWaitForResponse(packet, response, false) !=
2860 PacketResult::Success)
2861 return Status("failed to send '%s' packet", stream.GetData());
2863 if (response.GetChar() != 'F')
2864 return Status("invalid response to '%s' packet", stream.GetData());
2866 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2869 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2870 uint64_t fail_result, Status &error) {
2871 response.SetFilePos(0);
2872 if (response.GetChar() != 'F')
2874 int32_t result = response.GetS32(-2);
2877 if (response.GetChar() == ',') {
2878 int result_errno = response.GetS32(-2);
2879 if (result_errno != -2)
2880 error.SetError(result_errno, eErrorTypePOSIX);
2882 error.SetError(-1, eErrorTypeGeneric);
2888 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2889 uint32_t flags, mode_t mode,
2891 std::string path(file_spec.GetPath(false));
2892 lldb_private::StreamString stream;
2893 stream.PutCString("vFile:open:");
2896 stream.PutCStringAsRawHex8(path.c_str());
2897 stream.PutChar(',');
2898 stream.PutHex32(flags);
2899 stream.PutChar(',');
2900 stream.PutHex32(mode);
2901 StringExtractorGDBRemote response;
2902 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2903 PacketResult::Success) {
2904 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2909 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2911 lldb_private::StreamString stream;
2912 stream.Printf("vFile:close:%i", (int)fd);
2913 StringExtractorGDBRemote response;
2914 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2915 PacketResult::Success) {
2916 return ParseHostIOPacketResponse(response, -1, error) == 0;
2921 // Extension of host I/O packets to get the file size.
2922 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2923 const lldb_private::FileSpec &file_spec) {
2924 std::string path(file_spec.GetPath(false));
2925 lldb_private::StreamString stream;
2926 stream.PutCString("vFile:size:");
2927 stream.PutCStringAsRawHex8(path.c_str());
2928 StringExtractorGDBRemote response;
2929 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2930 PacketResult::Success) {
2931 if (response.GetChar() != 'F')
2933 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2940 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2941 uint32_t &file_permissions) {
2942 std::string path{file_spec.GetPath(false)};
2944 lldb_private::StreamString stream;
2945 stream.PutCString("vFile:mode:");
2946 stream.PutCStringAsRawHex8(path.c_str());
2947 StringExtractorGDBRemote response;
2948 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2949 PacketResult::Success) {
2950 if (response.GetChar() != 'F') {
2951 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2954 const uint32_t mode = response.GetS32(-1);
2955 if (static_cast<int32_t>(mode) == -1) {
2956 if (response.GetChar() == ',') {
2957 int response_errno = response.GetS32(-1);
2958 if (response_errno > 0)
2959 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2961 error.SetErrorToGenericError();
2963 error.SetErrorToGenericError();
2965 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2969 error.SetErrorStringWithFormat("failed to send '%s' packet",
2975 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2976 uint64_t offset, void *dst,
2979 lldb_private::StreamString stream;
2980 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2982 StringExtractorGDBRemote response;
2983 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2984 PacketResult::Success) {
2985 if (response.GetChar() != 'F')
2987 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2988 if (retcode == UINT32_MAX)
2990 const char next = (response.Peek() ? *response.Peek() : 0);
2994 response.GetChar(); // skip the semicolon
2996 if (response.GetEscapedBinaryData(buffer)) {
2997 const uint64_t data_to_write =
2998 std::min<uint64_t>(dst_len, buffer.size());
2999 if (data_to_write > 0)
3000 memcpy(dst, &buffer[0], data_to_write);
3001 return data_to_write;
3008 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3013 lldb_private::StreamGDBRemote stream;
3014 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3015 stream.PutEscapedBytes(src, src_len);
3016 StringExtractorGDBRemote response;
3017 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3018 PacketResult::Success) {
3019 if (response.GetChar() != 'F') {
3020 error.SetErrorStringWithFormat("write file failed");
3023 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3024 if (bytes_written == UINT64_MAX) {
3025 error.SetErrorToGenericError();
3026 if (response.GetChar() == ',') {
3027 int response_errno = response.GetS32(-1);
3028 if (response_errno > 0)
3029 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3033 return bytes_written;
3035 error.SetErrorString("failed to send vFile:pwrite packet");
3040 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3041 const FileSpec &dst) {
3042 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3044 lldb_private::StreamGDBRemote stream;
3045 stream.PutCString("vFile:symlink:");
3046 // the unix symlink() command reverses its parameters where the dst if first,
3047 // so we follow suit here
3048 stream.PutCStringAsRawHex8(dst_path.c_str());
3049 stream.PutChar(',');
3050 stream.PutCStringAsRawHex8(src_path.c_str());
3051 StringExtractorGDBRemote response;
3052 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3053 PacketResult::Success) {
3054 if (response.GetChar() == 'F') {
3055 uint32_t result = response.GetU32(UINT32_MAX);
3057 error.SetErrorToGenericError();
3058 if (response.GetChar() == ',') {
3059 int response_errno = response.GetS32(-1);
3060 if (response_errno > 0)
3061 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3065 // Should have returned with 'F<result>[,<errno>]'
3066 error.SetErrorStringWithFormat("symlink failed");
3069 error.SetErrorString("failed to send vFile:symlink packet");
3074 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3075 std::string path{file_spec.GetPath(false)};
3077 lldb_private::StreamGDBRemote stream;
3078 stream.PutCString("vFile:unlink:");
3079 // the unix symlink() command reverses its parameters where the dst if first,
3080 // so we follow suit here
3081 stream.PutCStringAsRawHex8(path.c_str());
3082 StringExtractorGDBRemote response;
3083 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3084 PacketResult::Success) {
3085 if (response.GetChar() == 'F') {
3086 uint32_t result = response.GetU32(UINT32_MAX);
3088 error.SetErrorToGenericError();
3089 if (response.GetChar() == ',') {
3090 int response_errno = response.GetS32(-1);
3091 if (response_errno > 0)
3092 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3096 // Should have returned with 'F<result>[,<errno>]'
3097 error.SetErrorStringWithFormat("unlink failed");
3100 error.SetErrorString("failed to send vFile:unlink packet");
3105 // Extension of host I/O packets to get whether a file exists.
3106 bool GDBRemoteCommunicationClient::GetFileExists(
3107 const lldb_private::FileSpec &file_spec) {
3108 std::string path(file_spec.GetPath(false));
3109 lldb_private::StreamString stream;
3110 stream.PutCString("vFile:exists:");
3111 stream.PutCStringAsRawHex8(path.c_str());
3112 StringExtractorGDBRemote response;
3113 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3114 PacketResult::Success) {
3115 if (response.GetChar() != 'F')
3117 if (response.GetChar() != ',')
3119 bool retcode = (response.GetChar() != '0');
3125 bool GDBRemoteCommunicationClient::CalculateMD5(
3126 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3127 std::string path(file_spec.GetPath(false));
3128 lldb_private::StreamString stream;
3129 stream.PutCString("vFile:MD5:");
3130 stream.PutCStringAsRawHex8(path.c_str());
3131 StringExtractorGDBRemote response;
3132 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3133 PacketResult::Success) {
3134 if (response.GetChar() != 'F')
3136 if (response.GetChar() != ',')
3138 if (response.Peek() && *response.Peek() == 'x')
3140 low = response.GetHexMaxU64(false, UINT64_MAX);
3141 high = response.GetHexMaxU64(false, UINT64_MAX);
3147 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3148 // Some targets have issues with g/G packets and we need to avoid using them
3149 if (m_avoid_g_packets == eLazyBoolCalculate) {
3151 m_avoid_g_packets = eLazyBoolNo;
3152 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3153 if (arch.IsValid() &&
3154 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3155 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3156 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3157 m_avoid_g_packets = eLazyBoolYes;
3158 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3159 if (gdb_server_version != 0) {
3160 const char *gdb_server_name = GetGDBServerProgramName();
3161 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3162 if (gdb_server_version >= 310)
3163 m_avoid_g_packets = eLazyBoolNo;
3169 return m_avoid_g_packets == eLazyBoolYes;
3172 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3174 StreamString payload;
3175 payload.Printf("p%x", reg);
3176 StringExtractorGDBRemote response;
3177 if (SendThreadSpecificPacketAndWaitForResponse(
3178 tid, std::move(payload), response, false) != PacketResult::Success ||
3179 !response.IsNormalResponse())
3182 DataBufferSP buffer_sp(
3183 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3184 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3188 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3189 StreamString payload;
3190 payload.PutChar('g');
3191 StringExtractorGDBRemote response;
3192 if (SendThreadSpecificPacketAndWaitForResponse(
3193 tid, std::move(payload), response, false) != PacketResult::Success ||
3194 !response.IsNormalResponse())
3197 DataBufferSP buffer_sp(
3198 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3199 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3203 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3205 llvm::ArrayRef<uint8_t> data) {
3206 StreamString payload;
3207 payload.Printf("P%x=", reg_num);
3208 payload.PutBytesAsRawHex8(data.data(), data.size(),
3209 endian::InlHostByteOrder(),
3210 endian::InlHostByteOrder());
3211 StringExtractorGDBRemote response;
3212 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3214 PacketResult::Success &&
3215 response.IsOKResponse();
3218 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3219 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3220 StreamString payload;
3221 payload.PutChar('G');
3222 payload.PutBytesAsRawHex8(data.data(), data.size(),
3223 endian::InlHostByteOrder(),
3224 endian::InlHostByteOrder());
3225 StringExtractorGDBRemote response;
3226 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3228 PacketResult::Success &&
3229 response.IsOKResponse();
3232 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3233 uint32_t &save_id) {
3234 save_id = 0; // Set to invalid save ID
3235 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3238 m_supports_QSaveRegisterState = eLazyBoolYes;
3239 StreamString payload;
3240 payload.PutCString("QSaveRegisterState");
3241 StringExtractorGDBRemote response;
3242 if (SendThreadSpecificPacketAndWaitForResponse(
3243 tid, std::move(payload), response, false) != PacketResult::Success)
3246 if (response.IsUnsupportedResponse())
3247 m_supports_QSaveRegisterState = eLazyBoolNo;
3249 const uint32_t response_save_id = response.GetU32(0);
3250 if (response_save_id == 0)
3253 save_id = response_save_id;
3257 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3259 // We use the "m_supports_QSaveRegisterState" variable here because the
3260 // QSaveRegisterState and QRestoreRegisterState packets must both be
3261 // supported in order to be useful
3262 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3265 StreamString payload;
3266 payload.Printf("QRestoreRegisterState:%u", save_id);
3267 StringExtractorGDBRemote response;
3268 if (SendThreadSpecificPacketAndWaitForResponse(
3269 tid, std::move(payload), response, false) != PacketResult::Success)
3272 if (response.IsOKResponse())
3275 if (response.IsUnsupportedResponse())
3276 m_supports_QSaveRegisterState = eLazyBoolNo;
3280 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3281 if (!GetSyncThreadStateSupported())
3284 StreamString packet;
3285 StringExtractorGDBRemote response;
3286 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3287 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3288 GDBRemoteCommunication::PacketResult::Success &&
3289 response.IsOKResponse();
3293 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3295 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3296 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3298 StreamGDBRemote escaped_packet;
3299 escaped_packet.PutCString("jTraceStart:");
3301 StructuredData::Dictionary json_packet;
3302 json_packet.AddIntegerItem("type", options.getType());
3303 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3304 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3306 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3307 json_packet.AddIntegerItem("threadid", options.getThreadID());
3309 StructuredData::DictionarySP custom_params = options.getTraceParams();
3311 json_packet.AddItem("params", custom_params);
3313 StreamString json_string;
3314 json_packet.Dump(json_string, false);
3315 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3317 StringExtractorGDBRemote response;
3318 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3320 GDBRemoteCommunication::PacketResult::Success) {
3321 if (!response.IsNormalResponse()) {
3322 error = response.GetStatus();
3323 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
3325 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3328 LLDB_LOG(log, "failed to send packet");
3329 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3330 escaped_packet.GetData());
3336 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3337 lldb::tid_t thread_id) {
3338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3339 StringExtractorGDBRemote response;
3342 StructuredData::Dictionary json_packet;
3343 StreamGDBRemote escaped_packet;
3344 StreamString json_string;
3345 escaped_packet.PutCString("jTraceStop:");
3347 json_packet.AddIntegerItem("traceid", uid);
3349 if (thread_id != LLDB_INVALID_THREAD_ID)
3350 json_packet.AddIntegerItem("threadid", thread_id);
3352 json_packet.Dump(json_string, false);
3354 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3356 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3358 GDBRemoteCommunication::PacketResult::Success) {
3359 if (!response.IsOKResponse()) {
3360 error = response.GetStatus();
3361 LLDB_LOG(log, "stop tracing failed");
3364 LLDB_LOG(log, "failed to send packet");
3365 error.SetErrorStringWithFormat(
3366 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3367 response.GetError());
3372 Status GDBRemoteCommunicationClient::SendGetDataPacket(
3373 lldb::user_id_t uid, lldb::tid_t thread_id,
3374 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3376 StreamGDBRemote escaped_packet;
3377 escaped_packet.PutCString("jTraceBufferRead:");
3378 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3381 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3382 lldb::user_id_t uid, lldb::tid_t thread_id,
3383 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3385 StreamGDBRemote escaped_packet;
3386 escaped_packet.PutCString("jTraceMetaRead:");
3387 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3391 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3392 TraceOptions &options) {
3393 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3394 StringExtractorGDBRemote response;
3397 StreamString json_string;
3398 StreamGDBRemote escaped_packet;
3399 escaped_packet.PutCString("jTraceConfigRead:");
3401 StructuredData::Dictionary json_packet;
3402 json_packet.AddIntegerItem("traceid", uid);
3404 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3405 json_packet.AddIntegerItem("threadid", options.getThreadID());
3407 json_packet.Dump(json_string, false);
3408 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3410 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3412 GDBRemoteCommunication::PacketResult::Success) {
3413 if (response.IsNormalResponse()) {
3414 uint64_t type = std::numeric_limits<uint64_t>::max();
3415 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3416 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3418 auto json_object = StructuredData::ParseJSON(response.Peek());
3421 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
3422 error.SetErrorString("Invalid Configuration obtained");
3426 auto json_dict = json_object->GetAsDictionary();
3428 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3430 options.setMetaDataBufferSize(metabuffersize);
3432 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3433 options.setTraceBufferSize(buffersize);
3435 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3436 options.setType(static_cast<lldb::TraceType>(type));
3438 StructuredData::ObjectSP custom_params_sp =
3439 json_dict->GetValueForKey("params");
3440 if (custom_params_sp) {
3441 if (custom_params_sp->GetType() !=
3442 lldb::eStructuredDataTypeDictionary) {
3443 error.SetErrorString("Invalid Configuration obtained");
3446 options.setTraceParams(
3447 static_pointer_cast<StructuredData::Dictionary>(
3451 error = response.GetStatus();
3454 LLDB_LOG(log, "failed to send packet");
3455 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3456 escaped_packet.GetData());
3461 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3462 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3463 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3464 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3467 StructuredData::Dictionary json_packet;
3469 json_packet.AddIntegerItem("traceid", uid);
3470 json_packet.AddIntegerItem("offset", offset);
3471 json_packet.AddIntegerItem("buffersize", buffer.size());
3473 if (thread_id != LLDB_INVALID_THREAD_ID)
3474 json_packet.AddIntegerItem("threadid", thread_id);
3476 StreamString json_string;
3477 json_packet.Dump(json_string, false);
3479 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3480 StringExtractorGDBRemote response;
3481 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3482 GDBRemoteCommunication::PacketResult::Success) {
3483 if (response.IsNormalResponse()) {
3484 size_t filled_size = response.GetHexBytesAvail(buffer);
3485 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3487 error = response.GetStatus();
3488 buffer = buffer.slice(buffer.size());
3491 LLDB_LOG(log, "failed to send packet");
3492 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3494 buffer = buffer.slice(buffer.size());
3499 bool GDBRemoteCommunicationClient::GetModuleInfo(
3500 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3501 ModuleSpec &module_spec) {
3502 if (!m_supports_qModuleInfo)
3505 std::string module_path = module_file_spec.GetPath(false);
3506 if (module_path.empty())
3509 StreamString packet;
3510 packet.PutCString("qModuleInfo:");
3511 packet.PutCStringAsRawHex8(module_path.c_str());
3512 packet.PutCString(";");
3513 const auto &triple = arch_spec.GetTriple().getTriple();
3514 packet.PutCStringAsRawHex8(triple.c_str());
3516 StringExtractorGDBRemote response;
3517 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3518 PacketResult::Success)
3521 if (response.IsErrorResponse())
3524 if (response.IsUnsupportedResponse()) {
3525 m_supports_qModuleInfo = false;
3529 llvm::StringRef name;
3530 llvm::StringRef value;
3532 module_spec.Clear();
3533 module_spec.GetFileSpec() = module_file_spec;
3535 while (response.GetNameColonValue(name, value)) {
3536 if (name == "uuid" || name == "md5") {
3537 StringExtractor extractor(value);
3539 extractor.GetHexByteString(uuid);
3540 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
3541 } else if (name == "triple") {
3542 StringExtractor extractor(value);
3544 extractor.GetHexByteString(triple);
3545 module_spec.GetArchitecture().SetTriple(triple.c_str());
3546 } else if (name == "file_offset") {
3548 if (!value.getAsInteger(16, ival))
3549 module_spec.SetObjectOffset(ival);
3550 } else if (name == "file_size") {
3552 if (!value.getAsInteger(16, ival))
3553 module_spec.SetObjectSize(ival);
3554 } else if (name == "file_path") {
3555 StringExtractor extractor(value);
3557 extractor.GetHexByteString(path);
3558 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3565 static llvm::Optional<ModuleSpec>
3566 ParseModuleSpec(StructuredData::Dictionary *dict) {
3571 llvm::StringRef string;
3574 if (!dict->GetValueForKeyAsString("uuid", string))
3576 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3580 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3582 result.SetObjectOffset(integer);
3584 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3586 result.SetObjectSize(integer);
3588 if (!dict->GetValueForKeyAsString("triple", string))
3590 result.GetArchitecture().SetTriple(string);
3592 if (!dict->GetValueForKeyAsString("file_path", string))
3594 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3599 llvm::Optional<std::vector<ModuleSpec>>
3600 GDBRemoteCommunicationClient::GetModulesInfo(
3601 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3602 if (!m_supports_jModulesInfo)
3605 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3606 for (const FileSpec &module_file_spec : module_file_specs) {
3607 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3608 module_array_sp->AppendObject(module_sp);
3609 module_sp->SetObject(
3610 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
3611 module_sp->SetObject("triple",
3612 std::make_shared<JSONString>(triple.getTriple()));
3614 StreamString unescaped_payload;
3615 unescaped_payload.PutCString("jModulesInfo:");
3616 module_array_sp->Write(unescaped_payload);
3617 StreamGDBRemote payload;
3618 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3619 unescaped_payload.GetSize());
3621 // Increase the timeout for jModulesInfo since this packet can take longer.
3622 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3624 StringExtractorGDBRemote response;
3625 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3626 PacketResult::Success ||
3627 response.IsErrorResponse())
3630 if (response.IsUnsupportedResponse()) {
3631 m_supports_jModulesInfo = false;
3635 StructuredData::ObjectSP response_object_sp =
3636 StructuredData::ParseJSON(response.GetStringRef());
3637 if (!response_object_sp)
3640 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3641 if (!response_array)
3644 std::vector<ModuleSpec> result;
3645 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3646 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3647 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3648 result.push_back(*module_spec);
3654 // query the target remote for extended information using the qXfer packet
3656 // example: object='features', annex='target.xml', out=<xml output> return:
3657 // 'true' on success
3658 // 'false' on failure (err set)
3659 bool GDBRemoteCommunicationClient::ReadExtFeature(
3660 const lldb_private::ConstString object,
3661 const lldb_private::ConstString annex, std::string &out,
3662 lldb_private::Status &err) {
3664 std::stringstream output;
3665 StringExtractorGDBRemote chunk;
3667 uint64_t size = GetRemoteMaxPacketSize();
3670 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3674 // loop until all data has been read
3677 // send query extended feature packet
3678 std::stringstream packet;
3679 packet << "qXfer:" << object.AsCString("")
3680 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3681 << "," << std::hex << size;
3683 GDBRemoteCommunication::PacketResult res =
3684 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3686 if (res != GDBRemoteCommunication::PacketResult::Success) {
3687 err.SetErrorString("Error sending $qXfer packet");
3691 const std::string &str = chunk.GetStringRef();
3692 if (str.length() == 0) {
3693 // should have some data in chunk
3694 err.SetErrorString("Empty response from $qXfer packet");
3698 // check packet code
3707 if (str.length() > 1)
3714 err.SetErrorString("Invalid continuation code from $qXfer packet");
3724 // Notify the target that gdb is prepared to serve symbol lookup requests.
3725 // packet: "qSymbol::"
3727 // OK The target does not need to look up any (more) symbols.
3728 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3730 // LLDB may provide the value by sending another qSymbol
3732 // in the form of"qSymbol:<sym_value>:<sym_name>".
3736 // lldb sends: qSymbol::
3737 // lldb receives: OK
3738 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3740 // need to ask again in this session.
3742 // lldb sends: qSymbol::
3743 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3744 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3745 // lldb receives: OK
3746 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3748 // the address at this time. lldb needs to send qSymbol:: again when it has
3752 // lldb sends: qSymbol::
3753 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3754 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3755 // lldb receives: OK
3756 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3758 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3760 // need any more symbols. lldb does not need to ask again in this session.
3762 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3763 lldb_private::Process *process) {
3764 // Set to true once we've resolved a symbol to an address for the remote
3765 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3766 // any more symbols and we can stop asking.
3767 bool symbol_response_provided = false;
3769 // Is this the initial qSymbol:: packet?
3770 bool first_qsymbol_query = true;
3772 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
3773 Lock lock(*this, false);
3775 StreamString packet;
3776 packet.PutCString("qSymbol::");
3777 StringExtractorGDBRemote response;
3778 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3779 PacketResult::Success) {
3780 if (response.IsOKResponse()) {
3781 if (symbol_response_provided || first_qsymbol_query) {
3782 m_qSymbol_requests_done = true;
3785 // We are done serving symbols requests
3788 first_qsymbol_query = false;
3790 if (response.IsUnsupportedResponse()) {
3791 // qSymbol is not supported by the current GDB server we are
3793 m_supports_qSymbol = false;
3796 llvm::StringRef response_str(response.GetStringRef());
3797 if (response_str.startswith("qSymbol:")) {
3798 response.SetFilePos(strlen("qSymbol:"));
3799 std::string symbol_name;
3800 if (response.GetHexByteString(symbol_name)) {
3801 if (symbol_name.empty())
3804 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3805 lldb_private::SymbolContextList sc_list;
3806 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3807 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3808 const size_t num_scs = sc_list.GetSize();
3809 for (size_t sc_idx = 0;
3811 symbol_load_addr == LLDB_INVALID_ADDRESS;
3814 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3816 switch (sc.symbol->GetType()) {
3817 case eSymbolTypeInvalid:
3818 case eSymbolTypeAbsolute:
3819 case eSymbolTypeUndefined:
3820 case eSymbolTypeSourceFile:
3821 case eSymbolTypeHeaderFile:
3822 case eSymbolTypeObjectFile:
3823 case eSymbolTypeCommonBlock:
3824 case eSymbolTypeBlock:
3825 case eSymbolTypeLocal:
3826 case eSymbolTypeParam:
3827 case eSymbolTypeVariable:
3828 case eSymbolTypeVariableType:
3829 case eSymbolTypeLineEntry:
3830 case eSymbolTypeLineHeader:
3831 case eSymbolTypeScopeBegin:
3832 case eSymbolTypeScopeEnd:
3833 case eSymbolTypeAdditional:
3834 case eSymbolTypeCompiler:
3835 case eSymbolTypeInstrumentation:
3836 case eSymbolTypeTrampoline:
3839 case eSymbolTypeCode:
3840 case eSymbolTypeResolver:
3841 case eSymbolTypeData:
3842 case eSymbolTypeRuntime:
3843 case eSymbolTypeException:
3844 case eSymbolTypeObjCClass:
3845 case eSymbolTypeObjCMetaClass:
3846 case eSymbolTypeObjCIVar:
3847 case eSymbolTypeReExported:
3849 sc.symbol->GetLoadAddress(&process->GetTarget());
3856 // This is the normal path where our symbol lookup was successful
3857 // and we want to send a packet with the new symbol value and see
3858 // if another lookup needs to be done.
3860 // Change "packet" to contain the requested symbol value and name
3862 packet.PutCString("qSymbol:");
3863 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3864 packet.Printf("%" PRIx64, symbol_load_addr);
3865 symbol_response_provided = true;
3867 symbol_response_provided = false;
3869 packet.PutCString(":");
3870 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3871 continue; // go back to the while loop and send "packet" and wait
3872 // for another response
3877 // If we make it here, the symbol request packet response wasn't valid or
3878 // our symbol lookup failed so we must abort
3881 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3882 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3884 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3890 StructuredData::Array *
3891 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3892 if (!m_supported_async_json_packets_is_valid) {
3893 // Query the server for the array of supported asynchronous JSON packets.
3894 m_supported_async_json_packets_is_valid = true;
3896 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3899 StringExtractorGDBRemote response;
3900 const bool send_async = false;
3901 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3902 send_async) == PacketResult::Success) {
3903 m_supported_async_json_packets_sp =
3904 StructuredData::ParseJSON(response.GetStringRef());
3905 if (m_supported_async_json_packets_sp &&
3906 !m_supported_async_json_packets_sp->GetAsArray()) {
3907 // We were returned something other than a JSON array. This is
3908 // invalid. Clear it out.
3910 log->Printf("GDBRemoteCommunicationClient::%s(): "
3911 "QSupportedAsyncJSONPackets returned invalid "
3913 __FUNCTION__, response.GetStringRef().c_str());
3914 m_supported_async_json_packets_sp.reset();
3918 log->Printf("GDBRemoteCommunicationClient::%s(): "
3919 "QSupportedAsyncJSONPackets unsupported",
3923 if (log && m_supported_async_json_packets_sp) {
3924 StreamString stream;
3925 m_supported_async_json_packets_sp->Dump(stream);
3926 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3928 __FUNCTION__, stream.GetData());
3932 return m_supported_async_json_packets_sp
3933 ? m_supported_async_json_packets_sp->GetAsArray()
3937 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
3938 llvm::ArrayRef<int32_t> signals) {
3940 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3941 auto range = llvm::make_range(signals.begin(), signals.end());
3942 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3944 StringExtractorGDBRemote response;
3945 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3947 if (send_status != GDBRemoteCommunication::PacketResult::Success)
3948 return Status("Sending QPassSignals packet failed");
3950 if (response.IsOKResponse()) {
3953 return Status("Unknown error happened during sending QPassSignals packet.");
3957 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3958 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3961 if (type_name.GetLength() == 0) {
3962 error.SetErrorString("invalid type_name argument");
3966 // Build command: Configure{type_name}: serialized config data.
3967 StreamGDBRemote stream;
3968 stream.PutCString("QConfigure");
3969 stream.PutCString(type_name.AsCString());
3970 stream.PutChar(':');
3972 // Gather the plain-text version of the configuration data.
3973 StreamString unescaped_stream;
3974 config_sp->Dump(unescaped_stream);
3975 unescaped_stream.Flush();
3977 // Add it to the stream in escaped fashion.
3978 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
3979 unescaped_stream.GetSize());
3984 const bool send_async = false;
3985 StringExtractorGDBRemote response;
3987 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
3988 if (result == PacketResult::Success) {
3989 // We failed if the config result comes back other than OK.
3990 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3994 error.SetErrorStringWithFormat("configuring StructuredData feature "
3995 "%s failed with error %s",
3996 type_name.AsCString(),
3997 response.GetStringRef().c_str());
4000 // Can we get more data here on the failure?
4001 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4002 "failed when sending packet: "
4004 type_name.AsCString(), (int)result);
4009 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4010 GDBRemoteClientBase::OnRunPacketSent(first);
4011 m_curr_tid = LLDB_INVALID_THREAD_ID;