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();
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::GetDefaultThreadId (lldb::tid_t &tid)
1625 {
1626     StringExtractorGDBRemote response;
1627     if (SendPacketAndWaitForResponse("qC",response,false) !=  PacketResult::Success)
1628         return false;
1629 
1630     if (!response.IsNormalResponse())
1631         return false;
1632 
1633     if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1634         tid = response.GetHexMaxU32(true, -1);
1635 
1636     return true;
1637 }
1638 
1639 bool
1640 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1641 {
1642     Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1643 
1644     if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1645     {
1646         m_qHostInfo_is_valid = eLazyBoolNo;
1647         StringExtractorGDBRemote response;
1648         if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
1649         {
1650             if (response.IsNormalResponse())
1651             {
1652                 std::string name;
1653                 std::string value;
1654                 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1655                 uint32_t sub = 0;
1656                 std::string arch_name;
1657                 std::string os_name;
1658                 std::string vendor_name;
1659                 std::string triple;
1660                 std::string distribution_id;
1661                 uint32_t pointer_byte_size = 0;
1662                 StringExtractor extractor;
1663                 ByteOrder byte_order = eByteOrderInvalid;
1664                 uint32_t num_keys_decoded = 0;
1665                 while (response.GetNameColonValue(name, value))
1666                 {
1667                     if (name.compare("cputype") == 0)
1668                     {
1669                         // exception type in big endian hex
1670                         cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1671                         if (cpu != LLDB_INVALID_CPUTYPE)
1672                             ++num_keys_decoded;
1673                     }
1674                     else if (name.compare("cpusubtype") == 0)
1675                     {
1676                         // exception count in big endian hex
1677                         sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
1678                         if (sub != 0)
1679                             ++num_keys_decoded;
1680                     }
1681                     else if (name.compare("arch") == 0)
1682                     {
1683                         arch_name.swap (value);
1684                         ++num_keys_decoded;
1685                     }
1686                     else if (name.compare("triple") == 0)
1687                     {
1688                         extractor.GetStringRef ().swap (value);
1689                         extractor.SetFilePos(0);
1690                         extractor.GetHexByteString (triple);
1691                         ++num_keys_decoded;
1692                     }
1693                     else if (name.compare ("distribution_id") == 0)
1694                     {
1695                         extractor.GetStringRef ().swap (value);
1696                         extractor.SetFilePos (0);
1697                         extractor.GetHexByteString (distribution_id);
1698                         ++num_keys_decoded;
1699                     }
1700                     else if (name.compare("os_build") == 0)
1701                     {
1702                         extractor.GetStringRef().swap(value);
1703                         extractor.SetFilePos(0);
1704                         extractor.GetHexByteString (m_os_build);
1705                         ++num_keys_decoded;
1706                     }
1707                     else if (name.compare("hostname") == 0)
1708                     {
1709                         extractor.GetStringRef().swap(value);
1710                         extractor.SetFilePos(0);
1711                         extractor.GetHexByteString (m_hostname);
1712                         ++num_keys_decoded;
1713                     }
1714                     else if (name.compare("os_kernel") == 0)
1715                     {
1716                         extractor.GetStringRef().swap(value);
1717                         extractor.SetFilePos(0);
1718                         extractor.GetHexByteString (m_os_kernel);
1719                         ++num_keys_decoded;
1720                     }
1721                     else if (name.compare("ostype") == 0)
1722                     {
1723                         os_name.swap (value);
1724                         ++num_keys_decoded;
1725                     }
1726                     else if (name.compare("vendor") == 0)
1727                     {
1728                         vendor_name.swap(value);
1729                         ++num_keys_decoded;
1730                     }
1731                     else if (name.compare("endian") == 0)
1732                     {
1733                         ++num_keys_decoded;
1734                         if (value.compare("little") == 0)
1735                             byte_order = eByteOrderLittle;
1736                         else if (value.compare("big") == 0)
1737                             byte_order = eByteOrderBig;
1738                         else if (value.compare("pdp") == 0)
1739                             byte_order = eByteOrderPDP;
1740                         else
1741                             --num_keys_decoded;
1742                     }
1743                     else if (name.compare("ptrsize") == 0)
1744                     {
1745                         pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
1746                         if (pointer_byte_size != 0)
1747                             ++num_keys_decoded;
1748                     }
1749                     else if (name.compare("os_version") == 0)
1750                     {
1751                         Args::StringToVersion (value.c_str(),
1752                                                m_os_version_major,
1753                                                m_os_version_minor,
1754                                                m_os_version_update);
1755                         if (m_os_version_major != UINT32_MAX)
1756                             ++num_keys_decoded;
1757                     }
1758                     else if (name.compare("watchpoint_exceptions_received") == 0)
1759                     {
1760                         ++num_keys_decoded;
1761                         if (strcmp(value.c_str(),"before") == 0)
1762                             m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1763                         else if (strcmp(value.c_str(),"after") == 0)
1764                             m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1765                         else
1766                             --num_keys_decoded;
1767                     }
1768                     else if (name.compare("default_packet_timeout") == 0)
1769                     {
1770                         m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
1771                         if (m_default_packet_timeout > 0)
1772                         {
1773                             SetPacketTimeout(m_default_packet_timeout);
1774                             ++num_keys_decoded;
1775                         }
1776                     }
1777 
1778                 }
1779 
1780                 if (num_keys_decoded > 0)
1781                     m_qHostInfo_is_valid = eLazyBoolYes;
1782 
1783                 if (triple.empty())
1784                 {
1785                     if (arch_name.empty())
1786                     {
1787                         if (cpu != LLDB_INVALID_CPUTYPE)
1788                         {
1789                             m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1790                             if (pointer_byte_size)
1791                             {
1792                                 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1793                             }
1794                             if (byte_order != eByteOrderInvalid)
1795                             {
1796                                 assert (byte_order == m_host_arch.GetByteOrder());
1797                             }
1798 
1799                             if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1800                             {
1801                                 switch (m_host_arch.GetMachine())
1802                                 {
1803                                 case llvm::Triple::aarch64:
1804                                 case llvm::Triple::arm:
1805                                 case llvm::Triple::thumb:
1806                                     os_name = "ios";
1807                                     break;
1808                                 default:
1809                                     os_name = "macosx";
1810                                     break;
1811                                 }
1812                             }
1813                             if (!vendor_name.empty())
1814                                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1815                             if (!os_name.empty())
1816                                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1817 
1818                         }
1819                     }
1820                     else
1821                     {
1822                         std::string triple;
1823                         triple += arch_name;
1824                         if (!vendor_name.empty() || !os_name.empty())
1825                         {
1826                             triple += '-';
1827                             if (vendor_name.empty())
1828                                 triple += "unknown";
1829                             else
1830                                 triple += vendor_name;
1831                             triple += '-';
1832                             if (os_name.empty())
1833                                 triple += "unknown";
1834                             else
1835                                 triple += os_name;
1836                         }
1837                         m_host_arch.SetTriple (triple.c_str());
1838 
1839                         llvm::Triple &host_triple = m_host_arch.GetTriple();
1840                         if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1841                         {
1842                             switch (m_host_arch.GetMachine())
1843                             {
1844                                 case llvm::Triple::aarch64:
1845                                 case llvm::Triple::arm:
1846                                 case llvm::Triple::thumb:
1847                                     host_triple.setOS(llvm::Triple::IOS);
1848                                     break;
1849                                 default:
1850                                     host_triple.setOS(llvm::Triple::MacOSX);
1851                                     break;
1852                             }
1853                         }
1854                         if (pointer_byte_size)
1855                         {
1856                             assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1857                         }
1858                         if (byte_order != eByteOrderInvalid)
1859                         {
1860                             assert (byte_order == m_host_arch.GetByteOrder());
1861                         }
1862 
1863                     }
1864                 }
1865                 else
1866                 {
1867                     m_host_arch.SetTriple (triple.c_str());
1868                     if (pointer_byte_size)
1869                     {
1870                         assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1871                     }
1872                     if (byte_order != eByteOrderInvalid)
1873                     {
1874                         assert (byte_order == m_host_arch.GetByteOrder());
1875                     }
1876 
1877                     if (log)
1878                         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 ());
1879                 }
1880                 if (!distribution_id.empty ())
1881                     m_host_arch.SetDistributionId (distribution_id.c_str ());
1882             }
1883         }
1884     }
1885     return m_qHostInfo_is_valid == eLazyBoolYes;
1886 }
1887 
1888 int
1889 GDBRemoteCommunicationClient::SendAttach
1890 (
1891     lldb::pid_t pid,
1892     StringExtractorGDBRemote& response
1893 )
1894 {
1895     if (pid != LLDB_INVALID_PROCESS_ID)
1896     {
1897         char packet[64];
1898         const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1899         assert (packet_len < (int)sizeof(packet));
1900         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1901         {
1902             if (response.IsErrorResponse())
1903                 return response.GetError();
1904             return 0;
1905         }
1906     }
1907     return -1;
1908 }
1909 
1910 int
1911 GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1912 {
1913     StreamString packet;
1914     packet.PutCString("I");
1915     packet.PutBytesAsRawHex8(data, data_len);
1916     StringExtractorGDBRemote response;
1917     if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1918     {
1919         return 0;
1920     }
1921     return response.GetError();
1922 
1923 }
1924 
1925 const lldb_private::ArchSpec &
1926 GDBRemoteCommunicationClient::GetHostArchitecture ()
1927 {
1928     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1929         GetHostInfo ();
1930     return m_host_arch;
1931 }
1932 
1933 uint32_t
1934 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1935 {
1936     if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1937         GetHostInfo ();
1938     return m_default_packet_timeout;
1939 }
1940 
1941 addr_t
1942 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1943 {
1944     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1945     {
1946         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1947         char packet[64];
1948         const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1949                                            (uint64_t)size,
1950                                            permissions & lldb::ePermissionsReadable ? "r" : "",
1951                                            permissions & lldb::ePermissionsWritable ? "w" : "",
1952                                            permissions & lldb::ePermissionsExecutable ? "x" : "");
1953         assert (packet_len < (int)sizeof(packet));
1954         StringExtractorGDBRemote response;
1955         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1956         {
1957             if (response.IsUnsupportedResponse())
1958                 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1959             else if (!response.IsErrorResponse())
1960                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1961         }
1962         else
1963         {
1964             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1965         }
1966     }
1967     return LLDB_INVALID_ADDRESS;
1968 }
1969 
1970 bool
1971 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1972 {
1973     if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1974     {
1975         m_supports_alloc_dealloc_memory = eLazyBoolYes;
1976         char packet[64];
1977         const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1978         assert (packet_len < (int)sizeof(packet));
1979         StringExtractorGDBRemote response;
1980         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1981         {
1982             if (response.IsUnsupportedResponse())
1983                 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1984             else if (response.IsOKResponse())
1985                 return true;
1986         }
1987         else
1988         {
1989             m_supports_alloc_dealloc_memory = eLazyBoolNo;
1990         }
1991     }
1992     return false;
1993 }
1994 
1995 Error
1996 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1997 {
1998     Error error;
1999 
2000     if (keep_stopped)
2001     {
2002         if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2003         {
2004             char packet[64];
2005             const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
2006             assert (packet_len < (int)sizeof(packet));
2007             StringExtractorGDBRemote response;
2008             if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2009             {
2010                 m_supports_detach_stay_stopped = eLazyBoolYes;
2011             }
2012             else
2013             {
2014                 m_supports_detach_stay_stopped = eLazyBoolNo;
2015             }
2016         }
2017 
2018         if (m_supports_detach_stay_stopped == eLazyBoolNo)
2019         {
2020             error.SetErrorString("Stays stopped not supported by this target.");
2021             return error;
2022         }
2023         else
2024         {
2025             StringExtractorGDBRemote response;
2026             PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
2027             if (packet_result != PacketResult::Success)
2028                 error.SetErrorString ("Sending extended disconnect packet failed.");
2029         }
2030     }
2031     else
2032     {
2033         StringExtractorGDBRemote response;
2034         PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
2035         if (packet_result != PacketResult::Success)
2036             error.SetErrorString ("Sending disconnect packet failed.");
2037     }
2038     return error;
2039 }
2040 
2041 Error
2042 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2043                                                   lldb_private::MemoryRegionInfo &region_info)
2044 {
2045     Error error;
2046     region_info.Clear();
2047 
2048     if (m_supports_memory_region_info != eLazyBoolNo)
2049     {
2050         m_supports_memory_region_info = eLazyBoolYes;
2051         char packet[64];
2052         const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
2053         assert (packet_len < (int)sizeof(packet));
2054         StringExtractorGDBRemote response;
2055         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2056         {
2057             std::string name;
2058             std::string value;
2059             addr_t addr_value;
2060             bool success = true;
2061             bool saw_permissions = false;
2062             while (success && response.GetNameColonValue(name, value))
2063             {
2064                 if (name.compare ("start") == 0)
2065                 {
2066                     addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
2067                     if (success)
2068                         region_info.GetRange().SetRangeBase(addr_value);
2069                 }
2070                 else if (name.compare ("size") == 0)
2071                 {
2072                     addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
2073                     if (success)
2074                         region_info.GetRange().SetByteSize (addr_value);
2075                 }
2076                 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
2077                 {
2078                     saw_permissions = true;
2079                     if (region_info.GetRange().Contains (addr))
2080                     {
2081                         if (value.find('r') != std::string::npos)
2082                             region_info.SetReadable (MemoryRegionInfo::eYes);
2083                         else
2084                             region_info.SetReadable (MemoryRegionInfo::eNo);
2085 
2086                         if (value.find('w') != std::string::npos)
2087                             region_info.SetWritable (MemoryRegionInfo::eYes);
2088                         else
2089                             region_info.SetWritable (MemoryRegionInfo::eNo);
2090 
2091                         if (value.find('x') != std::string::npos)
2092                             region_info.SetExecutable (MemoryRegionInfo::eYes);
2093                         else
2094                             region_info.SetExecutable (MemoryRegionInfo::eNo);
2095                     }
2096                     else
2097                     {
2098                         // The reported region does not contain this address -- we're looking at an unmapped page
2099                         region_info.SetReadable (MemoryRegionInfo::eNo);
2100                         region_info.SetWritable (MemoryRegionInfo::eNo);
2101                         region_info.SetExecutable (MemoryRegionInfo::eNo);
2102                     }
2103                 }
2104                 else if (name.compare ("error") == 0)
2105                 {
2106                     StringExtractorGDBRemote name_extractor;
2107                     // Swap "value" over into "name_extractor"
2108                     name_extractor.GetStringRef().swap(value);
2109                     // Now convert the HEX bytes into a string value
2110                     name_extractor.GetHexByteString (value);
2111                     error.SetErrorString(value.c_str());
2112                 }
2113             }
2114 
2115             // We got a valid address range back but no permissions -- which means this is an unmapped page
2116             if (region_info.GetRange().IsValid() && saw_permissions == false)
2117             {
2118                 region_info.SetReadable (MemoryRegionInfo::eNo);
2119                 region_info.SetWritable (MemoryRegionInfo::eNo);
2120                 region_info.SetExecutable (MemoryRegionInfo::eNo);
2121             }
2122         }
2123         else
2124         {
2125             m_supports_memory_region_info = eLazyBoolNo;
2126         }
2127     }
2128 
2129     if (m_supports_memory_region_info == eLazyBoolNo)
2130     {
2131         error.SetErrorString("qMemoryRegionInfo is not supported");
2132     }
2133     if (error.Fail())
2134         region_info.Clear();
2135     return error;
2136 
2137 }
2138 
2139 Error
2140 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2141 {
2142     Error error;
2143 
2144     if (m_supports_watchpoint_support_info == eLazyBoolYes)
2145     {
2146         num = m_num_supported_hardware_watchpoints;
2147         return error;
2148     }
2149 
2150     // Set num to 0 first.
2151     num = 0;
2152     if (m_supports_watchpoint_support_info != eLazyBoolNo)
2153     {
2154         char packet[64];
2155         const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
2156         assert (packet_len < (int)sizeof(packet));
2157         StringExtractorGDBRemote response;
2158         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2159         {
2160             m_supports_watchpoint_support_info = eLazyBoolYes;
2161             std::string name;
2162             std::string value;
2163             while (response.GetNameColonValue(name, value))
2164             {
2165                 if (name.compare ("num") == 0)
2166                 {
2167                     num = StringConvert::ToUInt32(value.c_str(), 0, 0);
2168                     m_num_supported_hardware_watchpoints = num;
2169                 }
2170             }
2171         }
2172         else
2173         {
2174             m_supports_watchpoint_support_info = eLazyBoolNo;
2175         }
2176     }
2177 
2178     if (m_supports_watchpoint_support_info == eLazyBoolNo)
2179     {
2180         error.SetErrorString("qWatchpointSupportInfo is not supported");
2181     }
2182     return error;
2183 
2184 }
2185 
2186 lldb_private::Error
2187 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2188 {
2189     Error error(GetWatchpointSupportInfo(num));
2190     if (error.Success())
2191         error = GetWatchpointsTriggerAfterInstruction(after);
2192     return error;
2193 }
2194 
2195 lldb_private::Error
2196 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2197 {
2198     Error error;
2199 
2200     // we assume watchpoints will happen after running the relevant opcode
2201     // and we only want to override this behavior if we have explicitly
2202     // received a qHostInfo telling us otherwise
2203     if (m_qHostInfo_is_valid != eLazyBoolYes)
2204         after = true;
2205     else
2206         after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2207     return error;
2208 }
2209 
2210 int
2211 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2212 {
2213     if (path && path[0])
2214     {
2215         StreamString packet;
2216         packet.PutCString("QSetSTDIN:");
2217         packet.PutBytesAsRawHex8(path, strlen(path));
2218 
2219         StringExtractorGDBRemote response;
2220         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2221         {
2222             if (response.IsOKResponse())
2223                 return 0;
2224             uint8_t error = response.GetError();
2225             if (error)
2226                 return error;
2227         }
2228     }
2229     return -1;
2230 }
2231 
2232 int
2233 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2234 {
2235     if (path && path[0])
2236     {
2237         StreamString packet;
2238         packet.PutCString("QSetSTDOUT:");
2239         packet.PutBytesAsRawHex8(path, strlen(path));
2240 
2241         StringExtractorGDBRemote response;
2242         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2243         {
2244             if (response.IsOKResponse())
2245                 return 0;
2246             uint8_t error = response.GetError();
2247             if (error)
2248                 return error;
2249         }
2250     }
2251     return -1;
2252 }
2253 
2254 int
2255 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2256 {
2257     if (path && path[0])
2258     {
2259         StreamString packet;
2260         packet.PutCString("QSetSTDERR:");
2261         packet.PutBytesAsRawHex8(path, strlen(path));
2262 
2263         StringExtractorGDBRemote response;
2264         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2265         {
2266             if (response.IsOKResponse())
2267                 return 0;
2268             uint8_t error = response.GetError();
2269             if (error)
2270                 return error;
2271         }
2272     }
2273     return -1;
2274 }
2275 
2276 bool
2277 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2278 {
2279     StringExtractorGDBRemote response;
2280     if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2281     {
2282         if (response.IsUnsupportedResponse())
2283             return false;
2284         if (response.IsErrorResponse())
2285             return false;
2286         response.GetHexByteString (cwd);
2287         return !cwd.empty();
2288     }
2289     return false;
2290 }
2291 
2292 int
2293 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2294 {
2295     if (path && path[0])
2296     {
2297         StreamString packet;
2298         packet.PutCString("QSetWorkingDir:");
2299         packet.PutBytesAsRawHex8(path, strlen(path));
2300 
2301         StringExtractorGDBRemote response;
2302         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2303         {
2304             if (response.IsOKResponse())
2305                 return 0;
2306             uint8_t error = response.GetError();
2307             if (error)
2308                 return error;
2309         }
2310     }
2311     return -1;
2312 }
2313 
2314 int
2315 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2316 {
2317     char packet[32];
2318     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2319     assert (packet_len < (int)sizeof(packet));
2320     StringExtractorGDBRemote response;
2321     if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2322     {
2323         if (response.IsOKResponse())
2324             return 0;
2325         uint8_t error = response.GetError();
2326         if (error)
2327             return error;
2328     }
2329     return -1;
2330 }
2331 
2332 int
2333 GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2334 {
2335     char packet[32];
2336     const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2337     assert (packet_len < (int)sizeof(packet));
2338     StringExtractorGDBRemote response;
2339     if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2340     {
2341         if (response.IsOKResponse())
2342             return 0;
2343         uint8_t error = response.GetError();
2344         if (error)
2345             return error;
2346     }
2347     return -1;
2348 }
2349 
2350 
2351 bool
2352 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2353 {
2354     if (response.IsNormalResponse())
2355     {
2356         std::string name;
2357         std::string value;
2358         StringExtractor extractor;
2359 
2360         uint32_t cpu = LLDB_INVALID_CPUTYPE;
2361         uint32_t sub = 0;
2362         std::string vendor;
2363         std::string os_type;
2364 
2365         while (response.GetNameColonValue(name, value))
2366         {
2367             if (name.compare("pid") == 0)
2368             {
2369                 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2370             }
2371             else if (name.compare("ppid") == 0)
2372             {
2373                 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2374             }
2375             else if (name.compare("uid") == 0)
2376             {
2377                 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2378             }
2379             else if (name.compare("euid") == 0)
2380             {
2381                 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2382             }
2383             else if (name.compare("gid") == 0)
2384             {
2385                 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2386             }
2387             else if (name.compare("egid") == 0)
2388             {
2389                 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2390             }
2391             else if (name.compare("triple") == 0)
2392             {
2393                 StringExtractor extractor;
2394                 extractor.GetStringRef().swap(value);
2395                 extractor.SetFilePos(0);
2396                 extractor.GetHexByteString (value);
2397                 process_info.GetArchitecture ().SetTriple (value.c_str());
2398             }
2399             else if (name.compare("name") == 0)
2400             {
2401                 StringExtractor extractor;
2402                 // The process name from ASCII hex bytes since we can't
2403                 // control the characters in a process name
2404                 extractor.GetStringRef().swap(value);
2405                 extractor.SetFilePos(0);
2406                 extractor.GetHexByteString (value);
2407                 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2408             }
2409             else if (name.compare("cputype") == 0)
2410             {
2411                 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2412             }
2413             else if (name.compare("cpusubtype") == 0)
2414             {
2415                 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2416             }
2417             else if (name.compare("vendor") == 0)
2418             {
2419                 vendor = value;
2420             }
2421             else if (name.compare("ostype") == 0)
2422             {
2423                 os_type = value;
2424             }
2425         }
2426 
2427         if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2428         {
2429             if (vendor == "apple")
2430             {
2431                 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2432                 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2433                 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2434             }
2435         }
2436 
2437         if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2438             return true;
2439     }
2440     return false;
2441 }
2442 
2443 bool
2444 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2445 {
2446     process_info.Clear();
2447 
2448     if (m_supports_qProcessInfoPID)
2449     {
2450         char packet[32];
2451         const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2452         assert (packet_len < (int)sizeof(packet));
2453         StringExtractorGDBRemote response;
2454         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2455         {
2456             return DecodeProcessInfoResponse (response, process_info);
2457         }
2458         else
2459         {
2460             m_supports_qProcessInfoPID = false;
2461             return false;
2462         }
2463     }
2464     return false;
2465 }
2466 
2467 bool
2468 GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
2469 {
2470     Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2471 
2472     if (allow_lazy)
2473     {
2474         if (m_qProcessInfo_is_valid == eLazyBoolYes)
2475             return true;
2476         if (m_qProcessInfo_is_valid == eLazyBoolNo)
2477             return false;
2478     }
2479 
2480     GetHostInfo ();
2481 
2482     StringExtractorGDBRemote response;
2483     if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2484     {
2485         if (response.IsNormalResponse())
2486         {
2487             std::string name;
2488             std::string value;
2489             uint32_t cpu = LLDB_INVALID_CPUTYPE;
2490             uint32_t sub = 0;
2491             std::string arch_name;
2492             std::string os_name;
2493             std::string vendor_name;
2494             std::string triple;
2495             uint32_t pointer_byte_size = 0;
2496             StringExtractor extractor;
2497             ByteOrder byte_order = eByteOrderInvalid;
2498             uint32_t num_keys_decoded = 0;
2499             lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2500             while (response.GetNameColonValue(name, value))
2501             {
2502                 if (name.compare("cputype") == 0)
2503                 {
2504                     cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2505                     if (cpu != LLDB_INVALID_CPUTYPE)
2506                         ++num_keys_decoded;
2507                 }
2508                 else if (name.compare("cpusubtype") == 0)
2509                 {
2510                     sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2511                     if (sub != 0)
2512                         ++num_keys_decoded;
2513                 }
2514                 else if (name.compare("triple") == 0)
2515                 {
2516                     StringExtractor extractor;
2517                     extractor.GetStringRef().swap(value);
2518                     extractor.SetFilePos(0);
2519                     extractor.GetHexByteString (triple);
2520                     ++num_keys_decoded;
2521                 }
2522                 else if (name.compare("ostype") == 0)
2523                 {
2524                     os_name.swap (value);
2525                     ++num_keys_decoded;
2526                 }
2527                 else if (name.compare("vendor") == 0)
2528                 {
2529                     vendor_name.swap(value);
2530                     ++num_keys_decoded;
2531                 }
2532                 else if (name.compare("endian") == 0)
2533                 {
2534                     ++num_keys_decoded;
2535                     if (value.compare("little") == 0)
2536                         byte_order = eByteOrderLittle;
2537                     else if (value.compare("big") == 0)
2538                         byte_order = eByteOrderBig;
2539                     else if (value.compare("pdp") == 0)
2540                         byte_order = eByteOrderPDP;
2541                     else
2542                         --num_keys_decoded;
2543                 }
2544                 else if (name.compare("ptrsize") == 0)
2545                 {
2546                     pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2547                     if (pointer_byte_size != 0)
2548                         ++num_keys_decoded;
2549                 }
2550                 else if (name.compare("pid") == 0)
2551                 {
2552                     pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
2553                     if (pid != LLDB_INVALID_PROCESS_ID)
2554                         ++num_keys_decoded;
2555                 }
2556             }
2557             if (num_keys_decoded > 0)
2558                 m_qProcessInfo_is_valid = eLazyBoolYes;
2559             if (pid != LLDB_INVALID_PROCESS_ID)
2560             {
2561                 m_curr_pid_is_valid = eLazyBoolYes;
2562                 m_curr_pid = pid;
2563             }
2564 
2565             // Set the ArchSpec from the triple if we have it.
2566             if (!triple.empty ())
2567             {
2568                 m_process_arch.SetTriple (triple.c_str ());
2569                 if (pointer_byte_size)
2570                 {
2571                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2572                 }
2573             }
2574             else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2575             {
2576                 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2577 
2578                 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2579                 switch (triple.getObjectFormat()) {
2580                     case llvm::Triple::MachO:
2581                         m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2582                         break;
2583                     case llvm::Triple::ELF:
2584                         m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2585                         break;
2586                     case llvm::Triple::COFF:
2587                         m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2588                         break;
2589                     case llvm::Triple::UnknownObjectFormat:
2590                         if (log)
2591                             log->Printf("error: failed to determine target architecture");
2592                         return false;
2593                 }
2594 
2595                 if (pointer_byte_size)
2596                 {
2597                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2598                 }
2599                 if (byte_order != eByteOrderInvalid)
2600                 {
2601                     assert (byte_order == m_process_arch.GetByteOrder());
2602                 }
2603                 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2604                 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2605                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2606                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2607             }
2608             return true;
2609         }
2610     }
2611     else
2612     {
2613         m_qProcessInfo_is_valid = eLazyBoolNo;
2614     }
2615 
2616     return false;
2617 }
2618 
2619 
2620 uint32_t
2621 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2622                                              ProcessInstanceInfoList &process_infos)
2623 {
2624     process_infos.Clear();
2625 
2626     if (m_supports_qfProcessInfo)
2627     {
2628         StreamString packet;
2629         packet.PutCString ("qfProcessInfo");
2630         if (!match_info.MatchAllProcesses())
2631         {
2632             packet.PutChar (':');
2633             const char *name = match_info.GetProcessInfo().GetName();
2634             bool has_name_match = false;
2635             if (name && name[0])
2636             {
2637                 has_name_match = true;
2638                 NameMatchType name_match_type = match_info.GetNameMatchType();
2639                 switch (name_match_type)
2640                 {
2641                 case eNameMatchIgnore:
2642                     has_name_match = false;
2643                     break;
2644 
2645                 case eNameMatchEquals:
2646                     packet.PutCString ("name_match:equals;");
2647                     break;
2648 
2649                 case eNameMatchContains:
2650                     packet.PutCString ("name_match:contains;");
2651                     break;
2652 
2653                 case eNameMatchStartsWith:
2654                     packet.PutCString ("name_match:starts_with;");
2655                     break;
2656 
2657                 case eNameMatchEndsWith:
2658                     packet.PutCString ("name_match:ends_with;");
2659                     break;
2660 
2661                 case eNameMatchRegularExpression:
2662                     packet.PutCString ("name_match:regex;");
2663                     break;
2664                 }
2665                 if (has_name_match)
2666                 {
2667                     packet.PutCString ("name:");
2668                     packet.PutBytesAsRawHex8(name, ::strlen(name));
2669                     packet.PutChar (';');
2670                 }
2671             }
2672 
2673             if (match_info.GetProcessInfo().ProcessIDIsValid())
2674                 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2675             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2676                 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2677             if (match_info.GetProcessInfo().UserIDIsValid())
2678                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2679             if (match_info.GetProcessInfo().GroupIDIsValid())
2680                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2681             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2682                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2683             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2684                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2685             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2686                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2687             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2688             {
2689                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2690                 const llvm::Triple &triple = match_arch.GetTriple();
2691                 packet.PutCString("triple:");
2692                 packet.PutCString(triple.getTriple().c_str());
2693                 packet.PutChar (';');
2694             }
2695         }
2696         StringExtractorGDBRemote response;
2697         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2698         {
2699             do
2700             {
2701                 ProcessInstanceInfo process_info;
2702                 if (!DecodeProcessInfoResponse (response, process_info))
2703                     break;
2704                 process_infos.Append(process_info);
2705                 response.GetStringRef().clear();
2706                 response.SetFilePos(0);
2707             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2708         }
2709         else
2710         {
2711             m_supports_qfProcessInfo = false;
2712             return 0;
2713         }
2714     }
2715     return process_infos.GetSize();
2716 
2717 }
2718 
2719 bool
2720 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2721 {
2722     if (m_supports_qUserName)
2723     {
2724         char packet[32];
2725         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2726         assert (packet_len < (int)sizeof(packet));
2727         StringExtractorGDBRemote response;
2728         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2729         {
2730             if (response.IsNormalResponse())
2731             {
2732                 // Make sure we parsed the right number of characters. The response is
2733                 // the hex encoded user name and should make up the entire packet.
2734                 // If there are any non-hex ASCII bytes, the length won't match below..
2735                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2736                     return true;
2737             }
2738         }
2739         else
2740         {
2741             m_supports_qUserName = false;
2742             return false;
2743         }
2744     }
2745     return false;
2746 
2747 }
2748 
2749 bool
2750 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2751 {
2752     if (m_supports_qGroupName)
2753     {
2754         char packet[32];
2755         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2756         assert (packet_len < (int)sizeof(packet));
2757         StringExtractorGDBRemote response;
2758         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2759         {
2760             if (response.IsNormalResponse())
2761             {
2762                 // Make sure we parsed the right number of characters. The response is
2763                 // the hex encoded group name and should make up the entire packet.
2764                 // If there are any non-hex ASCII bytes, the length won't match below..
2765                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2766                     return true;
2767             }
2768         }
2769         else
2770         {
2771             m_supports_qGroupName = false;
2772             return false;
2773         }
2774     }
2775     return false;
2776 }
2777 
2778 bool
2779 GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2780 {
2781     // Form non-stop packet request
2782     char packet[32];
2783     const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2784     assert(packet_len < (int)sizeof(packet));
2785 
2786     StringExtractorGDBRemote response;
2787     // Send to target
2788     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2789         if (response.IsOKResponse())
2790             return true;
2791 
2792     // Failed or not supported
2793     return false;
2794 
2795 }
2796 
2797 void
2798 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2799 {
2800     uint32_t i;
2801     TimeValue start_time, end_time;
2802     uint64_t total_time_nsec;
2803     if (SendSpeedTestPacket (0, 0))
2804     {
2805         static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2806         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 };
2807         const size_t k_num_send_sizes = llvm::array_lengthof(g_send_sizes);
2808         const size_t k_num_recv_sizes = llvm::array_lengthof(g_recv_sizes);
2809         const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2810         for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
2811         {
2812             const uint32_t send_size = g_send_sizes[send_idx];
2813             for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
2814             {
2815                 const uint32_t recv_size = g_recv_sizes[recv_idx];
2816                 StreamString packet;
2817                 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2818                 uint32_t bytes_left = send_size;
2819                 while (bytes_left > 0)
2820                 {
2821                     if (bytes_left >= 26)
2822                     {
2823                         packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2824                         bytes_left -= 26;
2825                     }
2826                     else
2827                     {
2828                         packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2829                         bytes_left = 0;
2830                     }
2831                 }
2832 
2833                 start_time = TimeValue::Now();
2834                 if (recv_size == 0)
2835                 {
2836                     for (i=0; i<num_packets; ++i)
2837                     {
2838                         StringExtractorGDBRemote response;
2839                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2840                     }
2841                 }
2842                 else
2843                 {
2844                     uint32_t bytes_read = 0;
2845                     while (bytes_read < k_recv_amount)
2846                     {
2847                         StringExtractorGDBRemote response;
2848                         SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2849                         bytes_read += recv_size;
2850                     }
2851                 }
2852                 end_time = TimeValue::Now();
2853                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2854                 if (recv_size == 0)
2855                 {
2856                     float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2857                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2858                             num_packets,
2859                             send_size,
2860                             recv_size,
2861                             total_time_nsec / TimeValue::NanoSecPerSec,
2862                             total_time_nsec % TimeValue::NanoSecPerSec,
2863                             packets_per_second);
2864                 }
2865                 else
2866                 {
2867                     float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2868                     printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2869                             num_packets,
2870                             send_size,
2871                             recv_size,
2872                             total_time_nsec / TimeValue::NanoSecPerSec,
2873                             total_time_nsec % TimeValue::NanoSecPerSec,
2874                             mb_second);
2875                 }
2876             }
2877         }
2878     }
2879 }
2880 
2881 bool
2882 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2883 {
2884     StreamString packet;
2885     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2886     uint32_t bytes_left = send_size;
2887     while (bytes_left > 0)
2888     {
2889         if (bytes_left >= 26)
2890         {
2891             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2892             bytes_left -= 26;
2893         }
2894         else
2895         {
2896             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2897             bytes_left = 0;
2898         }
2899     }
2900 
2901     StringExtractorGDBRemote response;
2902     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)  == PacketResult::Success;
2903 }
2904 
2905 uint16_t
2906 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
2907 {
2908     pid = LLDB_INVALID_PROCESS_ID;
2909     StringExtractorGDBRemote response;
2910     StreamString stream;
2911     stream.PutCString("qLaunchGDBServer;");
2912     std::string hostname;
2913     if (remote_accept_hostname  && remote_accept_hostname[0])
2914         hostname = remote_accept_hostname;
2915     else
2916     {
2917         if (HostInfo::GetHostname(hostname))
2918         {
2919             // Make the GDB server we launch only accept connections from this host
2920             stream.Printf("host:%s;", hostname.c_str());
2921         }
2922         else
2923         {
2924             // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2925             stream.Printf("host:*;");
2926         }
2927     }
2928     const char *packet = stream.GetData();
2929     int packet_len = stream.GetSize();
2930 
2931     // give the process a few seconds to startup
2932     GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
2933 
2934     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2935     {
2936         std::string name;
2937         std::string value;
2938         uint16_t port = 0;
2939         while (response.GetNameColonValue(name, value))
2940         {
2941             if (name.compare("port") == 0)
2942                 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
2943             else if (name.compare("pid") == 0)
2944                 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2945         }
2946         return port;
2947     }
2948     return 0;
2949 }
2950 
2951 bool
2952 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2953 {
2954     StreamString stream;
2955     stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2956     const char *packet = stream.GetData();
2957     int packet_len = stream.GetSize();
2958 
2959     StringExtractorGDBRemote response;
2960     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2961     {
2962         if (response.IsOKResponse())
2963             return true;
2964     }
2965     return false;
2966 }
2967 
2968 bool
2969 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2970 {
2971     if (m_curr_tid == tid)
2972         return true;
2973 
2974     char packet[32];
2975     int packet_len;
2976     if (tid == UINT64_MAX)
2977         packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2978     else
2979         packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2980     assert (packet_len + 1 < (int)sizeof(packet));
2981     StringExtractorGDBRemote response;
2982     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2983     {
2984         if (response.IsOKResponse())
2985         {
2986             m_curr_tid = tid;
2987             return true;
2988         }
2989     }
2990     return false;
2991 }
2992 
2993 bool
2994 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2995 {
2996     if (m_curr_tid_run == tid)
2997         return true;
2998 
2999     char packet[32];
3000     int packet_len;
3001     if (tid == UINT64_MAX)
3002         packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
3003     else
3004         packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3005 
3006     assert (packet_len + 1 < (int)sizeof(packet));
3007     StringExtractorGDBRemote response;
3008     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3009     {
3010         if (response.IsOKResponse())
3011         {
3012             m_curr_tid_run = tid;
3013             return true;
3014         }
3015     }
3016     return false;
3017 }
3018 
3019 bool
3020 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3021 {
3022     if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
3023         return response.IsNormalResponse();
3024     return false;
3025 }
3026 
3027 bool
3028 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
3029 {
3030     if (m_supports_qThreadStopInfo)
3031     {
3032         char packet[256];
3033         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3034         assert (packet_len < (int)sizeof(packet));
3035         if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3036         {
3037             if (response.IsUnsupportedResponse())
3038                 m_supports_qThreadStopInfo = false;
3039             else if (response.IsNormalResponse())
3040                 return true;
3041             else
3042                 return false;
3043         }
3044         else
3045         {
3046             m_supports_qThreadStopInfo = false;
3047         }
3048     }
3049     return false;
3050 }
3051 
3052 
3053 uint8_t
3054 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
3055 {
3056     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3057     if (log)
3058         log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3059                      __FUNCTION__, insert ? "add" : "remove", addr);
3060 
3061     // Check if the stub is known not to support this breakpoint type
3062     if (!SupportsGDBStoppointPacket(type))
3063         return UINT8_MAX;
3064     // Construct the breakpoint packet
3065     char packet[64];
3066     const int packet_len = ::snprintf (packet,
3067                                        sizeof(packet),
3068                                        "%c%i,%" PRIx64 ",%x",
3069                                        insert ? 'Z' : 'z',
3070                                        type,
3071                                        addr,
3072                                        length);
3073     // Check we haven't overwritten the end of the packet buffer
3074     assert (packet_len + 1 < (int)sizeof(packet));
3075     StringExtractorGDBRemote response;
3076     // Try to send the breakpoint packet, and check that it was correctly sent
3077     if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
3078     {
3079         // Receive and OK packet when the breakpoint successfully placed
3080         if (response.IsOKResponse())
3081             return 0;
3082 
3083         // Error while setting breakpoint, send back specific error
3084         if (response.IsErrorResponse())
3085             return response.GetError();
3086 
3087         // Empty packet informs us that breakpoint is not supported
3088         if (response.IsUnsupportedResponse())
3089         {
3090             // Disable this breakpoint type since it is unsupported
3091             switch (type)
3092             {
3093             case eBreakpointSoftware:   m_supports_z0 = false; break;
3094             case eBreakpointHardware:   m_supports_z1 = false; break;
3095             case eWatchpointWrite:      m_supports_z2 = false; break;
3096             case eWatchpointRead:       m_supports_z3 = false; break;
3097             case eWatchpointReadWrite:  m_supports_z4 = false; break;
3098             case eStoppointInvalid:     return UINT8_MAX;
3099             }
3100         }
3101     }
3102     // Signal generic failure
3103     return UINT8_MAX;
3104 }
3105 
3106 size_t
3107 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3108                                                    bool &sequence_mutex_unavailable)
3109 {
3110     Mutex::Locker locker;
3111     thread_ids.clear();
3112 
3113     if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
3114     {
3115         sequence_mutex_unavailable = false;
3116         StringExtractorGDBRemote response;
3117 
3118         PacketResult packet_result;
3119         for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3120              packet_result == PacketResult::Success && response.IsNormalResponse();
3121              packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
3122         {
3123             char ch = response.GetChar();
3124             if (ch == 'l')
3125                 break;
3126             if (ch == 'm')
3127             {
3128                 do
3129                 {
3130                     tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3131 
3132                     if (tid != LLDB_INVALID_THREAD_ID)
3133                     {
3134                         thread_ids.push_back (tid);
3135                     }
3136                     ch = response.GetChar();    // Skip the command separator
3137                 } while (ch == ',');            // Make sure we got a comma separator
3138             }
3139         }
3140     }
3141     else
3142     {
3143 #if defined (LLDB_CONFIGURATION_DEBUG)
3144         // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3145 #else
3146         Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3147         if (log)
3148             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3149 #endif
3150         sequence_mutex_unavailable = true;
3151     }
3152     return thread_ids.size();
3153 }
3154 
3155 lldb::addr_t
3156 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3157 {
3158     if (!IsRunning())
3159     {
3160         StringExtractorGDBRemote response;
3161         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3162         {
3163             if (response.IsNormalResponse())
3164                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3165         }
3166     }
3167     return LLDB_INVALID_ADDRESS;
3168 }
3169 
3170 lldb_private::Error
3171 GDBRemoteCommunicationClient::RunShellCommand (const char *command,           // Shouldn't be NULL
3172                                                const char *working_dir,       // Pass NULL to use the current working directory
3173                                                int *status_ptr,               // Pass NULL if you don't want the process exit status
3174                                                int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
3175                                                std::string *command_output,   // Pass NULL if you don't want the command output
3176                                                uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
3177 {
3178     lldb_private::StreamString stream;
3179     stream.PutCString("qPlatform_shell:");
3180     stream.PutBytesAsRawHex8(command, strlen(command));
3181     stream.PutChar(',');
3182     stream.PutHex32(timeout_sec);
3183     if (working_dir && *working_dir)
3184     {
3185         stream.PutChar(',');
3186         stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
3187     }
3188     const char *packet = stream.GetData();
3189     int packet_len = stream.GetSize();
3190     StringExtractorGDBRemote response;
3191     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3192     {
3193         if (response.GetChar() != 'F')
3194             return Error("malformed reply");
3195         if (response.GetChar() != ',')
3196             return Error("malformed reply");
3197         uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3198         if (exitcode == UINT32_MAX)
3199             return Error("unable to run remote process");
3200         else if (status_ptr)
3201             *status_ptr = exitcode;
3202         if (response.GetChar() != ',')
3203             return Error("malformed reply");
3204         uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3205         if (signo_ptr)
3206             *signo_ptr = signo;
3207         if (response.GetChar() != ',')
3208             return Error("malformed reply");
3209         std::string output;
3210         response.GetEscapedBinaryData(output);
3211         if (command_output)
3212             command_output->assign(output);
3213         return Error();
3214     }
3215     return Error("unable to send packet");
3216 }
3217 
3218 Error
3219 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
3220                                              uint32_t file_permissions)
3221 {
3222     lldb_private::StreamString stream;
3223     stream.PutCString("qPlatform_mkdir:");
3224     stream.PutHex32(file_permissions);
3225     stream.PutChar(',');
3226     stream.PutBytesAsRawHex8(path, strlen(path));
3227     const char *packet = stream.GetData();
3228     int packet_len = stream.GetSize();
3229     StringExtractorGDBRemote response;
3230 
3231     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3232         return Error("failed to send '%s' packet", packet);
3233 
3234     if (response.GetChar() != 'F')
3235         return Error("invalid response to '%s' packet", packet);
3236 
3237     return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3238 }
3239 
3240 Error
3241 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
3242                                                   uint32_t file_permissions)
3243 {
3244     lldb_private::StreamString stream;
3245     stream.PutCString("qPlatform_chmod:");
3246     stream.PutHex32(file_permissions);
3247     stream.PutChar(',');
3248     stream.PutBytesAsRawHex8(path, strlen(path));
3249     const char *packet = stream.GetData();
3250     int packet_len = stream.GetSize();
3251     StringExtractorGDBRemote response;
3252 
3253     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3254         return Error("failed to send '%s' packet", packet);
3255 
3256     if (response.GetChar() != 'F')
3257         return Error("invalid response to '%s' packet", packet);
3258 
3259     return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3260 }
3261 
3262 static uint64_t
3263 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3264                            uint64_t fail_result,
3265                            Error &error)
3266 {
3267     response.SetFilePos(0);
3268     if (response.GetChar() != 'F')
3269         return fail_result;
3270     int32_t result = response.GetS32 (-2);
3271     if (result == -2)
3272         return fail_result;
3273     if (response.GetChar() == ',')
3274     {
3275         int result_errno = response.GetS32 (-2);
3276         if (result_errno != -2)
3277             error.SetError(result_errno, eErrorTypePOSIX);
3278         else
3279             error.SetError(-1, eErrorTypeGeneric);
3280     }
3281     else
3282         error.Clear();
3283     return  result;
3284 }
3285 lldb::user_id_t
3286 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3287                                         uint32_t flags,
3288                                         mode_t mode,
3289                                         Error &error)
3290 {
3291     lldb_private::StreamString stream;
3292     stream.PutCString("vFile:open:");
3293     std::string path (file_spec.GetPath(false));
3294     if (path.empty())
3295         return UINT64_MAX;
3296     stream.PutCStringAsRawHex8(path.c_str());
3297     stream.PutChar(',');
3298     stream.PutHex32(flags);
3299     stream.PutChar(',');
3300     stream.PutHex32(mode);
3301     const char* packet = stream.GetData();
3302     int packet_len = stream.GetSize();
3303     StringExtractorGDBRemote response;
3304     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3305     {
3306         return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3307     }
3308     return UINT64_MAX;
3309 }
3310 
3311 bool
3312 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3313                                          Error &error)
3314 {
3315     lldb_private::StreamString stream;
3316     stream.Printf("vFile:close:%i", (int)fd);
3317     const char* packet = stream.GetData();
3318     int packet_len = stream.GetSize();
3319     StringExtractorGDBRemote response;
3320     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3321     {
3322         return ParseHostIOPacketResponse (response, -1, error) == 0;
3323     }
3324     return false;
3325 }
3326 
3327 // Extension of host I/O packets to get the file size.
3328 lldb::user_id_t
3329 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3330 {
3331     lldb_private::StreamString stream;
3332     stream.PutCString("vFile:size:");
3333     std::string path (file_spec.GetPath());
3334     stream.PutCStringAsRawHex8(path.c_str());
3335     const char* packet = stream.GetData();
3336     int packet_len = stream.GetSize();
3337     StringExtractorGDBRemote response;
3338     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3339     {
3340         if (response.GetChar() != 'F')
3341             return UINT64_MAX;
3342         uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3343         return retcode;
3344     }
3345     return UINT64_MAX;
3346 }
3347 
3348 Error
3349 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
3350 {
3351     Error error;
3352     lldb_private::StreamString stream;
3353     stream.PutCString("vFile:mode:");
3354     stream.PutCStringAsRawHex8(path);
3355     const char* packet = stream.GetData();
3356     int packet_len = stream.GetSize();
3357     StringExtractorGDBRemote response;
3358     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3359     {
3360         if (response.GetChar() != 'F')
3361         {
3362             error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3363         }
3364         else
3365         {
3366             const uint32_t mode = response.GetS32(-1);
3367             if (static_cast<int32_t>(mode) == -1)
3368             {
3369                 if (response.GetChar() == ',')
3370                 {
3371                     int response_errno = response.GetS32(-1);
3372                     if (response_errno > 0)
3373                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3374                     else
3375                         error.SetErrorToGenericError();
3376                 }
3377                 else
3378                     error.SetErrorToGenericError();
3379             }
3380             else
3381             {
3382                 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3383             }
3384         }
3385     }
3386     else
3387     {
3388         error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3389     }
3390     return error;
3391 }
3392 
3393 uint64_t
3394 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3395                                         uint64_t offset,
3396                                         void *dst,
3397                                         uint64_t dst_len,
3398                                         Error &error)
3399 {
3400     lldb_private::StreamString stream;
3401     stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3402     const char* packet = stream.GetData();
3403     int packet_len = stream.GetSize();
3404     StringExtractorGDBRemote response;
3405     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3406     {
3407         if (response.GetChar() != 'F')
3408             return 0;
3409         uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3410         if (retcode == UINT32_MAX)
3411             return retcode;
3412         const char next = (response.Peek() ? *response.Peek() : 0);
3413         if (next == ',')
3414             return 0;
3415         if (next == ';')
3416         {
3417             response.GetChar(); // skip the semicolon
3418             std::string buffer;
3419             if (response.GetEscapedBinaryData(buffer))
3420             {
3421                 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3422                 if (data_to_write > 0)
3423                     memcpy(dst, &buffer[0], data_to_write);
3424                 return data_to_write;
3425             }
3426         }
3427     }
3428     return 0;
3429 }
3430 
3431 uint64_t
3432 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3433                                          uint64_t offset,
3434                                          const void* src,
3435                                          uint64_t src_len,
3436                                          Error &error)
3437 {
3438     lldb_private::StreamGDBRemote stream;
3439     stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3440     stream.PutEscapedBytes(src, src_len);
3441     const char* packet = stream.GetData();
3442     int packet_len = stream.GetSize();
3443     StringExtractorGDBRemote response;
3444     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3445     {
3446         if (response.GetChar() != 'F')
3447         {
3448             error.SetErrorStringWithFormat("write file failed");
3449             return 0;
3450         }
3451         uint64_t bytes_written = response.GetU64(UINT64_MAX);
3452         if (bytes_written == UINT64_MAX)
3453         {
3454             error.SetErrorToGenericError();
3455             if (response.GetChar() == ',')
3456             {
3457                 int response_errno = response.GetS32(-1);
3458                 if (response_errno > 0)
3459                     error.SetError(response_errno, lldb::eErrorTypePOSIX);
3460             }
3461             return 0;
3462         }
3463         return bytes_written;
3464     }
3465     else
3466     {
3467         error.SetErrorString ("failed to send vFile:pwrite packet");
3468     }
3469     return 0;
3470 }
3471 
3472 Error
3473 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3474 {
3475     Error error;
3476     lldb_private::StreamGDBRemote stream;
3477     stream.PutCString("vFile:symlink:");
3478     // the unix symlink() command reverses its parameters where the dst if first,
3479     // so we follow suit here
3480     stream.PutCStringAsRawHex8(dst);
3481     stream.PutChar(',');
3482     stream.PutCStringAsRawHex8(src);
3483     const char* packet = stream.GetData();
3484     int packet_len = stream.GetSize();
3485     StringExtractorGDBRemote response;
3486     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3487     {
3488         if (response.GetChar() == 'F')
3489         {
3490             uint32_t result = response.GetU32(UINT32_MAX);
3491             if (result != 0)
3492             {
3493                 error.SetErrorToGenericError();
3494                 if (response.GetChar() == ',')
3495                 {
3496                     int response_errno = response.GetS32(-1);
3497                     if (response_errno > 0)
3498                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3499                 }
3500             }
3501         }
3502         else
3503         {
3504             // Should have returned with 'F<result>[,<errno>]'
3505             error.SetErrorStringWithFormat("symlink failed");
3506         }
3507     }
3508     else
3509     {
3510         error.SetErrorString ("failed to send vFile:symlink packet");
3511     }
3512     return error;
3513 }
3514 
3515 Error
3516 GDBRemoteCommunicationClient::Unlink (const char *path)
3517 {
3518     Error error;
3519     lldb_private::StreamGDBRemote stream;
3520     stream.PutCString("vFile:unlink:");
3521     // the unix symlink() command reverses its parameters where the dst if first,
3522     // so we follow suit here
3523     stream.PutCStringAsRawHex8(path);
3524     const char* packet = stream.GetData();
3525     int packet_len = stream.GetSize();
3526     StringExtractorGDBRemote response;
3527     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3528     {
3529         if (response.GetChar() == 'F')
3530         {
3531             uint32_t result = response.GetU32(UINT32_MAX);
3532             if (result != 0)
3533             {
3534                 error.SetErrorToGenericError();
3535                 if (response.GetChar() == ',')
3536                 {
3537                     int response_errno = response.GetS32(-1);
3538                     if (response_errno > 0)
3539                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3540                 }
3541             }
3542         }
3543         else
3544         {
3545             // Should have returned with 'F<result>[,<errno>]'
3546             error.SetErrorStringWithFormat("unlink failed");
3547         }
3548     }
3549     else
3550     {
3551         error.SetErrorString ("failed to send vFile:unlink packet");
3552     }
3553     return error;
3554 }
3555 
3556 // Extension of host I/O packets to get whether a file exists.
3557 bool
3558 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3559 {
3560     lldb_private::StreamString stream;
3561     stream.PutCString("vFile:exists:");
3562     std::string path (file_spec.GetPath());
3563     stream.PutCStringAsRawHex8(path.c_str());
3564     const char* packet = stream.GetData();
3565     int packet_len = stream.GetSize();
3566     StringExtractorGDBRemote response;
3567     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3568     {
3569         if (response.GetChar() != 'F')
3570             return false;
3571         if (response.GetChar() != ',')
3572             return false;
3573         bool retcode = (response.GetChar() != '0');
3574         return retcode;
3575     }
3576     return false;
3577 }
3578 
3579 bool
3580 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3581                                             uint64_t &high,
3582                                             uint64_t &low)
3583 {
3584     lldb_private::StreamString stream;
3585     stream.PutCString("vFile:MD5:");
3586     std::string path (file_spec.GetPath());
3587     stream.PutCStringAsRawHex8(path.c_str());
3588     const char* packet = stream.GetData();
3589     int packet_len = stream.GetSize();
3590     StringExtractorGDBRemote response;
3591     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3592     {
3593         if (response.GetChar() != 'F')
3594             return false;
3595         if (response.GetChar() != ',')
3596             return false;
3597         if (response.Peek() && *response.Peek() == 'x')
3598             return false;
3599         low = response.GetHexMaxU64(false, UINT64_MAX);
3600         high = response.GetHexMaxU64(false, UINT64_MAX);
3601         return true;
3602     }
3603     return false;
3604 }
3605 
3606 bool
3607 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3608 {
3609     // Some targets have issues with g/G packets and we need to avoid using them
3610     if (m_avoid_g_packets == eLazyBoolCalculate)
3611     {
3612         if (process)
3613         {
3614             m_avoid_g_packets = eLazyBoolNo;
3615             const ArchSpec &arch = process->GetTarget().GetArchitecture();
3616             if (arch.IsValid()
3617                 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3618                 && arch.GetTriple().getOS() == llvm::Triple::IOS
3619                 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
3620             {
3621                 m_avoid_g_packets = eLazyBoolYes;
3622                 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3623                 if (gdb_server_version != 0)
3624                 {
3625                     const char *gdb_server_name = GetGDBServerProgramName();
3626                     if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3627                     {
3628                         if (gdb_server_version >= 310)
3629                             m_avoid_g_packets = eLazyBoolNo;
3630                     }
3631                 }
3632             }
3633         }
3634     }
3635     return m_avoid_g_packets == eLazyBoolYes;
3636 }
3637 
3638 bool
3639 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3640 {
3641     Mutex::Locker locker;
3642     if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3643     {
3644         const bool thread_suffix_supported = GetThreadSuffixSupported();
3645 
3646         if (thread_suffix_supported || SetCurrentThread(tid))
3647         {
3648             char packet[64];
3649             int packet_len = 0;
3650             if (thread_suffix_supported)
3651                 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3652             else
3653                 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3654             assert (packet_len < ((int)sizeof(packet) - 1));
3655             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3656         }
3657     }
3658     return false;
3659 
3660 }
3661 
3662 
3663 bool
3664 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3665 {
3666     Mutex::Locker locker;
3667     if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3668     {
3669         const bool thread_suffix_supported = GetThreadSuffixSupported();
3670 
3671         if (thread_suffix_supported || SetCurrentThread(tid))
3672         {
3673             char packet[64];
3674             int packet_len = 0;
3675             // Get all registers in one packet
3676             if (thread_suffix_supported)
3677                 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3678             else
3679                 packet_len = ::snprintf (packet, sizeof(packet), "g");
3680             assert (packet_len < ((int)sizeof(packet) - 1));
3681             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3682         }
3683     }
3684     return false;
3685 }
3686 bool
3687 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3688 {
3689     save_id = 0; // Set to invalid save ID
3690     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3691         return false;
3692 
3693     m_supports_QSaveRegisterState = eLazyBoolYes;
3694     Mutex::Locker locker;
3695     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3696     {
3697         const bool thread_suffix_supported = GetThreadSuffixSupported();
3698         if (thread_suffix_supported || SetCurrentThread(tid))
3699         {
3700             char packet[256];
3701             if (thread_suffix_supported)
3702                 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3703             else
3704                 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
3705 
3706             StringExtractorGDBRemote response;
3707 
3708             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3709             {
3710                 if (response.IsUnsupportedResponse())
3711                 {
3712                     // This packet isn't supported, don't try calling it again
3713                     m_supports_QSaveRegisterState = eLazyBoolNo;
3714                 }
3715 
3716                 const uint32_t response_save_id = response.GetU32(0);
3717                 if (response_save_id != 0)
3718                 {
3719                     save_id = response_save_id;
3720                     return true;
3721                 }
3722             }
3723         }
3724     }
3725     return false;
3726 }
3727 
3728 bool
3729 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3730 {
3731     // We use the "m_supports_QSaveRegisterState" variable here because the
3732     // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3733     // order to be useful
3734     if (m_supports_QSaveRegisterState == eLazyBoolNo)
3735         return false;
3736 
3737     Mutex::Locker locker;
3738     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3739     {
3740         const bool thread_suffix_supported = GetThreadSuffixSupported();
3741         if (thread_suffix_supported || SetCurrentThread(tid))
3742         {
3743             char packet[256];
3744             if (thread_suffix_supported)
3745                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3746             else
3747                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3748 
3749             StringExtractorGDBRemote response;
3750 
3751             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3752             {
3753                 if (response.IsOKResponse())
3754                 {
3755                     return true;
3756                 }
3757                 else if (response.IsUnsupportedResponse())
3758                 {
3759                     // This packet isn't supported, don't try calling this packet or
3760                     // QSaveRegisterState again...
3761                     m_supports_QSaveRegisterState = eLazyBoolNo;
3762                 }
3763             }
3764         }
3765     }
3766     return false;
3767 }
3768 
3769 bool
3770 GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
3771                                              const lldb_private::ArchSpec& arch_spec,
3772                                              ModuleSpec &module_spec)
3773 {
3774     std::string module_path = module_file_spec.GetPath (false);
3775     if (module_path.empty ())
3776         return false;
3777 
3778     StreamString packet;
3779     packet.PutCString("qModuleInfo:");
3780     packet.PutCStringAsRawHex8(module_path.c_str());
3781     packet.PutCString(";");
3782     const auto& triple = arch_spec.GetTriple().getTriple();
3783     packet.PutBytesAsRawHex8(triple.c_str(), triple.size());
3784 
3785     StringExtractorGDBRemote response;
3786     if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3787         return false;
3788 
3789     if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
3790         return false;
3791 
3792     std::string name;
3793     std::string value;
3794     bool success;
3795     StringExtractor extractor;
3796 
3797     module_spec.Clear ();
3798     module_spec.GetFileSpec () = module_file_spec;
3799 
3800     while (response.GetNameColonValue (name, value))
3801     {
3802         if (name == "uuid" || name == "md5")
3803         {
3804             extractor.GetStringRef ().swap (value);
3805             extractor.SetFilePos (0);
3806             extractor.GetHexByteString (value);
3807             module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3808         }
3809         else if (name == "triple")
3810         {
3811             extractor.GetStringRef ().swap (value);
3812             extractor.SetFilePos (0);
3813             extractor.GetHexByteString (value);
3814             module_spec.GetArchitecture().SetTriple (value.c_str ());
3815         }
3816         else if (name == "file_offset")
3817         {
3818             const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3819             if (success)
3820                 module_spec.SetObjectOffset (ival);
3821         }
3822         else if (name == "file_size")
3823         {
3824             const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3825             if (success)
3826                 module_spec.SetObjectSize (ival);
3827         }
3828         else if (name == "file_path")
3829         {
3830             extractor.GetStringRef ().swap (value);
3831             extractor.SetFilePos (0);
3832             extractor.GetHexByteString (value);
3833             module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
3834         }
3835     }
3836 
3837     return true;
3838 }
3839 
3840 // query the target remote for extended information using the qXfer packet
3841 //
3842 // example: object='features', annex='target.xml', out=<xml output>
3843 // return:  'true'  on success
3844 //          'false' on failure (err set)
3845 bool
3846 GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3847                                               const lldb_private::ConstString annex,
3848                                               std::string & out,
3849                                               lldb_private::Error & err) {
3850 
3851     std::stringstream output;
3852     StringExtractorGDBRemote chunk;
3853 
3854     const int size   = 0xfff;
3855     int       offset = 0;
3856     bool      active = true;
3857 
3858     // loop until all data has been read
3859     while ( active ) {
3860 
3861         // send query extended feature packet
3862         std::stringstream packet;
3863         packet << "qXfer:"
3864                << object.AsCString( ) << ":read:"
3865                << annex.AsCString( )  << ":"
3866                << std::hex << offset  << ","
3867                << std::hex << size;
3868 
3869         GDBRemoteCommunication::PacketResult res =
3870             SendPacketAndWaitForResponse( packet.str().c_str(),
3871                                           chunk,
3872                                           false );
3873 
3874         if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3875             err.SetErrorString( "Error sending $qXfer packet" );
3876             return false;
3877         }
3878 
3879         const std::string & str = chunk.GetStringRef( );
3880         if ( str.length() == 0 ) {
3881             // should have some data in chunk
3882             err.SetErrorString( "Empty response from $qXfer packet" );
3883             return false;
3884         }
3885 
3886         // check packet code
3887         switch ( str[0] ) {
3888             // last chunk
3889         case ( 'l' ):
3890             active = false;
3891             // fall through intentional
3892 
3893             // more chunks
3894         case ( 'm' ) :
3895             if ( str.length() > 1 )
3896                 output << &str[1];
3897             offset += size;
3898             break;
3899 
3900             // unknown chunk
3901         default:
3902             err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3903             return false;
3904         }
3905     }
3906 
3907     out = output.str( );
3908     err.Success( );
3909     return true;
3910 }
3911