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