xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp (revision bdb4468d39496088fc05d8c5575647fac9c8062a)
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           addr_t addr;
2210           while (!value.empty()) {
2211             llvm::StringRef addr_str;
2212             std::tie(addr_str, value) = value.split(',');
2213             if (!addr_str.getAsInteger(16, addr))
2214               m_binary_addresses.push_back(addr);
2215           }
2216         }
2217       }
2218       if (num_keys_decoded > 0)
2219         m_qProcessInfo_is_valid = eLazyBoolYes;
2220       if (pid != LLDB_INVALID_PROCESS_ID) {
2221         m_curr_pid_is_valid = eLazyBoolYes;
2222         m_curr_pid_run = m_curr_pid = pid;
2223       }
2224 
2225       // Set the ArchSpec from the triple if we have it.
2226       if (!triple.empty()) {
2227         m_process_arch.SetTriple(triple.c_str());
2228         m_process_arch.SetFlags(elf_abi);
2229         if (pointer_byte_size) {
2230           assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2231         }
2232       } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2233                  !vendor_name.empty()) {
2234         llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2235         if (!environment.empty())
2236             triple.setEnvironmentName(environment);
2237 
2238         assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2239         assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2240         assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
2241         switch (triple.getObjectFormat()) {
2242         case llvm::Triple::MachO:
2243           m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2244           break;
2245         case llvm::Triple::ELF:
2246           m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2247           break;
2248         case llvm::Triple::COFF:
2249           m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2250           break;
2251         case llvm::Triple::GOFF:
2252         case llvm::Triple::SPIRV:
2253         case llvm::Triple::Wasm:
2254         case llvm::Triple::XCOFF:
2255         case llvm::Triple::DXContainer:
2256           LLDB_LOGF(log, "error: not supported target architecture");
2257           return false;
2258         case llvm::Triple::UnknownObjectFormat:
2259           LLDB_LOGF(log, "error: failed to determine target architecture");
2260           return false;
2261         }
2262 
2263         if (pointer_byte_size) {
2264           assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2265         }
2266         if (byte_order != eByteOrderInvalid) {
2267           assert(byte_order == m_process_arch.GetByteOrder());
2268         }
2269         m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2270         m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2271         m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
2272       }
2273       return true;
2274     }
2275   } else {
2276     m_qProcessInfo_is_valid = eLazyBoolNo;
2277   }
2278 
2279   return false;
2280 }
2281 
2282 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2283     const ProcessInstanceInfoMatch &match_info,
2284     ProcessInstanceInfoList &process_infos) {
2285   process_infos.clear();
2286 
2287   if (m_supports_qfProcessInfo) {
2288     StreamString packet;
2289     packet.PutCString("qfProcessInfo");
2290     if (!match_info.MatchAllProcesses()) {
2291       packet.PutChar(':');
2292       const char *name = match_info.GetProcessInfo().GetName();
2293       bool has_name_match = false;
2294       if (name && name[0]) {
2295         has_name_match = true;
2296         NameMatch name_match_type = match_info.GetNameMatchType();
2297         switch (name_match_type) {
2298         case NameMatch::Ignore:
2299           has_name_match = false;
2300           break;
2301 
2302         case NameMatch::Equals:
2303           packet.PutCString("name_match:equals;");
2304           break;
2305 
2306         case NameMatch::Contains:
2307           packet.PutCString("name_match:contains;");
2308           break;
2309 
2310         case NameMatch::StartsWith:
2311           packet.PutCString("name_match:starts_with;");
2312           break;
2313 
2314         case NameMatch::EndsWith:
2315           packet.PutCString("name_match:ends_with;");
2316           break;
2317 
2318         case NameMatch::RegularExpression:
2319           packet.PutCString("name_match:regex;");
2320           break;
2321         }
2322         if (has_name_match) {
2323           packet.PutCString("name:");
2324           packet.PutBytesAsRawHex8(name, ::strlen(name));
2325           packet.PutChar(';');
2326         }
2327       }
2328 
2329       if (match_info.GetProcessInfo().ProcessIDIsValid())
2330         packet.Printf("pid:%" PRIu64 ";",
2331                       match_info.GetProcessInfo().GetProcessID());
2332       if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2333         packet.Printf("parent_pid:%" PRIu64 ";",
2334                       match_info.GetProcessInfo().GetParentProcessID());
2335       if (match_info.GetProcessInfo().UserIDIsValid())
2336         packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2337       if (match_info.GetProcessInfo().GroupIDIsValid())
2338         packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2339       if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2340         packet.Printf("euid:%u;",
2341                       match_info.GetProcessInfo().GetEffectiveUserID());
2342       if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2343         packet.Printf("egid:%u;",
2344                       match_info.GetProcessInfo().GetEffectiveGroupID());
2345       packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2346       if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2347         const ArchSpec &match_arch =
2348             match_info.GetProcessInfo().GetArchitecture();
2349         const llvm::Triple &triple = match_arch.GetTriple();
2350         packet.PutCString("triple:");
2351         packet.PutCString(triple.getTriple());
2352         packet.PutChar(';');
2353       }
2354     }
2355     StringExtractorGDBRemote response;
2356     // Increase timeout as the first qfProcessInfo packet takes a long time on
2357     // Android. The value of 1min was arrived at empirically.
2358     ScopedTimeout timeout(*this, minutes(1));
2359     if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2360         PacketResult::Success) {
2361       do {
2362         ProcessInstanceInfo process_info;
2363         if (!DecodeProcessInfoResponse(response, process_info))
2364           break;
2365         process_infos.push_back(process_info);
2366         response = StringExtractorGDBRemote();
2367       } while (SendPacketAndWaitForResponse("qsProcessInfo", response) ==
2368                PacketResult::Success);
2369     } else {
2370       m_supports_qfProcessInfo = false;
2371       return 0;
2372     }
2373   }
2374   return process_infos.size();
2375 }
2376 
2377 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2378                                                std::string &name) {
2379   if (m_supports_qUserName) {
2380     char packet[32];
2381     const int packet_len =
2382         ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2383     assert(packet_len < (int)sizeof(packet));
2384     UNUSED_IF_ASSERT_DISABLED(packet_len);
2385     StringExtractorGDBRemote response;
2386     if (SendPacketAndWaitForResponse(packet, response) ==
2387         PacketResult::Success) {
2388       if (response.IsNormalResponse()) {
2389         // Make sure we parsed the right number of characters. The response is
2390         // the hex encoded user name and should make up the entire packet. If
2391         // there are any non-hex ASCII bytes, the length won't match below..
2392         if (response.GetHexByteString(name) * 2 ==
2393             response.GetStringRef().size())
2394           return true;
2395       }
2396     } else {
2397       m_supports_qUserName = false;
2398       return false;
2399     }
2400   }
2401   return false;
2402 }
2403 
2404 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2405                                                 std::string &name) {
2406   if (m_supports_qGroupName) {
2407     char packet[32];
2408     const int packet_len =
2409         ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2410     assert(packet_len < (int)sizeof(packet));
2411     UNUSED_IF_ASSERT_DISABLED(packet_len);
2412     StringExtractorGDBRemote response;
2413     if (SendPacketAndWaitForResponse(packet, response) ==
2414         PacketResult::Success) {
2415       if (response.IsNormalResponse()) {
2416         // Make sure we parsed the right number of characters. The response is
2417         // the hex encoded group name and should make up the entire packet. If
2418         // there are any non-hex ASCII bytes, the length won't match below..
2419         if (response.GetHexByteString(name) * 2 ==
2420             response.GetStringRef().size())
2421           return true;
2422       }
2423     } else {
2424       m_supports_qGroupName = false;
2425       return false;
2426     }
2427   }
2428   return false;
2429 }
2430 
2431 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2432                                 uint32_t recv_size) {
2433   packet.Clear();
2434   packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2435   uint32_t bytes_left = send_size;
2436   while (bytes_left > 0) {
2437     if (bytes_left >= 26) {
2438       packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2439       bytes_left -= 26;
2440     } else {
2441       packet.Printf("%*.*s;", bytes_left, bytes_left,
2442                     "abcdefghijklmnopqrstuvwxyz");
2443       bytes_left = 0;
2444     }
2445   }
2446 }
2447 
2448 duration<float>
2449 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2450   if (v.size() == 0)
2451     return duration<float>::zero();
2452   using Dur = duration<float>;
2453   Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2454   Dur mean = sum / v.size();
2455   float accum = 0;
2456   for (auto d : v) {
2457     float delta = (d - mean).count();
2458     accum += delta * delta;
2459   };
2460 
2461   return Dur(sqrtf(accum / (v.size() - 1)));
2462 }
2463 
2464 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2465                                                    uint32_t max_send,
2466                                                    uint32_t max_recv,
2467                                                    uint64_t recv_amount,
2468                                                    bool json, Stream &strm) {
2469 
2470   if (SendSpeedTestPacket(0, 0)) {
2471     StreamString packet;
2472     if (json)
2473       strm.Printf("{ \"packet_speeds\" : {\n    \"num_packets\" : %u,\n    "
2474                   "\"results\" : [",
2475                   num_packets);
2476     else
2477       strm.Printf("Testing sending %u packets of various sizes:\n",
2478                   num_packets);
2479     strm.Flush();
2480 
2481     uint32_t result_idx = 0;
2482     uint32_t send_size;
2483     std::vector<duration<float>> packet_times;
2484 
2485     for (send_size = 0; send_size <= max_send;
2486          send_size ? send_size *= 2 : send_size = 4) {
2487       for (uint32_t recv_size = 0; recv_size <= max_recv;
2488            recv_size ? recv_size *= 2 : recv_size = 4) {
2489         MakeSpeedTestPacket(packet, send_size, recv_size);
2490 
2491         packet_times.clear();
2492         // Test how long it takes to send 'num_packets' packets
2493         const auto start_time = steady_clock::now();
2494         for (uint32_t i = 0; i < num_packets; ++i) {
2495           const auto packet_start_time = steady_clock::now();
2496           StringExtractorGDBRemote response;
2497           SendPacketAndWaitForResponse(packet.GetString(), response);
2498           const auto packet_end_time = steady_clock::now();
2499           packet_times.push_back(packet_end_time - packet_start_time);
2500         }
2501         const auto end_time = steady_clock::now();
2502         const auto total_time = end_time - start_time;
2503 
2504         float packets_per_second =
2505             ((float)num_packets) / duration<float>(total_time).count();
2506         auto average_per_packet = num_packets > 0 ? total_time / num_packets
2507                                                   : duration<float>::zero();
2508         const duration<float> standard_deviation =
2509             calculate_standard_deviation(packet_times);
2510         if (json) {
2511           strm.Format("{0}\n     {{\"send_size\" : {1,6}, \"recv_size\" : "
2512                       "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2513                       "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2514                       result_idx > 0 ? "," : "", send_size, recv_size,
2515                       total_time, standard_deviation);
2516           ++result_idx;
2517         } else {
2518           strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2519                       "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2520                       "standard deviation of {5,10:ms+f6}\n",
2521                       send_size, recv_size, duration<float>(total_time),
2522                       packets_per_second, duration<float>(average_per_packet),
2523                       standard_deviation);
2524         }
2525         strm.Flush();
2526       }
2527     }
2528 
2529     const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2530     if (json)
2531       strm.Printf("\n    ]\n  },\n  \"download_speed\" : {\n    \"byte_size\" "
2532                   ": %" PRIu64 ",\n    \"results\" : [",
2533                   recv_amount);
2534     else
2535       strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2536                   "packet sizes:\n",
2537                   k_recv_amount_mb);
2538     strm.Flush();
2539     send_size = 0;
2540     result_idx = 0;
2541     for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2542       MakeSpeedTestPacket(packet, send_size, recv_size);
2543 
2544       // If we have a receive size, test how long it takes to receive 4MB of
2545       // data
2546       if (recv_size > 0) {
2547         const auto start_time = steady_clock::now();
2548         uint32_t bytes_read = 0;
2549         uint32_t packet_count = 0;
2550         while (bytes_read < recv_amount) {
2551           StringExtractorGDBRemote response;
2552           SendPacketAndWaitForResponse(packet.GetString(), response);
2553           bytes_read += recv_size;
2554           ++packet_count;
2555         }
2556         const auto end_time = steady_clock::now();
2557         const auto total_time = end_time - start_time;
2558         float mb_second = ((float)recv_amount) /
2559                           duration<float>(total_time).count() /
2560                           (1024.0 * 1024.0);
2561         float packets_per_second =
2562             ((float)packet_count) / duration<float>(total_time).count();
2563         const auto average_per_packet = packet_count > 0
2564                                             ? total_time / packet_count
2565                                             : duration<float>::zero();
2566 
2567         if (json) {
2568           strm.Format("{0}\n     {{\"send_size\" : {1,6}, \"recv_size\" : "
2569                       "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2570                       result_idx > 0 ? "," : "", send_size, recv_size,
2571                       total_time);
2572           ++result_idx;
2573         } else {
2574           strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2575                       "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2576                       "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2577                       send_size, recv_size, packet_count, k_recv_amount_mb,
2578                       duration<float>(total_time), mb_second,
2579                       packets_per_second, duration<float>(average_per_packet));
2580         }
2581         strm.Flush();
2582       }
2583     }
2584     if (json)
2585       strm.Printf("\n    ]\n  }\n}\n");
2586     else
2587       strm.EOL();
2588   }
2589 }
2590 
2591 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2592                                                        uint32_t recv_size) {
2593   StreamString packet;
2594   packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2595   uint32_t bytes_left = send_size;
2596   while (bytes_left > 0) {
2597     if (bytes_left >= 26) {
2598       packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2599       bytes_left -= 26;
2600     } else {
2601       packet.Printf("%*.*s;", bytes_left, bytes_left,
2602                     "abcdefghijklmnopqrstuvwxyz");
2603       bytes_left = 0;
2604     }
2605   }
2606 
2607   StringExtractorGDBRemote response;
2608   return SendPacketAndWaitForResponse(packet.GetString(), response) ==
2609          PacketResult::Success;
2610 }
2611 
2612 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2613     const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2614     std::string &socket_name) {
2615   pid = LLDB_INVALID_PROCESS_ID;
2616   port = 0;
2617   socket_name.clear();
2618 
2619   StringExtractorGDBRemote response;
2620   StreamString stream;
2621   stream.PutCString("qLaunchGDBServer;");
2622   std::string hostname;
2623   if (remote_accept_hostname && remote_accept_hostname[0])
2624     hostname = remote_accept_hostname;
2625   else {
2626     if (HostInfo::GetHostname(hostname)) {
2627       // Make the GDB server we launch only accept connections from this host
2628       stream.Printf("host:%s;", hostname.c_str());
2629     } else {
2630       // Make the GDB server we launch accept connections from any host since
2631       // we can't figure out the hostname
2632       stream.Printf("host:*;");
2633     }
2634   }
2635   // give the process a few seconds to startup
2636   ScopedTimeout timeout(*this, seconds(10));
2637 
2638   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2639       PacketResult::Success) {
2640     llvm::StringRef name;
2641     llvm::StringRef value;
2642     while (response.GetNameColonValue(name, value)) {
2643       if (name.equals("port"))
2644         value.getAsInteger(0, port);
2645       else if (name.equals("pid"))
2646         value.getAsInteger(0, pid);
2647       else if (name.compare("socket_name") == 0) {
2648         StringExtractor extractor(value);
2649         extractor.GetHexByteString(socket_name);
2650       }
2651     }
2652     return true;
2653   }
2654   return false;
2655 }
2656 
2657 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2658     std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2659   connection_urls.clear();
2660 
2661   StringExtractorGDBRemote response;
2662   if (SendPacketAndWaitForResponse("qQueryGDBServer", response) !=
2663       PacketResult::Success)
2664     return 0;
2665 
2666   StructuredData::ObjectSP data =
2667       StructuredData::ParseJSON(std::string(response.GetStringRef()));
2668   if (!data)
2669     return 0;
2670 
2671   StructuredData::Array *array = data->GetAsArray();
2672   if (!array)
2673     return 0;
2674 
2675   for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2676     StructuredData::Dictionary *element = nullptr;
2677     if (!array->GetItemAtIndexAsDictionary(i, element))
2678       continue;
2679 
2680     uint16_t port = 0;
2681     if (StructuredData::ObjectSP port_osp =
2682             element->GetValueForKey(llvm::StringRef("port")))
2683       port = port_osp->GetIntegerValue(0);
2684 
2685     std::string socket_name;
2686     if (StructuredData::ObjectSP socket_name_osp =
2687             element->GetValueForKey(llvm::StringRef("socket_name")))
2688       socket_name = std::string(socket_name_osp->GetStringValue());
2689 
2690     if (port != 0 || !socket_name.empty())
2691       connection_urls.emplace_back(port, socket_name);
2692   }
2693   return connection_urls.size();
2694 }
2695 
2696 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2697   StreamString stream;
2698   stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2699 
2700   StringExtractorGDBRemote response;
2701   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2702       PacketResult::Success) {
2703     if (response.IsOKResponse())
2704       return true;
2705   }
2706   return false;
2707 }
2708 
2709 llvm::Optional<PidTid>
2710 GDBRemoteCommunicationClient::SendSetCurrentThreadPacket(uint64_t tid,
2711                                                          uint64_t pid,
2712                                                          char op) {
2713   lldb_private::StreamString packet;
2714   packet.PutChar('H');
2715   packet.PutChar(op);
2716 
2717   if (pid != LLDB_INVALID_PROCESS_ID)
2718     packet.Printf("p%" PRIx64 ".", pid);
2719 
2720   if (tid == UINT64_MAX)
2721     packet.PutCString("-1");
2722   else
2723     packet.Printf("%" PRIx64, tid);
2724 
2725   StringExtractorGDBRemote response;
2726   if (SendPacketAndWaitForResponse(packet.GetString(), response) ==
2727       PacketResult::Success) {
2728     if (response.IsOKResponse())
2729       return {{pid, tid}};
2730 
2731     /*
2732      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2733      * Hg packet.
2734      * The reply from '?' packet could be as simple as 'S05'. There is no packet
2735      * which can
2736      * give us pid and/or tid. Assume pid=tid=1 in such cases.
2737      */
2738     if (response.IsUnsupportedResponse() && IsConnected())
2739       return {{1, 1}};
2740   }
2741   return llvm::None;
2742 }
2743 
2744 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid,
2745                                                     uint64_t pid) {
2746   if (m_curr_tid == tid &&
2747       (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid))
2748     return true;
2749 
2750   llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
2751   if (ret) {
2752     if (ret->pid != LLDB_INVALID_PROCESS_ID)
2753       m_curr_pid = ret->pid;
2754     m_curr_tid = ret->tid;
2755   }
2756   return ret.has_value();
2757 }
2758 
2759 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid,
2760                                                           uint64_t pid) {
2761   if (m_curr_tid_run == tid &&
2762       (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid))
2763     return true;
2764 
2765   llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
2766   if (ret) {
2767     if (ret->pid != LLDB_INVALID_PROCESS_ID)
2768       m_curr_pid_run = ret->pid;
2769     m_curr_tid_run = ret->tid;
2770   }
2771   return ret.has_value();
2772 }
2773 
2774 bool GDBRemoteCommunicationClient::GetStopReply(
2775     StringExtractorGDBRemote &response) {
2776   if (SendPacketAndWaitForResponse("?", response) == PacketResult::Success)
2777     return response.IsNormalResponse();
2778   return false;
2779 }
2780 
2781 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2782     lldb::tid_t tid, StringExtractorGDBRemote &response) {
2783   if (m_supports_qThreadStopInfo) {
2784     char packet[256];
2785     int packet_len =
2786         ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2787     assert(packet_len < (int)sizeof(packet));
2788     UNUSED_IF_ASSERT_DISABLED(packet_len);
2789     if (SendPacketAndWaitForResponse(packet, response) ==
2790         PacketResult::Success) {
2791       if (response.IsUnsupportedResponse())
2792         m_supports_qThreadStopInfo = false;
2793       else if (response.IsNormalResponse())
2794         return true;
2795       else
2796         return false;
2797     } else {
2798       m_supports_qThreadStopInfo = false;
2799     }
2800   }
2801   return false;
2802 }
2803 
2804 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2805     GDBStoppointType type, bool insert, addr_t addr, uint32_t length,
2806     std::chrono::seconds timeout) {
2807   Log *log = GetLog(LLDBLog::Breakpoints);
2808   LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2809             __FUNCTION__, insert ? "add" : "remove", addr);
2810 
2811   // Check if the stub is known not to support this breakpoint type
2812   if (!SupportsGDBStoppointPacket(type))
2813     return UINT8_MAX;
2814   // Construct the breakpoint packet
2815   char packet[64];
2816   const int packet_len =
2817       ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2818                  insert ? 'Z' : 'z', type, addr, length);
2819   // Check we haven't overwritten the end of the packet buffer
2820   assert(packet_len + 1 < (int)sizeof(packet));
2821   UNUSED_IF_ASSERT_DISABLED(packet_len);
2822   StringExtractorGDBRemote response;
2823   // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2824   // or "" (unsupported)
2825   response.SetResponseValidatorToOKErrorNotSupported();
2826   // Try to send the breakpoint packet, and check that it was correctly sent
2827   if (SendPacketAndWaitForResponse(packet, response, timeout) ==
2828       PacketResult::Success) {
2829     // Receive and OK packet when the breakpoint successfully placed
2830     if (response.IsOKResponse())
2831       return 0;
2832 
2833     // Status while setting breakpoint, send back specific error
2834     if (response.IsErrorResponse())
2835       return response.GetError();
2836 
2837     // Empty packet informs us that breakpoint is not supported
2838     if (response.IsUnsupportedResponse()) {
2839       // Disable this breakpoint type since it is unsupported
2840       switch (type) {
2841       case eBreakpointSoftware:
2842         m_supports_z0 = false;
2843         break;
2844       case eBreakpointHardware:
2845         m_supports_z1 = false;
2846         break;
2847       case eWatchpointWrite:
2848         m_supports_z2 = false;
2849         break;
2850       case eWatchpointRead:
2851         m_supports_z3 = false;
2852         break;
2853       case eWatchpointReadWrite:
2854         m_supports_z4 = false;
2855         break;
2856       case eStoppointInvalid:
2857         return UINT8_MAX;
2858       }
2859     }
2860   }
2861   // Signal generic failure
2862   return UINT8_MAX;
2863 }
2864 
2865 std::vector<std::pair<lldb::pid_t, lldb::tid_t>>
2866 GDBRemoteCommunicationClient::GetCurrentProcessAndThreadIDs(
2867     bool &sequence_mutex_unavailable) {
2868   std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids;
2869 
2870   Lock lock(*this);
2871   if (lock) {
2872     sequence_mutex_unavailable = false;
2873     StringExtractorGDBRemote response;
2874 
2875     PacketResult packet_result;
2876     for (packet_result =
2877              SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2878          packet_result == PacketResult::Success && response.IsNormalResponse();
2879          packet_result =
2880              SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2881       char ch = response.GetChar();
2882       if (ch == 'l')
2883         break;
2884       if (ch == 'm') {
2885         do {
2886           auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID);
2887           // If we get an invalid response, break out of the loop.
2888           // If there are valid tids, they have been added to ids.
2889           // If there are no valid tids, we'll fall through to the
2890           // bare-iron target handling below.
2891           if (!pid_tid)
2892             break;
2893 
2894           ids.push_back(*pid_tid);
2895           ch = response.GetChar(); // Skip the command separator
2896         } while (ch == ',');       // Make sure we got a comma separator
2897       }
2898     }
2899 
2900     /*
2901      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2902      * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2903      * could
2904      * be as simple as 'S05'. There is no packet which can give us pid and/or
2905      * tid.
2906      * Assume pid=tid=1 in such cases.
2907      */
2908     if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2909         ids.size() == 0 && IsConnected()) {
2910       ids.emplace_back(1, 1);
2911     }
2912   } else {
2913     Log *log(GetLog(GDBRLog::Process | GDBRLog::Packets));
2914     LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending "
2915                   "packet 'qfThreadInfo'");
2916     sequence_mutex_unavailable = true;
2917   }
2918 
2919   return ids;
2920 }
2921 
2922 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2923     std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2924   lldb::pid_t pid = GetCurrentProcessID();
2925   thread_ids.clear();
2926 
2927   auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable);
2928   if (ids.empty() || sequence_mutex_unavailable)
2929     return 0;
2930 
2931   for (auto id : ids) {
2932     // skip threads that do not belong to the current process
2933     if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid)
2934       continue;
2935     if (id.second != LLDB_INVALID_THREAD_ID &&
2936         id.second != StringExtractorGDBRemote::AllThreads)
2937       thread_ids.push_back(id.second);
2938   }
2939 
2940   return thread_ids.size();
2941 }
2942 
2943 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2944   StringExtractorGDBRemote response;
2945   if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) !=
2946           PacketResult::Success ||
2947       !response.IsNormalResponse())
2948     return LLDB_INVALID_ADDRESS;
2949   return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2950 }
2951 
2952 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2953     llvm::StringRef command,
2954     const FileSpec &
2955         working_dir, // Pass empty FileSpec to use the current working directory
2956     int *status_ptr, // Pass NULL if you don't want the process exit status
2957     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
2958                      // process to exit
2959     std::string
2960         *command_output, // Pass NULL if you don't want the command output
2961     const Timeout<std::micro> &timeout) {
2962   lldb_private::StreamString stream;
2963   stream.PutCString("qPlatform_shell:");
2964   stream.PutBytesAsRawHex8(command.data(), command.size());
2965   stream.PutChar(',');
2966   uint32_t timeout_sec = UINT32_MAX;
2967   if (timeout) {
2968     // TODO: Use chrono version of std::ceil once c++17 is available.
2969     timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2970   }
2971   stream.PutHex32(timeout_sec);
2972   if (working_dir) {
2973     std::string path{working_dir.GetPath(false)};
2974     stream.PutChar(',');
2975     stream.PutStringAsRawHex8(path);
2976   }
2977   StringExtractorGDBRemote response;
2978   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
2979       PacketResult::Success) {
2980     if (response.GetChar() != 'F')
2981       return Status("malformed reply");
2982     if (response.GetChar() != ',')
2983       return Status("malformed reply");
2984     uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2985     if (exitcode == UINT32_MAX)
2986       return Status("unable to run remote process");
2987     else if (status_ptr)
2988       *status_ptr = exitcode;
2989     if (response.GetChar() != ',')
2990       return Status("malformed reply");
2991     uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2992     if (signo_ptr)
2993       *signo_ptr = signo;
2994     if (response.GetChar() != ',')
2995       return Status("malformed reply");
2996     std::string output;
2997     response.GetEscapedBinaryData(output);
2998     if (command_output)
2999       command_output->assign(output);
3000     return Status();
3001   }
3002   return Status("unable to send packet");
3003 }
3004 
3005 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3006                                                    uint32_t file_permissions) {
3007   std::string path{file_spec.GetPath(false)};
3008   lldb_private::StreamString stream;
3009   stream.PutCString("qPlatform_mkdir:");
3010   stream.PutHex32(file_permissions);
3011   stream.PutChar(',');
3012   stream.PutStringAsRawHex8(path);
3013   llvm::StringRef packet = stream.GetString();
3014   StringExtractorGDBRemote response;
3015 
3016   if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3017     return Status("failed to send '%s' packet", packet.str().c_str());
3018 
3019   if (response.GetChar() != 'F')
3020     return Status("invalid response to '%s' packet", packet.str().c_str());
3021 
3022   return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3023 }
3024 
3025 Status
3026 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3027                                                  uint32_t file_permissions) {
3028   std::string path{file_spec.GetPath(false)};
3029   lldb_private::StreamString stream;
3030   stream.PutCString("qPlatform_chmod:");
3031   stream.PutHex32(file_permissions);
3032   stream.PutChar(',');
3033   stream.PutStringAsRawHex8(path);
3034   llvm::StringRef packet = stream.GetString();
3035   StringExtractorGDBRemote response;
3036 
3037   if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success)
3038     return Status("failed to send '%s' packet", stream.GetData());
3039 
3040   if (response.GetChar() != 'F')
3041     return Status("invalid response to '%s' packet", stream.GetData());
3042 
3043   return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3044 }
3045 
3046 static int gdb_errno_to_system(int err) {
3047   switch (err) {
3048 #define HANDLE_ERRNO(name, value)                                              \
3049   case GDB_##name:                                                             \
3050     return name;
3051 #include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
3052   default:
3053     return -1;
3054   }
3055 }
3056 
3057 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
3058                                           uint64_t fail_result, Status &error) {
3059   response.SetFilePos(0);
3060   if (response.GetChar() != 'F')
3061     return fail_result;
3062   int32_t result = response.GetS32(-2, 16);
3063   if (result == -2)
3064     return fail_result;
3065   if (response.GetChar() == ',') {
3066     int result_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3067     if (result_errno != -1)
3068       error.SetError(result_errno, eErrorTypePOSIX);
3069     else
3070       error.SetError(-1, eErrorTypeGeneric);
3071   } else
3072     error.Clear();
3073   return result;
3074 }
3075 lldb::user_id_t
3076 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
3077                                        File::OpenOptions flags, mode_t mode,
3078                                        Status &error) {
3079   std::string path(file_spec.GetPath(false));
3080   lldb_private::StreamString stream;
3081   stream.PutCString("vFile:open:");
3082   if (path.empty())
3083     return UINT64_MAX;
3084   stream.PutStringAsRawHex8(path);
3085   stream.PutChar(',');
3086   stream.PutHex32(flags);
3087   stream.PutChar(',');
3088   stream.PutHex32(mode);
3089   StringExtractorGDBRemote response;
3090   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3091       PacketResult::Success) {
3092     return ParseHostIOPacketResponse(response, UINT64_MAX, error);
3093   }
3094   return UINT64_MAX;
3095 }
3096 
3097 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
3098                                              Status &error) {
3099   lldb_private::StreamString stream;
3100   stream.Printf("vFile:close:%x", (int)fd);
3101   StringExtractorGDBRemote response;
3102   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3103       PacketResult::Success) {
3104     return ParseHostIOPacketResponse(response, -1, error) == 0;
3105   }
3106   return false;
3107 }
3108 
3109 llvm::Optional<GDBRemoteFStatData>
3110 GDBRemoteCommunicationClient::FStat(lldb::user_id_t fd) {
3111   lldb_private::StreamString stream;
3112   stream.Printf("vFile:fstat:%" PRIx64, fd);
3113   StringExtractorGDBRemote response;
3114   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3115       PacketResult::Success) {
3116     if (response.GetChar() != 'F')
3117       return llvm::None;
3118     int64_t size = response.GetS64(-1, 16);
3119     if (size > 0 && response.GetChar() == ';') {
3120       std::string buffer;
3121       if (response.GetEscapedBinaryData(buffer)) {
3122         GDBRemoteFStatData out;
3123         if (buffer.size() != sizeof(out))
3124           return llvm::None;
3125         memcpy(&out, buffer.data(), sizeof(out));
3126         return out;
3127       }
3128     }
3129   }
3130   return llvm::None;
3131 }
3132 
3133 llvm::Optional<GDBRemoteFStatData>
3134 GDBRemoteCommunicationClient::Stat(const lldb_private::FileSpec &file_spec) {
3135   Status error;
3136   lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error);
3137   if (fd == UINT64_MAX)
3138     return llvm::None;
3139   llvm::Optional<GDBRemoteFStatData> st = FStat(fd);
3140   CloseFile(fd, error);
3141   return st;
3142 }
3143 
3144 // Extension of host I/O packets to get the file size.
3145 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
3146     const lldb_private::FileSpec &file_spec) {
3147   if (m_supports_vFileSize) {
3148     std::string path(file_spec.GetPath(false));
3149     lldb_private::StreamString stream;
3150     stream.PutCString("vFile:size:");
3151     stream.PutStringAsRawHex8(path);
3152     StringExtractorGDBRemote response;
3153     if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3154         PacketResult::Success)
3155       return UINT64_MAX;
3156 
3157     if (!response.IsUnsupportedResponse()) {
3158       if (response.GetChar() != 'F')
3159         return UINT64_MAX;
3160       uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3161       return retcode;
3162     }
3163     m_supports_vFileSize = false;
3164   }
3165 
3166   // Fallback to fstat.
3167   llvm::Optional<GDBRemoteFStatData> st = Stat(file_spec);
3168   return st ? st->gdb_st_size : UINT64_MAX;
3169 }
3170 
3171 void GDBRemoteCommunicationClient::AutoCompleteDiskFileOrDirectory(
3172     CompletionRequest &request, bool only_dir) {
3173   lldb_private::StreamString stream;
3174   stream.PutCString("qPathComplete:");
3175   stream.PutHex32(only_dir ? 1 : 0);
3176   stream.PutChar(',');
3177   stream.PutStringAsRawHex8(request.GetCursorArgumentPrefix());
3178   StringExtractorGDBRemote response;
3179   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3180       PacketResult::Success) {
3181     StreamString strm;
3182     char ch = response.GetChar();
3183     if (ch != 'M')
3184       return;
3185     while (response.Peek()) {
3186       strm.Clear();
3187       while ((ch = response.GetHexU8(0, false)) != '\0')
3188         strm.PutChar(ch);
3189       request.AddCompletion(strm.GetString());
3190       if (response.GetChar() != ',')
3191         break;
3192     }
3193   }
3194 }
3195 
3196 Status
3197 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3198                                                  uint32_t &file_permissions) {
3199   if (m_supports_vFileMode) {
3200     std::string path{file_spec.GetPath(false)};
3201     Status error;
3202     lldb_private::StreamString stream;
3203     stream.PutCString("vFile:mode:");
3204     stream.PutStringAsRawHex8(path);
3205     StringExtractorGDBRemote response;
3206     if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3207         PacketResult::Success) {
3208       error.SetErrorStringWithFormat("failed to send '%s' packet",
3209                                      stream.GetData());
3210       return error;
3211     }
3212     if (!response.IsUnsupportedResponse()) {
3213       if (response.GetChar() != 'F') {
3214         error.SetErrorStringWithFormat("invalid response to '%s' packet",
3215                                        stream.GetData());
3216       } else {
3217         const uint32_t mode = response.GetS32(-1, 16);
3218         if (static_cast<int32_t>(mode) == -1) {
3219           if (response.GetChar() == ',') {
3220             int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3221             if (response_errno > 0)
3222               error.SetError(response_errno, lldb::eErrorTypePOSIX);
3223             else
3224               error.SetErrorToGenericError();
3225           } else
3226             error.SetErrorToGenericError();
3227         } else {
3228           file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3229         }
3230       }
3231       return error;
3232     } else { // response.IsUnsupportedResponse()
3233       m_supports_vFileMode = false;
3234     }
3235   }
3236 
3237   // Fallback to fstat.
3238   if (llvm::Optional<GDBRemoteFStatData> st = Stat(file_spec)) {
3239     file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3240     return Status();
3241   }
3242   return Status("fstat failed");
3243 }
3244 
3245 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
3246                                                 uint64_t offset, void *dst,
3247                                                 uint64_t dst_len,
3248                                                 Status &error) {
3249   lldb_private::StreamString stream;
3250   stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len,
3251                 offset);
3252   StringExtractorGDBRemote response;
3253   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3254       PacketResult::Success) {
3255     if (response.GetChar() != 'F')
3256       return 0;
3257     int64_t retcode = response.GetS64(-1, 16);
3258     if (retcode == -1) {
3259       error.SetErrorToGenericError();
3260       if (response.GetChar() == ',') {
3261         int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3262         if (response_errno > 0)
3263           error.SetError(response_errno, lldb::eErrorTypePOSIX);
3264       }
3265       return -1;
3266     }
3267     const char next = (response.Peek() ? *response.Peek() : 0);
3268     if (next == ',')
3269       return 0;
3270     if (next == ';') {
3271       response.GetChar(); // skip the semicolon
3272       std::string buffer;
3273       if (response.GetEscapedBinaryData(buffer)) {
3274         const uint64_t data_to_write =
3275             std::min<uint64_t>(dst_len, buffer.size());
3276         if (data_to_write > 0)
3277           memcpy(dst, &buffer[0], data_to_write);
3278         return data_to_write;
3279       }
3280     }
3281   }
3282   return 0;
3283 }
3284 
3285 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3286                                                  uint64_t offset,
3287                                                  const void *src,
3288                                                  uint64_t src_len,
3289                                                  Status &error) {
3290   lldb_private::StreamGDBRemote stream;
3291   stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset);
3292   stream.PutEscapedBytes(src, src_len);
3293   StringExtractorGDBRemote response;
3294   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3295       PacketResult::Success) {
3296     if (response.GetChar() != 'F') {
3297       error.SetErrorStringWithFormat("write file failed");
3298       return 0;
3299     }
3300     int64_t bytes_written = response.GetS64(-1, 16);
3301     if (bytes_written == -1) {
3302       error.SetErrorToGenericError();
3303       if (response.GetChar() == ',') {
3304         int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3305         if (response_errno > 0)
3306           error.SetError(response_errno, lldb::eErrorTypePOSIX);
3307       }
3308       return -1;
3309     }
3310     return bytes_written;
3311   } else {
3312     error.SetErrorString("failed to send vFile:pwrite packet");
3313   }
3314   return 0;
3315 }
3316 
3317 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3318                                                    const FileSpec &dst) {
3319   std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3320   Status error;
3321   lldb_private::StreamGDBRemote stream;
3322   stream.PutCString("vFile:symlink:");
3323   // the unix symlink() command reverses its parameters where the dst if first,
3324   // so we follow suit here
3325   stream.PutStringAsRawHex8(dst_path);
3326   stream.PutChar(',');
3327   stream.PutStringAsRawHex8(src_path);
3328   StringExtractorGDBRemote response;
3329   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3330       PacketResult::Success) {
3331     if (response.GetChar() == 'F') {
3332       uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3333       if (result != 0) {
3334         error.SetErrorToGenericError();
3335         if (response.GetChar() == ',') {
3336           int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3337           if (response_errno > 0)
3338             error.SetError(response_errno, lldb::eErrorTypePOSIX);
3339         }
3340       }
3341     } else {
3342       // Should have returned with 'F<result>[,<errno>]'
3343       error.SetErrorStringWithFormat("symlink failed");
3344     }
3345   } else {
3346     error.SetErrorString("failed to send vFile:symlink packet");
3347   }
3348   return error;
3349 }
3350 
3351 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3352   std::string path{file_spec.GetPath(false)};
3353   Status error;
3354   lldb_private::StreamGDBRemote stream;
3355   stream.PutCString("vFile:unlink:");
3356   // the unix symlink() command reverses its parameters where the dst if first,
3357   // so we follow suit here
3358   stream.PutStringAsRawHex8(path);
3359   StringExtractorGDBRemote response;
3360   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3361       PacketResult::Success) {
3362     if (response.GetChar() == 'F') {
3363       uint32_t result = response.GetHexMaxU32(false, UINT32_MAX);
3364       if (result != 0) {
3365         error.SetErrorToGenericError();
3366         if (response.GetChar() == ',') {
3367           int response_errno = gdb_errno_to_system(response.GetS32(-1, 16));
3368           if (response_errno > 0)
3369             error.SetError(response_errno, lldb::eErrorTypePOSIX);
3370         }
3371       }
3372     } else {
3373       // Should have returned with 'F<result>[,<errno>]'
3374       error.SetErrorStringWithFormat("unlink failed");
3375     }
3376   } else {
3377     error.SetErrorString("failed to send vFile:unlink packet");
3378   }
3379   return error;
3380 }
3381 
3382 // Extension of host I/O packets to get whether a file exists.
3383 bool GDBRemoteCommunicationClient::GetFileExists(
3384     const lldb_private::FileSpec &file_spec) {
3385   if (m_supports_vFileExists) {
3386     std::string path(file_spec.GetPath(false));
3387     lldb_private::StreamString stream;
3388     stream.PutCString("vFile:exists:");
3389     stream.PutStringAsRawHex8(path);
3390     StringExtractorGDBRemote response;
3391     if (SendPacketAndWaitForResponse(stream.GetString(), response) !=
3392         PacketResult::Success)
3393       return false;
3394     if (!response.IsUnsupportedResponse()) {
3395       if (response.GetChar() != 'F')
3396         return false;
3397       if (response.GetChar() != ',')
3398         return false;
3399       bool retcode = (response.GetChar() != '0');
3400       return retcode;
3401     } else
3402       m_supports_vFileExists = false;
3403   }
3404 
3405   // Fallback to open.
3406   Status error;
3407   lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error);
3408   if (fd == UINT64_MAX)
3409     return false;
3410   CloseFile(fd, error);
3411   return true;
3412 }
3413 
3414 bool GDBRemoteCommunicationClient::CalculateMD5(
3415     const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3416   std::string path(file_spec.GetPath(false));
3417   lldb_private::StreamString stream;
3418   stream.PutCString("vFile:MD5:");
3419   stream.PutStringAsRawHex8(path);
3420   StringExtractorGDBRemote response;
3421   if (SendPacketAndWaitForResponse(stream.GetString(), response) ==
3422       PacketResult::Success) {
3423     if (response.GetChar() != 'F')
3424       return false;
3425     if (response.GetChar() != ',')
3426       return false;
3427     if (response.Peek() && *response.Peek() == 'x')
3428       return false;
3429     low = response.GetHexMaxU64(false, UINT64_MAX);
3430     high = response.GetHexMaxU64(false, UINT64_MAX);
3431     return true;
3432   }
3433   return false;
3434 }
3435 
3436 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3437   // Some targets have issues with g/G packets and we need to avoid using them
3438   if (m_avoid_g_packets == eLazyBoolCalculate) {
3439     if (process) {
3440       m_avoid_g_packets = eLazyBoolNo;
3441       const ArchSpec &arch = process->GetTarget().GetArchitecture();
3442       if (arch.IsValid() &&
3443           arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3444           arch.GetTriple().getOS() == llvm::Triple::IOS &&
3445           (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3446            arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
3447         m_avoid_g_packets = eLazyBoolYes;
3448         uint32_t gdb_server_version = GetGDBServerProgramVersion();
3449         if (gdb_server_version != 0) {
3450           const char *gdb_server_name = GetGDBServerProgramName();
3451           if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3452             if (gdb_server_version >= 310)
3453               m_avoid_g_packets = eLazyBoolNo;
3454           }
3455         }
3456       }
3457     }
3458   }
3459   return m_avoid_g_packets == eLazyBoolYes;
3460 }
3461 
3462 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3463                                                         uint32_t reg) {
3464   StreamString payload;
3465   payload.Printf("p%x", reg);
3466   StringExtractorGDBRemote response;
3467   if (SendThreadSpecificPacketAndWaitForResponse(
3468           tid, std::move(payload), response) != PacketResult::Success ||
3469       !response.IsNormalResponse())
3470     return nullptr;
3471 
3472   WritableDataBufferSP buffer_sp(
3473       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3474   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3475   return buffer_sp;
3476 }
3477 
3478 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3479   StreamString payload;
3480   payload.PutChar('g');
3481   StringExtractorGDBRemote response;
3482   if (SendThreadSpecificPacketAndWaitForResponse(
3483           tid, std::move(payload), response) != PacketResult::Success ||
3484       !response.IsNormalResponse())
3485     return nullptr;
3486 
3487   WritableDataBufferSP buffer_sp(
3488       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3489   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3490   return buffer_sp;
3491 }
3492 
3493 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3494                                                  uint32_t reg_num,
3495                                                  llvm::ArrayRef<uint8_t> data) {
3496   StreamString payload;
3497   payload.Printf("P%x=", reg_num);
3498   payload.PutBytesAsRawHex8(data.data(), data.size(),
3499                             endian::InlHostByteOrder(),
3500                             endian::InlHostByteOrder());
3501   StringExtractorGDBRemote response;
3502   return SendThreadSpecificPacketAndWaitForResponse(
3503              tid, std::move(payload), response) == PacketResult::Success &&
3504          response.IsOKResponse();
3505 }
3506 
3507 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3508     lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3509   StreamString payload;
3510   payload.PutChar('G');
3511   payload.PutBytesAsRawHex8(data.data(), data.size(),
3512                             endian::InlHostByteOrder(),
3513                             endian::InlHostByteOrder());
3514   StringExtractorGDBRemote response;
3515   return SendThreadSpecificPacketAndWaitForResponse(
3516              tid, std::move(payload), response) == PacketResult::Success &&
3517          response.IsOKResponse();
3518 }
3519 
3520 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3521                                                      uint32_t &save_id) {
3522   save_id = 0; // Set to invalid save ID
3523   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3524     return false;
3525 
3526   m_supports_QSaveRegisterState = eLazyBoolYes;
3527   StreamString payload;
3528   payload.PutCString("QSaveRegisterState");
3529   StringExtractorGDBRemote response;
3530   if (SendThreadSpecificPacketAndWaitForResponse(
3531           tid, std::move(payload), response) != PacketResult::Success)
3532     return false;
3533 
3534   if (response.IsUnsupportedResponse())
3535     m_supports_QSaveRegisterState = eLazyBoolNo;
3536 
3537   const uint32_t response_save_id = response.GetU32(0);
3538   if (response_save_id == 0)
3539     return false;
3540 
3541   save_id = response_save_id;
3542   return true;
3543 }
3544 
3545 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3546                                                         uint32_t save_id) {
3547   // We use the "m_supports_QSaveRegisterState" variable here because the
3548   // QSaveRegisterState and QRestoreRegisterState packets must both be
3549   // supported in order to be useful
3550   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3551     return false;
3552 
3553   StreamString payload;
3554   payload.Printf("QRestoreRegisterState:%u", save_id);
3555   StringExtractorGDBRemote response;
3556   if (SendThreadSpecificPacketAndWaitForResponse(
3557           tid, std::move(payload), response) != PacketResult::Success)
3558     return false;
3559 
3560   if (response.IsOKResponse())
3561     return true;
3562 
3563   if (response.IsUnsupportedResponse())
3564     m_supports_QSaveRegisterState = eLazyBoolNo;
3565   return false;
3566 }
3567 
3568 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3569   if (!GetSyncThreadStateSupported())
3570     return false;
3571 
3572   StreamString packet;
3573   StringExtractorGDBRemote response;
3574   packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3575   return SendPacketAndWaitForResponse(packet.GetString(), response) ==
3576              GDBRemoteCommunication::PacketResult::Success &&
3577          response.IsOKResponse();
3578 }
3579 
3580 llvm::Expected<TraceSupportedResponse>
3581 GDBRemoteCommunicationClient::SendTraceSupported(std::chrono::seconds timeout) {
3582   Log *log = GetLog(GDBRLog::Process);
3583 
3584   StreamGDBRemote escaped_packet;
3585   escaped_packet.PutCString("jLLDBTraceSupported");
3586 
3587   StringExtractorGDBRemote response;
3588   if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3589                                    timeout) ==
3590       GDBRemoteCommunication::PacketResult::Success) {
3591     if (response.IsErrorResponse())
3592       return response.GetStatus().ToError();
3593     if (response.IsUnsupportedResponse())
3594       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3595                                      "jLLDBTraceSupported is unsupported");
3596 
3597     return llvm::json::parse<TraceSupportedResponse>(response.Peek(),
3598                                                      "TraceSupportedResponse");
3599   }
3600   LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported");
3601   return llvm::createStringError(llvm::inconvertibleErrorCode(),
3602                                  "failed to send packet: jLLDBTraceSupported");
3603 }
3604 
3605 llvm::Error
3606 GDBRemoteCommunicationClient::SendTraceStop(const TraceStopRequest &request,
3607                                             std::chrono::seconds timeout) {
3608   Log *log = GetLog(GDBRLog::Process);
3609 
3610   StreamGDBRemote escaped_packet;
3611   escaped_packet.PutCString("jLLDBTraceStop:");
3612 
3613   std::string json_string;
3614   llvm::raw_string_ostream os(json_string);
3615   os << toJSON(request);
3616   os.flush();
3617 
3618   escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3619 
3620   StringExtractorGDBRemote response;
3621   if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3622                                    timeout) ==
3623       GDBRemoteCommunication::PacketResult::Success) {
3624     if (response.IsErrorResponse())
3625       return response.GetStatus().ToError();
3626     if (response.IsUnsupportedResponse())
3627       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3628                                      "jLLDBTraceStop is unsupported");
3629     if (response.IsOKResponse())
3630       return llvm::Error::success();
3631     return llvm::createStringError(llvm::inconvertibleErrorCode(),
3632                                    "Invalid jLLDBTraceStart response");
3633   }
3634   LLDB_LOG(log, "failed to send packet: jLLDBTraceStop");
3635   return llvm::createStringError(llvm::inconvertibleErrorCode(),
3636                                  "failed to send packet: jLLDBTraceStop '%s'",
3637                                  escaped_packet.GetData());
3638 }
3639 
3640 llvm::Error
3641 GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value &params,
3642                                              std::chrono::seconds timeout) {
3643   Log *log = GetLog(GDBRLog::Process);
3644 
3645   StreamGDBRemote escaped_packet;
3646   escaped_packet.PutCString("jLLDBTraceStart:");
3647 
3648   std::string json_string;
3649   llvm::raw_string_ostream os(json_string);
3650   os << params;
3651   os.flush();
3652 
3653   escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3654 
3655   StringExtractorGDBRemote response;
3656   if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3657                                    timeout) ==
3658       GDBRemoteCommunication::PacketResult::Success) {
3659     if (response.IsErrorResponse())
3660       return response.GetStatus().ToError();
3661     if (response.IsUnsupportedResponse())
3662       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3663                                      "jLLDBTraceStart is unsupported");
3664     if (response.IsOKResponse())
3665       return llvm::Error::success();
3666     return llvm::createStringError(llvm::inconvertibleErrorCode(),
3667                                    "Invalid jLLDBTraceStart response");
3668   }
3669   LLDB_LOG(log, "failed to send packet: jLLDBTraceStart");
3670   return llvm::createStringError(llvm::inconvertibleErrorCode(),
3671                                  "failed to send packet: jLLDBTraceStart '%s'",
3672                                  escaped_packet.GetData());
3673 }
3674 
3675 llvm::Expected<std::string>
3676 GDBRemoteCommunicationClient::SendTraceGetState(llvm::StringRef type,
3677                                                 std::chrono::seconds timeout) {
3678   Log *log = GetLog(GDBRLog::Process);
3679 
3680   StreamGDBRemote escaped_packet;
3681   escaped_packet.PutCString("jLLDBTraceGetState:");
3682 
3683   std::string json_string;
3684   llvm::raw_string_ostream os(json_string);
3685   os << toJSON(TraceGetStateRequest{type.str()});
3686   os.flush();
3687 
3688   escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3689 
3690   StringExtractorGDBRemote response;
3691   if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3692                                    timeout) ==
3693       GDBRemoteCommunication::PacketResult::Success) {
3694     if (response.IsErrorResponse())
3695       return response.GetStatus().ToError();
3696     if (response.IsUnsupportedResponse())
3697       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3698                                      "jLLDBTraceGetState is unsupported");
3699     return std::string(response.Peek());
3700   }
3701 
3702   LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState");
3703   return llvm::createStringError(
3704       llvm::inconvertibleErrorCode(),
3705       "failed to send packet: jLLDBTraceGetState '%s'",
3706       escaped_packet.GetData());
3707 }
3708 
3709 llvm::Expected<std::vector<uint8_t>>
3710 GDBRemoteCommunicationClient::SendTraceGetBinaryData(
3711     const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) {
3712   Log *log = GetLog(GDBRLog::Process);
3713 
3714   StreamGDBRemote escaped_packet;
3715   escaped_packet.PutCString("jLLDBTraceGetBinaryData:");
3716 
3717   std::string json_string;
3718   llvm::raw_string_ostream os(json_string);
3719   os << toJSON(request);
3720   os.flush();
3721 
3722   escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
3723 
3724   StringExtractorGDBRemote response;
3725   if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3726                                    timeout) ==
3727       GDBRemoteCommunication::PacketResult::Success) {
3728     if (response.IsErrorResponse())
3729       return response.GetStatus().ToError();
3730     std::string data;
3731     response.GetEscapedBinaryData(data);
3732     return std::vector<uint8_t>(data.begin(), data.end());
3733   }
3734   LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData");
3735   return llvm::createStringError(
3736       llvm::inconvertibleErrorCode(),
3737       "failed to send packet: jLLDBTraceGetBinaryData '%s'",
3738       escaped_packet.GetData());
3739 }
3740 
3741 llvm::Optional<QOffsets> GDBRemoteCommunicationClient::GetQOffsets() {
3742   StringExtractorGDBRemote response;
3743   if (SendPacketAndWaitForResponse("qOffsets", response) !=
3744       PacketResult::Success)
3745     return llvm::None;
3746   if (!response.IsNormalResponse())
3747     return llvm::None;
3748 
3749   QOffsets result;
3750   llvm::StringRef ref = response.GetStringRef();
3751   const auto &GetOffset = [&] {
3752     addr_t offset;
3753     if (ref.consumeInteger(16, offset))
3754       return false;
3755     result.offsets.push_back(offset);
3756     return true;
3757   };
3758 
3759   if (ref.consume_front("Text=")) {
3760     result.segments = false;
3761     if (!GetOffset())
3762       return llvm::None;
3763     if (!ref.consume_front(";Data=") || !GetOffset())
3764       return llvm::None;
3765     if (ref.empty())
3766       return result;
3767     if (ref.consume_front(";Bss=") && GetOffset() && ref.empty())
3768       return result;
3769   } else if (ref.consume_front("TextSeg=")) {
3770     result.segments = true;
3771     if (!GetOffset())
3772       return llvm::None;
3773     if (ref.empty())
3774       return result;
3775     if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty())
3776       return result;
3777   }
3778   return llvm::None;
3779 }
3780 
3781 bool GDBRemoteCommunicationClient::GetModuleInfo(
3782     const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3783     ModuleSpec &module_spec) {
3784   if (!m_supports_qModuleInfo)
3785     return false;
3786 
3787   std::string module_path = module_file_spec.GetPath(false);
3788   if (module_path.empty())
3789     return false;
3790 
3791   StreamString packet;
3792   packet.PutCString("qModuleInfo:");
3793   packet.PutStringAsRawHex8(module_path);
3794   packet.PutCString(";");
3795   const auto &triple = arch_spec.GetTriple().getTriple();
3796   packet.PutStringAsRawHex8(triple);
3797 
3798   StringExtractorGDBRemote response;
3799   if (SendPacketAndWaitForResponse(packet.GetString(), response) !=
3800       PacketResult::Success)
3801     return false;
3802 
3803   if (response.IsErrorResponse())
3804     return false;
3805 
3806   if (response.IsUnsupportedResponse()) {
3807     m_supports_qModuleInfo = false;
3808     return false;
3809   }
3810 
3811   llvm::StringRef name;
3812   llvm::StringRef value;
3813 
3814   module_spec.Clear();
3815   module_spec.GetFileSpec() = module_file_spec;
3816 
3817   while (response.GetNameColonValue(name, value)) {
3818     if (name == "uuid" || name == "md5") {
3819       StringExtractor extractor(value);
3820       std::string uuid;
3821       extractor.GetHexByteString(uuid);
3822       module_spec.GetUUID().SetFromStringRef(uuid);
3823     } else if (name == "triple") {
3824       StringExtractor extractor(value);
3825       std::string triple;
3826       extractor.GetHexByteString(triple);
3827       module_spec.GetArchitecture().SetTriple(triple.c_str());
3828     } else if (name == "file_offset") {
3829       uint64_t ival = 0;
3830       if (!value.getAsInteger(16, ival))
3831         module_spec.SetObjectOffset(ival);
3832     } else if (name == "file_size") {
3833       uint64_t ival = 0;
3834       if (!value.getAsInteger(16, ival))
3835         module_spec.SetObjectSize(ival);
3836     } else if (name == "file_path") {
3837       StringExtractor extractor(value);
3838       std::string path;
3839       extractor.GetHexByteString(path);
3840       module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3841     }
3842   }
3843 
3844   return true;
3845 }
3846 
3847 static llvm::Optional<ModuleSpec>
3848 ParseModuleSpec(StructuredData::Dictionary *dict) {
3849   ModuleSpec result;
3850   if (!dict)
3851     return llvm::None;
3852 
3853   llvm::StringRef string;
3854   uint64_t integer;
3855 
3856   if (!dict->GetValueForKeyAsString("uuid", string))
3857     return llvm::None;
3858   if (!result.GetUUID().SetFromStringRef(string))
3859     return llvm::None;
3860 
3861   if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3862     return llvm::None;
3863   result.SetObjectOffset(integer);
3864 
3865   if (!dict->GetValueForKeyAsInteger("file_size", integer))
3866     return llvm::None;
3867   result.SetObjectSize(integer);
3868 
3869   if (!dict->GetValueForKeyAsString("triple", string))
3870     return llvm::None;
3871   result.GetArchitecture().SetTriple(string);
3872 
3873   if (!dict->GetValueForKeyAsString("file_path", string))
3874     return llvm::None;
3875   result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3876 
3877   return result;
3878 }
3879 
3880 llvm::Optional<std::vector<ModuleSpec>>
3881 GDBRemoteCommunicationClient::GetModulesInfo(
3882     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3883   namespace json = llvm::json;
3884 
3885   if (!m_supports_jModulesInfo)
3886     return llvm::None;
3887 
3888   json::Array module_array;
3889   for (const FileSpec &module_file_spec : module_file_specs) {
3890     module_array.push_back(
3891         json::Object{{"file", module_file_spec.GetPath(false)},
3892                      {"triple", triple.getTriple()}});
3893   }
3894   StreamString unescaped_payload;
3895   unescaped_payload.PutCString("jModulesInfo:");
3896   unescaped_payload.AsRawOstream() << std::move(module_array);
3897 
3898   StreamGDBRemote payload;
3899   payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3900                           unescaped_payload.GetSize());
3901 
3902   // Increase the timeout for jModulesInfo since this packet can take longer.
3903   ScopedTimeout timeout(*this, std::chrono::seconds(10));
3904 
3905   StringExtractorGDBRemote response;
3906   if (SendPacketAndWaitForResponse(payload.GetString(), response) !=
3907           PacketResult::Success ||
3908       response.IsErrorResponse())
3909     return llvm::None;
3910 
3911   if (response.IsUnsupportedResponse()) {
3912     m_supports_jModulesInfo = false;
3913     return llvm::None;
3914   }
3915 
3916   StructuredData::ObjectSP response_object_sp =
3917       StructuredData::ParseJSON(std::string(response.GetStringRef()));
3918   if (!response_object_sp)
3919     return llvm::None;
3920 
3921   StructuredData::Array *response_array = response_object_sp->GetAsArray();
3922   if (!response_array)
3923     return llvm::None;
3924 
3925   std::vector<ModuleSpec> result;
3926   for (size_t i = 0; i < response_array->GetSize(); ++i) {
3927     if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3928             response_array->GetItemAtIndex(i)->GetAsDictionary()))
3929       result.push_back(*module_spec);
3930   }
3931 
3932   return result;
3933 }
3934 
3935 // query the target remote for extended information using the qXfer packet
3936 //
3937 // example: object='features', annex='target.xml'
3938 // return: <xml output> or error
3939 llvm::Expected<std::string>
3940 GDBRemoteCommunicationClient::ReadExtFeature(llvm::StringRef object,
3941                                              llvm::StringRef annex) {
3942 
3943   std::string output;
3944   llvm::raw_string_ostream output_stream(output);
3945   StringExtractorGDBRemote chunk;
3946 
3947   uint64_t size = GetRemoteMaxPacketSize();
3948   if (size == 0)
3949     size = 0x1000;
3950   size = size - 1; // Leave space for the 'm' or 'l' character in the response
3951   int offset = 0;
3952   bool active = true;
3953 
3954   // loop until all data has been read
3955   while (active) {
3956 
3957     // send query extended feature packet
3958     std::string packet =
3959         ("qXfer:" + object + ":read:" + annex + ":" +
3960          llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size))
3961             .str();
3962 
3963     GDBRemoteCommunication::PacketResult res =
3964         SendPacketAndWaitForResponse(packet, chunk);
3965 
3966     if (res != GDBRemoteCommunication::PacketResult::Success ||
3967         chunk.GetStringRef().empty()) {
3968       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3969                                      "Error sending $qXfer packet");
3970     }
3971 
3972     // check packet code
3973     switch (chunk.GetStringRef()[0]) {
3974     // last chunk
3975     case ('l'):
3976       active = false;
3977       [[fallthrough]];
3978 
3979     // more chunks
3980     case ('m'):
3981       output_stream << chunk.GetStringRef().drop_front();
3982       offset += chunk.GetStringRef().size() - 1;
3983       break;
3984 
3985     // unknown chunk
3986     default:
3987       return llvm::createStringError(
3988           llvm::inconvertibleErrorCode(),
3989           "Invalid continuation code from $qXfer packet");
3990     }
3991   }
3992 
3993   return output_stream.str();
3994 }
3995 
3996 // Notify the target that gdb is prepared to serve symbol lookup requests.
3997 //  packet: "qSymbol::"
3998 //  reply:
3999 //  OK                  The target does not need to look up any (more) symbols.
4000 //  qSymbol:<sym_name>  The target requests the value of symbol sym_name (hex
4001 //  encoded).
4002 //                      LLDB may provide the value by sending another qSymbol
4003 //                      packet
4004 //                      in the form of"qSymbol:<sym_value>:<sym_name>".
4005 //
4006 //  Three examples:
4007 //
4008 //  lldb sends:    qSymbol::
4009 //  lldb receives: OK
4010 //     Remote gdb stub does not need to know the addresses of any symbols, lldb
4011 //     does not
4012 //     need to ask again in this session.
4013 //
4014 //  lldb sends:    qSymbol::
4015 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4016 //  lldb sends:    qSymbol::64697370617463685f71756575655f6f666673657473
4017 //  lldb receives: OK
4018 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb does
4019 //     not know
4020 //     the address at this time.  lldb needs to send qSymbol:: again when it has
4021 //     more
4022 //     solibs loaded.
4023 //
4024 //  lldb sends:    qSymbol::
4025 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4026 //  lldb sends:    qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4027 //  lldb receives: OK
4028 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb says
4029 //     that it
4030 //     is at address 0x2bc97554.  Remote gdb stub sends 'OK' indicating that it
4031 //     does not
4032 //     need any more symbols.  lldb does not need to ask again in this session.
4033 
4034 void GDBRemoteCommunicationClient::ServeSymbolLookups(
4035     lldb_private::Process *process) {
4036   // Set to true once we've resolved a symbol to an address for the remote
4037   // stub. If we get an 'OK' response after this, the remote stub doesn't need
4038   // any more symbols and we can stop asking.
4039   bool symbol_response_provided = false;
4040 
4041   // Is this the initial qSymbol:: packet?
4042   bool first_qsymbol_query = true;
4043 
4044   if (m_supports_qSymbol && !m_qSymbol_requests_done) {
4045     Lock lock(*this);
4046     if (lock) {
4047       StreamString packet;
4048       packet.PutCString("qSymbol::");
4049       StringExtractorGDBRemote response;
4050       while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
4051              PacketResult::Success) {
4052         if (response.IsOKResponse()) {
4053           if (symbol_response_provided || first_qsymbol_query) {
4054             m_qSymbol_requests_done = true;
4055           }
4056 
4057           // We are done serving symbols requests
4058           return;
4059         }
4060         first_qsymbol_query = false;
4061 
4062         if (response.IsUnsupportedResponse()) {
4063           // qSymbol is not supported by the current GDB server we are
4064           // connected to
4065           m_supports_qSymbol = false;
4066           return;
4067         } else {
4068           llvm::StringRef response_str(response.GetStringRef());
4069           if (response_str.startswith("qSymbol:")) {
4070             response.SetFilePos(strlen("qSymbol:"));
4071             std::string symbol_name;
4072             if (response.GetHexByteString(symbol_name)) {
4073               if (symbol_name.empty())
4074                 return;
4075 
4076               addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4077               lldb_private::SymbolContextList sc_list;
4078               process->GetTarget().GetImages().FindSymbolsWithNameAndType(
4079                   ConstString(symbol_name), eSymbolTypeAny, sc_list);
4080               if (!sc_list.IsEmpty()) {
4081                 const size_t num_scs = sc_list.GetSize();
4082                 for (size_t sc_idx = 0;
4083                      sc_idx < num_scs &&
4084                      symbol_load_addr == LLDB_INVALID_ADDRESS;
4085                      ++sc_idx) {
4086                   SymbolContext sc;
4087                   if (sc_list.GetContextAtIndex(sc_idx, sc)) {
4088                     if (sc.symbol) {
4089                       switch (sc.symbol->GetType()) {
4090                       case eSymbolTypeInvalid:
4091                       case eSymbolTypeAbsolute:
4092                       case eSymbolTypeUndefined:
4093                       case eSymbolTypeSourceFile:
4094                       case eSymbolTypeHeaderFile:
4095                       case eSymbolTypeObjectFile:
4096                       case eSymbolTypeCommonBlock:
4097                       case eSymbolTypeBlock:
4098                       case eSymbolTypeLocal:
4099                       case eSymbolTypeParam:
4100                       case eSymbolTypeVariable:
4101                       case eSymbolTypeVariableType:
4102                       case eSymbolTypeLineEntry:
4103                       case eSymbolTypeLineHeader:
4104                       case eSymbolTypeScopeBegin:
4105                       case eSymbolTypeScopeEnd:
4106                       case eSymbolTypeAdditional:
4107                       case eSymbolTypeCompiler:
4108                       case eSymbolTypeInstrumentation:
4109                       case eSymbolTypeTrampoline:
4110                         break;
4111 
4112                       case eSymbolTypeCode:
4113                       case eSymbolTypeResolver:
4114                       case eSymbolTypeData:
4115                       case eSymbolTypeRuntime:
4116                       case eSymbolTypeException:
4117                       case eSymbolTypeObjCClass:
4118                       case eSymbolTypeObjCMetaClass:
4119                       case eSymbolTypeObjCIVar:
4120                       case eSymbolTypeReExported:
4121                         symbol_load_addr =
4122                             sc.symbol->GetLoadAddress(&process->GetTarget());
4123                         break;
4124                       }
4125                     }
4126                   }
4127                 }
4128               }
4129               // This is the normal path where our symbol lookup was successful
4130               // and we want to send a packet with the new symbol value and see
4131               // if another lookup needs to be done.
4132 
4133               // Change "packet" to contain the requested symbol value and name
4134               packet.Clear();
4135               packet.PutCString("qSymbol:");
4136               if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
4137                 packet.Printf("%" PRIx64, symbol_load_addr);
4138                 symbol_response_provided = true;
4139               } else {
4140                 symbol_response_provided = false;
4141               }
4142               packet.PutCString(":");
4143               packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4144               continue; // go back to the while loop and send "packet" and wait
4145                         // for another response
4146             }
4147           }
4148         }
4149       }
4150       // If we make it here, the symbol request packet response wasn't valid or
4151       // our symbol lookup failed so we must abort
4152       return;
4153 
4154     } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) {
4155       LLDB_LOGF(log,
4156                 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
4157                 __FUNCTION__);
4158     }
4159   }
4160 }
4161 
4162 StructuredData::Array *
4163 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
4164   if (!m_supported_async_json_packets_is_valid) {
4165     // Query the server for the array of supported asynchronous JSON packets.
4166     m_supported_async_json_packets_is_valid = true;
4167 
4168     Log *log = GetLog(GDBRLog::Process);
4169 
4170     // Poll it now.
4171     StringExtractorGDBRemote response;
4172     if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) ==
4173         PacketResult::Success) {
4174       m_supported_async_json_packets_sp =
4175           StructuredData::ParseJSON(std::string(response.GetStringRef()));
4176       if (m_supported_async_json_packets_sp &&
4177           !m_supported_async_json_packets_sp->GetAsArray()) {
4178         // We were returned something other than a JSON array.  This is
4179         // invalid.  Clear it out.
4180         LLDB_LOGF(log,
4181                   "GDBRemoteCommunicationClient::%s(): "
4182                   "QSupportedAsyncJSONPackets returned invalid "
4183                   "result: %s",
4184                   __FUNCTION__, response.GetStringRef().data());
4185         m_supported_async_json_packets_sp.reset();
4186       }
4187     } else {
4188       LLDB_LOGF(log,
4189                 "GDBRemoteCommunicationClient::%s(): "
4190                 "QSupportedAsyncJSONPackets unsupported",
4191                 __FUNCTION__);
4192     }
4193 
4194     if (log && m_supported_async_json_packets_sp) {
4195       StreamString stream;
4196       m_supported_async_json_packets_sp->Dump(stream);
4197       LLDB_LOGF(log,
4198                 "GDBRemoteCommunicationClient::%s(): supported async "
4199                 "JSON packets: %s",
4200                 __FUNCTION__, stream.GetData());
4201     }
4202   }
4203 
4204   return m_supported_async_json_packets_sp
4205              ? m_supported_async_json_packets_sp->GetAsArray()
4206              : nullptr;
4207 }
4208 
4209 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
4210     llvm::ArrayRef<int32_t> signals) {
4211   // Format packet:
4212   // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
4213   auto range = llvm::make_range(signals.begin(), signals.end());
4214   std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
4215 
4216   StringExtractorGDBRemote response;
4217   auto send_status = SendPacketAndWaitForResponse(packet, response);
4218 
4219   if (send_status != GDBRemoteCommunication::PacketResult::Success)
4220     return Status("Sending QPassSignals packet failed");
4221 
4222   if (response.IsOKResponse()) {
4223     return Status();
4224   } else {
4225     return Status("Unknown error happened during sending QPassSignals packet.");
4226   }
4227 }
4228 
4229 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
4230     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4231   Status error;
4232 
4233   if (type_name.GetLength() == 0) {
4234     error.SetErrorString("invalid type_name argument");
4235     return error;
4236   }
4237 
4238   // Build command: Configure{type_name}: serialized config data.
4239   StreamGDBRemote stream;
4240   stream.PutCString("QConfigure");
4241   stream.PutCString(type_name.GetStringRef());
4242   stream.PutChar(':');
4243   if (config_sp) {
4244     // Gather the plain-text version of the configuration data.
4245     StreamString unescaped_stream;
4246     config_sp->Dump(unescaped_stream);
4247     unescaped_stream.Flush();
4248 
4249     // Add it to the stream in escaped fashion.
4250     stream.PutEscapedBytes(unescaped_stream.GetString().data(),
4251                            unescaped_stream.GetSize());
4252   }
4253   stream.Flush();
4254 
4255   // Send the packet.
4256   StringExtractorGDBRemote response;
4257   auto result = SendPacketAndWaitForResponse(stream.GetString(), response);
4258   if (result == PacketResult::Success) {
4259     // We failed if the config result comes back other than OK.
4260     if (strcmp(response.GetStringRef().data(), "OK") == 0) {
4261       // Okay!
4262       error.Clear();
4263     } else {
4264       error.SetErrorStringWithFormat("configuring StructuredData feature "
4265                                      "%s failed with error %s",
4266                                      type_name.AsCString(),
4267                                      response.GetStringRef().data());
4268     }
4269   } else {
4270     // Can we get more data here on the failure?
4271     error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4272                                    "failed when sending packet: "
4273                                    "PacketResult=%d",
4274                                    type_name.AsCString(), (int)result);
4275   }
4276   return error;
4277 }
4278 
4279 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4280   GDBRemoteClientBase::OnRunPacketSent(first);
4281   m_curr_tid = LLDB_INVALID_THREAD_ID;
4282 }
4283 
4284 bool GDBRemoteCommunicationClient::UsesNativeSignals() {
4285   if (m_uses_native_signals == eLazyBoolCalculate)
4286     GetRemoteQSupported();
4287   if (m_uses_native_signals == eLazyBoolYes)
4288     return true;
4289 
4290   // If the remote didn't indicate native-signal support explicitly,
4291   // check whether it is an old version of lldb-server.
4292   return GetThreadSuffixSupported();
4293 }
4294 
4295 llvm::Expected<int> GDBRemoteCommunicationClient::KillProcess(lldb::pid_t pid) {
4296   StringExtractorGDBRemote response;
4297   GDBRemoteCommunication::ScopedTimeout(*this, seconds(3));
4298 
4299   if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout()) !=
4300       PacketResult::Success)
4301     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4302                                    "failed to send k packet");
4303 
4304   char packet_cmd = response.GetChar(0);
4305   if (packet_cmd == 'W' || packet_cmd == 'X')
4306     return response.GetHexU8();
4307 
4308   return llvm::createStringError(llvm::inconvertibleErrorCode(),
4309                                  "unexpected response to k packet: %s",
4310                                  response.GetStringRef().str().c_str());
4311 }
4312