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