LLDB mainline
GDBRemoteCommunicationClient.cpp
Go to the documentation of this file.
1//===-- GDBRemoteCommunicationClient.cpp ----------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <cmath>
12#include <sys/stat.h>
13
14#include <numeric>
15#include <optional>
16#include <sstream>
17
18#include "lldb/Core/Module.h"
20#include "lldb/Host/HostInfo.h"
21#include "lldb/Host/SafeMachO.h"
22#include "lldb/Host/XML.h"
23#include "lldb/Symbol/Symbol.h"
25#include "lldb/Target/Target.h"
28#include "lldb/Utility/Args.h"
32#include "lldb/Utility/Log.h"
33#include "lldb/Utility/State.h"
35
36#include "ProcessGDBRemote.h"
37#include "ProcessGDBRemoteLog.h"
38#include "lldb/Host/Config.h"
40
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
43#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
44#include "llvm/Support/ErrorExtras.h"
45#include "llvm/Support/JSON.h"
46#include "llvm/TargetParser/Triple.h"
47
48#if HAVE_LIBCOMPRESSION
49#include <compression.h>
50#endif
51
52using namespace lldb;
54using namespace lldb_private;
55using namespace std::chrono;
56
57llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os,
58 const QOffsets &offsets) {
59 return os << llvm::formatv(
60 "QOffsets({0}, [{1:@[x]}])", offsets.segments,
61 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end()));
62}
63
64// GDBRemoteCommunicationClient constructor
83
84// Destructor
89
92
93 // Start the read thread after we send the handshake ack since if we fail to
94 // send the handshake ack, there is no reason to continue...
95 std::chrono::steady_clock::time_point start_of_handshake =
96 std::chrono::steady_clock::now();
97 if (SendAck()) {
98 // The return value from QueryNoAckModeSupported() is true if the packet
99 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
100 // false if no response was received. This quickly tells us if we have a
101 // live connection to a remote GDB server...
103 return true;
104 } else {
105 std::chrono::steady_clock::time_point end_of_handshake =
106 std::chrono::steady_clock::now();
107 auto handshake_timeout =
108 std::chrono::duration<double>(end_of_handshake - start_of_handshake)
109 .count();
110 if (error_ptr) {
111 if (!IsConnected())
112 *error_ptr =
113 Status::FromErrorString("Connection shut down by remote side "
114 "while waiting for reply to initial "
115 "handshake packet");
116 else
118 "failed to get reply to handshake packet within timeout of "
119 "%.1f seconds",
120 handshake_timeout);
121 }
122 }
123 } else {
124 if (error_ptr)
125 *error_ptr = Status::FromErrorString("failed to send the handshake ack");
126 }
127 return false;
128}
129
136
143
150
157
164
171
178
185
192
198
205
211
217
223
229
235
241
242llvm::Expected<std::vector<AcceleratorActions>>
244 // Get the initial actions (e.g. breakpoints to set) requested by any
245 // accelerator plugins using the "jAcceleratorPluginInitialize" packet. This
246 // is sent once when a native process is launched or attached. The empty
247 // state (no plugins / no actions) is modelled as an empty vector; errors are
248 // returned to the caller to report.
250 return std::vector<AcceleratorActions>();
251
254 if (SendPacketAndWaitForResponse("jAcceleratorPluginInitialize", response) !=
256 return llvm::createStringError(
257 "failed to send jAcceleratorPluginInitialize packet");
258
259 if (response.IsUnsupportedResponse())
260 return std::vector<AcceleratorActions>();
261
262 if (response.IsErrorResponse())
263 return response.GetStatus().takeError();
264
265 llvm::Expected<std::vector<AcceleratorActions>> actions =
266 llvm::json::parse<std::vector<AcceleratorActions>>(response.Peek(),
267 "AcceleratorActions");
268 if (actions)
269 return actions;
270
271 // A bare JSON parse error (e.g. "missing comma at line 4") is meaningless on
272 // its own, so include both the full response and the parse error; the caller
273 // logs this and the user can spot the problem in the response.
274 return llvm::createStringErrorV(
275 "malformed jAcceleratorPluginInitialize response '{0}': {1}",
276 response.GetStringRef(), llvm::toString(actions.takeError()));
277}
278
283 return std::nullopt;
284 if (m_lldb_settings)
285 return m_lldb_settings;
286
289 if (SendPacketAndWaitForResponse("jLLDBSettings", response) !=
291 return std::nullopt;
292
293 if (response.IsUnsupportedResponse()) {
295 return std::nullopt;
296 }
297 if (response.IsErrorResponse())
298 return std::nullopt;
299
300 llvm::Expected<LLDBSettings> settings =
301 llvm::json::parse<LLDBSettings>(response.Peek(), "LLDBSettings");
302 if (!settings) {
304 LLDB_LOG_ERROR(log, settings.takeError(),
305 "malformed jLLDBSettings response '{1}': {0}",
306 response.GetStringRef());
307 return std::nullopt;
308 }
309
310 m_lldb_settings = std::move(*settings);
311 return m_lldb_settings;
312}
313
314llvm::Expected<AcceleratorBreakpointHitResponse>
316 const AcceleratorBreakpointHitArgs &args) {
317 StreamGDBRemote packet;
318 packet.PutCString("jAcceleratorPluginBreakpointHit:");
319 packet.PutAsJSON(args, /*hex_ascii=*/false);
320
322 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
324 return llvm::createStringError(
325 "failed to send jAcceleratorPluginBreakpointHit packet");
326
327 if (response.IsErrorResponse())
328 return response.GetStatus().takeError();
329
330 llvm::Expected<AcceleratorBreakpointHitResponse> hit_response =
331 llvm::json::parse<AcceleratorBreakpointHitResponse>(
332 response.Peek(), "AcceleratorBreakpointHitResponse");
333 if (hit_response)
334 return hit_response;
335
336 // A bare JSON parse error (e.g. "missing comma at line 4") is meaningless on
337 // its own, so include both the full response and the parse error; the caller
338 // logs this and the user can spot the problem in the response.
339 return llvm::createStringErrorV(
340 "malformed jAcceleratorPluginBreakpointHit response '{0}': {1}",
341 response.GetStringRef(), llvm::toString(hit_response.takeError()));
342}
343
344std::optional<AcceleratorDynamicLoaderResponse>
346 const AcceleratorDynamicLoaderArgs &args) {
347 StreamGDBRemote packet;
348 packet.PutCString("jAcceleratorPluginGetDynamicLoaderLibraryInfo:");
349 packet.PutAsJSON(args, /*hex_ascii=*/false);
350
353 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
355 response.IsErrorResponse())
356 return std::nullopt;
357
358 llvm::Expected<AcceleratorDynamicLoaderResponse> parsed =
359 llvm::json::parse<AcceleratorDynamicLoaderResponse>(
360 response.Peek(), "AcceleratorDynamicLoaderResponse");
361 if (!parsed) {
362 llvm::consumeError(parsed.takeError());
363 return std::nullopt;
364 }
365 return *parsed;
366}
367
370 m_send_acks = true;
372
373 // This is the first real packet that we'll send in a debug session and it
374 // may take a little longer than normal to receive a reply. Wait at least
375 // 6 seconds for a reply to this packet.
376
377 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
378
380 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) ==
382 if (response.IsOKResponse()) {
383 m_send_acks = false;
385 }
386 return true;
387 }
388 }
389 return false;
390}
391
404
418
432
434 if (!did_exec) {
435 // Hard reset everything, this is when we first connect to a GDB server
464 m_x_packet_state.reset();
474 m_supports_z0 = true;
475 m_supports_z1 = true;
476 m_supports_z2 = true;
477 m_supports_z3 = true;
478 m_supports_z4 = true;
481 m_supports_qSymbol = true;
484 m_host_arch.Clear();
486 m_os_version = llvm::VersionTuple();
487 m_os_build.clear();
488 m_os_kernel.clear();
489 m_hostname.clear();
490 m_gdb_server_name.clear();
492 m_default_packet_timeout = seconds(0);
495 m_qSupported_response.clear();
502 }
503
504 // These flags should be reset when we first connect to a GDB server and when
505 // our inferior process execs
507 m_process_arch.Clear();
508 m_lldb_settings.reset();
509}
510
512 // Clear out any capabilities we expect to see in the qSupported response
527 m_x_packet_state.reset();
535
536 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
537 // not, we assume no limit
538
539 // build the qSupported packet
540 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc",
541 "multiprocess+",
542 "fork-events+",
543 "vfork-events+",
544 "swbreak+",
545 "hwbreak+",
546 "qXfer:libraries:read+",
547 "qXfer:libraries-svr4:read+"};
548 StreamString packet;
549 packet.PutCString("qSupported");
550 for (uint32_t i = 0; i < features.size(); ++i) {
551 packet.PutCString(i == 0 ? ":" : ";");
552 packet.PutCString(features[i]);
553 }
554
556 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
558 // Hang on to the qSupported packet, so that platforms can do custom
559 // configuration of the transport before attaching/launching the process.
560 m_qSupported_response = response.GetStringRef().str();
561
562 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) {
563 if (x == "qXfer:auxv:read+")
565 else if (x == "qXfer:libraries-svr4:read+")
567 else if (x == "augmented-libraries-svr4-read") {
570 } else if (x == "qXfer:libraries:read+")
572 else if (x == "qXfer:features:read+")
574 else if (x == "qXfer:memory-map:read+")
576 else if (x == "qXfer:siginfo:read+")
578 else if (x == "qEcho+")
580 else if (x == "QPassSignals+")
582 else if (x == "multiprocess+")
584 else if (x == "memory-tagging+")
586 else if (x == "qSaveCore+")
588 else if (x == "address-spaces+")
590 else if (x == "native-signals+")
592 else if (x == "binary-upload+")
594 else if (x == "ReverseContinue+")
596 else if (x == "ReverseStep+")
598 else if (x == "MultiMemRead+")
600 else if (x == "jMultiBreakpoint+")
602 else if (x == "accelerator-plugins+")
604 else if (x == "lldb-settings+")
606 else if (x == "qWasmInstance+")
608 // Look for a list of compressions in the features list e.g.
609 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
610 // deflate,lzma
611 else if (x.consume_front("SupportedCompressions=")) {
612 llvm::SmallVector<llvm::StringRef, 4> compressions;
613 x.split(compressions, ',');
614 if (!compressions.empty())
615 MaybeEnableCompression(compressions);
616 } else if (x.consume_front("SupportedWatchpointTypes=")) {
617 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types;
618 x.split(watchpoint_types, ',');
619 m_watchpoint_types = eWatchpointHardwareFeatureUnknown;
620 for (auto wp_type : watchpoint_types) {
621 if (wp_type == "x86_64")
622 m_watchpoint_types |= eWatchpointHardwareX86;
623 if (wp_type == "aarch64-mask")
624 m_watchpoint_types |= eWatchpointHardwareArmMASK;
625 if (wp_type == "aarch64-bas")
626 m_watchpoint_types |= eWatchpointHardwareArmBAS;
627 }
628 } else if (x.consume_front("PacketSize=")) {
629 StringExtractorGDBRemote packet_response(x);
631 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
632 if (m_max_packet_size == 0) {
633 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
635 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
636 }
637 }
638 }
639 }
640}
641
654
656 assert(!flavor.empty());
665 if (SendPacketAndWaitForResponse("vCont?", response) ==
667 for (llvm::StringRef token : llvm::split(response.GetStringRef(), ';')) {
668 if (token == "c")
670 if (token == "C")
672 if (token == "s")
674 if (token == "S")
676 }
677
683 }
684
690 }
691 }
692 }
693
694 return llvm::StringSwitch<bool>(flavor)
695 .Case("a", m_supports_vCont_any)
696 .Case("A", m_supports_vCont_all)
697 .Case("c", m_supports_vCont_c)
698 .Case("C", m_supports_vCont_C)
699 .Case("s", m_supports_vCont_s)
700 .Case("S", m_supports_vCont_S)
701 .Default(false);
702}
703
706 lldb::tid_t tid, StreamString &&payload,
707 StringExtractorGDBRemote &response) {
708 Lock lock(*this);
709 if (!lock) {
711 LLDB_LOGF(log,
712 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
713 "for %s packet.",
714 __FUNCTION__, payload.GetData());
716 }
717
719 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
720 else {
721 if (!SetCurrentThread(tid))
723 }
724
725 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
726}
727
728// Check if the target supports 'p' packet. It sends out a 'p' packet and
729// checks the response. A normal packet will tell us that support is available.
730//
731// Takes a valid thread ID because p needs to apply to a thread.
737
739 lldb::tid_t tid, llvm::StringRef packetStr) {
740 StreamString payload;
741 payload.PutCString(packetStr);
744 tid, std::move(payload), response) == PacketResult::Success &&
745 response.IsNormalResponse()) {
746 return eLazyBoolYes;
747 }
748 return eLazyBoolNo;
749}
750
754
756 // Get information on all threads at one using the "jThreadsInfo" packet
757 StructuredData::ObjectSP object_sp;
758
762 if (SendPacketAndWaitForResponse("jThreadsInfo", response) ==
764 if (response.IsUnsupportedResponse()) {
766 } else if (!response.Empty()) {
767 object_sp = StructuredData::ParseJSON(response.GetStringRef());
768 }
769 }
770 }
771 return object_sp;
772}
773
787
791 // We try to enable error strings in remote packets but if we fail, we just
792 // work in the older way.
794 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) ==
796 if (response.IsOKResponse()) {
798 }
799 }
800 }
801}
802
816
830
843
850
852 size_t len,
853 int32_t type) {
854 StreamString packet;
855 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type);
857
858 Log *log = GetLog(GDBRLog::Memory);
859
860 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
862 !response.IsNormalResponse()) {
863 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed",
864 __FUNCTION__);
865 return nullptr;
866 }
867
868 // We are expecting
869 // m<hex encoded bytes>
870
871 if (response.GetChar() != 'm') {
872 LLDB_LOGF(log,
873 "GDBRemoteCommunicationClient::%s: qMemTags response did not "
874 "begin with \"m\"",
875 __FUNCTION__);
876 return nullptr;
877 }
878
879 size_t expected_bytes = response.GetBytesLeft() / 2;
880 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0));
881 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData());
882 // Check both because in some situations chars are consumed even
883 // if the decoding fails.
884 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) {
885 LLDB_LOGF(
886 log,
887 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response",
888 __FUNCTION__);
889 return nullptr;
890 }
891
892 return buffer_sp;
893}
894
896 lldb::addr_t addr, size_t len, int32_t type,
897 const std::vector<uint8_t> &tags) {
898 // Format QMemTags:address,length:type:tags
899 StreamString packet;
900 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type);
901 packet.PutBytesAsRawHex8(tags.data(), tags.size());
902
903 Status status;
905 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
907 !response.IsOKResponse()) {
908 status = Status::FromErrorString("QMemTags packet failed");
909 }
910 return status;
911}
912
928
930 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
931 return m_curr_pid;
932
933 // First try to retrieve the pid via the qProcessInfo request.
934 GetCurrentProcessInfo(allow_lazy);
936 // We really got it.
937 return m_curr_pid;
938 } else {
939 // If we don't get a response for qProcessInfo, check if $qC gives us a
940 // result. $qC only returns a real process id on older debugserver and
941 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
942 // the thread id, which newer debugserver and lldb-gdbserver stubs return
943 // correctly.
946 if (response.GetChar() == 'Q') {
947 if (response.GetChar() == 'C') {
949 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID);
952 return m_curr_pid;
953 }
954 }
955 }
956 }
957
958 // If we don't get a response for $qC, check if $qfThreadID gives us a
959 // result.
961 bool sequence_mutex_unavailable;
962 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
963 if (!ids.empty() && !sequence_mutex_unavailable) {
964 // If server returned an explicit PID, use that.
965 m_curr_pid_run = m_curr_pid = ids.front().first;
966 // Otherwise, use the TID of the first thread (Linux hack).
968 m_curr_pid_run = m_curr_pid = ids.front().second;
970 return m_curr_pid;
971 }
972 }
973 }
974
976}
977
978llvm::Expected<StringExtractorGDBRemote>
980 if (!args.GetArgumentAtIndex(0))
981 return llvm::createStringError(llvm::inconvertibleErrorCode(),
982 "Nothing to launch");
983
985
986 // try vRun first
987 if (m_supports_vRun) {
988 StreamString packet;
989 packet.PutCString("vRun");
990 for (const Args::ArgEntry &arg : args) {
991 packet.PutChar(';');
992 packet.PutStringAsRawHex8(arg.ref());
993 }
994
995 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
997 return llvm::createStringError(llvm::inconvertibleErrorCode(),
998 "Sending vRun packet failed");
999
1000 if (response.IsErrorResponse())
1001 return response.GetStatus().ToError();
1002
1003 if (!response.IsUnsupportedResponse())
1004 return response;
1005
1006 m_supports_vRun = false;
1007 }
1008
1009 // fallback to A
1010 StreamString packet;
1011 packet.PutChar('A');
1012 llvm::ListSeparator LS(",");
1013 for (const auto &arg : llvm::enumerate(args)) {
1014 packet << LS;
1015 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index());
1016 packet.PutStringAsRawHex8(arg.value().ref());
1017 }
1018
1019 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1021 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1022 "Sending A packet failed");
1023 }
1024 if (!response.IsOKResponse())
1025 return response.GetStatus().ToError();
1026
1027 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
1029 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1030 "Sending qLaunchSuccess packet failed");
1031 }
1032 if (response.IsOKResponse())
1033 return response;
1034 if (response.GetChar() == 'E') {
1035 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1036 response.GetStringRef().substr(1));
1037 }
1038 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1039 "unknown error occurred launching process");
1040}
1041
1043 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
1044 for (const auto &kv : env)
1045 vec.emplace_back(kv.first(), kv.second);
1046 llvm::sort(vec, llvm::less_first());
1047 for (const auto &[k, v] : vec) {
1048 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
1049 if (r != 0)
1050 return r;
1051 }
1052 return 0;
1053}
1054
1056 char const *name_equal_value) {
1057 if (name_equal_value && name_equal_value[0]) {
1058 bool send_hex_encoding = false;
1059 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
1060 ++p) {
1061 if (llvm::isPrint(*p)) {
1062 switch (*p) {
1063 case '$':
1064 case '#':
1065 case '*':
1066 case '}':
1067 send_hex_encoding = true;
1068 break;
1069 default:
1070 break;
1071 }
1072 } else {
1073 // We have non printable characters, lets hex encode this...
1074 send_hex_encoding = true;
1075 }
1076 }
1077
1078 StringExtractorGDBRemote response;
1079 // Prefer sending unencoded, if possible and the server supports it.
1080 if (!send_hex_encoding && m_supports_QEnvironment) {
1081 StreamString packet;
1082 packet.Printf("QEnvironment:%s", name_equal_value);
1083 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1085 return -1;
1086
1087 if (response.IsOKResponse())
1088 return 0;
1089 if (response.IsUnsupportedResponse())
1091 else {
1092 uint8_t error = response.GetError();
1093 if (error)
1094 return error;
1095 return -1;
1096 }
1097 }
1098
1100 StreamString packet;
1101 packet.PutCString("QEnvironmentHexEncoded:");
1102 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
1103 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1105 return -1;
1106
1107 if (response.IsOKResponse())
1108 return 0;
1109 if (response.IsUnsupportedResponse())
1111 else {
1112 uint8_t error = response.GetError();
1113 if (error)
1114 return error;
1115 return -1;
1116 }
1117 }
1118 }
1119 return -1;
1120}
1121
1123 if (arch && arch[0]) {
1124 StreamString packet;
1125 packet.Printf("QLaunchArch:%s", arch);
1126 StringExtractorGDBRemote response;
1127 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1129 if (response.IsOKResponse())
1130 return 0;
1131 uint8_t error = response.GetError();
1132 if (error)
1133 return error;
1134 }
1135 }
1136 return -1;
1137}
1138
1140 char const *data, bool *was_supported) {
1141 if (data && *data != '\0') {
1142 StreamString packet;
1143 packet.Printf("QSetProcessEvent:%s", data);
1144 StringExtractorGDBRemote response;
1145 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1147 if (response.IsOKResponse()) {
1148 if (was_supported)
1149 *was_supported = true;
1150 return 0;
1151 } else if (response.IsUnsupportedResponse()) {
1152 if (was_supported)
1153 *was_supported = false;
1154 return -1;
1155 } else {
1156 uint8_t error = response.GetError();
1157 if (was_supported)
1158 *was_supported = true;
1159 if (error)
1160 return error;
1161 }
1162 }
1163 }
1164 return -1;
1165}
1166
1168 GetHostInfo();
1169 return m_os_version;
1170}
1171
1176
1178 if (GetHostInfo()) {
1179 if (!m_os_build.empty())
1180 return m_os_build;
1181 }
1182 return std::nullopt;
1183}
1184
1185std::optional<std::string>
1187 if (GetHostInfo()) {
1188 if (!m_os_kernel.empty())
1189 return m_os_kernel;
1190 }
1191 return std::nullopt;
1192}
1193
1195 if (GetHostInfo()) {
1196 if (!m_hostname.empty()) {
1197 s = m_hostname;
1198 return true;
1199 }
1200 }
1201 s.clear();
1202 return false;
1203}
1204
1210
1217
1219 UUID &uuid, addr_t &value, bool &value_is_offset) {
1222
1223 // Return true if we have a UUID or an address/offset of the
1224 // main standalone / firmware binary being used.
1225 if (!m_process_standalone_uuid.IsValid() &&
1227 return false;
1228
1231 value_is_offset = m_process_standalone_value_is_offset;
1232 return true;
1233}
1234
1235std::vector<addr_t>
1241
1242std::vector<AddressSpaceInfo> GDBRemoteCommunicationClient::GetAddressSpaces() {
1244 return {};
1245
1246 StringExtractorGDBRemote response;
1247 response.SetResponseValidatorToJSON();
1248 if (SendPacketAndWaitForResponse("jAddressSpacesInfo", response) !=
1250 return {};
1251
1252 if (response.IsUnsupportedResponse() || response.IsErrorResponse()) {
1254 return {};
1255 }
1256
1257 llvm::Expected<std::vector<AddressSpaceInfo>> info =
1258 llvm::json::parse<std::vector<AddressSpaceInfo>>(response.Peek(),
1259 "AddressSpaceInfo");
1260 if (info)
1261 return std::move(*info);
1262
1263 Log *log = GetLog(GDBRLog::Process);
1264 LLDB_LOG_ERROR(log, info.takeError(),
1265 "malformed jAddressSpacesInfo response '{1}': {0}",
1266 response.GetStringRef());
1267 return {};
1268}
1269
1272 m_gdb_server_name.clear();
1275
1276 StringExtractorGDBRemote response;
1277 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1279 if (response.IsNormalResponse()) {
1280 llvm::StringRef name, value;
1281 bool success = false;
1282 while (response.GetNameColonValue(name, value)) {
1283 if (name == "name") {
1284 success = true;
1285 m_gdb_server_name = std::string(value);
1286 } else if (name == "version") {
1287 llvm::StringRef major, minor;
1288 std::tie(major, minor) = value.split('.');
1289 if (!major.getAsInteger(BASE_10, m_gdb_server_version))
1290 success = true;
1291 }
1292 }
1293 if (success)
1295 }
1296 }
1297 }
1299}
1300
1302 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1304 llvm::StringRef avail_name;
1305
1306#if HAVE_LIBCOMPRESSION
1307 if (avail_type == CompressionType::None) {
1308 for (auto compression : supported_compressions) {
1309 if (compression == "lzfse") {
1310 avail_type = CompressionType::LZFSE;
1311 avail_name = compression;
1312 break;
1313 }
1314 }
1315 }
1316 if (avail_type == CompressionType::None) {
1317 for (auto compression : supported_compressions) {
1318 if (compression == "zlib-deflate") {
1319 avail_type = CompressionType::ZlibDeflate;
1320 avail_name = compression;
1321 break;
1322 }
1323 }
1324 }
1325#endif
1326
1327#if LLVM_ENABLE_ZLIB
1328 if (avail_type == CompressionType::None) {
1329 for (auto compression : supported_compressions) {
1330 if (compression == "zlib-deflate") {
1331 avail_type = CompressionType::ZlibDeflate;
1332 avail_name = compression;
1333 break;
1334 }
1335 }
1336 }
1337#endif
1338
1339#if HAVE_LIBCOMPRESSION
1340 if (avail_type == CompressionType::None) {
1341 for (auto compression : supported_compressions) {
1342 if (compression == "lz4") {
1343 avail_type = CompressionType::LZ4;
1344 avail_name = compression;
1345 break;
1346 }
1347 }
1348 }
1349 if (avail_type == CompressionType::None) {
1350 for (auto compression : supported_compressions) {
1351 if (compression == "lzma") {
1352 avail_type = CompressionType::LZMA;
1353 avail_name = compression;
1354 break;
1355 }
1356 }
1357 }
1358#endif
1359
1360 if (avail_type != CompressionType::None) {
1361 StringExtractorGDBRemote response;
1362 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1363 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1364 return;
1365
1366 if (response.IsOKResponse()) {
1367 m_compression_type = avail_type;
1368 }
1369 }
1370}
1371
1373 if (GetGDBServerVersion()) {
1374 if (!m_gdb_server_name.empty())
1375 return m_gdb_server_name.c_str();
1376 }
1377 return nullptr;
1378}
1379
1385
1387 StringExtractorGDBRemote response;
1389 return false;
1390
1391 if (!response.IsNormalResponse())
1392 return false;
1393
1394 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1395 auto pid_tid = response.GetPidTid(0);
1396 if (!pid_tid)
1397 return false;
1398
1399 lldb::pid_t pid = pid_tid->first;
1400 // invalid
1402 return false;
1403
1404 // if we get pid as well, update m_curr_pid
1405 if (pid != 0) {
1406 m_curr_pid_run = m_curr_pid = pid;
1408 }
1409 tid = pid_tid->second;
1410 }
1411
1412 return true;
1413}
1414
1415static void ParseOSType(llvm::StringRef value, std::string &os_name,
1416 std::string &environment) {
1417 if (value == "iossimulator" || value == "tvossimulator" ||
1418 value == "watchossimulator" || value == "xrossimulator" ||
1419 value == "visionossimulator") {
1420 environment = "simulator";
1421 os_name = value.drop_back(environment.size()).str();
1422 } else if (value == "maccatalyst") {
1423 os_name = "ios";
1424 environment = "macabi";
1425 } else {
1426 os_name = value.str();
1427 }
1428}
1429
1431 Log *log = GetLog(GDBRLog::Process);
1432
1433 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1434 // host info computation can require DNS traffic and shelling out to external processes.
1435 // Increase the timeout to account for that.
1436 ScopedTimeout timeout(*this, seconds(10));
1438 StringExtractorGDBRemote response;
1439 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1441 if (response.IsNormalResponse()) {
1442 llvm::StringRef name;
1443 llvm::StringRef value;
1444 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1445 uint32_t sub = 0;
1446 std::string arch_name;
1447 std::string os_name;
1448 std::string environment;
1449 std::string vendor_name;
1450 std::string triple;
1451 uint32_t pointer_byte_size = 0;
1452 ByteOrder byte_order = eByteOrderInvalid;
1453 uint32_t num_keys_decoded = 0;
1454 while (response.GetNameColonValue(name, value)) {
1455 if (name == "cputype") {
1456 // exception type in big endian hex
1457 if (!value.getAsInteger(BASE_10, cpu))
1458 ++num_keys_decoded;
1459 } else if (name == "cpusubtype") {
1460 // exception count in big endian hex
1461 if (!value.getAsInteger(BASE_10, sub))
1462 ++num_keys_decoded;
1463 } else if (name == "arch") {
1464 arch_name = std::string(value);
1465 ++num_keys_decoded;
1466 } else if (name == "triple") {
1467 StringExtractor extractor(value);
1468 extractor.GetHexByteString(triple);
1469 ++num_keys_decoded;
1470 } else if (name == "distribution_id") {
1471 StringExtractor extractor(value);
1473 ++num_keys_decoded;
1474 } else if (name == "os_build") {
1475 StringExtractor extractor(value);
1476 extractor.GetHexByteString(m_os_build);
1477 ++num_keys_decoded;
1478 } else if (name == "hostname") {
1479 StringExtractor extractor(value);
1480 extractor.GetHexByteString(m_hostname);
1481 ++num_keys_decoded;
1482 } else if (name == "os_kernel") {
1483 StringExtractor extractor(value);
1484 extractor.GetHexByteString(m_os_kernel);
1485 ++num_keys_decoded;
1486 } else if (name == "ostype") {
1487 ParseOSType(value, os_name, environment);
1488 ++num_keys_decoded;
1489 } else if (name == "vendor") {
1490 vendor_name = std::string(value);
1491 ++num_keys_decoded;
1492 } else if (name == "endian") {
1493 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1494 .Case("little", eByteOrderLittle)
1495 .Case("big", eByteOrderBig)
1496 .Case("pdp", eByteOrderPDP)
1497 .Default(eByteOrderInvalid);
1498 if (byte_order != eByteOrderInvalid)
1499 ++num_keys_decoded;
1500 } else if (name == "ptrsize") {
1501 if (!value.getAsInteger(BASE_10, pointer_byte_size))
1502 ++num_keys_decoded;
1503 } else if (name == "addressing_bits") {
1504 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits)) {
1505 ++num_keys_decoded;
1506 }
1507 } else if (name == "high_mem_addressing_bits") {
1508 if (!value.getAsInteger(BASE_10, m_high_mem_addressing_bits))
1509 ++num_keys_decoded;
1510 } else if (name == "low_mem_addressing_bits") {
1511 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits))
1512 ++num_keys_decoded;
1513 } else if (name == "os_version" ||
1514 name == "version") // Older debugserver binaries used
1515 // the "version" key instead of
1516 // "os_version"...
1517 {
1518 if (!m_os_version.tryParse(value))
1519 ++num_keys_decoded;
1520 } else if (name == "maccatalyst_version") {
1521 if (!m_maccatalyst_version.tryParse(value))
1522 ++num_keys_decoded;
1523 } else if (name == "watchpoint_exceptions_received") {
1525 llvm::StringSwitch<LazyBool>(value)
1526 .Case("before", eLazyBoolNo)
1527 .Case("after", eLazyBoolYes)
1528 .Default(eLazyBoolCalculate);
1530 ++num_keys_decoded;
1531 } else if (name == "default_packet_timeout") {
1532 uint32_t timeout_seconds;
1533 if (!value.getAsInteger(BASE_10, timeout_seconds)) {
1534 m_default_packet_timeout = seconds(timeout_seconds);
1536 ++num_keys_decoded;
1537 }
1538 } else if (name == "vm-page-size") {
1539 int page_size;
1540 if (!value.getAsInteger(BASE_10, page_size)) {
1541 m_target_vm_page_size = page_size;
1542 ++num_keys_decoded;
1543 }
1544 }
1545 }
1546
1547 if (num_keys_decoded > 0)
1549
1550 if (triple.empty()) {
1551 if (arch_name.empty()) {
1552 if (cpu != LLDB_INVALID_CPUTYPE) {
1553 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1554 if (pointer_byte_size) {
1555 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1556 }
1557 if (byte_order != eByteOrderInvalid) {
1558 assert(byte_order == m_host_arch.GetByteOrder());
1559 }
1560
1561 if (!vendor_name.empty())
1562 m_host_arch.GetTriple().setVendorName(
1563 llvm::StringRef(vendor_name));
1564 if (!os_name.empty())
1565 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1566 if (!environment.empty())
1567 m_host_arch.GetTriple().setEnvironmentName(environment);
1568 }
1569 } else {
1570 std::string triple;
1571 triple += arch_name;
1572 if (!vendor_name.empty() || !os_name.empty()) {
1573 triple += '-';
1574 if (vendor_name.empty())
1575 triple += "unknown";
1576 else
1577 triple += vendor_name;
1578 triple += '-';
1579 if (os_name.empty())
1580 triple += "unknown";
1581 else
1582 triple += os_name;
1583 }
1584 m_host_arch.SetTriple(triple.c_str());
1585
1586 llvm::Triple &host_triple = m_host_arch.GetTriple();
1587 if (host_triple.getVendor() == llvm::Triple::Apple &&
1588 host_triple.getOS() == llvm::Triple::Darwin) {
1589 switch (m_host_arch.GetMachine()) {
1590 case llvm::Triple::aarch64:
1591 case llvm::Triple::aarch64_32:
1592 case llvm::Triple::arm:
1593 case llvm::Triple::thumb:
1594 host_triple.setOS(llvm::Triple::IOS);
1595 break;
1596 default:
1597 host_triple.setOS(llvm::Triple::MacOSX);
1598 break;
1599 }
1600 }
1601 if (pointer_byte_size) {
1602 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1603 }
1604 if (byte_order != eByteOrderInvalid) {
1605 assert(byte_order == m_host_arch.GetByteOrder());
1606 }
1607 }
1608 } else {
1609 m_host_arch.SetTriple(triple.c_str());
1610 if (pointer_byte_size) {
1611 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1612 }
1613 if (byte_order != eByteOrderInvalid) {
1614 assert(byte_order == m_host_arch.GetByteOrder());
1615 }
1616
1617 LLDB_LOGF(log,
1618 "GDBRemoteCommunicationClient::%s parsed host "
1619 "architecture as %s, triple as %s from triple text %s",
1620 __FUNCTION__,
1621 m_host_arch.GetArchitectureName()
1622 ? m_host_arch.GetArchitectureName()
1623 : "<null-arch-name>",
1624 m_host_arch.GetTriple().getTriple().c_str(),
1625 triple.c_str());
1626 }
1627 }
1628 }
1629 }
1631}
1632
1634 const char *data, size_t data_len, std::chrono::seconds interrupt_timeout) {
1635 StreamString packet;
1636 packet.PutCString("I");
1637 packet.PutBytesAsRawHex8(data, data_len);
1638 StringExtractorGDBRemote response;
1639 if (SendPacketAndWaitForResponse(packet.GetString(), response,
1640 interrupt_timeout) ==
1642 return 0;
1643 }
1644 return response.GetError();
1645}
1646
1653
1666
1672
1674 uint32_t permissions) {
1677 char packet[64];
1678 const int packet_len = ::snprintf(
1679 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1680 permissions & lldb::ePermissionsReadable ? "r" : "",
1681 permissions & lldb::ePermissionsWritable ? "w" : "",
1682 permissions & lldb::ePermissionsExecutable ? "x" : "");
1683 assert(packet_len < (int)sizeof(packet));
1684 UNUSED_IF_ASSERT_DISABLED(packet_len);
1685 StringExtractorGDBRemote response;
1686 if (SendPacketAndWaitForResponse(packet, response) ==
1688 if (response.IsUnsupportedResponse())
1690 else if (!response.IsErrorResponse())
1691 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1692 } else {
1694 }
1695 }
1696 return LLDB_INVALID_ADDRESS;
1697}
1698
1702 char packet[64];
1703 const int packet_len =
1704 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1705 assert(packet_len < (int)sizeof(packet));
1706 UNUSED_IF_ASSERT_DISABLED(packet_len);
1707 StringExtractorGDBRemote response;
1708 if (SendPacketAndWaitForResponse(packet, response) ==
1710 if (response.IsUnsupportedResponse())
1712 else if (response.IsOKResponse())
1713 return true;
1714 } else {
1716 }
1717 }
1718 return false;
1719}
1720
1722 lldb::pid_t pid) {
1723 Status error;
1725
1726 packet.PutChar('D');
1727 if (keep_stopped) {
1729 char packet[64];
1730 const int packet_len =
1731 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1732 assert(packet_len < (int)sizeof(packet));
1733 UNUSED_IF_ASSERT_DISABLED(packet_len);
1734 StringExtractorGDBRemote response;
1735 if (SendPacketAndWaitForResponse(packet, response) ==
1737 response.IsOKResponse()) {
1739 } else {
1741 }
1742 }
1743
1746 "Stays stopped not supported by this target.");
1747 return error;
1748 } else {
1749 packet.PutChar('1');
1750 }
1751 }
1752
1754 // Some servers (e.g. qemu) require specifying the PID even if only a single
1755 // process is running.
1756 if (pid == LLDB_INVALID_PROCESS_ID)
1757 pid = GetCurrentProcessID();
1758 packet.PutChar(';');
1759 packet.PutHex64(pid);
1760 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1762 "Multiprocess extension not supported by the server.");
1763 return error;
1764 }
1765
1766 StringExtractorGDBRemote response;
1767 PacketResult packet_result =
1768 SendPacketAndWaitForResponse(packet.GetString(), response);
1769 if (packet_result != PacketResult::Success)
1770 error = Status::FromErrorString("Sending disconnect packet failed.");
1771 return error;
1772}
1773
1775 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1776 Status error;
1777 region_info.Clear();
1778
1781 char packet[64];
1782 const int packet_len = ::snprintf(
1783 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1784 assert(packet_len < (int)sizeof(packet));
1785 UNUSED_IF_ASSERT_DISABLED(packet_len);
1786 StringExtractorGDBRemote response;
1787 if (SendPacketAndWaitForResponse(packet, response) ==
1790 llvm::StringRef name;
1791 llvm::StringRef value;
1792 addr_t addr_value = LLDB_INVALID_ADDRESS;
1793 bool success = true;
1794 bool saw_permissions = false;
1795 while (success && response.GetNameColonValue(name, value)) {
1796 if (name == "start") {
1797 if (!value.getAsInteger(BASE_16, addr_value))
1798 region_info.GetRange().SetRangeBase(addr_value);
1799 } else if (name == "size") {
1800 if (!value.getAsInteger(BASE_16, addr_value)) {
1801 region_info.GetRange().SetByteSize(addr_value);
1802 if (region_info.GetRange().GetRangeEnd() <
1803 region_info.GetRange().GetRangeBase()) {
1804 // Range size overflowed, truncate it.
1806 }
1807 }
1808 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1809 saw_permissions = true;
1810 if (region_info.GetRange().Contains(addr)) {
1811 if (value.contains('r'))
1812 region_info.SetReadable(eLazyBoolYes);
1813 else
1814 region_info.SetReadable(eLazyBoolNo);
1815
1816 if (value.contains('w'))
1817 region_info.SetWritable(eLazyBoolYes);
1818 else
1819 region_info.SetWritable(eLazyBoolNo);
1820
1821 if (value.contains('x'))
1822 region_info.SetExecutable(eLazyBoolYes);
1823 else
1824 region_info.SetExecutable(eLazyBoolNo);
1825
1826 region_info.SetMapped(eLazyBoolYes);
1827 } else {
1828 // The reported region does not contain this address -- we're
1829 // looking at an unmapped page
1830 region_info.SetReadable(eLazyBoolNo);
1831 region_info.SetWritable(eLazyBoolNo);
1832 region_info.SetExecutable(eLazyBoolNo);
1833 region_info.SetMapped(eLazyBoolNo);
1834 }
1835 } else if (name == "name") {
1836 StringExtractorGDBRemote name_extractor(value);
1837 std::string name;
1838 name_extractor.GetHexByteString(name);
1839 region_info.SetName(name.c_str());
1840 } else if (name == "flags") {
1841 region_info.SetMemoryTagged(eLazyBoolNo);
1842 region_info.SetIsShadowStack(eLazyBoolNo);
1843
1844 llvm::StringRef flags = value;
1845 llvm::StringRef flag;
1846 while (flags.size()) {
1847 flags = flags.ltrim();
1848 std::tie(flag, flags) = flags.split(' ');
1849 // To account for trailing whitespace
1850 if (flag.size()) {
1851 if (flag == "mt")
1852 region_info.SetMemoryTagged(eLazyBoolYes);
1853 else if (flag == "ss")
1854 region_info.SetIsShadowStack(eLazyBoolYes);
1855 }
1856 }
1857 } else if (name == "type") {
1858 for (llvm::StringRef entry : llvm::split(value, ',')) {
1859 if (entry == "stack")
1860 region_info.SetIsStackMemory(eLazyBoolYes);
1861 else if (entry == "heap")
1862 region_info.SetIsStackMemory(eLazyBoolNo);
1863 }
1864 } else if (name == "error") {
1865 StringExtractorGDBRemote error_extractor(value);
1866 std::string error_string;
1867 // Now convert the HEX bytes into a string value
1868 error_extractor.GetHexByteString(error_string);
1869 error = Status::FromErrorString(error_string.c_str());
1870 } else if (name == "dirty-pages") {
1871 std::vector<addr_t> dirty_page_list;
1872 for (llvm::StringRef x : llvm::split(value, ',')) {
1873 addr_t page;
1874 x.consume_front("0x");
1875 if (llvm::to_integer(x, page, 16))
1876 dirty_page_list.push_back(page);
1877 }
1878 region_info.SetDirtyPageList(dirty_page_list);
1879 } else if (name == "protection-key") {
1880 unsigned protection_key = 0;
1881 if (!value.getAsInteger(BASE_10, protection_key))
1882 region_info.SetProtectionKey(protection_key);
1883 }
1884 }
1885
1886 if (m_target_vm_page_size != 0)
1888
1889 if (region_info.GetRange().IsValid()) {
1890 // We got a valid address range back but no permissions -- which means
1891 // this is an unmapped page
1892 if (!saw_permissions) {
1893 region_info.SetReadable(eLazyBoolNo);
1894 region_info.SetWritable(eLazyBoolNo);
1895 region_info.SetExecutable(eLazyBoolNo);
1896 region_info.SetMapped(eLazyBoolNo);
1897 }
1898 } else {
1899 // We got an invalid address range back
1900 error = Status::FromErrorString("Server returned invalid range");
1901 }
1902 } else {
1904 }
1905 }
1906
1908 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1909 }
1910
1911 // Try qXfer:memory-map:read to get region information not included in
1912 // qMemoryRegionInfo
1913 MemoryRegionInfo qXfer_region_info;
1914 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1915
1916 if (error.Fail()) {
1917 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1918 // the qXfer result as a fallback
1919 if (qXfer_error.Success()) {
1920 region_info = qXfer_region_info;
1921 error.Clear();
1922 } else {
1923 region_info.Clear();
1924 }
1925 } else if (qXfer_error.Success()) {
1926 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1927 // both regions are the same range, update the result to include the flash-
1928 // memory information that is specific to the qXfer result.
1929 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1930 region_info.SetFlash(qXfer_region_info.GetFlash());
1931 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1932 }
1933 }
1934 return error;
1935}
1936
1938 lldb::addr_t addr, MemoryRegionInfo &region) {
1940 if (!error.Success())
1941 return error;
1942 for (const auto &map_region : m_qXfer_memory_map) {
1943 if (map_region.GetRange().Contains(addr)) {
1944 region = map_region;
1945 return error;
1946 }
1947 }
1948 error = Status::FromErrorString("Region not found");
1949 return error;
1950}
1951
1953
1954 Status error;
1955
1957 // Already loaded, return success
1958 return error;
1959
1960 if (!XMLDocument::XMLEnabled()) {
1961 error = Status::FromErrorString("XML is not supported");
1962 return error;
1963 }
1964
1966 error = Status::FromErrorString("Memory map is not supported");
1967 return error;
1968 }
1969
1970 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1971 if (!xml)
1972 return Status::FromError(xml.takeError());
1973
1974 XMLDocument xml_document;
1975
1976 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1977 error = Status::FromErrorString("Failed to parse memory map xml");
1978 return error;
1979 }
1980
1981 XMLNode map_node = xml_document.GetRootElement("memory-map");
1982 if (!map_node) {
1983 error = Status::FromErrorString("Invalid root node in memory map xml");
1984 return error;
1985 }
1986
1987 m_qXfer_memory_map.clear();
1988
1989 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1990 if (!memory_node.IsElement())
1991 return true;
1992 if (memory_node.GetName() != "memory")
1993 return true;
1994 auto type = memory_node.GetAttributeValue("type", "");
1995 uint64_t start;
1996 uint64_t length;
1997 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1998 return true;
1999 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
2000 return true;
2001 MemoryRegionInfo region;
2002 region.GetRange().SetRangeBase(start);
2003 region.GetRange().SetByteSize(length);
2004 if (type == "rom") {
2005 region.SetReadable(eLazyBoolYes);
2006 this->m_qXfer_memory_map.push_back(region);
2007 } else if (type == "ram") {
2008 region.SetReadable(eLazyBoolYes);
2009 region.SetWritable(eLazyBoolYes);
2010 this->m_qXfer_memory_map.push_back(region);
2011 } else if (type == "flash") {
2012 region.SetFlash(eLazyBoolYes);
2013 memory_node.ForEachChildElement(
2014 [&region](const XMLNode &prop_node) -> bool {
2015 if (!prop_node.IsElement())
2016 return true;
2017 if (prop_node.GetName() != "property")
2018 return true;
2019 auto propname = prop_node.GetAttributeValue("name", "");
2020 if (propname == "blocksize") {
2021 uint64_t blocksize;
2022 if (prop_node.GetElementTextAsUnsigned(blocksize))
2023 region.SetBlocksize(blocksize);
2024 }
2025 return true;
2026 });
2027 this->m_qXfer_memory_map.push_back(region);
2028 }
2029 return true;
2030 });
2031
2033
2034 return error;
2035}
2036
2040 }
2041
2042 std::optional<uint32_t> num;
2044 StringExtractorGDBRemote response;
2045 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
2048 llvm::StringRef name;
2049 llvm::StringRef value;
2050 while (response.GetNameColonValue(name, value)) {
2051 if (name == "num") {
2052 value.getAsInteger(BASE_10, m_num_supported_hardware_watchpoints);
2054 }
2055 }
2056 if (!num) {
2058 }
2059 } else {
2061 }
2062 }
2063
2064 return num;
2065}
2066
2067WatchpointHardwareFeature
2071
2074 GetHostInfo();
2075
2076 // Process determines this by target CPU, but allow for the
2077 // remote stub to override it via the qHostInfo
2078 // watchpoint_exceptions_received key, if it is present.
2081 return false;
2083 return true;
2084 }
2085
2086 return std::nullopt;
2087}
2088
2090 if (file_spec) {
2091 std::string path{file_spec.GetPath(false)};
2092 StreamString packet;
2093 packet.PutCString("QSetSTDIN:");
2094 packet.PutStringAsRawHex8(path);
2095
2096 StringExtractorGDBRemote response;
2097 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2099 if (response.IsOKResponse())
2100 return 0;
2101 uint8_t error = response.GetError();
2102 if (error)
2103 return error;
2104 }
2105 }
2106 return -1;
2107}
2108
2110 if (file_spec) {
2111 std::string path{file_spec.GetPath(false)};
2112 StreamString packet;
2113 packet.PutCString("QSetSTDOUT:");
2114 packet.PutStringAsRawHex8(path);
2115
2116 StringExtractorGDBRemote response;
2117 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2119 if (response.IsOKResponse())
2120 return 0;
2121 uint8_t error = response.GetError();
2122 if (error)
2123 return error;
2124 }
2125 }
2126 return -1;
2127}
2128
2130 if (file_spec) {
2131 std::string path{file_spec.GetPath(false)};
2132 StreamString packet;
2133 packet.PutCString("QSetSTDERR:");
2134 packet.PutStringAsRawHex8(path);
2135
2136 StringExtractorGDBRemote response;
2137 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2139 if (response.IsOKResponse())
2140 return 0;
2141 uint8_t error = response.GetError();
2142 if (error)
2143 return error;
2144 }
2145 }
2146 return -1;
2147}
2148
2150 uint16_t rows) {
2151 // The size is only valid if both or none of the dimensions are zero.
2152 if ((cols == 0) != (rows == 0))
2153 return -1;
2154 StreamString packet;
2155 packet.Printf("QSetSTDIOWindowSize:cols=%u;rows=%u",
2156 static_cast<unsigned>(cols), static_cast<unsigned>(rows));
2157 StringExtractorGDBRemote response;
2158 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
2160 return -1;
2161 if (response.IsOKResponse())
2162 return 0;
2163 if (response.IsUnsupportedResponse())
2164 return 0;
2165 uint8_t error = response.GetError();
2166 return error ? error : -1;
2167}
2168
2170 StringExtractorGDBRemote response;
2171 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
2173 if (response.IsUnsupportedResponse())
2174 return false;
2175 if (response.IsErrorResponse())
2176 return false;
2177 std::string cwd;
2178 response.GetHexByteString(cwd);
2179 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
2180 return !cwd.empty();
2181 }
2182 return false;
2183}
2184
2186 if (working_dir) {
2187 std::string path{working_dir.GetPath(false)};
2188 StreamString packet;
2189 packet.PutCString("QSetWorkingDir:");
2190 packet.PutStringAsRawHex8(path);
2191
2192 StringExtractorGDBRemote response;
2193 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2195 if (response.IsOKResponse())
2196 return 0;
2197 uint8_t error = response.GetError();
2198 if (error)
2199 return error;
2200 }
2201 }
2202 return -1;
2203}
2204
2206 char packet[32];
2207 const int packet_len =
2208 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2209 assert(packet_len < (int)sizeof(packet));
2210 UNUSED_IF_ASSERT_DISABLED(packet_len);
2211 StringExtractorGDBRemote response;
2212 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2213 if (response.IsOKResponse())
2214 return 0;
2215 uint8_t error = response.GetError();
2216 if (error)
2217 return error;
2218 }
2219 return -1;
2220}
2221
2223 char packet[32];
2224 const int packet_len = ::snprintf(packet, sizeof(packet),
2225 "QSetDetachOnError:%i", enable ? 1 : 0);
2226 assert(packet_len < (int)sizeof(packet));
2227 UNUSED_IF_ASSERT_DISABLED(packet_len);
2228 StringExtractorGDBRemote response;
2229 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2230 if (response.IsOKResponse())
2231 return 0;
2232 uint8_t error = response.GetError();
2233 if (error)
2234 return error;
2235 }
2236 return -1;
2237}
2238
2240 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2241 if (response.IsNormalResponse()) {
2242 llvm::StringRef name;
2243 llvm::StringRef value;
2244 StringExtractor extractor;
2245
2246 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2247 uint32_t sub = 0;
2248 std::string vendor;
2249 std::string os_type;
2250
2251 while (response.GetNameColonValue(name, value)) {
2252 if (name == "pid") {
2254 value.getAsInteger(BASE_10, pid);
2255 process_info.SetProcessID(pid);
2256 } else if (name == "ppid") {
2258 value.getAsInteger(BASE_10, pid);
2259 process_info.SetParentProcessID(pid);
2260 } else if (name == "uid") {
2261 uint32_t uid = UINT32_MAX;
2262 value.getAsInteger(BASE_10, uid);
2263 process_info.SetUserID(uid);
2264 } else if (name == "euid") {
2265 uint32_t uid = UINT32_MAX;
2266 value.getAsInteger(BASE_10, uid);
2267 process_info.SetEffectiveUserID(uid);
2268 } else if (name == "gid") {
2269 uint32_t gid = UINT32_MAX;
2270 value.getAsInteger(BASE_10, gid);
2271 process_info.SetGroupID(gid);
2272 } else if (name == "egid") {
2273 uint32_t gid = UINT32_MAX;
2274 value.getAsInteger(BASE_10, gid);
2275 process_info.SetEffectiveGroupID(gid);
2276 } else if (name == "triple") {
2277 StringExtractor extractor(value);
2278 std::string triple;
2279 extractor.GetHexByteString(triple);
2280 process_info.GetArchitecture().SetTriple(triple.c_str());
2281 } else if (name == "name") {
2282 StringExtractor extractor(value);
2283 // The process name from ASCII hex bytes since we can't control the
2284 // characters in a process name
2285 std::string name;
2286 extractor.GetHexByteString(name);
2287 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2288 } else if (name == "args") {
2289 llvm::StringRef encoded_args(value), hex_arg;
2290
2291 bool is_arg0 = true;
2292 while (!encoded_args.empty()) {
2293 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2294 std::string arg;
2295 StringExtractor extractor(hex_arg);
2296 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2297 // In case of wrong encoding, we discard all the arguments
2298 process_info.GetArguments().Clear();
2299 process_info.SetArg0("");
2300 break;
2301 }
2302 if (is_arg0)
2303 process_info.SetArg0(arg);
2304 else
2305 process_info.GetArguments().AppendArgument(arg);
2306 is_arg0 = false;
2307 }
2308 } else if (name == "cputype") {
2309 value.getAsInteger(BASE_10, cpu);
2310 } else if (name == "cpusubtype") {
2311 value.getAsInteger(BASE_10, sub);
2312 } else if (name == "vendor") {
2313 vendor = std::string(value);
2314 } else if (name == "ostype") {
2315 os_type = std::string(value);
2316 }
2317 }
2318
2319 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2320 if (vendor == "apple") {
2322 sub);
2323 process_info.GetArchitecture().GetTriple().setVendorName(
2324 llvm::StringRef(vendor));
2325 process_info.GetArchitecture().GetTriple().setOSName(
2326 llvm::StringRef(os_type));
2327 }
2328 }
2329
2330 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2331 return true;
2332 }
2333 return false;
2334}
2335
2337 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2338 process_info.Clear();
2339
2341 char packet[32];
2342 const int packet_len =
2343 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2344 assert(packet_len < (int)sizeof(packet));
2345 UNUSED_IF_ASSERT_DISABLED(packet_len);
2346 StringExtractorGDBRemote response;
2347 if (SendPacketAndWaitForResponse(packet, response) ==
2349 return DecodeProcessInfoResponse(response, process_info);
2350 } else {
2352 return false;
2353 }
2354 }
2355 return false;
2356}
2357
2360
2361 if (allow_lazy) {
2363 return true;
2365 return false;
2366 }
2367
2368 GetHostInfo();
2369
2370 StringExtractorGDBRemote response;
2371 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2373 if (response.IsNormalResponse()) {
2374 llvm::StringRef name;
2375 llvm::StringRef value;
2376 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2377 uint32_t sub = 0;
2378 std::string os_name;
2379 std::string environment;
2380 std::string vendor_name;
2381 std::string triple;
2382 std::string elf_abi;
2383 uint32_t pointer_byte_size = 0;
2384 StringExtractor extractor;
2385 ByteOrder byte_order = eByteOrderInvalid;
2386 uint32_t num_keys_decoded = 0;
2388 while (response.GetNameColonValue(name, value)) {
2389 if (name == "cputype") {
2390 if (!value.getAsInteger(BASE_16, cpu))
2391 ++num_keys_decoded;
2392 } else if (name == "cpusubtype") {
2393 if (!value.getAsInteger(BASE_16, sub)) {
2394 ++num_keys_decoded;
2395 // Workaround for pre-2024 Apple debugserver, which always
2396 // returns arm64e on arm64e-capable hardware regardless of
2397 // what the process is. This can be deleted at some point
2398 // in the future.
2399 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2400 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2401 if (GetGDBServerVersion())
2402 if (m_gdb_server_version >= 1000 &&
2403 m_gdb_server_version <= 1504)
2404 sub = 0;
2405 }
2406 }
2407 } else if (name == "triple") {
2408 StringExtractor extractor(value);
2409 extractor.GetHexByteString(triple);
2410 ++num_keys_decoded;
2411 } else if (name == "ostype") {
2412 ParseOSType(value, os_name, environment);
2413 ++num_keys_decoded;
2414 } else if (name == "vendor") {
2415 vendor_name = std::string(value);
2416 ++num_keys_decoded;
2417 } else if (name == "endian") {
2418 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2419 .Case("little", eByteOrderLittle)
2420 .Case("big", eByteOrderBig)
2421 .Case("pdp", eByteOrderPDP)
2422 .Default(eByteOrderInvalid);
2423 if (byte_order != eByteOrderInvalid)
2424 ++num_keys_decoded;
2425 } else if (name == "ptrsize") {
2426 if (!value.getAsInteger(BASE_16, pointer_byte_size))
2427 ++num_keys_decoded;
2428 } else if (name == "pid") {
2429 if (!value.getAsInteger(BASE_16, pid))
2430 ++num_keys_decoded;
2431 } else if (name == "elf_abi") {
2432 elf_abi = std::string(value);
2433 ++num_keys_decoded;
2434 } else if (name == "main-binary-uuid") {
2435 m_process_standalone_uuid.SetFromStringRef(value);
2436 ++num_keys_decoded;
2437 } else if (name == "main-binary-slide") {
2438 StringExtractor extractor(value);
2440 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2443 ++num_keys_decoded;
2444 }
2445 } else if (name == "main-binary-address") {
2446 StringExtractor extractor(value);
2448 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2451 ++num_keys_decoded;
2452 }
2453 } else if (name == "binary-addresses") {
2454 m_binary_addresses.clear();
2455 ++num_keys_decoded;
2456 for (llvm::StringRef x : llvm::split(value, ',')) {
2457 addr_t vmaddr;
2458 x.consume_front("0x");
2459 if (llvm::to_integer(x, vmaddr, 16))
2460 m_binary_addresses.push_back(vmaddr);
2461 }
2462 }
2463 }
2464 if (num_keys_decoded > 0)
2466 if (pid != LLDB_INVALID_PROCESS_ID) {
2468 m_curr_pid_run = m_curr_pid = pid;
2469 }
2470
2471 // Set the ArchSpec from the triple if we have it.
2472 if (!triple.empty()) {
2473 m_process_arch.SetTriple(triple.c_str());
2474 m_process_arch.SetFlags(elf_abi);
2475 if (pointer_byte_size) {
2476 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2477 }
2478 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2479 !vendor_name.empty()) {
2480 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2481 if (!environment.empty())
2482 triple.setEnvironmentName(environment);
2483
2484 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2485 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2486 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2487 switch (triple.getObjectFormat()) {
2488 case llvm::Triple::MachO:
2489 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2490 break;
2491 case llvm::Triple::ELF:
2492 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2493 break;
2494 case llvm::Triple::COFF:
2495 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2496 break;
2497 case llvm::Triple::GOFF:
2498 case llvm::Triple::SPIRV:
2499 case llvm::Triple::Wasm:
2500 case llvm::Triple::XCOFF:
2501 case llvm::Triple::DXContainer:
2502 LLDB_LOGF(log, "error: not supported target architecture");
2503 return false;
2504 case llvm::Triple::UnknownObjectFormat:
2505 LLDB_LOGF(log, "error: failed to determine target architecture");
2506 return false;
2507 }
2508
2509 if (pointer_byte_size) {
2510 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2511 }
2512 if (byte_order != eByteOrderInvalid) {
2513 assert(byte_order == m_process_arch.GetByteOrder());
2514 }
2515 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2516 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2517 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2518 }
2519 return true;
2520 }
2521 } else {
2523 }
2524
2525 return false;
2526}
2527
2529 const ProcessInstanceInfoMatch &match_info,
2530 ProcessInstanceInfoList &process_infos) {
2531 process_infos.clear();
2532
2534 StreamString packet;
2535 packet.PutCString("qfProcessInfo");
2536 if (!match_info.MatchAllProcesses()) {
2537 packet.PutChar(':');
2538 llvm::StringRef name = match_info.GetProcessInfo().GetName();
2539 bool has_name_match = false;
2540 if (!name.empty()) {
2541 has_name_match = true;
2542 NameMatch name_match_type = match_info.GetNameMatchType();
2543 switch (name_match_type) {
2544 case NameMatch::Ignore:
2545 has_name_match = false;
2546 break;
2547
2548 case NameMatch::Equals:
2549 packet.PutCString("name_match:equals;");
2550 break;
2551
2553 packet.PutCString("name_match:contains;");
2554 break;
2555
2557 packet.PutCString("name_match:starts_with;");
2558 break;
2559
2561 packet.PutCString("name_match:ends_with;");
2562 break;
2563
2565 packet.PutCString("name_match:regex;");
2566 break;
2567 }
2568 if (has_name_match) {
2569 packet.PutCString("name:");
2570 packet.PutBytesAsRawHex8(name.data(), name.size());
2571 packet.PutChar(';');
2572 }
2573 }
2574
2575 if (match_info.GetProcessInfo().ProcessIDIsValid())
2576 packet.Printf("pid:%" PRIu64 ";",
2577 match_info.GetProcessInfo().GetProcessID());
2578 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2579 packet.Printf("parent_pid:%" PRIu64 ";",
2580 match_info.GetProcessInfo().GetParentProcessID());
2581 if (match_info.GetProcessInfo().UserIDIsValid())
2582 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2583 if (match_info.GetProcessInfo().GroupIDIsValid())
2584 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2585 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2586 packet.Printf("euid:%u;",
2587 match_info.GetProcessInfo().GetEffectiveUserID());
2588 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2589 packet.Printf("egid:%u;",
2590 match_info.GetProcessInfo().GetEffectiveGroupID());
2591 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2592 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2593 const ArchSpec &match_arch =
2594 match_info.GetProcessInfo().GetArchitecture();
2595 const llvm::Triple &triple = match_arch.GetTriple();
2596 packet.PutCString("triple:");
2597 packet.PutCString(triple.getTriple());
2598 packet.PutChar(';');
2599 }
2600 }
2601 StringExtractorGDBRemote response;
2602 // Increase timeout as the first qfProcessInfo packet takes a long time on
2603 // Android. The value of 1min was arrived at empirically.
2604 ScopedTimeout timeout(*this, minutes(1));
2605 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2607 do {
2608 ProcessInstanceInfo process_info;
2609 if (!DecodeProcessInfoResponse(response, process_info))
2610 break;
2611 process_infos.push_back(process_info);
2612 response = StringExtractorGDBRemote();
2613 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2615 } else {
2617 return 0;
2618 }
2619 }
2620 return process_infos.size();
2621}
2622
2624 std::string &name) {
2626 char packet[32];
2627 const int packet_len =
2628 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2629 assert(packet_len < (int)sizeof(packet));
2630 UNUSED_IF_ASSERT_DISABLED(packet_len);
2631 StringExtractorGDBRemote response;
2632 if (SendPacketAndWaitForResponse(packet, response) ==
2634 if (response.IsNormalResponse()) {
2635 // Make sure we parsed the right number of characters. The response is
2636 // the hex encoded user name and should make up the entire packet. If
2637 // there are any non-hex ASCII bytes, the length won't match below..
2638 if (response.GetHexByteString(name) * 2 ==
2639 response.GetStringRef().size())
2640 return true;
2641 }
2642 } else {
2643 m_supports_qUserName = false;
2644 return false;
2645 }
2646 }
2647 return false;
2648}
2649
2651 std::string &name) {
2653 char packet[32];
2654 const int packet_len =
2655 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2656 assert(packet_len < (int)sizeof(packet));
2657 UNUSED_IF_ASSERT_DISABLED(packet_len);
2658 StringExtractorGDBRemote response;
2659 if (SendPacketAndWaitForResponse(packet, response) ==
2661 if (response.IsNormalResponse()) {
2662 // Make sure we parsed the right number of characters. The response is
2663 // the hex encoded group name and should make up the entire packet. If
2664 // there are any non-hex ASCII bytes, the length won't match below..
2665 if (response.GetHexByteString(name) * 2 ==
2666 response.GetStringRef().size())
2667 return true;
2668 }
2669 } else {
2670 m_supports_qGroupName = false;
2671 return false;
2672 }
2673 }
2674 return false;
2675}
2676
2677static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2678 uint32_t recv_size) {
2679 packet.Clear();
2680 packet.Printf("qSpeedTest:response_size:%x;data:", recv_size);
2681 uint32_t bytes_left = send_size;
2682 while (bytes_left > 0) {
2683 if (bytes_left >= 26) {
2684 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2685 bytes_left -= 26;
2686 } else {
2687 packet.Printf("%*.*s;", bytes_left, bytes_left,
2688 "abcdefghijklmnopqrstuvwxyz");
2689 bytes_left = 0;
2690 }
2691 }
2692}
2693
2694duration<float>
2695calculate_standard_deviation(const std::vector<duration<float>> &v) {
2696 if (v.size() == 0)
2697 return duration<float>::zero();
2698 using Dur = duration<float>;
2699 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2700 Dur mean = sum / v.size();
2701 float accum = 0;
2702 for (auto d : v) {
2703 float delta = (d - mean).count();
2704 accum += delta * delta;
2705 };
2706
2707 return Dur(sqrtf(accum / (v.size() - 1)));
2708}
2709
2711 uint32_t max_send,
2712 uint32_t max_recv,
2713 uint64_t recv_amount,
2714 bool json, Stream &strm) {
2715
2716 if (SendSpeedTestPacket(0, 0)) {
2717 StreamString packet;
2718 if (json)
2719 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2720 "\"results\" : [",
2721 num_packets);
2722 else
2723 strm.Printf("Testing sending %u packets of various sizes:\n",
2724 num_packets);
2725 strm.Flush();
2726
2727 uint32_t result_idx = 0;
2728 uint32_t send_size;
2729 std::vector<duration<float>> packet_times;
2730
2731 for (send_size = 0; send_size <= max_send;
2732 send_size ? send_size *= 2 : send_size = 4) {
2733 for (uint32_t recv_size = 0; recv_size <= max_recv;
2734 recv_size ? recv_size *= 2 : recv_size = 4) {
2735 MakeSpeedTestPacket(packet, send_size, recv_size);
2736
2737 packet_times.clear();
2738 // Test how long it takes to send 'num_packets' packets
2739 const auto start_time = steady_clock::now();
2740 for (uint32_t i = 0; i < num_packets; ++i) {
2741 const auto packet_start_time = steady_clock::now();
2742 StringExtractorGDBRemote response;
2743 SendPacketAndWaitForResponse(packet.GetString(), response);
2744 const auto packet_end_time = steady_clock::now();
2745 packet_times.push_back(packet_end_time - packet_start_time);
2746 }
2747 const auto end_time = steady_clock::now();
2748 const auto total_time = end_time - start_time;
2749
2750 float packets_per_second =
2751 ((float)num_packets) / duration<float>(total_time).count();
2752 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2753 : duration<float>::zero();
2754 const duration<float> standard_deviation =
2755 calculate_standard_deviation(packet_times);
2756 if (json) {
2757 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2758 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2759 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2760 result_idx > 0 ? "," : "", send_size, recv_size,
2761 total_time, standard_deviation);
2762 ++result_idx;
2763 } else {
2764 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2765 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2766 "standard deviation of {5,10:ms+f6}\n",
2767 send_size, recv_size, duration<float>(total_time),
2768 packets_per_second, duration<float>(average_per_packet),
2769 standard_deviation);
2770 }
2771 strm.Flush();
2772 }
2773 }
2774
2775 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2776 if (json)
2777 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2778 ": %" PRIu64 ",\n \"results\" : [",
2779 recv_amount);
2780 else
2781 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2782 "packet sizes:\n",
2783 k_recv_amount_mb);
2784 strm.Flush();
2785 send_size = 0;
2786 result_idx = 0;
2787 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2788 MakeSpeedTestPacket(packet, send_size, recv_size);
2789
2790 // If we have a receive size, test how long it takes to receive 4MB of
2791 // data
2792 if (recv_size > 0) {
2793 const auto start_time = steady_clock::now();
2794 uint32_t bytes_read = 0;
2795 uint32_t packet_count = 0;
2796 while (bytes_read < recv_amount) {
2797 StringExtractorGDBRemote response;
2798 SendPacketAndWaitForResponse(packet.GetString(), response);
2799 bytes_read += recv_size;
2800 ++packet_count;
2801 }
2802 const auto end_time = steady_clock::now();
2803 const auto total_time = end_time - start_time;
2804 float mb_second = ((float)recv_amount) /
2805 duration<float>(total_time).count() /
2806 (1024.0 * 1024.0);
2807 float packets_per_second =
2808 ((float)packet_count) / duration<float>(total_time).count();
2809 const auto average_per_packet = packet_count > 0
2810 ? total_time / packet_count
2811 : duration<float>::zero();
2812
2813 if (json) {
2814 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2815 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2816 result_idx > 0 ? "," : "", send_size, recv_size,
2817 total_time);
2818 ++result_idx;
2819 } else {
2820 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2821 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2822 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2823 send_size, recv_size, packet_count, k_recv_amount_mb,
2824 duration<float>(total_time), mb_second,
2825 packets_per_second, duration<float>(average_per_packet));
2826 }
2827 strm.Flush();
2828 }
2829 }
2830 if (json)
2831 strm.Printf("\n ]\n }\n}\n");
2832 else
2833 strm.EOL();
2834 }
2835}
2836
2838 uint32_t recv_size) {
2839 StreamString packet;
2840 MakeSpeedTestPacket(packet, send_size, recv_size);
2841
2842 StringExtractorGDBRemote response;
2843 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2845}
2846
2848 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2849 std::string &socket_name) {
2851 port = 0;
2852 socket_name.clear();
2853
2854 StringExtractorGDBRemote response;
2855 StreamString stream;
2856 stream.PutCString("qLaunchGDBServer;");
2857 std::string hostname;
2858 if (remote_accept_hostname && remote_accept_hostname[0])
2859 hostname = remote_accept_hostname;
2860 else {
2861 if (HostInfo::GetHostname(hostname)) {
2862 // Make the GDB server we launch only accept connections from this host
2863 stream.Printf("host:%s;", hostname.c_str());
2864 } else {
2865 // Make the GDB server we launch accept connections from any host since
2866 // we can't figure out the hostname
2867 stream.Printf("host:*;");
2868 }
2869 }
2870 // give the process a few seconds to startup
2871 ScopedTimeout timeout(*this, seconds(10));
2872
2873 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2875 if (response.IsErrorResponse())
2876 return false;
2877
2878 llvm::StringRef name;
2879 llvm::StringRef value;
2880 while (response.GetNameColonValue(name, value)) {
2881 if (name == "port")
2882 value.getAsInteger(BASE_10, port);
2883 else if (name == "pid")
2884 value.getAsInteger(BASE_10, pid);
2885 else if (name.compare("socket_name") == 0) {
2886 StringExtractor extractor(value);
2887 extractor.GetHexByteString(socket_name);
2888 }
2889 }
2890 return true;
2891 }
2892 return false;
2893}
2894
2896 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2897 connection_urls.clear();
2898
2899 StringExtractorGDBRemote response;
2900 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2902 return 0;
2903
2906 if (!data)
2907 return 0;
2908
2909 StructuredData::Array *array = data->GetAsArray();
2910 if (!array)
2911 return 0;
2912
2913 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2914 std::optional<StructuredData::Dictionary *> maybe_element =
2916 if (!maybe_element)
2917 continue;
2918
2919 StructuredData::Dictionary *element = *maybe_element;
2920 uint16_t port = 0;
2921 if (StructuredData::ObjectSP port_osp =
2922 element->GetValueForKey(llvm::StringRef("port")))
2923 port = port_osp->GetUnsignedIntegerValue(0);
2924
2925 std::string socket_name;
2926 if (StructuredData::ObjectSP socket_name_osp =
2927 element->GetValueForKey(llvm::StringRef("socket_name")))
2928 socket_name = std::string(socket_name_osp->GetStringValue());
2929
2930 if (port != 0 || !socket_name.empty())
2931 connection_urls.emplace_back(port, socket_name);
2932 }
2933 return connection_urls.size();
2934}
2935
2937 StreamString stream;
2938 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2939
2940 StringExtractorGDBRemote response;
2941 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2943 if (response.IsOKResponse())
2944 return true;
2945 }
2946 return false;
2947}
2948
2950 uint64_t tid, uint64_t pid, char op) {
2952 packet.PutChar('H');
2953 packet.PutChar(op);
2954
2955 if (pid != LLDB_INVALID_PROCESS_ID)
2956 packet.Printf("p%" PRIx64 ".", pid);
2957
2958 if (tid == UINT64_MAX)
2959 packet.PutCString("-1");
2960 else
2961 packet.Printf("%" PRIx64, tid);
2962
2963 StringExtractorGDBRemote response;
2964 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2966 if (response.IsOKResponse())
2967 return {{pid, tid}};
2968
2969 /*
2970 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2971 * Hg packet.
2972 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2973 * which can
2974 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2975 */
2976 if (response.IsUnsupportedResponse() && IsConnected())
2977 return {{1, 1}};
2978 }
2979 return std::nullopt;
2980}
2981
2983 uint64_t pid) {
2984 if (m_curr_tid == tid &&
2985 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2986 return true;
2987
2988 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2989 if (ret) {
2990 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2991 m_curr_pid = ret->pid;
2992 m_curr_tid = ret->tid;
2993 }
2994 return ret.has_value();
2995}
2996
2998 uint64_t pid) {
2999 if (m_curr_tid_run == tid &&
3000 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
3001 return true;
3002
3003 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
3004 if (ret) {
3005 if (ret->pid != LLDB_INVALID_PROCESS_ID)
3006 m_curr_pid_run = ret->pid;
3007 m_curr_tid_run = ret->tid;
3008 }
3009 return ret.has_value();
3010}
3011
3013 StringExtractorGDBRemote &response) {
3015 return response.IsNormalResponse();
3016 return false;
3017}
3018
3020 lldb::tid_t tid, StringExtractorGDBRemote &response) {
3022 char packet[256];
3023 int packet_len =
3024 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3025 assert(packet_len < (int)sizeof(packet));
3026 UNUSED_IF_ASSERT_DISABLED(packet_len);
3027 if (SendPacketAndWaitForResponse(packet, response) ==
3029 if (response.IsUnsupportedResponse())
3031 else if (response.IsNormalResponse())
3032 return true;
3033 else
3034 return false;
3035 } else {
3037 }
3038 }
3039 return false;
3040}
3041
3043 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
3044 std::chrono::seconds timeout) {
3046 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3047 __FUNCTION__, insert ? "add" : "remove", addr);
3048
3049 // Check if the stub is known not to support this breakpoint type
3050 if (!SupportsGDBStoppointPacket(type))
3051 return UINT8_MAX;
3052 // Construct the breakpoint packet
3053 char packet[64];
3054 const int packet_len =
3055 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
3056 insert ? 'Z' : 'z', type, addr, length);
3057 // Check we haven't overwritten the end of the packet buffer
3058 assert(packet_len + 1 < (int)sizeof(packet));
3059 UNUSED_IF_ASSERT_DISABLED(packet_len);
3060 StringExtractorGDBRemote response;
3061 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
3062 // or "" (unsupported)
3064 // Try to send the breakpoint packet, and check that it was correctly sent
3065 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
3067 // Receive and OK packet when the breakpoint successfully placed
3068 if (response.IsOKResponse())
3069 return 0;
3070
3071 // Status while setting breakpoint, send back specific error
3072 if (response.IsErrorResponse())
3073 return response.GetError();
3074
3075 // Empty packet informs us that breakpoint is not supported
3076 if (response.IsUnsupportedResponse()) {
3077 // Disable this breakpoint type since it is unsupported
3078 switch (type) {
3080 m_supports_z0 = false;
3081 break;
3083 m_supports_z1 = false;
3084 break;
3085 case eWatchpointWrite:
3086 m_supports_z2 = false;
3087 break;
3088 case eWatchpointRead:
3089 m_supports_z3 = false;
3090 break;
3092 m_supports_z4 = false;
3093 break;
3094 case eStoppointInvalid:
3095 return UINT8_MAX;
3096 }
3097 }
3098 }
3099 // Signal generic failure
3100 return UINT8_MAX;
3101}
3102
3103std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
3105 bool &sequence_mutex_unavailable) {
3106 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
3107
3108 Lock lock(*this);
3109 if (lock) {
3110 sequence_mutex_unavailable = false;
3111 StringExtractorGDBRemote response;
3112
3113 PacketResult packet_result;
3114 for (packet_result =
3115 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
3116 packet_result == PacketResult::Success && response.IsNormalResponse();
3117 packet_result =
3118 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
3119 char ch = response.GetChar();
3120 if (ch == 'l')
3121 break;
3122 if (ch == 'm') {
3123 do {
3124 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
3125 // If we get an invalid response, break out of the loop.
3126 // If there are valid tids, they have been added to ids.
3127 // If there are no valid tids, we'll fall through to the
3128 // bare-iron target handling below.
3129 if (!pid_tid)
3130 break;
3131
3132 ids.push_back(*pid_tid);
3133 ch = response.GetChar(); // Skip the command separator
3134 } while (ch == ','); // Make sure we got a comma separator
3135 }
3136 }
3137
3138 /*
3139 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3140 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
3141 * could
3142 * be as simple as 'S05'. There is no packet which can give us pid and/or
3143 * tid.
3144 * Assume pid=tid=1 in such cases.
3145 */
3146 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
3147 ids.size() == 0 && IsConnected()) {
3148 ids.emplace_back(1, 1);
3149 }
3150 } else {
3152 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
3153 "packet 'qfThreadInfo'");
3154 sequence_mutex_unavailable = true;
3155 }
3156
3157 return ids;
3158}
3159
3161 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
3163 thread_ids.clear();
3164
3165 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
3166 if (ids.empty() || sequence_mutex_unavailable)
3167 return 0;
3168
3169 for (auto id : ids) {
3170 // skip threads that do not belong to the current process
3171 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
3172 continue;
3173 if (id.second != LLDB_INVALID_THREAD_ID &&
3175 thread_ids.push_back(id.second);
3176 }
3177
3178 return thread_ids.size();
3179}
3180
3182 StringExtractorGDBRemote response;
3183 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
3185 !response.IsNormalResponse())
3186 return LLDB_INVALID_ADDRESS;
3187 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3188}
3189
3191 llvm::StringRef command,
3192 const FileSpec &
3193 working_dir, // Pass empty FileSpec to use the current working directory
3194 int *status_ptr, // Pass NULL if you don't want the process exit status
3195 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
3196 // process to exit
3197 std::string
3198 *command_output, // Pass nullptr if you don't want the command output
3199 std::string *separated_error_output, // Pass nullptr if you don't want the
3200 // command error output
3201 const Timeout<std::micro> &timeout) {
3203 stream.PutCString("qPlatform_shell:");
3204 stream.PutBytesAsRawHex8(command.data(), command.size());
3205 stream.PutChar(',');
3206 uint32_t timeout_sec = UINT32_MAX;
3207 if (timeout) {
3208 // TODO: Use chrono version of std::ceil once c++17 is available.
3209 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
3210 }
3211 stream.PutHex32(timeout_sec);
3212 if (working_dir) {
3213 std::string path{working_dir.GetPath(false)};
3214 stream.PutChar(',');
3215 stream.PutStringAsRawHex8(path);
3216 }
3217 StringExtractorGDBRemote response;
3218 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3220 if (response.GetChar() != 'F')
3221 return Status::FromErrorString("malformed reply");
3222 if (response.GetChar() != ',')
3223 return Status::FromErrorString("malformed reply");
3224 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3225 if (exitcode == UINT32_MAX)
3226 return Status::FromErrorString("unable to run remote process");
3227 else if (status_ptr)
3228 *status_ptr = exitcode;
3229 if (response.GetChar() != ',')
3230 return Status::FromErrorString("malformed reply");
3231 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3232 if (signo_ptr)
3233 *signo_ptr = signo;
3234 if (response.GetChar() != ',')
3235 return Status::FromErrorString("malformed reply");
3236 std::string output;
3237 response.GetEscapedBinaryData(output);
3238 if (command_output)
3239 command_output->assign(output);
3240 return Status();
3241 }
3242 return Status::FromErrorString("unable to send packet");
3243}
3244
3246 uint32_t file_permissions) {
3247 std::string path{file_spec.GetPath(false)};
3249 stream.PutCString("qPlatform_mkdir:");
3250 stream.PutHex32(file_permissions);
3251 stream.PutChar(',');
3252 stream.PutStringAsRawHex8(path);
3253 llvm::StringRef packet = stream.GetString();
3254 StringExtractorGDBRemote response;
3255
3256 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3257 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3258 packet.str().c_str());
3259
3260 if (response.GetChar() != 'F')
3261 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3262 packet.str().c_str());
3263
3264 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3265}
3266
3267Status
3269 uint32_t file_permissions) {
3270 std::string path{file_spec.GetPath(false)};
3272 stream.PutCString("qPlatform_chmod:");
3273 stream.PutHex32(file_permissions);
3274 stream.PutChar(',');
3275 stream.PutStringAsRawHex8(path);
3276 llvm::StringRef packet = stream.GetString();
3277 StringExtractorGDBRemote response;
3278
3279 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3280 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3281 stream.GetData());
3282
3283 if (response.GetChar() != 'F')
3284 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3285 stream.GetData());
3286
3287 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3288}
3289
3290static int gdb_errno_to_system(int err) {
3291 switch (err) {
3292#define HANDLE_ERRNO(name, value) \
3293 case GDB_##name: \
3294 return name;
3295#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3296 default:
3297 return -1;
3298 }
3299}
3300
3302 uint64_t fail_result, Status &error) {
3303 response.SetFilePos(0);
3304 if (response.GetChar() != 'F')
3305 return fail_result;
3306 int32_t result = response.GetS32(-2, 16);
3307 if (result == -2)
3308 return fail_result;
3309 if (response.GetChar() == ',') {
3310 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3311 if (result_errno != -1)
3312 error = Status(result_errno, eErrorTypePOSIX);
3313 else
3315 } else
3316 error.Clear();
3317 return result;
3318}
3321 File::OpenOptions flags, mode_t mode,
3322 Status &error) {
3323 std::string path(file_spec.GetPath(false));
3325 stream.PutCString("vFile:open:");
3326 if (path.empty())
3327 return UINT64_MAX;
3328 stream.PutStringAsRawHex8(path);
3329 stream.PutChar(',');
3330 stream.PutHex32(flags);
3331 stream.PutChar(',');
3332 stream.PutHex32(mode);
3333 StringExtractorGDBRemote response;
3334 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3336 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3337 }
3338 return UINT64_MAX;
3339}
3340
3342 Status &error) {
3344 stream.Printf("vFile:close:%x", (int)fd);
3345 StringExtractorGDBRemote response;
3346 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3348 return ParseHostIOPacketResponse(response, -1, error) == 0;
3349 }
3350 return false;
3351}
3352
3353std::optional<GDBRemoteFStatData>
3356 stream.Printf("vFile:fstat:%" PRIx64, fd);
3357 StringExtractorGDBRemote response;
3358 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3360 if (response.GetChar() != 'F')
3361 return std::nullopt;
3362 int64_t size = response.GetS64(-1, 16);
3363 if (size > 0 && response.GetChar() == ';') {
3364 std::string buffer;
3365 if (response.GetEscapedBinaryData(buffer)) {
3367 if (buffer.size() != sizeof(out))
3368 return std::nullopt;
3369 memcpy(&out, buffer.data(), sizeof(out));
3370 return out;
3371 }
3372 }
3373 }
3374 return std::nullopt;
3375}
3376
3377std::optional<GDBRemoteFStatData>
3379 Status error;
3381 if (fd == UINT64_MAX)
3382 return std::nullopt;
3383 std::optional<GDBRemoteFStatData> st = FStat(fd);
3384 CloseFile(fd, error);
3385 return st;
3386}
3387
3388// Extension of host I/O packets to get the file size.
3390 const lldb_private::FileSpec &file_spec) {
3392 std::string path(file_spec.GetPath(false));
3394 stream.PutCString("vFile:size:");
3395 stream.PutStringAsRawHex8(path);
3396 StringExtractorGDBRemote response;
3397 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3399 return UINT64_MAX;
3400
3401 if (!response.IsUnsupportedResponse()) {
3402 if (response.GetChar() != 'F')
3403 return UINT64_MAX;
3404 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3405 return retcode;
3406 }
3407 m_supports_vFileSize = false;
3408 }
3409
3410 // Fallback to fstat.
3411 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3412 return st ? st->gdb_st_size : UINT64_MAX;
3413}
3414
3416 CompletionRequest &request, bool only_dir) {
3418 stream.PutCString("qPathComplete:");
3419 stream.PutHex32(only_dir ? 1 : 0);
3420 stream.PutChar(',');
3422 StringExtractorGDBRemote response;
3423 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3425 StreamString strm;
3426 char ch = response.GetChar();
3427 if (ch != 'M')
3428 return;
3429 while (response.Peek()) {
3430 strm.Clear();
3431 while ((ch = response.GetHexU8(0, false)) != '\0')
3432 strm.PutChar(ch);
3433 request.AddCompletion(strm.GetString());
3434 if (response.GetChar() != ',')
3435 break;
3436 }
3437 }
3438}
3439
3440Status
3442 uint32_t &file_permissions) {
3444 std::string path{file_spec.GetPath(false)};
3445 Status error;
3447 stream.PutCString("vFile:mode:");
3448 stream.PutStringAsRawHex8(path);
3449 StringExtractorGDBRemote response;
3450 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3452 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3453 stream.GetData());
3454 return error;
3455 }
3456 if (!response.IsUnsupportedResponse()) {
3457 if (response.GetChar() != 'F') {
3459 "invalid response to '%s' packet", stream.GetData());
3460 } else {
3461 const uint32_t mode = response.GetS32(-1, 16);
3462 if (static_cast<int32_t>(mode) == -1) {
3463 if (response.GetChar() == ',') {
3464 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3465 if (response_errno > 0)
3466 error = Status(response_errno, lldb::eErrorTypePOSIX);
3467 else
3468 error = Status::FromErrorString("unknown error");
3469 } else
3470 error = Status::FromErrorString("unknown error");
3471 } else {
3472 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3473 }
3474 }
3475 return error;
3476 } else { // response.IsUnsupportedResponse()
3477 m_supports_vFileMode = false;
3478 }
3479 }
3480
3481 // Fallback to fstat.
3482 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3483 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3484 return Status();
3485 }
3486 return Status::FromErrorString("fstat failed");
3487}
3488
3490 uint64_t offset, void *dst,
3491 uint64_t dst_len,
3492 Status &error) {
3494 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3495 offset);
3496 StringExtractorGDBRemote response;
3497 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3499 if (response.GetChar() != 'F')
3500 return 0;
3501 int64_t retcode = response.GetS64(-1, 16);
3502 if (retcode == -1) {
3503 error = Status::FromErrorString("unknown error");
3504 if (response.GetChar() == ',') {
3505 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3506 if (response_errno > 0)
3507 error = Status(response_errno, lldb::eErrorTypePOSIX);
3508 }
3509 return -1;
3510 }
3511 const char next = (response.Peek() ? *response.Peek() : 0);
3512 if (next == ',')
3513 return 0;
3514 if (next == ';') {
3515 response.GetChar(); // skip the semicolon
3516 std::string buffer;
3517 if (response.GetEscapedBinaryData(buffer)) {
3518 const uint64_t data_to_write =
3519 std::min<uint64_t>(dst_len, buffer.size());
3520 if (data_to_write > 0)
3521 memcpy(dst, &buffer[0], data_to_write);
3522 return data_to_write;
3523 }
3524 }
3525 }
3526 return 0;
3527}
3528
3530 uint64_t offset,
3531 const void *src,
3532 uint64_t src_len,
3533 Status &error) {
3535 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3536 stream.PutEscapedBytes(src, src_len);
3537 StringExtractorGDBRemote response;
3538 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3540 if (response.GetChar() != 'F') {
3541 error = Status::FromErrorStringWithFormat("write file failed");
3542 return 0;
3543 }
3544 int64_t bytes_written = response.GetS64(-1, 16);
3545 if (bytes_written == -1) {
3546 error = Status::FromErrorString("unknown error");
3547 if (response.GetChar() == ',') {
3548 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3549 if (response_errno > 0)
3550 error = Status(response_errno, lldb::eErrorTypePOSIX);
3551 }
3552 return -1;
3553 }
3554 return bytes_written;
3555 } else {
3556 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3557 }
3558 return 0;
3559}
3560
3562 const FileSpec &dst) {
3563 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3564 Status error;
3566 stream.PutCString("vFile:symlink:");
3567 // the unix symlink() command reverses its parameters where the dst if first,
3568 // so we follow suit here
3569 stream.PutStringAsRawHex8(dst_path);
3570 stream.PutChar(',');
3571 stream.PutStringAsRawHex8(src_path);
3572 StringExtractorGDBRemote response;
3573 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3575 if (response.GetChar() == 'F') {
3576 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3577 if (result != 0) {
3578 error = Status::FromErrorString("unknown error");
3579 if (response.GetChar() == ',') {
3580 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3581 if (response_errno > 0)
3582 error = Status(response_errno, lldb::eErrorTypePOSIX);
3583 }
3584 }
3585 } else {
3586 // Should have returned with 'F<result>[,<errno>]'
3587 error = Status::FromErrorStringWithFormat("symlink failed");
3588 }
3589 } else {
3590 error = Status::FromErrorString("failed to send vFile:symlink packet");
3591 }
3592 return error;
3593}
3594
3596 std::string path{file_spec.GetPath(false)};
3597 Status error;
3599 stream.PutCString("vFile:unlink:");
3600 // the unix symlink() command reverses its parameters where the dst if first,
3601 // so we follow suit here
3602 stream.PutStringAsRawHex8(path);
3603 StringExtractorGDBRemote response;
3604 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3606 if (response.GetChar() == 'F') {
3607 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3608 if (result != 0) {
3609 error = Status::FromErrorString("unknown error");
3610 if (response.GetChar() == ',') {
3611 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3612 if (response_errno > 0)
3613 error = Status(response_errno, lldb::eErrorTypePOSIX);
3614 }
3615 }
3616 } else {
3617 // Should have returned with 'F<result>[,<errno>]'
3618 error = Status::FromErrorStringWithFormat("unlink failed");
3619 }
3620 } else {
3621 error = Status::FromErrorString("failed to send vFile:unlink packet");
3622 }
3623 return error;
3624}
3625
3626// Extension of host I/O packets to get whether a file exists.
3628 const lldb_private::FileSpec &file_spec) {
3630 std::string path(file_spec.GetPath(false));
3632 stream.PutCString("vFile:exists:");
3633 stream.PutStringAsRawHex8(path);
3634 StringExtractorGDBRemote response;
3635 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3637 return false;
3638 if (!response.IsUnsupportedResponse()) {
3639 if (response.GetChar() != 'F')
3640 return false;
3641 if (response.GetChar() != ',')
3642 return false;
3643 bool retcode = (response.GetChar() != '0');
3644 return retcode;
3645 } else
3646 m_supports_vFileExists = false;
3647 }
3648
3649 // Fallback to open.
3650 Status error;
3652 if (fd == UINT64_MAX)
3653 return false;
3654 CloseFile(fd, error);
3655 return true;
3656}
3657
3658llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3659 const lldb_private::FileSpec &file_spec) {
3660 std::string path(file_spec.GetPath(false));
3662 stream.PutCString("vFile:MD5:");
3663 stream.PutStringAsRawHex8(path);
3664 StringExtractorGDBRemote response;
3665 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3667 if (response.GetChar() != 'F')
3668 return std::make_error_code(std::errc::illegal_byte_sequence);
3669 if (response.GetChar() != ',')
3670 return std::make_error_code(std::errc::illegal_byte_sequence);
3671 if (response.Peek() && *response.Peek() == 'x')
3672 return std::make_error_code(std::errc::no_such_file_or_directory);
3673
3674 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3675 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3676 // handle the concatenated hex string. What would happen is parsing the low
3677 // would consume the whole response packet which would give incorrect
3678 // results. Instead, we get the byte string for each low and high hex
3679 // separately, and parse them.
3680 //
3681 // An alternate way to handle this is to change the server to put a
3682 // delimiter between the low/high parts, and change the client to parse the
3683 // delimiter. However, we choose not to do this so existing lldb-servers
3684 // don't have to be patched
3685
3686 // The checksum is 128 bits encoded as hex
3687 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3688 // Each byte takes 2 hex characters in the response.
3689 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3690
3691 // Get low part
3692 auto part =
3693 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3694 if (part.size() != MD5_HALF_LENGTH)
3695 return std::make_error_code(std::errc::illegal_byte_sequence);
3696 response.SetFilePos(response.GetFilePos() + part.size());
3697
3698 uint64_t low;
3699 if (part.getAsInteger(BASE_16, low))
3700 return std::make_error_code(std::errc::illegal_byte_sequence);
3701
3702 // Get high part
3703 part =
3704 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3705 if (part.size() != MD5_HALF_LENGTH)
3706 return std::make_error_code(std::errc::illegal_byte_sequence);
3707 response.SetFilePos(response.GetFilePos() + part.size());
3708
3709 uint64_t high;
3710 if (part.getAsInteger(BASE_16, high))
3711 return std::make_error_code(std::errc::illegal_byte_sequence);
3712
3713 llvm::MD5::MD5Result result;
3714 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3715 result.data(), low);
3716 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3717 result.data() + 8, high);
3718
3719 return result;
3720 }
3721 return std::make_error_code(std::errc::operation_canceled);
3722}
3723
3725 // Some targets have issues with g/G packets and we need to avoid using them
3727 if (process) {
3729 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3730 if (arch.IsValid() &&
3731 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3732 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3733 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3734 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3736 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3737 if (gdb_server_version != 0) {
3738 const char *gdb_server_name = GetGDBServerProgramName();
3739 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3740 if (gdb_server_version >= 310)
3742 }
3743 }
3744 }
3745 }
3746 }
3748}
3749
3751 uint32_t reg) {
3752 StreamString payload;
3753 payload.Printf("p%x", reg);
3754 StringExtractorGDBRemote response;
3756 tid, std::move(payload), response) != PacketResult::Success ||
3757 !response.IsNormalResponse())
3758 return nullptr;
3759
3760 WritableDataBufferSP buffer_sp(
3761 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3762 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3763 return buffer_sp;
3764}
3765
3767 StreamString payload;
3768 payload.PutChar('g');
3769 StringExtractorGDBRemote response;
3771 tid, std::move(payload), response) != PacketResult::Success ||
3772 !response.IsNormalResponse())
3773 return nullptr;
3774
3775 WritableDataBufferSP buffer_sp(
3776 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3777 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3778 return buffer_sp;
3779}
3780
3782 uint32_t reg_num,
3783 llvm::ArrayRef<uint8_t> data) {
3784 StreamString payload;
3785 payload.Printf("P%x=", reg_num);
3786 payload.PutBytesAsRawHex8(data.data(), data.size(),
3789 StringExtractorGDBRemote response;
3791 tid, std::move(payload), response) == PacketResult::Success &&
3792 response.IsOKResponse();
3793}
3794
3796 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3797 StreamString payload;
3798 payload.PutChar('G');
3799 payload.PutBytesAsRawHex8(data.data(), data.size(),
3802 StringExtractorGDBRemote response;
3804 tid, std::move(payload), response) == PacketResult::Success &&
3805 response.IsOKResponse();
3806}
3807
3809 uint32_t &save_id) {
3810 save_id = 0; // Set to invalid save ID
3812 return false;
3813
3815 StreamString payload;
3816 payload.PutCString("QSaveRegisterState");
3817 StringExtractorGDBRemote response;
3819 tid, std::move(payload), response) != PacketResult::Success)
3820 return false;
3821
3822 if (response.IsUnsupportedResponse())
3824
3825 const uint32_t response_save_id = response.GetU32(0);
3826 if (response_save_id == 0)
3827 return false;
3828
3829 save_id = response_save_id;
3830 return true;
3831}
3832
3834 uint32_t save_id) {
3835 // We use the "m_supports_QSaveRegisterState" variable here because the
3836 // QSaveRegisterState and QRestoreRegisterState packets must both be
3837 // supported in order to be useful
3839 return false;
3840
3841 StreamString payload;
3842 payload.Printf("QRestoreRegisterState:%u", save_id);
3843 StringExtractorGDBRemote response;
3845 tid, std::move(payload), response) != PacketResult::Success)
3846 return false;
3847
3848 if (response.IsOKResponse())
3849 return true;
3850
3851 if (response.IsUnsupportedResponse())
3853 return false;
3854}
3855
3858 return false;
3859
3860 StreamString packet;
3861 StringExtractorGDBRemote response;
3862 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3863 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3865 response.IsOKResponse();
3866}
3867
3868llvm::Expected<TraceSupportedResponse>
3870 Log *log = GetLog(GDBRLog::Process);
3871
3872 StreamGDBRemote escaped_packet;
3873 escaped_packet.PutCString("jLLDBTraceSupported");
3874
3875 StringExtractorGDBRemote response;
3876 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3877 timeout) ==
3879 if (response.IsErrorResponse())
3880 return response.GetStatus().ToError();
3881 if (response.IsUnsupportedResponse())
3882 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3883 "jLLDBTraceSupported is unsupported");
3884
3885 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3886 "TraceSupportedResponse");
3887 }
3888 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3889 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3890 "failed to send packet: jLLDBTraceSupported");
3891}
3892
3893llvm::Error
3895 std::chrono::seconds timeout) {
3896 Log *log = GetLog(GDBRLog::Process);
3897
3898 StreamGDBRemote escaped_packet;
3899 escaped_packet.PutCString("jLLDBTraceStop:");
3900
3901 std::string json_string;
3902 llvm::raw_string_ostream os(json_string);
3903 os << toJSON(request);
3904
3905 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3906
3907 StringExtractorGDBRemote response;
3908 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3909 timeout) ==
3911 if (response.IsErrorResponse())
3912 return response.GetStatus().ToError();
3913 if (response.IsUnsupportedResponse())
3914 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3915 "jLLDBTraceStop is unsupported");
3916 if (response.IsOKResponse())
3917 return llvm::Error::success();
3918 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3919 "Invalid jLLDBTraceStart response");
3920 }
3921 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3922 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3923 "failed to send packet: jLLDBTraceStop '%s'",
3924 escaped_packet.GetData());
3925}
3926
3927llvm::Error
3928GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3929 std::chrono::seconds timeout) {
3930 Log *log = GetLog(GDBRLog::Process);
3931
3932 StreamGDBRemote escaped_packet;
3933 escaped_packet.PutCString("jLLDBTraceStart:");
3934
3935 std::string json_string;
3936 llvm::raw_string_ostream os(json_string);
3937 os << params;
3938
3939 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3940
3941 StringExtractorGDBRemote response;
3942 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3943 timeout) ==
3945 if (response.IsErrorResponse())
3946 return response.GetStatus().ToError();
3947 if (response.IsUnsupportedResponse())
3948 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3949 "jLLDBTraceStart is unsupported");
3950 if (response.IsOKResponse())
3951 return llvm::Error::success();
3952 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3953 "Invalid jLLDBTraceStart response");
3954 }
3955 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3956 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3957 "failed to send packet: jLLDBTraceStart '%s'",
3958 escaped_packet.GetData());
3959}
3960
3961llvm::Expected<std::string>
3963 std::chrono::seconds timeout) {
3964 Log *log = GetLog(GDBRLog::Process);
3965
3966 StreamGDBRemote escaped_packet;
3967 escaped_packet.PutCString("jLLDBTraceGetState:");
3968
3969 std::string json_string;
3970 llvm::raw_string_ostream os(json_string);
3971 os << toJSON(TraceGetStateRequest{type.str()});
3972
3973 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3974
3975 StringExtractorGDBRemote response;
3976 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3977 timeout) ==
3979 if (response.IsErrorResponse())
3980 return response.GetStatus().ToError();
3981 if (response.IsUnsupportedResponse())
3982 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3983 "jLLDBTraceGetState is unsupported");
3984 return std::string(response.Peek());
3985 }
3986
3987 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3988 return llvm::createStringError(
3989 llvm::inconvertibleErrorCode(),
3990 "failed to send packet: jLLDBTraceGetState '%s'",
3991 escaped_packet.GetData());
3992}
3993
3994llvm::Expected<std::vector<uint8_t>>
3996 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3997 Log *log = GetLog(GDBRLog::Process);
3998
3999 StreamGDBRemote escaped_packet;
4000 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
4001
4002 std::string json_string;
4003 llvm::raw_string_ostream os(json_string);
4004 os << toJSON(request);
4005
4006 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
4007
4008 StringExtractorGDBRemote response;
4009 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
4010 timeout) ==
4012 if (response.IsErrorResponse())
4013 return response.GetStatus().ToError();
4014 std::string data;
4015 response.GetEscapedBinaryData(data);
4016 return std::vector<uint8_t>(data.begin(), data.end());
4017 }
4018 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
4019 return llvm::createStringError(
4020 llvm::inconvertibleErrorCode(),
4021 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
4022 escaped_packet.GetData());
4023}
4024
4026 StringExtractorGDBRemote response;
4027 if (SendPacketAndWaitForResponse("qOffsets", response) !=
4029 return std::nullopt;
4030 if (!response.IsNormalResponse())
4031 return std::nullopt;
4032
4033 QOffsets result;
4034 llvm::StringRef ref = response.GetStringRef();
4035 const auto &GetOffset = [&] {
4036 addr_t offset;
4037 if (ref.consumeInteger(16, offset))
4038 return false;
4039 result.offsets.push_back(offset);
4040 return true;
4041 };
4042
4043 if (ref.consume_front("Text=")) {
4044 result.segments = false;
4045 if (!GetOffset())
4046 return std::nullopt;
4047 if (!ref.consume_front(";Data=") || !GetOffset())
4048 return std::nullopt;
4049 if (ref.empty())
4050 return result;
4051 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
4052 return result;
4053 } else if (ref.consume_front("TextSeg=")) {
4054 result.segments = true;
4055 if (!GetOffset())
4056 return std::nullopt;
4057 if (ref.empty())
4058 return result;
4059 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
4060 return result;
4061 }
4062 return std::nullopt;
4063}
4064
4066 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
4067 ModuleSpec &module_spec) {
4069 return false;
4070
4071 std::string module_path = module_file_spec.GetPath(false);
4072 if (module_path.empty())
4073 return false;
4074
4075 StreamString packet;
4076 packet.PutCString("qModuleInfo:");
4077 packet.PutStringAsRawHex8(module_path);
4078 packet.PutCString(";");
4079 const auto &triple = arch_spec.GetTriple().getTriple();
4080 packet.PutStringAsRawHex8(triple);
4081
4082 StringExtractorGDBRemote response;
4083 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
4085 return false;
4086
4087 if (response.IsErrorResponse())
4088 return false;
4089
4090 if (response.IsUnsupportedResponse()) {
4091 m_supports_qModuleInfo = false;
4092 return false;
4093 }
4094
4095 llvm::StringRef name;
4096 llvm::StringRef value;
4097
4098 module_spec.Clear();
4099 module_spec.GetFileSpec() = module_file_spec;
4100
4101 while (response.GetNameColonValue(name, value)) {
4102 if (name == "uuid" || name == "md5") {
4103 StringExtractor extractor(value);
4104 std::string uuid;
4105 extractor.GetHexByteString(uuid);
4106 module_spec.GetUUID().SetFromStringRef(uuid);
4107 } else if (name == "triple") {
4108 StringExtractor extractor(value);
4109 std::string triple;
4110 extractor.GetHexByteString(triple);
4111 module_spec.GetArchitecture().SetTriple(triple.c_str());
4112 } else if (name == "file_offset") {
4113 uint64_t ival = 0;
4114 if (!value.getAsInteger(BASE_16, ival))
4115 module_spec.SetObjectOffset(ival);
4116 } else if (name == "file_size") {
4117 uint64_t ival = 0;
4118 if (!value.getAsInteger(BASE_16, ival))
4119 module_spec.SetObjectSize(ival);
4120 } else if (name == "file_path") {
4121 StringExtractor extractor(value);
4122 std::string path;
4123 extractor.GetHexByteString(path);
4124 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
4125 }
4126 }
4127
4128 return true;
4129}
4130
4131static std::optional<ModuleSpec>
4133 ModuleSpec result;
4134 if (!dict)
4135 return std::nullopt;
4136
4137 llvm::StringRef string;
4138 uint64_t integer;
4139
4140 if (!dict->GetValueForKeyAsString("uuid", string))
4141 return std::nullopt;
4142 if (!result.GetUUID().SetFromStringRef(string))
4143 return std::nullopt;
4144
4145 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
4146 return std::nullopt;
4147 result.SetObjectOffset(integer);
4148
4149 if (!dict->GetValueForKeyAsInteger("file_size", integer))
4150 return std::nullopt;
4151 result.SetObjectSize(integer);
4152
4153 if (!dict->GetValueForKeyAsString("triple", string))
4154 return std::nullopt;
4155 result.GetArchitecture().SetTriple(string);
4156
4157 if (!dict->GetValueForKeyAsString("file_path", string))
4158 return std::nullopt;
4159 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
4160
4161 return result;
4162}
4163
4164std::optional<std::vector<ModuleSpec>>
4166 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4167 namespace json = llvm::json;
4168
4170 return std::nullopt;
4171
4172 json::Array module_array;
4173 for (const FileSpec &module_file_spec : module_file_specs) {
4174 module_array.push_back(
4175 json::Object{{"file", module_file_spec.GetPath(false)},
4176 {"triple", triple.getTriple()}});
4177 }
4178 StreamString unescaped_payload;
4179 unescaped_payload.PutCString("jModulesInfo:");
4180 unescaped_payload.AsRawOstream() << std::move(module_array);
4181
4182 StreamGDBRemote payload;
4183 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
4184 unescaped_payload.GetSize());
4185
4186 // Increase the timeout for jModulesInfo since this packet can take longer.
4187 ScopedTimeout timeout(*this, std::chrono::seconds(10));
4188
4189 StringExtractorGDBRemote response;
4190 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
4192 response.IsErrorResponse())
4193 return std::nullopt;
4194
4195 if (response.IsUnsupportedResponse()) {
4197 return std::nullopt;
4198 }
4199
4200 StructuredData::ObjectSP response_object_sp =
4202 if (!response_object_sp)
4203 return std::nullopt;
4204
4205 StructuredData::Array *response_array = response_object_sp->GetAsArray();
4206 if (!response_array)
4207 return std::nullopt;
4208
4209 std::vector<ModuleSpec> result;
4210 for (size_t i = 0; i < response_array->GetSize(); ++i) {
4211 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4212 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4213 result.push_back(*module_spec);
4214 }
4215
4216 return result;
4217}
4218
4219// query the target remote for extended information using the qXfer packet
4220//
4221// example: object='features', annex='target.xml'
4222// return: <xml output> or error
4223llvm::Expected<std::string>
4225 llvm::StringRef annex) {
4226
4227 std::string output;
4228 llvm::raw_string_ostream output_stream(output);
4230
4231 uint64_t size = GetRemoteMaxPacketSize();
4232 if (size == 0)
4233 size = 0x1000;
4234 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4235 int offset = 0;
4236 bool active = true;
4237
4238 // loop until all data has been read
4239 while (active) {
4240
4241 // send query extended feature packet
4242 std::string packet =
4243 ("qXfer:" + object + ":read:" + annex + ":" +
4244 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4245 .str();
4246
4248 SendPacketAndWaitForResponse(packet, chunk);
4249
4251 chunk.GetStringRef().empty()) {
4252 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4253 "Error sending $qXfer packet");
4254 }
4255
4256 // check packet code
4257 switch (chunk.GetStringRef()[0]) {
4258 // last chunk
4259 case ('l'):
4260 active = false;
4261 [[fallthrough]];
4262
4263 // more chunks
4264 case ('m'):
4265 output_stream << chunk.GetStringRef().drop_front();
4266 offset += chunk.GetStringRef().size() - 1;
4267 break;
4268
4269 // unknown chunk
4270 default:
4271 return llvm::createStringError(
4272 llvm::inconvertibleErrorCode(),
4273 "Invalid continuation code from $qXfer packet");
4274 }
4275 }
4276
4277 return output;
4278}
4279
4280llvm::Expected<std::string>
4282 // qXfer:siginfo:read returns the siginfo of the thread selected by the Hg
4283 // packet. Hold the lock to make sure nobody selects a different thread
4284 // before we're done.
4285 Lock lock(*this);
4286 if (!lock)
4287 return llvm::createStringError("failed to get the sequence mutex");
4288 if (!SetCurrentThread(tid))
4289 return llvm::createStringError("failed to select thread");
4290 return ReadExtFeature("siginfo", "");
4291}
4292
4293// Notify the target that gdb is prepared to serve symbol lookup requests.
4294// packet: "qSymbol::"
4295// reply:
4296// OK The target does not need to look up any (more) symbols.
4297// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4298// encoded).
4299// LLDB may provide the value by sending another qSymbol
4300// packet
4301// in the form of"qSymbol:<sym_value>:<sym_name>".
4302//
4303// Three examples:
4304//
4305// lldb sends: qSymbol::
4306// lldb receives: OK
4307// Remote gdb stub does not need to know the addresses of any symbols, lldb
4308// does not
4309// need to ask again in this session.
4310//
4311// lldb sends: qSymbol::
4312// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4313// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4314// lldb receives: OK
4315// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4316// not know
4317// the address at this time. lldb needs to send qSymbol:: again when it has
4318// more
4319// solibs loaded.
4320//
4321// lldb sends: qSymbol::
4322// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4323// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4324// lldb receives: OK
4325// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4326// that it
4327// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4328// does not
4329// need any more symbols. lldb does not need to ask again in this session.
4330
4332 lldb_private::Process *process) {
4333 // Set to true once we've resolved a symbol to an address for the remote
4334 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4335 // any more symbols and we can stop asking.
4336 bool symbol_response_provided = false;
4337
4338 // Is this the initial qSymbol:: packet?
4339 bool first_qsymbol_query = true;
4340
4342 Lock lock(*this);
4343 if (lock) {
4344 StreamString packet;
4345 packet.PutCString("qSymbol::");
4346 StringExtractorGDBRemote response;
4347 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4349 if (response.IsOKResponse()) {
4350 if (symbol_response_provided || first_qsymbol_query) {
4352 }
4353
4354 // We are done serving symbols requests
4355 return;
4356 }
4357 first_qsymbol_query = false;
4358
4359 if (response.IsUnsupportedResponse()) {
4360 // qSymbol is not supported by the current GDB server we are
4361 // connected to
4362 m_supports_qSymbol = false;
4363 return;
4364 } else {
4365 llvm::StringRef response_str(response.GetStringRef());
4366 if (response_str.starts_with("qSymbol:")) {
4367 response.SetFilePos(strlen("qSymbol:"));
4368 std::string symbol_name;
4369 if (response.GetHexByteString(symbol_name)) {
4370 if (symbol_name.empty())
4371 return;
4372
4373 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4376 symbol_name, eSymbolTypeAny, sc_list);
4377 for (const SymbolContext &sc : sc_list) {
4378 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4379 break;
4380 if (sc.symbol) {
4381 switch (sc.symbol->GetType()) {
4382 case eSymbolTypeInvalid:
4389 case eSymbolTypeBlock:
4390 case eSymbolTypeLocal:
4391 case eSymbolTypeParam:
4402 case eSymbolTypeASTFile:
4403 if (sc.module_sp->GetArchitecture()
4404 .GetTriple()
4405 .getObjectFormat() !=
4406 llvm::Triple::ObjectFormatType::MachO) {
4407 // GDB does return symbols even when they are of unknown
4408 // type, following this behavior on non Mach-O
4409 // architectures.
4410 symbol_load_addr =
4411 sc.symbol->GetLoadAddress(&process->GetTarget());
4412 if (symbol_load_addr == LLDB_INVALID_ADDRESS) {
4413 symbol_load_addr = sc.symbol->GetRawValue();
4414 }
4415 }
4416 break;
4417
4418 case eSymbolTypeCode:
4420 case eSymbolTypeData:
4421 case eSymbolTypeRuntime:
4427 symbol_load_addr =
4428 sc.symbol->GetLoadAddress(&process->GetTarget());
4429 break;
4430 }
4431 }
4432 }
4433 // This is the normal path where our symbol lookup was successful
4434 // and we want to send a packet with the new symbol value and see
4435 // if another lookup needs to be done.
4436
4437 // Change "packet" to contain the requested symbol value and name
4438 packet.Clear();
4439 packet.PutCString("qSymbol:");
4440 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4441 packet.Printf("%" PRIx64, symbol_load_addr);
4442 symbol_response_provided = true;
4443 } else {
4444 symbol_response_provided = false;
4445 }
4446 packet.PutCString(":");
4447 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4448 continue; // go back to the while loop and send "packet" and wait
4449 // for another response
4450 }
4451 }
4452 }
4453 }
4454 // If we make it here, the symbol request packet response wasn't valid or
4455 // our symbol lookup failed so we must abort
4456 return;
4457
4458 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4459 LLDB_LOGF(log,
4460 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4461 __FUNCTION__);
4462 }
4463 }
4464}
4465
4469 // Query the server for the array of supported asynchronous JSON packets.
4471
4472 Log *log = GetLog(GDBRLog::Process);
4473
4474 // Poll it now.
4475 StringExtractorGDBRemote response;
4476 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4481 !m_supported_async_json_packets_sp->GetAsArray()) {
4482 // We were returned something other than a JSON array. This is
4483 // invalid. Clear it out.
4484 LLDB_LOGF(log,
4485 "GDBRemoteCommunicationClient::%s(): "
4486 "QSupportedAsyncJSONPackets returned invalid "
4487 "result: %s",
4488 __FUNCTION__, response.GetStringRef().data());
4490 }
4491 } else {
4492 LLDB_LOGF(log,
4493 "GDBRemoteCommunicationClient::%s(): "
4494 "QSupportedAsyncJSONPackets unsupported",
4495 __FUNCTION__);
4496 }
4497
4499 StreamString stream;
4501 LLDB_LOGF(log,
4502 "GDBRemoteCommunicationClient::%s(): supported async "
4503 "JSON packets: %s",
4504 __FUNCTION__, stream.GetData());
4505 }
4506 }
4507
4509 ? m_supported_async_json_packets_sp->GetAsArray()
4510 : nullptr;
4511}
4512
4514 llvm::ArrayRef<int32_t> signals) {
4515 // Format packet:
4516 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4517 auto range = llvm::make_range(signals.begin(), signals.end());
4518 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4519
4520 StringExtractorGDBRemote response;
4521 auto send_status = SendPacketAndWaitForResponse(packet, response);
4522
4524 return Status::FromErrorString("Sending QPassSignals packet failed");
4525
4526 if (response.IsOKResponse()) {
4527 return Status();
4528 } else {
4530 "Unknown error happened during sending QPassSignals packet.");
4531 }
4532}
4533
4535 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4536 Status error;
4537
4538 if (type_name.empty()) {
4539 error = Status::FromErrorString("invalid type_name argument");
4540 return error;
4541 }
4542
4543 // Build command: Configure{type_name}: serialized config data.
4544 StreamGDBRemote stream;
4545 stream.PutCString("QConfigure");
4546 stream.PutCString(type_name);
4547 stream.PutChar(':');
4548 if (config_sp) {
4549 // Gather the plain-text version of the configuration data.
4550 StreamString unescaped_stream;
4551 config_sp->Dump(unescaped_stream);
4552 unescaped_stream.Flush();
4553
4554 // Add it to the stream in escaped fashion.
4555 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4556 unescaped_stream.GetSize());
4557 }
4558 stream.Flush();
4559
4560 // Send the packet.
4561 StringExtractorGDBRemote response;
4562 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4563 if (result == PacketResult::Success) {
4564 // We failed if the config result comes back other than OK.
4565 if (response.GetStringRef() == "OK") {
4566 // Okay!
4567 error.Clear();
4568 } else {
4570 "configuring StructuredData feature {0} failed with error {1}",
4571 type_name, response.GetStringRef());
4572 }
4573 } else {
4574 // Can we get more data here on the failure?
4576 "configuring StructuredData feature {0} failed when sending packet: "
4577 "PacketResult={1}",
4578 type_name, (int)result);
4579 }
4580 return error;
4581}
4582
4587
4592 return true;
4593
4594 // If the remote didn't indicate native-signal support explicitly,
4595 // check whether it is an old version of lldb-server.
4596 return GetThreadSuffixSupported();
4597}
4598
4600 StringExtractorGDBRemote response;
4601 GDBRemoteCommunication::ScopedTimeout timeout(*this, seconds(3));
4602
4603 // LLDB server typically sends no response for "k", so we shouldn't try
4604 // to sync on timeout.
4605 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout(), false) !=
4607 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4608 "failed to send k packet");
4609
4610 char packet_cmd = response.GetChar(0);
4611 if (packet_cmd == 'W' || packet_cmd == 'X')
4612 return response.GetHexU8();
4613
4614 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4615 "unexpected response to k packet: %s",
4616 response.GetStringRef().str().c_str());
4617}
static llvm::raw_ostream & error(Stream &strm)
#define integer
duration< float > calculate_standard_deviation(const std::vector< duration< float > > &v)
static std::optional< ModuleSpec > ParseModuleSpec(StructuredData::Dictionary *dict)
static int gdb_errno_to_system(int err)
static void ParseOSType(llvm::StringRef value, std::string &os_name, std::string &environment)
static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, uint64_t fail_result, Status &error)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static constexpr lldb::tid_t AllThreads
size_t GetEscapedBinaryData(std::string &str)
static constexpr lldb::pid_t AllProcesses
std::optional< std::pair< lldb::pid_t, lldb::tid_t > > GetPidTid(lldb::pid_t default_pid)
void SetFilePos(uint32_t idx)
int64_t GetS64(int64_t fail_value, int base=0)
uint32_t GetHexMaxU32(bool little_endian, uint32_t fail_value)
uint64_t GetHexMaxU64(bool little_endian, uint64_t fail_value)
bool GetNameColonValue(llvm::StringRef &name, llvm::StringRef &value)
uint64_t GetU64(uint64_t fail_value, int base=0)
size_t GetHexBytesAvail(llvm::MutableArrayRef< uint8_t > dest)
size_t GetHexByteString(std::string &str)
uint8_t GetHexU8(uint8_t fail_value=0, bool set_eof_on_fail=true)
char GetChar(char fail_value='\0')
const char * Peek()
int32_t GetS32(int32_t fail_value, int base=0)
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
uint64_t GetFilePos() const
llvm::StringRef GetStringRef() const
uint32_t GetU32(uint32_t fail_value, int base=0)
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
void SetAddressableBits(uint32_t addressing_bits)
When a single value is available for the number of bits.
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:375
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:768
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition ArchSpec.cpp:909
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
const char * GetArgumentAtIndex(size_t idx) const
Gets the null-terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
void Clear()
Clear the arguments.
Definition Args.cpp:388
bool IsConnected() const
Check if the connection is valid.
virtual lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
llvm::StringRef GetCursorArgumentPrefix() const
A subclass of DataBuffer that stores a data buffer on the heap.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
MemoryRegionInfo & SetMemoryTagged(LazyBool val)
void SetBlocksize(lldb::offset_t blocksize)
void SetName(const char *name)
MemoryRegionInfo & SetIsShadowStack(LazyBool val)
lldb::offset_t GetBlocksize() const
MemoryRegionInfo & SetIsStackMemory(LazyBool val)
void SetDirtyPageList(std::vector< lldb::addr_t > pagelist)
MemoryRegionInfo & SetProtectionKey(std::optional< unsigned > key)
void FindSymbolsWithNameAndType(llvm::StringRef name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:119
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:113
void SetGroupID(uint32_t gid)
Definition ProcessInfo.h:58
bool ProcessIDIsValid() const
Definition ProcessInfo.h:70
void SetArg0(llvm::StringRef arg)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:68
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
llvm::StringRef GetName() const
uint32_t GetUserID() const
Definition ProcessInfo.h:48
uint32_t GetGroupID() const
Definition ProcessInfo.h:50
void SetUserID(uint32_t uid)
Definition ProcessInfo.h:56
bool GroupIDIsValid() const
Definition ProcessInfo.h:54
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:60
ProcessInstanceInfo & GetProcessInfo()
void SetEffectiveGroupID(uint32_t gid)
lldb::pid_t GetParentProcessID() const
void SetParentProcessID(lldb::pid_t pid)
void SetEffectiveUserID(uint32_t uid)
A plug-in interface definition class for debugging a process.
Definition Process.h:370
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1271
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
int PutAsJSON(const T &obj, bool hex_ascii)
Definition GDBRemote.h:50
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:31
const char * GetData() const
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:418
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:307
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:291
virtual void Flush()=0
Flush the stream.
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:391
ObjectSP GetItemAtIndex(size_t idx) const
std::optional< Dictionary * > GetItemAtIndexAsDictionary(size_t idx) const
Retrieves the element at index idx from a StructuredData::Array if it is a Dictionary.
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
ObjectSP GetValueForKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(llvm::StringRef json_text)
Defines a list of symbol context objects.
Defines a symbol context baton that can be handed other debug core functions.
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
Represents UUID's of various sizes.
Definition UUID.h:27
bool SetFromStringRef(llvm::StringRef str)
Definition UUID.cpp:101
static bool XMLEnabled()
Definition XML.cpp:83
XMLNode GetRootElement(const char *required_name=nullptr)
Definition XML.cpp:65
bool ParseMemory(const char *xml, size_t xml_length, const char *url="untitled.xml")
Definition XML.cpp:54
void ForEachChildElement(NodeCallback const &callback) const
Definition XML.cpp:169
llvm::StringRef GetName() const
Definition XML.cpp:268
std::string GetAttributeValue(const char *name, const char *fail_value=nullptr) const
Definition XML.cpp:135
bool GetElementTextAsUnsigned(uint64_t &value, uint64_t fail_value=0, int base=0) const
Definition XML.cpp:299
bool GetAttributeValueAsUnsigned(const char *name, uint64_t &value, uint64_t fail_value=0, int base=0) const
Definition XML.cpp:156
bool IsElement() const
Definition XML.cpp:345
PacketResult SendPacketAndWaitForResponse(llvm::StringRef payload, StringExtractorGDBRemote &response, std::chrono::seconds interrupt_timeout=std::chrono::seconds(0), bool sync_on_timeout=true)
PacketResult SendPacketAndWaitForResponseNoLock(llvm::StringRef payload, StringExtractorGDBRemote &response, bool sync_on_timeout=true)
lldb::DataBufferSP ReadRegister(lldb::tid_t tid, uint32_t reg_num)
PacketResult SendThreadSpecificPacketAndWaitForResponse(lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response)
llvm::Expected< StringExtractorGDBRemote > LaunchProcess(const Args &args)
Launch the process using the provided arguments.
bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
llvm::Expected< std::string > ReadSiginfo(lldb::tid_t tid)
Read the siginfo of the given thread using the qXfer:siginfo:read packet.
lldb_private::StructuredData::Array * GetSupportedStructuredDataPlugins()
Return the array of async JSON packet types supported by the remote.
lldb::tid_t m_curr_tid_run
Current gdb remote protocol thread identifier for continue, step, etc.
int SetSTDIOWindowSize(uint16_t cols, uint16_t rows)
Send the dimensions of the user's stdio terminal window to the server.
int SendLaunchEventDataPacket(const char *data, bool *was_supported=nullptr)
std::optional< std::vector< ModuleSpec > > GetModulesInfo(llvm::ArrayRef< FileSpec > module_file_specs, const llvm::Triple &triple)
llvm::Expected< std::string > ReadExtFeature(llvm::StringRef object, llvm::StringRef annex)
std::optional< GDBRemoteFStatData > Stat(const FileSpec &file_spec)
std::optional< QOffsets > GetQOffsets()
Use qOffsets to query the offset used when relocating the target executable.
size_t QueryGDBServer(std::vector< std::pair< uint16_t, std::string > > &connection_urls)
llvm::Error SendTraceStop(const TraceStopRequest &request, std::chrono::seconds interrupt_timeout)
void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, uint64_t recv_amount, bool json, Stream &strm)
std::optional< LLDBSettings > GetLLDBSettings()
Return LLDB-specific settings for this GDB-remote process.
bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, std::string &socket_name)
bool SetCurrentThreadForRun(uint64_t tid, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
uint8_t SendGDBStoppointTypePacket(GDBStoppointType type, bool insert, lldb::addr_t addr, uint32_t length, std::chrono::seconds interrupt_timeout)
uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error)
bool GetWorkingDir(FileSpec &working_dir)
Gets the current working directory of a remote platform GDB server.
lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, mode_t mode, Status &error)
std::optional< GDBRemoteFStatData > FStat(lldb::user_id_t fd)
Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *separated_error_output, const Timeout< std::micro > &timeout)
llvm::Expected< std::string > SendTraceGetState(llvm::StringRef type, std::chrono::seconds interrupt_timeout)
Status ConfigureRemoteStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure a StructuredData feature on the remote end.
uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error)
llvm::Expected< std::vector< AcceleratorActions > > GetAcceleratorInitializeActions()
Send the "jAcceleratorPluginInitialize" packet and return the actions requested by each accelerator p...
bool SetCurrentThread(uint64_t tid, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
int SendStdinNotification(const char *data, size_t data_len, std::chrono::seconds interrupt_timeout=std::chrono::seconds(0))
Sends a GDB remote protocol 'I' packet that delivers stdin data to the remote process.
lldb::tid_t m_curr_tid
Current gdb remote protocol thread identifier for all other operations.
bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef< uint8_t > data)
bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info)
Status SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions)
Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr, MemoryRegionInfo &region)
std::vector< AddressSpaceInfo > GetAddressSpaces()
Empty if the server does not support "jAddressSpacesInfo".
int SetDetachOnError(bool enable)
Sets the DetachOnError flag to enable for the process controlled by the stub.
LazyBool GetThreadPacketSupported(lldb::tid_t tid, llvm::StringRef packetStr)
bool WriteRegister(lldb::tid_t tid, uint32_t reg_num, llvm::ArrayRef< uint8_t > data)
llvm::Expected< std::vector< uint8_t > > SendTraceGetBinaryData(const TraceGetBinaryDataRequest &request, std::chrono::seconds interrupt_timeout)
int SetSTDIN(const FileSpec &file_spec)
Sets the path to use for stdin/out/err for a process that will be launched with the 'A' packet.
lldb::pid_t m_curr_pid
Current gdb remote protocol process identifier for all other operations.
Status WriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, const std::vector< uint8_t > &tags)
size_t GetCurrentThreadIDs(std::vector< lldb::tid_t > &thread_ids, bool &sequence_mutex_unavailable)
Status Detach(bool keep_stopped, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
int SetDisableASLR(bool enable)
Sets the disable ASLR flag to enable for a process that will be launched with the 'A' packet.
Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info)
bool GetWasmInstanceSupported()
Whether the WebAssembly stub can be told which module instance to read from, which it advertises with...
std::optional< AcceleratorDynamicLoaderResponse > GetAcceleratorDynamicLoaderLibraryInfos(const AcceleratorDynamicLoaderArgs &args)
Returns std::nullopt if the packet failed or the response did not parse.
void AutoCompleteDiskFileOrDirectory(CompletionRequest &request, bool only_dir)
lldb::pid_t m_curr_pid_run
Current gdb remote protocol process identifier for continue, step, etc.
void MaybeEnableCompression(llvm::ArrayRef< llvm::StringRef > supported_compressions)
llvm::Expected< TraceSupportedResponse > SendTraceSupported(std::chrono::seconds interrupt_timeout)
llvm::ErrorOr< llvm::MD5::MD5Result > CalculateMD5(const FileSpec &file_spec)
llvm::Error SendTraceStart(const llvm::json::Value &request, std::chrono::seconds interrupt_timeout)
llvm::Expected< AcceleratorBreakpointHitResponse > AcceleratorBreakpointHit(const AcceleratorBreakpointHitArgs &args)
Send the "jAcceleratorPluginBreakpointHit" packet to notify the accelerator plugin that one of its re...
bool GetModuleInfo(const FileSpec &module_file_spec, const ArchSpec &arch_spec, ModuleSpec &module_spec)
std::optional< PidTid > SendSetCurrentThreadPacket(uint64_t tid, uint64_t pid, char op)
Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions)
uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info, ProcessInstanceInfoList &process_infos)
lldb::DataBufferSP ReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type)
int SetWorkingDir(const FileSpec &working_dir)
Sets the working directory to path for a process that will be launched with the 'A' packet for non pl...
std::vector< std::pair< lldb::pid_t, lldb::tid_t > > GetCurrentProcessAndThreadIDs(bool &sequence_mutex_unavailable)
bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response)
bool GetProcessStandaloneBinary(UUID &uuid, lldb::addr_t &value, bool &value_is_offset)
int SendEnvironmentPacket(char const *name_equal_value)
Sends a "QEnvironment:NAME=VALUE" packet that will build up the environment that will get used when l...
std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout)
#define UINT64_MAX
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_CPUTYPE
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const QOffsets &offsets)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
llvm::json::Value toJSON(const Diagnostics::Report &report)
Render a diagnostics report as JSON, for diagnostics dump's terminal output.
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
@ eErrorTypeGeneric
Generic errors that can be any value.
@ eErrorTypePOSIX
POSIX error codes.
@ eSymbolTypeUndefined
@ eSymbolTypeVariableType
@ eSymbolTypeObjCMetaClass
@ eSymbolTypeReExported
@ eSymbolTypeObjCClass
@ eSymbolTypeObjectFile
@ eSymbolTypeTrampoline
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeException
@ eSymbolTypeVariable
@ eSymbolTypeASTFile
The symbol's name is the path to a compiler AST file.
@ eSymbolTypeAbsolute
@ eSymbolTypeAdditional
When symbols take more than one entry, the extra entries get this type.
@ eSymbolTypeInstrumentation
@ eSymbolTypeHeaderFile
@ eSymbolTypeCommonBlock
@ eSymbolTypeCompiler
@ eSymbolTypeLineHeader
@ eSymbolTypeObjCIVar
@ eSymbolTypeLineEntry
@ eSymbolTypeScopeBegin
@ eSymbolTypeScopeEnd
uint64_t pid_t
Definition lldb-types.h:84
ByteOrder
Byte ordering definitions.
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
uint64_t tid_t
Definition lldb-types.h:85
Sent by the client when a plugin-requested breakpoint is hit.
Arguments for the jAcceleratorPluginGetDynamicLoaderLibraryInfo packet.
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
bool IsValid() const
Definition RangeMap.h:91
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
BaseType GetRangeEnd() const
Definition RangeMap.h:78
void SetByteSize(SizeType s)
Definition RangeMap.h:89
jLLDBTraceGetBinaryData gdb-remote packet
jLLDBTraceStop gdb-remote packet
The offsets used by the target when relocating the executable.
bool segments
If true, the offsets field describes segments.
std::vector< uint64_t > offsets
The individual offsets.
#define S_IRWXG
#define S_IRWXO
#define S_IRWXU