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