xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp (revision 0f8f0d369d719cf3cb785e294463722f94d05cc0)
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", 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", response, false) ==
738       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.GetString(), response, false) ==
792         PacketResult::Success) {
793       if (response.IsOKResponse())
794         return 0;
795       uint8_t error = response.GetError();
796       if (error)
797         return error;
798     }
799   }
800   return -1;
801 }
802 
803 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
804     char const *name_equal_value) {
805   if (name_equal_value && name_equal_value[0]) {
806     StreamString packet;
807     bool send_hex_encoding = false;
808     for (const char *p = name_equal_value;
809          *p != '\0' && send_hex_encoding == false; ++p) {
810       if (isprint(*p)) {
811         switch (*p) {
812         case '$':
813         case '#':
814         case '*':
815         case '}':
816           send_hex_encoding = true;
817           break;
818         default:
819           break;
820         }
821       } else {
822         // We have non printable characters, lets hex encode this...
823         send_hex_encoding = true;
824       }
825     }
826 
827     StringExtractorGDBRemote response;
828     if (send_hex_encoding) {
829       if (m_supports_QEnvironmentHexEncoded) {
830         packet.PutCString("QEnvironmentHexEncoded:");
831         packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
832         if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
833             PacketResult::Success) {
834           if (response.IsOKResponse())
835             return 0;
836           uint8_t error = response.GetError();
837           if (error)
838             return error;
839           if (response.IsUnsupportedResponse())
840             m_supports_QEnvironmentHexEncoded = false;
841         }
842       }
843 
844     } else if (m_supports_QEnvironment) {
845       packet.Printf("QEnvironment:%s", name_equal_value);
846       if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
847           PacketResult::Success) {
848         if (response.IsOKResponse())
849           return 0;
850         uint8_t error = response.GetError();
851         if (error)
852           return error;
853         if (response.IsUnsupportedResponse())
854           m_supports_QEnvironment = false;
855       }
856     }
857   }
858   return -1;
859 }
860 
861 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
862   if (arch && arch[0]) {
863     StreamString packet;
864     packet.Printf("QLaunchArch:%s", arch);
865     StringExtractorGDBRemote response;
866     if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
867         PacketResult::Success) {
868       if (response.IsOKResponse())
869         return 0;
870       uint8_t error = response.GetError();
871       if (error)
872         return error;
873     }
874   }
875   return -1;
876 }
877 
878 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
879     char const *data, bool *was_supported) {
880   if (data && *data != '\0') {
881     StreamString packet;
882     packet.Printf("QSetProcessEvent:%s", data);
883     StringExtractorGDBRemote response;
884     if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
885         PacketResult::Success) {
886       if (response.IsOKResponse()) {
887         if (was_supported)
888           *was_supported = true;
889         return 0;
890       } else if (response.IsUnsupportedResponse()) {
891         if (was_supported)
892           *was_supported = false;
893         return -1;
894       } else {
895         uint8_t error = response.GetError();
896         if (was_supported)
897           *was_supported = true;
898         if (error)
899           return error;
900       }
901     }
902   }
903   return -1;
904 }
905 
906 bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
907                                                 uint32_t &minor,
908                                                 uint32_t &update) {
909   if (GetHostInfo()) {
910     if (m_os_version_major != UINT32_MAX) {
911       major = m_os_version_major;
912       minor = m_os_version_minor;
913       update = m_os_version_update;
914       return true;
915     }
916   }
917   return false;
918 }
919 
920 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
921   if (GetHostInfo()) {
922     if (!m_os_build.empty()) {
923       s = m_os_build;
924       return true;
925     }
926   }
927   s.clear();
928   return false;
929 }
930 
931 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
932   if (GetHostInfo()) {
933     if (!m_os_kernel.empty()) {
934       s = m_os_kernel;
935       return true;
936     }
937   }
938   s.clear();
939   return false;
940 }
941 
942 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
943   if (GetHostInfo()) {
944     if (!m_hostname.empty()) {
945       s = m_hostname;
946       return true;
947     }
948   }
949   s.clear();
950   return false;
951 }
952 
953 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
954   if (GetHostInfo())
955     return m_host_arch;
956   return ArchSpec();
957 }
958 
959 const lldb_private::ArchSpec &
960 GDBRemoteCommunicationClient::GetProcessArchitecture() {
961   if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
962     GetCurrentProcessInfo();
963   return m_process_arch;
964 }
965 
966 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
967   if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
968     m_gdb_server_name.clear();
969     m_gdb_server_version = 0;
970     m_qGDBServerVersion_is_valid = eLazyBoolNo;
971 
972     StringExtractorGDBRemote response;
973     if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
974         PacketResult::Success) {
975       if (response.IsNormalResponse()) {
976         llvm::StringRef name, value;
977         bool success = false;
978         while (response.GetNameColonValue(name, value)) {
979           if (name.equals("name")) {
980             success = true;
981             m_gdb_server_name = value;
982           } else if (name.equals("version")) {
983             llvm::StringRef major, minor;
984             std::tie(major, minor) = value.split('.');
985             if (!major.getAsInteger(0, m_gdb_server_version))
986               success = true;
987           }
988         }
989         if (success)
990           m_qGDBServerVersion_is_valid = eLazyBoolYes;
991       }
992     }
993   }
994   return m_qGDBServerVersion_is_valid == eLazyBoolYes;
995 }
996 
997 void GDBRemoteCommunicationClient::MaybeEnableCompression(
998     std::vector<std::string> supported_compressions) {
999   CompressionType avail_type = CompressionType::None;
1000   std::string avail_name;
1001 
1002 #if defined(HAVE_LIBCOMPRESSION)
1003   // libcompression is weak linked so test if compression_decode_buffer() is
1004   // available
1005   if (compression_decode_buffer != NULL &&
1006       avail_type == CompressionType::None) {
1007     for (auto compression : supported_compressions) {
1008       if (compression == "lzfse") {
1009         avail_type = CompressionType::LZFSE;
1010         avail_name = compression;
1011         break;
1012       }
1013     }
1014   }
1015 #endif
1016 
1017 #if defined(HAVE_LIBCOMPRESSION)
1018   // libcompression is weak linked so test if compression_decode_buffer() is
1019   // available
1020   if (compression_decode_buffer != NULL &&
1021       avail_type == CompressionType::None) {
1022     for (auto compression : supported_compressions) {
1023       if (compression == "zlib-deflate") {
1024         avail_type = CompressionType::ZlibDeflate;
1025         avail_name = compression;
1026         break;
1027       }
1028     }
1029   }
1030 #endif
1031 
1032 #if defined(HAVE_LIBZ)
1033   if (avail_type == CompressionType::None) {
1034     for (auto compression : supported_compressions) {
1035       if (compression == "zlib-deflate") {
1036         avail_type = CompressionType::ZlibDeflate;
1037         avail_name = compression;
1038         break;
1039       }
1040     }
1041   }
1042 #endif
1043 
1044 #if defined(HAVE_LIBCOMPRESSION)
1045   // libcompression is weak linked so test if compression_decode_buffer() is
1046   // available
1047   if (compression_decode_buffer != NULL &&
1048       avail_type == CompressionType::None) {
1049     for (auto compression : supported_compressions) {
1050       if (compression == "lz4") {
1051         avail_type = CompressionType::LZ4;
1052         avail_name = compression;
1053         break;
1054       }
1055     }
1056   }
1057 #endif
1058 
1059 #if defined(HAVE_LIBCOMPRESSION)
1060   // libcompression is weak linked so test if compression_decode_buffer() is
1061   // available
1062   if (compression_decode_buffer != NULL &&
1063       avail_type == CompressionType::None) {
1064     for (auto compression : supported_compressions) {
1065       if (compression == "lzma") {
1066         avail_type = CompressionType::LZMA;
1067         avail_name = compression;
1068         break;
1069       }
1070     }
1071   }
1072 #endif
1073 
1074   if (avail_type != CompressionType::None) {
1075     StringExtractorGDBRemote response;
1076     std::string packet = "QEnableCompression:type:" + avail_name + ";";
1077     if (SendPacketAndWaitForResponse(packet.c_str(), response, false) !=
1078         PacketResult::Success)
1079       return;
1080 
1081     if (response.IsOKResponse()) {
1082       m_compression_type = avail_type;
1083     }
1084   }
1085 }
1086 
1087 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1088   if (GetGDBServerVersion()) {
1089     if (!m_gdb_server_name.empty())
1090       return m_gdb_server_name.c_str();
1091   }
1092   return NULL;
1093 }
1094 
1095 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1096   if (GetGDBServerVersion())
1097     return m_gdb_server_version;
1098   return 0;
1099 }
1100 
1101 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1102   StringExtractorGDBRemote response;
1103   if (SendPacketAndWaitForResponse("qC", response, false) !=
1104       PacketResult::Success)
1105     return false;
1106 
1107   if (!response.IsNormalResponse())
1108     return false;
1109 
1110   if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1111     tid = response.GetHexMaxU32(true, -1);
1112 
1113   return true;
1114 }
1115 
1116 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1117   Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1118 
1119   if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1120     m_qHostInfo_is_valid = eLazyBoolNo;
1121     StringExtractorGDBRemote response;
1122     if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1123         PacketResult::Success) {
1124       if (response.IsNormalResponse()) {
1125         llvm::StringRef name;
1126         llvm::StringRef value;
1127         uint32_t cpu = LLDB_INVALID_CPUTYPE;
1128         uint32_t sub = 0;
1129         std::string arch_name;
1130         std::string os_name;
1131         std::string vendor_name;
1132         std::string triple;
1133         std::string distribution_id;
1134         uint32_t pointer_byte_size = 0;
1135         ByteOrder byte_order = eByteOrderInvalid;
1136         uint32_t num_keys_decoded = 0;
1137         while (response.GetNameColonValue(name, value)) {
1138           if (name.equals("cputype")) {
1139             // exception type in big endian hex
1140             if (!value.getAsInteger(0, cpu))
1141               ++num_keys_decoded;
1142           } else if (name.equals("cpusubtype")) {
1143             // exception count in big endian hex
1144             if (!value.getAsInteger(0, sub))
1145               ++num_keys_decoded;
1146           } else if (name.equals("arch")) {
1147             arch_name = value;
1148             ++num_keys_decoded;
1149           } else if (name.equals("triple")) {
1150             StringExtractor extractor(value);
1151             extractor.GetHexByteString(triple);
1152             ++num_keys_decoded;
1153           } else if (name.equals("distribution_id")) {
1154             StringExtractor extractor(value);
1155             extractor.GetHexByteString(distribution_id);
1156             ++num_keys_decoded;
1157           } else if (name.equals("os_build")) {
1158             StringExtractor extractor(value);
1159             extractor.GetHexByteString(m_os_build);
1160             ++num_keys_decoded;
1161           } else if (name.equals("hostname")) {
1162             StringExtractor extractor(value);
1163             extractor.GetHexByteString(m_hostname);
1164             ++num_keys_decoded;
1165           } else if (name.equals("os_kernel")) {
1166             StringExtractor extractor(value);
1167             extractor.GetHexByteString(m_os_kernel);
1168             ++num_keys_decoded;
1169           } else if (name.equals("ostype")) {
1170             os_name = value;
1171             ++num_keys_decoded;
1172           } else if (name.equals("vendor")) {
1173             vendor_name = value;
1174             ++num_keys_decoded;
1175           } else if (name.equals("endian")) {
1176             byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1177                              .Case("little", eByteOrderLittle)
1178                              .Case("big", eByteOrderBig)
1179                              .Case("pdp", eByteOrderPDP)
1180                              .Default(eByteOrderInvalid);
1181             if (byte_order != eByteOrderInvalid)
1182               ++num_keys_decoded;
1183           } else if (name.equals("ptrsize")) {
1184             if (!value.getAsInteger(0, pointer_byte_size))
1185               ++num_keys_decoded;
1186           } else if (name.equals("os_version") ||
1187                      name.equals(
1188                          "version")) // Older debugserver binaries used the
1189                                      // "version" key instead of
1190                                      // "os_version"...
1191           {
1192             Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1193                                   m_os_version_update);
1194             if (m_os_version_major != UINT32_MAX)
1195               ++num_keys_decoded;
1196           } else if (name.equals("watchpoint_exceptions_received")) {
1197             m_watchpoints_trigger_after_instruction =
1198                 llvm::StringSwitch<LazyBool>(value)
1199                     .Case("before", eLazyBoolNo)
1200                     .Case("after", eLazyBoolYes)
1201                     .Default(eLazyBoolCalculate);
1202             if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1203               ++num_keys_decoded;
1204           } else if (name.equals("default_packet_timeout")) {
1205             if (!value.getAsInteger(0, m_default_packet_timeout)) {
1206               SetPacketTimeout(m_default_packet_timeout);
1207               ++num_keys_decoded;
1208             }
1209           }
1210         }
1211 
1212         if (num_keys_decoded > 0)
1213           m_qHostInfo_is_valid = eLazyBoolYes;
1214 
1215         if (triple.empty()) {
1216           if (arch_name.empty()) {
1217             if (cpu != LLDB_INVALID_CPUTYPE) {
1218               m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1219               if (pointer_byte_size) {
1220                 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1221               }
1222               if (byte_order != eByteOrderInvalid) {
1223                 assert(byte_order == m_host_arch.GetByteOrder());
1224               }
1225 
1226               if (!vendor_name.empty())
1227                 m_host_arch.GetTriple().setVendorName(
1228                     llvm::StringRef(vendor_name));
1229               if (!os_name.empty())
1230                 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1231             }
1232           } else {
1233             std::string triple;
1234             triple += arch_name;
1235             if (!vendor_name.empty() || !os_name.empty()) {
1236               triple += '-';
1237               if (vendor_name.empty())
1238                 triple += "unknown";
1239               else
1240                 triple += vendor_name;
1241               triple += '-';
1242               if (os_name.empty())
1243                 triple += "unknown";
1244               else
1245                 triple += os_name;
1246             }
1247             m_host_arch.SetTriple(triple.c_str());
1248 
1249             llvm::Triple &host_triple = m_host_arch.GetTriple();
1250             if (host_triple.getVendor() == llvm::Triple::Apple &&
1251                 host_triple.getOS() == llvm::Triple::Darwin) {
1252               switch (m_host_arch.GetMachine()) {
1253               case llvm::Triple::aarch64:
1254               case llvm::Triple::arm:
1255               case llvm::Triple::thumb:
1256                 host_triple.setOS(llvm::Triple::IOS);
1257                 break;
1258               default:
1259                 host_triple.setOS(llvm::Triple::MacOSX);
1260                 break;
1261               }
1262             }
1263             if (pointer_byte_size) {
1264               assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1265             }
1266             if (byte_order != eByteOrderInvalid) {
1267               assert(byte_order == m_host_arch.GetByteOrder());
1268             }
1269           }
1270         } else {
1271           m_host_arch.SetTriple(triple.c_str());
1272           if (pointer_byte_size) {
1273             assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1274           }
1275           if (byte_order != eByteOrderInvalid) {
1276             assert(byte_order == m_host_arch.GetByteOrder());
1277           }
1278 
1279           if (log)
1280             log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1281                         "architecture as %s, triple as %s from triple text %s",
1282                         __FUNCTION__, m_host_arch.GetArchitectureName()
1283                                           ? m_host_arch.GetArchitectureName()
1284                                           : "<null-arch-name>",
1285                         m_host_arch.GetTriple().getTriple().c_str(),
1286                         triple.c_str());
1287         }
1288         if (!distribution_id.empty())
1289           m_host_arch.SetDistributionId(distribution_id.c_str());
1290       }
1291     }
1292   }
1293   return m_qHostInfo_is_valid == eLazyBoolYes;
1294 }
1295 
1296 int GDBRemoteCommunicationClient::SendAttach(
1297     lldb::pid_t pid, StringExtractorGDBRemote &response) {
1298   if (pid != LLDB_INVALID_PROCESS_ID) {
1299     char packet[64];
1300     const int packet_len =
1301         ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1302     UNUSED_IF_ASSERT_DISABLED(packet_len);
1303     assert(packet_len < (int)sizeof(packet));
1304     if (SendPacketAndWaitForResponse(packet, response, false) ==
1305         PacketResult::Success) {
1306       if (response.IsErrorResponse())
1307         return response.GetError();
1308       return 0;
1309     }
1310   }
1311   return -1;
1312 }
1313 
1314 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1315                                                         size_t data_len) {
1316   StreamString packet;
1317   packet.PutCString("I");
1318   packet.PutBytesAsRawHex8(data, data_len);
1319   StringExtractorGDBRemote response;
1320   if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1321       PacketResult::Success) {
1322     return 0;
1323   }
1324   return response.GetError();
1325 }
1326 
1327 const lldb_private::ArchSpec &
1328 GDBRemoteCommunicationClient::GetHostArchitecture() {
1329   if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1330     GetHostInfo();
1331   return m_host_arch;
1332 }
1333 
1334 uint32_t GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1335   if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1336     GetHostInfo();
1337   return m_default_packet_timeout;
1338 }
1339 
1340 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1341                                                     uint32_t permissions) {
1342   if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1343     m_supports_alloc_dealloc_memory = eLazyBoolYes;
1344     char packet[64];
1345     const int packet_len = ::snprintf(
1346         packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1347         permissions & lldb::ePermissionsReadable ? "r" : "",
1348         permissions & lldb::ePermissionsWritable ? "w" : "",
1349         permissions & lldb::ePermissionsExecutable ? "x" : "");
1350     assert(packet_len < (int)sizeof(packet));
1351     UNUSED_IF_ASSERT_DISABLED(packet_len);
1352     StringExtractorGDBRemote response;
1353     if (SendPacketAndWaitForResponse(packet, response, false) ==
1354         PacketResult::Success) {
1355       if (response.IsUnsupportedResponse())
1356         m_supports_alloc_dealloc_memory = eLazyBoolNo;
1357       else if (!response.IsErrorResponse())
1358         return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1359     } else {
1360       m_supports_alloc_dealloc_memory = eLazyBoolNo;
1361     }
1362   }
1363   return LLDB_INVALID_ADDRESS;
1364 }
1365 
1366 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1367   if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1368     m_supports_alloc_dealloc_memory = eLazyBoolYes;
1369     char packet[64];
1370     const int packet_len =
1371         ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1372     assert(packet_len < (int)sizeof(packet));
1373     UNUSED_IF_ASSERT_DISABLED(packet_len);
1374     StringExtractorGDBRemote response;
1375     if (SendPacketAndWaitForResponse(packet, response, false) ==
1376         PacketResult::Success) {
1377       if (response.IsUnsupportedResponse())
1378         m_supports_alloc_dealloc_memory = eLazyBoolNo;
1379       else if (response.IsOKResponse())
1380         return true;
1381     } else {
1382       m_supports_alloc_dealloc_memory = eLazyBoolNo;
1383     }
1384   }
1385   return false;
1386 }
1387 
1388 Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1389   Error error;
1390 
1391   if (keep_stopped) {
1392     if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1393       char packet[64];
1394       const int packet_len =
1395           ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1396       assert(packet_len < (int)sizeof(packet));
1397       UNUSED_IF_ASSERT_DISABLED(packet_len);
1398       StringExtractorGDBRemote response;
1399       if (SendPacketAndWaitForResponse(packet, response, false) ==
1400               PacketResult::Success &&
1401           response.IsOKResponse()) {
1402         m_supports_detach_stay_stopped = eLazyBoolYes;
1403       } else {
1404         m_supports_detach_stay_stopped = eLazyBoolNo;
1405       }
1406     }
1407 
1408     if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1409       error.SetErrorString("Stays stopped not supported by this target.");
1410       return error;
1411     } else {
1412       StringExtractorGDBRemote response;
1413       PacketResult packet_result =
1414           SendPacketAndWaitForResponse("D1", response, false);
1415       if (packet_result != PacketResult::Success)
1416         error.SetErrorString("Sending extended disconnect packet failed.");
1417     }
1418   } else {
1419     StringExtractorGDBRemote response;
1420     PacketResult packet_result =
1421         SendPacketAndWaitForResponse("D", response, false);
1422     if (packet_result != PacketResult::Success)
1423       error.SetErrorString("Sending disconnect packet failed.");
1424   }
1425   return error;
1426 }
1427 
1428 Error GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1429     lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1430   Error error;
1431   region_info.Clear();
1432 
1433   if (m_supports_memory_region_info != eLazyBoolNo) {
1434     m_supports_memory_region_info = eLazyBoolYes;
1435     char packet[64];
1436     const int packet_len = ::snprintf(
1437         packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1438     assert(packet_len < (int)sizeof(packet));
1439     UNUSED_IF_ASSERT_DISABLED(packet_len);
1440     StringExtractorGDBRemote response;
1441     if (SendPacketAndWaitForResponse(packet, 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     UNUSED_IF_ASSERT_DISABLED(packet_len);
1534     StringExtractorGDBRemote response;
1535     if (SendPacketAndWaitForResponse(packet, response, false) ==
1536         PacketResult::Success) {
1537       m_supports_watchpoint_support_info = eLazyBoolYes;
1538       llvm::StringRef name;
1539       llvm::StringRef value;
1540       while (response.GetNameColonValue(name, value)) {
1541         if (name.equals("num")) {
1542           value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1543           num = m_num_supported_hardware_watchpoints;
1544         }
1545       }
1546     } else {
1547       m_supports_watchpoint_support_info = eLazyBoolNo;
1548     }
1549   }
1550 
1551   if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1552     error.SetErrorString("qWatchpointSupportInfo is not supported");
1553   }
1554   return error;
1555 }
1556 
1557 lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1558     uint32_t &num, bool &after, const ArchSpec &arch) {
1559   Error error(GetWatchpointSupportInfo(num));
1560   if (error.Success())
1561     error = GetWatchpointsTriggerAfterInstruction(after, arch);
1562   return error;
1563 }
1564 
1565 lldb_private::Error
1566 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1567     bool &after, const ArchSpec &arch) {
1568   Error error;
1569   llvm::Triple::ArchType atype = arch.GetMachine();
1570 
1571   // we assume watchpoints will happen after running the relevant opcode
1572   // and we only want to override this behavior if we have explicitly
1573   // received a qHostInfo telling us otherwise
1574   if (m_qHostInfo_is_valid != eLazyBoolYes) {
1575     // On targets like MIPS, watchpoint exceptions are always generated
1576     // before the instruction is executed. The connected target may not
1577     // support qHostInfo or qWatchpointSupportInfo packets.
1578     if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1579         atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1580       after = false;
1581     else
1582       after = true;
1583   } else {
1584     // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1585     // if it is not calculated before.
1586     if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1587         (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1588          atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1589       m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1590 
1591     after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1592   }
1593   return error;
1594 }
1595 
1596 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1597   if (file_spec) {
1598     std::string path{file_spec.GetPath(false)};
1599     StreamString packet;
1600     packet.PutCString("QSetSTDIN:");
1601     packet.PutCStringAsRawHex8(path.c_str());
1602 
1603     StringExtractorGDBRemote response;
1604     if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1605         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.GetString(), response, false) ==
1625         PacketResult::Success) {
1626       if (response.IsOKResponse())
1627         return 0;
1628       uint8_t error = response.GetError();
1629       if (error)
1630         return error;
1631     }
1632   }
1633   return -1;
1634 }
1635 
1636 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1637   if (file_spec) {
1638     std::string path{file_spec.GetPath(false)};
1639     StreamString packet;
1640     packet.PutCString("QSetSTDERR:");
1641     packet.PutCStringAsRawHex8(path.c_str());
1642 
1643     StringExtractorGDBRemote response;
1644     if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1645         PacketResult::Success) {
1646       if (response.IsOKResponse())
1647         return 0;
1648       uint8_t error = response.GetError();
1649       if (error)
1650         return error;
1651     }
1652   }
1653   return -1;
1654 }
1655 
1656 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1657   StringExtractorGDBRemote response;
1658   if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1659       PacketResult::Success) {
1660     if (response.IsUnsupportedResponse())
1661       return false;
1662     if (response.IsErrorResponse())
1663       return false;
1664     std::string cwd;
1665     response.GetHexByteString(cwd);
1666     working_dir.SetFile(cwd, false, GetHostArchitecture());
1667     return !cwd.empty();
1668   }
1669   return false;
1670 }
1671 
1672 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1673   if (working_dir) {
1674     std::string path{working_dir.GetPath(false)};
1675     StreamString packet;
1676     packet.PutCString("QSetWorkingDir:");
1677     packet.PutCStringAsRawHex8(path.c_str());
1678 
1679     StringExtractorGDBRemote response;
1680     if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1681         PacketResult::Success) {
1682       if (response.IsOKResponse())
1683         return 0;
1684       uint8_t error = response.GetError();
1685       if (error)
1686         return error;
1687     }
1688   }
1689   return -1;
1690 }
1691 
1692 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1693   char packet[32];
1694   const int packet_len =
1695       ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1696   assert(packet_len < (int)sizeof(packet));
1697   UNUSED_IF_ASSERT_DISABLED(packet_len);
1698   StringExtractorGDBRemote response;
1699   if (SendPacketAndWaitForResponse(packet, response, false) ==
1700       PacketResult::Success) {
1701     if (response.IsOKResponse())
1702       return 0;
1703     uint8_t error = response.GetError();
1704     if (error)
1705       return error;
1706   }
1707   return -1;
1708 }
1709 
1710 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1711   char packet[32];
1712   const int packet_len = ::snprintf(packet, sizeof(packet),
1713                                     "QSetDetachOnError:%i", enable ? 1 : 0);
1714   assert(packet_len < (int)sizeof(packet));
1715   UNUSED_IF_ASSERT_DISABLED(packet_len);
1716   StringExtractorGDBRemote response;
1717   if (SendPacketAndWaitForResponse(packet, response, false) ==
1718       PacketResult::Success) {
1719     if (response.IsOKResponse())
1720       return 0;
1721     uint8_t error = response.GetError();
1722     if (error)
1723       return error;
1724   }
1725   return -1;
1726 }
1727 
1728 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1729     StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1730   if (response.IsNormalResponse()) {
1731     llvm::StringRef name;
1732     llvm::StringRef value;
1733     StringExtractor extractor;
1734 
1735     uint32_t cpu = LLDB_INVALID_CPUTYPE;
1736     uint32_t sub = 0;
1737     std::string vendor;
1738     std::string os_type;
1739 
1740     while (response.GetNameColonValue(name, value)) {
1741       if (name.equals("pid")) {
1742         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1743         value.getAsInteger(0, pid);
1744         process_info.SetProcessID(pid);
1745       } else if (name.equals("ppid")) {
1746         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1747         value.getAsInteger(0, pid);
1748         process_info.SetParentProcessID(pid);
1749       } else if (name.equals("uid")) {
1750         uint32_t uid = UINT32_MAX;
1751         value.getAsInteger(0, uid);
1752         process_info.SetUserID(uid);
1753       } else if (name.equals("euid")) {
1754         uint32_t uid = UINT32_MAX;
1755         value.getAsInteger(0, uid);
1756         process_info.SetEffectiveGroupID(uid);
1757       } else if (name.equals("gid")) {
1758         uint32_t gid = UINT32_MAX;
1759         value.getAsInteger(0, gid);
1760         process_info.SetGroupID(gid);
1761       } else if (name.equals("egid")) {
1762         uint32_t gid = UINT32_MAX;
1763         value.getAsInteger(0, gid);
1764         process_info.SetEffectiveGroupID(gid);
1765       } else if (name.equals("triple")) {
1766         StringExtractor extractor(value);
1767         std::string triple;
1768         extractor.GetHexByteString(triple);
1769         process_info.GetArchitecture().SetTriple(triple.c_str());
1770       } else if (name.equals("name")) {
1771         StringExtractor extractor(value);
1772         // The process name from ASCII hex bytes since we can't
1773         // control the characters in a process name
1774         std::string name;
1775         extractor.GetHexByteString(name);
1776         process_info.GetExecutableFile().SetFile(name.c_str(), false);
1777       } else if (name.equals("cputype")) {
1778         value.getAsInteger(0, cpu);
1779       } else if (name.equals("cpusubtype")) {
1780         value.getAsInteger(0, sub);
1781       } else if (name.equals("vendor")) {
1782         vendor = value;
1783       } else if (name.equals("ostype")) {
1784         os_type = value;
1785       }
1786     }
1787 
1788     if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1789       if (vendor == "apple") {
1790         process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1791                                                        sub);
1792         process_info.GetArchitecture().GetTriple().setVendorName(
1793             llvm::StringRef(vendor));
1794         process_info.GetArchitecture().GetTriple().setOSName(
1795             llvm::StringRef(os_type));
1796       }
1797     }
1798 
1799     if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1800       return true;
1801   }
1802   return false;
1803 }
1804 
1805 bool GDBRemoteCommunicationClient::GetProcessInfo(
1806     lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1807   process_info.Clear();
1808 
1809   if (m_supports_qProcessInfoPID) {
1810     char packet[32];
1811     const int packet_len =
1812         ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1813     assert(packet_len < (int)sizeof(packet));
1814     UNUSED_IF_ASSERT_DISABLED(packet_len);
1815     StringExtractorGDBRemote response;
1816     if (SendPacketAndWaitForResponse(packet, 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.GetString(), response, false) ==
2023         PacketResult::Success) {
2024       do {
2025         ProcessInstanceInfo process_info;
2026         if (!DecodeProcessInfoResponse(response, process_info))
2027           break;
2028         process_infos.Append(process_info);
2029         response.GetStringRef().clear();
2030         response.SetFilePos(0);
2031       } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2032                PacketResult::Success);
2033     } else {
2034       m_supports_qfProcessInfo = false;
2035       return 0;
2036     }
2037   }
2038   return process_infos.GetSize();
2039 }
2040 
2041 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2042                                                std::string &name) {
2043   if (m_supports_qUserName) {
2044     char packet[32];
2045     const int packet_len =
2046         ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2047     assert(packet_len < (int)sizeof(packet));
2048     UNUSED_IF_ASSERT_DISABLED(packet_len);
2049     StringExtractorGDBRemote response;
2050     if (SendPacketAndWaitForResponse(packet, response, false) ==
2051         PacketResult::Success) {
2052       if (response.IsNormalResponse()) {
2053         // Make sure we parsed the right number of characters. The response is
2054         // the hex encoded user name and should make up the entire packet.
2055         // If there are any non-hex ASCII bytes, the length won't match below..
2056         if (response.GetHexByteString(name) * 2 ==
2057             response.GetStringRef().size())
2058           return true;
2059       }
2060     } else {
2061       m_supports_qUserName = false;
2062       return false;
2063     }
2064   }
2065   return false;
2066 }
2067 
2068 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2069                                                 std::string &name) {
2070   if (m_supports_qGroupName) {
2071     char packet[32];
2072     const int packet_len =
2073         ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2074     assert(packet_len < (int)sizeof(packet));
2075     UNUSED_IF_ASSERT_DISABLED(packet_len);
2076     StringExtractorGDBRemote response;
2077     if (SendPacketAndWaitForResponse(packet, 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   UNUSED_IF_ASSERT_DISABLED(packet_len);
2102 
2103   StringExtractorGDBRemote response;
2104   // Send to target
2105   if (SendPacketAndWaitForResponse(packet, response, false) ==
2106       PacketResult::Success)
2107     if (response.IsOKResponse())
2108       return true;
2109 
2110   // Failed or not supported
2111   return false;
2112 }
2113 
2114 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2115                                 uint32_t recv_size) {
2116   packet.Clear();
2117   packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2118   uint32_t bytes_left = send_size;
2119   while (bytes_left > 0) {
2120     if (bytes_left >= 26) {
2121       packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2122       bytes_left -= 26;
2123     } else {
2124       packet.Printf("%*.*s;", bytes_left, bytes_left,
2125                     "abcdefghijklmnopqrstuvwxyz");
2126       bytes_left = 0;
2127     }
2128   }
2129 }
2130 
2131 template <typename T> T calculate_standard_deviation(const std::vector<T> &v) {
2132   T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2133   T mean = sum / (T)v.size();
2134   T accum = T(0);
2135   std::for_each(std::begin(v), std::end(v), [&](const T d) {
2136     T delta = d - mean;
2137     accum += delta * delta;
2138   });
2139 
2140   T stdev = sqrt(accum / (v.size() - 1));
2141   return stdev;
2142 }
2143 
2144 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2145                                                    uint32_t max_send,
2146                                                    uint32_t max_recv, bool json,
2147                                                    Stream &strm) {
2148   uint32_t i;
2149   TimeValue start_time, end_time;
2150   uint64_t total_time_nsec;
2151   if (SendSpeedTestPacket(0, 0)) {
2152     StreamString packet;
2153     if (json)
2154       strm.Printf("{ \"packet_speeds\" : {\n    \"num_packets\" : %u,\n    "
2155                   "\"results\" : [",
2156                   num_packets);
2157     else
2158       strm.Printf("Testing sending %u packets of various sizes:\n",
2159                   num_packets);
2160     strm.Flush();
2161 
2162     uint32_t result_idx = 0;
2163     uint32_t send_size;
2164     std::vector<float> packet_times;
2165 
2166     for (send_size = 0; send_size <= max_send;
2167          send_size ? send_size *= 2 : send_size = 4) {
2168       for (uint32_t recv_size = 0; recv_size <= max_recv;
2169            recv_size ? recv_size *= 2 : recv_size = 4) {
2170         MakeSpeedTestPacket(packet, send_size, recv_size);
2171 
2172         packet_times.clear();
2173         // Test how long it takes to send 'num_packets' packets
2174         start_time = TimeValue::Now();
2175         for (i = 0; i < num_packets; ++i) {
2176           TimeValue packet_start_time = TimeValue::Now();
2177           StringExtractorGDBRemote response;
2178           SendPacketAndWaitForResponse(packet.GetString(), 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.GetString(), response, false);
2245           bytes_read += recv_size;
2246           ++packet_count;
2247         }
2248         end_time = TimeValue::Now();
2249         total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() -
2250                           start_time.GetAsNanoSecondsSinceJan1_1970();
2251         float mb_second = ((((float)k_recv_amount) / (float)total_time_nsec) *
2252                            (float)TimeValue::NanoSecPerSec) /
2253                           (1024.0 * 1024.0);
2254         float packets_per_second =
2255             (((float)packet_count) / (float)total_time_nsec) *
2256             (float)TimeValue::NanoSecPerSec;
2257         float total_ms =
2258             (float)total_time_nsec / (float)TimeValue::NanoSecPerMilliSec;
2259         float average_ms_per_packet = total_ms / packet_count;
2260 
2261         if (json) {
2262           strm.Printf("%s\n     {\"send_size\" : %6" PRIu32
2263                       ", \"recv_size\" : %6" PRIu32
2264                       ", \"total_time_nsec\" : %12" PRIu64 " }",
2265                       result_idx > 0 ? "," : "", send_size, recv_size,
2266                       total_time_nsec);
2267           ++result_idx;
2268         } else {
2269           strm.Printf("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to "
2270                       "receive %2.1fMB in %" PRIu64 ".%9.9" PRIu64
2271                       " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per "
2272                       "packet)\n",
2273                       send_size, recv_size, packet_count, k_recv_amount_mb,
2274                       total_time_nsec / TimeValue::NanoSecPerSec,
2275                       total_time_nsec % TimeValue::NanoSecPerSec, mb_second,
2276                       packets_per_second, average_ms_per_packet);
2277         }
2278         strm.Flush();
2279       }
2280     }
2281     if (json)
2282       strm.Printf("\n    ]\n  }\n}\n");
2283     else
2284       strm.EOL();
2285   }
2286 }
2287 
2288 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2289                                                        uint32_t recv_size) {
2290   StreamString packet;
2291   packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2292   uint32_t bytes_left = send_size;
2293   while (bytes_left > 0) {
2294     if (bytes_left >= 26) {
2295       packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2296       bytes_left -= 26;
2297     } else {
2298       packet.Printf("%*.*s;", bytes_left, bytes_left,
2299                     "abcdefghijklmnopqrstuvwxyz");
2300       bytes_left = 0;
2301     }
2302   }
2303 
2304   StringExtractorGDBRemote response;
2305   return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2306          PacketResult::Success;
2307 }
2308 
2309 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2310     const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2311     std::string &socket_name) {
2312   pid = LLDB_INVALID_PROCESS_ID;
2313   port = 0;
2314   socket_name.clear();
2315 
2316   StringExtractorGDBRemote response;
2317   StreamString stream;
2318   stream.PutCString("qLaunchGDBServer;");
2319   std::string hostname;
2320   if (remote_accept_hostname && remote_accept_hostname[0])
2321     hostname = remote_accept_hostname;
2322   else {
2323     if (HostInfo::GetHostname(hostname)) {
2324       // Make the GDB server we launch only accept connections from this host
2325       stream.Printf("host:%s;", hostname.c_str());
2326     } else {
2327       // Make the GDB server we launch accept connections from any host since we
2328       // can't figure out the hostname
2329       stream.Printf("host:*;");
2330     }
2331   }
2332   // give the process a few seconds to startup
2333   GDBRemoteCommunication::ScopedTimeout timeout(*this, 10);
2334 
2335   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2336       PacketResult::Success) {
2337     llvm::StringRef name;
2338     llvm::StringRef value;
2339     while (response.GetNameColonValue(name, value)) {
2340       if (name.equals("port"))
2341         value.getAsInteger(0, port);
2342       else if (name.equals("pid"))
2343         value.getAsInteger(0, pid);
2344       else if (name.compare("socket_name") == 0) {
2345         StringExtractor extractor(value);
2346         extractor.GetHexByteString(socket_name);
2347       }
2348     }
2349     return true;
2350   }
2351   return false;
2352 }
2353 
2354 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2355     std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2356   connection_urls.clear();
2357 
2358   StringExtractorGDBRemote response;
2359   if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2360       PacketResult::Success)
2361     return 0;
2362 
2363   StructuredData::ObjectSP data =
2364       StructuredData::ParseJSON(response.GetStringRef());
2365   if (!data)
2366     return 0;
2367 
2368   StructuredData::Array *array = data->GetAsArray();
2369   if (!array)
2370     return 0;
2371 
2372   for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2373     StructuredData::Dictionary *element = nullptr;
2374     if (!array->GetItemAtIndexAsDictionary(i, element))
2375       continue;
2376 
2377     uint16_t port = 0;
2378     if (StructuredData::ObjectSP port_osp =
2379             element->GetValueForKey(llvm::StringRef("port")))
2380       port = port_osp->GetIntegerValue(0);
2381 
2382     std::string socket_name;
2383     if (StructuredData::ObjectSP socket_name_osp =
2384             element->GetValueForKey(llvm::StringRef("socket_name")))
2385       socket_name = socket_name_osp->GetStringValue();
2386 
2387     if (port != 0 || !socket_name.empty())
2388       connection_urls.emplace_back(port, socket_name);
2389   }
2390   return connection_urls.size();
2391 }
2392 
2393 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2394   StreamString stream;
2395   stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2396 
2397   StringExtractorGDBRemote response;
2398   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2399       PacketResult::Success) {
2400     if (response.IsOKResponse())
2401       return true;
2402   }
2403   return false;
2404 }
2405 
2406 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2407   if (m_curr_tid == tid)
2408     return true;
2409 
2410   char packet[32];
2411   int packet_len;
2412   if (tid == UINT64_MAX)
2413     packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2414   else
2415     packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2416   assert(packet_len + 1 < (int)sizeof(packet));
2417   UNUSED_IF_ASSERT_DISABLED(packet_len);
2418   StringExtractorGDBRemote response;
2419   if (SendPacketAndWaitForResponse(packet, response, false) ==
2420       PacketResult::Success) {
2421     if (response.IsOKResponse()) {
2422       m_curr_tid = tid;
2423       return true;
2424     }
2425 
2426     /*
2427      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2428      * Hg packet.
2429      * The reply from '?' packet could be as simple as 'S05'. There is no packet
2430      * which can
2431      * give us pid and/or tid. Assume pid=tid=1 in such cases.
2432     */
2433     if (response.IsUnsupportedResponse() && IsConnected()) {
2434       m_curr_tid = 1;
2435       return true;
2436     }
2437   }
2438   return false;
2439 }
2440 
2441 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2442   if (m_curr_tid_run == tid)
2443     return true;
2444 
2445   char packet[32];
2446   int packet_len;
2447   if (tid == UINT64_MAX)
2448     packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2449   else
2450     packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2451 
2452   assert(packet_len + 1 < (int)sizeof(packet));
2453   UNUSED_IF_ASSERT_DISABLED(packet_len);
2454   StringExtractorGDBRemote response;
2455   if (SendPacketAndWaitForResponse(packet, response, false) ==
2456       PacketResult::Success) {
2457     if (response.IsOKResponse()) {
2458       m_curr_tid_run = tid;
2459       return true;
2460     }
2461 
2462     /*
2463      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2464      * Hc packet.
2465      * The reply from '?' packet could be as simple as 'S05'. There is no packet
2466      * which can
2467      * give us pid and/or tid. Assume pid=tid=1 in such cases.
2468     */
2469     if (response.IsUnsupportedResponse() && IsConnected()) {
2470       m_curr_tid_run = 1;
2471       return true;
2472     }
2473   }
2474   return false;
2475 }
2476 
2477 bool GDBRemoteCommunicationClient::GetStopReply(
2478     StringExtractorGDBRemote &response) {
2479   if (SendPacketAndWaitForResponse("?", response, false) ==
2480       PacketResult::Success)
2481     return response.IsNormalResponse();
2482   return false;
2483 }
2484 
2485 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2486     lldb::tid_t tid, StringExtractorGDBRemote &response) {
2487   if (m_supports_qThreadStopInfo) {
2488     char packet[256];
2489     int packet_len =
2490         ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2491     assert(packet_len < (int)sizeof(packet));
2492     UNUSED_IF_ASSERT_DISABLED(packet_len);
2493     if (SendPacketAndWaitForResponse(packet, 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   UNUSED_IF_ASSERT_DISABLED(packet_len);
2526   StringExtractorGDBRemote response;
2527   // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2528   // or "" (unsupported)
2529   response.SetResponseValidatorToOKErrorNotSupported();
2530   // Try to send the breakpoint packet, and check that it was correctly sent
2531   if (SendPacketAndWaitForResponse(packet, response, true) ==
2532       PacketResult::Success) {
2533     // Receive and OK packet when the breakpoint successfully placed
2534     if (response.IsOKResponse())
2535       return 0;
2536 
2537     // Error while setting breakpoint, send back specific error
2538     if (response.IsErrorResponse())
2539       return response.GetError();
2540 
2541     // Empty packet informs us that breakpoint is not supported
2542     if (response.IsUnsupportedResponse()) {
2543       // Disable this breakpoint type since it is unsupported
2544       switch (type) {
2545       case eBreakpointSoftware:
2546         m_supports_z0 = false;
2547         break;
2548       case eBreakpointHardware:
2549         m_supports_z1 = false;
2550         break;
2551       case eWatchpointWrite:
2552         m_supports_z2 = false;
2553         break;
2554       case eWatchpointRead:
2555         m_supports_z3 = false;
2556         break;
2557       case eWatchpointReadWrite:
2558         m_supports_z4 = false;
2559         break;
2560       case eStoppointInvalid:
2561         return UINT8_MAX;
2562       }
2563     }
2564   }
2565   // Signal generic failure
2566   return UINT8_MAX;
2567 }
2568 
2569 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2570     std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2571   thread_ids.clear();
2572 
2573   Lock lock(*this, false);
2574   if (lock) {
2575     sequence_mutex_unavailable = false;
2576     StringExtractorGDBRemote response;
2577 
2578     PacketResult packet_result;
2579     for (packet_result =
2580              SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2581          packet_result == PacketResult::Success && response.IsNormalResponse();
2582          packet_result =
2583              SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2584       char ch = response.GetChar();
2585       if (ch == 'l')
2586         break;
2587       if (ch == 'm') {
2588         do {
2589           tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2590 
2591           if (tid != LLDB_INVALID_THREAD_ID) {
2592             thread_ids.push_back(tid);
2593           }
2594           ch = response.GetChar(); // Skip the command separator
2595         } while (ch == ',');       // Make sure we got a comma separator
2596       }
2597     }
2598 
2599     /*
2600      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2601      * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2602      * could
2603      * be as simple as 'S05'. There is no packet which can give us pid and/or
2604      * tid.
2605      * Assume pid=tid=1 in such cases.
2606     */
2607     if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2608         IsConnected()) {
2609       thread_ids.push_back(1);
2610     }
2611   } else {
2612 #if defined(LLDB_CONFIGURATION_DEBUG)
2613 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the
2614 // sequence mutex");
2615 #else
2616     Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2617                                                            GDBR_LOG_PACKETS));
2618     if (log)
2619       log->Printf("error: failed to get packet sequence mutex, not sending "
2620                   "packet 'qfThreadInfo'");
2621 #endif
2622     sequence_mutex_unavailable = true;
2623   }
2624   return thread_ids.size();
2625 }
2626 
2627 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2628   StringExtractorGDBRemote response;
2629   if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2630           PacketResult::Success ||
2631       !response.IsNormalResponse())
2632     return LLDB_INVALID_ADDRESS;
2633   return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2634 }
2635 
2636 lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2637     const char *command, // Shouldn't be NULL
2638     const FileSpec &
2639         working_dir, // Pass empty FileSpec to use the current working directory
2640     int *status_ptr, // Pass NULL if you don't want the process exit status
2641     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
2642                      // process to exit
2643     std::string
2644         *command_output, // Pass NULL if you don't want the command output
2645     uint32_t
2646         timeout_sec) // Timeout in seconds to wait for shell program to finish
2647 {
2648   lldb_private::StreamString stream;
2649   stream.PutCString("qPlatform_shell:");
2650   stream.PutBytesAsRawHex8(command, strlen(command));
2651   stream.PutChar(',');
2652   stream.PutHex32(timeout_sec);
2653   if (working_dir) {
2654     std::string path{working_dir.GetPath(false)};
2655     stream.PutChar(',');
2656     stream.PutCStringAsRawHex8(path.c_str());
2657   }
2658   StringExtractorGDBRemote response;
2659   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2660       PacketResult::Success) {
2661     if (response.GetChar() != 'F')
2662       return Error("malformed reply");
2663     if (response.GetChar() != ',')
2664       return Error("malformed reply");
2665     uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2666     if (exitcode == UINT32_MAX)
2667       return Error("unable to run remote process");
2668     else if (status_ptr)
2669       *status_ptr = exitcode;
2670     if (response.GetChar() != ',')
2671       return Error("malformed reply");
2672     uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2673     if (signo_ptr)
2674       *signo_ptr = signo;
2675     if (response.GetChar() != ',')
2676       return Error("malformed reply");
2677     std::string output;
2678     response.GetEscapedBinaryData(output);
2679     if (command_output)
2680       command_output->assign(output);
2681     return Error();
2682   }
2683   return Error("unable to send packet");
2684 }
2685 
2686 Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2687                                                   uint32_t file_permissions) {
2688   std::string path{file_spec.GetPath(false)};
2689   lldb_private::StreamString stream;
2690   stream.PutCString("qPlatform_mkdir:");
2691   stream.PutHex32(file_permissions);
2692   stream.PutChar(',');
2693   stream.PutCStringAsRawHex8(path.c_str());
2694   const char *packet = stream.GetData();
2695   StringExtractorGDBRemote response;
2696 
2697   if (SendPacketAndWaitForResponse(packet, response, false) !=
2698       PacketResult::Success)
2699     return Error("failed to send '%s' packet", packet);
2700 
2701   if (response.GetChar() != 'F')
2702     return Error("invalid response to '%s' packet", packet);
2703 
2704   return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2705 }
2706 
2707 Error GDBRemoteCommunicationClient::SetFilePermissions(
2708     const FileSpec &file_spec, uint32_t file_permissions) {
2709   std::string path{file_spec.GetPath(false)};
2710   lldb_private::StreamString stream;
2711   stream.PutCString("qPlatform_chmod:");
2712   stream.PutHex32(file_permissions);
2713   stream.PutChar(',');
2714   stream.PutCStringAsRawHex8(path.c_str());
2715   const char *packet = stream.GetData();
2716   StringExtractorGDBRemote response;
2717 
2718   if (SendPacketAndWaitForResponse(packet, response, false) !=
2719       PacketResult::Success)
2720     return Error("failed to send '%s' packet", packet);
2721 
2722   if (response.GetChar() != 'F')
2723     return Error("invalid response to '%s' packet", packet);
2724 
2725   return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2726 }
2727 
2728 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2729                                           uint64_t fail_result, Error &error) {
2730   response.SetFilePos(0);
2731   if (response.GetChar() != 'F')
2732     return fail_result;
2733   int32_t result = response.GetS32(-2);
2734   if (result == -2)
2735     return fail_result;
2736   if (response.GetChar() == ',') {
2737     int result_errno = response.GetS32(-2);
2738     if (result_errno != -2)
2739       error.SetError(result_errno, eErrorTypePOSIX);
2740     else
2741       error.SetError(-1, eErrorTypeGeneric);
2742   } else
2743     error.Clear();
2744   return result;
2745 }
2746 lldb::user_id_t
2747 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2748                                        uint32_t flags, mode_t mode,
2749                                        Error &error) {
2750   std::string path(file_spec.GetPath(false));
2751   lldb_private::StreamString stream;
2752   stream.PutCString("vFile:open:");
2753   if (path.empty())
2754     return UINT64_MAX;
2755   stream.PutCStringAsRawHex8(path.c_str());
2756   stream.PutChar(',');
2757   stream.PutHex32(flags);
2758   stream.PutChar(',');
2759   stream.PutHex32(mode);
2760   StringExtractorGDBRemote response;
2761   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2762       PacketResult::Success) {
2763     return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2764   }
2765   return UINT64_MAX;
2766 }
2767 
2768 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2769   lldb_private::StreamString stream;
2770   stream.Printf("vFile:close:%i", (int)fd);
2771   StringExtractorGDBRemote response;
2772   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2773       PacketResult::Success) {
2774     return ParseHostIOPacketResponse(response, -1, error) == 0;
2775   }
2776   return false;
2777 }
2778 
2779 // Extension of host I/O packets to get the file size.
2780 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2781     const lldb_private::FileSpec &file_spec) {
2782   std::string path(file_spec.GetPath(false));
2783   lldb_private::StreamString stream;
2784   stream.PutCString("vFile:size:");
2785   stream.PutCStringAsRawHex8(path.c_str());
2786   StringExtractorGDBRemote response;
2787   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2788       PacketResult::Success) {
2789     if (response.GetChar() != 'F')
2790       return UINT64_MAX;
2791     uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2792     return retcode;
2793   }
2794   return UINT64_MAX;
2795 }
2796 
2797 Error GDBRemoteCommunicationClient::GetFilePermissions(
2798     const FileSpec &file_spec, uint32_t &file_permissions) {
2799   std::string path{file_spec.GetPath(false)};
2800   Error error;
2801   lldb_private::StreamString stream;
2802   stream.PutCString("vFile:mode:");
2803   stream.PutCStringAsRawHex8(path.c_str());
2804   StringExtractorGDBRemote response;
2805   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2806       PacketResult::Success) {
2807     if (response.GetChar() != 'F') {
2808       error.SetErrorStringWithFormat("invalid response to '%s' packet",
2809                                      stream.GetString().c_str());
2810     } else {
2811       const uint32_t mode = response.GetS32(-1);
2812       if (static_cast<int32_t>(mode) == -1) {
2813         if (response.GetChar() == ',') {
2814           int response_errno = response.GetS32(-1);
2815           if (response_errno > 0)
2816             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2817           else
2818             error.SetErrorToGenericError();
2819         } else
2820           error.SetErrorToGenericError();
2821       } else {
2822         file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2823       }
2824     }
2825   } else {
2826     error.SetErrorStringWithFormat("failed to send '%s' packet",
2827                                    stream.GetString().c_str());
2828   }
2829   return error;
2830 }
2831 
2832 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2833                                                 uint64_t offset, void *dst,
2834                                                 uint64_t dst_len,
2835                                                 Error &error) {
2836   lldb_private::StreamString stream;
2837   stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2838                 offset);
2839   StringExtractorGDBRemote response;
2840   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2841       PacketResult::Success) {
2842     if (response.GetChar() != 'F')
2843       return 0;
2844     uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2845     if (retcode == UINT32_MAX)
2846       return retcode;
2847     const char next = (response.Peek() ? *response.Peek() : 0);
2848     if (next == ',')
2849       return 0;
2850     if (next == ';') {
2851       response.GetChar(); // skip the semicolon
2852       std::string buffer;
2853       if (response.GetEscapedBinaryData(buffer)) {
2854         const uint64_t data_to_write =
2855             std::min<uint64_t>(dst_len, buffer.size());
2856         if (data_to_write > 0)
2857           memcpy(dst, &buffer[0], data_to_write);
2858         return data_to_write;
2859       }
2860     }
2861   }
2862   return 0;
2863 }
2864 
2865 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2866                                                  uint64_t offset,
2867                                                  const void *src,
2868                                                  uint64_t src_len,
2869                                                  Error &error) {
2870   lldb_private::StreamGDBRemote stream;
2871   stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2872   stream.PutEscapedBytes(src, src_len);
2873   StringExtractorGDBRemote response;
2874   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2875       PacketResult::Success) {
2876     if (response.GetChar() != 'F') {
2877       error.SetErrorStringWithFormat("write file failed");
2878       return 0;
2879     }
2880     uint64_t bytes_written = response.GetU64(UINT64_MAX);
2881     if (bytes_written == UINT64_MAX) {
2882       error.SetErrorToGenericError();
2883       if (response.GetChar() == ',') {
2884         int response_errno = response.GetS32(-1);
2885         if (response_errno > 0)
2886           error.SetError(response_errno, lldb::eErrorTypePOSIX);
2887       }
2888       return 0;
2889     }
2890     return bytes_written;
2891   } else {
2892     error.SetErrorString("failed to send vFile:pwrite packet");
2893   }
2894   return 0;
2895 }
2896 
2897 Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2898                                                   const FileSpec &dst) {
2899   std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2900   Error error;
2901   lldb_private::StreamGDBRemote stream;
2902   stream.PutCString("vFile:symlink:");
2903   // the unix symlink() command reverses its parameters where the dst if first,
2904   // so we follow suit here
2905   stream.PutCStringAsRawHex8(dst_path.c_str());
2906   stream.PutChar(',');
2907   stream.PutCStringAsRawHex8(src_path.c_str());
2908   StringExtractorGDBRemote response;
2909   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2910       PacketResult::Success) {
2911     if (response.GetChar() == 'F') {
2912       uint32_t result = response.GetU32(UINT32_MAX);
2913       if (result != 0) {
2914         error.SetErrorToGenericError();
2915         if (response.GetChar() == ',') {
2916           int response_errno = response.GetS32(-1);
2917           if (response_errno > 0)
2918             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2919         }
2920       }
2921     } else {
2922       // Should have returned with 'F<result>[,<errno>]'
2923       error.SetErrorStringWithFormat("symlink failed");
2924     }
2925   } else {
2926     error.SetErrorString("failed to send vFile:symlink packet");
2927   }
2928   return error;
2929 }
2930 
2931 Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2932   std::string path{file_spec.GetPath(false)};
2933   Error error;
2934   lldb_private::StreamGDBRemote stream;
2935   stream.PutCString("vFile:unlink:");
2936   // the unix symlink() command reverses its parameters where the dst if first,
2937   // so we follow suit here
2938   stream.PutCStringAsRawHex8(path.c_str());
2939   StringExtractorGDBRemote response;
2940   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2941       PacketResult::Success) {
2942     if (response.GetChar() == 'F') {
2943       uint32_t result = response.GetU32(UINT32_MAX);
2944       if (result != 0) {
2945         error.SetErrorToGenericError();
2946         if (response.GetChar() == ',') {
2947           int response_errno = response.GetS32(-1);
2948           if (response_errno > 0)
2949             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2950         }
2951       }
2952     } else {
2953       // Should have returned with 'F<result>[,<errno>]'
2954       error.SetErrorStringWithFormat("unlink failed");
2955     }
2956   } else {
2957     error.SetErrorString("failed to send vFile:unlink packet");
2958   }
2959   return error;
2960 }
2961 
2962 // Extension of host I/O packets to get whether a file exists.
2963 bool GDBRemoteCommunicationClient::GetFileExists(
2964     const lldb_private::FileSpec &file_spec) {
2965   std::string path(file_spec.GetPath(false));
2966   lldb_private::StreamString stream;
2967   stream.PutCString("vFile:exists:");
2968   stream.PutCStringAsRawHex8(path.c_str());
2969   StringExtractorGDBRemote response;
2970   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2971       PacketResult::Success) {
2972     if (response.GetChar() != 'F')
2973       return false;
2974     if (response.GetChar() != ',')
2975       return false;
2976     bool retcode = (response.GetChar() != '0');
2977     return retcode;
2978   }
2979   return false;
2980 }
2981 
2982 bool GDBRemoteCommunicationClient::CalculateMD5(
2983     const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2984   std::string path(file_spec.GetPath(false));
2985   lldb_private::StreamString stream;
2986   stream.PutCString("vFile:MD5:");
2987   stream.PutCStringAsRawHex8(path.c_str());
2988   StringExtractorGDBRemote response;
2989   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2990       PacketResult::Success) {
2991     if (response.GetChar() != 'F')
2992       return false;
2993     if (response.GetChar() != ',')
2994       return false;
2995     if (response.Peek() && *response.Peek() == 'x')
2996       return false;
2997     low = response.GetHexMaxU64(false, UINT64_MAX);
2998     high = response.GetHexMaxU64(false, UINT64_MAX);
2999     return true;
3000   }
3001   return false;
3002 }
3003 
3004 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3005   // Some targets have issues with g/G packets and we need to avoid using them
3006   if (m_avoid_g_packets == eLazyBoolCalculate) {
3007     if (process) {
3008       m_avoid_g_packets = eLazyBoolNo;
3009       const ArchSpec &arch = process->GetTarget().GetArchitecture();
3010       if (arch.IsValid() &&
3011           arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3012           arch.GetTriple().getOS() == llvm::Triple::IOS &&
3013           arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3014         m_avoid_g_packets = eLazyBoolYes;
3015         uint32_t gdb_server_version = GetGDBServerProgramVersion();
3016         if (gdb_server_version != 0) {
3017           const char *gdb_server_name = GetGDBServerProgramName();
3018           if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3019             if (gdb_server_version >= 310)
3020               m_avoid_g_packets = eLazyBoolNo;
3021           }
3022         }
3023       }
3024     }
3025   }
3026   return m_avoid_g_packets == eLazyBoolYes;
3027 }
3028 
3029 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3030                                                         uint32_t reg) {
3031   StreamString payload;
3032   payload.Printf("p%x", reg);
3033   StringExtractorGDBRemote response;
3034   if (SendThreadSpecificPacketAndWaitForResponse(
3035           tid, std::move(payload), response, false) != PacketResult::Success ||
3036       !response.IsNormalResponse())
3037     return nullptr;
3038 
3039   DataBufferSP buffer_sp(
3040       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3041   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3042   return buffer_sp;
3043 }
3044 
3045 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3046   StreamString payload;
3047   payload.PutChar('g');
3048   StringExtractorGDBRemote response;
3049   if (SendThreadSpecificPacketAndWaitForResponse(
3050           tid, std::move(payload), response, false) != PacketResult::Success ||
3051       !response.IsNormalResponse())
3052     return nullptr;
3053 
3054   DataBufferSP buffer_sp(
3055       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3056   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3057   return buffer_sp;
3058 }
3059 
3060 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3061                                                  uint32_t reg_num,
3062                                                  llvm::ArrayRef<uint8_t> data) {
3063   StreamString payload;
3064   payload.Printf("P%x=", reg_num);
3065   payload.PutBytesAsRawHex8(data.data(), data.size(),
3066                             endian::InlHostByteOrder(),
3067                             endian::InlHostByteOrder());
3068   StringExtractorGDBRemote response;
3069   return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3070                                                     response, false) ==
3071              PacketResult::Success &&
3072          response.IsOKResponse();
3073 }
3074 
3075 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3076     lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3077   StreamString payload;
3078   payload.PutChar('G');
3079   payload.PutBytesAsRawHex8(data.data(), data.size(),
3080                             endian::InlHostByteOrder(),
3081                             endian::InlHostByteOrder());
3082   StringExtractorGDBRemote response;
3083   return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3084                                                     response, false) ==
3085              PacketResult::Success &&
3086          response.IsOKResponse();
3087 }
3088 
3089 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3090                                                      uint32_t &save_id) {
3091   save_id = 0; // Set to invalid save ID
3092   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3093     return false;
3094 
3095   m_supports_QSaveRegisterState = eLazyBoolYes;
3096   StreamString payload;
3097   payload.PutCString("QSaveRegisterState");
3098   StringExtractorGDBRemote response;
3099   if (SendThreadSpecificPacketAndWaitForResponse(
3100           tid, std::move(payload), response, false) != PacketResult::Success)
3101     return false;
3102 
3103   if (response.IsUnsupportedResponse())
3104     m_supports_QSaveRegisterState = eLazyBoolNo;
3105 
3106   const uint32_t response_save_id = response.GetU32(0);
3107   if (response_save_id == 0)
3108     return false;
3109 
3110   save_id = response_save_id;
3111   return true;
3112 }
3113 
3114 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3115                                                         uint32_t save_id) {
3116   // We use the "m_supports_QSaveRegisterState" variable here because the
3117   // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3118   // in
3119   // order to be useful
3120   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3121     return false;
3122 
3123   StreamString payload;
3124   payload.Printf("QRestoreRegisterState:%u", save_id);
3125   StringExtractorGDBRemote response;
3126   if (SendThreadSpecificPacketAndWaitForResponse(
3127           tid, std::move(payload), response, false) != PacketResult::Success)
3128     return false;
3129 
3130   if (response.IsOKResponse())
3131     return true;
3132 
3133   if (response.IsUnsupportedResponse())
3134     m_supports_QSaveRegisterState = eLazyBoolNo;
3135   return false;
3136 }
3137 
3138 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3139   if (!GetSyncThreadStateSupported())
3140     return false;
3141 
3142   StreamString packet;
3143   StringExtractorGDBRemote response;
3144   packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3145   return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3146              GDBRemoteCommunication::PacketResult::Success &&
3147          response.IsOKResponse();
3148 }
3149 
3150 bool GDBRemoteCommunicationClient::GetModuleInfo(
3151     const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3152     ModuleSpec &module_spec) {
3153   if (!m_supports_qModuleInfo)
3154     return false;
3155 
3156   std::string module_path = module_file_spec.GetPath(false);
3157   if (module_path.empty())
3158     return false;
3159 
3160   StreamString packet;
3161   packet.PutCString("qModuleInfo:");
3162   packet.PutCStringAsRawHex8(module_path.c_str());
3163   packet.PutCString(";");
3164   const auto &triple = arch_spec.GetTriple().getTriple();
3165   packet.PutCStringAsRawHex8(triple.c_str());
3166 
3167   StringExtractorGDBRemote response;
3168   if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3169       PacketResult::Success)
3170     return false;
3171 
3172   if (response.IsErrorResponse())
3173     return false;
3174 
3175   if (response.IsUnsupportedResponse()) {
3176     m_supports_qModuleInfo = false;
3177     return false;
3178   }
3179 
3180   llvm::StringRef name;
3181   llvm::StringRef value;
3182 
3183   module_spec.Clear();
3184   module_spec.GetFileSpec() = module_file_spec;
3185 
3186   while (response.GetNameColonValue(name, value)) {
3187     if (name == "uuid" || name == "md5") {
3188       StringExtractor extractor(value);
3189       std::string uuid;
3190       extractor.GetHexByteString(uuid);
3191       module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3192     } else if (name == "triple") {
3193       StringExtractor extractor(value);
3194       std::string triple;
3195       extractor.GetHexByteString(triple);
3196       module_spec.GetArchitecture().SetTriple(triple.c_str());
3197     } else if (name == "file_offset") {
3198       uint64_t ival = 0;
3199       if (!value.getAsInteger(16, ival))
3200         module_spec.SetObjectOffset(ival);
3201     } else if (name == "file_size") {
3202       uint64_t ival = 0;
3203       if (!value.getAsInteger(16, ival))
3204         module_spec.SetObjectSize(ival);
3205     } else if (name == "file_path") {
3206       StringExtractor extractor(value);
3207       std::string path;
3208       extractor.GetHexByteString(path);
3209       module_spec.GetFileSpec() = FileSpec(path.c_str(), false, arch_spec);
3210     }
3211   }
3212 
3213   return true;
3214 }
3215 
3216 static llvm::Optional<ModuleSpec>
3217 ParseModuleSpec(StructuredData::Dictionary *dict) {
3218   ModuleSpec result;
3219   if (!dict)
3220     return llvm::None;
3221 
3222   std::string string;
3223   uint64_t integer;
3224 
3225   if (!dict->GetValueForKeyAsString("uuid", string))
3226     return llvm::None;
3227   result.GetUUID().SetFromCString(string.c_str(), string.size());
3228 
3229   if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3230     return llvm::None;
3231   result.SetObjectOffset(integer);
3232 
3233   if (!dict->GetValueForKeyAsInteger("file_size", integer))
3234     return llvm::None;
3235   result.SetObjectSize(integer);
3236 
3237   if (!dict->GetValueForKeyAsString("triple", string))
3238     return llvm::None;
3239   result.GetArchitecture().SetTriple(string.c_str());
3240 
3241   if (!dict->GetValueForKeyAsString("file_path", string))
3242     return llvm::None;
3243   result.GetFileSpec() = FileSpec(string, false, result.GetArchitecture());
3244 
3245   return result;
3246 }
3247 
3248 llvm::Optional<std::vector<ModuleSpec>>
3249 GDBRemoteCommunicationClient::GetModulesInfo(
3250     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3251   if (!m_supports_jModulesInfo)
3252     return llvm::None;
3253 
3254   JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3255   for (const FileSpec &module_file_spec : module_file_specs) {
3256     JSONObject::SP module_sp = std::make_shared<JSONObject>();
3257     module_array_sp->AppendObject(module_sp);
3258     module_sp->SetObject(
3259         "file", std::make_shared<JSONString>(module_file_spec.GetPath()));
3260     module_sp->SetObject("triple",
3261                          std::make_shared<JSONString>(triple.getTriple()));
3262   }
3263   StreamString unescaped_payload;
3264   unescaped_payload.PutCString("jModulesInfo:");
3265   module_array_sp->Write(unescaped_payload);
3266   StreamGDBRemote payload;
3267   payload.PutEscapedBytes(unescaped_payload.GetData(),
3268                           unescaped_payload.GetSize());
3269 
3270   StringExtractorGDBRemote response;
3271   if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3272           PacketResult::Success ||
3273       response.IsErrorResponse())
3274     return llvm::None;
3275 
3276   if (response.IsUnsupportedResponse()) {
3277     m_supports_jModulesInfo = false;
3278     return llvm::None;
3279   }
3280 
3281   StructuredData::ObjectSP response_object_sp =
3282       StructuredData::ParseJSON(response.GetStringRef());
3283   if (!response_object_sp)
3284     return llvm::None;
3285 
3286   StructuredData::Array *response_array = response_object_sp->GetAsArray();
3287   if (!response_array)
3288     return llvm::None;
3289 
3290   std::vector<ModuleSpec> result;
3291   for (size_t i = 0; i < response_array->GetSize(); ++i) {
3292     if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3293             response_array->GetItemAtIndex(i)->GetAsDictionary()))
3294       result.push_back(*module_spec);
3295   }
3296 
3297   return result;
3298 }
3299 
3300 // query the target remote for extended information using the qXfer packet
3301 //
3302 // example: object='features', annex='target.xml', out=<xml output>
3303 // return:  'true'  on success
3304 //          'false' on failure (err set)
3305 bool GDBRemoteCommunicationClient::ReadExtFeature(
3306     const lldb_private::ConstString object,
3307     const lldb_private::ConstString annex, std::string &out,
3308     lldb_private::Error &err) {
3309 
3310   std::stringstream output;
3311   StringExtractorGDBRemote chunk;
3312 
3313   uint64_t size = GetRemoteMaxPacketSize();
3314   if (size == 0)
3315     size = 0x1000;
3316   size = size - 1; // Leave space for the 'm' or 'l' character in the response
3317   int offset = 0;
3318   bool active = true;
3319 
3320   // loop until all data has been read
3321   while (active) {
3322 
3323     // send query extended feature packet
3324     std::stringstream packet;
3325     packet << "qXfer:" << object.AsCString("")
3326            << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3327            << "," << std::hex << size;
3328 
3329     GDBRemoteCommunication::PacketResult res =
3330         SendPacketAndWaitForResponse(packet.str().c_str(), chunk, false);
3331 
3332     if (res != GDBRemoteCommunication::PacketResult::Success) {
3333       err.SetErrorString("Error sending $qXfer packet");
3334       return false;
3335     }
3336 
3337     const std::string &str = chunk.GetStringRef();
3338     if (str.length() == 0) {
3339       // should have some data in chunk
3340       err.SetErrorString("Empty response from $qXfer packet");
3341       return false;
3342     }
3343 
3344     // check packet code
3345     switch (str[0]) {
3346     // last chunk
3347     case ('l'):
3348       active = false;
3349       LLVM_FALLTHROUGH;
3350 
3351     // more chunks
3352     case ('m'):
3353       if (str.length() > 1)
3354         output << &str[1];
3355       offset += size;
3356       break;
3357 
3358     // unknown chunk
3359     default:
3360       err.SetErrorString("Invalid continuation code from $qXfer packet");
3361       return false;
3362     }
3363   }
3364 
3365   out = output.str();
3366   err.Success();
3367   return true;
3368 }
3369 
3370 // Notify the target that gdb is prepared to serve symbol lookup requests.
3371 //  packet: "qSymbol::"
3372 //  reply:
3373 //  OK                  The target does not need to look up any (more) symbols.
3374 //  qSymbol:<sym_name>  The target requests the value of symbol sym_name (hex
3375 //  encoded).
3376 //                      LLDB may provide the value by sending another qSymbol
3377 //                      packet
3378 //                      in the form of"qSymbol:<sym_value>:<sym_name>".
3379 //
3380 //  Three examples:
3381 //
3382 //  lldb sends:    qSymbol::
3383 //  lldb receives: OK
3384 //     Remote gdb stub does not need to know the addresses of any symbols, lldb
3385 //     does not
3386 //     need to ask again in this session.
3387 //
3388 //  lldb sends:    qSymbol::
3389 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3390 //  lldb sends:    qSymbol::64697370617463685f71756575655f6f666673657473
3391 //  lldb receives: OK
3392 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb does
3393 //     not know
3394 //     the address at this time.  lldb needs to send qSymbol:: again when it has
3395 //     more
3396 //     solibs loaded.
3397 //
3398 //  lldb sends:    qSymbol::
3399 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3400 //  lldb sends:    qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3401 //  lldb receives: OK
3402 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb says
3403 //     that it
3404 //     is at address 0x2bc97554.  Remote gdb stub sends 'OK' indicating that it
3405 //     does not
3406 //     need any more symbols.  lldb does not need to ask again in this session.
3407 
3408 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3409     lldb_private::Process *process) {
3410   // Set to true once we've resolved a symbol to an address for the remote stub.
3411   // If we get an 'OK' response after this, the remote stub doesn't need any
3412   // more
3413   // symbols and we can stop asking.
3414   bool symbol_response_provided = false;
3415 
3416   // Is this the initial qSymbol:: packet?
3417   bool first_qsymbol_query = true;
3418 
3419   if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3420     Lock lock(*this, false);
3421     if (lock) {
3422       StreamString packet;
3423       packet.PutCString("qSymbol::");
3424       StringExtractorGDBRemote response;
3425       while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3426              PacketResult::Success) {
3427         if (response.IsOKResponse()) {
3428           if (symbol_response_provided || first_qsymbol_query) {
3429             m_qSymbol_requests_done = true;
3430           }
3431 
3432           // We are done serving symbols requests
3433           return;
3434         }
3435         first_qsymbol_query = false;
3436 
3437         if (response.IsUnsupportedResponse()) {
3438           // qSymbol is not supported by the current GDB server we are connected
3439           // to
3440           m_supports_qSymbol = false;
3441           return;
3442         } else {
3443           llvm::StringRef response_str(response.GetStringRef());
3444           if (response_str.startswith("qSymbol:")) {
3445             response.SetFilePos(strlen("qSymbol:"));
3446             std::string symbol_name;
3447             if (response.GetHexByteString(symbol_name)) {
3448               if (symbol_name.empty())
3449                 return;
3450 
3451               addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3452               lldb_private::SymbolContextList sc_list;
3453               if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3454                       ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3455                 const size_t num_scs = sc_list.GetSize();
3456                 for (size_t sc_idx = 0;
3457                      sc_idx < num_scs &&
3458                      symbol_load_addr == LLDB_INVALID_ADDRESS;
3459                      ++sc_idx) {
3460                   SymbolContext sc;
3461                   if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3462                     if (sc.symbol) {
3463                       switch (sc.symbol->GetType()) {
3464                       case eSymbolTypeInvalid:
3465                       case eSymbolTypeAbsolute:
3466                       case eSymbolTypeUndefined:
3467                       case eSymbolTypeSourceFile:
3468                       case eSymbolTypeHeaderFile:
3469                       case eSymbolTypeObjectFile:
3470                       case eSymbolTypeCommonBlock:
3471                       case eSymbolTypeBlock:
3472                       case eSymbolTypeLocal:
3473                       case eSymbolTypeParam:
3474                       case eSymbolTypeVariable:
3475                       case eSymbolTypeVariableType:
3476                       case eSymbolTypeLineEntry:
3477                       case eSymbolTypeLineHeader:
3478                       case eSymbolTypeScopeBegin:
3479                       case eSymbolTypeScopeEnd:
3480                       case eSymbolTypeAdditional:
3481                       case eSymbolTypeCompiler:
3482                       case eSymbolTypeInstrumentation:
3483                       case eSymbolTypeTrampoline:
3484                         break;
3485 
3486                       case eSymbolTypeCode:
3487                       case eSymbolTypeResolver:
3488                       case eSymbolTypeData:
3489                       case eSymbolTypeRuntime:
3490                       case eSymbolTypeException:
3491                       case eSymbolTypeObjCClass:
3492                       case eSymbolTypeObjCMetaClass:
3493                       case eSymbolTypeObjCIVar:
3494                       case eSymbolTypeReExported:
3495                         symbol_load_addr =
3496                             sc.symbol->GetLoadAddress(&process->GetTarget());
3497                         break;
3498                       }
3499                     }
3500                   }
3501                 }
3502               }
3503               // This is the normal path where our symbol lookup was successful
3504               // and we want
3505               // to send a packet with the new symbol value and see if another
3506               // lookup needs to be
3507               // done.
3508 
3509               // Change "packet" to contain the requested symbol value and name
3510               packet.Clear();
3511               packet.PutCString("qSymbol:");
3512               if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3513                 packet.Printf("%" PRIx64, symbol_load_addr);
3514                 symbol_response_provided = true;
3515               } else {
3516                 symbol_response_provided = false;
3517               }
3518               packet.PutCString(":");
3519               packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3520               continue; // go back to the while loop and send "packet" and wait
3521                         // for another response
3522             }
3523           }
3524         }
3525       }
3526       // If we make it here, the symbol request packet response wasn't valid or
3527       // our symbol lookup failed so we must abort
3528       return;
3529 
3530     } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3531                    GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3532       log->Printf(
3533           "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3534           __FUNCTION__);
3535     }
3536   }
3537 }
3538 
3539 StructuredData::Array *
3540 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3541   if (!m_supported_async_json_packets_is_valid) {
3542     // Query the server for the array of supported asynchronous JSON
3543     // packets.
3544     m_supported_async_json_packets_is_valid = true;
3545 
3546     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3547 
3548     // Poll it now.
3549     StringExtractorGDBRemote response;
3550     const bool send_async = false;
3551     if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3552                                      send_async) == PacketResult::Success) {
3553       m_supported_async_json_packets_sp =
3554           StructuredData::ParseJSON(response.GetStringRef());
3555       if (m_supported_async_json_packets_sp &&
3556           !m_supported_async_json_packets_sp->GetAsArray()) {
3557         // We were returned something other than a JSON array.  This
3558         // is invalid.  Clear it out.
3559         if (log)
3560           log->Printf("GDBRemoteCommunicationClient::%s(): "
3561                       "QSupportedAsyncJSONPackets returned invalid "
3562                       "result: %s",
3563                       __FUNCTION__, response.GetStringRef().c_str());
3564         m_supported_async_json_packets_sp.reset();
3565       }
3566     } else {
3567       if (log)
3568         log->Printf("GDBRemoteCommunicationClient::%s(): "
3569                     "QSupportedAsyncJSONPackets unsupported",
3570                     __FUNCTION__);
3571     }
3572 
3573     if (log && m_supported_async_json_packets_sp) {
3574       StreamString stream;
3575       m_supported_async_json_packets_sp->Dump(stream);
3576       log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3577                   "JSON packets: %s",
3578                   __FUNCTION__, stream.GetString().c_str());
3579     }
3580   }
3581 
3582   return m_supported_async_json_packets_sp
3583              ? m_supported_async_json_packets_sp->GetAsArray()
3584              : nullptr;
3585 }
3586 
3587 Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3588     const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3589   Error error;
3590 
3591   if (type_name.GetLength() == 0) {
3592     error.SetErrorString("invalid type_name argument");
3593     return error;
3594   }
3595 
3596   // Build command: Configure{type_name}: serialized config
3597   // data.
3598   StreamGDBRemote stream;
3599   stream.PutCString("QConfigure");
3600   stream.PutCString(type_name.AsCString());
3601   stream.PutChar(':');
3602   if (config_sp) {
3603     // Gather the plain-text version of the configuration data.
3604     StreamString unescaped_stream;
3605     config_sp->Dump(unescaped_stream);
3606     unescaped_stream.Flush();
3607 
3608     // Add it to the stream in escaped fashion.
3609     stream.PutEscapedBytes(unescaped_stream.GetData(),
3610                            unescaped_stream.GetSize());
3611   }
3612   stream.Flush();
3613 
3614   // Send the packet.
3615   const bool send_async = false;
3616   StringExtractorGDBRemote response;
3617   auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(),
3618                                              response, send_async);
3619   if (result == PacketResult::Success) {
3620     // We failed if the config result comes back other than OK.
3621     if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3622       // Okay!
3623       error.Clear();
3624     } else {
3625       error.SetErrorStringWithFormat("configuring StructuredData feature "
3626                                      "%s failed with error %s",
3627                                      type_name.AsCString(),
3628                                      response.GetStringRef().c_str());
3629     }
3630   } else {
3631     // Can we get more data here on the failure?
3632     error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3633                                    "failed when sending packet: "
3634                                    "PacketResult=%d",
3635                                    type_name.AsCString(), (int)result);
3636   }
3637   return error;
3638 }
3639 
3640 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3641   GDBRemoteClientBase::OnRunPacketSent(first);
3642   m_curr_tid = LLDB_INVALID_THREAD_ID;
3643 }
3644