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