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