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