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