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
979 if (!args.GetArgumentAtIndex(0))
980 return llvm::createStringError(llvm::inconvertibleErrorCode(),
981 "Nothing to launch");
982 // try vRun first
983 if (m_supports_vRun) {
984 StreamString packet;
985 packet.PutCString("vRun");
986 for (const Args::ArgEntry &arg : args) {
987 packet.PutChar(';');
988 packet.PutStringAsRawHex8(arg.ref());
989 }
990
992 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
994 return llvm::createStringError(llvm::inconvertibleErrorCode(),
995 "Sending vRun packet failed");
996
997 if (response.IsErrorResponse())
998 return response.GetStatus().ToError();
999
1000 // vRun replies with a stop reason packet
1001 // FIXME: right now we just discard the packet and LLDB queries
1002 // for stop reason again
1003 if (!response.IsUnsupportedResponse())
1004 return llvm::Error::success();
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 StringExtractorGDBRemote response;
1020 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1022 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1023 "Sending A packet failed");
1024 }
1025 if (!response.IsOKResponse())
1026 return response.GetStatus().ToError();
1027
1028 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
1030 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1031 "Sending qLaunchSuccess packet failed");
1032 }
1033 if (response.IsOKResponse())
1034 return llvm::Error::success();
1035 if (response.GetChar() == 'E') {
1036 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1037 response.GetStringRef().substr(1));
1038 }
1039 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1040 "unknown error occurred launching process");
1041}
1042
1044 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
1045 for (const auto &kv : env)
1046 vec.emplace_back(kv.first(), kv.second);
1047 llvm::sort(vec, llvm::less_first());
1048 for (const auto &[k, v] : vec) {
1049 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
1050 if (r != 0)
1051 return r;
1052 }
1053 return 0;
1054}
1055
1057 char const *name_equal_value) {
1058 if (name_equal_value && name_equal_value[0]) {
1059 bool send_hex_encoding = false;
1060 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
1061 ++p) {
1062 if (llvm::isPrint(*p)) {
1063 switch (*p) {
1064 case '$':
1065 case '#':
1066 case '*':
1067 case '}':
1068 send_hex_encoding = true;
1069 break;
1070 default:
1071 break;
1072 }
1073 } else {
1074 // We have non printable characters, lets hex encode this...
1075 send_hex_encoding = true;
1076 }
1077 }
1078
1079 StringExtractorGDBRemote response;
1080 // Prefer sending unencoded, if possible and the server supports it.
1081 if (!send_hex_encoding && m_supports_QEnvironment) {
1082 StreamString packet;
1083 packet.Printf("QEnvironment:%s", name_equal_value);
1084 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1086 return -1;
1087
1088 if (response.IsOKResponse())
1089 return 0;
1090 if (response.IsUnsupportedResponse())
1092 else {
1093 uint8_t error = response.GetError();
1094 if (error)
1095 return error;
1096 return -1;
1097 }
1098 }
1099
1101 StreamString packet;
1102 packet.PutCString("QEnvironmentHexEncoded:");
1103 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
1104 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1106 return -1;
1107
1108 if (response.IsOKResponse())
1109 return 0;
1110 if (response.IsUnsupportedResponse())
1112 else {
1113 uint8_t error = response.GetError();
1114 if (error)
1115 return error;
1116 return -1;
1117 }
1118 }
1119 }
1120 return -1;
1121}
1122
1124 if (arch && arch[0]) {
1125 StreamString packet;
1126 packet.Printf("QLaunchArch:%s", arch);
1127 StringExtractorGDBRemote response;
1128 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1130 if (response.IsOKResponse())
1131 return 0;
1132 uint8_t error = response.GetError();
1133 if (error)
1134 return error;
1135 }
1136 }
1137 return -1;
1138}
1139
1141 char const *data, bool *was_supported) {
1142 if (data && *data != '\0') {
1143 StreamString packet;
1144 packet.Printf("QSetProcessEvent:%s", data);
1145 StringExtractorGDBRemote response;
1146 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1148 if (response.IsOKResponse()) {
1149 if (was_supported)
1150 *was_supported = true;
1151 return 0;
1152 } else if (response.IsUnsupportedResponse()) {
1153 if (was_supported)
1154 *was_supported = false;
1155 return -1;
1156 } else {
1157 uint8_t error = response.GetError();
1158 if (was_supported)
1159 *was_supported = true;
1160 if (error)
1161 return error;
1162 }
1163 }
1164 }
1165 return -1;
1166}
1167
1169 GetHostInfo();
1170 return m_os_version;
1171}
1172
1177
1179 if (GetHostInfo()) {
1180 if (!m_os_build.empty())
1181 return m_os_build;
1182 }
1183 return std::nullopt;
1184}
1185
1186std::optional<std::string>
1188 if (GetHostInfo()) {
1189 if (!m_os_kernel.empty())
1190 return m_os_kernel;
1191 }
1192 return std::nullopt;
1193}
1194
1196 if (GetHostInfo()) {
1197 if (!m_hostname.empty()) {
1198 s = m_hostname;
1199 return true;
1200 }
1201 }
1202 s.clear();
1203 return false;
1204}
1205
1211
1218
1220 UUID &uuid, addr_t &value, bool &value_is_offset) {
1223
1224 // Return true if we have a UUID or an address/offset of the
1225 // main standalone / firmware binary being used.
1226 if (!m_process_standalone_uuid.IsValid() &&
1228 return false;
1229
1232 value_is_offset = m_process_standalone_value_is_offset;
1233 return true;
1234}
1235
1236std::vector<addr_t>
1242
1243std::vector<AddressSpaceInfo> GDBRemoteCommunicationClient::GetAddressSpaces() {
1245 return {};
1246
1247 StringExtractorGDBRemote response;
1248 response.SetResponseValidatorToJSON();
1249 if (SendPacketAndWaitForResponse("jAddressSpacesInfo", response) !=
1251 return {};
1252
1253 if (response.IsUnsupportedResponse() || response.IsErrorResponse()) {
1255 return {};
1256 }
1257
1258 llvm::Expected<std::vector<AddressSpaceInfo>> info =
1259 llvm::json::parse<std::vector<AddressSpaceInfo>>(response.Peek(),
1260 "AddressSpaceInfo");
1261 if (info)
1262 return std::move(*info);
1263
1264 Log *log = GetLog(GDBRLog::Process);
1265 LLDB_LOG_ERROR(log, info.takeError(),
1266 "malformed jAddressSpacesInfo response '{1}': {0}",
1267 response.GetStringRef());
1268 return {};
1269}
1270
1273 m_gdb_server_name.clear();
1276
1277 StringExtractorGDBRemote response;
1278 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1280 if (response.IsNormalResponse()) {
1281 llvm::StringRef name, value;
1282 bool success = false;
1283 while (response.GetNameColonValue(name, value)) {
1284 if (name == "name") {
1285 success = true;
1286 m_gdb_server_name = std::string(value);
1287 } else if (name == "version") {
1288 llvm::StringRef major, minor;
1289 std::tie(major, minor) = value.split('.');
1290 if (!major.getAsInteger(BASE_10, m_gdb_server_version))
1291 success = true;
1292 }
1293 }
1294 if (success)
1296 }
1297 }
1298 }
1300}
1301
1303 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1305 llvm::StringRef avail_name;
1306
1307#if HAVE_LIBCOMPRESSION
1308 if (avail_type == CompressionType::None) {
1309 for (auto compression : supported_compressions) {
1310 if (compression == "lzfse") {
1311 avail_type = CompressionType::LZFSE;
1312 avail_name = compression;
1313 break;
1314 }
1315 }
1316 }
1317 if (avail_type == CompressionType::None) {
1318 for (auto compression : supported_compressions) {
1319 if (compression == "zlib-deflate") {
1320 avail_type = CompressionType::ZlibDeflate;
1321 avail_name = compression;
1322 break;
1323 }
1324 }
1325 }
1326#endif
1327
1328#if LLVM_ENABLE_ZLIB
1329 if (avail_type == CompressionType::None) {
1330 for (auto compression : supported_compressions) {
1331 if (compression == "zlib-deflate") {
1332 avail_type = CompressionType::ZlibDeflate;
1333 avail_name = compression;
1334 break;
1335 }
1336 }
1337 }
1338#endif
1339
1340#if HAVE_LIBCOMPRESSION
1341 if (avail_type == CompressionType::None) {
1342 for (auto compression : supported_compressions) {
1343 if (compression == "lz4") {
1344 avail_type = CompressionType::LZ4;
1345 avail_name = compression;
1346 break;
1347 }
1348 }
1349 }
1350 if (avail_type == CompressionType::None) {
1351 for (auto compression : supported_compressions) {
1352 if (compression == "lzma") {
1353 avail_type = CompressionType::LZMA;
1354 avail_name = compression;
1355 break;
1356 }
1357 }
1358 }
1359#endif
1360
1361 if (avail_type != CompressionType::None) {
1362 StringExtractorGDBRemote response;
1363 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1364 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1365 return;
1366
1367 if (response.IsOKResponse()) {
1368 m_compression_type = avail_type;
1369 }
1370 }
1371}
1372
1374 if (GetGDBServerVersion()) {
1375 if (!m_gdb_server_name.empty())
1376 return m_gdb_server_name.c_str();
1377 }
1378 return nullptr;
1379}
1380
1386
1388 StringExtractorGDBRemote response;
1390 return false;
1391
1392 if (!response.IsNormalResponse())
1393 return false;
1394
1395 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1396 auto pid_tid = response.GetPidTid(0);
1397 if (!pid_tid)
1398 return false;
1399
1400 lldb::pid_t pid = pid_tid->first;
1401 // invalid
1403 return false;
1404
1405 // if we get pid as well, update m_curr_pid
1406 if (pid != 0) {
1407 m_curr_pid_run = m_curr_pid = pid;
1409 }
1410 tid = pid_tid->second;
1411 }
1412
1413 return true;
1414}
1415
1416static void ParseOSType(llvm::StringRef value, std::string &os_name,
1417 std::string &environment) {
1418 if (value == "iossimulator" || value == "tvossimulator" ||
1419 value == "watchossimulator" || value == "xrossimulator" ||
1420 value == "visionossimulator") {
1421 environment = "simulator";
1422 os_name = value.drop_back(environment.size()).str();
1423 } else if (value == "maccatalyst") {
1424 os_name = "ios";
1425 environment = "macabi";
1426 } else {
1427 os_name = value.str();
1428 }
1429}
1430
1432 Log *log = GetLog(GDBRLog::Process);
1433
1434 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1435 // host info computation can require DNS traffic and shelling out to external processes.
1436 // Increase the timeout to account for that.
1437 ScopedTimeout timeout(*this, seconds(10));
1439 StringExtractorGDBRemote response;
1440 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1442 if (response.IsNormalResponse()) {
1443 llvm::StringRef name;
1444 llvm::StringRef value;
1445 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1446 uint32_t sub = 0;
1447 std::string arch_name;
1448 std::string os_name;
1449 std::string environment;
1450 std::string vendor_name;
1451 std::string triple;
1452 uint32_t pointer_byte_size = 0;
1453 ByteOrder byte_order = eByteOrderInvalid;
1454 uint32_t num_keys_decoded = 0;
1455 while (response.GetNameColonValue(name, value)) {
1456 if (name == "cputype") {
1457 // exception type in big endian hex
1458 if (!value.getAsInteger(BASE_10, cpu))
1459 ++num_keys_decoded;
1460 } else if (name == "cpusubtype") {
1461 // exception count in big endian hex
1462 if (!value.getAsInteger(BASE_10, sub))
1463 ++num_keys_decoded;
1464 } else if (name == "arch") {
1465 arch_name = std::string(value);
1466 ++num_keys_decoded;
1467 } else if (name == "triple") {
1468 StringExtractor extractor(value);
1469 extractor.GetHexByteString(triple);
1470 ++num_keys_decoded;
1471 } else if (name == "distribution_id") {
1472 StringExtractor extractor(value);
1474 ++num_keys_decoded;
1475 } else if (name == "os_build") {
1476 StringExtractor extractor(value);
1477 extractor.GetHexByteString(m_os_build);
1478 ++num_keys_decoded;
1479 } else if (name == "hostname") {
1480 StringExtractor extractor(value);
1481 extractor.GetHexByteString(m_hostname);
1482 ++num_keys_decoded;
1483 } else if (name == "os_kernel") {
1484 StringExtractor extractor(value);
1485 extractor.GetHexByteString(m_os_kernel);
1486 ++num_keys_decoded;
1487 } else if (name == "ostype") {
1488 ParseOSType(value, os_name, environment);
1489 ++num_keys_decoded;
1490 } else if (name == "vendor") {
1491 vendor_name = std::string(value);
1492 ++num_keys_decoded;
1493 } else if (name == "endian") {
1494 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1495 .Case("little", eByteOrderLittle)
1496 .Case("big", eByteOrderBig)
1497 .Case("pdp", eByteOrderPDP)
1498 .Default(eByteOrderInvalid);
1499 if (byte_order != eByteOrderInvalid)
1500 ++num_keys_decoded;
1501 } else if (name == "ptrsize") {
1502 if (!value.getAsInteger(BASE_10, pointer_byte_size))
1503 ++num_keys_decoded;
1504 } else if (name == "addressing_bits") {
1505 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits)) {
1506 ++num_keys_decoded;
1507 }
1508 } else if (name == "high_mem_addressing_bits") {
1509 if (!value.getAsInteger(BASE_10, m_high_mem_addressing_bits))
1510 ++num_keys_decoded;
1511 } else if (name == "low_mem_addressing_bits") {
1512 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits))
1513 ++num_keys_decoded;
1514 } else if (name == "os_version" ||
1515 name == "version") // Older debugserver binaries used
1516 // the "version" key instead of
1517 // "os_version"...
1518 {
1519 if (!m_os_version.tryParse(value))
1520 ++num_keys_decoded;
1521 } else if (name == "maccatalyst_version") {
1522 if (!m_maccatalyst_version.tryParse(value))
1523 ++num_keys_decoded;
1524 } else if (name == "watchpoint_exceptions_received") {
1526 llvm::StringSwitch<LazyBool>(value)
1527 .Case("before", eLazyBoolNo)
1528 .Case("after", eLazyBoolYes)
1529 .Default(eLazyBoolCalculate);
1531 ++num_keys_decoded;
1532 } else if (name == "default_packet_timeout") {
1533 uint32_t timeout_seconds;
1534 if (!value.getAsInteger(BASE_10, timeout_seconds)) {
1535 m_default_packet_timeout = seconds(timeout_seconds);
1537 ++num_keys_decoded;
1538 }
1539 } else if (name == "vm-page-size") {
1540 int page_size;
1541 if (!value.getAsInteger(BASE_10, page_size)) {
1542 m_target_vm_page_size = page_size;
1543 ++num_keys_decoded;
1544 }
1545 }
1546 }
1547
1548 if (num_keys_decoded > 0)
1550
1551 if (triple.empty()) {
1552 if (arch_name.empty()) {
1553 if (cpu != LLDB_INVALID_CPUTYPE) {
1554 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1555 if (pointer_byte_size) {
1556 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1557 }
1558 if (byte_order != eByteOrderInvalid) {
1559 assert(byte_order == m_host_arch.GetByteOrder());
1560 }
1561
1562 if (!vendor_name.empty())
1563 m_host_arch.GetTriple().setVendorName(
1564 llvm::StringRef(vendor_name));
1565 if (!os_name.empty())
1566 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1567 if (!environment.empty())
1568 m_host_arch.GetTriple().setEnvironmentName(environment);
1569 }
1570 } else {
1571 std::string triple;
1572 triple += arch_name;
1573 if (!vendor_name.empty() || !os_name.empty()) {
1574 triple += '-';
1575 if (vendor_name.empty())
1576 triple += "unknown";
1577 else
1578 triple += vendor_name;
1579 triple += '-';
1580 if (os_name.empty())
1581 triple += "unknown";
1582 else
1583 triple += os_name;
1584 }
1585 m_host_arch.SetTriple(triple.c_str());
1586
1587 llvm::Triple &host_triple = m_host_arch.GetTriple();
1588 if (host_triple.getVendor() == llvm::Triple::Apple &&
1589 host_triple.getOS() == llvm::Triple::Darwin) {
1590 switch (m_host_arch.GetMachine()) {
1591 case llvm::Triple::aarch64:
1592 case llvm::Triple::aarch64_32:
1593 case llvm::Triple::arm:
1594 case llvm::Triple::thumb:
1595 host_triple.setOS(llvm::Triple::IOS);
1596 break;
1597 default:
1598 host_triple.setOS(llvm::Triple::MacOSX);
1599 break;
1600 }
1601 }
1602 if (pointer_byte_size) {
1603 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1604 }
1605 if (byte_order != eByteOrderInvalid) {
1606 assert(byte_order == m_host_arch.GetByteOrder());
1607 }
1608 }
1609 } else {
1610 m_host_arch.SetTriple(triple.c_str());
1611 if (pointer_byte_size) {
1612 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1613 }
1614 if (byte_order != eByteOrderInvalid) {
1615 assert(byte_order == m_host_arch.GetByteOrder());
1616 }
1617
1618 LLDB_LOGF(log,
1619 "GDBRemoteCommunicationClient::%s parsed host "
1620 "architecture as %s, triple as %s from triple text %s",
1621 __FUNCTION__,
1622 m_host_arch.GetArchitectureName()
1623 ? m_host_arch.GetArchitectureName()
1624 : "<null-arch-name>",
1625 m_host_arch.GetTriple().getTriple().c_str(),
1626 triple.c_str());
1627 }
1628 }
1629 }
1630 }
1632}
1633
1635 const char *data, size_t data_len, std::chrono::seconds interrupt_timeout) {
1636 StreamString packet;
1637 packet.PutCString("I");
1638 packet.PutBytesAsRawHex8(data, data_len);
1639 StringExtractorGDBRemote response;
1640 if (SendPacketAndWaitForResponse(packet.GetString(), response,
1641 interrupt_timeout) ==
1643 return 0;
1644 }
1645 return response.GetError();
1646}
1647
1654
1667
1673
1675 uint32_t permissions) {
1678 char packet[64];
1679 const int packet_len = ::snprintf(
1680 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1681 permissions & lldb::ePermissionsReadable ? "r" : "",
1682 permissions & lldb::ePermissionsWritable ? "w" : "",
1683 permissions & lldb::ePermissionsExecutable ? "x" : "");
1684 assert(packet_len < (int)sizeof(packet));
1685 UNUSED_IF_ASSERT_DISABLED(packet_len);
1686 StringExtractorGDBRemote response;
1687 if (SendPacketAndWaitForResponse(packet, response) ==
1689 if (response.IsUnsupportedResponse())
1691 else if (!response.IsErrorResponse())
1692 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1693 } else {
1695 }
1696 }
1697 return LLDB_INVALID_ADDRESS;
1698}
1699
1703 char packet[64];
1704 const int packet_len =
1705 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1706 assert(packet_len < (int)sizeof(packet));
1707 UNUSED_IF_ASSERT_DISABLED(packet_len);
1708 StringExtractorGDBRemote response;
1709 if (SendPacketAndWaitForResponse(packet, response) ==
1711 if (response.IsUnsupportedResponse())
1713 else if (response.IsOKResponse())
1714 return true;
1715 } else {
1717 }
1718 }
1719 return false;
1720}
1721
1723 lldb::pid_t pid) {
1724 Status error;
1726
1727 packet.PutChar('D');
1728 if (keep_stopped) {
1730 char packet[64];
1731 const int packet_len =
1732 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1733 assert(packet_len < (int)sizeof(packet));
1734 UNUSED_IF_ASSERT_DISABLED(packet_len);
1735 StringExtractorGDBRemote response;
1736 if (SendPacketAndWaitForResponse(packet, response) ==
1738 response.IsOKResponse()) {
1740 } else {
1742 }
1743 }
1744
1747 "Stays stopped not supported by this target.");
1748 return error;
1749 } else {
1750 packet.PutChar('1');
1751 }
1752 }
1753
1755 // Some servers (e.g. qemu) require specifying the PID even if only a single
1756 // process is running.
1757 if (pid == LLDB_INVALID_PROCESS_ID)
1758 pid = GetCurrentProcessID();
1759 packet.PutChar(';');
1760 packet.PutHex64(pid);
1761 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1763 "Multiprocess extension not supported by the server.");
1764 return error;
1765 }
1766
1767 StringExtractorGDBRemote response;
1768 PacketResult packet_result =
1769 SendPacketAndWaitForResponse(packet.GetString(), response);
1770 if (packet_result != PacketResult::Success)
1771 error = Status::FromErrorString("Sending disconnect packet failed.");
1772 return error;
1773}
1774
1776 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1777 Status error;
1778 region_info.Clear();
1779
1782 char packet[64];
1783 const int packet_len = ::snprintf(
1784 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1785 assert(packet_len < (int)sizeof(packet));
1786 UNUSED_IF_ASSERT_DISABLED(packet_len);
1787 StringExtractorGDBRemote response;
1788 if (SendPacketAndWaitForResponse(packet, response) ==
1791 llvm::StringRef name;
1792 llvm::StringRef value;
1793 addr_t addr_value = LLDB_INVALID_ADDRESS;
1794 bool success = true;
1795 bool saw_permissions = false;
1796 while (success && response.GetNameColonValue(name, value)) {
1797 if (name == "start") {
1798 if (!value.getAsInteger(BASE_16, addr_value))
1799 region_info.GetRange().SetRangeBase(addr_value);
1800 } else if (name == "size") {
1801 if (!value.getAsInteger(BASE_16, addr_value)) {
1802 region_info.GetRange().SetByteSize(addr_value);
1803 if (region_info.GetRange().GetRangeEnd() <
1804 region_info.GetRange().GetRangeBase()) {
1805 // Range size overflowed, truncate it.
1807 }
1808 }
1809 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1810 saw_permissions = true;
1811 if (region_info.GetRange().Contains(addr)) {
1812 if (value.contains('r'))
1813 region_info.SetReadable(eLazyBoolYes);
1814 else
1815 region_info.SetReadable(eLazyBoolNo);
1816
1817 if (value.contains('w'))
1818 region_info.SetWritable(eLazyBoolYes);
1819 else
1820 region_info.SetWritable(eLazyBoolNo);
1821
1822 if (value.contains('x'))
1823 region_info.SetExecutable(eLazyBoolYes);
1824 else
1825 region_info.SetExecutable(eLazyBoolNo);
1826
1827 region_info.SetMapped(eLazyBoolYes);
1828 } else {
1829 // The reported region does not contain this address -- we're
1830 // looking at an unmapped page
1831 region_info.SetReadable(eLazyBoolNo);
1832 region_info.SetWritable(eLazyBoolNo);
1833 region_info.SetExecutable(eLazyBoolNo);
1834 region_info.SetMapped(eLazyBoolNo);
1835 }
1836 } else if (name == "name") {
1837 StringExtractorGDBRemote name_extractor(value);
1838 std::string name;
1839 name_extractor.GetHexByteString(name);
1840 region_info.SetName(name.c_str());
1841 } else if (name == "flags") {
1842 region_info.SetMemoryTagged(eLazyBoolNo);
1843 region_info.SetIsShadowStack(eLazyBoolNo);
1844
1845 llvm::StringRef flags = value;
1846 llvm::StringRef flag;
1847 while (flags.size()) {
1848 flags = flags.ltrim();
1849 std::tie(flag, flags) = flags.split(' ');
1850 // To account for trailing whitespace
1851 if (flag.size()) {
1852 if (flag == "mt")
1853 region_info.SetMemoryTagged(eLazyBoolYes);
1854 else if (flag == "ss")
1855 region_info.SetIsShadowStack(eLazyBoolYes);
1856 }
1857 }
1858 } else if (name == "type") {
1859 for (llvm::StringRef entry : llvm::split(value, ',')) {
1860 if (entry == "stack")
1861 region_info.SetIsStackMemory(eLazyBoolYes);
1862 else if (entry == "heap")
1863 region_info.SetIsStackMemory(eLazyBoolNo);
1864 }
1865 } else if (name == "error") {
1866 StringExtractorGDBRemote error_extractor(value);
1867 std::string error_string;
1868 // Now convert the HEX bytes into a string value
1869 error_extractor.GetHexByteString(error_string);
1870 error = Status::FromErrorString(error_string.c_str());
1871 } else if (name == "dirty-pages") {
1872 std::vector<addr_t> dirty_page_list;
1873 for (llvm::StringRef x : llvm::split(value, ',')) {
1874 addr_t page;
1875 x.consume_front("0x");
1876 if (llvm::to_integer(x, page, 16))
1877 dirty_page_list.push_back(page);
1878 }
1879 region_info.SetDirtyPageList(dirty_page_list);
1880 } else if (name == "protection-key") {
1881 unsigned protection_key = 0;
1882 if (!value.getAsInteger(BASE_10, protection_key))
1883 region_info.SetProtectionKey(protection_key);
1884 }
1885 }
1886
1887 if (m_target_vm_page_size != 0)
1889
1890 if (region_info.GetRange().IsValid()) {
1891 // We got a valid address range back but no permissions -- which means
1892 // this is an unmapped page
1893 if (!saw_permissions) {
1894 region_info.SetReadable(eLazyBoolNo);
1895 region_info.SetWritable(eLazyBoolNo);
1896 region_info.SetExecutable(eLazyBoolNo);
1897 region_info.SetMapped(eLazyBoolNo);
1898 }
1899 } else {
1900 // We got an invalid address range back
1901 error = Status::FromErrorString("Server returned invalid range");
1902 }
1903 } else {
1905 }
1906 }
1907
1909 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1910 }
1911
1912 // Try qXfer:memory-map:read to get region information not included in
1913 // qMemoryRegionInfo
1914 MemoryRegionInfo qXfer_region_info;
1915 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1916
1917 if (error.Fail()) {
1918 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1919 // the qXfer result as a fallback
1920 if (qXfer_error.Success()) {
1921 region_info = qXfer_region_info;
1922 error.Clear();
1923 } else {
1924 region_info.Clear();
1925 }
1926 } else if (qXfer_error.Success()) {
1927 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1928 // both regions are the same range, update the result to include the flash-
1929 // memory information that is specific to the qXfer result.
1930 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1931 region_info.SetFlash(qXfer_region_info.GetFlash());
1932 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1933 }
1934 }
1935 return error;
1936}
1937
1939 lldb::addr_t addr, MemoryRegionInfo &region) {
1941 if (!error.Success())
1942 return error;
1943 for (const auto &map_region : m_qXfer_memory_map) {
1944 if (map_region.GetRange().Contains(addr)) {
1945 region = map_region;
1946 return error;
1947 }
1948 }
1949 error = Status::FromErrorString("Region not found");
1950 return error;
1951}
1952
1954
1955 Status error;
1956
1958 // Already loaded, return success
1959 return error;
1960
1961 if (!XMLDocument::XMLEnabled()) {
1962 error = Status::FromErrorString("XML is not supported");
1963 return error;
1964 }
1965
1967 error = Status::FromErrorString("Memory map is not supported");
1968 return error;
1969 }
1970
1971 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1972 if (!xml)
1973 return Status::FromError(xml.takeError());
1974
1975 XMLDocument xml_document;
1976
1977 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1978 error = Status::FromErrorString("Failed to parse memory map xml");
1979 return error;
1980 }
1981
1982 XMLNode map_node = xml_document.GetRootElement("memory-map");
1983 if (!map_node) {
1984 error = Status::FromErrorString("Invalid root node in memory map xml");
1985 return error;
1986 }
1987
1988 m_qXfer_memory_map.clear();
1989
1990 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1991 if (!memory_node.IsElement())
1992 return true;
1993 if (memory_node.GetName() != "memory")
1994 return true;
1995 auto type = memory_node.GetAttributeValue("type", "");
1996 uint64_t start;
1997 uint64_t length;
1998 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1999 return true;
2000 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
2001 return true;
2002 MemoryRegionInfo region;
2003 region.GetRange().SetRangeBase(start);
2004 region.GetRange().SetByteSize(length);
2005 if (type == "rom") {
2006 region.SetReadable(eLazyBoolYes);
2007 this->m_qXfer_memory_map.push_back(region);
2008 } else if (type == "ram") {
2009 region.SetReadable(eLazyBoolYes);
2010 region.SetWritable(eLazyBoolYes);
2011 this->m_qXfer_memory_map.push_back(region);
2012 } else if (type == "flash") {
2013 region.SetFlash(eLazyBoolYes);
2014 memory_node.ForEachChildElement(
2015 [&region](const XMLNode &prop_node) -> bool {
2016 if (!prop_node.IsElement())
2017 return true;
2018 if (prop_node.GetName() != "property")
2019 return true;
2020 auto propname = prop_node.GetAttributeValue("name", "");
2021 if (propname == "blocksize") {
2022 uint64_t blocksize;
2023 if (prop_node.GetElementTextAsUnsigned(blocksize))
2024 region.SetBlocksize(blocksize);
2025 }
2026 return true;
2027 });
2028 this->m_qXfer_memory_map.push_back(region);
2029 }
2030 return true;
2031 });
2032
2034
2035 return error;
2036}
2037
2041 }
2042
2043 std::optional<uint32_t> num;
2045 StringExtractorGDBRemote response;
2046 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
2049 llvm::StringRef name;
2050 llvm::StringRef value;
2051 while (response.GetNameColonValue(name, value)) {
2052 if (name == "num") {
2053 value.getAsInteger(BASE_10, m_num_supported_hardware_watchpoints);
2055 }
2056 }
2057 if (!num) {
2059 }
2060 } else {
2062 }
2063 }
2064
2065 return num;
2066}
2067
2068WatchpointHardwareFeature
2072
2075 GetHostInfo();
2076
2077 // Process determines this by target CPU, but allow for the
2078 // remote stub to override it via the qHostInfo
2079 // watchpoint_exceptions_received key, if it is present.
2082 return false;
2084 return true;
2085 }
2086
2087 return std::nullopt;
2088}
2089
2091 if (file_spec) {
2092 std::string path{file_spec.GetPath(false)};
2093 StreamString packet;
2094 packet.PutCString("QSetSTDIN:");
2095 packet.PutStringAsRawHex8(path);
2096
2097 StringExtractorGDBRemote response;
2098 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2100 if (response.IsOKResponse())
2101 return 0;
2102 uint8_t error = response.GetError();
2103 if (error)
2104 return error;
2105 }
2106 }
2107 return -1;
2108}
2109
2111 if (file_spec) {
2112 std::string path{file_spec.GetPath(false)};
2113 StreamString packet;
2114 packet.PutCString("QSetSTDOUT:");
2115 packet.PutStringAsRawHex8(path);
2116
2117 StringExtractorGDBRemote response;
2118 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2120 if (response.IsOKResponse())
2121 return 0;
2122 uint8_t error = response.GetError();
2123 if (error)
2124 return error;
2125 }
2126 }
2127 return -1;
2128}
2129
2131 if (file_spec) {
2132 std::string path{file_spec.GetPath(false)};
2133 StreamString packet;
2134 packet.PutCString("QSetSTDERR:");
2135 packet.PutStringAsRawHex8(path);
2136
2137 StringExtractorGDBRemote response;
2138 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2140 if (response.IsOKResponse())
2141 return 0;
2142 uint8_t error = response.GetError();
2143 if (error)
2144 return error;
2145 }
2146 }
2147 return -1;
2148}
2149
2151 uint16_t rows) {
2152 // The size is only valid if both or none of the dimensions are zero.
2153 if ((cols == 0) != (rows == 0))
2154 return -1;
2155 StreamString packet;
2156 packet.Printf("QSetSTDIOWindowSize:cols=%u;rows=%u",
2157 static_cast<unsigned>(cols), static_cast<unsigned>(rows));
2158 StringExtractorGDBRemote response;
2159 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
2161 return -1;
2162 if (response.IsOKResponse())
2163 return 0;
2164 if (response.IsUnsupportedResponse())
2165 return 0;
2166 uint8_t error = response.GetError();
2167 return error ? error : -1;
2168}
2169
2171 StringExtractorGDBRemote response;
2172 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
2174 if (response.IsUnsupportedResponse())
2175 return false;
2176 if (response.IsErrorResponse())
2177 return false;
2178 std::string cwd;
2179 response.GetHexByteString(cwd);
2180 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
2181 return !cwd.empty();
2182 }
2183 return false;
2184}
2185
2187 if (working_dir) {
2188 std::string path{working_dir.GetPath(false)};
2189 StreamString packet;
2190 packet.PutCString("QSetWorkingDir:");
2191 packet.PutStringAsRawHex8(path);
2192
2193 StringExtractorGDBRemote response;
2194 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2196 if (response.IsOKResponse())
2197 return 0;
2198 uint8_t error = response.GetError();
2199 if (error)
2200 return error;
2201 }
2202 }
2203 return -1;
2204}
2205
2207 char packet[32];
2208 const int packet_len =
2209 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2210 assert(packet_len < (int)sizeof(packet));
2211 UNUSED_IF_ASSERT_DISABLED(packet_len);
2212 StringExtractorGDBRemote response;
2213 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2214 if (response.IsOKResponse())
2215 return 0;
2216 uint8_t error = response.GetError();
2217 if (error)
2218 return error;
2219 }
2220 return -1;
2221}
2222
2224 char packet[32];
2225 const int packet_len = ::snprintf(packet, sizeof(packet),
2226 "QSetDetachOnError:%i", enable ? 1 : 0);
2227 assert(packet_len < (int)sizeof(packet));
2228 UNUSED_IF_ASSERT_DISABLED(packet_len);
2229 StringExtractorGDBRemote response;
2230 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2231 if (response.IsOKResponse())
2232 return 0;
2233 uint8_t error = response.GetError();
2234 if (error)
2235 return error;
2236 }
2237 return -1;
2238}
2239
2241 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2242 if (response.IsNormalResponse()) {
2243 llvm::StringRef name;
2244 llvm::StringRef value;
2245 StringExtractor extractor;
2246
2247 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2248 uint32_t sub = 0;
2249 std::string vendor;
2250 std::string os_type;
2251
2252 while (response.GetNameColonValue(name, value)) {
2253 if (name == "pid") {
2255 value.getAsInteger(BASE_10, pid);
2256 process_info.SetProcessID(pid);
2257 } else if (name == "ppid") {
2259 value.getAsInteger(BASE_10, pid);
2260 process_info.SetParentProcessID(pid);
2261 } else if (name == "uid") {
2262 uint32_t uid = UINT32_MAX;
2263 value.getAsInteger(BASE_10, uid);
2264 process_info.SetUserID(uid);
2265 } else if (name == "euid") {
2266 uint32_t uid = UINT32_MAX;
2267 value.getAsInteger(BASE_10, uid);
2268 process_info.SetEffectiveUserID(uid);
2269 } else if (name == "gid") {
2270 uint32_t gid = UINT32_MAX;
2271 value.getAsInteger(BASE_10, gid);
2272 process_info.SetGroupID(gid);
2273 } else if (name == "egid") {
2274 uint32_t gid = UINT32_MAX;
2275 value.getAsInteger(BASE_10, gid);
2276 process_info.SetEffectiveGroupID(gid);
2277 } else if (name == "triple") {
2278 StringExtractor extractor(value);
2279 std::string triple;
2280 extractor.GetHexByteString(triple);
2281 process_info.GetArchitecture().SetTriple(triple.c_str());
2282 } else if (name == "name") {
2283 StringExtractor extractor(value);
2284 // The process name from ASCII hex bytes since we can't control the
2285 // characters in a process name
2286 std::string name;
2287 extractor.GetHexByteString(name);
2288 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2289 } else if (name == "args") {
2290 llvm::StringRef encoded_args(value), hex_arg;
2291
2292 bool is_arg0 = true;
2293 while (!encoded_args.empty()) {
2294 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2295 std::string arg;
2296 StringExtractor extractor(hex_arg);
2297 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2298 // In case of wrong encoding, we discard all the arguments
2299 process_info.GetArguments().Clear();
2300 process_info.SetArg0("");
2301 break;
2302 }
2303 if (is_arg0)
2304 process_info.SetArg0(arg);
2305 else
2306 process_info.GetArguments().AppendArgument(arg);
2307 is_arg0 = false;
2308 }
2309 } else if (name == "cputype") {
2310 value.getAsInteger(BASE_10, cpu);
2311 } else if (name == "cpusubtype") {
2312 value.getAsInteger(BASE_10, sub);
2313 } else if (name == "vendor") {
2314 vendor = std::string(value);
2315 } else if (name == "ostype") {
2316 os_type = std::string(value);
2317 }
2318 }
2319
2320 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2321 if (vendor == "apple") {
2323 sub);
2324 process_info.GetArchitecture().GetTriple().setVendorName(
2325 llvm::StringRef(vendor));
2326 process_info.GetArchitecture().GetTriple().setOSName(
2327 llvm::StringRef(os_type));
2328 }
2329 }
2330
2331 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2332 return true;
2333 }
2334 return false;
2335}
2336
2338 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2339 process_info.Clear();
2340
2342 char packet[32];
2343 const int packet_len =
2344 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2345 assert(packet_len < (int)sizeof(packet));
2346 UNUSED_IF_ASSERT_DISABLED(packet_len);
2347 StringExtractorGDBRemote response;
2348 if (SendPacketAndWaitForResponse(packet, response) ==
2350 return DecodeProcessInfoResponse(response, process_info);
2351 } else {
2353 return false;
2354 }
2355 }
2356 return false;
2357}
2358
2361
2362 if (allow_lazy) {
2364 return true;
2366 return false;
2367 }
2368
2369 GetHostInfo();
2370
2371 StringExtractorGDBRemote response;
2372 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2374 if (response.IsNormalResponse()) {
2375 llvm::StringRef name;
2376 llvm::StringRef value;
2377 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2378 uint32_t sub = 0;
2379 std::string os_name;
2380 std::string environment;
2381 std::string vendor_name;
2382 std::string triple;
2383 std::string elf_abi;
2384 uint32_t pointer_byte_size = 0;
2385 StringExtractor extractor;
2386 ByteOrder byte_order = eByteOrderInvalid;
2387 uint32_t num_keys_decoded = 0;
2389 while (response.GetNameColonValue(name, value)) {
2390 if (name == "cputype") {
2391 if (!value.getAsInteger(BASE_16, cpu))
2392 ++num_keys_decoded;
2393 } else if (name == "cpusubtype") {
2394 if (!value.getAsInteger(BASE_16, sub)) {
2395 ++num_keys_decoded;
2396 // Workaround for pre-2024 Apple debugserver, which always
2397 // returns arm64e on arm64e-capable hardware regardless of
2398 // what the process is. This can be deleted at some point
2399 // in the future.
2400 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2401 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2402 if (GetGDBServerVersion())
2403 if (m_gdb_server_version >= 1000 &&
2404 m_gdb_server_version <= 1504)
2405 sub = 0;
2406 }
2407 }
2408 } else if (name == "triple") {
2409 StringExtractor extractor(value);
2410 extractor.GetHexByteString(triple);
2411 ++num_keys_decoded;
2412 } else if (name == "ostype") {
2413 ParseOSType(value, os_name, environment);
2414 ++num_keys_decoded;
2415 } else if (name == "vendor") {
2416 vendor_name = std::string(value);
2417 ++num_keys_decoded;
2418 } else if (name == "endian") {
2419 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2420 .Case("little", eByteOrderLittle)
2421 .Case("big", eByteOrderBig)
2422 .Case("pdp", eByteOrderPDP)
2423 .Default(eByteOrderInvalid);
2424 if (byte_order != eByteOrderInvalid)
2425 ++num_keys_decoded;
2426 } else if (name == "ptrsize") {
2427 if (!value.getAsInteger(BASE_16, pointer_byte_size))
2428 ++num_keys_decoded;
2429 } else if (name == "pid") {
2430 if (!value.getAsInteger(BASE_16, pid))
2431 ++num_keys_decoded;
2432 } else if (name == "elf_abi") {
2433 elf_abi = std::string(value);
2434 ++num_keys_decoded;
2435 } else if (name == "main-binary-uuid") {
2436 m_process_standalone_uuid.SetFromStringRef(value);
2437 ++num_keys_decoded;
2438 } else if (name == "main-binary-slide") {
2439 StringExtractor extractor(value);
2441 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2444 ++num_keys_decoded;
2445 }
2446 } else if (name == "main-binary-address") {
2447 StringExtractor extractor(value);
2449 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2452 ++num_keys_decoded;
2453 }
2454 } else if (name == "binary-addresses") {
2455 m_binary_addresses.clear();
2456 ++num_keys_decoded;
2457 for (llvm::StringRef x : llvm::split(value, ',')) {
2458 addr_t vmaddr;
2459 x.consume_front("0x");
2460 if (llvm::to_integer(x, vmaddr, 16))
2461 m_binary_addresses.push_back(vmaddr);
2462 }
2463 }
2464 }
2465 if (num_keys_decoded > 0)
2467 if (pid != LLDB_INVALID_PROCESS_ID) {
2469 m_curr_pid_run = m_curr_pid = pid;
2470 }
2471
2472 // Set the ArchSpec from the triple if we have it.
2473 if (!triple.empty()) {
2474 m_process_arch.SetTriple(triple.c_str());
2475 m_process_arch.SetFlags(elf_abi);
2476 if (pointer_byte_size) {
2477 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2478 }
2479 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2480 !vendor_name.empty()) {
2481 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2482 if (!environment.empty())
2483 triple.setEnvironmentName(environment);
2484
2485 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2486 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2487 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2488 switch (triple.getObjectFormat()) {
2489 case llvm::Triple::MachO:
2490 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2491 break;
2492 case llvm::Triple::ELF:
2493 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2494 break;
2495 case llvm::Triple::COFF:
2496 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2497 break;
2498 case llvm::Triple::GOFF:
2499 case llvm::Triple::SPIRV:
2500 case llvm::Triple::Wasm:
2501 case llvm::Triple::XCOFF:
2502 case llvm::Triple::DXContainer:
2503 LLDB_LOGF(log, "error: not supported target architecture");
2504 return false;
2505 case llvm::Triple::UnknownObjectFormat:
2506 LLDB_LOGF(log, "error: failed to determine target architecture");
2507 return false;
2508 }
2509
2510 if (pointer_byte_size) {
2511 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2512 }
2513 if (byte_order != eByteOrderInvalid) {
2514 assert(byte_order == m_process_arch.GetByteOrder());
2515 }
2516 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2517 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2518 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2519 }
2520 return true;
2521 }
2522 } else {
2524 }
2525
2526 return false;
2527}
2528
2530 const ProcessInstanceInfoMatch &match_info,
2531 ProcessInstanceInfoList &process_infos) {
2532 process_infos.clear();
2533
2535 StreamString packet;
2536 packet.PutCString("qfProcessInfo");
2537 if (!match_info.MatchAllProcesses()) {
2538 packet.PutChar(':');
2539 llvm::StringRef name = match_info.GetProcessInfo().GetName();
2540 bool has_name_match = false;
2541 if (!name.empty()) {
2542 has_name_match = true;
2543 NameMatch name_match_type = match_info.GetNameMatchType();
2544 switch (name_match_type) {
2545 case NameMatch::Ignore:
2546 has_name_match = false;
2547 break;
2548
2549 case NameMatch::Equals:
2550 packet.PutCString("name_match:equals;");
2551 break;
2552
2554 packet.PutCString("name_match:contains;");
2555 break;
2556
2558 packet.PutCString("name_match:starts_with;");
2559 break;
2560
2562 packet.PutCString("name_match:ends_with;");
2563 break;
2564
2566 packet.PutCString("name_match:regex;");
2567 break;
2568 }
2569 if (has_name_match) {
2570 packet.PutCString("name:");
2571 packet.PutBytesAsRawHex8(name.data(), name.size());
2572 packet.PutChar(';');
2573 }
2574 }
2575
2576 if (match_info.GetProcessInfo().ProcessIDIsValid())
2577 packet.Printf("pid:%" PRIu64 ";",
2578 match_info.GetProcessInfo().GetProcessID());
2579 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2580 packet.Printf("parent_pid:%" PRIu64 ";",
2581 match_info.GetProcessInfo().GetParentProcessID());
2582 if (match_info.GetProcessInfo().UserIDIsValid())
2583 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2584 if (match_info.GetProcessInfo().GroupIDIsValid())
2585 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2586 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2587 packet.Printf("euid:%u;",
2588 match_info.GetProcessInfo().GetEffectiveUserID());
2589 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2590 packet.Printf("egid:%u;",
2591 match_info.GetProcessInfo().GetEffectiveGroupID());
2592 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2593 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2594 const ArchSpec &match_arch =
2595 match_info.GetProcessInfo().GetArchitecture();
2596 const llvm::Triple &triple = match_arch.GetTriple();
2597 packet.PutCString("triple:");
2598 packet.PutCString(triple.getTriple());
2599 packet.PutChar(';');
2600 }
2601 }
2602 StringExtractorGDBRemote response;
2603 // Increase timeout as the first qfProcessInfo packet takes a long time on
2604 // Android. The value of 1min was arrived at empirically.
2605 ScopedTimeout timeout(*this, minutes(1));
2606 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2608 do {
2609 ProcessInstanceInfo process_info;
2610 if (!DecodeProcessInfoResponse(response, process_info))
2611 break;
2612 process_infos.push_back(process_info);
2613 response = StringExtractorGDBRemote();
2614 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2616 } else {
2618 return 0;
2619 }
2620 }
2621 return process_infos.size();
2622}
2623
2625 std::string &name) {
2627 char packet[32];
2628 const int packet_len =
2629 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2630 assert(packet_len < (int)sizeof(packet));
2631 UNUSED_IF_ASSERT_DISABLED(packet_len);
2632 StringExtractorGDBRemote response;
2633 if (SendPacketAndWaitForResponse(packet, response) ==
2635 if (response.IsNormalResponse()) {
2636 // Make sure we parsed the right number of characters. The response is
2637 // the hex encoded user name and should make up the entire packet. If
2638 // there are any non-hex ASCII bytes, the length won't match below..
2639 if (response.GetHexByteString(name) * 2 ==
2640 response.GetStringRef().size())
2641 return true;
2642 }
2643 } else {
2644 m_supports_qUserName = false;
2645 return false;
2646 }
2647 }
2648 return false;
2649}
2650
2652 std::string &name) {
2654 char packet[32];
2655 const int packet_len =
2656 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2657 assert(packet_len < (int)sizeof(packet));
2658 UNUSED_IF_ASSERT_DISABLED(packet_len);
2659 StringExtractorGDBRemote response;
2660 if (SendPacketAndWaitForResponse(packet, response) ==
2662 if (response.IsNormalResponse()) {
2663 // Make sure we parsed the right number of characters. The response is
2664 // the hex encoded group name and should make up the entire packet. If
2665 // there are any non-hex ASCII bytes, the length won't match below..
2666 if (response.GetHexByteString(name) * 2 ==
2667 response.GetStringRef().size())
2668 return true;
2669 }
2670 } else {
2671 m_supports_qGroupName = false;
2672 return false;
2673 }
2674 }
2675 return false;
2676}
2677
2678static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2679 uint32_t recv_size) {
2680 packet.Clear();
2681 packet.Printf("qSpeedTest:response_size:%x;data:", recv_size);
2682 uint32_t bytes_left = send_size;
2683 while (bytes_left > 0) {
2684 if (bytes_left >= 26) {
2685 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2686 bytes_left -= 26;
2687 } else {
2688 packet.Printf("%*.*s;", bytes_left, bytes_left,
2689 "abcdefghijklmnopqrstuvwxyz");
2690 bytes_left = 0;
2691 }
2692 }
2693}
2694
2695duration<float>
2696calculate_standard_deviation(const std::vector<duration<float>> &v) {
2697 if (v.size() == 0)
2698 return duration<float>::zero();
2699 using Dur = duration<float>;
2700 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2701 Dur mean = sum / v.size();
2702 float accum = 0;
2703 for (auto d : v) {
2704 float delta = (d - mean).count();
2705 accum += delta * delta;
2706 };
2707
2708 return Dur(sqrtf(accum / (v.size() - 1)));
2709}
2710
2712 uint32_t max_send,
2713 uint32_t max_recv,
2714 uint64_t recv_amount,
2715 bool json, Stream &strm) {
2716
2717 if (SendSpeedTestPacket(0, 0)) {
2718 StreamString packet;
2719 if (json)
2720 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2721 "\"results\" : [",
2722 num_packets);
2723 else
2724 strm.Printf("Testing sending %u packets of various sizes:\n",
2725 num_packets);
2726 strm.Flush();
2727
2728 uint32_t result_idx = 0;
2729 uint32_t send_size;
2730 std::vector<duration<float>> packet_times;
2731
2732 for (send_size = 0; send_size <= max_send;
2733 send_size ? send_size *= 2 : send_size = 4) {
2734 for (uint32_t recv_size = 0; recv_size <= max_recv;
2735 recv_size ? recv_size *= 2 : recv_size = 4) {
2736 MakeSpeedTestPacket(packet, send_size, recv_size);
2737
2738 packet_times.clear();
2739 // Test how long it takes to send 'num_packets' packets
2740 const auto start_time = steady_clock::now();
2741 for (uint32_t i = 0; i < num_packets; ++i) {
2742 const auto packet_start_time = steady_clock::now();
2743 StringExtractorGDBRemote response;
2744 SendPacketAndWaitForResponse(packet.GetString(), response);
2745 const auto packet_end_time = steady_clock::now();
2746 packet_times.push_back(packet_end_time - packet_start_time);
2747 }
2748 const auto end_time = steady_clock::now();
2749 const auto total_time = end_time - start_time;
2750
2751 float packets_per_second =
2752 ((float)num_packets) / duration<float>(total_time).count();
2753 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2754 : duration<float>::zero();
2755 const duration<float> standard_deviation =
2756 calculate_standard_deviation(packet_times);
2757 if (json) {
2758 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2759 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2760 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2761 result_idx > 0 ? "," : "", send_size, recv_size,
2762 total_time, standard_deviation);
2763 ++result_idx;
2764 } else {
2765 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2766 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2767 "standard deviation of {5,10:ms+f6}\n",
2768 send_size, recv_size, duration<float>(total_time),
2769 packets_per_second, duration<float>(average_per_packet),
2770 standard_deviation);
2771 }
2772 strm.Flush();
2773 }
2774 }
2775
2776 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2777 if (json)
2778 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2779 ": %" PRIu64 ",\n \"results\" : [",
2780 recv_amount);
2781 else
2782 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2783 "packet sizes:\n",
2784 k_recv_amount_mb);
2785 strm.Flush();
2786 send_size = 0;
2787 result_idx = 0;
2788 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2789 MakeSpeedTestPacket(packet, send_size, recv_size);
2790
2791 // If we have a receive size, test how long it takes to receive 4MB of
2792 // data
2793 if (recv_size > 0) {
2794 const auto start_time = steady_clock::now();
2795 uint32_t bytes_read = 0;
2796 uint32_t packet_count = 0;
2797 while (bytes_read < recv_amount) {
2798 StringExtractorGDBRemote response;
2799 SendPacketAndWaitForResponse(packet.GetString(), response);
2800 bytes_read += recv_size;
2801 ++packet_count;
2802 }
2803 const auto end_time = steady_clock::now();
2804 const auto total_time = end_time - start_time;
2805 float mb_second = ((float)recv_amount) /
2806 duration<float>(total_time).count() /
2807 (1024.0 * 1024.0);
2808 float packets_per_second =
2809 ((float)packet_count) / duration<float>(total_time).count();
2810 const auto average_per_packet = packet_count > 0
2811 ? total_time / packet_count
2812 : duration<float>::zero();
2813
2814 if (json) {
2815 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2816 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2817 result_idx > 0 ? "," : "", send_size, recv_size,
2818 total_time);
2819 ++result_idx;
2820 } else {
2821 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2822 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2823 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2824 send_size, recv_size, packet_count, k_recv_amount_mb,
2825 duration<float>(total_time), mb_second,
2826 packets_per_second, duration<float>(average_per_packet));
2827 }
2828 strm.Flush();
2829 }
2830 }
2831 if (json)
2832 strm.Printf("\n ]\n }\n}\n");
2833 else
2834 strm.EOL();
2835 }
2836}
2837
2839 uint32_t recv_size) {
2840 StreamString packet;
2841 MakeSpeedTestPacket(packet, send_size, recv_size);
2842
2843 StringExtractorGDBRemote response;
2844 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2846}
2847
2849 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2850 std::string &socket_name) {
2852 port = 0;
2853 socket_name.clear();
2854
2855 StringExtractorGDBRemote response;
2856 StreamString stream;
2857 stream.PutCString("qLaunchGDBServer;");
2858 std::string hostname;
2859 if (remote_accept_hostname && remote_accept_hostname[0])
2860 hostname = remote_accept_hostname;
2861 else {
2862 if (HostInfo::GetHostname(hostname)) {
2863 // Make the GDB server we launch only accept connections from this host
2864 stream.Printf("host:%s;", hostname.c_str());
2865 } else {
2866 // Make the GDB server we launch accept connections from any host since
2867 // we can't figure out the hostname
2868 stream.Printf("host:*;");
2869 }
2870 }
2871 // give the process a few seconds to startup
2872 ScopedTimeout timeout(*this, seconds(10));
2873
2874 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2876 if (response.IsErrorResponse())
2877 return false;
2878
2879 llvm::StringRef name;
2880 llvm::StringRef value;
2881 while (response.GetNameColonValue(name, value)) {
2882 if (name == "port")
2883 value.getAsInteger(BASE_10, port);
2884 else if (name == "pid")
2885 value.getAsInteger(BASE_10, pid);
2886 else if (name.compare("socket_name") == 0) {
2887 StringExtractor extractor(value);
2888 extractor.GetHexByteString(socket_name);
2889 }
2890 }
2891 return true;
2892 }
2893 return false;
2894}
2895
2897 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2898 connection_urls.clear();
2899
2900 StringExtractorGDBRemote response;
2901 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2903 return 0;
2904
2907 if (!data)
2908 return 0;
2909
2910 StructuredData::Array *array = data->GetAsArray();
2911 if (!array)
2912 return 0;
2913
2914 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2915 std::optional<StructuredData::Dictionary *> maybe_element =
2917 if (!maybe_element)
2918 continue;
2919
2920 StructuredData::Dictionary *element = *maybe_element;
2921 uint16_t port = 0;
2922 if (StructuredData::ObjectSP port_osp =
2923 element->GetValueForKey(llvm::StringRef("port")))
2924 port = port_osp->GetUnsignedIntegerValue(0);
2925
2926 std::string socket_name;
2927 if (StructuredData::ObjectSP socket_name_osp =
2928 element->GetValueForKey(llvm::StringRef("socket_name")))
2929 socket_name = std::string(socket_name_osp->GetStringValue());
2930
2931 if (port != 0 || !socket_name.empty())
2932 connection_urls.emplace_back(port, socket_name);
2933 }
2934 return connection_urls.size();
2935}
2936
2938 StreamString stream;
2939 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2940
2941 StringExtractorGDBRemote response;
2942 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2944 if (response.IsOKResponse())
2945 return true;
2946 }
2947 return false;
2948}
2949
2951 uint64_t tid, uint64_t pid, char op) {
2953 packet.PutChar('H');
2954 packet.PutChar(op);
2955
2956 if (pid != LLDB_INVALID_PROCESS_ID)
2957 packet.Printf("p%" PRIx64 ".", pid);
2958
2959 if (tid == UINT64_MAX)
2960 packet.PutCString("-1");
2961 else
2962 packet.Printf("%" PRIx64, tid);
2963
2964 StringExtractorGDBRemote response;
2965 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2967 if (response.IsOKResponse())
2968 return {{pid, tid}};
2969
2970 /*
2971 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2972 * Hg packet.
2973 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2974 * which can
2975 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2976 */
2977 if (response.IsUnsupportedResponse() && IsConnected())
2978 return {{1, 1}};
2979 }
2980 return std::nullopt;
2981}
2982
2984 uint64_t pid) {
2985 if (m_curr_tid == tid &&
2986 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2987 return true;
2988
2989 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2990 if (ret) {
2991 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2992 m_curr_pid = ret->pid;
2993 m_curr_tid = ret->tid;
2994 }
2995 return ret.has_value();
2996}
2997
2999 uint64_t pid) {
3000 if (m_curr_tid_run == tid &&
3001 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
3002 return true;
3003
3004 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
3005 if (ret) {
3006 if (ret->pid != LLDB_INVALID_PROCESS_ID)
3007 m_curr_pid_run = ret->pid;
3008 m_curr_tid_run = ret->tid;
3009 }
3010 return ret.has_value();
3011}
3012
3014 StringExtractorGDBRemote &response) {
3016 return response.IsNormalResponse();
3017 return false;
3018}
3019
3021 lldb::tid_t tid, StringExtractorGDBRemote &response) {
3023 char packet[256];
3024 int packet_len =
3025 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3026 assert(packet_len < (int)sizeof(packet));
3027 UNUSED_IF_ASSERT_DISABLED(packet_len);
3028 if (SendPacketAndWaitForResponse(packet, response) ==
3030 if (response.IsUnsupportedResponse())
3032 else if (response.IsNormalResponse())
3033 return true;
3034 else
3035 return false;
3036 } else {
3038 }
3039 }
3040 return false;
3041}
3042
3044 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
3045 std::chrono::seconds timeout) {
3047 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3048 __FUNCTION__, insert ? "add" : "remove", addr);
3049
3050 // Check if the stub is known not to support this breakpoint type
3051 if (!SupportsGDBStoppointPacket(type))
3052 return UINT8_MAX;
3053 // Construct the breakpoint packet
3054 char packet[64];
3055 const int packet_len =
3056 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
3057 insert ? 'Z' : 'z', type, addr, length);
3058 // Check we haven't overwritten the end of the packet buffer
3059 assert(packet_len + 1 < (int)sizeof(packet));
3060 UNUSED_IF_ASSERT_DISABLED(packet_len);
3061 StringExtractorGDBRemote response;
3062 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
3063 // or "" (unsupported)
3065 // Try to send the breakpoint packet, and check that it was correctly sent
3066 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
3068 // Receive and OK packet when the breakpoint successfully placed
3069 if (response.IsOKResponse())
3070 return 0;
3071
3072 // Status while setting breakpoint, send back specific error
3073 if (response.IsErrorResponse())
3074 return response.GetError();
3075
3076 // Empty packet informs us that breakpoint is not supported
3077 if (response.IsUnsupportedResponse()) {
3078 // Disable this breakpoint type since it is unsupported
3079 switch (type) {
3081 m_supports_z0 = false;
3082 break;
3084 m_supports_z1 = false;
3085 break;
3086 case eWatchpointWrite:
3087 m_supports_z2 = false;
3088 break;
3089 case eWatchpointRead:
3090 m_supports_z3 = false;
3091 break;
3093 m_supports_z4 = false;
3094 break;
3095 case eStoppointInvalid:
3096 return UINT8_MAX;
3097 }
3098 }
3099 }
3100 // Signal generic failure
3101 return UINT8_MAX;
3102}
3103
3104std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
3106 bool &sequence_mutex_unavailable) {
3107 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
3108
3109 Lock lock(*this);
3110 if (lock) {
3111 sequence_mutex_unavailable = false;
3112 StringExtractorGDBRemote response;
3113
3114 PacketResult packet_result;
3115 for (packet_result =
3116 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
3117 packet_result == PacketResult::Success && response.IsNormalResponse();
3118 packet_result =
3119 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
3120 char ch = response.GetChar();
3121 if (ch == 'l')
3122 break;
3123 if (ch == 'm') {
3124 do {
3125 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
3126 // If we get an invalid response, break out of the loop.
3127 // If there are valid tids, they have been added to ids.
3128 // If there are no valid tids, we'll fall through to the
3129 // bare-iron target handling below.
3130 if (!pid_tid)
3131 break;
3132
3133 ids.push_back(*pid_tid);
3134 ch = response.GetChar(); // Skip the command separator
3135 } while (ch == ','); // Make sure we got a comma separator
3136 }
3137 }
3138
3139 /*
3140 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3141 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
3142 * could
3143 * be as simple as 'S05'. There is no packet which can give us pid and/or
3144 * tid.
3145 * Assume pid=tid=1 in such cases.
3146 */
3147 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
3148 ids.size() == 0 && IsConnected()) {
3149 ids.emplace_back(1, 1);
3150 }
3151 } else {
3153 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
3154 "packet 'qfThreadInfo'");
3155 sequence_mutex_unavailable = true;
3156 }
3157
3158 return ids;
3159}
3160
3162 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
3164 thread_ids.clear();
3165
3166 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
3167 if (ids.empty() || sequence_mutex_unavailable)
3168 return 0;
3169
3170 for (auto id : ids) {
3171 // skip threads that do not belong to the current process
3172 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
3173 continue;
3174 if (id.second != LLDB_INVALID_THREAD_ID &&
3176 thread_ids.push_back(id.second);
3177 }
3178
3179 return thread_ids.size();
3180}
3181
3183 StringExtractorGDBRemote response;
3184 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
3186 !response.IsNormalResponse())
3187 return LLDB_INVALID_ADDRESS;
3188 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3189}
3190
3192 llvm::StringRef command,
3193 const FileSpec &
3194 working_dir, // Pass empty FileSpec to use the current working directory
3195 int *status_ptr, // Pass NULL if you don't want the process exit status
3196 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
3197 // process to exit
3198 std::string
3199 *command_output, // Pass nullptr if you don't want the command output
3200 std::string *separated_error_output, // Pass nullptr if you don't want the
3201 // command error output
3202 const Timeout<std::micro> &timeout) {
3204 stream.PutCString("qPlatform_shell:");
3205 stream.PutBytesAsRawHex8(command.data(), command.size());
3206 stream.PutChar(',');
3207 uint32_t timeout_sec = UINT32_MAX;
3208 if (timeout) {
3209 // TODO: Use chrono version of std::ceil once c++17 is available.
3210 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
3211 }
3212 stream.PutHex32(timeout_sec);
3213 if (working_dir) {
3214 std::string path{working_dir.GetPath(false)};
3215 stream.PutChar(',');
3216 stream.PutStringAsRawHex8(path);
3217 }
3218 StringExtractorGDBRemote response;
3219 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3221 if (response.GetChar() != 'F')
3222 return Status::FromErrorString("malformed reply");
3223 if (response.GetChar() != ',')
3224 return Status::FromErrorString("malformed reply");
3225 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3226 if (exitcode == UINT32_MAX)
3227 return Status::FromErrorString("unable to run remote process");
3228 else if (status_ptr)
3229 *status_ptr = exitcode;
3230 if (response.GetChar() != ',')
3231 return Status::FromErrorString("malformed reply");
3232 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3233 if (signo_ptr)
3234 *signo_ptr = signo;
3235 if (response.GetChar() != ',')
3236 return Status::FromErrorString("malformed reply");
3237 std::string output;
3238 response.GetEscapedBinaryData(output);
3239 if (command_output)
3240 command_output->assign(output);
3241 return Status();
3242 }
3243 return Status::FromErrorString("unable to send packet");
3244}
3245
3247 uint32_t file_permissions) {
3248 std::string path{file_spec.GetPath(false)};
3250 stream.PutCString("qPlatform_mkdir:");
3251 stream.PutHex32(file_permissions);
3252 stream.PutChar(',');
3253 stream.PutStringAsRawHex8(path);
3254 llvm::StringRef packet = stream.GetString();
3255 StringExtractorGDBRemote response;
3256
3257 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3258 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3259 packet.str().c_str());
3260
3261 if (response.GetChar() != 'F')
3262 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3263 packet.str().c_str());
3264
3265 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3266}
3267
3268Status
3270 uint32_t file_permissions) {
3271 std::string path{file_spec.GetPath(false)};
3273 stream.PutCString("qPlatform_chmod:");
3274 stream.PutHex32(file_permissions);
3275 stream.PutChar(',');
3276 stream.PutStringAsRawHex8(path);
3277 llvm::StringRef packet = stream.GetString();
3278 StringExtractorGDBRemote response;
3279
3280 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3281 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3282 stream.GetData());
3283
3284 if (response.GetChar() != 'F')
3285 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3286 stream.GetData());
3287
3288 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3289}
3290
3291static int gdb_errno_to_system(int err) {
3292 switch (err) {
3293#define HANDLE_ERRNO(name, value) \
3294 case GDB_##name: \
3295 return name;
3296#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3297 default:
3298 return -1;
3299 }
3300}
3301
3303 uint64_t fail_result, Status &error) {
3304 response.SetFilePos(0);
3305 if (response.GetChar() != 'F')
3306 return fail_result;
3307 int32_t result = response.GetS32(-2, 16);
3308 if (result == -2)
3309 return fail_result;
3310 if (response.GetChar() == ',') {
3311 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3312 if (result_errno != -1)
3313 error = Status(result_errno, eErrorTypePOSIX);
3314 else
3316 } else
3317 error.Clear();
3318 return result;
3319}
3322 File::OpenOptions flags, mode_t mode,
3323 Status &error) {
3324 std::string path(file_spec.GetPath(false));
3326 stream.PutCString("vFile:open:");
3327 if (path.empty())
3328 return UINT64_MAX;
3329 stream.PutStringAsRawHex8(path);
3330 stream.PutChar(',');
3331 stream.PutHex32(flags);
3332 stream.PutChar(',');
3333 stream.PutHex32(mode);
3334 StringExtractorGDBRemote response;
3335 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3337 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3338 }
3339 return UINT64_MAX;
3340}
3341
3343 Status &error) {
3345 stream.Printf("vFile:close:%x", (int)fd);
3346 StringExtractorGDBRemote response;
3347 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3349 return ParseHostIOPacketResponse(response, -1, error) == 0;
3350 }
3351 return false;
3352}
3353
3354std::optional<GDBRemoteFStatData>
3357 stream.Printf("vFile:fstat:%" PRIx64, fd);
3358 StringExtractorGDBRemote response;
3359 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3361 if (response.GetChar() != 'F')
3362 return std::nullopt;
3363 int64_t size = response.GetS64(-1, 16);
3364 if (size > 0 && response.GetChar() == ';') {
3365 std::string buffer;
3366 if (response.GetEscapedBinaryData(buffer)) {
3368 if (buffer.size() != sizeof(out))
3369 return std::nullopt;
3370 memcpy(&out, buffer.data(), sizeof(out));
3371 return out;
3372 }
3373 }
3374 }
3375 return std::nullopt;
3376}
3377
3378std::optional<GDBRemoteFStatData>
3380 Status error;
3382 if (fd == UINT64_MAX)
3383 return std::nullopt;
3384 std::optional<GDBRemoteFStatData> st = FStat(fd);
3385 CloseFile(fd, error);
3386 return st;
3387}
3388
3389// Extension of host I/O packets to get the file size.
3391 const lldb_private::FileSpec &file_spec) {
3393 std::string path(file_spec.GetPath(false));
3395 stream.PutCString("vFile:size:");
3396 stream.PutStringAsRawHex8(path);
3397 StringExtractorGDBRemote response;
3398 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3400 return UINT64_MAX;
3401
3402 if (!response.IsUnsupportedResponse()) {
3403 if (response.GetChar() != 'F')
3404 return UINT64_MAX;
3405 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3406 return retcode;
3407 }
3408 m_supports_vFileSize = false;
3409 }
3410
3411 // Fallback to fstat.
3412 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3413 return st ? st->gdb_st_size : UINT64_MAX;
3414}
3415
3417 CompletionRequest &request, bool only_dir) {
3419 stream.PutCString("qPathComplete:");
3420 stream.PutHex32(only_dir ? 1 : 0);
3421 stream.PutChar(',');
3423 StringExtractorGDBRemote response;
3424 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3426 StreamString strm;
3427 char ch = response.GetChar();
3428 if (ch != 'M')
3429 return;
3430 while (response.Peek()) {
3431 strm.Clear();
3432 while ((ch = response.GetHexU8(0, false)) != '\0')
3433 strm.PutChar(ch);
3434 request.AddCompletion(strm.GetString());
3435 if (response.GetChar() != ',')
3436 break;
3437 }
3438 }
3439}
3440
3441Status
3443 uint32_t &file_permissions) {
3445 std::string path{file_spec.GetPath(false)};
3446 Status error;
3448 stream.PutCString("vFile:mode:");
3449 stream.PutStringAsRawHex8(path);
3450 StringExtractorGDBRemote response;
3451 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3453 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3454 stream.GetData());
3455 return error;
3456 }
3457 if (!response.IsUnsupportedResponse()) {
3458 if (response.GetChar() != 'F') {
3460 "invalid response to '%s' packet", stream.GetData());
3461 } else {
3462 const uint32_t mode = response.GetS32(-1, 16);
3463 if (static_cast<int32_t>(mode) == -1) {
3464 if (response.GetChar() == ',') {
3465 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3466 if (response_errno > 0)
3467 error = Status(response_errno, lldb::eErrorTypePOSIX);
3468 else
3469 error = Status::FromErrorString("unknown error");
3470 } else
3471 error = Status::FromErrorString("unknown error");
3472 } else {
3473 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3474 }
3475 }
3476 return error;
3477 } else { // response.IsUnsupportedResponse()
3478 m_supports_vFileMode = false;
3479 }
3480 }
3481
3482 // Fallback to fstat.
3483 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3484 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3485 return Status();
3486 }
3487 return Status::FromErrorString("fstat failed");
3488}
3489
3491 uint64_t offset, void *dst,
3492 uint64_t dst_len,
3493 Status &error) {
3495 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3496 offset);
3497 StringExtractorGDBRemote response;
3498 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3500 if (response.GetChar() != 'F')
3501 return 0;
3502 int64_t retcode = response.GetS64(-1, 16);
3503 if (retcode == -1) {
3504 error = Status::FromErrorString("unknown error");
3505 if (response.GetChar() == ',') {
3506 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3507 if (response_errno > 0)
3508 error = Status(response_errno, lldb::eErrorTypePOSIX);
3509 }
3510 return -1;
3511 }
3512 const char next = (response.Peek() ? *response.Peek() : 0);
3513 if (next == ',')
3514 return 0;
3515 if (next == ';') {
3516 response.GetChar(); // skip the semicolon
3517 std::string buffer;
3518 if (response.GetEscapedBinaryData(buffer)) {
3519 const uint64_t data_to_write =
3520 std::min<uint64_t>(dst_len, buffer.size());
3521 if (data_to_write > 0)
3522 memcpy(dst, &buffer[0], data_to_write);
3523 return data_to_write;
3524 }
3525 }
3526 }
3527 return 0;
3528}
3529
3531 uint64_t offset,
3532 const void *src,
3533 uint64_t src_len,
3534 Status &error) {
3536 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3537 stream.PutEscapedBytes(src, src_len);
3538 StringExtractorGDBRemote response;
3539 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3541 if (response.GetChar() != 'F') {
3542 error = Status::FromErrorStringWithFormat("write file failed");
3543 return 0;
3544 }
3545 int64_t bytes_written = response.GetS64(-1, 16);
3546 if (bytes_written == -1) {
3547 error = Status::FromErrorString("unknown error");
3548 if (response.GetChar() == ',') {
3549 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3550 if (response_errno > 0)
3551 error = Status(response_errno, lldb::eErrorTypePOSIX);
3552 }
3553 return -1;
3554 }
3555 return bytes_written;
3556 } else {
3557 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3558 }
3559 return 0;
3560}
3561
3563 const FileSpec &dst) {
3564 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3565 Status error;
3567 stream.PutCString("vFile:symlink:");
3568 // the unix symlink() command reverses its parameters where the dst if first,
3569 // so we follow suit here
3570 stream.PutStringAsRawHex8(dst_path);
3571 stream.PutChar(',');
3572 stream.PutStringAsRawHex8(src_path);
3573 StringExtractorGDBRemote response;
3574 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3576 if (response.GetChar() == 'F') {
3577 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3578 if (result != 0) {
3579 error = Status::FromErrorString("unknown error");
3580 if (response.GetChar() == ',') {
3581 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3582 if (response_errno > 0)
3583 error = Status(response_errno, lldb::eErrorTypePOSIX);
3584 }
3585 }
3586 } else {
3587 // Should have returned with 'F<result>[,<errno>]'
3588 error = Status::FromErrorStringWithFormat("symlink failed");
3589 }
3590 } else {
3591 error = Status::FromErrorString("failed to send vFile:symlink packet");
3592 }
3593 return error;
3594}
3595
3597 std::string path{file_spec.GetPath(false)};
3598 Status error;
3600 stream.PutCString("vFile:unlink:");
3601 // the unix symlink() command reverses its parameters where the dst if first,
3602 // so we follow suit here
3603 stream.PutStringAsRawHex8(path);
3604 StringExtractorGDBRemote response;
3605 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3607 if (response.GetChar() == 'F') {
3608 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3609 if (result != 0) {
3610 error = Status::FromErrorString("unknown error");
3611 if (response.GetChar() == ',') {
3612 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3613 if (response_errno > 0)
3614 error = Status(response_errno, lldb::eErrorTypePOSIX);
3615 }
3616 }
3617 } else {
3618 // Should have returned with 'F<result>[,<errno>]'
3619 error = Status::FromErrorStringWithFormat("unlink failed");
3620 }
3621 } else {
3622 error = Status::FromErrorString("failed to send vFile:unlink packet");
3623 }
3624 return error;
3625}
3626
3627// Extension of host I/O packets to get whether a file exists.
3629 const lldb_private::FileSpec &file_spec) {
3631 std::string path(file_spec.GetPath(false));
3633 stream.PutCString("vFile:exists:");
3634 stream.PutStringAsRawHex8(path);
3635 StringExtractorGDBRemote response;
3636 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3638 return false;
3639 if (!response.IsUnsupportedResponse()) {
3640 if (response.GetChar() != 'F')
3641 return false;
3642 if (response.GetChar() != ',')
3643 return false;
3644 bool retcode = (response.GetChar() != '0');
3645 return retcode;
3646 } else
3647 m_supports_vFileExists = false;
3648 }
3649
3650 // Fallback to open.
3651 Status error;
3653 if (fd == UINT64_MAX)
3654 return false;
3655 CloseFile(fd, error);
3656 return true;
3657}
3658
3659llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3660 const lldb_private::FileSpec &file_spec) {
3661 std::string path(file_spec.GetPath(false));
3663 stream.PutCString("vFile:MD5:");
3664 stream.PutStringAsRawHex8(path);
3665 StringExtractorGDBRemote response;
3666 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3668 if (response.GetChar() != 'F')
3669 return std::make_error_code(std::errc::illegal_byte_sequence);
3670 if (response.GetChar() != ',')
3671 return std::make_error_code(std::errc::illegal_byte_sequence);
3672 if (response.Peek() && *response.Peek() == 'x')
3673 return std::make_error_code(std::errc::no_such_file_or_directory);
3674
3675 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3676 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3677 // handle the concatenated hex string. What would happen is parsing the low
3678 // would consume the whole response packet which would give incorrect
3679 // results. Instead, we get the byte string for each low and high hex
3680 // separately, and parse them.
3681 //
3682 // An alternate way to handle this is to change the server to put a
3683 // delimiter between the low/high parts, and change the client to parse the
3684 // delimiter. However, we choose not to do this so existing lldb-servers
3685 // don't have to be patched
3686
3687 // The checksum is 128 bits encoded as hex
3688 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3689 // Each byte takes 2 hex characters in the response.
3690 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3691
3692 // Get low part
3693 auto part =
3694 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3695 if (part.size() != MD5_HALF_LENGTH)
3696 return std::make_error_code(std::errc::illegal_byte_sequence);
3697 response.SetFilePos(response.GetFilePos() + part.size());
3698
3699 uint64_t low;
3700 if (part.getAsInteger(BASE_16, low))
3701 return std::make_error_code(std::errc::illegal_byte_sequence);
3702
3703 // Get high part
3704 part =
3705 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3706 if (part.size() != MD5_HALF_LENGTH)
3707 return std::make_error_code(std::errc::illegal_byte_sequence);
3708 response.SetFilePos(response.GetFilePos() + part.size());
3709
3710 uint64_t high;
3711 if (part.getAsInteger(BASE_16, high))
3712 return std::make_error_code(std::errc::illegal_byte_sequence);
3713
3714 llvm::MD5::MD5Result result;
3715 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3716 result.data(), low);
3717 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3718 result.data() + 8, high);
3719
3720 return result;
3721 }
3722 return std::make_error_code(std::errc::operation_canceled);
3723}
3724
3726 // Some targets have issues with g/G packets and we need to avoid using them
3728 if (process) {
3730 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3731 if (arch.IsValid() &&
3732 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3733 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3734 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3735 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3737 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3738 if (gdb_server_version != 0) {
3739 const char *gdb_server_name = GetGDBServerProgramName();
3740 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3741 if (gdb_server_version >= 310)
3743 }
3744 }
3745 }
3746 }
3747 }
3749}
3750
3752 uint32_t reg) {
3753 StreamString payload;
3754 payload.Printf("p%x", reg);
3755 StringExtractorGDBRemote response;
3757 tid, std::move(payload), response) != PacketResult::Success ||
3758 !response.IsNormalResponse())
3759 return nullptr;
3760
3761 WritableDataBufferSP buffer_sp(
3762 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3763 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3764 return buffer_sp;
3765}
3766
3768 StreamString payload;
3769 payload.PutChar('g');
3770 StringExtractorGDBRemote response;
3772 tid, std::move(payload), response) != PacketResult::Success ||
3773 !response.IsNormalResponse())
3774 return nullptr;
3775
3776 WritableDataBufferSP buffer_sp(
3777 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3778 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3779 return buffer_sp;
3780}
3781
3783 uint32_t reg_num,
3784 llvm::ArrayRef<uint8_t> data) {
3785 StreamString payload;
3786 payload.Printf("P%x=", reg_num);
3787 payload.PutBytesAsRawHex8(data.data(), data.size(),
3790 StringExtractorGDBRemote response;
3792 tid, std::move(payload), response) == PacketResult::Success &&
3793 response.IsOKResponse();
3794}
3795
3797 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3798 StreamString payload;
3799 payload.PutChar('G');
3800 payload.PutBytesAsRawHex8(data.data(), data.size(),
3803 StringExtractorGDBRemote response;
3805 tid, std::move(payload), response) == PacketResult::Success &&
3806 response.IsOKResponse();
3807}
3808
3810 uint32_t &save_id) {
3811 save_id = 0; // Set to invalid save ID
3813 return false;
3814
3816 StreamString payload;
3817 payload.PutCString("QSaveRegisterState");
3818 StringExtractorGDBRemote response;
3820 tid, std::move(payload), response) != PacketResult::Success)
3821 return false;
3822
3823 if (response.IsUnsupportedResponse())
3825
3826 const uint32_t response_save_id = response.GetU32(0);
3827 if (response_save_id == 0)
3828 return false;
3829
3830 save_id = response_save_id;
3831 return true;
3832}
3833
3835 uint32_t save_id) {
3836 // We use the "m_supports_QSaveRegisterState" variable here because the
3837 // QSaveRegisterState and QRestoreRegisterState packets must both be
3838 // supported in order to be useful
3840 return false;
3841
3842 StreamString payload;
3843 payload.Printf("QRestoreRegisterState:%u", save_id);
3844 StringExtractorGDBRemote response;
3846 tid, std::move(payload), response) != PacketResult::Success)
3847 return false;
3848
3849 if (response.IsOKResponse())
3850 return true;
3851
3852 if (response.IsUnsupportedResponse())
3854 return false;
3855}
3856
3859 return false;
3860
3861 StreamString packet;
3862 StringExtractorGDBRemote response;
3863 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3864 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3866 response.IsOKResponse();
3867}
3868
3869llvm::Expected<TraceSupportedResponse>
3871 Log *log = GetLog(GDBRLog::Process);
3872
3873 StreamGDBRemote escaped_packet;
3874 escaped_packet.PutCString("jLLDBTraceSupported");
3875
3876 StringExtractorGDBRemote response;
3877 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3878 timeout) ==
3880 if (response.IsErrorResponse())
3881 return response.GetStatus().ToError();
3882 if (response.IsUnsupportedResponse())
3883 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3884 "jLLDBTraceSupported is unsupported");
3885
3886 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3887 "TraceSupportedResponse");
3888 }
3889 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3890 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3891 "failed to send packet: jLLDBTraceSupported");
3892}
3893
3894llvm::Error
3896 std::chrono::seconds timeout) {
3897 Log *log = GetLog(GDBRLog::Process);
3898
3899 StreamGDBRemote escaped_packet;
3900 escaped_packet.PutCString("jLLDBTraceStop:");
3901
3902 std::string json_string;
3903 llvm::raw_string_ostream os(json_string);
3904 os << toJSON(request);
3905
3906 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3907
3908 StringExtractorGDBRemote response;
3909 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3910 timeout) ==
3912 if (response.IsErrorResponse())
3913 return response.GetStatus().ToError();
3914 if (response.IsUnsupportedResponse())
3915 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3916 "jLLDBTraceStop is unsupported");
3917 if (response.IsOKResponse())
3918 return llvm::Error::success();
3919 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3920 "Invalid jLLDBTraceStart response");
3921 }
3922 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3923 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3924 "failed to send packet: jLLDBTraceStop '%s'",
3925 escaped_packet.GetData());
3926}
3927
3928llvm::Error
3929GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3930 std::chrono::seconds timeout) {
3931 Log *log = GetLog(GDBRLog::Process);
3932
3933 StreamGDBRemote escaped_packet;
3934 escaped_packet.PutCString("jLLDBTraceStart:");
3935
3936 std::string json_string;
3937 llvm::raw_string_ostream os(json_string);
3938 os << params;
3939
3940 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3941
3942 StringExtractorGDBRemote response;
3943 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3944 timeout) ==
3946 if (response.IsErrorResponse())
3947 return response.GetStatus().ToError();
3948 if (response.IsUnsupportedResponse())
3949 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3950 "jLLDBTraceStart is unsupported");
3951 if (response.IsOKResponse())
3952 return llvm::Error::success();
3953 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3954 "Invalid jLLDBTraceStart response");
3955 }
3956 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3957 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3958 "failed to send packet: jLLDBTraceStart '%s'",
3959 escaped_packet.GetData());
3960}
3961
3962llvm::Expected<std::string>
3964 std::chrono::seconds timeout) {
3965 Log *log = GetLog(GDBRLog::Process);
3966
3967 StreamGDBRemote escaped_packet;
3968 escaped_packet.PutCString("jLLDBTraceGetState:");
3969
3970 std::string json_string;
3971 llvm::raw_string_ostream os(json_string);
3972 os << toJSON(TraceGetStateRequest{type.str()});
3973
3974 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3975
3976 StringExtractorGDBRemote response;
3977 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3978 timeout) ==
3980 if (response.IsErrorResponse())
3981 return response.GetStatus().ToError();
3982 if (response.IsUnsupportedResponse())
3983 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3984 "jLLDBTraceGetState is unsupported");
3985 return std::string(response.Peek());
3986 }
3987
3988 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3989 return llvm::createStringError(
3990 llvm::inconvertibleErrorCode(),
3991 "failed to send packet: jLLDBTraceGetState '%s'",
3992 escaped_packet.GetData());
3993}
3994
3995llvm::Expected<std::vector<uint8_t>>
3997 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3998 Log *log = GetLog(GDBRLog::Process);
3999
4000 StreamGDBRemote escaped_packet;
4001 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
4002
4003 std::string json_string;
4004 llvm::raw_string_ostream os(json_string);
4005 os << toJSON(request);
4006
4007 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
4008
4009 StringExtractorGDBRemote response;
4010 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
4011 timeout) ==
4013 if (response.IsErrorResponse())
4014 return response.GetStatus().ToError();
4015 std::string data;
4016 response.GetEscapedBinaryData(data);
4017 return std::vector<uint8_t>(data.begin(), data.end());
4018 }
4019 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
4020 return llvm::createStringError(
4021 llvm::inconvertibleErrorCode(),
4022 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
4023 escaped_packet.GetData());
4024}
4025
4027 StringExtractorGDBRemote response;
4028 if (SendPacketAndWaitForResponse("qOffsets", response) !=
4030 return std::nullopt;
4031 if (!response.IsNormalResponse())
4032 return std::nullopt;
4033
4034 QOffsets result;
4035 llvm::StringRef ref = response.GetStringRef();
4036 const auto &GetOffset = [&] {
4037 addr_t offset;
4038 if (ref.consumeInteger(16, offset))
4039 return false;
4040 result.offsets.push_back(offset);
4041 return true;
4042 };
4043
4044 if (ref.consume_front("Text=")) {
4045 result.segments = false;
4046 if (!GetOffset())
4047 return std::nullopt;
4048 if (!ref.consume_front(";Data=") || !GetOffset())
4049 return std::nullopt;
4050 if (ref.empty())
4051 return result;
4052 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
4053 return result;
4054 } else if (ref.consume_front("TextSeg=")) {
4055 result.segments = true;
4056 if (!GetOffset())
4057 return std::nullopt;
4058 if (ref.empty())
4059 return result;
4060 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
4061 return result;
4062 }
4063 return std::nullopt;
4064}
4065
4067 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
4068 ModuleSpec &module_spec) {
4070 return false;
4071
4072 std::string module_path = module_file_spec.GetPath(false);
4073 if (module_path.empty())
4074 return false;
4075
4076 StreamString packet;
4077 packet.PutCString("qModuleInfo:");
4078 packet.PutStringAsRawHex8(module_path);
4079 packet.PutCString(";");
4080 const auto &triple = arch_spec.GetTriple().getTriple();
4081 packet.PutStringAsRawHex8(triple);
4082
4083 StringExtractorGDBRemote response;
4084 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
4086 return false;
4087
4088 if (response.IsErrorResponse())
4089 return false;
4090
4091 if (response.IsUnsupportedResponse()) {
4092 m_supports_qModuleInfo = false;
4093 return false;
4094 }
4095
4096 llvm::StringRef name;
4097 llvm::StringRef value;
4098
4099 module_spec.Clear();
4100 module_spec.GetFileSpec() = module_file_spec;
4101
4102 while (response.GetNameColonValue(name, value)) {
4103 if (name == "uuid" || name == "md5") {
4104 StringExtractor extractor(value);
4105 std::string uuid;
4106 extractor.GetHexByteString(uuid);
4107 module_spec.GetUUID().SetFromStringRef(uuid);
4108 } else if (name == "triple") {
4109 StringExtractor extractor(value);
4110 std::string triple;
4111 extractor.GetHexByteString(triple);
4112 module_spec.GetArchitecture().SetTriple(triple.c_str());
4113 } else if (name == "file_offset") {
4114 uint64_t ival = 0;
4115 if (!value.getAsInteger(BASE_16, ival))
4116 module_spec.SetObjectOffset(ival);
4117 } else if (name == "file_size") {
4118 uint64_t ival = 0;
4119 if (!value.getAsInteger(BASE_16, ival))
4120 module_spec.SetObjectSize(ival);
4121 } else if (name == "file_path") {
4122 StringExtractor extractor(value);
4123 std::string path;
4124 extractor.GetHexByteString(path);
4125 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
4126 }
4127 }
4128
4129 return true;
4130}
4131
4132static std::optional<ModuleSpec>
4134 ModuleSpec result;
4135 if (!dict)
4136 return std::nullopt;
4137
4138 llvm::StringRef string;
4139 uint64_t integer;
4140
4141 if (!dict->GetValueForKeyAsString("uuid", string))
4142 return std::nullopt;
4143 if (!result.GetUUID().SetFromStringRef(string))
4144 return std::nullopt;
4145
4146 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
4147 return std::nullopt;
4148 result.SetObjectOffset(integer);
4149
4150 if (!dict->GetValueForKeyAsInteger("file_size", integer))
4151 return std::nullopt;
4152 result.SetObjectSize(integer);
4153
4154 if (!dict->GetValueForKeyAsString("triple", string))
4155 return std::nullopt;
4156 result.GetArchitecture().SetTriple(string);
4157
4158 if (!dict->GetValueForKeyAsString("file_path", string))
4159 return std::nullopt;
4160 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
4161
4162 return result;
4163}
4164
4165std::optional<std::vector<ModuleSpec>>
4167 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4168 namespace json = llvm::json;
4169
4171 return std::nullopt;
4172
4173 json::Array module_array;
4174 for (const FileSpec &module_file_spec : module_file_specs) {
4175 module_array.push_back(
4176 json::Object{{"file", module_file_spec.GetPath(false)},
4177 {"triple", triple.getTriple()}});
4178 }
4179 StreamString unescaped_payload;
4180 unescaped_payload.PutCString("jModulesInfo:");
4181 unescaped_payload.AsRawOstream() << std::move(module_array);
4182
4183 StreamGDBRemote payload;
4184 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
4185 unescaped_payload.GetSize());
4186
4187 // Increase the timeout for jModulesInfo since this packet can take longer.
4188 ScopedTimeout timeout(*this, std::chrono::seconds(10));
4189
4190 StringExtractorGDBRemote response;
4191 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
4193 response.IsErrorResponse())
4194 return std::nullopt;
4195
4196 if (response.IsUnsupportedResponse()) {
4198 return std::nullopt;
4199 }
4200
4201 StructuredData::ObjectSP response_object_sp =
4203 if (!response_object_sp)
4204 return std::nullopt;
4205
4206 StructuredData::Array *response_array = response_object_sp->GetAsArray();
4207 if (!response_array)
4208 return std::nullopt;
4209
4210 std::vector<ModuleSpec> result;
4211 for (size_t i = 0; i < response_array->GetSize(); ++i) {
4212 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4213 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4214 result.push_back(*module_spec);
4215 }
4216
4217 return result;
4218}
4219
4220// query the target remote for extended information using the qXfer packet
4221//
4222// example: object='features', annex='target.xml'
4223// return: <xml output> or error
4224llvm::Expected<std::string>
4226 llvm::StringRef annex) {
4227
4228 std::string output;
4229 llvm::raw_string_ostream output_stream(output);
4231
4232 uint64_t size = GetRemoteMaxPacketSize();
4233 if (size == 0)
4234 size = 0x1000;
4235 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4236 int offset = 0;
4237 bool active = true;
4238
4239 // loop until all data has been read
4240 while (active) {
4241
4242 // send query extended feature packet
4243 std::string packet =
4244 ("qXfer:" + object + ":read:" + annex + ":" +
4245 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4246 .str();
4247
4249 SendPacketAndWaitForResponse(packet, chunk);
4250
4252 chunk.GetStringRef().empty()) {
4253 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4254 "Error sending $qXfer packet");
4255 }
4256
4257 // check packet code
4258 switch (chunk.GetStringRef()[0]) {
4259 // last chunk
4260 case ('l'):
4261 active = false;
4262 [[fallthrough]];
4263
4264 // more chunks
4265 case ('m'):
4266 output_stream << chunk.GetStringRef().drop_front();
4267 offset += chunk.GetStringRef().size() - 1;
4268 break;
4269
4270 // unknown chunk
4271 default:
4272 return llvm::createStringError(
4273 llvm::inconvertibleErrorCode(),
4274 "Invalid continuation code from $qXfer packet");
4275 }
4276 }
4277
4278 return output;
4279}
4280
4281llvm::Expected<std::string>
4283 // qXfer:siginfo:read returns the siginfo of the thread selected by the Hg
4284 // packet. Hold the lock to make sure nobody selects a different thread
4285 // before we're done.
4286 Lock lock(*this);
4287 if (!lock)
4288 return llvm::createStringError("failed to get the sequence mutex");
4289 if (!SetCurrentThread(tid))
4290 return llvm::createStringError("failed to select thread");
4291 return ReadExtFeature("siginfo", "");
4292}
4293
4294// Notify the target that gdb is prepared to serve symbol lookup requests.
4295// packet: "qSymbol::"
4296// reply:
4297// OK The target does not need to look up any (more) symbols.
4298// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4299// encoded).
4300// LLDB may provide the value by sending another qSymbol
4301// packet
4302// in the form of"qSymbol:<sym_value>:<sym_name>".
4303//
4304// Three examples:
4305//
4306// lldb sends: qSymbol::
4307// lldb receives: OK
4308// Remote gdb stub does not need to know the addresses of any symbols, lldb
4309// does not
4310// need to ask again in this session.
4311//
4312// lldb sends: qSymbol::
4313// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4314// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4315// lldb receives: OK
4316// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4317// not know
4318// the address at this time. lldb needs to send qSymbol:: again when it has
4319// more
4320// solibs loaded.
4321//
4322// lldb sends: qSymbol::
4323// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4324// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4325// lldb receives: OK
4326// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4327// that it
4328// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4329// does not
4330// need any more symbols. lldb does not need to ask again in this session.
4331
4333 lldb_private::Process *process) {
4334 // Set to true once we've resolved a symbol to an address for the remote
4335 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4336 // any more symbols and we can stop asking.
4337 bool symbol_response_provided = false;
4338
4339 // Is this the initial qSymbol:: packet?
4340 bool first_qsymbol_query = true;
4341
4343 Lock lock(*this);
4344 if (lock) {
4345 StreamString packet;
4346 packet.PutCString("qSymbol::");
4347 StringExtractorGDBRemote response;
4348 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4350 if (response.IsOKResponse()) {
4351 if (symbol_response_provided || first_qsymbol_query) {
4353 }
4354
4355 // We are done serving symbols requests
4356 return;
4357 }
4358 first_qsymbol_query = false;
4359
4360 if (response.IsUnsupportedResponse()) {
4361 // qSymbol is not supported by the current GDB server we are
4362 // connected to
4363 m_supports_qSymbol = false;
4364 return;
4365 } else {
4366 llvm::StringRef response_str(response.GetStringRef());
4367 if (response_str.starts_with("qSymbol:")) {
4368 response.SetFilePos(strlen("qSymbol:"));
4369 std::string symbol_name;
4370 if (response.GetHexByteString(symbol_name)) {
4371 if (symbol_name.empty())
4372 return;
4373
4374 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4377 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4378 for (const SymbolContext &sc : sc_list) {
4379 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4380 break;
4381 if (sc.symbol) {
4382 switch (sc.symbol->GetType()) {
4383 case eSymbolTypeInvalid:
4390 case eSymbolTypeBlock:
4391 case eSymbolTypeLocal:
4392 case eSymbolTypeParam:
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 uniqued constant string class.
Definition ConstString.h:40
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(ConstString 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:369
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
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:1283
const ArchSpec & GetArchitecture() const
Definition Target.h:1325
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)
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)
llvm::Error LaunchProcess(const Args &args)
Launch the process using the provided arguments.
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
@ 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