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
279llvm::Expected<AcceleratorBreakpointHitResponse>
281 const AcceleratorBreakpointHitArgs &args) {
282 StreamGDBRemote packet;
283 packet.PutCString("jAcceleratorPluginBreakpointHit:");
284 packet.PutAsJSON(args, /*hex_ascii=*/false);
285
287 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
289 return llvm::createStringError(
290 "failed to send jAcceleratorPluginBreakpointHit packet");
291
292 if (response.IsErrorResponse())
293 return response.GetStatus().takeError();
294
295 llvm::Expected<AcceleratorBreakpointHitResponse> hit_response =
296 llvm::json::parse<AcceleratorBreakpointHitResponse>(
297 response.Peek(), "AcceleratorBreakpointHitResponse");
298 if (hit_response)
299 return hit_response;
300
301 // A bare JSON parse error (e.g. "missing comma at line 4") is meaningless on
302 // its own, so include both the full response and the parse error; the caller
303 // logs this and the user can spot the problem in the response.
304 return llvm::createStringErrorV(
305 "malformed jAcceleratorPluginBreakpointHit response '{0}': {1}",
306 response.GetStringRef(), llvm::toString(hit_response.takeError()));
307}
308
311 m_send_acks = true;
313
314 // This is the first real packet that we'll send in a debug session and it
315 // may take a little longer than normal to receive a reply. Wait at least
316 // 6 seconds for a reply to this packet.
317
318 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
319
321 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) ==
323 if (response.IsOKResponse()) {
324 m_send_acks = false;
326 }
327 return true;
328 }
329 }
330 return false;
331}
332
345
359
373
375 if (!did_exec) {
376 // Hard reset everything, this is when we first connect to a GDB server
405 m_x_packet_state.reset();
414 m_supports_z0 = true;
415 m_supports_z1 = true;
416 m_supports_z2 = true;
417 m_supports_z3 = true;
418 m_supports_z4 = true;
421 m_supports_qSymbol = true;
424 m_host_arch.Clear();
426 m_os_version = llvm::VersionTuple();
427 m_os_build.clear();
428 m_os_kernel.clear();
429 m_hostname.clear();
430 m_gdb_server_name.clear();
432 m_default_packet_timeout = seconds(0);
435 m_qSupported_response.clear();
442 }
443
444 // These flags should be reset when we first connect to a GDB server and when
445 // our inferior process execs
447 m_process_arch.Clear();
448}
449
451 // Clear out any capabilities we expect to see in the qSupported response
466 m_x_packet_state.reset();
473
474 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
475 // not, we assume no limit
476
477 // build the qSupported packet
478 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc",
479 "multiprocess+",
480 "fork-events+",
481 "vfork-events+",
482 "swbreak+",
483 "hwbreak+",
484 "qXfer:libraries:read+",
485 "qXfer:libraries-svr4:read+"};
486 StreamString packet;
487 packet.PutCString("qSupported");
488 for (uint32_t i = 0; i < features.size(); ++i) {
489 packet.PutCString(i == 0 ? ":" : ";");
490 packet.PutCString(features[i]);
491 }
492
494 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
496 // Hang on to the qSupported packet, so that platforms can do custom
497 // configuration of the transport before attaching/launching the process.
498 m_qSupported_response = response.GetStringRef().str();
499
500 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) {
501 if (x == "qXfer:auxv:read+")
503 else if (x == "qXfer:libraries-svr4:read+")
505 else if (x == "augmented-libraries-svr4-read") {
508 } else if (x == "qXfer:libraries:read+")
510 else if (x == "qXfer:features:read+")
512 else if (x == "qXfer:memory-map:read+")
514 else if (x == "qXfer:siginfo:read+")
516 else if (x == "qEcho+")
518 else if (x == "QPassSignals+")
520 else if (x == "multiprocess+")
522 else if (x == "memory-tagging+")
524 else if (x == "qSaveCore+")
526 else if (x == "address-spaces+")
528 else if (x == "native-signals+")
530 else if (x == "binary-upload+")
532 else if (x == "ReverseContinue+")
534 else if (x == "ReverseStep+")
536 else if (x == "MultiMemRead+")
538 else if (x == "jMultiBreakpoint+")
540 else if (x == "accelerator-plugins+")
542 else if (x == "qWasmInstance+")
544 // Look for a list of compressions in the features list e.g.
545 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
546 // deflate,lzma
547 else if (x.consume_front("SupportedCompressions=")) {
548 llvm::SmallVector<llvm::StringRef, 4> compressions;
549 x.split(compressions, ',');
550 if (!compressions.empty())
551 MaybeEnableCompression(compressions);
552 } else if (x.consume_front("SupportedWatchpointTypes=")) {
553 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types;
554 x.split(watchpoint_types, ',');
555 m_watchpoint_types = eWatchpointHardwareFeatureUnknown;
556 for (auto wp_type : watchpoint_types) {
557 if (wp_type == "x86_64")
558 m_watchpoint_types |= eWatchpointHardwareX86;
559 if (wp_type == "aarch64-mask")
560 m_watchpoint_types |= eWatchpointHardwareArmMASK;
561 if (wp_type == "aarch64-bas")
562 m_watchpoint_types |= eWatchpointHardwareArmBAS;
563 }
564 } else if (x.consume_front("PacketSize=")) {
565 StringExtractorGDBRemote packet_response(x);
567 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
568 if (m_max_packet_size == 0) {
569 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
571 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
572 }
573 }
574 }
575 }
576}
577
590
592 assert(!flavor.empty());
601 if (SendPacketAndWaitForResponse("vCont?", response) ==
603 for (llvm::StringRef token : llvm::split(response.GetStringRef(), ';')) {
604 if (token == "c")
606 if (token == "C")
608 if (token == "s")
610 if (token == "S")
612 }
613
619 }
620
626 }
627 }
628 }
629
630 return llvm::StringSwitch<bool>(flavor)
631 .Case("a", m_supports_vCont_any)
632 .Case("A", m_supports_vCont_all)
633 .Case("c", m_supports_vCont_c)
634 .Case("C", m_supports_vCont_C)
635 .Case("s", m_supports_vCont_s)
636 .Case("S", m_supports_vCont_S)
637 .Default(false);
638}
639
642 lldb::tid_t tid, StreamString &&payload,
643 StringExtractorGDBRemote &response) {
644 Lock lock(*this);
645 if (!lock) {
647 LLDB_LOGF(log,
648 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
649 "for %s packet.",
650 __FUNCTION__, payload.GetData());
652 }
653
655 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
656 else {
657 if (!SetCurrentThread(tid))
659 }
660
661 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
662}
663
664// Check if the target supports 'p' packet. It sends out a 'p' packet and
665// checks the response. A normal packet will tell us that support is available.
666//
667// Takes a valid thread ID because p needs to apply to a thread.
673
675 lldb::tid_t tid, llvm::StringRef packetStr) {
676 StreamString payload;
677 payload.PutCString(packetStr);
680 tid, std::move(payload), response) == PacketResult::Success &&
681 response.IsNormalResponse()) {
682 return eLazyBoolYes;
683 }
684 return eLazyBoolNo;
685}
686
690
692 // Get information on all threads at one using the "jThreadsInfo" packet
693 StructuredData::ObjectSP object_sp;
694
698 if (SendPacketAndWaitForResponse("jThreadsInfo", response) ==
700 if (response.IsUnsupportedResponse()) {
702 } else if (!response.Empty()) {
703 object_sp = StructuredData::ParseJSON(response.GetStringRef());
704 }
705 }
706 }
707 return object_sp;
708}
709
723
727 // We try to enable error strings in remote packets but if we fail, we just
728 // work in the older way.
730 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) ==
732 if (response.IsOKResponse()) {
734 }
735 }
736 }
737}
738
752
766
779
786
788 size_t len,
789 int32_t type) {
790 StreamString packet;
791 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type);
793
794 Log *log = GetLog(GDBRLog::Memory);
795
796 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
798 !response.IsNormalResponse()) {
799 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed",
800 __FUNCTION__);
801 return nullptr;
802 }
803
804 // We are expecting
805 // m<hex encoded bytes>
806
807 if (response.GetChar() != 'm') {
808 LLDB_LOGF(log,
809 "GDBRemoteCommunicationClient::%s: qMemTags response did not "
810 "begin with \"m\"",
811 __FUNCTION__);
812 return nullptr;
813 }
814
815 size_t expected_bytes = response.GetBytesLeft() / 2;
816 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0));
817 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData());
818 // Check both because in some situations chars are consumed even
819 // if the decoding fails.
820 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) {
821 LLDB_LOGF(
822 log,
823 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response",
824 __FUNCTION__);
825 return nullptr;
826 }
827
828 return buffer_sp;
829}
830
832 lldb::addr_t addr, size_t len, int32_t type,
833 const std::vector<uint8_t> &tags) {
834 // Format QMemTags:address,length:type:tags
835 StreamString packet;
836 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type);
837 packet.PutBytesAsRawHex8(tags.data(), tags.size());
838
839 Status status;
841 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
843 !response.IsOKResponse()) {
844 status = Status::FromErrorString("QMemTags packet failed");
845 }
846 return status;
847}
848
864
866 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
867 return m_curr_pid;
868
869 // First try to retrieve the pid via the qProcessInfo request.
870 GetCurrentProcessInfo(allow_lazy);
872 // We really got it.
873 return m_curr_pid;
874 } else {
875 // If we don't get a response for qProcessInfo, check if $qC gives us a
876 // result. $qC only returns a real process id on older debugserver and
877 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
878 // the thread id, which newer debugserver and lldb-gdbserver stubs return
879 // correctly.
882 if (response.GetChar() == 'Q') {
883 if (response.GetChar() == 'C') {
885 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID);
888 return m_curr_pid;
889 }
890 }
891 }
892 }
893
894 // If we don't get a response for $qC, check if $qfThreadID gives us a
895 // result.
897 bool sequence_mutex_unavailable;
898 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
899 if (!ids.empty() && !sequence_mutex_unavailable) {
900 // If server returned an explicit PID, use that.
901 m_curr_pid_run = m_curr_pid = ids.front().first;
902 // Otherwise, use the TID of the first thread (Linux hack).
904 m_curr_pid_run = m_curr_pid = ids.front().second;
906 return m_curr_pid;
907 }
908 }
909 }
910
912}
913
915 if (!args.GetArgumentAtIndex(0))
916 return llvm::createStringError(llvm::inconvertibleErrorCode(),
917 "Nothing to launch");
918 // try vRun first
919 if (m_supports_vRun) {
920 StreamString packet;
921 packet.PutCString("vRun");
922 for (const Args::ArgEntry &arg : args) {
923 packet.PutChar(';');
924 packet.PutStringAsRawHex8(arg.ref());
925 }
926
928 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
930 return llvm::createStringError(llvm::inconvertibleErrorCode(),
931 "Sending vRun packet failed");
932
933 if (response.IsErrorResponse())
934 return response.GetStatus().ToError();
935
936 // vRun replies with a stop reason packet
937 // FIXME: right now we just discard the packet and LLDB queries
938 // for stop reason again
939 if (!response.IsUnsupportedResponse())
940 return llvm::Error::success();
941
942 m_supports_vRun = false;
943 }
944
945 // fallback to A
946 StreamString packet;
947 packet.PutChar('A');
948 llvm::ListSeparator LS(",");
949 for (const auto &arg : llvm::enumerate(args)) {
950 packet << LS;
951 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index());
952 packet.PutStringAsRawHex8(arg.value().ref());
953 }
954
956 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
958 return llvm::createStringError(llvm::inconvertibleErrorCode(),
959 "Sending A packet failed");
960 }
961 if (!response.IsOKResponse())
962 return response.GetStatus().ToError();
963
964 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
966 return llvm::createStringError(llvm::inconvertibleErrorCode(),
967 "Sending qLaunchSuccess packet failed");
968 }
969 if (response.IsOKResponse())
970 return llvm::Error::success();
971 if (response.GetChar() == 'E') {
972 return llvm::createStringError(llvm::inconvertibleErrorCode(),
973 response.GetStringRef().substr(1));
974 }
975 return llvm::createStringError(llvm::inconvertibleErrorCode(),
976 "unknown error occurred launching process");
977}
978
980 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
981 for (const auto &kv : env)
982 vec.emplace_back(kv.first(), kv.second);
983 llvm::sort(vec, llvm::less_first());
984 for (const auto &[k, v] : vec) {
985 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
986 if (r != 0)
987 return r;
988 }
989 return 0;
990}
991
993 char const *name_equal_value) {
994 if (name_equal_value && name_equal_value[0]) {
995 bool send_hex_encoding = false;
996 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
997 ++p) {
998 if (llvm::isPrint(*p)) {
999 switch (*p) {
1000 case '$':
1001 case '#':
1002 case '*':
1003 case '}':
1004 send_hex_encoding = true;
1005 break;
1006 default:
1007 break;
1008 }
1009 } else {
1010 // We have non printable characters, lets hex encode this...
1011 send_hex_encoding = true;
1012 }
1013 }
1014
1015 StringExtractorGDBRemote response;
1016 // Prefer sending unencoded, if possible and the server supports it.
1017 if (!send_hex_encoding && m_supports_QEnvironment) {
1018 StreamString packet;
1019 packet.Printf("QEnvironment:%s", name_equal_value);
1020 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1022 return -1;
1023
1024 if (response.IsOKResponse())
1025 return 0;
1026 if (response.IsUnsupportedResponse())
1028 else {
1029 uint8_t error = response.GetError();
1030 if (error)
1031 return error;
1032 return -1;
1033 }
1034 }
1035
1037 StreamString packet;
1038 packet.PutCString("QEnvironmentHexEncoded:");
1039 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
1040 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1042 return -1;
1043
1044 if (response.IsOKResponse())
1045 return 0;
1046 if (response.IsUnsupportedResponse())
1048 else {
1049 uint8_t error = response.GetError();
1050 if (error)
1051 return error;
1052 return -1;
1053 }
1054 }
1055 }
1056 return -1;
1057}
1058
1060 if (arch && arch[0]) {
1061 StreamString packet;
1062 packet.Printf("QLaunchArch:%s", arch);
1063 StringExtractorGDBRemote response;
1064 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1066 if (response.IsOKResponse())
1067 return 0;
1068 uint8_t error = response.GetError();
1069 if (error)
1070 return error;
1071 }
1072 }
1073 return -1;
1074}
1075
1077 char const *data, bool *was_supported) {
1078 if (data && *data != '\0') {
1079 StreamString packet;
1080 packet.Printf("QSetProcessEvent:%s", data);
1081 StringExtractorGDBRemote response;
1082 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1084 if (response.IsOKResponse()) {
1085 if (was_supported)
1086 *was_supported = true;
1087 return 0;
1088 } else if (response.IsUnsupportedResponse()) {
1089 if (was_supported)
1090 *was_supported = false;
1091 return -1;
1092 } else {
1093 uint8_t error = response.GetError();
1094 if (was_supported)
1095 *was_supported = true;
1096 if (error)
1097 return error;
1098 }
1099 }
1100 }
1101 return -1;
1102}
1103
1105 GetHostInfo();
1106 return m_os_version;
1107}
1108
1113
1115 if (GetHostInfo()) {
1116 if (!m_os_build.empty())
1117 return m_os_build;
1118 }
1119 return std::nullopt;
1120}
1121
1122std::optional<std::string>
1124 if (GetHostInfo()) {
1125 if (!m_os_kernel.empty())
1126 return m_os_kernel;
1127 }
1128 return std::nullopt;
1129}
1130
1132 if (GetHostInfo()) {
1133 if (!m_hostname.empty()) {
1134 s = m_hostname;
1135 return true;
1136 }
1137 }
1138 s.clear();
1139 return false;
1140}
1141
1147
1154
1156 UUID &uuid, addr_t &value, bool &value_is_offset) {
1159
1160 // Return true if we have a UUID or an address/offset of the
1161 // main standalone / firmware binary being used.
1162 if (!m_process_standalone_uuid.IsValid() &&
1164 return false;
1165
1168 value_is_offset = m_process_standalone_value_is_offset;
1169 return true;
1170}
1171
1172std::vector<addr_t>
1178
1179std::vector<AddressSpaceInfo> GDBRemoteCommunicationClient::GetAddressSpaces() {
1181 return {};
1182
1183 StringExtractorGDBRemote response;
1184 response.SetResponseValidatorToJSON();
1185 if (SendPacketAndWaitForResponse("jAddressSpacesInfo", response) !=
1187 return {};
1188
1189 if (response.IsUnsupportedResponse() || response.IsErrorResponse()) {
1191 return {};
1192 }
1193
1194 llvm::Expected<std::vector<AddressSpaceInfo>> info =
1195 llvm::json::parse<std::vector<AddressSpaceInfo>>(response.Peek(),
1196 "AddressSpaceInfo");
1197 if (info)
1198 return std::move(*info);
1199
1200 Log *log = GetLog(GDBRLog::Process);
1201 LLDB_LOG_ERROR(log, info.takeError(),
1202 "malformed jAddressSpacesInfo response '{1}': {0}",
1203 response.GetStringRef());
1204 return {};
1205}
1206
1209 m_gdb_server_name.clear();
1212
1213 StringExtractorGDBRemote response;
1214 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1216 if (response.IsNormalResponse()) {
1217 llvm::StringRef name, value;
1218 bool success = false;
1219 while (response.GetNameColonValue(name, value)) {
1220 if (name == "name") {
1221 success = true;
1222 m_gdb_server_name = std::string(value);
1223 } else if (name == "version") {
1224 llvm::StringRef major, minor;
1225 std::tie(major, minor) = value.split('.');
1226 if (!major.getAsInteger(BASE_10, m_gdb_server_version))
1227 success = true;
1228 }
1229 }
1230 if (success)
1232 }
1233 }
1234 }
1236}
1237
1239 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1241 llvm::StringRef avail_name;
1242
1243#if HAVE_LIBCOMPRESSION
1244 if (avail_type == CompressionType::None) {
1245 for (auto compression : supported_compressions) {
1246 if (compression == "lzfse") {
1247 avail_type = CompressionType::LZFSE;
1248 avail_name = compression;
1249 break;
1250 }
1251 }
1252 }
1253 if (avail_type == CompressionType::None) {
1254 for (auto compression : supported_compressions) {
1255 if (compression == "zlib-deflate") {
1256 avail_type = CompressionType::ZlibDeflate;
1257 avail_name = compression;
1258 break;
1259 }
1260 }
1261 }
1262#endif
1263
1264#if LLVM_ENABLE_ZLIB
1265 if (avail_type == CompressionType::None) {
1266 for (auto compression : supported_compressions) {
1267 if (compression == "zlib-deflate") {
1268 avail_type = CompressionType::ZlibDeflate;
1269 avail_name = compression;
1270 break;
1271 }
1272 }
1273 }
1274#endif
1275
1276#if HAVE_LIBCOMPRESSION
1277 if (avail_type == CompressionType::None) {
1278 for (auto compression : supported_compressions) {
1279 if (compression == "lz4") {
1280 avail_type = CompressionType::LZ4;
1281 avail_name = compression;
1282 break;
1283 }
1284 }
1285 }
1286 if (avail_type == CompressionType::None) {
1287 for (auto compression : supported_compressions) {
1288 if (compression == "lzma") {
1289 avail_type = CompressionType::LZMA;
1290 avail_name = compression;
1291 break;
1292 }
1293 }
1294 }
1295#endif
1296
1297 if (avail_type != CompressionType::None) {
1298 StringExtractorGDBRemote response;
1299 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1300 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1301 return;
1302
1303 if (response.IsOKResponse()) {
1304 m_compression_type = avail_type;
1305 }
1306 }
1307}
1308
1310 if (GetGDBServerVersion()) {
1311 if (!m_gdb_server_name.empty())
1312 return m_gdb_server_name.c_str();
1313 }
1314 return nullptr;
1315}
1316
1322
1324 StringExtractorGDBRemote response;
1326 return false;
1327
1328 if (!response.IsNormalResponse())
1329 return false;
1330
1331 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1332 auto pid_tid = response.GetPidTid(0);
1333 if (!pid_tid)
1334 return false;
1335
1336 lldb::pid_t pid = pid_tid->first;
1337 // invalid
1339 return false;
1340
1341 // if we get pid as well, update m_curr_pid
1342 if (pid != 0) {
1343 m_curr_pid_run = m_curr_pid = pid;
1345 }
1346 tid = pid_tid->second;
1347 }
1348
1349 return true;
1350}
1351
1352static void ParseOSType(llvm::StringRef value, std::string &os_name,
1353 std::string &environment) {
1354 if (value == "iossimulator" || value == "tvossimulator" ||
1355 value == "watchossimulator" || value == "xrossimulator" ||
1356 value == "visionossimulator") {
1357 environment = "simulator";
1358 os_name = value.drop_back(environment.size()).str();
1359 } else if (value == "maccatalyst") {
1360 os_name = "ios";
1361 environment = "macabi";
1362 } else {
1363 os_name = value.str();
1364 }
1365}
1366
1368 Log *log = GetLog(GDBRLog::Process);
1369
1370 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1371 // host info computation can require DNS traffic and shelling out to external processes.
1372 // Increase the timeout to account for that.
1373 ScopedTimeout timeout(*this, seconds(10));
1375 StringExtractorGDBRemote response;
1376 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1378 if (response.IsNormalResponse()) {
1379 llvm::StringRef name;
1380 llvm::StringRef value;
1381 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1382 uint32_t sub = 0;
1383 std::string arch_name;
1384 std::string os_name;
1385 std::string environment;
1386 std::string vendor_name;
1387 std::string triple;
1388 uint32_t pointer_byte_size = 0;
1389 ByteOrder byte_order = eByteOrderInvalid;
1390 uint32_t num_keys_decoded = 0;
1391 while (response.GetNameColonValue(name, value)) {
1392 if (name == "cputype") {
1393 // exception type in big endian hex
1394 if (!value.getAsInteger(BASE_10, cpu))
1395 ++num_keys_decoded;
1396 } else if (name == "cpusubtype") {
1397 // exception count in big endian hex
1398 if (!value.getAsInteger(BASE_10, sub))
1399 ++num_keys_decoded;
1400 } else if (name == "arch") {
1401 arch_name = std::string(value);
1402 ++num_keys_decoded;
1403 } else if (name == "triple") {
1404 StringExtractor extractor(value);
1405 extractor.GetHexByteString(triple);
1406 ++num_keys_decoded;
1407 } else if (name == "distribution_id") {
1408 StringExtractor extractor(value);
1410 ++num_keys_decoded;
1411 } else if (name == "os_build") {
1412 StringExtractor extractor(value);
1413 extractor.GetHexByteString(m_os_build);
1414 ++num_keys_decoded;
1415 } else if (name == "hostname") {
1416 StringExtractor extractor(value);
1417 extractor.GetHexByteString(m_hostname);
1418 ++num_keys_decoded;
1419 } else if (name == "os_kernel") {
1420 StringExtractor extractor(value);
1421 extractor.GetHexByteString(m_os_kernel);
1422 ++num_keys_decoded;
1423 } else if (name == "ostype") {
1424 ParseOSType(value, os_name, environment);
1425 ++num_keys_decoded;
1426 } else if (name == "vendor") {
1427 vendor_name = std::string(value);
1428 ++num_keys_decoded;
1429 } else if (name == "endian") {
1430 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1431 .Case("little", eByteOrderLittle)
1432 .Case("big", eByteOrderBig)
1433 .Case("pdp", eByteOrderPDP)
1434 .Default(eByteOrderInvalid);
1435 if (byte_order != eByteOrderInvalid)
1436 ++num_keys_decoded;
1437 } else if (name == "ptrsize") {
1438 if (!value.getAsInteger(BASE_10, pointer_byte_size))
1439 ++num_keys_decoded;
1440 } else if (name == "addressing_bits") {
1441 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits)) {
1442 ++num_keys_decoded;
1443 }
1444 } else if (name == "high_mem_addressing_bits") {
1445 if (!value.getAsInteger(BASE_10, m_high_mem_addressing_bits))
1446 ++num_keys_decoded;
1447 } else if (name == "low_mem_addressing_bits") {
1448 if (!value.getAsInteger(BASE_10, m_low_mem_addressing_bits))
1449 ++num_keys_decoded;
1450 } else if (name == "os_version" ||
1451 name == "version") // Older debugserver binaries used
1452 // the "version" key instead of
1453 // "os_version"...
1454 {
1455 if (!m_os_version.tryParse(value))
1456 ++num_keys_decoded;
1457 } else if (name == "maccatalyst_version") {
1458 if (!m_maccatalyst_version.tryParse(value))
1459 ++num_keys_decoded;
1460 } else if (name == "watchpoint_exceptions_received") {
1462 llvm::StringSwitch<LazyBool>(value)
1463 .Case("before", eLazyBoolNo)
1464 .Case("after", eLazyBoolYes)
1465 .Default(eLazyBoolCalculate);
1467 ++num_keys_decoded;
1468 } else if (name == "default_packet_timeout") {
1469 uint32_t timeout_seconds;
1470 if (!value.getAsInteger(BASE_10, timeout_seconds)) {
1471 m_default_packet_timeout = seconds(timeout_seconds);
1473 ++num_keys_decoded;
1474 }
1475 } else if (name == "vm-page-size") {
1476 int page_size;
1477 if (!value.getAsInteger(BASE_10, page_size)) {
1478 m_target_vm_page_size = page_size;
1479 ++num_keys_decoded;
1480 }
1481 }
1482 }
1483
1484 if (num_keys_decoded > 0)
1486
1487 if (triple.empty()) {
1488 if (arch_name.empty()) {
1489 if (cpu != LLDB_INVALID_CPUTYPE) {
1490 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1491 if (pointer_byte_size) {
1492 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1493 }
1494 if (byte_order != eByteOrderInvalid) {
1495 assert(byte_order == m_host_arch.GetByteOrder());
1496 }
1497
1498 if (!vendor_name.empty())
1499 m_host_arch.GetTriple().setVendorName(
1500 llvm::StringRef(vendor_name));
1501 if (!os_name.empty())
1502 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1503 if (!environment.empty())
1504 m_host_arch.GetTriple().setEnvironmentName(environment);
1505 }
1506 } else {
1507 std::string triple;
1508 triple += arch_name;
1509 if (!vendor_name.empty() || !os_name.empty()) {
1510 triple += '-';
1511 if (vendor_name.empty())
1512 triple += "unknown";
1513 else
1514 triple += vendor_name;
1515 triple += '-';
1516 if (os_name.empty())
1517 triple += "unknown";
1518 else
1519 triple += os_name;
1520 }
1521 m_host_arch.SetTriple(triple.c_str());
1522
1523 llvm::Triple &host_triple = m_host_arch.GetTriple();
1524 if (host_triple.getVendor() == llvm::Triple::Apple &&
1525 host_triple.getOS() == llvm::Triple::Darwin) {
1526 switch (m_host_arch.GetMachine()) {
1527 case llvm::Triple::aarch64:
1528 case llvm::Triple::aarch64_32:
1529 case llvm::Triple::arm:
1530 case llvm::Triple::thumb:
1531 host_triple.setOS(llvm::Triple::IOS);
1532 break;
1533 default:
1534 host_triple.setOS(llvm::Triple::MacOSX);
1535 break;
1536 }
1537 }
1538 if (pointer_byte_size) {
1539 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1540 }
1541 if (byte_order != eByteOrderInvalid) {
1542 assert(byte_order == m_host_arch.GetByteOrder());
1543 }
1544 }
1545 } else {
1546 m_host_arch.SetTriple(triple.c_str());
1547 if (pointer_byte_size) {
1548 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1549 }
1550 if (byte_order != eByteOrderInvalid) {
1551 assert(byte_order == m_host_arch.GetByteOrder());
1552 }
1553
1554 LLDB_LOGF(log,
1555 "GDBRemoteCommunicationClient::%s parsed host "
1556 "architecture as %s, triple as %s from triple text %s",
1557 __FUNCTION__,
1558 m_host_arch.GetArchitectureName()
1559 ? m_host_arch.GetArchitectureName()
1560 : "<null-arch-name>",
1561 m_host_arch.GetTriple().getTriple().c_str(),
1562 triple.c_str());
1563 }
1564 }
1565 }
1566 }
1568}
1569
1571 const char *data, size_t data_len, std::chrono::seconds interrupt_timeout) {
1572 StreamString packet;
1573 packet.PutCString("I");
1574 packet.PutBytesAsRawHex8(data, data_len);
1575 StringExtractorGDBRemote response;
1576 if (SendPacketAndWaitForResponse(packet.GetString(), response,
1577 interrupt_timeout) ==
1579 return 0;
1580 }
1581 return response.GetError();
1582}
1583
1590
1603
1609
1611 uint32_t permissions) {
1614 char packet[64];
1615 const int packet_len = ::snprintf(
1616 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1617 permissions & lldb::ePermissionsReadable ? "r" : "",
1618 permissions & lldb::ePermissionsWritable ? "w" : "",
1619 permissions & lldb::ePermissionsExecutable ? "x" : "");
1620 assert(packet_len < (int)sizeof(packet));
1621 UNUSED_IF_ASSERT_DISABLED(packet_len);
1622 StringExtractorGDBRemote response;
1623 if (SendPacketAndWaitForResponse(packet, response) ==
1625 if (response.IsUnsupportedResponse())
1627 else if (!response.IsErrorResponse())
1628 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1629 } else {
1631 }
1632 }
1633 return LLDB_INVALID_ADDRESS;
1634}
1635
1639 char packet[64];
1640 const int packet_len =
1641 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1642 assert(packet_len < (int)sizeof(packet));
1643 UNUSED_IF_ASSERT_DISABLED(packet_len);
1644 StringExtractorGDBRemote response;
1645 if (SendPacketAndWaitForResponse(packet, response) ==
1647 if (response.IsUnsupportedResponse())
1649 else if (response.IsOKResponse())
1650 return true;
1651 } else {
1653 }
1654 }
1655 return false;
1656}
1657
1659 lldb::pid_t pid) {
1660 Status error;
1662
1663 packet.PutChar('D');
1664 if (keep_stopped) {
1666 char packet[64];
1667 const int packet_len =
1668 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1669 assert(packet_len < (int)sizeof(packet));
1670 UNUSED_IF_ASSERT_DISABLED(packet_len);
1671 StringExtractorGDBRemote response;
1672 if (SendPacketAndWaitForResponse(packet, response) ==
1674 response.IsOKResponse()) {
1676 } else {
1678 }
1679 }
1680
1683 "Stays stopped not supported by this target.");
1684 return error;
1685 } else {
1686 packet.PutChar('1');
1687 }
1688 }
1689
1691 // Some servers (e.g. qemu) require specifying the PID even if only a single
1692 // process is running.
1693 if (pid == LLDB_INVALID_PROCESS_ID)
1694 pid = GetCurrentProcessID();
1695 packet.PutChar(';');
1696 packet.PutHex64(pid);
1697 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1699 "Multiprocess extension not supported by the server.");
1700 return error;
1701 }
1702
1703 StringExtractorGDBRemote response;
1704 PacketResult packet_result =
1705 SendPacketAndWaitForResponse(packet.GetString(), response);
1706 if (packet_result != PacketResult::Success)
1707 error = Status::FromErrorString("Sending disconnect packet failed.");
1708 return error;
1709}
1710
1712 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1713 Status error;
1714 region_info.Clear();
1715
1718 char packet[64];
1719 const int packet_len = ::snprintf(
1720 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1721 assert(packet_len < (int)sizeof(packet));
1722 UNUSED_IF_ASSERT_DISABLED(packet_len);
1723 StringExtractorGDBRemote response;
1724 if (SendPacketAndWaitForResponse(packet, response) ==
1727 llvm::StringRef name;
1728 llvm::StringRef value;
1729 addr_t addr_value = LLDB_INVALID_ADDRESS;
1730 bool success = true;
1731 bool saw_permissions = false;
1732 while (success && response.GetNameColonValue(name, value)) {
1733 if (name == "start") {
1734 if (!value.getAsInteger(BASE_16, addr_value))
1735 region_info.GetRange().SetRangeBase(addr_value);
1736 } else if (name == "size") {
1737 if (!value.getAsInteger(BASE_16, addr_value)) {
1738 region_info.GetRange().SetByteSize(addr_value);
1739 if (region_info.GetRange().GetRangeEnd() <
1740 region_info.GetRange().GetRangeBase()) {
1741 // Range size overflowed, truncate it.
1743 }
1744 }
1745 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1746 saw_permissions = true;
1747 if (region_info.GetRange().Contains(addr)) {
1748 if (value.contains('r'))
1749 region_info.SetReadable(eLazyBoolYes);
1750 else
1751 region_info.SetReadable(eLazyBoolNo);
1752
1753 if (value.contains('w'))
1754 region_info.SetWritable(eLazyBoolYes);
1755 else
1756 region_info.SetWritable(eLazyBoolNo);
1757
1758 if (value.contains('x'))
1759 region_info.SetExecutable(eLazyBoolYes);
1760 else
1761 region_info.SetExecutable(eLazyBoolNo);
1762
1763 region_info.SetMapped(eLazyBoolYes);
1764 } else {
1765 // The reported region does not contain this address -- we're
1766 // looking at an unmapped page
1767 region_info.SetReadable(eLazyBoolNo);
1768 region_info.SetWritable(eLazyBoolNo);
1769 region_info.SetExecutable(eLazyBoolNo);
1770 region_info.SetMapped(eLazyBoolNo);
1771 }
1772 } else if (name == "name") {
1773 StringExtractorGDBRemote name_extractor(value);
1774 std::string name;
1775 name_extractor.GetHexByteString(name);
1776 region_info.SetName(name.c_str());
1777 } else if (name == "flags") {
1778 region_info.SetMemoryTagged(eLazyBoolNo);
1779 region_info.SetIsShadowStack(eLazyBoolNo);
1780
1781 llvm::StringRef flags = value;
1782 llvm::StringRef flag;
1783 while (flags.size()) {
1784 flags = flags.ltrim();
1785 std::tie(flag, flags) = flags.split(' ');
1786 // To account for trailing whitespace
1787 if (flag.size()) {
1788 if (flag == "mt")
1789 region_info.SetMemoryTagged(eLazyBoolYes);
1790 else if (flag == "ss")
1791 region_info.SetIsShadowStack(eLazyBoolYes);
1792 }
1793 }
1794 } else if (name == "type") {
1795 for (llvm::StringRef entry : llvm::split(value, ',')) {
1796 if (entry == "stack")
1797 region_info.SetIsStackMemory(eLazyBoolYes);
1798 else if (entry == "heap")
1799 region_info.SetIsStackMemory(eLazyBoolNo);
1800 }
1801 } else if (name == "error") {
1802 StringExtractorGDBRemote error_extractor(value);
1803 std::string error_string;
1804 // Now convert the HEX bytes into a string value
1805 error_extractor.GetHexByteString(error_string);
1806 error = Status::FromErrorString(error_string.c_str());
1807 } else if (name == "dirty-pages") {
1808 std::vector<addr_t> dirty_page_list;
1809 for (llvm::StringRef x : llvm::split(value, ',')) {
1810 addr_t page;
1811 x.consume_front("0x");
1812 if (llvm::to_integer(x, page, 16))
1813 dirty_page_list.push_back(page);
1814 }
1815 region_info.SetDirtyPageList(dirty_page_list);
1816 } else if (name == "protection-key") {
1817 unsigned protection_key = 0;
1818 if (!value.getAsInteger(BASE_10, protection_key))
1819 region_info.SetProtectionKey(protection_key);
1820 }
1821 }
1822
1823 if (m_target_vm_page_size != 0)
1825
1826 if (region_info.GetRange().IsValid()) {
1827 // We got a valid address range back but no permissions -- which means
1828 // this is an unmapped page
1829 if (!saw_permissions) {
1830 region_info.SetReadable(eLazyBoolNo);
1831 region_info.SetWritable(eLazyBoolNo);
1832 region_info.SetExecutable(eLazyBoolNo);
1833 region_info.SetMapped(eLazyBoolNo);
1834 }
1835 } else {
1836 // We got an invalid address range back
1837 error = Status::FromErrorString("Server returned invalid range");
1838 }
1839 } else {
1841 }
1842 }
1843
1845 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1846 }
1847
1848 // Try qXfer:memory-map:read to get region information not included in
1849 // qMemoryRegionInfo
1850 MemoryRegionInfo qXfer_region_info;
1851 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1852
1853 if (error.Fail()) {
1854 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1855 // the qXfer result as a fallback
1856 if (qXfer_error.Success()) {
1857 region_info = qXfer_region_info;
1858 error.Clear();
1859 } else {
1860 region_info.Clear();
1861 }
1862 } else if (qXfer_error.Success()) {
1863 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1864 // both regions are the same range, update the result to include the flash-
1865 // memory information that is specific to the qXfer result.
1866 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1867 region_info.SetFlash(qXfer_region_info.GetFlash());
1868 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1869 }
1870 }
1871 return error;
1872}
1873
1875 lldb::addr_t addr, MemoryRegionInfo &region) {
1877 if (!error.Success())
1878 return error;
1879 for (const auto &map_region : m_qXfer_memory_map) {
1880 if (map_region.GetRange().Contains(addr)) {
1881 region = map_region;
1882 return error;
1883 }
1884 }
1885 error = Status::FromErrorString("Region not found");
1886 return error;
1887}
1888
1890
1891 Status error;
1892
1894 // Already loaded, return success
1895 return error;
1896
1897 if (!XMLDocument::XMLEnabled()) {
1898 error = Status::FromErrorString("XML is not supported");
1899 return error;
1900 }
1901
1903 error = Status::FromErrorString("Memory map is not supported");
1904 return error;
1905 }
1906
1907 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1908 if (!xml)
1909 return Status::FromError(xml.takeError());
1910
1911 XMLDocument xml_document;
1912
1913 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1914 error = Status::FromErrorString("Failed to parse memory map xml");
1915 return error;
1916 }
1917
1918 XMLNode map_node = xml_document.GetRootElement("memory-map");
1919 if (!map_node) {
1920 error = Status::FromErrorString("Invalid root node in memory map xml");
1921 return error;
1922 }
1923
1924 m_qXfer_memory_map.clear();
1925
1926 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1927 if (!memory_node.IsElement())
1928 return true;
1929 if (memory_node.GetName() != "memory")
1930 return true;
1931 auto type = memory_node.GetAttributeValue("type", "");
1932 uint64_t start;
1933 uint64_t length;
1934 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1935 return true;
1936 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1937 return true;
1938 MemoryRegionInfo region;
1939 region.GetRange().SetRangeBase(start);
1940 region.GetRange().SetByteSize(length);
1941 if (type == "rom") {
1942 region.SetReadable(eLazyBoolYes);
1943 this->m_qXfer_memory_map.push_back(region);
1944 } else if (type == "ram") {
1945 region.SetReadable(eLazyBoolYes);
1946 region.SetWritable(eLazyBoolYes);
1947 this->m_qXfer_memory_map.push_back(region);
1948 } else if (type == "flash") {
1949 region.SetFlash(eLazyBoolYes);
1950 memory_node.ForEachChildElement(
1951 [&region](const XMLNode &prop_node) -> bool {
1952 if (!prop_node.IsElement())
1953 return true;
1954 if (prop_node.GetName() != "property")
1955 return true;
1956 auto propname = prop_node.GetAttributeValue("name", "");
1957 if (propname == "blocksize") {
1958 uint64_t blocksize;
1959 if (prop_node.GetElementTextAsUnsigned(blocksize))
1960 region.SetBlocksize(blocksize);
1961 }
1962 return true;
1963 });
1964 this->m_qXfer_memory_map.push_back(region);
1965 }
1966 return true;
1967 });
1968
1970
1971 return error;
1972}
1973
1977 }
1978
1979 std::optional<uint32_t> num;
1981 StringExtractorGDBRemote response;
1982 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
1985 llvm::StringRef name;
1986 llvm::StringRef value;
1987 while (response.GetNameColonValue(name, value)) {
1988 if (name == "num") {
1989 value.getAsInteger(BASE_10, m_num_supported_hardware_watchpoints);
1991 }
1992 }
1993 if (!num) {
1995 }
1996 } else {
1998 }
1999 }
2000
2001 return num;
2002}
2003
2004WatchpointHardwareFeature
2008
2011 GetHostInfo();
2012
2013 // Process determines this by target CPU, but allow for the
2014 // remote stub to override it via the qHostInfo
2015 // watchpoint_exceptions_received key, if it is present.
2018 return false;
2020 return true;
2021 }
2022
2023 return std::nullopt;
2024}
2025
2027 if (file_spec) {
2028 std::string path{file_spec.GetPath(false)};
2029 StreamString packet;
2030 packet.PutCString("QSetSTDIN:");
2031 packet.PutStringAsRawHex8(path);
2032
2033 StringExtractorGDBRemote response;
2034 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2036 if (response.IsOKResponse())
2037 return 0;
2038 uint8_t error = response.GetError();
2039 if (error)
2040 return error;
2041 }
2042 }
2043 return -1;
2044}
2045
2047 if (file_spec) {
2048 std::string path{file_spec.GetPath(false)};
2049 StreamString packet;
2050 packet.PutCString("QSetSTDOUT:");
2051 packet.PutStringAsRawHex8(path);
2052
2053 StringExtractorGDBRemote response;
2054 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2056 if (response.IsOKResponse())
2057 return 0;
2058 uint8_t error = response.GetError();
2059 if (error)
2060 return error;
2061 }
2062 }
2063 return -1;
2064}
2065
2067 if (file_spec) {
2068 std::string path{file_spec.GetPath(false)};
2069 StreamString packet;
2070 packet.PutCString("QSetSTDERR:");
2071 packet.PutStringAsRawHex8(path);
2072
2073 StringExtractorGDBRemote response;
2074 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2076 if (response.IsOKResponse())
2077 return 0;
2078 uint8_t error = response.GetError();
2079 if (error)
2080 return error;
2081 }
2082 }
2083 return -1;
2084}
2085
2087 uint16_t rows) {
2088 // The size is only valid if both or none of the dimensions are zero.
2089 if ((cols == 0) != (rows == 0))
2090 return -1;
2091 StreamString packet;
2092 packet.Printf("QSetSTDIOWindowSize:cols=%u;rows=%u",
2093 static_cast<unsigned>(cols), static_cast<unsigned>(rows));
2094 StringExtractorGDBRemote response;
2095 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
2097 return -1;
2098 if (response.IsOKResponse())
2099 return 0;
2100 if (response.IsUnsupportedResponse())
2101 return 0;
2102 uint8_t error = response.GetError();
2103 return error ? error : -1;
2104}
2105
2107 StringExtractorGDBRemote response;
2108 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
2110 if (response.IsUnsupportedResponse())
2111 return false;
2112 if (response.IsErrorResponse())
2113 return false;
2114 std::string cwd;
2115 response.GetHexByteString(cwd);
2116 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
2117 return !cwd.empty();
2118 }
2119 return false;
2120}
2121
2123 if (working_dir) {
2124 std::string path{working_dir.GetPath(false)};
2125 StreamString packet;
2126 packet.PutCString("QSetWorkingDir:");
2127 packet.PutStringAsRawHex8(path);
2128
2129 StringExtractorGDBRemote response;
2130 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2132 if (response.IsOKResponse())
2133 return 0;
2134 uint8_t error = response.GetError();
2135 if (error)
2136 return error;
2137 }
2138 }
2139 return -1;
2140}
2141
2143 char packet[32];
2144 const int packet_len =
2145 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2146 assert(packet_len < (int)sizeof(packet));
2147 UNUSED_IF_ASSERT_DISABLED(packet_len);
2148 StringExtractorGDBRemote response;
2149 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2150 if (response.IsOKResponse())
2151 return 0;
2152 uint8_t error = response.GetError();
2153 if (error)
2154 return error;
2155 }
2156 return -1;
2157}
2158
2160 char packet[32];
2161 const int packet_len = ::snprintf(packet, sizeof(packet),
2162 "QSetDetachOnError:%i", enable ? 1 : 0);
2163 assert(packet_len < (int)sizeof(packet));
2164 UNUSED_IF_ASSERT_DISABLED(packet_len);
2165 StringExtractorGDBRemote response;
2166 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2167 if (response.IsOKResponse())
2168 return 0;
2169 uint8_t error = response.GetError();
2170 if (error)
2171 return error;
2172 }
2173 return -1;
2174}
2175
2177 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2178 if (response.IsNormalResponse()) {
2179 llvm::StringRef name;
2180 llvm::StringRef value;
2181 StringExtractor extractor;
2182
2183 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2184 uint32_t sub = 0;
2185 std::string vendor;
2186 std::string os_type;
2187
2188 while (response.GetNameColonValue(name, value)) {
2189 if (name == "pid") {
2191 value.getAsInteger(BASE_10, pid);
2192 process_info.SetProcessID(pid);
2193 } else if (name == "ppid") {
2195 value.getAsInteger(BASE_10, pid);
2196 process_info.SetParentProcessID(pid);
2197 } else if (name == "uid") {
2198 uint32_t uid = UINT32_MAX;
2199 value.getAsInteger(BASE_10, uid);
2200 process_info.SetUserID(uid);
2201 } else if (name == "euid") {
2202 uint32_t uid = UINT32_MAX;
2203 value.getAsInteger(BASE_10, uid);
2204 process_info.SetEffectiveUserID(uid);
2205 } else if (name == "gid") {
2206 uint32_t gid = UINT32_MAX;
2207 value.getAsInteger(BASE_10, gid);
2208 process_info.SetGroupID(gid);
2209 } else if (name == "egid") {
2210 uint32_t gid = UINT32_MAX;
2211 value.getAsInteger(BASE_10, gid);
2212 process_info.SetEffectiveGroupID(gid);
2213 } else if (name == "triple") {
2214 StringExtractor extractor(value);
2215 std::string triple;
2216 extractor.GetHexByteString(triple);
2217 process_info.GetArchitecture().SetTriple(triple.c_str());
2218 } else if (name == "name") {
2219 StringExtractor extractor(value);
2220 // The process name from ASCII hex bytes since we can't control the
2221 // characters in a process name
2222 std::string name;
2223 extractor.GetHexByteString(name);
2224 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2225 } else if (name == "args") {
2226 llvm::StringRef encoded_args(value), hex_arg;
2227
2228 bool is_arg0 = true;
2229 while (!encoded_args.empty()) {
2230 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2231 std::string arg;
2232 StringExtractor extractor(hex_arg);
2233 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2234 // In case of wrong encoding, we discard all the arguments
2235 process_info.GetArguments().Clear();
2236 process_info.SetArg0("");
2237 break;
2238 }
2239 if (is_arg0)
2240 process_info.SetArg0(arg);
2241 else
2242 process_info.GetArguments().AppendArgument(arg);
2243 is_arg0 = false;
2244 }
2245 } else if (name == "cputype") {
2246 value.getAsInteger(BASE_10, cpu);
2247 } else if (name == "cpusubtype") {
2248 value.getAsInteger(BASE_10, sub);
2249 } else if (name == "vendor") {
2250 vendor = std::string(value);
2251 } else if (name == "ostype") {
2252 os_type = std::string(value);
2253 }
2254 }
2255
2256 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2257 if (vendor == "apple") {
2259 sub);
2260 process_info.GetArchitecture().GetTriple().setVendorName(
2261 llvm::StringRef(vendor));
2262 process_info.GetArchitecture().GetTriple().setOSName(
2263 llvm::StringRef(os_type));
2264 }
2265 }
2266
2267 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2268 return true;
2269 }
2270 return false;
2271}
2272
2274 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2275 process_info.Clear();
2276
2278 char packet[32];
2279 const int packet_len =
2280 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2281 assert(packet_len < (int)sizeof(packet));
2282 UNUSED_IF_ASSERT_DISABLED(packet_len);
2283 StringExtractorGDBRemote response;
2284 if (SendPacketAndWaitForResponse(packet, response) ==
2286 return DecodeProcessInfoResponse(response, process_info);
2287 } else {
2289 return false;
2290 }
2291 }
2292 return false;
2293}
2294
2297
2298 if (allow_lazy) {
2300 return true;
2302 return false;
2303 }
2304
2305 GetHostInfo();
2306
2307 StringExtractorGDBRemote response;
2308 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2310 if (response.IsNormalResponse()) {
2311 llvm::StringRef name;
2312 llvm::StringRef value;
2313 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2314 uint32_t sub = 0;
2315 std::string os_name;
2316 std::string environment;
2317 std::string vendor_name;
2318 std::string triple;
2319 std::string elf_abi;
2320 uint32_t pointer_byte_size = 0;
2321 StringExtractor extractor;
2322 ByteOrder byte_order = eByteOrderInvalid;
2323 uint32_t num_keys_decoded = 0;
2325 while (response.GetNameColonValue(name, value)) {
2326 if (name == "cputype") {
2327 if (!value.getAsInteger(BASE_16, cpu))
2328 ++num_keys_decoded;
2329 } else if (name == "cpusubtype") {
2330 if (!value.getAsInteger(BASE_16, sub)) {
2331 ++num_keys_decoded;
2332 // Workaround for pre-2024 Apple debugserver, which always
2333 // returns arm64e on arm64e-capable hardware regardless of
2334 // what the process is. This can be deleted at some point
2335 // in the future.
2336 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2337 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2338 if (GetGDBServerVersion())
2339 if (m_gdb_server_version >= 1000 &&
2340 m_gdb_server_version <= 1504)
2341 sub = 0;
2342 }
2343 }
2344 } else if (name == "triple") {
2345 StringExtractor extractor(value);
2346 extractor.GetHexByteString(triple);
2347 ++num_keys_decoded;
2348 } else if (name == "ostype") {
2349 ParseOSType(value, os_name, environment);
2350 ++num_keys_decoded;
2351 } else if (name == "vendor") {
2352 vendor_name = std::string(value);
2353 ++num_keys_decoded;
2354 } else if (name == "endian") {
2355 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2356 .Case("little", eByteOrderLittle)
2357 .Case("big", eByteOrderBig)
2358 .Case("pdp", eByteOrderPDP)
2359 .Default(eByteOrderInvalid);
2360 if (byte_order != eByteOrderInvalid)
2361 ++num_keys_decoded;
2362 } else if (name == "ptrsize") {
2363 if (!value.getAsInteger(BASE_16, pointer_byte_size))
2364 ++num_keys_decoded;
2365 } else if (name == "pid") {
2366 if (!value.getAsInteger(BASE_16, pid))
2367 ++num_keys_decoded;
2368 } else if (name == "elf_abi") {
2369 elf_abi = std::string(value);
2370 ++num_keys_decoded;
2371 } else if (name == "main-binary-uuid") {
2372 m_process_standalone_uuid.SetFromStringRef(value);
2373 ++num_keys_decoded;
2374 } else if (name == "main-binary-slide") {
2375 StringExtractor extractor(value);
2377 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2380 ++num_keys_decoded;
2381 }
2382 } else if (name == "main-binary-address") {
2383 StringExtractor extractor(value);
2385 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2388 ++num_keys_decoded;
2389 }
2390 } else if (name == "binary-addresses") {
2391 m_binary_addresses.clear();
2392 ++num_keys_decoded;
2393 for (llvm::StringRef x : llvm::split(value, ',')) {
2394 addr_t vmaddr;
2395 x.consume_front("0x");
2396 if (llvm::to_integer(x, vmaddr, 16))
2397 m_binary_addresses.push_back(vmaddr);
2398 }
2399 }
2400 }
2401 if (num_keys_decoded > 0)
2403 if (pid != LLDB_INVALID_PROCESS_ID) {
2405 m_curr_pid_run = m_curr_pid = pid;
2406 }
2407
2408 // Set the ArchSpec from the triple if we have it.
2409 if (!triple.empty()) {
2410 m_process_arch.SetTriple(triple.c_str());
2411 m_process_arch.SetFlags(elf_abi);
2412 if (pointer_byte_size) {
2413 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2414 }
2415 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2416 !vendor_name.empty()) {
2417 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2418 if (!environment.empty())
2419 triple.setEnvironmentName(environment);
2420
2421 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2422 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2423 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2424 switch (triple.getObjectFormat()) {
2425 case llvm::Triple::MachO:
2426 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2427 break;
2428 case llvm::Triple::ELF:
2429 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2430 break;
2431 case llvm::Triple::COFF:
2432 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2433 break;
2434 case llvm::Triple::GOFF:
2435 case llvm::Triple::SPIRV:
2436 case llvm::Triple::Wasm:
2437 case llvm::Triple::XCOFF:
2438 case llvm::Triple::DXContainer:
2439 LLDB_LOGF(log, "error: not supported target architecture");
2440 return false;
2441 case llvm::Triple::UnknownObjectFormat:
2442 LLDB_LOGF(log, "error: failed to determine target architecture");
2443 return false;
2444 }
2445
2446 if (pointer_byte_size) {
2447 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2448 }
2449 if (byte_order != eByteOrderInvalid) {
2450 assert(byte_order == m_process_arch.GetByteOrder());
2451 }
2452 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2453 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2454 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2455 }
2456 return true;
2457 }
2458 } else {
2460 }
2461
2462 return false;
2463}
2464
2466 const ProcessInstanceInfoMatch &match_info,
2467 ProcessInstanceInfoList &process_infos) {
2468 process_infos.clear();
2469
2471 StreamString packet;
2472 packet.PutCString("qfProcessInfo");
2473 if (!match_info.MatchAllProcesses()) {
2474 packet.PutChar(':');
2475 llvm::StringRef name = match_info.GetProcessInfo().GetName();
2476 bool has_name_match = false;
2477 if (!name.empty()) {
2478 has_name_match = true;
2479 NameMatch name_match_type = match_info.GetNameMatchType();
2480 switch (name_match_type) {
2481 case NameMatch::Ignore:
2482 has_name_match = false;
2483 break;
2484
2485 case NameMatch::Equals:
2486 packet.PutCString("name_match:equals;");
2487 break;
2488
2490 packet.PutCString("name_match:contains;");
2491 break;
2492
2494 packet.PutCString("name_match:starts_with;");
2495 break;
2496
2498 packet.PutCString("name_match:ends_with;");
2499 break;
2500
2502 packet.PutCString("name_match:regex;");
2503 break;
2504 }
2505 if (has_name_match) {
2506 packet.PutCString("name:");
2507 packet.PutBytesAsRawHex8(name.data(), name.size());
2508 packet.PutChar(';');
2509 }
2510 }
2511
2512 if (match_info.GetProcessInfo().ProcessIDIsValid())
2513 packet.Printf("pid:%" PRIu64 ";",
2514 match_info.GetProcessInfo().GetProcessID());
2515 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2516 packet.Printf("parent_pid:%" PRIu64 ";",
2517 match_info.GetProcessInfo().GetParentProcessID());
2518 if (match_info.GetProcessInfo().UserIDIsValid())
2519 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2520 if (match_info.GetProcessInfo().GroupIDIsValid())
2521 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2522 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2523 packet.Printf("euid:%u;",
2524 match_info.GetProcessInfo().GetEffectiveUserID());
2525 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2526 packet.Printf("egid:%u;",
2527 match_info.GetProcessInfo().GetEffectiveGroupID());
2528 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2529 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2530 const ArchSpec &match_arch =
2531 match_info.GetProcessInfo().GetArchitecture();
2532 const llvm::Triple &triple = match_arch.GetTriple();
2533 packet.PutCString("triple:");
2534 packet.PutCString(triple.getTriple());
2535 packet.PutChar(';');
2536 }
2537 }
2538 StringExtractorGDBRemote response;
2539 // Increase timeout as the first qfProcessInfo packet takes a long time on
2540 // Android. The value of 1min was arrived at empirically.
2541 ScopedTimeout timeout(*this, minutes(1));
2542 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2544 do {
2545 ProcessInstanceInfo process_info;
2546 if (!DecodeProcessInfoResponse(response, process_info))
2547 break;
2548 process_infos.push_back(process_info);
2549 response = StringExtractorGDBRemote();
2550 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2552 } else {
2554 return 0;
2555 }
2556 }
2557 return process_infos.size();
2558}
2559
2561 std::string &name) {
2563 char packet[32];
2564 const int packet_len =
2565 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2566 assert(packet_len < (int)sizeof(packet));
2567 UNUSED_IF_ASSERT_DISABLED(packet_len);
2568 StringExtractorGDBRemote response;
2569 if (SendPacketAndWaitForResponse(packet, response) ==
2571 if (response.IsNormalResponse()) {
2572 // Make sure we parsed the right number of characters. The response is
2573 // the hex encoded user name and should make up the entire packet. If
2574 // there are any non-hex ASCII bytes, the length won't match below..
2575 if (response.GetHexByteString(name) * 2 ==
2576 response.GetStringRef().size())
2577 return true;
2578 }
2579 } else {
2580 m_supports_qUserName = false;
2581 return false;
2582 }
2583 }
2584 return false;
2585}
2586
2588 std::string &name) {
2590 char packet[32];
2591 const int packet_len =
2592 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2593 assert(packet_len < (int)sizeof(packet));
2594 UNUSED_IF_ASSERT_DISABLED(packet_len);
2595 StringExtractorGDBRemote response;
2596 if (SendPacketAndWaitForResponse(packet, response) ==
2598 if (response.IsNormalResponse()) {
2599 // Make sure we parsed the right number of characters. The response is
2600 // the hex encoded group name and should make up the entire packet. If
2601 // there are any non-hex ASCII bytes, the length won't match below..
2602 if (response.GetHexByteString(name) * 2 ==
2603 response.GetStringRef().size())
2604 return true;
2605 }
2606 } else {
2607 m_supports_qGroupName = false;
2608 return false;
2609 }
2610 }
2611 return false;
2612}
2613
2614static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2615 uint32_t recv_size) {
2616 packet.Clear();
2617 packet.Printf("qSpeedTest:response_size:%x;data:", recv_size);
2618 uint32_t bytes_left = send_size;
2619 while (bytes_left > 0) {
2620 if (bytes_left >= 26) {
2621 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2622 bytes_left -= 26;
2623 } else {
2624 packet.Printf("%*.*s;", bytes_left, bytes_left,
2625 "abcdefghijklmnopqrstuvwxyz");
2626 bytes_left = 0;
2627 }
2628 }
2629}
2630
2631duration<float>
2632calculate_standard_deviation(const std::vector<duration<float>> &v) {
2633 if (v.size() == 0)
2634 return duration<float>::zero();
2635 using Dur = duration<float>;
2636 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2637 Dur mean = sum / v.size();
2638 float accum = 0;
2639 for (auto d : v) {
2640 float delta = (d - mean).count();
2641 accum += delta * delta;
2642 };
2643
2644 return Dur(sqrtf(accum / (v.size() - 1)));
2645}
2646
2648 uint32_t max_send,
2649 uint32_t max_recv,
2650 uint64_t recv_amount,
2651 bool json, Stream &strm) {
2652
2653 if (SendSpeedTestPacket(0, 0)) {
2654 StreamString packet;
2655 if (json)
2656 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2657 "\"results\" : [",
2658 num_packets);
2659 else
2660 strm.Printf("Testing sending %u packets of various sizes:\n",
2661 num_packets);
2662 strm.Flush();
2663
2664 uint32_t result_idx = 0;
2665 uint32_t send_size;
2666 std::vector<duration<float>> packet_times;
2667
2668 for (send_size = 0; send_size <= max_send;
2669 send_size ? send_size *= 2 : send_size = 4) {
2670 for (uint32_t recv_size = 0; recv_size <= max_recv;
2671 recv_size ? recv_size *= 2 : recv_size = 4) {
2672 MakeSpeedTestPacket(packet, send_size, recv_size);
2673
2674 packet_times.clear();
2675 // Test how long it takes to send 'num_packets' packets
2676 const auto start_time = steady_clock::now();
2677 for (uint32_t i = 0; i < num_packets; ++i) {
2678 const auto packet_start_time = steady_clock::now();
2679 StringExtractorGDBRemote response;
2680 SendPacketAndWaitForResponse(packet.GetString(), response);
2681 const auto packet_end_time = steady_clock::now();
2682 packet_times.push_back(packet_end_time - packet_start_time);
2683 }
2684 const auto end_time = steady_clock::now();
2685 const auto total_time = end_time - start_time;
2686
2687 float packets_per_second =
2688 ((float)num_packets) / duration<float>(total_time).count();
2689 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2690 : duration<float>::zero();
2691 const duration<float> standard_deviation =
2692 calculate_standard_deviation(packet_times);
2693 if (json) {
2694 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2695 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2696 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2697 result_idx > 0 ? "," : "", send_size, recv_size,
2698 total_time, standard_deviation);
2699 ++result_idx;
2700 } else {
2701 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2702 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2703 "standard deviation of {5,10:ms+f6}\n",
2704 send_size, recv_size, duration<float>(total_time),
2705 packets_per_second, duration<float>(average_per_packet),
2706 standard_deviation);
2707 }
2708 strm.Flush();
2709 }
2710 }
2711
2712 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2713 if (json)
2714 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2715 ": %" PRIu64 ",\n \"results\" : [",
2716 recv_amount);
2717 else
2718 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2719 "packet sizes:\n",
2720 k_recv_amount_mb);
2721 strm.Flush();
2722 send_size = 0;
2723 result_idx = 0;
2724 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2725 MakeSpeedTestPacket(packet, send_size, recv_size);
2726
2727 // If we have a receive size, test how long it takes to receive 4MB of
2728 // data
2729 if (recv_size > 0) {
2730 const auto start_time = steady_clock::now();
2731 uint32_t bytes_read = 0;
2732 uint32_t packet_count = 0;
2733 while (bytes_read < recv_amount) {
2734 StringExtractorGDBRemote response;
2735 SendPacketAndWaitForResponse(packet.GetString(), response);
2736 bytes_read += recv_size;
2737 ++packet_count;
2738 }
2739 const auto end_time = steady_clock::now();
2740 const auto total_time = end_time - start_time;
2741 float mb_second = ((float)recv_amount) /
2742 duration<float>(total_time).count() /
2743 (1024.0 * 1024.0);
2744 float packets_per_second =
2745 ((float)packet_count) / duration<float>(total_time).count();
2746 const auto average_per_packet = packet_count > 0
2747 ? total_time / packet_count
2748 : duration<float>::zero();
2749
2750 if (json) {
2751 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2752 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2753 result_idx > 0 ? "," : "", send_size, recv_size,
2754 total_time);
2755 ++result_idx;
2756 } else {
2757 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2758 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2759 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2760 send_size, recv_size, packet_count, k_recv_amount_mb,
2761 duration<float>(total_time), mb_second,
2762 packets_per_second, duration<float>(average_per_packet));
2763 }
2764 strm.Flush();
2765 }
2766 }
2767 if (json)
2768 strm.Printf("\n ]\n }\n}\n");
2769 else
2770 strm.EOL();
2771 }
2772}
2773
2775 uint32_t recv_size) {
2776 StreamString packet;
2777 MakeSpeedTestPacket(packet, send_size, recv_size);
2778
2779 StringExtractorGDBRemote response;
2780 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2782}
2783
2785 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2786 std::string &socket_name) {
2788 port = 0;
2789 socket_name.clear();
2790
2791 StringExtractorGDBRemote response;
2792 StreamString stream;
2793 stream.PutCString("qLaunchGDBServer;");
2794 std::string hostname;
2795 if (remote_accept_hostname && remote_accept_hostname[0])
2796 hostname = remote_accept_hostname;
2797 else {
2798 if (HostInfo::GetHostname(hostname)) {
2799 // Make the GDB server we launch only accept connections from this host
2800 stream.Printf("host:%s;", hostname.c_str());
2801 } else {
2802 // Make the GDB server we launch accept connections from any host since
2803 // we can't figure out the hostname
2804 stream.Printf("host:*;");
2805 }
2806 }
2807 // give the process a few seconds to startup
2808 ScopedTimeout timeout(*this, seconds(10));
2809
2810 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2812 if (response.IsErrorResponse())
2813 return false;
2814
2815 llvm::StringRef name;
2816 llvm::StringRef value;
2817 while (response.GetNameColonValue(name, value)) {
2818 if (name == "port")
2819 value.getAsInteger(BASE_10, port);
2820 else if (name == "pid")
2821 value.getAsInteger(BASE_10, pid);
2822 else if (name.compare("socket_name") == 0) {
2823 StringExtractor extractor(value);
2824 extractor.GetHexByteString(socket_name);
2825 }
2826 }
2827 return true;
2828 }
2829 return false;
2830}
2831
2833 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2834 connection_urls.clear();
2835
2836 StringExtractorGDBRemote response;
2837 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2839 return 0;
2840
2843 if (!data)
2844 return 0;
2845
2846 StructuredData::Array *array = data->GetAsArray();
2847 if (!array)
2848 return 0;
2849
2850 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2851 std::optional<StructuredData::Dictionary *> maybe_element =
2853 if (!maybe_element)
2854 continue;
2855
2856 StructuredData::Dictionary *element = *maybe_element;
2857 uint16_t port = 0;
2858 if (StructuredData::ObjectSP port_osp =
2859 element->GetValueForKey(llvm::StringRef("port")))
2860 port = port_osp->GetUnsignedIntegerValue(0);
2861
2862 std::string socket_name;
2863 if (StructuredData::ObjectSP socket_name_osp =
2864 element->GetValueForKey(llvm::StringRef("socket_name")))
2865 socket_name = std::string(socket_name_osp->GetStringValue());
2866
2867 if (port != 0 || !socket_name.empty())
2868 connection_urls.emplace_back(port, socket_name);
2869 }
2870 return connection_urls.size();
2871}
2872
2874 StreamString stream;
2875 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2876
2877 StringExtractorGDBRemote response;
2878 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2880 if (response.IsOKResponse())
2881 return true;
2882 }
2883 return false;
2884}
2885
2887 uint64_t tid, uint64_t pid, char op) {
2889 packet.PutChar('H');
2890 packet.PutChar(op);
2891
2892 if (pid != LLDB_INVALID_PROCESS_ID)
2893 packet.Printf("p%" PRIx64 ".", pid);
2894
2895 if (tid == UINT64_MAX)
2896 packet.PutCString("-1");
2897 else
2898 packet.Printf("%" PRIx64, tid);
2899
2900 StringExtractorGDBRemote response;
2901 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2903 if (response.IsOKResponse())
2904 return {{pid, tid}};
2905
2906 /*
2907 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2908 * Hg packet.
2909 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2910 * which can
2911 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2912 */
2913 if (response.IsUnsupportedResponse() && IsConnected())
2914 return {{1, 1}};
2915 }
2916 return std::nullopt;
2917}
2918
2920 uint64_t pid) {
2921 if (m_curr_tid == tid &&
2922 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2923 return true;
2924
2925 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2926 if (ret) {
2927 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2928 m_curr_pid = ret->pid;
2929 m_curr_tid = ret->tid;
2930 }
2931 return ret.has_value();
2932}
2933
2935 uint64_t pid) {
2936 if (m_curr_tid_run == tid &&
2937 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2938 return true;
2939
2940 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2941 if (ret) {
2942 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2943 m_curr_pid_run = ret->pid;
2944 m_curr_tid_run = ret->tid;
2945 }
2946 return ret.has_value();
2947}
2948
2950 StringExtractorGDBRemote &response) {
2952 return response.IsNormalResponse();
2953 return false;
2954}
2955
2957 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2959 char packet[256];
2960 int packet_len =
2961 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2962 assert(packet_len < (int)sizeof(packet));
2963 UNUSED_IF_ASSERT_DISABLED(packet_len);
2964 if (SendPacketAndWaitForResponse(packet, response) ==
2966 if (response.IsUnsupportedResponse())
2968 else if (response.IsNormalResponse())
2969 return true;
2970 else
2971 return false;
2972 } else {
2974 }
2975 }
2976 return false;
2977}
2978
2980 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2981 std::chrono::seconds timeout) {
2983 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2984 __FUNCTION__, insert ? "add" : "remove", addr);
2985
2986 // Check if the stub is known not to support this breakpoint type
2987 if (!SupportsGDBStoppointPacket(type))
2988 return UINT8_MAX;
2989 // Construct the breakpoint packet
2990 char packet[64];
2991 const int packet_len =
2992 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2993 insert ? 'Z' : 'z', type, addr, length);
2994 // Check we haven't overwritten the end of the packet buffer
2995 assert(packet_len + 1 < (int)sizeof(packet));
2996 UNUSED_IF_ASSERT_DISABLED(packet_len);
2997 StringExtractorGDBRemote response;
2998 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2999 // or "" (unsupported)
3001 // Try to send the breakpoint packet, and check that it was correctly sent
3002 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
3004 // Receive and OK packet when the breakpoint successfully placed
3005 if (response.IsOKResponse())
3006 return 0;
3007
3008 // Status while setting breakpoint, send back specific error
3009 if (response.IsErrorResponse())
3010 return response.GetError();
3011
3012 // Empty packet informs us that breakpoint is not supported
3013 if (response.IsUnsupportedResponse()) {
3014 // Disable this breakpoint type since it is unsupported
3015 switch (type) {
3017 m_supports_z0 = false;
3018 break;
3020 m_supports_z1 = false;
3021 break;
3022 case eWatchpointWrite:
3023 m_supports_z2 = false;
3024 break;
3025 case eWatchpointRead:
3026 m_supports_z3 = false;
3027 break;
3029 m_supports_z4 = false;
3030 break;
3031 case eStoppointInvalid:
3032 return UINT8_MAX;
3033 }
3034 }
3035 }
3036 // Signal generic failure
3037 return UINT8_MAX;
3038}
3039
3040std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
3042 bool &sequence_mutex_unavailable) {
3043 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
3044
3045 Lock lock(*this);
3046 if (lock) {
3047 sequence_mutex_unavailable = false;
3048 StringExtractorGDBRemote response;
3049
3050 PacketResult packet_result;
3051 for (packet_result =
3052 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
3053 packet_result == PacketResult::Success && response.IsNormalResponse();
3054 packet_result =
3055 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
3056 char ch = response.GetChar();
3057 if (ch == 'l')
3058 break;
3059 if (ch == 'm') {
3060 do {
3061 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
3062 // If we get an invalid response, break out of the loop.
3063 // If there are valid tids, they have been added to ids.
3064 // If there are no valid tids, we'll fall through to the
3065 // bare-iron target handling below.
3066 if (!pid_tid)
3067 break;
3068
3069 ids.push_back(*pid_tid);
3070 ch = response.GetChar(); // Skip the command separator
3071 } while (ch == ','); // Make sure we got a comma separator
3072 }
3073 }
3074
3075 /*
3076 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3077 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
3078 * could
3079 * be as simple as 'S05'. There is no packet which can give us pid and/or
3080 * tid.
3081 * Assume pid=tid=1 in such cases.
3082 */
3083 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
3084 ids.size() == 0 && IsConnected()) {
3085 ids.emplace_back(1, 1);
3086 }
3087 } else {
3089 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
3090 "packet 'qfThreadInfo'");
3091 sequence_mutex_unavailable = true;
3092 }
3093
3094 return ids;
3095}
3096
3098 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
3100 thread_ids.clear();
3101
3102 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
3103 if (ids.empty() || sequence_mutex_unavailable)
3104 return 0;
3105
3106 for (auto id : ids) {
3107 // skip threads that do not belong to the current process
3108 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
3109 continue;
3110 if (id.second != LLDB_INVALID_THREAD_ID &&
3112 thread_ids.push_back(id.second);
3113 }
3114
3115 return thread_ids.size();
3116}
3117
3119 StringExtractorGDBRemote response;
3120 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
3122 !response.IsNormalResponse())
3123 return LLDB_INVALID_ADDRESS;
3124 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3125}
3126
3128 llvm::StringRef command,
3129 const FileSpec &
3130 working_dir, // Pass empty FileSpec to use the current working directory
3131 int *status_ptr, // Pass NULL if you don't want the process exit status
3132 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
3133 // process to exit
3134 std::string
3135 *command_output, // Pass nullptr if you don't want the command output
3136 std::string *separated_error_output, // Pass nullptr if you don't want the
3137 // command error output
3138 const Timeout<std::micro> &timeout) {
3140 stream.PutCString("qPlatform_shell:");
3141 stream.PutBytesAsRawHex8(command.data(), command.size());
3142 stream.PutChar(',');
3143 uint32_t timeout_sec = UINT32_MAX;
3144 if (timeout) {
3145 // TODO: Use chrono version of std::ceil once c++17 is available.
3146 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
3147 }
3148 stream.PutHex32(timeout_sec);
3149 if (working_dir) {
3150 std::string path{working_dir.GetPath(false)};
3151 stream.PutChar(',');
3152 stream.PutStringAsRawHex8(path);
3153 }
3154 StringExtractorGDBRemote response;
3155 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3157 if (response.GetChar() != 'F')
3158 return Status::FromErrorString("malformed reply");
3159 if (response.GetChar() != ',')
3160 return Status::FromErrorString("malformed reply");
3161 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3162 if (exitcode == UINT32_MAX)
3163 return Status::FromErrorString("unable to run remote process");
3164 else if (status_ptr)
3165 *status_ptr = exitcode;
3166 if (response.GetChar() != ',')
3167 return Status::FromErrorString("malformed reply");
3168 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3169 if (signo_ptr)
3170 *signo_ptr = signo;
3171 if (response.GetChar() != ',')
3172 return Status::FromErrorString("malformed reply");
3173 std::string output;
3174 response.GetEscapedBinaryData(output);
3175 if (command_output)
3176 command_output->assign(output);
3177 return Status();
3178 }
3179 return Status::FromErrorString("unable to send packet");
3180}
3181
3183 uint32_t file_permissions) {
3184 std::string path{file_spec.GetPath(false)};
3186 stream.PutCString("qPlatform_mkdir:");
3187 stream.PutHex32(file_permissions);
3188 stream.PutChar(',');
3189 stream.PutStringAsRawHex8(path);
3190 llvm::StringRef packet = stream.GetString();
3191 StringExtractorGDBRemote response;
3192
3193 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3194 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3195 packet.str().c_str());
3196
3197 if (response.GetChar() != 'F')
3198 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3199 packet.str().c_str());
3200
3201 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3202}
3203
3204Status
3206 uint32_t file_permissions) {
3207 std::string path{file_spec.GetPath(false)};
3209 stream.PutCString("qPlatform_chmod:");
3210 stream.PutHex32(file_permissions);
3211 stream.PutChar(',');
3212 stream.PutStringAsRawHex8(path);
3213 llvm::StringRef packet = stream.GetString();
3214 StringExtractorGDBRemote response;
3215
3216 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3217 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3218 stream.GetData());
3219
3220 if (response.GetChar() != 'F')
3221 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3222 stream.GetData());
3223
3224 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3225}
3226
3227static int gdb_errno_to_system(int err) {
3228 switch (err) {
3229#define HANDLE_ERRNO(name, value) \
3230 case GDB_##name: \
3231 return name;
3232#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3233 default:
3234 return -1;
3235 }
3236}
3237
3239 uint64_t fail_result, Status &error) {
3240 response.SetFilePos(0);
3241 if (response.GetChar() != 'F')
3242 return fail_result;
3243 int32_t result = response.GetS32(-2, 16);
3244 if (result == -2)
3245 return fail_result;
3246 if (response.GetChar() == ',') {
3247 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3248 if (result_errno != -1)
3249 error = Status(result_errno, eErrorTypePOSIX);
3250 else
3252 } else
3253 error.Clear();
3254 return result;
3255}
3258 File::OpenOptions flags, mode_t mode,
3259 Status &error) {
3260 std::string path(file_spec.GetPath(false));
3262 stream.PutCString("vFile:open:");
3263 if (path.empty())
3264 return UINT64_MAX;
3265 stream.PutStringAsRawHex8(path);
3266 stream.PutChar(',');
3267 stream.PutHex32(flags);
3268 stream.PutChar(',');
3269 stream.PutHex32(mode);
3270 StringExtractorGDBRemote response;
3271 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3273 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3274 }
3275 return UINT64_MAX;
3276}
3277
3279 Status &error) {
3281 stream.Printf("vFile:close:%x", (int)fd);
3282 StringExtractorGDBRemote response;
3283 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3285 return ParseHostIOPacketResponse(response, -1, error) == 0;
3286 }
3287 return false;
3288}
3289
3290std::optional<GDBRemoteFStatData>
3293 stream.Printf("vFile:fstat:%" PRIx64, fd);
3294 StringExtractorGDBRemote response;
3295 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3297 if (response.GetChar() != 'F')
3298 return std::nullopt;
3299 int64_t size = response.GetS64(-1, 16);
3300 if (size > 0 && response.GetChar() == ';') {
3301 std::string buffer;
3302 if (response.GetEscapedBinaryData(buffer)) {
3304 if (buffer.size() != sizeof(out))
3305 return std::nullopt;
3306 memcpy(&out, buffer.data(), sizeof(out));
3307 return out;
3308 }
3309 }
3310 }
3311 return std::nullopt;
3312}
3313
3314std::optional<GDBRemoteFStatData>
3316 Status error;
3318 if (fd == UINT64_MAX)
3319 return std::nullopt;
3320 std::optional<GDBRemoteFStatData> st = FStat(fd);
3321 CloseFile(fd, error);
3322 return st;
3323}
3324
3325// Extension of host I/O packets to get the file size.
3327 const lldb_private::FileSpec &file_spec) {
3329 std::string path(file_spec.GetPath(false));
3331 stream.PutCString("vFile:size:");
3332 stream.PutStringAsRawHex8(path);
3333 StringExtractorGDBRemote response;
3334 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3336 return UINT64_MAX;
3337
3338 if (!response.IsUnsupportedResponse()) {
3339 if (response.GetChar() != 'F')
3340 return UINT64_MAX;
3341 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3342 return retcode;
3343 }
3344 m_supports_vFileSize = false;
3345 }
3346
3347 // Fallback to fstat.
3348 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3349 return st ? st->gdb_st_size : UINT64_MAX;
3350}
3351
3353 CompletionRequest &request, bool only_dir) {
3355 stream.PutCString("qPathComplete:");
3356 stream.PutHex32(only_dir ? 1 : 0);
3357 stream.PutChar(',');
3359 StringExtractorGDBRemote response;
3360 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3362 StreamString strm;
3363 char ch = response.GetChar();
3364 if (ch != 'M')
3365 return;
3366 while (response.Peek()) {
3367 strm.Clear();
3368 while ((ch = response.GetHexU8(0, false)) != '\0')
3369 strm.PutChar(ch);
3370 request.AddCompletion(strm.GetString());
3371 if (response.GetChar() != ',')
3372 break;
3373 }
3374 }
3375}
3376
3377Status
3379 uint32_t &file_permissions) {
3381 std::string path{file_spec.GetPath(false)};
3382 Status error;
3384 stream.PutCString("vFile:mode:");
3385 stream.PutStringAsRawHex8(path);
3386 StringExtractorGDBRemote response;
3387 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3389 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3390 stream.GetData());
3391 return error;
3392 }
3393 if (!response.IsUnsupportedResponse()) {
3394 if (response.GetChar() != 'F') {
3396 "invalid response to '%s' packet", stream.GetData());
3397 } else {
3398 const uint32_t mode = response.GetS32(-1, 16);
3399 if (static_cast<int32_t>(mode) == -1) {
3400 if (response.GetChar() == ',') {
3401 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3402 if (response_errno > 0)
3403 error = Status(response_errno, lldb::eErrorTypePOSIX);
3404 else
3405 error = Status::FromErrorString("unknown error");
3406 } else
3407 error = Status::FromErrorString("unknown error");
3408 } else {
3409 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3410 }
3411 }
3412 return error;
3413 } else { // response.IsUnsupportedResponse()
3414 m_supports_vFileMode = false;
3415 }
3416 }
3417
3418 // Fallback to fstat.
3419 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3420 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3421 return Status();
3422 }
3423 return Status::FromErrorString("fstat failed");
3424}
3425
3427 uint64_t offset, void *dst,
3428 uint64_t dst_len,
3429 Status &error) {
3431 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3432 offset);
3433 StringExtractorGDBRemote response;
3434 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3436 if (response.GetChar() != 'F')
3437 return 0;
3438 int64_t retcode = response.GetS64(-1, 16);
3439 if (retcode == -1) {
3440 error = Status::FromErrorString("unknown error");
3441 if (response.GetChar() == ',') {
3442 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3443 if (response_errno > 0)
3444 error = Status(response_errno, lldb::eErrorTypePOSIX);
3445 }
3446 return -1;
3447 }
3448 const char next = (response.Peek() ? *response.Peek() : 0);
3449 if (next == ',')
3450 return 0;
3451 if (next == ';') {
3452 response.GetChar(); // skip the semicolon
3453 std::string buffer;
3454 if (response.GetEscapedBinaryData(buffer)) {
3455 const uint64_t data_to_write =
3456 std::min<uint64_t>(dst_len, buffer.size());
3457 if (data_to_write > 0)
3458 memcpy(dst, &buffer[0], data_to_write);
3459 return data_to_write;
3460 }
3461 }
3462 }
3463 return 0;
3464}
3465
3467 uint64_t offset,
3468 const void *src,
3469 uint64_t src_len,
3470 Status &error) {
3472 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3473 stream.PutEscapedBytes(src, src_len);
3474 StringExtractorGDBRemote response;
3475 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3477 if (response.GetChar() != 'F') {
3478 error = Status::FromErrorStringWithFormat("write file failed");
3479 return 0;
3480 }
3481 int64_t bytes_written = response.GetS64(-1, 16);
3482 if (bytes_written == -1) {
3483 error = Status::FromErrorString("unknown error");
3484 if (response.GetChar() == ',') {
3485 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3486 if (response_errno > 0)
3487 error = Status(response_errno, lldb::eErrorTypePOSIX);
3488 }
3489 return -1;
3490 }
3491 return bytes_written;
3492 } else {
3493 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3494 }
3495 return 0;
3496}
3497
3499 const FileSpec &dst) {
3500 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3501 Status error;
3503 stream.PutCString("vFile:symlink:");
3504 // the unix symlink() command reverses its parameters where the dst if first,
3505 // so we follow suit here
3506 stream.PutStringAsRawHex8(dst_path);
3507 stream.PutChar(',');
3508 stream.PutStringAsRawHex8(src_path);
3509 StringExtractorGDBRemote response;
3510 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3512 if (response.GetChar() == 'F') {
3513 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3514 if (result != 0) {
3515 error = Status::FromErrorString("unknown error");
3516 if (response.GetChar() == ',') {
3517 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3518 if (response_errno > 0)
3519 error = Status(response_errno, lldb::eErrorTypePOSIX);
3520 }
3521 }
3522 } else {
3523 // Should have returned with 'F<result>[,<errno>]'
3524 error = Status::FromErrorStringWithFormat("symlink failed");
3525 }
3526 } else {
3527 error = Status::FromErrorString("failed to send vFile:symlink packet");
3528 }
3529 return error;
3530}
3531
3533 std::string path{file_spec.GetPath(false)};
3534 Status error;
3536 stream.PutCString("vFile:unlink:");
3537 // the unix symlink() command reverses its parameters where the dst if first,
3538 // so we follow suit here
3539 stream.PutStringAsRawHex8(path);
3540 StringExtractorGDBRemote response;
3541 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3543 if (response.GetChar() == 'F') {
3544 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3545 if (result != 0) {
3546 error = Status::FromErrorString("unknown error");
3547 if (response.GetChar() == ',') {
3548 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3549 if (response_errno > 0)
3550 error = Status(response_errno, lldb::eErrorTypePOSIX);
3551 }
3552 }
3553 } else {
3554 // Should have returned with 'F<result>[,<errno>]'
3555 error = Status::FromErrorStringWithFormat("unlink failed");
3556 }
3557 } else {
3558 error = Status::FromErrorString("failed to send vFile:unlink packet");
3559 }
3560 return error;
3561}
3562
3563// Extension of host I/O packets to get whether a file exists.
3565 const lldb_private::FileSpec &file_spec) {
3567 std::string path(file_spec.GetPath(false));
3569 stream.PutCString("vFile:exists:");
3570 stream.PutStringAsRawHex8(path);
3571 StringExtractorGDBRemote response;
3572 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3574 return false;
3575 if (!response.IsUnsupportedResponse()) {
3576 if (response.GetChar() != 'F')
3577 return false;
3578 if (response.GetChar() != ',')
3579 return false;
3580 bool retcode = (response.GetChar() != '0');
3581 return retcode;
3582 } else
3583 m_supports_vFileExists = false;
3584 }
3585
3586 // Fallback to open.
3587 Status error;
3589 if (fd == UINT64_MAX)
3590 return false;
3591 CloseFile(fd, error);
3592 return true;
3593}
3594
3595llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3596 const lldb_private::FileSpec &file_spec) {
3597 std::string path(file_spec.GetPath(false));
3599 stream.PutCString("vFile:MD5:");
3600 stream.PutStringAsRawHex8(path);
3601 StringExtractorGDBRemote response;
3602 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3604 if (response.GetChar() != 'F')
3605 return std::make_error_code(std::errc::illegal_byte_sequence);
3606 if (response.GetChar() != ',')
3607 return std::make_error_code(std::errc::illegal_byte_sequence);
3608 if (response.Peek() && *response.Peek() == 'x')
3609 return std::make_error_code(std::errc::no_such_file_or_directory);
3610
3611 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3612 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3613 // handle the concatenated hex string. What would happen is parsing the low
3614 // would consume the whole response packet which would give incorrect
3615 // results. Instead, we get the byte string for each low and high hex
3616 // separately, and parse them.
3617 //
3618 // An alternate way to handle this is to change the server to put a
3619 // delimiter between the low/high parts, and change the client to parse the
3620 // delimiter. However, we choose not to do this so existing lldb-servers
3621 // don't have to be patched
3622
3623 // The checksum is 128 bits encoded as hex
3624 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3625 // Each byte takes 2 hex characters in the response.
3626 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3627
3628 // Get low part
3629 auto part =
3630 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3631 if (part.size() != MD5_HALF_LENGTH)
3632 return std::make_error_code(std::errc::illegal_byte_sequence);
3633 response.SetFilePos(response.GetFilePos() + part.size());
3634
3635 uint64_t low;
3636 if (part.getAsInteger(BASE_16, low))
3637 return std::make_error_code(std::errc::illegal_byte_sequence);
3638
3639 // Get high part
3640 part =
3641 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3642 if (part.size() != MD5_HALF_LENGTH)
3643 return std::make_error_code(std::errc::illegal_byte_sequence);
3644 response.SetFilePos(response.GetFilePos() + part.size());
3645
3646 uint64_t high;
3647 if (part.getAsInteger(BASE_16, high))
3648 return std::make_error_code(std::errc::illegal_byte_sequence);
3649
3650 llvm::MD5::MD5Result result;
3651 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3652 result.data(), low);
3653 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3654 result.data() + 8, high);
3655
3656 return result;
3657 }
3658 return std::make_error_code(std::errc::operation_canceled);
3659}
3660
3662 // Some targets have issues with g/G packets and we need to avoid using them
3664 if (process) {
3666 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3667 if (arch.IsValid() &&
3668 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3669 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3670 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3671 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3673 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3674 if (gdb_server_version != 0) {
3675 const char *gdb_server_name = GetGDBServerProgramName();
3676 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3677 if (gdb_server_version >= 310)
3679 }
3680 }
3681 }
3682 }
3683 }
3685}
3686
3688 uint32_t reg) {
3689 StreamString payload;
3690 payload.Printf("p%x", reg);
3691 StringExtractorGDBRemote response;
3693 tid, std::move(payload), response) != PacketResult::Success ||
3694 !response.IsNormalResponse())
3695 return nullptr;
3696
3697 WritableDataBufferSP buffer_sp(
3698 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3699 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3700 return buffer_sp;
3701}
3702
3704 StreamString payload;
3705 payload.PutChar('g');
3706 StringExtractorGDBRemote response;
3708 tid, std::move(payload), response) != PacketResult::Success ||
3709 !response.IsNormalResponse())
3710 return nullptr;
3711
3712 WritableDataBufferSP buffer_sp(
3713 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3714 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3715 return buffer_sp;
3716}
3717
3719 uint32_t reg_num,
3720 llvm::ArrayRef<uint8_t> data) {
3721 StreamString payload;
3722 payload.Printf("P%x=", reg_num);
3723 payload.PutBytesAsRawHex8(data.data(), data.size(),
3726 StringExtractorGDBRemote response;
3728 tid, std::move(payload), response) == PacketResult::Success &&
3729 response.IsOKResponse();
3730}
3731
3733 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3734 StreamString payload;
3735 payload.PutChar('G');
3736 payload.PutBytesAsRawHex8(data.data(), data.size(),
3739 StringExtractorGDBRemote response;
3741 tid, std::move(payload), response) == PacketResult::Success &&
3742 response.IsOKResponse();
3743}
3744
3746 uint32_t &save_id) {
3747 save_id = 0; // Set to invalid save ID
3749 return false;
3750
3752 StreamString payload;
3753 payload.PutCString("QSaveRegisterState");
3754 StringExtractorGDBRemote response;
3756 tid, std::move(payload), response) != PacketResult::Success)
3757 return false;
3758
3759 if (response.IsUnsupportedResponse())
3761
3762 const uint32_t response_save_id = response.GetU32(0);
3763 if (response_save_id == 0)
3764 return false;
3765
3766 save_id = response_save_id;
3767 return true;
3768}
3769
3771 uint32_t save_id) {
3772 // We use the "m_supports_QSaveRegisterState" variable here because the
3773 // QSaveRegisterState and QRestoreRegisterState packets must both be
3774 // supported in order to be useful
3776 return false;
3777
3778 StreamString payload;
3779 payload.Printf("QRestoreRegisterState:%u", save_id);
3780 StringExtractorGDBRemote response;
3782 tid, std::move(payload), response) != PacketResult::Success)
3783 return false;
3784
3785 if (response.IsOKResponse())
3786 return true;
3787
3788 if (response.IsUnsupportedResponse())
3790 return false;
3791}
3792
3795 return false;
3796
3797 StreamString packet;
3798 StringExtractorGDBRemote response;
3799 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3800 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3802 response.IsOKResponse();
3803}
3804
3805llvm::Expected<TraceSupportedResponse>
3807 Log *log = GetLog(GDBRLog::Process);
3808
3809 StreamGDBRemote escaped_packet;
3810 escaped_packet.PutCString("jLLDBTraceSupported");
3811
3812 StringExtractorGDBRemote response;
3813 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3814 timeout) ==
3816 if (response.IsErrorResponse())
3817 return response.GetStatus().ToError();
3818 if (response.IsUnsupportedResponse())
3819 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3820 "jLLDBTraceSupported is unsupported");
3821
3822 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3823 "TraceSupportedResponse");
3824 }
3825 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3826 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3827 "failed to send packet: jLLDBTraceSupported");
3828}
3829
3830llvm::Error
3832 std::chrono::seconds timeout) {
3833 Log *log = GetLog(GDBRLog::Process);
3834
3835 StreamGDBRemote escaped_packet;
3836 escaped_packet.PutCString("jLLDBTraceStop:");
3837
3838 std::string json_string;
3839 llvm::raw_string_ostream os(json_string);
3840 os << toJSON(request);
3841
3842 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3843
3844 StringExtractorGDBRemote response;
3845 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3846 timeout) ==
3848 if (response.IsErrorResponse())
3849 return response.GetStatus().ToError();
3850 if (response.IsUnsupportedResponse())
3851 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3852 "jLLDBTraceStop is unsupported");
3853 if (response.IsOKResponse())
3854 return llvm::Error::success();
3855 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3856 "Invalid jLLDBTraceStart response");
3857 }
3858 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3859 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3860 "failed to send packet: jLLDBTraceStop '%s'",
3861 escaped_packet.GetData());
3862}
3863
3864llvm::Error
3865GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3866 std::chrono::seconds timeout) {
3867 Log *log = GetLog(GDBRLog::Process);
3868
3869 StreamGDBRemote escaped_packet;
3870 escaped_packet.PutCString("jLLDBTraceStart:");
3871
3872 std::string json_string;
3873 llvm::raw_string_ostream os(json_string);
3874 os << params;
3875
3876 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3877
3878 StringExtractorGDBRemote response;
3879 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3880 timeout) ==
3882 if (response.IsErrorResponse())
3883 return response.GetStatus().ToError();
3884 if (response.IsUnsupportedResponse())
3885 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3886 "jLLDBTraceStart is unsupported");
3887 if (response.IsOKResponse())
3888 return llvm::Error::success();
3889 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3890 "Invalid jLLDBTraceStart response");
3891 }
3892 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3893 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3894 "failed to send packet: jLLDBTraceStart '%s'",
3895 escaped_packet.GetData());
3896}
3897
3898llvm::Expected<std::string>
3900 std::chrono::seconds timeout) {
3901 Log *log = GetLog(GDBRLog::Process);
3902
3903 StreamGDBRemote escaped_packet;
3904 escaped_packet.PutCString("jLLDBTraceGetState:");
3905
3906 std::string json_string;
3907 llvm::raw_string_ostream os(json_string);
3908 os << toJSON(TraceGetStateRequest{type.str()});
3909
3910 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3911
3912 StringExtractorGDBRemote response;
3913 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3914 timeout) ==
3916 if (response.IsErrorResponse())
3917 return response.GetStatus().ToError();
3918 if (response.IsUnsupportedResponse())
3919 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3920 "jLLDBTraceGetState is unsupported");
3921 return std::string(response.Peek());
3922 }
3923
3924 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3925 return llvm::createStringError(
3926 llvm::inconvertibleErrorCode(),
3927 "failed to send packet: jLLDBTraceGetState '%s'",
3928 escaped_packet.GetData());
3929}
3930
3931llvm::Expected<std::vector<uint8_t>>
3933 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3934 Log *log = GetLog(GDBRLog::Process);
3935
3936 StreamGDBRemote escaped_packet;
3937 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3938
3939 std::string json_string;
3940 llvm::raw_string_ostream os(json_string);
3941 os << toJSON(request);
3942
3943 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3944
3945 StringExtractorGDBRemote response;
3946 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3947 timeout) ==
3949 if (response.IsErrorResponse())
3950 return response.GetStatus().ToError();
3951 std::string data;
3952 response.GetEscapedBinaryData(data);
3953 return std::vector<uint8_t>(data.begin(), data.end());
3954 }
3955 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3956 return llvm::createStringError(
3957 llvm::inconvertibleErrorCode(),
3958 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3959 escaped_packet.GetData());
3960}
3961
3963 StringExtractorGDBRemote response;
3964 if (SendPacketAndWaitForResponse("qOffsets", response) !=
3966 return std::nullopt;
3967 if (!response.IsNormalResponse())
3968 return std::nullopt;
3969
3970 QOffsets result;
3971 llvm::StringRef ref = response.GetStringRef();
3972 const auto &GetOffset = [&] {
3973 addr_t offset;
3974 if (ref.consumeInteger(16, offset))
3975 return false;
3976 result.offsets.push_back(offset);
3977 return true;
3978 };
3979
3980 if (ref.consume_front("Text=")) {
3981 result.segments = false;
3982 if (!GetOffset())
3983 return std::nullopt;
3984 if (!ref.consume_front(";Data=") || !GetOffset())
3985 return std::nullopt;
3986 if (ref.empty())
3987 return result;
3988 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3989 return result;
3990 } else if (ref.consume_front("TextSeg=")) {
3991 result.segments = true;
3992 if (!GetOffset())
3993 return std::nullopt;
3994 if (ref.empty())
3995 return result;
3996 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3997 return result;
3998 }
3999 return std::nullopt;
4000}
4001
4003 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
4004 ModuleSpec &module_spec) {
4006 return false;
4007
4008 std::string module_path = module_file_spec.GetPath(false);
4009 if (module_path.empty())
4010 return false;
4011
4012 StreamString packet;
4013 packet.PutCString("qModuleInfo:");
4014 packet.PutStringAsRawHex8(module_path);
4015 packet.PutCString(";");
4016 const auto &triple = arch_spec.GetTriple().getTriple();
4017 packet.PutStringAsRawHex8(triple);
4018
4019 StringExtractorGDBRemote response;
4020 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
4022 return false;
4023
4024 if (response.IsErrorResponse())
4025 return false;
4026
4027 if (response.IsUnsupportedResponse()) {
4028 m_supports_qModuleInfo = false;
4029 return false;
4030 }
4031
4032 llvm::StringRef name;
4033 llvm::StringRef value;
4034
4035 module_spec.Clear();
4036 module_spec.GetFileSpec() = module_file_spec;
4037
4038 while (response.GetNameColonValue(name, value)) {
4039 if (name == "uuid" || name == "md5") {
4040 StringExtractor extractor(value);
4041 std::string uuid;
4042 extractor.GetHexByteString(uuid);
4043 module_spec.GetUUID().SetFromStringRef(uuid);
4044 } else if (name == "triple") {
4045 StringExtractor extractor(value);
4046 std::string triple;
4047 extractor.GetHexByteString(triple);
4048 module_spec.GetArchitecture().SetTriple(triple.c_str());
4049 } else if (name == "file_offset") {
4050 uint64_t ival = 0;
4051 if (!value.getAsInteger(BASE_16, ival))
4052 module_spec.SetObjectOffset(ival);
4053 } else if (name == "file_size") {
4054 uint64_t ival = 0;
4055 if (!value.getAsInteger(BASE_16, ival))
4056 module_spec.SetObjectSize(ival);
4057 } else if (name == "file_path") {
4058 StringExtractor extractor(value);
4059 std::string path;
4060 extractor.GetHexByteString(path);
4061 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
4062 }
4063 }
4064
4065 return true;
4066}
4067
4068static std::optional<ModuleSpec>
4070 ModuleSpec result;
4071 if (!dict)
4072 return std::nullopt;
4073
4074 llvm::StringRef string;
4075 uint64_t integer;
4076
4077 if (!dict->GetValueForKeyAsString("uuid", string))
4078 return std::nullopt;
4079 if (!result.GetUUID().SetFromStringRef(string))
4080 return std::nullopt;
4081
4082 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
4083 return std::nullopt;
4084 result.SetObjectOffset(integer);
4085
4086 if (!dict->GetValueForKeyAsInteger("file_size", integer))
4087 return std::nullopt;
4088 result.SetObjectSize(integer);
4089
4090 if (!dict->GetValueForKeyAsString("triple", string))
4091 return std::nullopt;
4092 result.GetArchitecture().SetTriple(string);
4093
4094 if (!dict->GetValueForKeyAsString("file_path", string))
4095 return std::nullopt;
4096 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
4097
4098 return result;
4099}
4100
4101std::optional<std::vector<ModuleSpec>>
4103 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4104 namespace json = llvm::json;
4105
4107 return std::nullopt;
4108
4109 json::Array module_array;
4110 for (const FileSpec &module_file_spec : module_file_specs) {
4111 module_array.push_back(
4112 json::Object{{"file", module_file_spec.GetPath(false)},
4113 {"triple", triple.getTriple()}});
4114 }
4115 StreamString unescaped_payload;
4116 unescaped_payload.PutCString("jModulesInfo:");
4117 unescaped_payload.AsRawOstream() << std::move(module_array);
4118
4119 StreamGDBRemote payload;
4120 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
4121 unescaped_payload.GetSize());
4122
4123 // Increase the timeout for jModulesInfo since this packet can take longer.
4124 ScopedTimeout timeout(*this, std::chrono::seconds(10));
4125
4126 StringExtractorGDBRemote response;
4127 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
4129 response.IsErrorResponse())
4130 return std::nullopt;
4131
4132 if (response.IsUnsupportedResponse()) {
4134 return std::nullopt;
4135 }
4136
4137 StructuredData::ObjectSP response_object_sp =
4139 if (!response_object_sp)
4140 return std::nullopt;
4141
4142 StructuredData::Array *response_array = response_object_sp->GetAsArray();
4143 if (!response_array)
4144 return std::nullopt;
4145
4146 std::vector<ModuleSpec> result;
4147 for (size_t i = 0; i < response_array->GetSize(); ++i) {
4148 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4149 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4150 result.push_back(*module_spec);
4151 }
4152
4153 return result;
4154}
4155
4156// query the target remote for extended information using the qXfer packet
4157//
4158// example: object='features', annex='target.xml'
4159// return: <xml output> or error
4160llvm::Expected<std::string>
4162 llvm::StringRef annex) {
4163
4164 std::string output;
4165 llvm::raw_string_ostream output_stream(output);
4167
4168 uint64_t size = GetRemoteMaxPacketSize();
4169 if (size == 0)
4170 size = 0x1000;
4171 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4172 int offset = 0;
4173 bool active = true;
4174
4175 // loop until all data has been read
4176 while (active) {
4177
4178 // send query extended feature packet
4179 std::string packet =
4180 ("qXfer:" + object + ":read:" + annex + ":" +
4181 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4182 .str();
4183
4185 SendPacketAndWaitForResponse(packet, chunk);
4186
4188 chunk.GetStringRef().empty()) {
4189 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4190 "Error sending $qXfer packet");
4191 }
4192
4193 // check packet code
4194 switch (chunk.GetStringRef()[0]) {
4195 // last chunk
4196 case ('l'):
4197 active = false;
4198 [[fallthrough]];
4199
4200 // more chunks
4201 case ('m'):
4202 output_stream << chunk.GetStringRef().drop_front();
4203 offset += chunk.GetStringRef().size() - 1;
4204 break;
4205
4206 // unknown chunk
4207 default:
4208 return llvm::createStringError(
4209 llvm::inconvertibleErrorCode(),
4210 "Invalid continuation code from $qXfer packet");
4211 }
4212 }
4213
4214 return output;
4215}
4216
4217// Notify the target that gdb is prepared to serve symbol lookup requests.
4218// packet: "qSymbol::"
4219// reply:
4220// OK The target does not need to look up any (more) symbols.
4221// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4222// encoded).
4223// LLDB may provide the value by sending another qSymbol
4224// packet
4225// in the form of"qSymbol:<sym_value>:<sym_name>".
4226//
4227// Three examples:
4228//
4229// lldb sends: qSymbol::
4230// lldb receives: OK
4231// Remote gdb stub does not need to know the addresses of any symbols, lldb
4232// does not
4233// need to ask again in this session.
4234//
4235// lldb sends: qSymbol::
4236// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4237// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4238// lldb receives: OK
4239// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4240// not know
4241// the address at this time. lldb needs to send qSymbol:: again when it has
4242// more
4243// solibs loaded.
4244//
4245// lldb sends: qSymbol::
4246// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4247// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4248// lldb receives: OK
4249// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4250// that it
4251// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4252// does not
4253// need any more symbols. lldb does not need to ask again in this session.
4254
4256 lldb_private::Process *process) {
4257 // Set to true once we've resolved a symbol to an address for the remote
4258 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4259 // any more symbols and we can stop asking.
4260 bool symbol_response_provided = false;
4261
4262 // Is this the initial qSymbol:: packet?
4263 bool first_qsymbol_query = true;
4264
4266 Lock lock(*this);
4267 if (lock) {
4268 StreamString packet;
4269 packet.PutCString("qSymbol::");
4270 StringExtractorGDBRemote response;
4271 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4273 if (response.IsOKResponse()) {
4274 if (symbol_response_provided || first_qsymbol_query) {
4276 }
4277
4278 // We are done serving symbols requests
4279 return;
4280 }
4281 first_qsymbol_query = false;
4282
4283 if (response.IsUnsupportedResponse()) {
4284 // qSymbol is not supported by the current GDB server we are
4285 // connected to
4286 m_supports_qSymbol = false;
4287 return;
4288 } else {
4289 llvm::StringRef response_str(response.GetStringRef());
4290 if (response_str.starts_with("qSymbol:")) {
4291 response.SetFilePos(strlen("qSymbol:"));
4292 std::string symbol_name;
4293 if (response.GetHexByteString(symbol_name)) {
4294 if (symbol_name.empty())
4295 return;
4296
4297 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4300 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4301 for (const SymbolContext &sc : sc_list) {
4302 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4303 break;
4304 if (sc.symbol) {
4305 switch (sc.symbol->GetType()) {
4306 case eSymbolTypeInvalid:
4313 case eSymbolTypeBlock:
4314 case eSymbolTypeLocal:
4315 case eSymbolTypeParam:
4326 if (sc.module_sp->GetArchitecture()
4327 .GetTriple()
4328 .getObjectFormat() !=
4329 llvm::Triple::ObjectFormatType::MachO) {
4330 // GDB does return symbols even when they are of unknown
4331 // type, following this behavior on non Mach-O
4332 // architectures.
4333 symbol_load_addr =
4334 sc.symbol->GetLoadAddress(&process->GetTarget());
4335 if (symbol_load_addr == LLDB_INVALID_ADDRESS) {
4336 symbol_load_addr = sc.symbol->GetRawValue();
4337 }
4338 }
4339 break;
4340
4341 case eSymbolTypeCode:
4343 case eSymbolTypeData:
4344 case eSymbolTypeRuntime:
4350 symbol_load_addr =
4351 sc.symbol->GetLoadAddress(&process->GetTarget());
4352 break;
4353 }
4354 }
4355 }
4356 // This is the normal path where our symbol lookup was successful
4357 // and we want to send a packet with the new symbol value and see
4358 // if another lookup needs to be done.
4359
4360 // Change "packet" to contain the requested symbol value and name
4361 packet.Clear();
4362 packet.PutCString("qSymbol:");
4363 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4364 packet.Printf("%" PRIx64, symbol_load_addr);
4365 symbol_response_provided = true;
4366 } else {
4367 symbol_response_provided = false;
4368 }
4369 packet.PutCString(":");
4370 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4371 continue; // go back to the while loop and send "packet" and wait
4372 // for another response
4373 }
4374 }
4375 }
4376 }
4377 // If we make it here, the symbol request packet response wasn't valid or
4378 // our symbol lookup failed so we must abort
4379 return;
4380
4381 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4382 LLDB_LOGF(log,
4383 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4384 __FUNCTION__);
4385 }
4386 }
4387}
4388
4392 // Query the server for the array of supported asynchronous JSON packets.
4394
4395 Log *log = GetLog(GDBRLog::Process);
4396
4397 // Poll it now.
4398 StringExtractorGDBRemote response;
4399 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4404 !m_supported_async_json_packets_sp->GetAsArray()) {
4405 // We were returned something other than a JSON array. This is
4406 // invalid. Clear it out.
4407 LLDB_LOGF(log,
4408 "GDBRemoteCommunicationClient::%s(): "
4409 "QSupportedAsyncJSONPackets returned invalid "
4410 "result: %s",
4411 __FUNCTION__, response.GetStringRef().data());
4413 }
4414 } else {
4415 LLDB_LOGF(log,
4416 "GDBRemoteCommunicationClient::%s(): "
4417 "QSupportedAsyncJSONPackets unsupported",
4418 __FUNCTION__);
4419 }
4420
4422 StreamString stream;
4424 LLDB_LOGF(log,
4425 "GDBRemoteCommunicationClient::%s(): supported async "
4426 "JSON packets: %s",
4427 __FUNCTION__, stream.GetData());
4428 }
4429 }
4430
4432 ? m_supported_async_json_packets_sp->GetAsArray()
4433 : nullptr;
4434}
4435
4437 llvm::ArrayRef<int32_t> signals) {
4438 // Format packet:
4439 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4440 auto range = llvm::make_range(signals.begin(), signals.end());
4441 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4442
4443 StringExtractorGDBRemote response;
4444 auto send_status = SendPacketAndWaitForResponse(packet, response);
4445
4447 return Status::FromErrorString("Sending QPassSignals packet failed");
4448
4449 if (response.IsOKResponse()) {
4450 return Status();
4451 } else {
4453 "Unknown error happened during sending QPassSignals packet.");
4454 }
4455}
4456
4458 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4459 Status error;
4460
4461 if (type_name.empty()) {
4462 error = Status::FromErrorString("invalid type_name argument");
4463 return error;
4464 }
4465
4466 // Build command: Configure{type_name}: serialized config data.
4467 StreamGDBRemote stream;
4468 stream.PutCString("QConfigure");
4469 stream.PutCString(type_name);
4470 stream.PutChar(':');
4471 if (config_sp) {
4472 // Gather the plain-text version of the configuration data.
4473 StreamString unescaped_stream;
4474 config_sp->Dump(unescaped_stream);
4475 unescaped_stream.Flush();
4476
4477 // Add it to the stream in escaped fashion.
4478 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4479 unescaped_stream.GetSize());
4480 }
4481 stream.Flush();
4482
4483 // Send the packet.
4484 StringExtractorGDBRemote response;
4485 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4486 if (result == PacketResult::Success) {
4487 // We failed if the config result comes back other than OK.
4488 if (response.GetStringRef() == "OK") {
4489 // Okay!
4490 error.Clear();
4491 } else {
4493 "configuring StructuredData feature {0} failed with error {1}",
4494 type_name, response.GetStringRef());
4495 }
4496 } else {
4497 // Can we get more data here on the failure?
4499 "configuring StructuredData feature {0} failed when sending packet: "
4500 "PacketResult={1}",
4501 type_name, (int)result);
4502 }
4503 return error;
4504}
4505
4510
4515 return true;
4516
4517 // If the remote didn't indicate native-signal support explicitly,
4518 // check whether it is an old version of lldb-server.
4519 return GetThreadSuffixSupported();
4520}
4521
4523 StringExtractorGDBRemote response;
4524 GDBRemoteCommunication::ScopedTimeout timeout(*this, seconds(3));
4525
4526 // LLDB server typically sends no response for "k", so we shouldn't try
4527 // to sync on timeout.
4528 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout(), false) !=
4530 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4531 "failed to send k packet");
4532
4533 char packet_cmd = response.GetChar(0);
4534 if (packet_cmd == 'W' || packet_cmd == 'X')
4535 return response.GetHexU8();
4536
4537 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4538 "unexpected response to k packet: %s",
4539 response.GetStringRef().str().c_str());
4540}
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:453
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:545
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:949
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.
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:367
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
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:1254
const ArchSpec & GetArchitecture() const
Definition Target.h:1296
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)
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)
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...
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.
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