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