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