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