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