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