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