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
19#include "lldb/Host/HostInfo.h"
20#include "lldb/Host/SafeMachO.h"
21#include "lldb/Host/XML.h"
22#include "lldb/Symbol/Symbol.h"
24#include "lldb/Target/Target.h"
26#include "lldb/Utility/Args.h"
30#include "lldb/Utility/Log.h"
31#include "lldb/Utility/State.h"
33
34#include "ProcessGDBRemote.h"
35#include "ProcessGDBRemoteLog.h"
36#include "lldb/Host/Config.h"
38
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/StringSwitch.h"
41#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
42#include "llvm/Support/JSON.h"
43
44#if HAVE_LIBCOMPRESSION
45#include <compression.h>
46#endif
47
48using namespace lldb;
50using namespace lldb_private;
51using namespace std::chrono;
52
53llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os,
54 const QOffsets &offsets) {
55 return os << llvm::formatv(
56 "QOffsets({0}, [{1:@[x]}])", offsets.segments,
57 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end()));
58}
59
60// GDBRemoteCommunicationClient constructor
79
80// Destructor
85
88
89 // Start the read thread after we send the handshake ack since if we fail to
90 // send the handshake ack, there is no reason to continue...
91 std::chrono::steady_clock::time_point start_of_handshake =
92 std::chrono::steady_clock::now();
93 if (SendAck()) {
94 // The return value from QueryNoAckModeSupported() is true if the packet
95 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
96 // false if no response was received. This quickly tells us if we have a
97 // live connection to a remote GDB server...
99 return true;
100 } else {
101 std::chrono::steady_clock::time_point end_of_handshake =
102 std::chrono::steady_clock::now();
103 auto handshake_timeout =
104 std::chrono::duration<double>(end_of_handshake - start_of_handshake)
105 .count();
106 if (error_ptr) {
107 if (!IsConnected())
108 *error_ptr =
109 Status::FromErrorString("Connection shut down by remote side "
110 "while waiting for reply to initial "
111 "handshake packet");
112 else
114 "failed to get reply to handshake packet within timeout of "
115 "%.1f seconds",
116 handshake_timeout);
117 }
118 }
119 } else {
120 if (error_ptr)
121 *error_ptr = Status::FromErrorString("failed to send the handshake ack");
122 }
123 return false;
124}
125
132
139
146
153
160
167
174
181
188
194
201
207
213
219
222 m_send_acks = true;
224
225 // This is the first real packet that we'll send in a debug session and it
226 // may take a little longer than normal to receive a reply. Wait at least
227 // 6 seconds for a reply to this packet.
228
229 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
230
232 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) ==
234 if (response.IsOKResponse()) {
235 m_send_acks = false;
237 }
238 return true;
239 }
240 }
241 return false;
242}
243
256
270
284
286 if (!did_exec) {
287 // Hard reset everything, this is when we first connect to a GDB server
315 m_x_packet_state.reset();
323 m_supports_z0 = true;
324 m_supports_z1 = true;
325 m_supports_z2 = true;
326 m_supports_z3 = true;
327 m_supports_z4 = true;
330 m_supports_qSymbol = true;
333 m_host_arch.Clear();
335 m_os_version = llvm::VersionTuple();
336 m_os_build.clear();
337 m_os_kernel.clear();
338 m_hostname.clear();
339 m_gdb_server_name.clear();
341 m_default_packet_timeout = seconds(0);
344 m_qSupported_response.clear();
349 }
350
351 // These flags should be reset when we first connect to a GDB server and when
352 // our inferior process execs
354 m_process_arch.Clear();
355}
356
358 // Clear out any capabilities we expect to see in the qSupported response
372 m_x_packet_state.reset();
376
377 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
378 // not, we assume no limit
379
380 // build the qSupported packet
381 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc",
382 "multiprocess+",
383 "fork-events+",
384 "vfork-events+",
385 "swbreak+",
386 "hwbreak+"};
387 StreamString packet;
388 packet.PutCString("qSupported");
389 for (uint32_t i = 0; i < features.size(); ++i) {
390 packet.PutCString(i == 0 ? ":" : ";");
391 packet.PutCString(features[i]);
392 }
393
395 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
397 // Hang on to the qSupported packet, so that platforms can do custom
398 // configuration of the transport before attaching/launching the process.
399 m_qSupported_response = response.GetStringRef().str();
400
401 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) {
402 if (x == "qXfer:auxv:read+")
404 else if (x == "qXfer:libraries-svr4:read+")
406 else if (x == "augmented-libraries-svr4-read") {
409 } else if (x == "qXfer:libraries:read+")
411 else if (x == "qXfer:features:read+")
413 else if (x == "qXfer:memory-map:read+")
415 else if (x == "qXfer:siginfo:read+")
417 else if (x == "qEcho+")
419 else if (x == "QPassSignals+")
421 else if (x == "multiprocess+")
423 else if (x == "memory-tagging+")
425 else if (x == "qSaveCore+")
427 else if (x == "native-signals+")
429 else if (x == "binary-upload+")
431 else if (x == "ReverseContinue+")
433 else if (x == "ReverseStep+")
435 else if (x == "MultiMemRead+")
437 // Look for a list of compressions in the features list e.g.
438 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
439 // deflate,lzma
440 else if (x.consume_front("SupportedCompressions=")) {
441 llvm::SmallVector<llvm::StringRef, 4> compressions;
442 x.split(compressions, ',');
443 if (!compressions.empty())
444 MaybeEnableCompression(compressions);
445 } else if (x.consume_front("SupportedWatchpointTypes=")) {
446 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types;
447 x.split(watchpoint_types, ',');
448 m_watchpoint_types = eWatchpointHardwareFeatureUnknown;
449 for (auto wp_type : watchpoint_types) {
450 if (wp_type == "x86_64")
451 m_watchpoint_types |= eWatchpointHardwareX86;
452 if (wp_type == "aarch64-mask")
453 m_watchpoint_types |= eWatchpointHardwareArmMASK;
454 if (wp_type == "aarch64-bas")
455 m_watchpoint_types |= eWatchpointHardwareArmBAS;
456 }
457 } else if (x.consume_front("PacketSize=")) {
458 StringExtractorGDBRemote packet_response(x);
460 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
461 if (m_max_packet_size == 0) {
462 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
464 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
465 }
466 }
467 }
468 }
469}
470
483
485 assert(!flavor.empty());
494 if (SendPacketAndWaitForResponse("vCont?", response) ==
496 for (llvm::StringRef token : llvm::split(response.GetStringRef(), ';')) {
497 if (token == "c")
499 if (token == "C")
501 if (token == "s")
503 if (token == "S")
505 }
506
512 }
513
519 }
520 }
521 }
522
523 return llvm::StringSwitch<bool>(flavor)
524 .Case("a", m_supports_vCont_any)
525 .Case("A", m_supports_vCont_all)
526 .Case("c", m_supports_vCont_c)
527 .Case("C", m_supports_vCont_C)
528 .Case("s", m_supports_vCont_s)
529 .Case("S", m_supports_vCont_S)
530 .Default(false);
531}
532
535 lldb::tid_t tid, StreamString &&payload,
536 StringExtractorGDBRemote &response) {
537 Lock lock(*this);
538 if (!lock) {
540 LLDB_LOGF(log,
541 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
542 "for %s packet.",
543 __FUNCTION__, payload.GetData());
545 }
546
548 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
549 else {
550 if (!SetCurrentThread(tid))
552 }
553
554 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
555}
556
557// Check if the target supports 'p' packet. It sends out a 'p' packet and
558// checks the response. A normal packet will tell us that support is available.
559//
560// Takes a valid thread ID because p needs to apply to a thread.
566
568 lldb::tid_t tid, llvm::StringRef packetStr) {
569 StreamString payload;
570 payload.PutCString(packetStr);
573 tid, std::move(payload), response) == PacketResult::Success &&
574 response.IsNormalResponse()) {
575 return eLazyBoolYes;
576 }
577 return eLazyBoolNo;
578}
579
583
585 // Get information on all threads at one using the "jThreadsInfo" packet
586 StructuredData::ObjectSP object_sp;
587
591 if (SendPacketAndWaitForResponse("jThreadsInfo", response) ==
593 if (response.IsUnsupportedResponse()) {
595 } else if (!response.Empty()) {
596 object_sp = StructuredData::ParseJSON(response.GetStringRef());
597 }
598 }
599 }
600 return object_sp;
601}
602
616
620 // We try to enable error strings in remote packets but if we fail, we just
621 // work in the older way.
623 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) ==
625 if (response.IsOKResponse()) {
627 }
628 }
629 }
630}
631
645
659
672
679
681 size_t len,
682 int32_t type) {
683 StreamString packet;
684 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type);
686
687 Log *log = GetLog(GDBRLog::Memory);
688
689 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
691 !response.IsNormalResponse()) {
692 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed",
693 __FUNCTION__);
694 return nullptr;
695 }
696
697 // We are expecting
698 // m<hex encoded bytes>
699
700 if (response.GetChar() != 'm') {
701 LLDB_LOGF(log,
702 "GDBRemoteCommunicationClient::%s: qMemTags response did not "
703 "begin with \"m\"",
704 __FUNCTION__);
705 return nullptr;
706 }
707
708 size_t expected_bytes = response.GetBytesLeft() / 2;
709 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0));
710 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData());
711 // Check both because in some situations chars are consumed even
712 // if the decoding fails.
713 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) {
714 LLDB_LOGF(
715 log,
716 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response",
717 __FUNCTION__);
718 return nullptr;
719 }
720
721 return buffer_sp;
722}
723
725 lldb::addr_t addr, size_t len, int32_t type,
726 const std::vector<uint8_t> &tags) {
727 // Format QMemTags:address,length:type:tags
728 StreamString packet;
729 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type);
730 packet.PutBytesAsRawHex8(tags.data(), tags.size());
731
732 Status status;
734 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
736 !response.IsOKResponse()) {
737 status = Status::FromErrorString("QMemTags packet failed");
738 }
739 return status;
740}
741
757
759 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
760 return m_curr_pid;
761
762 // First try to retrieve the pid via the qProcessInfo request.
763 GetCurrentProcessInfo(allow_lazy);
765 // We really got it.
766 return m_curr_pid;
767 } else {
768 // If we don't get a response for qProcessInfo, check if $qC gives us a
769 // result. $qC only returns a real process id on older debugserver and
770 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
771 // the thread id, which newer debugserver and lldb-gdbserver stubs return
772 // correctly.
775 if (response.GetChar() == 'Q') {
776 if (response.GetChar() == 'C') {
778 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID);
781 return m_curr_pid;
782 }
783 }
784 }
785 }
786
787 // If we don't get a response for $qC, check if $qfThreadID gives us a
788 // result.
790 bool sequence_mutex_unavailable;
791 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
792 if (!ids.empty() && !sequence_mutex_unavailable) {
793 // If server returned an explicit PID, use that.
794 m_curr_pid_run = m_curr_pid = ids.front().first;
795 // Otherwise, use the TID of the first thread (Linux hack).
797 m_curr_pid_run = m_curr_pid = ids.front().second;
799 return m_curr_pid;
800 }
801 }
802 }
803
805}
806
808 if (!args.GetArgumentAtIndex(0))
809 return llvm::createStringError(llvm::inconvertibleErrorCode(),
810 "Nothing to launch");
811 // try vRun first
812 if (m_supports_vRun) {
813 StreamString packet;
814 packet.PutCString("vRun");
815 for (const Args::ArgEntry &arg : args) {
816 packet.PutChar(';');
817 packet.PutStringAsRawHex8(arg.ref());
818 }
819
821 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
823 return llvm::createStringError(llvm::inconvertibleErrorCode(),
824 "Sending vRun packet failed");
825
826 if (response.IsErrorResponse())
827 return response.GetStatus().ToError();
828
829 // vRun replies with a stop reason packet
830 // FIXME: right now we just discard the packet and LLDB queries
831 // for stop reason again
832 if (!response.IsUnsupportedResponse())
833 return llvm::Error::success();
834
835 m_supports_vRun = false;
836 }
837
838 // fallback to A
839 StreamString packet;
840 packet.PutChar('A');
841 llvm::ListSeparator LS(",");
842 for (const auto &arg : llvm::enumerate(args)) {
843 packet << LS;
844 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index());
845 packet.PutStringAsRawHex8(arg.value().ref());
846 }
847
849 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
851 return llvm::createStringError(llvm::inconvertibleErrorCode(),
852 "Sending A packet failed");
853 }
854 if (!response.IsOKResponse())
855 return response.GetStatus().ToError();
856
857 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
859 return llvm::createStringError(llvm::inconvertibleErrorCode(),
860 "Sending qLaunchSuccess packet failed");
861 }
862 if (response.IsOKResponse())
863 return llvm::Error::success();
864 if (response.GetChar() == 'E') {
865 return llvm::createStringError(llvm::inconvertibleErrorCode(),
866 response.GetStringRef().substr(1));
867 }
868 return llvm::createStringError(llvm::inconvertibleErrorCode(),
869 "unknown error occurred launching process");
870}
871
873 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
874 for (const auto &kv : env)
875 vec.emplace_back(kv.first(), kv.second);
876 llvm::sort(vec, llvm::less_first());
877 for (const auto &[k, v] : vec) {
878 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
879 if (r != 0)
880 return r;
881 }
882 return 0;
883}
884
886 char const *name_equal_value) {
887 if (name_equal_value && name_equal_value[0]) {
888 bool send_hex_encoding = false;
889 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
890 ++p) {
891 if (llvm::isPrint(*p)) {
892 switch (*p) {
893 case '$':
894 case '#':
895 case '*':
896 case '}':
897 send_hex_encoding = true;
898 break;
899 default:
900 break;
901 }
902 } else {
903 // We have non printable characters, lets hex encode this...
904 send_hex_encoding = true;
905 }
906 }
907
909 // Prefer sending unencoded, if possible and the server supports it.
910 if (!send_hex_encoding && m_supports_QEnvironment) {
911 StreamString packet;
912 packet.Printf("QEnvironment:%s", name_equal_value);
913 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
915 return -1;
916
917 if (response.IsOKResponse())
918 return 0;
919 if (response.IsUnsupportedResponse())
921 else {
922 uint8_t error = response.GetError();
923 if (error)
924 return error;
925 return -1;
926 }
927 }
928
930 StreamString packet;
931 packet.PutCString("QEnvironmentHexEncoded:");
932 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
933 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
935 return -1;
936
937 if (response.IsOKResponse())
938 return 0;
939 if (response.IsUnsupportedResponse())
941 else {
942 uint8_t error = response.GetError();
943 if (error)
944 return error;
945 return -1;
946 }
947 }
948 }
949 return -1;
950}
951
953 if (arch && arch[0]) {
954 StreamString packet;
955 packet.Printf("QLaunchArch:%s", arch);
957 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
959 if (response.IsOKResponse())
960 return 0;
961 uint8_t error = response.GetError();
962 if (error)
963 return error;
964 }
965 }
966 return -1;
967}
968
970 char const *data, bool *was_supported) {
971 if (data && *data != '\0') {
972 StreamString packet;
973 packet.Printf("QSetProcessEvent:%s", data);
975 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
977 if (response.IsOKResponse()) {
978 if (was_supported)
979 *was_supported = true;
980 return 0;
981 } else if (response.IsUnsupportedResponse()) {
982 if (was_supported)
983 *was_supported = false;
984 return -1;
985 } else {
986 uint8_t error = response.GetError();
987 if (was_supported)
988 *was_supported = true;
989 if (error)
990 return error;
991 }
992 }
993 }
994 return -1;
995}
996
998 GetHostInfo();
999 return m_os_version;
1000}
1001
1006
1008 if (GetHostInfo()) {
1009 if (!m_os_build.empty())
1010 return m_os_build;
1011 }
1012 return std::nullopt;
1013}
1014
1015std::optional<std::string>
1017 if (GetHostInfo()) {
1018 if (!m_os_kernel.empty())
1019 return m_os_kernel;
1020 }
1021 return std::nullopt;
1022}
1023
1025 if (GetHostInfo()) {
1026 if (!m_hostname.empty()) {
1027 s = m_hostname;
1028 return true;
1029 }
1030 }
1031 s.clear();
1032 return false;
1033}
1034
1040
1047
1049 UUID &uuid, addr_t &value, bool &value_is_offset) {
1052
1053 // Return true if we have a UUID or an address/offset of the
1054 // main standalone / firmware binary being used.
1055 if (!m_process_standalone_uuid.IsValid() &&
1057 return false;
1058
1061 value_is_offset = m_process_standalone_value_is_offset;
1062 return true;
1063}
1064
1065std::vector<addr_t>
1071
1074 m_gdb_server_name.clear();
1077
1078 StringExtractorGDBRemote response;
1079 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1081 if (response.IsNormalResponse()) {
1082 llvm::StringRef name, value;
1083 bool success = false;
1084 while (response.GetNameColonValue(name, value)) {
1085 if (name == "name") {
1086 success = true;
1087 m_gdb_server_name = std::string(value);
1088 } else if (name == "version") {
1089 llvm::StringRef major, minor;
1090 std::tie(major, minor) = value.split('.');
1091 if (!major.getAsInteger(0, m_gdb_server_version))
1092 success = true;
1093 }
1094 }
1095 if (success)
1097 }
1098 }
1099 }
1101}
1102
1104 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1106 llvm::StringRef avail_name;
1107
1108#if HAVE_LIBCOMPRESSION
1109 if (avail_type == CompressionType::None) {
1110 for (auto compression : supported_compressions) {
1111 if (compression == "lzfse") {
1112 avail_type = CompressionType::LZFSE;
1113 avail_name = compression;
1114 break;
1115 }
1116 }
1117 }
1118 if (avail_type == CompressionType::None) {
1119 for (auto compression : supported_compressions) {
1120 if (compression == "zlib-deflate") {
1121 avail_type = CompressionType::ZlibDeflate;
1122 avail_name = compression;
1123 break;
1124 }
1125 }
1126 }
1127#endif
1128
1129#if LLVM_ENABLE_ZLIB
1130 if (avail_type == CompressionType::None) {
1131 for (auto compression : supported_compressions) {
1132 if (compression == "zlib-deflate") {
1133 avail_type = CompressionType::ZlibDeflate;
1134 avail_name = compression;
1135 break;
1136 }
1137 }
1138 }
1139#endif
1140
1141#if HAVE_LIBCOMPRESSION
1142 if (avail_type == CompressionType::None) {
1143 for (auto compression : supported_compressions) {
1144 if (compression == "lz4") {
1145 avail_type = CompressionType::LZ4;
1146 avail_name = compression;
1147 break;
1148 }
1149 }
1150 }
1151 if (avail_type == CompressionType::None) {
1152 for (auto compression : supported_compressions) {
1153 if (compression == "lzma") {
1154 avail_type = CompressionType::LZMA;
1155 avail_name = compression;
1156 break;
1157 }
1158 }
1159 }
1160#endif
1161
1162 if (avail_type != CompressionType::None) {
1163 StringExtractorGDBRemote response;
1164 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1165 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1166 return;
1167
1168 if (response.IsOKResponse()) {
1169 m_compression_type = avail_type;
1170 }
1171 }
1172}
1173
1175 if (GetGDBServerVersion()) {
1176 if (!m_gdb_server_name.empty())
1177 return m_gdb_server_name.c_str();
1178 }
1179 return nullptr;
1180}
1181
1187
1189 StringExtractorGDBRemote response;
1191 return false;
1192
1193 if (!response.IsNormalResponse())
1194 return false;
1195
1196 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1197 auto pid_tid = response.GetPidTid(0);
1198 if (!pid_tid)
1199 return false;
1200
1201 lldb::pid_t pid = pid_tid->first;
1202 // invalid
1204 return false;
1205
1206 // if we get pid as well, update m_curr_pid
1207 if (pid != 0) {
1208 m_curr_pid_run = m_curr_pid = pid;
1210 }
1211 tid = pid_tid->second;
1212 }
1213
1214 return true;
1215}
1216
1217static void ParseOSType(llvm::StringRef value, std::string &os_name,
1218 std::string &environment) {
1219 if (value == "iossimulator" || value == "tvossimulator" ||
1220 value == "watchossimulator" || value == "xrossimulator" ||
1221 value == "visionossimulator") {
1222 environment = "simulator";
1223 os_name = value.drop_back(environment.size()).str();
1224 } else if (value == "maccatalyst") {
1225 os_name = "ios";
1226 environment = "macabi";
1227 } else {
1228 os_name = value.str();
1229 }
1230}
1231
1233 Log *log = GetLog(GDBRLog::Process);
1234
1235 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1236 // host info computation can require DNS traffic and shelling out to external processes.
1237 // Increase the timeout to account for that.
1238 ScopedTimeout timeout(*this, seconds(10));
1240 StringExtractorGDBRemote response;
1241 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1243 if (response.IsNormalResponse()) {
1244 llvm::StringRef name;
1245 llvm::StringRef value;
1246 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1247 uint32_t sub = 0;
1248 std::string arch_name;
1249 std::string os_name;
1250 std::string environment;
1251 std::string vendor_name;
1252 std::string triple;
1253 uint32_t pointer_byte_size = 0;
1254 ByteOrder byte_order = eByteOrderInvalid;
1255 uint32_t num_keys_decoded = 0;
1256 while (response.GetNameColonValue(name, value)) {
1257 if (name == "cputype") {
1258 // exception type in big endian hex
1259 if (!value.getAsInteger(0, cpu))
1260 ++num_keys_decoded;
1261 } else if (name == "cpusubtype") {
1262 // exception count in big endian hex
1263 if (!value.getAsInteger(0, sub))
1264 ++num_keys_decoded;
1265 } else if (name == "arch") {
1266 arch_name = std::string(value);
1267 ++num_keys_decoded;
1268 } else if (name == "triple") {
1269 StringExtractor extractor(value);
1270 extractor.GetHexByteString(triple);
1271 ++num_keys_decoded;
1272 } else if (name == "distribution_id") {
1273 StringExtractor extractor(value);
1275 ++num_keys_decoded;
1276 } else if (name == "os_build") {
1277 StringExtractor extractor(value);
1278 extractor.GetHexByteString(m_os_build);
1279 ++num_keys_decoded;
1280 } else if (name == "hostname") {
1281 StringExtractor extractor(value);
1282 extractor.GetHexByteString(m_hostname);
1283 ++num_keys_decoded;
1284 } else if (name == "os_kernel") {
1285 StringExtractor extractor(value);
1286 extractor.GetHexByteString(m_os_kernel);
1287 ++num_keys_decoded;
1288 } else if (name == "ostype") {
1289 ParseOSType(value, os_name, environment);
1290 ++num_keys_decoded;
1291 } else if (name == "vendor") {
1292 vendor_name = std::string(value);
1293 ++num_keys_decoded;
1294 } else if (name == "endian") {
1295 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1296 .Case("little", eByteOrderLittle)
1297 .Case("big", eByteOrderBig)
1298 .Case("pdp", eByteOrderPDP)
1299 .Default(eByteOrderInvalid);
1300 if (byte_order != eByteOrderInvalid)
1301 ++num_keys_decoded;
1302 } else if (name == "ptrsize") {
1303 if (!value.getAsInteger(0, pointer_byte_size))
1304 ++num_keys_decoded;
1305 } else if (name == "addressing_bits") {
1306 if (!value.getAsInteger(0, m_low_mem_addressing_bits)) {
1307 ++num_keys_decoded;
1308 }
1309 } else if (name == "high_mem_addressing_bits") {
1310 if (!value.getAsInteger(0, m_high_mem_addressing_bits))
1311 ++num_keys_decoded;
1312 } else if (name == "low_mem_addressing_bits") {
1313 if (!value.getAsInteger(0, m_low_mem_addressing_bits))
1314 ++num_keys_decoded;
1315 } else if (name == "os_version" ||
1316 name == "version") // Older debugserver binaries used
1317 // the "version" key instead of
1318 // "os_version"...
1319 {
1320 if (!m_os_version.tryParse(value))
1321 ++num_keys_decoded;
1322 } else if (name == "maccatalyst_version") {
1323 if (!m_maccatalyst_version.tryParse(value))
1324 ++num_keys_decoded;
1325 } else if (name == "watchpoint_exceptions_received") {
1327 llvm::StringSwitch<LazyBool>(value)
1328 .Case("before", eLazyBoolNo)
1329 .Case("after", eLazyBoolYes)
1330 .Default(eLazyBoolCalculate);
1332 ++num_keys_decoded;
1333 } else if (name == "default_packet_timeout") {
1334 uint32_t timeout_seconds;
1335 if (!value.getAsInteger(0, timeout_seconds)) {
1336 m_default_packet_timeout = seconds(timeout_seconds);
1338 ++num_keys_decoded;
1339 }
1340 } else if (name == "vm-page-size") {
1341 int page_size;
1342 if (!value.getAsInteger(0, page_size)) {
1343 m_target_vm_page_size = page_size;
1344 ++num_keys_decoded;
1345 }
1346 }
1347 }
1348
1349 if (num_keys_decoded > 0)
1351
1352 if (triple.empty()) {
1353 if (arch_name.empty()) {
1354 if (cpu != LLDB_INVALID_CPUTYPE) {
1355 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1356 if (pointer_byte_size) {
1357 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1358 }
1359 if (byte_order != eByteOrderInvalid) {
1360 assert(byte_order == m_host_arch.GetByteOrder());
1361 }
1362
1363 if (!vendor_name.empty())
1364 m_host_arch.GetTriple().setVendorName(
1365 llvm::StringRef(vendor_name));
1366 if (!os_name.empty())
1367 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1368 if (!environment.empty())
1369 m_host_arch.GetTriple().setEnvironmentName(environment);
1370 }
1371 } else {
1372 std::string triple;
1373 triple += arch_name;
1374 if (!vendor_name.empty() || !os_name.empty()) {
1375 triple += '-';
1376 if (vendor_name.empty())
1377 triple += "unknown";
1378 else
1379 triple += vendor_name;
1380 triple += '-';
1381 if (os_name.empty())
1382 triple += "unknown";
1383 else
1384 triple += os_name;
1385 }
1386 m_host_arch.SetTriple(triple.c_str());
1387
1388 llvm::Triple &host_triple = m_host_arch.GetTriple();
1389 if (host_triple.getVendor() == llvm::Triple::Apple &&
1390 host_triple.getOS() == llvm::Triple::Darwin) {
1391 switch (m_host_arch.GetMachine()) {
1392 case llvm::Triple::aarch64:
1393 case llvm::Triple::aarch64_32:
1394 case llvm::Triple::arm:
1395 case llvm::Triple::thumb:
1396 host_triple.setOS(llvm::Triple::IOS);
1397 break;
1398 default:
1399 host_triple.setOS(llvm::Triple::MacOSX);
1400 break;
1401 }
1402 }
1403 if (pointer_byte_size) {
1404 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1405 }
1406 if (byte_order != eByteOrderInvalid) {
1407 assert(byte_order == m_host_arch.GetByteOrder());
1408 }
1409 }
1410 } else {
1411 m_host_arch.SetTriple(triple.c_str());
1412 if (pointer_byte_size) {
1413 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1414 }
1415 if (byte_order != eByteOrderInvalid) {
1416 assert(byte_order == m_host_arch.GetByteOrder());
1417 }
1418
1419 LLDB_LOGF(log,
1420 "GDBRemoteCommunicationClient::%s parsed host "
1421 "architecture as %s, triple as %s from triple text %s",
1422 __FUNCTION__,
1423 m_host_arch.GetArchitectureName()
1424 ? m_host_arch.GetArchitectureName()
1425 : "<null-arch-name>",
1426 m_host_arch.GetTriple().getTriple().c_str(),
1427 triple.c_str());
1428 }
1429 }
1430 }
1431 }
1433}
1434
1436 size_t data_len) {
1437 StreamString packet;
1438 packet.PutCString("I");
1439 packet.PutBytesAsRawHex8(data, data_len);
1440 StringExtractorGDBRemote response;
1441 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1443 return 0;
1444 }
1445 return response.GetError();
1446}
1447
1454
1467
1473
1475 uint32_t permissions) {
1478 char packet[64];
1479 const int packet_len = ::snprintf(
1480 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1481 permissions & lldb::ePermissionsReadable ? "r" : "",
1482 permissions & lldb::ePermissionsWritable ? "w" : "",
1483 permissions & lldb::ePermissionsExecutable ? "x" : "");
1484 assert(packet_len < (int)sizeof(packet));
1485 UNUSED_IF_ASSERT_DISABLED(packet_len);
1486 StringExtractorGDBRemote response;
1487 if (SendPacketAndWaitForResponse(packet, response) ==
1489 if (response.IsUnsupportedResponse())
1491 else if (!response.IsErrorResponse())
1492 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1493 } else {
1495 }
1496 }
1497 return LLDB_INVALID_ADDRESS;
1498}
1499
1503 char packet[64];
1504 const int packet_len =
1505 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1506 assert(packet_len < (int)sizeof(packet));
1507 UNUSED_IF_ASSERT_DISABLED(packet_len);
1508 StringExtractorGDBRemote response;
1509 if (SendPacketAndWaitForResponse(packet, response) ==
1511 if (response.IsUnsupportedResponse())
1513 else if (response.IsOKResponse())
1514 return true;
1515 } else {
1517 }
1518 }
1519 return false;
1520}
1521
1523 lldb::pid_t pid) {
1524 Status error;
1526
1527 packet.PutChar('D');
1528 if (keep_stopped) {
1530 char packet[64];
1531 const int packet_len =
1532 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1533 assert(packet_len < (int)sizeof(packet));
1534 UNUSED_IF_ASSERT_DISABLED(packet_len);
1535 StringExtractorGDBRemote response;
1536 if (SendPacketAndWaitForResponse(packet, response) ==
1538 response.IsOKResponse()) {
1540 } else {
1542 }
1543 }
1544
1547 "Stays stopped not supported by this target.");
1548 return error;
1549 } else {
1550 packet.PutChar('1');
1551 }
1552 }
1553
1555 // Some servers (e.g. qemu) require specifying the PID even if only a single
1556 // process is running.
1557 if (pid == LLDB_INVALID_PROCESS_ID)
1558 pid = GetCurrentProcessID();
1559 packet.PutChar(';');
1560 packet.PutHex64(pid);
1561 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1563 "Multiprocess extension not supported by the server.");
1564 return error;
1565 }
1566
1567 StringExtractorGDBRemote response;
1568 PacketResult packet_result =
1569 SendPacketAndWaitForResponse(packet.GetString(), response);
1570 if (packet_result != PacketResult::Success)
1571 error = Status::FromErrorString("Sending disconnect packet failed.");
1572 return error;
1573}
1574
1576 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1577 Status error;
1578 region_info.Clear();
1579
1582 char packet[64];
1583 const int packet_len = ::snprintf(
1584 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1585 assert(packet_len < (int)sizeof(packet));
1586 UNUSED_IF_ASSERT_DISABLED(packet_len);
1587 StringExtractorGDBRemote response;
1588 if (SendPacketAndWaitForResponse(packet, response) ==
1591 llvm::StringRef name;
1592 llvm::StringRef value;
1593 addr_t addr_value = LLDB_INVALID_ADDRESS;
1594 bool success = true;
1595 bool saw_permissions = false;
1596 while (success && response.GetNameColonValue(name, value)) {
1597 if (name == "start") {
1598 if (!value.getAsInteger(16, addr_value))
1599 region_info.GetRange().SetRangeBase(addr_value);
1600 } else if (name == "size") {
1601 if (!value.getAsInteger(16, addr_value)) {
1602 region_info.GetRange().SetByteSize(addr_value);
1603 if (region_info.GetRange().GetRangeEnd() <
1604 region_info.GetRange().GetRangeBase()) {
1605 // Range size overflowed, truncate it.
1607 }
1608 }
1609 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1610 saw_permissions = true;
1611 if (region_info.GetRange().Contains(addr)) {
1612 if (value.contains('r'))
1614 else
1616
1617 if (value.contains('w'))
1619 else
1621
1622 if (value.contains('x'))
1624 else
1626
1627 region_info.SetMapped(MemoryRegionInfo::eYes);
1628 } else {
1629 // The reported region does not contain this address -- we're
1630 // looking at an unmapped page
1634 region_info.SetMapped(MemoryRegionInfo::eNo);
1635 }
1636 } else if (name == "name") {
1637 StringExtractorGDBRemote name_extractor(value);
1638 std::string name;
1639 name_extractor.GetHexByteString(name);
1640 region_info.SetName(name.c_str());
1641 } else if (name == "flags") {
1644
1645 llvm::StringRef flags = value;
1646 llvm::StringRef flag;
1647 while (flags.size()) {
1648 flags = flags.ltrim();
1649 std::tie(flag, flags) = flags.split(' ');
1650 // To account for trailing whitespace
1651 if (flag.size()) {
1652 if (flag == "mt")
1654 else if (flag == "ss")
1656 }
1657 }
1658 } else if (name == "type") {
1659 for (llvm::StringRef entry : llvm::split(value, ',')) {
1660 if (entry == "stack")
1662 else if (entry == "heap")
1664 }
1665 } else if (name == "error") {
1666 StringExtractorGDBRemote error_extractor(value);
1667 std::string error_string;
1668 // Now convert the HEX bytes into a string value
1669 error_extractor.GetHexByteString(error_string);
1670 error = Status::FromErrorString(error_string.c_str());
1671 } else if (name == "dirty-pages") {
1672 std::vector<addr_t> dirty_page_list;
1673 for (llvm::StringRef x : llvm::split(value, ',')) {
1674 addr_t page;
1675 x.consume_front("0x");
1676 if (llvm::to_integer(x, page, 16))
1677 dirty_page_list.push_back(page);
1678 }
1679 region_info.SetDirtyPageList(dirty_page_list);
1680 }
1681 }
1682
1683 if (m_target_vm_page_size != 0)
1685
1686 if (region_info.GetRange().IsValid()) {
1687 // We got a valid address range back but no permissions -- which means
1688 // this is an unmapped page
1689 if (!saw_permissions) {
1693 region_info.SetMapped(MemoryRegionInfo::eNo);
1694 }
1695 } else {
1696 // We got an invalid address range back
1697 error = Status::FromErrorString("Server returned invalid range");
1698 }
1699 } else {
1701 }
1702 }
1703
1705 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1706 }
1707
1708 // Try qXfer:memory-map:read to get region information not included in
1709 // qMemoryRegionInfo
1710 MemoryRegionInfo qXfer_region_info;
1711 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1712
1713 if (error.Fail()) {
1714 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1715 // the qXfer result as a fallback
1716 if (qXfer_error.Success()) {
1717 region_info = qXfer_region_info;
1718 error.Clear();
1719 } else {
1720 region_info.Clear();
1721 }
1722 } else if (qXfer_error.Success()) {
1723 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1724 // both regions are the same range, update the result to include the flash-
1725 // memory information that is specific to the qXfer result.
1726 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1727 region_info.SetFlash(qXfer_region_info.GetFlash());
1728 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1729 }
1730 }
1731 return error;
1732}
1733
1735 lldb::addr_t addr, MemoryRegionInfo &region) {
1737 if (!error.Success())
1738 return error;
1739 for (const auto &map_region : m_qXfer_memory_map) {
1740 if (map_region.GetRange().Contains(addr)) {
1741 region = map_region;
1742 return error;
1743 }
1744 }
1745 error = Status::FromErrorString("Region not found");
1746 return error;
1747}
1748
1750
1751 Status error;
1752
1754 // Already loaded, return success
1755 return error;
1756
1757 if (!XMLDocument::XMLEnabled()) {
1758 error = Status::FromErrorString("XML is not supported");
1759 return error;
1760 }
1761
1763 error = Status::FromErrorString("Memory map is not supported");
1764 return error;
1765 }
1766
1767 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1768 if (!xml)
1769 return Status::FromError(xml.takeError());
1770
1771 XMLDocument xml_document;
1772
1773 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1774 error = Status::FromErrorString("Failed to parse memory map xml");
1775 return error;
1776 }
1777
1778 XMLNode map_node = xml_document.GetRootElement("memory-map");
1779 if (!map_node) {
1780 error = Status::FromErrorString("Invalid root node in memory map xml");
1781 return error;
1782 }
1783
1784 m_qXfer_memory_map.clear();
1785
1786 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1787 if (!memory_node.IsElement())
1788 return true;
1789 if (memory_node.GetName() != "memory")
1790 return true;
1791 auto type = memory_node.GetAttributeValue("type", "");
1792 uint64_t start;
1793 uint64_t length;
1794 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1795 return true;
1796 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1797 return true;
1798 MemoryRegionInfo region;
1799 region.GetRange().SetRangeBase(start);
1800 region.GetRange().SetByteSize(length);
1801 if (type == "rom") {
1803 this->m_qXfer_memory_map.push_back(region);
1804 } else if (type == "ram") {
1807 this->m_qXfer_memory_map.push_back(region);
1808 } else if (type == "flash") {
1810 memory_node.ForEachChildElement(
1811 [&region](const XMLNode &prop_node) -> bool {
1812 if (!prop_node.IsElement())
1813 return true;
1814 if (prop_node.GetName() != "property")
1815 return true;
1816 auto propname = prop_node.GetAttributeValue("name", "");
1817 if (propname == "blocksize") {
1818 uint64_t blocksize;
1819 if (prop_node.GetElementTextAsUnsigned(blocksize))
1820 region.SetBlocksize(blocksize);
1821 }
1822 return true;
1823 });
1824 this->m_qXfer_memory_map.push_back(region);
1825 }
1826 return true;
1827 });
1828
1830
1831 return error;
1832}
1833
1837 }
1838
1839 std::optional<uint32_t> num;
1841 StringExtractorGDBRemote response;
1842 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
1845 llvm::StringRef name;
1846 llvm::StringRef value;
1847 while (response.GetNameColonValue(name, value)) {
1848 if (name == "num") {
1849 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1851 }
1852 }
1853 if (!num) {
1855 }
1856 } else {
1858 }
1859 }
1860
1861 return num;
1862}
1863
1864WatchpointHardwareFeature
1868
1871 GetHostInfo();
1872
1873 // Process determines this by target CPU, but allow for the
1874 // remote stub to override it via the qHostInfo
1875 // watchpoint_exceptions_received key, if it is present.
1878 return false;
1880 return true;
1881 }
1882
1883 return std::nullopt;
1884}
1885
1887 if (file_spec) {
1888 std::string path{file_spec.GetPath(false)};
1889 StreamString packet;
1890 packet.PutCString("QSetSTDIN:");
1891 packet.PutStringAsRawHex8(path);
1892
1893 StringExtractorGDBRemote response;
1894 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1896 if (response.IsOKResponse())
1897 return 0;
1898 uint8_t error = response.GetError();
1899 if (error)
1900 return error;
1901 }
1902 }
1903 return -1;
1904}
1905
1907 if (file_spec) {
1908 std::string path{file_spec.GetPath(false)};
1909 StreamString packet;
1910 packet.PutCString("QSetSTDOUT:");
1911 packet.PutStringAsRawHex8(path);
1912
1913 StringExtractorGDBRemote response;
1914 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1916 if (response.IsOKResponse())
1917 return 0;
1918 uint8_t error = response.GetError();
1919 if (error)
1920 return error;
1921 }
1922 }
1923 return -1;
1924}
1925
1927 if (file_spec) {
1928 std::string path{file_spec.GetPath(false)};
1929 StreamString packet;
1930 packet.PutCString("QSetSTDERR:");
1931 packet.PutStringAsRawHex8(path);
1932
1933 StringExtractorGDBRemote response;
1934 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1936 if (response.IsOKResponse())
1937 return 0;
1938 uint8_t error = response.GetError();
1939 if (error)
1940 return error;
1941 }
1942 }
1943 return -1;
1944}
1945
1947 StringExtractorGDBRemote response;
1948 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
1950 if (response.IsUnsupportedResponse())
1951 return false;
1952 if (response.IsErrorResponse())
1953 return false;
1954 std::string cwd;
1955 response.GetHexByteString(cwd);
1956 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1957 return !cwd.empty();
1958 }
1959 return false;
1960}
1961
1963 if (working_dir) {
1964 std::string path{working_dir.GetPath(false)};
1965 StreamString packet;
1966 packet.PutCString("QSetWorkingDir:");
1967 packet.PutStringAsRawHex8(path);
1968
1969 StringExtractorGDBRemote response;
1970 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1972 if (response.IsOKResponse())
1973 return 0;
1974 uint8_t error = response.GetError();
1975 if (error)
1976 return error;
1977 }
1978 }
1979 return -1;
1980}
1981
1983 char packet[32];
1984 const int packet_len =
1985 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1986 assert(packet_len < (int)sizeof(packet));
1987 UNUSED_IF_ASSERT_DISABLED(packet_len);
1988 StringExtractorGDBRemote response;
1989 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
1990 if (response.IsOKResponse())
1991 return 0;
1992 uint8_t error = response.GetError();
1993 if (error)
1994 return error;
1995 }
1996 return -1;
1997}
1998
2000 char packet[32];
2001 const int packet_len = ::snprintf(packet, sizeof(packet),
2002 "QSetDetachOnError:%i", enable ? 1 : 0);
2003 assert(packet_len < (int)sizeof(packet));
2004 UNUSED_IF_ASSERT_DISABLED(packet_len);
2005 StringExtractorGDBRemote response;
2006 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2007 if (response.IsOKResponse())
2008 return 0;
2009 uint8_t error = response.GetError();
2010 if (error)
2011 return error;
2012 }
2013 return -1;
2014}
2015
2017 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2018 if (response.IsNormalResponse()) {
2019 llvm::StringRef name;
2020 llvm::StringRef value;
2021 StringExtractor extractor;
2022
2023 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2024 uint32_t sub = 0;
2025 std::string vendor;
2026 std::string os_type;
2027
2028 while (response.GetNameColonValue(name, value)) {
2029 if (name == "pid") {
2031 value.getAsInteger(0, pid);
2032 process_info.SetProcessID(pid);
2033 } else if (name == "ppid") {
2035 value.getAsInteger(0, pid);
2036 process_info.SetParentProcessID(pid);
2037 } else if (name == "uid") {
2038 uint32_t uid = UINT32_MAX;
2039 value.getAsInteger(0, uid);
2040 process_info.SetUserID(uid);
2041 } else if (name == "euid") {
2042 uint32_t uid = UINT32_MAX;
2043 value.getAsInteger(0, uid);
2044 process_info.SetEffectiveUserID(uid);
2045 } else if (name == "gid") {
2046 uint32_t gid = UINT32_MAX;
2047 value.getAsInteger(0, gid);
2048 process_info.SetGroupID(gid);
2049 } else if (name == "egid") {
2050 uint32_t gid = UINT32_MAX;
2051 value.getAsInteger(0, gid);
2052 process_info.SetEffectiveGroupID(gid);
2053 } else if (name == "triple") {
2054 StringExtractor extractor(value);
2055 std::string triple;
2056 extractor.GetHexByteString(triple);
2057 process_info.GetArchitecture().SetTriple(triple.c_str());
2058 } else if (name == "name") {
2059 StringExtractor extractor(value);
2060 // The process name from ASCII hex bytes since we can't control the
2061 // characters in a process name
2062 std::string name;
2063 extractor.GetHexByteString(name);
2064 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2065 } else if (name == "args") {
2066 llvm::StringRef encoded_args(value), hex_arg;
2067
2068 bool is_arg0 = true;
2069 while (!encoded_args.empty()) {
2070 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2071 std::string arg;
2072 StringExtractor extractor(hex_arg);
2073 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2074 // In case of wrong encoding, we discard all the arguments
2075 process_info.GetArguments().Clear();
2076 process_info.SetArg0("");
2077 break;
2078 }
2079 if (is_arg0)
2080 process_info.SetArg0(arg);
2081 else
2082 process_info.GetArguments().AppendArgument(arg);
2083 is_arg0 = false;
2084 }
2085 } else if (name == "cputype") {
2086 value.getAsInteger(0, cpu);
2087 } else if (name == "cpusubtype") {
2088 value.getAsInteger(0, sub);
2089 } else if (name == "vendor") {
2090 vendor = std::string(value);
2091 } else if (name == "ostype") {
2092 os_type = std::string(value);
2093 }
2094 }
2095
2096 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2097 if (vendor == "apple") {
2099 sub);
2100 process_info.GetArchitecture().GetTriple().setVendorName(
2101 llvm::StringRef(vendor));
2102 process_info.GetArchitecture().GetTriple().setOSName(
2103 llvm::StringRef(os_type));
2104 }
2105 }
2106
2107 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2108 return true;
2109 }
2110 return false;
2111}
2112
2114 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2115 process_info.Clear();
2116
2118 char packet[32];
2119 const int packet_len =
2120 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2121 assert(packet_len < (int)sizeof(packet));
2122 UNUSED_IF_ASSERT_DISABLED(packet_len);
2123 StringExtractorGDBRemote response;
2124 if (SendPacketAndWaitForResponse(packet, response) ==
2126 return DecodeProcessInfoResponse(response, process_info);
2127 } else {
2129 return false;
2130 }
2131 }
2132 return false;
2133}
2134
2137
2138 if (allow_lazy) {
2140 return true;
2142 return false;
2143 }
2144
2145 GetHostInfo();
2146
2147 StringExtractorGDBRemote response;
2148 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2150 if (response.IsNormalResponse()) {
2151 llvm::StringRef name;
2152 llvm::StringRef value;
2153 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2154 uint32_t sub = 0;
2155 std::string os_name;
2156 std::string environment;
2157 std::string vendor_name;
2158 std::string triple;
2159 std::string elf_abi;
2160 uint32_t pointer_byte_size = 0;
2161 StringExtractor extractor;
2162 ByteOrder byte_order = eByteOrderInvalid;
2163 uint32_t num_keys_decoded = 0;
2165 while (response.GetNameColonValue(name, value)) {
2166 if (name == "cputype") {
2167 if (!value.getAsInteger(16, cpu))
2168 ++num_keys_decoded;
2169 } else if (name == "cpusubtype") {
2170 if (!value.getAsInteger(16, sub)) {
2171 ++num_keys_decoded;
2172 // Workaround for pre-2024 Apple debugserver, which always
2173 // returns arm64e on arm64e-capable hardware regardless of
2174 // what the process is. This can be deleted at some point
2175 // in the future.
2176 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2177 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2178 if (GetGDBServerVersion())
2179 if (m_gdb_server_version >= 1000 &&
2180 m_gdb_server_version <= 1504)
2181 sub = 0;
2182 }
2183 }
2184 } else if (name == "triple") {
2185 StringExtractor extractor(value);
2186 extractor.GetHexByteString(triple);
2187 ++num_keys_decoded;
2188 } else if (name == "ostype") {
2189 ParseOSType(value, os_name, environment);
2190 ++num_keys_decoded;
2191 } else if (name == "vendor") {
2192 vendor_name = std::string(value);
2193 ++num_keys_decoded;
2194 } else if (name == "endian") {
2195 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2196 .Case("little", eByteOrderLittle)
2197 .Case("big", eByteOrderBig)
2198 .Case("pdp", eByteOrderPDP)
2199 .Default(eByteOrderInvalid);
2200 if (byte_order != eByteOrderInvalid)
2201 ++num_keys_decoded;
2202 } else if (name == "ptrsize") {
2203 if (!value.getAsInteger(16, pointer_byte_size))
2204 ++num_keys_decoded;
2205 } else if (name == "pid") {
2206 if (!value.getAsInteger(16, pid))
2207 ++num_keys_decoded;
2208 } else if (name == "elf_abi") {
2209 elf_abi = std::string(value);
2210 ++num_keys_decoded;
2211 } else if (name == "main-binary-uuid") {
2212 m_process_standalone_uuid.SetFromStringRef(value);
2213 ++num_keys_decoded;
2214 } else if (name == "main-binary-slide") {
2215 StringExtractor extractor(value);
2217 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2220 ++num_keys_decoded;
2221 }
2222 } else if (name == "main-binary-address") {
2223 StringExtractor extractor(value);
2225 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2228 ++num_keys_decoded;
2229 }
2230 } else if (name == "binary-addresses") {
2231 m_binary_addresses.clear();
2232 ++num_keys_decoded;
2233 for (llvm::StringRef x : llvm::split(value, ',')) {
2234 addr_t vmaddr;
2235 x.consume_front("0x");
2236 if (llvm::to_integer(x, vmaddr, 16))
2237 m_binary_addresses.push_back(vmaddr);
2238 }
2239 }
2240 }
2241 if (num_keys_decoded > 0)
2243 if (pid != LLDB_INVALID_PROCESS_ID) {
2245 m_curr_pid_run = m_curr_pid = pid;
2246 }
2247
2248 // Set the ArchSpec from the triple if we have it.
2249 if (!triple.empty()) {
2250 m_process_arch.SetTriple(triple.c_str());
2251 m_process_arch.SetFlags(elf_abi);
2252 if (pointer_byte_size) {
2253 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2254 }
2255 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2256 !vendor_name.empty()) {
2257 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2258 if (!environment.empty())
2259 triple.setEnvironmentName(environment);
2260
2261 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2262 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2263 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2264 switch (triple.getObjectFormat()) {
2265 case llvm::Triple::MachO:
2266 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2267 break;
2268 case llvm::Triple::ELF:
2269 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2270 break;
2271 case llvm::Triple::COFF:
2272 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2273 break;
2274 case llvm::Triple::GOFF:
2275 case llvm::Triple::SPIRV:
2276 case llvm::Triple::Wasm:
2277 case llvm::Triple::XCOFF:
2278 case llvm::Triple::DXContainer:
2279 LLDB_LOGF(log, "error: not supported target architecture");
2280 return false;
2281 case llvm::Triple::UnknownObjectFormat:
2282 LLDB_LOGF(log, "error: failed to determine target architecture");
2283 return false;
2284 }
2285
2286 if (pointer_byte_size) {
2287 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2288 }
2289 if (byte_order != eByteOrderInvalid) {
2290 assert(byte_order == m_process_arch.GetByteOrder());
2291 }
2292 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2293 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2294 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2295 }
2296 return true;
2297 }
2298 } else {
2300 }
2301
2302 return false;
2303}
2304
2306 const ProcessInstanceInfoMatch &match_info,
2307 ProcessInstanceInfoList &process_infos) {
2308 process_infos.clear();
2309
2311 StreamString packet;
2312 packet.PutCString("qfProcessInfo");
2313 if (!match_info.MatchAllProcesses()) {
2314 packet.PutChar(':');
2315 const char *name = match_info.GetProcessInfo().GetName();
2316 bool has_name_match = false;
2317 if (name && name[0]) {
2318 has_name_match = true;
2319 NameMatch name_match_type = match_info.GetNameMatchType();
2320 switch (name_match_type) {
2321 case NameMatch::Ignore:
2322 has_name_match = false;
2323 break;
2324
2325 case NameMatch::Equals:
2326 packet.PutCString("name_match:equals;");
2327 break;
2328
2330 packet.PutCString("name_match:contains;");
2331 break;
2332
2334 packet.PutCString("name_match:starts_with;");
2335 break;
2336
2338 packet.PutCString("name_match:ends_with;");
2339 break;
2340
2342 packet.PutCString("name_match:regex;");
2343 break;
2344 }
2345 if (has_name_match) {
2346 packet.PutCString("name:");
2347 packet.PutBytesAsRawHex8(name, ::strlen(name));
2348 packet.PutChar(';');
2349 }
2350 }
2351
2352 if (match_info.GetProcessInfo().ProcessIDIsValid())
2353 packet.Printf("pid:%" PRIu64 ";",
2354 match_info.GetProcessInfo().GetProcessID());
2355 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2356 packet.Printf("parent_pid:%" PRIu64 ";",
2357 match_info.GetProcessInfo().GetParentProcessID());
2358 if (match_info.GetProcessInfo().UserIDIsValid())
2359 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2360 if (match_info.GetProcessInfo().GroupIDIsValid())
2361 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2362 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2363 packet.Printf("euid:%u;",
2364 match_info.GetProcessInfo().GetEffectiveUserID());
2365 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2366 packet.Printf("egid:%u;",
2367 match_info.GetProcessInfo().GetEffectiveGroupID());
2368 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2369 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2370 const ArchSpec &match_arch =
2371 match_info.GetProcessInfo().GetArchitecture();
2372 const llvm::Triple &triple = match_arch.GetTriple();
2373 packet.PutCString("triple:");
2374 packet.PutCString(triple.getTriple());
2375 packet.PutChar(';');
2376 }
2377 }
2378 StringExtractorGDBRemote response;
2379 // Increase timeout as the first qfProcessInfo packet takes a long time on
2380 // Android. The value of 1min was arrived at empirically.
2381 ScopedTimeout timeout(*this, minutes(1));
2382 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2384 do {
2385 ProcessInstanceInfo process_info;
2386 if (!DecodeProcessInfoResponse(response, process_info))
2387 break;
2388 process_infos.push_back(process_info);
2389 response = StringExtractorGDBRemote();
2390 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2392 } else {
2394 return 0;
2395 }
2396 }
2397 return process_infos.size();
2398}
2399
2401 std::string &name) {
2403 char packet[32];
2404 const int packet_len =
2405 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2406 assert(packet_len < (int)sizeof(packet));
2407 UNUSED_IF_ASSERT_DISABLED(packet_len);
2408 StringExtractorGDBRemote response;
2409 if (SendPacketAndWaitForResponse(packet, response) ==
2411 if (response.IsNormalResponse()) {
2412 // Make sure we parsed the right number of characters. The response is
2413 // the hex encoded user name and should make up the entire packet. If
2414 // there are any non-hex ASCII bytes, the length won't match below..
2415 if (response.GetHexByteString(name) * 2 ==
2416 response.GetStringRef().size())
2417 return true;
2418 }
2419 } else {
2420 m_supports_qUserName = false;
2421 return false;
2422 }
2423 }
2424 return false;
2425}
2426
2428 std::string &name) {
2430 char packet[32];
2431 const int packet_len =
2432 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2433 assert(packet_len < (int)sizeof(packet));
2434 UNUSED_IF_ASSERT_DISABLED(packet_len);
2435 StringExtractorGDBRemote response;
2436 if (SendPacketAndWaitForResponse(packet, response) ==
2438 if (response.IsNormalResponse()) {
2439 // Make sure we parsed the right number of characters. The response is
2440 // the hex encoded group name and should make up the entire packet. If
2441 // there are any non-hex ASCII bytes, the length won't match below..
2442 if (response.GetHexByteString(name) * 2 ==
2443 response.GetStringRef().size())
2444 return true;
2445 }
2446 } else {
2447 m_supports_qGroupName = false;
2448 return false;
2449 }
2450 }
2451 return false;
2452}
2453
2454static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2455 uint32_t recv_size) {
2456 packet.Clear();
2457 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2458 uint32_t bytes_left = send_size;
2459 while (bytes_left > 0) {
2460 if (bytes_left >= 26) {
2461 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2462 bytes_left -= 26;
2463 } else {
2464 packet.Printf("%*.*s;", bytes_left, bytes_left,
2465 "abcdefghijklmnopqrstuvwxyz");
2466 bytes_left = 0;
2467 }
2468 }
2469}
2470
2471duration<float>
2472calculate_standard_deviation(const std::vector<duration<float>> &v) {
2473 if (v.size() == 0)
2474 return duration<float>::zero();
2475 using Dur = duration<float>;
2476 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2477 Dur mean = sum / v.size();
2478 float accum = 0;
2479 for (auto d : v) {
2480 float delta = (d - mean).count();
2481 accum += delta * delta;
2482 };
2483
2484 return Dur(sqrtf(accum / (v.size() - 1)));
2485}
2486
2488 uint32_t max_send,
2489 uint32_t max_recv,
2490 uint64_t recv_amount,
2491 bool json, Stream &strm) {
2492
2493 if (SendSpeedTestPacket(0, 0)) {
2494 StreamString packet;
2495 if (json)
2496 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2497 "\"results\" : [",
2498 num_packets);
2499 else
2500 strm.Printf("Testing sending %u packets of various sizes:\n",
2501 num_packets);
2502 strm.Flush();
2503
2504 uint32_t result_idx = 0;
2505 uint32_t send_size;
2506 std::vector<duration<float>> packet_times;
2507
2508 for (send_size = 0; send_size <= max_send;
2509 send_size ? send_size *= 2 : send_size = 4) {
2510 for (uint32_t recv_size = 0; recv_size <= max_recv;
2511 recv_size ? recv_size *= 2 : recv_size = 4) {
2512 MakeSpeedTestPacket(packet, send_size, recv_size);
2513
2514 packet_times.clear();
2515 // Test how long it takes to send 'num_packets' packets
2516 const auto start_time = steady_clock::now();
2517 for (uint32_t i = 0; i < num_packets; ++i) {
2518 const auto packet_start_time = steady_clock::now();
2519 StringExtractorGDBRemote response;
2520 SendPacketAndWaitForResponse(packet.GetString(), response);
2521 const auto packet_end_time = steady_clock::now();
2522 packet_times.push_back(packet_end_time - packet_start_time);
2523 }
2524 const auto end_time = steady_clock::now();
2525 const auto total_time = end_time - start_time;
2526
2527 float packets_per_second =
2528 ((float)num_packets) / duration<float>(total_time).count();
2529 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2530 : duration<float>::zero();
2531 const duration<float> standard_deviation =
2532 calculate_standard_deviation(packet_times);
2533 if (json) {
2534 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2535 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2536 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2537 result_idx > 0 ? "," : "", send_size, recv_size,
2538 total_time, standard_deviation);
2539 ++result_idx;
2540 } else {
2541 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2542 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2543 "standard deviation of {5,10:ms+f6}\n",
2544 send_size, recv_size, duration<float>(total_time),
2545 packets_per_second, duration<float>(average_per_packet),
2546 standard_deviation);
2547 }
2548 strm.Flush();
2549 }
2550 }
2551
2552 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2553 if (json)
2554 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2555 ": %" PRIu64 ",\n \"results\" : [",
2556 recv_amount);
2557 else
2558 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2559 "packet sizes:\n",
2560 k_recv_amount_mb);
2561 strm.Flush();
2562 send_size = 0;
2563 result_idx = 0;
2564 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2565 MakeSpeedTestPacket(packet, send_size, recv_size);
2566
2567 // If we have a receive size, test how long it takes to receive 4MB of
2568 // data
2569 if (recv_size > 0) {
2570 const auto start_time = steady_clock::now();
2571 uint32_t bytes_read = 0;
2572 uint32_t packet_count = 0;
2573 while (bytes_read < recv_amount) {
2574 StringExtractorGDBRemote response;
2575 SendPacketAndWaitForResponse(packet.GetString(), response);
2576 bytes_read += recv_size;
2577 ++packet_count;
2578 }
2579 const auto end_time = steady_clock::now();
2580 const auto total_time = end_time - start_time;
2581 float mb_second = ((float)recv_amount) /
2582 duration<float>(total_time).count() /
2583 (1024.0 * 1024.0);
2584 float packets_per_second =
2585 ((float)packet_count) / duration<float>(total_time).count();
2586 const auto average_per_packet = packet_count > 0
2587 ? total_time / packet_count
2588 : duration<float>::zero();
2589
2590 if (json) {
2591 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2592 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2593 result_idx > 0 ? "," : "", send_size, recv_size,
2594 total_time);
2595 ++result_idx;
2596 } else {
2597 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2598 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2599 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2600 send_size, recv_size, packet_count, k_recv_amount_mb,
2601 duration<float>(total_time), mb_second,
2602 packets_per_second, duration<float>(average_per_packet));
2603 }
2604 strm.Flush();
2605 }
2606 }
2607 if (json)
2608 strm.Printf("\n ]\n }\n}\n");
2609 else
2610 strm.EOL();
2611 }
2612}
2613
2615 uint32_t recv_size) {
2616 StreamString packet;
2617 packet.Printf("qSpeedTest:response_size:%i;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 StringExtractorGDBRemote response;
2631 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2633}
2634
2636 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2637 std::string &socket_name) {
2639 port = 0;
2640 socket_name.clear();
2641
2642 StringExtractorGDBRemote response;
2643 StreamString stream;
2644 stream.PutCString("qLaunchGDBServer;");
2645 std::string hostname;
2646 if (remote_accept_hostname && remote_accept_hostname[0])
2647 hostname = remote_accept_hostname;
2648 else {
2649 if (HostInfo::GetHostname(hostname)) {
2650 // Make the GDB server we launch only accept connections from this host
2651 stream.Printf("host:%s;", hostname.c_str());
2652 } else {
2653 // Make the GDB server we launch accept connections from any host since
2654 // we can't figure out the hostname
2655 stream.Printf("host:*;");
2656 }
2657 }
2658 // give the process a few seconds to startup
2659 ScopedTimeout timeout(*this, seconds(10));
2660
2661 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2663 if (response.IsErrorResponse())
2664 return false;
2665
2666 llvm::StringRef name;
2667 llvm::StringRef value;
2668 while (response.GetNameColonValue(name, value)) {
2669 if (name == "port")
2670 value.getAsInteger(0, port);
2671 else if (name == "pid")
2672 value.getAsInteger(0, pid);
2673 else if (name.compare("socket_name") == 0) {
2674 StringExtractor extractor(value);
2675 extractor.GetHexByteString(socket_name);
2676 }
2677 }
2678 return true;
2679 }
2680 return false;
2681}
2682
2684 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2685 connection_urls.clear();
2686
2687 StringExtractorGDBRemote response;
2688 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2690 return 0;
2691
2694 if (!data)
2695 return 0;
2696
2697 StructuredData::Array *array = data->GetAsArray();
2698 if (!array)
2699 return 0;
2700
2701 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2702 std::optional<StructuredData::Dictionary *> maybe_element =
2704 if (!maybe_element)
2705 continue;
2706
2707 StructuredData::Dictionary *element = *maybe_element;
2708 uint16_t port = 0;
2709 if (StructuredData::ObjectSP port_osp =
2710 element->GetValueForKey(llvm::StringRef("port")))
2711 port = port_osp->GetUnsignedIntegerValue(0);
2712
2713 std::string socket_name;
2714 if (StructuredData::ObjectSP socket_name_osp =
2715 element->GetValueForKey(llvm::StringRef("socket_name")))
2716 socket_name = std::string(socket_name_osp->GetStringValue());
2717
2718 if (port != 0 || !socket_name.empty())
2719 connection_urls.emplace_back(port, socket_name);
2720 }
2721 return connection_urls.size();
2722}
2723
2725 StreamString stream;
2726 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2727
2728 StringExtractorGDBRemote response;
2729 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2731 if (response.IsOKResponse())
2732 return true;
2733 }
2734 return false;
2735}
2736
2738 uint64_t tid, uint64_t pid, char op) {
2740 packet.PutChar('H');
2741 packet.PutChar(op);
2742
2743 if (pid != LLDB_INVALID_PROCESS_ID)
2744 packet.Printf("p%" PRIx64 ".", pid);
2745
2746 if (tid == UINT64_MAX)
2747 packet.PutCString("-1");
2748 else
2749 packet.Printf("%" PRIx64, tid);
2750
2751 StringExtractorGDBRemote response;
2752 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2754 if (response.IsOKResponse())
2755 return {{pid, tid}};
2756
2757 /*
2758 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2759 * Hg packet.
2760 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2761 * which can
2762 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2763 */
2764 if (response.IsUnsupportedResponse() && IsConnected())
2765 return {{1, 1}};
2766 }
2767 return std::nullopt;
2768}
2769
2771 uint64_t pid) {
2772 if (m_curr_tid == tid &&
2773 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2774 return true;
2775
2776 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2777 if (ret) {
2778 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2779 m_curr_pid = ret->pid;
2780 m_curr_tid = ret->tid;
2781 }
2782 return ret.has_value();
2783}
2784
2786 uint64_t pid) {
2787 if (m_curr_tid_run == tid &&
2788 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2789 return true;
2790
2791 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2792 if (ret) {
2793 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2794 m_curr_pid_run = ret->pid;
2795 m_curr_tid_run = ret->tid;
2796 }
2797 return ret.has_value();
2798}
2799
2801 StringExtractorGDBRemote &response) {
2803 return response.IsNormalResponse();
2804 return false;
2805}
2806
2808 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2810 char packet[256];
2811 int packet_len =
2812 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2813 assert(packet_len < (int)sizeof(packet));
2814 UNUSED_IF_ASSERT_DISABLED(packet_len);
2815 if (SendPacketAndWaitForResponse(packet, response) ==
2817 if (response.IsUnsupportedResponse())
2819 else if (response.IsNormalResponse())
2820 return true;
2821 else
2822 return false;
2823 } else {
2825 }
2826 }
2827 return false;
2828}
2829
2831 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2832 std::chrono::seconds timeout) {
2834 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2835 __FUNCTION__, insert ? "add" : "remove", addr);
2836
2837 // Check if the stub is known not to support this breakpoint type
2838 if (!SupportsGDBStoppointPacket(type))
2839 return UINT8_MAX;
2840 // Construct the breakpoint packet
2841 char packet[64];
2842 const int packet_len =
2843 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2844 insert ? 'Z' : 'z', type, addr, length);
2845 // Check we haven't overwritten the end of the packet buffer
2846 assert(packet_len + 1 < (int)sizeof(packet));
2847 UNUSED_IF_ASSERT_DISABLED(packet_len);
2848 StringExtractorGDBRemote response;
2849 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2850 // or "" (unsupported)
2852 // Try to send the breakpoint packet, and check that it was correctly sent
2853 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
2855 // Receive and OK packet when the breakpoint successfully placed
2856 if (response.IsOKResponse())
2857 return 0;
2858
2859 // Status while setting breakpoint, send back specific error
2860 if (response.IsErrorResponse())
2861 return response.GetError();
2862
2863 // Empty packet informs us that breakpoint is not supported
2864 if (response.IsUnsupportedResponse()) {
2865 // Disable this breakpoint type since it is unsupported
2866 switch (type) {
2868 m_supports_z0 = false;
2869 break;
2871 m_supports_z1 = false;
2872 break;
2873 case eWatchpointWrite:
2874 m_supports_z2 = false;
2875 break;
2876 case eWatchpointRead:
2877 m_supports_z3 = false;
2878 break;
2880 m_supports_z4 = false;
2881 break;
2882 case eStoppointInvalid:
2883 return UINT8_MAX;
2884 }
2885 }
2886 }
2887 // Signal generic failure
2888 return UINT8_MAX;
2889}
2890
2891std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
2893 bool &sequence_mutex_unavailable) {
2894 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
2895
2896 Lock lock(*this);
2897 if (lock) {
2898 sequence_mutex_unavailable = false;
2899 StringExtractorGDBRemote response;
2900
2901 PacketResult packet_result;
2902 for (packet_result =
2903 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2904 packet_result == PacketResult::Success && response.IsNormalResponse();
2905 packet_result =
2906 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2907 char ch = response.GetChar();
2908 if (ch == 'l')
2909 break;
2910 if (ch == 'm') {
2911 do {
2912 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
2913 // If we get an invalid response, break out of the loop.
2914 // If there are valid tids, they have been added to ids.
2915 // If there are no valid tids, we'll fall through to the
2916 // bare-iron target handling below.
2917 if (!pid_tid)
2918 break;
2919
2920 ids.push_back(*pid_tid);
2921 ch = response.GetChar(); // Skip the command separator
2922 } while (ch == ','); // Make sure we got a comma separator
2923 }
2924 }
2925
2926 /*
2927 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2928 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2929 * could
2930 * be as simple as 'S05'. There is no packet which can give us pid and/or
2931 * tid.
2932 * Assume pid=tid=1 in such cases.
2933 */
2934 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2935 ids.size() == 0 && IsConnected()) {
2936 ids.emplace_back(1, 1);
2937 }
2938 } else {
2940 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
2941 "packet 'qfThreadInfo'");
2942 sequence_mutex_unavailable = true;
2943 }
2944
2945 return ids;
2946}
2947
2949 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2951 thread_ids.clear();
2952
2953 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
2954 if (ids.empty() || sequence_mutex_unavailable)
2955 return 0;
2956
2957 for (auto id : ids) {
2958 // skip threads that do not belong to the current process
2959 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
2960 continue;
2961 if (id.second != LLDB_INVALID_THREAD_ID &&
2963 thread_ids.push_back(id.second);
2964 }
2965
2966 return thread_ids.size();
2967}
2968
2970 StringExtractorGDBRemote response;
2971 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
2973 !response.IsNormalResponse())
2974 return LLDB_INVALID_ADDRESS;
2975 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2976}
2977
2979 llvm::StringRef command,
2980 const FileSpec &
2981 working_dir, // Pass empty FileSpec to use the current working directory
2982 int *status_ptr, // Pass NULL if you don't want the process exit status
2983 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2984 // process to exit
2985 std::string
2986 *command_output, // Pass nullptr if you don't want the command output
2987 std::string *separated_error_output, // Pass nullptr if you don't want the
2988 // command error output
2989 const Timeout<std::micro> &timeout) {
2991 stream.PutCString("qPlatform_shell:");
2992 stream.PutBytesAsRawHex8(command.data(), command.size());
2993 stream.PutChar(',');
2994 uint32_t timeout_sec = UINT32_MAX;
2995 if (timeout) {
2996 // TODO: Use chrono version of std::ceil once c++17 is available.
2997 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2998 }
2999 stream.PutHex32(timeout_sec);
3000 if (working_dir) {
3001 std::string path{working_dir.GetPath(false)};
3002 stream.PutChar(',');
3003 stream.PutStringAsRawHex8(path);
3004 }
3005 StringExtractorGDBRemote response;
3006 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3008 if (response.GetChar() != 'F')
3009 return Status::FromErrorString("malformed reply");
3010 if (response.GetChar() != ',')
3011 return Status::FromErrorString("malformed reply");
3012 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3013 if (exitcode == UINT32_MAX)
3014 return Status::FromErrorString("unable to run remote process");
3015 else if (status_ptr)
3016 *status_ptr = exitcode;
3017 if (response.GetChar() != ',')
3018 return Status::FromErrorString("malformed reply");
3019 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3020 if (signo_ptr)
3021 *signo_ptr = signo;
3022 if (response.GetChar() != ',')
3023 return Status::FromErrorString("malformed reply");
3024 std::string output;
3025 response.GetEscapedBinaryData(output);
3026 if (command_output)
3027 command_output->assign(output);
3028 return Status();
3029 }
3030 return Status::FromErrorString("unable to send packet");
3031}
3032
3034 uint32_t file_permissions) {
3035 std::string path{file_spec.GetPath(false)};
3037 stream.PutCString("qPlatform_mkdir:");
3038 stream.PutHex32(file_permissions);
3039 stream.PutChar(',');
3040 stream.PutStringAsRawHex8(path);
3041 llvm::StringRef packet = stream.GetString();
3042 StringExtractorGDBRemote response;
3043
3044 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3045 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3046 packet.str().c_str());
3047
3048 if (response.GetChar() != 'F')
3049 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3050 packet.str().c_str());
3051
3052 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3053}
3054
3055Status
3057 uint32_t file_permissions) {
3058 std::string path{file_spec.GetPath(false)};
3060 stream.PutCString("qPlatform_chmod:");
3061 stream.PutHex32(file_permissions);
3062 stream.PutChar(',');
3063 stream.PutStringAsRawHex8(path);
3064 llvm::StringRef packet = stream.GetString();
3065 StringExtractorGDBRemote response;
3066
3067 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3068 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3069 stream.GetData());
3070
3071 if (response.GetChar() != 'F')
3072 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3073 stream.GetData());
3074
3075 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3076}
3077
3078static int gdb_errno_to_system(int err) {
3079 switch (err) {
3080#define HANDLE_ERRNO(name, value) \
3081 case GDB_##name: \
3082 return name;
3083#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3084 default:
3085 return -1;
3086 }
3087}
3088
3090 uint64_t fail_result, Status &error) {
3091 response.SetFilePos(0);
3092 if (response.GetChar() != 'F')
3093 return fail_result;
3094 int32_t result = response.GetS32(-2, 16);
3095 if (result == -2)
3096 return fail_result;
3097 if (response.GetChar() == ',') {
3098 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3099 if (result_errno != -1)
3100 error = Status(result_errno, eErrorTypePOSIX);
3101 else
3103 } else
3104 error.Clear();
3105 return result;
3106}
3109 File::OpenOptions flags, mode_t mode,
3110 Status &error) {
3111 std::string path(file_spec.GetPath(false));
3113 stream.PutCString("vFile:open:");
3114 if (path.empty())
3115 return UINT64_MAX;
3116 stream.PutStringAsRawHex8(path);
3117 stream.PutChar(',');
3118 stream.PutHex32(flags);
3119 stream.PutChar(',');
3120 stream.PutHex32(mode);
3121 StringExtractorGDBRemote response;
3122 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3124 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3125 }
3126 return UINT64_MAX;
3127}
3128
3130 Status &error) {
3132 stream.Printf("vFile:close:%x", (int)fd);
3133 StringExtractorGDBRemote response;
3134 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3136 return ParseHostIOPacketResponse(response, -1, error) == 0;
3137 }
3138 return false;
3139}
3140
3141std::optional<GDBRemoteFStatData>
3144 stream.Printf("vFile:fstat:%" PRIx64, fd);
3145 StringExtractorGDBRemote response;
3146 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3148 if (response.GetChar() != 'F')
3149 return std::nullopt;
3150 int64_t size = response.GetS64(-1, 16);
3151 if (size > 0 && response.GetChar() == ';') {
3152 std::string buffer;
3153 if (response.GetEscapedBinaryData(buffer)) {
3155 if (buffer.size() != sizeof(out))
3156 return std::nullopt;
3157 memcpy(&out, buffer.data(), sizeof(out));
3158 return out;
3159 }
3160 }
3161 }
3162 return std::nullopt;
3163}
3164
3165std::optional<GDBRemoteFStatData>
3167 Status error;
3169 if (fd == UINT64_MAX)
3170 return std::nullopt;
3171 std::optional<GDBRemoteFStatData> st = FStat(fd);
3172 CloseFile(fd, error);
3173 return st;
3174}
3175
3176// Extension of host I/O packets to get the file size.
3178 const lldb_private::FileSpec &file_spec) {
3180 std::string path(file_spec.GetPath(false));
3182 stream.PutCString("vFile:size:");
3183 stream.PutStringAsRawHex8(path);
3184 StringExtractorGDBRemote response;
3185 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3187 return UINT64_MAX;
3188
3189 if (!response.IsUnsupportedResponse()) {
3190 if (response.GetChar() != 'F')
3191 return UINT64_MAX;
3192 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3193 return retcode;
3194 }
3195 m_supports_vFileSize = false;
3196 }
3197
3198 // Fallback to fstat.
3199 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3200 return st ? st->gdb_st_size : UINT64_MAX;
3201}
3202
3204 CompletionRequest &request, bool only_dir) {
3206 stream.PutCString("qPathComplete:");
3207 stream.PutHex32(only_dir ? 1 : 0);
3208 stream.PutChar(',');
3210 StringExtractorGDBRemote response;
3211 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3213 StreamString strm;
3214 char ch = response.GetChar();
3215 if (ch != 'M')
3216 return;
3217 while (response.Peek()) {
3218 strm.Clear();
3219 while ((ch = response.GetHexU8(0, false)) != '\0')
3220 strm.PutChar(ch);
3221 request.AddCompletion(strm.GetString());
3222 if (response.GetChar() != ',')
3223 break;
3224 }
3225 }
3226}
3227
3228Status
3230 uint32_t &file_permissions) {
3232 std::string path{file_spec.GetPath(false)};
3233 Status error;
3235 stream.PutCString("vFile:mode:");
3236 stream.PutStringAsRawHex8(path);
3237 StringExtractorGDBRemote response;
3238 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3240 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3241 stream.GetData());
3242 return error;
3243 }
3244 if (!response.IsUnsupportedResponse()) {
3245 if (response.GetChar() != 'F') {
3247 "invalid response to '%s' packet", stream.GetData());
3248 } else {
3249 const uint32_t mode = response.GetS32(-1, 16);
3250 if (static_cast<int32_t>(mode) == -1) {
3251 if (response.GetChar() == ',') {
3252 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3253 if (response_errno > 0)
3254 error = Status(response_errno, lldb::eErrorTypePOSIX);
3255 else
3256 error = Status::FromErrorString("unknown error");
3257 } else
3258 error = Status::FromErrorString("unknown error");
3259 } else {
3260 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3261 }
3262 }
3263 return error;
3264 } else { // response.IsUnsupportedResponse()
3265 m_supports_vFileMode = false;
3266 }
3267 }
3268
3269 // Fallback to fstat.
3270 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3271 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3272 return Status();
3273 }
3274 return Status::FromErrorString("fstat failed");
3275}
3276
3278 uint64_t offset, void *dst,
3279 uint64_t dst_len,
3280 Status &error) {
3282 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3283 offset);
3284 StringExtractorGDBRemote response;
3285 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3287 if (response.GetChar() != 'F')
3288 return 0;
3289 int64_t retcode = response.GetS64(-1, 16);
3290 if (retcode == -1) {
3291 error = Status::FromErrorString("unknown error");
3292 if (response.GetChar() == ',') {
3293 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3294 if (response_errno > 0)
3295 error = Status(response_errno, lldb::eErrorTypePOSIX);
3296 }
3297 return -1;
3298 }
3299 const char next = (response.Peek() ? *response.Peek() : 0);
3300 if (next == ',')
3301 return 0;
3302 if (next == ';') {
3303 response.GetChar(); // skip the semicolon
3304 std::string buffer;
3305 if (response.GetEscapedBinaryData(buffer)) {
3306 const uint64_t data_to_write =
3307 std::min<uint64_t>(dst_len, buffer.size());
3308 if (data_to_write > 0)
3309 memcpy(dst, &buffer[0], data_to_write);
3310 return data_to_write;
3311 }
3312 }
3313 }
3314 return 0;
3315}
3316
3318 uint64_t offset,
3319 const void *src,
3320 uint64_t src_len,
3321 Status &error) {
3323 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3324 stream.PutEscapedBytes(src, src_len);
3325 StringExtractorGDBRemote response;
3326 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3328 if (response.GetChar() != 'F') {
3329 error = Status::FromErrorStringWithFormat("write file failed");
3330 return 0;
3331 }
3332 int64_t bytes_written = response.GetS64(-1, 16);
3333 if (bytes_written == -1) {
3334 error = Status::FromErrorString("unknown error");
3335 if (response.GetChar() == ',') {
3336 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3337 if (response_errno > 0)
3338 error = Status(response_errno, lldb::eErrorTypePOSIX);
3339 }
3340 return -1;
3341 }
3342 return bytes_written;
3343 } else {
3344 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3345 }
3346 return 0;
3347}
3348
3350 const FileSpec &dst) {
3351 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3352 Status error;
3354 stream.PutCString("vFile:symlink:");
3355 // the unix symlink() command reverses its parameters where the dst if first,
3356 // so we follow suit here
3357 stream.PutStringAsRawHex8(dst_path);
3358 stream.PutChar(',');
3359 stream.PutStringAsRawHex8(src_path);
3360 StringExtractorGDBRemote response;
3361 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3363 if (response.GetChar() == 'F') {
3364 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3365 if (result != 0) {
3366 error = Status::FromErrorString("unknown error");
3367 if (response.GetChar() == ',') {
3368 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3369 if (response_errno > 0)
3370 error = Status(response_errno, lldb::eErrorTypePOSIX);
3371 }
3372 }
3373 } else {
3374 // Should have returned with 'F<result>[,<errno>]'
3375 error = Status::FromErrorStringWithFormat("symlink failed");
3376 }
3377 } else {
3378 error = Status::FromErrorString("failed to send vFile:symlink packet");
3379 }
3380 return error;
3381}
3382
3384 std::string path{file_spec.GetPath(false)};
3385 Status error;
3387 stream.PutCString("vFile:unlink:");
3388 // the unix symlink() command reverses its parameters where the dst if first,
3389 // so we follow suit here
3390 stream.PutStringAsRawHex8(path);
3391 StringExtractorGDBRemote response;
3392 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3394 if (response.GetChar() == 'F') {
3395 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3396 if (result != 0) {
3397 error = Status::FromErrorString("unknown error");
3398 if (response.GetChar() == ',') {
3399 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3400 if (response_errno > 0)
3401 error = Status(response_errno, lldb::eErrorTypePOSIX);
3402 }
3403 }
3404 } else {
3405 // Should have returned with 'F<result>[,<errno>]'
3406 error = Status::FromErrorStringWithFormat("unlink failed");
3407 }
3408 } else {
3409 error = Status::FromErrorString("failed to send vFile:unlink packet");
3410 }
3411 return error;
3412}
3413
3414// Extension of host I/O packets to get whether a file exists.
3416 const lldb_private::FileSpec &file_spec) {
3418 std::string path(file_spec.GetPath(false));
3420 stream.PutCString("vFile:exists:");
3421 stream.PutStringAsRawHex8(path);
3422 StringExtractorGDBRemote response;
3423 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3425 return false;
3426 if (!response.IsUnsupportedResponse()) {
3427 if (response.GetChar() != 'F')
3428 return false;
3429 if (response.GetChar() != ',')
3430 return false;
3431 bool retcode = (response.GetChar() != '0');
3432 return retcode;
3433 } else
3434 m_supports_vFileExists = false;
3435 }
3436
3437 // Fallback to open.
3438 Status error;
3440 if (fd == UINT64_MAX)
3441 return false;
3442 CloseFile(fd, error);
3443 return true;
3444}
3445
3446llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3447 const lldb_private::FileSpec &file_spec) {
3448 std::string path(file_spec.GetPath(false));
3450 stream.PutCString("vFile:MD5:");
3451 stream.PutStringAsRawHex8(path);
3452 StringExtractorGDBRemote response;
3453 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3455 if (response.GetChar() != 'F')
3456 return std::make_error_code(std::errc::illegal_byte_sequence);
3457 if (response.GetChar() != ',')
3458 return std::make_error_code(std::errc::illegal_byte_sequence);
3459 if (response.Peek() && *response.Peek() == 'x')
3460 return std::make_error_code(std::errc::no_such_file_or_directory);
3461
3462 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3463 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3464 // handle the concatenated hex string. What would happen is parsing the low
3465 // would consume the whole response packet which would give incorrect
3466 // results. Instead, we get the byte string for each low and high hex
3467 // separately, and parse them.
3468 //
3469 // An alternate way to handle this is to change the server to put a
3470 // delimiter between the low/high parts, and change the client to parse the
3471 // delimiter. However, we choose not to do this so existing lldb-servers
3472 // don't have to be patched
3473
3474 // The checksum is 128 bits encoded as hex
3475 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3476 // Each byte takes 2 hex characters in the response.
3477 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3478
3479 // Get low part
3480 auto part =
3481 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3482 if (part.size() != MD5_HALF_LENGTH)
3483 return std::make_error_code(std::errc::illegal_byte_sequence);
3484 response.SetFilePos(response.GetFilePos() + part.size());
3485
3486 uint64_t low;
3487 if (part.getAsInteger(/*radix=*/16, low))
3488 return std::make_error_code(std::errc::illegal_byte_sequence);
3489
3490 // Get high part
3491 part =
3492 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3493 if (part.size() != MD5_HALF_LENGTH)
3494 return std::make_error_code(std::errc::illegal_byte_sequence);
3495 response.SetFilePos(response.GetFilePos() + part.size());
3496
3497 uint64_t high;
3498 if (part.getAsInteger(/*radix=*/16, high))
3499 return std::make_error_code(std::errc::illegal_byte_sequence);
3500
3501 llvm::MD5::MD5Result result;
3502 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3503 result.data(), low);
3504 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3505 result.data() + 8, high);
3506
3507 return result;
3508 }
3509 return std::make_error_code(std::errc::operation_canceled);
3510}
3511
3513 // Some targets have issues with g/G packets and we need to avoid using them
3515 if (process) {
3517 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3518 if (arch.IsValid() &&
3519 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3520 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3521 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3522 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3524 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3525 if (gdb_server_version != 0) {
3526 const char *gdb_server_name = GetGDBServerProgramName();
3527 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3528 if (gdb_server_version >= 310)
3530 }
3531 }
3532 }
3533 }
3534 }
3536}
3537
3539 uint32_t reg) {
3540 StreamString payload;
3541 payload.Printf("p%x", reg);
3542 StringExtractorGDBRemote response;
3544 tid, std::move(payload), response) != PacketResult::Success ||
3545 !response.IsNormalResponse())
3546 return nullptr;
3547
3548 WritableDataBufferSP buffer_sp(
3549 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3550 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3551 return buffer_sp;
3552}
3553
3555 StreamString payload;
3556 payload.PutChar('g');
3557 StringExtractorGDBRemote response;
3559 tid, std::move(payload), response) != PacketResult::Success ||
3560 !response.IsNormalResponse())
3561 return nullptr;
3562
3563 WritableDataBufferSP buffer_sp(
3564 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3565 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3566 return buffer_sp;
3567}
3568
3570 uint32_t reg_num,
3571 llvm::ArrayRef<uint8_t> data) {
3572 StreamString payload;
3573 payload.Printf("P%x=", reg_num);
3574 payload.PutBytesAsRawHex8(data.data(), data.size(),
3577 StringExtractorGDBRemote response;
3579 tid, std::move(payload), response) == PacketResult::Success &&
3580 response.IsOKResponse();
3581}
3582
3584 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3585 StreamString payload;
3586 payload.PutChar('G');
3587 payload.PutBytesAsRawHex8(data.data(), data.size(),
3590 StringExtractorGDBRemote response;
3592 tid, std::move(payload), response) == PacketResult::Success &&
3593 response.IsOKResponse();
3594}
3595
3597 uint32_t &save_id) {
3598 save_id = 0; // Set to invalid save ID
3600 return false;
3601
3603 StreamString payload;
3604 payload.PutCString("QSaveRegisterState");
3605 StringExtractorGDBRemote response;
3607 tid, std::move(payload), response) != PacketResult::Success)
3608 return false;
3609
3610 if (response.IsUnsupportedResponse())
3612
3613 const uint32_t response_save_id = response.GetU32(0);
3614 if (response_save_id == 0)
3615 return false;
3616
3617 save_id = response_save_id;
3618 return true;
3619}
3620
3622 uint32_t save_id) {
3623 // We use the "m_supports_QSaveRegisterState" variable here because the
3624 // QSaveRegisterState and QRestoreRegisterState packets must both be
3625 // supported in order to be useful
3627 return false;
3628
3629 StreamString payload;
3630 payload.Printf("QRestoreRegisterState:%u", save_id);
3631 StringExtractorGDBRemote response;
3633 tid, std::move(payload), response) != PacketResult::Success)
3634 return false;
3635
3636 if (response.IsOKResponse())
3637 return true;
3638
3639 if (response.IsUnsupportedResponse())
3641 return false;
3642}
3643
3646 return false;
3647
3648 StreamString packet;
3649 StringExtractorGDBRemote response;
3650 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3651 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3653 response.IsOKResponse();
3654}
3655
3656llvm::Expected<TraceSupportedResponse>
3658 Log *log = GetLog(GDBRLog::Process);
3659
3660 StreamGDBRemote escaped_packet;
3661 escaped_packet.PutCString("jLLDBTraceSupported");
3662
3663 StringExtractorGDBRemote response;
3664 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3665 timeout) ==
3667 if (response.IsErrorResponse())
3668 return response.GetStatus().ToError();
3669 if (response.IsUnsupportedResponse())
3670 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3671 "jLLDBTraceSupported is unsupported");
3672
3673 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3674 "TraceSupportedResponse");
3675 }
3676 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3677 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3678 "failed to send packet: jLLDBTraceSupported");
3679}
3680
3681llvm::Error
3683 std::chrono::seconds timeout) {
3684 Log *log = GetLog(GDBRLog::Process);
3685
3686 StreamGDBRemote escaped_packet;
3687 escaped_packet.PutCString("jLLDBTraceStop:");
3688
3689 std::string json_string;
3690 llvm::raw_string_ostream os(json_string);
3691 os << toJSON(request);
3692
3693 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3694
3695 StringExtractorGDBRemote response;
3696 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3697 timeout) ==
3699 if (response.IsErrorResponse())
3700 return response.GetStatus().ToError();
3701 if (response.IsUnsupportedResponse())
3702 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3703 "jLLDBTraceStop is unsupported");
3704 if (response.IsOKResponse())
3705 return llvm::Error::success();
3706 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3707 "Invalid jLLDBTraceStart response");
3708 }
3709 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3710 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3711 "failed to send packet: jLLDBTraceStop '%s'",
3712 escaped_packet.GetData());
3713}
3714
3715llvm::Error
3716GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3717 std::chrono::seconds timeout) {
3718 Log *log = GetLog(GDBRLog::Process);
3719
3720 StreamGDBRemote escaped_packet;
3721 escaped_packet.PutCString("jLLDBTraceStart:");
3722
3723 std::string json_string;
3724 llvm::raw_string_ostream os(json_string);
3725 os << params;
3726
3727 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3728
3729 StringExtractorGDBRemote response;
3730 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3731 timeout) ==
3733 if (response.IsErrorResponse())
3734 return response.GetStatus().ToError();
3735 if (response.IsUnsupportedResponse())
3736 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3737 "jLLDBTraceStart is unsupported");
3738 if (response.IsOKResponse())
3739 return llvm::Error::success();
3740 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3741 "Invalid jLLDBTraceStart response");
3742 }
3743 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3744 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3745 "failed to send packet: jLLDBTraceStart '%s'",
3746 escaped_packet.GetData());
3747}
3748
3749llvm::Expected<std::string>
3751 std::chrono::seconds timeout) {
3752 Log *log = GetLog(GDBRLog::Process);
3753
3754 StreamGDBRemote escaped_packet;
3755 escaped_packet.PutCString("jLLDBTraceGetState:");
3756
3757 std::string json_string;
3758 llvm::raw_string_ostream os(json_string);
3759 os << toJSON(TraceGetStateRequest{type.str()});
3760
3761 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3762
3763 StringExtractorGDBRemote response;
3764 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3765 timeout) ==
3767 if (response.IsErrorResponse())
3768 return response.GetStatus().ToError();
3769 if (response.IsUnsupportedResponse())
3770 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3771 "jLLDBTraceGetState is unsupported");
3772 return std::string(response.Peek());
3773 }
3774
3775 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3776 return llvm::createStringError(
3777 llvm::inconvertibleErrorCode(),
3778 "failed to send packet: jLLDBTraceGetState '%s'",
3779 escaped_packet.GetData());
3780}
3781
3782llvm::Expected<std::vector<uint8_t>>
3784 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3785 Log *log = GetLog(GDBRLog::Process);
3786
3787 StreamGDBRemote escaped_packet;
3788 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3789
3790 std::string json_string;
3791 llvm::raw_string_ostream os(json_string);
3792 os << toJSON(request);
3793
3794 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3795
3796 StringExtractorGDBRemote response;
3797 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3798 timeout) ==
3800 if (response.IsErrorResponse())
3801 return response.GetStatus().ToError();
3802 std::string data;
3803 response.GetEscapedBinaryData(data);
3804 return std::vector<uint8_t>(data.begin(), data.end());
3805 }
3806 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3807 return llvm::createStringError(
3808 llvm::inconvertibleErrorCode(),
3809 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3810 escaped_packet.GetData());
3811}
3812
3814 StringExtractorGDBRemote response;
3815 if (SendPacketAndWaitForResponse("qOffsets", response) !=
3817 return std::nullopt;
3818 if (!response.IsNormalResponse())
3819 return std::nullopt;
3820
3821 QOffsets result;
3822 llvm::StringRef ref = response.GetStringRef();
3823 const auto &GetOffset = [&] {
3824 addr_t offset;
3825 if (ref.consumeInteger(16, offset))
3826 return false;
3827 result.offsets.push_back(offset);
3828 return true;
3829 };
3830
3831 if (ref.consume_front("Text=")) {
3832 result.segments = false;
3833 if (!GetOffset())
3834 return std::nullopt;
3835 if (!ref.consume_front(";Data=") || !GetOffset())
3836 return std::nullopt;
3837 if (ref.empty())
3838 return result;
3839 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3840 return result;
3841 } else if (ref.consume_front("TextSeg=")) {
3842 result.segments = true;
3843 if (!GetOffset())
3844 return std::nullopt;
3845 if (ref.empty())
3846 return result;
3847 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3848 return result;
3849 }
3850 return std::nullopt;
3851}
3852
3854 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3855 ModuleSpec &module_spec) {
3857 return false;
3858
3859 std::string module_path = module_file_spec.GetPath(false);
3860 if (module_path.empty())
3861 return false;
3862
3863 StreamString packet;
3864 packet.PutCString("qModuleInfo:");
3865 packet.PutStringAsRawHex8(module_path);
3866 packet.PutCString(";");
3867 const auto &triple = arch_spec.GetTriple().getTriple();
3868 packet.PutStringAsRawHex8(triple);
3869
3870 StringExtractorGDBRemote response;
3871 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
3873 return false;
3874
3875 if (response.IsErrorResponse())
3876 return false;
3877
3878 if (response.IsUnsupportedResponse()) {
3879 m_supports_qModuleInfo = false;
3880 return false;
3881 }
3882
3883 llvm::StringRef name;
3884 llvm::StringRef value;
3885
3886 module_spec.Clear();
3887 module_spec.GetFileSpec() = module_file_spec;
3888
3889 while (response.GetNameColonValue(name, value)) {
3890 if (name == "uuid" || name == "md5") {
3891 StringExtractor extractor(value);
3892 std::string uuid;
3893 extractor.GetHexByteString(uuid);
3894 module_spec.GetUUID().SetFromStringRef(uuid);
3895 } else if (name == "triple") {
3896 StringExtractor extractor(value);
3897 std::string triple;
3898 extractor.GetHexByteString(triple);
3899 module_spec.GetArchitecture().SetTriple(triple.c_str());
3900 } else if (name == "file_offset") {
3901 uint64_t ival = 0;
3902 if (!value.getAsInteger(16, ival))
3903 module_spec.SetObjectOffset(ival);
3904 } else if (name == "file_size") {
3905 uint64_t ival = 0;
3906 if (!value.getAsInteger(16, ival))
3907 module_spec.SetObjectSize(ival);
3908 } else if (name == "file_path") {
3909 StringExtractor extractor(value);
3910 std::string path;
3911 extractor.GetHexByteString(path);
3912 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3913 }
3914 }
3915
3916 return true;
3917}
3918
3919static std::optional<ModuleSpec>
3921 ModuleSpec result;
3922 if (!dict)
3923 return std::nullopt;
3924
3925 llvm::StringRef string;
3926 uint64_t integer;
3927
3928 if (!dict->GetValueForKeyAsString("uuid", string))
3929 return std::nullopt;
3930 if (!result.GetUUID().SetFromStringRef(string))
3931 return std::nullopt;
3932
3933 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3934 return std::nullopt;
3935 result.SetObjectOffset(integer);
3936
3937 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3938 return std::nullopt;
3939 result.SetObjectSize(integer);
3940
3941 if (!dict->GetValueForKeyAsString("triple", string))
3942 return std::nullopt;
3943 result.GetArchitecture().SetTriple(string);
3944
3945 if (!dict->GetValueForKeyAsString("file_path", string))
3946 return std::nullopt;
3947 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3948
3949 return result;
3950}
3951
3952std::optional<std::vector<ModuleSpec>>
3954 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3955 namespace json = llvm::json;
3956
3958 return std::nullopt;
3959
3960 json::Array module_array;
3961 for (const FileSpec &module_file_spec : module_file_specs) {
3962 module_array.push_back(
3963 json::Object{{"file", module_file_spec.GetPath(false)},
3964 {"triple", triple.getTriple()}});
3965 }
3966 StreamString unescaped_payload;
3967 unescaped_payload.PutCString("jModulesInfo:");
3968 unescaped_payload.AsRawOstream() << std::move(module_array);
3969
3970 StreamGDBRemote payload;
3971 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3972 unescaped_payload.GetSize());
3973
3974 // Increase the timeout for jModulesInfo since this packet can take longer.
3975 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3976
3977 StringExtractorGDBRemote response;
3978 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
3980 response.IsErrorResponse())
3981 return std::nullopt;
3982
3983 if (response.IsUnsupportedResponse()) {
3985 return std::nullopt;
3986 }
3987
3988 StructuredData::ObjectSP response_object_sp =
3990 if (!response_object_sp)
3991 return std::nullopt;
3992
3993 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3994 if (!response_array)
3995 return std::nullopt;
3996
3997 std::vector<ModuleSpec> result;
3998 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3999 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4000 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4001 result.push_back(*module_spec);
4002 }
4003
4004 return result;
4005}
4006
4007// query the target remote for extended information using the qXfer packet
4008//
4009// example: object='features', annex='target.xml'
4010// return: <xml output> or error
4011llvm::Expected<std::string>
4013 llvm::StringRef annex) {
4014
4015 std::string output;
4016 llvm::raw_string_ostream output_stream(output);
4018
4019 uint64_t size = GetRemoteMaxPacketSize();
4020 if (size == 0)
4021 size = 0x1000;
4022 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4023 int offset = 0;
4024 bool active = true;
4025
4026 // loop until all data has been read
4027 while (active) {
4028
4029 // send query extended feature packet
4030 std::string packet =
4031 ("qXfer:" + object + ":read:" + annex + ":" +
4032 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4033 .str();
4034
4036 SendPacketAndWaitForResponse(packet, chunk);
4037
4039 chunk.GetStringRef().empty()) {
4040 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4041 "Error sending $qXfer packet");
4042 }
4043
4044 // check packet code
4045 switch (chunk.GetStringRef()[0]) {
4046 // last chunk
4047 case ('l'):
4048 active = false;
4049 [[fallthrough]];
4050
4051 // more chunks
4052 case ('m'):
4053 output_stream << chunk.GetStringRef().drop_front();
4054 offset += chunk.GetStringRef().size() - 1;
4055 break;
4056
4057 // unknown chunk
4058 default:
4059 return llvm::createStringError(
4060 llvm::inconvertibleErrorCode(),
4061 "Invalid continuation code from $qXfer packet");
4062 }
4063 }
4064
4065 return output;
4066}
4067
4068// Notify the target that gdb is prepared to serve symbol lookup requests.
4069// packet: "qSymbol::"
4070// reply:
4071// OK The target does not need to look up any (more) symbols.
4072// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4073// encoded).
4074// LLDB may provide the value by sending another qSymbol
4075// packet
4076// in the form of"qSymbol:<sym_value>:<sym_name>".
4077//
4078// Three examples:
4079//
4080// lldb sends: qSymbol::
4081// lldb receives: OK
4082// Remote gdb stub does not need to know the addresses of any symbols, lldb
4083// does not
4084// need to ask again in this session.
4085//
4086// lldb sends: qSymbol::
4087// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4088// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4089// lldb receives: OK
4090// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4091// not know
4092// the address at this time. lldb needs to send qSymbol:: again when it has
4093// more
4094// solibs loaded.
4095//
4096// lldb sends: qSymbol::
4097// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4098// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4099// lldb receives: OK
4100// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4101// that it
4102// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4103// does not
4104// need any more symbols. lldb does not need to ask again in this session.
4105
4107 lldb_private::Process *process) {
4108 // Set to true once we've resolved a symbol to an address for the remote
4109 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4110 // any more symbols and we can stop asking.
4111 bool symbol_response_provided = false;
4112
4113 // Is this the initial qSymbol:: packet?
4114 bool first_qsymbol_query = true;
4115
4117 Lock lock(*this);
4118 if (lock) {
4119 StreamString packet;
4120 packet.PutCString("qSymbol::");
4121 StringExtractorGDBRemote response;
4122 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4124 if (response.IsOKResponse()) {
4125 if (symbol_response_provided || first_qsymbol_query) {
4127 }
4128
4129 // We are done serving symbols requests
4130 return;
4131 }
4132 first_qsymbol_query = false;
4133
4134 if (response.IsUnsupportedResponse()) {
4135 // qSymbol is not supported by the current GDB server we are
4136 // connected to
4137 m_supports_qSymbol = false;
4138 return;
4139 } else {
4140 llvm::StringRef response_str(response.GetStringRef());
4141 if (response_str.starts_with("qSymbol:")) {
4142 response.SetFilePos(strlen("qSymbol:"));
4143 std::string symbol_name;
4144 if (response.GetHexByteString(symbol_name)) {
4145 if (symbol_name.empty())
4146 return;
4147
4148 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4151 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4152 for (const SymbolContext &sc : sc_list) {
4153 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4154 break;
4155 if (sc.symbol) {
4156 switch (sc.symbol->GetType()) {
4157 case eSymbolTypeInvalid:
4164 case eSymbolTypeBlock:
4165 case eSymbolTypeLocal:
4166 case eSymbolTypeParam:
4177 break;
4178
4179 case eSymbolTypeCode:
4181 case eSymbolTypeData:
4182 case eSymbolTypeRuntime:
4188 symbol_load_addr =
4189 sc.symbol->GetLoadAddress(&process->GetTarget());
4190 break;
4191 }
4192 }
4193 }
4194 // This is the normal path where our symbol lookup was successful
4195 // and we want to send a packet with the new symbol value and see
4196 // if another lookup needs to be done.
4197
4198 // Change "packet" to contain the requested symbol value and name
4199 packet.Clear();
4200 packet.PutCString("qSymbol:");
4201 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4202 packet.Printf("%" PRIx64, symbol_load_addr);
4203 symbol_response_provided = true;
4204 } else {
4205 symbol_response_provided = false;
4206 }
4207 packet.PutCString(":");
4208 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4209 continue; // go back to the while loop and send "packet" and wait
4210 // for another response
4211 }
4212 }
4213 }
4214 }
4215 // If we make it here, the symbol request packet response wasn't valid or
4216 // our symbol lookup failed so we must abort
4217 return;
4218
4219 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4220 LLDB_LOGF(log,
4221 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4222 __FUNCTION__);
4223 }
4224 }
4225}
4226
4230 // Query the server for the array of supported asynchronous JSON packets.
4232
4233 Log *log = GetLog(GDBRLog::Process);
4234
4235 // Poll it now.
4236 StringExtractorGDBRemote response;
4237 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4242 !m_supported_async_json_packets_sp->GetAsArray()) {
4243 // We were returned something other than a JSON array. This is
4244 // invalid. Clear it out.
4245 LLDB_LOGF(log,
4246 "GDBRemoteCommunicationClient::%s(): "
4247 "QSupportedAsyncJSONPackets returned invalid "
4248 "result: %s",
4249 __FUNCTION__, response.GetStringRef().data());
4251 }
4252 } else {
4253 LLDB_LOGF(log,
4254 "GDBRemoteCommunicationClient::%s(): "
4255 "QSupportedAsyncJSONPackets unsupported",
4256 __FUNCTION__);
4257 }
4258
4260 StreamString stream;
4262 LLDB_LOGF(log,
4263 "GDBRemoteCommunicationClient::%s(): supported async "
4264 "JSON packets: %s",
4265 __FUNCTION__, stream.GetData());
4266 }
4267 }
4268
4270 ? m_supported_async_json_packets_sp->GetAsArray()
4271 : nullptr;
4272}
4273
4275 llvm::ArrayRef<int32_t> signals) {
4276 // Format packet:
4277 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4278 auto range = llvm::make_range(signals.begin(), signals.end());
4279 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4280
4281 StringExtractorGDBRemote response;
4282 auto send_status = SendPacketAndWaitForResponse(packet, response);
4283
4285 return Status::FromErrorString("Sending QPassSignals packet failed");
4286
4287 if (response.IsOKResponse()) {
4288 return Status();
4289 } else {
4291 "Unknown error happened during sending QPassSignals packet.");
4292 }
4293}
4294
4296 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4297 Status error;
4298
4299 if (type_name.empty()) {
4300 error = Status::FromErrorString("invalid type_name argument");
4301 return error;
4302 }
4303
4304 // Build command: Configure{type_name}: serialized config data.
4305 StreamGDBRemote stream;
4306 stream.PutCString("QConfigure");
4307 stream.PutCString(type_name);
4308 stream.PutChar(':');
4309 if (config_sp) {
4310 // Gather the plain-text version of the configuration data.
4311 StreamString unescaped_stream;
4312 config_sp->Dump(unescaped_stream);
4313 unescaped_stream.Flush();
4314
4315 // Add it to the stream in escaped fashion.
4316 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4317 unescaped_stream.GetSize());
4318 }
4319 stream.Flush();
4320
4321 // Send the packet.
4322 StringExtractorGDBRemote response;
4323 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4324 if (result == PacketResult::Success) {
4325 // We failed if the config result comes back other than OK.
4326 if (response.GetStringRef() == "OK") {
4327 // Okay!
4328 error.Clear();
4329 } else {
4331 "configuring StructuredData feature {0} failed with error {1}",
4332 type_name, response.GetStringRef());
4333 }
4334 } else {
4335 // Can we get more data here on the failure?
4337 "configuring StructuredData feature {0} failed when sending packet: "
4338 "PacketResult={1}",
4339 type_name, (int)result);
4340 }
4341 return error;
4342}
4343
4348
4353 return true;
4354
4355 // If the remote didn't indicate native-signal support explicitly,
4356 // check whether it is an old version of lldb-server.
4357 return GetThreadSuffixSupported();
4358}
4359
4361 StringExtractorGDBRemote response;
4362 GDBRemoteCommunication::ScopedTimeout(*this, seconds(3));
4363
4364 // LLDB server typically sends no response for "k", so we shouldn't try
4365 // to sync on timeout.
4366 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout(), false) !=
4368 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4369 "failed to send k packet");
4370
4371 char packet_cmd = response.GetChar(0);
4372 if (packet_cmd == 'W' || packet_cmd == 'X')
4373 return response.GetHexU8();
4374
4375 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4376 "unexpected response to k packet: %s",
4377 response.GetStringRef().str().c_str());
4378}
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:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
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:367
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:457
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:739
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition ArchSpec.cpp:843
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:57
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:374
@ eOpenOptionReadOnly
Definition File.h:51
void SetFlash(OptionalBool val)
void SetMapped(OptionalBool val)
void SetBlocksize(lldb::offset_t blocksize)
void SetMemoryTagged(OptionalBool val)
void SetReadable(OptionalBool val)
void SetExecutable(OptionalBool val)
void SetIsStackMemory(OptionalBool val)
void SetName(const char *name)
void SetWritable(OptionalBool val)
lldb::offset_t GetBlocksize() const
void SetDirtyPageList(std::vector< lldb::addr_t > pagelist)
void SetIsShadowStack(OptionalBool val)
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:60
bool ProcessIDIsValid() const
Definition ProcessInfo.h:72
void SetArg0(llvm::StringRef arg)
const char * GetName() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:70
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:43
uint32_t GetUserID() const
Definition ProcessInfo.h:50
uint32_t GetGroupID() const
Definition ProcessInfo.h:52
void SetUserID(uint32_t uid)
Definition ProcessInfo.h:58
bool GroupIDIsValid() const
Definition ProcessInfo.h:56
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:62
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:354
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1250
An error handling class.
Definition Status.h:118
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 PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:28
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)
Definition Stream.h:364
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:406
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:65
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:1141
const ArchSpec & GetArchitecture() const
Definition Target.h:1183
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 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)
bool SetCurrentThread(uint64_t tid, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
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)
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)
int SendStdinNotification(const char *data, size_t data_len)
Sends a GDB remote protocol 'I' packet that delivers stdin data to the remote process.
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)
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:332
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
llvm::json::Value toJSON(const TraceSupportedResponse &packet)
@ 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:83
ByteOrder
Byte ordering definitions.
uint64_t user_id_t
Definition lldb-types.h:82
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:84
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