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