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