LLDB mainline
GDBRemoteCommunicationClient.cpp
Go to the documentation of this file.
1//===-- GDBRemoteCommunicationClient.cpp ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <cmath>
12#include <sys/stat.h>
13
14#include <numeric>
15#include <optional>
16#include <sstream>
17
19#include "lldb/Host/HostInfo.h"
20#include "lldb/Host/SafeMachO.h"
21#include "lldb/Host/XML.h"
22#include "lldb/Symbol/Symbol.h"
24#include "lldb/Target/Target.h"
26#include "lldb/Utility/Args.h"
30#include "lldb/Utility/Log.h"
31#include "lldb/Utility/State.h"
33
34#include "ProcessGDBRemote.h"
35#include "ProcessGDBRemoteLog.h"
36#include "lldb/Host/Config.h"
38
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/StringSwitch.h"
41#include "llvm/Support/JSON.h"
42
43#if defined(HAVE_LIBCOMPRESSION)
44#include <compression.h>
45#endif
46
47using namespace lldb;
49using namespace lldb_private;
50using namespace std::chrono;
51
52llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os,
53 const QOffsets &offsets) {
54 return os << llvm::formatv(
55 "QOffsets({0}, [{1:@[x]}])", offsets.segments,
56 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end()));
57}
58
59// GDBRemoteCommunicationClient constructor
61 : GDBRemoteClientBase("gdb-remote.client"),
62
63 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
64 m_supports_qUserName(true), m_supports_qGroupName(true),
65 m_supports_qThreadStopInfo(true), m_supports_z0(true),
66 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
67 m_supports_z4(true), m_supports_QEnvironment(true),
68 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
69 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
70 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
71 m_supports_vFileSize(true), m_supports_vFileMode(true),
72 m_supports_vFileExists(true), m_supports_vRun(true),
73
74 m_host_arch(), m_host_distribution_id(), m_process_arch(), m_os_build(),
75 m_os_kernel(), m_hostname(), m_gdb_server_name(),
76 m_default_packet_timeout(0), m_qSupported_response(),
77 m_supported_async_json_packets_sp(), m_qXfer_memory_map() {}
78
79// Destructor
81 if (IsConnected())
82 Disconnect();
83}
84
87
88 // Start the read thread after we send the handshake ack since if we fail to
89 // send the handshake ack, there is no reason to continue...
90 std::chrono::steady_clock::time_point start_of_handshake =
91 std::chrono::steady_clock::now();
92 if (SendAck()) {
93 // The return value from QueryNoAckModeSupported() is true if the packet
94 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
95 // false if no response was received. This quickly tells us if we have a
96 // live connection to a remote GDB server...
98 return true;
99 } else {
100 std::chrono::steady_clock::time_point end_of_handshake =
101 std::chrono::steady_clock::now();
102 auto handshake_timeout =
103 std::chrono::duration<double>(end_of_handshake - start_of_handshake)
104 .count();
105 if (error_ptr) {
106 if (!IsConnected())
107 error_ptr->SetErrorString("Connection shut down by remote side "
108 "while waiting for reply to initial "
109 "handshake packet");
110 else
111 error_ptr->SetErrorStringWithFormat(
112 "failed to get reply to handshake packet within timeout of "
113 "%.1f seconds",
114 handshake_timeout);
115 }
116 }
117 } else {
118 if (error_ptr)
119 error_ptr->SetErrorString("failed to send the handshake ack");
120 }
121 return false;
122}
123
127 }
129}
130
134 }
136}
137
141 }
143}
144
148 }
150}
151
155 }
157}
158
162 }
164}
165
169 }
171}
172
176 }
178}
179
183 }
185}
186
191}
192
194 if (m_max_packet_size == 0) {
196 }
197 return m_max_packet_size;
198}
199
202 m_send_acks = true;
204
205 // This is the first real packet that we'll send in a debug session and it
206 // may take a little longer than normal to receive a reply. Wait at least
207 // 6 seconds for a reply to this packet.
208
209 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
210
212 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) ==
214 if (response.IsOKResponse()) {
215 m_send_acks = false;
217 }
218 return true;
219 }
220 }
221 return false;
222}
223
227
229 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response) ==
231 if (response.IsOKResponse())
233 }
234 }
235}
236
240
242 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response) ==
244 if (response.IsOKResponse())
246 }
247 }
249}
250
254
256 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response) ==
258 if (response.IsOKResponse())
260 }
261 }
263}
264
266 if (!did_exec) {
267 // Hard reset everything, this is when we first connect to a GDB server
301 m_supports_z0 = true;
302 m_supports_z1 = true;
303 m_supports_z2 = true;
304 m_supports_z3 = true;
305 m_supports_z4 = true;
308 m_supports_qSymbol = true;
313 m_os_version = llvm::VersionTuple();
314 m_os_build.clear();
315 m_os_kernel.clear();
316 m_hostname.clear();
317 m_gdb_server_name.clear();
319 m_default_packet_timeout = seconds(0);
322 m_qSupported_response.clear();
326 }
327
328 // These flags should be reset when we first connect to a GDB server and when
329 // our inferior process execs
332}
333
335 // Clear out any capabilities we expect to see in the qSupported response
349
350 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
351 // not, we assume no limit
352
353 // build the qSupported packet
354 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc",
355 "multiprocess+",
356 "fork-events+",
357 "vfork-events+",
358 "swbreak+",
359 "hwbreak+"};
360 StreamString packet;
361 packet.PutCString("qSupported");
362 for (uint32_t i = 0; i < features.size(); ++i) {
363 packet.PutCString(i == 0 ? ":" : ";");
364 packet.PutCString(features[i]);
365 }
366
368 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
370 // Hang on to the qSupported packet, so that platforms can do custom
371 // configuration of the transport before attaching/launching the process.
372 m_qSupported_response = response.GetStringRef().str();
373
374 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) {
375 if (x == "qXfer:auxv:read+")
377 else if (x == "qXfer:libraries-svr4:read+")
379 else if (x == "augmented-libraries-svr4-read") {
382 } else if (x == "qXfer:libraries:read+")
384 else if (x == "qXfer:features:read+")
386 else if (x == "qXfer:memory-map:read+")
388 else if (x == "qXfer:siginfo:read+")
390 else if (x == "qEcho")
392 else if (x == "QPassSignals+")
394 else if (x == "multiprocess+")
396 else if (x == "memory-tagging+")
398 else if (x == "qSaveCore+")
400 else if (x == "native-signals+")
402 // Look for a list of compressions in the features list e.g.
403 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
404 // deflate,lzma
405 else if (x.consume_front("SupportedCompressions=")) {
406 llvm::SmallVector<llvm::StringRef, 4> compressions;
407 x.split(compressions, ',');
408 if (!compressions.empty())
409 MaybeEnableCompression(compressions);
410 } else if (x.consume_front("SupportedWatchpointTypes=")) {
411 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types;
412 x.split(watchpoint_types, ',');
413 m_watchpoint_types = eWatchpointHardwareFeatureUnknown;
414 for (auto wp_type : watchpoint_types) {
415 if (wp_type == "x86_64")
416 m_watchpoint_types |= eWatchpointHardwareX86;
417 if (wp_type == "aarch64-mask")
418 m_watchpoint_types |= eWatchpointHardwareArmMASK;
419 if (wp_type == "aarch64-bas")
420 m_watchpoint_types |= eWatchpointHardwareArmBAS;
421 }
422 } else if (x.consume_front("PacketSize=")) {
423 StringExtractorGDBRemote packet_response(x);
425 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
426 if (m_max_packet_size == 0) {
427 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
429 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
430 }
431 }
432 }
433 }
434}
435
440 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response) ==
442 if (response.IsOKResponse())
444 }
445 }
447}
457 if (SendPacketAndWaitForResponse("vCont?", response) ==
459 const char *response_cstr = response.GetStringRef().data();
460 if (::strstr(response_cstr, ";c"))
462
463 if (::strstr(response_cstr, ";C"))
465
466 if (::strstr(response_cstr, ";s"))
468
469 if (::strstr(response_cstr, ";S"))
471
477 }
478
484 }
485 }
486 }
487
488 switch (flavor) {
489 case 'a':
491 case 'A':
493 case 'c':
494 return m_supports_vCont_c;
495 case 'C':
496 return m_supports_vCont_C;
497 case 's':
498 return m_supports_vCont_s;
499 case 'S':
500 return m_supports_vCont_S;
501 default:
502 break;
503 }
504 return false;
505}
506
509 lldb::tid_t tid, StreamString &&payload,
510 StringExtractorGDBRemote &response) {
511 Lock lock(*this);
512 if (!lock) {
514 LLDB_LOGF(log,
515 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
516 "for %s packet.",
517 __FUNCTION__, payload.GetData());
519 }
520
522 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
523 else {
524 if (!SetCurrentThread(tid))
526 }
527
528 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
529}
530
531// Check if the target supports 'p' packet. It sends out a 'p' packet and
532// checks the response. A normal packet will tell us that support is available.
533//
534// Takes a valid thread ID because p needs to apply to a thread.
538 return m_supports_p;
539}
540
542 lldb::tid_t tid, llvm::StringRef packetStr) {
543 StreamString payload;
544 payload.PutCString(packetStr);
547 tid, std::move(payload), response) == PacketResult::Success &&
548 response.IsNormalResponse()) {
549 return eLazyBoolYes;
550 }
551 return eLazyBoolNo;
552}
553
556}
557
559 // Get information on all threads at one using the "jThreadsInfo" packet
560 StructuredData::ObjectSP object_sp;
561
565 if (SendPacketAndWaitForResponse("jThreadsInfo", response) ==
567 if (response.IsUnsupportedResponse()) {
569 } else if (!response.Empty()) {
570 object_sp = StructuredData::ParseJSON(response.GetStringRef());
571 }
572 }
573 }
574 return object_sp;
575}
576
581 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response) ==
583 if (response.IsOKResponse()) {
585 }
586 }
587 }
589}
590
594 // We try to enable error strings in remote packets but if we fail, we just
595 // work in the older way.
597 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) ==
599 if (response.IsOKResponse()) {
601 }
602 }
603 }
604}
605
610 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
611 response) == PacketResult::Success) {
612 if (response.IsOKResponse()) {
614 }
615 }
616 }
618}
619
624 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response) ==
626 if (response.IsOKResponse()) {
628 }
629 }
630 }
632}
633
638 if (SendPacketAndWaitForResponse("jGetDyldProcessState", response) ==
640 if (!response.IsUnsupportedResponse())
642 }
643 }
645}
646
650 }
652}
653
655 size_t len,
656 int32_t type) {
657 StreamString packet;
658 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type);
660
661 Log *log = GetLog(GDBRLog::Memory);
662
663 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
665 !response.IsNormalResponse()) {
666 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed",
667 __FUNCTION__);
668 return nullptr;
669 }
670
671 // We are expecting
672 // m<hex encoded bytes>
673
674 if (response.GetChar() != 'm') {
675 LLDB_LOGF(log,
676 "GDBRemoteCommunicationClient::%s: qMemTags response did not "
677 "begin with \"m\"",
678 __FUNCTION__);
679 return nullptr;
680 }
681
682 size_t expected_bytes = response.GetBytesLeft() / 2;
683 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0));
684 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData());
685 // Check both because in some situations chars are consumed even
686 // if the decoding fails.
687 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) {
688 LLDB_LOGF(
689 log,
690 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response",
691 __FUNCTION__);
692 return nullptr;
693 }
694
695 return buffer_sp;
696}
697
699 lldb::addr_t addr, size_t len, int32_t type,
700 const std::vector<uint8_t> &tags) {
701 // Format QMemTags:address,length:type:tags
702 StreamString packet;
703 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type);
704 packet.PutBytesAsRawHex8(tags.data(), tags.size());
705
706 Status status;
708 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
710 !response.IsOKResponse()) {
711 status.SetErrorString("QMemTags packet failed");
712 }
713 return status;
714}
715
720 char packet[256];
721 snprintf(packet, sizeof(packet), "x0,0");
722 if (SendPacketAndWaitForResponse(packet, response) ==
724 if (response.IsOKResponse())
726 }
727 }
728 return m_supports_x;
729}
730
732 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
733 return m_curr_pid;
734
735 // First try to retrieve the pid via the qProcessInfo request.
736 GetCurrentProcessInfo(allow_lazy);
738 // We really got it.
739 return m_curr_pid;
740 } else {
741 // If we don't get a response for qProcessInfo, check if $qC gives us a
742 // result. $qC only returns a real process id on older debugserver and
743 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
744 // the thread id, which newer debugserver and lldb-gdbserver stubs return
745 // correctly.
748 if (response.GetChar() == 'Q') {
749 if (response.GetChar() == 'C') {
751 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID);
754 return m_curr_pid;
755 }
756 }
757 }
758 }
759
760 // If we don't get a response for $qC, check if $qfThreadID gives us a
761 // result.
763 bool sequence_mutex_unavailable;
764 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
765 if (!ids.empty() && !sequence_mutex_unavailable) {
766 // If server returned an explicit PID, use that.
767 m_curr_pid_run = m_curr_pid = ids.front().first;
768 // Otherwise, use the TID of the first thread (Linux hack).
770 m_curr_pid_run = m_curr_pid = ids.front().second;
772 return m_curr_pid;
773 }
774 }
775 }
776
778}
779
781 if (!args.GetArgumentAtIndex(0))
782 return llvm::createStringError(llvm::inconvertibleErrorCode(),
783 "Nothing to launch");
784 // try vRun first
785 if (m_supports_vRun) {
786 StreamString packet;
787 packet.PutCString("vRun");
788 for (const Args::ArgEntry &arg : args) {
789 packet.PutChar(';');
790 packet.PutStringAsRawHex8(arg.ref());
791 }
792
794 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
796 return llvm::createStringError(llvm::inconvertibleErrorCode(),
797 "Sending vRun packet failed");
798
799 if (response.IsErrorResponse())
800 return response.GetStatus().ToError();
801
802 // vRun replies with a stop reason packet
803 // FIXME: right now we just discard the packet and LLDB queries
804 // for stop reason again
805 if (!response.IsUnsupportedResponse())
806 return llvm::Error::success();
807
808 m_supports_vRun = false;
809 }
810
811 // fallback to A
812 StreamString packet;
813 packet.PutChar('A');
814 llvm::ListSeparator LS(",");
815 for (const auto &arg : llvm::enumerate(args)) {
816 packet << LS;
817 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index());
818 packet.PutStringAsRawHex8(arg.value().ref());
819 }
820
822 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
824 return llvm::createStringError(llvm::inconvertibleErrorCode(),
825 "Sending A packet failed");
826 }
827 if (!response.IsOKResponse())
828 return response.GetStatus().ToError();
829
830 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) !=
832 return llvm::createStringError(llvm::inconvertibleErrorCode(),
833 "Sending qLaunchSuccess packet failed");
834 }
835 if (response.IsOKResponse())
836 return llvm::Error::success();
837 if (response.GetChar() == 'E') {
838 return llvm::createStringError(llvm::inconvertibleErrorCode(),
839 response.GetStringRef().substr(1));
840 }
841 return llvm::createStringError(llvm::inconvertibleErrorCode(),
842 "unknown error occurred launching process");
843}
844
846 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec;
847 for (const auto &kv : env)
848 vec.emplace_back(kv.first(), kv.second);
849 llvm::sort(vec, llvm::less_first());
850 for (const auto &[k, v] : vec) {
851 int r = SendEnvironmentPacket((k + "=" + v).str().c_str());
852 if (r != 0)
853 return r;
854 }
855 return 0;
856}
857
859 char const *name_equal_value) {
860 if (name_equal_value && name_equal_value[0]) {
861 bool send_hex_encoding = false;
862 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
863 ++p) {
864 if (llvm::isPrint(*p)) {
865 switch (*p) {
866 case '$':
867 case '#':
868 case '*':
869 case '}':
870 send_hex_encoding = true;
871 break;
872 default:
873 break;
874 }
875 } else {
876 // We have non printable characters, lets hex encode this...
877 send_hex_encoding = true;
878 }
879 }
880
882 // Prefer sending unencoded, if possible and the server supports it.
883 if (!send_hex_encoding && m_supports_QEnvironment) {
884 StreamString packet;
885 packet.Printf("QEnvironment:%s", name_equal_value);
886 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
888 return -1;
889
890 if (response.IsOKResponse())
891 return 0;
892 if (response.IsUnsupportedResponse())
894 else {
895 uint8_t error = response.GetError();
896 if (error)
897 return error;
898 return -1;
899 }
900 }
901
903 StreamString packet;
904 packet.PutCString("QEnvironmentHexEncoded:");
905 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
906 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
908 return -1;
909
910 if (response.IsOKResponse())
911 return 0;
912 if (response.IsUnsupportedResponse())
914 else {
915 uint8_t error = response.GetError();
916 if (error)
917 return error;
918 return -1;
919 }
920 }
921 }
922 return -1;
923}
924
926 if (arch && arch[0]) {
927 StreamString packet;
928 packet.Printf("QLaunchArch:%s", arch);
930 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
932 if (response.IsOKResponse())
933 return 0;
934 uint8_t error = response.GetError();
935 if (error)
936 return error;
937 }
938 }
939 return -1;
940}
941
943 char const *data, bool *was_supported) {
944 if (data && *data != '\0') {
945 StreamString packet;
946 packet.Printf("QSetProcessEvent:%s", data);
948 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
950 if (response.IsOKResponse()) {
951 if (was_supported)
952 *was_supported = true;
953 return 0;
954 } else if (response.IsUnsupportedResponse()) {
955 if (was_supported)
956 *was_supported = false;
957 return -1;
958 } else {
959 uint8_t error = response.GetError();
960 if (was_supported)
961 *was_supported = true;
962 if (error)
963 return error;
964 }
965 }
966 }
967 return -1;
968}
969
971 GetHostInfo();
972 return m_os_version;
973}
974
976 GetHostInfo();
978}
979
981 if (GetHostInfo()) {
982 if (!m_os_build.empty())
983 return m_os_build;
984 }
985 return std::nullopt;
986}
987
988std::optional<std::string>
990 if (GetHostInfo()) {
991 if (!m_os_kernel.empty())
992 return m_os_kernel;
993 }
994 return std::nullopt;
995}
996
998 if (GetHostInfo()) {
999 if (!m_hostname.empty()) {
1000 s = m_hostname;
1001 return true;
1002 }
1003 }
1004 s.clear();
1005 return false;
1006}
1007
1009 if (GetHostInfo())
1010 return m_host_arch;
1011 return ArchSpec();
1012}
1013
1018 return m_process_arch;
1019}
1020
1022 UUID &uuid, addr_t &value, bool &value_is_offset) {
1025
1026 // Return true if we have a UUID or an address/offset of the
1027 // main standalone / firmware binary being used.
1030 return false;
1031
1034 value_is_offset = m_process_standalone_value_is_offset;
1035 return true;
1036}
1037
1038std::vector<addr_t>
1042 return m_binary_addresses;
1043}
1044
1047 m_gdb_server_name.clear();
1050
1051 StringExtractorGDBRemote response;
1052 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) ==
1054 if (response.IsNormalResponse()) {
1055 llvm::StringRef name, value;
1056 bool success = false;
1057 while (response.GetNameColonValue(name, value)) {
1058 if (name == "name") {
1059 success = true;
1060 m_gdb_server_name = std::string(value);
1061 } else if (name == "version") {
1062 llvm::StringRef major, minor;
1063 std::tie(major, minor) = value.split('.');
1064 if (!major.getAsInteger(0, m_gdb_server_version))
1065 success = true;
1066 }
1067 }
1068 if (success)
1070 }
1071 }
1072 }
1074}
1075
1077 llvm::ArrayRef<llvm::StringRef> supported_compressions) {
1079 llvm::StringRef avail_name;
1080
1081#if defined(HAVE_LIBCOMPRESSION)
1082 if (avail_type == CompressionType::None) {
1083 for (auto compression : supported_compressions) {
1084 if (compression == "lzfse") {
1085 avail_type = CompressionType::LZFSE;
1086 avail_name = compression;
1087 break;
1088 }
1089 }
1090 }
1091#endif
1092
1093#if defined(HAVE_LIBCOMPRESSION)
1094 if (avail_type == CompressionType::None) {
1095 for (auto compression : supported_compressions) {
1096 if (compression == "zlib-deflate") {
1097 avail_type = CompressionType::ZlibDeflate;
1098 avail_name = compression;
1099 break;
1100 }
1101 }
1102 }
1103#endif
1104
1105#if LLVM_ENABLE_ZLIB
1106 if (avail_type == CompressionType::None) {
1107 for (auto compression : supported_compressions) {
1108 if (compression == "zlib-deflate") {
1109 avail_type = CompressionType::ZlibDeflate;
1110 avail_name = compression;
1111 break;
1112 }
1113 }
1114 }
1115#endif
1116
1117#if defined(HAVE_LIBCOMPRESSION)
1118 if (avail_type == CompressionType::None) {
1119 for (auto compression : supported_compressions) {
1120 if (compression == "lz4") {
1121 avail_type = CompressionType::LZ4;
1122 avail_name = compression;
1123 break;
1124 }
1125 }
1126 }
1127#endif
1128
1129#if defined(HAVE_LIBCOMPRESSION)
1130 if (avail_type == CompressionType::None) {
1131 for (auto compression : supported_compressions) {
1132 if (compression == "lzma") {
1133 avail_type = CompressionType::LZMA;
1134 avail_name = compression;
1135 break;
1136 }
1137 }
1138 }
1139#endif
1140
1141 if (avail_type != CompressionType::None) {
1142 StringExtractorGDBRemote response;
1143 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";";
1144 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
1145 return;
1146
1147 if (response.IsOKResponse()) {
1148 m_compression_type = avail_type;
1149 }
1150 }
1151}
1152
1154 if (GetGDBServerVersion()) {
1155 if (!m_gdb_server_name.empty())
1156 return m_gdb_server_name.c_str();
1157 }
1158 return nullptr;
1159}
1160
1162 if (GetGDBServerVersion())
1163 return m_gdb_server_version;
1164 return 0;
1165}
1166
1168 StringExtractorGDBRemote response;
1170 return false;
1171
1172 if (!response.IsNormalResponse())
1173 return false;
1174
1175 if (response.GetChar() == 'Q' && response.GetChar() == 'C') {
1176 auto pid_tid = response.GetPidTid(0);
1177 if (!pid_tid)
1178 return false;
1179
1180 lldb::pid_t pid = pid_tid->first;
1181 // invalid
1183 return false;
1184
1185 // if we get pid as well, update m_curr_pid
1186 if (pid != 0) {
1187 m_curr_pid_run = m_curr_pid = pid;
1189 }
1190 tid = pid_tid->second;
1191 }
1192
1193 return true;
1194}
1195
1196static void ParseOSType(llvm::StringRef value, std::string &os_name,
1197 std::string &environment) {
1198 if (value == "iossimulator" || value == "tvossimulator" ||
1199 value == "watchossimulator" || value == "xrossimulator" ||
1200 value == "visionossimulator") {
1201 environment = "simulator";
1202 os_name = value.drop_back(environment.size()).str();
1203 } else if (value == "maccatalyst") {
1204 os_name = "ios";
1205 environment = "macabi";
1206 } else {
1207 os_name = value.str();
1208 }
1209}
1210
1212 Log *log = GetLog(GDBRLog::Process);
1213
1214 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1215 // host info computation can require DNS traffic and shelling out to external processes.
1216 // Increase the timeout to account for that.
1217 ScopedTimeout timeout(*this, seconds(10));
1219 StringExtractorGDBRemote response;
1220 if (SendPacketAndWaitForResponse("qHostInfo", response) ==
1222 if (response.IsNormalResponse()) {
1223 llvm::StringRef name;
1224 llvm::StringRef value;
1225 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1226 uint32_t sub = 0;
1227 std::string arch_name;
1228 std::string os_name;
1229 std::string environment;
1230 std::string vendor_name;
1231 std::string triple;
1232 uint32_t pointer_byte_size = 0;
1233 ByteOrder byte_order = eByteOrderInvalid;
1234 uint32_t num_keys_decoded = 0;
1235 while (response.GetNameColonValue(name, value)) {
1236 if (name == "cputype") {
1237 // exception type in big endian hex
1238 if (!value.getAsInteger(0, cpu))
1239 ++num_keys_decoded;
1240 } else if (name == "cpusubtype") {
1241 // exception count in big endian hex
1242 if (!value.getAsInteger(0, sub))
1243 ++num_keys_decoded;
1244 } else if (name == "arch") {
1245 arch_name = std::string(value);
1246 ++num_keys_decoded;
1247 } else if (name == "triple") {
1248 StringExtractor extractor(value);
1249 extractor.GetHexByteString(triple);
1250 ++num_keys_decoded;
1251 } else if (name == "distribution_id") {
1252 StringExtractor extractor(value);
1254 ++num_keys_decoded;
1255 } else if (name == "os_build") {
1256 StringExtractor extractor(value);
1257 extractor.GetHexByteString(m_os_build);
1258 ++num_keys_decoded;
1259 } else if (name == "hostname") {
1260 StringExtractor extractor(value);
1261 extractor.GetHexByteString(m_hostname);
1262 ++num_keys_decoded;
1263 } else if (name == "os_kernel") {
1264 StringExtractor extractor(value);
1265 extractor.GetHexByteString(m_os_kernel);
1266 ++num_keys_decoded;
1267 } else if (name == "ostype") {
1268 ParseOSType(value, os_name, environment);
1269 ++num_keys_decoded;
1270 } else if (name == "vendor") {
1271 vendor_name = std::string(value);
1272 ++num_keys_decoded;
1273 } else if (name == "endian") {
1274 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1275 .Case("little", eByteOrderLittle)
1276 .Case("big", eByteOrderBig)
1277 .Case("pdp", eByteOrderPDP)
1278 .Default(eByteOrderInvalid);
1279 if (byte_order != eByteOrderInvalid)
1280 ++num_keys_decoded;
1281 } else if (name == "ptrsize") {
1282 if (!value.getAsInteger(0, pointer_byte_size))
1283 ++num_keys_decoded;
1284 } else if (name == "addressing_bits") {
1285 if (!value.getAsInteger(0, m_low_mem_addressing_bits)) {
1286 ++num_keys_decoded;
1287 }
1288 } else if (name == "high_mem_addressing_bits") {
1289 if (!value.getAsInteger(0, m_high_mem_addressing_bits))
1290 ++num_keys_decoded;
1291 } else if (name == "low_mem_addressing_bits") {
1292 if (!value.getAsInteger(0, m_low_mem_addressing_bits))
1293 ++num_keys_decoded;
1294 } else if (name == "os_version" ||
1295 name == "version") // Older debugserver binaries used
1296 // the "version" key instead of
1297 // "os_version"...
1298 {
1299 if (!m_os_version.tryParse(value))
1300 ++num_keys_decoded;
1301 } else if (name == "maccatalyst_version") {
1302 if (!m_maccatalyst_version.tryParse(value))
1303 ++num_keys_decoded;
1304 } else if (name == "watchpoint_exceptions_received") {
1306 llvm::StringSwitch<LazyBool>(value)
1307 .Case("before", eLazyBoolNo)
1308 .Case("after", eLazyBoolYes)
1309 .Default(eLazyBoolCalculate);
1311 ++num_keys_decoded;
1312 } else if (name == "default_packet_timeout") {
1313 uint32_t timeout_seconds;
1314 if (!value.getAsInteger(0, timeout_seconds)) {
1315 m_default_packet_timeout = seconds(timeout_seconds);
1317 ++num_keys_decoded;
1318 }
1319 } else if (name == "vm-page-size") {
1320 int page_size;
1321 if (!value.getAsInteger(0, page_size)) {
1322 m_target_vm_page_size = page_size;
1323 ++num_keys_decoded;
1324 }
1325 }
1326 }
1327
1328 if (num_keys_decoded > 0)
1330
1331 if (triple.empty()) {
1332 if (arch_name.empty()) {
1333 if (cpu != LLDB_INVALID_CPUTYPE) {
1335 if (pointer_byte_size) {
1336 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1337 }
1338 if (byte_order != eByteOrderInvalid) {
1339 assert(byte_order == m_host_arch.GetByteOrder());
1340 }
1341
1342 if (!vendor_name.empty())
1343 m_host_arch.GetTriple().setVendorName(
1344 llvm::StringRef(vendor_name));
1345 if (!os_name.empty())
1346 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1347 if (!environment.empty())
1348 m_host_arch.GetTriple().setEnvironmentName(environment);
1349 }
1350 } else {
1351 std::string triple;
1352 triple += arch_name;
1353 if (!vendor_name.empty() || !os_name.empty()) {
1354 triple += '-';
1355 if (vendor_name.empty())
1356 triple += "unknown";
1357 else
1358 triple += vendor_name;
1359 triple += '-';
1360 if (os_name.empty())
1361 triple += "unknown";
1362 else
1363 triple += os_name;
1364 }
1365 m_host_arch.SetTriple(triple.c_str());
1366
1367 llvm::Triple &host_triple = m_host_arch.GetTriple();
1368 if (host_triple.getVendor() == llvm::Triple::Apple &&
1369 host_triple.getOS() == llvm::Triple::Darwin) {
1370 switch (m_host_arch.GetMachine()) {
1371 case llvm::Triple::aarch64:
1372 case llvm::Triple::aarch64_32:
1373 case llvm::Triple::arm:
1374 case llvm::Triple::thumb:
1375 host_triple.setOS(llvm::Triple::IOS);
1376 break;
1377 default:
1378 host_triple.setOS(llvm::Triple::MacOSX);
1379 break;
1380 }
1381 }
1382 if (pointer_byte_size) {
1383 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1384 }
1385 if (byte_order != eByteOrderInvalid) {
1386 assert(byte_order == m_host_arch.GetByteOrder());
1387 }
1388 }
1389 } else {
1390 m_host_arch.SetTriple(triple.c_str());
1391 if (pointer_byte_size) {
1392 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1393 }
1394 if (byte_order != eByteOrderInvalid) {
1395 assert(byte_order == m_host_arch.GetByteOrder());
1396 }
1397
1398 LLDB_LOGF(log,
1399 "GDBRemoteCommunicationClient::%s parsed host "
1400 "architecture as %s, triple as %s from triple text %s",
1401 __FUNCTION__,
1404 : "<null-arch-name>",
1405 m_host_arch.GetTriple().getTriple().c_str(),
1406 triple.c_str());
1407 }
1408 }
1409 }
1410 }
1412}
1413
1415 size_t data_len) {
1416 StreamString packet;
1417 packet.PutCString("I");
1418 packet.PutBytesAsRawHex8(data, data_len);
1419 StringExtractorGDBRemote response;
1420 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1422 return 0;
1423 }
1424 return response.GetError();
1425}
1426
1430 GetHostInfo();
1431 return m_host_arch;
1432}
1433
1435 AddressableBits addressable_bits;
1437 GetHostInfo();
1438
1441 else
1444 return addressable_bits;
1445}
1446
1449 GetHostInfo();
1451}
1452
1454 uint32_t permissions) {
1457 char packet[64];
1458 const int packet_len = ::snprintf(
1459 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1460 permissions & lldb::ePermissionsReadable ? "r" : "",
1461 permissions & lldb::ePermissionsWritable ? "w" : "",
1462 permissions & lldb::ePermissionsExecutable ? "x" : "");
1463 assert(packet_len < (int)sizeof(packet));
1464 UNUSED_IF_ASSERT_DISABLED(packet_len);
1465 StringExtractorGDBRemote response;
1466 if (SendPacketAndWaitForResponse(packet, response) ==
1468 if (response.IsUnsupportedResponse())
1470 else if (!response.IsErrorResponse())
1471 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1472 } else {
1474 }
1475 }
1476 return LLDB_INVALID_ADDRESS;
1477}
1478
1482 char packet[64];
1483 const int packet_len =
1484 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1485 assert(packet_len < (int)sizeof(packet));
1486 UNUSED_IF_ASSERT_DISABLED(packet_len);
1487 StringExtractorGDBRemote response;
1488 if (SendPacketAndWaitForResponse(packet, response) ==
1490 if (response.IsUnsupportedResponse())
1492 else if (response.IsOKResponse())
1493 return true;
1494 } else {
1496 }
1497 }
1498 return false;
1499}
1500
1502 lldb::pid_t pid) {
1503 Status error;
1505
1506 packet.PutChar('D');
1507 if (keep_stopped) {
1509 char packet[64];
1510 const int packet_len =
1511 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1512 assert(packet_len < (int)sizeof(packet));
1513 UNUSED_IF_ASSERT_DISABLED(packet_len);
1514 StringExtractorGDBRemote response;
1515 if (SendPacketAndWaitForResponse(packet, response) ==
1517 response.IsOKResponse()) {
1519 } else {
1521 }
1522 }
1523
1525 error.SetErrorString("Stays stopped not supported by this target.");
1526 return error;
1527 } else {
1528 packet.PutChar('1');
1529 }
1530 }
1531
1533 // Some servers (e.g. qemu) require specifying the PID even if only a single
1534 // process is running.
1535 if (pid == LLDB_INVALID_PROCESS_ID)
1536 pid = GetCurrentProcessID();
1537 packet.PutChar(';');
1538 packet.PutHex64(pid);
1539 } else if (pid != LLDB_INVALID_PROCESS_ID) {
1540 error.SetErrorString("Multiprocess extension not supported by the server.");
1541 return error;
1542 }
1543
1544 StringExtractorGDBRemote response;
1545 PacketResult packet_result =
1546 SendPacketAndWaitForResponse(packet.GetString(), response);
1547 if (packet_result != PacketResult::Success)
1548 error.SetErrorString("Sending isconnect packet failed.");
1549 return error;
1550}
1551
1553 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1554 Status error;
1555 region_info.Clear();
1556
1559 char packet[64];
1560 const int packet_len = ::snprintf(
1561 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1562 assert(packet_len < (int)sizeof(packet));
1563 UNUSED_IF_ASSERT_DISABLED(packet_len);
1564 StringExtractorGDBRemote response;
1565 if (SendPacketAndWaitForResponse(packet, response) ==
1568 llvm::StringRef name;
1569 llvm::StringRef value;
1570 addr_t addr_value = LLDB_INVALID_ADDRESS;
1571 bool success = true;
1572 bool saw_permissions = false;
1573 while (success && response.GetNameColonValue(name, value)) {
1574 if (name == "start") {
1575 if (!value.getAsInteger(16, addr_value))
1576 region_info.GetRange().SetRangeBase(addr_value);
1577 } else if (name == "size") {
1578 if (!value.getAsInteger(16, addr_value)) {
1579 region_info.GetRange().SetByteSize(addr_value);
1580 if (region_info.GetRange().GetRangeEnd() <
1581 region_info.GetRange().GetRangeBase()) {
1582 // Range size overflowed, truncate it.
1584 }
1585 }
1586 } else if (name == "permissions" && region_info.GetRange().IsValid()) {
1587 saw_permissions = true;
1588 if (region_info.GetRange().Contains(addr)) {
1589 if (value.contains('r'))
1591 else
1593
1594 if (value.contains('w'))
1596 else
1598
1599 if (value.contains('x'))
1601 else
1603
1604 region_info.SetMapped(MemoryRegionInfo::eYes);
1605 } else {
1606 // The reported region does not contain this address -- we're
1607 // looking at an unmapped page
1611 region_info.SetMapped(MemoryRegionInfo::eNo);
1612 }
1613 } else if (name == "name") {
1614 StringExtractorGDBRemote name_extractor(value);
1615 std::string name;
1616 name_extractor.GetHexByteString(name);
1617 region_info.SetName(name.c_str());
1618 } else if (name == "flags") {
1620
1621 llvm::StringRef flags = value;
1622 llvm::StringRef flag;
1623 while (flags.size()) {
1624 flags = flags.ltrim();
1625 std::tie(flag, flags) = flags.split(' ');
1626 // To account for trailing whitespace
1627 if (flag.size()) {
1628 if (flag == "mt") {
1630 break;
1631 }
1632 }
1633 }
1634 } else if (name == "type") {
1635 std::string comma_sep_str = value.str();
1636 size_t comma_pos;
1637 while ((comma_pos = comma_sep_str.find(',')) != std::string::npos) {
1638 comma_sep_str[comma_pos] = '\0';
1639 if (comma_sep_str == "stack") {
1641 }
1642 }
1643 // handle final (or only) type of "stack"
1644 if (comma_sep_str == "stack") {
1646 }
1647 } else if (name == "error") {
1648 StringExtractorGDBRemote error_extractor(value);
1649 std::string error_string;
1650 // Now convert the HEX bytes into a string value
1651 error_extractor.GetHexByteString(error_string);
1652 error.SetErrorString(error_string.c_str());
1653 } else if (name == "dirty-pages") {
1654 std::vector<addr_t> dirty_page_list;
1655 for (llvm::StringRef x : llvm::split(value, ',')) {
1656 addr_t page;
1657 x.consume_front("0x");
1658 if (llvm::to_integer(x, page, 16))
1659 dirty_page_list.push_back(page);
1660 }
1661 region_info.SetDirtyPageList(dirty_page_list);
1662 }
1663 }
1664
1665 if (m_target_vm_page_size != 0)
1667
1668 if (region_info.GetRange().IsValid()) {
1669 // We got a valid address range back but no permissions -- which means
1670 // this is an unmapped page
1671 if (!saw_permissions) {
1675 region_info.SetMapped(MemoryRegionInfo::eNo);
1676 }
1677 } else {
1678 // We got an invalid address range back
1679 error.SetErrorString("Server returned invalid range");
1680 }
1681 } else {
1683 }
1684 }
1685
1687 error.SetErrorString("qMemoryRegionInfo is not supported");
1688 }
1689
1690 // Try qXfer:memory-map:read to get region information not included in
1691 // qMemoryRegionInfo
1692 MemoryRegionInfo qXfer_region_info;
1693 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1694
1695 if (error.Fail()) {
1696 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1697 // the qXfer result as a fallback
1698 if (qXfer_error.Success()) {
1699 region_info = qXfer_region_info;
1700 error.Clear();
1701 } else {
1702 region_info.Clear();
1703 }
1704 } else if (qXfer_error.Success()) {
1705 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1706 // both regions are the same range, update the result to include the flash-
1707 // memory information that is specific to the qXfer result.
1708 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1709 region_info.SetFlash(qXfer_region_info.GetFlash());
1710 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1711 }
1712 }
1713 return error;
1714}
1715
1717 lldb::addr_t addr, MemoryRegionInfo &region) {
1719 if (!error.Success())
1720 return error;
1721 for (const auto &map_region : m_qXfer_memory_map) {
1722 if (map_region.GetRange().Contains(addr)) {
1723 region = map_region;
1724 return error;
1725 }
1726 }
1727 error.SetErrorString("Region not found");
1728 return error;
1729}
1730
1732
1733 Status error;
1734
1736 // Already loaded, return success
1737 return error;
1738
1739 if (!XMLDocument::XMLEnabled()) {
1740 error.SetErrorString("XML is not supported");
1741 return error;
1742 }
1743
1745 error.SetErrorString("Memory map is not supported");
1746 return error;
1747 }
1748
1749 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", "");
1750 if (!xml)
1751 return Status(xml.takeError());
1752
1753 XMLDocument xml_document;
1754
1755 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) {
1756 error.SetErrorString("Failed to parse memory map xml");
1757 return error;
1758 }
1759
1760 XMLNode map_node = xml_document.GetRootElement("memory-map");
1761 if (!map_node) {
1762 error.SetErrorString("Invalid root node in memory map xml");
1763 return error;
1764 }
1765
1766 m_qXfer_memory_map.clear();
1767
1768 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1769 if (!memory_node.IsElement())
1770 return true;
1771 if (memory_node.GetName() != "memory")
1772 return true;
1773 auto type = memory_node.GetAttributeValue("type", "");
1774 uint64_t start;
1775 uint64_t length;
1776 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1777 return true;
1778 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1779 return true;
1780 MemoryRegionInfo region;
1781 region.GetRange().SetRangeBase(start);
1782 region.GetRange().SetByteSize(length);
1783 if (type == "rom") {
1784 region.SetReadable(MemoryRegionInfo::eYes);
1785 this->m_qXfer_memory_map.push_back(region);
1786 } else if (type == "ram") {
1787 region.SetReadable(MemoryRegionInfo::eYes);
1788 region.SetWritable(MemoryRegionInfo::eYes);
1789 this->m_qXfer_memory_map.push_back(region);
1790 } else if (type == "flash") {
1791 region.SetFlash(MemoryRegionInfo::eYes);
1792 memory_node.ForEachChildElement(
1793 [&region](const XMLNode &prop_node) -> bool {
1794 if (!prop_node.IsElement())
1795 return true;
1796 if (prop_node.GetName() != "property")
1797 return true;
1798 auto propname = prop_node.GetAttributeValue("name", "");
1799 if (propname == "blocksize") {
1800 uint64_t blocksize;
1801 if (prop_node.GetElementTextAsUnsigned(blocksize))
1802 region.SetBlocksize(blocksize);
1803 }
1804 return true;
1805 });
1806 this->m_qXfer_memory_map.push_back(region);
1807 }
1808 return true;
1809 });
1810
1812
1813 return error;
1814}
1815
1819 }
1820
1821 std::optional<uint32_t> num;
1823 StringExtractorGDBRemote response;
1824 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) ==
1827 llvm::StringRef name;
1828 llvm::StringRef value;
1829 while (response.GetNameColonValue(name, value)) {
1830 if (name == "num") {
1831 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1833 }
1834 }
1835 if (!num) {
1837 }
1838 } else {
1840 }
1841 }
1842
1843 return num;
1844}
1845
1846WatchpointHardwareFeature
1848 return m_watchpoint_types;
1849}
1850
1853 GetHostInfo();
1854
1855 // Process determines this by target CPU, but allow for the
1856 // remote stub to override it via the qHostInfo
1857 // watchpoint_exceptions_received key, if it is present.
1860 return false;
1862 return true;
1863 }
1864
1865 return std::nullopt;
1866}
1867
1869 if (file_spec) {
1870 std::string path{file_spec.GetPath(false)};
1871 StreamString packet;
1872 packet.PutCString("QSetSTDIN:");
1873 packet.PutStringAsRawHex8(path);
1874
1875 StringExtractorGDBRemote response;
1876 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1878 if (response.IsOKResponse())
1879 return 0;
1880 uint8_t error = response.GetError();
1881 if (error)
1882 return error;
1883 }
1884 }
1885 return -1;
1886}
1887
1889 if (file_spec) {
1890 std::string path{file_spec.GetPath(false)};
1891 StreamString packet;
1892 packet.PutCString("QSetSTDOUT:");
1893 packet.PutStringAsRawHex8(path);
1894
1895 StringExtractorGDBRemote response;
1896 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1898 if (response.IsOKResponse())
1899 return 0;
1900 uint8_t error = response.GetError();
1901 if (error)
1902 return error;
1903 }
1904 }
1905 return -1;
1906}
1907
1909 if (file_spec) {
1910 std::string path{file_spec.GetPath(false)};
1911 StreamString packet;
1912 packet.PutCString("QSetSTDERR:");
1913 packet.PutStringAsRawHex8(path);
1914
1915 StringExtractorGDBRemote response;
1916 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1918 if (response.IsOKResponse())
1919 return 0;
1920 uint8_t error = response.GetError();
1921 if (error)
1922 return error;
1923 }
1924 }
1925 return -1;
1926}
1927
1929 StringExtractorGDBRemote response;
1930 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) ==
1932 if (response.IsUnsupportedResponse())
1933 return false;
1934 if (response.IsErrorResponse())
1935 return false;
1936 std::string cwd;
1937 response.GetHexByteString(cwd);
1938 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1939 return !cwd.empty();
1940 }
1941 return false;
1942}
1943
1945 if (working_dir) {
1946 std::string path{working_dir.GetPath(false)};
1947 StreamString packet;
1948 packet.PutCString("QSetWorkingDir:");
1949 packet.PutStringAsRawHex8(path);
1950
1951 StringExtractorGDBRemote response;
1952 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
1954 if (response.IsOKResponse())
1955 return 0;
1956 uint8_t error = response.GetError();
1957 if (error)
1958 return error;
1959 }
1960 }
1961 return -1;
1962}
1963
1965 char packet[32];
1966 const int packet_len =
1967 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1968 assert(packet_len < (int)sizeof(packet));
1969 UNUSED_IF_ASSERT_DISABLED(packet_len);
1970 StringExtractorGDBRemote response;
1971 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
1972 if (response.IsOKResponse())
1973 return 0;
1974 uint8_t error = response.GetError();
1975 if (error)
1976 return error;
1977 }
1978 return -1;
1979}
1980
1982 char packet[32];
1983 const int packet_len = ::snprintf(packet, sizeof(packet),
1984 "QSetDetachOnError:%i", enable ? 1 : 0);
1985 assert(packet_len < (int)sizeof(packet));
1986 UNUSED_IF_ASSERT_DISABLED(packet_len);
1987 StringExtractorGDBRemote response;
1988 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) {
1989 if (response.IsOKResponse())
1990 return 0;
1991 uint8_t error = response.GetError();
1992 if (error)
1993 return error;
1994 }
1995 return -1;
1996}
1997
1999 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
2000 if (response.IsNormalResponse()) {
2001 llvm::StringRef name;
2002 llvm::StringRef value;
2003 StringExtractor extractor;
2004
2005 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2006 uint32_t sub = 0;
2007 std::string vendor;
2008 std::string os_type;
2009
2010 while (response.GetNameColonValue(name, value)) {
2011 if (name == "pid") {
2013 value.getAsInteger(0, pid);
2014 process_info.SetProcessID(pid);
2015 } else if (name == "ppid") {
2017 value.getAsInteger(0, pid);
2018 process_info.SetParentProcessID(pid);
2019 } else if (name == "uid") {
2020 uint32_t uid = UINT32_MAX;
2021 value.getAsInteger(0, uid);
2022 process_info.SetUserID(uid);
2023 } else if (name == "euid") {
2024 uint32_t uid = UINT32_MAX;
2025 value.getAsInteger(0, uid);
2026 process_info.SetEffectiveUserID(uid);
2027 } else if (name == "gid") {
2028 uint32_t gid = UINT32_MAX;
2029 value.getAsInteger(0, gid);
2030 process_info.SetGroupID(gid);
2031 } else if (name == "egid") {
2032 uint32_t gid = UINT32_MAX;
2033 value.getAsInteger(0, gid);
2034 process_info.SetEffectiveGroupID(gid);
2035 } else if (name == "triple") {
2036 StringExtractor extractor(value);
2037 std::string triple;
2038 extractor.GetHexByteString(triple);
2039 process_info.GetArchitecture().SetTriple(triple.c_str());
2040 } else if (name == "name") {
2041 StringExtractor extractor(value);
2042 // The process name from ASCII hex bytes since we can't control the
2043 // characters in a process name
2044 std::string name;
2045 extractor.GetHexByteString(name);
2046 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
2047 } else if (name == "args") {
2048 llvm::StringRef encoded_args(value), hex_arg;
2049
2050 bool is_arg0 = true;
2051 while (!encoded_args.empty()) {
2052 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
2053 std::string arg;
2054 StringExtractor extractor(hex_arg);
2055 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
2056 // In case of wrong encoding, we discard all the arguments
2057 process_info.GetArguments().Clear();
2058 process_info.SetArg0("");
2059 break;
2060 }
2061 if (is_arg0)
2062 process_info.SetArg0(arg);
2063 else
2064 process_info.GetArguments().AppendArgument(arg);
2065 is_arg0 = false;
2066 }
2067 } else if (name == "cputype") {
2068 value.getAsInteger(0, cpu);
2069 } else if (name == "cpusubtype") {
2070 value.getAsInteger(0, sub);
2071 } else if (name == "vendor") {
2072 vendor = std::string(value);
2073 } else if (name == "ostype") {
2074 os_type = std::string(value);
2075 }
2076 }
2077
2078 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
2079 if (vendor == "apple") {
2081 sub);
2082 process_info.GetArchitecture().GetTriple().setVendorName(
2083 llvm::StringRef(vendor));
2084 process_info.GetArchitecture().GetTriple().setOSName(
2085 llvm::StringRef(os_type));
2086 }
2087 }
2088
2089 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2090 return true;
2091 }
2092 return false;
2093}
2094
2096 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
2097 process_info.Clear();
2098
2100 char packet[32];
2101 const int packet_len =
2102 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
2103 assert(packet_len < (int)sizeof(packet));
2104 UNUSED_IF_ASSERT_DISABLED(packet_len);
2105 StringExtractorGDBRemote response;
2106 if (SendPacketAndWaitForResponse(packet, response) ==
2108 return DecodeProcessInfoResponse(response, process_info);
2109 } else {
2111 return false;
2112 }
2113 }
2114 return false;
2115}
2116
2119
2120 if (allow_lazy) {
2122 return true;
2124 return false;
2125 }
2126
2127 GetHostInfo();
2128
2129 StringExtractorGDBRemote response;
2130 if (SendPacketAndWaitForResponse("qProcessInfo", response) ==
2132 if (response.IsNormalResponse()) {
2133 llvm::StringRef name;
2134 llvm::StringRef value;
2135 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2136 uint32_t sub = 0;
2137 std::string arch_name;
2138 std::string os_name;
2139 std::string environment;
2140 std::string vendor_name;
2141 std::string triple;
2142 std::string elf_abi;
2143 uint32_t pointer_byte_size = 0;
2144 StringExtractor extractor;
2145 ByteOrder byte_order = eByteOrderInvalid;
2146 uint32_t num_keys_decoded = 0;
2148 while (response.GetNameColonValue(name, value)) {
2149 if (name == "cputype") {
2150 if (!value.getAsInteger(16, cpu))
2151 ++num_keys_decoded;
2152 } else if (name == "cpusubtype") {
2153 if (!value.getAsInteger(16, sub)) {
2154 ++num_keys_decoded;
2155 // Workaround for pre-2024 Apple debugserver, which always
2156 // returns arm64e on arm64e-capable hardware regardless of
2157 // what the process is. This can be deleted at some point
2158 // in the future.
2159 if (cpu == llvm::MachO::CPU_TYPE_ARM64 &&
2160 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) {
2161 if (GetGDBServerVersion())
2162 if (m_gdb_server_version >= 1000 &&
2163 m_gdb_server_version <= 1504)
2164 sub = 0;
2165 }
2166 }
2167 } else if (name == "triple") {
2168 StringExtractor extractor(value);
2169 extractor.GetHexByteString(triple);
2170 ++num_keys_decoded;
2171 } else if (name == "ostype") {
2172 ParseOSType(value, os_name, environment);
2173 ++num_keys_decoded;
2174 } else if (name == "vendor") {
2175 vendor_name = std::string(value);
2176 ++num_keys_decoded;
2177 } else if (name == "endian") {
2178 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2179 .Case("little", eByteOrderLittle)
2180 .Case("big", eByteOrderBig)
2181 .Case("pdp", eByteOrderPDP)
2182 .Default(eByteOrderInvalid);
2183 if (byte_order != eByteOrderInvalid)
2184 ++num_keys_decoded;
2185 } else if (name == "ptrsize") {
2186 if (!value.getAsInteger(16, pointer_byte_size))
2187 ++num_keys_decoded;
2188 } else if (name == "pid") {
2189 if (!value.getAsInteger(16, pid))
2190 ++num_keys_decoded;
2191 } else if (name == "elf_abi") {
2192 elf_abi = std::string(value);
2193 ++num_keys_decoded;
2194 } else if (name == "main-binary-uuid") {
2196 ++num_keys_decoded;
2197 } else if (name == "main-binary-slide") {
2198 StringExtractor extractor(value);
2200 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2203 ++num_keys_decoded;
2204 }
2205 } else if (name == "main-binary-address") {
2206 StringExtractor extractor(value);
2208 extractor.GetU64(LLDB_INVALID_ADDRESS, 16);
2211 ++num_keys_decoded;
2212 }
2213 } else if (name == "binary-addresses") {
2214 m_binary_addresses.clear();
2215 ++num_keys_decoded;
2216 for (llvm::StringRef x : llvm::split(value, ',')) {
2217 addr_t vmaddr;
2218 x.consume_front("0x");
2219 if (llvm::to_integer(x, vmaddr, 16))
2220 m_binary_addresses.push_back(vmaddr);
2221 }
2222 }
2223 }
2224 if (num_keys_decoded > 0)
2226 if (pid != LLDB_INVALID_PROCESS_ID) {
2228 m_curr_pid_run = m_curr_pid = pid;
2229 }
2230
2231 // Set the ArchSpec from the triple if we have it.
2232 if (!triple.empty()) {
2233 m_process_arch.SetTriple(triple.c_str());
2234 m_process_arch.SetFlags(elf_abi);
2235 if (pointer_byte_size) {
2236 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2237 }
2238 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2239 !vendor_name.empty()) {
2240 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2241 if (!environment.empty())
2242 triple.setEnvironmentName(environment);
2243
2244 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2245 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2246 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2247 switch (triple.getObjectFormat()) {
2248 case llvm::Triple::MachO:
2250 break;
2251 case llvm::Triple::ELF:
2253 break;
2254 case llvm::Triple::COFF:
2256 break;
2257 case llvm::Triple::GOFF:
2258 case llvm::Triple::SPIRV:
2259 case llvm::Triple::Wasm:
2260 case llvm::Triple::XCOFF:
2261 case llvm::Triple::DXContainer:
2262 LLDB_LOGF(log, "error: not supported target architecture");
2263 return false;
2264 case llvm::Triple::UnknownObjectFormat:
2265 LLDB_LOGF(log, "error: failed to determine target architecture");
2266 return false;
2267 }
2268
2269 if (pointer_byte_size) {
2270 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2271 }
2272 if (byte_order != eByteOrderInvalid) {
2273 assert(byte_order == m_process_arch.GetByteOrder());
2274 }
2275 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2276 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2277 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2278 }
2279 return true;
2280 }
2281 } else {
2283 }
2284
2285 return false;
2286}
2287
2289 const ProcessInstanceInfoMatch &match_info,
2290 ProcessInstanceInfoList &process_infos) {
2291 process_infos.clear();
2292
2294 StreamString packet;
2295 packet.PutCString("qfProcessInfo");
2296 if (!match_info.MatchAllProcesses()) {
2297 packet.PutChar(':');
2298 const char *name = match_info.GetProcessInfo().GetName();
2299 bool has_name_match = false;
2300 if (name && name[0]) {
2301 has_name_match = true;
2302 NameMatch name_match_type = match_info.GetNameMatchType();
2303 switch (name_match_type) {
2304 case NameMatch::Ignore:
2305 has_name_match = false;
2306 break;
2307
2308 case NameMatch::Equals:
2309 packet.PutCString("name_match:equals;");
2310 break;
2311
2313 packet.PutCString("name_match:contains;");
2314 break;
2315
2317 packet.PutCString("name_match:starts_with;");
2318 break;
2319
2321 packet.PutCString("name_match:ends_with;");
2322 break;
2323
2325 packet.PutCString("name_match:regex;");
2326 break;
2327 }
2328 if (has_name_match) {
2329 packet.PutCString("name:");
2330 packet.PutBytesAsRawHex8(name, ::strlen(name));
2331 packet.PutChar(';');
2332 }
2333 }
2334
2335 if (match_info.GetProcessInfo().ProcessIDIsValid())
2336 packet.Printf("pid:%" PRIu64 ";",
2337 match_info.GetProcessInfo().GetProcessID());
2338 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2339 packet.Printf("parent_pid:%" PRIu64 ";",
2340 match_info.GetProcessInfo().GetParentProcessID());
2341 if (match_info.GetProcessInfo().UserIDIsValid())
2342 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2343 if (match_info.GetProcessInfo().GroupIDIsValid())
2344 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2345 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2346 packet.Printf("euid:%u;",
2347 match_info.GetProcessInfo().GetEffectiveUserID());
2348 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2349 packet.Printf("egid:%u;",
2350 match_info.GetProcessInfo().GetEffectiveGroupID());
2351 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2352 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2353 const ArchSpec &match_arch =
2354 match_info.GetProcessInfo().GetArchitecture();
2355 const llvm::Triple &triple = match_arch.GetTriple();
2356 packet.PutCString("triple:");
2357 packet.PutCString(triple.getTriple());
2358 packet.PutChar(';');
2359 }
2360 }
2361 StringExtractorGDBRemote response;
2362 // Increase timeout as the first qfProcessInfo packet takes a long time on
2363 // Android. The value of 1min was arrived at empirically.
2364 ScopedTimeout timeout(*this, minutes(1));
2365 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2367 do {
2368 ProcessInstanceInfo process_info;
2369 if (!DecodeProcessInfoResponse(response, process_info))
2370 break;
2371 process_infos.push_back(process_info);
2372 response = StringExtractorGDBRemote();
2373 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2375 } else {
2377 return 0;
2378 }
2379 }
2380 return process_infos.size();
2381}
2382
2384 std::string &name) {
2386 char packet[32];
2387 const int packet_len =
2388 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2389 assert(packet_len < (int)sizeof(packet));
2390 UNUSED_IF_ASSERT_DISABLED(packet_len);
2391 StringExtractorGDBRemote response;
2392 if (SendPacketAndWaitForResponse(packet, response) ==
2394 if (response.IsNormalResponse()) {
2395 // Make sure we parsed the right number of characters. The response is
2396 // the hex encoded user name and should make up the entire packet. If
2397 // there are any non-hex ASCII bytes, the length won't match below..
2398 if (response.GetHexByteString(name) * 2 ==
2399 response.GetStringRef().size())
2400 return true;
2401 }
2402 } else {
2403 m_supports_qUserName = false;
2404 return false;
2405 }
2406 }
2407 return false;
2408}
2409
2411 std::string &name) {
2413 char packet[32];
2414 const int packet_len =
2415 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2416 assert(packet_len < (int)sizeof(packet));
2417 UNUSED_IF_ASSERT_DISABLED(packet_len);
2418 StringExtractorGDBRemote response;
2419 if (SendPacketAndWaitForResponse(packet, response) ==
2421 if (response.IsNormalResponse()) {
2422 // Make sure we parsed the right number of characters. The response is
2423 // the hex encoded group name and should make up the entire packet. If
2424 // there are any non-hex ASCII bytes, the length won't match below..
2425 if (response.GetHexByteString(name) * 2 ==
2426 response.GetStringRef().size())
2427 return true;
2428 }
2429 } else {
2430 m_supports_qGroupName = false;
2431 return false;
2432 }
2433 }
2434 return false;
2435}
2436
2437static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2438 uint32_t recv_size) {
2439 packet.Clear();
2440 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2441 uint32_t bytes_left = send_size;
2442 while (bytes_left > 0) {
2443 if (bytes_left >= 26) {
2444 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2445 bytes_left -= 26;
2446 } else {
2447 packet.Printf("%*.*s;", bytes_left, bytes_left,
2448 "abcdefghijklmnopqrstuvwxyz");
2449 bytes_left = 0;
2450 }
2451 }
2452}
2453
2454duration<float>
2455calculate_standard_deviation(const std::vector<duration<float>> &v) {
2456 if (v.size() == 0)
2457 return duration<float>::zero();
2458 using Dur = duration<float>;
2459 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2460 Dur mean = sum / v.size();
2461 float accum = 0;
2462 for (auto d : v) {
2463 float delta = (d - mean).count();
2464 accum += delta * delta;
2465 };
2466
2467 return Dur(sqrtf(accum / (v.size() - 1)));
2468}
2469
2471 uint32_t max_send,
2472 uint32_t max_recv,
2473 uint64_t recv_amount,
2474 bool json, Stream &strm) {
2475
2476 if (SendSpeedTestPacket(0, 0)) {
2477 StreamString packet;
2478 if (json)
2479 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2480 "\"results\" : [",
2481 num_packets);
2482 else
2483 strm.Printf("Testing sending %u packets of various sizes:\n",
2484 num_packets);
2485 strm.Flush();
2486
2487 uint32_t result_idx = 0;
2488 uint32_t send_size;
2489 std::vector<duration<float>> packet_times;
2490
2491 for (send_size = 0; send_size <= max_send;
2492 send_size ? send_size *= 2 : send_size = 4) {
2493 for (uint32_t recv_size = 0; recv_size <= max_recv;
2494 recv_size ? recv_size *= 2 : recv_size = 4) {
2495 MakeSpeedTestPacket(packet, send_size, recv_size);
2496
2497 packet_times.clear();
2498 // Test how long it takes to send 'num_packets' packets
2499 const auto start_time = steady_clock::now();
2500 for (uint32_t i = 0; i < num_packets; ++i) {
2501 const auto packet_start_time = steady_clock::now();
2502 StringExtractorGDBRemote response;
2503 SendPacketAndWaitForResponse(packet.GetString(), response);
2504 const auto packet_end_time = steady_clock::now();
2505 packet_times.push_back(packet_end_time - packet_start_time);
2506 }
2507 const auto end_time = steady_clock::now();
2508 const auto total_time = end_time - start_time;
2509
2510 float packets_per_second =
2511 ((float)num_packets) / duration<float>(total_time).count();
2512 auto average_per_packet = num_packets > 0 ? total_time / num_packets
2513 : duration<float>::zero();
2514 const duration<float> standard_deviation =
2515 calculate_standard_deviation(packet_times);
2516 if (json) {
2517 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2518 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2519 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2520 result_idx > 0 ? "," : "", send_size, recv_size,
2521 total_time, standard_deviation);
2522 ++result_idx;
2523 } else {
2524 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2525 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2526 "standard deviation of {5,10:ms+f6}\n",
2527 send_size, recv_size, duration<float>(total_time),
2528 packets_per_second, duration<float>(average_per_packet),
2529 standard_deviation);
2530 }
2531 strm.Flush();
2532 }
2533 }
2534
2535 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2536 if (json)
2537 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2538 ": %" PRIu64 ",\n \"results\" : [",
2539 recv_amount);
2540 else
2541 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2542 "packet sizes:\n",
2543 k_recv_amount_mb);
2544 strm.Flush();
2545 send_size = 0;
2546 result_idx = 0;
2547 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2548 MakeSpeedTestPacket(packet, send_size, recv_size);
2549
2550 // If we have a receive size, test how long it takes to receive 4MB of
2551 // data
2552 if (recv_size > 0) {
2553 const auto start_time = steady_clock::now();
2554 uint32_t bytes_read = 0;
2555 uint32_t packet_count = 0;
2556 while (bytes_read < recv_amount) {
2557 StringExtractorGDBRemote response;
2558 SendPacketAndWaitForResponse(packet.GetString(), response);
2559 bytes_read += recv_size;
2560 ++packet_count;
2561 }
2562 const auto end_time = steady_clock::now();
2563 const auto total_time = end_time - start_time;
2564 float mb_second = ((float)recv_amount) /
2565 duration<float>(total_time).count() /
2566 (1024.0 * 1024.0);
2567 float packets_per_second =
2568 ((float)packet_count) / duration<float>(total_time).count();
2569 const auto average_per_packet = packet_count > 0
2570 ? total_time / packet_count
2571 : duration<float>::zero();
2572
2573 if (json) {
2574 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2575 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2576 result_idx > 0 ? "," : "", send_size, recv_size,
2577 total_time);
2578 ++result_idx;
2579 } else {
2580 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2581 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2582 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2583 send_size, recv_size, packet_count, k_recv_amount_mb,
2584 duration<float>(total_time), mb_second,
2585 packets_per_second, duration<float>(average_per_packet));
2586 }
2587 strm.Flush();
2588 }
2589 }
2590 if (json)
2591 strm.Printf("\n ]\n }\n}\n");
2592 else
2593 strm.EOL();
2594 }
2595}
2596
2598 uint32_t recv_size) {
2599 StreamString packet;
2600 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2601 uint32_t bytes_left = send_size;
2602 while (bytes_left > 0) {
2603 if (bytes_left >= 26) {
2604 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2605 bytes_left -= 26;
2606 } else {
2607 packet.Printf("%*.*s;", bytes_left, bytes_left,
2608 "abcdefghijklmnopqrstuvwxyz");
2609 bytes_left = 0;
2610 }
2611 }
2612
2613 StringExtractorGDBRemote response;
2614 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2616}
2617
2619 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2620 std::string &socket_name) {
2622 port = 0;
2623 socket_name.clear();
2624
2625 StringExtractorGDBRemote response;
2626 StreamString stream;
2627 stream.PutCString("qLaunchGDBServer;");
2628 std::string hostname;
2629 if (remote_accept_hostname && remote_accept_hostname[0])
2630 hostname = remote_accept_hostname;
2631 else {
2632 if (HostInfo::GetHostname(hostname)) {
2633 // Make the GDB server we launch only accept connections from this host
2634 stream.Printf("host:%s;", hostname.c_str());
2635 } else {
2636 // Make the GDB server we launch accept connections from any host since
2637 // we can't figure out the hostname
2638 stream.Printf("host:*;");
2639 }
2640 }
2641 // give the process a few seconds to startup
2642 ScopedTimeout timeout(*this, seconds(10));
2643
2644 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2646 if (response.IsErrorResponse())
2647 return false;
2648
2649 llvm::StringRef name;
2650 llvm::StringRef value;
2651 while (response.GetNameColonValue(name, value)) {
2652 if (name == "port")
2653 value.getAsInteger(0, port);
2654 else if (name == "pid")
2655 value.getAsInteger(0, pid);
2656 else if (name.compare("socket_name") == 0) {
2657 StringExtractor extractor(value);
2658 extractor.GetHexByteString(socket_name);
2659 }
2660 }
2661 return true;
2662 }
2663 return false;
2664}
2665
2667 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2668 connection_urls.clear();
2669
2670 StringExtractorGDBRemote response;
2671 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2673 return 0;
2674
2677 if (!data)
2678 return 0;
2679
2680 StructuredData::Array *array = data->GetAsArray();
2681 if (!array)
2682 return 0;
2683
2684 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2685 std::optional<StructuredData::Dictionary *> maybe_element =
2687 if (!maybe_element)
2688 continue;
2689
2690 StructuredData::Dictionary *element = *maybe_element;
2691 uint16_t port = 0;
2692 if (StructuredData::ObjectSP port_osp =
2693 element->GetValueForKey(llvm::StringRef("port")))
2694 port = port_osp->GetUnsignedIntegerValue(0);
2695
2696 std::string socket_name;
2697 if (StructuredData::ObjectSP socket_name_osp =
2698 element->GetValueForKey(llvm::StringRef("socket_name")))
2699 socket_name = std::string(socket_name_osp->GetStringValue());
2700
2701 if (port != 0 || !socket_name.empty())
2702 connection_urls.emplace_back(port, socket_name);
2703 }
2704 return connection_urls.size();
2705}
2706
2708 StreamString stream;
2709 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2710
2711 StringExtractorGDBRemote response;
2712 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2714 if (response.IsOKResponse())
2715 return true;
2716 }
2717 return false;
2718}
2719
2721 uint64_t tid, uint64_t pid, char op) {
2723 packet.PutChar('H');
2724 packet.PutChar(op);
2725
2726 if (pid != LLDB_INVALID_PROCESS_ID)
2727 packet.Printf("p%" PRIx64 ".", pid);
2728
2729 if (tid == UINT64_MAX)
2730 packet.PutCString("-1");
2731 else
2732 packet.Printf("%" PRIx64, tid);
2733
2734 StringExtractorGDBRemote response;
2735 if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2737 if (response.IsOKResponse())
2738 return {{pid, tid}};
2739
2740 /*
2741 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2742 * Hg packet.
2743 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2744 * which can
2745 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2746 */
2747 if (response.IsUnsupportedResponse() && IsConnected())
2748 return {{1, 1}};
2749 }
2750 return std::nullopt;
2751}
2752
2754 uint64_t pid) {
2755 if (m_curr_tid == tid &&
2756 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2757 return true;
2758
2759 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2760 if (ret) {
2761 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2762 m_curr_pid = ret->pid;
2763 m_curr_tid = ret->tid;
2764 }
2765 return ret.has_value();
2766}
2767
2769 uint64_t pid) {
2770 if (m_curr_tid_run == tid &&
2771 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2772 return true;
2773
2774 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2775 if (ret) {
2776 if (ret->pid != LLDB_INVALID_PROCESS_ID)
2777 m_curr_pid_run = ret->pid;
2778 m_curr_tid_run = ret->tid;
2779 }
2780 return ret.has_value();
2781}
2782
2784 StringExtractorGDBRemote &response) {
2786 return response.IsNormalResponse();
2787 return false;
2788}
2789
2791 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2793 char packet[256];
2794 int packet_len =
2795 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2796 assert(packet_len < (int)sizeof(packet));
2797 UNUSED_IF_ASSERT_DISABLED(packet_len);
2798 if (SendPacketAndWaitForResponse(packet, response) ==
2800 if (response.IsUnsupportedResponse())
2802 else if (response.IsNormalResponse())
2803 return true;
2804 else
2805 return false;
2806 } else {
2808 }
2809 }
2810 return false;
2811}
2812
2814 GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2815 std::chrono::seconds timeout) {
2817 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2818 __FUNCTION__, insert ? "add" : "remove", addr);
2819
2820 // Check if the stub is known not to support this breakpoint type
2821 if (!SupportsGDBStoppointPacket(type))
2822 return UINT8_MAX;
2823 // Construct the breakpoint packet
2824 char packet[64];
2825 const int packet_len =
2826 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2827 insert ? 'Z' : 'z', type, addr, length);
2828 // Check we haven't overwritten the end of the packet buffer
2829 assert(packet_len + 1 < (int)sizeof(packet));
2830 UNUSED_IF_ASSERT_DISABLED(packet_len);
2831 StringExtractorGDBRemote response;
2832 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2833 // or "" (unsupported)
2835 // Try to send the breakpoint packet, and check that it was correctly sent
2836 if (SendPacketAndWaitForResponse(packet, response, timeout) ==
2838 // Receive and OK packet when the breakpoint successfully placed
2839 if (response.IsOKResponse())
2840 return 0;
2841
2842 // Status while setting breakpoint, send back specific error
2843 if (response.IsErrorResponse())
2844 return response.GetError();
2845
2846 // Empty packet informs us that breakpoint is not supported
2847 if (response.IsUnsupportedResponse()) {
2848 // Disable this breakpoint type since it is unsupported
2849 switch (type) {
2851 m_supports_z0 = false;
2852 break;
2854 m_supports_z1 = false;
2855 break;
2856 case eWatchpointWrite:
2857 m_supports_z2 = false;
2858 break;
2859 case eWatchpointRead:
2860 m_supports_z3 = false;
2861 break;
2863 m_supports_z4 = false;
2864 break;
2865 case eStoppointInvalid:
2866 return UINT8_MAX;
2867 }
2868 }
2869 }
2870 // Signal generic failure
2871 return UINT8_MAX;
2872}
2873
2874std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
2876 bool &sequence_mutex_unavailable) {
2877 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
2878
2879 Lock lock(*this);
2880 if (lock) {
2881 sequence_mutex_unavailable = false;
2882 StringExtractorGDBRemote response;
2883
2884 PacketResult packet_result;
2885 for (packet_result =
2886 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2887 packet_result == PacketResult::Success && response.IsNormalResponse();
2888 packet_result =
2889 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2890 char ch = response.GetChar();
2891 if (ch == 'l')
2892 break;
2893 if (ch == 'm') {
2894 do {
2895 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
2896 // If we get an invalid response, break out of the loop.
2897 // If there are valid tids, they have been added to ids.
2898 // If there are no valid tids, we'll fall through to the
2899 // bare-iron target handling below.
2900 if (!pid_tid)
2901 break;
2902
2903 ids.push_back(*pid_tid);
2904 ch = response.GetChar(); // Skip the command separator
2905 } while (ch == ','); // Make sure we got a comma separator
2906 }
2907 }
2908
2909 /*
2910 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2911 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2912 * could
2913 * be as simple as 'S05'. There is no packet which can give us pid and/or
2914 * tid.
2915 * Assume pid=tid=1 in such cases.
2916 */
2917 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2918 ids.size() == 0 && IsConnected()) {
2919 ids.emplace_back(1, 1);
2920 }
2921 } else {
2923 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
2924 "packet 'qfThreadInfo'");
2925 sequence_mutex_unavailable = true;
2926 }
2927
2928 return ids;
2929}
2930
2932 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2934 thread_ids.clear();
2935
2936 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
2937 if (ids.empty() || sequence_mutex_unavailable)
2938 return 0;
2939
2940 for (auto id : ids) {
2941 // skip threads that do not belong to the current process
2942 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
2943 continue;
2944 if (id.second != LLDB_INVALID_THREAD_ID &&
2946 thread_ids.push_back(id.second);
2947 }
2948
2949 return thread_ids.size();
2950}
2951
2953 StringExtractorGDBRemote response;
2954 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
2956 !response.IsNormalResponse())
2957 return LLDB_INVALID_ADDRESS;
2958 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2959}
2960
2962 llvm::StringRef command,
2963 const FileSpec &
2964 working_dir, // Pass empty FileSpec to use the current working directory
2965 int *status_ptr, // Pass NULL if you don't want the process exit status
2966 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2967 // process to exit
2968 std::string
2969 *command_output, // Pass NULL if you don't want the command output
2970 const Timeout<std::micro> &timeout) {
2972 stream.PutCString("qPlatform_shell:");
2973 stream.PutBytesAsRawHex8(command.data(), command.size());
2974 stream.PutChar(',');
2975 uint32_t timeout_sec = UINT32_MAX;
2976 if (timeout) {
2977 // TODO: Use chrono version of std::ceil once c++17 is available.
2978 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2979 }
2980 stream.PutHex32(timeout_sec);
2981 if (working_dir) {
2982 std::string path{working_dir.GetPath(false)};
2983 stream.PutChar(',');
2984 stream.PutStringAsRawHex8(path);
2985 }
2986 StringExtractorGDBRemote response;
2987 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2989 if (response.GetChar() != 'F')
2990 return Status("malformed reply");
2991 if (response.GetChar() != ',')
2992 return Status("malformed reply");
2993 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2994 if (exitcode == UINT32_MAX)
2995 return Status("unable to run remote process");
2996 else if (status_ptr)
2997 *status_ptr = exitcode;
2998 if (response.GetChar() != ',')
2999 return Status("malformed reply");
3000 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3001 if (signo_ptr)
3002 *signo_ptr = signo;
3003 if (response.GetChar() != ',')
3004 return Status("malformed reply");
3005 std::string output;
3006 response.GetEscapedBinaryData(output);
3007 if (command_output)
3008 command_output->assign(output);
3009 return Status();
3010 }
3011 return Status("unable to send packet");
3012}
3013
3015 uint32_t file_permissions) {
3016 std::string path{file_spec.GetPath(false)};
3018 stream.PutCString("qPlatform_mkdir:");
3019 stream.PutHex32(file_permissions);
3020 stream.PutChar(',');
3021 stream.PutStringAsRawHex8(path);
3022 llvm::StringRef packet = stream.GetString();
3023 StringExtractorGDBRemote response;
3024
3025 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3026 return Status("failed to send '%s' packet", packet.str().c_str());
3027
3028 if (response.GetChar() != 'F')
3029 return Status("invalid response to '%s' packet", packet.str().c_str());
3030
3031 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3032}
3033
3034Status
3036 uint32_t file_permissions) {
3037 std::string path{file_spec.GetPath(false)};
3039 stream.PutCString("qPlatform_chmod:");
3040 stream.PutHex32(file_permissions);
3041 stream.PutChar(',');
3042 stream.PutStringAsRawHex8(path);
3043 llvm::StringRef packet = stream.GetString();
3044 StringExtractorGDBRemote response;
3045
3046 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3047 return Status("failed to send '%s' packet", stream.GetData());
3048
3049 if (response.GetChar() != 'F')
3050 return Status("invalid response to '%s' packet", stream.GetData());
3051
3052 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3053}
3054
3055static int gdb_errno_to_system(int err) {
3056 switch (err) {
3057#define HANDLE_ERRNO(name, value) \
3058 case GDB_##name: \
3059 return name;
3060#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3061 default:
3062 return -1;
3063 }
3064}
3065
3067 uint64_t fail_result, Status &error) {
3068 response.SetFilePos(0);
3069 if (response.GetChar() != 'F')
3070 return fail_result;
3071 int32_t result = response.GetS32(-2, 16);
3072 if (result == -2)
3073 return fail_result;
3074 if (response.GetChar() == ',') {
3075 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3076 if (result_errno != -1)
3077 error.SetError(result_errno, eErrorTypePOSIX);
3078 else
3079 error.SetError(-1, eErrorTypeGeneric);
3080 } else
3081 error.Clear();
3082 return result;
3083}
3086 File::OpenOptions flags, mode_t mode,
3087 Status &error) {
3088 std::string path(file_spec.GetPath(false));
3090 stream.PutCString("vFile:open:");
3091 if (path.empty())
3092 return UINT64_MAX;
3093 stream.PutStringAsRawHex8(path);
3094 stream.PutChar(',');
3095 stream.PutHex32(flags);
3096 stream.PutChar(',');
3097 stream.PutHex32(mode);
3098 StringExtractorGDBRemote response;
3099 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3101 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3102 }
3103 return UINT64_MAX;
3104}
3105
3107 Status &error) {
3109 stream.Printf("vFile:close:%x", (int)fd);
3110 StringExtractorGDBRemote response;
3111 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3113 return ParseHostIOPacketResponse(response, -1, error) == 0;
3114 }
3115 return false;
3116}
3117
3118std::optional<GDBRemoteFStatData>
3121 stream.Printf("vFile:fstat:%" PRIx64, fd);
3122 StringExtractorGDBRemote response;
3123 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3125 if (response.GetChar() != 'F')
3126 return std::nullopt;
3127 int64_t size = response.GetS64(-1, 16);
3128 if (size > 0 && response.GetChar() == ';') {
3129 std::string buffer;
3130 if (response.GetEscapedBinaryData(buffer)) {
3132 if (buffer.size() != sizeof(out))
3133 return std::nullopt;
3134 memcpy(&out, buffer.data(), sizeof(out));
3135 return out;
3136 }
3137 }
3138 }
3139 return std::nullopt;
3140}
3141
3142std::optional<GDBRemoteFStatData>
3144 Status error;
3146 if (fd == UINT64_MAX)
3147 return std::nullopt;
3148 std::optional<GDBRemoteFStatData> st = FStat(fd);
3149 CloseFile(fd, error);
3150 return st;
3151}
3152
3153// Extension of host I/O packets to get the file size.
3155 const lldb_private::FileSpec &file_spec) {
3157 std::string path(file_spec.GetPath(false));
3159 stream.PutCString("vFile:size:");
3160 stream.PutStringAsRawHex8(path);
3161 StringExtractorGDBRemote response;
3162 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3164 return UINT64_MAX;
3165
3166 if (!response.IsUnsupportedResponse()) {
3167 if (response.GetChar() != 'F')
3168 return UINT64_MAX;
3169 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3170 return retcode;
3171 }
3172 m_supports_vFileSize = false;
3173 }
3174
3175 // Fallback to fstat.
3176 std::optional<GDBRemoteFStatData> st = Stat(file_spec);
3177 return st ? st->gdb_st_size : UINT64_MAX;
3178}
3179
3181 CompletionRequest &request, bool only_dir) {
3183 stream.PutCString("qPathComplete:");
3184 stream.PutHex32(only_dir ? 1 : 0);
3185 stream.PutChar(',');
3187 StringExtractorGDBRemote response;
3188 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3190 StreamString strm;
3191 char ch = response.GetChar();
3192 if (ch != 'M')
3193 return;
3194 while (response.Peek()) {
3195 strm.Clear();
3196 while ((ch = response.GetHexU8(0, false)) != '\0')
3197 strm.PutChar(ch);
3198 request.AddCompletion(strm.GetString());
3199 if (response.GetChar() != ',')
3200 break;
3201 }
3202 }
3203}
3204
3205Status
3207 uint32_t &file_permissions) {
3209 std::string path{file_spec.GetPath(false)};
3210 Status error;
3212 stream.PutCString("vFile:mode:");
3213 stream.PutStringAsRawHex8(path);
3214 StringExtractorGDBRemote response;
3215 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3217 error.SetErrorStringWithFormat("failed to send '%s' packet",
3218 stream.GetData());
3219 return error;
3220 }
3221 if (!response.IsUnsupportedResponse()) {
3222 if (response.GetChar() != 'F') {
3223 error.SetErrorStringWithFormat("invalid response to '%s' packet",
3224 stream.GetData());
3225 } else {
3226 const uint32_t mode = response.GetS32(-1, 16);
3227 if (static_cast<int32_t>(mode) == -1) {
3228 if (response.GetChar() == ',') {
3229 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3230 if (response_errno > 0)
3231 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3232 else
3233 error.SetErrorToGenericError();
3234 } else
3235 error.SetErrorToGenericError();
3236 } else {
3237 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3238 }
3239 }
3240 return error;
3241 } else { // response.IsUnsupportedResponse()
3242 m_supports_vFileMode = false;
3243 }
3244 }
3245
3246 // Fallback to fstat.
3247 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3248 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3249 return Status();
3250 }
3251 return Status("fstat failed");
3252}
3253
3255 uint64_t offset, void *dst,
3256 uint64_t dst_len,
3257 Status &error) {
3259 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3260 offset);
3261 StringExtractorGDBRemote response;
3262 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3264 if (response.GetChar() != 'F')
3265 return 0;
3266 int64_t retcode = response.GetS64(-1, 16);
3267 if (retcode == -1) {
3268 error.SetErrorToGenericError();
3269 if (response.GetChar() == ',') {
3270 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3271 if (response_errno > 0)
3272 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3273 }
3274 return -1;
3275 }
3276 const char next = (response.Peek() ? *response.Peek() : 0);
3277 if (next == ',')
3278 return 0;
3279 if (next == ';') {
3280 response.GetChar(); // skip the semicolon
3281 std::string buffer;
3282 if (response.GetEscapedBinaryData(buffer)) {
3283 const uint64_t data_to_write =
3284 std::min<uint64_t>(dst_len, buffer.size());
3285 if (data_to_write > 0)
3286 memcpy(dst, &buffer[0], data_to_write);
3287 return data_to_write;
3288 }
3289 }
3290 }
3291 return 0;
3292}
3293
3295 uint64_t offset,
3296 const void *src,
3297 uint64_t src_len,
3298 Status &error) {
3300 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3301 stream.PutEscapedBytes(src, src_len);
3302 StringExtractorGDBRemote response;
3303 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3305 if (response.GetChar() != 'F') {
3306 error.SetErrorStringWithFormat("write file failed");
3307 return 0;
3308 }
3309 int64_t bytes_written = response.GetS64(-1, 16);
3310 if (bytes_written == -1) {
3311 error.SetErrorToGenericError();
3312 if (response.GetChar() == ',') {
3313 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3314 if (response_errno > 0)
3315 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3316 }
3317 return -1;
3318 }
3319 return bytes_written;
3320 } else {
3321 error.SetErrorString("failed to send vFile:pwrite packet");
3322 }
3323 return 0;
3324}
3325
3327 const FileSpec &dst) {
3328 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3329 Status error;
3331 stream.PutCString("vFile:symlink:");
3332 // the unix symlink() command reverses its parameters where the dst if first,
3333 // so we follow suit here
3334 stream.PutStringAsRawHex8(dst_path);
3335 stream.PutChar(',');
3336 stream.PutStringAsRawHex8(src_path);
3337 StringExtractorGDBRemote response;
3338 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3340 if (response.GetChar() == 'F') {
3341 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3342 if (result != 0) {
3343 error.SetErrorToGenericError();
3344 if (response.GetChar() == ',') {
3345 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3346 if (response_errno > 0)
3347 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3348 }
3349 }
3350 } else {
3351 // Should have returned with 'F<result>[,<errno>]'
3352 error.SetErrorStringWithFormat("symlink failed");
3353 }
3354 } else {
3355 error.SetErrorString("failed to send vFile:symlink packet");
3356 }
3357 return error;
3358}
3359
3361 std::string path{file_spec.GetPath(false)};
3362 Status error;
3364 stream.PutCString("vFile:unlink:");
3365 // the unix symlink() command reverses its parameters where the dst if first,
3366 // so we follow suit here
3367 stream.PutStringAsRawHex8(path);
3368 StringExtractorGDBRemote response;
3369 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3371 if (response.GetChar() == 'F') {
3372 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3373 if (result != 0) {
3374 error.SetErrorToGenericError();
3375 if (response.GetChar() == ',') {
3376 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3377 if (response_errno > 0)
3378 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3379 }
3380 }
3381 } else {
3382 // Should have returned with 'F<result>[,<errno>]'
3383 error.SetErrorStringWithFormat("unlink failed");
3384 }
3385 } else {
3386 error.SetErrorString("failed to send vFile:unlink packet");
3387 }
3388 return error;
3389}
3390
3391// Extension of host I/O packets to get whether a file exists.
3393 const lldb_private::FileSpec &file_spec) {
3395 std::string path(file_spec.GetPath(false));
3397 stream.PutCString("vFile:exists:");
3398 stream.PutStringAsRawHex8(path);
3399 StringExtractorGDBRemote response;
3400 if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3402 return false;
3403 if (!response.IsUnsupportedResponse()) {
3404 if (response.GetChar() != 'F')
3405 return false;
3406 if (response.GetChar() != ',')
3407 return false;
3408 bool retcode = (response.GetChar() != '0');
3409 return retcode;
3410 } else
3411 m_supports_vFileExists = false;
3412 }
3413
3414 // Fallback to open.
3415 Status error;
3417 if (fd == UINT64_MAX)
3418 return false;
3419 CloseFile(fd, error);
3420 return true;
3421}
3422
3423llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5(
3424 const lldb_private::FileSpec &file_spec) {
3425 std::string path(file_spec.GetPath(false));
3427 stream.PutCString("vFile:MD5:");
3428 stream.PutStringAsRawHex8(path);
3429 StringExtractorGDBRemote response;
3430 if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3432 if (response.GetChar() != 'F')
3433 return std::make_error_code(std::errc::illegal_byte_sequence);
3434 if (response.GetChar() != ',')
3435 return std::make_error_code(std::errc::illegal_byte_sequence);
3436 if (response.Peek() && *response.Peek() == 'x')
3437 return std::make_error_code(std::errc::no_such_file_or_directory);
3438
3439 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and
3440 // high hex strings. We can't use response.GetHexMaxU64 because that can't
3441 // handle the concatenated hex string. What would happen is parsing the low
3442 // would consume the whole response packet which would give incorrect
3443 // results. Instead, we get the byte string for each low and high hex
3444 // separately, and parse them.
3445 //
3446 // An alternate way to handle this is to change the server to put a
3447 // delimiter between the low/high parts, and change the client to parse the
3448 // delimiter. However, we choose not to do this so existing lldb-servers
3449 // don't have to be patched
3450
3451 // The checksum is 128 bits encoded as hex
3452 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes.
3453 // Each byte takes 2 hex characters in the response.
3454 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2;
3455
3456 // Get low part
3457 auto part =
3458 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3459 if (part.size() != MD5_HALF_LENGTH)
3460 return std::make_error_code(std::errc::illegal_byte_sequence);
3461 response.SetFilePos(response.GetFilePos() + part.size());
3462
3463 uint64_t low;
3464 if (part.getAsInteger(/*radix=*/16, low))
3465 return std::make_error_code(std::errc::illegal_byte_sequence);
3466
3467 // Get high part
3468 part =
3469 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH);
3470 if (part.size() != MD5_HALF_LENGTH)
3471 return std::make_error_code(std::errc::illegal_byte_sequence);
3472 response.SetFilePos(response.GetFilePos() + part.size());
3473
3474 uint64_t high;
3475 if (part.getAsInteger(/*radix=*/16, high))
3476 return std::make_error_code(std::errc::illegal_byte_sequence);
3477
3478 llvm::MD5::MD5Result result;
3479 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3480 result.data(), low);
3481 llvm::support::endian::write<uint64_t, llvm::endianness::little>(
3482 result.data() + 8, high);
3483
3484 return result;
3485 }
3486 return std::make_error_code(std::errc::operation_canceled);
3487}
3488
3490 // Some targets have issues with g/G packets and we need to avoid using them
3492 if (process) {
3494 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3495 if (arch.IsValid() &&
3496 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3497 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3498 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3499 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3501 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3502 if (gdb_server_version != 0) {
3503 const char *gdb_server_name = GetGDBServerProgramName();
3504 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3505 if (gdb_server_version >= 310)
3507 }
3508 }
3509 }
3510 }
3511 }
3513}
3514
3516 uint32_t reg) {
3517 StreamString payload;
3518 payload.Printf("p%x", reg);
3519 StringExtractorGDBRemote response;
3521 tid, std::move(payload), response) != PacketResult::Success ||
3522 !response.IsNormalResponse())
3523 return nullptr;
3524
3525 WritableDataBufferSP buffer_sp(
3526 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3527 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3528 return buffer_sp;
3529}
3530
3532 StreamString payload;
3533 payload.PutChar('g');
3534 StringExtractorGDBRemote response;
3536 tid, std::move(payload), response) != PacketResult::Success ||
3537 !response.IsNormalResponse())
3538 return nullptr;
3539
3540 WritableDataBufferSP buffer_sp(
3541 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3542 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3543 return buffer_sp;
3544}
3545
3547 uint32_t reg_num,
3548 llvm::ArrayRef<uint8_t> data) {
3549 StreamString payload;
3550 payload.Printf("P%x=", reg_num);
3551 payload.PutBytesAsRawHex8(data.data(), data.size(),
3554 StringExtractorGDBRemote response;
3556 tid, std::move(payload), response) == PacketResult::Success &&
3557 response.IsOKResponse();
3558}
3559
3561 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3562 StreamString payload;
3563 payload.PutChar('G');
3564 payload.PutBytesAsRawHex8(data.data(), data.size(),
3567 StringExtractorGDBRemote response;
3569 tid, std::move(payload), response) == PacketResult::Success &&
3570 response.IsOKResponse();
3571}
3572
3574 uint32_t &save_id) {
3575 save_id = 0; // Set to invalid save ID
3577 return false;
3578
3580 StreamString payload;
3581 payload.PutCString("QSaveRegisterState");
3582 StringExtractorGDBRemote response;
3584 tid, std::move(payload), response) != PacketResult::Success)
3585 return false;
3586
3587 if (response.IsUnsupportedResponse())
3589
3590 const uint32_t response_save_id = response.GetU32(0);
3591 if (response_save_id == 0)
3592 return false;
3593
3594 save_id = response_save_id;
3595 return true;
3596}
3597
3599 uint32_t save_id) {
3600 // We use the "m_supports_QSaveRegisterState" variable here because the
3601 // QSaveRegisterState and QRestoreRegisterState packets must both be
3602 // supported in order to be useful
3604 return false;
3605
3606 StreamString payload;
3607 payload.Printf("QRestoreRegisterState:%u", save_id);
3608 StringExtractorGDBRemote response;
3610 tid, std::move(payload), response) != PacketResult::Success)
3611 return false;
3612
3613 if (response.IsOKResponse())
3614 return true;
3615
3616 if (response.IsUnsupportedResponse())
3618 return false;
3619}
3620
3623 return false;
3624
3625 StreamString packet;
3626 StringExtractorGDBRemote response;
3627 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3628 return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3630 response.IsOKResponse();
3631}
3632
3633llvm::Expected<TraceSupportedResponse>
3635 Log *log = GetLog(GDBRLog::Process);
3636
3637 StreamGDBRemote escaped_packet;
3638 escaped_packet.PutCString("jLLDBTraceSupported");
3639
3640 StringExtractorGDBRemote response;
3641 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3642 timeout) ==
3644 if (response.IsErrorResponse())
3645 return response.GetStatus().ToError();
3646 if (response.IsUnsupportedResponse())
3647 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3648 "jLLDBTraceSupported is unsupported");
3649
3650 return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3651 "TraceSupportedResponse");
3652 }
3653 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3654 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3655 "failed to send packet: jLLDBTraceSupported");
3656}
3657
3658llvm::Error
3660 std::chrono::seconds timeout) {
3661 Log *log = GetLog(GDBRLog::Process);
3662
3663 StreamGDBRemote escaped_packet;
3664 escaped_packet.PutCString("jLLDBTraceStop:");
3665
3666 std::string json_string;
3667 llvm::raw_string_ostream os(json_string);
3668 os << toJSON(request);
3669 os.flush();
3670
3671 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3672
3673 StringExtractorGDBRemote response;
3674 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3675 timeout) ==
3677 if (response.IsErrorResponse())
3678 return response.GetStatus().ToError();
3679 if (response.IsUnsupportedResponse())
3680 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3681 "jLLDBTraceStop is unsupported");
3682 if (response.IsOKResponse())
3683 return llvm::Error::success();
3684 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3685 "Invalid jLLDBTraceStart response");
3686 }
3687 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3688 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3689 "failed to send packet: jLLDBTraceStop '%s'",
3690 escaped_packet.GetData());
3691}
3692
3693llvm::Error
3694GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3695 std::chrono::seconds timeout) {
3696 Log *log = GetLog(GDBRLog::Process);
3697
3698 StreamGDBRemote escaped_packet;
3699 escaped_packet.PutCString("jLLDBTraceStart:");
3700
3701 std::string json_string;
3702 llvm::raw_string_ostream os(json_string);
3703 os << params;
3704 os.flush();
3705
3706 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3707
3708 StringExtractorGDBRemote response;
3709 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3710 timeout) ==
3712 if (response.IsErrorResponse())
3713 return response.GetStatus().ToError();
3714 if (response.IsUnsupportedResponse())
3715 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3716 "jLLDBTraceStart is unsupported");
3717 if (response.IsOKResponse())
3718 return llvm::Error::success();
3719 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3720 "Invalid jLLDBTraceStart response");
3721 }
3722 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3723 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3724 "failed to send packet: jLLDBTraceStart '%s'",
3725 escaped_packet.GetData());
3726}
3727
3728llvm::Expected<std::string>
3730 std::chrono::seconds timeout) {
3731 Log *log = GetLog(GDBRLog::Process);
3732
3733 StreamGDBRemote escaped_packet;
3734 escaped_packet.PutCString("jLLDBTraceGetState:");
3735
3736 std::string json_string;
3737 llvm::raw_string_ostream os(json_string);
3738 os << toJSON(TraceGetStateRequest{type.str()});
3739 os.flush();
3740
3741 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3742
3743 StringExtractorGDBRemote response;
3744 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3745 timeout) ==
3747 if (response.IsErrorResponse())
3748 return response.GetStatus().ToError();
3749 if (response.IsUnsupportedResponse())
3750 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3751 "jLLDBTraceGetState is unsupported");
3752 return std::string(response.Peek());
3753 }
3754
3755 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3756 return llvm::createStringError(
3757 llvm::inconvertibleErrorCode(),
3758 "failed to send packet: jLLDBTraceGetState '%s'",
3759 escaped_packet.GetData());
3760}
3761
3762llvm::Expected<std::vector<uint8_t>>
3764 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3765 Log *log = GetLog(GDBRLog::Process);
3766
3767 StreamGDBRemote escaped_packet;
3768 escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3769
3770 std::string json_string;
3771 llvm::raw_string_ostream os(json_string);
3772 os << toJSON(request);
3773 os.flush();
3774
3775 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3776
3777 StringExtractorGDBRemote response;
3778 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3779 timeout) ==
3781 if (response.IsErrorResponse())
3782 return response.GetStatus().ToError();
3783 std::string data;
3784 response.GetEscapedBinaryData(data);
3785 return std::vector<uint8_t>(data.begin(), data.end());
3786 }
3787 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3788 return llvm::createStringError(
3789 llvm::inconvertibleErrorCode(),
3790 "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3791 escaped_packet.GetData());
3792}
3793
3795 StringExtractorGDBRemote response;
3796 if (SendPacketAndWaitForResponse("qOffsets", response) !=
3798 return std::nullopt;
3799 if (!response.IsNormalResponse())
3800 return std::nullopt;
3801
3802 QOffsets result;
3803 llvm::StringRef ref = response.GetStringRef();
3804 const auto &GetOffset = [&] {
3805 addr_t offset;
3806 if (ref.consumeInteger(16, offset))
3807 return false;
3808 result.offsets.push_back(offset);
3809 return true;
3810 };
3811
3812 if (ref.consume_front("Text=")) {
3813 result.segments = false;
3814 if (!GetOffset())
3815 return std::nullopt;
3816 if (!ref.consume_front(";Data=") || !GetOffset())
3817 return std::nullopt;
3818 if (ref.empty())
3819 return result;
3820 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3821 return result;
3822 } else if (ref.consume_front("TextSeg=")) {
3823 result.segments = true;
3824 if (!GetOffset())
3825 return std::nullopt;
3826 if (ref.empty())
3827 return result;
3828 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3829 return result;
3830 }
3831 return std::nullopt;
3832}
3833
3835 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3836 ModuleSpec &module_spec) {
3838 return false;
3839
3840 std::string module_path = module_file_spec.GetPath(false);
3841 if (module_path.empty())
3842 return false;
3843
3844 StreamString packet;
3845 packet.PutCString("qModuleInfo:");
3846 packet.PutStringAsRawHex8(module_path);
3847 packet.PutCString(";");
3848 const auto &triple = arch_spec.GetTriple().getTriple();
3849 packet.PutStringAsRawHex8(triple);
3850
3851 StringExtractorGDBRemote response;
3852 if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
3854 return false;
3855
3856 if (response.IsErrorResponse())
3857 return false;
3858
3859 if (response.IsUnsupportedResponse()) {
3860 m_supports_qModuleInfo = false;
3861 return false;
3862 }
3863
3864 llvm::StringRef name;
3865 llvm::StringRef value;
3866
3867 module_spec.Clear();
3868 module_spec.GetFileSpec() = module_file_spec;
3869
3870 while (response.GetNameColonValue(name, value)) {
3871 if (name == "uuid" || name == "md5") {
3872 StringExtractor extractor(value);
3873 std::string uuid;
3874 extractor.GetHexByteString(uuid);
3875 module_spec.GetUUID().SetFromStringRef(uuid);
3876 } else if (name == "triple") {
3877 StringExtractor extractor(value);
3878 std::string triple;
3879 extractor.GetHexByteString(triple);
3880 module_spec.GetArchitecture().SetTriple(triple.c_str());
3881 } else if (name == "file_offset") {
3882 uint64_t ival = 0;
3883 if (!value.getAsInteger(16, ival))
3884 module_spec.SetObjectOffset(ival);
3885 } else if (name == "file_size") {
3886 uint64_t ival = 0;
3887 if (!value.getAsInteger(16, ival))
3888 module_spec.SetObjectSize(ival);
3889 } else if (name == "file_path") {
3890 StringExtractor extractor(value);
3891 std::string path;
3892 extractor.GetHexByteString(path);
3893 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3894 }
3895 }
3896
3897 return true;
3898}
3899
3900static std::optional<ModuleSpec>
3902 ModuleSpec result;
3903 if (!dict)
3904 return std::nullopt;
3905
3906 llvm::StringRef string;
3907 uint64_t integer;
3908
3909 if (!dict->GetValueForKeyAsString("uuid", string))
3910 return std::nullopt;
3911 if (!result.GetUUID().SetFromStringRef(string))
3912 return std::nullopt;
3913
3914 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3915 return std::nullopt;
3916 result.SetObjectOffset(integer);
3917
3918 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3919 return std::nullopt;
3920 result.SetObjectSize(integer);
3921
3922 if (!dict->GetValueForKeyAsString("triple", string))
3923 return std::nullopt;
3924 result.GetArchitecture().SetTriple(string);
3925
3926 if (!dict->GetValueForKeyAsString("file_path", string))
3927 return std::nullopt;
3928 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3929
3930 return result;
3931}
3932
3933std::optional<std::vector<ModuleSpec>>
3935 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3936 namespace json = llvm::json;
3937
3939 return std::nullopt;
3940
3941 json::Array module_array;
3942 for (const FileSpec &module_file_spec : module_file_specs) {
3943 module_array.push_back(
3944 json::Object{{"file", module_file_spec.GetPath(false)},
3945 {"triple", triple.getTriple()}});
3946 }
3947 StreamString unescaped_payload;
3948 unescaped_payload.PutCString("jModulesInfo:");
3949 unescaped_payload.AsRawOstream() << std::move(module_array);
3950
3951 StreamGDBRemote payload;
3952 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3953 unescaped_payload.GetSize());
3954
3955 // Increase the timeout for jModulesInfo since this packet can take longer.
3956 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3957
3958 StringExtractorGDBRemote response;
3959 if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
3961 response.IsErrorResponse())
3962 return std::nullopt;
3963
3964 if (response.IsUnsupportedResponse()) {
3966 return std::nullopt;
3967 }
3968
3969 StructuredData::ObjectSP response_object_sp =
3971 if (!response_object_sp)
3972 return std::nullopt;
3973
3974 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3975 if (!response_array)
3976 return std::nullopt;
3977
3978 std::vector<ModuleSpec> result;
3979 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3980 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec(
3981 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3982 result.push_back(*module_spec);
3983 }
3984
3985 return result;
3986}
3987
3988// query the target remote for extended information using the qXfer packet
3989//
3990// example: object='features', annex='target.xml'
3991// return: <xml output> or error
3992llvm::Expected<std::string>
3994 llvm::StringRef annex) {
3995
3996 std::string output;
3997 llvm::raw_string_ostream output_stream(output);
3999
4000 uint64_t size = GetRemoteMaxPacketSize();
4001 if (size == 0)
4002 size = 0x1000;
4003 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4004 int offset = 0;
4005 bool active = true;
4006
4007 // loop until all data has been read
4008 while (active) {
4009
4010 // send query extended feature packet
4011 std::string packet =
4012 ("qXfer:" + object + ":read:" + annex + ":" +
4013 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
4014 .str();
4015
4017 SendPacketAndWaitForResponse(packet, chunk);
4018
4020 chunk.GetStringRef().empty()) {
4021 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4022 "Error sending $qXfer packet");
4023 }
4024
4025 // check packet code
4026 switch (chunk.GetStringRef()[0]) {
4027 // last chunk
4028 case ('l'):
4029 active = false;
4030 [[fallthrough]];
4031
4032 // more chunks
4033 case ('m'):
4034 output_stream << chunk.GetStringRef().drop_front();
4035 offset += chunk.GetStringRef().size() - 1;
4036 break;
4037
4038 // unknown chunk
4039 default:
4040 return llvm::createStringError(
4041 llvm::inconvertibleErrorCode(),
4042 "Invalid continuation code from $qXfer packet");
4043 }
4044 }
4045
4046 return output_stream.str();
4047}
4048
4049// Notify the target that gdb is prepared to serve symbol lookup requests.
4050// packet: "qSymbol::"
4051// reply:
4052// OK The target does not need to look up any (more) symbols.
4053// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
4054// encoded).
4055// LLDB may provide the value by sending another qSymbol
4056// packet
4057// in the form of"qSymbol:<sym_value>:<sym_name>".
4058//
4059// Three examples:
4060//
4061// lldb sends: qSymbol::
4062// lldb receives: OK
4063// Remote gdb stub does not need to know the addresses of any symbols, lldb
4064// does not
4065// need to ask again in this session.
4066//
4067// lldb sends: qSymbol::
4068// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4069// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4070// lldb receives: OK
4071// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
4072// not know
4073// the address at this time. lldb needs to send qSymbol:: again when it has
4074// more
4075// solibs loaded.
4076//
4077// lldb sends: qSymbol::
4078// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4079// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4080// lldb receives: OK
4081// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
4082// that it
4083// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
4084// does not
4085// need any more symbols. lldb does not need to ask again in this session.
4086
4088 lldb_private::Process *process) {
4089 // Set to true once we've resolved a symbol to an address for the remote
4090 // stub. If we get an 'OK' response after this, the remote stub doesn't need
4091 // any more symbols and we can stop asking.
4092 bool symbol_response_provided = false;
4093
4094 // Is this the initial qSymbol:: packet?
4095 bool first_qsymbol_query = true;
4096
4098 Lock lock(*this);
4099 if (lock) {
4100 StreamString packet;
4101 packet.PutCString("qSymbol::");
4102 StringExtractorGDBRemote response;
4103 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4105 if (response.IsOKResponse()) {
4106 if (symbol_response_provided || first_qsymbol_query) {
4108 }
4109
4110 // We are done serving symbols requests
4111 return;
4112 }
4113 first_qsymbol_query = false;
4114
4115 if (response.IsUnsupportedResponse()) {
4116 // qSymbol is not supported by the current GDB server we are
4117 // connected to
4118 m_supports_qSymbol = false;
4119 return;
4120 } else {
4121 llvm::StringRef response_str(response.GetStringRef());
4122 if (response_str.starts_with("qSymbol:")) {
4123 response.SetFilePos(strlen("qSymbol:"));
4124 std::string symbol_name;
4125 if (response.GetHexByteString(symbol_name)) {
4126 if (symbol_name.empty())
4127 return;
4128
4129 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4132 ConstString(symbol_name), eSymbolTypeAny, sc_list);
4133 for (const SymbolContext &sc : sc_list) {
4134 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4135 break;
4136 if (sc.symbol) {
4137 switch (sc.symbol->GetType()) {
4138 case eSymbolTypeInvalid:
4145 case eSymbolTypeBlock:
4146 case eSymbolTypeLocal:
4147 case eSymbolTypeParam:
4158 break;
4159
4160 case eSymbolTypeCode:
4162 case eSymbolTypeData:
4163 case eSymbolTypeRuntime:
4169 symbol_load_addr =
4170 sc.symbol->GetLoadAddress(&process->GetTarget());
4171 break;
4172 }
4173 }
4174 }
4175 // This is the normal path where our symbol lookup was successful
4176 // and we want to send a packet with the new symbol value and see
4177 // if another lookup needs to be done.
4178
4179 // Change "packet" to contain the requested symbol value and name
4180 packet.Clear();
4181 packet.PutCString("qSymbol:");
4182 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4183 packet.Printf("%" PRIx64, symbol_load_addr);
4184 symbol_response_provided = true;
4185 } else {
4186 symbol_response_provided = false;
4187 }
4188 packet.PutCString(":");
4189 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4190 continue; // go back to the while loop and send "packet" and wait
4191 // for another response
4192 }
4193 }
4194 }
4195 }
4196 // If we make it here, the symbol request packet response wasn't valid or
4197 // our symbol lookup failed so we must abort
4198 return;
4199
4200 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4201 LLDB_LOGF(log,
4202 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4203 __FUNCTION__);
4204 }
4205 }
4206}
4207
4211 // Query the server for the array of supported asynchronous JSON packets.
4213
4214 Log *log = GetLog(GDBRLog::Process);
4215
4216 // Poll it now.
4217 StringExtractorGDBRemote response;
4218 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4223 !m_supported_async_json_packets_sp->GetAsArray()) {
4224 // We were returned something other than a JSON array. This is
4225 // invalid. Clear it out.
4226 LLDB_LOGF(log,
4227 "GDBRemoteCommunicationClient::%s(): "
4228 "QSupportedAsyncJSONPackets returned invalid "
4229 "result: %s",
4230 __FUNCTION__, response.GetStringRef().data());
4232 }
4233 } else {
4234 LLDB_LOGF(log,
4235 "GDBRemoteCommunicationClient::%s(): "
4236 "QSupportedAsyncJSONPackets unsupported",
4237 __FUNCTION__);
4238 }
4239
4241 StreamString stream;
4243 LLDB_LOGF(log,
4244 "GDBRemoteCommunicationClient::%s(): supported async "
4245 "JSON packets: %s",
4246 __FUNCTION__, stream.GetData());
4247 }
4248 }
4249
4251 ? m_supported_async_json_packets_sp->GetAsArray()
4252 : nullptr;
4253}
4254
4256 llvm::ArrayRef<int32_t> signals) {
4257 // Format packet:
4258 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4259 auto range = llvm::make_range(signals.begin(), signals.end());
4260 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4261
4262 StringExtractorGDBRemote response;
4263 auto send_status = SendPacketAndWaitForResponse(packet, response);
4264
4266 return Status("Sending QPassSignals packet failed");
4267
4268 if (response.IsOKResponse()) {
4269 return Status();
4270 } else {
4271 return Status("Unknown error happened during sending QPassSignals packet.");
4272 }
4273}
4274
4276 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4277 Status error;
4278
4279 if (type_name.empty()) {
4280 error.SetErrorString("invalid type_name argument");
4281 return error;
4282 }
4283
4284 // Build command: Configure{type_name}: serialized config data.
4285 StreamGDBRemote stream;
4286 stream.PutCString("QConfigure");
4287 stream.PutCString(type_name);
4288 stream.PutChar(':');
4289 if (config_sp) {
4290 // Gather the plain-text version of the configuration data.
4291 StreamString unescaped_stream;
4292 config_sp->Dump(unescaped_stream);
4293 unescaped_stream.Flush();
4294
4295 // Add it to the stream in escaped fashion.
4296 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4297 unescaped_stream.GetSize());
4298 }
4299 stream.Flush();
4300
4301 // Send the packet.
4302 StringExtractorGDBRemote response;
4303 auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4304 if (result == PacketResult::Success) {
4305 // We failed if the config result comes back other than OK.
4306 if (response.GetStringRef() == "OK") {
4307 // Okay!
4308 error.Clear();
4309 } else {
4310 error.SetErrorStringWithFormatv(
4311 "configuring StructuredData feature {0} failed with error {1}",
4312 type_name, response.GetStringRef());
4313 }
4314 } else {
4315 // Can we get more data here on the failure?
4316 error.SetErrorStringWithFormatv(
4317 "configuring StructuredData feature {0} failed when sending packet: "
4318 "PacketResult={1}",
4319 type_name, (int)result);
4320 }
4321 return error;
4322}
4323
4327}
4328
4333 return true;
4334
4335 // If the remote didn't indicate native-signal support explicitly,
4336 // check whether it is an old version of lldb-server.
4337 return GetThreadSuffixSupported();
4338}
4339
4341 StringExtractorGDBRemote response;
4342 GDBRemoteCommunication::ScopedTimeout(*this, seconds(3));
4343
4344 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout()) !=
4346 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4347 "failed to send k packet");
4348
4349 char packet_cmd = response.GetChar(0);
4350 if (packet_cmd == 'W' || packet_cmd == 'X')
4351 return response.GetHexU8();
4352
4353 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4354 "unexpected response to k packet: %s",
4355 response.GetStringRef().str().c_str());
4356}
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:359
#define LLDB_LOGF(log,...)
Definition: Log.h:366
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)
ResponseType GetResponseType() const
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)
size_t GetBytesLeft()
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:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:348
void Clear()
Clears the object state.
Definition: ArchSpec.cpp:542
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
void SetFlags(uint32_t flags)
Definition: ArchSpec.h:523
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition: ArchSpec.cpp:747
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:851
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:738
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition: ArchSpec.cpp:683
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:552
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:322
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition: Args.cpp:263
void Clear()
Clear the arguments.
Definition: Args.cpp:378
bool IsConnected() const
Check if the connection is valid.
virtual lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
llvm::StringRef GetCursorArgumentPrefix() const
A uniqued constant string class.
Definition: ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
A file utility class.
Definition: FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
@ eOpenOptionReadOnly
Definition: File.h:51
void SetFlash(OptionalBool val)
void SetMapped(OptionalBool val)
void SetBlocksize(lldb::offset_t blocksize)
void SetMemoryTagged(OptionalBool val)
void SetReadable(OptionalBool val)
void SetExecutable(OptionalBool val)
void SetIsStackMemory(OptionalBool val)
void SetName(const char *name)
void SetWritable(OptionalBool val)
lldb::offset_t GetBlocksize() const
void SetDirtyPageList(std::vector< lldb::addr_t > pagelist)
OptionalBool GetFlash() const
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
Definition: ModuleList.cpp:527
void SetObjectSize(uint64_t object_size)
Definition: ModuleSpec.h:115
FileSpec & GetFileSpec()
Definition: ModuleSpec.h:53
ArchSpec & GetArchitecture()
Definition: ModuleSpec.h:89
void SetObjectOffset(uint64_t object_offset)
Definition: ModuleSpec.h:109
void SetGroupID(uint32_t gid)
Definition: ProcessInfo.h:60
bool ProcessIDIsValid() const
Definition: ProcessInfo.h:72
void SetArg0(llvm::StringRef arg)
Definition: ProcessInfo.cpp:82
const char * GetName() const
Definition: ProcessInfo.cpp:45
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:68
void SetProcessID(lldb::pid_t pid)
Definition: ProcessInfo.h:70
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:43
bool UserIDIsValid() const
Definition: ProcessInfo.h:54
uint32_t GetUserID() const
Definition: ProcessInfo.h:50
uint32_t GetGroupID() const
Definition: ProcessInfo.h:52
void SetUserID(uint32_t uid)
Definition: ProcessInfo.h:58
bool GroupIDIsValid() const
Definition: ProcessInfo.h:56
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:62
ProcessInstanceInfo & GetProcessInfo()
Definition: ProcessInfo.h:308
uint32_t GetEffectiveUserID() const
Definition: ProcessInfo.h:160
void SetEffectiveGroupID(uint32_t gid)
Definition: ProcessInfo.h:170
lldb::pid_t GetParentProcessID() const
Definition: ProcessInfo.h:172
uint32_t GetEffectiveGroupID() const
Definition: ProcessInfo.h:162
void SetParentProcessID(lldb::pid_t pid)
Definition: ProcessInfo.h:174
void SetEffectiveUserID(uint32_t uid)
Definition: ProcessInfo.h:168
A plug-in interface definition class for debugging a process.
Definition: Process.h:341
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1285
An error handling class.
Definition: Status.h:44
llvm::Error ToError() const
Definition: Status.cpp:89
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:246
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:232
bool Success() const
Test for success condition.
Definition: Status.cpp:278
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition: GDBRemote.cpp:28
const char * GetData() const
Definition: StreamString.h:45
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
void Format(const char *format, Args &&... args)
Definition: Stream.h:353
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition: Stream.h:401
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition: Stream.cpp:410
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:299
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:65
size_t PutChar(char ch)
Definition: Stream.cpp:131
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:283
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:383
ObjectSP GetItemAtIndex(size_t idx) const