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