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