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