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