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