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