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