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