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 #include <sys/stat.h>
15 
16 // C++ Includes
17 #include <sstream>
18 
19 // Other libraries and framework includes
20 #include "llvm/ADT/Triple.h"
21 #include "lldb/Interpreter/Args.h"
22 #include "lldb/Core/ConnectionFileDescriptor.h"
23 #include "lldb/Core/Log.h"
24 #include "lldb/Core/State.h"
25 #include "lldb/Core/StreamGDBRemote.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Host/Endian.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/TimeValue.h"
30 
31 // Project includes
32 #include "Utility/StringExtractorGDBRemote.h"
33 #include "ProcessGDBRemote.h"
34 #include "ProcessGDBRemoteLog.h"
35 #include "lldb/Host/Config.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 #ifdef LLDB_DISABLE_POSIX
41 #define SIGSTOP 17
42 #endif
43 
44 //----------------------------------------------------------------------
45 // GDBRemoteCommunicationClient constructor
46 //----------------------------------------------------------------------
47 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
48     GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
49     m_supports_not_sending_acks (eLazyBoolCalculate),
50     m_supports_thread_suffix (eLazyBoolCalculate),
51     m_supports_threads_in_stop_reply (eLazyBoolCalculate),
52     m_supports_vCont_all (eLazyBoolCalculate),
53     m_supports_vCont_any (eLazyBoolCalculate),
54     m_supports_vCont_c (eLazyBoolCalculate),
55     m_supports_vCont_C (eLazyBoolCalculate),
56     m_supports_vCont_s (eLazyBoolCalculate),
57     m_supports_vCont_S (eLazyBoolCalculate),
58     m_qHostInfo_is_valid (eLazyBoolCalculate),
59     m_qProcessInfo_is_valid (eLazyBoolCalculate),
60     m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
61     m_supports_memory_region_info  (eLazyBoolCalculate),
62     m_supports_watchpoint_support_info  (eLazyBoolCalculate),
63     m_supports_detach_stay_stopped (eLazyBoolCalculate),
64     m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
65     m_attach_or_wait_reply(eLazyBoolCalculate),
66     m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
67     m_supports_p (eLazyBoolCalculate),
68     m_supports_QSaveRegisterState (eLazyBoolCalculate),
69     m_supports_qProcessInfoPID (true),
70     m_supports_qfProcessInfo (true),
71     m_supports_qUserName (true),
72     m_supports_qGroupName (true),
73     m_supports_qThreadStopInfo (true),
74     m_supports_z0 (true),
75     m_supports_z1 (true),
76     m_supports_z2 (true),
77     m_supports_z3 (true),
78     m_supports_z4 (true),
79     m_supports_QEnvironment (true),
80     m_supports_QEnvironmentHexEncoded (true),
81     m_curr_tid (LLDB_INVALID_THREAD_ID),
82     m_curr_tid_run (LLDB_INVALID_THREAD_ID),
83     m_num_supported_hardware_watchpoints (0),
84     m_async_mutex (Mutex::eMutexTypeRecursive),
85     m_async_packet_predicate (false),
86     m_async_packet (),
87     m_async_response (),
88     m_async_signal (-1),
89     m_thread_id_to_used_usec_map (),
90     m_host_arch(),
91     m_process_arch(),
92     m_os_version_major (UINT32_MAX),
93     m_os_version_minor (UINT32_MAX),
94     m_os_version_update (UINT32_MAX),
95     m_os_build (),
96     m_os_kernel (),
97     m_hostname (),
98     m_default_packet_timeout (0)
99 {
100 }
101 
102 //----------------------------------------------------------------------
103 // Destructor
104 //----------------------------------------------------------------------
105 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
106 {
107     if (IsConnected())
108         Disconnect();
109 }
110 
111 bool
112 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
113 {
114     ResetDiscoverableSettings();
115 
116     // Start the read thread after we send the handshake ack since if we
117     // fail to send the handshake ack, there is no reason to continue...
118     if (SendAck())
119     {
120         // The return value from QueryNoAckModeSupported() is true if the packet
121         // was sent and _any_ response (including UNIMPLEMENTED) was received),
122         // or false if no response was received. This quickly tells us if we have
123         // a live connection to a remote GDB server...
124         if (QueryNoAckModeSupported())
125         {
126             return true;
127         }
128         else
129         {
130             if (error_ptr)
131                 error_ptr->SetErrorString("failed to get reply to handshake packet");
132         }
133     }
134     else
135     {
136         if (error_ptr)
137             error_ptr->SetErrorString("failed to send the handshake ack");
138     }
139     return false;
140 }
141 
142 bool
143 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
144 {
145     if (m_supports_not_sending_acks == eLazyBoolCalculate)
146     {
147         m_send_acks = true;
148         m_supports_not_sending_acks = eLazyBoolNo;
149 
150         StringExtractorGDBRemote response;
151         if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
152         {
153             if (response.IsOKResponse())
154             {
155                 m_send_acks = false;
156                 m_supports_not_sending_acks = eLazyBoolYes;
157             }
158             return true;
159         }
160     }
161     return false;
162 }
163 
164 void
165 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
166 {
167     if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
168     {
169         m_supports_threads_in_stop_reply = eLazyBoolNo;
170 
171         StringExtractorGDBRemote response;
172         if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
173         {
174             if (response.IsOKResponse())
175                 m_supports_threads_in_stop_reply = eLazyBoolYes;
176         }
177     }
178 }
179 
180 bool
181 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
182 {
183     if (m_attach_or_wait_reply == eLazyBoolCalculate)
184     {
185         m_attach_or_wait_reply = eLazyBoolNo;
186 
187         StringExtractorGDBRemote response;
188         if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
189         {
190             if (response.IsOKResponse())
191                 m_attach_or_wait_reply = eLazyBoolYes;
192         }
193     }
194     if (m_attach_or_wait_reply == eLazyBoolYes)
195         return true;
196     else
197         return false;
198 }
199 
200 bool
201 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
202 {
203     if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
204     {
205         m_prepare_for_reg_writing_reply = eLazyBoolNo;
206 
207         StringExtractorGDBRemote response;
208         if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
209         {
210             if (response.IsOKResponse())
211                 m_prepare_for_reg_writing_reply = eLazyBoolYes;
212         }
213     }
214     if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
215         return true;
216     else
217         return false;
218 }
219 
220 
221 void
222 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
223 {
224     m_supports_not_sending_acks = eLazyBoolCalculate;
225     m_supports_thread_suffix = eLazyBoolCalculate;
226     m_supports_threads_in_stop_reply = eLazyBoolCalculate;
227     m_supports_vCont_c = eLazyBoolCalculate;
228     m_supports_vCont_C = eLazyBoolCalculate;
229     m_supports_vCont_s = eLazyBoolCalculate;
230     m_supports_vCont_S = eLazyBoolCalculate;
231     m_supports_p = eLazyBoolCalculate;
232     m_supports_QSaveRegisterState = eLazyBoolCalculate;
233     m_qHostInfo_is_valid = eLazyBoolCalculate;
234     m_qProcessInfo_is_valid = eLazyBoolCalculate;
235     m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
236     m_supports_memory_region_info = eLazyBoolCalculate;
237     m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
238     m_attach_or_wait_reply = eLazyBoolCalculate;
239 
240     m_supports_qProcessInfoPID = true;
241     m_supports_qfProcessInfo = true;
242     m_supports_qUserName = true;
243     m_supports_qGroupName = true;
244     m_supports_qThreadStopInfo = true;
245     m_supports_z0 = true;
246     m_supports_z1 = true;
247     m_supports_z2 = true;
248     m_supports_z3 = true;
249     m_supports_z4 = true;
250     m_supports_QEnvironment = true;
251     m_supports_QEnvironmentHexEncoded = true;
252     m_host_arch.Clear();
253     m_process_arch.Clear();
254 }
255 
256 
257 bool
258 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
259 {
260     if (m_supports_thread_suffix == eLazyBoolCalculate)
261     {
262         StringExtractorGDBRemote response;
263         m_supports_thread_suffix = eLazyBoolNo;
264         if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
265         {
266             if (response.IsOKResponse())
267                 m_supports_thread_suffix = eLazyBoolYes;
268         }
269     }
270     return m_supports_thread_suffix;
271 }
272 bool
273 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
274 {
275     if (m_supports_vCont_c == eLazyBoolCalculate)
276     {
277         StringExtractorGDBRemote response;
278         m_supports_vCont_any = eLazyBoolNo;
279         m_supports_vCont_all = eLazyBoolNo;
280         m_supports_vCont_c = eLazyBoolNo;
281         m_supports_vCont_C = eLazyBoolNo;
282         m_supports_vCont_s = eLazyBoolNo;
283         m_supports_vCont_S = eLazyBoolNo;
284         if (SendPacketAndWaitForResponse("vCont?", response, false))
285         {
286             const char *response_cstr = response.GetStringRef().c_str();
287             if (::strstr (response_cstr, ";c"))
288                 m_supports_vCont_c = eLazyBoolYes;
289 
290             if (::strstr (response_cstr, ";C"))
291                 m_supports_vCont_C = eLazyBoolYes;
292 
293             if (::strstr (response_cstr, ";s"))
294                 m_supports_vCont_s = eLazyBoolYes;
295 
296             if (::strstr (response_cstr, ";S"))
297                 m_supports_vCont_S = eLazyBoolYes;
298 
299             if (m_supports_vCont_c == eLazyBoolYes &&
300                 m_supports_vCont_C == eLazyBoolYes &&
301                 m_supports_vCont_s == eLazyBoolYes &&
302                 m_supports_vCont_S == eLazyBoolYes)
303             {
304                 m_supports_vCont_all = eLazyBoolYes;
305             }
306 
307             if (m_supports_vCont_c == eLazyBoolYes ||
308                 m_supports_vCont_C == eLazyBoolYes ||
309                 m_supports_vCont_s == eLazyBoolYes ||
310                 m_supports_vCont_S == eLazyBoolYes)
311             {
312                 m_supports_vCont_any = eLazyBoolYes;
313             }
314         }
315     }
316 
317     switch (flavor)
318     {
319     case 'a': return m_supports_vCont_any;
320     case 'A': return m_supports_vCont_all;
321     case 'c': return m_supports_vCont_c;
322     case 'C': return m_supports_vCont_C;
323     case 's': return m_supports_vCont_s;
324     case 'S': return m_supports_vCont_S;
325     default: break;
326     }
327     return false;
328 }
329 
330 // Check if the target supports 'p' packet. It sends out a 'p'
331 // packet and checks the response. A normal packet will tell us
332 // that support is available.
333 //
334 // Takes a valid thread ID because p needs to apply to a thread.
335 bool
336 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
337 {
338     if (m_supports_p == eLazyBoolCalculate)
339     {
340         StringExtractorGDBRemote response;
341         m_supports_p = eLazyBoolNo;
342         char packet[256];
343         if (GetThreadSuffixSupported())
344             snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
345         else
346             snprintf(packet, sizeof(packet), "p0");
347 
348         if (SendPacketAndWaitForResponse(packet, response, false))
349         {
350             if (response.IsNormalResponse())
351                 m_supports_p = eLazyBoolYes;
352         }
353     }
354     return m_supports_p;
355 }
356 
357 size_t
358 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
359 (
360     const char *payload,
361     StringExtractorGDBRemote &response,
362     bool send_async
363 )
364 {
365     return SendPacketAndWaitForResponse (payload,
366                                          ::strlen (payload),
367                                          response,
368                                          send_async);
369 }
370 
371 size_t
372 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
373 (
374     const char *payload,
375     size_t payload_length,
376     StringExtractorGDBRemote &response,
377     bool send_async
378 )
379 {
380     Mutex::Locker locker;
381     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
382     size_t response_len = 0;
383     if (GetSequenceMutex (locker))
384     {
385         if (SendPacketNoLock (payload, payload_length))
386            response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
387         else
388         {
389             if (log)
390                 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
391         }
392     }
393     else
394     {
395         if (send_async)
396         {
397             if (IsRunning())
398             {
399                 Mutex::Locker async_locker (m_async_mutex);
400                 m_async_packet.assign(payload, payload_length);
401                 m_async_packet_predicate.SetValue (true, eBroadcastNever);
402 
403                 if (log)
404                     log->Printf ("async: async packet = %s", m_async_packet.c_str());
405 
406                 bool timed_out = false;
407                 if (SendInterrupt(locker, 2, timed_out))
408                 {
409                     if (m_interrupt_sent)
410                     {
411                         m_interrupt_sent = false;
412                         TimeValue timeout_time;
413                         timeout_time = TimeValue::Now();
414                         timeout_time.OffsetWithSeconds (m_packet_timeout);
415 
416                         if (log)
417                             log->Printf ("async: sent interrupt");
418 
419                         if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
420                         {
421                             if (log)
422                                 log->Printf ("async: got response");
423 
424                             // Swap the response buffer to avoid malloc and string copy
425                             response.GetStringRef().swap (m_async_response.GetStringRef());
426                             response_len = response.GetStringRef().size();
427                         }
428                         else
429                         {
430                             if (log)
431                                 log->Printf ("async: timed out waiting for response");
432                         }
433 
434                         // Make sure we wait until the continue packet has been sent again...
435                         if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
436                         {
437                             if (log)
438                             {
439                                 if (timed_out)
440                                     log->Printf ("async: timed out waiting for process to resume, but process was resumed");
441                                 else
442                                     log->Printf ("async: async packet sent");
443                             }
444                         }
445                         else
446                         {
447                             if (log)
448                                 log->Printf ("async: timed out waiting for process to resume");
449                         }
450                     }
451                     else
452                     {
453                         // We had a racy condition where we went to send the interrupt
454                         // yet we were able to get the lock, so the process must have
455                         // just stopped?
456                         if (log)
457                             log->Printf ("async: got lock without sending interrupt");
458                         // Send the packet normally since we got the lock
459                         if (SendPacketNoLock (payload, payload_length))
460                             response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
461                         else
462                         {
463                             if (log)
464                                 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
465                         }
466                     }
467                 }
468                 else
469                 {
470                     if (log)
471                         log->Printf ("async: failed to interrupt");
472                 }
473             }
474             else
475             {
476                 if (log)
477                     log->Printf ("async: not running, async is ignored");
478             }
479         }
480         else
481         {
482             if (log)
483                 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
484         }
485     }
486     if (response_len == 0)
487     {
488         if (log)
489             log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
490     }
491     return response_len;
492 }
493 
494 static const char *end_delimiter = "--end--;";
495 static const int end_delimiter_len = 8;
496 
497 std::string
498 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
499 (   ProcessGDBRemote *process,
500     StringExtractorGDBRemote& profileDataExtractor
501 )
502 {
503     std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
504     std::stringstream final_output;
505     std::string name, value;
506 
507     // Going to assuming thread_used_usec comes first, else bail out.
508     while (profileDataExtractor.GetNameColonValue(name, value))
509     {
510         if (name.compare("thread_used_id") == 0)
511         {
512             StringExtractor threadIDHexExtractor(value.c_str());
513             uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
514 
515             bool has_used_usec = false;
516             uint32_t curr_used_usec = 0;
517             std::string usec_name, usec_value;
518             uint32_t input_file_pos = profileDataExtractor.GetFilePos();
519             if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
520             {
521                 if (usec_name.compare("thread_used_usec") == 0)
522                 {
523                     has_used_usec = true;
524                     curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
525                 }
526                 else
527                 {
528                     // We didn't find what we want, it is probably
529                     // an older version. Bail out.
530                     profileDataExtractor.SetFilePos(input_file_pos);
531                 }
532             }
533 
534             if (has_used_usec)
535             {
536                 uint32_t prev_used_usec = 0;
537                 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
538                 if (iterator != m_thread_id_to_used_usec_map.end())
539                 {
540                     prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
541                 }
542 
543                 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
544                 // A good first time record is one that runs for at least 0.25 sec
545                 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
546                 bool good_subsequent_time = (prev_used_usec > 0) &&
547                     ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
548 
549                 if (good_first_time || good_subsequent_time)
550                 {
551                     // We try to avoid doing too many index id reservation,
552                     // resulting in fast increase of index ids.
553 
554                     final_output << name << ":";
555                     int32_t index_id = process->AssignIndexIDToThread(thread_id);
556                     final_output << index_id << ";";
557 
558                     final_output << usec_name << ":" << usec_value << ";";
559                 }
560                 else
561                 {
562                     // Skip past 'thread_used_name'.
563                     std::string local_name, local_value;
564                     profileDataExtractor.GetNameColonValue(local_name, local_value);
565                 }
566 
567                 // Store current time as previous time so that they can be compared later.
568                 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
569             }
570             else
571             {
572                 // Bail out and use old string.
573                 final_output << name << ":" << value << ";";
574             }
575         }
576         else
577         {
578             final_output << name << ":" << value << ";";
579         }
580     }
581     final_output << end_delimiter;
582     m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
583 
584     return final_output.str();
585 }
586 
587 StateType
588 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
589 (
590     ProcessGDBRemote *process,
591     const char *payload,
592     size_t packet_length,
593     StringExtractorGDBRemote &response
594 )
595 {
596     m_curr_tid = LLDB_INVALID_THREAD_ID;
597     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
598     if (log)
599         log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
600 
601     Mutex::Locker locker(m_sequence_mutex);
602     StateType state = eStateRunning;
603 
604     BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
605     m_public_is_running.SetValue (true, eBroadcastNever);
606     // Set the starting continue packet into "continue_packet". This packet
607     // may change if we are interrupted and we continue after an async packet...
608     std::string continue_packet(payload, packet_length);
609 
610     bool got_async_packet = false;
611 
612     while (state == eStateRunning)
613     {
614         if (!got_async_packet)
615         {
616             if (log)
617                 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
618             if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
619                 state = eStateInvalid;
620 
621             m_private_is_running.SetValue (true, eBroadcastAlways);
622         }
623 
624         got_async_packet = false;
625 
626         if (log)
627             log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
628 
629         if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
630         {
631             if (response.Empty())
632                 state = eStateInvalid;
633             else
634             {
635                 const char stop_type = response.GetChar();
636                 if (log)
637                     log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
638                 switch (stop_type)
639                 {
640                 case 'T':
641                 case 'S':
642                     {
643                         if (process->GetStopID() == 0)
644                         {
645                             if (process->GetID() == LLDB_INVALID_PROCESS_ID)
646                             {
647                                 lldb::pid_t pid = GetCurrentProcessID ();
648                                 if (pid != LLDB_INVALID_PROCESS_ID)
649                                     process->SetID (pid);
650                             }
651                             process->BuildDynamicRegisterInfo (true);
652                         }
653 
654                         // Privately notify any internal threads that we have stopped
655                         // in case we wanted to interrupt our process, yet we might
656                         // send a packet and continue without returning control to the
657                         // user.
658                         m_private_is_running.SetValue (false, eBroadcastAlways);
659 
660                         const uint8_t signo = response.GetHexU8 (UINT8_MAX);
661 
662                         bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
663                         if (continue_after_async || m_interrupt_sent)
664                         {
665                             // We sent an interrupt packet to stop the inferior process
666                             // for an async signal or to send an async packet while running
667                             // but we might have been single stepping and received the
668                             // stop packet for the step instead of for the interrupt packet.
669                             // Typically when an interrupt is sent a SIGINT or SIGSTOP
670                             // is used, so if we get anything else, we need to try and
671                             // get another stop reply packet that may have been sent
672                             // due to sending the interrupt when the target is stopped
673                             // which will just re-send a copy of the last stop reply
674                             // packet. If we don't do this, then the reply for our
675                             // async packet will be the repeat stop reply packet and cause
676                             // a lot of trouble for us!
677                             if (signo != SIGINT && signo != SIGSTOP)
678                             {
679                                 continue_after_async = false;
680 
681                                 // We didn't get a a SIGINT or SIGSTOP, so try for a
682                                 // very brief time (1 ms) to get another stop reply
683                                 // packet to make sure it doesn't get in the way
684                                 StringExtractorGDBRemote extra_stop_reply_packet;
685                                 uint32_t timeout_usec = 1000;
686                                 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
687                                 {
688                                     switch (extra_stop_reply_packet.GetChar())
689                                     {
690                                     case 'T':
691                                     case 'S':
692                                         // We did get an extra stop reply, which means
693                                         // our interrupt didn't stop the target so we
694                                         // shouldn't continue after the async signal
695                                         // or packet is sent...
696                                         continue_after_async = false;
697                                         break;
698                                     }
699                                 }
700                             }
701                         }
702 
703                         if (m_async_signal != -1)
704                         {
705                             if (log)
706                                 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
707 
708                             // Save off the async signal we are supposed to send
709                             const int async_signal = m_async_signal;
710                             // Clear the async signal member so we don't end up
711                             // sending the signal multiple times...
712                             m_async_signal = -1;
713                             // Check which signal we stopped with
714                             if (signo == async_signal)
715                             {
716                                 if (log)
717                                     log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
718 
719                                 // We already stopped with a signal that we wanted
720                                 // to stop with, so we are done
721                             }
722                             else
723                             {
724                                 // We stopped with a different signal that the one
725                                 // we wanted to stop with, so now we must resume
726                                 // with the signal we want
727                                 char signal_packet[32];
728                                 int signal_packet_len = 0;
729                                 signal_packet_len = ::snprintf (signal_packet,
730                                                                 sizeof (signal_packet),
731                                                                 "C%2.2x",
732                                                                 async_signal);
733 
734                                 if (log)
735                                     log->Printf ("async: stopped with signal %s, resume with %s",
736                                                        Host::GetSignalAsCString (signo),
737                                                        Host::GetSignalAsCString (async_signal));
738 
739                                 // Set the continue packet to resume even if the
740                                 // interrupt didn't cause our stop (ignore continue_after_async)
741                                 continue_packet.assign(signal_packet, signal_packet_len);
742                                 continue;
743                             }
744                         }
745                         else if (m_async_packet_predicate.GetValue())
746                         {
747                             Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
748 
749                             // We are supposed to send an asynchronous packet while
750                             // we are running.
751                             m_async_response.Clear();
752                             if (m_async_packet.empty())
753                             {
754                                 if (packet_log)
755                                     packet_log->Printf ("async: error: empty async packet");
756 
757                             }
758                             else
759                             {
760                                 if (packet_log)
761                                     packet_log->Printf ("async: sending packet");
762 
763                                 SendPacketAndWaitForResponse (&m_async_packet[0],
764                                                               m_async_packet.size(),
765                                                               m_async_response,
766                                                               false);
767                             }
768                             // Let the other thread that was trying to send the async
769                             // packet know that the packet has been sent and response is
770                             // ready...
771                             m_async_packet_predicate.SetValue(false, eBroadcastAlways);
772 
773                             if (packet_log)
774                                 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
775 
776                             // Set the continue packet to resume if our interrupt
777                             // for the async packet did cause the stop
778                             if (continue_after_async)
779                             {
780                                 // Reverting this for now as it is causing deadlocks
781                                 // in programs (<rdar://problem/11529853>). In the future
782                                 // we should check our thread list and "do the right thing"
783                                 // for new threads that show up while we stop and run async
784                                 // packets. Setting the packet to 'c' to continue all threads
785                                 // is the right thing to do 99.99% of the time because if a
786                                 // thread was single stepping, and we sent an interrupt, we
787                                 // will notice above that we didn't stop due to an interrupt
788                                 // but stopped due to stepping and we would _not_ continue.
789                                 continue_packet.assign (1, 'c');
790                                 continue;
791                             }
792                         }
793                         // Stop with signal and thread info
794                         state = eStateStopped;
795                     }
796                     break;
797 
798                 case 'W':
799                 case 'X':
800                     // process exited
801                     state = eStateExited;
802                     break;
803 
804                 case 'O':
805                     // STDOUT
806                     {
807                         got_async_packet = true;
808                         std::string inferior_stdout;
809                         inferior_stdout.reserve(response.GetBytesLeft () / 2);
810                         char ch;
811                         while ((ch = response.GetHexU8()) != '\0')
812                             inferior_stdout.append(1, ch);
813                         process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
814                     }
815                     break;
816 
817                 case 'A':
818                     // Async miscellaneous reply. Right now, only profile data is coming through this channel.
819                     {
820                         got_async_packet = true;
821                         std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
822                         if (m_partial_profile_data.length() > 0)
823                         {
824                             m_partial_profile_data.append(input);
825                             input = m_partial_profile_data;
826                             m_partial_profile_data.clear();
827                         }
828 
829                         size_t found, pos = 0, len = input.length();
830                         while ((found = input.find(end_delimiter, pos)) != std::string::npos)
831                         {
832                             StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
833                             std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
834                             process->BroadcastAsyncProfileData (profile_data);
835 
836                             pos = found + end_delimiter_len;
837                         }
838 
839                         if (pos < len)
840                         {
841                             // Last incomplete chunk.
842                             m_partial_profile_data = input.substr(pos);
843                         }
844                     }
845                     break;
846 
847                 case 'E':
848                     // ERROR
849                     state = eStateInvalid;
850                     break;
851 
852                 default:
853                     if (log)
854                         log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
855                     state = eStateInvalid;
856                     break;
857                 }
858             }
859         }
860         else
861         {
862             if (log)
863                 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
864             state = eStateInvalid;
865         }
866     }
867     if (log)
868         log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
869     response.SetFilePos(0);
870     m_private_is_running.SetValue (false, eBroadcastAlways);
871     m_public_is_running.SetValue (false, eBroadcastAlways);
872     return state;
873 }
874 
875 bool
876 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
877 {
878     Mutex::Locker async_locker (m_async_mutex);
879     m_async_signal = signo;
880     bool timed_out = false;
881     Mutex::Locker locker;
882     if (SendInterrupt (locker, 1, timed_out))
883         return true;
884     m_async_signal = -1;
885     return false;
886 }
887 
888 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
889 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
890 // (the expected result), then it will send the halt packet. If it does succeed
891 // then the caller that requested the interrupt will want to keep the sequence
892 // locked down so that no one else can send packets while the caller has control.
893 // This function usually gets called when we are running and need to stop the
894 // target. It can also be used when we are running and and we need to do something
895 // else (like read/write memory), so we need to interrupt the running process
896 // (gdb remote protocol requires this), and do what we need to do, then resume.
897 
898 bool
899 GDBRemoteCommunicationClient::SendInterrupt
900 (
901     Mutex::Locker& locker,
902     uint32_t seconds_to_wait_for_stop,
903     bool &timed_out
904 )
905 {
906     timed_out = false;
907     Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
908 
909     if (IsRunning())
910     {
911         // Only send an interrupt if our debugserver is running...
912         if (GetSequenceMutex (locker))
913         {
914             if (log)
915                 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
916         }
917         else
918         {
919             // Someone has the mutex locked waiting for a response or for the
920             // inferior to stop, so send the interrupt on the down low...
921             char ctrl_c = '\x03';
922             ConnectionStatus status = eConnectionStatusSuccess;
923             size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
924             if (log)
925                 log->PutCString("send packet: \\x03");
926             if (bytes_written > 0)
927             {
928                 m_interrupt_sent = true;
929                 if (seconds_to_wait_for_stop)
930                 {
931                     TimeValue timeout;
932                     if (seconds_to_wait_for_stop)
933                     {
934                         timeout = TimeValue::Now();
935                         timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
936                     }
937                     if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
938                     {
939                         if (log)
940                             log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
941                         return true;
942                     }
943                     else
944                     {
945                         if (log)
946                             log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
947                     }
948                 }
949                 else
950                 {
951                     if (log)
952                         log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
953                     return true;
954                 }
955             }
956             else
957             {
958                 if (log)
959                     log->Printf ("SendInterrupt () - failed to write interrupt");
960             }
961             return false;
962         }
963     }
964     else
965     {
966         if (log)
967             log->Printf ("SendInterrupt () - not running");
968     }
969     return true;
970 }
971 
972 lldb::pid_t
973 GDBRemoteCommunicationClient::GetCurrentProcessID ()
974 {
975     StringExtractorGDBRemote response;
976     if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
977     {
978         if (response.GetChar() == 'Q')
979             if (response.GetChar() == 'C')
980                 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
981     }
982     return LLDB_INVALID_PROCESS_ID;
983 }
984 
985 bool
986 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
987 {
988     error_str.clear();
989     StringExtractorGDBRemote response;
990     if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
991     {
992         if (response.IsOKResponse())
993             return true;
994         if (response.GetChar() == 'E')
995         {
996             // A string the describes what failed when launching...
997             error_str = response.GetStringRef().substr(1);
998         }
999         else
1000         {
1001             error_str.assign ("unknown error occurred launching process");
1002         }
1003     }
1004     else
1005     {
1006         error_str.assign ("timed out waiting for app to launch");
1007     }
1008     return false;
1009 }
1010 
1011 int
1012 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
1013 {
1014     // Since we don't get the send argv0 separate from the executable path, we need to
1015     // make sure to use the actual exectuable path found in the launch_info...
1016     std::vector<const char *> argv;
1017     FileSpec exe_file = launch_info.GetExecutableFile();
1018     std::string exe_path;
1019     const char *arg = NULL;
1020     const Args &launch_args = launch_info.GetArguments();
1021     if (exe_file)
1022         exe_path = exe_file.GetPath();
1023     else
1024     {
1025         arg = launch_args.GetArgumentAtIndex(0);
1026         if (arg)
1027             exe_path = arg;
1028     }
1029     if (!exe_path.empty())
1030     {
1031         argv.push_back(exe_path.c_str());
1032         for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1033         {
1034             if (arg)
1035                 argv.push_back(arg);
1036         }
1037     }
1038     if (!argv.empty())
1039     {
1040         StreamString packet;
1041         packet.PutChar('A');
1042         for (size_t i = 0, n = argv.size(); i < n; ++i)
1043         {
1044             arg = argv[i];
1045             const int arg_len = strlen(arg);
1046             if (i > 0)
1047                 packet.PutChar(',');
1048             packet.Printf("%i,%i,", arg_len * 2, (int)i);
1049             packet.PutBytesAsRawHex8 (arg, arg_len);
1050         }
1051 
1052         StringExtractorGDBRemote response;
1053         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1054         {
1055             if (response.IsOKResponse())
1056                 return 0;
1057             uint8_t error = response.GetError();
1058             if (error)
1059                 return error;
1060         }
1061     }
1062     return -1;
1063 }
1064 
1065 int
1066 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1067 {
1068     if (name_equal_value && name_equal_value[0])
1069     {
1070         StreamString packet;
1071         bool send_hex_encoding = false;
1072         for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
1073         {
1074             if (isprint(*p))
1075             {
1076                 switch (*p)
1077                 {
1078                     case '$':
1079                     case '#':
1080                         send_hex_encoding = true;
1081                         break;
1082                     default:
1083                         break;
1084                 }
1085             }
1086             else
1087             {
1088                 // We have non printable characters, lets hex encode this...
1089                 send_hex_encoding = true;
1090             }
1091         }
1092 
1093         StringExtractorGDBRemote response;
1094         if (send_hex_encoding)
1095         {
1096             if (m_supports_QEnvironmentHexEncoded)
1097             {
1098                 packet.PutCString("QEnvironmentHexEncoded:");
1099                 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1100                 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1101                 {
1102                     if (response.IsOKResponse())
1103                         return 0;
1104                     uint8_t error = response.GetError();
1105                     if (error)
1106                         return error;
1107                     if (response.IsUnsupportedResponse())
1108                         m_supports_QEnvironmentHexEncoded = false;
1109                 }
1110             }
1111 
1112         }
1113         else if (m_supports_QEnvironment)
1114         {
1115             packet.Printf("QEnvironment:%s", name_equal_value);
1116             if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1117             {
1118                 if (response.IsOKResponse())
1119                     return 0;
1120                 uint8_t error = response.GetError();
1121                 if (error)
1122                     return error;
1123                 if (response.IsUnsupportedResponse())
1124                     m_supports_QEnvironment = false;
1125             }
1126         }
1127     }
1128     return -1;
1129 }
1130 
1131 int
1132 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1133 {
1134     if (arch && arch[0])
1135     {
1136         StreamString packet;
1137         packet.Printf("QLaunchArch:%s", arch);
1138         StringExtractorGDBRemote response;
1139         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1140         {
1141             if (response.IsOKResponse())
1142                 return 0;
1143             uint8_t error = response.GetError();
1144             if (error)
1145                 return error;
1146         }
1147     }
1148     return -1;
1149 }
1150 
1151 bool
1152 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1153                                             uint32_t &minor,
1154                                             uint32_t &update)
1155 {
1156     if (GetHostInfo ())
1157     {
1158         if (m_os_version_major != UINT32_MAX)
1159         {
1160             major = m_os_version_major;
1161             minor = m_os_version_minor;
1162             update = m_os_version_update;
1163             return true;
1164         }
1165     }
1166     return false;
1167 }
1168 
1169 bool
1170 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1171 {
1172     if (GetHostInfo ())
1173     {
1174         if (!m_os_build.empty())
1175         {
1176             s = m_os_build;
1177             return true;
1178         }
1179     }
1180     s.clear();
1181     return false;
1182 }
1183 
1184 
1185 bool
1186 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1187 {
1188     if (GetHostInfo ())
1189     {
1190         if (!m_os_kernel.empty())
1191         {
1192             s = m_os_kernel;
1193             return true;
1194         }
1195     }
1196     s.clear();
1197     return false;
1198 }
1199 
1200 bool
1201 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1202 {
1203     if (GetHostInfo ())
1204     {
1205         if (!m_hostname.empty())
1206         {
1207             s = m_hostname;
1208             return true;
1209         }
1210     }
1211     s.clear();
1212     return false;
1213 }
1214 
1215 ArchSpec
1216 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1217 {
1218     if (GetHostInfo ())
1219         return m_host_arch;
1220     return ArchSpec();
1221 }
1222 
1223 const lldb_private::ArchSpec &
1224 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1225 {
1226     if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1227         GetCurrentProcessInfo ();
1228     return m_process_arch;
1229 }
1230 
1231 
1232 bool
1233 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1234 {
1235     if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1236     {
1237         m_qHostInfo_is_valid = eLazyBoolNo;
1238         StringExtractorGDBRemote response;
1239         if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1240         {
1241             if (response.IsNormalResponse())
1242             {
1243                 std::string name;
1244                 std::string value;
1245                 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1246                 uint32_t sub = 0;
1247                 std::string arch_name;
1248                 std::string os_name;
1249                 std::string vendor_name;
1250                 std::string triple;
1251                 uint32_t pointer_byte_size = 0;
1252                 StringExtractor extractor;
1253                 ByteOrder byte_order = eByteOrderInvalid;
1254                 uint32_t num_keys_decoded = 0;
1255                 while (response.GetNameColonValue(name, value))
1256                 {
1257                     if (name.compare("cputype") == 0)
1258                     {
1259                         // exception type in big endian hex
1260                         cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1261                         if (cpu != LLDB_INVALID_CPUTYPE)
1262                             ++num_keys_decoded;
1263                     }
1264                     else if (name.compare("cpusubtype") == 0)
1265                     {
1266                         // exception count in big endian hex
1267                         sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1268                         if (sub != 0)
1269                             ++num_keys_decoded;
1270                     }
1271                     else if (name.compare("arch") == 0)
1272                     {
1273                         arch_name.swap (value);
1274                         ++num_keys_decoded;
1275                     }
1276                     else if (name.compare("triple") == 0)
1277                     {
1278                         // The triple comes as ASCII hex bytes since it contains '-' chars
1279                         extractor.GetStringRef().swap(value);
1280                         extractor.SetFilePos(0);
1281                         extractor.GetHexByteString (triple);
1282                         ++num_keys_decoded;
1283                     }
1284                     else if (name.compare("os_build") == 0)
1285                     {
1286                         extractor.GetStringRef().swap(value);
1287                         extractor.SetFilePos(0);
1288                         extractor.GetHexByteString (m_os_build);
1289                         ++num_keys_decoded;
1290                     }
1291                     else if (name.compare("hostname") == 0)
1292                     {
1293                         extractor.GetStringRef().swap(value);
1294                         extractor.SetFilePos(0);
1295                         extractor.GetHexByteString (m_hostname);
1296                         ++num_keys_decoded;
1297                     }
1298                     else if (name.compare("os_kernel") == 0)
1299                     {
1300                         extractor.GetStringRef().swap(value);
1301                         extractor.SetFilePos(0);
1302                         extractor.GetHexByteString (m_os_kernel);
1303                         ++num_keys_decoded;
1304                     }
1305                     else if (name.compare("ostype") == 0)
1306                     {
1307                         os_name.swap (value);
1308                         ++num_keys_decoded;
1309                     }
1310                     else if (name.compare("vendor") == 0)
1311                     {
1312                         vendor_name.swap(value);
1313                         ++num_keys_decoded;
1314                     }
1315                     else if (name.compare("endian") == 0)
1316                     {
1317                         ++num_keys_decoded;
1318                         if (value.compare("little") == 0)
1319                             byte_order = eByteOrderLittle;
1320                         else if (value.compare("big") == 0)
1321                             byte_order = eByteOrderBig;
1322                         else if (value.compare("pdp") == 0)
1323                             byte_order = eByteOrderPDP;
1324                         else
1325                             --num_keys_decoded;
1326                     }
1327                     else if (name.compare("ptrsize") == 0)
1328                     {
1329                         pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1330                         if (pointer_byte_size != 0)
1331                             ++num_keys_decoded;
1332                     }
1333                     else if (name.compare("os_version") == 0)
1334                     {
1335                         Args::StringToVersion (value.c_str(),
1336                                                m_os_version_major,
1337                                                m_os_version_minor,
1338                                                m_os_version_update);
1339                         if (m_os_version_major != UINT32_MAX)
1340                             ++num_keys_decoded;
1341                     }
1342                     else if (name.compare("watchpoint_exceptions_received") == 0)
1343                     {
1344                         ++num_keys_decoded;
1345                         if (strcmp(value.c_str(),"before") == 0)
1346                             m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1347                         else if (strcmp(value.c_str(),"after") == 0)
1348                             m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1349                         else
1350                             --num_keys_decoded;
1351                     }
1352                     else if (name.compare("default_packet_timeout") == 0)
1353                     {
1354                         m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1355                         if (m_default_packet_timeout > 0)
1356                         {
1357                             SetPacketTimeout(m_default_packet_timeout);
1358                             ++num_keys_decoded;
1359                         }
1360                     }
1361 
1362                 }
1363 
1364                 if (num_keys_decoded > 0)
1365                     m_qHostInfo_is_valid = eLazyBoolYes;
1366 
1367                 if (triple.empty())
1368                 {
1369                     if (arch_name.empty())
1370                     {
1371                         if (cpu != LLDB_INVALID_CPUTYPE)
1372                         {
1373                             m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1374                             if (pointer_byte_size)
1375                             {
1376                                 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1377                             }
1378                             if (byte_order != eByteOrderInvalid)
1379                             {
1380                                 assert (byte_order == m_host_arch.GetByteOrder());
1381                             }
1382 
1383                             if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1384                             {
1385                                 switch (m_host_arch.GetMachine())
1386                                 {
1387                                 case llvm::Triple::arm:
1388                                 case llvm::Triple::thumb:
1389                                     os_name = "ios";
1390                                     break;
1391                                 default:
1392                                     os_name = "macosx";
1393                                     break;
1394                                 }
1395                             }
1396                             if (!vendor_name.empty())
1397                                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1398                             if (!os_name.empty())
1399                                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1400 
1401                         }
1402                     }
1403                     else
1404                     {
1405                         std::string triple;
1406                         triple += arch_name;
1407                         if (!vendor_name.empty() || !os_name.empty())
1408                         {
1409                             triple += '-';
1410                             if (vendor_name.empty())
1411                                 triple += "unknown";
1412                             else
1413                                 triple += vendor_name;
1414                             triple += '-';
1415                             if (os_name.empty())
1416                                 triple += "unknown";
1417                             else
1418                                 triple += os_name;
1419                         }
1420                         m_host_arch.SetTriple (triple.c_str());
1421 
1422                         llvm::Triple &host_triple = m_host_arch.GetTriple();
1423                         if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1424                         {
1425                             switch (m_host_arch.GetMachine())
1426                             {
1427                                 case llvm::Triple::arm:
1428                                 case llvm::Triple::thumb:
1429                                     host_triple.setOS(llvm::Triple::IOS);
1430                                     break;
1431                                 default:
1432                                     host_triple.setOS(llvm::Triple::MacOSX);
1433                                     break;
1434                             }
1435                         }
1436                         if (pointer_byte_size)
1437                         {
1438                             assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1439                         }
1440                         if (byte_order != eByteOrderInvalid)
1441                         {
1442                             assert (byte_order == m_host_arch.GetByteOrder());
1443                         }
1444 
1445                     }
1446                 }
1447                 else
1448                 {
1449                     m_host_arch.SetTriple (triple.c_str());
1450                     if (pointer_byte_size)
1451                     {
1452                         assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1453                     }
1454                     if (byte_order != eByteOrderInvalid)
1455                     {
1456                         assert (byte_order == m_host_arch.GetByteOrder());
1457                     }
1458                 }
1459             }
1460         }
1461     }
1462     return m_qHostInfo_is_valid == eLazyBoolYes;
1463 }
1464 
1465 int
1466 GDBRemoteCommunicationClient::SendAttach
1467 (
1468     lldb::pid_t pid,
1469     StringExtractorGDBRemote& response
1470 )
1471 {
1472     if (pid != LLDB_INVALID_PROCESS_ID)
1473     {
1474         char packet[64];
1475         const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1476         assert (packet_len < (int)sizeof(packet));
1477         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1478         {
1479             if (response.IsErrorResponse())
1480                 return response.GetError();
1481             return 0;
1482         }
1483     }
1484     return -1;
1485 }
1486 
1487 const lldb_private::ArchSpec &
1488 GDBRemoteCommunicationClient::GetHostArchitecture ()
1489 {
1490     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1491         GetHostInfo ();
1492     return m_host_arch;
1493 }
1494 
1495 uint32_t
1496 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1497 {
1498     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1499         GetHostInfo ();
1500     return m_default_packet_timeout;
1501 }
1502 
1503 addr_t
1504 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1505 {
1506     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1507     {
1508         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1509         char packet[64];
1510         const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1511                                            (uint64_t)size,
1512                                            permissions & lldb::ePermissionsReadable ? "r" : "",
1513                                            permissions & lldb::ePermissionsWritable ? "w" : "",
1514                                            permissions & lldb::ePermissionsExecutable ? "x" : "");
1515         assert (packet_len < (int)sizeof(packet));
1516         StringExtractorGDBRemote response;
1517         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1518         {
1519             if (!response.IsErrorResponse())
1520                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1521         }
1522         else
1523         {
1524             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1525         }
1526     }
1527     return LLDB_INVALID_ADDRESS;
1528 }
1529 
1530 bool
1531 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1532 {
1533     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1534     {
1535         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1536         char packet[64];
1537         const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1538         assert (packet_len < (int)sizeof(packet));
1539         StringExtractorGDBRemote response;
1540         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1541         {
1542             if (response.IsOKResponse())
1543                 return true;
1544         }
1545         else
1546         {
1547             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1548         }
1549     }
1550     return false;
1551 }
1552 
1553 Error
1554 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1555 {
1556     Error error;
1557 
1558     if (keep_stopped)
1559     {
1560         if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1561         {
1562             char packet[64];
1563             const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1564             assert (packet_len < (int)sizeof(packet));
1565             StringExtractorGDBRemote response;
1566             if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1567             {
1568                 m_supports_detach_stay_stopped = eLazyBoolYes;
1569             }
1570             else
1571             {
1572                 m_supports_detach_stay_stopped = eLazyBoolNo;
1573             }
1574         }
1575 
1576         if (m_supports_detach_stay_stopped == eLazyBoolNo)
1577         {
1578             error.SetErrorString("Stays stopped not supported by this target.");
1579             return error;
1580         }
1581         else
1582         {
1583             size_t num_sent = SendPacket ("D1", 2);
1584             if (num_sent == 0)
1585                 error.SetErrorString ("Sending extended disconnect packet failed.");
1586         }
1587     }
1588     else
1589     {
1590         size_t num_sent = SendPacket ("D", 1);
1591         if (num_sent == 0)
1592             error.SetErrorString ("Sending disconnect packet failed.");
1593     }
1594     return error;
1595 }
1596 
1597 Error
1598 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1599                                                   lldb_private::MemoryRegionInfo &region_info)
1600 {
1601     Error error;
1602     region_info.Clear();
1603 
1604     if (m_supports_memory_region_info != eLazyBoolNo)
1605     {
1606         m_supports_memory_region_info = eLazyBoolYes;
1607         char packet[64];
1608         const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1609         assert (packet_len < (int)sizeof(packet));
1610         StringExtractorGDBRemote response;
1611         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1612         {
1613             std::string name;
1614             std::string value;
1615             addr_t addr_value;
1616             bool success = true;
1617             bool saw_permissions = false;
1618             while (success && response.GetNameColonValue(name, value))
1619             {
1620                 if (name.compare ("start") == 0)
1621                 {
1622                     addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1623                     if (success)
1624                         region_info.GetRange().SetRangeBase(addr_value);
1625                 }
1626                 else if (name.compare ("size") == 0)
1627                 {
1628                     addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1629                     if (success)
1630                         region_info.GetRange().SetByteSize (addr_value);
1631                 }
1632                 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1633                 {
1634                     saw_permissions = true;
1635                     if (region_info.GetRange().Contains (addr))
1636                     {
1637                         if (value.find('r') != std::string::npos)
1638                             region_info.SetReadable (MemoryRegionInfo::eYes);
1639                         else
1640                             region_info.SetReadable (MemoryRegionInfo::eNo);
1641 
1642                         if (value.find('w') != std::string::npos)
1643                             region_info.SetWritable (MemoryRegionInfo::eYes);
1644                         else
1645                             region_info.SetWritable (MemoryRegionInfo::eNo);
1646 
1647                         if (value.find('x') != std::string::npos)
1648                             region_info.SetExecutable (MemoryRegionInfo::eYes);
1649                         else
1650                             region_info.SetExecutable (MemoryRegionInfo::eNo);
1651                     }
1652                     else
1653                     {
1654                         // The reported region does not contain this address -- we're looking at an unmapped page
1655                         region_info.SetReadable (MemoryRegionInfo::eNo);
1656                         region_info.SetWritable (MemoryRegionInfo::eNo);
1657                         region_info.SetExecutable (MemoryRegionInfo::eNo);
1658                     }
1659                 }
1660                 else if (name.compare ("error") == 0)
1661                 {
1662                     StringExtractorGDBRemote name_extractor;
1663                     // Swap "value" over into "name_extractor"
1664                     name_extractor.GetStringRef().swap(value);
1665                     // Now convert the HEX bytes into a string value
1666                     name_extractor.GetHexByteString (value);
1667                     error.SetErrorString(value.c_str());
1668                 }
1669             }
1670 
1671             // We got a valid address range back but no permissions -- which means this is an unmapped page
1672             if (region_info.GetRange().IsValid() && saw_permissions == false)
1673             {
1674                 region_info.SetReadable (MemoryRegionInfo::eNo);
1675                 region_info.SetWritable (MemoryRegionInfo::eNo);
1676                 region_info.SetExecutable (MemoryRegionInfo::eNo);
1677             }
1678         }
1679         else
1680         {
1681             m_supports_memory_region_info = eLazyBoolNo;
1682         }
1683     }
1684 
1685     if (m_supports_memory_region_info == eLazyBoolNo)
1686     {
1687         error.SetErrorString("qMemoryRegionInfo is not supported");
1688     }
1689     if (error.Fail())
1690         region_info.Clear();
1691     return error;
1692 
1693 }
1694 
1695 Error
1696 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1697 {
1698     Error error;
1699 
1700     if (m_supports_watchpoint_support_info == eLazyBoolYes)
1701     {
1702         num = m_num_supported_hardware_watchpoints;
1703         return error;
1704     }
1705 
1706     // Set num to 0 first.
1707     num = 0;
1708     if (m_supports_watchpoint_support_info != eLazyBoolNo)
1709     {
1710         char packet[64];
1711         const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1712         assert (packet_len < (int)sizeof(packet));
1713         StringExtractorGDBRemote response;
1714         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1715         {
1716             m_supports_watchpoint_support_info = eLazyBoolYes;
1717             std::string name;
1718             std::string value;
1719             while (response.GetNameColonValue(name, value))
1720             {
1721                 if (name.compare ("num") == 0)
1722                 {
1723                     num = Args::StringToUInt32(value.c_str(), 0, 0);
1724                     m_num_supported_hardware_watchpoints = num;
1725                 }
1726             }
1727         }
1728         else
1729         {
1730             m_supports_watchpoint_support_info = eLazyBoolNo;
1731         }
1732     }
1733 
1734     if (m_supports_watchpoint_support_info == eLazyBoolNo)
1735     {
1736         error.SetErrorString("qWatchpointSupportInfo is not supported");
1737     }
1738     return error;
1739 
1740 }
1741 
1742 lldb_private::Error
1743 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1744 {
1745     Error error(GetWatchpointSupportInfo(num));
1746     if (error.Success())
1747         error = GetWatchpointsTriggerAfterInstruction(after);
1748     return error;
1749 }
1750 
1751 lldb_private::Error
1752 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1753 {
1754     Error error;
1755 
1756     // we assume watchpoints will happen after running the relevant opcode
1757     // and we only want to override this behavior if we have explicitly
1758     // received a qHostInfo telling us otherwise
1759     if (m_qHostInfo_is_valid != eLazyBoolYes)
1760         after = true;
1761     else
1762         after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1763     return error;
1764 }
1765 
1766 int
1767 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1768 {
1769     if (path && path[0])
1770     {
1771         StreamString packet;
1772         packet.PutCString("QSetSTDIN:");
1773         packet.PutBytesAsRawHex8(path, strlen(path));
1774 
1775         StringExtractorGDBRemote response;
1776         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1777         {
1778             if (response.IsOKResponse())
1779                 return 0;
1780             uint8_t error = response.GetError();
1781             if (error)
1782                 return error;
1783         }
1784     }
1785     return -1;
1786 }
1787 
1788 int
1789 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1790 {
1791     if (path && path[0])
1792     {
1793         StreamString packet;
1794         packet.PutCString("QSetSTDOUT:");
1795         packet.PutBytesAsRawHex8(path, strlen(path));
1796 
1797         StringExtractorGDBRemote response;
1798         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1799         {
1800             if (response.IsOKResponse())
1801                 return 0;
1802             uint8_t error = response.GetError();
1803             if (error)
1804                 return error;
1805         }
1806     }
1807     return -1;
1808 }
1809 
1810 int
1811 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1812 {
1813     if (path && path[0])
1814     {
1815         StreamString packet;
1816         packet.PutCString("QSetSTDERR:");
1817         packet.PutBytesAsRawHex8(path, strlen(path));
1818 
1819         StringExtractorGDBRemote response;
1820         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1821         {
1822             if (response.IsOKResponse())
1823                 return 0;
1824             uint8_t error = response.GetError();
1825             if (error)
1826                 return error;
1827         }
1828     }
1829     return -1;
1830 }
1831 
1832 bool
1833 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
1834 {
1835     StringExtractorGDBRemote response;
1836     if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false))
1837     {
1838         if (response.IsUnsupportedResponse())
1839             return false;
1840         if (response.IsErrorResponse())
1841             return false;
1842         response.GetHexByteString (cwd);
1843         return !cwd.empty();
1844     }
1845     return false;
1846 }
1847 
1848 int
1849 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1850 {
1851     if (path && path[0])
1852     {
1853         StreamString packet;
1854         packet.PutCString("QSetWorkingDir:");
1855         packet.PutBytesAsRawHex8(path, strlen(path));
1856 
1857         StringExtractorGDBRemote response;
1858         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1859         {
1860             if (response.IsOKResponse())
1861                 return 0;
1862             uint8_t error = response.GetError();
1863             if (error)
1864                 return error;
1865         }
1866     }
1867     return -1;
1868 }
1869 
1870 int
1871 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1872 {
1873     char packet[32];
1874     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1875     assert (packet_len < (int)sizeof(packet));
1876     StringExtractorGDBRemote response;
1877     if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1878     {
1879         if (response.IsOKResponse())
1880             return 0;
1881         uint8_t error = response.GetError();
1882         if (error)
1883             return error;
1884     }
1885     return -1;
1886 }
1887 
1888 bool
1889 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
1890 {
1891     if (response.IsNormalResponse())
1892     {
1893         std::string name;
1894         std::string value;
1895         StringExtractor extractor;
1896 
1897         while (response.GetNameColonValue(name, value))
1898         {
1899             if (name.compare("pid") == 0)
1900             {
1901                 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1902             }
1903             else if (name.compare("ppid") == 0)
1904             {
1905                 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1906             }
1907             else if (name.compare("uid") == 0)
1908             {
1909                 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1910             }
1911             else if (name.compare("euid") == 0)
1912             {
1913                 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1914             }
1915             else if (name.compare("gid") == 0)
1916             {
1917                 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1918             }
1919             else if (name.compare("egid") == 0)
1920             {
1921                 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1922             }
1923             else if (name.compare("triple") == 0)
1924             {
1925                 // The triple comes as ASCII hex bytes since it contains '-' chars
1926                 extractor.GetStringRef().swap(value);
1927                 extractor.SetFilePos(0);
1928                 extractor.GetHexByteString (value);
1929                 process_info.GetArchitecture ().SetTriple (value.c_str());
1930             }
1931             else if (name.compare("name") == 0)
1932             {
1933                 StringExtractor extractor;
1934                 // The process name from ASCII hex bytes since we can't
1935                 // control the characters in a process name
1936                 extractor.GetStringRef().swap(value);
1937                 extractor.SetFilePos(0);
1938                 extractor.GetHexByteString (value);
1939                 process_info.GetExecutableFile().SetFile (value.c_str(), false);
1940             }
1941         }
1942 
1943         if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1944             return true;
1945     }
1946     return false;
1947 }
1948 
1949 bool
1950 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1951 {
1952     process_info.Clear();
1953 
1954     if (m_supports_qProcessInfoPID)
1955     {
1956         char packet[32];
1957         const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
1958         assert (packet_len < (int)sizeof(packet));
1959         StringExtractorGDBRemote response;
1960         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1961         {
1962             return DecodeProcessInfoResponse (response, process_info);
1963         }
1964         else
1965         {
1966             m_supports_qProcessInfoPID = false;
1967             return false;
1968         }
1969     }
1970     return false;
1971 }
1972 
1973 bool
1974 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1975 {
1976     if (m_qProcessInfo_is_valid == eLazyBoolYes)
1977         return true;
1978     if (m_qProcessInfo_is_valid == eLazyBoolNo)
1979         return false;
1980 
1981     GetHostInfo ();
1982 
1983     StringExtractorGDBRemote response;
1984     if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1985     {
1986         if (response.IsNormalResponse())
1987         {
1988             std::string name;
1989             std::string value;
1990             uint32_t cpu = LLDB_INVALID_CPUTYPE;
1991             uint32_t sub = 0;
1992             std::string arch_name;
1993             std::string os_name;
1994             std::string vendor_name;
1995             std::string triple;
1996             uint32_t pointer_byte_size = 0;
1997             StringExtractor extractor;
1998             ByteOrder byte_order = eByteOrderInvalid;
1999             uint32_t num_keys_decoded = 0;
2000             while (response.GetNameColonValue(name, value))
2001             {
2002                 if (name.compare("cputype") == 0)
2003                 {
2004                     cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2005                     if (cpu != LLDB_INVALID_CPUTYPE)
2006                         ++num_keys_decoded;
2007                 }
2008                 else if (name.compare("cpusubtype") == 0)
2009                 {
2010                     sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2011                     if (sub != 0)
2012                         ++num_keys_decoded;
2013                 }
2014                 else if (name.compare("ostype") == 0)
2015                 {
2016                     os_name.swap (value);
2017                     ++num_keys_decoded;
2018                 }
2019                 else if (name.compare("vendor") == 0)
2020                 {
2021                     vendor_name.swap(value);
2022                     ++num_keys_decoded;
2023                 }
2024                 else if (name.compare("endian") == 0)
2025                 {
2026                     ++num_keys_decoded;
2027                     if (value.compare("little") == 0)
2028                         byte_order = eByteOrderLittle;
2029                     else if (value.compare("big") == 0)
2030                         byte_order = eByteOrderBig;
2031                     else if (value.compare("pdp") == 0)
2032                         byte_order = eByteOrderPDP;
2033                     else
2034                         --num_keys_decoded;
2035                 }
2036                 else if (name.compare("ptrsize") == 0)
2037                 {
2038                     pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2039                     if (pointer_byte_size != 0)
2040                         ++num_keys_decoded;
2041                 }
2042             }
2043             if (num_keys_decoded > 0)
2044                 m_qProcessInfo_is_valid = eLazyBoolYes;
2045             if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2046             {
2047                 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2048                 if (pointer_byte_size)
2049                 {
2050                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2051                 }
2052                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2053                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2054                 return true;
2055             }
2056         }
2057     }
2058     else
2059     {
2060         m_qProcessInfo_is_valid = eLazyBoolNo;
2061     }
2062 
2063     return false;
2064 }
2065 
2066 
2067 uint32_t
2068 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2069                                              ProcessInstanceInfoList &process_infos)
2070 {
2071     process_infos.Clear();
2072 
2073     if (m_supports_qfProcessInfo)
2074     {
2075         StreamString packet;
2076         packet.PutCString ("qfProcessInfo");
2077         if (!match_info.MatchAllProcesses())
2078         {
2079             packet.PutChar (':');
2080             const char *name = match_info.GetProcessInfo().GetName();
2081             bool has_name_match = false;
2082             if (name && name[0])
2083             {
2084                 has_name_match = true;
2085                 NameMatchType name_match_type = match_info.GetNameMatchType();
2086                 switch (name_match_type)
2087                 {
2088                 case eNameMatchIgnore:
2089                     has_name_match = false;
2090                     break;
2091 
2092                 case eNameMatchEquals:
2093                     packet.PutCString ("name_match:equals;");
2094                     break;
2095 
2096                 case eNameMatchContains:
2097                     packet.PutCString ("name_match:contains;");
2098                     break;
2099 
2100                 case eNameMatchStartsWith:
2101                     packet.PutCString ("name_match:starts_with;");
2102                     break;
2103 
2104                 case eNameMatchEndsWith:
2105                     packet.PutCString ("name_match:ends_with;");
2106                     break;
2107 
2108                 case eNameMatchRegularExpression:
2109                     packet.PutCString ("name_match:regex;");
2110                     break;
2111                 }
2112                 if (has_name_match)
2113                 {
2114                     packet.PutCString ("name:");
2115                     packet.PutBytesAsRawHex8(name, ::strlen(name));
2116                     packet.PutChar (';');
2117                 }
2118             }
2119 
2120             if (match_info.GetProcessInfo().ProcessIDIsValid())
2121                 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2122             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2123                 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2124             if (match_info.GetProcessInfo().UserIDIsValid())
2125                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2126             if (match_info.GetProcessInfo().GroupIDIsValid())
2127                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2128             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2129                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2130             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2131                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2132             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2133                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2134             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2135             {
2136                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2137                 const llvm::Triple &triple = match_arch.GetTriple();
2138                 packet.PutCString("triple:");
2139                 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2140                 packet.PutChar (';');
2141             }
2142         }
2143         StringExtractorGDBRemote response;
2144         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
2145         {
2146             do
2147             {
2148                 ProcessInstanceInfo process_info;
2149                 if (!DecodeProcessInfoResponse (response, process_info))
2150                     break;
2151                 process_infos.Append(process_info);
2152                 response.GetStringRef().clear();
2153                 response.SetFilePos(0);
2154             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
2155         }
2156         else
2157         {
2158             m_supports_qfProcessInfo = false;
2159             return 0;
2160         }
2161     }
2162     return process_infos.GetSize();
2163 
2164 }
2165 
2166 bool
2167 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2168 {
2169     if (m_supports_qUserName)
2170     {
2171         char packet[32];
2172         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2173         assert (packet_len < (int)sizeof(packet));
2174         StringExtractorGDBRemote response;
2175         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2176         {
2177             if (response.IsNormalResponse())
2178             {
2179                 // Make sure we parsed the right number of characters. The response is
2180                 // the hex encoded user name and should make up the entire packet.
2181                 // If there are any non-hex ASCII bytes, the length won't match below..
2182                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2183                     return true;
2184             }
2185         }
2186         else
2187         {
2188             m_supports_qUserName = false;
2189             return false;
2190         }
2191     }
2192     return false;
2193 
2194 }
2195 
2196 bool
2197 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2198 {
2199     if (m_supports_qGroupName)
2200     {
2201         char packet[32];
2202         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2203         assert (packet_len < (int)sizeof(packet));
2204         StringExtractorGDBRemote response;
2205         if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2206         {
2207             if (response.IsNormalResponse())
2208             {
2209                 // Make sure we parsed the right number of characters. The response is
2210                 // the hex encoded group name and should make up the entire packet.
2211                 // If there are any non-hex ASCII bytes, the length won't match below..
2212                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2213                     return true;
2214             }
2215         }
2216         else
2217         {
2218             m_supports_qGroupName = false;
2219             return false;
2220         }
2221     }
2222     return false;
2223 }
2224 
2225 void
2226 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2227 {
2228     uint32_t i;
2229     TimeValue start_time, end_time;
2230     uint64_t total_time_nsec;
2231     float packets_per_second;
2232     if (SendSpeedTestPacket (0, 0))
2233     {
2234         for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2235         {
2236             for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2237             {
2238                 start_time = TimeValue::Now();
2239                 for (i=0; i<num_packets; ++i)
2240                 {
2241                     SendSpeedTestPacket (send_size, recv_size);
2242                 }
2243                 end_time = TimeValue::Now();
2244                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2245                 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2246                 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2247                         num_packets,
2248                         send_size,
2249                         recv_size,
2250                         total_time_nsec / TimeValue::NanoSecPerSec,
2251                         total_time_nsec % TimeValue::NanoSecPerSec,
2252                         packets_per_second);
2253                 if (recv_size == 0)
2254                     recv_size = 32;
2255             }
2256             if (send_size == 0)
2257                 send_size = 32;
2258         }
2259     }
2260     else
2261     {
2262         start_time = TimeValue::Now();
2263         for (i=0; i<num_packets; ++i)
2264         {
2265             GetCurrentProcessID ();
2266         }
2267         end_time = TimeValue::Now();
2268         total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2269         packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2270         printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
2271                 num_packets,
2272                 total_time_nsec / TimeValue::NanoSecPerSec,
2273                 total_time_nsec % TimeValue::NanoSecPerSec,
2274                 packets_per_second);
2275     }
2276 }
2277 
2278 bool
2279 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2280 {
2281     StreamString packet;
2282     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2283     uint32_t bytes_left = send_size;
2284     while (bytes_left > 0)
2285     {
2286         if (bytes_left >= 26)
2287         {
2288             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2289             bytes_left -= 26;
2290         }
2291         else
2292         {
2293             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2294             bytes_left = 0;
2295         }
2296     }
2297 
2298     StringExtractorGDBRemote response;
2299     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
2300     return false;
2301 }
2302 
2303 uint16_t
2304 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
2305 {
2306     pid = LLDB_INVALID_PROCESS_ID;
2307     StringExtractorGDBRemote response;
2308     StreamString stream;
2309     stream.PutCString("qLaunchGDBServer;");
2310     std::string hostname;
2311     if (Host::GetHostname (hostname))
2312     {
2313         // Make the GDB server we launch only accept connections from this host
2314         stream.Printf("host:%s;", hostname.c_str());
2315     }
2316     else
2317     {
2318         // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2319         stream.Printf("host:*;");
2320     }
2321     const char *packet = stream.GetData();
2322     int packet_len = stream.GetSize();
2323 
2324     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2325     {
2326         std::string name;
2327         std::string value;
2328         uint16_t port = 0;
2329         while (response.GetNameColonValue(name, value))
2330         {
2331             if (name.compare("port") == 0)
2332                 port = Args::StringToUInt32(value.c_str(), 0, 0);
2333             else if (name.compare("pid") == 0)
2334                 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2335         }
2336         return port;
2337     }
2338     return 0;
2339 }
2340 
2341 bool
2342 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2343 {
2344     StreamString stream;
2345     stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2346     const char *packet = stream.GetData();
2347     int packet_len = stream.GetSize();
2348 
2349     StringExtractorGDBRemote response;
2350     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2351     {
2352         if (response.IsOKResponse())
2353             return true;
2354     }
2355     return false;
2356 }
2357 
2358 bool
2359 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2360 {
2361     if (m_curr_tid == tid)
2362         return true;
2363 
2364     char packet[32];
2365     int packet_len;
2366     if (tid == UINT64_MAX)
2367         packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2368     else
2369         packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2370     assert (packet_len + 1 < (int)sizeof(packet));
2371     StringExtractorGDBRemote response;
2372     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2373     {
2374         if (response.IsOKResponse())
2375         {
2376             m_curr_tid = tid;
2377             return true;
2378         }
2379     }
2380     return false;
2381 }
2382 
2383 bool
2384 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2385 {
2386     if (m_curr_tid_run == tid)
2387         return true;
2388 
2389     char packet[32];
2390     int packet_len;
2391     if (tid == UINT64_MAX)
2392         packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2393     else
2394         packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2395 
2396     assert (packet_len + 1 < (int)sizeof(packet));
2397     StringExtractorGDBRemote response;
2398     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2399     {
2400         if (response.IsOKResponse())
2401         {
2402             m_curr_tid_run = tid;
2403             return true;
2404         }
2405     }
2406     return false;
2407 }
2408 
2409 bool
2410 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2411 {
2412     if (SendPacketAndWaitForResponse("?", 1, response, false))
2413         return response.IsNormalResponse();
2414     return false;
2415 }
2416 
2417 bool
2418 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2419 {
2420     if (m_supports_qThreadStopInfo)
2421     {
2422         char packet[256];
2423         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2424         assert (packet_len < (int)sizeof(packet));
2425         if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2426         {
2427             if (response.IsUnsupportedResponse())
2428                 m_supports_qThreadStopInfo = false;
2429             else if (response.IsNormalResponse())
2430                 return true;
2431             else
2432                 return false;
2433         }
2434         else
2435         {
2436             m_supports_qThreadStopInfo = false;
2437         }
2438     }
2439     return false;
2440 }
2441 
2442 
2443 uint8_t
2444 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
2445 {
2446     switch (type)
2447     {
2448     case eBreakpointSoftware:   if (!m_supports_z0) return UINT8_MAX; break;
2449     case eBreakpointHardware:   if (!m_supports_z1) return UINT8_MAX; break;
2450     case eWatchpointWrite:      if (!m_supports_z2) return UINT8_MAX; break;
2451     case eWatchpointRead:       if (!m_supports_z3) return UINT8_MAX; break;
2452     case eWatchpointReadWrite:  if (!m_supports_z4) return UINT8_MAX; break;
2453     }
2454 
2455     char packet[64];
2456     const int packet_len = ::snprintf (packet,
2457                                        sizeof(packet),
2458                                        "%c%i,%" PRIx64 ",%x",
2459                                        insert ? 'Z' : 'z',
2460                                        type,
2461                                        addr,
2462                                        length);
2463 
2464     assert (packet_len + 1 < (int)sizeof(packet));
2465     StringExtractorGDBRemote response;
2466     if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2467     {
2468         if (response.IsOKResponse())
2469             return 0;
2470         else if (response.IsErrorResponse())
2471             return response.GetError();
2472     }
2473     else
2474     {
2475         switch (type)
2476         {
2477             case eBreakpointSoftware:   m_supports_z0 = false; break;
2478             case eBreakpointHardware:   m_supports_z1 = false; break;
2479             case eWatchpointWrite:      m_supports_z2 = false; break;
2480             case eWatchpointRead:       m_supports_z3 = false; break;
2481             case eWatchpointReadWrite:  m_supports_z4 = false; break;
2482         }
2483     }
2484 
2485     return UINT8_MAX;
2486 }
2487 
2488 size_t
2489 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2490                                                    bool &sequence_mutex_unavailable)
2491 {
2492     Mutex::Locker locker;
2493     thread_ids.clear();
2494 
2495     if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2496     {
2497         sequence_mutex_unavailable = false;
2498         StringExtractorGDBRemote response;
2499 
2500         for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
2501              response.IsNormalResponse();
2502              SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
2503         {
2504             char ch = response.GetChar();
2505             if (ch == 'l')
2506                 break;
2507             if (ch == 'm')
2508             {
2509                 do
2510                 {
2511                     tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2512 
2513                     if (tid != LLDB_INVALID_THREAD_ID)
2514                     {
2515                         thread_ids.push_back (tid);
2516                     }
2517                     ch = response.GetChar();    // Skip the command separator
2518                 } while (ch == ',');            // Make sure we got a comma separator
2519             }
2520         }
2521     }
2522     else
2523     {
2524 #if defined (LLDB_CONFIGURATION_DEBUG)
2525         // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2526 #else
2527         Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2528         if (log)
2529             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
2530 #endif
2531         sequence_mutex_unavailable = true;
2532     }
2533     return thread_ids.size();
2534 }
2535 
2536 lldb::addr_t
2537 GDBRemoteCommunicationClient::GetShlibInfoAddr()
2538 {
2539     if (!IsRunning())
2540     {
2541         StringExtractorGDBRemote response;
2542         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2543         {
2544             if (response.IsNormalResponse())
2545                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2546         }
2547     }
2548     return LLDB_INVALID_ADDRESS;
2549 }
2550 
2551 lldb_private::Error
2552 GDBRemoteCommunicationClient::RunShellCommand (const char *command,           // Shouldn't be NULL
2553                                                const char *working_dir,       // Pass NULL to use the current working directory
2554                                                int *status_ptr,               // Pass NULL if you don't want the process exit status
2555                                                int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
2556                                                std::string *command_output,   // Pass NULL if you don't want the command output
2557                                                uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
2558 {
2559     lldb_private::StreamString stream;
2560     stream.PutCString("qPlatform_shell:");
2561     stream.PutBytesAsRawHex8(command, strlen(command));
2562     stream.PutChar(',');
2563     stream.PutHex32(timeout_sec);
2564     if (working_dir && *working_dir)
2565     {
2566         stream.PutChar(',');
2567         stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2568     }
2569     const char *packet = stream.GetData();
2570     int packet_len = stream.GetSize();
2571     StringExtractorGDBRemote response;
2572     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2573     {
2574         if (response.GetChar() != 'F')
2575             return Error("malformed reply");
2576         if (response.GetChar() != ',')
2577             return Error("malformed reply");
2578         uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2579         if (exitcode == UINT32_MAX)
2580             return Error("unable to run remote process");
2581         else if (status_ptr)
2582             *status_ptr = exitcode;
2583         if (response.GetChar() != ',')
2584             return Error("malformed reply");
2585         uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2586         if (signo_ptr)
2587             *signo_ptr = signo;
2588         if (response.GetChar() != ',')
2589             return Error("malformed reply");
2590         std::string output;
2591         response.GetEscapedBinaryData(output);
2592         if (command_output)
2593             command_output->assign(output);
2594         return Error();
2595     }
2596     return Error("unable to send packet");
2597 }
2598 
2599 Error
2600 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2601                                              uint32_t file_permissions)
2602 {
2603     lldb_private::StreamString stream;
2604     stream.PutCString("qPlatform_mkdir:");
2605     stream.PutHex32(file_permissions);
2606     stream.PutChar(',');
2607     stream.PutBytesAsRawHex8(path, strlen(path));
2608     const char *packet = stream.GetData();
2609     int packet_len = stream.GetSize();
2610     StringExtractorGDBRemote response;
2611     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2612     {
2613         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2614     }
2615     return Error();
2616 
2617 }
2618 
2619 Error
2620 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2621                                                   uint32_t file_permissions)
2622 {
2623     lldb_private::StreamString stream;
2624     stream.PutCString("qPlatform_chmod:");
2625     stream.PutHex32(file_permissions);
2626     stream.PutChar(',');
2627     stream.PutBytesAsRawHex8(path, strlen(path));
2628     const char *packet = stream.GetData();
2629     int packet_len = stream.GetSize();
2630     StringExtractorGDBRemote response;
2631     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2632     {
2633         return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2634     }
2635     return Error();
2636 
2637 }
2638 
2639 static uint64_t
2640 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2641                            uint64_t fail_result,
2642                            Error &error)
2643 {
2644     response.SetFilePos(0);
2645     if (response.GetChar() != 'F')
2646         return fail_result;
2647     int32_t result = response.GetS32 (-2);
2648     if (result == -2)
2649         return fail_result;
2650     if (response.GetChar() == ',')
2651     {
2652         int result_errno = response.GetS32 (-2);
2653         if (result_errno != -2)
2654             error.SetError(result_errno, eErrorTypePOSIX);
2655         else
2656             error.SetError(-1, eErrorTypeGeneric);
2657     }
2658     else
2659         error.Clear();
2660     return  result;
2661 }
2662 lldb::user_id_t
2663 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2664                                         uint32_t flags,
2665                                         mode_t mode,
2666                                         Error &error)
2667 {
2668     lldb_private::StreamString stream;
2669     stream.PutCString("vFile:open:");
2670     std::string path (file_spec.GetPath());
2671     if (path.empty())
2672         return UINT64_MAX;
2673     stream.PutCStringAsRawHex8(path.c_str());
2674     stream.PutChar(',');
2675     const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2676     stream.PutHex32(posix_open_flags);
2677     stream.PutChar(',');
2678     stream.PutHex32(mode);
2679     const char* packet = stream.GetData();
2680     int packet_len = stream.GetSize();
2681     StringExtractorGDBRemote response;
2682     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2683     {
2684         return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2685     }
2686     return UINT64_MAX;
2687 }
2688 
2689 bool
2690 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2691                                          Error &error)
2692 {
2693     lldb_private::StreamString stream;
2694     stream.Printf("vFile:close:%i", (int)fd);
2695     const char* packet = stream.GetData();
2696     int packet_len = stream.GetSize();
2697     StringExtractorGDBRemote response;
2698     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2699     {
2700         return ParseHostIOPacketResponse (response, -1, error) == 0;
2701     }
2702     return false;
2703 }
2704 
2705 // Extension of host I/O packets to get the file size.
2706 lldb::user_id_t
2707 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2708 {
2709     lldb_private::StreamString stream;
2710     stream.PutCString("vFile:size:");
2711     std::string path (file_spec.GetPath());
2712     stream.PutCStringAsRawHex8(path.c_str());
2713     const char* packet = stream.GetData();
2714     int packet_len = stream.GetSize();
2715     StringExtractorGDBRemote response;
2716     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2717     {
2718         if (response.GetChar() != 'F')
2719             return UINT64_MAX;
2720         uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2721         return retcode;
2722     }
2723     return UINT64_MAX;
2724 }
2725 
2726 Error
2727 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
2728 {
2729     Error error;
2730     lldb_private::StreamString stream;
2731     stream.PutCString("vFile:mode:");
2732     stream.PutCStringAsRawHex8(path);
2733     const char* packet = stream.GetData();
2734     int packet_len = stream.GetSize();
2735     StringExtractorGDBRemote response;
2736     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2737     {
2738         if (response.GetChar() != 'F')
2739         {
2740             error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2741         }
2742         else
2743         {
2744             const uint32_t mode = response.GetS32(-1);
2745             if (mode == -1)
2746             {
2747                 if (response.GetChar() == ',')
2748                 {
2749                     int response_errno = response.GetS32(-1);
2750                     if (response_errno > 0)
2751                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
2752                     else
2753                         error.SetErrorToGenericError();
2754                 }
2755                 else
2756                     error.SetErrorToGenericError();
2757             }
2758             else
2759             {
2760                 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2761             }
2762         }
2763     }
2764     else
2765     {
2766         error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2767     }
2768     return error;
2769 }
2770 
2771 uint64_t
2772 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2773                                         uint64_t offset,
2774                                         void *dst,
2775                                         uint64_t dst_len,
2776                                         Error &error)
2777 {
2778     lldb_private::StreamString stream;
2779     stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2780     const char* packet = stream.GetData();
2781     int packet_len = stream.GetSize();
2782     StringExtractorGDBRemote response;
2783     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2784     {
2785         if (response.GetChar() != 'F')
2786             return 0;
2787         uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2788         if (retcode == UINT32_MAX)
2789             return retcode;
2790         const char next = (response.Peek() ? *response.Peek() : 0);
2791         if (next == ',')
2792             return 0;
2793         if (next == ';')
2794         {
2795             response.GetChar(); // skip the semicolon
2796             std::string buffer;
2797             if (response.GetEscapedBinaryData(buffer))
2798             {
2799                 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2800                 if (data_to_write > 0)
2801                     memcpy(dst, &buffer[0], data_to_write);
2802                 return data_to_write;
2803             }
2804         }
2805     }
2806     return 0;
2807 }
2808 
2809 uint64_t
2810 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2811                                          uint64_t offset,
2812                                          const void* src,
2813                                          uint64_t src_len,
2814                                          Error &error)
2815 {
2816     lldb_private::StreamGDBRemote stream;
2817     stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2818     stream.PutEscapedBytes(src, src_len);
2819     const char* packet = stream.GetData();
2820     int packet_len = stream.GetSize();
2821     StringExtractorGDBRemote response;
2822     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2823     {
2824         if (response.GetChar() != 'F')
2825         {
2826             error.SetErrorStringWithFormat("write file failed");
2827             return 0;
2828         }
2829         uint64_t bytes_written = response.GetU64(UINT64_MAX);
2830         if (bytes_written == UINT64_MAX)
2831         {
2832             error.SetErrorToGenericError();
2833             if (response.GetChar() == ',')
2834             {
2835                 int response_errno = response.GetS32(-1);
2836                 if (response_errno > 0)
2837                     error.SetError(response_errno, lldb::eErrorTypePOSIX);
2838             }
2839             return 0;
2840         }
2841         return bytes_written;
2842     }
2843     else
2844     {
2845         error.SetErrorString ("failed to send vFile:pwrite packet");
2846     }
2847     return 0;
2848 }
2849 
2850 Error
2851 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
2852 {
2853     Error error;
2854     lldb_private::StreamGDBRemote stream;
2855     stream.PutCString("vFile:symlink:");
2856     // the unix symlink() command reverses its parameters where the dst if first,
2857     // so we follow suit here
2858     stream.PutCStringAsRawHex8(dst);
2859     stream.PutChar(',');
2860     stream.PutCStringAsRawHex8(src);
2861     const char* packet = stream.GetData();
2862     int packet_len = stream.GetSize();
2863     StringExtractorGDBRemote response;
2864     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2865     {
2866         if (response.GetChar() == 'F')
2867         {
2868             uint32_t result = response.GetU32(UINT32_MAX);
2869             if (result != 0)
2870             {
2871                 error.SetErrorToGenericError();
2872                 if (response.GetChar() == ',')
2873                 {
2874                     int response_errno = response.GetS32(-1);
2875                     if (response_errno > 0)
2876                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
2877                 }
2878             }
2879         }
2880         else
2881         {
2882             // Should have returned with 'F<result>[,<errno>]'
2883             error.SetErrorStringWithFormat("symlink failed");
2884         }
2885     }
2886     else
2887     {
2888         error.SetErrorString ("failed to send vFile:symlink packet");
2889     }
2890     return error;
2891 }
2892 
2893 Error
2894 GDBRemoteCommunicationClient::Unlink (const char *path)
2895 {
2896     Error error;
2897     lldb_private::StreamGDBRemote stream;
2898     stream.PutCString("vFile:unlink:");
2899     // the unix symlink() command reverses its parameters where the dst if first,
2900     // so we follow suit here
2901     stream.PutCStringAsRawHex8(path);
2902     const char* packet = stream.GetData();
2903     int packet_len = stream.GetSize();
2904     StringExtractorGDBRemote response;
2905     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2906     {
2907         if (response.GetChar() == 'F')
2908         {
2909             uint32_t result = response.GetU32(UINT32_MAX);
2910             if (result != 0)
2911             {
2912                 error.SetErrorToGenericError();
2913                 if (response.GetChar() == ',')
2914                 {
2915                     int response_errno = response.GetS32(-1);
2916                     if (response_errno > 0)
2917                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
2918                 }
2919             }
2920         }
2921         else
2922         {
2923             // Should have returned with 'F<result>[,<errno>]'
2924             error.SetErrorStringWithFormat("unlink failed");
2925         }
2926     }
2927     else
2928     {
2929         error.SetErrorString ("failed to send vFile:unlink packet");
2930     }
2931     return error;
2932 }
2933 
2934 // Extension of host I/O packets to get whether a file exists.
2935 bool
2936 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2937 {
2938     lldb_private::StreamString stream;
2939     stream.PutCString("vFile:exists:");
2940     std::string path (file_spec.GetPath());
2941     stream.PutCStringAsRawHex8(path.c_str());
2942     const char* packet = stream.GetData();
2943     int packet_len = stream.GetSize();
2944     StringExtractorGDBRemote response;
2945     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2946     {
2947         if (response.GetChar() != 'F')
2948             return false;
2949         if (response.GetChar() != ',')
2950             return false;
2951         bool retcode = (response.GetChar() != '0');
2952         return retcode;
2953     }
2954     return false;
2955 }
2956 
2957 bool
2958 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2959                                             uint64_t &high,
2960                                             uint64_t &low)
2961 {
2962     lldb_private::StreamString stream;
2963     stream.PutCString("vFile:MD5:");
2964     std::string path (file_spec.GetPath());
2965     stream.PutCStringAsRawHex8(path.c_str());
2966     const char* packet = stream.GetData();
2967     int packet_len = stream.GetSize();
2968     StringExtractorGDBRemote response;
2969     if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2970     {
2971         if (response.GetChar() != 'F')
2972             return false;
2973         if (response.GetChar() != ',')
2974             return false;
2975         if (response.Peek() && *response.Peek() == 'x')
2976             return false;
2977         low = response.GetHexMaxU64(false, UINT64_MAX);
2978         high = response.GetHexMaxU64(false, UINT64_MAX);
2979         return true;
2980     }
2981     return false;
2982 }
2983 
2984 bool
2985 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
2986 {
2987     Mutex::Locker locker;
2988     if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
2989     {
2990         const bool thread_suffix_supported = GetThreadSuffixSupported();
2991 
2992         if (thread_suffix_supported || SetCurrentThread(tid))
2993         {
2994             char packet[64];
2995             int packet_len = 0;
2996             if (thread_suffix_supported)
2997                 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
2998             else
2999                 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3000             assert (packet_len < ((int)sizeof(packet) - 1));
3001             return SendPacketAndWaitForResponse(packet, response, false);
3002         }
3003     }
3004     return false;
3005 
3006 }
3007 
3008 
3009 bool
3010 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3011 {
3012     Mutex::Locker locker;
3013     if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3014     {
3015         const bool thread_suffix_supported = GetThreadSuffixSupported();
3016 
3017         if (thread_suffix_supported || SetCurrentThread(tid))
3018         {
3019             char packet[64];
3020             int packet_len = 0;
3021             // Get all registers in one packet
3022             if (thread_suffix_supported)
3023                 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3024             else
3025                 packet_len = ::snprintf (packet, sizeof(packet), "g");
3026             assert (packet_len < ((int)sizeof(packet) - 1));
3027             return SendPacketAndWaitForResponse(packet, response, false);
3028         }
3029     }
3030     return false;
3031 }
3032 bool
3033 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3034 {
3035     save_id = 0; // Set to invalid save ID
3036     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3037         return false;
3038 
3039     m_supports_QSaveRegisterState = eLazyBoolYes;
3040     Mutex::Locker locker;
3041     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3042     {
3043         const bool thread_suffix_supported = GetThreadSuffixSupported();
3044         if (thread_suffix_supported || SetCurrentThread(tid))
3045         {
3046             char packet[256];
3047             if (thread_suffix_supported)
3048                 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3049             else
3050                 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3051 
3052             StringExtractorGDBRemote response;
3053 
3054             if (SendPacketAndWaitForResponse(packet, response, false))
3055             {
3056                 if (response.IsUnsupportedResponse())
3057                 {
3058                     // This packet isn't supported, don't try calling it again
3059                     m_supports_QSaveRegisterState = eLazyBoolNo;
3060                 }
3061 
3062                 const uint32_t response_save_id = response.GetU32(0);
3063                 if (response_save_id != 0)
3064                 {
3065                     save_id = response_save_id;
3066                     return true;
3067                 }
3068             }
3069         }
3070     }
3071     return false;
3072 }
3073 
3074 bool
3075 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3076 {
3077     // We use the "m_supports_QSaveRegisterState" variable here becuase the
3078     // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3079     // order to be useful
3080     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3081         return false;
3082 
3083     Mutex::Locker locker;
3084     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3085     {
3086         const bool thread_suffix_supported = GetThreadSuffixSupported();
3087         if (thread_suffix_supported || SetCurrentThread(tid))
3088         {
3089             char packet[256];
3090             if (thread_suffix_supported)
3091                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3092             else
3093                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3094 
3095             StringExtractorGDBRemote response;
3096 
3097             if (SendPacketAndWaitForResponse(packet, response, false))
3098             {
3099                 if (response.IsOKResponse())
3100                 {
3101                     return true;
3102                 }
3103                 else if (response.IsUnsupportedResponse())
3104                 {
3105                     // This packet isn't supported, don't try calling this packet or
3106                     // QSaveRegisterState again...
3107                     m_supports_QSaveRegisterState = eLazyBoolNo;
3108                 }
3109             }
3110         }
3111     }
3112     return false;
3113 }
3114