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