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