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