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