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