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