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