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