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