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