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