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