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'))
1613 region_info.SetReadable(eLazyBoolYes);
1614 else
1615 region_info.SetReadable(eLazyBoolNo);
1616
1617 if (value.contains('w'))
1618 region_info.SetWritable(eLazyBoolYes);
1619 else
1620 region_info.SetWritable(eLazyBoolNo);
1621
1622 if (value.contains('x'))
1623 region_info.SetExecutable(eLazyBoolYes);
1624 else
1625 region_info.SetExecutable(eLazyBoolNo);
1626
1627 region_info.SetMapped(eLazyBoolYes);
1628 } else {
1629 // The reported region does not contain this address -- we're
1630 // looking at an unmapped page
1631 region_info.SetReadable(eLazyBoolNo);
1632 region_info.SetWritable(eLazyBoolNo);
1633 region_info.SetExecutable(eLazyBoolNo);
1634 region_info.SetMapped(eLazyBoolNo);
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") {
1642 region_info.SetMemoryTagged(eLazyBoolNo);
1643 region_info.SetIsShadowStack(eLazyBoolNo);
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")
1653 region_info.SetMemoryTagged(eLazyBoolYes);
1654 else if (flag == "ss")
1655 region_info.SetIsShadowStack(eLazyBoolYes);
1656 }
1657 }
1658 } else if (name == "type") {
1659 for (llvm::StringRef entry : llvm::split(value, ',')) {
1660 if (entry == "stack")
1661 region_info.SetIsStackMemory(eLazyBoolYes);
1662 else if (entry == "heap")
1663 region_info.SetIsStackMemory(eLazyBoolNo);
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 } else if (name == "protection-key") {
1681 unsigned protection_key = 0;
1682 if (!value.getAsInteger(10, protection_key))
1683 region_info.SetProtectionKey(protection_key);
1684 }
1685 }
1686
1687 if (m_target_vm_page_size != 0)
1689
1690 if (region_info.GetRange().IsValid()) {
1691 // We got a valid address range back but no permissions -- which means
1692 // this is an unmapped page
1693 if (!saw_permissions) {
1694 region_info.SetReadable(eLazyBoolNo);
1695 region_info.SetWritable(eLazyBoolNo);
1696 region_info.SetExecutable(eLazyBoolNo);
1697 region_info.SetMapped(eLazyBoolNo);
1698 }
1699 } else {
1700 // We got an invalid address range back
1701 error = Status::FromErrorString("Server returned invalid range");
1702 }
1703 } else {
1705 }
1706 }
1707
1709 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1710 }
1711
1712 // Try qXfer:memory-map:read to get region information not included in
1713 // qMemoryRegionInfo
1714 MemoryRegionInfo qXfer_region_info;
1715 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1716
1717 if (error.Fail()) {
1718 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1719 // the qXfer result as a fallback
1720 if (qXfer_error.Success()) {
1721 region_info = qXfer_region_info;
1722 error.Clear();
1723 } else {
1724 region_info.Clear();
1725 }
1726 } else if (qXfer_error.Success()) {
1727 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1728 // both regions are the same range, update the result to include the flash-
1729 // memory information that is specific to the qXfer result.
1730 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1731 region_info.SetFlash(qXfer_region_info.GetFlash());
1732 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1733 }
1734 }
1735 return error;
1736}
1737
1739 lldb::addr_t addr, MemoryRegionInfo &region) {
1741 if (!error.Success())
1742 return error;
1743 for (const auto &map_region : m_qXfer_memory_map) {
1744 if (map_region.GetRange().Contains(addr)) {
1745 region = map_region;
1746 return error;
1747 }
1748 }
1749 error = Status::FromErrorString("Region not found");
1750 return error;
1751}
1752
1754
1755 Status error;
1756
1758 // Already loaded, return success
1759 return error;
1760
1761 if (!XMLDocument::XMLEnabled()) {
1762 error = Status::FromErrorString("XML is not supported");
1763 return error;
1764 }
1765
1767 error = Status::FromErrorString("Memory map is not supported");
1768 return error;
1769 }
1770
1771 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1772 if (!xml)
1773 return Status::FromError(xml.takeError());
1774
1775 XMLDocument xml_document;
1776
1777 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1778 error = Status::FromErrorString("Failed to parse memory map xml");
1779 return error;
1780 }
1781
1782 XMLNode map_node = xml_document.GetRootElement("memory-map");
1783 if (!map_node) {
1784 error = Status::FromErrorString("Invalid root node in memory map xml");
1785 return error;
1786 }
1787
1788 m_qXfer_memory_map.clear();
1789
1790 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1791 if (!memory_node.IsElement())
1792 return true;
1793 if (memory_node.GetName() != "memory")
1794 return true;
1795 auto type = memory_node.GetAttributeValue("type", "");
1796 uint64_t start;
1797 uint64_t length;
1798 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1799 return true;
1800 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1801 return true;
1802 MemoryRegionInfo region;
1803 region.GetRange().SetRangeBase(start);
1804 region.GetRange().SetByteSize(length);
1805 if (type == "rom") {
1806 region.SetReadable(eLazyBoolYes);
1807 this->m_qXfer_memory_map.push_back(region);
1808 } else if (type == "ram") {
1809 region.SetReadable(eLazyBoolYes);
1810 region.SetWritable(eLazyBoolYes);
1811 this->m_qXfer_memory_map.push_back(region);
1812 } else if (type == "flash") {
1813 region.SetFlash(eLazyBoolYes);
1814 memory_node.ForEachChildElement(
1815 [&region](const XMLNode &prop_node) -> bool {
1816 if (!prop_node.IsElement())
1817 return true;
1818 if (prop_node.GetName() != "property")
1819 return true;
1820 auto propname = prop_node.GetAttributeValue("name", "");
1821 if (propname == "blocksize") {
1822 uint64_t blocksize;
1823 if (prop_node.GetElementTextAsUnsigned(blocksize))
1824 region.SetBlocksize(blocksize);
1825 }
1826 return true;
1827 });
1828 this->m_qXfer_memory_map.push_back(region);
1829 }
1830 return true;
1831 });
1832
1834
1835 return error;
1836}
1837
1841 }
1842
1843 std::optional<uint32_t> num;
1845 StringExtractorGDBRemote response;
1846 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
1849 llvm::StringRef name;
1850 llvm::StringRef value;
1851 while (response.GetNameColonValue(name, value)) {
1852 if (name == "num") {
1853 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1855 }
1856 }
1857 if (!num) {
1859 }
1860 } else {
1862 }
1863 }
1864
1865 return num;
1866}
1867
1868WatchpointHardwareFeature
1872
1875 GetHostInfo();
1876
1877 // Process determines this by target CPU, but allow for the
1878 // remote stub to override it via the qHostInfo
1879 // watchpoint_exceptions_received key, if it is present.
1882 return false;
1884 return true;
1885 }
1886
1887 return std::nullopt;
1888}
1889
1891 if (file_spec) {
1892 std::string path{file_spec.GetPath(false)};
1893 StreamString packet;
1894 packet.PutCString("QSetSTDIN:");
1895 packet.PutStringAsRawHex8(path);
1896
1897 StringExtractorGDBRemote response;
1898 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1900 if (response.IsOKResponse())
1901 return 0;
1902 uint8_t error = response.GetError();
1903 if (error)
1904 return error;
1905 }
1906 }
1907 return -1;
1908}
1909
1911 if (file_spec) {
1912 std::string path{file_spec.GetPath(false)};
1913 StreamString packet;
1914 packet.PutCString("QSetSTDOUT:");
1915 packet.PutStringAsRawHex8(path);
1916
1917 StringExtractorGDBRemote response;
1918 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1920 if (response.IsOKResponse())
1921 return 0;
1922 uint8_t error = response.GetError();
1923 if (error)
1924 return error;
1925 }
1926 }
1927 return -1;
1928}
1929
1931 if (file_spec) {
1932 std::string path{file_spec.GetPath(false)};
1933 StreamString packet;
1934 packet.PutCString("QSetSTDERR:");
1935 packet.PutStringAsRawHex8(path);
1936
1937 StringExtractorGDBRemote response;
1938 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1940 if (response.IsOKResponse())
1941 return 0;
1942 uint8_t error = response.GetError();
1943 if (error)
1944 return error;
1945 }
1946 }
1947 return -1;
1948}
1949
1951 StringExtractorGDBRemote response;
1952 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
1954 if (response.IsUnsupportedResponse())
1955 return false;
1956 if (response.IsErrorResponse())
1957 return false;
1958 std::string cwd;
1959 response.GetHexByteString(cwd);
1960 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1961 return !cwd.empty();
1962 }
1963 return false;
1964}
1965
1967 if (working_dir) {
1968 std::string path{working_dir.GetPath(false)};
1969 StreamString packet;
1970 packet.PutCString("QSetWorkingDir:");
1971 packet.PutStringAsRawHex8(path);
1972
1973 StringExtractorGDBRemote response;
1974 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1976 if (response.IsOKResponse())
1977 return 0;
1978 uint8_t error = response.GetError();
1979 if (error)
1980 return error;
1981 }
1982 }
1983 return -1;
1984}
1985
1987 char packet[32];
1988 const int packet_len =
1989 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1990 assert(packet_len < (int)sizeof(packet));
1991 UNUSED_IF_ASSERT_DISABLED(packet_len);
1992 StringExtractorGDBRemote response;
1993 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
1994 if (response.IsOKResponse())
1995 return 0;
1996 uint8_t error = response.GetError();
1997 if (error)
1998 return error;
1999 }
2000 return -1;
2001}
2002
2004 char packet[32];
2005 const int packet_len = ::snprintf(packet, sizeof(packet),
2006 "QSetDetachOnError:%i", enable ? 1 : 0);
2007 assert(packet_len < (int)sizeof(packet));
2008 UNUSED_IF_ASSERT_DISABLED(packet_len);
2009 StringExtractorGDBRemote response;
2010 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2011 if (response.IsOKResponse())
2012 return 0;
2013 uint8_t error = response.GetError();
2014 if (error)
2015 return error;
2016 }
2017 return -1;
2018}
2019
2021 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2022 if (response.IsNormalResponse()) {
2023 llvm::StringRef name;
2024 llvm::StringRef value;
2025 StringExtractor extractor;
2026
2027 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2028 uint32_t sub = 0;
2029 std::string vendor;
2030 std::string os_type;
2031
2032 while (response.GetNameColonValue(name, value)) {
2033 if (name == "pid") {
2035 value.getAsInteger(0, pid);
2036 process_info.SetProcessID(pid);
2037 } else if (name == "ppid") {
2039 value.getAsInteger(0, pid);
2040 process_info.SetParentProcessID(pid);
2041 } else if (name == "uid") {
2042 uint32_t uid = UINT32_MAX;
2043 value.getAsInteger(0, uid);
2044 process_info.SetUserID(uid);
2045 } else if (name == "euid") {
2046 uint32_t uid = UINT32_MAX;
2047 value.getAsInteger(0, uid);
2048 process_info.SetEffectiveUserID(uid);
2049 } else if (name == "gid") {
2050 uint32_t gid = UINT32_MAX;
2051 value.getAsInteger(0, gid);
2052 process_info.SetGroupID(gid);
2053 } else if (name == "egid") {
2054 uint32_t gid = UINT32_MAX;
2055 value.getAsInteger(0, gid);
2056 process_info.SetEffectiveGroupID(gid);
2057 } else if (name == "triple") {
2058 StringExtractor extractor(value);
2059 std::string triple;
2060 extractor.GetHexByteString(triple);
2061 process_info.GetArchitecture().SetTriple(triple.c_str());
2062 } else if (name == "name") {
2063 StringExtractor extractor(value);
2064 // The process name from ASCII hex bytes since we can't control the
2065 // characters in a process name
2066 std::string name;
2067 extractor.GetHexByteString(name);
2068 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2069 } else if (name == "args") {
2070 llvm::StringRef encoded_args(value), hex_arg;
2071
2072 bool is_arg0 = true;
2073 while (!encoded_args.empty()) {
2074 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2075 std::string arg;
2076 StringExtractor extractor(hex_arg);
2077 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2078 // In case of wrong encoding, we discard all the arguments
2079 process_info.GetArguments().Clear();
2080 process_info.SetArg0("");
2081 break;
2082 }
2083 if (is_arg0)
2084 process_info.SetArg0(arg);
2085 else
2086 process_info.GetArguments().AppendArgument(arg);
2087 is_arg0 = false;
2088 }
2089 } else if (name == "cputype") {
2090 value.getAsInteger(0, cpu);
2091 } else if (name == "cpusubtype") {
2092 value.getAsInteger(0, sub);
2093 } else if (name == "vendor") {
2094 vendor = std::string(value);
2095 } else if (name == "ostype") {
2096 os_type = std::string(value);
2097 }
2098 }
2099
2100 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2101 if (vendor == "apple") {
2103 sub);
2104 process_info.GetArchitecture().GetTriple().setVendorName(
2105 llvm::StringRef(vendor));
2106 process_info.GetArchitecture().GetTriple().setOSName(
2107 llvm::StringRef(os_type));
2108 }
2109 }
2110
2111 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2112 return true;
2113 }
2114 return false;
2115}
2116
2118 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2119 process_info.Clear();
2120
2122 char packet[32];
2123 const int packet_len =
2124 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2125 assert(packet_len < (int)sizeof(packet));
2126 UNUSED_IF_ASSERT_DISABLED(packet_len);
2127 StringExtractorGDBRemote response;
2128 if (SendPacketAndWaitForResponse(packet, response) ==
2130 return DecodeProcessInfoResponse(response, process_info);
2131 } else {
2133 return false;
2134 }
2135 }
2136 return false;
2137}
2138
2141
2142 if (allow_lazy) {
2144 return true;
2146 return false;
2147 }
2148
2149 GetHostInfo();
2150
2151 StringExtractorGDBRemote response;
2152 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2154 if (response.IsNormalResponse()) {
2155 llvm::StringRef name;
2156 llvm::StringRef value;
2157 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2158 uint32_t sub = 0;
2159 std::string os_name;
2160 std::string environment;
2161 std::string vendor_name;
2162 std::string triple;
2163 std::string elf_abi;
2164 uint32_t pointer_byte_size = 0;
2165 StringExtractor extractor;
2166 ByteOrder byte_order = eByteOrderInvalid;
2167 uint32_t num_keys_decoded = 0;
2169 while (response.GetNameColonValue(name, value)) {
2170 if (name == "cputype") {
2171 if (!value.getAsInteger(16, cpu))
2172 ++num_keys_decoded;
2173 } else if (name == "cpusubtype") {
2174 if (!value.getAsInteger(16, sub)) {
2175 ++num_keys_decoded;
2176 // Workaround for pre-2024 Apple debugserver, which always
2177 // returns arm64e on arm64e-capable hardware regardless of
2178 // what the process is. This can be deleted at some point
2179 // in the future.
2180 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2181 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2182 if (GetGDBServerVersion())
2183 if (m_gdb_server_version >= 1000 &&
2184 m_gdb_server_version <= 1504)
2185 sub = 0;
2186 }
2187 }
2188 } else if (name == "triple") {
2189 StringExtractor extractor(value);
2190 extractor.GetHexByteString(triple);
2191 ++num_keys_decoded;
2192 } else if (name == "ostype") {
2193 ParseOSType(value, os_name, environment);
2194 ++num_keys_decoded;
2195 } else if (name == "vendor") {
2196 vendor_name = std::string(value);
2197 ++num_keys_decoded;
2198 } else if (name == "endian") {
2199 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2200 .Case("little", eByteOrderLittle)
2201 .Case("big", eByteOrderBig)
2202 .Case("pdp", eByteOrderPDP)
2203 .Default(eByteOrderInvalid);
2204 if (byte_order != eByteOrderInvalid)
2205 ++num_keys_decoded;
2206 } else if (name == "ptrsize") {
2207 if (!value.getAsInteger(16, pointer_byte_size))
2208 ++num_keys_decoded;
2209 } else if (name == "pid") {
2210 if (!value.getAsInteger(16, pid))
2211 ++num_keys_decoded;
2212 } else if (name == "elf_abi") {
2213 elf_abi = std::string(value);
2214 ++num_keys_decoded;
2215 } else if (name == "main-binary-uuid") {
2216 m_process_standalone_uuid.SetFromStringRef(value);
2217 ++num_keys_decoded;
2218 } else if (name == "main-binary-slide") {
2219 StringExtractor extractor(value);
2221 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2224 ++num_keys_decoded;
2225 }
2226 } else if (name == "main-binary-address") {
2227 StringExtractor extractor(value);
2229 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2232 ++num_keys_decoded;
2233 }
2234 } else if (name == "binary-addresses") {
2235 m_binary_addresses.clear();
2236 ++num_keys_decoded;
2237 for (llvm::StringRef x : llvm::split(value, ',')) {
2238 addr_t vmaddr;
2239 x.consume_front("0x");
2240 if (llvm::to_integer(x, vmaddr, 16))
2241 m_binary_addresses.push_back(vmaddr);
2242 }
2243 }
2244 }
2245 if (num_keys_decoded > 0)
2247 if (pid != LLDB_INVALID_PROCESS_ID) {
2249 m_curr_pid_run = m_curr_pid = pid;
2250 }
2251
2252 // Set the ArchSpec from the triple if we have it.
2253 if (!triple.empty()) {
2254 m_process_arch.SetTriple(triple.c_str());
2255 m_process_arch.SetFlags(elf_abi);
2256 if (pointer_byte_size) {
2257 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2258 }
2259 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2260 !vendor_name.empty()) {
2261 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2262 if (!environment.empty())
2263 triple.setEnvironmentName(environment);
2264
2265 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2266 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2267 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2268 switch (triple.getObjectFormat()) {
2269 case llvm::Triple::MachO:
2270 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2271 break;
2272 case llvm::Triple::ELF:
2273 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2274 break;
2275 case llvm::Triple::COFF:
2276 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2277 break;
2278 case llvm::Triple::GOFF:
2279 case llvm::Triple::SPIRV:
2280 case llvm::Triple::Wasm:
2281 case llvm::Triple::XCOFF:
2282 case llvm::Triple::DXContainer:
2283 LLDB_LOGF(log, "error: not supported target architecture");
2284 return false;
2285 case llvm::Triple::UnknownObjectFormat:
2286 LLDB_LOGF(log, "error: failed to determine target architecture");
2287 return false;
2288 }
2289
2290 if (pointer_byte_size) {
2291 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2292 }
2293 if (byte_order != eByteOrderInvalid) {
2294 assert(byte_order == m_process_arch.GetByteOrder());
2295 }
2296 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2297 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2298 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2299 }
2300 return true;
2301 }
2302 } else {
2304 }
2305
2306 return false;
2307}
2308
2310 const ProcessInstanceInfoMatch &match_info,
2311 ProcessInstanceInfoList &process_infos) {
2312 process_infos.clear();
2313
2315 StreamString packet;
2316 packet.PutCString("qfProcessInfo");
2317 if (!match_info.MatchAllProcesses()) {
2318 packet.PutChar(':');
2319 const char *name = match_info.GetProcessInfo().GetName();
2320 bool has_name_match = false;
2321 if (name && name[0]) {
2322 has_name_match = true;
2323 NameMatch name_match_type = match_info.GetNameMatchType();
2324 switch (name_match_type) {
2325 case NameMatch::Ignore:
2326 has_name_match = false;
2327 break;
2328
2329 case NameMatch::Equals:
2330 packet.PutCString("name_match:equals;");
2331 break;
2332
2334 packet.PutCString("name_match:contains;");
2335 break;
2336
2338 packet.PutCString("name_match:starts_with;");
2339 break;
2340
2342 packet.PutCString("name_match:ends_with;");
2343 break;
2344
2346 packet.PutCString("name_match:regex;");
2347 break;
2348 }
2349 if (has_name_match) {
2350 packet.PutCString("name:");
2351 packet.PutBytesAsRawHex8(name, ::strlen(name));
2352 packet.PutChar(';');
2353 }
2354 }
2355
2356 if (match_info.GetProcessInfo().ProcessIDIsValid())
2357 packet.Printf("pid:%" PRIu64 ";",
2358 match_info.GetProcessInfo().GetProcessID());
2359 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2360 packet.Printf("parent_pid:%" PRIu64 ";",
2361 match_info.GetProcessInfo().GetParentProcessID());
2362 if (match_info.GetProcessInfo().UserIDIsValid())
2363 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2364 if (match_info.GetProcessInfo().GroupIDIsValid())
2365 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2366 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2367 packet.Printf("euid:%u;",
2368 match_info.GetProcessInfo().GetEffectiveUserID());
2369 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2370 packet.Printf("egid:%u;",
2371 match_info.GetProcessInfo().GetEffectiveGroupID());
2372 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2373 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2374 const ArchSpec &match_arch =
2375 match_info.GetProcessInfo().GetArchitecture();
2376 const llvm::Triple &triple = match_arch.GetTriple();
2377 packet.PutCString("triple:");
2378 packet.PutCString(triple.getTriple());
2379 packet.PutChar(';');
2380 }
2381 }
2382 StringExtractorGDBRemote response;
2383 // Increase timeout as the first qfProcessInfo packet takes a long time on
2384 // Android. The value of 1min was arrived at empirically.
2385 ScopedTimeout timeout(*this, minutes(1));
2386 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2388 do {
2389 ProcessInstanceInfo process_info;
2390 if (!DecodeProcessInfoResponse(response, process_info))
2391 break;
2392 process_infos.push_back(process_info);
2393 response = StringExtractorGDBRemote();
2394 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2396 } else {
2398 return 0;
2399 }
2400 }
2401 return process_infos.size();
2402}
2403
2405 std::string &name) {
2407 char packet[32];
2408 const int packet_len =
2409 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2410 assert(packet_len < (int)sizeof(packet));
2411 UNUSED_IF_ASSERT_DISABLED(packet_len);
2412 StringExtractorGDBRemote response;
2413 if (SendPacketAndWaitForResponse(packet, response) ==
2415 if (response.IsNormalResponse()) {
2416 // Make sure we parsed the right number of characters. The response is
2417 // the hex encoded user name and should make up the entire packet. If
2418 // there are any non-hex ASCII bytes, the length won't match below..
2419 if (response.GetHexByteString(name) * 2 ==
2420 response.GetStringRef().size())
2421 return true;
2422 }
2423 } else {
2424 m_supports_qUserName = false;
2425 return false;
2426 }
2427 }
2428 return false;
2429}
2430
2432 std::string &name) {
2434 char packet[32];
2435 const int packet_len =
2436 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2437 assert(packet_len < (int)sizeof(packet));
2438 UNUSED_IF_ASSERT_DISABLED(packet_len);
2439 StringExtractorGDBRemote response;
2440 if (SendPacketAndWaitForResponse(packet, response) ==
2442 if (response.IsNormalResponse()) {
2443 // Make sure we parsed the right number of characters. The response is
2444 // the hex encoded group name and should make up the entire packet. If
2445 // there are any non-hex ASCII bytes, the length won't match below..
2446 if (response.GetHexByteString(name) * 2 ==
2447 response.GetStringRef().size())
2448 return true;
2449 }
2450 } else {
2451 m_supports_qGroupName = false;
2452 return false;
2453 }
2454 }
2455 return false;
2456}
2457
2458static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2459 uint32_t recv_size) {
2460 packet.Clear();
2461 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2462 uint32_t bytes_left = send_size;
2463 while (bytes_left > 0) {
2464 if (bytes_left >= 26) {
2465 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2466 bytes_left -= 26;
2467 } else {
2468 packet.Printf("%*.*s;", bytes_left, bytes_left,
2469 "abcdefghijklmnopqrstuvwxyz");
2470 bytes_left = 0;
2471 }
2472 }
2473}
2474
2475duration<float>
2476calculate_standard_deviation(const std::vector<duration<float>> &v) {
2477 if (v.size() == 0)
2478 return duration<float>::zero();
2479 using Dur = duration<float>;
2480 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2481 Dur mean = sum / v.size();
2482 float accum = 0;
2483 for (auto d : v) {
2484 float delta = (d - mean).count();
2485 accum += delta * delta;
2486 };
2487
2488 return Dur(sqrtf(accum / (v.size() - 1)));
2489}
2490
2492 uint32_t max_send,
2493 uint32_t max_recv,
2494 uint64_t recv_amount,
2495 bool json, Stream &strm) {
2496
2497 if (SendSpeedTestPacket(0, 0)) {
2498 StreamString packet;
2499 if (json)
2500 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2501 "\"results\" : [",
2502 num_packets);
2503 else
2504 strm.Printf("Testing sending %u packets of various sizes:\n",
2505 num_packets);
2506 strm.Flush();
2507
2508 uint32_t result_idx = 0;
2509 uint32_t send_size;
2510 std::vector<duration<float>> packet_times;
2511
2512 for (send_size = 0; send_size <= max_send;
2513 send_size ? send_size *= 2 : send_size = 4) {
2514 for (uint32_t recv_size = 0; recv_size <= max_recv;
2515 recv_size ? recv_size *= 2 : recv_size = 4) {
2516 MakeSpeedTestPacket(packet, send_size, recv_size);
2517
2518 packet_times.clear();
2519 // Test how long it takes to send 'num_packets' packets
2520 const auto start_time = steady_clock::now();
2521 for (uint32_t i = 0; i < num_packets; ++i) {
2522 const auto packet_start_time = steady_clock::now();
2523 StringExtractorGDBRemote response;
2524 SendPacketAndWaitForResponse(packet.GetString(), response);
2525 const auto packet_end_time = steady_clock::now();
2526 packet_times.push_back(packet_end_time - packet_start_time);
2527 }
2528 const auto end_time = steady_clock::now();
2529 const auto total_time = end_time - start_time;
2530
2531 float packets_per_second =
2532 ((float)num_packets) / duration<float>(total_time).count();
2533 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2534 : duration<float>::zero();
2535 const duration<float> standard_deviation =
2536 calculate_standard_deviation(packet_times);
2537 if (json) {
2538 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2539 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2540 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2541 result_idx > 0 ? "," : "", send_size, recv_size,
2542 total_time, standard_deviation);
2543 ++result_idx;
2544 } else {
2545 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2546 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2547 "standard deviation of {5,10:ms+f6}\n",
2548 send_size, recv_size, duration<float>(total_time),
2549 packets_per_second, duration<float>(average_per_packet),
2550 standard_deviation);
2551 }
2552 strm.Flush();
2553 }
2554 }
2555
2556 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2557 if (json)
2558 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2559 ": %" PRIu64 ",\n \"results\" : [",
2560 recv_amount);
2561 else
2562 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2563 "packet sizes:\n",
2564 k_recv_amount_mb);
2565 strm.Flush();
2566 send_size = 0;
2567 result_idx = 0;
2568 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2569 MakeSpeedTestPacket(packet, send_size, recv_size);
2570
2571 // If we have a receive size, test how long it takes to receive 4MB of
2572 // data
2573 if (recv_size > 0) {
2574 const auto start_time = steady_clock::now();
2575 uint32_t bytes_read = 0;
2576 uint32_t packet_count = 0;
2577 while (bytes_read < recv_amount) {
2578 StringExtractorGDBRemote response;
2579 SendPacketAndWaitForResponse(packet.GetString(), response);
2580 bytes_read += recv_size;
2581 ++packet_count;
2582 }
2583 const auto end_time = steady_clock::now();
2584 const auto total_time = end_time - start_time;
2585 float mb_second = ((float)recv_amount) /
2586 duration<float>(total_time).count() /
2587 (1024.0 * 1024.0);
2588 float packets_per_second =
2589 ((float)packet_count) / duration<float>(total_time).count();
2590 const auto average_per_packet = packet_count > 0
2591 ? total_time / packet_count
2592 : duration<float>::zero();
2593
2594 if (json) {
2595 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2596 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2597 result_idx > 0 ? "," : "", send_size, recv_size,
2598 total_time);
2599 ++result_idx;
2600 } else {
2601 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2602 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2603 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2604 send_size, recv_size, packet_count, k_recv_amount_mb,
2605 duration<float>(total_time), mb_second,
2606 packets_per_second, duration<float>(average_per_packet));
2607 }
2608 strm.Flush();
2609 }
2610 }
2611 if (json)
2612 strm.Printf("\n ]\n }\n}\n");
2613 else
2614 strm.EOL();
2615 }
2616}
2617
2619 uint32_t recv_size) {
2620 StreamString packet;
2621 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2622 uint32_t bytes_left = send_size;
2623 while (bytes_left > 0) {
2624 if (bytes_left >= 26) {
2625 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2626 bytes_left -= 26;
2627 } else {
2628 packet.Printf("%*.*s;", bytes_left, bytes_left,
2629 "abcdefghijklmnopqrstuvwxyz");
2630 bytes_left = 0;
2631 }
2632 }
2633
2634 StringExtractorGDBRemote response;
2635 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2637}
2638
2640 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2641 std::string &socket_name) {
2643 port = 0;
2644 socket_name.clear();
2645
2646 StringExtractorGDBRemote response;
2647 StreamString stream;
2648 stream.PutCString("qLaunchGDBServer;");
2649 std::string hostname;
2650 if (remote_accept_hostname && remote_accept_hostname[0])
2651 hostname = remote_accept_hostname;
2652 else {
2653 if (HostInfo::GetHostname(hostname)) {
2654 // Make the GDB server we launch only accept connections from this host
2655 stream.Printf("host:%s;", hostname.c_str());
2656 } else {
2657 // Make the GDB server we launch accept connections from any host since
2658 // we can't figure out the hostname
2659 stream.Printf("host:*;");
2660 }
2661 }
2662 // give the process a few seconds to startup
2663 ScopedTimeout timeout(*this, seconds(10));
2664
2665 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2667 if (response.IsErrorResponse())
2668 return false;
2669
2670 llvm::StringRef name;
2671 llvm::StringRef value;
2672 while (response.GetNameColonValue(name, value)) {
2673 if (name == "port")
2674 value.getAsInteger(0, port);
2675 else if (name == "pid")
2676 value.getAsInteger(0, pid);
2677 else if (name.compare("socket_name") == 0) {
2678 StringExtractor extractor(value);
2679 extractor.GetHexByteString(socket_name);
2680 }
2681 }
2682 return true;
2683 }
2684 return false;
2685}
2686
2688 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2689 connection_urls.clear();
2690
2691 StringExtractorGDBRemote response;
2692 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2694 return 0;
2695
2698 if (!data)
2699 return 0;
2700
2701 StructuredData::Array *array = data->GetAsArray();
2702 if (!array)
2703 return 0;
2704
2705 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2706 std::optional<StructuredData::Dictionary *> maybe_element =
2708 if (!maybe_element)
2709 continue;
2710
2711 StructuredData::Dictionary *element = *maybe_element;
2712 uint16_t port = 0;
2713 if (StructuredData::ObjectSP port_osp =
2714 element->GetValueForKey(llvm::StringRef("port")))
2715 port = port_osp->GetUnsignedIntegerValue(0);
2716
2717 std::string socket_name;
2718 if (StructuredData::ObjectSP socket_name_osp =
2719 element->GetValueForKey(llvm::StringRef("socket_name")))
2720 socket_name = std::string(socket_name_osp->GetStringValue());
2721
2722 if (port != 0 || !socket_name.empty())
2723 connection_urls.emplace_back(port, socket_name);
2724 }
2725 return connection_urls.size();
2726}
2727
2729 StreamString stream;
2730 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2731
2732 StringExtractorGDBRemote response;
2733 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2735 if (response.IsOKResponse())
2736 return true;
2737 }
2738 return false;
2739}
2740
2742 uint64_t tid, uint64_t pid, char op) {
2744 packet.PutChar('H');
2745 packet.PutChar(op);
2746
2747 if (pid != LLDB_INVALID_PROCESS_ID)
2748 packet.Printf("p%" PRIx64 ".", pid);
2749
2750 if (tid == UINT64_MAX)
2751 packet.PutCString("-1");
2752 else
2753 packet.Printf("%" PRIx64, tid);
2754
2755 StringExtractorGDBRemote response;
2756 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2758 if (response.IsOKResponse())
2759 return {{pid, tid}};
2760
2761 /*
2762 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2763 * Hg packet.
2764 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2765 * which can
2766 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2767 */
2768 if (response.IsUnsupportedResponse() && IsConnected())
2769 return {{1, 1}};
2770 }
2771 return std::nullopt;
2772}
2773
2775 uint64_t pid) {
2776 if (m_curr_tid == tid &&
2777 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2778 return true;
2779
2780 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2781 if (ret) {
2782 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2783 m_curr_pid = ret->pid;
2784 m_curr_tid = ret->tid;
2785 }
2786 return ret.has_value();
2787}
2788
2790 uint64_t pid) {
2791 if (m_curr_tid_run == tid &&
2792 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2793 return true;
2794
2795 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2796 if (ret) {
2797 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2798 m_curr_pid_run = ret->pid;
2799 m_curr_tid_run = ret->tid;
2800 }
2801 return ret.has_value();
2802}
2803
2805 StringExtractorGDBRemote &response) {
2807 return response.IsNormalResponse();
2808 return false;
2809}
2810
2812 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2814 char packet[256];
2815 int packet_len =
2816 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2817 assert(packet_len < (int)sizeof(packet));
2818 UNUSED_IF_ASSERT_DISABLED(packet_len);
2819 if (SendPacketAndWaitForResponse(packet, response) ==
2821 if (response.IsUnsupportedResponse())
2823 else if (response.IsNormalResponse())
2824 return true;
2825 else
2826 return false;
2827 } else {
2829 }
2830 }
2831 return false;
2832}
2833
2835 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2836 std::chrono::seconds timeout) {
2838 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2839 __FUNCTION__, insert ? "add" : "remove", addr);
2840
2841 // Check if the stub is known not to support this breakpoint type
2842 if (!SupportsGDBStoppointPacket(type))
2843 return UINT8_MAX;
2844 // Construct the breakpoint packet
2845 char packet[64];
2846 const int packet_len =
2847 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2848 insert ? 'Z' : 'z', type, addr, length);
2849 // Check we haven't overwritten the end of the packet buffer
2850 assert(packet_len + 1 < (int)sizeof(packet));
2851 UNUSED_IF_ASSERT_DISABLED(packet_len);
2852 StringExtractorGDBRemote response;
2853 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2854 // or "" (unsupported)
2856 // Try to send the breakpoint packet, and check that it was correctly sent
2857 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
2859 // Receive and OK packet when the breakpoint successfully placed
2860 if (response.IsOKResponse())
2861 return 0;
2862
2863 // Status while setting breakpoint, send back specific error
2864 if (response.IsErrorResponse())
2865 return response.GetError();
2866
2867 // Empty packet informs us that breakpoint is not supported
2868 if (response.IsUnsupportedResponse()) {
2869 // Disable this breakpoint type since it is unsupported
2870 switch (type) {
2872 m_supports_z0 = false;
2873 break;
2875 m_supports_z1 = false;
2876 break;
2877 case eWatchpointWrite:
2878 m_supports_z2 = false;
2879 break;
2880 case eWatchpointRead:
2881 m_supports_z3 = false;
2882 break;
2884 m_supports_z4 = false;
2885 break;
2886 case eStoppointInvalid:
2887 return UINT8_MAX;
2888 }
2889 }
2890 }
2891 // Signal generic failure
2892 return UINT8_MAX;
2893}
2894
2895std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
2897 bool &sequence_mutex_unavailable) {
2898 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
2899
2900 Lock lock(*this);
2901 if (lock) {
2902 sequence_mutex_unavailable = false;
2903 StringExtractorGDBRemote response;
2904
2905 PacketResult packet_result;
2906 for (packet_result =
2907 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2908 packet_result == PacketResult::Success && response.IsNormalResponse();
2909 packet_result =
2910 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2911 char ch = response.GetChar();
2912 if (ch == 'l')
2913 break;
2914 if (ch == 'm') {
2915 do {
2916 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
2917 // If we get an invalid response, break out of the loop.
2918 // If there are valid tids, they have been added to ids.
2919 // If there are no valid tids, we'll fall through to the
2920 // bare-iron target handling below.
2921 if (!pid_tid)
2922 break;
2923
2924 ids.push_back(*pid_tid);
2925 ch = response.GetChar(); // Skip the command separator
2926 } while (ch == ','); // Make sure we got a comma separator
2927 }
2928 }
2929
2930 /*
2931 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2932 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2933 * could
2934 * be as simple as 'S05'. There is no packet which can give us pid and/or
2935 * tid.
2936 * Assume pid=tid=1 in such cases.
2937 */
2938 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2939 ids.size() == 0 && IsConnected()) {
2940 ids.emplace_back(1, 1);
2941 }
2942 } else {
2944 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
2945 "packet 'qfThreadInfo'");
2946 sequence_mutex_unavailable = true;
2947 }
2948
2949 return ids;
2950}
2951
2953 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2955 thread_ids.clear();
2956
2957 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
2958 if (ids.empty() || sequence_mutex_unavailable)
2959 return 0;
2960
2961 for (auto id : ids) {
2962 // skip threads that do not belong to the current process
2963 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
2964 continue;
2965 if (id.second != LLDB_INVALID_THREAD_ID &&
2967 thread_ids.push_back(id.second);
2968 }
2969
2970 return thread_ids.size();
2971}
2972
2974 StringExtractorGDBRemote response;
2975 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
2977 !response.IsNormalResponse())
2978 return LLDB_INVALID_ADDRESS;
2979 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2980}
2981
2983 llvm::StringRef command,
2984 const FileSpec &
2985 working_dir, // Pass empty FileSpec to use the current working directory
2986 int *status_ptr, // Pass NULL if you don't want the process exit status
2987 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2988 // process to exit
2989 std::string
2990 *command_output, // Pass nullptr if you don't want the command output
2991 std::string *separated_error_output, // Pass nullptr if you don't want the
2992 // command error output
2993 const Timeout<std::micro> &timeout) {
2995 stream.PutCString("qPlatform_shell:");
2996 stream.PutBytesAsRawHex8(command.data(), command.size());
2997 stream.PutChar(',');
2998 uint32_t timeout_sec = UINT32_MAX;
2999 if (timeout) {
3000 // TODO: Use chrono version of std::ceil once c++17 is available.
3001 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
3002 }
3003 stream.PutHex32(timeout_sec);
3004 if (working_dir) {
3005 std::string path{working_dir.GetPath(false)};
3006 stream.PutChar(',');
3007 stream.PutStringAsRawHex8(path);
3008 }
3009 StringExtractorGDBRemote response;
3010 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3012 if (response.GetChar() != 'F')
3013 return Status::FromErrorString("malformed reply");
3014 if (response.GetChar() != ',')
3015 return Status::FromErrorString("malformed reply");
3016 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3017 if (exitcode == UINT32_MAX)
3018 return Status::FromErrorString("unable to run remote process");
3019 else if (status_ptr)
3020 *status_ptr = exitcode;
3021 if (response.GetChar() != ',')
3022 return Status::FromErrorString("malformed reply");
3023 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3024 if (signo_ptr)
3025 *signo_ptr = signo;
3026 if (response.GetChar() != ',')
3027 return Status::FromErrorString("malformed reply");
3028 std::string output;
3029 response.GetEscapedBinaryData(output);
3030 if (command_output)
3031 command_output->assign(output);
3032 return Status();
3033 }
3034 return Status::FromErrorString("unable to send packet");
3035}
3036
3038 uint32_t file_permissions) {
3039 std::string path{file_spec.GetPath(false)};
3041 stream.PutCString("qPlatform_mkdir:");
3042 stream.PutHex32(file_permissions);
3043 stream.PutChar(',');
3044 stream.PutStringAsRawHex8(path);
3045 llvm::StringRef packet = stream.GetString();
3046 StringExtractorGDBRemote response;
3047
3048 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3049 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3050 packet.str().c_str());
3051
3052 if (response.GetChar() != 'F')
3053 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3054 packet.str().c_str());
3055
3056 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3057}
3058
3059Status
3061 uint32_t file_permissions) {
3062 std::string path{file_spec.GetPath(false)};
3064 stream.PutCString("qPlatform_chmod:");
3065 stream.PutHex32(file_permissions);
3066 stream.PutChar(',');
3067 stream.PutStringAsRawHex8(path);
3068 llvm::StringRef packet = stream.GetString();
3069 StringExtractorGDBRemote response;
3070
3071 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3072 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3073 stream.GetData());
3074
3075 if (response.GetChar() != 'F')
3076 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3077 stream.GetData());
3078
3079 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3080}
3081
3082static int gdb_errno_to_system(int err) {
3083 switch (err) {
3084#define HANDLE_ERRNO(name, value) \
3085 case GDB_##name: \
3086 return name;
3087#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3088 default:
3089 return -1;
3090 }
3091}
3092
3094 uint64_t fail_result, Status &error) {
3095 response.SetFilePos(0);
3096 if (response.GetChar() != 'F')
3097 return fail_result;
3098 int32_t result = response.GetS32(-2, 16);
3099 if (result == -2)
3100 return fail_result;
3101 if (response.GetChar() == ',') {
3102 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3103 if (result_errno != -1)
3104 error = Status(result_errno, eErrorTypePOSIX);
3105 else
3107 } else
3108 error.Clear();
3109 return result;
3110}
3113 File::OpenOptions flags, mode_t mode,
3114 Status &error) {
3115 std::string path(file_spec.GetPath(false));
3117 stream.PutCString("vFile:open:");
3118 if (path.empty())
3119 return UINT64_MAX;
3120 stream.PutStringAsRawHex8(path);
3121 stream.PutChar(',');
3122 stream.PutHex32(flags);
3123 stream.PutChar(',');
3124 stream.PutHex32(mode);
3125 StringExtractorGDBRemote response;
3126 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3128 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3129 }
3130 return UINT64_MAX;
3131}
3132
3134 Status &error) {
3136 stream.Printf("vFile:close:%x", (int)fd);
3137 StringExtractorGDBRemote response;
3138 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3140 return ParseHostIOPacketResponse(response, -1, error) == 0;
3141 }
3142 return false;
3143}
3144
3145std::optional<GDBRemoteFStatData>
3148 stream.Printf("vFile:fstat:%" PRIx64, fd);
3149 StringExtractorGDBRemote response;
3150 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3152 if (response.GetChar() != 'F')
3153 return std::nullopt;
3154 int64_t size = response.GetS64(-1, 16);
3155 if (size > 0 && response.GetChar() == ';') {
3156 std::string buffer;
3157 if (response.GetEscapedBinaryData(buffer)) {
3159 if (buffer.size() != sizeof(out))
3160 return std::nullopt;
3161 memcpy(&out, buffer.data(), sizeof(out));
3162 return out;
3163 }
3164 }
3165 }
3166 return std::nullopt;
3167}
3168
3169std::optional<GDBRemoteFStatData>
3171 Status error;
3173 if (fd == UINT64_MAX)
3174 return std::nullopt;
3175 std::optional<GDBRemoteFStatData> st = FStat(fd);
3176 CloseFile(fd, error);
3177 return st;
3178}
3179
3180// Extension of host I/O packets to get the file size.
3182 const lldb_private::FileSpec &file_spec) {
3184 std::string path(file_spec.GetPath(false));
3186 stream.PutCString("vFile:size:");
3187 stream.PutStringAsRawHex8(path);
3188 StringExtractorGDBRemote response;
3189 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3191 return UINT64_MAX;
3192
3193 if (!response.IsUnsupportedResponse()) {
3194 if (response.GetChar() != 'F')
3195 return UINT64_MAX;
3196 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3197 return retcode;
3198 }
3199 m_supports_vFileSize = false;
3200 }
3201
3202 // Fallback to fstat.
3203 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3204 return st ? st->gdb_st_size : UINT64_MAX;
3205}
3206
3208 CompletionRequest &request, bool only_dir) {
3210 stream.PutCString("qPathComplete:");
3211 stream.PutHex32(only_dir ? 1 : 0);
3212 stream.PutChar(',');
3214 StringExtractorGDBRemote response;
3215 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3217 StreamString strm;
3218 char ch = response.GetChar();
3219 if (ch != 'M')
3220 return;
3221 while (response.Peek()) {
3222 strm.Clear();
3223 while ((ch = response.GetHexU8(0, false)) != '\0')
3224 strm.PutChar(ch);
3225 request.AddCompletion(strm.GetString());
3226 if (response.GetChar() != ',')
3227 break;
3228 }
3229 }
3230}
3231
3232Status
3234 uint32_t &file_permissions) {
3236 std::string path{file_spec.GetPath(false)};
3237 Status error;
3239 stream.PutCString("vFile:mode:");
3240 stream.PutStringAsRawHex8(path);
3241 StringExtractorGDBRemote response;
3242 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3244 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3245 stream.GetData());
3246 return error;
3247 }
3248 if (!response.IsUnsupportedResponse()) {
3249 if (response.GetChar() != 'F') {
3251 "invalid response to '%s' packet", stream.GetData());
3252 } else {
3253 const uint32_t mode = response.GetS32(-1, 16);
3254 if (static_cast<int32_t>(mode) == -1) {
3255 if (response.GetChar() == ',') {
3256 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3257 if (response_errno > 0)
3258 error = Status(response_errno, lldb::eErrorTypePOSIX);
3259 else
3260 error = Status::FromErrorString("unknown error");
3261 } else
3262 error = Status::FromErrorString("unknown error");
3263 } else {
3264 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3265 }
3266 }
3267 return error;
3268 } else { // response.IsUnsupportedResponse()
3269 m_supports_vFileMode = false;
3270 }
3271 }
3272
3273 // Fallback to fstat.
3274 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3275 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3276 return Status();
3277 }
3278 return Status::FromErrorString("fstat failed");
3279}
3280
3282 uint64_t offset, void *dst,
3283 uint64_t dst_len,
3284 Status &error) {
3286 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3287 offset);
3288 StringExtractorGDBRemote response;
3289 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3291 if (response.GetChar() != 'F')
3292 return 0;
3293 int64_t retcode = response.GetS64(-1, 16);
3294 if (retcode == -1) {
3295 error = Status::FromErrorString("unknown error");
3296 if (response.GetChar() == ',') {
3297 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3298 if (response_errno > 0)
3299 error = Status(response_errno, lldb::eErrorTypePOSIX);
3300 }
3301 return -1;
3302 }
3303 const char next = (response.Peek() ? *response.Peek() : 0);
3304 if (next == ',')
3305 return 0;
3306 if (next == ';') {
3307 response.GetChar(); // skip the semicolon
3308 std::string buffer;
3309 if (response.GetEscapedBinaryData(buffer)) {
3310 const uint64_t data_to_write =
3311 std::min<uint64_t>(dst_len, buffer.size());
3312 if (data_to_write > 0)
3313 memcpy(dst, &buffer[0], data_to_write);
3314 return data_to_write;
3315 }
3316 }
3317 }
3318 return 0;
3319}
3320
3322 uint64_t offset,
3323 const void *src,
3324 uint64_t src_len,
3325 Status &error) {
3327 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3328 stream.PutEscapedBytes(src, src_len);
3329 StringExtractorGDBRemote response;
3330 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3332 if (response.GetChar() != 'F') {
3333 error = Status::FromErrorStringWithFormat("write file failed");
3334 return 0;
3335 }
3336 int64_t bytes_written = response.GetS64(-1, 16);
3337 if (bytes_written == -1) {
3338 error = Status::FromErrorString("unknown error");
3339 if (response.GetChar() == ',') {
3340 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3341 if (response_errno > 0)
3342 error = Status(response_errno, lldb::eErrorTypePOSIX);
3343 }
3344 return -1;
3345 }
3346 return bytes_written;
3347 } else {
3348 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3349 }
3350 return 0;
3351}
3352
3354 const FileSpec &dst) {
3355 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3356 Status error;
3358 stream.PutCString("vFile:symlink:");
3359 // the unix symlink() command reverses its parameters where the dst if first,
3360 // so we follow suit here
3361 stream.PutStringAsRawHex8(dst_path);
3362 stream.PutChar(',');
3363 stream.PutStringAsRawHex8(src_path);
3364 StringExtractorGDBRemote response;
3365 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3367 if (response.GetChar() == 'F') {
3368 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3369 if (result != 0) {
3370 error = Status::FromErrorString("unknown error");
3371 if (response.GetChar() == ',') {
3372 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3373 if (response_errno > 0)
3374 error = Status(response_errno, lldb::eErrorTypePOSIX);
3375 }
3376 }
3377 } else {
3378 // Should have returned with 'F<result>[,<errno>]'
3379 error = Status::FromErrorStringWithFormat("symlink failed");
3380 }
3381 } else {
3382 error = Status::FromErrorString("failed to send vFile:symlink packet");
3383 }
3384 return error;
3385}
3386
3388 std::string path{file_spec.GetPath(false)};
3389 Status error;
3391 stream.PutCString("vFile:unlink:");
3392 // the unix symlink() command reverses its parameters where the dst if first,
3393 // so we follow suit here
3394 stream.PutStringAsRawHex8(path);
3395 StringExtractorGDBRemote response;
3396 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3398 if (response.GetChar() == 'F') {
3399 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3400 if (result != 0) {
3401 error = Status::FromErrorString("unknown error");
3402 if (response.GetChar() == ',') {
3403 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3404 if (response_errno > 0)
3405 error = Status(response_errno, lldb::eErrorTypePOSIX);
3406 }
3407 }
3408 } else {
3409 // Should have returned with 'F<result>[,<errno>]'
3410 error = Status::FromErrorStringWithFormat("unlink failed");
3411 }
3412 } else {
3413 error = Status::FromErrorString("failed to send vFile:unlink packet");
3414 }
3415 return error;
3416}
3417
3418// Extension of host I/O packets to get whether a file exists.
3420 const lldb_private::FileSpec &file_spec) {
3422 std::string path(file_spec.GetPath(false));
3424 stream.PutCString("vFile:exists:");
3425 stream.PutStringAsRawHex8(path);
3426 StringExtractorGDBRemote response;
3427 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3429 return false;
3430 if (!response.IsUnsupportedResponse()) {
3431 if (response.GetChar() != 'F')
3432 return false;
3433 if (response.GetChar() != ',')
3434 return false;
3435 bool retcode = (response.GetChar() != '0');
3436 return retcode;
3437 } else
3438 m_supports_vFileExists = false;
3439 }
3440
3441 // Fallback to open.
3442 Status error;
3444 if (fd == UINT64_MAX)
3445 return false;
3446 CloseFile(fd, error);
3447 return true;
3448}
3449
3450llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3451 const lldb_private::FileSpec &file_spec) {
3452 std::string path(file_spec.GetPath(false));
3454 stream.PutCString("vFile:MD5:");
3455 stream.PutStringAsRawHex8(path);
3456 StringExtractorGDBRemote response;
3457 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3459 if (response.GetChar() != 'F')
3460 return std::make_error_code(std::errc::illegal_byte_sequence);
3461 if (response.GetChar() != ',')
3462 return std::make_error_code(std::errc::illegal_byte_sequence);
3463 if (response.Peek() && *response.Peek() == 'x')
3464 return std::make_error_code(std::errc::no_such_file_or_directory);
3465
3466 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3467 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3468 // handle the concatenated hex string. What would happen is parsing the low
3469 // would consume the whole response packet which would give incorrect
3470 // results. Instead, we get the byte string for each low and high hex
3471 // separately, and parse them.
3472 //
3473 // An alternate way to handle this is to change the server to put a
3474 // delimiter between the low/high parts, and change the client to parse the
3475 // delimiter. However, we choose not to do this so existing lldb-servers
3476 // don't have to be patched
3477
3478 // The checksum is 128 bits encoded as hex
3479 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3480 // Each byte takes 2 hex characters in the response.
3481 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3482
3483 // Get low part
3484 auto part =
3485 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3486 if (part.size() != MD5_HALF_LENGTH)
3487 return std::make_error_code(std::errc::illegal_byte_sequence);
3488 response.SetFilePos(response.GetFilePos() + part.size());
3489
3490 uint64_t low;
3491 if (part.getAsInteger(/*radix=*/16, low))
3492 return std::make_error_code(std::errc::illegal_byte_sequence);
3493
3494 // Get high part
3495 part =
3496 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3497 if (part.size() != MD5_HALF_LENGTH)
3498 return std::make_error_code(std::errc::illegal_byte_sequence);
3499 response.SetFilePos(response.GetFilePos() + part.size());
3500
3501 uint64_t high;
3502 if (part.getAsInteger(/*radix=*/16, high))
3503 return std::make_error_code(std::errc::illegal_byte_sequence);
3504
3505 llvm::MD5::MD5Result result;
3506 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3507 result.data(), low);
3508 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3509 result.data() + 8, high);
3510
3511 return result;
3512 }
3513 return std::make_error_code(std::errc::operation_canceled);
3514}
3515
3517 // Some targets have issues with g/G packets and we need to avoid using them
3519 if (process) {
3521 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3522 if (arch.IsValid() &&
3523 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3524 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3525 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3526 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3528 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3529 if (gdb_server_version != 0) {
3530 const char *gdb_server_name = GetGDBServerProgramName();
3531 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3532 if (gdb_server_version >= 310)
3534 }
3535 }
3536 }
3537 }
3538 }
3540}
3541
3543 uint32_t reg) {
3544 StreamString payload;
3545 payload.Printf("p%x", reg);
3546 StringExtractorGDBRemote response;
3548 tid, std::move(payload), response) != PacketResult::Success ||
3549 !response.IsNormalResponse())
3550 return nullptr;
3551
3552 WritableDataBufferSP buffer_sp(
3553 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3554 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3555 return buffer_sp;
3556}
3557
3559 StreamString payload;
3560 payload.PutChar('g');
3561 StringExtractorGDBRemote response;
3563 tid, std::move(payload), response) != PacketResult::Success ||
3564 !response.IsNormalResponse())
3565 return nullptr;
3566
3567 WritableDataBufferSP buffer_sp(
3568 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3569 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3570 return buffer_sp;
3571}
3572
3574 uint32_t reg_num,
3575 llvm::ArrayRef<uint8_t> data) {
3576 StreamString payload;
3577 payload.Printf("P%x=", reg_num);
3578 payload.PutBytesAsRawHex8(data.data(), data.size(),
3581 StringExtractorGDBRemote response;
3583 tid, std::move(payload), response) == PacketResult::Success &&
3584 response.IsOKResponse();
3585}
3586
3588 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3589 StreamString payload;
3590 payload.PutChar('G');
3591 payload.PutBytesAsRawHex8(data.data(), data.size(),
3594 StringExtractorGDBRemote response;
3596 tid, std::move(payload), response) == PacketResult::Success &&
3597 response.IsOKResponse();
3598}
3599
3601 uint32_t &save_id) {
3602 save_id = 0; // Set to invalid save ID
3604 return false;
3605
3607 StreamString payload;
3608 payload.PutCString("QSaveRegisterState");
3609 StringExtractorGDBRemote response;
3611 tid, std::move(payload), response) != PacketResult::Success)
3612 return false;
3613
3614 if (response.IsUnsupportedResponse())
3616
3617 const uint32_t response_save_id = response.GetU32(0);
3618 if (response_save_id == 0)
3619 return false;
3620
3621 save_id = response_save_id;
3622 return true;
3623}
3624
3626 uint32_t save_id) {
3627 // We use the "m_supports_QSaveRegisterState" variable here because the
3628 // QSaveRegisterState and QRestoreRegisterState packets must both be
3629 // supported in order to be useful
3631 return false;
3632
3633 StreamString payload;
3634 payload.Printf("QRestoreRegisterState:%u", save_id);
3635 StringExtractorGDBRemote response;
3637 tid, std::move(payload), response) != PacketResult::Success)
3638 return false;
3639
3640 if (response.IsOKResponse())
3641 return true;
3642
3643 if (response.IsUnsupportedResponse())
3645 return false;
3646}
3647
3650 return false;
3651
3652 StreamString packet;
3653 StringExtractorGDBRemote response;
3654 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3655 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3657 response.IsOKResponse();
3658}
3659
3660llvm::Expected<TraceSupportedResponse>
3662 Log *log = GetLog(GDBRLog::Process);
3663
3664 StreamGDBRemote escaped_packet;
3665 escaped_packet.PutCString("jLLDBTraceSupported");
3666
3667 StringExtractorGDBRemote response;
3668 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3669 timeout) ==
3671 if (response.IsErrorResponse())
3672 return response.GetStatus().ToError();
3673 if (response.IsUnsupportedResponse())
3674 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3675 "jLLDBTraceSupported is unsupported");
3676
3677 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3678 "TraceSupportedResponse");
3679 }
3680 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3681 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3682 "failed to send packet: jLLDBTraceSupported");
3683}
3684
3685llvm::Error
3687 std::chrono::seconds timeout) {
3688 Log *log = GetLog(GDBRLog::Process);
3689
3690 StreamGDBRemote escaped_packet;
3691 escaped_packet.PutCString("jLLDBTraceStop:");
3692
3693 std::string json_string;
3694 llvm::raw_string_ostream os(json_string);
3695 os << toJSON(request);
3696
3697 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3698
3699 StringExtractorGDBRemote response;
3700 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3701 timeout) ==
3703 if (response.IsErrorResponse())
3704 return response.GetStatus().ToError();
3705 if (response.IsUnsupportedResponse())
3706 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3707 "jLLDBTraceStop is unsupported");
3708 if (response.IsOKResponse())
3709 return llvm::Error::success();
3710 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3711 "Invalid jLLDBTraceStart response");
3712 }
3713 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3714 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3715 "failed to send packet: jLLDBTraceStop '%s'",
3716 escaped_packet.GetData());
3717}
3718
3719llvm::Error
3720GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3721 std::chrono::seconds timeout) {
3722 Log *log = GetLog(GDBRLog::Process);
3723
3724 StreamGDBRemote escaped_packet;
3725 escaped_packet.PutCString("jLLDBTraceStart:");
3726
3727 std::string json_string;
3728 llvm::raw_string_ostream os(json_string);
3729 os << params;
3730
3731 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3732
3733 StringExtractorGDBRemote response;
3734 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3735 timeout) ==
3737 if (response.IsErrorResponse())
3738 return response.GetStatus().ToError();
3739 if (response.IsUnsupportedResponse())
3740 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3741 "jLLDBTraceStart is unsupported");
3742 if (response.IsOKResponse())
3743 return llvm::Error::success();
3744 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3745 "Invalid jLLDBTraceStart response");
3746 }
3747 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3748 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3749 "failed to send packet: jLLDBTraceStart '%s'",
3750 escaped_packet.GetData());
3751}
3752
3753llvm::Expected<std::string>
3755 std::chrono::seconds timeout) {
3756 Log *log = GetLog(GDBRLog::Process);
3757
3758 StreamGDBRemote escaped_packet;
3759 escaped_packet.PutCString("jLLDBTraceGetState:");
3760
3761 std::string json_string;
3762 llvm::raw_string_ostream os(json_string);
3763 os << toJSON(TraceGetStateRequest{type.str()});
3764
3765 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3766
3767 StringExtractorGDBRemote response;
3768 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3769 timeout) ==
3771 if (response.IsErrorResponse())
3772 return response.GetStatus().ToError();
3773 if (response.IsUnsupportedResponse())
3774 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3775 "jLLDBTraceGetState is unsupported");
3776 return std::string(response.Peek());
3777 }
3778
3779 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3780 return llvm::createStringError(
3781 llvm::inconvertibleErrorCode(),
3782 "failed to send packet: jLLDBTraceGetState '%s'",
3783 escaped_packet.GetData());
3784}
3785
3786llvm::Expected<std::vector<uint8_t>>
3788 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3789 Log *log = GetLog(GDBRLog::Process);
3790
3791 StreamGDBRemote escaped_packet;
3792 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3793
3794 std::string json_string;
3795 llvm::raw_string_ostream os(json_string);
3796 os << toJSON(request);
3797
3798 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3799
3800 StringExtractorGDBRemote response;
3801 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3802 timeout) ==
3804 if (response.IsErrorResponse())
3805 return response.GetStatus().ToError();
3806 std::string data;
3807 response.GetEscapedBinaryData(data);
3808 return std::vector<uint8_t>(data.begin(), data.end());
3809 }
3810 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3811 return llvm::createStringError(
3812 llvm::inconvertibleErrorCode(),
3813 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3814 escaped_packet.GetData());
3815}
3816
3818 StringExtractorGDBRemote response;
3819 if (SendPacketAndWaitForResponse("qOffsets", response) !=
3821 return std::nullopt;
3822 if (!response.IsNormalResponse())
3823 return std::nullopt;
3824
3825 QOffsets result;
3826 llvm::StringRef ref = response.GetStringRef();
3827 const auto &GetOffset = [&] {
3828 addr_t offset;
3829 if (ref.consumeInteger(16, offset))
3830 return false;
3831 result.offsets.push_back(offset);
3832 return true;
3833 };
3834
3835 if (ref.consume_front("Text=")) {
3836 result.segments = false;
3837 if (!GetOffset())
3838 return std::nullopt;
3839 if (!ref.consume_front(";Data=") || !GetOffset())
3840 return std::nullopt;
3841 if (ref.empty())
3842 return result;
3843 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3844 return result;
3845 } else if (ref.consume_front("TextSeg=")) {
3846 result.segments = true;
3847 if (!GetOffset())
3848 return std::nullopt;
3849 if (ref.empty())
3850 return result;
3851 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3852 return result;
3853 }
3854 return std::nullopt;
3855}
3856
3858 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3859 ModuleSpec &module_spec) {
3861 return false;
3862
3863 std::string module_path = module_file_spec.GetPath(false);
3864 if (module_path.empty())
3865 return false;
3866
3867 StreamString packet;
3868 packet.PutCString("qModuleInfo:");
3869 packet.PutStringAsRawHex8(module_path);
3870 packet.PutCString(";");
3871 const auto &triple = arch_spec.GetTriple().getTriple();
3872 packet.PutStringAsRawHex8(triple);
3873
3874 StringExtractorGDBRemote response;
3875 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
3877 return false;
3878
3879 if (response.IsErrorResponse())
3880 return false;
3881
3882 if (response.IsUnsupportedResponse()) {
3883 m_supports_qModuleInfo = false;
3884 return false;
3885 }
3886
3887 llvm::StringRef name;
3888 llvm::StringRef value;
3889
3890 module_spec.Clear();
3891 module_spec.GetFileSpec() = module_file_spec;
3892
3893 while (response.GetNameColonValue(name, value)) {
3894 if (name == "uuid" || name == "md5") {
3895 StringExtractor extractor(value);
3896 std::string uuid;
3897 extractor.GetHexByteString(uuid);
3898 module_spec.GetUUID().SetFromStringRef(uuid);
3899 } else if (name == "triple") {
3900 StringExtractor extractor(value);
3901 std::string triple;
3902 extractor.GetHexByteString(triple);
3903 module_spec.GetArchitecture().SetTriple(triple.c_str());
3904 } else if (name == "file_offset") {
3905 uint64_t ival = 0;
3906 if (!value.getAsInteger(16, ival))
3907 module_spec.SetObjectOffset(ival);
3908 } else if (name == "file_size") {
3909 uint64_t ival = 0;
3910 if (!value.getAsInteger(16, ival))
3911 module_spec.SetObjectSize(ival);
3912 } else if (name == "file_path") {
3913 StringExtractor extractor(value);
3914 std::string path;
3915 extractor.GetHexByteString(path);
3916 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3917 }
3918 }
3919
3920 return true;
3921}
3922
3923static std::optional<ModuleSpec>
3925 ModuleSpec result;
3926 if (!dict)
3927 return std::nullopt;
3928
3929 llvm::StringRef string;
3930 uint64_t integer;
3931
3932 if (!dict->GetValueForKeyAsString("uuid", string))
3933 return std::nullopt;
3934 if (!result.GetUUID().SetFromStringRef(string))
3935 return std::nullopt;
3936
3937 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3938 return std::nullopt;
3939 result.SetObjectOffset(integer);
3940
3941 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3942 return std::nullopt;
3943 result.SetObjectSize(integer);
3944
3945 if (!dict->GetValueForKeyAsString("triple", string))
3946 return std::nullopt;
3947 result.GetArchitecture().SetTriple(string);
3948
3949 if (!dict->GetValueForKeyAsString("file_path", string))
3950 return std::nullopt;
3951 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3952
3953 return result;
3954}
3955
3956std::optional<std::vector<ModuleSpec>>
3958 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3959 namespace json = llvm::json;
3960
3962 return std::nullopt;
3963
3964 json::Array module_array;
3965 for (const FileSpec &module_file_spec : module_file_specs) {
3966 module_array.push_back(
3967 json::Object{{"file", module_file_spec.GetPath(false)},
3968 {"triple", triple.getTriple()}});
3969 }
3970 StreamString unescaped_payload;
3971 unescaped_payload.PutCString("jModulesInfo:");
3972 unescaped_payload.AsRawOstream() << std::move(module_array);
3973
3974 StreamGDBRemote payload;
3975 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3976 unescaped_payload.GetSize());
3977
3978 // Increase the timeout for jModulesInfo since this packet can take longer.
3979 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3980
3981 StringExtractorGDBRemote response;
3982 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
3984 response.IsErrorResponse())
3985 return std::nullopt;
3986
3987 if (response.IsUnsupportedResponse()) {
3989 return std::nullopt;
3990 }
3991
3992 StructuredData::ObjectSP response_object_sp =
3994 if (!response_object_sp)
3995 return std::nullopt;
3996
3997 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3998 if (!response_array)
3999 return std::nullopt;
4000
4001 std::vector<ModuleSpec> result;
4002 for (size_t i = 0; i < response_array->GetSize(); ++i) {
4003 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4004 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4005 result.push_back(*module_spec);
4006 }
4007
4008 return result;
4009}
4010
4011// query the target remote for extended information using the qXfer packet
4012//
4013// example: object='features', annex='target.xml'
4014// return: <xml output> or error
4015llvm::Expected<std::string>
4017 llvm::StringRef annex) {
4018
4019 std::string output;
4020 llvm::raw_string_ostream output_stream(output);
4022
4023 uint64_t size = GetRemoteMaxPacketSize();
4024 if (size == 0)
4025 size = 0x1000;
4026 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4027 int offset = 0;
4028 bool active = true;
4029
4030 // loop until all data has been read
4031 while (active) {
4032
4033 // send query extended feature packet
4034 std::string packet =
4035 ("qXfer:" + object + ":read:" + annex + ":" +
4036 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4037 .str();
4038
4040 SendPacketAndWaitForResponse(packet, chunk);
4041
4043 chunk.GetStringRef().empty()) {
4044 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4045 "Error sending $qXfer packet");
4046 }
4047
4048 // check packet code
4049 switch (chunk.GetStringRef()[0]) {
4050 // last chunk
4051 case ('l'):
4052 active = false;
4053 [[fallthrough]];
4054
4055 // more chunks
4056 case ('m'):
4057 output_stream << chunk.GetStringRef().drop_front();
4058 offset += chunk.GetStringRef().size() - 1;
4059 break;
4060
4061 // unknown chunk
4062 default:
4063 return llvm::createStringError(
4064 llvm::inconvertibleErrorCode(),
4065 "Invalid continuation code from $qXfer packet");
4066 }
4067 }
4068
4069 return output;
4070}
4071
4072// Notify the target that gdb is prepared to serve symbol lookup requests.
4073// packet: "qSymbol::"
4074// reply:
4075// OK The target does not need to look up any (more) symbols.
4076// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4077// encoded).
4078// LLDB may provide the value by sending another qSymbol
4079// packet
4080// in the form of"qSymbol:<sym_value>:<sym_name>".
4081//
4082// Three examples:
4083//
4084// lldb sends: qSymbol::
4085// lldb receives: OK
4086// Remote gdb stub does not need to know the addresses of any symbols, lldb
4087// does not
4088// need to ask again in this session.
4089//
4090// lldb sends: qSymbol::
4091// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4092// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4093// lldb receives: OK
4094// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4095// not know
4096// the address at this time. lldb needs to send qSymbol:: again when it has
4097// more
4098// solibs loaded.
4099//
4100// lldb sends: qSymbol::
4101// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4102// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4103// lldb receives: OK
4104// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4105// that it
4106// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4107// does not
4108// need any more symbols. lldb does not need to ask again in this session.
4109
4111 lldb_private::Process *process) {
4112 // Set to true once we've resolved a symbol to an address for the remote
4113 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4114 // any more symbols and we can stop asking.
4115 bool symbol_response_provided = false;
4116
4117 // Is this the initial qSymbol:: packet?
4118 bool first_qsymbol_query = true;
4119
4121 Lock lock(*this);
4122 if (lock) {
4123 StreamString packet;
4124 packet.PutCString("qSymbol::");
4125 StringExtractorGDBRemote response;
4126 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4128 if (response.IsOKResponse()) {
4129 if (symbol_response_provided || first_qsymbol_query) {
4131 }
4132
4133 // We are done serving symbols requests
4134 return;
4135 }
4136 first_qsymbol_query = false;
4137
4138 if (response.IsUnsupportedResponse()) {
4139 // qSymbol is not supported by the current GDB server we are
4140 // connected to
4141 m_supports_qSymbol = false;
4142 return;
4143 } else {
4144 llvm::StringRef response_str(response.GetStringRef());
4145 if (response_str.starts_with("qSymbol:")) {
4146 response.SetFilePos(strlen("qSymbol:"));
4147 std::string symbol_name;
4148 if (response.GetHexByteString(symbol_name)) {
4149 if (symbol_name.empty())
4150 return;
4151
4152 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4155 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4156 for (const SymbolContext &sc : sc_list) {
4157 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4158 break;
4159 if (sc.symbol) {
4160 switch (sc.symbol->GetType()) {
4161 case eSymbolTypeInvalid:
4168 case eSymbolTypeBlock:
4169 case eSymbolTypeLocal:
4170 case eSymbolTypeParam:
4181 break;
4182
4183 case eSymbolTypeCode:
4185 case eSymbolTypeData:
4186 case eSymbolTypeRuntime:
4192 symbol_load_addr =
4193 sc.symbol->GetLoadAddress(&process->GetTarget());
4194 break;
4195 }
4196 }
4197 }
4198 // This is the normal path where our symbol lookup was successful
4199 // and we want to send a packet with the new symbol value and see
4200 // if another lookup needs to be done.
4201
4202 // Change "packet" to contain the requested symbol value and name
4203 packet.Clear();
4204 packet.PutCString("qSymbol:");
4205 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4206 packet.Printf("%" PRIx64, symbol_load_addr);
4207 symbol_response_provided = true;
4208 } else {
4209 symbol_response_provided = false;
4210 }
4211 packet.PutCString(":");
4212 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4213 continue; // go back to the while loop and send "packet" and wait
4214 // for another response
4215 }
4216 }
4217 }
4218 }
4219 // If we make it here, the symbol request packet response wasn't valid or
4220 // our symbol lookup failed so we must abort
4221 return;
4222
4223 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4224 LLDB_LOGF(log,
4225 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4226 __FUNCTION__);
4227 }
4228 }
4229}
4230
4234 // Query the server for the array of supported asynchronous JSON packets.
4236
4237 Log *log = GetLog(GDBRLog::Process);
4238
4239 // Poll it now.
4240 StringExtractorGDBRemote response;
4241 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4246 !m_supported_async_json_packets_sp->GetAsArray()) {
4247 // We were returned something other than a JSON array. This is
4248 // invalid. Clear it out.
4249 LLDB_LOGF(log,
4250 "GDBRemoteCommunicationClient::%s(): "
4251 "QSupportedAsyncJSONPackets returned invalid "
4252 "result: %s",
4253 __FUNCTION__, response.GetStringRef().data());
4255 }
4256 } else {
4257 LLDB_LOGF(log,
4258 "GDBRemoteCommunicationClient::%s(): "
4259 "QSupportedAsyncJSONPackets unsupported",
4260 __FUNCTION__);
4261 }
4262
4264 StreamString stream;
4266 LLDB_LOGF(log,
4267 "GDBRemoteCommunicationClient::%s(): supported async "
4268 "JSON packets: %s",
4269 __FUNCTION__, stream.GetData());
4270 }
4271 }
4272
4274 ? m_supported_async_json_packets_sp->GetAsArray()
4275 : nullptr;
4276}
4277
4279 llvm::ArrayRef<int32_t> signals) {
4280 // Format packet:
4281 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4282 auto range = llvm::make_range(signals.begin(), signals.end());
4283 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4284
4285 StringExtractorGDBRemote response;
4286 auto send_status = SendPacketAndWaitForResponse(packet, response);
4287
4289 return Status::FromErrorString("Sending QPassSignals packet failed");
4290
4291 if (response.IsOKResponse()) {
4292 return Status();
4293 } else {
4295 "Unknown error happened during sending QPassSignals packet.");
4296 }
4297}
4298
4300 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4301 Status error;
4302
4303 if (type_name.empty()) {
4304 error = Status::FromErrorString("invalid type_name argument");
4305 return error;
4306 }
4307
4308 // Build command: Configure{type_name}: serialized config data.
4309 StreamGDBRemote stream;
4310 stream.PutCString("QConfigure");
4311 stream.PutCString(type_name);
4312 stream.PutChar(':');
4313 if (config_sp) {
4314 // Gather the plain-text version of the configuration data.
4315 StreamString unescaped_stream;
4316 config_sp->Dump(unescaped_stream);
4317 unescaped_stream.Flush();
4318
4319 // Add it to the stream in escaped fashion.
4320 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4321 unescaped_stream.GetSize());
4322 }
4323 stream.Flush();
4324
4325 // Send the packet.
4326 StringExtractorGDBRemote response;
4327 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4328 if (result == PacketResult::Success) {
4329 // We failed if the config result comes back other than OK.
4330 if (response.GetStringRef() == "OK") {
4331 // Okay!
4332 error.Clear();
4333 } else {
4335 "configuring StructuredData feature {0} failed with error {1}",
4336 type_name, response.GetStringRef());
4337 }
4338 } else {
4339 // Can we get more data here on the failure?
4341 "configuring StructuredData feature {0} failed when sending packet: "
4342 "PacketResult={1}",
4343 type_name, (int)result);
4344 }
4345 return error;
4346}
4347
4352
4357 return true;
4358
4359 // If the remote didn't indicate native-signal support explicitly,
4360 // check whether it is an old version of lldb-server.
4361 return GetThreadSuffixSupported();
4362}
4363
4365 StringExtractorGDBRemote response;
4366 GDBRemoteCommunication::ScopedTimeout timeout(*this, seconds(3));
4367
4368 // LLDB server typically sends no response for "k", so we shouldn't try
4369 // to sync on timeout.
4370 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout(), false) !=
4372 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4373 "failed to send k packet");
4374
4375 char packet_cmd = response.GetChar(0);
4376 if (packet_cmd == 'W' || packet_cmd == 'X')
4377 return response.GetHexU8();
4378
4379 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4380 "unexpected response to k packet: %s",
4381 response.GetStringRef().str().c_str());
4382}
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:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
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
MemoryRegionInfo & SetMemoryTagged(LazyBool val)
void SetBlocksize(lldb::offset_t blocksize)
void SetName(const char *name)
MemoryRegionInfo & SetIsShadowStack(LazyBool val)
lldb::offset_t GetBlocksize() const
void SetDirtyPageList(std::vector< lldb::addr_t > pagelist)
MemoryRegionInfo & SetProtectionKey(std::optional< unsigned > key)
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:119
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:113
void SetGroupID(uint32_t gid)
Definition ProcessInfo.h: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:355
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1253
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:27
const char * GetData() const
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:367
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:402
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:416
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:305
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:129
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:289
virtual void Flush()=0
Flush the stream.
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:153
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:389
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:1166
const ArchSpec & GetArchitecture() const
Definition Target.h:1208
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:327
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