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