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