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