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