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