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