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