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