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