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