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