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