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