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