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