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