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