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