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 // C++ Includes
15 // Other libraries and framework includes
16 #include "llvm/ADT/Triple.h"
17 #include "lldb/Interpreter/Args.h"
18 #include "lldb/Core/ConnectionFileDescriptor.h"
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/State.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Host/Endian.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Host/TimeValue.h"
25 
26 // Project includes
27 #include "Utility/StringExtractorGDBRemote.h"
28 #include "ProcessGDBRemote.h"
29 #include "ProcessGDBRemoteLog.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 //----------------------------------------------------------------------
35 // GDBRemoteCommunicationClient constructor
36 //----------------------------------------------------------------------
37 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
38     GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
39     m_supports_not_sending_acks (eLazyBoolCalculate),
40     m_supports_thread_suffix (eLazyBoolCalculate),
41     m_supports_threads_in_stop_reply (eLazyBoolCalculate),
42     m_supports_vCont_all (eLazyBoolCalculate),
43     m_supports_vCont_any (eLazyBoolCalculate),
44     m_supports_vCont_c (eLazyBoolCalculate),
45     m_supports_vCont_C (eLazyBoolCalculate),
46     m_supports_vCont_s (eLazyBoolCalculate),
47     m_supports_vCont_S (eLazyBoolCalculate),
48     m_qHostInfo_is_valid (eLazyBoolCalculate),
49     m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
50     m_supports_memory_region_info  (eLazyBoolCalculate),
51     m_supports_qProcessInfoPID (true),
52     m_supports_qfProcessInfo (true),
53     m_supports_qUserName (true),
54     m_supports_qGroupName (true),
55     m_supports_qThreadStopInfo (true),
56     m_supports_z0 (true),
57     m_supports_z1 (true),
58     m_supports_z2 (true),
59     m_supports_z3 (true),
60     m_supports_z4 (true),
61     m_curr_tid (LLDB_INVALID_THREAD_ID),
62     m_curr_tid_run (LLDB_INVALID_THREAD_ID),
63     m_async_mutex (Mutex::eMutexTypeRecursive),
64     m_async_packet_predicate (false),
65     m_async_packet (),
66     m_async_response (),
67     m_async_signal (-1),
68     m_host_arch(),
69     m_os_version_major (UINT32_MAX),
70     m_os_version_minor (UINT32_MAX),
71     m_os_version_update (UINT32_MAX)
72 {
73 }
74 
75 //----------------------------------------------------------------------
76 // Destructor
77 //----------------------------------------------------------------------
78 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
79 {
80     if (IsConnected())
81         Disconnect();
82 }
83 
84 bool
85 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
86 {
87     // Start the read thread after we send the handshake ack since if we
88     // fail to send the handshake ack, there is no reason to continue...
89     if (SendAck())
90         return true;
91 
92     if (error_ptr)
93         error_ptr->SetErrorString("failed to send the handshake ack");
94     return false;
95 }
96 
97 void
98 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
99 {
100     if (m_supports_not_sending_acks == eLazyBoolCalculate)
101     {
102         m_send_acks = true;
103         m_supports_not_sending_acks = eLazyBoolNo;
104 
105         StringExtractorGDBRemote response;
106         if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
107         {
108             if (response.IsOKResponse())
109             {
110                 m_send_acks = false;
111                 m_supports_not_sending_acks = eLazyBoolYes;
112             }
113         }
114     }
115 }
116 
117 void
118 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
119 {
120     if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
121     {
122         m_supports_threads_in_stop_reply = eLazyBoolNo;
123 
124         StringExtractorGDBRemote response;
125         if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
126         {
127             if (response.IsOKResponse())
128                 m_supports_threads_in_stop_reply = eLazyBoolYes;
129         }
130     }
131 }
132 
133 
134 void
135 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
136 {
137     m_supports_not_sending_acks = eLazyBoolCalculate;
138     m_supports_thread_suffix = eLazyBoolCalculate;
139     m_supports_threads_in_stop_reply = eLazyBoolCalculate;
140     m_supports_vCont_c = eLazyBoolCalculate;
141     m_supports_vCont_C = eLazyBoolCalculate;
142     m_supports_vCont_s = eLazyBoolCalculate;
143     m_supports_vCont_S = eLazyBoolCalculate;
144     m_qHostInfo_is_valid = eLazyBoolCalculate;
145     m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
146     m_supports_memory_region_info = eLazyBoolCalculate;
147 
148     m_supports_qProcessInfoPID = true;
149     m_supports_qfProcessInfo = true;
150     m_supports_qUserName = true;
151     m_supports_qGroupName = true;
152     m_supports_qThreadStopInfo = true;
153     m_supports_z0 = true;
154     m_supports_z1 = true;
155     m_supports_z2 = true;
156     m_supports_z3 = true;
157     m_supports_z4 = true;
158     m_host_arch.Clear();
159 }
160 
161 
162 bool
163 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
164 {
165     if (m_supports_thread_suffix == eLazyBoolCalculate)
166     {
167         StringExtractorGDBRemote response;
168         m_supports_thread_suffix = eLazyBoolNo;
169         if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
170         {
171             if (response.IsOKResponse())
172                 m_supports_thread_suffix = eLazyBoolYes;
173         }
174     }
175     return m_supports_thread_suffix;
176 }
177 bool
178 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
179 {
180     if (m_supports_vCont_c == eLazyBoolCalculate)
181     {
182         StringExtractorGDBRemote response;
183         m_supports_vCont_any = eLazyBoolNo;
184         m_supports_vCont_all = eLazyBoolNo;
185         m_supports_vCont_c = eLazyBoolNo;
186         m_supports_vCont_C = eLazyBoolNo;
187         m_supports_vCont_s = eLazyBoolNo;
188         m_supports_vCont_S = eLazyBoolNo;
189         if (SendPacketAndWaitForResponse("vCont?", response, false))
190         {
191             const char *response_cstr = response.GetStringRef().c_str();
192             if (::strstr (response_cstr, ";c"))
193                 m_supports_vCont_c = eLazyBoolYes;
194 
195             if (::strstr (response_cstr, ";C"))
196                 m_supports_vCont_C = eLazyBoolYes;
197 
198             if (::strstr (response_cstr, ";s"))
199                 m_supports_vCont_s = eLazyBoolYes;
200 
201             if (::strstr (response_cstr, ";S"))
202                 m_supports_vCont_S = eLazyBoolYes;
203 
204             if (m_supports_vCont_c == eLazyBoolYes &&
205                 m_supports_vCont_C == eLazyBoolYes &&
206                 m_supports_vCont_s == eLazyBoolYes &&
207                 m_supports_vCont_S == eLazyBoolYes)
208             {
209                 m_supports_vCont_all = eLazyBoolYes;
210             }
211 
212             if (m_supports_vCont_c == eLazyBoolYes ||
213                 m_supports_vCont_C == eLazyBoolYes ||
214                 m_supports_vCont_s == eLazyBoolYes ||
215                 m_supports_vCont_S == eLazyBoolYes)
216             {
217                 m_supports_vCont_any = eLazyBoolYes;
218             }
219         }
220     }
221 
222     switch (flavor)
223     {
224     case 'a': return m_supports_vCont_any;
225     case 'A': return m_supports_vCont_all;
226     case 'c': return m_supports_vCont_c;
227     case 'C': return m_supports_vCont_C;
228     case 's': return m_supports_vCont_s;
229     case 'S': return m_supports_vCont_S;
230     default: break;
231     }
232     return false;
233 }
234 
235 
236 size_t
237 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
238 (
239     const char *payload,
240     StringExtractorGDBRemote &response,
241     bool send_async
242 )
243 {
244     return SendPacketAndWaitForResponse (payload,
245                                          ::strlen (payload),
246                                          response,
247                                          send_async);
248 }
249 
250 size_t
251 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
252 (
253     const char *payload,
254     size_t payload_length,
255     StringExtractorGDBRemote &response,
256     bool send_async
257 )
258 {
259     Mutex::Locker locker;
260     LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
261     size_t response_len = 0;
262     if (GetSequenceMutex (locker))
263     {
264         if (SendPacketNoLock (payload, payload_length))
265            response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
266         else
267         {
268             if (log)
269                 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
270         }
271     }
272     else
273     {
274         if (send_async)
275         {
276             Mutex::Locker async_locker (m_async_mutex);
277             m_async_packet.assign(payload, payload_length);
278             m_async_packet_predicate.SetValue (true, eBroadcastNever);
279 
280             if (log)
281                 log->Printf ("async: async packet = %s", m_async_packet.c_str());
282 
283             bool timed_out = false;
284             if (SendInterrupt(locker, 2, timed_out))
285             {
286                 if (m_interrupt_sent)
287                 {
288                     TimeValue timeout_time;
289                     timeout_time = TimeValue::Now();
290                     timeout_time.OffsetWithSeconds (m_packet_timeout);
291 
292                     if (log)
293                         log->Printf ("async: sent interrupt");
294 
295                     if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
296                     {
297                         if (log)
298                             log->Printf ("async: got response");
299 
300                         // Swap the response buffer to avoid malloc and string copy
301                         response.GetStringRef().swap (m_async_response.GetStringRef());
302                         response_len = response.GetStringRef().size();
303                     }
304                     else
305                     {
306                         if (log)
307                             log->Printf ("async: timed out waiting for response");
308                     }
309 
310                     // Make sure we wait until the continue packet has been sent again...
311                     if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
312                     {
313                         if (log)
314                         {
315                             if (timed_out)
316                                 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
317                             else
318                                 log->Printf ("async: async packet sent");
319                         }
320                     }
321                     else
322                     {
323                         if (log)
324                             log->Printf ("async: timed out waiting for process to resume");
325                     }
326                 }
327                 else
328                 {
329                     // We had a racy condition where we went to send the interrupt
330                     // yet we were able to get the lock, so the process must have
331                     // just stopped?
332                     if (log)
333                         log->Printf ("async: got lock without sending interrupt");
334                     // Send the packet normally since we got the lock
335                     if (SendPacketNoLock (payload, payload_length))
336                         response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
337                     else
338                     {
339                         if (log)
340                             log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
341                     }
342                 }
343             }
344             else
345             {
346                 if (log)
347                     log->Printf ("async: failed to interrupt");
348             }
349         }
350         else
351         {
352             if (log)
353                 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
354         }
355     }
356     if (response_len == 0)
357     {
358         if (log)
359             log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
360     }
361     return response_len;
362 }
363 
364 StateType
365 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
366 (
367     ProcessGDBRemote *process,
368     const char *payload,
369     size_t packet_length,
370     StringExtractorGDBRemote &response
371 )
372 {
373     LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
374     if (log)
375         log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
376 
377     Mutex::Locker locker(m_sequence_mutex);
378     StateType state = eStateRunning;
379 
380     BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
381     m_public_is_running.SetValue (true, eBroadcastNever);
382     // Set the starting continue packet into "continue_packet". This packet
383     // make change if we are interrupted and we continue after an async packet...
384     std::string continue_packet(payload, packet_length);
385 
386     bool got_stdout = false;
387 
388     while (state == eStateRunning)
389     {
390         if (!got_stdout)
391         {
392             if (log)
393                 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
394             if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
395                 state = eStateInvalid;
396 
397             m_private_is_running.SetValue (true, eBroadcastAlways);
398         }
399 
400         got_stdout = false;
401 
402         if (log)
403             log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
404 
405         if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
406         {
407             if (response.Empty())
408                 state = eStateInvalid;
409             else
410             {
411                 const char stop_type = response.GetChar();
412                 if (log)
413                     log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
414                 switch (stop_type)
415                 {
416                 case 'T':
417                 case 'S':
418                     {
419                         if (process->GetStopID() == 0)
420                         {
421                             if (process->GetID() == LLDB_INVALID_PROCESS_ID)
422                             {
423                                 lldb::pid_t pid = GetCurrentProcessID ();
424                                 if (pid != LLDB_INVALID_PROCESS_ID)
425                                     process->SetID (pid);
426                             }
427                             process->BuildDynamicRegisterInfo (true);
428                         }
429 
430                         // Privately notify any internal threads that we have stopped
431                         // in case we wanted to interrupt our process, yet we might
432                         // send a packet and continue without returning control to the
433                         // user.
434                         m_private_is_running.SetValue (false, eBroadcastAlways);
435 
436                         const uint8_t signo = response.GetHexU8 (UINT8_MAX);
437 
438                         bool continue_after_aync = false;
439                         if (m_async_signal != -1 || m_async_packet_predicate.GetValue())
440                         {
441                             continue_after_aync = true;
442                             // We sent an interrupt packet to stop the inferior process
443                             // for an async signal or to send an async packet while running
444                             // but we might have been single stepping and received the
445                             // stop packet for the step instead of for the interrupt packet.
446                             // Typically when an interrupt is sent a SIGINT or SIGSTOP
447                             // is used, so if we get anything else, we need to try and
448                             // get another stop reply packet that may have been sent
449                             // due to sending the interrupt when the target is stopped
450                             // which will just re-send a copy of the last stop reply
451                             // packet. If we don't do this, then the reply for our
452                             // async packet will be the repeat stop reply packet and cause
453                             // a lot of trouble for us!
454                             if (signo != SIGINT && signo != SIGSTOP)
455                             {
456                                 continue_after_aync = false;
457 
458                                 // We didn't get a a SIGINT or SIGSTOP, so try for a
459                                 // very brief time (1 ms) to get another stop reply
460                                 // packet to make sure it doesn't get in the way
461                                 StringExtractorGDBRemote extra_stop_reply_packet;
462                                 uint32_t timeout_usec = 1000;
463                                 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
464                                 {
465                                     switch (extra_stop_reply_packet.GetChar())
466                                     {
467                                     case 'T':
468                                     case 'S':
469                                         // We did get an extra stop reply, which means
470                                         // our interrupt didn't stop the target so we
471                                         // shouldn't continue after the async signal
472                                         // or packet is sent...
473                                         continue_after_aync = false;
474                                         break;
475                                     }
476                                 }
477                             }
478                         }
479 
480                         if (m_async_signal != -1)
481                         {
482                             if (log)
483                                 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
484 
485                             // Save off the async signal we are supposed to send
486                             const int async_signal = m_async_signal;
487                             // Clear the async signal member so we don't end up
488                             // sending the signal multiple times...
489                             m_async_signal = -1;
490                             // Check which signal we stopped with
491                             if (signo == async_signal)
492                             {
493                                 if (log)
494                                     log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
495 
496                                 // We already stopped with a signal that we wanted
497                                 // to stop with, so we are done
498                             }
499                             else
500                             {
501                                 // We stopped with a different signal that the one
502                                 // we wanted to stop with, so now we must resume
503                                 // with the signal we want
504                                 char signal_packet[32];
505                                 int signal_packet_len = 0;
506                                 signal_packet_len = ::snprintf (signal_packet,
507                                                                 sizeof (signal_packet),
508                                                                 "C%2.2x",
509                                                                 async_signal);
510 
511                                 if (log)
512                                     log->Printf ("async: stopped with signal %s, resume with %s",
513                                                        Host::GetSignalAsCString (signo),
514                                                        Host::GetSignalAsCString (async_signal));
515 
516                                 // Set the continue packet to resume even if the
517                                 // interrupt didn't cause our stop (ignore continue_after_aync)
518                                 continue_packet.assign(signal_packet, signal_packet_len);
519                                 continue;
520                             }
521                         }
522                         else if (m_async_packet_predicate.GetValue())
523                         {
524                             LogSP packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
525 
526                             // We are supposed to send an asynchronous packet while
527                             // we are running.
528                             m_async_response.Clear();
529                             if (m_async_packet.empty())
530                             {
531                                 if (packet_log)
532                                     packet_log->Printf ("async: error: empty async packet");
533 
534                             }
535                             else
536                             {
537                                 if (packet_log)
538                                     packet_log->Printf ("async: sending packet");
539 
540                                 SendPacketAndWaitForResponse (&m_async_packet[0],
541                                                               m_async_packet.size(),
542                                                               m_async_response,
543                                                               false);
544                             }
545                             // Let the other thread that was trying to send the async
546                             // packet know that the packet has been sent and response is
547                             // ready...
548                             m_async_packet_predicate.SetValue(false, eBroadcastAlways);
549 
550                             if (packet_log)
551                                 packet_log->Printf ("async: sent packet, continue_after_aync = %i", continue_after_aync);
552 
553                             // Set the continue packet to resume if our interrupt
554                             // for the async packet did cause the stop
555                             if (continue_after_aync)
556                             {
557                                 continue_packet.assign (1, 'c');
558                                 continue;
559                             }
560                         }
561                         // Stop with signal and thread info
562                         state = eStateStopped;
563                     }
564                     break;
565 
566                 case 'W':
567                 case 'X':
568                     // process exited
569                     state = eStateExited;
570                     break;
571 
572                 case 'O':
573                     // STDOUT
574                     {
575                         got_stdout = true;
576                         std::string inferior_stdout;
577                         inferior_stdout.reserve(response.GetBytesLeft () / 2);
578                         char ch;
579                         while ((ch = response.GetHexU8()) != '\0')
580                             inferior_stdout.append(1, ch);
581                         process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
582                     }
583                     break;
584 
585                 case 'E':
586                     // ERROR
587                     state = eStateInvalid;
588                     break;
589 
590                 default:
591                     if (log)
592                         log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
593                     state = eStateInvalid;
594                     break;
595                 }
596             }
597         }
598         else
599         {
600             if (log)
601                 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
602             state = eStateInvalid;
603         }
604     }
605     if (log)
606         log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
607     response.SetFilePos(0);
608     m_private_is_running.SetValue (false, eBroadcastAlways);
609     m_public_is_running.SetValue (false, eBroadcastAlways);
610     return state;
611 }
612 
613 bool
614 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
615 {
616     Mutex::Locker async_locker (m_async_mutex);
617     m_async_signal = signo;
618     bool timed_out = false;
619     Mutex::Locker locker;
620     if (SendInterrupt (locker, 1, timed_out))
621         return true;
622     m_async_signal = -1;
623     return false;
624 }
625 
626 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
627 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
628 // (the expected result), then it will send the halt packet. If it does succeed
629 // then the caller that requested the interrupt will want to keep the sequence
630 // locked down so that no one else can send packets while the caller has control.
631 // This function usually gets called when we are running and need to stop the
632 // target. It can also be used when we are running and and we need to do something
633 // else (like read/write memory), so we need to interrupt the running process
634 // (gdb remote protocol requires this), and do what we need to do, then resume.
635 
636 bool
637 GDBRemoteCommunicationClient::SendInterrupt
638 (
639     Mutex::Locker& locker,
640     uint32_t seconds_to_wait_for_stop,
641     bool &timed_out
642 )
643 {
644     m_interrupt_sent = false;
645     timed_out = false;
646     LogSP log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
647 
648     if (IsRunning())
649     {
650         // Only send an interrupt if our debugserver is running...
651         if (GetSequenceMutex (locker))
652         {
653             if (log)
654                 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
655         }
656         else
657         {
658             // Someone has the mutex locked waiting for a response or for the
659             // inferior to stop, so send the interrupt on the down low...
660             char ctrl_c = '\x03';
661             ConnectionStatus status = eConnectionStatusSuccess;
662             size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
663             if (log)
664                 log->PutCString("send packet: \\x03");
665             if (bytes_written > 0)
666             {
667                 m_interrupt_sent = true;
668                 if (seconds_to_wait_for_stop)
669                 {
670                     TimeValue timeout;
671                     if (seconds_to_wait_for_stop)
672                     {
673                         timeout = TimeValue::Now();
674                         timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
675                     }
676                     if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
677                     {
678                         if (log)
679                             log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
680                         return true;
681                     }
682                     else
683                     {
684                         if (log)
685                             log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
686                     }
687                 }
688                 else
689                 {
690                     if (log)
691                         log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
692                     return true;
693                 }
694             }
695             else
696             {
697                 if (log)
698                     log->Printf ("SendInterrupt () - failed to write interrupt");
699             }
700             return false;
701         }
702     }
703     else
704     {
705         if (log)
706             log->Printf ("SendInterrupt () - not running");
707     }
708     return true;
709 }
710 
711 lldb::pid_t
712 GDBRemoteCommunicationClient::GetCurrentProcessID ()
713 {
714     StringExtractorGDBRemote response;
715     if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
716     {
717         if (response.GetChar() == 'Q')
718             if (response.GetChar() == 'C')
719                 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
720     }
721     return LLDB_INVALID_PROCESS_ID;
722 }
723 
724 bool
725 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
726 {
727     error_str.clear();
728     StringExtractorGDBRemote response;
729     if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
730     {
731         if (response.IsOKResponse())
732             return true;
733         if (response.GetChar() == 'E')
734         {
735             // A string the describes what failed when launching...
736             error_str = response.GetStringRef().substr(1);
737         }
738         else
739         {
740             error_str.assign ("unknown error occurred launching process");
741         }
742     }
743     else
744     {
745         error_str.assign ("failed to send the qLaunchSuccess packet");
746     }
747     return false;
748 }
749 
750 int
751 GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
752 {
753     if (argv && argv[0])
754     {
755         StreamString packet;
756         packet.PutChar('A');
757         const char *arg;
758         for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
759         {
760             const int arg_len = strlen(arg);
761             if (i > 0)
762                 packet.PutChar(',');
763             packet.Printf("%i,%i,", arg_len * 2, i);
764             packet.PutBytesAsRawHex8 (arg, arg_len);
765         }
766 
767         StringExtractorGDBRemote response;
768         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
769         {
770             if (response.IsOKResponse())
771                 return 0;
772             uint8_t error = response.GetError();
773             if (error)
774                 return error;
775         }
776     }
777     return -1;
778 }
779 
780 int
781 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
782 {
783     if (name_equal_value && name_equal_value[0])
784     {
785         StreamString packet;
786         packet.Printf("QEnvironment:%s", name_equal_value);
787         StringExtractorGDBRemote response;
788         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
789         {
790             if (response.IsOKResponse())
791                 return 0;
792             uint8_t error = response.GetError();
793             if (error)
794                 return error;
795         }
796     }
797     return -1;
798 }
799 
800 int
801 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
802 {
803     if (arch && arch[0])
804     {
805         StreamString packet;
806         packet.Printf("QLaunchArch:%s", arch);
807         StringExtractorGDBRemote response;
808         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
809         {
810             if (response.IsOKResponse())
811                 return 0;
812             uint8_t error = response.GetError();
813             if (error)
814                 return error;
815         }
816     }
817     return -1;
818 }
819 
820 bool
821 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
822                                             uint32_t &minor,
823                                             uint32_t &update)
824 {
825     if (GetHostInfo ())
826     {
827         if (m_os_version_major != UINT32_MAX)
828         {
829             major = m_os_version_major;
830             minor = m_os_version_minor;
831             update = m_os_version_update;
832             return true;
833         }
834     }
835     return false;
836 }
837 
838 bool
839 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
840 {
841     if (GetHostInfo ())
842     {
843         if (!m_os_build.empty())
844         {
845             s = m_os_build;
846             return true;
847         }
848     }
849     s.clear();
850     return false;
851 }
852 
853 
854 bool
855 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
856 {
857     if (GetHostInfo ())
858     {
859         if (!m_os_kernel.empty())
860         {
861             s = m_os_kernel;
862             return true;
863         }
864     }
865     s.clear();
866     return false;
867 }
868 
869 bool
870 GDBRemoteCommunicationClient::GetHostname (std::string &s)
871 {
872     if (GetHostInfo ())
873     {
874         if (!m_hostname.empty())
875         {
876             s = m_hostname;
877             return true;
878         }
879     }
880     s.clear();
881     return false;
882 }
883 
884 ArchSpec
885 GDBRemoteCommunicationClient::GetSystemArchitecture ()
886 {
887     if (GetHostInfo ())
888         return m_host_arch;
889     return ArchSpec();
890 }
891 
892 
893 bool
894 GDBRemoteCommunicationClient::GetHostInfo (bool force)
895 {
896     if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
897     {
898         m_qHostInfo_is_valid = eLazyBoolNo;
899         StringExtractorGDBRemote response;
900         if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
901         {
902             if (response.IsNormalResponse())
903             {
904                 std::string name;
905                 std::string value;
906                 uint32_t cpu = LLDB_INVALID_CPUTYPE;
907                 uint32_t sub = 0;
908                 std::string arch_name;
909                 std::string os_name;
910                 std::string vendor_name;
911                 std::string triple;
912                 uint32_t pointer_byte_size = 0;
913                 StringExtractor extractor;
914                 ByteOrder byte_order = eByteOrderInvalid;
915                 uint32_t num_keys_decoded = 0;
916                 while (response.GetNameColonValue(name, value))
917                 {
918                     if (name.compare("cputype") == 0)
919                     {
920                         // exception type in big endian hex
921                         cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
922                         if (cpu != LLDB_INVALID_CPUTYPE)
923                             ++num_keys_decoded;
924                     }
925                     else if (name.compare("cpusubtype") == 0)
926                     {
927                         // exception count in big endian hex
928                         sub = Args::StringToUInt32 (value.c_str(), 0, 0);
929                         if (sub != 0)
930                             ++num_keys_decoded;
931                     }
932                     else if (name.compare("arch") == 0)
933                     {
934                         arch_name.swap (value);
935                         ++num_keys_decoded;
936                     }
937                     else if (name.compare("triple") == 0)
938                     {
939                         // The triple comes as ASCII hex bytes since it contains '-' chars
940                         extractor.GetStringRef().swap(value);
941                         extractor.SetFilePos(0);
942                         extractor.GetHexByteString (triple);
943                         ++num_keys_decoded;
944                     }
945                     else if (name.compare("os_build") == 0)
946                     {
947                         extractor.GetStringRef().swap(value);
948                         extractor.SetFilePos(0);
949                         extractor.GetHexByteString (m_os_build);
950                         ++num_keys_decoded;
951                     }
952                     else if (name.compare("hostname") == 0)
953                     {
954                         extractor.GetStringRef().swap(value);
955                         extractor.SetFilePos(0);
956                         extractor.GetHexByteString (m_hostname);
957                         ++num_keys_decoded;
958                     }
959                     else if (name.compare("os_kernel") == 0)
960                     {
961                         extractor.GetStringRef().swap(value);
962                         extractor.SetFilePos(0);
963                         extractor.GetHexByteString (m_os_kernel);
964                         ++num_keys_decoded;
965                     }
966                     else if (name.compare("ostype") == 0)
967                     {
968                         os_name.swap (value);
969                         ++num_keys_decoded;
970                     }
971                     else if (name.compare("vendor") == 0)
972                     {
973                         vendor_name.swap(value);
974                         ++num_keys_decoded;
975                     }
976                     else if (name.compare("endian") == 0)
977                     {
978                         ++num_keys_decoded;
979                         if (value.compare("little") == 0)
980                             byte_order = eByteOrderLittle;
981                         else if (value.compare("big") == 0)
982                             byte_order = eByteOrderBig;
983                         else if (value.compare("pdp") == 0)
984                             byte_order = eByteOrderPDP;
985                         else
986                             --num_keys_decoded;
987                     }
988                     else if (name.compare("ptrsize") == 0)
989                     {
990                         pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
991                         if (pointer_byte_size != 0)
992                             ++num_keys_decoded;
993                     }
994                     else if (name.compare("os_version") == 0)
995                     {
996                         Args::StringToVersion (value.c_str(),
997                                                m_os_version_major,
998                                                m_os_version_minor,
999                                                m_os_version_update);
1000                         if (m_os_version_major != UINT32_MAX)
1001                             ++num_keys_decoded;
1002                     }
1003                 }
1004 
1005                 if (num_keys_decoded > 0)
1006                     m_qHostInfo_is_valid = eLazyBoolYes;
1007 
1008                 if (triple.empty())
1009                 {
1010                     if (arch_name.empty())
1011                     {
1012                         if (cpu != LLDB_INVALID_CPUTYPE)
1013                         {
1014                             m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1015                             if (pointer_byte_size)
1016                             {
1017                                 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1018                             }
1019                             if (byte_order != eByteOrderInvalid)
1020                             {
1021                                 assert (byte_order == m_host_arch.GetByteOrder());
1022                             }
1023                             if (!vendor_name.empty())
1024                                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1025                             if (!os_name.empty())
1026                                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1027 
1028                         }
1029                     }
1030                     else
1031                     {
1032                         std::string triple;
1033                         triple += arch_name;
1034                         triple += '-';
1035                         if (vendor_name.empty())
1036                             triple += "unknown";
1037                         else
1038                             triple += vendor_name;
1039                         triple += '-';
1040                         if (os_name.empty())
1041                             triple += "unknown";
1042                         else
1043                             triple += os_name;
1044                         m_host_arch.SetTriple (triple.c_str(), NULL);
1045                         if (pointer_byte_size)
1046                         {
1047                             assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1048                         }
1049                         if (byte_order != eByteOrderInvalid)
1050                         {
1051                             assert (byte_order == m_host_arch.GetByteOrder());
1052                         }
1053 
1054                     }
1055                 }
1056                 else
1057                 {
1058                     m_host_arch.SetTriple (triple.c_str(), NULL);
1059                     if (pointer_byte_size)
1060                     {
1061                         assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1062                     }
1063                     if (byte_order != eByteOrderInvalid)
1064                     {
1065                         assert (byte_order == m_host_arch.GetByteOrder());
1066                     }
1067                 }
1068             }
1069         }
1070     }
1071     return m_qHostInfo_is_valid == eLazyBoolYes;
1072 }
1073 
1074 int
1075 GDBRemoteCommunicationClient::SendAttach
1076 (
1077     lldb::pid_t pid,
1078     StringExtractorGDBRemote& response
1079 )
1080 {
1081     if (pid != LLDB_INVALID_PROCESS_ID)
1082     {
1083         char packet[64];
1084         const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", pid);
1085         assert (packet_len < sizeof(packet));
1086         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1087         {
1088             if (response.IsErrorResponse())
1089                 return response.GetError();
1090             return 0;
1091         }
1092     }
1093     return -1;
1094 }
1095 
1096 const lldb_private::ArchSpec &
1097 GDBRemoteCommunicationClient::GetHostArchitecture ()
1098 {
1099     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1100         GetHostInfo ();
1101     return m_host_arch;
1102 }
1103 
1104 addr_t
1105 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1106 {
1107     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1108     {
1109         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1110         char packet[64];
1111         const int packet_len = ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
1112                                            permissions & lldb::ePermissionsReadable ? "r" : "",
1113                                            permissions & lldb::ePermissionsWritable ? "w" : "",
1114                                            permissions & lldb::ePermissionsExecutable ? "x" : "");
1115         assert (packet_len < sizeof(packet));
1116         StringExtractorGDBRemote response;
1117         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1118         {
1119             if (!response.IsErrorResponse())
1120                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1121         }
1122         else
1123         {
1124             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1125         }
1126     }
1127     return LLDB_INVALID_ADDRESS;
1128 }
1129 
1130 bool
1131 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1132 {
1133     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1134     {
1135         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1136         char packet[64];
1137         const int packet_len = ::snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
1138         assert (packet_len < sizeof(packet));
1139         StringExtractorGDBRemote response;
1140         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1141         {
1142             if (response.IsOKResponse())
1143                 return true;
1144         }
1145         else
1146         {
1147             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1148         }
1149     }
1150     return false;
1151 }
1152 
1153 bool
1154 GDBRemoteCommunicationClient::Detach ()
1155 {
1156     return SendPacket ("D", 1) > 0;
1157 }
1158 
1159 Error
1160 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1161                                                   lldb_private::MemoryRegionInfo &region_info)
1162 {
1163     Error error;
1164     region_info.Clear();
1165 
1166     if (m_supports_memory_region_info != eLazyBoolNo)
1167     {
1168         m_supports_memory_region_info = eLazyBoolYes;
1169         char packet[64];
1170         const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%llx", (uint64_t)addr);
1171         assert (packet_len < sizeof(packet));
1172         StringExtractorGDBRemote response;
1173         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1174         {
1175             std::string name;
1176             std::string value;
1177             addr_t addr_value;
1178             bool success = true;
1179             bool saw_permissions = false;
1180             while (success && response.GetNameColonValue(name, value))
1181             {
1182                 if (name.compare ("start") == 0)
1183                 {
1184                     addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1185                     if (success)
1186                         region_info.GetRange().SetRangeBase(addr_value);
1187                 }
1188                 else if (name.compare ("size") == 0)
1189                 {
1190                     addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1191                     if (success)
1192                         region_info.GetRange().SetByteSize (addr_value);
1193                 }
1194                 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1195                 {
1196                     saw_permissions = true;
1197                     if (region_info.GetRange().Contains (addr))
1198                     {
1199                         if (value.find('r') != std::string::npos)
1200                             region_info.SetReadable (MemoryRegionInfo::eYes);
1201                         else
1202                             region_info.SetReadable (MemoryRegionInfo::eNo);
1203 
1204                         if (value.find('w') != std::string::npos)
1205                             region_info.SetWritable (MemoryRegionInfo::eYes);
1206                         else
1207                             region_info.SetWritable (MemoryRegionInfo::eNo);
1208 
1209                         if (value.find('x') != std::string::npos)
1210                             region_info.SetExecutable (MemoryRegionInfo::eYes);
1211                         else
1212                             region_info.SetExecutable (MemoryRegionInfo::eNo);
1213                     }
1214                     else
1215                     {
1216                         // The reported region does not contain this address -- we're looking at an unmapped page
1217                         region_info.SetReadable (MemoryRegionInfo::eNo);
1218                         region_info.SetWritable (MemoryRegionInfo::eNo);
1219                         region_info.SetExecutable (MemoryRegionInfo::eNo);
1220                     }
1221                 }
1222                 else if (name.compare ("error") == 0)
1223                 {
1224                     StringExtractorGDBRemote name_extractor;
1225                     // Swap "value" over into "name_extractor"
1226                     name_extractor.GetStringRef().swap(value);
1227                     // Now convert the HEX bytes into a string value
1228                     name_extractor.GetHexByteString (value);
1229                     error.SetErrorString(value.c_str());
1230                 }
1231             }
1232 
1233             // We got a valid address range back but no permissions -- which means this is an unmapped page
1234             if (region_info.GetRange().IsValid() && saw_permissions == false)
1235             {
1236                 region_info.SetReadable (MemoryRegionInfo::eNo);
1237                 region_info.SetWritable (MemoryRegionInfo::eNo);
1238                 region_info.SetExecutable (MemoryRegionInfo::eNo);
1239             }
1240         }
1241         else
1242         {
1243             m_supports_memory_region_info = eLazyBoolNo;
1244         }
1245     }
1246 
1247     if (m_supports_memory_region_info == eLazyBoolNo)
1248     {
1249         error.SetErrorString("qMemoryRegionInfo is not supported");
1250     }
1251     if (error.Fail())
1252         region_info.Clear();
1253     return error;
1254 
1255 }
1256 
1257 
1258 int
1259 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1260 {
1261     if (path && path[0])
1262     {
1263         StreamString packet;
1264         packet.PutCString("QSetSTDIN:");
1265         packet.PutBytesAsRawHex8(path, strlen(path));
1266 
1267         StringExtractorGDBRemote response;
1268         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1269         {
1270             if (response.IsOKResponse())
1271                 return 0;
1272             uint8_t error = response.GetError();
1273             if (error)
1274                 return error;
1275         }
1276     }
1277     return -1;
1278 }
1279 
1280 int
1281 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1282 {
1283     if (path && path[0])
1284     {
1285         StreamString packet;
1286         packet.PutCString("QSetSTDOUT:");
1287         packet.PutBytesAsRawHex8(path, strlen(path));
1288 
1289         StringExtractorGDBRemote response;
1290         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1291         {
1292             if (response.IsOKResponse())
1293                 return 0;
1294             uint8_t error = response.GetError();
1295             if (error)
1296                 return error;
1297         }
1298     }
1299     return -1;
1300 }
1301 
1302 int
1303 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1304 {
1305     if (path && path[0])
1306     {
1307         StreamString packet;
1308         packet.PutCString("QSetSTDERR:");
1309         packet.PutBytesAsRawHex8(path, strlen(path));
1310 
1311         StringExtractorGDBRemote response;
1312         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1313         {
1314             if (response.IsOKResponse())
1315                 return 0;
1316             uint8_t error = response.GetError();
1317             if (error)
1318                 return error;
1319         }
1320     }
1321     return -1;
1322 }
1323 
1324 int
1325 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1326 {
1327     if (path && path[0])
1328     {
1329         StreamString packet;
1330         packet.PutCString("QSetWorkingDir:");
1331         packet.PutBytesAsRawHex8(path, strlen(path));
1332 
1333         StringExtractorGDBRemote response;
1334         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1335         {
1336             if (response.IsOKResponse())
1337                 return 0;
1338             uint8_t error = response.GetError();
1339             if (error)
1340                 return error;
1341         }
1342     }
1343     return -1;
1344 }
1345 
1346 int
1347 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1348 {
1349     char packet[32];
1350     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1351     assert (packet_len < sizeof(packet));
1352     StringExtractorGDBRemote response;
1353     if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1354     {
1355         if (response.IsOKResponse())
1356             return 0;
1357         uint8_t error = response.GetError();
1358         if (error)
1359             return error;
1360     }
1361     return -1;
1362 }
1363 
1364 bool
1365 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
1366 {
1367     if (response.IsNormalResponse())
1368     {
1369         std::string name;
1370         std::string value;
1371         StringExtractor extractor;
1372 
1373         while (response.GetNameColonValue(name, value))
1374         {
1375             if (name.compare("pid") == 0)
1376             {
1377                 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1378             }
1379             else if (name.compare("ppid") == 0)
1380             {
1381                 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1382             }
1383             else if (name.compare("uid") == 0)
1384             {
1385                 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1386             }
1387             else if (name.compare("euid") == 0)
1388             {
1389                 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1390             }
1391             else if (name.compare("gid") == 0)
1392             {
1393                 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1394             }
1395             else if (name.compare("egid") == 0)
1396             {
1397                 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1398             }
1399             else if (name.compare("triple") == 0)
1400             {
1401                 // The triple comes as ASCII hex bytes since it contains '-' chars
1402                 extractor.GetStringRef().swap(value);
1403                 extractor.SetFilePos(0);
1404                 extractor.GetHexByteString (value);
1405                 process_info.GetArchitecture ().SetTriple (value.c_str(), NULL);
1406             }
1407             else if (name.compare("name") == 0)
1408             {
1409                 StringExtractor extractor;
1410                 // The the process name from ASCII hex bytes since we can't
1411                 // control the characters in a process name
1412                 extractor.GetStringRef().swap(value);
1413                 extractor.SetFilePos(0);
1414                 extractor.GetHexByteString (value);
1415                 process_info.GetExecutableFile().SetFile (value.c_str(), false);
1416             }
1417         }
1418 
1419         if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1420             return true;
1421     }
1422     return false;
1423 }
1424 
1425 bool
1426 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1427 {
1428     process_info.Clear();
1429 
1430     if (m_supports_qProcessInfoPID)
1431     {
1432         char packet[32];
1433         const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%llu", pid);
1434         assert (packet_len < sizeof(packet));
1435         StringExtractorGDBRemote response;
1436         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1437         {
1438             return DecodeProcessInfoResponse (response, process_info);
1439         }
1440         else
1441         {
1442             m_supports_qProcessInfoPID = false;
1443             return false;
1444         }
1445     }
1446     return false;
1447 }
1448 
1449 uint32_t
1450 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1451                                              ProcessInstanceInfoList &process_infos)
1452 {
1453     process_infos.Clear();
1454 
1455     if (m_supports_qfProcessInfo)
1456     {
1457         StreamString packet;
1458         packet.PutCString ("qfProcessInfo");
1459         if (!match_info.MatchAllProcesses())
1460         {
1461             packet.PutChar (':');
1462             const char *name = match_info.GetProcessInfo().GetName();
1463             bool has_name_match = false;
1464             if (name && name[0])
1465             {
1466                 has_name_match = true;
1467                 NameMatchType name_match_type = match_info.GetNameMatchType();
1468                 switch (name_match_type)
1469                 {
1470                 case eNameMatchIgnore:
1471                     has_name_match = false;
1472                     break;
1473 
1474                 case eNameMatchEquals:
1475                     packet.PutCString ("name_match:equals;");
1476                     break;
1477 
1478                 case eNameMatchContains:
1479                     packet.PutCString ("name_match:contains;");
1480                     break;
1481 
1482                 case eNameMatchStartsWith:
1483                     packet.PutCString ("name_match:starts_with;");
1484                     break;
1485 
1486                 case eNameMatchEndsWith:
1487                     packet.PutCString ("name_match:ends_with;");
1488                     break;
1489 
1490                 case eNameMatchRegularExpression:
1491                     packet.PutCString ("name_match:regex;");
1492                     break;
1493                 }
1494                 if (has_name_match)
1495                 {
1496                     packet.PutCString ("name:");
1497                     packet.PutBytesAsRawHex8(name, ::strlen(name));
1498                     packet.PutChar (';');
1499                 }
1500             }
1501 
1502             if (match_info.GetProcessInfo().ProcessIDIsValid())
1503                 packet.Printf("pid:%llu;",match_info.GetProcessInfo().GetProcessID());
1504             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1505                 packet.Printf("parent_pid:%llu;",match_info.GetProcessInfo().GetParentProcessID());
1506             if (match_info.GetProcessInfo().UserIDIsValid())
1507                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1508             if (match_info.GetProcessInfo().GroupIDIsValid())
1509                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
1510             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1511                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1512             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1513                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1514             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1515                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1516             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1517             {
1518                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1519                 const llvm::Triple &triple = match_arch.GetTriple();
1520                 packet.PutCString("triple:");
1521                 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1522                 packet.PutChar (';');
1523             }
1524         }
1525         StringExtractorGDBRemote response;
1526         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1527         {
1528             do
1529             {
1530                 ProcessInstanceInfo process_info;
1531                 if (!DecodeProcessInfoResponse (response, process_info))
1532                     break;
1533                 process_infos.Append(process_info);
1534                 response.GetStringRef().clear();
1535                 response.SetFilePos(0);
1536             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1537         }
1538         else
1539         {
1540             m_supports_qfProcessInfo = false;
1541             return 0;
1542         }
1543     }
1544     return process_infos.GetSize();
1545 
1546 }
1547 
1548 bool
1549 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
1550 {
1551     if (m_supports_qUserName)
1552     {
1553         char packet[32];
1554         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
1555         assert (packet_len < sizeof(packet));
1556         StringExtractorGDBRemote response;
1557         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1558         {
1559             if (response.IsNormalResponse())
1560             {
1561                 // Make sure we parsed the right number of characters. The response is
1562                 // the hex encoded user name and should make up the entire packet.
1563                 // If there are any non-hex ASCII bytes, the length won't match below..
1564                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1565                     return true;
1566             }
1567         }
1568         else
1569         {
1570             m_supports_qUserName = false;
1571             return false;
1572         }
1573     }
1574     return false;
1575 
1576 }
1577 
1578 bool
1579 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
1580 {
1581     if (m_supports_qGroupName)
1582     {
1583         char packet[32];
1584         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
1585         assert (packet_len < sizeof(packet));
1586         StringExtractorGDBRemote response;
1587         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1588         {
1589             if (response.IsNormalResponse())
1590             {
1591                 // Make sure we parsed the right number of characters. The response is
1592                 // the hex encoded group name and should make up the entire packet.
1593                 // If there are any non-hex ASCII bytes, the length won't match below..
1594                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1595                     return true;
1596             }
1597         }
1598         else
1599         {
1600             m_supports_qGroupName = false;
1601             return false;
1602         }
1603     }
1604     return false;
1605 }
1606 
1607 void
1608 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
1609 {
1610     uint32_t i;
1611     TimeValue start_time, end_time;
1612     uint64_t total_time_nsec;
1613     float packets_per_second;
1614     if (SendSpeedTestPacket (0, 0))
1615     {
1616         for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
1617         {
1618             for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
1619             {
1620                 start_time = TimeValue::Now();
1621                 for (i=0; i<num_packets; ++i)
1622                 {
1623                     SendSpeedTestPacket (send_size, recv_size);
1624                 }
1625                 end_time = TimeValue::Now();
1626                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
1627                 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
1628                 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %llu.%9.9llu sec for %f packets/sec.\n",
1629                         num_packets,
1630                         send_size,
1631                         recv_size,
1632                         total_time_nsec / TimeValue::NanoSecPerSec,
1633                         total_time_nsec % TimeValue::NanoSecPerSec,
1634                         packets_per_second);
1635                 if (recv_size == 0)
1636                     recv_size = 32;
1637             }
1638             if (send_size == 0)
1639                 send_size = 32;
1640         }
1641     }
1642     else
1643     {
1644         start_time = TimeValue::Now();
1645         for (i=0; i<num_packets; ++i)
1646         {
1647             GetCurrentProcessID ();
1648         }
1649         end_time = TimeValue::Now();
1650         total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
1651         packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
1652         printf ("%u 'qC' packets packets in 0x%llu%9.9llu sec for %f packets/sec.\n",
1653                 num_packets,
1654                 total_time_nsec / TimeValue::NanoSecPerSec,
1655                 total_time_nsec % TimeValue::NanoSecPerSec,
1656                 packets_per_second);
1657     }
1658 }
1659 
1660 bool
1661 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
1662 {
1663     StreamString packet;
1664     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
1665     uint32_t bytes_left = send_size;
1666     while (bytes_left > 0)
1667     {
1668         if (bytes_left >= 26)
1669         {
1670             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
1671             bytes_left -= 26;
1672         }
1673         else
1674         {
1675             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
1676             bytes_left = 0;
1677         }
1678     }
1679 
1680     StringExtractorGDBRemote response;
1681     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
1682     return false;
1683 }
1684 
1685 uint16_t
1686 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
1687 {
1688     StringExtractorGDBRemote response;
1689     if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
1690     {
1691         std::string name;
1692         std::string value;
1693         uint16_t port = 0;
1694         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1695         while (response.GetNameColonValue(name, value))
1696         {
1697             if (name.size() == 4 && name.compare("port") == 0)
1698                 port = Args::StringToUInt32(value.c_str(), 0, 0);
1699             if (name.size() == 3 && name.compare("pid") == 0)
1700                 pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
1701         }
1702         return port;
1703     }
1704     return 0;
1705 }
1706 
1707 bool
1708 GDBRemoteCommunicationClient::SetCurrentThread (int tid)
1709 {
1710     if (m_curr_tid == tid)
1711         return true;
1712 
1713     char packet[32];
1714     int packet_len;
1715     if (tid <= 0)
1716         packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
1717     else
1718         packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1719     assert (packet_len + 1 < sizeof(packet));
1720     StringExtractorGDBRemote response;
1721     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1722     {
1723         if (response.IsOKResponse())
1724         {
1725             m_curr_tid = tid;
1726             return true;
1727         }
1728     }
1729     return false;
1730 }
1731 
1732 bool
1733 GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid)
1734 {
1735     if (m_curr_tid_run == tid)
1736         return true;
1737 
1738     char packet[32];
1739     int packet_len;
1740     if (tid <= 0)
1741         packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
1742     else
1743         packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
1744 
1745     assert (packet_len + 1 < sizeof(packet));
1746     StringExtractorGDBRemote response;
1747     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1748     {
1749         if (response.IsOKResponse())
1750         {
1751             m_curr_tid_run = tid;
1752             return true;
1753         }
1754     }
1755     return false;
1756 }
1757 
1758 bool
1759 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
1760 {
1761     if (SendPacketAndWaitForResponse("?", 1, response, false))
1762         return response.IsNormalResponse();
1763     return false;
1764 }
1765 
1766 bool
1767 GDBRemoteCommunicationClient::GetThreadStopInfo (uint32_t tid, StringExtractorGDBRemote &response)
1768 {
1769     if (m_supports_qThreadStopInfo)
1770     {
1771         char packet[256];
1772         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%x", tid);
1773         assert (packet_len < sizeof(packet));
1774         if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1775         {
1776             if (response.IsNormalResponse())
1777                 return true;
1778             else
1779                 return false;
1780         }
1781         else
1782         {
1783             m_supports_qThreadStopInfo = false;
1784         }
1785     }
1786 //    if (SetCurrentThread (tid))
1787 //        return GetStopReply (response);
1788     return false;
1789 }
1790 
1791 
1792 uint8_t
1793 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
1794 {
1795     switch (type)
1796     {
1797     case eBreakpointSoftware:   if (!m_supports_z0) return UINT8_MAX; break;
1798     case eBreakpointHardware:   if (!m_supports_z1) return UINT8_MAX; break;
1799     case eWatchpointWrite:      if (!m_supports_z2) return UINT8_MAX; break;
1800     case eWatchpointRead:       if (!m_supports_z3) return UINT8_MAX; break;
1801     case eWatchpointReadWrite:  if (!m_supports_z4) return UINT8_MAX; break;
1802     default:                    return UINT8_MAX;
1803     }
1804 
1805     char packet[64];
1806     const int packet_len = ::snprintf (packet,
1807                                        sizeof(packet),
1808                                        "%c%i,%llx,%x",
1809                                        insert ? 'Z' : 'z',
1810                                        type,
1811                                        addr,
1812                                        length);
1813 
1814     assert (packet_len + 1 < sizeof(packet));
1815     StringExtractorGDBRemote response;
1816     if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
1817     {
1818         if (response.IsOKResponse())
1819             return 0;
1820         else if (response.IsErrorResponse())
1821             return response.GetError();
1822     }
1823     else
1824     {
1825         switch (type)
1826         {
1827             case eBreakpointSoftware:   m_supports_z0 = false; break;
1828             case eBreakpointHardware:   m_supports_z1 = false; break;
1829             case eWatchpointWrite:      m_supports_z2 = false; break;
1830             case eWatchpointRead:       m_supports_z3 = false; break;
1831             case eWatchpointReadWrite:  m_supports_z4 = false; break;
1832             default:                    break;
1833         }
1834     }
1835 
1836     return UINT8_MAX;
1837 }
1838 
1839 size_t
1840 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
1841                                                    bool &sequence_mutex_unavailable)
1842 {
1843     Mutex::Locker locker;
1844     thread_ids.clear();
1845 
1846     if (GetSequenceMutex (locker))
1847     {
1848         sequence_mutex_unavailable = false;
1849         StringExtractorGDBRemote response;
1850 
1851         for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
1852              response.IsNormalResponse();
1853              SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
1854         {
1855             char ch = response.GetChar();
1856             if (ch == 'l')
1857                 break;
1858             if (ch == 'm')
1859             {
1860                 do
1861                 {
1862                     tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1863 
1864                     if (tid != LLDB_INVALID_THREAD_ID)
1865                     {
1866                         thread_ids.push_back (tid);
1867                     }
1868                     ch = response.GetChar();    // Skip the command separator
1869                 } while (ch == ',');            // Make sure we got a comma separator
1870             }
1871         }
1872     }
1873     else
1874     {
1875         LogSP log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
1876         if (log)
1877             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
1878         sequence_mutex_unavailable = true;
1879     }
1880     return thread_ids.size();
1881 }
1882 
1883 lldb::addr_t
1884 GDBRemoteCommunicationClient::GetShlibInfoAddr()
1885 {
1886     if (!IsRunning())
1887     {
1888         StringExtractorGDBRemote response;
1889         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
1890         {
1891             if (response.IsNormalResponse())
1892                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1893         }
1894     }
1895     return LLDB_INVALID_ADDRESS;
1896 }
1897 
1898