1 //===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 
11 #include "GDBRemoteCommunicationClient.h"
12 
13 // C Includes
14 #include <sys/stat.h>
15 
16 // C++ Includes
17 #include <sstream>
18 
19 // Other libraries and framework includes
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "lldb/Interpreter/Args.h"
23 #include "lldb/Core/ConnectionFileDescriptor.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Core/StreamGDBRemote.h"
27 #include "lldb/Core/StreamString.h"
28 #include "lldb/Host/Endian.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Host/TimeValue.h"
31 #include "lldb/Target/Target.h"
32 
33 // Project includes
34 #include "Utility/StringExtractorGDBRemote.h"
35 #include "ProcessGDBRemote.h"
36 #include "ProcessGDBRemoteLog.h"
37 #include "lldb/Host/Config.h"
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 #if defined(LLDB_DISABLE_POSIX) && !defined(SIGSTOP)
43 #define SIGSTOP 17
44 #endif
45 
46 //----------------------------------------------------------------------
47 // GDBRemoteCommunicationClient constructor
48 //----------------------------------------------------------------------
49 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
50     GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
51     m_supports_not_sending_acks (eLazyBoolCalculate),
52     m_supports_thread_suffix (eLazyBoolCalculate),
53     m_supports_threads_in_stop_reply (eLazyBoolCalculate),
54     m_supports_vCont_all (eLazyBoolCalculate),
55     m_supports_vCont_any (eLazyBoolCalculate),
56     m_supports_vCont_c (eLazyBoolCalculate),
57     m_supports_vCont_C (eLazyBoolCalculate),
58     m_supports_vCont_s (eLazyBoolCalculate),
59     m_supports_vCont_S (eLazyBoolCalculate),
60     m_qHostInfo_is_valid (eLazyBoolCalculate),
61     m_curr_pid_is_valid (eLazyBoolCalculate),
62     m_qProcessInfo_is_valid (eLazyBoolCalculate),
63     m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
64     m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
65     m_supports_memory_region_info  (eLazyBoolCalculate),
66     m_supports_watchpoint_support_info  (eLazyBoolCalculate),
67     m_supports_detach_stay_stopped (eLazyBoolCalculate),
68     m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
69     m_attach_or_wait_reply(eLazyBoolCalculate),
70     m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
71     m_supports_p (eLazyBoolCalculate),
72     m_supports_x (eLazyBoolCalculate),
73     m_avoid_g_packets (eLazyBoolCalculate),
74     m_supports_QSaveRegisterState (eLazyBoolCalculate),
75     m_supports_qXfer_auxv_read (eLazyBoolCalculate),
76     m_supports_qXfer_libraries_read (eLazyBoolCalculate),
77     m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
78     m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
79     m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
80     m_supports_qProcessInfoPID (true),
81     m_supports_qfProcessInfo (true),
82     m_supports_qUserName (true),
83     m_supports_qGroupName (true),
84     m_supports_qThreadStopInfo (true),
85     m_supports_z0 (true),
86     m_supports_z1 (true),
87     m_supports_z2 (true),
88     m_supports_z3 (true),
89     m_supports_z4 (true),
90     m_supports_QEnvironment (true),
91     m_supports_QEnvironmentHexEncoded (true),
92     m_curr_pid (LLDB_INVALID_PROCESS_ID),
93     m_curr_tid (LLDB_INVALID_THREAD_ID),
94     m_curr_tid_run (LLDB_INVALID_THREAD_ID),
95     m_num_supported_hardware_watchpoints (0),
96     m_async_mutex (Mutex::eMutexTypeRecursive),
97     m_async_packet_predicate (false),
98     m_async_packet (),
99     m_async_result (PacketResult::Success),
100     m_async_response (),
101     m_async_signal (-1),
102     m_interrupt_sent (false),
103     m_thread_id_to_used_usec_map (),
104     m_host_arch(),
105     m_process_arch(),
106     m_os_version_major (UINT32_MAX),
107     m_os_version_minor (UINT32_MAX),
108     m_os_version_update (UINT32_MAX),
109     m_os_build (),
110     m_os_kernel (),
111     m_hostname (),
112     m_gdb_server_name(),
113     m_gdb_server_version(UINT32_MAX),
114     m_default_packet_timeout (0),
115     m_max_packet_size (0)
116 {
117 }
118 
119 //----------------------------------------------------------------------
120 // Destructor
121 //----------------------------------------------------------------------
122 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
123 {
124     if (IsConnected())
125         Disconnect();
126 }
127 
128 bool
129 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
130 {
131     ResetDiscoverableSettings();
132 
133     // Start the read thread after we send the handshake ack since if we
134     // fail to send the handshake ack, there is no reason to continue...
135     if (SendAck())
136     {
137         // Wait for any responses that might have been queued up in the remote
138         // GDB server and flush them all
139         StringExtractorGDBRemote response;
140         PacketResult packet_result = PacketResult::Success;
141         const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
142         while (packet_result == PacketResult::Success)
143             packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
144 
145         // The return value from QueryNoAckModeSupported() is true if the packet
146         // was sent and _any_ response (including UNIMPLEMENTED) was received),
147         // or false if no response was received. This quickly tells us if we have
148         // a live connection to a remote GDB server...
149         if (QueryNoAckModeSupported())
150         {
151 #if 0
152             // Set above line to "#if 1" to test packet speed if remote GDB server
153             // supports the qSpeedTest packet...
154             TestPacketSpeed(10000);
155 #endif
156             return true;
157         }
158         else
159         {
160             if (error_ptr)
161                 error_ptr->SetErrorString("failed to get reply to handshake packet");
162         }
163     }
164     else
165     {
166         if (error_ptr)
167             error_ptr->SetErrorString("failed to send the handshake ack");
168     }
169     return false;
170 }
171 
172 bool
173 GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
174 {
175     if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
176     {
177         GetRemoteQSupported();
178     }
179     return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
180 }
181 
182 bool
183 GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
184 {
185     if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
186     {
187         GetRemoteQSupported();
188     }
189     return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
190 }
191 
192 bool
193 GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
194 {
195     if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
196     {
197         GetRemoteQSupported();
198     }
199     return (m_supports_qXfer_libraries_read == eLazyBoolYes);
200 }
201 
202 bool
203 GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
204 {
205     if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
206     {
207         GetRemoteQSupported();
208     }
209     return (m_supports_qXfer_auxv_read == eLazyBoolYes);
210 }
211 
212 uint64_t
213 GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
214 {
215     if (m_max_packet_size == 0)
216     {
217         GetRemoteQSupported();
218     }
219     return m_max_packet_size;
220 }
221 
222 bool
223 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
224 {
225     if (m_supports_not_sending_acks == eLazyBoolCalculate)
226     {
227         m_send_acks = true;
228         m_supports_not_sending_acks = eLazyBoolNo;
229 
230         // This is the first real packet that we'll send in a debug session and it may take a little
231         // longer than normal to receive a reply.  Wait at least 6 seconds for a reply to this packet.
232 
233         const uint32_t minimum_timeout = 6;
234         uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
235         SetPacketTimeout (std::max (old_timeout, minimum_timeout));
236 
237         StringExtractorGDBRemote response;
238         PacketResult packet_send_result = SendPacketAndWaitForResponse("QStartNoAckMode", response, false);
239         SetPacketTimeout (old_timeout);
240 
241         if (packet_send_result == 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 ()
1213 {
1214     if (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 ();
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 = Args::StringToUInt32(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 = Args::StringToUInt32 (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 = Args::StringToUInt32 (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                         triple.swap(value);
1646                         ++num_keys_decoded;
1647                     }
1648                     else if (name.compare ("distribution_id") == 0)
1649                     {
1650                         extractor.GetStringRef ().swap (value);
1651                         extractor.SetFilePos (0);
1652                         extractor.GetHexByteString (distribution_id);
1653                         ++num_keys_decoded;
1654                     }
1655                     else if (name.compare("os_build") == 0)
1656                     {
1657                         extractor.GetStringRef().swap(value);
1658                         extractor.SetFilePos(0);
1659                         extractor.GetHexByteString (m_os_build);
1660                         ++num_keys_decoded;
1661                     }
1662                     else if (name.compare("hostname") == 0)
1663                     {
1664                         extractor.GetStringRef().swap(value);
1665                         extractor.SetFilePos(0);
1666                         extractor.GetHexByteString (m_hostname);
1667                         ++num_keys_decoded;
1668                     }
1669                     else if (name.compare("os_kernel") == 0)
1670                     {
1671                         extractor.GetStringRef().swap(value);
1672                         extractor.SetFilePos(0);
1673                         extractor.GetHexByteString (m_os_kernel);
1674                         ++num_keys_decoded;
1675                     }
1676                     else if (name.compare("ostype") == 0)
1677                     {
1678                         os_name.swap (value);
1679                         ++num_keys_decoded;
1680                     }
1681                     else if (name.compare("vendor") == 0)
1682                     {
1683                         vendor_name.swap(value);
1684                         ++num_keys_decoded;
1685                     }
1686                     else if (name.compare("endian") == 0)
1687                     {
1688                         ++num_keys_decoded;
1689                         if (value.compare("little") == 0)
1690                             byte_order = eByteOrderLittle;
1691                         else if (value.compare("big") == 0)
1692                             byte_order = eByteOrderBig;
1693                         else if (value.compare("pdp") == 0)
1694                             byte_order = eByteOrderPDP;
1695                         else
1696                             --num_keys_decoded;
1697                     }
1698                     else if (name.compare("ptrsize") == 0)
1699                     {
1700                         pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1701                         if (pointer_byte_size != 0)
1702                             ++num_keys_decoded;
1703                     }
1704                     else if (name.compare("os_version") == 0)
1705                     {
1706                         Args::StringToVersion (value.c_str(),
1707                                                m_os_version_major,
1708                                                m_os_version_minor,
1709                                                m_os_version_update);
1710                         if (m_os_version_major != UINT32_MAX)
1711                             ++num_keys_decoded;
1712                     }
1713                     else if (name.compare("watchpoint_exceptions_received") == 0)
1714                     {
1715                         ++num_keys_decoded;
1716                         if (strcmp(value.c_str(),"before") == 0)
1717                             m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1718                         else if (strcmp(value.c_str(),"after") == 0)
1719                             m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1720                         else
1721                             --num_keys_decoded;
1722                     }
1723                     else if (name.compare("default_packet_timeout") == 0)
1724                     {
1725                         m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1726                         if (m_default_packet_timeout > 0)
1727                         {
1728                             SetPacketTimeout(m_default_packet_timeout);
1729                             ++num_keys_decoded;
1730                         }
1731                     }
1732 
1733                 }
1734 
1735                 if (num_keys_decoded > 0)
1736                     m_qHostInfo_is_valid = eLazyBoolYes;
1737 
1738                 if (triple.empty())
1739                 {
1740                     if (arch_name.empty())
1741                     {
1742                         if (cpu != LLDB_INVALID_CPUTYPE)
1743                         {
1744                             m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1745                             if (pointer_byte_size)
1746                             {
1747                                 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1748                             }
1749                             if (byte_order != eByteOrderInvalid)
1750                             {
1751                                 assert (byte_order == m_host_arch.GetByteOrder());
1752                             }
1753 
1754                             if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1755                             {
1756                                 switch (m_host_arch.GetMachine())
1757                                 {
1758                                 case llvm::Triple::aarch64:
1759                                 case llvm::Triple::arm:
1760                                 case llvm::Triple::thumb:
1761                                     os_name = "ios";
1762                                     break;
1763                                 default:
1764                                     os_name = "macosx";
1765                                     break;
1766                                 }
1767                             }
1768                             if (!vendor_name.empty())
1769                                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1770                             if (!os_name.empty())
1771                                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1772 
1773                         }
1774                     }
1775                     else
1776                     {
1777                         std::string triple;
1778                         triple += arch_name;
1779                         if (!vendor_name.empty() || !os_name.empty())
1780                         {
1781                             triple += '-';
1782                             if (vendor_name.empty())
1783                                 triple += "unknown";
1784                             else
1785                                 triple += vendor_name;
1786                             triple += '-';
1787                             if (os_name.empty())
1788                                 triple += "unknown";
1789                             else
1790                                 triple += os_name;
1791                         }
1792                         m_host_arch.SetTriple (triple.c_str());
1793 
1794                         llvm::Triple &host_triple = m_host_arch.GetTriple();
1795                         if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1796                         {
1797                             switch (m_host_arch.GetMachine())
1798                             {
1799                                 case llvm::Triple::aarch64:
1800                                 case llvm::Triple::arm:
1801                                 case llvm::Triple::thumb:
1802                                     host_triple.setOS(llvm::Triple::IOS);
1803                                     break;
1804                                 default:
1805                                     host_triple.setOS(llvm::Triple::MacOSX);
1806                                     break;
1807                             }
1808                         }
1809                         if (pointer_byte_size)
1810                         {
1811                             assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1812                         }
1813                         if (byte_order != eByteOrderInvalid)
1814                         {
1815                             assert (byte_order == m_host_arch.GetByteOrder());
1816                         }
1817 
1818                     }
1819                 }
1820                 else
1821                 {
1822                     m_host_arch.SetTriple (triple.c_str());
1823                     if (pointer_byte_size)
1824                     {
1825                         assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1826                     }
1827                     if (byte_order != eByteOrderInvalid)
1828                     {
1829                         assert (byte_order == m_host_arch.GetByteOrder());
1830                     }
1831 
1832                     if (log)
1833                         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 ());
1834                 }
1835                 if (!distribution_id.empty ())
1836                     m_host_arch.SetDistributionId (distribution_id.c_str ());
1837             }
1838         }
1839     }
1840     return m_qHostInfo_is_valid == eLazyBoolYes;
1841 }
1842 
1843 int
1844 GDBRemoteCommunicationClient::SendAttach
1845 (
1846     lldb::pid_t pid,
1847     StringExtractorGDBRemote& response
1848 )
1849 {
1850     if (pid != LLDB_INVALID_PROCESS_ID)
1851     {
1852         char packet[64];
1853         const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1854         assert (packet_len < (int)sizeof(packet));
1855         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1856         {
1857             if (response.IsErrorResponse())
1858                 return response.GetError();
1859             return 0;
1860         }
1861     }
1862     return -1;
1863 }
1864 
1865 const lldb_private::ArchSpec &
1866 GDBRemoteCommunicationClient::GetHostArchitecture ()
1867 {
1868     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1869         GetHostInfo ();
1870     return m_host_arch;
1871 }
1872 
1873 uint32_t
1874 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1875 {
1876     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1877         GetHostInfo ();
1878     return m_default_packet_timeout;
1879 }
1880 
1881 addr_t
1882 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1883 {
1884     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1885     {
1886         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1887         char packet[64];
1888         const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1889                                            (uint64_t)size,
1890                                            permissions & lldb::ePermissionsReadable ? "r" : "",
1891                                            permissions & lldb::ePermissionsWritable ? "w" : "",
1892                                            permissions & lldb::ePermissionsExecutable ? "x" : "");
1893         assert (packet_len < (int)sizeof(packet));
1894         StringExtractorGDBRemote response;
1895         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1896         {
1897             if (response.IsUnsupportedResponse())
1898                 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1899             else if (!response.IsErrorResponse())
1900                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1901         }
1902         else
1903         {
1904             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1905         }
1906     }
1907     return LLDB_INVALID_ADDRESS;
1908 }
1909 
1910 bool
1911 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1912 {
1913     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1914     {
1915         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1916         char packet[64];
1917         const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1918         assert (packet_len < (int)sizeof(packet));
1919         StringExtractorGDBRemote response;
1920         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1921         {
1922             if (response.IsUnsupportedResponse())
1923                 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1924             else if (response.IsOKResponse())
1925                 return true;
1926         }
1927         else
1928         {
1929             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1930         }
1931     }
1932     return false;
1933 }
1934 
1935 Error
1936 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1937 {
1938     Error error;
1939 
1940     if (keep_stopped)
1941     {
1942         if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1943         {
1944             char packet[64];
1945             const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1946             assert (packet_len < (int)sizeof(packet));
1947             StringExtractorGDBRemote response;
1948             if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1949             {
1950                 m_supports_detach_stay_stopped = eLazyBoolYes;
1951             }
1952             else
1953             {
1954                 m_supports_detach_stay_stopped = eLazyBoolNo;
1955             }
1956         }
1957 
1958         if (m_supports_detach_stay_stopped == eLazyBoolNo)
1959         {
1960             error.SetErrorString("Stays stopped not supported by this target.");
1961             return error;
1962         }
1963         else
1964         {
1965             StringExtractorGDBRemote response;
1966             PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
1967             if (packet_result != PacketResult::Success)
1968                 error.SetErrorString ("Sending extended disconnect packet failed.");
1969         }
1970     }
1971     else
1972     {
1973         StringExtractorGDBRemote response;
1974         PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
1975         if (packet_result != PacketResult::Success)
1976             error.SetErrorString ("Sending disconnect packet failed.");
1977     }
1978     return error;
1979 }
1980 
1981 Error
1982 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1983                                                   lldb_private::MemoryRegionInfo &region_info)
1984 {
1985     Error error;
1986     region_info.Clear();
1987 
1988     if (m_supports_memory_region_info != eLazyBoolNo)
1989     {
1990         m_supports_memory_region_info = eLazyBoolYes;
1991         char packet[64];
1992         const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1993         assert (packet_len < (int)sizeof(packet));
1994         StringExtractorGDBRemote response;
1995         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1996         {
1997             std::string name;
1998             std::string value;
1999             addr_t addr_value;
2000             bool success = true;
2001             bool saw_permissions = false;
2002             while (success && response.GetNameColonValue(name, value))
2003             {
2004                 if (name.compare ("start") == 0)
2005                 {
2006                     addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
2007                     if (success)
2008                         region_info.GetRange().SetRangeBase(addr_value);
2009                 }
2010                 else if (name.compare ("size") == 0)
2011                 {
2012                     addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
2013                     if (success)
2014                         region_info.GetRange().SetByteSize (addr_value);
2015                 }
2016                 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
2017                 {
2018                     saw_permissions = true;
2019                     if (region_info.GetRange().Contains (addr))
2020                     {
2021                         if (value.find('r') != std::string::npos)
2022                             region_info.SetReadable (MemoryRegionInfo::eYes);
2023                         else
2024                             region_info.SetReadable (MemoryRegionInfo::eNo);
2025 
2026                         if (value.find('w') != std::string::npos)
2027                             region_info.SetWritable (MemoryRegionInfo::eYes);
2028                         else
2029                             region_info.SetWritable (MemoryRegionInfo::eNo);
2030 
2031                         if (value.find('x') != std::string::npos)
2032                             region_info.SetExecutable (MemoryRegionInfo::eYes);
2033                         else
2034                             region_info.SetExecutable (MemoryRegionInfo::eNo);
2035                     }
2036                     else
2037                     {
2038                         // The reported region does not contain this address -- we're looking at an unmapped page
2039                         region_info.SetReadable (MemoryRegionInfo::eNo);
2040                         region_info.SetWritable (MemoryRegionInfo::eNo);
2041                         region_info.SetExecutable (MemoryRegionInfo::eNo);
2042                     }
2043                 }
2044                 else if (name.compare ("error") == 0)
2045                 {
2046                     StringExtractorGDBRemote name_extractor;
2047                     // Swap "value" over into "name_extractor"
2048                     name_extractor.GetStringRef().swap(value);
2049                     // Now convert the HEX bytes into a string value
2050                     name_extractor.GetHexByteString (value);
2051                     error.SetErrorString(value.c_str());
2052                 }
2053             }
2054 
2055             // We got a valid address range back but no permissions -- which means this is an unmapped page
2056             if (region_info.GetRange().IsValid() && saw_permissions == false)
2057             {
2058                 region_info.SetReadable (MemoryRegionInfo::eNo);
2059                 region_info.SetWritable (MemoryRegionInfo::eNo);
2060                 region_info.SetExecutable (MemoryRegionInfo::eNo);
2061             }
2062         }
2063         else
2064         {
2065             m_supports_memory_region_info = eLazyBoolNo;
2066         }
2067     }
2068 
2069     if (m_supports_memory_region_info == eLazyBoolNo)
2070     {
2071         error.SetErrorString("qMemoryRegionInfo is not supported");
2072     }
2073     if (error.Fail())
2074         region_info.Clear();
2075     return error;
2076 
2077 }
2078 
2079 Error
2080 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2081 {
2082     Error error;
2083 
2084     if (m_supports_watchpoint_support_info == eLazyBoolYes)
2085     {
2086         num = m_num_supported_hardware_watchpoints;
2087         return error;
2088     }
2089 
2090     // Set num to 0 first.
2091     num = 0;
2092     if (m_supports_watchpoint_support_info != eLazyBoolNo)
2093     {
2094         char packet[64];
2095         const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
2096         assert (packet_len < (int)sizeof(packet));
2097         StringExtractorGDBRemote response;
2098         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2099         {
2100             m_supports_watchpoint_support_info = eLazyBoolYes;
2101             std::string name;
2102             std::string value;
2103             while (response.GetNameColonValue(name, value))
2104             {
2105                 if (name.compare ("num") == 0)
2106                 {
2107                     num = Args::StringToUInt32(value.c_str(), 0, 0);
2108                     m_num_supported_hardware_watchpoints = num;
2109                 }
2110             }
2111         }
2112         else
2113         {
2114             m_supports_watchpoint_support_info = eLazyBoolNo;
2115         }
2116     }
2117 
2118     if (m_supports_watchpoint_support_info == eLazyBoolNo)
2119     {
2120         error.SetErrorString("qWatchpointSupportInfo is not supported");
2121     }
2122     return error;
2123 
2124 }
2125 
2126 lldb_private::Error
2127 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2128 {
2129     Error error(GetWatchpointSupportInfo(num));
2130     if (error.Success())
2131         error = GetWatchpointsTriggerAfterInstruction(after);
2132     return error;
2133 }
2134 
2135 lldb_private::Error
2136 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2137 {
2138     Error error;
2139 
2140     // we assume watchpoints will happen after running the relevant opcode
2141     // and we only want to override this behavior if we have explicitly
2142     // received a qHostInfo telling us otherwise
2143     if (m_qHostInfo_is_valid != eLazyBoolYes)
2144         after = true;
2145     else
2146         after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2147     return error;
2148 }
2149 
2150 int
2151 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2152 {
2153     if (path && path[0])
2154     {
2155         StreamString packet;
2156         packet.PutCString("QSetSTDIN:");
2157         packet.PutBytesAsRawHex8(path, strlen(path));
2158 
2159         StringExtractorGDBRemote response;
2160         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2161         {
2162             if (response.IsOKResponse())
2163                 return 0;
2164             uint8_t error = response.GetError();
2165             if (error)
2166                 return error;
2167         }
2168     }
2169     return -1;
2170 }
2171 
2172 int
2173 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2174 {
2175     if (path && path[0])
2176     {
2177         StreamString packet;
2178         packet.PutCString("QSetSTDOUT:");
2179         packet.PutBytesAsRawHex8(path, strlen(path));
2180 
2181         StringExtractorGDBRemote response;
2182         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2183         {
2184             if (response.IsOKResponse())
2185                 return 0;
2186             uint8_t error = response.GetError();
2187             if (error)
2188                 return error;
2189         }
2190     }
2191     return -1;
2192 }
2193 
2194 int
2195 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2196 {
2197     if (path && path[0])
2198     {
2199         StreamString packet;
2200         packet.PutCString("QSetSTDERR:");
2201         packet.PutBytesAsRawHex8(path, strlen(path));
2202 
2203         StringExtractorGDBRemote response;
2204         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2205         {
2206             if (response.IsOKResponse())
2207                 return 0;
2208             uint8_t error = response.GetError();
2209             if (error)
2210                 return error;
2211         }
2212     }
2213     return -1;
2214 }
2215 
2216 bool
2217 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2218 {
2219     StringExtractorGDBRemote response;
2220     if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2221     {
2222         if (response.IsUnsupportedResponse())
2223             return false;
2224         if (response.IsErrorResponse())
2225             return false;
2226         response.GetHexByteString (cwd);
2227         return !cwd.empty();
2228     }
2229     return false;
2230 }
2231 
2232 int
2233 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2234 {
2235     if (path && path[0])
2236     {
2237         StreamString packet;
2238         packet.PutCString("QSetWorkingDir:");
2239         packet.PutBytesAsRawHex8(path, strlen(path));
2240 
2241         StringExtractorGDBRemote response;
2242         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2243         {
2244             if (response.IsOKResponse())
2245                 return 0;
2246             uint8_t error = response.GetError();
2247             if (error)
2248                 return error;
2249         }
2250     }
2251     return -1;
2252 }
2253 
2254 int
2255 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2256 {
2257     char packet[32];
2258     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2259     assert (packet_len < (int)sizeof(packet));
2260     StringExtractorGDBRemote response;
2261     if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2262     {
2263         if (response.IsOKResponse())
2264             return 0;
2265         uint8_t error = response.GetError();
2266         if (error)
2267             return error;
2268     }
2269     return -1;
2270 }
2271 
2272 int
2273 GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2274 {
2275     char packet[32];
2276     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2277     assert (packet_len < (int)sizeof(packet));
2278     StringExtractorGDBRemote response;
2279     if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2280     {
2281         if (response.IsOKResponse())
2282             return 0;
2283         uint8_t error = response.GetError();
2284         if (error)
2285             return error;
2286     }
2287     return -1;
2288 }
2289 
2290 
2291 bool
2292 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2293 {
2294     if (response.IsNormalResponse())
2295     {
2296         std::string name;
2297         std::string value;
2298         StringExtractor extractor;
2299 
2300         uint32_t cpu = LLDB_INVALID_CPUTYPE;
2301         uint32_t sub = 0;
2302         std::string vendor;
2303         std::string os_type;
2304 
2305         while (response.GetNameColonValue(name, value))
2306         {
2307             if (name.compare("pid") == 0)
2308             {
2309                 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2310             }
2311             else if (name.compare("ppid") == 0)
2312             {
2313                 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2314             }
2315             else if (name.compare("uid") == 0)
2316             {
2317                 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2318             }
2319             else if (name.compare("euid") == 0)
2320             {
2321                 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2322             }
2323             else if (name.compare("gid") == 0)
2324             {
2325                 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2326             }
2327             else if (name.compare("egid") == 0)
2328             {
2329                 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2330             }
2331             else if (name.compare("triple") == 0)
2332             {
2333                 process_info.GetArchitecture ().SetTriple (value.c_str());
2334             }
2335             else if (name.compare("name") == 0)
2336             {
2337                 StringExtractor extractor;
2338                 // The process name from ASCII hex bytes since we can't
2339                 // control the characters in a process name
2340                 extractor.GetStringRef().swap(value);
2341                 extractor.SetFilePos(0);
2342                 extractor.GetHexByteString (value);
2343                 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2344             }
2345             else if (name.compare("cputype") == 0)
2346             {
2347                 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2348             }
2349             else if (name.compare("cpusubtype") == 0)
2350             {
2351                 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2352             }
2353             else if (name.compare("vendor") == 0)
2354             {
2355                 vendor = value;
2356             }
2357             else if (name.compare("ostype") == 0)
2358             {
2359                 os_type = value;
2360             }
2361         }
2362 
2363         if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2364         {
2365             if (vendor == "apple")
2366             {
2367                 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2368                 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2369                 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2370             }
2371         }
2372 
2373         if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2374             return true;
2375     }
2376     return false;
2377 }
2378 
2379 bool
2380 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2381 {
2382     process_info.Clear();
2383 
2384     if (m_supports_qProcessInfoPID)
2385     {
2386         char packet[32];
2387         const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2388         assert (packet_len < (int)sizeof(packet));
2389         StringExtractorGDBRemote response;
2390         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2391         {
2392             return DecodeProcessInfoResponse (response, process_info);
2393         }
2394         else
2395         {
2396             m_supports_qProcessInfoPID = false;
2397             return false;
2398         }
2399     }
2400     return false;
2401 }
2402 
2403 bool
2404 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2405 {
2406     if (m_qProcessInfo_is_valid == eLazyBoolYes)
2407         return true;
2408     if (m_qProcessInfo_is_valid == eLazyBoolNo)
2409         return false;
2410 
2411     GetHostInfo ();
2412 
2413     StringExtractorGDBRemote response;
2414     if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2415     {
2416         if (response.IsNormalResponse())
2417         {
2418             std::string name;
2419             std::string value;
2420             uint32_t cpu = LLDB_INVALID_CPUTYPE;
2421             uint32_t sub = 0;
2422             std::string arch_name;
2423             std::string os_name;
2424             std::string vendor_name;
2425             std::string triple;
2426             uint32_t pointer_byte_size = 0;
2427             StringExtractor extractor;
2428             uint32_t num_keys_decoded = 0;
2429             lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2430             while (response.GetNameColonValue(name, value))
2431             {
2432                 if (name.compare("cputype") == 0)
2433                 {
2434                     cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2435                     if (cpu != LLDB_INVALID_CPUTYPE)
2436                         ++num_keys_decoded;
2437                 }
2438                 else if (name.compare("cpusubtype") == 0)
2439                 {
2440                     sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2441                     if (sub != 0)
2442                         ++num_keys_decoded;
2443                 }
2444                 else if (name.compare("ostype") == 0)
2445                 {
2446                     os_name.swap (value);
2447                     ++num_keys_decoded;
2448                 }
2449                 else if (name.compare("vendor") == 0)
2450                 {
2451                     vendor_name.swap(value);
2452                     ++num_keys_decoded;
2453                 }
2454                 else if (name.compare("endian") == 0)
2455                 {
2456                     if (value.compare("little") == 0 ||
2457                         value.compare("big") == 0 ||
2458                         value.compare("pdp") == 0)
2459                         ++num_keys_decoded;
2460                 }
2461                 else if (name.compare("ptrsize") == 0)
2462                 {
2463                     pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2464                     if (pointer_byte_size != 0)
2465                         ++num_keys_decoded;
2466                 }
2467                 else if (name.compare("pid") == 0)
2468                 {
2469                     pid = Args::StringToUInt64(value.c_str(), 0, 16);
2470                     if (pid != LLDB_INVALID_PROCESS_ID)
2471                         ++num_keys_decoded;
2472                 }
2473             }
2474             if (num_keys_decoded > 0)
2475                 m_qProcessInfo_is_valid = eLazyBoolYes;
2476             if (pid != LLDB_INVALID_PROCESS_ID)
2477             {
2478                 m_curr_pid_is_valid = eLazyBoolYes;
2479                 m_curr_pid = pid;
2480             }
2481             if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2482             {
2483                 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2484                 if (pointer_byte_size)
2485                 {
2486                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2487                 }
2488                 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2489                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2490                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2491             }
2492             return true;
2493         }
2494     }
2495     else
2496     {
2497         m_qProcessInfo_is_valid = eLazyBoolNo;
2498     }
2499 
2500     return false;
2501 }
2502 
2503 
2504 uint32_t
2505 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2506                                              ProcessInstanceInfoList &process_infos)
2507 {
2508     process_infos.Clear();
2509 
2510     if (m_supports_qfProcessInfo)
2511     {
2512         StreamString packet;
2513         packet.PutCString ("qfProcessInfo");
2514         if (!match_info.MatchAllProcesses())
2515         {
2516             packet.PutChar (':');
2517             const char *name = match_info.GetProcessInfo().GetName();
2518             bool has_name_match = false;
2519             if (name && name[0])
2520             {
2521                 has_name_match = true;
2522                 NameMatchType name_match_type = match_info.GetNameMatchType();
2523                 switch (name_match_type)
2524                 {
2525                 case eNameMatchIgnore:
2526                     has_name_match = false;
2527                     break;
2528 
2529                 case eNameMatchEquals:
2530                     packet.PutCString ("name_match:equals;");
2531                     break;
2532 
2533                 case eNameMatchContains:
2534                     packet.PutCString ("name_match:contains;");
2535                     break;
2536 
2537                 case eNameMatchStartsWith:
2538                     packet.PutCString ("name_match:starts_with;");
2539                     break;
2540 
2541                 case eNameMatchEndsWith:
2542                     packet.PutCString ("name_match:ends_with;");
2543                     break;
2544 
2545                 case eNameMatchRegularExpression:
2546                     packet.PutCString ("name_match:regex;");
2547                     break;
2548                 }
2549                 if (has_name_match)
2550                 {
2551                     packet.PutCString ("name:");
2552                     packet.PutBytesAsRawHex8(name, ::strlen(name));
2553                     packet.PutChar (';');
2554                 }
2555             }
2556 
2557             if (match_info.GetProcessInfo().ProcessIDIsValid())
2558                 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2559             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2560                 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2561             if (match_info.GetProcessInfo().UserIDIsValid())
2562                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2563             if (match_info.GetProcessInfo().GroupIDIsValid())
2564                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2565             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2566                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2567             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2568                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2569             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2570                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2571             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2572             {
2573                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2574                 const llvm::Triple &triple = match_arch.GetTriple();
2575                 packet.PutCString("triple:");
2576                 packet.PutCString(triple.getTriple().c_str());
2577                 packet.PutChar (';');
2578             }
2579         }
2580         StringExtractorGDBRemote response;
2581         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2582         {
2583             do
2584             {
2585                 ProcessInstanceInfo process_info;
2586                 if (!DecodeProcessInfoResponse (response, process_info))
2587                     break;
2588                 process_infos.Append(process_info);
2589                 response.GetStringRef().clear();
2590                 response.SetFilePos(0);
2591             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2592         }
2593         else
2594         {
2595             m_supports_qfProcessInfo = false;
2596             return 0;
2597         }
2598     }
2599     return process_infos.GetSize();
2600 
2601 }
2602 
2603 bool
2604 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2605 {
2606     if (m_supports_qUserName)
2607     {
2608         char packet[32];
2609         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2610         assert (packet_len < (int)sizeof(packet));
2611         StringExtractorGDBRemote response;
2612         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2613         {
2614             if (response.IsNormalResponse())
2615             {
2616                 // Make sure we parsed the right number of characters. The response is
2617                 // the hex encoded user name and should make up the entire packet.
2618                 // If there are any non-hex ASCII bytes, the length won't match below..
2619                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2620                     return true;
2621             }
2622         }
2623         else
2624         {
2625             m_supports_qUserName = false;
2626             return false;
2627         }
2628     }
2629     return false;
2630 
2631 }
2632 
2633 bool
2634 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2635 {
2636     if (m_supports_qGroupName)
2637     {
2638         char packet[32];
2639         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2640         assert (packet_len < (int)sizeof(packet));
2641         StringExtractorGDBRemote response;
2642         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2643         {
2644             if (response.IsNormalResponse())
2645             {
2646                 // Make sure we parsed the right number of characters. The response is
2647                 // the hex encoded group name and should make up the entire packet.
2648                 // If there are any non-hex ASCII bytes, the length won't match below..
2649                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2650                     return true;
2651             }
2652         }
2653         else
2654         {
2655             m_supports_qGroupName = false;
2656             return false;
2657         }
2658     }
2659     return false;
2660 }
2661 
2662 void
2663 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2664 {
2665     uint32_t i;
2666     TimeValue start_time, end_time;
2667     uint64_t total_time_nsec;
2668     if (SendSpeedTestPacket (0, 0))
2669     {
2670         static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2671         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 };
2672         const size_t k_num_send_sizes = llvm::array_lengthof(g_send_sizes);
2673         const size_t k_num_recv_sizes = llvm::array_lengthof(g_recv_sizes);
2674         const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2675         for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
2676         {
2677             const uint32_t send_size = g_send_sizes[send_idx];
2678             for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
2679             {
2680                 const uint32_t recv_size = g_recv_sizes[recv_idx];
2681                 StreamString packet;
2682                 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2683                 uint32_t bytes_left = send_size;
2684                 while (bytes_left > 0)
2685                 {
2686                     if (bytes_left >= 26)
2687                     {
2688                         packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2689                         bytes_left -= 26;
2690                     }
2691                     else
2692                     {
2693                         packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2694                         bytes_left = 0;
2695                     }
2696                 }
2697 
2698                 start_time = TimeValue::Now();
2699                 if (recv_size == 0)
2700                 {
2701                     for (i=0; i<num_packets; ++i)
2702                     {
2703                         StringExtractorGDBRemote response;
2704                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2705                     }
2706                 }
2707                 else
2708                 {
2709                     uint32_t bytes_read = 0;
2710                     while (bytes_read < k_recv_amount)
2711                     {
2712                         StringExtractorGDBRemote response;
2713                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2714                         bytes_read += recv_size;
2715                     }
2716                 }
2717                 end_time = TimeValue::Now();
2718                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2719                 if (recv_size == 0)
2720                 {
2721                     float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2722                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2723                             num_packets,
2724                             send_size,
2725                             recv_size,
2726                             total_time_nsec / TimeValue::NanoSecPerSec,
2727                             total_time_nsec % TimeValue::NanoSecPerSec,
2728                             packets_per_second);
2729                 }
2730                 else
2731                 {
2732                     float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2733                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2734                             num_packets,
2735                             send_size,
2736                             recv_size,
2737                             total_time_nsec / TimeValue::NanoSecPerSec,
2738                             total_time_nsec % TimeValue::NanoSecPerSec,
2739                             mb_second);
2740                 }
2741             }
2742         }
2743     }
2744 }
2745 
2746 bool
2747 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2748 {
2749     StreamString packet;
2750     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2751     uint32_t bytes_left = send_size;
2752     while (bytes_left > 0)
2753     {
2754         if (bytes_left >= 26)
2755         {
2756             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2757             bytes_left -= 26;
2758         }
2759         else
2760         {
2761             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2762             bytes_left = 0;
2763         }
2764     }
2765 
2766     StringExtractorGDBRemote response;
2767     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)  == PacketResult::Success;
2768 }
2769 
2770 uint16_t
2771 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
2772 {
2773     pid = LLDB_INVALID_PROCESS_ID;
2774     StringExtractorGDBRemote response;
2775     StreamString stream;
2776     stream.PutCString("qLaunchGDBServer;");
2777     std::string hostname;
2778     if (remote_accept_hostname  && remote_accept_hostname[0])
2779         hostname = remote_accept_hostname;
2780     else
2781     {
2782         if (Host::GetHostname (hostname))
2783         {
2784             // Make the GDB server we launch only accept connections from this host
2785             stream.Printf("host:%s;", hostname.c_str());
2786         }
2787         else
2788         {
2789             // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2790             stream.Printf("host:*;");
2791         }
2792     }
2793     const char *packet = stream.GetData();
2794     int packet_len = stream.GetSize();
2795 
2796     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2797     {
2798         std::string name;
2799         std::string value;
2800         uint16_t port = 0;
2801         while (response.GetNameColonValue(name, value))
2802         {
2803             if (name.compare("port") == 0)
2804                 port = Args::StringToUInt32(value.c_str(), 0, 0);
2805             else if (name.compare("pid") == 0)
2806                 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2807         }
2808         return port;
2809     }
2810     return 0;
2811 }
2812 
2813 bool
2814 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2815 {
2816     StreamString stream;
2817     stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2818     const char *packet = stream.GetData();
2819     int packet_len = stream.GetSize();
2820 
2821     StringExtractorGDBRemote response;
2822     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2823     {
2824         if (response.IsOKResponse())
2825             return true;
2826     }
2827     return false;
2828 }
2829 
2830 bool
2831 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2832 {
2833     if (m_curr_tid == tid)
2834         return true;
2835 
2836     char packet[32];
2837     int packet_len;
2838     if (tid == UINT64_MAX)
2839         packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2840     else
2841         packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2842     assert (packet_len + 1 < (int)sizeof(packet));
2843     StringExtractorGDBRemote response;
2844     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2845     {
2846         if (response.IsOKResponse())
2847         {
2848             m_curr_tid = tid;
2849             return true;
2850         }
2851     }
2852     return false;
2853 }
2854 
2855 bool
2856 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2857 {
2858     if (m_curr_tid_run == tid)
2859         return true;
2860 
2861     char packet[32];
2862     int packet_len;
2863     if (tid == UINT64_MAX)
2864         packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2865     else
2866         packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2867 
2868     assert (packet_len + 1 < (int)sizeof(packet));
2869     StringExtractorGDBRemote response;
2870     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2871     {
2872         if (response.IsOKResponse())
2873         {
2874             m_curr_tid_run = tid;
2875             return true;
2876         }
2877     }
2878     return false;
2879 }
2880 
2881 bool
2882 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2883 {
2884     if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
2885         return response.IsNormalResponse();
2886     return false;
2887 }
2888 
2889 bool
2890 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2891 {
2892     if (m_supports_qThreadStopInfo)
2893     {
2894         char packet[256];
2895         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2896         assert (packet_len < (int)sizeof(packet));
2897         if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2898         {
2899             if (response.IsUnsupportedResponse())
2900                 m_supports_qThreadStopInfo = false;
2901             else if (response.IsNormalResponse())
2902                 return true;
2903             else
2904                 return false;
2905         }
2906         else
2907         {
2908             m_supports_qThreadStopInfo = false;
2909         }
2910     }
2911     return false;
2912 }
2913 
2914 
2915 uint8_t
2916 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
2917 {
2918     // Check if the stub is known not to support this breakpoint type
2919     if (!SupportsGDBStoppointPacket(type))
2920         return UINT8_MAX;
2921     // Construct the breakpoint packet
2922     char packet[64];
2923     const int packet_len = ::snprintf (packet,
2924                                        sizeof(packet),
2925                                        "%c%i,%" PRIx64 ",%x",
2926                                        insert ? 'Z' : 'z',
2927                                        type,
2928                                        addr,
2929                                        length);
2930     // Check we haven't overwritten the end of the packet buffer
2931     assert (packet_len + 1 < (int)sizeof(packet));
2932     StringExtractorGDBRemote response;
2933     // Try to send the breakpoint packet, and check that it was correctly sent
2934     if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
2935     {
2936         // Receive and OK packet when the breakpoint successfully placed
2937         if (response.IsOKResponse())
2938             return 0;
2939 
2940         // Error while setting breakpoint, send back specific error
2941         if (response.IsErrorResponse())
2942             return response.GetError();
2943 
2944         // Empty packet informs us that breakpoint is not supported
2945         if (response.IsUnsupportedResponse())
2946         {
2947             // Disable this breakpoint type since it is unsupported
2948             switch (type)
2949             {
2950             case eBreakpointSoftware:   m_supports_z0 = false; break;
2951             case eBreakpointHardware:   m_supports_z1 = false; break;
2952             case eWatchpointWrite:      m_supports_z2 = false; break;
2953             case eWatchpointRead:       m_supports_z3 = false; break;
2954             case eWatchpointReadWrite:  m_supports_z4 = false; break;
2955             }
2956         }
2957     }
2958     // Signal generic failure
2959     return UINT8_MAX;
2960 }
2961 
2962 size_t
2963 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2964                                                    bool &sequence_mutex_unavailable)
2965 {
2966     Mutex::Locker locker;
2967     thread_ids.clear();
2968 
2969     if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2970     {
2971         sequence_mutex_unavailable = false;
2972         StringExtractorGDBRemote response;
2973 
2974         PacketResult packet_result;
2975         for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2976              packet_result == PacketResult::Success && response.IsNormalResponse();
2977              packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
2978         {
2979             char ch = response.GetChar();
2980             if (ch == 'l')
2981                 break;
2982             if (ch == 'm')
2983             {
2984                 do
2985                 {
2986                     tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2987 
2988                     if (tid != LLDB_INVALID_THREAD_ID)
2989                     {
2990                         thread_ids.push_back (tid);
2991                     }
2992                     ch = response.GetChar();    // Skip the command separator
2993                 } while (ch == ',');            // Make sure we got a comma separator
2994             }
2995         }
2996     }
2997     else
2998     {
2999 #if defined (LLDB_CONFIGURATION_DEBUG)
3000         // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3001 #else
3002         Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3003         if (log)
3004             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3005 #endif
3006         sequence_mutex_unavailable = true;
3007     }
3008     return thread_ids.size();
3009 }
3010 
3011 lldb::addr_t
3012 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3013 {
3014     if (!IsRunning())
3015     {
3016         StringExtractorGDBRemote response;
3017         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3018         {
3019             if (response.IsNormalResponse())
3020                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3021         }
3022     }
3023     return LLDB_INVALID_ADDRESS;
3024 }
3025 
3026 lldb_private::Error
3027 GDBRemoteCommunicationClient::RunShellCommand (const char *command,           // Shouldn't be NULL
3028                                                const char *working_dir,       // Pass NULL to use the current working directory
3029                                                int *status_ptr,               // Pass NULL if you don't want the process exit status
3030                                                int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
3031                                                std::string *command_output,   // Pass NULL if you don't want the command output
3032                                                uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
3033 {
3034     lldb_private::StreamString stream;
3035     stream.PutCString("qPlatform_shell:");
3036     stream.PutBytesAsRawHex8(command, strlen(command));
3037     stream.PutChar(',');
3038     stream.PutHex32(timeout_sec);
3039     if (working_dir && *working_dir)
3040     {
3041         stream.PutChar(',');
3042         stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
3043     }
3044     const char *packet = stream.GetData();
3045     int packet_len = stream.GetSize();
3046     StringExtractorGDBRemote response;
3047     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3048     {
3049         if (response.GetChar() != 'F')
3050             return Error("malformed reply");
3051         if (response.GetChar() != ',')
3052             return Error("malformed reply");
3053         uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3054         if (exitcode == UINT32_MAX)
3055             return Error("unable to run remote process");
3056         else if (status_ptr)
3057             *status_ptr = exitcode;
3058         if (response.GetChar() != ',')
3059             return Error("malformed reply");
3060         uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3061         if (signo_ptr)
3062             *signo_ptr = signo;
3063         if (response.GetChar() != ',')
3064             return Error("malformed reply");
3065         std::string output;
3066         response.GetEscapedBinaryData(output);
3067         if (command_output)
3068             command_output->assign(output);
3069         return Error();
3070     }
3071     return Error("unable to send packet");
3072 }
3073 
3074 Error
3075 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
3076                                              uint32_t file_permissions)
3077 {
3078     lldb_private::StreamString stream;
3079     stream.PutCString("qPlatform_mkdir:");
3080     stream.PutHex32(file_permissions);
3081     stream.PutChar(',');
3082     stream.PutBytesAsRawHex8(path, strlen(path));
3083     const char *packet = stream.GetData();
3084     int packet_len = stream.GetSize();
3085     StringExtractorGDBRemote response;
3086     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3087     {
3088         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3089     }
3090     return Error();
3091 
3092 }
3093 
3094 Error
3095 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
3096                                                   uint32_t file_permissions)
3097 {
3098     lldb_private::StreamString stream;
3099     stream.PutCString("qPlatform_chmod:");
3100     stream.PutHex32(file_permissions);
3101     stream.PutChar(',');
3102     stream.PutBytesAsRawHex8(path, strlen(path));
3103     const char *packet = stream.GetData();
3104     int packet_len = stream.GetSize();
3105     StringExtractorGDBRemote response;
3106     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3107     {
3108         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3109     }
3110     return Error();
3111 
3112 }
3113 
3114 static uint64_t
3115 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3116                            uint64_t fail_result,
3117                            Error &error)
3118 {
3119     response.SetFilePos(0);
3120     if (response.GetChar() != 'F')
3121         return fail_result;
3122     int32_t result = response.GetS32 (-2);
3123     if (result == -2)
3124         return fail_result;
3125     if (response.GetChar() == ',')
3126     {
3127         int result_errno = response.GetS32 (-2);
3128         if (result_errno != -2)
3129             error.SetError(result_errno, eErrorTypePOSIX);
3130         else
3131             error.SetError(-1, eErrorTypeGeneric);
3132     }
3133     else
3134         error.Clear();
3135     return  result;
3136 }
3137 lldb::user_id_t
3138 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3139                                         uint32_t flags,
3140                                         mode_t mode,
3141                                         Error &error)
3142 {
3143     lldb_private::StreamString stream;
3144     stream.PutCString("vFile:open:");
3145     std::string path (file_spec.GetPath());
3146     if (path.empty())
3147         return UINT64_MAX;
3148     stream.PutCStringAsRawHex8(path.c_str());
3149     stream.PutChar(',');
3150     const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
3151     stream.PutHex32(posix_open_flags);
3152     stream.PutChar(',');
3153     stream.PutHex32(mode);
3154     const char* packet = stream.GetData();
3155     int packet_len = stream.GetSize();
3156     StringExtractorGDBRemote response;
3157     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3158     {
3159         return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3160     }
3161     return UINT64_MAX;
3162 }
3163 
3164 bool
3165 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3166                                          Error &error)
3167 {
3168     lldb_private::StreamString stream;
3169     stream.Printf("vFile:close:%i", (int)fd);
3170     const char* packet = stream.GetData();
3171     int packet_len = stream.GetSize();
3172     StringExtractorGDBRemote response;
3173     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3174     {
3175         return ParseHostIOPacketResponse (response, -1, error) == 0;
3176     }
3177     return false;
3178 }
3179 
3180 // Extension of host I/O packets to get the file size.
3181 lldb::user_id_t
3182 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3183 {
3184     lldb_private::StreamString stream;
3185     stream.PutCString("vFile:size:");
3186     std::string path (file_spec.GetPath());
3187     stream.PutCStringAsRawHex8(path.c_str());
3188     const char* packet = stream.GetData();
3189     int packet_len = stream.GetSize();
3190     StringExtractorGDBRemote response;
3191     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3192     {
3193         if (response.GetChar() != 'F')
3194             return UINT64_MAX;
3195         uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3196         return retcode;
3197     }
3198     return UINT64_MAX;
3199 }
3200 
3201 Error
3202 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
3203 {
3204     Error error;
3205     lldb_private::StreamString stream;
3206     stream.PutCString("vFile:mode:");
3207     stream.PutCStringAsRawHex8(path);
3208     const char* packet = stream.GetData();
3209     int packet_len = stream.GetSize();
3210     StringExtractorGDBRemote response;
3211     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3212     {
3213         if (response.GetChar() != 'F')
3214         {
3215             error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3216         }
3217         else
3218         {
3219             const uint32_t mode = response.GetS32(-1);
3220             if (static_cast<int32_t>(mode) == -1)
3221             {
3222                 if (response.GetChar() == ',')
3223                 {
3224                     int response_errno = response.GetS32(-1);
3225                     if (response_errno > 0)
3226                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3227                     else
3228                         error.SetErrorToGenericError();
3229                 }
3230                 else
3231                     error.SetErrorToGenericError();
3232             }
3233             else
3234             {
3235                 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3236             }
3237         }
3238     }
3239     else
3240     {
3241         error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3242     }
3243     return error;
3244 }
3245 
3246 uint64_t
3247 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3248                                         uint64_t offset,
3249                                         void *dst,
3250                                         uint64_t dst_len,
3251                                         Error &error)
3252 {
3253     lldb_private::StreamString stream;
3254     stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3255     const char* packet = stream.GetData();
3256     int packet_len = stream.GetSize();
3257     StringExtractorGDBRemote response;
3258     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3259     {
3260         if (response.GetChar() != 'F')
3261             return 0;
3262         uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3263         if (retcode == UINT32_MAX)
3264             return retcode;
3265         const char next = (response.Peek() ? *response.Peek() : 0);
3266         if (next == ',')
3267             return 0;
3268         if (next == ';')
3269         {
3270             response.GetChar(); // skip the semicolon
3271             std::string buffer;
3272             if (response.GetEscapedBinaryData(buffer))
3273             {
3274                 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3275                 if (data_to_write > 0)
3276                     memcpy(dst, &buffer[0], data_to_write);
3277                 return data_to_write;
3278             }
3279         }
3280     }
3281     return 0;
3282 }
3283 
3284 uint64_t
3285 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3286                                          uint64_t offset,
3287                                          const void* src,
3288                                          uint64_t src_len,
3289                                          Error &error)
3290 {
3291     lldb_private::StreamGDBRemote stream;
3292     stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3293     stream.PutEscapedBytes(src, src_len);
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("write file failed");
3302             return 0;
3303         }
3304         uint64_t bytes_written = response.GetU64(UINT64_MAX);
3305         if (bytes_written == UINT64_MAX)
3306         {
3307             error.SetErrorToGenericError();
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             }
3314             return 0;
3315         }
3316         return bytes_written;
3317     }
3318     else
3319     {
3320         error.SetErrorString ("failed to send vFile:pwrite packet");
3321     }
3322     return 0;
3323 }
3324 
3325 Error
3326 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3327 {
3328     Error error;
3329     lldb_private::StreamGDBRemote stream;
3330     stream.PutCString("vFile:symlink:");
3331     // the unix symlink() command reverses its parameters where the dst if first,
3332     // so we follow suit here
3333     stream.PutCStringAsRawHex8(dst);
3334     stream.PutChar(',');
3335     stream.PutCStringAsRawHex8(src);
3336     const char* packet = stream.GetData();
3337     int packet_len = stream.GetSize();
3338     StringExtractorGDBRemote response;
3339     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3340     {
3341         if (response.GetChar() == 'F')
3342         {
3343             uint32_t result = response.GetU32(UINT32_MAX);
3344             if (result != 0)
3345             {
3346                 error.SetErrorToGenericError();
3347                 if (response.GetChar() == ',')
3348                 {
3349                     int response_errno = response.GetS32(-1);
3350                     if (response_errno > 0)
3351                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3352                 }
3353             }
3354         }
3355         else
3356         {
3357             // Should have returned with 'F<result>[,<errno>]'
3358             error.SetErrorStringWithFormat("symlink failed");
3359         }
3360     }
3361     else
3362     {
3363         error.SetErrorString ("failed to send vFile:symlink packet");
3364     }
3365     return error;
3366 }
3367 
3368 Error
3369 GDBRemoteCommunicationClient::Unlink (const char *path)
3370 {
3371     Error error;
3372     lldb_private::StreamGDBRemote stream;
3373     stream.PutCString("vFile:unlink:");
3374     // the unix symlink() command reverses its parameters where the dst if first,
3375     // so we follow suit here
3376     stream.PutCStringAsRawHex8(path);
3377     const char* packet = stream.GetData();
3378     int packet_len = stream.GetSize();
3379     StringExtractorGDBRemote response;
3380     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3381     {
3382         if (response.GetChar() == 'F')
3383         {
3384             uint32_t result = response.GetU32(UINT32_MAX);
3385             if (result != 0)
3386             {
3387                 error.SetErrorToGenericError();
3388                 if (response.GetChar() == ',')
3389                 {
3390                     int response_errno = response.GetS32(-1);
3391                     if (response_errno > 0)
3392                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3393                 }
3394             }
3395         }
3396         else
3397         {
3398             // Should have returned with 'F<result>[,<errno>]'
3399             error.SetErrorStringWithFormat("unlink failed");
3400         }
3401     }
3402     else
3403     {
3404         error.SetErrorString ("failed to send vFile:unlink packet");
3405     }
3406     return error;
3407 }
3408 
3409 // Extension of host I/O packets to get whether a file exists.
3410 bool
3411 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3412 {
3413     lldb_private::StreamString stream;
3414     stream.PutCString("vFile:exists:");
3415     std::string path (file_spec.GetPath());
3416     stream.PutCStringAsRawHex8(path.c_str());
3417     const char* packet = stream.GetData();
3418     int packet_len = stream.GetSize();
3419     StringExtractorGDBRemote response;
3420     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3421     {
3422         if (response.GetChar() != 'F')
3423             return false;
3424         if (response.GetChar() != ',')
3425             return false;
3426         bool retcode = (response.GetChar() != '0');
3427         return retcode;
3428     }
3429     return false;
3430 }
3431 
3432 bool
3433 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3434                                             uint64_t &high,
3435                                             uint64_t &low)
3436 {
3437     lldb_private::StreamString stream;
3438     stream.PutCString("vFile:MD5:");
3439     std::string path (file_spec.GetPath());
3440     stream.PutCStringAsRawHex8(path.c_str());
3441     const char* packet = stream.GetData();
3442     int packet_len = stream.GetSize();
3443     StringExtractorGDBRemote response;
3444     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3445     {
3446         if (response.GetChar() != 'F')
3447             return false;
3448         if (response.GetChar() != ',')
3449             return false;
3450         if (response.Peek() && *response.Peek() == 'x')
3451             return false;
3452         low = response.GetHexMaxU64(false, UINT64_MAX);
3453         high = response.GetHexMaxU64(false, UINT64_MAX);
3454         return true;
3455     }
3456     return false;
3457 }
3458 
3459 bool
3460 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3461 {
3462     // Some targets have issues with g/G packets and we need to avoid using them
3463     if (m_avoid_g_packets == eLazyBoolCalculate)
3464     {
3465         if (process)
3466         {
3467             m_avoid_g_packets = eLazyBoolNo;
3468             const ArchSpec &arch = process->GetTarget().GetArchitecture();
3469             if (arch.IsValid()
3470                 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3471                 && arch.GetTriple().getOS() == llvm::Triple::IOS
3472                 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
3473             {
3474                 m_avoid_g_packets = eLazyBoolYes;
3475                 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3476                 if (gdb_server_version != 0)
3477                 {
3478                     const char *gdb_server_name = GetGDBServerProgramName();
3479                     if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3480                     {
3481                         if (gdb_server_version >= 310)
3482                             m_avoid_g_packets = eLazyBoolNo;
3483                     }
3484                 }
3485             }
3486         }
3487     }
3488     return m_avoid_g_packets == eLazyBoolYes;
3489 }
3490 
3491 bool
3492 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3493 {
3494     Mutex::Locker locker;
3495     if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3496     {
3497         const bool thread_suffix_supported = GetThreadSuffixSupported();
3498 
3499         if (thread_suffix_supported || SetCurrentThread(tid))
3500         {
3501             char packet[64];
3502             int packet_len = 0;
3503             if (thread_suffix_supported)
3504                 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3505             else
3506                 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3507             assert (packet_len < ((int)sizeof(packet) - 1));
3508             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3509         }
3510     }
3511     return false;
3512 
3513 }
3514 
3515 
3516 bool
3517 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3518 {
3519     Mutex::Locker locker;
3520     if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3521     {
3522         const bool thread_suffix_supported = GetThreadSuffixSupported();
3523 
3524         if (thread_suffix_supported || SetCurrentThread(tid))
3525         {
3526             char packet[64];
3527             int packet_len = 0;
3528             // Get all registers in one packet
3529             if (thread_suffix_supported)
3530                 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3531             else
3532                 packet_len = ::snprintf (packet, sizeof(packet), "g");
3533             assert (packet_len < ((int)sizeof(packet) - 1));
3534             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3535         }
3536     }
3537     return false;
3538 }
3539 bool
3540 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3541 {
3542     save_id = 0; // Set to invalid save ID
3543     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3544         return false;
3545 
3546     m_supports_QSaveRegisterState = eLazyBoolYes;
3547     Mutex::Locker locker;
3548     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3549     {
3550         const bool thread_suffix_supported = GetThreadSuffixSupported();
3551         if (thread_suffix_supported || SetCurrentThread(tid))
3552         {
3553             char packet[256];
3554             if (thread_suffix_supported)
3555                 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3556             else
3557                 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3558 
3559             StringExtractorGDBRemote response;
3560 
3561             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3562             {
3563                 if (response.IsUnsupportedResponse())
3564                 {
3565                     // This packet isn't supported, don't try calling it again
3566                     m_supports_QSaveRegisterState = eLazyBoolNo;
3567                 }
3568 
3569                 const uint32_t response_save_id = response.GetU32(0);
3570                 if (response_save_id != 0)
3571                 {
3572                     save_id = response_save_id;
3573                     return true;
3574                 }
3575             }
3576         }
3577     }
3578     return false;
3579 }
3580 
3581 bool
3582 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3583 {
3584     // We use the "m_supports_QSaveRegisterState" variable here because the
3585     // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3586     // order to be useful
3587     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3588         return false;
3589 
3590     Mutex::Locker locker;
3591     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3592     {
3593         const bool thread_suffix_supported = GetThreadSuffixSupported();
3594         if (thread_suffix_supported || SetCurrentThread(tid))
3595         {
3596             char packet[256];
3597             if (thread_suffix_supported)
3598                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3599             else
3600                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3601 
3602             StringExtractorGDBRemote response;
3603 
3604             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3605             {
3606                 if (response.IsOKResponse())
3607                 {
3608                     return true;
3609                 }
3610                 else if (response.IsUnsupportedResponse())
3611                 {
3612                     // This packet isn't supported, don't try calling this packet or
3613                     // QSaveRegisterState again...
3614                     m_supports_QSaveRegisterState = eLazyBoolNo;
3615                 }
3616             }
3617         }
3618     }
3619     return false;
3620 }
3621