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