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