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