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