1 //===-- GDBRemoteCommunicationClient.cpp ----------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "GDBRemoteCommunicationClient.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Host/HostInfo.h"
19 #include "lldb/Host/XML.h"
20 #include "lldb/Symbol/Symbol.h"
21 #include "lldb/Target/MemoryRegionInfo.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/UnixSignals.h"
24 #include "lldb/Utility/Args.h"
25 #include "lldb/Utility/DataBufferHeap.h"
26 #include "lldb/Utility/LLDBAssert.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/State.h"
29 #include "lldb/Utility/StreamString.h"
31 #include "ProcessGDBRemote.h"
32 #include "ProcessGDBRemoteLog.h"
33 #include "lldb/Host/Config.h"
34 #include "lldb/Utility/StringExtractorGDBRemote.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/Support/JSON.h"
39 #if defined(HAVE_LIBCOMPRESSION)
40 #include <compression.h>
44 using namespace lldb_private::process_gdb_remote;
45 using namespace lldb_private;
46 using namespace std::chrono;
48 llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os,
49 const QOffsets &offsets) {
50 return os << llvm::formatv(
51 "QOffsets({0}, [{1:@[x]}])", offsets.segments,
52 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end()));
55 // GDBRemoteCommunicationClient constructor
56 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
57 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
58 m_supports_not_sending_acks(eLazyBoolCalculate),
59 m_supports_thread_suffix(eLazyBoolCalculate),
60 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
61 m_supports_vCont_all(eLazyBoolCalculate),
62 m_supports_vCont_any(eLazyBoolCalculate),
63 m_supports_vCont_c(eLazyBoolCalculate),
64 m_supports_vCont_C(eLazyBoolCalculate),
65 m_supports_vCont_s(eLazyBoolCalculate),
66 m_supports_vCont_S(eLazyBoolCalculate),
67 m_qHostInfo_is_valid(eLazyBoolCalculate),
68 m_curr_pid_is_valid(eLazyBoolCalculate),
69 m_qProcessInfo_is_valid(eLazyBoolCalculate),
70 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
71 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
72 m_supports_memory_region_info(eLazyBoolCalculate),
73 m_supports_watchpoint_support_info(eLazyBoolCalculate),
74 m_supports_detach_stay_stopped(eLazyBoolCalculate),
75 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
76 m_attach_or_wait_reply(eLazyBoolCalculate),
77 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
78 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
79 m_avoid_g_packets(eLazyBoolCalculate),
80 m_supports_QSaveRegisterState(eLazyBoolCalculate),
81 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
82 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
83 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_qXfer_features_read(eLazyBoolCalculate),
85 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
86 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
87 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
88 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
89 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
90 m_supports_QPassSignals(eLazyBoolCalculate),
91 m_supports_error_string_reply(eLazyBoolCalculate),
92 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
93 m_supports_qUserName(true), m_supports_qGroupName(true),
94 m_supports_qThreadStopInfo(true), m_supports_z0(true),
95 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
96 m_supports_z4(true), m_supports_QEnvironment(true),
97 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
98 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
99 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
100 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
101 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
102 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
103 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
104 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
105 m_max_packet_size(0), m_qSupported_response(),
106 m_supported_async_json_packets_is_valid(false),
107 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
108 m_qXfer_memory_map_loaded(false) {}
111 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
116 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
117 ResetDiscoverableSettings(false);
119 // Start the read thread after we send the handshake ack since if we fail to
120 // send the handshake ack, there is no reason to continue...
122 // Wait for any responses that might have been queued up in the remote
123 // GDB server and flush them all
124 StringExtractorGDBRemote response;
125 PacketResult packet_result = PacketResult::Success;
126 while (packet_result == PacketResult::Success)
127 packet_result = ReadPacket(response, milliseconds(10), false);
129 // The return value from QueryNoAckModeSupported() is true if the packet
130 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
131 // false if no response was received. This quickly tells us if we have a
132 // live connection to a remote GDB server...
133 if (QueryNoAckModeSupported()) {
137 error_ptr->SetErrorString("failed to get reply to handshake packet");
141 error_ptr->SetErrorString("failed to send the handshake ack");
146 bool GDBRemoteCommunicationClient::GetEchoSupported() {
147 if (m_supports_qEcho == eLazyBoolCalculate) {
148 GetRemoteQSupported();
150 return m_supports_qEcho == eLazyBoolYes;
153 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
154 if (m_supports_QPassSignals == eLazyBoolCalculate) {
155 GetRemoteQSupported();
157 return m_supports_QPassSignals == eLazyBoolYes;
160 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
161 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
164 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
167 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
168 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
171 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
174 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
175 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
178 return m_supports_qXfer_libraries_read == eLazyBoolYes;
181 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
182 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
185 return m_supports_qXfer_auxv_read == eLazyBoolYes;
188 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
189 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
190 GetRemoteQSupported();
192 return m_supports_qXfer_features_read == eLazyBoolYes;
195 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
196 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
197 GetRemoteQSupported();
199 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
202 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
203 if (m_max_packet_size == 0) {
204 GetRemoteQSupported();
206 return m_max_packet_size;
209 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
210 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
212 m_supports_not_sending_acks = eLazyBoolNo;
214 // This is the first real packet that we'll send in a debug session and it
215 // may take a little longer than normal to receive a reply. Wait at least
216 // 6 seconds for a reply to this packet.
218 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
220 StringExtractorGDBRemote response;
221 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
222 PacketResult::Success) {
223 if (response.IsOKResponse()) {
225 m_supports_not_sending_acks = eLazyBoolYes;
233 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
234 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
235 m_supports_threads_in_stop_reply = eLazyBoolNo;
237 StringExtractorGDBRemote response;
238 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
239 false) == PacketResult::Success) {
240 if (response.IsOKResponse())
241 m_supports_threads_in_stop_reply = eLazyBoolYes;
246 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
247 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
248 m_attach_or_wait_reply = eLazyBoolNo;
250 StringExtractorGDBRemote response;
251 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
252 false) == PacketResult::Success) {
253 if (response.IsOKResponse())
254 m_attach_or_wait_reply = eLazyBoolYes;
257 return m_attach_or_wait_reply == eLazyBoolYes;
260 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
261 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
262 m_prepare_for_reg_writing_reply = eLazyBoolNo;
264 StringExtractorGDBRemote response;
265 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
266 false) == PacketResult::Success) {
267 if (response.IsOKResponse())
268 m_prepare_for_reg_writing_reply = eLazyBoolYes;
271 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
274 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
276 // Hard reset everything, this is when we first connect to a GDB server
277 m_supports_not_sending_acks = eLazyBoolCalculate;
278 m_supports_thread_suffix = eLazyBoolCalculate;
279 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
280 m_supports_vCont_c = eLazyBoolCalculate;
281 m_supports_vCont_C = eLazyBoolCalculate;
282 m_supports_vCont_s = eLazyBoolCalculate;
283 m_supports_vCont_S = eLazyBoolCalculate;
284 m_supports_p = eLazyBoolCalculate;
285 m_supports_x = eLazyBoolCalculate;
286 m_supports_QSaveRegisterState = eLazyBoolCalculate;
287 m_qHostInfo_is_valid = eLazyBoolCalculate;
288 m_curr_pid_is_valid = eLazyBoolCalculate;
289 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
290 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
291 m_supports_memory_region_info = eLazyBoolCalculate;
292 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
293 m_attach_or_wait_reply = eLazyBoolCalculate;
294 m_avoid_g_packets = eLazyBoolCalculate;
295 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
297 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
298 m_supports_qXfer_features_read = eLazyBoolCalculate;
299 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
300 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
301 m_supports_qProcessInfoPID = true;
302 m_supports_qfProcessInfo = true;
303 m_supports_qUserName = true;
304 m_supports_qGroupName = true;
305 m_supports_qThreadStopInfo = true;
306 m_supports_z0 = true;
307 m_supports_z1 = true;
308 m_supports_z2 = true;
309 m_supports_z3 = true;
310 m_supports_z4 = true;
311 m_supports_QEnvironment = true;
312 m_supports_QEnvironmentHexEncoded = true;
313 m_supports_qSymbol = true;
314 m_qSymbol_requests_done = false;
315 m_supports_qModuleInfo = true;
317 m_os_version = llvm::VersionTuple();
321 m_gdb_server_name.clear();
322 m_gdb_server_version = UINT32_MAX;
323 m_default_packet_timeout = seconds(0);
324 m_max_packet_size = 0;
325 m_qSupported_response.clear();
326 m_supported_async_json_packets_is_valid = false;
327 m_supported_async_json_packets_sp.reset();
328 m_supports_jModulesInfo = true;
331 // These flags should be reset when we first connect to a GDB server and when
332 // our inferior process execs
333 m_qProcessInfo_is_valid = eLazyBoolCalculate;
334 m_process_arch.Clear();
337 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
338 // Clear out any capabilities we expect to see in the qSupported response
339 m_supports_qXfer_auxv_read = eLazyBoolNo;
340 m_supports_qXfer_libraries_read = eLazyBoolNo;
341 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
342 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
343 m_supports_qXfer_features_read = eLazyBoolNo;
344 m_supports_qXfer_memory_map_read = eLazyBoolNo;
345 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
346 // not, we assume no limit
348 // build the qSupported packet
349 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc"};
351 packet.PutCString("qSupported");
352 for (uint32_t i = 0; i < features.size(); ++i) {
353 packet.PutCString(i == 0 ? ":" : ";");
354 packet.PutCString(features[i]);
357 StringExtractorGDBRemote response;
358 if (SendPacketAndWaitForResponse(packet.GetString(), response,
359 /*send_async=*/false) ==
360 PacketResult::Success) {
361 const char *response_cstr = response.GetStringRef().data();
363 // Hang on to the qSupported packet, so that platforms can do custom
364 // configuration of the transport before attaching/launching the process.
365 m_qSupported_response = response_cstr;
367 if (::strstr(response_cstr, "qXfer:auxv:read+"))
368 m_supports_qXfer_auxv_read = eLazyBoolYes;
369 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
370 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
371 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
372 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
373 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
375 if (::strstr(response_cstr, "qXfer:libraries:read+"))
376 m_supports_qXfer_libraries_read = eLazyBoolYes;
377 if (::strstr(response_cstr, "qXfer:features:read+"))
378 m_supports_qXfer_features_read = eLazyBoolYes;
379 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
380 m_supports_qXfer_memory_map_read = eLazyBoolYes;
382 // Look for a list of compressions in the features list e.g.
383 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
385 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
387 const char *compressions =
388 ::strstr(features_list, "SupportedCompressions=");
390 std::vector<std::string> supported_compressions;
391 compressions += sizeof("SupportedCompressions=") - 1;
392 const char *end_of_compressions = strchr(compressions, ';');
393 if (end_of_compressions == nullptr) {
394 end_of_compressions = strchr(compressions, '\0');
396 const char *current_compression = compressions;
397 while (current_compression < end_of_compressions) {
398 const char *next_compression_name = strchr(current_compression, ',');
399 const char *end_of_this_word = next_compression_name;
400 if (next_compression_name == nullptr ||
401 end_of_compressions < next_compression_name) {
402 end_of_this_word = end_of_compressions;
405 if (end_of_this_word) {
406 if (end_of_this_word == current_compression) {
407 current_compression++;
409 std::string this_compression(
410 current_compression, end_of_this_word - current_compression);
411 supported_compressions.push_back(this_compression);
412 current_compression = end_of_this_word + 1;
415 supported_compressions.push_back(current_compression);
416 current_compression = end_of_compressions;
420 if (supported_compressions.size() > 0) {
421 MaybeEnableCompression(supported_compressions);
426 if (::strstr(response_cstr, "qEcho"))
427 m_supports_qEcho = eLazyBoolYes;
429 m_supports_qEcho = eLazyBoolNo;
431 if (::strstr(response_cstr, "QPassSignals+"))
432 m_supports_QPassSignals = eLazyBoolYes;
434 m_supports_QPassSignals = eLazyBoolNo;
436 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
437 if (packet_size_str) {
438 StringExtractorGDBRemote packet_response(packet_size_str +
439 strlen("PacketSize="));
441 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
442 if (m_max_packet_size == 0) {
443 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
445 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
446 LLDB_LOGF(log, "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().data();
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))
532 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
534 __FUNCTION__, payload.GetData());
535 return PacketResult::ErrorNoSequenceLock;
538 if (GetThreadSuffixSupported())
539 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
541 if (!SetCurrentThread(tid))
542 return PacketResult::ErrorSendFailed;
545 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
548 // Check if the target supports 'p' packet. It sends out a 'p' packet and
549 // checks the response. A normal packet will tell us that support is available.
551 // Takes a valid thread ID because p needs to apply to a thread.
552 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
553 if (m_supports_p == eLazyBoolCalculate)
554 m_supports_p = GetThreadPacketSupported(tid, "p0");
558 LazyBool GDBRemoteCommunicationClient::GetThreadPacketSupported(
559 lldb::tid_t tid, llvm::StringRef packetStr) {
560 StreamString payload;
561 payload.PutCString(packetStr);
562 StringExtractorGDBRemote response;
563 if (SendThreadSpecificPacketAndWaitForResponse(
564 tid, std::move(payload), response, false) == PacketResult::Success &&
565 response.IsNormalResponse()) {
571 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
572 // Get information on all threads at one using the "jThreadsInfo" packet
573 StructuredData::ObjectSP object_sp;
575 if (m_supports_jThreadsInfo) {
576 StringExtractorGDBRemote response;
577 response.SetResponseValidatorToJSON();
578 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
579 PacketResult::Success) {
580 if (response.IsUnsupportedResponse()) {
581 m_supports_jThreadsInfo = false;
582 } else if (!response.Empty()) {
584 StructuredData::ParseJSON(std::string(response.GetStringRef()));
591 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
592 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
593 StringExtractorGDBRemote response;
594 m_supports_jThreadExtendedInfo = eLazyBoolNo;
595 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
596 PacketResult::Success) {
597 if (response.IsOKResponse()) {
598 m_supports_jThreadExtendedInfo = eLazyBoolYes;
602 return m_supports_jThreadExtendedInfo;
605 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
606 if (m_supports_error_string_reply == eLazyBoolCalculate) {
607 StringExtractorGDBRemote response;
608 // We try to enable error strings in remote packets but if we fail, we just
609 // work in the older way.
610 m_supports_error_string_reply = eLazyBoolNo;
611 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
612 PacketResult::Success) {
613 if (response.IsOKResponse()) {
614 m_supports_error_string_reply = eLazyBoolYes;
620 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
621 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
622 StringExtractorGDBRemote response;
623 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
624 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
626 false) == PacketResult::Success) {
627 if (response.IsOKResponse()) {
628 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
632 return m_supports_jLoadedDynamicLibrariesInfos;
635 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
636 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
637 StringExtractorGDBRemote response;
638 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
639 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
640 PacketResult::Success) {
641 if (response.IsOKResponse()) {
642 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
646 return m_supports_jGetSharedCacheInfo;
649 bool GDBRemoteCommunicationClient::GetxPacketSupported() {
650 if (m_supports_x == eLazyBoolCalculate) {
651 StringExtractorGDBRemote response;
652 m_supports_x = eLazyBoolNo;
654 snprintf(packet, sizeof(packet), "x0,0");
655 if (SendPacketAndWaitForResponse(packet, response, false) ==
656 PacketResult::Success) {
657 if (response.IsOKResponse())
658 m_supports_x = eLazyBoolYes;
664 GDBRemoteCommunicationClient::PacketResult
665 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
666 const char *payload_prefix, std::string &response_string) {
667 Lock lock(*this, false);
669 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
672 "error: failed to get packet sequence mutex, not sending "
673 "packets with prefix '%s'",
675 return PacketResult::ErrorNoSequenceLock;
678 response_string = "";
679 std::string payload_prefix_str(payload_prefix);
680 unsigned int response_size = 0x1000;
681 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
682 response_size = GetRemoteMaxPacketSize();
685 for (unsigned int offset = 0; true; offset += response_size) {
686 StringExtractorGDBRemote this_response;
688 char sizeDescriptor[128];
689 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
691 PacketResult result = SendPacketAndWaitForResponseNoLock(
692 payload_prefix_str + sizeDescriptor, this_response);
693 if (result != PacketResult::Success)
696 const std::string &this_string = std::string(this_response.GetStringRef());
698 // Check for m or l as first character; l seems to mean this is the last
700 char first_char = *this_string.c_str();
701 if (first_char != 'm' && first_char != 'l') {
702 return PacketResult::ErrorReplyInvalid;
704 // Concatenate the result so far (skipping 'm' or 'l')
705 response_string.append(this_string, 1, std::string::npos);
706 if (first_char == 'l')
708 return PacketResult::Success;
712 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
713 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
716 // First try to retrieve the pid via the qProcessInfo request.
717 GetCurrentProcessInfo(allow_lazy);
718 if (m_curr_pid_is_valid == eLazyBoolYes) {
722 // If we don't get a response for qProcessInfo, check if $qC gives us a
723 // result. $qC only returns a real process id on older debugserver and
724 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
725 // the thread id, which newer debugserver and lldb-gdbserver stubs return
727 StringExtractorGDBRemote response;
728 if (SendPacketAndWaitForResponse("qC", response, false) ==
729 PacketResult::Success) {
730 if (response.GetChar() == 'Q') {
731 if (response.GetChar() == 'C') {
732 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
733 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
734 m_curr_pid_is_valid = eLazyBoolYes;
741 // If we don't get a response for $qC, check if $qfThreadID gives us a
743 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
744 std::vector<lldb::tid_t> thread_ids;
745 bool sequence_mutex_unavailable;
747 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
748 if (size && !sequence_mutex_unavailable) {
749 m_curr_pid = thread_ids.front();
750 m_curr_pid_is_valid = eLazyBoolYes;
756 return LLDB_INVALID_PROCESS_ID;
759 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
761 StringExtractorGDBRemote response;
762 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
763 PacketResult::Success) {
764 if (response.IsOKResponse())
766 if (response.GetChar() == 'E') {
767 // A string the describes what failed when launching...
768 error_str = std::string(response.GetStringRef().substr(1));
770 error_str.assign("unknown error occurred launching process");
773 error_str.assign("timed out waiting for app to launch");
778 int GDBRemoteCommunicationClient::SendArgumentsPacket(
779 const ProcessLaunchInfo &launch_info) {
780 // Since we don't get the send argv0 separate from the executable path, we
781 // need to make sure to use the actual executable path found in the
783 std::vector<const char *> argv;
784 FileSpec exe_file = launch_info.GetExecutableFile();
785 std::string exe_path;
786 const char *arg = nullptr;
787 const Args &launch_args = launch_info.GetArguments();
789 exe_path = exe_file.GetPath(false);
791 arg = launch_args.GetArgumentAtIndex(0);
795 if (!exe_path.empty()) {
796 argv.push_back(exe_path.c_str());
797 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != nullptr;
806 for (size_t i = 0, n = argv.size(); i < n; ++i) {
808 const int arg_len = strlen(arg);
811 packet.Printf("%i,%i,", arg_len * 2, (int)i);
812 packet.PutBytesAsRawHex8(arg, arg_len);
815 StringExtractorGDBRemote response;
816 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
817 PacketResult::Success) {
818 if (response.IsOKResponse())
820 uint8_t error = response.GetError();
828 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
829 for (const auto &KV : env) {
830 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
837 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
838 char const *name_equal_value) {
839 if (name_equal_value && name_equal_value[0]) {
841 bool send_hex_encoding = false;
842 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
844 if (llvm::isPrint(*p)) {
850 send_hex_encoding = true;
856 // We have non printable characters, lets hex encode this...
857 send_hex_encoding = true;
861 StringExtractorGDBRemote response;
862 if (send_hex_encoding) {
863 if (m_supports_QEnvironmentHexEncoded) {
864 packet.PutCString("QEnvironmentHexEncoded:");
865 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
866 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
867 PacketResult::Success) {
868 if (response.IsOKResponse())
870 uint8_t error = response.GetError();
873 if (response.IsUnsupportedResponse())
874 m_supports_QEnvironmentHexEncoded = false;
878 } else if (m_supports_QEnvironment) {
879 packet.Printf("QEnvironment:%s", name_equal_value);
880 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
881 PacketResult::Success) {
882 if (response.IsOKResponse())
884 uint8_t error = response.GetError();
887 if (response.IsUnsupportedResponse())
888 m_supports_QEnvironment = false;
895 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
896 if (arch && arch[0]) {
898 packet.Printf("QLaunchArch:%s", arch);
899 StringExtractorGDBRemote response;
900 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
901 PacketResult::Success) {
902 if (response.IsOKResponse())
904 uint8_t error = response.GetError();
912 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
913 char const *data, bool *was_supported) {
914 if (data && *data != '\0') {
916 packet.Printf("QSetProcessEvent:%s", data);
917 StringExtractorGDBRemote response;
918 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
919 PacketResult::Success) {
920 if (response.IsOKResponse()) {
922 *was_supported = true;
924 } else if (response.IsUnsupportedResponse()) {
926 *was_supported = false;
929 uint8_t error = response.GetError();
931 *was_supported = true;
940 llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
945 llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() {
947 return m_maccatalyst_version;
950 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
952 if (!m_os_build.empty()) {
961 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
963 if (!m_os_kernel.empty()) {
972 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
974 if (!m_hostname.empty()) {
983 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
989 const lldb_private::ArchSpec &
990 GDBRemoteCommunicationClient::GetProcessArchitecture() {
991 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
992 GetCurrentProcessInfo();
993 return m_process_arch;
996 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
997 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
998 m_gdb_server_name.clear();
999 m_gdb_server_version = 0;
1000 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1002 StringExtractorGDBRemote response;
1003 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
1004 PacketResult::Success) {
1005 if (response.IsNormalResponse()) {
1006 llvm::StringRef name, value;
1007 bool success = false;
1008 while (response.GetNameColonValue(name, value)) {
1009 if (name.equals("name")) {
1011 m_gdb_server_name = std::string(value);
1012 } else if (name.equals("version")) {
1013 llvm::StringRef major, minor;
1014 std::tie(major, minor) = value.split('.');
1015 if (!major.getAsInteger(0, m_gdb_server_version))
1020 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1024 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1027 void GDBRemoteCommunicationClient::MaybeEnableCompression(
1028 std::vector<std::string> supported_compressions) {
1029 CompressionType avail_type = CompressionType::None;
1030 std::string avail_name;
1032 #if defined(HAVE_LIBCOMPRESSION)
1033 if (avail_type == CompressionType::None) {
1034 for (auto compression : supported_compressions) {
1035 if (compression == "lzfse") {
1036 avail_type = CompressionType::LZFSE;
1037 avail_name = compression;
1044 #if defined(HAVE_LIBCOMPRESSION)
1045 if (avail_type == CompressionType::None) {
1046 for (auto compression : supported_compressions) {
1047 if (compression == "zlib-deflate") {
1048 avail_type = CompressionType::ZlibDeflate;
1049 avail_name = compression;
1056 #if defined(HAVE_LIBZ)
1057 if (avail_type == CompressionType::None) {
1058 for (auto compression : supported_compressions) {
1059 if (compression == "zlib-deflate") {
1060 avail_type = CompressionType::ZlibDeflate;
1061 avail_name = compression;
1068 #if defined(HAVE_LIBCOMPRESSION)
1069 if (avail_type == CompressionType::None) {
1070 for (auto compression : supported_compressions) {
1071 if (compression == "lz4") {
1072 avail_type = CompressionType::LZ4;
1073 avail_name = compression;
1080 #if defined(HAVE_LIBCOMPRESSION)
1081 if (avail_type == CompressionType::None) {
1082 for (auto compression : supported_compressions) {
1083 if (compression == "lzma") {
1084 avail_type = CompressionType::LZMA;
1085 avail_name = compression;
1092 if (avail_type != CompressionType::None) {
1093 StringExtractorGDBRemote response;
1094 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1095 if (SendPacketAndWaitForResponse(packet, response, false) !=
1096 PacketResult::Success)
1099 if (response.IsOKResponse()) {
1100 m_compression_type = avail_type;
1105 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1106 if (GetGDBServerVersion()) {
1107 if (!m_gdb_server_name.empty())
1108 return m_gdb_server_name.c_str();
1113 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1114 if (GetGDBServerVersion())
1115 return m_gdb_server_version;
1119 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1120 StringExtractorGDBRemote response;
1121 if (SendPacketAndWaitForResponse("qC", response, false) !=
1122 PacketResult::Success)
1125 if (!response.IsNormalResponse())
1128 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1129 tid = response.GetHexMaxU32(true, -1);
1134 static void ParseOSType(llvm::StringRef value, std::string &os_name,
1135 std::string &environment) {
1136 if (value.equals("iossimulator") || value.equals("tvossimulator") ||
1137 value.equals("watchossimulator")) {
1138 environment = "simulator";
1139 os_name = value.drop_back(environment.size()).str();
1140 } else if (value.equals("maccatalyst")) {
1142 environment = "macabi";
1144 os_name = value.str();
1148 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1149 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1151 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1152 // host info computation can require DNS traffic and shelling out to external processes.
1153 // Increase the timeout to account for that.
1154 ScopedTimeout timeout(*this, seconds(10));
1155 m_qHostInfo_is_valid = eLazyBoolNo;
1156 StringExtractorGDBRemote response;
1157 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1158 PacketResult::Success) {
1159 if (response.IsNormalResponse()) {
1160 llvm::StringRef name;
1161 llvm::StringRef value;
1162 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1164 std::string arch_name;
1165 std::string os_name;
1166 std::string environment;
1167 std::string vendor_name;
1169 std::string distribution_id;
1170 uint32_t pointer_byte_size = 0;
1171 ByteOrder byte_order = eByteOrderInvalid;
1172 uint32_t num_keys_decoded = 0;
1173 while (response.GetNameColonValue(name, value)) {
1174 if (name.equals("cputype")) {
1175 // exception type in big endian hex
1176 if (!value.getAsInteger(0, cpu))
1178 } else if (name.equals("cpusubtype")) {
1179 // exception count in big endian hex
1180 if (!value.getAsInteger(0, sub))
1182 } else if (name.equals("arch")) {
1183 arch_name = std::string(value);
1185 } else if (name.equals("triple")) {
1186 StringExtractor extractor(value);
1187 extractor.GetHexByteString(triple);
1189 } else if (name.equals("distribution_id")) {
1190 StringExtractor extractor(value);
1191 extractor.GetHexByteString(distribution_id);
1193 } else if (name.equals("os_build")) {
1194 StringExtractor extractor(value);
1195 extractor.GetHexByteString(m_os_build);
1197 } else if (name.equals("hostname")) {
1198 StringExtractor extractor(value);
1199 extractor.GetHexByteString(m_hostname);
1201 } else if (name.equals("os_kernel")) {
1202 StringExtractor extractor(value);
1203 extractor.GetHexByteString(m_os_kernel);
1205 } else if (name.equals("ostype")) {
1206 ParseOSType(value, os_name, environment);
1208 } else if (name.equals("vendor")) {
1209 vendor_name = std::string(value);
1211 } else if (name.equals("endian")) {
1212 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1213 .Case("little", eByteOrderLittle)
1214 .Case("big", eByteOrderBig)
1215 .Case("pdp", eByteOrderPDP)
1216 .Default(eByteOrderInvalid);
1217 if (byte_order != eByteOrderInvalid)
1219 } else if (name.equals("ptrsize")) {
1220 if (!value.getAsInteger(0, pointer_byte_size))
1222 } else if (name.equals("os_version") ||
1224 "version")) // Older debugserver binaries used the
1225 // "version" key instead of
1228 if (!m_os_version.tryParse(value))
1230 } else if (name.equals("maccatalyst_version")) {
1231 if (!m_maccatalyst_version.tryParse(value))
1233 } else if (name.equals("watchpoint_exceptions_received")) {
1234 m_watchpoints_trigger_after_instruction =
1235 llvm::StringSwitch<LazyBool>(value)
1236 .Case("before", eLazyBoolNo)
1237 .Case("after", eLazyBoolYes)
1238 .Default(eLazyBoolCalculate);
1239 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1241 } else if (name.equals("default_packet_timeout")) {
1242 uint32_t timeout_seconds;
1243 if (!value.getAsInteger(0, timeout_seconds)) {
1244 m_default_packet_timeout = seconds(timeout_seconds);
1245 SetPacketTimeout(m_default_packet_timeout);
1251 if (num_keys_decoded > 0)
1252 m_qHostInfo_is_valid = eLazyBoolYes;
1254 if (triple.empty()) {
1255 if (arch_name.empty()) {
1256 if (cpu != LLDB_INVALID_CPUTYPE) {
1257 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1258 if (pointer_byte_size) {
1259 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1261 if (byte_order != eByteOrderInvalid) {
1262 assert(byte_order == m_host_arch.GetByteOrder());
1265 if (!vendor_name.empty())
1266 m_host_arch.GetTriple().setVendorName(
1267 llvm::StringRef(vendor_name));
1268 if (!os_name.empty())
1269 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1270 if (!environment.empty())
1271 m_host_arch.GetTriple().setEnvironmentName(environment);
1275 triple += arch_name;
1276 if (!vendor_name.empty() || !os_name.empty()) {
1278 if (vendor_name.empty())
1279 triple += "unknown";
1281 triple += vendor_name;
1283 if (os_name.empty())
1284 triple += "unknown";
1288 m_host_arch.SetTriple(triple.c_str());
1290 llvm::Triple &host_triple = m_host_arch.GetTriple();
1291 if (host_triple.getVendor() == llvm::Triple::Apple &&
1292 host_triple.getOS() == llvm::Triple::Darwin) {
1293 switch (m_host_arch.GetMachine()) {
1294 case llvm::Triple::aarch64:
1295 case llvm::Triple::aarch64_32:
1296 case llvm::Triple::arm:
1297 case llvm::Triple::thumb:
1298 host_triple.setOS(llvm::Triple::IOS);
1301 host_triple.setOS(llvm::Triple::MacOSX);
1305 if (pointer_byte_size) {
1306 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1308 if (byte_order != eByteOrderInvalid) {
1309 assert(byte_order == m_host_arch.GetByteOrder());
1313 m_host_arch.SetTriple(triple.c_str());
1314 if (pointer_byte_size) {
1315 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1317 if (byte_order != eByteOrderInvalid) {
1318 assert(byte_order == m_host_arch.GetByteOrder());
1322 "GDBRemoteCommunicationClient::%s parsed host "
1323 "architecture as %s, triple as %s from triple text %s",
1325 m_host_arch.GetArchitectureName()
1326 ? m_host_arch.GetArchitectureName()
1327 : "<null-arch-name>",
1328 m_host_arch.GetTriple().getTriple().c_str(),
1331 if (!distribution_id.empty())
1332 m_host_arch.SetDistributionId(distribution_id.c_str());
1336 return m_qHostInfo_is_valid == eLazyBoolYes;
1339 int GDBRemoteCommunicationClient::SendAttach(
1340 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1341 if (pid != LLDB_INVALID_PROCESS_ID) {
1343 const int packet_len =
1344 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1345 UNUSED_IF_ASSERT_DISABLED(packet_len);
1346 assert(packet_len < (int)sizeof(packet));
1347 if (SendPacketAndWaitForResponse(packet, response, false) ==
1348 PacketResult::Success) {
1349 if (response.IsErrorResponse())
1350 return response.GetError();
1357 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1359 StreamString packet;
1360 packet.PutCString("I");
1361 packet.PutBytesAsRawHex8(data, data_len);
1362 StringExtractorGDBRemote response;
1363 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1364 PacketResult::Success) {
1367 return response.GetError();
1370 const lldb_private::ArchSpec &
1371 GDBRemoteCommunicationClient::GetHostArchitecture() {
1372 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1377 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1378 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1380 return m_default_packet_timeout;
1383 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1384 uint32_t permissions) {
1385 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1386 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1388 const int packet_len = ::snprintf(
1389 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1390 permissions & lldb::ePermissionsReadable ? "r" : "",
1391 permissions & lldb::ePermissionsWritable ? "w" : "",
1392 permissions & lldb::ePermissionsExecutable ? "x" : "");
1393 assert(packet_len < (int)sizeof(packet));
1394 UNUSED_IF_ASSERT_DISABLED(packet_len);
1395 StringExtractorGDBRemote response;
1396 if (SendPacketAndWaitForResponse(packet, response, false) ==
1397 PacketResult::Success) {
1398 if (response.IsUnsupportedResponse())
1399 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1400 else if (!response.IsErrorResponse())
1401 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1403 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1406 return LLDB_INVALID_ADDRESS;
1409 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1410 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1411 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1413 const int packet_len =
1414 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1415 assert(packet_len < (int)sizeof(packet));
1416 UNUSED_IF_ASSERT_DISABLED(packet_len);
1417 StringExtractorGDBRemote response;
1418 if (SendPacketAndWaitForResponse(packet, response, false) ==
1419 PacketResult::Success) {
1420 if (response.IsUnsupportedResponse())
1421 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1422 else if (response.IsOKResponse())
1425 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1431 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1435 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1437 const int packet_len =
1438 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1439 assert(packet_len < (int)sizeof(packet));
1440 UNUSED_IF_ASSERT_DISABLED(packet_len);
1441 StringExtractorGDBRemote response;
1442 if (SendPacketAndWaitForResponse(packet, response, false) ==
1443 PacketResult::Success &&
1444 response.IsOKResponse()) {
1445 m_supports_detach_stay_stopped = eLazyBoolYes;
1447 m_supports_detach_stay_stopped = eLazyBoolNo;
1451 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1452 error.SetErrorString("Stays stopped not supported by this target.");
1455 StringExtractorGDBRemote response;
1456 PacketResult packet_result =
1457 SendPacketAndWaitForResponse("D1", response, false);
1458 if (packet_result != PacketResult::Success)
1459 error.SetErrorString("Sending extended disconnect packet failed.");
1462 StringExtractorGDBRemote response;
1463 PacketResult packet_result =
1464 SendPacketAndWaitForResponse("D", response, false);
1465 if (packet_result != PacketResult::Success)
1466 error.SetErrorString("Sending disconnect packet failed.");
1471 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1472 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1474 region_info.Clear();
1476 if (m_supports_memory_region_info != eLazyBoolNo) {
1477 m_supports_memory_region_info = eLazyBoolYes;
1479 const int packet_len = ::snprintf(
1480 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1481 assert(packet_len < (int)sizeof(packet));
1482 UNUSED_IF_ASSERT_DISABLED(packet_len);
1483 StringExtractorGDBRemote response;
1484 if (SendPacketAndWaitForResponse(packet, response, false) ==
1485 PacketResult::Success &&
1486 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
1487 llvm::StringRef name;
1488 llvm::StringRef value;
1489 addr_t addr_value = LLDB_INVALID_ADDRESS;
1490 bool success = true;
1491 bool saw_permissions = false;
1492 while (success && response.GetNameColonValue(name, value)) {
1493 if (name.equals("start")) {
1494 if (!value.getAsInteger(16, addr_value))
1495 region_info.GetRange().SetRangeBase(addr_value);
1496 } else if (name.equals("size")) {
1497 if (!value.getAsInteger(16, addr_value))
1498 region_info.GetRange().SetByteSize(addr_value);
1499 } else if (name.equals("permissions") &&
1500 region_info.GetRange().IsValid()) {
1501 saw_permissions = true;
1502 if (region_info.GetRange().Contains(addr)) {
1503 if (value.find('r') != llvm::StringRef::npos)
1504 region_info.SetReadable(MemoryRegionInfo::eYes);
1506 region_info.SetReadable(MemoryRegionInfo::eNo);
1508 if (value.find('w') != llvm::StringRef::npos)
1509 region_info.SetWritable(MemoryRegionInfo::eYes);
1511 region_info.SetWritable(MemoryRegionInfo::eNo);
1513 if (value.find('x') != llvm::StringRef::npos)
1514 region_info.SetExecutable(MemoryRegionInfo::eYes);
1516 region_info.SetExecutable(MemoryRegionInfo::eNo);
1518 region_info.SetMapped(MemoryRegionInfo::eYes);
1520 // The reported region does not contain this address -- we're
1521 // looking at an unmapped page
1522 region_info.SetReadable(MemoryRegionInfo::eNo);
1523 region_info.SetWritable(MemoryRegionInfo::eNo);
1524 region_info.SetExecutable(MemoryRegionInfo::eNo);
1525 region_info.SetMapped(MemoryRegionInfo::eNo);
1527 } else if (name.equals("name")) {
1528 StringExtractorGDBRemote name_extractor(value);
1530 name_extractor.GetHexByteString(name);
1531 region_info.SetName(name.c_str());
1532 } else if (name.equals("error")) {
1533 StringExtractorGDBRemote error_extractor(value);
1534 std::string error_string;
1535 // Now convert the HEX bytes into a string value
1536 error_extractor.GetHexByteString(error_string);
1537 error.SetErrorString(error_string.c_str());
1541 if (region_info.GetRange().IsValid()) {
1542 // We got a valid address range back but no permissions -- which means
1543 // this is an unmapped page
1544 if (!saw_permissions) {
1545 region_info.SetReadable(MemoryRegionInfo::eNo);
1546 region_info.SetWritable(MemoryRegionInfo::eNo);
1547 region_info.SetExecutable(MemoryRegionInfo::eNo);
1548 region_info.SetMapped(MemoryRegionInfo::eNo);
1551 // We got an invalid address range back
1552 error.SetErrorString("Server returned invalid range");
1555 m_supports_memory_region_info = eLazyBoolNo;
1559 if (m_supports_memory_region_info == eLazyBoolNo) {
1560 error.SetErrorString("qMemoryRegionInfo is not supported");
1563 // Try qXfer:memory-map:read to get region information not included in
1564 // qMemoryRegionInfo
1565 MemoryRegionInfo qXfer_region_info;
1566 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1569 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1570 // the qXfer result as a fallback
1571 if (qXfer_error.Success()) {
1572 region_info = qXfer_region_info;
1575 region_info.Clear();
1577 } else if (qXfer_error.Success()) {
1578 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1579 // both regions are the same range, update the result to include the flash-
1580 // memory information that is specific to the qXfer result.
1581 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1582 region_info.SetFlash(qXfer_region_info.GetFlash());
1583 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1589 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1590 lldb::addr_t addr, MemoryRegionInfo ®ion) {
1591 Status error = LoadQXferMemoryMap();
1592 if (!error.Success())
1594 for (const auto &map_region : m_qXfer_memory_map) {
1595 if (map_region.GetRange().Contains(addr)) {
1596 region = map_region;
1600 error.SetErrorString("Region not found");
1604 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1608 if (m_qXfer_memory_map_loaded)
1609 // Already loaded, return success
1612 if (!XMLDocument::XMLEnabled()) {
1613 error.SetErrorString("XML is not supported");
1617 if (!GetQXferMemoryMapReadSupported()) {
1618 error.SetErrorString("Memory map is not supported");
1623 lldb_private::Status lldberr;
1624 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1626 error.SetErrorString("Failed to read memory map");
1630 XMLDocument xml_document;
1632 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1633 error.SetErrorString("Failed to parse memory map xml");
1637 XMLNode map_node = xml_document.GetRootElement("memory-map");
1639 error.SetErrorString("Invalid root node in memory map xml");
1643 m_qXfer_memory_map.clear();
1645 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1646 if (!memory_node.IsElement())
1648 if (memory_node.GetName() != "memory")
1650 auto type = memory_node.GetAttributeValue("type", "");
1653 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1655 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1657 MemoryRegionInfo region;
1658 region.GetRange().SetRangeBase(start);
1659 region.GetRange().SetByteSize(length);
1660 if (type == "rom") {
1661 region.SetReadable(MemoryRegionInfo::eYes);
1662 this->m_qXfer_memory_map.push_back(region);
1663 } else if (type == "ram") {
1664 region.SetReadable(MemoryRegionInfo::eYes);
1665 region.SetWritable(MemoryRegionInfo::eYes);
1666 this->m_qXfer_memory_map.push_back(region);
1667 } else if (type == "flash") {
1668 region.SetFlash(MemoryRegionInfo::eYes);
1669 memory_node.ForEachChildElement(
1670 [®ion](const XMLNode &prop_node) -> bool {
1671 if (!prop_node.IsElement())
1673 if (prop_node.GetName() != "property")
1675 auto propname = prop_node.GetAttributeValue("name", "");
1676 if (propname == "blocksize") {
1678 if (prop_node.GetElementTextAsUnsigned(blocksize))
1679 region.SetBlocksize(blocksize);
1683 this->m_qXfer_memory_map.push_back(region);
1688 m_qXfer_memory_map_loaded = true;
1693 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1696 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1697 num = m_num_supported_hardware_watchpoints;
1701 // Set num to 0 first.
1703 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1705 const int packet_len =
1706 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1707 assert(packet_len < (int)sizeof(packet));
1708 UNUSED_IF_ASSERT_DISABLED(packet_len);
1709 StringExtractorGDBRemote response;
1710 if (SendPacketAndWaitForResponse(packet, response, false) ==
1711 PacketResult::Success) {
1712 m_supports_watchpoint_support_info = eLazyBoolYes;
1713 llvm::StringRef name;
1714 llvm::StringRef value;
1715 bool found_num_field = false;
1716 while (response.GetNameColonValue(name, value)) {
1717 if (name.equals("num")) {
1718 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1719 num = m_num_supported_hardware_watchpoints;
1720 found_num_field = true;
1723 if (!found_num_field) {
1724 m_supports_watchpoint_support_info = eLazyBoolNo;
1727 m_supports_watchpoint_support_info = eLazyBoolNo;
1731 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1732 error.SetErrorString("qWatchpointSupportInfo is not supported");
1737 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1738 uint32_t &num, bool &after, const ArchSpec &arch) {
1739 Status error(GetWatchpointSupportInfo(num));
1740 if (error.Success())
1741 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1745 lldb_private::Status
1746 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1747 bool &after, const ArchSpec &arch) {
1749 llvm::Triple triple = arch.GetTriple();
1751 // we assume watchpoints will happen after running the relevant opcode and we
1752 // only want to override this behavior if we have explicitly received a
1753 // qHostInfo telling us otherwise
1754 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1755 // On targets like MIPS and ppc64, watchpoint exceptions are always
1756 // generated before the instruction is executed. The connected target may
1757 // not support qHostInfo or qWatchpointSupportInfo packets.
1758 after = !(triple.isMIPS() || triple.isPPC64());
1760 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
1761 // eLazyBoolNo if it is not calculated before.
1762 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1763 (triple.isMIPS() || triple.isPPC64()))
1764 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1766 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1771 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1773 std::string path{file_spec.GetPath(false)};
1774 StreamString packet;
1775 packet.PutCString("QSetSTDIN:");
1776 packet.PutStringAsRawHex8(path);
1778 StringExtractorGDBRemote response;
1779 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1780 PacketResult::Success) {
1781 if (response.IsOKResponse())
1783 uint8_t error = response.GetError();
1791 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1793 std::string path{file_spec.GetPath(false)};
1794 StreamString packet;
1795 packet.PutCString("QSetSTDOUT:");
1796 packet.PutStringAsRawHex8(path);
1798 StringExtractorGDBRemote response;
1799 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1800 PacketResult::Success) {
1801 if (response.IsOKResponse())
1803 uint8_t error = response.GetError();
1811 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1813 std::string path{file_spec.GetPath(false)};
1814 StreamString packet;
1815 packet.PutCString("QSetSTDERR:");
1816 packet.PutStringAsRawHex8(path);
1818 StringExtractorGDBRemote response;
1819 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1820 PacketResult::Success) {
1821 if (response.IsOKResponse())
1823 uint8_t error = response.GetError();
1831 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1832 StringExtractorGDBRemote response;
1833 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1834 PacketResult::Success) {
1835 if (response.IsUnsupportedResponse())
1837 if (response.IsErrorResponse())
1840 response.GetHexByteString(cwd);
1841 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1842 return !cwd.empty();
1847 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1849 std::string path{working_dir.GetPath(false)};
1850 StreamString packet;
1851 packet.PutCString("QSetWorkingDir:");
1852 packet.PutStringAsRawHex8(path);
1854 StringExtractorGDBRemote response;
1855 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1856 PacketResult::Success) {
1857 if (response.IsOKResponse())
1859 uint8_t error = response.GetError();
1867 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1869 const int packet_len =
1870 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1871 assert(packet_len < (int)sizeof(packet));
1872 UNUSED_IF_ASSERT_DISABLED(packet_len);
1873 StringExtractorGDBRemote response;
1874 if (SendPacketAndWaitForResponse(packet, response, false) ==
1875 PacketResult::Success) {
1876 if (response.IsOKResponse())
1878 uint8_t error = response.GetError();
1885 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1887 const int packet_len = ::snprintf(packet, sizeof(packet),
1888 "QSetDetachOnError:%i", enable ? 1 : 0);
1889 assert(packet_len < (int)sizeof(packet));
1890 UNUSED_IF_ASSERT_DISABLED(packet_len);
1891 StringExtractorGDBRemote response;
1892 if (SendPacketAndWaitForResponse(packet, response, false) ==
1893 PacketResult::Success) {
1894 if (response.IsOKResponse())
1896 uint8_t error = response.GetError();
1903 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1904 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1905 if (response.IsNormalResponse()) {
1906 llvm::StringRef name;
1907 llvm::StringRef value;
1908 StringExtractor extractor;
1910 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1913 std::string os_type;
1915 while (response.GetNameColonValue(name, value)) {
1916 if (name.equals("pid")) {
1917 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1918 value.getAsInteger(0, pid);
1919 process_info.SetProcessID(pid);
1920 } else if (name.equals("ppid")) {
1921 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1922 value.getAsInteger(0, pid);
1923 process_info.SetParentProcessID(pid);
1924 } else if (name.equals("uid")) {
1925 uint32_t uid = UINT32_MAX;
1926 value.getAsInteger(0, uid);
1927 process_info.SetUserID(uid);
1928 } else if (name.equals("euid")) {
1929 uint32_t uid = UINT32_MAX;
1930 value.getAsInteger(0, uid);
1931 process_info.SetEffectiveUserID(uid);
1932 } else if (name.equals("gid")) {
1933 uint32_t gid = UINT32_MAX;
1934 value.getAsInteger(0, gid);
1935 process_info.SetGroupID(gid);
1936 } else if (name.equals("egid")) {
1937 uint32_t gid = UINT32_MAX;
1938 value.getAsInteger(0, gid);
1939 process_info.SetEffectiveGroupID(gid);
1940 } else if (name.equals("triple")) {
1941 StringExtractor extractor(value);
1943 extractor.GetHexByteString(triple);
1944 process_info.GetArchitecture().SetTriple(triple.c_str());
1945 } else if (name.equals("name")) {
1946 StringExtractor extractor(value);
1947 // The process name from ASCII hex bytes since we can't control the
1948 // characters in a process name
1950 extractor.GetHexByteString(name);
1951 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
1952 } else if (name.equals("args")) {
1953 llvm::StringRef encoded_args(value), hex_arg;
1955 bool is_arg0 = true;
1956 while (!encoded_args.empty()) {
1957 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
1959 StringExtractor extractor(hex_arg);
1960 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
1961 // In case of wrong encoding, we discard all the arguments
1962 process_info.GetArguments().Clear();
1963 process_info.SetArg0("");
1967 process_info.SetArg0(arg);
1969 process_info.GetArguments().AppendArgument(arg);
1972 } else if (name.equals("cputype")) {
1973 value.getAsInteger(0, cpu);
1974 } else if (name.equals("cpusubtype")) {
1975 value.getAsInteger(0, sub);
1976 } else if (name.equals("vendor")) {
1977 vendor = std::string(value);
1978 } else if (name.equals("ostype")) {
1979 os_type = std::string(value);
1983 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1984 if (vendor == "apple") {
1985 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1987 process_info.GetArchitecture().GetTriple().setVendorName(
1988 llvm::StringRef(vendor));
1989 process_info.GetArchitecture().GetTriple().setOSName(
1990 llvm::StringRef(os_type));
1994 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2000 bool GDBRemoteCommunicationClient::GetProcessInfo(
2001 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2002 process_info.Clear();
2004 if (m_supports_qProcessInfoPID) {
2006 const int packet_len =
2007 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2008 assert(packet_len < (int)sizeof(packet));
2009 UNUSED_IF_ASSERT_DISABLED(packet_len);
2010 StringExtractorGDBRemote response;
2011 if (SendPacketAndWaitForResponse(packet, response, false) ==
2012 PacketResult::Success) {
2013 return DecodeProcessInfoResponse(response, process_info);
2015 m_supports_qProcessInfoPID = false;
2022 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
2023 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2027 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2029 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2035 StringExtractorGDBRemote response;
2036 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
2037 PacketResult::Success) {
2038 if (response.IsNormalResponse()) {
2039 llvm::StringRef name;
2040 llvm::StringRef value;
2041 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2043 std::string arch_name;
2044 std::string os_name;
2045 std::string environment;
2046 std::string vendor_name;
2048 std::string elf_abi;
2049 uint32_t pointer_byte_size = 0;
2050 StringExtractor extractor;
2051 ByteOrder byte_order = eByteOrderInvalid;
2052 uint32_t num_keys_decoded = 0;
2053 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2054 while (response.GetNameColonValue(name, value)) {
2055 if (name.equals("cputype")) {
2056 if (!value.getAsInteger(16, cpu))
2058 } else if (name.equals("cpusubtype")) {
2059 if (!value.getAsInteger(16, sub))
2061 } else if (name.equals("triple")) {
2062 StringExtractor extractor(value);
2063 extractor.GetHexByteString(triple);
2065 } else if (name.equals("ostype")) {
2066 ParseOSType(value, os_name, environment);
2068 } else if (name.equals("vendor")) {
2069 vendor_name = std::string(value);
2071 } else if (name.equals("endian")) {
2072 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2073 .Case("little", eByteOrderLittle)
2074 .Case("big", eByteOrderBig)
2075 .Case("pdp", eByteOrderPDP)
2076 .Default(eByteOrderInvalid);
2077 if (byte_order != eByteOrderInvalid)
2079 } else if (name.equals("ptrsize")) {
2080 if (!value.getAsInteger(16, pointer_byte_size))
2082 } else if (name.equals("pid")) {
2083 if (!value.getAsInteger(16, pid))
2085 } else if (name.equals("elf_abi")) {
2086 elf_abi = std::string(value);
2090 if (num_keys_decoded > 0)
2091 m_qProcessInfo_is_valid = eLazyBoolYes;
2092 if (pid != LLDB_INVALID_PROCESS_ID) {
2093 m_curr_pid_is_valid = eLazyBoolYes;
2097 // Set the ArchSpec from the triple if we have it.
2098 if (!triple.empty()) {
2099 m_process_arch.SetTriple(triple.c_str());
2100 m_process_arch.SetFlags(elf_abi);
2101 if (pointer_byte_size) {
2102 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2104 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2105 !vendor_name.empty()) {
2106 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2107 if (!environment.empty())
2108 triple.setEnvironmentName(environment);
2110 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2111 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2112 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2113 switch (triple.getObjectFormat()) {
2114 case llvm::Triple::MachO:
2115 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2117 case llvm::Triple::ELF:
2118 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2120 case llvm::Triple::COFF:
2121 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2123 case llvm::Triple::Wasm:
2124 case llvm::Triple::XCOFF:
2125 LLDB_LOGF(log, "error: not supported target architecture");
2127 case llvm::Triple::UnknownObjectFormat:
2128 LLDB_LOGF(log, "error: failed to determine target architecture");
2132 if (pointer_byte_size) {
2133 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2135 if (byte_order != eByteOrderInvalid) {
2136 assert(byte_order == m_process_arch.GetByteOrder());
2138 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2139 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2140 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2141 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2142 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2143 m_host_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2148 m_qProcessInfo_is_valid = eLazyBoolNo;
2154 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2155 const ProcessInstanceInfoMatch &match_info,
2156 ProcessInstanceInfoList &process_infos) {
2157 process_infos.clear();
2159 if (m_supports_qfProcessInfo) {
2160 StreamString packet;
2161 packet.PutCString("qfProcessInfo");
2162 if (!match_info.MatchAllProcesses()) {
2163 packet.PutChar(':');
2164 const char *name = match_info.GetProcessInfo().GetName();
2165 bool has_name_match = false;
2166 if (name && name[0]) {
2167 has_name_match = true;
2168 NameMatch name_match_type = match_info.GetNameMatchType();
2169 switch (name_match_type) {
2170 case NameMatch::Ignore:
2171 has_name_match = false;
2174 case NameMatch::Equals:
2175 packet.PutCString("name_match:equals;");
2178 case NameMatch::Contains:
2179 packet.PutCString("name_match:contains;");
2182 case NameMatch::StartsWith:
2183 packet.PutCString("name_match:starts_with;");
2186 case NameMatch::EndsWith:
2187 packet.PutCString("name_match:ends_with;");
2190 case NameMatch::RegularExpression:
2191 packet.PutCString("name_match:regex;");
2194 if (has_name_match) {
2195 packet.PutCString("name:");
2196 packet.PutBytesAsRawHex8(name, ::strlen(name));
2197 packet.PutChar(';');
2201 if (match_info.GetProcessInfo().ProcessIDIsValid())
2202 packet.Printf("pid:%" PRIu64 ";",
2203 match_info.GetProcessInfo().GetProcessID());
2204 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2205 packet.Printf("parent_pid:%" PRIu64 ";",
2206 match_info.GetProcessInfo().GetParentProcessID());
2207 if (match_info.GetProcessInfo().UserIDIsValid())
2208 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2209 if (match_info.GetProcessInfo().GroupIDIsValid())
2210 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2211 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2212 packet.Printf("euid:%u;",
2213 match_info.GetProcessInfo().GetEffectiveUserID());
2214 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2215 packet.Printf("egid:%u;",
2216 match_info.GetProcessInfo().GetEffectiveGroupID());
2217 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2218 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2219 const ArchSpec &match_arch =
2220 match_info.GetProcessInfo().GetArchitecture();
2221 const llvm::Triple &triple = match_arch.GetTriple();
2222 packet.PutCString("triple:");
2223 packet.PutCString(triple.getTriple());
2224 packet.PutChar(';');
2227 StringExtractorGDBRemote response;
2228 // Increase timeout as the first qfProcessInfo packet takes a long time on
2229 // Android. The value of 1min was arrived at empirically.
2230 ScopedTimeout timeout(*this, minutes(1));
2231 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2232 PacketResult::Success) {
2234 ProcessInstanceInfo process_info;
2235 if (!DecodeProcessInfoResponse(response, process_info))
2237 process_infos.push_back(process_info);
2238 response = StringExtractorGDBRemote();
2239 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2240 PacketResult::Success);
2242 m_supports_qfProcessInfo = false;
2246 return process_infos.size();
2249 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2250 std::string &name) {
2251 if (m_supports_qUserName) {
2253 const int packet_len =
2254 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2255 assert(packet_len < (int)sizeof(packet));
2256 UNUSED_IF_ASSERT_DISABLED(packet_len);
2257 StringExtractorGDBRemote response;
2258 if (SendPacketAndWaitForResponse(packet, response, false) ==
2259 PacketResult::Success) {
2260 if (response.IsNormalResponse()) {
2261 // Make sure we parsed the right number of characters. The response is
2262 // the hex encoded user name and should make up the entire packet. If
2263 // there are any non-hex ASCII bytes, the length won't match below..
2264 if (response.GetHexByteString(name) * 2 ==
2265 response.GetStringRef().size())
2269 m_supports_qUserName = false;
2276 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2277 std::string &name) {
2278 if (m_supports_qGroupName) {
2280 const int packet_len =
2281 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2282 assert(packet_len < (int)sizeof(packet));
2283 UNUSED_IF_ASSERT_DISABLED(packet_len);
2284 StringExtractorGDBRemote response;
2285 if (SendPacketAndWaitForResponse(packet, response, false) ==
2286 PacketResult::Success) {
2287 if (response.IsNormalResponse()) {
2288 // Make sure we parsed the right number of characters. The response is
2289 // the hex encoded group name and should make up the entire packet. If
2290 // there are any non-hex ASCII bytes, the length won't match below..
2291 if (response.GetHexByteString(name) * 2 ==
2292 response.GetStringRef().size())
2296 m_supports_qGroupName = false;
2303 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2304 // Form non-stop packet request
2306 const int packet_len =
2307 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2308 assert(packet_len < (int)sizeof(packet));
2309 UNUSED_IF_ASSERT_DISABLED(packet_len);
2311 StringExtractorGDBRemote response;
2313 if (SendPacketAndWaitForResponse(packet, response, false) ==
2314 PacketResult::Success)
2315 if (response.IsOKResponse())
2318 // Failed or not supported
2322 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2323 uint32_t recv_size) {
2325 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2326 uint32_t bytes_left = send_size;
2327 while (bytes_left > 0) {
2328 if (bytes_left >= 26) {
2329 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2332 packet.Printf("%*.*s;", bytes_left, bytes_left,
2333 "abcdefghijklmnopqrstuvwxyz");
2340 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2341 using Dur = duration<float>;
2342 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2343 Dur mean = sum / v.size();
2346 float delta = (d - mean).count();
2347 accum += delta * delta;
2350 return Dur(sqrtf(accum / (v.size() - 1)));
2353 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2356 uint64_t recv_amount,
2357 bool json, Stream &strm) {
2359 if (SendSpeedTestPacket(0, 0)) {
2360 StreamString packet;
2362 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2366 strm.Printf("Testing sending %u packets of various sizes:\n",
2370 uint32_t result_idx = 0;
2372 std::vector<duration<float>> packet_times;
2374 for (send_size = 0; send_size <= max_send;
2375 send_size ? send_size *= 2 : send_size = 4) {
2376 for (uint32_t recv_size = 0; recv_size <= max_recv;
2377 recv_size ? recv_size *= 2 : recv_size = 4) {
2378 MakeSpeedTestPacket(packet, send_size, recv_size);
2380 packet_times.clear();
2381 // Test how long it takes to send 'num_packets' packets
2382 const auto start_time = steady_clock::now();
2383 for (i = 0; i < num_packets; ++i) {
2384 const auto packet_start_time = steady_clock::now();
2385 StringExtractorGDBRemote response;
2386 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2387 const auto packet_end_time = steady_clock::now();
2388 packet_times.push_back(packet_end_time - packet_start_time);
2390 const auto end_time = steady_clock::now();
2391 const auto total_time = end_time - start_time;
2393 float packets_per_second =
2394 ((float)num_packets) / duration<float>(total_time).count();
2395 auto average_per_packet = total_time / num_packets;
2396 const duration<float> standard_deviation =
2397 calculate_standard_deviation(packet_times);
2399 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2400 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2401 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2402 result_idx > 0 ? "," : "", send_size, recv_size,
2403 total_time, standard_deviation);
2406 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2407 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2408 "standard deviation of {5,10:ms+f6}\n",
2409 send_size, recv_size, duration<float>(total_time),
2410 packets_per_second, duration<float>(average_per_packet),
2411 standard_deviation);
2417 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2419 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2420 ": %" PRIu64 ",\n \"results\" : [",
2423 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2429 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2430 MakeSpeedTestPacket(packet, send_size, recv_size);
2432 // If we have a receive size, test how long it takes to receive 4MB of
2434 if (recv_size > 0) {
2435 const auto start_time = steady_clock::now();
2436 uint32_t bytes_read = 0;
2437 uint32_t packet_count = 0;
2438 while (bytes_read < recv_amount) {
2439 StringExtractorGDBRemote response;
2440 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2441 bytes_read += recv_size;
2444 const auto end_time = steady_clock::now();
2445 const auto total_time = end_time - start_time;
2446 float mb_second = ((float)recv_amount) /
2447 duration<float>(total_time).count() /
2449 float packets_per_second =
2450 ((float)packet_count) / duration<float>(total_time).count();
2451 const auto average_per_packet = total_time / packet_count;
2454 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2455 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2456 result_idx > 0 ? "," : "", send_size, recv_size,
2460 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2461 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2462 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2463 send_size, recv_size, packet_count, k_recv_amount_mb,
2464 duration<float>(total_time), mb_second,
2465 packets_per_second, duration<float>(average_per_packet));
2471 strm.Printf("\n ]\n }\n}\n");
2477 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2478 uint32_t recv_size) {
2479 StreamString packet;
2480 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2481 uint32_t bytes_left = send_size;
2482 while (bytes_left > 0) {
2483 if (bytes_left >= 26) {
2484 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2487 packet.Printf("%*.*s;", bytes_left, bytes_left,
2488 "abcdefghijklmnopqrstuvwxyz");
2493 StringExtractorGDBRemote response;
2494 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2495 PacketResult::Success;
2498 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2499 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2500 std::string &socket_name) {
2501 pid = LLDB_INVALID_PROCESS_ID;
2503 socket_name.clear();
2505 StringExtractorGDBRemote response;
2506 StreamString stream;
2507 stream.PutCString("qLaunchGDBServer;");
2508 std::string hostname;
2509 if (remote_accept_hostname && remote_accept_hostname[0])
2510 hostname = remote_accept_hostname;
2512 if (HostInfo::GetHostname(hostname)) {
2513 // Make the GDB server we launch only accept connections from this host
2514 stream.Printf("host:%s;", hostname.c_str());
2516 // Make the GDB server we launch accept connections from any host since
2517 // we can't figure out the hostname
2518 stream.Printf("host:*;");
2521 // give the process a few seconds to startup
2522 ScopedTimeout timeout(*this, seconds(10));
2524 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2525 PacketResult::Success) {
2526 llvm::StringRef name;
2527 llvm::StringRef value;
2528 while (response.GetNameColonValue(name, value)) {
2529 if (name.equals("port"))
2530 value.getAsInteger(0, port);
2531 else if (name.equals("pid"))
2532 value.getAsInteger(0, pid);
2533 else if (name.compare("socket_name") == 0) {
2534 StringExtractor extractor(value);
2535 extractor.GetHexByteString(socket_name);
2543 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2544 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2545 connection_urls.clear();
2547 StringExtractorGDBRemote response;
2548 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2549 PacketResult::Success)
2552 StructuredData::ObjectSP data =
2553 StructuredData::ParseJSON(std::string(response.GetStringRef()));
2557 StructuredData::Array *array = data->GetAsArray();
2561 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2562 StructuredData::Dictionary *element = nullptr;
2563 if (!array->GetItemAtIndexAsDictionary(i, element))
2567 if (StructuredData::ObjectSP port_osp =
2568 element->GetValueForKey(llvm::StringRef("port")))
2569 port = port_osp->GetIntegerValue(0);
2571 std::string socket_name;
2572 if (StructuredData::ObjectSP socket_name_osp =
2573 element->GetValueForKey(llvm::StringRef("socket_name")))
2574 socket_name = std::string(socket_name_osp->GetStringValue());
2576 if (port != 0 || !socket_name.empty())
2577 connection_urls.emplace_back(port, socket_name);
2579 return connection_urls.size();
2582 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2583 StreamString stream;
2584 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2586 StringExtractorGDBRemote response;
2587 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2588 PacketResult::Success) {
2589 if (response.IsOKResponse())
2595 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2596 if (m_curr_tid == tid)
2601 if (tid == UINT64_MAX)
2602 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2604 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2605 assert(packet_len + 1 < (int)sizeof(packet));
2606 UNUSED_IF_ASSERT_DISABLED(packet_len);
2607 StringExtractorGDBRemote response;
2608 if (SendPacketAndWaitForResponse(packet, response, false) ==
2609 PacketResult::Success) {
2610 if (response.IsOKResponse()) {
2616 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2618 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2620 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2622 if (response.IsUnsupportedResponse() && IsConnected()) {
2630 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2631 if (m_curr_tid_run == tid)
2636 if (tid == UINT64_MAX)
2637 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2639 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2641 assert(packet_len + 1 < (int)sizeof(packet));
2642 UNUSED_IF_ASSERT_DISABLED(packet_len);
2643 StringExtractorGDBRemote response;
2644 if (SendPacketAndWaitForResponse(packet, response, false) ==
2645 PacketResult::Success) {
2646 if (response.IsOKResponse()) {
2647 m_curr_tid_run = tid;
2652 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2654 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2656 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2658 if (response.IsUnsupportedResponse() && IsConnected()) {
2666 bool GDBRemoteCommunicationClient::GetStopReply(
2667 StringExtractorGDBRemote &response) {
2668 if (SendPacketAndWaitForResponse("?", response, false) ==
2669 PacketResult::Success)
2670 return response.IsNormalResponse();
2674 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2675 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2676 if (m_supports_qThreadStopInfo) {
2679 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2680 assert(packet_len < (int)sizeof(packet));
2681 UNUSED_IF_ASSERT_DISABLED(packet_len);
2682 if (SendPacketAndWaitForResponse(packet, response, false) ==
2683 PacketResult::Success) {
2684 if (response.IsUnsupportedResponse())
2685 m_supports_qThreadStopInfo = false;
2686 else if (response.IsNormalResponse())
2691 m_supports_qThreadStopInfo = false;
2697 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2698 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2699 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2700 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2701 __FUNCTION__, insert ? "add" : "remove", addr);
2703 // Check if the stub is known not to support this breakpoint type
2704 if (!SupportsGDBStoppointPacket(type))
2706 // Construct the breakpoint packet
2708 const int packet_len =
2709 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2710 insert ? 'Z' : 'z', type, addr, length);
2711 // Check we haven't overwritten the end of the packet buffer
2712 assert(packet_len + 1 < (int)sizeof(packet));
2713 UNUSED_IF_ASSERT_DISABLED(packet_len);
2714 StringExtractorGDBRemote response;
2715 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2716 // or "" (unsupported)
2717 response.SetResponseValidatorToOKErrorNotSupported();
2718 // Try to send the breakpoint packet, and check that it was correctly sent
2719 if (SendPacketAndWaitForResponse(packet, response, true) ==
2720 PacketResult::Success) {
2721 // Receive and OK packet when the breakpoint successfully placed
2722 if (response.IsOKResponse())
2725 // Status while setting breakpoint, send back specific error
2726 if (response.IsErrorResponse())
2727 return response.GetError();
2729 // Empty packet informs us that breakpoint is not supported
2730 if (response.IsUnsupportedResponse()) {
2731 // Disable this breakpoint type since it is unsupported
2733 case eBreakpointSoftware:
2734 m_supports_z0 = false;
2736 case eBreakpointHardware:
2737 m_supports_z1 = false;
2739 case eWatchpointWrite:
2740 m_supports_z2 = false;
2742 case eWatchpointRead:
2743 m_supports_z3 = false;
2745 case eWatchpointReadWrite:
2746 m_supports_z4 = false;
2748 case eStoppointInvalid:
2753 // Signal generic failure
2757 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2758 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2761 Lock lock(*this, false);
2763 sequence_mutex_unavailable = false;
2764 StringExtractorGDBRemote response;
2766 PacketResult packet_result;
2767 for (packet_result =
2768 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2769 packet_result == PacketResult::Success && response.IsNormalResponse();
2771 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2772 char ch = response.GetChar();
2777 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2779 if (tid != LLDB_INVALID_THREAD_ID) {
2780 thread_ids.push_back(tid);
2782 ch = response.GetChar(); // Skip the command separator
2783 } while (ch == ','); // Make sure we got a comma separator
2788 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2789 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2791 * be as simple as 'S05'. There is no packet which can give us pid and/or
2793 * Assume pid=tid=1 in such cases.
2795 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2796 thread_ids.size() == 0 && IsConnected()) {
2797 thread_ids.push_back(1);
2800 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2802 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
2803 "packet 'qfThreadInfo'");
2804 sequence_mutex_unavailable = true;
2806 return thread_ids.size();
2809 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2810 StringExtractorGDBRemote response;
2811 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2812 PacketResult::Success ||
2813 !response.IsNormalResponse())
2814 return LLDB_INVALID_ADDRESS;
2815 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2818 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2819 const char *command, // Shouldn't be NULL
2821 working_dir, // Pass empty FileSpec to use the current working directory
2822 int *status_ptr, // Pass NULL if you don't want the process exit status
2823 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2826 *command_output, // Pass NULL if you don't want the command output
2827 const Timeout<std::micro> &timeout) {
2828 lldb_private::StreamString stream;
2829 stream.PutCString("qPlatform_shell:");
2830 stream.PutBytesAsRawHex8(command, strlen(command));
2831 stream.PutChar(',');
2832 uint32_t timeout_sec = UINT32_MAX;
2834 // TODO: Use chrono version of std::ceil once c++17 is available.
2835 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2837 stream.PutHex32(timeout_sec);
2839 std::string path{working_dir.GetPath(false)};
2840 stream.PutChar(',');
2841 stream.PutStringAsRawHex8(path);
2843 StringExtractorGDBRemote response;
2844 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2845 PacketResult::Success) {
2846 if (response.GetChar() != 'F')
2847 return Status("malformed reply");
2848 if (response.GetChar() != ',')
2849 return Status("malformed reply");
2850 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2851 if (exitcode == UINT32_MAX)
2852 return Status("unable to run remote process");
2853 else if (status_ptr)
2854 *status_ptr = exitcode;
2855 if (response.GetChar() != ',')
2856 return Status("malformed reply");
2857 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2860 if (response.GetChar() != ',')
2861 return Status("malformed reply");
2863 response.GetEscapedBinaryData(output);
2865 command_output->assign(output);
2868 return Status("unable to send packet");
2871 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2872 uint32_t file_permissions) {
2873 std::string path{file_spec.GetPath(false)};
2874 lldb_private::StreamString stream;
2875 stream.PutCString("qPlatform_mkdir:");
2876 stream.PutHex32(file_permissions);
2877 stream.PutChar(',');
2878 stream.PutStringAsRawHex8(path);
2879 llvm::StringRef packet = stream.GetString();
2880 StringExtractorGDBRemote response;
2882 if (SendPacketAndWaitForResponse(packet, response, false) !=
2883 PacketResult::Success)
2884 return Status("failed to send '%s' packet", packet.str().c_str());
2886 if (response.GetChar() != 'F')
2887 return Status("invalid response to '%s' packet", packet.str().c_str());
2889 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2893 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2894 uint32_t file_permissions) {
2895 std::string path{file_spec.GetPath(false)};
2896 lldb_private::StreamString stream;
2897 stream.PutCString("qPlatform_chmod:");
2898 stream.PutHex32(file_permissions);
2899 stream.PutChar(',');
2900 stream.PutStringAsRawHex8(path);
2901 llvm::StringRef packet = stream.GetString();
2902 StringExtractorGDBRemote response;
2904 if (SendPacketAndWaitForResponse(packet, response, false) !=
2905 PacketResult::Success)
2906 return Status("failed to send '%s' packet", stream.GetData());
2908 if (response.GetChar() != 'F')
2909 return Status("invalid response to '%s' packet", stream.GetData());
2911 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2914 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2915 uint64_t fail_result, Status &error) {
2916 response.SetFilePos(0);
2917 if (response.GetChar() != 'F')
2919 int32_t result = response.GetS32(-2);
2922 if (response.GetChar() == ',') {
2923 int result_errno = response.GetS32(-2);
2924 if (result_errno != -2)
2925 error.SetError(result_errno, eErrorTypePOSIX);
2927 error.SetError(-1, eErrorTypeGeneric);
2933 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2934 File::OpenOptions flags, mode_t mode,
2936 std::string path(file_spec.GetPath(false));
2937 lldb_private::StreamString stream;
2938 stream.PutCString("vFile:open:");
2941 stream.PutStringAsRawHex8(path);
2942 stream.PutChar(',');
2943 stream.PutHex32(flags);
2944 stream.PutChar(',');
2945 stream.PutHex32(mode);
2946 StringExtractorGDBRemote response;
2947 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2948 PacketResult::Success) {
2949 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2954 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2956 lldb_private::StreamString stream;
2957 stream.Printf("vFile:close:%i", (int)fd);
2958 StringExtractorGDBRemote response;
2959 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2960 PacketResult::Success) {
2961 return ParseHostIOPacketResponse(response, -1, error) == 0;
2966 // Extension of host I/O packets to get the file size.
2967 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2968 const lldb_private::FileSpec &file_spec) {
2969 std::string path(file_spec.GetPath(false));
2970 lldb_private::StreamString stream;
2971 stream.PutCString("vFile:size:");
2972 stream.PutStringAsRawHex8(path);
2973 StringExtractorGDBRemote response;
2974 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2975 PacketResult::Success) {
2976 if (response.GetChar() != 'F')
2978 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2985 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2986 uint32_t &file_permissions) {
2987 std::string path{file_spec.GetPath(false)};
2989 lldb_private::StreamString stream;
2990 stream.PutCString("vFile:mode:");
2991 stream.PutStringAsRawHex8(path);
2992 StringExtractorGDBRemote response;
2993 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2994 PacketResult::Success) {
2995 if (response.GetChar() != 'F') {
2996 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2999 const uint32_t mode = response.GetS32(-1);
3000 if (static_cast<int32_t>(mode) == -1) {
3001 if (response.GetChar() == ',') {
3002 int response_errno = response.GetS32(-1);
3003 if (response_errno > 0)
3004 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3006 error.SetErrorToGenericError();
3008 error.SetErrorToGenericError();
3010 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3014 error.SetErrorStringWithFormat("failed to send '%s' packet",
3020 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
3021 uint64_t offset, void *dst,
3024 lldb_private::StreamString stream;
3025 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
3027 StringExtractorGDBRemote response;
3028 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3029 PacketResult::Success) {
3030 if (response.GetChar() != 'F')
3032 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3033 if (retcode == UINT32_MAX)
3035 const char next = (response.Peek() ? *response.Peek() : 0);
3039 response.GetChar(); // skip the semicolon
3041 if (response.GetEscapedBinaryData(buffer)) {
3042 const uint64_t data_to_write =
3043 std::min<uint64_t>(dst_len, buffer.size());
3044 if (data_to_write > 0)
3045 memcpy(dst, &buffer[0], data_to_write);
3046 return data_to_write;
3053 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3058 lldb_private::StreamGDBRemote stream;
3059 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3060 stream.PutEscapedBytes(src, src_len);
3061 StringExtractorGDBRemote response;
3062 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3063 PacketResult::Success) {
3064 if (response.GetChar() != 'F') {
3065 error.SetErrorStringWithFormat("write file failed");
3068 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3069 if (bytes_written == UINT64_MAX) {
3070 error.SetErrorToGenericError();
3071 if (response.GetChar() == ',') {
3072 int response_errno = response.GetS32(-1);
3073 if (response_errno > 0)
3074 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3078 return bytes_written;
3080 error.SetErrorString("failed to send vFile:pwrite packet");
3085 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3086 const FileSpec &dst) {
3087 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3089 lldb_private::StreamGDBRemote stream;
3090 stream.PutCString("vFile:symlink:");
3091 // the unix symlink() command reverses its parameters where the dst if first,
3092 // so we follow suit here
3093 stream.PutStringAsRawHex8(dst_path);
3094 stream.PutChar(',');
3095 stream.PutStringAsRawHex8(src_path);
3096 StringExtractorGDBRemote response;
3097 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3098 PacketResult::Success) {
3099 if (response.GetChar() == 'F') {
3100 uint32_t result = response.GetU32(UINT32_MAX);
3102 error.SetErrorToGenericError();
3103 if (response.GetChar() == ',') {
3104 int response_errno = response.GetS32(-1);
3105 if (response_errno > 0)
3106 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3110 // Should have returned with 'F<result>[,<errno>]'
3111 error.SetErrorStringWithFormat("symlink failed");
3114 error.SetErrorString("failed to send vFile:symlink packet");
3119 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3120 std::string path{file_spec.GetPath(false)};
3122 lldb_private::StreamGDBRemote stream;
3123 stream.PutCString("vFile:unlink:");
3124 // the unix symlink() command reverses its parameters where the dst if first,
3125 // so we follow suit here
3126 stream.PutStringAsRawHex8(path);
3127 StringExtractorGDBRemote response;
3128 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3129 PacketResult::Success) {
3130 if (response.GetChar() == 'F') {
3131 uint32_t result = response.GetU32(UINT32_MAX);
3133 error.SetErrorToGenericError();
3134 if (response.GetChar() == ',') {
3135 int response_errno = response.GetS32(-1);
3136 if (response_errno > 0)
3137 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3141 // Should have returned with 'F<result>[,<errno>]'
3142 error.SetErrorStringWithFormat("unlink failed");
3145 error.SetErrorString("failed to send vFile:unlink packet");
3150 // Extension of host I/O packets to get whether a file exists.
3151 bool GDBRemoteCommunicationClient::GetFileExists(
3152 const lldb_private::FileSpec &file_spec) {
3153 std::string path(file_spec.GetPath(false));
3154 lldb_private::StreamString stream;
3155 stream.PutCString("vFile:exists:");
3156 stream.PutStringAsRawHex8(path);
3157 StringExtractorGDBRemote response;
3158 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3159 PacketResult::Success) {
3160 if (response.GetChar() != 'F')
3162 if (response.GetChar() != ',')
3164 bool retcode = (response.GetChar() != '0');
3170 bool GDBRemoteCommunicationClient::CalculateMD5(
3171 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3172 std::string path(file_spec.GetPath(false));
3173 lldb_private::StreamString stream;
3174 stream.PutCString("vFile:MD5:");
3175 stream.PutStringAsRawHex8(path);
3176 StringExtractorGDBRemote response;
3177 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3178 PacketResult::Success) {
3179 if (response.GetChar() != 'F')
3181 if (response.GetChar() != ',')
3183 if (response.Peek() && *response.Peek() == 'x')
3185 low = response.GetHexMaxU64(false, UINT64_MAX);
3186 high = response.GetHexMaxU64(false, UINT64_MAX);
3192 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3193 // Some targets have issues with g/G packets and we need to avoid using them
3194 if (m_avoid_g_packets == eLazyBoolCalculate) {
3196 m_avoid_g_packets = eLazyBoolNo;
3197 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3198 if (arch.IsValid() &&
3199 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3200 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3201 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3202 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3203 m_avoid_g_packets = eLazyBoolYes;
3204 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3205 if (gdb_server_version != 0) {
3206 const char *gdb_server_name = GetGDBServerProgramName();
3207 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3208 if (gdb_server_version >= 310)
3209 m_avoid_g_packets = eLazyBoolNo;
3215 return m_avoid_g_packets == eLazyBoolYes;
3218 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3220 StreamString payload;
3221 payload.Printf("p%x", reg);
3222 StringExtractorGDBRemote response;
3223 if (SendThreadSpecificPacketAndWaitForResponse(
3224 tid, std::move(payload), response, false) != PacketResult::Success ||
3225 !response.IsNormalResponse())
3228 DataBufferSP buffer_sp(
3229 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3230 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3234 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3235 StreamString payload;
3236 payload.PutChar('g');
3237 StringExtractorGDBRemote response;
3238 if (SendThreadSpecificPacketAndWaitForResponse(
3239 tid, std::move(payload), response, false) != PacketResult::Success ||
3240 !response.IsNormalResponse())
3243 DataBufferSP buffer_sp(
3244 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3245 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3249 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3251 llvm::ArrayRef<uint8_t> data) {
3252 StreamString payload;
3253 payload.Printf("P%x=", reg_num);
3254 payload.PutBytesAsRawHex8(data.data(), data.size(),
3255 endian::InlHostByteOrder(),
3256 endian::InlHostByteOrder());
3257 StringExtractorGDBRemote response;
3258 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3260 PacketResult::Success &&
3261 response.IsOKResponse();
3264 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3265 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3266 StreamString payload;
3267 payload.PutChar('G');
3268 payload.PutBytesAsRawHex8(data.data(), data.size(),
3269 endian::InlHostByteOrder(),
3270 endian::InlHostByteOrder());
3271 StringExtractorGDBRemote response;
3272 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3274 PacketResult::Success &&
3275 response.IsOKResponse();
3278 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3279 uint32_t &save_id) {
3280 save_id = 0; // Set to invalid save ID
3281 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3284 m_supports_QSaveRegisterState = eLazyBoolYes;
3285 StreamString payload;
3286 payload.PutCString("QSaveRegisterState");
3287 StringExtractorGDBRemote response;
3288 if (SendThreadSpecificPacketAndWaitForResponse(
3289 tid, std::move(payload), response, false) != PacketResult::Success)
3292 if (response.IsUnsupportedResponse())
3293 m_supports_QSaveRegisterState = eLazyBoolNo;
3295 const uint32_t response_save_id = response.GetU32(0);
3296 if (response_save_id == 0)
3299 save_id = response_save_id;
3303 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3305 // We use the "m_supports_QSaveRegisterState" variable here because the
3306 // QSaveRegisterState and QRestoreRegisterState packets must both be
3307 // supported in order to be useful
3308 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3311 StreamString payload;
3312 payload.Printf("QRestoreRegisterState:%u", save_id);
3313 StringExtractorGDBRemote response;
3314 if (SendThreadSpecificPacketAndWaitForResponse(
3315 tid, std::move(payload), response, false) != PacketResult::Success)
3318 if (response.IsOKResponse())
3321 if (response.IsUnsupportedResponse())
3322 m_supports_QSaveRegisterState = eLazyBoolNo;
3326 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3327 if (!GetSyncThreadStateSupported())
3330 StreamString packet;
3331 StringExtractorGDBRemote response;
3332 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3333 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3334 GDBRemoteCommunication::PacketResult::Success &&
3335 response.IsOKResponse();
3339 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3341 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3342 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3344 StreamGDBRemote escaped_packet;
3345 escaped_packet.PutCString("jTraceStart:");
3347 StructuredData::Dictionary json_packet;
3348 json_packet.AddIntegerItem("type", options.getType());
3349 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3350 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3352 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3353 json_packet.AddIntegerItem("threadid", options.getThreadID());
3355 StructuredData::DictionarySP custom_params = options.getTraceParams();
3357 json_packet.AddItem("params", custom_params);
3359 StreamString json_string;
3360 json_packet.Dump(json_string, false);
3361 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3363 StringExtractorGDBRemote response;
3364 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3366 GDBRemoteCommunication::PacketResult::Success) {
3367 if (!response.IsNormalResponse()) {
3368 error = response.GetStatus();
3369 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
3371 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3374 LLDB_LOG(log, "failed to send packet");
3375 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3376 escaped_packet.GetData());
3382 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3383 lldb::tid_t thread_id) {
3384 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3385 StringExtractorGDBRemote response;
3388 StructuredData::Dictionary json_packet;
3389 StreamGDBRemote escaped_packet;
3390 StreamString json_string;
3391 escaped_packet.PutCString("jTraceStop:");
3393 json_packet.AddIntegerItem("traceid", uid);
3395 if (thread_id != LLDB_INVALID_THREAD_ID)
3396 json_packet.AddIntegerItem("threadid", thread_id);
3398 json_packet.Dump(json_string, false);
3400 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3402 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3404 GDBRemoteCommunication::PacketResult::Success) {
3405 if (!response.IsOKResponse()) {
3406 error = response.GetStatus();
3407 LLDB_LOG(log, "stop tracing failed");
3410 LLDB_LOG(log, "failed to send packet");
3411 error.SetErrorStringWithFormat(
3412 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3413 response.GetError());
3418 Status GDBRemoteCommunicationClient::SendGetDataPacket(
3419 lldb::user_id_t uid, lldb::tid_t thread_id,
3420 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3422 StreamGDBRemote escaped_packet;
3423 escaped_packet.PutCString("jTraceBufferRead:");
3424 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3427 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3428 lldb::user_id_t uid, lldb::tid_t thread_id,
3429 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3431 StreamGDBRemote escaped_packet;
3432 escaped_packet.PutCString("jTraceMetaRead:");
3433 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3437 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3438 TraceOptions &options) {
3439 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3440 StringExtractorGDBRemote response;
3443 StreamString json_string;
3444 StreamGDBRemote escaped_packet;
3445 escaped_packet.PutCString("jTraceConfigRead:");
3447 StructuredData::Dictionary json_packet;
3448 json_packet.AddIntegerItem("traceid", uid);
3450 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3451 json_packet.AddIntegerItem("threadid", options.getThreadID());
3453 json_packet.Dump(json_string, false);
3454 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3456 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3458 GDBRemoteCommunication::PacketResult::Success) {
3459 if (response.IsNormalResponse()) {
3460 uint64_t type = std::numeric_limits<uint64_t>::max();
3461 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3462 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3464 auto json_object = StructuredData::ParseJSON(response.Peek());
3467 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
3468 error.SetErrorString("Invalid Configuration obtained");
3472 auto json_dict = json_object->GetAsDictionary();
3474 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3476 options.setMetaDataBufferSize(metabuffersize);
3478 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3479 options.setTraceBufferSize(buffersize);
3481 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3482 options.setType(static_cast<lldb::TraceType>(type));
3484 StructuredData::ObjectSP custom_params_sp =
3485 json_dict->GetValueForKey("params");
3486 if (custom_params_sp) {
3487 if (custom_params_sp->GetType() !=
3488 lldb::eStructuredDataTypeDictionary) {
3489 error.SetErrorString("Invalid Configuration obtained");
3492 options.setTraceParams(
3493 std::static_pointer_cast<StructuredData::Dictionary>(
3497 error = response.GetStatus();
3500 LLDB_LOG(log, "failed to send packet");
3501 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3502 escaped_packet.GetData());
3507 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3508 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3509 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3510 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3513 StructuredData::Dictionary json_packet;
3515 json_packet.AddIntegerItem("traceid", uid);
3516 json_packet.AddIntegerItem("offset", offset);
3517 json_packet.AddIntegerItem("buffersize", buffer.size());
3519 if (thread_id != LLDB_INVALID_THREAD_ID)
3520 json_packet.AddIntegerItem("threadid", thread_id);
3522 StreamString json_string;
3523 json_packet.Dump(json_string, false);
3525 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3526 StringExtractorGDBRemote response;
3527 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3528 GDBRemoteCommunication::PacketResult::Success) {
3529 if (response.IsNormalResponse()) {
3530 size_t filled_size = response.GetHexBytesAvail(buffer);
3531 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3533 error = response.GetStatus();
3534 buffer = buffer.slice(buffer.size());
3537 LLDB_LOG(log, "failed to send packet");
3538 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3540 buffer = buffer.slice(buffer.size());
3545 llvm::Optional<QOffsets> GDBRemoteCommunicationClient::GetQOffsets() {
3546 StringExtractorGDBRemote response;
3547 if (SendPacketAndWaitForResponse(
3548 "qOffsets", response, /*send_async=*/false) != PacketResult::Success)
3550 if (!response.IsNormalResponse())
3554 llvm::StringRef ref = response.GetStringRef();
3555 const auto &GetOffset = [&] {
3557 if (ref.consumeInteger(16, offset))
3559 result.offsets.push_back(offset);
3563 if (ref.consume_front("Text=")) {
3564 result.segments = false;
3567 if (!ref.consume_front(";Data=") || !GetOffset())
3571 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3573 } else if (ref.consume_front("TextSeg=")) {
3574 result.segments = true;
3579 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3585 bool GDBRemoteCommunicationClient::GetModuleInfo(
3586 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3587 ModuleSpec &module_spec) {
3588 if (!m_supports_qModuleInfo)
3591 std::string module_path = module_file_spec.GetPath(false);
3592 if (module_path.empty())
3595 StreamString packet;
3596 packet.PutCString("qModuleInfo:");
3597 packet.PutStringAsRawHex8(module_path);
3598 packet.PutCString(";");
3599 const auto &triple = arch_spec.GetTriple().getTriple();
3600 packet.PutStringAsRawHex8(triple);
3602 StringExtractorGDBRemote response;
3603 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3604 PacketResult::Success)
3607 if (response.IsErrorResponse())
3610 if (response.IsUnsupportedResponse()) {
3611 m_supports_qModuleInfo = false;
3615 llvm::StringRef name;
3616 llvm::StringRef value;
3618 module_spec.Clear();
3619 module_spec.GetFileSpec() = module_file_spec;
3621 while (response.GetNameColonValue(name, value)) {
3622 if (name == "uuid" || name == "md5") {
3623 StringExtractor extractor(value);
3625 extractor.GetHexByteString(uuid);
3626 module_spec.GetUUID().SetFromStringRef(uuid);
3627 } else if (name == "triple") {
3628 StringExtractor extractor(value);
3630 extractor.GetHexByteString(triple);
3631 module_spec.GetArchitecture().SetTriple(triple.c_str());
3632 } else if (name == "file_offset") {
3634 if (!value.getAsInteger(16, ival))
3635 module_spec.SetObjectOffset(ival);
3636 } else if (name == "file_size") {
3638 if (!value.getAsInteger(16, ival))
3639 module_spec.SetObjectSize(ival);
3640 } else if (name == "file_path") {
3641 StringExtractor extractor(value);
3643 extractor.GetHexByteString(path);
3644 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3651 static llvm::Optional<ModuleSpec>
3652 ParseModuleSpec(StructuredData::Dictionary *dict) {
3657 llvm::StringRef string;
3660 if (!dict->GetValueForKeyAsString("uuid", string))
3662 if (!result.GetUUID().SetFromStringRef(string))
3665 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3667 result.SetObjectOffset(integer);
3669 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3671 result.SetObjectSize(integer);
3673 if (!dict->GetValueForKeyAsString("triple", string))
3675 result.GetArchitecture().SetTriple(string);
3677 if (!dict->GetValueForKeyAsString("file_path", string))
3679 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3684 llvm::Optional<std::vector<ModuleSpec>>
3685 GDBRemoteCommunicationClient::GetModulesInfo(
3686 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3687 namespace json = llvm::json;
3689 if (!m_supports_jModulesInfo)
3692 json::Array module_array;
3693 for (const FileSpec &module_file_spec : module_file_specs) {
3694 module_array.push_back(
3695 json::Object{{"file", module_file_spec.GetPath(false)},
3696 {"triple", triple.getTriple()}});
3698 StreamString unescaped_payload;
3699 unescaped_payload.PutCString("jModulesInfo:");
3700 unescaped_payload.AsRawOstream() << std::move(module_array);
3702 StreamGDBRemote payload;
3703 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3704 unescaped_payload.GetSize());
3706 // Increase the timeout for jModulesInfo since this packet can take longer.
3707 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3709 StringExtractorGDBRemote response;
3710 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3711 PacketResult::Success ||
3712 response.IsErrorResponse())
3715 if (response.IsUnsupportedResponse()) {
3716 m_supports_jModulesInfo = false;
3720 StructuredData::ObjectSP response_object_sp =
3721 StructuredData::ParseJSON(std::string(response.GetStringRef()));
3722 if (!response_object_sp)
3725 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3726 if (!response_array)
3729 std::vector<ModuleSpec> result;
3730 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3731 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3732 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3733 result.push_back(*module_spec);
3739 // query the target remote for extended information using the qXfer packet
3741 // example: object='features', annex='target.xml', out=<xml output> return:
3742 // 'true' on success
3743 // 'false' on failure (err set)
3744 bool GDBRemoteCommunicationClient::ReadExtFeature(
3745 const lldb_private::ConstString object,
3746 const lldb_private::ConstString annex, std::string &out,
3747 lldb_private::Status &err) {
3749 std::stringstream output;
3750 StringExtractorGDBRemote chunk;
3752 uint64_t size = GetRemoteMaxPacketSize();
3755 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3759 // loop until all data has been read
3762 // send query extended feature packet
3763 std::stringstream packet;
3764 packet << "qXfer:" << object.AsCString("")
3765 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3766 << "," << std::hex << size;
3768 GDBRemoteCommunication::PacketResult res =
3769 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3771 if (res != GDBRemoteCommunication::PacketResult::Success) {
3772 err.SetErrorString("Error sending $qXfer packet");
3776 const std::string &str = std::string(chunk.GetStringRef());
3777 if (str.length() == 0) {
3778 // should have some data in chunk
3779 err.SetErrorString("Empty response from $qXfer packet");
3783 // check packet code
3792 if (str.length() > 1)
3794 offset += str.length() - 1;
3799 err.SetErrorString("Invalid continuation code from $qXfer packet");
3809 // Notify the target that gdb is prepared to serve symbol lookup requests.
3810 // packet: "qSymbol::"
3812 // OK The target does not need to look up any (more) symbols.
3813 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3815 // LLDB may provide the value by sending another qSymbol
3817 // in the form of"qSymbol:<sym_value>:<sym_name>".
3821 // lldb sends: qSymbol::
3822 // lldb receives: OK
3823 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3825 // need to ask again in this session.
3827 // lldb sends: qSymbol::
3828 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3829 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3830 // lldb receives: OK
3831 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3833 // the address at this time. lldb needs to send qSymbol:: again when it has
3837 // lldb sends: qSymbol::
3838 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3839 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3840 // lldb receives: OK
3841 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3843 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3845 // need any more symbols. lldb does not need to ask again in this session.
3847 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3848 lldb_private::Process *process) {
3849 // Set to true once we've resolved a symbol to an address for the remote
3850 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3851 // any more symbols and we can stop asking.
3852 bool symbol_response_provided = false;
3854 // Is this the initial qSymbol:: packet?
3855 bool first_qsymbol_query = true;
3857 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
3858 Lock lock(*this, false);
3860 StreamString packet;
3861 packet.PutCString("qSymbol::");
3862 StringExtractorGDBRemote response;
3863 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3864 PacketResult::Success) {
3865 if (response.IsOKResponse()) {
3866 if (symbol_response_provided || first_qsymbol_query) {
3867 m_qSymbol_requests_done = true;
3870 // We are done serving symbols requests
3873 first_qsymbol_query = false;
3875 if (response.IsUnsupportedResponse()) {
3876 // qSymbol is not supported by the current GDB server we are
3878 m_supports_qSymbol = false;
3881 llvm::StringRef response_str(response.GetStringRef());
3882 if (response_str.startswith("qSymbol:")) {
3883 response.SetFilePos(strlen("qSymbol:"));
3884 std::string symbol_name;
3885 if (response.GetHexByteString(symbol_name)) {
3886 if (symbol_name.empty())
3889 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3890 lldb_private::SymbolContextList sc_list;
3891 process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3892 ConstString(symbol_name), eSymbolTypeAny, sc_list);
3893 if (!sc_list.IsEmpty()) {
3894 const size_t num_scs = sc_list.GetSize();
3895 for (size_t sc_idx = 0;
3897 symbol_load_addr == LLDB_INVALID_ADDRESS;
3900 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3902 switch (sc.symbol->GetType()) {
3903 case eSymbolTypeInvalid:
3904 case eSymbolTypeAbsolute:
3905 case eSymbolTypeUndefined:
3906 case eSymbolTypeSourceFile:
3907 case eSymbolTypeHeaderFile:
3908 case eSymbolTypeObjectFile:
3909 case eSymbolTypeCommonBlock:
3910 case eSymbolTypeBlock:
3911 case eSymbolTypeLocal:
3912 case eSymbolTypeParam:
3913 case eSymbolTypeVariable:
3914 case eSymbolTypeVariableType:
3915 case eSymbolTypeLineEntry:
3916 case eSymbolTypeLineHeader:
3917 case eSymbolTypeScopeBegin:
3918 case eSymbolTypeScopeEnd:
3919 case eSymbolTypeAdditional:
3920 case eSymbolTypeCompiler:
3921 case eSymbolTypeInstrumentation:
3922 case eSymbolTypeTrampoline:
3925 case eSymbolTypeCode:
3926 case eSymbolTypeResolver:
3927 case eSymbolTypeData:
3928 case eSymbolTypeRuntime:
3929 case eSymbolTypeException:
3930 case eSymbolTypeObjCClass:
3931 case eSymbolTypeObjCMetaClass:
3932 case eSymbolTypeObjCIVar:
3933 case eSymbolTypeReExported:
3935 sc.symbol->GetLoadAddress(&process->GetTarget());
3942 // This is the normal path where our symbol lookup was successful
3943 // and we want to send a packet with the new symbol value and see
3944 // if another lookup needs to be done.
3946 // Change "packet" to contain the requested symbol value and name
3948 packet.PutCString("qSymbol:");
3949 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3950 packet.Printf("%" PRIx64, symbol_load_addr);
3951 symbol_response_provided = true;
3953 symbol_response_provided = false;
3955 packet.PutCString(":");
3956 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3957 continue; // go back to the while loop and send "packet" and wait
3958 // for another response
3963 // If we make it here, the symbol request packet response wasn't valid or
3964 // our symbol lookup failed so we must abort
3967 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3968 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3970 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3976 StructuredData::Array *
3977 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3978 if (!m_supported_async_json_packets_is_valid) {
3979 // Query the server for the array of supported asynchronous JSON packets.
3980 m_supported_async_json_packets_is_valid = true;
3982 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3985 StringExtractorGDBRemote response;
3986 const bool send_async = false;
3987 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3988 send_async) == PacketResult::Success) {
3989 m_supported_async_json_packets_sp =
3990 StructuredData::ParseJSON(std::string(response.GetStringRef()));
3991 if (m_supported_async_json_packets_sp &&
3992 !m_supported_async_json_packets_sp->GetAsArray()) {
3993 // We were returned something other than a JSON array. This is
3994 // invalid. Clear it out.
3996 "GDBRemoteCommunicationClient::%s(): "
3997 "QSupportedAsyncJSONPackets returned invalid "
3999 __FUNCTION__, response.GetStringRef().data());
4000 m_supported_async_json_packets_sp.reset();
4004 "GDBRemoteCommunicationClient::%s(): "
4005 "QSupportedAsyncJSONPackets unsupported",
4009 if (log && m_supported_async_json_packets_sp) {
4010 StreamString stream;
4011 m_supported_async_json_packets_sp->Dump(stream);
4013 "GDBRemoteCommunicationClient::%s(): supported async "
4015 __FUNCTION__, stream.GetData());
4019 return m_supported_async_json_packets_sp
4020 ? m_supported_async_json_packets_sp->GetAsArray()
4024 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
4025 llvm::ArrayRef<int32_t> signals) {
4027 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4028 auto range = llvm::make_range(signals.begin(), signals.end());
4029 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4031 StringExtractorGDBRemote response;
4032 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
4034 if (send_status != GDBRemoteCommunication::PacketResult::Success)
4035 return Status("Sending QPassSignals packet failed");
4037 if (response.IsOKResponse()) {
4040 return Status("Unknown error happened during sending QPassSignals packet.");
4044 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
4045 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4048 if (type_name.GetLength() == 0) {
4049 error.SetErrorString("invalid type_name argument");
4053 // Build command: Configure{type_name}: serialized config data.
4054 StreamGDBRemote stream;
4055 stream.PutCString("QConfigure");
4056 stream.PutCString(type_name.GetStringRef());
4057 stream.PutChar(':');
4059 // Gather the plain-text version of the configuration data.
4060 StreamString unescaped_stream;
4061 config_sp->Dump(unescaped_stream);
4062 unescaped_stream.Flush();
4064 // Add it to the stream in escaped fashion.
4065 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4066 unescaped_stream.GetSize());
4071 const bool send_async = false;
4072 StringExtractorGDBRemote response;
4074 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
4075 if (result == PacketResult::Success) {
4076 // We failed if the config result comes back other than OK.
4077 if (strcmp(response.GetStringRef().data(), "OK") == 0) {
4081 error.SetErrorStringWithFormat("configuring StructuredData feature "
4082 "%s failed with error %s",
4083 type_name.AsCString(),
4084 response.GetStringRef().data());
4087 // Can we get more data here on the failure?
4088 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4089 "failed when sending packet: "
4091 type_name.AsCString(), (int)result);
4096 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4097 GDBRemoteClientBase::OnRunPacketSent(first);
4098 m_curr_tid = LLDB_INVALID_THREAD_ID;