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