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