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