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