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