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