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