xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp (revision 3aa049102fd0e80600622b29fde5c973b6138cf4)
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].c_str());
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.c_str(), 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.c_str(), 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().c_str());
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, bool json,
2152                                                    Stream &strm) {
2153   using namespace std::chrono;
2154 
2155   uint32_t i;
2156   if (SendSpeedTestPacket(0, 0)) {
2157     StreamString packet;
2158     if (json)
2159       strm.Printf("{ \"packet_speeds\" : {\n    \"num_packets\" : %u,\n    "
2160                   "\"results\" : [",
2161                   num_packets);
2162     else
2163       strm.Printf("Testing sending %u packets of various sizes:\n",
2164                   num_packets);
2165     strm.Flush();
2166 
2167     uint32_t result_idx = 0;
2168     uint32_t send_size;
2169     std::vector<duration<float>> packet_times;
2170 
2171     for (send_size = 0; send_size <= max_send;
2172          send_size ? send_size *= 2 : send_size = 4) {
2173       for (uint32_t recv_size = 0; recv_size <= max_recv;
2174            recv_size ? recv_size *= 2 : recv_size = 4) {
2175         MakeSpeedTestPacket(packet, send_size, recv_size);
2176 
2177         packet_times.clear();
2178         // Test how long it takes to send 'num_packets' packets
2179         const auto start_time = steady_clock::now();
2180         for (i = 0; i < num_packets; ++i) {
2181           const auto packet_start_time = steady_clock::now();
2182           StringExtractorGDBRemote response;
2183           SendPacketAndWaitForResponse(packet.GetString(), response, false);
2184           const auto packet_end_time = steady_clock::now();
2185           packet_times.push_back(packet_end_time - packet_start_time);
2186         }
2187         const auto end_time = steady_clock::now();
2188         const auto total_time = end_time - start_time;
2189 
2190         float packets_per_second =
2191             ((float)num_packets) / duration<float>(total_time).count();
2192         auto average_per_packet = total_time / num_packets;
2193         const duration<float> standard_deviation =
2194             calculate_standard_deviation(packet_times);
2195         if (json) {
2196           strm.Printf("%s\n     {\"send_size\" : %6" PRIu32
2197                       ", \"recv_size\" : %6" PRIu32
2198                       ", \"total_time_nsec\" : %12" PRIu64
2199                       ", \"standard_deviation_nsec\" : %9" PRIu64 " }",
2200                       result_idx > 0 ? "," : "", send_size, recv_size,
2201                       duration_cast<nanoseconds>(total_time).count(),
2202                       duration_cast<nanoseconds>(standard_deviation).count());
2203           ++result_idx;
2204         } else {
2205           strm.Printf(
2206               "qSpeedTest(send=%-7u, recv=%-7u) in %.9f"
2207               " sec for %9.2f packets/sec (%10.6f ms per packet) with standard "
2208               "deviation of %10.6f ms\n",
2209               send_size, recv_size, duration<float>(total_time).count(),
2210               packets_per_second,
2211               duration<float, std::milli>(average_per_packet).count(),
2212               duration<float, std::milli>(standard_deviation).count());
2213         }
2214         strm.Flush();
2215       }
2216     }
2217 
2218     const uint64_t k_recv_amount = 4 * 1024 * 1024; // Receive amount in bytes
2219 
2220     const float k_recv_amount_mb = (float)k_recv_amount / (1024.0f * 1024.0f);
2221     if (json)
2222       strm.Printf("\n    ]\n  },\n  \"download_speed\" : {\n    \"byte_size\" "
2223                   ": %" PRIu64 ",\n    \"results\" : [",
2224                   k_recv_amount);
2225     else
2226       strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2227                   "packet sizes:\n",
2228                   k_recv_amount_mb);
2229     strm.Flush();
2230     send_size = 0;
2231     result_idx = 0;
2232     for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2233       MakeSpeedTestPacket(packet, send_size, recv_size);
2234 
2235       // If we have a receive size, test how long it takes to receive 4MB of
2236       // data
2237       if (recv_size > 0) {
2238         const auto start_time = steady_clock::now();
2239         uint32_t bytes_read = 0;
2240         uint32_t packet_count = 0;
2241         while (bytes_read < k_recv_amount) {
2242           StringExtractorGDBRemote response;
2243           SendPacketAndWaitForResponse(packet.GetString(), response, false);
2244           bytes_read += recv_size;
2245           ++packet_count;
2246         }
2247         const auto end_time = steady_clock::now();
2248         const auto total_time = end_time - start_time;
2249         float mb_second = ((float)k_recv_amount) /
2250                           duration<float>(total_time).count() /
2251                           (1024.0 * 1024.0);
2252         float packets_per_second =
2253             ((float)packet_count) / duration<float>(total_time).count();
2254         const auto average_per_packet = total_time / packet_count;
2255 
2256         if (json) {
2257           strm.Printf("%s\n     {\"send_size\" : %6" PRIu32
2258                       ", \"recv_size\" : %6" PRIu32
2259                       ", \"total_time_nsec\" : %12" PRIu64 " }",
2260                       result_idx > 0 ? "," : "", send_size, recv_size,
2261                       duration_cast<nanoseconds>(total_time).count());
2262           ++result_idx;
2263         } else {
2264           strm.Printf("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to "
2265                       "receive %2.1fMB in %.9f"
2266                       " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per "
2267                       "packet)\n",
2268                       send_size, recv_size, packet_count, k_recv_amount_mb,
2269                       duration<float>(total_time).count(), mb_second,
2270                       packets_per_second,
2271                       duration<float, std::milli>(average_per_packet).count());
2272         }
2273         strm.Flush();
2274       }
2275     }
2276     if (json)
2277       strm.Printf("\n    ]\n  }\n}\n");
2278     else
2279       strm.EOL();
2280   }
2281 }
2282 
2283 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2284                                                        uint32_t recv_size) {
2285   StreamString packet;
2286   packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2287   uint32_t bytes_left = send_size;
2288   while (bytes_left > 0) {
2289     if (bytes_left >= 26) {
2290       packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2291       bytes_left -= 26;
2292     } else {
2293       packet.Printf("%*.*s;", bytes_left, bytes_left,
2294                     "abcdefghijklmnopqrstuvwxyz");
2295       bytes_left = 0;
2296     }
2297   }
2298 
2299   StringExtractorGDBRemote response;
2300   return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2301          PacketResult::Success;
2302 }
2303 
2304 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2305     const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2306     std::string &socket_name) {
2307   pid = LLDB_INVALID_PROCESS_ID;
2308   port = 0;
2309   socket_name.clear();
2310 
2311   StringExtractorGDBRemote response;
2312   StreamString stream;
2313   stream.PutCString("qLaunchGDBServer;");
2314   std::string hostname;
2315   if (remote_accept_hostname && remote_accept_hostname[0])
2316     hostname = remote_accept_hostname;
2317   else {
2318     if (HostInfo::GetHostname(hostname)) {
2319       // Make the GDB server we launch only accept connections from this host
2320       stream.Printf("host:%s;", hostname.c_str());
2321     } else {
2322       // Make the GDB server we launch accept connections from any host since we
2323       // can't figure out the hostname
2324       stream.Printf("host:*;");
2325     }
2326   }
2327   // give the process a few seconds to startup
2328   ScopedTimeout timeout(*this, std::chrono::seconds(10));
2329 
2330   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2331       PacketResult::Success) {
2332     llvm::StringRef name;
2333     llvm::StringRef value;
2334     while (response.GetNameColonValue(name, value)) {
2335       if (name.equals("port"))
2336         value.getAsInteger(0, port);
2337       else if (name.equals("pid"))
2338         value.getAsInteger(0, pid);
2339       else if (name.compare("socket_name") == 0) {
2340         StringExtractor extractor(value);
2341         extractor.GetHexByteString(socket_name);
2342       }
2343     }
2344     return true;
2345   }
2346   return false;
2347 }
2348 
2349 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2350     std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2351   connection_urls.clear();
2352 
2353   StringExtractorGDBRemote response;
2354   if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2355       PacketResult::Success)
2356     return 0;
2357 
2358   StructuredData::ObjectSP data =
2359       StructuredData::ParseJSON(response.GetStringRef());
2360   if (!data)
2361     return 0;
2362 
2363   StructuredData::Array *array = data->GetAsArray();
2364   if (!array)
2365     return 0;
2366 
2367   for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2368     StructuredData::Dictionary *element = nullptr;
2369     if (!array->GetItemAtIndexAsDictionary(i, element))
2370       continue;
2371 
2372     uint16_t port = 0;
2373     if (StructuredData::ObjectSP port_osp =
2374             element->GetValueForKey(llvm::StringRef("port")))
2375       port = port_osp->GetIntegerValue(0);
2376 
2377     std::string socket_name;
2378     if (StructuredData::ObjectSP socket_name_osp =
2379             element->GetValueForKey(llvm::StringRef("socket_name")))
2380       socket_name = socket_name_osp->GetStringValue();
2381 
2382     if (port != 0 || !socket_name.empty())
2383       connection_urls.emplace_back(port, socket_name);
2384   }
2385   return connection_urls.size();
2386 }
2387 
2388 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2389   StreamString stream;
2390   stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2391 
2392   StringExtractorGDBRemote response;
2393   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2394       PacketResult::Success) {
2395     if (response.IsOKResponse())
2396       return true;
2397   }
2398   return false;
2399 }
2400 
2401 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2402   if (m_curr_tid == tid)
2403     return true;
2404 
2405   char packet[32];
2406   int packet_len;
2407   if (tid == UINT64_MAX)
2408     packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2409   else
2410     packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2411   assert(packet_len + 1 < (int)sizeof(packet));
2412   UNUSED_IF_ASSERT_DISABLED(packet_len);
2413   StringExtractorGDBRemote response;
2414   if (SendPacketAndWaitForResponse(packet, response, false) ==
2415       PacketResult::Success) {
2416     if (response.IsOKResponse()) {
2417       m_curr_tid = tid;
2418       return true;
2419     }
2420 
2421     /*
2422      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2423      * Hg packet.
2424      * The reply from '?' packet could be as simple as 'S05'. There is no packet
2425      * which can
2426      * give us pid and/or tid. Assume pid=tid=1 in such cases.
2427     */
2428     if (response.IsUnsupportedResponse() && IsConnected()) {
2429       m_curr_tid = 1;
2430       return true;
2431     }
2432   }
2433   return false;
2434 }
2435 
2436 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2437   if (m_curr_tid_run == tid)
2438     return true;
2439 
2440   char packet[32];
2441   int packet_len;
2442   if (tid == UINT64_MAX)
2443     packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2444   else
2445     packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2446 
2447   assert(packet_len + 1 < (int)sizeof(packet));
2448   UNUSED_IF_ASSERT_DISABLED(packet_len);
2449   StringExtractorGDBRemote response;
2450   if (SendPacketAndWaitForResponse(packet, response, false) ==
2451       PacketResult::Success) {
2452     if (response.IsOKResponse()) {
2453       m_curr_tid_run = tid;
2454       return true;
2455     }
2456 
2457     /*
2458      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2459      * Hc packet.
2460      * The reply from '?' packet could be as simple as 'S05'. There is no packet
2461      * which can
2462      * give us pid and/or tid. Assume pid=tid=1 in such cases.
2463     */
2464     if (response.IsUnsupportedResponse() && IsConnected()) {
2465       m_curr_tid_run = 1;
2466       return true;
2467     }
2468   }
2469   return false;
2470 }
2471 
2472 bool GDBRemoteCommunicationClient::GetStopReply(
2473     StringExtractorGDBRemote &response) {
2474   if (SendPacketAndWaitForResponse("?", response, false) ==
2475       PacketResult::Success)
2476     return response.IsNormalResponse();
2477   return false;
2478 }
2479 
2480 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2481     lldb::tid_t tid, StringExtractorGDBRemote &response) {
2482   if (m_supports_qThreadStopInfo) {
2483     char packet[256];
2484     int packet_len =
2485         ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2486     assert(packet_len < (int)sizeof(packet));
2487     UNUSED_IF_ASSERT_DISABLED(packet_len);
2488     if (SendPacketAndWaitForResponse(packet, response, false) ==
2489         PacketResult::Success) {
2490       if (response.IsUnsupportedResponse())
2491         m_supports_qThreadStopInfo = false;
2492       else if (response.IsNormalResponse())
2493         return true;
2494       else
2495         return false;
2496     } else {
2497       m_supports_qThreadStopInfo = false;
2498     }
2499   }
2500   return false;
2501 }
2502 
2503 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2504     GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2505   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2506   if (log)
2507     log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2508                 __FUNCTION__, insert ? "add" : "remove", addr);
2509 
2510   // Check if the stub is known not to support this breakpoint type
2511   if (!SupportsGDBStoppointPacket(type))
2512     return UINT8_MAX;
2513   // Construct the breakpoint packet
2514   char packet[64];
2515   const int packet_len =
2516       ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2517                  insert ? 'Z' : 'z', type, addr, length);
2518   // Check we haven't overwritten the end of the packet buffer
2519   assert(packet_len + 1 < (int)sizeof(packet));
2520   UNUSED_IF_ASSERT_DISABLED(packet_len);
2521   StringExtractorGDBRemote response;
2522   // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2523   // or "" (unsupported)
2524   response.SetResponseValidatorToOKErrorNotSupported();
2525   // Try to send the breakpoint packet, and check that it was correctly sent
2526   if (SendPacketAndWaitForResponse(packet, response, true) ==
2527       PacketResult::Success) {
2528     // Receive and OK packet when the breakpoint successfully placed
2529     if (response.IsOKResponse())
2530       return 0;
2531 
2532     // Error while setting breakpoint, send back specific error
2533     if (response.IsErrorResponse())
2534       return response.GetError();
2535 
2536     // Empty packet informs us that breakpoint is not supported
2537     if (response.IsUnsupportedResponse()) {
2538       // Disable this breakpoint type since it is unsupported
2539       switch (type) {
2540       case eBreakpointSoftware:
2541         m_supports_z0 = false;
2542         break;
2543       case eBreakpointHardware:
2544         m_supports_z1 = false;
2545         break;
2546       case eWatchpointWrite:
2547         m_supports_z2 = false;
2548         break;
2549       case eWatchpointRead:
2550         m_supports_z3 = false;
2551         break;
2552       case eWatchpointReadWrite:
2553         m_supports_z4 = false;
2554         break;
2555       case eStoppointInvalid:
2556         return UINT8_MAX;
2557       }
2558     }
2559   }
2560   // Signal generic failure
2561   return UINT8_MAX;
2562 }
2563 
2564 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2565     std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2566   thread_ids.clear();
2567 
2568   Lock lock(*this, false);
2569   if (lock) {
2570     sequence_mutex_unavailable = false;
2571     StringExtractorGDBRemote response;
2572 
2573     PacketResult packet_result;
2574     for (packet_result =
2575              SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2576          packet_result == PacketResult::Success && response.IsNormalResponse();
2577          packet_result =
2578              SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2579       char ch = response.GetChar();
2580       if (ch == 'l')
2581         break;
2582       if (ch == 'm') {
2583         do {
2584           tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2585 
2586           if (tid != LLDB_INVALID_THREAD_ID) {
2587             thread_ids.push_back(tid);
2588           }
2589           ch = response.GetChar(); // Skip the command separator
2590         } while (ch == ',');       // Make sure we got a comma separator
2591       }
2592     }
2593 
2594     /*
2595      * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2596      * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2597      * could
2598      * be as simple as 'S05'. There is no packet which can give us pid and/or
2599      * tid.
2600      * Assume pid=tid=1 in such cases.
2601     */
2602     if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2603         IsConnected()) {
2604       thread_ids.push_back(1);
2605     }
2606   } else {
2607 #if defined(LLDB_CONFIGURATION_DEBUG)
2608 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the
2609 // sequence mutex");
2610 #else
2611     Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2612                                                            GDBR_LOG_PACKETS));
2613     if (log)
2614       log->Printf("error: failed to get packet sequence mutex, not sending "
2615                   "packet 'qfThreadInfo'");
2616 #endif
2617     sequence_mutex_unavailable = true;
2618   }
2619   return thread_ids.size();
2620 }
2621 
2622 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2623   StringExtractorGDBRemote response;
2624   if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2625           PacketResult::Success ||
2626       !response.IsNormalResponse())
2627     return LLDB_INVALID_ADDRESS;
2628   return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2629 }
2630 
2631 lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2632     const char *command, // Shouldn't be NULL
2633     const FileSpec &
2634         working_dir, // Pass empty FileSpec to use the current working directory
2635     int *status_ptr, // Pass NULL if you don't want the process exit status
2636     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
2637                      // process to exit
2638     std::string
2639         *command_output, // Pass NULL if you don't want the command output
2640     uint32_t
2641         timeout_sec) // Timeout in seconds to wait for shell program to finish
2642 {
2643   lldb_private::StreamString stream;
2644   stream.PutCString("qPlatform_shell:");
2645   stream.PutBytesAsRawHex8(command, strlen(command));
2646   stream.PutChar(',');
2647   stream.PutHex32(timeout_sec);
2648   if (working_dir) {
2649     std::string path{working_dir.GetPath(false)};
2650     stream.PutChar(',');
2651     stream.PutCStringAsRawHex8(path.c_str());
2652   }
2653   StringExtractorGDBRemote response;
2654   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2655       PacketResult::Success) {
2656     if (response.GetChar() != 'F')
2657       return Error("malformed reply");
2658     if (response.GetChar() != ',')
2659       return Error("malformed reply");
2660     uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2661     if (exitcode == UINT32_MAX)
2662       return Error("unable to run remote process");
2663     else if (status_ptr)
2664       *status_ptr = exitcode;
2665     if (response.GetChar() != ',')
2666       return Error("malformed reply");
2667     uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2668     if (signo_ptr)
2669       *signo_ptr = signo;
2670     if (response.GetChar() != ',')
2671       return Error("malformed reply");
2672     std::string output;
2673     response.GetEscapedBinaryData(output);
2674     if (command_output)
2675       command_output->assign(output);
2676     return Error();
2677   }
2678   return Error("unable to send packet");
2679 }
2680 
2681 Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2682                                                   uint32_t file_permissions) {
2683   std::string path{file_spec.GetPath(false)};
2684   lldb_private::StreamString stream;
2685   stream.PutCString("qPlatform_mkdir:");
2686   stream.PutHex32(file_permissions);
2687   stream.PutChar(',');
2688   stream.PutCStringAsRawHex8(path.c_str());
2689   const char *packet = stream.GetData();
2690   StringExtractorGDBRemote response;
2691 
2692   if (SendPacketAndWaitForResponse(packet, response, false) !=
2693       PacketResult::Success)
2694     return Error("failed to send '%s' packet", packet);
2695 
2696   if (response.GetChar() != 'F')
2697     return Error("invalid response to '%s' packet", packet);
2698 
2699   return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2700 }
2701 
2702 Error GDBRemoteCommunicationClient::SetFilePermissions(
2703     const FileSpec &file_spec, uint32_t file_permissions) {
2704   std::string path{file_spec.GetPath(false)};
2705   lldb_private::StreamString stream;
2706   stream.PutCString("qPlatform_chmod:");
2707   stream.PutHex32(file_permissions);
2708   stream.PutChar(',');
2709   stream.PutCStringAsRawHex8(path.c_str());
2710   const char *packet = stream.GetData();
2711   StringExtractorGDBRemote response;
2712 
2713   if (SendPacketAndWaitForResponse(packet, response, false) !=
2714       PacketResult::Success)
2715     return Error("failed to send '%s' packet", packet);
2716 
2717   if (response.GetChar() != 'F')
2718     return Error("invalid response to '%s' packet", packet);
2719 
2720   return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2721 }
2722 
2723 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2724                                           uint64_t fail_result, Error &error) {
2725   response.SetFilePos(0);
2726   if (response.GetChar() != 'F')
2727     return fail_result;
2728   int32_t result = response.GetS32(-2);
2729   if (result == -2)
2730     return fail_result;
2731   if (response.GetChar() == ',') {
2732     int result_errno = response.GetS32(-2);
2733     if (result_errno != -2)
2734       error.SetError(result_errno, eErrorTypePOSIX);
2735     else
2736       error.SetError(-1, eErrorTypeGeneric);
2737   } else
2738     error.Clear();
2739   return result;
2740 }
2741 lldb::user_id_t
2742 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2743                                        uint32_t flags, mode_t mode,
2744                                        Error &error) {
2745   std::string path(file_spec.GetPath(false));
2746   lldb_private::StreamString stream;
2747   stream.PutCString("vFile:open:");
2748   if (path.empty())
2749     return UINT64_MAX;
2750   stream.PutCStringAsRawHex8(path.c_str());
2751   stream.PutChar(',');
2752   stream.PutHex32(flags);
2753   stream.PutChar(',');
2754   stream.PutHex32(mode);
2755   StringExtractorGDBRemote response;
2756   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2757       PacketResult::Success) {
2758     return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2759   }
2760   return UINT64_MAX;
2761 }
2762 
2763 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2764   lldb_private::StreamString stream;
2765   stream.Printf("vFile:close:%i", (int)fd);
2766   StringExtractorGDBRemote response;
2767   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2768       PacketResult::Success) {
2769     return ParseHostIOPacketResponse(response, -1, error) == 0;
2770   }
2771   return false;
2772 }
2773 
2774 // Extension of host I/O packets to get the file size.
2775 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2776     const lldb_private::FileSpec &file_spec) {
2777   std::string path(file_spec.GetPath(false));
2778   lldb_private::StreamString stream;
2779   stream.PutCString("vFile:size:");
2780   stream.PutCStringAsRawHex8(path.c_str());
2781   StringExtractorGDBRemote response;
2782   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2783       PacketResult::Success) {
2784     if (response.GetChar() != 'F')
2785       return UINT64_MAX;
2786     uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2787     return retcode;
2788   }
2789   return UINT64_MAX;
2790 }
2791 
2792 Error GDBRemoteCommunicationClient::GetFilePermissions(
2793     const FileSpec &file_spec, uint32_t &file_permissions) {
2794   std::string path{file_spec.GetPath(false)};
2795   Error error;
2796   lldb_private::StreamString stream;
2797   stream.PutCString("vFile:mode:");
2798   stream.PutCStringAsRawHex8(path.c_str());
2799   StringExtractorGDBRemote response;
2800   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2801       PacketResult::Success) {
2802     if (response.GetChar() != 'F') {
2803       error.SetErrorStringWithFormat("invalid response to '%s' packet",
2804                                      stream.GetString().c_str());
2805     } else {
2806       const uint32_t mode = response.GetS32(-1);
2807       if (static_cast<int32_t>(mode) == -1) {
2808         if (response.GetChar() == ',') {
2809           int response_errno = response.GetS32(-1);
2810           if (response_errno > 0)
2811             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2812           else
2813             error.SetErrorToGenericError();
2814         } else
2815           error.SetErrorToGenericError();
2816       } else {
2817         file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2818       }
2819     }
2820   } else {
2821     error.SetErrorStringWithFormat("failed to send '%s' packet",
2822                                    stream.GetString().c_str());
2823   }
2824   return error;
2825 }
2826 
2827 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2828                                                 uint64_t offset, void *dst,
2829                                                 uint64_t dst_len,
2830                                                 Error &error) {
2831   lldb_private::StreamString stream;
2832   stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2833                 offset);
2834   StringExtractorGDBRemote response;
2835   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2836       PacketResult::Success) {
2837     if (response.GetChar() != 'F')
2838       return 0;
2839     uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2840     if (retcode == UINT32_MAX)
2841       return retcode;
2842     const char next = (response.Peek() ? *response.Peek() : 0);
2843     if (next == ',')
2844       return 0;
2845     if (next == ';') {
2846       response.GetChar(); // skip the semicolon
2847       std::string buffer;
2848       if (response.GetEscapedBinaryData(buffer)) {
2849         const uint64_t data_to_write =
2850             std::min<uint64_t>(dst_len, buffer.size());
2851         if (data_to_write > 0)
2852           memcpy(dst, &buffer[0], data_to_write);
2853         return data_to_write;
2854       }
2855     }
2856   }
2857   return 0;
2858 }
2859 
2860 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2861                                                  uint64_t offset,
2862                                                  const void *src,
2863                                                  uint64_t src_len,
2864                                                  Error &error) {
2865   lldb_private::StreamGDBRemote stream;
2866   stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2867   stream.PutEscapedBytes(src, src_len);
2868   StringExtractorGDBRemote response;
2869   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2870       PacketResult::Success) {
2871     if (response.GetChar() != 'F') {
2872       error.SetErrorStringWithFormat("write file failed");
2873       return 0;
2874     }
2875     uint64_t bytes_written = response.GetU64(UINT64_MAX);
2876     if (bytes_written == UINT64_MAX) {
2877       error.SetErrorToGenericError();
2878       if (response.GetChar() == ',') {
2879         int response_errno = response.GetS32(-1);
2880         if (response_errno > 0)
2881           error.SetError(response_errno, lldb::eErrorTypePOSIX);
2882       }
2883       return 0;
2884     }
2885     return bytes_written;
2886   } else {
2887     error.SetErrorString("failed to send vFile:pwrite packet");
2888   }
2889   return 0;
2890 }
2891 
2892 Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2893                                                   const FileSpec &dst) {
2894   std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2895   Error error;
2896   lldb_private::StreamGDBRemote stream;
2897   stream.PutCString("vFile:symlink:");
2898   // the unix symlink() command reverses its parameters where the dst if first,
2899   // so we follow suit here
2900   stream.PutCStringAsRawHex8(dst_path.c_str());
2901   stream.PutChar(',');
2902   stream.PutCStringAsRawHex8(src_path.c_str());
2903   StringExtractorGDBRemote response;
2904   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2905       PacketResult::Success) {
2906     if (response.GetChar() == 'F') {
2907       uint32_t result = response.GetU32(UINT32_MAX);
2908       if (result != 0) {
2909         error.SetErrorToGenericError();
2910         if (response.GetChar() == ',') {
2911           int response_errno = response.GetS32(-1);
2912           if (response_errno > 0)
2913             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2914         }
2915       }
2916     } else {
2917       // Should have returned with 'F<result>[,<errno>]'
2918       error.SetErrorStringWithFormat("symlink failed");
2919     }
2920   } else {
2921     error.SetErrorString("failed to send vFile:symlink packet");
2922   }
2923   return error;
2924 }
2925 
2926 Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2927   std::string path{file_spec.GetPath(false)};
2928   Error error;
2929   lldb_private::StreamGDBRemote stream;
2930   stream.PutCString("vFile:unlink:");
2931   // the unix symlink() command reverses its parameters where the dst if first,
2932   // so we follow suit here
2933   stream.PutCStringAsRawHex8(path.c_str());
2934   StringExtractorGDBRemote response;
2935   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2936       PacketResult::Success) {
2937     if (response.GetChar() == 'F') {
2938       uint32_t result = response.GetU32(UINT32_MAX);
2939       if (result != 0) {
2940         error.SetErrorToGenericError();
2941         if (response.GetChar() == ',') {
2942           int response_errno = response.GetS32(-1);
2943           if (response_errno > 0)
2944             error.SetError(response_errno, lldb::eErrorTypePOSIX);
2945         }
2946       }
2947     } else {
2948       // Should have returned with 'F<result>[,<errno>]'
2949       error.SetErrorStringWithFormat("unlink failed");
2950     }
2951   } else {
2952     error.SetErrorString("failed to send vFile:unlink packet");
2953   }
2954   return error;
2955 }
2956 
2957 // Extension of host I/O packets to get whether a file exists.
2958 bool GDBRemoteCommunicationClient::GetFileExists(
2959     const lldb_private::FileSpec &file_spec) {
2960   std::string path(file_spec.GetPath(false));
2961   lldb_private::StreamString stream;
2962   stream.PutCString("vFile:exists:");
2963   stream.PutCStringAsRawHex8(path.c_str());
2964   StringExtractorGDBRemote response;
2965   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2966       PacketResult::Success) {
2967     if (response.GetChar() != 'F')
2968       return false;
2969     if (response.GetChar() != ',')
2970       return false;
2971     bool retcode = (response.GetChar() != '0');
2972     return retcode;
2973   }
2974   return false;
2975 }
2976 
2977 bool GDBRemoteCommunicationClient::CalculateMD5(
2978     const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2979   std::string path(file_spec.GetPath(false));
2980   lldb_private::StreamString stream;
2981   stream.PutCString("vFile:MD5:");
2982   stream.PutCStringAsRawHex8(path.c_str());
2983   StringExtractorGDBRemote response;
2984   if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2985       PacketResult::Success) {
2986     if (response.GetChar() != 'F')
2987       return false;
2988     if (response.GetChar() != ',')
2989       return false;
2990     if (response.Peek() && *response.Peek() == 'x')
2991       return false;
2992     low = response.GetHexMaxU64(false, UINT64_MAX);
2993     high = response.GetHexMaxU64(false, UINT64_MAX);
2994     return true;
2995   }
2996   return false;
2997 }
2998 
2999 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3000   // Some targets have issues with g/G packets and we need to avoid using them
3001   if (m_avoid_g_packets == eLazyBoolCalculate) {
3002     if (process) {
3003       m_avoid_g_packets = eLazyBoolNo;
3004       const ArchSpec &arch = process->GetTarget().GetArchitecture();
3005       if (arch.IsValid() &&
3006           arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3007           arch.GetTriple().getOS() == llvm::Triple::IOS &&
3008           arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3009         m_avoid_g_packets = eLazyBoolYes;
3010         uint32_t gdb_server_version = GetGDBServerProgramVersion();
3011         if (gdb_server_version != 0) {
3012           const char *gdb_server_name = GetGDBServerProgramName();
3013           if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3014             if (gdb_server_version >= 310)
3015               m_avoid_g_packets = eLazyBoolNo;
3016           }
3017         }
3018       }
3019     }
3020   }
3021   return m_avoid_g_packets == eLazyBoolYes;
3022 }
3023 
3024 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3025                                                         uint32_t reg) {
3026   StreamString payload;
3027   payload.Printf("p%x", reg);
3028   StringExtractorGDBRemote response;
3029   if (SendThreadSpecificPacketAndWaitForResponse(
3030           tid, std::move(payload), response, false) != PacketResult::Success ||
3031       !response.IsNormalResponse())
3032     return nullptr;
3033 
3034   DataBufferSP buffer_sp(
3035       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3036   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3037   return buffer_sp;
3038 }
3039 
3040 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3041   StreamString payload;
3042   payload.PutChar('g');
3043   StringExtractorGDBRemote response;
3044   if (SendThreadSpecificPacketAndWaitForResponse(
3045           tid, std::move(payload), response, false) != PacketResult::Success ||
3046       !response.IsNormalResponse())
3047     return nullptr;
3048 
3049   DataBufferSP buffer_sp(
3050       new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3051   response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3052   return buffer_sp;
3053 }
3054 
3055 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3056                                                  uint32_t reg_num,
3057                                                  llvm::ArrayRef<uint8_t> data) {
3058   StreamString payload;
3059   payload.Printf("P%x=", reg_num);
3060   payload.PutBytesAsRawHex8(data.data(), data.size(),
3061                             endian::InlHostByteOrder(),
3062                             endian::InlHostByteOrder());
3063   StringExtractorGDBRemote response;
3064   return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3065                                                     response, false) ==
3066              PacketResult::Success &&
3067          response.IsOKResponse();
3068 }
3069 
3070 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3071     lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3072   StreamString payload;
3073   payload.PutChar('G');
3074   payload.PutBytesAsRawHex8(data.data(), data.size(),
3075                             endian::InlHostByteOrder(),
3076                             endian::InlHostByteOrder());
3077   StringExtractorGDBRemote response;
3078   return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3079                                                     response, false) ==
3080              PacketResult::Success &&
3081          response.IsOKResponse();
3082 }
3083 
3084 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3085                                                      uint32_t &save_id) {
3086   save_id = 0; // Set to invalid save ID
3087   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3088     return false;
3089 
3090   m_supports_QSaveRegisterState = eLazyBoolYes;
3091   StreamString payload;
3092   payload.PutCString("QSaveRegisterState");
3093   StringExtractorGDBRemote response;
3094   if (SendThreadSpecificPacketAndWaitForResponse(
3095           tid, std::move(payload), response, false) != PacketResult::Success)
3096     return false;
3097 
3098   if (response.IsUnsupportedResponse())
3099     m_supports_QSaveRegisterState = eLazyBoolNo;
3100 
3101   const uint32_t response_save_id = response.GetU32(0);
3102   if (response_save_id == 0)
3103     return false;
3104 
3105   save_id = response_save_id;
3106   return true;
3107 }
3108 
3109 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3110                                                         uint32_t save_id) {
3111   // We use the "m_supports_QSaveRegisterState" variable here because the
3112   // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3113   // in
3114   // order to be useful
3115   if (m_supports_QSaveRegisterState == eLazyBoolNo)
3116     return false;
3117 
3118   StreamString payload;
3119   payload.Printf("QRestoreRegisterState:%u", save_id);
3120   StringExtractorGDBRemote response;
3121   if (SendThreadSpecificPacketAndWaitForResponse(
3122           tid, std::move(payload), response, false) != PacketResult::Success)
3123     return false;
3124 
3125   if (response.IsOKResponse())
3126     return true;
3127 
3128   if (response.IsUnsupportedResponse())
3129     m_supports_QSaveRegisterState = eLazyBoolNo;
3130   return false;
3131 }
3132 
3133 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3134   if (!GetSyncThreadStateSupported())
3135     return false;
3136 
3137   StreamString packet;
3138   StringExtractorGDBRemote response;
3139   packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3140   return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3141              GDBRemoteCommunication::PacketResult::Success &&
3142          response.IsOKResponse();
3143 }
3144 
3145 bool GDBRemoteCommunicationClient::GetModuleInfo(
3146     const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3147     ModuleSpec &module_spec) {
3148   if (!m_supports_qModuleInfo)
3149     return false;
3150 
3151   std::string module_path = module_file_spec.GetPath(false);
3152   if (module_path.empty())
3153     return false;
3154 
3155   StreamString packet;
3156   packet.PutCString("qModuleInfo:");
3157   packet.PutCStringAsRawHex8(module_path.c_str());
3158   packet.PutCString(";");
3159   const auto &triple = arch_spec.GetTriple().getTriple();
3160   packet.PutCStringAsRawHex8(triple.c_str());
3161 
3162   StringExtractorGDBRemote response;
3163   if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3164       PacketResult::Success)
3165     return false;
3166 
3167   if (response.IsErrorResponse())
3168     return false;
3169 
3170   if (response.IsUnsupportedResponse()) {
3171     m_supports_qModuleInfo = false;
3172     return false;
3173   }
3174 
3175   llvm::StringRef name;
3176   llvm::StringRef value;
3177 
3178   module_spec.Clear();
3179   module_spec.GetFileSpec() = module_file_spec;
3180 
3181   while (response.GetNameColonValue(name, value)) {
3182     if (name == "uuid" || name == "md5") {
3183       StringExtractor extractor(value);
3184       std::string uuid;
3185       extractor.GetHexByteString(uuid);
3186       module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3187     } else if (name == "triple") {
3188       StringExtractor extractor(value);
3189       std::string triple;
3190       extractor.GetHexByteString(triple);
3191       module_spec.GetArchitecture().SetTriple(triple.c_str());
3192     } else if (name == "file_offset") {
3193       uint64_t ival = 0;
3194       if (!value.getAsInteger(16, ival))
3195         module_spec.SetObjectOffset(ival);
3196     } else if (name == "file_size") {
3197       uint64_t ival = 0;
3198       if (!value.getAsInteger(16, ival))
3199         module_spec.SetObjectSize(ival);
3200     } else if (name == "file_path") {
3201       StringExtractor extractor(value);
3202       std::string path;
3203       extractor.GetHexByteString(path);
3204       module_spec.GetFileSpec() = FileSpec(path.c_str(), false, arch_spec);
3205     }
3206   }
3207 
3208   return true;
3209 }
3210 
3211 static llvm::Optional<ModuleSpec>
3212 ParseModuleSpec(StructuredData::Dictionary *dict) {
3213   ModuleSpec result;
3214   if (!dict)
3215     return llvm::None;
3216 
3217   std::string string;
3218   uint64_t integer;
3219 
3220   if (!dict->GetValueForKeyAsString("uuid", string))
3221     return llvm::None;
3222   result.GetUUID().SetFromCString(string.c_str(), string.size());
3223 
3224   if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3225     return llvm::None;
3226   result.SetObjectOffset(integer);
3227 
3228   if (!dict->GetValueForKeyAsInteger("file_size", integer))
3229     return llvm::None;
3230   result.SetObjectSize(integer);
3231 
3232   if (!dict->GetValueForKeyAsString("triple", string))
3233     return llvm::None;
3234   result.GetArchitecture().SetTriple(string.c_str());
3235 
3236   if (!dict->GetValueForKeyAsString("file_path", string))
3237     return llvm::None;
3238   result.GetFileSpec() = FileSpec(string, false, result.GetArchitecture());
3239 
3240   return result;
3241 }
3242 
3243 llvm::Optional<std::vector<ModuleSpec>>
3244 GDBRemoteCommunicationClient::GetModulesInfo(
3245     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3246   if (!m_supports_jModulesInfo)
3247     return llvm::None;
3248 
3249   JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3250   for (const FileSpec &module_file_spec : module_file_specs) {
3251     JSONObject::SP module_sp = std::make_shared<JSONObject>();
3252     module_array_sp->AppendObject(module_sp);
3253     module_sp->SetObject(
3254         "file", std::make_shared<JSONString>(module_file_spec.GetPath()));
3255     module_sp->SetObject("triple",
3256                          std::make_shared<JSONString>(triple.getTriple()));
3257   }
3258   StreamString unescaped_payload;
3259   unescaped_payload.PutCString("jModulesInfo:");
3260   module_array_sp->Write(unescaped_payload);
3261   StreamGDBRemote payload;
3262   payload.PutEscapedBytes(unescaped_payload.GetData(),
3263                           unescaped_payload.GetSize());
3264 
3265   StringExtractorGDBRemote response;
3266   if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3267           PacketResult::Success ||
3268       response.IsErrorResponse())
3269     return llvm::None;
3270 
3271   if (response.IsUnsupportedResponse()) {
3272     m_supports_jModulesInfo = false;
3273     return llvm::None;
3274   }
3275 
3276   StructuredData::ObjectSP response_object_sp =
3277       StructuredData::ParseJSON(response.GetStringRef());
3278   if (!response_object_sp)
3279     return llvm::None;
3280 
3281   StructuredData::Array *response_array = response_object_sp->GetAsArray();
3282   if (!response_array)
3283     return llvm::None;
3284 
3285   std::vector<ModuleSpec> result;
3286   for (size_t i = 0; i < response_array->GetSize(); ++i) {
3287     if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3288             response_array->GetItemAtIndex(i)->GetAsDictionary()))
3289       result.push_back(*module_spec);
3290   }
3291 
3292   return result;
3293 }
3294 
3295 // query the target remote for extended information using the qXfer packet
3296 //
3297 // example: object='features', annex='target.xml', out=<xml output>
3298 // return:  'true'  on success
3299 //          'false' on failure (err set)
3300 bool GDBRemoteCommunicationClient::ReadExtFeature(
3301     const lldb_private::ConstString object,
3302     const lldb_private::ConstString annex, std::string &out,
3303     lldb_private::Error &err) {
3304 
3305   std::stringstream output;
3306   StringExtractorGDBRemote chunk;
3307 
3308   uint64_t size = GetRemoteMaxPacketSize();
3309   if (size == 0)
3310     size = 0x1000;
3311   size = size - 1; // Leave space for the 'm' or 'l' character in the response
3312   int offset = 0;
3313   bool active = true;
3314 
3315   // loop until all data has been read
3316   while (active) {
3317 
3318     // send query extended feature packet
3319     std::stringstream packet;
3320     packet << "qXfer:" << object.AsCString("")
3321            << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3322            << "," << std::hex << size;
3323 
3324     GDBRemoteCommunication::PacketResult res =
3325         SendPacketAndWaitForResponse(packet.str().c_str(), chunk, false);
3326 
3327     if (res != GDBRemoteCommunication::PacketResult::Success) {
3328       err.SetErrorString("Error sending $qXfer packet");
3329       return false;
3330     }
3331 
3332     const std::string &str = chunk.GetStringRef();
3333     if (str.length() == 0) {
3334       // should have some data in chunk
3335       err.SetErrorString("Empty response from $qXfer packet");
3336       return false;
3337     }
3338 
3339     // check packet code
3340     switch (str[0]) {
3341     // last chunk
3342     case ('l'):
3343       active = false;
3344       LLVM_FALLTHROUGH;
3345 
3346     // more chunks
3347     case ('m'):
3348       if (str.length() > 1)
3349         output << &str[1];
3350       offset += size;
3351       break;
3352 
3353     // unknown chunk
3354     default:
3355       err.SetErrorString("Invalid continuation code from $qXfer packet");
3356       return false;
3357     }
3358   }
3359 
3360   out = output.str();
3361   err.Success();
3362   return true;
3363 }
3364 
3365 // Notify the target that gdb is prepared to serve symbol lookup requests.
3366 //  packet: "qSymbol::"
3367 //  reply:
3368 //  OK                  The target does not need to look up any (more) symbols.
3369 //  qSymbol:<sym_name>  The target requests the value of symbol sym_name (hex
3370 //  encoded).
3371 //                      LLDB may provide the value by sending another qSymbol
3372 //                      packet
3373 //                      in the form of"qSymbol:<sym_value>:<sym_name>".
3374 //
3375 //  Three examples:
3376 //
3377 //  lldb sends:    qSymbol::
3378 //  lldb receives: OK
3379 //     Remote gdb stub does not need to know the addresses of any symbols, lldb
3380 //     does not
3381 //     need to ask again in this session.
3382 //
3383 //  lldb sends:    qSymbol::
3384 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3385 //  lldb sends:    qSymbol::64697370617463685f71756575655f6f666673657473
3386 //  lldb receives: OK
3387 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb does
3388 //     not know
3389 //     the address at this time.  lldb needs to send qSymbol:: again when it has
3390 //     more
3391 //     solibs loaded.
3392 //
3393 //  lldb sends:    qSymbol::
3394 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3395 //  lldb sends:    qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3396 //  lldb receives: OK
3397 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb says
3398 //     that it
3399 //     is at address 0x2bc97554.  Remote gdb stub sends 'OK' indicating that it
3400 //     does not
3401 //     need any more symbols.  lldb does not need to ask again in this session.
3402 
3403 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3404     lldb_private::Process *process) {
3405   // Set to true once we've resolved a symbol to an address for the remote stub.
3406   // If we get an 'OK' response after this, the remote stub doesn't need any
3407   // more
3408   // symbols and we can stop asking.
3409   bool symbol_response_provided = false;
3410 
3411   // Is this the initial qSymbol:: packet?
3412   bool first_qsymbol_query = true;
3413 
3414   if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3415     Lock lock(*this, false);
3416     if (lock) {
3417       StreamString packet;
3418       packet.PutCString("qSymbol::");
3419       StringExtractorGDBRemote response;
3420       while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3421              PacketResult::Success) {
3422         if (response.IsOKResponse()) {
3423           if (symbol_response_provided || first_qsymbol_query) {
3424             m_qSymbol_requests_done = true;
3425           }
3426 
3427           // We are done serving symbols requests
3428           return;
3429         }
3430         first_qsymbol_query = false;
3431 
3432         if (response.IsUnsupportedResponse()) {
3433           // qSymbol is not supported by the current GDB server we are connected
3434           // to
3435           m_supports_qSymbol = false;
3436           return;
3437         } else {
3438           llvm::StringRef response_str(response.GetStringRef());
3439           if (response_str.startswith("qSymbol:")) {
3440             response.SetFilePos(strlen("qSymbol:"));
3441             std::string symbol_name;
3442             if (response.GetHexByteString(symbol_name)) {
3443               if (symbol_name.empty())
3444                 return;
3445 
3446               addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3447               lldb_private::SymbolContextList sc_list;
3448               if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3449                       ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3450                 const size_t num_scs = sc_list.GetSize();
3451                 for (size_t sc_idx = 0;
3452                      sc_idx < num_scs &&
3453                      symbol_load_addr == LLDB_INVALID_ADDRESS;
3454                      ++sc_idx) {
3455                   SymbolContext sc;
3456                   if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3457                     if (sc.symbol) {
3458                       switch (sc.symbol->GetType()) {
3459                       case eSymbolTypeInvalid:
3460                       case eSymbolTypeAbsolute:
3461                       case eSymbolTypeUndefined:
3462                       case eSymbolTypeSourceFile:
3463                       case eSymbolTypeHeaderFile:
3464                       case eSymbolTypeObjectFile:
3465                       case eSymbolTypeCommonBlock:
3466                       case eSymbolTypeBlock:
3467                       case eSymbolTypeLocal:
3468                       case eSymbolTypeParam:
3469                       case eSymbolTypeVariable:
3470                       case eSymbolTypeVariableType:
3471                       case eSymbolTypeLineEntry:
3472                       case eSymbolTypeLineHeader:
3473                       case eSymbolTypeScopeBegin:
3474                       case eSymbolTypeScopeEnd:
3475                       case eSymbolTypeAdditional:
3476                       case eSymbolTypeCompiler:
3477                       case eSymbolTypeInstrumentation:
3478                       case eSymbolTypeTrampoline:
3479                         break;
3480 
3481                       case eSymbolTypeCode:
3482                       case eSymbolTypeResolver:
3483                       case eSymbolTypeData:
3484                       case eSymbolTypeRuntime:
3485                       case eSymbolTypeException:
3486                       case eSymbolTypeObjCClass:
3487                       case eSymbolTypeObjCMetaClass:
3488                       case eSymbolTypeObjCIVar:
3489                       case eSymbolTypeReExported:
3490                         symbol_load_addr =
3491                             sc.symbol->GetLoadAddress(&process->GetTarget());
3492                         break;
3493                       }
3494                     }
3495                   }
3496                 }
3497               }
3498               // This is the normal path where our symbol lookup was successful
3499               // and we want
3500               // to send a packet with the new symbol value and see if another
3501               // lookup needs to be
3502               // done.
3503 
3504               // Change "packet" to contain the requested symbol value and name
3505               packet.Clear();
3506               packet.PutCString("qSymbol:");
3507               if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3508                 packet.Printf("%" PRIx64, symbol_load_addr);
3509                 symbol_response_provided = true;
3510               } else {
3511                 symbol_response_provided = false;
3512               }
3513               packet.PutCString(":");
3514               packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3515               continue; // go back to the while loop and send "packet" and wait
3516                         // for another response
3517             }
3518           }
3519         }
3520       }
3521       // If we make it here, the symbol request packet response wasn't valid or
3522       // our symbol lookup failed so we must abort
3523       return;
3524 
3525     } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3526                    GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3527       log->Printf(
3528           "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3529           __FUNCTION__);
3530     }
3531   }
3532 }
3533 
3534 StructuredData::Array *
3535 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3536   if (!m_supported_async_json_packets_is_valid) {
3537     // Query the server for the array of supported asynchronous JSON
3538     // packets.
3539     m_supported_async_json_packets_is_valid = true;
3540 
3541     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3542 
3543     // Poll it now.
3544     StringExtractorGDBRemote response;
3545     const bool send_async = false;
3546     if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3547                                      send_async) == PacketResult::Success) {
3548       m_supported_async_json_packets_sp =
3549           StructuredData::ParseJSON(response.GetStringRef());
3550       if (m_supported_async_json_packets_sp &&
3551           !m_supported_async_json_packets_sp->GetAsArray()) {
3552         // We were returned something other than a JSON array.  This
3553         // is invalid.  Clear it out.
3554         if (log)
3555           log->Printf("GDBRemoteCommunicationClient::%s(): "
3556                       "QSupportedAsyncJSONPackets returned invalid "
3557                       "result: %s",
3558                       __FUNCTION__, response.GetStringRef().c_str());
3559         m_supported_async_json_packets_sp.reset();
3560       }
3561     } else {
3562       if (log)
3563         log->Printf("GDBRemoteCommunicationClient::%s(): "
3564                     "QSupportedAsyncJSONPackets unsupported",
3565                     __FUNCTION__);
3566     }
3567 
3568     if (log && m_supported_async_json_packets_sp) {
3569       StreamString stream;
3570       m_supported_async_json_packets_sp->Dump(stream);
3571       log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3572                   "JSON packets: %s",
3573                   __FUNCTION__, stream.GetString().c_str());
3574     }
3575   }
3576 
3577   return m_supported_async_json_packets_sp
3578              ? m_supported_async_json_packets_sp->GetAsArray()
3579              : nullptr;
3580 }
3581 
3582 Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3583     const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3584   Error error;
3585 
3586   if (type_name.GetLength() == 0) {
3587     error.SetErrorString("invalid type_name argument");
3588     return error;
3589   }
3590 
3591   // Build command: Configure{type_name}: serialized config
3592   // data.
3593   StreamGDBRemote stream;
3594   stream.PutCString("QConfigure");
3595   stream.PutCString(type_name.AsCString());
3596   stream.PutChar(':');
3597   if (config_sp) {
3598     // Gather the plain-text version of the configuration data.
3599     StreamString unescaped_stream;
3600     config_sp->Dump(unescaped_stream);
3601     unescaped_stream.Flush();
3602 
3603     // Add it to the stream in escaped fashion.
3604     stream.PutEscapedBytes(unescaped_stream.GetData(),
3605                            unescaped_stream.GetSize());
3606   }
3607   stream.Flush();
3608 
3609   // Send the packet.
3610   const bool send_async = false;
3611   StringExtractorGDBRemote response;
3612   auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(),
3613                                              response, send_async);
3614   if (result == PacketResult::Success) {
3615     // We failed if the config result comes back other than OK.
3616     if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3617       // Okay!
3618       error.Clear();
3619     } else {
3620       error.SetErrorStringWithFormat("configuring StructuredData feature "
3621                                      "%s failed with error %s",
3622                                      type_name.AsCString(),
3623                                      response.GetStringRef().c_str());
3624     }
3625   } else {
3626     // Can we get more data here on the failure?
3627     error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3628                                    "failed when sending packet: "
3629                                    "PacketResult=%d",
3630                                    type_name.AsCString(), (int)result);
3631   }
3632   return error;
3633 }
3634 
3635 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3636   GDBRemoteClientBase::OnRunPacketSent(first);
3637   m_curr_tid = LLDB_INVALID_THREAD_ID;
3638 }
3639