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