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