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             StringExtractorGDBRemote response;
1760             PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
1761             if (packet_result != PacketResult::Success)
1762                 error.SetErrorString ("Sending extended disconnect packet failed.");
1763         }
1764     }
1765     else
1766     {
1767         StringExtractorGDBRemote response;
1768         PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
1769         if (packet_result != PacketResult::Success)
1770             error.SetErrorString ("Sending disconnect packet failed.");
1771     }
1772     return error;
1773 }
1774 
1775 Error
1776 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1777                                                   lldb_private::MemoryRegionInfo &region_info)
1778 {
1779     Error error;
1780     region_info.Clear();
1781 
1782     if (m_supports_memory_region_info != eLazyBoolNo)
1783     {
1784         m_supports_memory_region_info = eLazyBoolYes;
1785         char packet[64];
1786         const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1787         assert (packet_len < (int)sizeof(packet));
1788         StringExtractorGDBRemote response;
1789         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1790         {
1791             std::string name;
1792             std::string value;
1793             addr_t addr_value;
1794             bool success = true;
1795             bool saw_permissions = false;
1796             while (success && response.GetNameColonValue(name, value))
1797             {
1798                 if (name.compare ("start") == 0)
1799                 {
1800                     addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1801                     if (success)
1802                         region_info.GetRange().SetRangeBase(addr_value);
1803                 }
1804                 else if (name.compare ("size") == 0)
1805                 {
1806                     addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1807                     if (success)
1808                         region_info.GetRange().SetByteSize (addr_value);
1809                 }
1810                 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1811                 {
1812                     saw_permissions = true;
1813                     if (region_info.GetRange().Contains (addr))
1814                     {
1815                         if (value.find('r') != std::string::npos)
1816                             region_info.SetReadable (MemoryRegionInfo::eYes);
1817                         else
1818                             region_info.SetReadable (MemoryRegionInfo::eNo);
1819 
1820                         if (value.find('w') != std::string::npos)
1821                             region_info.SetWritable (MemoryRegionInfo::eYes);
1822                         else
1823                             region_info.SetWritable (MemoryRegionInfo::eNo);
1824 
1825                         if (value.find('x') != std::string::npos)
1826                             region_info.SetExecutable (MemoryRegionInfo::eYes);
1827                         else
1828                             region_info.SetExecutable (MemoryRegionInfo::eNo);
1829                     }
1830                     else
1831                     {
1832                         // The reported region does not contain this address -- we're looking at an unmapped page
1833                         region_info.SetReadable (MemoryRegionInfo::eNo);
1834                         region_info.SetWritable (MemoryRegionInfo::eNo);
1835                         region_info.SetExecutable (MemoryRegionInfo::eNo);
1836                     }
1837                 }
1838                 else if (name.compare ("error") == 0)
1839                 {
1840                     StringExtractorGDBRemote name_extractor;
1841                     // Swap "value" over into "name_extractor"
1842                     name_extractor.GetStringRef().swap(value);
1843                     // Now convert the HEX bytes into a string value
1844                     name_extractor.GetHexByteString (value);
1845                     error.SetErrorString(value.c_str());
1846                 }
1847             }
1848 
1849             // We got a valid address range back but no permissions -- which means this is an unmapped page
1850             if (region_info.GetRange().IsValid() && saw_permissions == false)
1851             {
1852                 region_info.SetReadable (MemoryRegionInfo::eNo);
1853                 region_info.SetWritable (MemoryRegionInfo::eNo);
1854                 region_info.SetExecutable (MemoryRegionInfo::eNo);
1855             }
1856         }
1857         else
1858         {
1859             m_supports_memory_region_info = eLazyBoolNo;
1860         }
1861     }
1862 
1863     if (m_supports_memory_region_info == eLazyBoolNo)
1864     {
1865         error.SetErrorString("qMemoryRegionInfo is not supported");
1866     }
1867     if (error.Fail())
1868         region_info.Clear();
1869     return error;
1870 
1871 }
1872 
1873 Error
1874 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1875 {
1876     Error error;
1877 
1878     if (m_supports_watchpoint_support_info == eLazyBoolYes)
1879     {
1880         num = m_num_supported_hardware_watchpoints;
1881         return error;
1882     }
1883 
1884     // Set num to 0 first.
1885     num = 0;
1886     if (m_supports_watchpoint_support_info != eLazyBoolNo)
1887     {
1888         char packet[64];
1889         const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1890         assert (packet_len < (int)sizeof(packet));
1891         StringExtractorGDBRemote response;
1892         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1893         {
1894             m_supports_watchpoint_support_info = eLazyBoolYes;
1895             std::string name;
1896             std::string value;
1897             while (response.GetNameColonValue(name, value))
1898             {
1899                 if (name.compare ("num") == 0)
1900                 {
1901                     num = Args::StringToUInt32(value.c_str(), 0, 0);
1902                     m_num_supported_hardware_watchpoints = num;
1903                 }
1904             }
1905         }
1906         else
1907         {
1908             m_supports_watchpoint_support_info = eLazyBoolNo;
1909         }
1910     }
1911 
1912     if (m_supports_watchpoint_support_info == eLazyBoolNo)
1913     {
1914         error.SetErrorString("qWatchpointSupportInfo is not supported");
1915     }
1916     return error;
1917 
1918 }
1919 
1920 lldb_private::Error
1921 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1922 {
1923     Error error(GetWatchpointSupportInfo(num));
1924     if (error.Success())
1925         error = GetWatchpointsTriggerAfterInstruction(after);
1926     return error;
1927 }
1928 
1929 lldb_private::Error
1930 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1931 {
1932     Error error;
1933 
1934     // we assume watchpoints will happen after running the relevant opcode
1935     // and we only want to override this behavior if we have explicitly
1936     // received a qHostInfo telling us otherwise
1937     if (m_qHostInfo_is_valid != eLazyBoolYes)
1938         after = true;
1939     else
1940         after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1941     return error;
1942 }
1943 
1944 int
1945 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1946 {
1947     if (path && path[0])
1948     {
1949         StreamString packet;
1950         packet.PutCString("QSetSTDIN:");
1951         packet.PutBytesAsRawHex8(path, strlen(path));
1952 
1953         StringExtractorGDBRemote response;
1954         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1955         {
1956             if (response.IsOKResponse())
1957                 return 0;
1958             uint8_t error = response.GetError();
1959             if (error)
1960                 return error;
1961         }
1962     }
1963     return -1;
1964 }
1965 
1966 int
1967 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1968 {
1969     if (path && path[0])
1970     {
1971         StreamString packet;
1972         packet.PutCString("QSetSTDOUT:");
1973         packet.PutBytesAsRawHex8(path, strlen(path));
1974 
1975         StringExtractorGDBRemote response;
1976         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1977         {
1978             if (response.IsOKResponse())
1979                 return 0;
1980             uint8_t error = response.GetError();
1981             if (error)
1982                 return error;
1983         }
1984     }
1985     return -1;
1986 }
1987 
1988 int
1989 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1990 {
1991     if (path && path[0])
1992     {
1993         StreamString packet;
1994         packet.PutCString("QSetSTDERR:");
1995         packet.PutBytesAsRawHex8(path, strlen(path));
1996 
1997         StringExtractorGDBRemote response;
1998         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1999         {
2000             if (response.IsOKResponse())
2001                 return 0;
2002             uint8_t error = response.GetError();
2003             if (error)
2004                 return error;
2005         }
2006     }
2007     return -1;
2008 }
2009 
2010 bool
2011 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2012 {
2013     StringExtractorGDBRemote response;
2014     if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2015     {
2016         if (response.IsUnsupportedResponse())
2017             return false;
2018         if (response.IsErrorResponse())
2019             return false;
2020         response.GetHexByteString (cwd);
2021         return !cwd.empty();
2022     }
2023     return false;
2024 }
2025 
2026 int
2027 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2028 {
2029     if (path && path[0])
2030     {
2031         StreamString packet;
2032         packet.PutCString("QSetWorkingDir:");
2033         packet.PutBytesAsRawHex8(path, strlen(path));
2034 
2035         StringExtractorGDBRemote response;
2036         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2037         {
2038             if (response.IsOKResponse())
2039                 return 0;
2040             uint8_t error = response.GetError();
2041             if (error)
2042                 return error;
2043         }
2044     }
2045     return -1;
2046 }
2047 
2048 int
2049 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2050 {
2051     char packet[32];
2052     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2053     assert (packet_len < (int)sizeof(packet));
2054     StringExtractorGDBRemote response;
2055     if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2056     {
2057         if (response.IsOKResponse())
2058             return 0;
2059         uint8_t error = response.GetError();
2060         if (error)
2061             return error;
2062     }
2063     return -1;
2064 }
2065 
2066 bool
2067 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2068 {
2069     if (response.IsNormalResponse())
2070     {
2071         std::string name;
2072         std::string value;
2073         StringExtractor extractor;
2074 
2075         uint32_t cpu = LLDB_INVALID_CPUTYPE;
2076         uint32_t sub = 0;
2077         std::string vendor;
2078         std::string os_type;
2079 
2080         while (response.GetNameColonValue(name, value))
2081         {
2082             if (name.compare("pid") == 0)
2083             {
2084                 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2085             }
2086             else if (name.compare("ppid") == 0)
2087             {
2088                 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2089             }
2090             else if (name.compare("uid") == 0)
2091             {
2092                 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2093             }
2094             else if (name.compare("euid") == 0)
2095             {
2096                 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2097             }
2098             else if (name.compare("gid") == 0)
2099             {
2100                 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2101             }
2102             else if (name.compare("egid") == 0)
2103             {
2104                 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2105             }
2106             else if (name.compare("triple") == 0)
2107             {
2108                 // The triple comes as ASCII hex bytes since it contains '-' chars
2109                 extractor.GetStringRef().swap(value);
2110                 extractor.SetFilePos(0);
2111                 extractor.GetHexByteString (value);
2112                 process_info.GetArchitecture ().SetTriple (value.c_str());
2113             }
2114             else if (name.compare("name") == 0)
2115             {
2116                 StringExtractor extractor;
2117                 // The process name from ASCII hex bytes since we can't
2118                 // control the characters in a process name
2119                 extractor.GetStringRef().swap(value);
2120                 extractor.SetFilePos(0);
2121                 extractor.GetHexByteString (value);
2122                 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2123             }
2124             else if (name.compare("cputype") == 0)
2125             {
2126                 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2127             }
2128             else if (name.compare("cpusubtype") == 0)
2129             {
2130                 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2131             }
2132             else if (name.compare("vendor") == 0)
2133             {
2134                 vendor = value;
2135             }
2136             else if (name.compare("ostype") == 0)
2137             {
2138                 os_type = value;
2139             }
2140         }
2141 
2142         if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2143         {
2144             if (vendor == "apple")
2145             {
2146                 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2147                 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2148                 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2149             }
2150         }
2151 
2152         if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2153             return true;
2154     }
2155     return false;
2156 }
2157 
2158 bool
2159 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2160 {
2161     process_info.Clear();
2162 
2163     if (m_supports_qProcessInfoPID)
2164     {
2165         char packet[32];
2166         const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2167         assert (packet_len < (int)sizeof(packet));
2168         StringExtractorGDBRemote response;
2169         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2170         {
2171             return DecodeProcessInfoResponse (response, process_info);
2172         }
2173         else
2174         {
2175             m_supports_qProcessInfoPID = false;
2176             return false;
2177         }
2178     }
2179     return false;
2180 }
2181 
2182 bool
2183 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2184 {
2185     if (m_qProcessInfo_is_valid == eLazyBoolYes)
2186         return true;
2187     if (m_qProcessInfo_is_valid == eLazyBoolNo)
2188         return false;
2189 
2190     GetHostInfo ();
2191 
2192     StringExtractorGDBRemote response;
2193     if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2194     {
2195         if (response.IsNormalResponse())
2196         {
2197             std::string name;
2198             std::string value;
2199             uint32_t cpu = LLDB_INVALID_CPUTYPE;
2200             uint32_t sub = 0;
2201             std::string arch_name;
2202             std::string os_name;
2203             std::string vendor_name;
2204             std::string triple;
2205             uint32_t pointer_byte_size = 0;
2206             StringExtractor extractor;
2207             ByteOrder byte_order = eByteOrderInvalid;
2208             uint32_t num_keys_decoded = 0;
2209             while (response.GetNameColonValue(name, value))
2210             {
2211                 if (name.compare("cputype") == 0)
2212                 {
2213                     cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2214                     if (cpu != LLDB_INVALID_CPUTYPE)
2215                         ++num_keys_decoded;
2216                 }
2217                 else if (name.compare("cpusubtype") == 0)
2218                 {
2219                     sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2220                     if (sub != 0)
2221                         ++num_keys_decoded;
2222                 }
2223                 else if (name.compare("ostype") == 0)
2224                 {
2225                     os_name.swap (value);
2226                     ++num_keys_decoded;
2227                 }
2228                 else if (name.compare("vendor") == 0)
2229                 {
2230                     vendor_name.swap(value);
2231                     ++num_keys_decoded;
2232                 }
2233                 else if (name.compare("endian") == 0)
2234                 {
2235                     ++num_keys_decoded;
2236                     if (value.compare("little") == 0)
2237                         byte_order = eByteOrderLittle;
2238                     else if (value.compare("big") == 0)
2239                         byte_order = eByteOrderBig;
2240                     else if (value.compare("pdp") == 0)
2241                         byte_order = eByteOrderPDP;
2242                     else
2243                         --num_keys_decoded;
2244                 }
2245                 else if (name.compare("ptrsize") == 0)
2246                 {
2247                     pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2248                     if (pointer_byte_size != 0)
2249                         ++num_keys_decoded;
2250                 }
2251             }
2252             if (num_keys_decoded > 0)
2253                 m_qProcessInfo_is_valid = eLazyBoolYes;
2254             if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2255             {
2256                 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2257                 if (pointer_byte_size)
2258                 {
2259                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2260                 }
2261                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2262                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2263                 return true;
2264             }
2265         }
2266     }
2267     else
2268     {
2269         m_qProcessInfo_is_valid = eLazyBoolNo;
2270     }
2271 
2272     return false;
2273 }
2274 
2275 
2276 uint32_t
2277 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2278                                              ProcessInstanceInfoList &process_infos)
2279 {
2280     process_infos.Clear();
2281 
2282     if (m_supports_qfProcessInfo)
2283     {
2284         StreamString packet;
2285         packet.PutCString ("qfProcessInfo");
2286         if (!match_info.MatchAllProcesses())
2287         {
2288             packet.PutChar (':');
2289             const char *name = match_info.GetProcessInfo().GetName();
2290             bool has_name_match = false;
2291             if (name && name[0])
2292             {
2293                 has_name_match = true;
2294                 NameMatchType name_match_type = match_info.GetNameMatchType();
2295                 switch (name_match_type)
2296                 {
2297                 case eNameMatchIgnore:
2298                     has_name_match = false;
2299                     break;
2300 
2301                 case eNameMatchEquals:
2302                     packet.PutCString ("name_match:equals;");
2303                     break;
2304 
2305                 case eNameMatchContains:
2306                     packet.PutCString ("name_match:contains;");
2307                     break;
2308 
2309                 case eNameMatchStartsWith:
2310                     packet.PutCString ("name_match:starts_with;");
2311                     break;
2312 
2313                 case eNameMatchEndsWith:
2314                     packet.PutCString ("name_match:ends_with;");
2315                     break;
2316 
2317                 case eNameMatchRegularExpression:
2318                     packet.PutCString ("name_match:regex;");
2319                     break;
2320                 }
2321                 if (has_name_match)
2322                 {
2323                     packet.PutCString ("name:");
2324                     packet.PutBytesAsRawHex8(name, ::strlen(name));
2325                     packet.PutChar (';');
2326                 }
2327             }
2328 
2329             if (match_info.GetProcessInfo().ProcessIDIsValid())
2330                 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2331             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2332                 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2333             if (match_info.GetProcessInfo().UserIDIsValid())
2334                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2335             if (match_info.GetProcessInfo().GroupIDIsValid())
2336                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2337             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2338                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2339             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2340                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2341             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2342                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2343             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2344             {
2345                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2346                 const llvm::Triple &triple = match_arch.GetTriple();
2347                 packet.PutCString("triple:");
2348                 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2349                 packet.PutChar (';');
2350             }
2351         }
2352         StringExtractorGDBRemote response;
2353         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2354         {
2355             do
2356             {
2357                 ProcessInstanceInfo process_info;
2358                 if (!DecodeProcessInfoResponse (response, process_info))
2359                     break;
2360                 process_infos.Append(process_info);
2361                 response.GetStringRef().clear();
2362                 response.SetFilePos(0);
2363             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2364         }
2365         else
2366         {
2367             m_supports_qfProcessInfo = false;
2368             return 0;
2369         }
2370     }
2371     return process_infos.GetSize();
2372 
2373 }
2374 
2375 bool
2376 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2377 {
2378     if (m_supports_qUserName)
2379     {
2380         char packet[32];
2381         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2382         assert (packet_len < (int)sizeof(packet));
2383         StringExtractorGDBRemote response;
2384         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2385         {
2386             if (response.IsNormalResponse())
2387             {
2388                 // Make sure we parsed the right number of characters. The response is
2389                 // the hex encoded user name and should make up the entire packet.
2390                 // If there are any non-hex ASCII bytes, the length won't match below..
2391                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2392                     return true;
2393             }
2394         }
2395         else
2396         {
2397             m_supports_qUserName = false;
2398             return false;
2399         }
2400     }
2401     return false;
2402 
2403 }
2404 
2405 bool
2406 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2407 {
2408     if (m_supports_qGroupName)
2409     {
2410         char packet[32];
2411         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2412         assert (packet_len < (int)sizeof(packet));
2413         StringExtractorGDBRemote response;
2414         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2415         {
2416             if (response.IsNormalResponse())
2417             {
2418                 // Make sure we parsed the right number of characters. The response is
2419                 // the hex encoded group name and should make up the entire packet.
2420                 // If there are any non-hex ASCII bytes, the length won't match below..
2421                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2422                     return true;
2423             }
2424         }
2425         else
2426         {
2427             m_supports_qGroupName = false;
2428             return false;
2429         }
2430     }
2431     return false;
2432 }
2433 
2434 void
2435 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2436 {
2437     uint32_t i;
2438     TimeValue start_time, end_time;
2439     uint64_t total_time_nsec;
2440     if (SendSpeedTestPacket (0, 0))
2441     {
2442         static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2443         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 };
2444         const size_t k_num_send_sizes = sizeof(g_send_sizes)/sizeof(uint32_t);
2445         const size_t k_num_recv_sizes = sizeof(g_recv_sizes)/sizeof(uint32_t);
2446         const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2447         for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
2448         {
2449             const uint32_t send_size = g_send_sizes[send_idx];
2450             for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
2451             {
2452                 const uint32_t recv_size = g_recv_sizes[recv_idx];
2453                 StreamString packet;
2454                 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2455                 uint32_t bytes_left = send_size;
2456                 while (bytes_left > 0)
2457                 {
2458                     if (bytes_left >= 26)
2459                     {
2460                         packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2461                         bytes_left -= 26;
2462                     }
2463                     else
2464                     {
2465                         packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2466                         bytes_left = 0;
2467                     }
2468                 }
2469 
2470                 start_time = TimeValue::Now();
2471                 if (recv_size == 0)
2472                 {
2473                     for (i=0; i<num_packets; ++i)
2474                     {
2475                         StringExtractorGDBRemote response;
2476                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2477                     }
2478                 }
2479                 else
2480                 {
2481                     uint32_t bytes_read = 0;
2482                     while (bytes_read < k_recv_amount)
2483                     {
2484                         StringExtractorGDBRemote response;
2485                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2486                         bytes_read += recv_size;
2487                     }
2488                 }
2489                 end_time = TimeValue::Now();
2490                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2491                 if (recv_size == 0)
2492                 {
2493                     float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2494                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2495                             num_packets,
2496                             send_size,
2497                             recv_size,
2498                             total_time_nsec / TimeValue::NanoSecPerSec,
2499                             total_time_nsec % TimeValue::NanoSecPerSec,
2500                             packets_per_second);
2501                 }
2502                 else
2503                 {
2504                     float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2505                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2506                             num_packets,
2507                             send_size,
2508                             recv_size,
2509                             total_time_nsec / TimeValue::NanoSecPerSec,
2510                             total_time_nsec % TimeValue::NanoSecPerSec,
2511                             mb_second);
2512                 }
2513             }
2514         }
2515     }
2516 }
2517 
2518 bool
2519 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2520 {
2521     StreamString packet;
2522     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2523     uint32_t bytes_left = send_size;
2524     while (bytes_left > 0)
2525     {
2526         if (bytes_left >= 26)
2527         {
2528             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2529             bytes_left -= 26;
2530         }
2531         else
2532         {
2533             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2534             bytes_left = 0;
2535         }
2536     }
2537 
2538     StringExtractorGDBRemote response;
2539     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)  == PacketResult::Success;
2540 }
2541 
2542 uint16_t
2543 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
2544 {
2545     pid = LLDB_INVALID_PROCESS_ID;
2546     StringExtractorGDBRemote response;
2547     StreamString stream;
2548     stream.PutCString("qLaunchGDBServer;");
2549     std::string hostname;
2550     if (remote_accept_hostname  && remote_accept_hostname[0])
2551         hostname = remote_accept_hostname;
2552     else
2553     {
2554         if (Host::GetHostname (hostname))
2555         {
2556             // Make the GDB server we launch only accept connections from this host
2557             stream.Printf("host:%s;", hostname.c_str());
2558         }
2559         else
2560         {
2561             // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2562             stream.Printf("host:*;");
2563         }
2564     }
2565     const char *packet = stream.GetData();
2566     int packet_len = stream.GetSize();
2567 
2568     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2569     {
2570         std::string name;
2571         std::string value;
2572         uint16_t port = 0;
2573         while (response.GetNameColonValue(name, value))
2574         {
2575             if (name.compare("port") == 0)
2576                 port = Args::StringToUInt32(value.c_str(), 0, 0);
2577             else if (name.compare("pid") == 0)
2578                 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2579         }
2580         return port;
2581     }
2582     return 0;
2583 }
2584 
2585 bool
2586 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2587 {
2588     StreamString stream;
2589     stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2590     const char *packet = stream.GetData();
2591     int packet_len = stream.GetSize();
2592 
2593     StringExtractorGDBRemote response;
2594     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2595     {
2596         if (response.IsOKResponse())
2597             return true;
2598     }
2599     return false;
2600 }
2601 
2602 bool
2603 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2604 {
2605     if (m_curr_tid == tid)
2606         return true;
2607 
2608     char packet[32];
2609     int packet_len;
2610     if (tid == UINT64_MAX)
2611         packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2612     else
2613         packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2614     assert (packet_len + 1 < (int)sizeof(packet));
2615     StringExtractorGDBRemote response;
2616     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2617     {
2618         if (response.IsOKResponse())
2619         {
2620             m_curr_tid = tid;
2621             return true;
2622         }
2623     }
2624     return false;
2625 }
2626 
2627 bool
2628 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2629 {
2630     if (m_curr_tid_run == tid)
2631         return true;
2632 
2633     char packet[32];
2634     int packet_len;
2635     if (tid == UINT64_MAX)
2636         packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2637     else
2638         packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2639 
2640     assert (packet_len + 1 < (int)sizeof(packet));
2641     StringExtractorGDBRemote response;
2642     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2643     {
2644         if (response.IsOKResponse())
2645         {
2646             m_curr_tid_run = tid;
2647             return true;
2648         }
2649     }
2650     return false;
2651 }
2652 
2653 bool
2654 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2655 {
2656     if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
2657         return response.IsNormalResponse();
2658     return false;
2659 }
2660 
2661 bool
2662 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2663 {
2664     if (m_supports_qThreadStopInfo)
2665     {
2666         char packet[256];
2667         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2668         assert (packet_len < (int)sizeof(packet));
2669         if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2670         {
2671             if (response.IsUnsupportedResponse())
2672                 m_supports_qThreadStopInfo = false;
2673             else if (response.IsNormalResponse())
2674                 return true;
2675             else
2676                 return false;
2677         }
2678         else
2679         {
2680             m_supports_qThreadStopInfo = false;
2681         }
2682     }
2683     return false;
2684 }
2685 
2686 
2687 uint8_t
2688 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
2689 {
2690     // Check if the stub is known not to support this breakpoint type
2691     if (!SupportsGDBStoppointPacket(type))
2692         return UINT8_MAX;
2693     // Construct the breakpoint packet
2694     char packet[64];
2695     const int packet_len = ::snprintf (packet,
2696                                        sizeof(packet),
2697                                        "%c%i,%" PRIx64 ",%x",
2698                                        insert ? 'Z' : 'z',
2699                                        type,
2700                                        addr,
2701                                        length);
2702     // Check we havent overwritten the end of the packet buffer
2703     assert (packet_len + 1 < (int)sizeof(packet));
2704     StringExtractorGDBRemote response;
2705     // Try to send the breakpoint packet, and check that it was correctly sent
2706     if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
2707     {
2708         // Receive and OK packet when the breakpoint successfully placed
2709         if (response.IsOKResponse())
2710             return 0;
2711 
2712         // Error while setting breakpoint, send back specific error
2713         if (response.IsErrorResponse())
2714             return response.GetError();
2715 
2716         // Empty packet informs us that breakpoint is not supported
2717         if (response.IsUnsupportedResponse())
2718         {
2719             // Disable this breakpoint type since it is unsupported
2720             switch (type)
2721             {
2722             case eBreakpointSoftware:   m_supports_z0 = false; break;
2723             case eBreakpointHardware:   m_supports_z1 = false; break;
2724             case eWatchpointWrite:      m_supports_z2 = false; break;
2725             case eWatchpointRead:       m_supports_z3 = false; break;
2726             case eWatchpointReadWrite:  m_supports_z4 = false; break;
2727             }
2728         }
2729     }
2730     // Signal generic faliure
2731     return UINT8_MAX;
2732 }
2733 
2734 size_t
2735 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2736                                                    bool &sequence_mutex_unavailable)
2737 {
2738     Mutex::Locker locker;
2739     thread_ids.clear();
2740 
2741     if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2742     {
2743         sequence_mutex_unavailable = false;
2744         StringExtractorGDBRemote response;
2745 
2746         PacketResult packet_result;
2747         for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2748              packet_result == PacketResult::Success && response.IsNormalResponse();
2749              packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
2750         {
2751             char ch = response.GetChar();
2752             if (ch == 'l')
2753                 break;
2754             if (ch == 'm')
2755             {
2756                 do
2757                 {
2758                     tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2759 
2760                     if (tid != LLDB_INVALID_THREAD_ID)
2761                     {
2762                         thread_ids.push_back (tid);
2763                     }
2764                     ch = response.GetChar();    // Skip the command separator
2765                 } while (ch == ',');            // Make sure we got a comma separator
2766             }
2767         }
2768     }
2769     else
2770     {
2771 #if defined (LLDB_CONFIGURATION_DEBUG)
2772         // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2773 #else
2774         Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2775         if (log)
2776             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
2777 #endif
2778         sequence_mutex_unavailable = true;
2779     }
2780     return thread_ids.size();
2781 }
2782 
2783 lldb::addr_t
2784 GDBRemoteCommunicationClient::GetShlibInfoAddr()
2785 {
2786     if (!IsRunning())
2787     {
2788         StringExtractorGDBRemote response;
2789         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
2790         {
2791             if (response.IsNormalResponse())
2792                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2793         }
2794     }
2795     return LLDB_INVALID_ADDRESS;
2796 }
2797 
2798 lldb_private::Error
2799 GDBRemoteCommunicationClient::RunShellCommand (const char *command,           // Shouldn't be NULL
2800                                                const char *working_dir,       // Pass NULL to use the current working directory
2801                                                int *status_ptr,               // Pass NULL if you don't want the process exit status
2802                                                int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
2803                                                std::string *command_output,   // Pass NULL if you don't want the command output
2804                                                uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
2805 {
2806     lldb_private::StreamString stream;
2807     stream.PutCString("qPlatform_shell:");
2808     stream.PutBytesAsRawHex8(command, strlen(command));
2809     stream.PutChar(',');
2810     stream.PutHex32(timeout_sec);
2811     if (working_dir && *working_dir)
2812     {
2813         stream.PutChar(',');
2814         stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2815     }
2816     const char *packet = stream.GetData();
2817     int packet_len = stream.GetSize();
2818     StringExtractorGDBRemote response;
2819     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2820     {
2821         if (response.GetChar() != 'F')
2822             return Error("malformed reply");
2823         if (response.GetChar() != ',')
2824             return Error("malformed reply");
2825         uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2826         if (exitcode == UINT32_MAX)
2827             return Error("unable to run remote process");
2828         else if (status_ptr)
2829             *status_ptr = exitcode;
2830         if (response.GetChar() != ',')
2831             return Error("malformed reply");
2832         uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2833         if (signo_ptr)
2834             *signo_ptr = signo;
2835         if (response.GetChar() != ',')
2836             return Error("malformed reply");
2837         std::string output;
2838         response.GetEscapedBinaryData(output);
2839         if (command_output)
2840             command_output->assign(output);
2841         return Error();
2842     }
2843     return Error("unable to send packet");
2844 }
2845 
2846 Error
2847 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2848                                              uint32_t file_permissions)
2849 {
2850     lldb_private::StreamString stream;
2851     stream.PutCString("qPlatform_mkdir:");
2852     stream.PutHex32(file_permissions);
2853     stream.PutChar(',');
2854     stream.PutBytesAsRawHex8(path, strlen(path));
2855     const char *packet = stream.GetData();
2856     int packet_len = stream.GetSize();
2857     StringExtractorGDBRemote response;
2858     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2859     {
2860         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2861     }
2862     return Error();
2863 
2864 }
2865 
2866 Error
2867 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2868                                                   uint32_t file_permissions)
2869 {
2870     lldb_private::StreamString stream;
2871     stream.PutCString("qPlatform_chmod:");
2872     stream.PutHex32(file_permissions);
2873     stream.PutChar(',');
2874     stream.PutBytesAsRawHex8(path, strlen(path));
2875     const char *packet = stream.GetData();
2876     int packet_len = stream.GetSize();
2877     StringExtractorGDBRemote response;
2878     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2879     {
2880         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2881     }
2882     return Error();
2883 
2884 }
2885 
2886 static uint64_t
2887 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2888                            uint64_t fail_result,
2889                            Error &error)
2890 {
2891     response.SetFilePos(0);
2892     if (response.GetChar() != 'F')
2893         return fail_result;
2894     int32_t result = response.GetS32 (-2);
2895     if (result == -2)
2896         return fail_result;
2897     if (response.GetChar() == ',')
2898     {
2899         int result_errno = response.GetS32 (-2);
2900         if (result_errno != -2)
2901             error.SetError(result_errno, eErrorTypePOSIX);
2902         else
2903             error.SetError(-1, eErrorTypeGeneric);
2904     }
2905     else
2906         error.Clear();
2907     return  result;
2908 }
2909 lldb::user_id_t
2910 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2911                                         uint32_t flags,
2912                                         mode_t mode,
2913                                         Error &error)
2914 {
2915     lldb_private::StreamString stream;
2916     stream.PutCString("vFile:open:");
2917     std::string path (file_spec.GetPath());
2918     if (path.empty())
2919         return UINT64_MAX;
2920     stream.PutCStringAsRawHex8(path.c_str());
2921     stream.PutChar(',');
2922     const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2923     stream.PutHex32(posix_open_flags);
2924     stream.PutChar(',');
2925     stream.PutHex32(mode);
2926     const char* packet = stream.GetData();
2927     int packet_len = stream.GetSize();
2928     StringExtractorGDBRemote response;
2929     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2930     {
2931         return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2932     }
2933     return UINT64_MAX;
2934 }
2935 
2936 bool
2937 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2938                                          Error &error)
2939 {
2940     lldb_private::StreamString stream;
2941     stream.Printf("vFile:close:%i", (int)fd);
2942     const char* packet = stream.GetData();
2943     int packet_len = stream.GetSize();
2944     StringExtractorGDBRemote response;
2945     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2946     {
2947         return ParseHostIOPacketResponse (response, -1, error) == 0;
2948     }
2949     return false;
2950 }
2951 
2952 // Extension of host I/O packets to get the file size.
2953 lldb::user_id_t
2954 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2955 {
2956     lldb_private::StreamString stream;
2957     stream.PutCString("vFile:size:");
2958     std::string path (file_spec.GetPath());
2959     stream.PutCStringAsRawHex8(path.c_str());
2960     const char* packet = stream.GetData();
2961     int packet_len = stream.GetSize();
2962     StringExtractorGDBRemote response;
2963     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2964     {
2965         if (response.GetChar() != 'F')
2966             return UINT64_MAX;
2967         uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2968         return retcode;
2969     }
2970     return UINT64_MAX;
2971 }
2972 
2973 Error
2974 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
2975 {
2976     Error error;
2977     lldb_private::StreamString stream;
2978     stream.PutCString("vFile:mode:");
2979     stream.PutCStringAsRawHex8(path);
2980     const char* packet = stream.GetData();
2981     int packet_len = stream.GetSize();
2982     StringExtractorGDBRemote response;
2983     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2984     {
2985         if (response.GetChar() != 'F')
2986         {
2987             error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2988         }
2989         else
2990         {
2991             const uint32_t mode = response.GetS32(-1);
2992             if (mode == -1)
2993             {
2994                 if (response.GetChar() == ',')
2995                 {
2996                     int response_errno = response.GetS32(-1);
2997                     if (response_errno > 0)
2998                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
2999                     else
3000                         error.SetErrorToGenericError();
3001                 }
3002                 else
3003                     error.SetErrorToGenericError();
3004             }
3005             else
3006             {
3007                 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3008             }
3009         }
3010     }
3011     else
3012     {
3013         error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3014     }
3015     return error;
3016 }
3017 
3018 uint64_t
3019 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3020                                         uint64_t offset,
3021                                         void *dst,
3022                                         uint64_t dst_len,
3023                                         Error &error)
3024 {
3025     lldb_private::StreamString stream;
3026     stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3027     const char* packet = stream.GetData();
3028     int packet_len = stream.GetSize();
3029     StringExtractorGDBRemote response;
3030     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3031     {
3032         if (response.GetChar() != 'F')
3033             return 0;
3034         uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3035         if (retcode == UINT32_MAX)
3036             return retcode;
3037         const char next = (response.Peek() ? *response.Peek() : 0);
3038         if (next == ',')
3039             return 0;
3040         if (next == ';')
3041         {
3042             response.GetChar(); // skip the semicolon
3043             std::string buffer;
3044             if (response.GetEscapedBinaryData(buffer))
3045             {
3046                 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3047                 if (data_to_write > 0)
3048                     memcpy(dst, &buffer[0], data_to_write);
3049                 return data_to_write;
3050             }
3051         }
3052     }
3053     return 0;
3054 }
3055 
3056 uint64_t
3057 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3058                                          uint64_t offset,
3059                                          const void* src,
3060                                          uint64_t src_len,
3061                                          Error &error)
3062 {
3063     lldb_private::StreamGDBRemote stream;
3064     stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3065     stream.PutEscapedBytes(src, src_len);
3066     const char* packet = stream.GetData();
3067     int packet_len = stream.GetSize();
3068     StringExtractorGDBRemote response;
3069     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3070     {
3071         if (response.GetChar() != 'F')
3072         {
3073             error.SetErrorStringWithFormat("write file failed");
3074             return 0;
3075         }
3076         uint64_t bytes_written = response.GetU64(UINT64_MAX);
3077         if (bytes_written == UINT64_MAX)
3078         {
3079             error.SetErrorToGenericError();
3080             if (response.GetChar() == ',')
3081             {
3082                 int response_errno = response.GetS32(-1);
3083                 if (response_errno > 0)
3084                     error.SetError(response_errno, lldb::eErrorTypePOSIX);
3085             }
3086             return 0;
3087         }
3088         return bytes_written;
3089     }
3090     else
3091     {
3092         error.SetErrorString ("failed to send vFile:pwrite packet");
3093     }
3094     return 0;
3095 }
3096 
3097 Error
3098 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3099 {
3100     Error error;
3101     lldb_private::StreamGDBRemote stream;
3102     stream.PutCString("vFile:symlink:");
3103     // the unix symlink() command reverses its parameters where the dst if first,
3104     // so we follow suit here
3105     stream.PutCStringAsRawHex8(dst);
3106     stream.PutChar(',');
3107     stream.PutCStringAsRawHex8(src);
3108     const char* packet = stream.GetData();
3109     int packet_len = stream.GetSize();
3110     StringExtractorGDBRemote response;
3111     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3112     {
3113         if (response.GetChar() == 'F')
3114         {
3115             uint32_t result = response.GetU32(UINT32_MAX);
3116             if (result != 0)
3117             {
3118                 error.SetErrorToGenericError();
3119                 if (response.GetChar() == ',')
3120                 {
3121                     int response_errno = response.GetS32(-1);
3122                     if (response_errno > 0)
3123                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3124                 }
3125             }
3126         }
3127         else
3128         {
3129             // Should have returned with 'F<result>[,<errno>]'
3130             error.SetErrorStringWithFormat("symlink failed");
3131         }
3132     }
3133     else
3134     {
3135         error.SetErrorString ("failed to send vFile:symlink packet");
3136     }
3137     return error;
3138 }
3139 
3140 Error
3141 GDBRemoteCommunicationClient::Unlink (const char *path)
3142 {
3143     Error error;
3144     lldb_private::StreamGDBRemote stream;
3145     stream.PutCString("vFile:unlink:");
3146     // the unix symlink() command reverses its parameters where the dst if first,
3147     // so we follow suit here
3148     stream.PutCStringAsRawHex8(path);
3149     const char* packet = stream.GetData();
3150     int packet_len = stream.GetSize();
3151     StringExtractorGDBRemote response;
3152     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3153     {
3154         if (response.GetChar() == 'F')
3155         {
3156             uint32_t result = response.GetU32(UINT32_MAX);
3157             if (result != 0)
3158             {
3159                 error.SetErrorToGenericError();
3160                 if (response.GetChar() == ',')
3161                 {
3162                     int response_errno = response.GetS32(-1);
3163                     if (response_errno > 0)
3164                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3165                 }
3166             }
3167         }
3168         else
3169         {
3170             // Should have returned with 'F<result>[,<errno>]'
3171             error.SetErrorStringWithFormat("unlink failed");
3172         }
3173     }
3174     else
3175     {
3176         error.SetErrorString ("failed to send vFile:unlink packet");
3177     }
3178     return error;
3179 }
3180 
3181 // Extension of host I/O packets to get whether a file exists.
3182 bool
3183 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3184 {
3185     lldb_private::StreamString stream;
3186     stream.PutCString("vFile:exists:");
3187     std::string path (file_spec.GetPath());
3188     stream.PutCStringAsRawHex8(path.c_str());
3189     const char* packet = stream.GetData();
3190     int packet_len = stream.GetSize();
3191     StringExtractorGDBRemote response;
3192     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3193     {
3194         if (response.GetChar() != 'F')
3195             return false;
3196         if (response.GetChar() != ',')
3197             return false;
3198         bool retcode = (response.GetChar() != '0');
3199         return retcode;
3200     }
3201     return false;
3202 }
3203 
3204 bool
3205 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3206                                             uint64_t &high,
3207                                             uint64_t &low)
3208 {
3209     lldb_private::StreamString stream;
3210     stream.PutCString("vFile:MD5:");
3211     std::string path (file_spec.GetPath());
3212     stream.PutCStringAsRawHex8(path.c_str());
3213     const char* packet = stream.GetData();
3214     int packet_len = stream.GetSize();
3215     StringExtractorGDBRemote response;
3216     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3217     {
3218         if (response.GetChar() != 'F')
3219             return false;
3220         if (response.GetChar() != ',')
3221             return false;
3222         if (response.Peek() && *response.Peek() == 'x')
3223             return false;
3224         low = response.GetHexMaxU64(false, UINT64_MAX);
3225         high = response.GetHexMaxU64(false, UINT64_MAX);
3226         return true;
3227     }
3228     return false;
3229 }
3230 
3231 bool
3232 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3233 {
3234     Mutex::Locker locker;
3235     if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3236     {
3237         const bool thread_suffix_supported = GetThreadSuffixSupported();
3238 
3239         if (thread_suffix_supported || SetCurrentThread(tid))
3240         {
3241             char packet[64];
3242             int packet_len = 0;
3243             if (thread_suffix_supported)
3244                 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3245             else
3246                 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3247             assert (packet_len < ((int)sizeof(packet) - 1));
3248             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3249         }
3250     }
3251     return false;
3252 
3253 }
3254 
3255 
3256 bool
3257 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3258 {
3259     Mutex::Locker locker;
3260     if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3261     {
3262         const bool thread_suffix_supported = GetThreadSuffixSupported();
3263 
3264         if (thread_suffix_supported || SetCurrentThread(tid))
3265         {
3266             char packet[64];
3267             int packet_len = 0;
3268             // Get all registers in one packet
3269             if (thread_suffix_supported)
3270                 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3271             else
3272                 packet_len = ::snprintf (packet, sizeof(packet), "g");
3273             assert (packet_len < ((int)sizeof(packet) - 1));
3274             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3275         }
3276     }
3277     return false;
3278 }
3279 bool
3280 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3281 {
3282     save_id = 0; // Set to invalid save ID
3283     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3284         return false;
3285 
3286     m_supports_QSaveRegisterState = eLazyBoolYes;
3287     Mutex::Locker locker;
3288     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3289     {
3290         const bool thread_suffix_supported = GetThreadSuffixSupported();
3291         if (thread_suffix_supported || SetCurrentThread(tid))
3292         {
3293             char packet[256];
3294             if (thread_suffix_supported)
3295                 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3296             else
3297                 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3298 
3299             StringExtractorGDBRemote response;
3300 
3301             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3302             {
3303                 if (response.IsUnsupportedResponse())
3304                 {
3305                     // This packet isn't supported, don't try calling it again
3306                     m_supports_QSaveRegisterState = eLazyBoolNo;
3307                 }
3308 
3309                 const uint32_t response_save_id = response.GetU32(0);
3310                 if (response_save_id != 0)
3311                 {
3312                     save_id = response_save_id;
3313                     return true;
3314                 }
3315             }
3316         }
3317     }
3318     return false;
3319 }
3320 
3321 bool
3322 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3323 {
3324     // We use the "m_supports_QSaveRegisterState" variable here becuase the
3325     // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3326     // order to be useful
3327     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3328         return false;
3329 
3330     Mutex::Locker locker;
3331     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3332     {
3333         const bool thread_suffix_supported = GetThreadSuffixSupported();
3334         if (thread_suffix_supported || SetCurrentThread(tid))
3335         {
3336             char packet[256];
3337             if (thread_suffix_supported)
3338                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3339             else
3340                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3341 
3342             StringExtractorGDBRemote response;
3343 
3344             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3345             {
3346                 if (response.IsOKResponse())
3347                 {
3348                     return true;
3349                 }
3350                 else if (response.IsUnsupportedResponse())
3351                 {
3352                     // This packet isn't supported, don't try calling this packet or
3353                     // QSaveRegisterState again...
3354                     m_supports_QSaveRegisterState = eLazyBoolNo;
3355                 }
3356             }
3357         }
3358     }
3359     return false;
3360 }
3361