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