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"
27#include "lldb/Utility/Args.h"
31#include "lldb/Utility/Log.h"
32#include "lldb/Utility/State.h"
34
35#include "ProcessGDBRemote.h"
36#include "ProcessGDBRemoteLog.h"
37#include "lldb/Host/Config.h"
39
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
43#include "llvm/Support/ErrorExtras.h"
44#include "llvm/Support/JSON.h"
45
46#if HAVE_LIBCOMPRESSION
47#include <compression.h>
48#endif
49
50using namespace lldb;
52using namespace lldb_private;
53using namespace std::chrono;
54
55llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os,
56 const QOffsets &offsets) {
57 return os << llvm::formatv(
58 "QOffsets({0}, [{1:@[x]}])", offsets.segments,
59 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end()));
60}
61
62// GDBRemoteCommunicationClient constructor
81
82// Destructor
87
90
91 // Start the read thread after we send the handshake ack since if we fail to
92 // send the handshake ack, there is no reason to continue...
93 std::chrono::steady_clock::time_point start_of_handshake =
94 std::chrono::steady_clock::now();
95 if (SendAck()) {
96 // The return value from QueryNoAckModeSupported() is true if the packet
97 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
98 // false if no response was received. This quickly tells us if we have a
99 // live connection to a remote GDB server...
101 return true;
102 } else {
103 std::chrono::steady_clock::time_point end_of_handshake =
104 std::chrono::steady_clock::now();
105 auto handshake_timeout =
106 std::chrono::duration<double>(end_of_handshake - start_of_handshake)
107 .count();
108 if (error_ptr) {
109 if (!IsConnected())
110 *error_ptr =
111 Status::FromErrorString("Connection shut down by remote side "
112 "while waiting for reply to initial "
113 "handshake packet");
114 else
116 "failed to get reply to handshake packet within timeout of "
117 "%.1f seconds",
118 handshake_timeout);
119 }
120 }
121 } else {
122 if (error_ptr)
123 *error_ptr = Status::FromErrorString("failed to send the handshake ack");
124 }
125 return false;
126}
127
134
141
148
155
162
169
176
183
190
196
203
209
215
221
227
233
234llvm::Expected<std::vector<AcceleratorActions>>
236 // Get the initial actions (e.g. breakpoints to set) requested by any
237 // accelerator plugins using the "jAcceleratorPluginInitialize" packet. This
238 // is sent once when a native process is launched or attached. The empty
239 // state (no plugins / no actions) is modelled as an empty vector; errors are
240 // returned to the caller to report.
242 return std::vector<AcceleratorActions>();
243
246 if (SendPacketAndWaitForResponse("jAcceleratorPluginInitialize", response) !=
248 return llvm::createStringError(
249 "failed to send jAcceleratorPluginInitialize packet");
250
251 if (response.IsUnsupportedResponse())
252 return std::vector<AcceleratorActions>();
253
254 if (response.IsErrorResponse())
255 return response.GetStatus().takeError();
256
257 llvm::Expected<std::vector<AcceleratorActions>> actions =
258 llvm::json::parse<std::vector<AcceleratorActions>>(response.Peek(),
259 "AcceleratorActions");
260 if (actions)
261 return actions;
262
263 // A bare JSON parse error (e.g. "missing comma at line 4") is meaningless on
264 // its own, so include both the full response and the parse error; the caller
265 // logs this and the user can spot the problem in the response.
266 return llvm::createStringErrorV(
267 "malformed jAcceleratorPluginInitialize response '{0}': {1}",
268 response.GetStringRef(), llvm::toString(actions.takeError()));
269}
270
271llvm::Expected<AcceleratorBreakpointHitResponse>
273 const AcceleratorBreakpointHitArgs &args) {
274 StreamGDBRemote packet;
275 packet.PutCString("jAcceleratorPluginBreakpointHit:");
276 packet.PutAsJSON(args, /*hex_ascii=*/false);
277
279 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
281 return llvm::createStringError(
282 "failed to send jAcceleratorPluginBreakpointHit packet");
283
284 if (response.IsErrorResponse())
285 return response.GetStatus().takeError();
286
287 llvm::Expected<AcceleratorBreakpointHitResponse> hit_response =
288 llvm::json::parse<AcceleratorBreakpointHitResponse>(
289 response.Peek(), "AcceleratorBreakpointHitResponse");
290 if (hit_response)
291 return hit_response;
292
293 // A bare JSON parse error (e.g. "missing comma at line 4") is meaningless on
294 // its own, so include both the full response and the parse error; the caller
295 // logs this and the user can spot the problem in the response.
296 return llvm::createStringErrorV(
297 "malformed jAcceleratorPluginBreakpointHit response '{0}': {1}",
298 response.GetStringRef(), llvm::toString(hit_response.takeError()));
299}
300
303 m_send_acks = true;
305
306 // This is the first real packet that we'll send in a debug session and it
307 // may take a little longer than normal to receive a reply. Wait at least
308 // 6 seconds for a reply to this packet.
309
310 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
311
313 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) ==
315 if (response.IsOKResponse()) {
316 m_send_acks = false;
318 }
319 return true;
320 }
321 }
322 return false;
323}
324
337
351
365
367 if (!did_exec) {
368 // Hard reset everything, this is when we first connect to a GDB server
396 m_x_packet_state.reset();
405 m_supports_z0 = true;
406 m_supports_z1 = true;
407 m_supports_z2 = true;
408 m_supports_z3 = true;
409 m_supports_z4 = true;
412 m_supports_qSymbol = true;
415 m_host_arch.Clear();
417 m_os_version = llvm::VersionTuple();
418 m_os_build.clear();
419 m_os_kernel.clear();
420 m_hostname.clear();
421 m_gdb_server_name.clear();
423 m_default_packet_timeout = seconds(0);
426 m_qSupported_response.clear();
432 }
433
434 // These flags should be reset when we first connect to a GDB server and when
435 // our inferior process execs
437 m_process_arch.Clear();
438}
439
441 // Clear out any capabilities we expect to see in the qSupported response
455 m_x_packet_state.reset();
461
462 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
463 // not, we assume no limit
464
465 // build the qSupported packet
466 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc",
467 "multiprocess+",
468 "fork-events+",
469 "vfork-events+",
470 "swbreak+",
471 "hwbreak+",
472 "qXfer:libraries:read+",
473 "qXfer:libraries-svr4:read+"};
474 StreamString packet;
475 packet.PutCString("qSupported");
476 for (uint32_t i = 0; i < features.size(); ++i) {
477 packet.PutCString(i == 0 ? ":" : ";");
478 packet.PutCString(features[i]);
479 }
480
482 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
484 // Hang on to the qSupported packet, so that platforms can do custom
485 // configuration of the transport before attaching/launching the process.
486 m_qSupported_response = response.GetStringRef().str();
487
488 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) {
489 if (x == "qXfer:auxv:read+")
491 else if (x == "qXfer:libraries-svr4:read+")
493 else if (x == "augmented-libraries-svr4-read") {
496 } else if (x == "qXfer:libraries:read+")
498 else if (x == "qXfer:features:read+")
500 else if (x == "qXfer:memory-map:read+")
502 else if (x == "qXfer:siginfo:read+")
504 else if (x == "qEcho+")
506 else if (x == "QPassSignals+")
508 else if (x == "multiprocess+")
510 else if (x == "memory-tagging+")
512 else if (x == "qSaveCore+")
514 else if (x == "native-signals+")
516 else if (x == "binary-upload+")
518 else if (x == "ReverseContinue+")
520 else if (x == "ReverseStep+")
522 else if (x == "MultiMemRead+")
524 else if (x == "jMultiBreakpoint+")
526 else if (x == "accelerator-plugins+")
528 // Look for a list of compressions in the features list e.g.
529 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
530 // deflate,lzma
531 else if (x.consume_front("SupportedCompressions=")) {
532 llvm::SmallVector<llvm::StringRef, 4> compressions;
533 x.split(compressions, ',');
534 if (!compressions.empty())
535 MaybeEnableCompression(compressions);
536 } else if (x.consume_front("SupportedWatchpointTypes=")) {
537 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types;
538 x.split(watchpoint_types, ',');
539 m_watchpoint_types = eWatchpointHardwareFeatureUnknown;
540 for (auto wp_type : watchpoint_types) {
541 if (wp_type == "x86_64")
542 m_watchpoint_types |= eWatchpointHardwareX86;
543 if (wp_type == "aarch64-mask")
544 m_watchpoint_types |= eWatchpointHardwareArmMASK;
545 if (wp_type == "aarch64-bas")
546 m_watchpoint_types |= eWatchpointHardwareArmBAS;
547 }
548 } else if (x.consume_front("PacketSize=")) {
549 StringExtractorGDBRemote packet_response(x);
551 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
552 if (m_max_packet_size == 0) {
553 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
555 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
556 }
557 }
558 }
559 }
560}
561
574
576 assert(!flavor.empty());
585 if (SendPacketAndWaitForResponse("vCont?", response) ==
587 for (llvm::StringRef token : llvm::split(response.GetStringRef(), ';')) {
588 if (token == "c")
590 if (token == "C")
592 if (token == "s")
594 if (token == "S")
596 }
597
603 }
604
610 }
611 }
612 }
613
614 return llvm::StringSwitch<bool>(flavor)
615 .Case("a", m_supports_vCont_any)
616 .Case("A", m_supports_vCont_all)
617 .Case("c", m_supports_vCont_c)
618 .Case("C", m_supports_vCont_C)
619 .Case("s", m_supports_vCont_s)
620 .Case("S", m_supports_vCont_S)
621 .Default(false);
622}
623
626 lldb::tid_t tid, StreamString &&payload,
627 StringExtractorGDBRemote &response) {
628 Lock lock(*this);
629 if (!lock) {
631 LLDB_LOGF(log,
632 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
633 "for %s packet.",
634 __FUNCTION__, payload.GetData());
636 }
637
639 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
640 else {
641 if (!SetCurrentThread(tid))
643 }
644
645 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
646}
647
648// Check if the target supports 'p' packet. It sends out a 'p' packet and
649// checks the response. A normal packet will tell us that support is available.
650//
651// Takes a valid thread ID because p needs to apply to a thread.
657
659 lldb::tid_t tid, llvm::StringRef packetStr) {
660 StreamString payload;
661 payload.PutCString(packetStr);
664 tid, std::move(payload), response) == PacketResult::Success &&
665 response.IsNormalResponse()) {
666 return eLazyBoolYes;
667 }
668 return eLazyBoolNo;
669}
670
674
676 // Get information on all threads at one using the "jThreadsInfo" packet
677 StructuredData::ObjectSP object_sp;
678
682 if (SendPacketAndWaitForResponse("jThreadsInfo", response) ==
684 if (response.IsUnsupportedResponse()) {
686 } else if (!response.Empty()) {
687 object_sp = StructuredData::ParseJSON(response.GetStringRef());
688 }
689 }
690 }
691 return object_sp;
692}
693
707
711 // We try to enable error strings in remote packets but if we fail, we just
712 // work in the older way.
714 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) ==
716 if (response.IsOKResponse()) {
718 }
719 }
720 }
721}
722
736
750
763
770
772 size_t len,
773 int32_t type) {
774 StreamString packet;
775 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type);
777
778 Log *log = GetLog(GDBRLog::Memory);
779
780 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
782 !response.IsNormalResponse()) {
783 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed",
784 __FUNCTION__);
785 return nullptr;
786 }
787
788 // We are expecting
789 // m<hex encoded bytes>
790
791 if (response.GetChar() != 'm') {
792 LLDB_LOGF(log,
793 "GDBRemoteCommunicationClient::%s: qMemTags response did not "
794 "begin with \"m\"",
795 __FUNCTION__);
796 return nullptr;
797 }
798
799 size_t expected_bytes = response.GetBytesLeft() / 2;
800 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0));
801 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData());
802 // Check both because in some situations chars are consumed even
803 // if the decoding fails.
804 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) {
805 LLDB_LOGF(
806 log,
807 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response",
808 __FUNCTION__);
809 return nullptr;
810 }
811
812 return buffer_sp;
813}
814
816 lldb::addr_t addr, size_t len, int32_t type,
817 const std::vector<uint8_t> &tags) {
818 // Format QMemTags:address,length:type:tags
819 StreamString packet;
820 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type);
821 packet.PutBytesAsRawHex8(tags.data(), tags.size());
822
823 Status status;
825 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
827 !response.IsOKResponse()) {
828 status = Status::FromErrorString("QMemTags packet failed");
829 }
830 return status;
831}
832
848
850 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
851 return m_curr_pid;
852
853 // First try to retrieve the pid via the qProcessInfo request.
854 GetCurrentProcessInfo(allow_lazy);
856 // We really got it.
857 return m_curr_pid;
858 } else {
859 // If we don't get a response for qProcessInfo, check if $qC gives us a
860 // result. $qC only returns a real process id on older debugserver and
861 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
862 // the thread id, which newer debugserver and lldb-gdbserver stubs return
863 // correctly.
866 if (response.GetChar() == 'Q') {
867 if (response.GetChar() == 'C') {
869 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID);
872 return m_curr_pid;
873 }
874 }
875 }
876 }
877
878 // If we don't get a response for $qC, check if $qfThreadID gives us a
879 // result.
881 bool sequence_mutex_unavailable;
882 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
883 if (!ids.empty() && !sequence_mutex_unavailable) {
884 // If server returned an explicit PID, use that.
885 m_curr_pid_run = m_curr_pid = ids.front().first;
886 // Otherwise, use the TID of the first thread (Linux hack).
888 m_curr_pid_run = m_curr_pid = ids.front().second;
890 return m_curr_pid;
891 }
892 }
893 }
894
896}
897
899 if (!args.GetArgumentAtIndex(0))
900 return llvm::createStringError(llvm::inconvertibleErrorCode(),
901 "Nothing to launch");
902 // try vRun first
903 if (m_supports_vRun) {
904 StreamString packet;
905 packet.PutCString("vRun");
906 for (const Args::ArgEntry &arg : args) {
907 packet.PutChar(';');
908 packet.PutStringAsRawHex8(arg.ref());
909 }
910
912 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
914 return llvm::createStringError(llvm::inconvertibleErrorCode(),
915 "Sending vRun packet failed");
916
917 if (response.IsErrorResponse())
918 return response.GetStatus().ToError();
919
920 // vRun replies with a stop reason packet
921 // FIXME: right now we just discard the packet and LLDB queries
922 // for stop reason again
923 if (!response.IsUnsupportedResponse())
924 return llvm::Error::success();
925
926 m_supports_vRun = false;
927 }
928
929 // fallback to A
930 StreamString packet;
931 packet.PutChar('A');
932 llvm::ListSeparator LS(",");
933 for (const auto &arg : llvm::enumerate(args)) {
934 packet << LS;
935 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index());
936 packet.PutStringAsRawHex8(arg.value().ref());
937 }
938
940 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
942 return llvm::createStringError(llvm::inconvertibleErrorCode(),
943 "Sending A packet failed");
944 }
945 if (!response.IsOKResponse())
946 return response.GetStatus().ToError();
947
948 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
950 return llvm::createStringError(llvm::inconvertibleErrorCode(),
951 "Sending qLaunchSuccess packet failed");
952 }
953 if (response.IsOKResponse())
954 return llvm::Error::success();
955 if (response.GetChar() == 'E') {
956 return llvm::createStringError(llvm::inconvertibleErrorCode(),
957 response.GetStringRef().substr(1));
958 }
959 return llvm::createStringError(llvm::inconvertibleErrorCode(),
960 "unknown error occurred launching process");
961}
962
964 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
965 for (const auto &kv : env)
966 vec.emplace_back(kv.first(), kv.second);
967 llvm::sort(vec, llvm::less_first());
968 for (const auto &[k, v] : vec) {
969 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
970 if (r != 0)
971 return r;
972 }
973 return 0;
974}
975
977 char const *name_equal_value) {
978 if (name_equal_value && name_equal_value[0]) {
979 bool send_hex_encoding = false;
980 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
981 ++p) {
982 if (llvm::isPrint(*p)) {
983 switch (*p) {
984 case '$':
985 case '#':
986 case '*':
987 case '}':
988 send_hex_encoding = true;
989 break;
990 default:
991 break;
992 }
993 } else {
994 // We have non printable characters, lets hex encode this...
995 send_hex_encoding = true;
996 }
997 }
998
1000 // Prefer sending unencoded, if possible and the server supports it.
1001 if (!send_hex_encoding && m_supports_QEnvironment) {
1002 StreamString packet;
1003 packet.Printf("QEnvironment:%s", name_equal_value);
1004 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1006 return -1;
1007
1008 if (response.IsOKResponse())
1009 return 0;
1010 if (response.IsUnsupportedResponse())
1012 else {
1013 uint8_t error = response.GetError();
1014 if (error)
1015 return error;
1016 return -1;
1017 }
1018 }
1019
1021 StreamString packet;
1022 packet.PutCString("QEnvironmentHexEncoded:");
1023 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
1024 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
1026 return -1;
1027
1028 if (response.IsOKResponse())
1029 return 0;
1030 if (response.IsUnsupportedResponse())
1032 else {
1033 uint8_t error = response.GetError();
1034 if (error)
1035 return error;
1036 return -1;
1037 }
1038 }
1039 }
1040 return -1;
1041}
1042
1044 if (arch && arch[0]) {
1045 StreamString packet;
1046 packet.Printf("QLaunchArch:%s", arch);
1047 StringExtractorGDBRemote response;
1048 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1050 if (response.IsOKResponse())
1051 return 0;
1052 uint8_t error = response.GetError();
1053 if (error)
1054 return error;
1055 }
1056 }
1057 return -1;
1058}
1059
1061 char const *data, bool *was_supported) {
1062 if (data && *data != '\0') {
1063 StreamString packet;
1064 packet.Printf("QSetProcessEvent:%s", data);
1065 StringExtractorGDBRemote response;
1066 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1068 if (response.IsOKResponse()) {
1069 if (was_supported)
1070 *was_supported = true;
1071 return 0;
1072 } else if (response.IsUnsupportedResponse()) {
1073 if (was_supported)
1074 *was_supported = false;
1075 return -1;
1076 } else {
1077 uint8_t error = response.GetError();
1078 if (was_supported)
1079 *was_supported = true;
1080 if (error)
1081 return error;
1082 }
1083 }
1084 }
1085 return -1;
1086}
1087
1089 GetHostInfo();
1090 return m_os_version;
1091}
1092
1097
1099 if (GetHostInfo()) {
1100 if (!m_os_build.empty())
1101 return m_os_build;
1102 }
1103 return std::nullopt;
1104}
1105
1106std::optional<std::string>
1108 if (GetHostInfo()) {
1109 if (!m_os_kernel.empty())
1110 return m_os_kernel;
1111 }
1112 return std::nullopt;
1113}
1114
1116 if (GetHostInfo()) {
1117 if (!m_hostname.empty()) {
1118 s = m_hostname;
1119 return true;
1120 }
1121 }
1122 s.clear();
1123 return false;
1124}
1125
1131
1138
1140 UUID &uuid, addr_t &value, bool &value_is_offset) {
1143
1144 // Return true if we have a UUID or an address/offset of the
1145 // main standalone / firmware binary being used.
1146 if (!m_process_standalone_uuid.IsValid() &&
1148 return false;
1149
1152 value_is_offset = m_process_standalone_value_is_offset;
1153 return true;
1154}
1155
1156std::vector<addr_t>
1162
1165 m_gdb_server_name.clear();
1168
1169 StringExtractorGDBRemote response;
1170 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1172 if (response.IsNormalResponse()) {
1173 llvm::StringRef name, value;
1174 bool success = false;
1175 while (response.GetNameColonValue(name, value)) {
1176 if (name == "name") {
1177 success = true;
1178 m_gdb_server_name = std::string(value);
1179 } else if (name == "version") {
1180 llvm::StringRef major, minor;
1181 std::tie(major, minor) = value.split('.');
1182 if (!major.getAsInteger(0, m_gdb_server_version))
1183 success = true;
1184 }
1185 }
1186 if (success)
1188 }
1189 }
1190 }
1192}
1193
1195 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1197 llvm::StringRef avail_name;
1198
1199#if HAVE_LIBCOMPRESSION
1200 if (avail_type == CompressionType::None) {
1201 for (auto compression : supported_compressions) {
1202 if (compression == "lzfse") {
1203 avail_type = CompressionType::LZFSE;
1204 avail_name = compression;
1205 break;
1206 }
1207 }
1208 }
1209 if (avail_type == CompressionType::None) {
1210 for (auto compression : supported_compressions) {
1211 if (compression == "zlib-deflate") {
1212 avail_type = CompressionType::ZlibDeflate;
1213 avail_name = compression;
1214 break;
1215 }
1216 }
1217 }
1218#endif
1219
1220#if LLVM_ENABLE_ZLIB
1221 if (avail_type == CompressionType::None) {
1222 for (auto compression : supported_compressions) {
1223 if (compression == "zlib-deflate") {
1224 avail_type = CompressionType::ZlibDeflate;
1225 avail_name = compression;
1226 break;
1227 }
1228 }
1229 }
1230#endif
1231
1232#if HAVE_LIBCOMPRESSION
1233 if (avail_type == CompressionType::None) {
1234 for (auto compression : supported_compressions) {
1235 if (compression == "lz4") {
1236 avail_type = CompressionType::LZ4;
1237 avail_name = compression;
1238 break;
1239 }
1240 }
1241 }
1242 if (avail_type == CompressionType::None) {
1243 for (auto compression : supported_compressions) {
1244 if (compression == "lzma") {
1245 avail_type = CompressionType::LZMA;
1246 avail_name = compression;
1247 break;
1248 }
1249 }
1250 }
1251#endif
1252
1253 if (avail_type != CompressionType::None) {
1254 StringExtractorGDBRemote response;
1255 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1256 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1257 return;
1258
1259 if (response.IsOKResponse()) {
1260 m_compression_type = avail_type;
1261 }
1262 }
1263}
1264
1266 if (GetGDBServerVersion()) {
1267 if (!m_gdb_server_name.empty())
1268 return m_gdb_server_name.c_str();
1269 }
1270 return nullptr;
1271}
1272
1278
1280 StringExtractorGDBRemote response;
1282 return false;
1283
1284 if (!response.IsNormalResponse())
1285 return false;
1286
1287 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1288 auto pid_tid = response.GetPidTid(0);
1289 if (!pid_tid)
1290 return false;
1291
1292 lldb::pid_t pid = pid_tid->first;
1293 // invalid
1295 return false;
1296
1297 // if we get pid as well, update m_curr_pid
1298 if (pid != 0) {
1299 m_curr_pid_run = m_curr_pid = pid;
1301 }
1302 tid = pid_tid->second;
1303 }
1304
1305 return true;
1306}
1307
1308static void ParseOSType(llvm::StringRef value, std::string &os_name,
1309 std::string &environment) {
1310 if (value == "iossimulator" || value == "tvossimulator" ||
1311 value == "watchossimulator" || value == "xrossimulator" ||
1312 value == "visionossimulator") {
1313 environment = "simulator";
1314 os_name = value.drop_back(environment.size()).str();
1315 } else if (value == "maccatalyst") {
1316 os_name = "ios";
1317 environment = "macabi";
1318 } else {
1319 os_name = value.str();
1320 }
1321}
1322
1324 Log *log = GetLog(GDBRLog::Process);
1325
1326 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1327 // host info computation can require DNS traffic and shelling out to external processes.
1328 // Increase the timeout to account for that.
1329 ScopedTimeout timeout(*this, seconds(10));
1331 StringExtractorGDBRemote response;
1332 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1334 if (response.IsNormalResponse()) {
1335 llvm::StringRef name;
1336 llvm::StringRef value;
1337 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1338 uint32_t sub = 0;
1339 std::string arch_name;
1340 std::string os_name;
1341 std::string environment;
1342 std::string vendor_name;
1343 std::string triple;
1344 uint32_t pointer_byte_size = 0;
1345 ByteOrder byte_order = eByteOrderInvalid;
1346 uint32_t num_keys_decoded = 0;
1347 while (response.GetNameColonValue(name, value)) {
1348 if (name == "cputype") {
1349 // exception type in big endian hex
1350 if (!value.getAsInteger(0, cpu))
1351 ++num_keys_decoded;
1352 } else if (name == "cpusubtype") {
1353 // exception count in big endian hex
1354 if (!value.getAsInteger(0, sub))
1355 ++num_keys_decoded;
1356 } else if (name == "arch") {
1357 arch_name = std::string(value);
1358 ++num_keys_decoded;
1359 } else if (name == "triple") {
1360 StringExtractor extractor(value);
1361 extractor.GetHexByteString(triple);
1362 ++num_keys_decoded;
1363 } else if (name == "distribution_id") {
1364 StringExtractor extractor(value);
1366 ++num_keys_decoded;
1367 } else if (name == "os_build") {
1368 StringExtractor extractor(value);
1369 extractor.GetHexByteString(m_os_build);
1370 ++num_keys_decoded;
1371 } else if (name == "hostname") {
1372 StringExtractor extractor(value);
1373 extractor.GetHexByteString(m_hostname);
1374 ++num_keys_decoded;
1375 } else if (name == "os_kernel") {
1376 StringExtractor extractor(value);
1377 extractor.GetHexByteString(m_os_kernel);
1378 ++num_keys_decoded;
1379 } else if (name == "ostype") {
1380 ParseOSType(value, os_name, environment);
1381 ++num_keys_decoded;
1382 } else if (name == "vendor") {
1383 vendor_name = std::string(value);
1384 ++num_keys_decoded;
1385 } else if (name == "endian") {
1386 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1387 .Case("little", eByteOrderLittle)
1388 .Case("big", eByteOrderBig)
1389 .Case("pdp", eByteOrderPDP)
1390 .Default(eByteOrderInvalid);
1391 if (byte_order != eByteOrderInvalid)
1392 ++num_keys_decoded;
1393 } else if (name == "ptrsize") {
1394 if (!value.getAsInteger(0, pointer_byte_size))
1395 ++num_keys_decoded;
1396 } else if (name == "addressing_bits") {
1397 if (!value.getAsInteger(0, m_low_mem_addressing_bits)) {
1398 ++num_keys_decoded;
1399 }
1400 } else if (name == "high_mem_addressing_bits") {
1401 if (!value.getAsInteger(0, m_high_mem_addressing_bits))
1402 ++num_keys_decoded;
1403 } else if (name == "low_mem_addressing_bits") {
1404 if (!value.getAsInteger(0, m_low_mem_addressing_bits))
1405 ++num_keys_decoded;
1406 } else if (name == "os_version" ||
1407 name == "version") // Older debugserver binaries used
1408 // the "version" key instead of
1409 // "os_version"...
1410 {
1411 if (!m_os_version.tryParse(value))
1412 ++num_keys_decoded;
1413 } else if (name == "maccatalyst_version") {
1414 if (!m_maccatalyst_version.tryParse(value))
1415 ++num_keys_decoded;
1416 } else if (name == "watchpoint_exceptions_received") {
1418 llvm::StringSwitch<LazyBool>(value)
1419 .Case("before", eLazyBoolNo)
1420 .Case("after", eLazyBoolYes)
1421 .Default(eLazyBoolCalculate);
1423 ++num_keys_decoded;
1424 } else if (name == "default_packet_timeout") {
1425 uint32_t timeout_seconds;
1426 if (!value.getAsInteger(0, timeout_seconds)) {
1427 m_default_packet_timeout = seconds(timeout_seconds);
1429 ++num_keys_decoded;
1430 }
1431 } else if (name == "vm-page-size") {
1432 int page_size;
1433 if (!value.getAsInteger(0, page_size)) {
1434 m_target_vm_page_size = page_size;
1435 ++num_keys_decoded;
1436 }
1437 }
1438 }
1439
1440 if (num_keys_decoded > 0)
1442
1443 if (triple.empty()) {
1444 if (arch_name.empty()) {
1445 if (cpu != LLDB_INVALID_CPUTYPE) {
1446 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1447 if (pointer_byte_size) {
1448 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1449 }
1450 if (byte_order != eByteOrderInvalid) {
1451 assert(byte_order == m_host_arch.GetByteOrder());
1452 }
1453
1454 if (!vendor_name.empty())
1455 m_host_arch.GetTriple().setVendorName(
1456 llvm::StringRef(vendor_name));
1457 if (!os_name.empty())
1458 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1459 if (!environment.empty())
1460 m_host_arch.GetTriple().setEnvironmentName(environment);
1461 }
1462 } else {
1463 std::string triple;
1464 triple += arch_name;
1465 if (!vendor_name.empty() || !os_name.empty()) {
1466 triple += '-';
1467 if (vendor_name.empty())
1468 triple += "unknown";
1469 else
1470 triple += vendor_name;
1471 triple += '-';
1472 if (os_name.empty())
1473 triple += "unknown";
1474 else
1475 triple += os_name;
1476 }
1477 m_host_arch.SetTriple(triple.c_str());
1478
1479 llvm::Triple &host_triple = m_host_arch.GetTriple();
1480 if (host_triple.getVendor() == llvm::Triple::Apple &&
1481 host_triple.getOS() == llvm::Triple::Darwin) {
1482 switch (m_host_arch.GetMachine()) {
1483 case llvm::Triple::aarch64:
1484 case llvm::Triple::aarch64_32:
1485 case llvm::Triple::arm:
1486 case llvm::Triple::thumb:
1487 host_triple.setOS(llvm::Triple::IOS);
1488 break;
1489 default:
1490 host_triple.setOS(llvm::Triple::MacOSX);
1491 break;
1492 }
1493 }
1494 if (pointer_byte_size) {
1495 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1496 }
1497 if (byte_order != eByteOrderInvalid) {
1498 assert(byte_order == m_host_arch.GetByteOrder());
1499 }
1500 }
1501 } else {
1502 m_host_arch.SetTriple(triple.c_str());
1503 if (pointer_byte_size) {
1504 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1505 }
1506 if (byte_order != eByteOrderInvalid) {
1507 assert(byte_order == m_host_arch.GetByteOrder());
1508 }
1509
1510 LLDB_LOGF(log,
1511 "GDBRemoteCommunicationClient::%s parsed host "
1512 "architecture as %s, triple as %s from triple text %s",
1513 __FUNCTION__,
1514 m_host_arch.GetArchitectureName()
1515 ? m_host_arch.GetArchitectureName()
1516 : "<null-arch-name>",
1517 m_host_arch.GetTriple().getTriple().c_str(),
1518 triple.c_str());
1519 }
1520 }
1521 }
1522 }
1524}
1525
1527 const char *data, size_t data_len, std::chrono::seconds interrupt_timeout) {
1528 StreamString packet;
1529 packet.PutCString("I");
1530 packet.PutBytesAsRawHex8(data, data_len);
1531 StringExtractorGDBRemote response;
1532 if (SendPacketAndWaitForResponse(packet.GetString(), response,
1533 interrupt_timeout) ==
1535 return 0;
1536 }
1537 return response.GetError();
1538}
1539
1546
1559
1565
1567 uint32_t permissions) {
1570 char packet[64];
1571 const int packet_len = ::snprintf(
1572 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1573 permissions & lldb::ePermissionsReadable ? "r" : "",
1574 permissions & lldb::ePermissionsWritable ? "w" : "",
1575 permissions & lldb::ePermissionsExecutable ? "x" : "");
1576 assert(packet_len < (int)sizeof(packet));
1577 UNUSED_IF_ASSERT_DISABLED(packet_len);
1578 StringExtractorGDBRemote response;
1579 if (SendPacketAndWaitForResponse(packet, response) ==
1581 if (response.IsUnsupportedResponse())
1583 else if (!response.IsErrorResponse())
1584 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1585 } else {
1587 }
1588 }
1589 return LLDB_INVALID_ADDRESS;
1590}
1591
1595 char packet[64];
1596 const int packet_len =
1597 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1598 assert(packet_len < (int)sizeof(packet));
1599 UNUSED_IF_ASSERT_DISABLED(packet_len);
1600 StringExtractorGDBRemote response;
1601 if (SendPacketAndWaitForResponse(packet, response) ==
1603 if (response.IsUnsupportedResponse())
1605 else if (response.IsOKResponse())
1606 return true;
1607 } else {
1609 }
1610 }
1611 return false;
1612}
1613
1615 lldb::pid_t pid) {
1616 Status error;
1618
1619 packet.PutChar('D');
1620 if (keep_stopped) {
1622 char packet[64];
1623 const int packet_len =
1624 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1625 assert(packet_len < (int)sizeof(packet));
1626 UNUSED_IF_ASSERT_DISABLED(packet_len);
1627 StringExtractorGDBRemote response;
1628 if (SendPacketAndWaitForResponse(packet, response) ==
1630 response.IsOKResponse()) {
1632 } else {
1634 }
1635 }
1636
1639 "Stays stopped not supported by this target.");
1640 return error;
1641 } else {
1642 packet.PutChar('1');
1643 }
1644 }
1645
1647 // Some servers (e.g. qemu) require specifying the PID even if only a single
1648 // process is running.
1649 if (pid == LLDB_INVALID_PROCESS_ID)
1650 pid = GetCurrentProcessID();
1651 packet.PutChar(';');
1652 packet.PutHex64(pid);
1653 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1655 "Multiprocess extension not supported by the server.");
1656 return error;
1657 }
1658
1659 StringExtractorGDBRemote response;
1660 PacketResult packet_result =
1661 SendPacketAndWaitForResponse(packet.GetString(), response);
1662 if (packet_result != PacketResult::Success)
1663 error = Status::FromErrorString("Sending disconnect packet failed.");
1664 return error;
1665}
1666
1668 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1669 Status error;
1670 region_info.Clear();
1671
1674 char packet[64];
1675 const int packet_len = ::snprintf(
1676 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1677 assert(packet_len < (int)sizeof(packet));
1678 UNUSED_IF_ASSERT_DISABLED(packet_len);
1679 StringExtractorGDBRemote response;
1680 if (SendPacketAndWaitForResponse(packet, response) ==
1683 llvm::StringRef name;
1684 llvm::StringRef value;
1685 addr_t addr_value = LLDB_INVALID_ADDRESS;
1686 bool success = true;
1687 bool saw_permissions = false;
1688 while (success && response.GetNameColonValue(name, value)) {
1689 if (name == "start") {
1690 if (!value.getAsInteger(16, addr_value))
1691 region_info.GetRange().SetRangeBase(addr_value);
1692 } else if (name == "size") {
1693 if (!value.getAsInteger(16, addr_value)) {
1694 region_info.GetRange().SetByteSize(addr_value);
1695 if (region_info.GetRange().GetRangeEnd() <
1696 region_info.GetRange().GetRangeBase()) {
1697 // Range size overflowed, truncate it.
1699 }
1700 }
1701 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1702 saw_permissions = true;
1703 if (region_info.GetRange().Contains(addr)) {
1704 if (value.contains('r'))
1705 region_info.SetReadable(eLazyBoolYes);
1706 else
1707 region_info.SetReadable(eLazyBoolNo);
1708
1709 if (value.contains('w'))
1710 region_info.SetWritable(eLazyBoolYes);
1711 else
1712 region_info.SetWritable(eLazyBoolNo);
1713
1714 if (value.contains('x'))
1715 region_info.SetExecutable(eLazyBoolYes);
1716 else
1717 region_info.SetExecutable(eLazyBoolNo);
1718
1719 region_info.SetMapped(eLazyBoolYes);
1720 } else {
1721 // The reported region does not contain this address -- we're
1722 // looking at an unmapped page
1723 region_info.SetReadable(eLazyBoolNo);
1724 region_info.SetWritable(eLazyBoolNo);
1725 region_info.SetExecutable(eLazyBoolNo);
1726 region_info.SetMapped(eLazyBoolNo);
1727 }
1728 } else if (name == "name") {
1729 StringExtractorGDBRemote name_extractor(value);
1730 std::string name;
1731 name_extractor.GetHexByteString(name);
1732 region_info.SetName(name.c_str());
1733 } else if (name == "flags") {
1734 region_info.SetMemoryTagged(eLazyBoolNo);
1735 region_info.SetIsShadowStack(eLazyBoolNo);
1736
1737 llvm::StringRef flags = value;
1738 llvm::StringRef flag;
1739 while (flags.size()) {
1740 flags = flags.ltrim();
1741 std::tie(flag, flags) = flags.split(' ');
1742 // To account for trailing whitespace
1743 if (flag.size()) {
1744 if (flag == "mt")
1745 region_info.SetMemoryTagged(eLazyBoolYes);
1746 else if (flag == "ss")
1747 region_info.SetIsShadowStack(eLazyBoolYes);
1748 }
1749 }
1750 } else if (name == "type") {
1751 for (llvm::StringRef entry : llvm::split(value, ',')) {
1752 if (entry == "stack")
1753 region_info.SetIsStackMemory(eLazyBoolYes);
1754 else if (entry == "heap")
1755 region_info.SetIsStackMemory(eLazyBoolNo);
1756 }
1757 } else if (name == "error") {
1758 StringExtractorGDBRemote error_extractor(value);
1759 std::string error_string;
1760 // Now convert the HEX bytes into a string value
1761 error_extractor.GetHexByteString(error_string);
1762 error = Status::FromErrorString(error_string.c_str());
1763 } else if (name == "dirty-pages") {
1764 std::vector<addr_t> dirty_page_list;
1765 for (llvm::StringRef x : llvm::split(value, ',')) {
1766 addr_t page;
1767 x.consume_front("0x");
1768 if (llvm::to_integer(x, page, 16))
1769 dirty_page_list.push_back(page);
1770 }
1771 region_info.SetDirtyPageList(dirty_page_list);
1772 } else if (name == "protection-key") {
1773 unsigned protection_key = 0;
1774 if (!value.getAsInteger(10, protection_key))
1775 region_info.SetProtectionKey(protection_key);
1776 }
1777 }
1778
1779 if (m_target_vm_page_size != 0)
1781
1782 if (region_info.GetRange().IsValid()) {
1783 // We got a valid address range back but no permissions -- which means
1784 // this is an unmapped page
1785 if (!saw_permissions) {
1786 region_info.SetReadable(eLazyBoolNo);
1787 region_info.SetWritable(eLazyBoolNo);
1788 region_info.SetExecutable(eLazyBoolNo);
1789 region_info.SetMapped(eLazyBoolNo);
1790 }
1791 } else {
1792 // We got an invalid address range back
1793 error = Status::FromErrorString("Server returned invalid range");
1794 }
1795 } else {
1797 }
1798 }
1799
1801 error = Status::FromErrorString("qMemoryRegionInfo is not supported");
1802 }
1803
1804 // Try qXfer:memory-map:read to get region information not included in
1805 // qMemoryRegionInfo
1806 MemoryRegionInfo qXfer_region_info;
1807 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1808
1809 if (error.Fail()) {
1810 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1811 // the qXfer result as a fallback
1812 if (qXfer_error.Success()) {
1813 region_info = qXfer_region_info;
1814 error.Clear();
1815 } else {
1816 region_info.Clear();
1817 }
1818 } else if (qXfer_error.Success()) {
1819 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1820 // both regions are the same range, update the result to include the flash-
1821 // memory information that is specific to the qXfer result.
1822 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1823 region_info.SetFlash(qXfer_region_info.GetFlash());
1824 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1825 }
1826 }
1827 return error;
1828}
1829
1831 lldb::addr_t addr, MemoryRegionInfo &region) {
1833 if (!error.Success())
1834 return error;
1835 for (const auto &map_region : m_qXfer_memory_map) {
1836 if (map_region.GetRange().Contains(addr)) {
1837 region = map_region;
1838 return error;
1839 }
1840 }
1841 error = Status::FromErrorString("Region not found");
1842 return error;
1843}
1844
1846
1847 Status error;
1848
1850 // Already loaded, return success
1851 return error;
1852
1853 if (!XMLDocument::XMLEnabled()) {
1854 error = Status::FromErrorString("XML is not supported");
1855 return error;
1856 }
1857
1859 error = Status::FromErrorString("Memory map is not supported");
1860 return error;
1861 }
1862
1863 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1864 if (!xml)
1865 return Status::FromError(xml.takeError());
1866
1867 XMLDocument xml_document;
1868
1869 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1870 error = Status::FromErrorString("Failed to parse memory map xml");
1871 return error;
1872 }
1873
1874 XMLNode map_node = xml_document.GetRootElement("memory-map");
1875 if (!map_node) {
1876 error = Status::FromErrorString("Invalid root node in memory map xml");
1877 return error;
1878 }
1879
1880 m_qXfer_memory_map.clear();
1881
1882 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1883 if (!memory_node.IsElement())
1884 return true;
1885 if (memory_node.GetName() != "memory")
1886 return true;
1887 auto type = memory_node.GetAttributeValue("type", "");
1888 uint64_t start;
1889 uint64_t length;
1890 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1891 return true;
1892 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1893 return true;
1894 MemoryRegionInfo region;
1895 region.GetRange().SetRangeBase(start);
1896 region.GetRange().SetByteSize(length);
1897 if (type == "rom") {
1898 region.SetReadable(eLazyBoolYes);
1899 this->m_qXfer_memory_map.push_back(region);
1900 } else if (type == "ram") {
1901 region.SetReadable(eLazyBoolYes);
1902 region.SetWritable(eLazyBoolYes);
1903 this->m_qXfer_memory_map.push_back(region);
1904 } else if (type == "flash") {
1905 region.SetFlash(eLazyBoolYes);
1906 memory_node.ForEachChildElement(
1907 [&region](const XMLNode &prop_node) -> bool {
1908 if (!prop_node.IsElement())
1909 return true;
1910 if (prop_node.GetName() != "property")
1911 return true;
1912 auto propname = prop_node.GetAttributeValue("name", "");
1913 if (propname == "blocksize") {
1914 uint64_t blocksize;
1915 if (prop_node.GetElementTextAsUnsigned(blocksize))
1916 region.SetBlocksize(blocksize);
1917 }
1918 return true;
1919 });
1920 this->m_qXfer_memory_map.push_back(region);
1921 }
1922 return true;
1923 });
1924
1926
1927 return error;
1928}
1929
1933 }
1934
1935 std::optional<uint32_t> num;
1937 StringExtractorGDBRemote response;
1938 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
1941 llvm::StringRef name;
1942 llvm::StringRef value;
1943 while (response.GetNameColonValue(name, value)) {
1944 if (name == "num") {
1945 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1947 }
1948 }
1949 if (!num) {
1951 }
1952 } else {
1954 }
1955 }
1956
1957 return num;
1958}
1959
1960WatchpointHardwareFeature
1964
1967 GetHostInfo();
1968
1969 // Process determines this by target CPU, but allow for the
1970 // remote stub to override it via the qHostInfo
1971 // watchpoint_exceptions_received key, if it is present.
1974 return false;
1976 return true;
1977 }
1978
1979 return std::nullopt;
1980}
1981
1983 if (file_spec) {
1984 std::string path{file_spec.GetPath(false)};
1985 StreamString packet;
1986 packet.PutCString("QSetSTDIN:");
1987 packet.PutStringAsRawHex8(path);
1988
1989 StringExtractorGDBRemote response;
1990 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1992 if (response.IsOKResponse())
1993 return 0;
1994 uint8_t error = response.GetError();
1995 if (error)
1996 return error;
1997 }
1998 }
1999 return -1;
2000}
2001
2003 if (file_spec) {
2004 std::string path{file_spec.GetPath(false)};
2005 StreamString packet;
2006 packet.PutCString("QSetSTDOUT:");
2007 packet.PutStringAsRawHex8(path);
2008
2009 StringExtractorGDBRemote response;
2010 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2012 if (response.IsOKResponse())
2013 return 0;
2014 uint8_t error = response.GetError();
2015 if (error)
2016 return error;
2017 }
2018 }
2019 return -1;
2020}
2021
2023 if (file_spec) {
2024 std::string path{file_spec.GetPath(false)};
2025 StreamString packet;
2026 packet.PutCString("QSetSTDERR:");
2027 packet.PutStringAsRawHex8(path);
2028
2029 StringExtractorGDBRemote response;
2030 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2032 if (response.IsOKResponse())
2033 return 0;
2034 uint8_t error = response.GetError();
2035 if (error)
2036 return error;
2037 }
2038 }
2039 return -1;
2040}
2041
2043 uint16_t rows) {
2044 // The size is only valid if both or none of the dimensions are zero.
2045 if ((cols == 0) != (rows == 0))
2046 return -1;
2047 StreamString packet;
2048 packet.Printf("QSetSTDIOWindowSize:cols=%u;rows=%u",
2049 static_cast<unsigned>(cols), static_cast<unsigned>(rows));
2050 StringExtractorGDBRemote response;
2051 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
2053 return -1;
2054 if (response.IsOKResponse())
2055 return 0;
2056 if (response.IsUnsupportedResponse())
2057 return 0;
2058 uint8_t error = response.GetError();
2059 return error ? error : -1;
2060}
2061
2063 StringExtractorGDBRemote response;
2064 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
2066 if (response.IsUnsupportedResponse())
2067 return false;
2068 if (response.IsErrorResponse())
2069 return false;
2070 std::string cwd;
2071 response.GetHexByteString(cwd);
2072 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
2073 return !cwd.empty();
2074 }
2075 return false;
2076}
2077
2079 if (working_dir) {
2080 std::string path{working_dir.GetPath(false)};
2081 StreamString packet;
2082 packet.PutCString("QSetWorkingDir:");
2083 packet.PutStringAsRawHex8(path);
2084
2085 StringExtractorGDBRemote response;
2086 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2088 if (response.IsOKResponse())
2089 return 0;
2090 uint8_t error = response.GetError();
2091 if (error)
2092 return error;
2093 }
2094 }
2095 return -1;
2096}
2097
2099 char packet[32];
2100 const int packet_len =
2101 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2102 assert(packet_len < (int)sizeof(packet));
2103 UNUSED_IF_ASSERT_DISABLED(packet_len);
2104 StringExtractorGDBRemote response;
2105 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2106 if (response.IsOKResponse())
2107 return 0;
2108 uint8_t error = response.GetError();
2109 if (error)
2110 return error;
2111 }
2112 return -1;
2113}
2114
2116 char packet[32];
2117 const int packet_len = ::snprintf(packet, sizeof(packet),
2118 "QSetDetachOnError:%i", enable ? 1 : 0);
2119 assert(packet_len < (int)sizeof(packet));
2120 UNUSED_IF_ASSERT_DISABLED(packet_len);
2121 StringExtractorGDBRemote response;
2122 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
2123 if (response.IsOKResponse())
2124 return 0;
2125 uint8_t error = response.GetError();
2126 if (error)
2127 return error;
2128 }
2129 return -1;
2130}
2131
2133 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2134 if (response.IsNormalResponse()) {
2135 llvm::StringRef name;
2136 llvm::StringRef value;
2137 StringExtractor extractor;
2138
2139 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2140 uint32_t sub = 0;
2141 std::string vendor;
2142 std::string os_type;
2143
2144 while (response.GetNameColonValue(name, value)) {
2145 if (name == "pid") {
2147 value.getAsInteger(0, pid);
2148 process_info.SetProcessID(pid);
2149 } else if (name == "ppid") {
2151 value.getAsInteger(0, pid);
2152 process_info.SetParentProcessID(pid);
2153 } else if (name == "uid") {
2154 uint32_t uid = UINT32_MAX;
2155 value.getAsInteger(0, uid);
2156 process_info.SetUserID(uid);
2157 } else if (name == "euid") {
2158 uint32_t uid = UINT32_MAX;
2159 value.getAsInteger(0, uid);
2160 process_info.SetEffectiveUserID(uid);
2161 } else if (name == "gid") {
2162 uint32_t gid = UINT32_MAX;
2163 value.getAsInteger(0, gid);
2164 process_info.SetGroupID(gid);
2165 } else if (name == "egid") {
2166 uint32_t gid = UINT32_MAX;
2167 value.getAsInteger(0, gid);
2168 process_info.SetEffectiveGroupID(gid);
2169 } else if (name == "triple") {
2170 StringExtractor extractor(value);
2171 std::string triple;
2172 extractor.GetHexByteString(triple);
2173 process_info.GetArchitecture().SetTriple(triple.c_str());
2174 } else if (name == "name") {
2175 StringExtractor extractor(value);
2176 // The process name from ASCII hex bytes since we can't control the
2177 // characters in a process name
2178 std::string name;
2179 extractor.GetHexByteString(name);
2180 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2181 } else if (name == "args") {
2182 llvm::StringRef encoded_args(value), hex_arg;
2183
2184 bool is_arg0 = true;
2185 while (!encoded_args.empty()) {
2186 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2187 std::string arg;
2188 StringExtractor extractor(hex_arg);
2189 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2190 // In case of wrong encoding, we discard all the arguments
2191 process_info.GetArguments().Clear();
2192 process_info.SetArg0("");
2193 break;
2194 }
2195 if (is_arg0)
2196 process_info.SetArg0(arg);
2197 else
2198 process_info.GetArguments().AppendArgument(arg);
2199 is_arg0 = false;
2200 }
2201 } else if (name == "cputype") {
2202 value.getAsInteger(0, cpu);
2203 } else if (name == "cpusubtype") {
2204 value.getAsInteger(0, sub);
2205 } else if (name == "vendor") {
2206 vendor = std::string(value);
2207 } else if (name == "ostype") {
2208 os_type = std::string(value);
2209 }
2210 }
2211
2212 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2213 if (vendor == "apple") {
2215 sub);
2216 process_info.GetArchitecture().GetTriple().setVendorName(
2217 llvm::StringRef(vendor));
2218 process_info.GetArchitecture().GetTriple().setOSName(
2219 llvm::StringRef(os_type));
2220 }
2221 }
2222
2223 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2224 return true;
2225 }
2226 return false;
2227}
2228
2230 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2231 process_info.Clear();
2232
2234 char packet[32];
2235 const int packet_len =
2236 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2237 assert(packet_len < (int)sizeof(packet));
2238 UNUSED_IF_ASSERT_DISABLED(packet_len);
2239 StringExtractorGDBRemote response;
2240 if (SendPacketAndWaitForResponse(packet, response) ==
2242 return DecodeProcessInfoResponse(response, process_info);
2243 } else {
2245 return false;
2246 }
2247 }
2248 return false;
2249}
2250
2253
2254 if (allow_lazy) {
2256 return true;
2258 return false;
2259 }
2260
2261 GetHostInfo();
2262
2263 StringExtractorGDBRemote response;
2264 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2266 if (response.IsNormalResponse()) {
2267 llvm::StringRef name;
2268 llvm::StringRef value;
2269 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2270 uint32_t sub = 0;
2271 std::string os_name;
2272 std::string environment;
2273 std::string vendor_name;
2274 std::string triple;
2275 std::string elf_abi;
2276 uint32_t pointer_byte_size = 0;
2277 StringExtractor extractor;
2278 ByteOrder byte_order = eByteOrderInvalid;
2279 uint32_t num_keys_decoded = 0;
2281 while (response.GetNameColonValue(name, value)) {
2282 if (name == "cputype") {
2283 if (!value.getAsInteger(16, cpu))
2284 ++num_keys_decoded;
2285 } else if (name == "cpusubtype") {
2286 if (!value.getAsInteger(16, sub)) {
2287 ++num_keys_decoded;
2288 // Workaround for pre-2024 Apple debugserver, which always
2289 // returns arm64e on arm64e-capable hardware regardless of
2290 // what the process is. This can be deleted at some point
2291 // in the future.
2292 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2293 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2294 if (GetGDBServerVersion())
2295 if (m_gdb_server_version >= 1000 &&
2296 m_gdb_server_version <= 1504)
2297 sub = 0;
2298 }
2299 }
2300 } else if (name == "triple") {
2301 StringExtractor extractor(value);
2302 extractor.GetHexByteString(triple);
2303 ++num_keys_decoded;
2304 } else if (name == "ostype") {
2305 ParseOSType(value, os_name, environment);
2306 ++num_keys_decoded;
2307 } else if (name == "vendor") {
2308 vendor_name = std::string(value);
2309 ++num_keys_decoded;
2310 } else if (name == "endian") {
2311 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2312 .Case("little", eByteOrderLittle)
2313 .Case("big", eByteOrderBig)
2314 .Case("pdp", eByteOrderPDP)
2315 .Default(eByteOrderInvalid);
2316 if (byte_order != eByteOrderInvalid)
2317 ++num_keys_decoded;
2318 } else if (name == "ptrsize") {
2319 if (!value.getAsInteger(16, pointer_byte_size))
2320 ++num_keys_decoded;
2321 } else if (name == "pid") {
2322 if (!value.getAsInteger(16, pid))
2323 ++num_keys_decoded;
2324 } else if (name == "elf_abi") {
2325 elf_abi = std::string(value);
2326 ++num_keys_decoded;
2327 } else if (name == "main-binary-uuid") {
2328 m_process_standalone_uuid.SetFromStringRef(value);
2329 ++num_keys_decoded;
2330 } else if (name == "main-binary-slide") {
2331 StringExtractor extractor(value);
2333 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2336 ++num_keys_decoded;
2337 }
2338 } else if (name == "main-binary-address") {
2339 StringExtractor extractor(value);
2341 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2344 ++num_keys_decoded;
2345 }
2346 } else if (name == "binary-addresses") {
2347 m_binary_addresses.clear();
2348 ++num_keys_decoded;
2349 for (llvm::StringRef x : llvm::split(value, ',')) {
2350 addr_t vmaddr;
2351 x.consume_front("0x");
2352 if (llvm::to_integer(x, vmaddr, 16))
2353 m_binary_addresses.push_back(vmaddr);
2354 }
2355 }
2356 }
2357 if (num_keys_decoded > 0)
2359 if (pid != LLDB_INVALID_PROCESS_ID) {
2361 m_curr_pid_run = m_curr_pid = pid;
2362 }
2363
2364 // Set the ArchSpec from the triple if we have it.
2365 if (!triple.empty()) {
2366 m_process_arch.SetTriple(triple.c_str());
2367 m_process_arch.SetFlags(elf_abi);
2368 if (pointer_byte_size) {
2369 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2370 }
2371 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2372 !vendor_name.empty()) {
2373 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2374 if (!environment.empty())
2375 triple.setEnvironmentName(environment);
2376
2377 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2378 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2379 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2380 switch (triple.getObjectFormat()) {
2381 case llvm::Triple::MachO:
2382 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2383 break;
2384 case llvm::Triple::ELF:
2385 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2386 break;
2387 case llvm::Triple::COFF:
2388 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2389 break;
2390 case llvm::Triple::GOFF:
2391 case llvm::Triple::SPIRV:
2392 case llvm::Triple::Wasm:
2393 case llvm::Triple::XCOFF:
2394 case llvm::Triple::DXContainer:
2395 LLDB_LOGF(log, "error: not supported target architecture");
2396 return false;
2397 case llvm::Triple::UnknownObjectFormat:
2398 LLDB_LOGF(log, "error: failed to determine target architecture");
2399 return false;
2400 }
2401
2402 if (pointer_byte_size) {
2403 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2404 }
2405 if (byte_order != eByteOrderInvalid) {
2406 assert(byte_order == m_process_arch.GetByteOrder());
2407 }
2408 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2409 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2410 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2411 }
2412 return true;
2413 }
2414 } else {
2416 }
2417
2418 return false;
2419}
2420
2422 const ProcessInstanceInfoMatch &match_info,
2423 ProcessInstanceInfoList &process_infos) {
2424 process_infos.clear();
2425
2427 StreamString packet;
2428 packet.PutCString("qfProcessInfo");
2429 if (!match_info.MatchAllProcesses()) {
2430 packet.PutChar(':');
2431 llvm::StringRef name = match_info.GetProcessInfo().GetName();
2432 bool has_name_match = false;
2433 if (!name.empty()) {
2434 has_name_match = true;
2435 NameMatch name_match_type = match_info.GetNameMatchType();
2436 switch (name_match_type) {
2437 case NameMatch::Ignore:
2438 has_name_match = false;
2439 break;
2440
2441 case NameMatch::Equals:
2442 packet.PutCString("name_match:equals;");
2443 break;
2444
2446 packet.PutCString("name_match:contains;");
2447 break;
2448
2450 packet.PutCString("name_match:starts_with;");
2451 break;
2452
2454 packet.PutCString("name_match:ends_with;");
2455 break;
2456
2458 packet.PutCString("name_match:regex;");
2459 break;
2460 }
2461 if (has_name_match) {
2462 packet.PutCString("name:");
2463 packet.PutBytesAsRawHex8(name.data(), name.size());
2464 packet.PutChar(';');
2465 }
2466 }
2467
2468 if (match_info.GetProcessInfo().ProcessIDIsValid())
2469 packet.Printf("pid:%" PRIu64 ";",
2470 match_info.GetProcessInfo().GetProcessID());
2471 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2472 packet.Printf("parent_pid:%" PRIu64 ";",
2473 match_info.GetProcessInfo().GetParentProcessID());
2474 if (match_info.GetProcessInfo().UserIDIsValid())
2475 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2476 if (match_info.GetProcessInfo().GroupIDIsValid())
2477 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2478 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2479 packet.Printf("euid:%u;",
2480 match_info.GetProcessInfo().GetEffectiveUserID());
2481 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2482 packet.Printf("egid:%u;",
2483 match_info.GetProcessInfo().GetEffectiveGroupID());
2484 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2485 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2486 const ArchSpec &match_arch =
2487 match_info.GetProcessInfo().GetArchitecture();
2488 const llvm::Triple &triple = match_arch.GetTriple();
2489 packet.PutCString("triple:");
2490 packet.PutCString(triple.getTriple());
2491 packet.PutChar(';');
2492 }
2493 }
2494 StringExtractorGDBRemote response;
2495 // Increase timeout as the first qfProcessInfo packet takes a long time on
2496 // Android. The value of 1min was arrived at empirically.
2497 ScopedTimeout timeout(*this, minutes(1));
2498 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2500 do {
2501 ProcessInstanceInfo process_info;
2502 if (!DecodeProcessInfoResponse(response, process_info))
2503 break;
2504 process_infos.push_back(process_info);
2505 response = StringExtractorGDBRemote();
2506 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2508 } else {
2510 return 0;
2511 }
2512 }
2513 return process_infos.size();
2514}
2515
2517 std::string &name) {
2519 char packet[32];
2520 const int packet_len =
2521 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2522 assert(packet_len < (int)sizeof(packet));
2523 UNUSED_IF_ASSERT_DISABLED(packet_len);
2524 StringExtractorGDBRemote response;
2525 if (SendPacketAndWaitForResponse(packet, response) ==
2527 if (response.IsNormalResponse()) {
2528 // Make sure we parsed the right number of characters. The response is
2529 // the hex encoded user name and should make up the entire packet. If
2530 // there are any non-hex ASCII bytes, the length won't match below..
2531 if (response.GetHexByteString(name) * 2 ==
2532 response.GetStringRef().size())
2533 return true;
2534 }
2535 } else {
2536 m_supports_qUserName = false;
2537 return false;
2538 }
2539 }
2540 return false;
2541}
2542
2544 std::string &name) {
2546 char packet[32];
2547 const int packet_len =
2548 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2549 assert(packet_len < (int)sizeof(packet));
2550 UNUSED_IF_ASSERT_DISABLED(packet_len);
2551 StringExtractorGDBRemote response;
2552 if (SendPacketAndWaitForResponse(packet, response) ==
2554 if (response.IsNormalResponse()) {
2555 // Make sure we parsed the right number of characters. The response is
2556 // the hex encoded group name and should make up the entire packet. If
2557 // there are any non-hex ASCII bytes, the length won't match below..
2558 if (response.GetHexByteString(name) * 2 ==
2559 response.GetStringRef().size())
2560 return true;
2561 }
2562 } else {
2563 m_supports_qGroupName = false;
2564 return false;
2565 }
2566 }
2567 return false;
2568}
2569
2570static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2571 uint32_t recv_size) {
2572 packet.Clear();
2573 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2574 uint32_t bytes_left = send_size;
2575 while (bytes_left > 0) {
2576 if (bytes_left >= 26) {
2577 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2578 bytes_left -= 26;
2579 } else {
2580 packet.Printf("%*.*s;", bytes_left, bytes_left,
2581 "abcdefghijklmnopqrstuvwxyz");
2582 bytes_left = 0;
2583 }
2584 }
2585}
2586
2587duration<float>
2588calculate_standard_deviation(const std::vector<duration<float>> &v) {
2589 if (v.size() == 0)
2590 return duration<float>::zero();
2591 using Dur = duration<float>;
2592 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2593 Dur mean = sum / v.size();
2594 float accum = 0;
2595 for (auto d : v) {
2596 float delta = (d - mean).count();
2597 accum += delta * delta;
2598 };
2599
2600 return Dur(sqrtf(accum / (v.size() - 1)));
2601}
2602
2604 uint32_t max_send,
2605 uint32_t max_recv,
2606 uint64_t recv_amount,
2607 bool json, Stream &strm) {
2608
2609 if (SendSpeedTestPacket(0, 0)) {
2610 StreamString packet;
2611 if (json)
2612 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2613 "\"results\" : [",
2614 num_packets);
2615 else
2616 strm.Printf("Testing sending %u packets of various sizes:\n",
2617 num_packets);
2618 strm.Flush();
2619
2620 uint32_t result_idx = 0;
2621 uint32_t send_size;
2622 std::vector<duration<float>> packet_times;
2623
2624 for (send_size = 0; send_size <= max_send;
2625 send_size ? send_size *= 2 : send_size = 4) {
2626 for (uint32_t recv_size = 0; recv_size <= max_recv;
2627 recv_size ? recv_size *= 2 : recv_size = 4) {
2628 MakeSpeedTestPacket(packet, send_size, recv_size);
2629
2630 packet_times.clear();
2631 // Test how long it takes to send 'num_packets' packets
2632 const auto start_time = steady_clock::now();
2633 for (uint32_t i = 0; i < num_packets; ++i) {
2634 const auto packet_start_time = steady_clock::now();
2635 StringExtractorGDBRemote response;
2636 SendPacketAndWaitForResponse(packet.GetString(), response);
2637 const auto packet_end_time = steady_clock::now();
2638 packet_times.push_back(packet_end_time - packet_start_time);
2639 }
2640 const auto end_time = steady_clock::now();
2641 const auto total_time = end_time - start_time;
2642
2643 float packets_per_second =
2644 ((float)num_packets) / duration<float>(total_time).count();
2645 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2646 : duration<float>::zero();
2647 const duration<float> standard_deviation =
2648 calculate_standard_deviation(packet_times);
2649 if (json) {
2650 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2651 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2652 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2653 result_idx > 0 ? "," : "", send_size, recv_size,
2654 total_time, standard_deviation);
2655 ++result_idx;
2656 } else {
2657 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2658 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2659 "standard deviation of {5,10:ms+f6}\n",
2660 send_size, recv_size, duration<float>(total_time),
2661 packets_per_second, duration<float>(average_per_packet),
2662 standard_deviation);
2663 }
2664 strm.Flush();
2665 }
2666 }
2667
2668 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2669 if (json)
2670 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2671 ": %" PRIu64 ",\n \"results\" : [",
2672 recv_amount);
2673 else
2674 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2675 "packet sizes:\n",
2676 k_recv_amount_mb);
2677 strm.Flush();
2678 send_size = 0;
2679 result_idx = 0;
2680 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2681 MakeSpeedTestPacket(packet, send_size, recv_size);
2682
2683 // If we have a receive size, test how long it takes to receive 4MB of
2684 // data
2685 if (recv_size > 0) {
2686 const auto start_time = steady_clock::now();
2687 uint32_t bytes_read = 0;
2688 uint32_t packet_count = 0;
2689 while (bytes_read < recv_amount) {
2690 StringExtractorGDBRemote response;
2691 SendPacketAndWaitForResponse(packet.GetString(), response);
2692 bytes_read += recv_size;
2693 ++packet_count;
2694 }
2695 const auto end_time = steady_clock::now();
2696 const auto total_time = end_time - start_time;
2697 float mb_second = ((float)recv_amount) /
2698 duration<float>(total_time).count() /
2699 (1024.0 * 1024.0);
2700 float packets_per_second =
2701 ((float)packet_count) / duration<float>(total_time).count();
2702 const auto average_per_packet = packet_count > 0
2703 ? total_time / packet_count
2704 : duration<float>::zero();
2705
2706 if (json) {
2707 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2708 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2709 result_idx > 0 ? "," : "", send_size, recv_size,
2710 total_time);
2711 ++result_idx;
2712 } else {
2713 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2714 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2715 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2716 send_size, recv_size, packet_count, k_recv_amount_mb,
2717 duration<float>(total_time), mb_second,
2718 packets_per_second, duration<float>(average_per_packet));
2719 }
2720 strm.Flush();
2721 }
2722 }
2723 if (json)
2724 strm.Printf("\n ]\n }\n}\n");
2725 else
2726 strm.EOL();
2727 }
2728}
2729
2731 uint32_t recv_size) {
2732 StreamString packet;
2733 MakeSpeedTestPacket(packet, send_size, recv_size);
2734
2735 StringExtractorGDBRemote response;
2736 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2738}
2739
2741 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2742 std::string &socket_name) {
2744 port = 0;
2745 socket_name.clear();
2746
2747 StringExtractorGDBRemote response;
2748 StreamString stream;
2749 stream.PutCString("qLaunchGDBServer;");
2750 std::string hostname;
2751 if (remote_accept_hostname && remote_accept_hostname[0])
2752 hostname = remote_accept_hostname;
2753 else {
2754 if (HostInfo::GetHostname(hostname)) {
2755 // Make the GDB server we launch only accept connections from this host
2756 stream.Printf("host:%s;", hostname.c_str());
2757 } else {
2758 // Make the GDB server we launch accept connections from any host since
2759 // we can't figure out the hostname
2760 stream.Printf("host:*;");
2761 }
2762 }
2763 // give the process a few seconds to startup
2764 ScopedTimeout timeout(*this, seconds(10));
2765
2766 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2768 if (response.IsErrorResponse())
2769 return false;
2770
2771 llvm::StringRef name;
2772 llvm::StringRef value;
2773 while (response.GetNameColonValue(name, value)) {
2774 if (name == "port")
2775 value.getAsInteger(0, port);
2776 else if (name == "pid")
2777 value.getAsInteger(0, pid);
2778 else if (name.compare("socket_name") == 0) {
2779 StringExtractor extractor(value);
2780 extractor.GetHexByteString(socket_name);
2781 }
2782 }
2783 return true;
2784 }
2785 return false;
2786}
2787
2789 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2790 connection_urls.clear();
2791
2792 StringExtractorGDBRemote response;
2793 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2795 return 0;
2796
2799 if (!data)
2800 return 0;
2801
2802 StructuredData::Array *array = data->GetAsArray();
2803 if (!array)
2804 return 0;
2805
2806 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2807 std::optional<StructuredData::Dictionary *> maybe_element =
2809 if (!maybe_element)
2810 continue;
2811
2812 StructuredData::Dictionary *element = *maybe_element;
2813 uint16_t port = 0;
2814 if (StructuredData::ObjectSP port_osp =
2815 element->GetValueForKey(llvm::StringRef("port")))
2816 port = port_osp->GetUnsignedIntegerValue(0);
2817
2818 std::string socket_name;
2819 if (StructuredData::ObjectSP socket_name_osp =
2820 element->GetValueForKey(llvm::StringRef("socket_name")))
2821 socket_name = std::string(socket_name_osp->GetStringValue());
2822
2823 if (port != 0 || !socket_name.empty())
2824 connection_urls.emplace_back(port, socket_name);
2825 }
2826 return connection_urls.size();
2827}
2828
2830 StreamString stream;
2831 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2832
2833 StringExtractorGDBRemote response;
2834 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2836 if (response.IsOKResponse())
2837 return true;
2838 }
2839 return false;
2840}
2841
2843 uint64_t tid, uint64_t pid, char op) {
2845 packet.PutChar('H');
2846 packet.PutChar(op);
2847
2848 if (pid != LLDB_INVALID_PROCESS_ID)
2849 packet.Printf("p%" PRIx64 ".", pid);
2850
2851 if (tid == UINT64_MAX)
2852 packet.PutCString("-1");
2853 else
2854 packet.Printf("%" PRIx64, tid);
2855
2856 StringExtractorGDBRemote response;
2857 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2859 if (response.IsOKResponse())
2860 return {{pid, tid}};
2861
2862 /*
2863 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2864 * Hg packet.
2865 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2866 * which can
2867 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2868 */
2869 if (response.IsUnsupportedResponse() && IsConnected())
2870 return {{1, 1}};
2871 }
2872 return std::nullopt;
2873}
2874
2876 uint64_t pid) {
2877 if (m_curr_tid == tid &&
2878 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2879 return true;
2880
2881 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2882 if (ret) {
2883 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2884 m_curr_pid = ret->pid;
2885 m_curr_tid = ret->tid;
2886 }
2887 return ret.has_value();
2888}
2889
2891 uint64_t pid) {
2892 if (m_curr_tid_run == tid &&
2893 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2894 return true;
2895
2896 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2897 if (ret) {
2898 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2899 m_curr_pid_run = ret->pid;
2900 m_curr_tid_run = ret->tid;
2901 }
2902 return ret.has_value();
2903}
2904
2906 StringExtractorGDBRemote &response) {
2908 return response.IsNormalResponse();
2909 return false;
2910}
2911
2913 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2915 char packet[256];
2916 int packet_len =
2917 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2918 assert(packet_len < (int)sizeof(packet));
2919 UNUSED_IF_ASSERT_DISABLED(packet_len);
2920 if (SendPacketAndWaitForResponse(packet, response) ==
2922 if (response.IsUnsupportedResponse())
2924 else if (response.IsNormalResponse())
2925 return true;
2926 else
2927 return false;
2928 } else {
2930 }
2931 }
2932 return false;
2933}
2934
2936 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2937 std::chrono::seconds timeout) {
2939 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2940 __FUNCTION__, insert ? "add" : "remove", addr);
2941
2942 // Check if the stub is known not to support this breakpoint type
2943 if (!SupportsGDBStoppointPacket(type))
2944 return UINT8_MAX;
2945 // Construct the breakpoint packet
2946 char packet[64];
2947 const int packet_len =
2948 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2949 insert ? 'Z' : 'z', type, addr, length);
2950 // Check we haven't overwritten the end of the packet buffer
2951 assert(packet_len + 1 < (int)sizeof(packet));
2952 UNUSED_IF_ASSERT_DISABLED(packet_len);
2953 StringExtractorGDBRemote response;
2954 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2955 // or "" (unsupported)
2957 // Try to send the breakpoint packet, and check that it was correctly sent
2958 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
2960 // Receive and OK packet when the breakpoint successfully placed
2961 if (response.IsOKResponse())
2962 return 0;
2963
2964 // Status while setting breakpoint, send back specific error
2965 if (response.IsErrorResponse())
2966 return response.GetError();
2967
2968 // Empty packet informs us that breakpoint is not supported
2969 if (response.IsUnsupportedResponse()) {
2970 // Disable this breakpoint type since it is unsupported
2971 switch (type) {
2973 m_supports_z0 = false;
2974 break;
2976 m_supports_z1 = false;
2977 break;
2978 case eWatchpointWrite:
2979 m_supports_z2 = false;
2980 break;
2981 case eWatchpointRead:
2982 m_supports_z3 = false;
2983 break;
2985 m_supports_z4 = false;
2986 break;
2987 case eStoppointInvalid:
2988 return UINT8_MAX;
2989 }
2990 }
2991 }
2992 // Signal generic failure
2993 return UINT8_MAX;
2994}
2995
2996std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
2998 bool &sequence_mutex_unavailable) {
2999 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
3000
3001 Lock lock(*this);
3002 if (lock) {
3003 sequence_mutex_unavailable = false;
3004 StringExtractorGDBRemote response;
3005
3006 PacketResult packet_result;
3007 for (packet_result =
3008 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
3009 packet_result == PacketResult::Success && response.IsNormalResponse();
3010 packet_result =
3011 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
3012 char ch = response.GetChar();
3013 if (ch == 'l')
3014 break;
3015 if (ch == 'm') {
3016 do {
3017 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
3018 // If we get an invalid response, break out of the loop.
3019 // If there are valid tids, they have been added to ids.
3020 // If there are no valid tids, we'll fall through to the
3021 // bare-iron target handling below.
3022 if (!pid_tid)
3023 break;
3024
3025 ids.push_back(*pid_tid);
3026 ch = response.GetChar(); // Skip the command separator
3027 } while (ch == ','); // Make sure we got a comma separator
3028 }
3029 }
3030
3031 /*
3032 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3033 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
3034 * could
3035 * be as simple as 'S05'. There is no packet which can give us pid and/or
3036 * tid.
3037 * Assume pid=tid=1 in such cases.
3038 */
3039 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
3040 ids.size() == 0 && IsConnected()) {
3041 ids.emplace_back(1, 1);
3042 }
3043 } else {
3045 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
3046 "packet 'qfThreadInfo'");
3047 sequence_mutex_unavailable = true;
3048 }
3049
3050 return ids;
3051}
3052
3054 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
3056 thread_ids.clear();
3057
3058 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
3059 if (ids.empty() || sequence_mutex_unavailable)
3060 return 0;
3061
3062 for (auto id : ids) {
3063 // skip threads that do not belong to the current process
3064 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
3065 continue;
3066 if (id.second != LLDB_INVALID_THREAD_ID &&
3068 thread_ids.push_back(id.second);
3069 }
3070
3071 return thread_ids.size();
3072}
3073
3075 StringExtractorGDBRemote response;
3076 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
3078 !response.IsNormalResponse())
3079 return LLDB_INVALID_ADDRESS;
3080 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3081}
3082
3084 llvm::StringRef command,
3085 const FileSpec &
3086 working_dir, // Pass empty FileSpec to use the current working directory
3087 int *status_ptr, // Pass NULL if you don't want the process exit status
3088 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
3089 // process to exit
3090 std::string
3091 *command_output, // Pass nullptr if you don't want the command output
3092 std::string *separated_error_output, // Pass nullptr if you don't want the
3093 // command error output
3094 const Timeout<std::micro> &timeout) {
3096 stream.PutCString("qPlatform_shell:");
3097 stream.PutBytesAsRawHex8(command.data(), command.size());
3098 stream.PutChar(',');
3099 uint32_t timeout_sec = UINT32_MAX;
3100 if (timeout) {
3101 // TODO: Use chrono version of std::ceil once c++17 is available.
3102 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
3103 }
3104 stream.PutHex32(timeout_sec);
3105 if (working_dir) {
3106 std::string path{working_dir.GetPath(false)};
3107 stream.PutChar(',');
3108 stream.PutStringAsRawHex8(path);
3109 }
3110 StringExtractorGDBRemote response;
3111 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3113 if (response.GetChar() != 'F')
3114 return Status::FromErrorString("malformed reply");
3115 if (response.GetChar() != ',')
3116 return Status::FromErrorString("malformed reply");
3117 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3118 if (exitcode == UINT32_MAX)
3119 return Status::FromErrorString("unable to run remote process");
3120 else if (status_ptr)
3121 *status_ptr = exitcode;
3122 if (response.GetChar() != ',')
3123 return Status::FromErrorString("malformed reply");
3124 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3125 if (signo_ptr)
3126 *signo_ptr = signo;
3127 if (response.GetChar() != ',')
3128 return Status::FromErrorString("malformed reply");
3129 std::string output;
3130 response.GetEscapedBinaryData(output);
3131 if (command_output)
3132 command_output->assign(output);
3133 return Status();
3134 }
3135 return Status::FromErrorString("unable to send packet");
3136}
3137
3139 uint32_t file_permissions) {
3140 std::string path{file_spec.GetPath(false)};
3142 stream.PutCString("qPlatform_mkdir:");
3143 stream.PutHex32(file_permissions);
3144 stream.PutChar(',');
3145 stream.PutStringAsRawHex8(path);
3146 llvm::StringRef packet = stream.GetString();
3147 StringExtractorGDBRemote response;
3148
3149 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3150 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3151 packet.str().c_str());
3152
3153 if (response.GetChar() != 'F')
3154 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3155 packet.str().c_str());
3156
3157 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3158}
3159
3160Status
3162 uint32_t file_permissions) {
3163 std::string path{file_spec.GetPath(false)};
3165 stream.PutCString("qPlatform_chmod:");
3166 stream.PutHex32(file_permissions);
3167 stream.PutChar(',');
3168 stream.PutStringAsRawHex8(path);
3169 llvm::StringRef packet = stream.GetString();
3170 StringExtractorGDBRemote response;
3171
3172 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3173 return Status::FromErrorStringWithFormat("failed to send '%s' packet",
3174 stream.GetData());
3175
3176 if (response.GetChar() != 'F')
3177 return Status::FromErrorStringWithFormat("invalid response to '%s' packet",
3178 stream.GetData());
3179
3180 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3181}
3182
3183static int gdb_errno_to_system(int err) {
3184 switch (err) {
3185#define HANDLE_ERRNO(name, value) \
3186 case GDB_##name: \
3187 return name;
3188#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3189 default:
3190 return -1;
3191 }
3192}
3193
3195 uint64_t fail_result, Status &error) {
3196 response.SetFilePos(0);
3197 if (response.GetChar() != 'F')
3198 return fail_result;
3199 int32_t result = response.GetS32(-2, 16);
3200 if (result == -2)
3201 return fail_result;
3202 if (response.GetChar() == ',') {
3203 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3204 if (result_errno != -1)
3205 error = Status(result_errno, eErrorTypePOSIX);
3206 else
3208 } else
3209 error.Clear();
3210 return result;
3211}
3214 File::OpenOptions flags, mode_t mode,
3215 Status &error) {
3216 std::string path(file_spec.GetPath(false));
3218 stream.PutCString("vFile:open:");
3219 if (path.empty())
3220 return UINT64_MAX;
3221 stream.PutStringAsRawHex8(path);
3222 stream.PutChar(',');
3223 stream.PutHex32(flags);
3224 stream.PutChar(',');
3225 stream.PutHex32(mode);
3226 StringExtractorGDBRemote response;
3227 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3229 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3230 }
3231 return UINT64_MAX;
3232}
3233
3235 Status &error) {
3237 stream.Printf("vFile:close:%x", (int)fd);
3238 StringExtractorGDBRemote response;
3239 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3241 return ParseHostIOPacketResponse(response, -1, error) == 0;
3242 }
3243 return false;
3244}
3245
3246std::optional<GDBRemoteFStatData>
3249 stream.Printf("vFile:fstat:%" PRIx64, fd);
3250 StringExtractorGDBRemote response;
3251 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3253 if (response.GetChar() != 'F')
3254 return std::nullopt;
3255 int64_t size = response.GetS64(-1, 16);
3256 if (size > 0 && response.GetChar() == ';') {
3257 std::string buffer;
3258 if (response.GetEscapedBinaryData(buffer)) {
3260 if (buffer.size() != sizeof(out))
3261 return std::nullopt;
3262 memcpy(&out, buffer.data(), sizeof(out));
3263 return out;
3264 }
3265 }
3266 }
3267 return std::nullopt;
3268}
3269
3270std::optional<GDBRemoteFStatData>
3272 Status error;
3274 if (fd == UINT64_MAX)
3275 return std::nullopt;
3276 std::optional<GDBRemoteFStatData> st = FStat(fd);
3277 CloseFile(fd, error);
3278 return st;
3279}
3280
3281// Extension of host I/O packets to get the file size.
3283 const lldb_private::FileSpec &file_spec) {
3285 std::string path(file_spec.GetPath(false));
3287 stream.PutCString("vFile:size:");
3288 stream.PutStringAsRawHex8(path);
3289 StringExtractorGDBRemote response;
3290 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3292 return UINT64_MAX;
3293
3294 if (!response.IsUnsupportedResponse()) {
3295 if (response.GetChar() != 'F')
3296 return UINT64_MAX;
3297 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3298 return retcode;
3299 }
3300 m_supports_vFileSize = false;
3301 }
3302
3303 // Fallback to fstat.
3304 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3305 return st ? st->gdb_st_size : UINT64_MAX;
3306}
3307
3309 CompletionRequest &request, bool only_dir) {
3311 stream.PutCString("qPathComplete:");
3312 stream.PutHex32(only_dir ? 1 : 0);
3313 stream.PutChar(',');
3315 StringExtractorGDBRemote response;
3316 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3318 StreamString strm;
3319 char ch = response.GetChar();
3320 if (ch != 'M')
3321 return;
3322 while (response.Peek()) {
3323 strm.Clear();
3324 while ((ch = response.GetHexU8(0, false)) != '\0')
3325 strm.PutChar(ch);
3326 request.AddCompletion(strm.GetString());
3327 if (response.GetChar() != ',')
3328 break;
3329 }
3330 }
3331}
3332
3333Status
3335 uint32_t &file_permissions) {
3337 std::string path{file_spec.GetPath(false)};
3338 Status error;
3340 stream.PutCString("vFile:mode:");
3341 stream.PutStringAsRawHex8(path);
3342 StringExtractorGDBRemote response;
3343 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3345 error = Status::FromErrorStringWithFormat("failed to send '%s' packet",
3346 stream.GetData());
3347 return error;
3348 }
3349 if (!response.IsUnsupportedResponse()) {
3350 if (response.GetChar() != 'F') {
3352 "invalid response to '%s' packet", stream.GetData());
3353 } else {
3354 const uint32_t mode = response.GetS32(-1, 16);
3355 if (static_cast<int32_t>(mode) == -1) {
3356 if (response.GetChar() == ',') {
3357 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3358 if (response_errno > 0)
3359 error = Status(response_errno, lldb::eErrorTypePOSIX);
3360 else
3361 error = Status::FromErrorString("unknown error");
3362 } else
3363 error = Status::FromErrorString("unknown error");
3364 } else {
3365 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3366 }
3367 }
3368 return error;
3369 } else { // response.IsUnsupportedResponse()
3370 m_supports_vFileMode = false;
3371 }
3372 }
3373
3374 // Fallback to fstat.
3375 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3376 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3377 return Status();
3378 }
3379 return Status::FromErrorString("fstat failed");
3380}
3381
3383 uint64_t offset, void *dst,
3384 uint64_t dst_len,
3385 Status &error) {
3387 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3388 offset);
3389 StringExtractorGDBRemote response;
3390 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3392 if (response.GetChar() != 'F')
3393 return 0;
3394 int64_t retcode = response.GetS64(-1, 16);
3395 if (retcode == -1) {
3396 error = Status::FromErrorString("unknown error");
3397 if (response.GetChar() == ',') {
3398 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3399 if (response_errno > 0)
3400 error = Status(response_errno, lldb::eErrorTypePOSIX);
3401 }
3402 return -1;
3403 }
3404 const char next = (response.Peek() ? *response.Peek() : 0);
3405 if (next == ',')
3406 return 0;
3407 if (next == ';') {
3408 response.GetChar(); // skip the semicolon
3409 std::string buffer;
3410 if (response.GetEscapedBinaryData(buffer)) {
3411 const uint64_t data_to_write =
3412 std::min<uint64_t>(dst_len, buffer.size());
3413 if (data_to_write > 0)
3414 memcpy(dst, &buffer[0], data_to_write);
3415 return data_to_write;
3416 }
3417 }
3418 }
3419 return 0;
3420}
3421
3423 uint64_t offset,
3424 const void *src,
3425 uint64_t src_len,
3426 Status &error) {
3428 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3429 stream.PutEscapedBytes(src, src_len);
3430 StringExtractorGDBRemote response;
3431 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3433 if (response.GetChar() != 'F') {
3434 error = Status::FromErrorStringWithFormat("write file failed");
3435 return 0;
3436 }
3437 int64_t bytes_written = response.GetS64(-1, 16);
3438 if (bytes_written == -1) {
3439 error = Status::FromErrorString("unknown error");
3440 if (response.GetChar() == ',') {
3441 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3442 if (response_errno > 0)
3443 error = Status(response_errno, lldb::eErrorTypePOSIX);
3444 }
3445 return -1;
3446 }
3447 return bytes_written;
3448 } else {
3449 error = Status::FromErrorString("failed to send vFile:pwrite packet");
3450 }
3451 return 0;
3452}
3453
3455 const FileSpec &dst) {
3456 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3457 Status error;
3459 stream.PutCString("vFile:symlink:");
3460 // the unix symlink() command reverses its parameters where the dst if first,
3461 // so we follow suit here
3462 stream.PutStringAsRawHex8(dst_path);
3463 stream.PutChar(',');
3464 stream.PutStringAsRawHex8(src_path);
3465 StringExtractorGDBRemote response;
3466 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3468 if (response.GetChar() == 'F') {
3469 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3470 if (result != 0) {
3471 error = Status::FromErrorString("unknown error");
3472 if (response.GetChar() == ',') {
3473 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3474 if (response_errno > 0)
3475 error = Status(response_errno, lldb::eErrorTypePOSIX);
3476 }
3477 }
3478 } else {
3479 // Should have returned with 'F<result>[,<errno>]'
3480 error = Status::FromErrorStringWithFormat("symlink failed");
3481 }
3482 } else {
3483 error = Status::FromErrorString("failed to send vFile:symlink packet");
3484 }
3485 return error;
3486}
3487
3489 std::string path{file_spec.GetPath(false)};
3490 Status error;
3492 stream.PutCString("vFile:unlink:");
3493 // the unix symlink() command reverses its parameters where the dst if first,
3494 // so we follow suit here
3495 stream.PutStringAsRawHex8(path);
3496 StringExtractorGDBRemote response;
3497 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3499 if (response.GetChar() == 'F') {
3500 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3501 if (result != 0) {
3502 error = Status::FromErrorString("unknown error");
3503 if (response.GetChar() == ',') {
3504 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3505 if (response_errno > 0)
3506 error = Status(response_errno, lldb::eErrorTypePOSIX);
3507 }
3508 }
3509 } else {
3510 // Should have returned with 'F<result>[,<errno>]'
3511 error = Status::FromErrorStringWithFormat("unlink failed");
3512 }
3513 } else {
3514 error = Status::FromErrorString("failed to send vFile:unlink packet");
3515 }
3516 return error;
3517}
3518
3519// Extension of host I/O packets to get whether a file exists.
3521 const lldb_private::FileSpec &file_spec) {
3523 std::string path(file_spec.GetPath(false));
3525 stream.PutCString("vFile:exists:");
3526 stream.PutStringAsRawHex8(path);
3527 StringExtractorGDBRemote response;
3528 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3530 return false;
3531 if (!response.IsUnsupportedResponse()) {
3532 if (response.GetChar() != 'F')
3533 return false;
3534 if (response.GetChar() != ',')
3535 return false;
3536 bool retcode = (response.GetChar() != '0');
3537 return retcode;
3538 } else
3539 m_supports_vFileExists = false;
3540 }
3541
3542 // Fallback to open.
3543 Status error;
3545 if (fd == UINT64_MAX)
3546 return false;
3547 CloseFile(fd, error);
3548 return true;
3549}
3550
3551llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3552 const lldb_private::FileSpec &file_spec) {
3553 std::string path(file_spec.GetPath(false));
3555 stream.PutCString("vFile:MD5:");
3556 stream.PutStringAsRawHex8(path);
3557 StringExtractorGDBRemote response;
3558 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3560 if (response.GetChar() != 'F')
3561 return std::make_error_code(std::errc::illegal_byte_sequence);
3562 if (response.GetChar() != ',')
3563 return std::make_error_code(std::errc::illegal_byte_sequence);
3564 if (response.Peek() && *response.Peek() == 'x')
3565 return std::make_error_code(std::errc::no_such_file_or_directory);
3566
3567 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3568 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3569 // handle the concatenated hex string. What would happen is parsing the low
3570 // would consume the whole response packet which would give incorrect
3571 // results. Instead, we get the byte string for each low and high hex
3572 // separately, and parse them.
3573 //
3574 // An alternate way to handle this is to change the server to put a
3575 // delimiter between the low/high parts, and change the client to parse the
3576 // delimiter. However, we choose not to do this so existing lldb-servers
3577 // don't have to be patched
3578
3579 // The checksum is 128 bits encoded as hex
3580 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3581 // Each byte takes 2 hex characters in the response.
3582 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3583
3584 // Get low part
3585 auto part =
3586 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3587 if (part.size() != MD5_HALF_LENGTH)
3588 return std::make_error_code(std::errc::illegal_byte_sequence);
3589 response.SetFilePos(response.GetFilePos() + part.size());
3590
3591 uint64_t low;
3592 if (part.getAsInteger(/*radix=*/16, low))
3593 return std::make_error_code(std::errc::illegal_byte_sequence);
3594
3595 // Get high part
3596 part =
3597 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3598 if (part.size() != MD5_HALF_LENGTH)
3599 return std::make_error_code(std::errc::illegal_byte_sequence);
3600 response.SetFilePos(response.GetFilePos() + part.size());
3601
3602 uint64_t high;
3603 if (part.getAsInteger(/*radix=*/16, high))
3604 return std::make_error_code(std::errc::illegal_byte_sequence);
3605
3606 llvm::MD5::MD5Result result;
3607 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3608 result.data(), low);
3609 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3610 result.data() + 8, high);
3611
3612 return result;
3613 }
3614 return std::make_error_code(std::errc::operation_canceled);
3615}
3616
3618 // Some targets have issues with g/G packets and we need to avoid using them
3620 if (process) {
3622 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3623 if (arch.IsValid() &&
3624 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3625 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3626 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3627 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3629 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3630 if (gdb_server_version != 0) {
3631 const char *gdb_server_name = GetGDBServerProgramName();
3632 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3633 if (gdb_server_version >= 310)
3635 }
3636 }
3637 }
3638 }
3639 }
3641}
3642
3644 uint32_t reg) {
3645 StreamString payload;
3646 payload.Printf("p%x", reg);
3647 StringExtractorGDBRemote response;
3649 tid, std::move(payload), response) != PacketResult::Success ||
3650 !response.IsNormalResponse())
3651 return nullptr;
3652
3653 WritableDataBufferSP buffer_sp(
3654 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3655 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3656 return buffer_sp;
3657}
3658
3660 StreamString payload;
3661 payload.PutChar('g');
3662 StringExtractorGDBRemote response;
3664 tid, std::move(payload), response) != PacketResult::Success ||
3665 !response.IsNormalResponse())
3666 return nullptr;
3667
3668 WritableDataBufferSP buffer_sp(
3669 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3670 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3671 return buffer_sp;
3672}
3673
3675 uint32_t reg_num,
3676 llvm::ArrayRef<uint8_t> data) {
3677 StreamString payload;
3678 payload.Printf("P%x=", reg_num);
3679 payload.PutBytesAsRawHex8(data.data(), data.size(),
3682 StringExtractorGDBRemote response;
3684 tid, std::move(payload), response) == PacketResult::Success &&
3685 response.IsOKResponse();
3686}
3687
3689 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3690 StreamString payload;
3691 payload.PutChar('G');
3692 payload.PutBytesAsRawHex8(data.data(), data.size(),
3695 StringExtractorGDBRemote response;
3697 tid, std::move(payload), response) == PacketResult::Success &&
3698 response.IsOKResponse();
3699}
3700
3702 uint32_t &save_id) {
3703 save_id = 0; // Set to invalid save ID
3705 return false;
3706
3708 StreamString payload;
3709 payload.PutCString("QSaveRegisterState");
3710 StringExtractorGDBRemote response;
3712 tid, std::move(payload), response) != PacketResult::Success)
3713 return false;
3714
3715 if (response.IsUnsupportedResponse())
3717
3718 const uint32_t response_save_id = response.GetU32(0);
3719 if (response_save_id == 0)
3720 return false;
3721
3722 save_id = response_save_id;
3723 return true;
3724}
3725
3727 uint32_t save_id) {
3728 // We use the "m_supports_QSaveRegisterState" variable here because the
3729 // QSaveRegisterState and QRestoreRegisterState packets must both be
3730 // supported in order to be useful
3732 return false;
3733
3734 StreamString payload;
3735 payload.Printf("QRestoreRegisterState:%u", save_id);
3736 StringExtractorGDBRemote response;
3738 tid, std::move(payload), response) != PacketResult::Success)
3739 return false;
3740
3741 if (response.IsOKResponse())
3742 return true;
3743
3744 if (response.IsUnsupportedResponse())
3746 return false;
3747}
3748
3751 return false;
3752
3753 StreamString packet;
3754 StringExtractorGDBRemote response;
3755 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3756 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3758 response.IsOKResponse();
3759}
3760
3761llvm::Expected<TraceSupportedResponse>
3763 Log *log = GetLog(GDBRLog::Process);
3764
3765 StreamGDBRemote escaped_packet;
3766 escaped_packet.PutCString("jLLDBTraceSupported");
3767
3768 StringExtractorGDBRemote response;
3769 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3770 timeout) ==
3772 if (response.IsErrorResponse())
3773 return response.GetStatus().ToError();
3774 if (response.IsUnsupportedResponse())
3775 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3776 "jLLDBTraceSupported is unsupported");
3777
3778 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3779 "TraceSupportedResponse");
3780 }
3781 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3782 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3783 "failed to send packet: jLLDBTraceSupported");
3784}
3785
3786llvm::Error
3788 std::chrono::seconds timeout) {
3789 Log *log = GetLog(GDBRLog::Process);
3790
3791 StreamGDBRemote escaped_packet;
3792 escaped_packet.PutCString("jLLDBTraceStop:");
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 if (response.IsUnsupportedResponse())
3807 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3808 "jLLDBTraceStop is unsupported");
3809 if (response.IsOKResponse())
3810 return llvm::Error::success();
3811 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3812 "Invalid jLLDBTraceStart response");
3813 }
3814 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3815 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3816 "failed to send packet: jLLDBTraceStop '%s'",
3817 escaped_packet.GetData());
3818}
3819
3820llvm::Error
3821GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3822 std::chrono::seconds timeout) {
3823 Log *log = GetLog(GDBRLog::Process);
3824
3825 StreamGDBRemote escaped_packet;
3826 escaped_packet.PutCString("jLLDBTraceStart:");
3827
3828 std::string json_string;
3829 llvm::raw_string_ostream os(json_string);
3830 os << params;
3831
3832 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3833
3834 StringExtractorGDBRemote response;
3835 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3836 timeout) ==
3838 if (response.IsErrorResponse())
3839 return response.GetStatus().ToError();
3840 if (response.IsUnsupportedResponse())
3841 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3842 "jLLDBTraceStart is unsupported");
3843 if (response.IsOKResponse())
3844 return llvm::Error::success();
3845 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3846 "Invalid jLLDBTraceStart response");
3847 }
3848 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3849 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3850 "failed to send packet: jLLDBTraceStart '%s'",
3851 escaped_packet.GetData());
3852}
3853
3854llvm::Expected<std::string>
3856 std::chrono::seconds timeout) {
3857 Log *log = GetLog(GDBRLog::Process);
3858
3859 StreamGDBRemote escaped_packet;
3860 escaped_packet.PutCString("jLLDBTraceGetState:");
3861
3862 std::string json_string;
3863 llvm::raw_string_ostream os(json_string);
3864 os << toJSON(TraceGetStateRequest{type.str()});
3865
3866 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3867
3868 StringExtractorGDBRemote response;
3869 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3870 timeout) ==
3872 if (response.IsErrorResponse())
3873 return response.GetStatus().ToError();
3874 if (response.IsUnsupportedResponse())
3875 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3876 "jLLDBTraceGetState is unsupported");
3877 return std::string(response.Peek());
3878 }
3879
3880 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3881 return llvm::createStringError(
3882 llvm::inconvertibleErrorCode(),
3883 "failed to send packet: jLLDBTraceGetState '%s'",
3884 escaped_packet.GetData());
3885}
3886
3887llvm::Expected<std::vector<uint8_t>>
3889 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3890 Log *log = GetLog(GDBRLog::Process);
3891
3892 StreamGDBRemote escaped_packet;
3893 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3894
3895 std::string json_string;
3896 llvm::raw_string_ostream os(json_string);
3897 os << toJSON(request);
3898
3899 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3900
3901 StringExtractorGDBRemote response;
3902 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3903 timeout) ==
3905 if (response.IsErrorResponse())
3906 return response.GetStatus().ToError();
3907 std::string data;
3908 response.GetEscapedBinaryData(data);
3909 return std::vector<uint8_t>(data.begin(), data.end());
3910 }
3911 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3912 return llvm::createStringError(
3913 llvm::inconvertibleErrorCode(),
3914 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3915 escaped_packet.GetData());
3916}
3917
3919 StringExtractorGDBRemote response;
3920 if (SendPacketAndWaitForResponse("qOffsets", response) !=
3922 return std::nullopt;
3923 if (!response.IsNormalResponse())
3924 return std::nullopt;
3925
3926 QOffsets result;
3927 llvm::StringRef ref = response.GetStringRef();
3928 const auto &GetOffset = [&] {
3929 addr_t offset;
3930 if (ref.consumeInteger(16, offset))
3931 return false;
3932 result.offsets.push_back(offset);
3933 return true;
3934 };
3935
3936 if (ref.consume_front("Text=")) {
3937 result.segments = false;
3938 if (!GetOffset())
3939 return std::nullopt;
3940 if (!ref.consume_front(";Data=") || !GetOffset())
3941 return std::nullopt;
3942 if (ref.empty())
3943 return result;
3944 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3945 return result;
3946 } else if (ref.consume_front("TextSeg=")) {
3947 result.segments = true;
3948 if (!GetOffset())
3949 return std::nullopt;
3950 if (ref.empty())
3951 return result;
3952 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3953 return result;
3954 }
3955 return std::nullopt;
3956}
3957
3959 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3960 ModuleSpec &module_spec) {
3962 return false;
3963
3964 std::string module_path = module_file_spec.GetPath(false);
3965 if (module_path.empty())
3966 return false;
3967
3968 StreamString packet;
3969 packet.PutCString("qModuleInfo:");
3970 packet.PutStringAsRawHex8(module_path);
3971 packet.PutCString(";");
3972 const auto &triple = arch_spec.GetTriple().getTriple();
3973 packet.PutStringAsRawHex8(triple);
3974
3975 StringExtractorGDBRemote response;
3976 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
3978 return false;
3979
3980 if (response.IsErrorResponse())
3981 return false;
3982
3983 if (response.IsUnsupportedResponse()) {
3984 m_supports_qModuleInfo = false;
3985 return false;
3986 }
3987
3988 llvm::StringRef name;
3989 llvm::StringRef value;
3990
3991 module_spec.Clear();
3992 module_spec.GetFileSpec() = module_file_spec;
3993
3994 while (response.GetNameColonValue(name, value)) {
3995 if (name == "uuid" || name == "md5") {
3996 StringExtractor extractor(value);
3997 std::string uuid;
3998 extractor.GetHexByteString(uuid);
3999 module_spec.GetUUID().SetFromStringRef(uuid);
4000 } else if (name == "triple") {
4001 StringExtractor extractor(value);
4002 std::string triple;
4003 extractor.GetHexByteString(triple);
4004 module_spec.GetArchitecture().SetTriple(triple.c_str());
4005 } else if (name == "file_offset") {
4006 uint64_t ival = 0;
4007 if (!value.getAsInteger(16, ival))
4008 module_spec.SetObjectOffset(ival);
4009 } else if (name == "file_size") {
4010 uint64_t ival = 0;
4011 if (!value.getAsInteger(16, ival))
4012 module_spec.SetObjectSize(ival);
4013 } else if (name == "file_path") {
4014 StringExtractor extractor(value);
4015 std::string path;
4016 extractor.GetHexByteString(path);
4017 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
4018 }
4019 }
4020
4021 return true;
4022}
4023
4024static std::optional<ModuleSpec>
4026 ModuleSpec result;
4027 if (!dict)
4028 return std::nullopt;
4029
4030 llvm::StringRef string;
4031 uint64_t integer;
4032
4033 if (!dict->GetValueForKeyAsString("uuid", string))
4034 return std::nullopt;
4035 if (!result.GetUUID().SetFromStringRef(string))
4036 return std::nullopt;
4037
4038 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
4039 return std::nullopt;
4040 result.SetObjectOffset(integer);
4041
4042 if (!dict->GetValueForKeyAsInteger("file_size", integer))
4043 return std::nullopt;
4044 result.SetObjectSize(integer);
4045
4046 if (!dict->GetValueForKeyAsString("triple", string))
4047 return std::nullopt;
4048 result.GetArchitecture().SetTriple(string);
4049
4050 if (!dict->GetValueForKeyAsString("file_path", string))
4051 return std::nullopt;
4052 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
4053
4054 return result;
4055}
4056
4057std::optional<std::vector<ModuleSpec>>
4059 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4060 namespace json = llvm::json;
4061
4063 return std::nullopt;
4064
4065 json::Array module_array;
4066 for (const FileSpec &module_file_spec : module_file_specs) {
4067 module_array.push_back(
4068 json::Object{{"file", module_file_spec.GetPath(false)},
4069 {"triple", triple.getTriple()}});
4070 }
4071 StreamString unescaped_payload;
4072 unescaped_payload.PutCString("jModulesInfo:");
4073 unescaped_payload.AsRawOstream() << std::move(module_array);
4074
4075 StreamGDBRemote payload;
4076 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
4077 unescaped_payload.GetSize());
4078
4079 // Increase the timeout for jModulesInfo since this packet can take longer.
4080 ScopedTimeout timeout(*this, std::chrono::seconds(10));
4081
4082 StringExtractorGDBRemote response;
4083 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
4085 response.IsErrorResponse())
4086 return std::nullopt;
4087
4088 if (response.IsUnsupportedResponse()) {
4090 return std::nullopt;
4091 }
4092
4093 StructuredData::ObjectSP response_object_sp =
4095 if (!response_object_sp)
4096 return std::nullopt;
4097
4098 StructuredData::Array *response_array = response_object_sp->GetAsArray();
4099 if (!response_array)
4100 return std::nullopt;
4101
4102 std::vector<ModuleSpec> result;
4103 for (size_t i = 0; i < response_array->GetSize(); ++i) {
4104 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
4105 response_array->GetItemAtIndex(i)->GetAsDictionary()))
4106 result.push_back(*module_spec);
4107 }
4108
4109 return result;
4110}
4111
4112// query the target remote for extended information using the qXfer packet
4113//
4114// example: object='features', annex='target.xml'
4115// return: <xml output> or error
4116llvm::Expected<std::string>
4118 llvm::StringRef annex) {
4119
4120 std::string output;
4121 llvm::raw_string_ostream output_stream(output);
4123
4124 uint64_t size = GetRemoteMaxPacketSize();
4125 if (size == 0)
4126 size = 0x1000;
4127 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4128 int offset = 0;
4129 bool active = true;
4130
4131 // loop until all data has been read
4132 while (active) {
4133
4134 // send query extended feature packet
4135 std::string packet =
4136 ("qXfer:" + object + ":read:" + annex + ":" +
4137 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4138 .str();
4139
4141 SendPacketAndWaitForResponse(packet, chunk);
4142
4144 chunk.GetStringRef().empty()) {
4145 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4146 "Error sending $qXfer packet");
4147 }
4148
4149 // check packet code
4150 switch (chunk.GetStringRef()[0]) {
4151 // last chunk
4152 case ('l'):
4153 active = false;
4154 [[fallthrough]];
4155
4156 // more chunks
4157 case ('m'):
4158 output_stream << chunk.GetStringRef().drop_front();
4159 offset += chunk.GetStringRef().size() - 1;
4160 break;
4161
4162 // unknown chunk
4163 default:
4164 return llvm::createStringError(
4165 llvm::inconvertibleErrorCode(),
4166 "Invalid continuation code from $qXfer packet");
4167 }
4168 }
4169
4170 return output;
4171}
4172
4173// Notify the target that gdb is prepared to serve symbol lookup requests.
4174// packet: "qSymbol::"
4175// reply:
4176// OK The target does not need to look up any (more) symbols.
4177// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4178// encoded).
4179// LLDB may provide the value by sending another qSymbol
4180// packet
4181// in the form of"qSymbol:<sym_value>:<sym_name>".
4182//
4183// Three examples:
4184//
4185// lldb sends: qSymbol::
4186// lldb receives: OK
4187// Remote gdb stub does not need to know the addresses of any symbols, lldb
4188// does not
4189// need to ask again in this session.
4190//
4191// lldb sends: qSymbol::
4192// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4193// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4194// lldb receives: OK
4195// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4196// not know
4197// the address at this time. lldb needs to send qSymbol:: again when it has
4198// more
4199// solibs loaded.
4200//
4201// lldb sends: qSymbol::
4202// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4203// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4204// lldb receives: OK
4205// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4206// that it
4207// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4208// does not
4209// need any more symbols. lldb does not need to ask again in this session.
4210
4212 lldb_private::Process *process) {
4213 // Set to true once we've resolved a symbol to an address for the remote
4214 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4215 // any more symbols and we can stop asking.
4216 bool symbol_response_provided = false;
4217
4218 // Is this the initial qSymbol:: packet?
4219 bool first_qsymbol_query = true;
4220
4222 Lock lock(*this);
4223 if (lock) {
4224 StreamString packet;
4225 packet.PutCString("qSymbol::");
4226 StringExtractorGDBRemote response;
4227 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4229 if (response.IsOKResponse()) {
4230 if (symbol_response_provided || first_qsymbol_query) {
4232 }
4233
4234 // We are done serving symbols requests
4235 return;
4236 }
4237 first_qsymbol_query = false;
4238
4239 if (response.IsUnsupportedResponse()) {
4240 // qSymbol is not supported by the current GDB server we are
4241 // connected to
4242 m_supports_qSymbol = false;
4243 return;
4244 } else {
4245 llvm::StringRef response_str(response.GetStringRef());
4246 if (response_str.starts_with("qSymbol:")) {
4247 response.SetFilePos(strlen("qSymbol:"));
4248 std::string symbol_name;
4249 if (response.GetHexByteString(symbol_name)) {
4250 if (symbol_name.empty())
4251 return;
4252
4253 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4256 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4257 for (const SymbolContext &sc : sc_list) {
4258 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4259 break;
4260 if (sc.symbol) {
4261 switch (sc.symbol->GetType()) {
4262 case eSymbolTypeInvalid:
4269 case eSymbolTypeBlock:
4270 case eSymbolTypeLocal:
4271 case eSymbolTypeParam:
4282 break;
4283
4284 case eSymbolTypeCode:
4286 case eSymbolTypeData:
4287 case eSymbolTypeRuntime:
4293 symbol_load_addr =
4294 sc.symbol->GetLoadAddress(&process->GetTarget());
4295 break;
4296 }
4297 }
4298 }
4299 // This is the normal path where our symbol lookup was successful
4300 // and we want to send a packet with the new symbol value and see
4301 // if another lookup needs to be done.
4302
4303 // Change "packet" to contain the requested symbol value and name
4304 packet.Clear();
4305 packet.PutCString("qSymbol:");
4306 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4307 packet.Printf("%" PRIx64, symbol_load_addr);
4308 symbol_response_provided = true;
4309 } else {
4310 symbol_response_provided = false;
4311 }
4312 packet.PutCString(":");
4313 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4314 continue; // go back to the while loop and send "packet" and wait
4315 // for another response
4316 }
4317 }
4318 }
4319 }
4320 // If we make it here, the symbol request packet response wasn't valid or
4321 // our symbol lookup failed so we must abort
4322 return;
4323
4324 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4325 LLDB_LOGF(log,
4326 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4327 __FUNCTION__);
4328 }
4329 }
4330}
4331
4335 // Query the server for the array of supported asynchronous JSON packets.
4337
4338 Log *log = GetLog(GDBRLog::Process);
4339
4340 // Poll it now.
4341 StringExtractorGDBRemote response;
4342 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4347 !m_supported_async_json_packets_sp->GetAsArray()) {
4348 // We were returned something other than a JSON array. This is
4349 // invalid. Clear it out.
4350 LLDB_LOGF(log,
4351 "GDBRemoteCommunicationClient::%s(): "
4352 "QSupportedAsyncJSONPackets returned invalid "
4353 "result: %s",
4354 __FUNCTION__, response.GetStringRef().data());
4356 }
4357 } else {
4358 LLDB_LOGF(log,
4359 "GDBRemoteCommunicationClient::%s(): "
4360 "QSupportedAsyncJSONPackets unsupported",
4361 __FUNCTION__);
4362 }
4363
4365 StreamString stream;
4367 LLDB_LOGF(log,
4368 "GDBRemoteCommunicationClient::%s(): supported async "
4369 "JSON packets: %s",
4370 __FUNCTION__, stream.GetData());
4371 }
4372 }
4373
4375 ? m_supported_async_json_packets_sp->GetAsArray()
4376 : nullptr;
4377}
4378
4380 llvm::ArrayRef<int32_t> signals) {
4381 // Format packet:
4382 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4383 auto range = llvm::make_range(signals.begin(), signals.end());
4384 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4385
4386 StringExtractorGDBRemote response;
4387 auto send_status = SendPacketAndWaitForResponse(packet, response);
4388
4390 return Status::FromErrorString("Sending QPassSignals packet failed");
4391
4392 if (response.IsOKResponse()) {
4393 return Status();
4394 } else {
4396 "Unknown error happened during sending QPassSignals packet.");
4397 }
4398}
4399
4401 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4402 Status error;
4403
4404 if (type_name.empty()) {
4405 error = Status::FromErrorString("invalid type_name argument");
4406 return error;
4407 }
4408
4409 // Build command: Configure{type_name}: serialized config data.
4410 StreamGDBRemote stream;
4411 stream.PutCString("QConfigure");
4412 stream.PutCString(type_name);
4413 stream.PutChar(':');
4414 if (config_sp) {
4415 // Gather the plain-text version of the configuration data.
4416 StreamString unescaped_stream;
4417 config_sp->Dump(unescaped_stream);
4418 unescaped_stream.Flush();
4419
4420 // Add it to the stream in escaped fashion.
4421 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4422 unescaped_stream.GetSize());
4423 }
4424 stream.Flush();
4425
4426 // Send the packet.
4427 StringExtractorGDBRemote response;
4428 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4429 if (result == PacketResult::Success) {
4430 // We failed if the config result comes back other than OK.
4431 if (response.GetStringRef() == "OK") {
4432 // Okay!
4433 error.Clear();
4434 } else {
4436 "configuring StructuredData feature {0} failed with error {1}",
4437 type_name, response.GetStringRef());
4438 }
4439 } else {
4440 // Can we get more data here on the failure?
4442 "configuring StructuredData feature {0} failed when sending packet: "
4443 "PacketResult={1}",
4444 type_name, (int)result);
4445 }
4446 return error;
4447}
4448
4453
4458 return true;
4459
4460 // If the remote didn't indicate native-signal support explicitly,
4461 // check whether it is an old version of lldb-server.
4462 return GetThreadSuffixSupported();
4463}
4464
4466 StringExtractorGDBRemote response;
4467 GDBRemoteCommunication::ScopedTimeout timeout(*this, seconds(3));
4468
4469 // LLDB server typically sends no response for "k", so we shouldn't try
4470 // to sync on timeout.
4471 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout(), false) !=
4473 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4474 "failed to send k packet");
4475
4476 char packet_cmd = response.GetChar(0);
4477 if (packet_cmd == 'W' || packet_cmd == 'X')
4478 return response.GetHexU8();
4479
4480 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4481 "unexpected response to k packet: %s",
4482 response.GetStringRef().str().c_str());
4483}
static llvm::raw_ostream & error(Stream &strm)
#define integer
duration< float > calculate_standard_deviation(const std::vector< duration< float > > &v)
static std::optional< ModuleSpec > ParseModuleSpec(StructuredData::Dictionary *dict)
static int gdb_errno_to_system(int err)
static void ParseOSType(llvm::StringRef value, std::string &os_name, std::string &environment)
static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, uint64_t fail_result, Status &error)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
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:452
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:947
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
void Clear()
Clear the arguments.
Definition Args.cpp:388
bool IsConnected() const
Check if the connection is valid.
virtual lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
llvm::StringRef GetCursorArgumentPrefix() const
A uniqued constant string class.
Definition ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
A file utility class.
Definition FileSpec.h: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:376
MemoryRegionInfo & SetMemoryTagged(LazyBool val)
void SetBlocksize(lldb::offset_t blocksize)
void SetName(const char *name)
MemoryRegionInfo & SetIsShadowStack(LazyBool val)
lldb::offset_t GetBlocksize() const
MemoryRegionInfo & SetIsStackMemory(LazyBool val)
void SetDirtyPageList(std::vector< lldb::addr_t > pagelist)
MemoryRegionInfo & SetProtectionKey(std::optional< unsigned > key)
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:119
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:113
void SetGroupID(uint32_t gid)
Definition ProcessInfo.h:58
bool ProcessIDIsValid() const
Definition ProcessInfo.h:70
void SetArg0(llvm::StringRef arg)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:68
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
llvm::StringRef GetName() const
uint32_t GetUserID() const
Definition ProcessInfo.h:48
uint32_t GetGroupID() const
Definition ProcessInfo.h:50
void SetUserID(uint32_t uid)
Definition ProcessInfo.h:56
bool GroupIDIsValid() const
Definition ProcessInfo.h:54
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:60
ProcessInstanceInfo & GetProcessInfo()
void SetEffectiveGroupID(uint32_t gid)
lldb::pid_t GetParentProcessID() const
void SetParentProcessID(lldb::pid_t pid)
void SetEffectiveUserID(uint32_t uid)
A plug-in interface definition class for debugging a process.
Definition Process.h:359
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
int PutAsJSON(const T &obj, bool hex_ascii)
Definition GDBRemote.h:50
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:31
const char * GetData() const
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:418
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:307
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:291
virtual void Flush()=0
Flush the stream.
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:391
ObjectSP GetItemAtIndex(size_t idx) const
std::optional< Dictionary * > GetItemAtIndexAsDictionary(size_t idx) const
Retrieves the element at index idx from a StructuredData::Array if it is a Dictionary.
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
ObjectSP GetValueForKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(llvm::StringRef json_text)
Defines a list of symbol context objects.
Defines a symbol context baton that can be handed other debug core functions.
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1243
const ArchSpec & GetArchitecture() const
Definition Target.h:1285
Represents UUID's of various sizes.
Definition UUID.h:27
bool SetFromStringRef(llvm::StringRef str)
Definition UUID.cpp:101
static bool XMLEnabled()
Definition XML.cpp:83
XMLNode GetRootElement(const char *required_name=nullptr)
Definition XML.cpp:65
bool ParseMemory(const char *xml, size_t xml_length, const char *url="untitled.xml")
Definition XML.cpp:54
void ForEachChildElement(NodeCallback const &callback) const
Definition XML.cpp:169
llvm::StringRef GetName() const
Definition XML.cpp:268
std::string GetAttributeValue(const char *name, const char *fail_value=nullptr) const
Definition XML.cpp:135
bool GetElementTextAsUnsigned(uint64_t &value, uint64_t fail_value=0, int base=0) const
Definition XML.cpp:299
bool GetAttributeValueAsUnsigned(const char *name, uint64_t &value, uint64_t fail_value=0, int base=0) const
Definition XML.cpp:156
bool IsElement() const
Definition XML.cpp:345
PacketResult SendPacketAndWaitForResponse(llvm::StringRef payload, StringExtractorGDBRemote &response, std::chrono::seconds interrupt_timeout=std::chrono::seconds(0), bool sync_on_timeout=true)
PacketResult SendPacketAndWaitForResponseNoLock(llvm::StringRef payload, StringExtractorGDBRemote &response, bool sync_on_timeout=true)
lldb::DataBufferSP ReadRegister(lldb::tid_t tid, uint32_t reg_num)
PacketResult SendThreadSpecificPacketAndWaitForResponse(lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response)
bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
lldb_private::StructuredData::Array * GetSupportedStructuredDataPlugins()
Return the array of async JSON packet types supported by the remote.
lldb::tid_t m_curr_tid_run
Current gdb remote protocol thread identifier for continue, step, etc.
int SetSTDIOWindowSize(uint16_t cols, uint16_t rows)
Send the dimensions of the user's stdio terminal window to the server.
int SendLaunchEventDataPacket(const char *data, bool *was_supported=nullptr)
std::optional< std::vector< ModuleSpec > > GetModulesInfo(llvm::ArrayRef< FileSpec > module_file_specs, const llvm::Triple &triple)
llvm::Expected< std::string > ReadExtFeature(llvm::StringRef object, llvm::StringRef annex)
std::optional< GDBRemoteFStatData > Stat(const FileSpec &file_spec)
std::optional< QOffsets > GetQOffsets()
Use qOffsets to query the offset used when relocating the target executable.
size_t QueryGDBServer(std::vector< std::pair< uint16_t, std::string > > &connection_urls)
llvm::Error SendTraceStop(const TraceStopRequest &request, std::chrono::seconds interrupt_timeout)
void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, uint64_t recv_amount, bool json, Stream &strm)
bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, std::string &socket_name)
bool SetCurrentThreadForRun(uint64_t tid, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
uint8_t SendGDBStoppointTypePacket(GDBStoppointType type, bool insert, lldb::addr_t addr, uint32_t length, std::chrono::seconds interrupt_timeout)
uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error)
bool GetWorkingDir(FileSpec &working_dir)
Gets the current working directory of a remote platform GDB server.
lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, mode_t mode, Status &error)
std::optional< GDBRemoteFStatData > FStat(lldb::user_id_t fd)
Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *separated_error_output, const Timeout< std::micro > &timeout)
llvm::Expected< std::string > SendTraceGetState(llvm::StringRef type, std::chrono::seconds interrupt_timeout)
llvm::Error LaunchProcess(const Args &args)
Launch the process using the provided arguments.
Status ConfigureRemoteStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure a StructuredData feature on the remote end.
uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error)
llvm::Expected< std::vector< AcceleratorActions > > GetAcceleratorInitializeActions()
Send the "jAcceleratorPluginInitialize" packet and return the actions requested by each accelerator p...
bool SetCurrentThread(uint64_t tid, lldb::pid_t pid=LLDB_INVALID_PROCESS_ID)
int SendStdinNotification(const char *data, size_t data_len, std::chrono::seconds interrupt_timeout=std::chrono::seconds(0))
Sends a GDB remote protocol 'I' packet that delivers stdin data to the remote process.
lldb::tid_t m_curr_tid
Current gdb remote protocol thread identifier for all other operations.
bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef< uint8_t > data)
bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info)
Status SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions)
Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr, MemoryRegionInfo &region)
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)
void AutoCompleteDiskFileOrDirectory(CompletionRequest &request, bool only_dir)
lldb::pid_t m_curr_pid_run
Current gdb remote protocol process identifier for continue, step, etc.
void MaybeEnableCompression(llvm::ArrayRef< llvm::StringRef > supported_compressions)
llvm::Expected< TraceSupportedResponse > SendTraceSupported(std::chrono::seconds interrupt_timeout)
llvm::ErrorOr< llvm::MD5::MD5Result > CalculateMD5(const FileSpec &file_spec)
llvm::Error SendTraceStart(const llvm::json::Value &request, std::chrono::seconds interrupt_timeout)
llvm::Expected< AcceleratorBreakpointHitResponse > AcceleratorBreakpointHit(const AcceleratorBreakpointHitArgs &args)
Send the "jAcceleratorPluginBreakpointHit" packet to notify the accelerator plugin that one of its re...
bool GetModuleInfo(const FileSpec &module_file_spec, const ArchSpec &arch_spec, ModuleSpec &module_spec)
std::optional< PidTid > SendSetCurrentThreadPacket(uint64_t tid, uint64_t pid, char op)
Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions)
uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info, ProcessInstanceInfoList &process_infos)
lldb::DataBufferSP ReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type)
int SetWorkingDir(const FileSpec &working_dir)
Sets the working directory to path for a process that will be launched with the 'A' packet for non pl...
std::vector< std::pair< lldb::pid_t, lldb::tid_t > > GetCurrentProcessAndThreadIDs(bool &sequence_mutex_unavailable)
bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response)
bool GetProcessStandaloneBinary(UUID &uuid, lldb::addr_t &value, bool &value_is_offset)
int SendEnvironmentPacket(char const *name_equal_value)
Sends a "QEnvironment:NAME=VALUE" packet that will build up the environment that will get used when l...
std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout)
#define UINT64_MAX
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_CPUTYPE
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const QOffsets &offsets)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
llvm::json::Value toJSON(const Diagnostics::Report &report)
Render a diagnostics report as JSON, for diagnostics dump's terminal output.
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
@ eErrorTypeGeneric
Generic errors that can be any value.
@ eErrorTypePOSIX
POSIX error codes.
@ eSymbolTypeUndefined
@ eSymbolTypeVariableType
@ eSymbolTypeObjCMetaClass
@ eSymbolTypeReExported
@ eSymbolTypeObjCClass
@ eSymbolTypeObjectFile
@ eSymbolTypeTrampoline
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeException
@ eSymbolTypeVariable
@ eSymbolTypeAbsolute
@ eSymbolTypeAdditional
When symbols take more than one entry, the extra entries get this type.
@ eSymbolTypeInstrumentation
@ eSymbolTypeHeaderFile
@ eSymbolTypeCommonBlock
@ eSymbolTypeCompiler
@ eSymbolTypeLineHeader
@ eSymbolTypeObjCIVar
@ eSymbolTypeLineEntry
@ eSymbolTypeScopeBegin
@ eSymbolTypeScopeEnd
uint64_t pid_t
Definition lldb-types.h: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
Sent by the client when a plugin-requested breakpoint is hit.
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
bool IsValid() const
Definition RangeMap.h:91
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
BaseType GetRangeEnd() const
Definition RangeMap.h:78
void SetByteSize(SizeType s)
Definition RangeMap.h:89
jLLDBTraceGetBinaryData gdb-remote packet
jLLDBTraceStop gdb-remote packet
The offsets used by the target when relocating the executable.
bool segments
If true, the offsets field describes segments.
std::vector< uint64_t > offsets
The individual offsets.
#define S_IRWXG
#define S_IRWXO
#define S_IRWXU