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             std::string elf_abi;
2860             uint32_t pointer_byte_size = 0;
2861             StringExtractor extractor;
2862             ByteOrder byte_order = eByteOrderInvalid;
2863             uint32_t num_keys_decoded = 0;
2864             lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2865             while (response.GetNameColonValue(name, value))
2866             {
2867                 if (name.compare("cputype") == 0)
2868                 {
2869                     cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2870                     if (cpu != LLDB_INVALID_CPUTYPE)
2871                         ++num_keys_decoded;
2872                 }
2873                 else if (name.compare("cpusubtype") == 0)
2874                 {
2875                     sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2876                     if (sub != 0)
2877                         ++num_keys_decoded;
2878                 }
2879                 else if (name.compare("triple") == 0)
2880                 {
2881                     StringExtractor extractor;
2882                     extractor.GetStringRef().swap(value);
2883                     extractor.SetFilePos(0);
2884                     extractor.GetHexByteString (triple);
2885                     ++num_keys_decoded;
2886                 }
2887                 else if (name.compare("ostype") == 0)
2888                 {
2889                     os_name.swap (value);
2890                     ++num_keys_decoded;
2891                 }
2892                 else if (name.compare("vendor") == 0)
2893                 {
2894                     vendor_name.swap(value);
2895                     ++num_keys_decoded;
2896                 }
2897                 else if (name.compare("endian") == 0)
2898                 {
2899                     ++num_keys_decoded;
2900                     if (value.compare("little") == 0)
2901                         byte_order = eByteOrderLittle;
2902                     else if (value.compare("big") == 0)
2903                         byte_order = eByteOrderBig;
2904                     else if (value.compare("pdp") == 0)
2905                         byte_order = eByteOrderPDP;
2906                     else
2907                         --num_keys_decoded;
2908                 }
2909                 else if (name.compare("ptrsize") == 0)
2910                 {
2911                     pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2912                     if (pointer_byte_size != 0)
2913                         ++num_keys_decoded;
2914                 }
2915                 else if (name.compare("pid") == 0)
2916                 {
2917                     pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
2918                     if (pid != LLDB_INVALID_PROCESS_ID)
2919                         ++num_keys_decoded;
2920                 }
2921                 else if (name.compare("elf_abi") == 0)
2922                 {
2923                     elf_abi = value;
2924                     ++num_keys_decoded;
2925                 }
2926             }
2927             if (num_keys_decoded > 0)
2928                 m_qProcessInfo_is_valid = eLazyBoolYes;
2929             if (pid != LLDB_INVALID_PROCESS_ID)
2930             {
2931                 m_curr_pid_is_valid = eLazyBoolYes;
2932                 m_curr_pid = pid;
2933             }
2934 
2935             // Set the ArchSpec from the triple if we have it.
2936             if (!triple.empty ())
2937             {
2938                 m_process_arch.SetTriple (triple.c_str ());
2939                 m_process_arch.SetFlags(elf_abi);
2940                 if (pointer_byte_size)
2941                 {
2942                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2943                 }
2944             }
2945             else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2946             {
2947                 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2948 
2949                 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2950                 switch (triple.getObjectFormat()) {
2951                     case llvm::Triple::MachO:
2952                         m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2953                         break;
2954                     case llvm::Triple::ELF:
2955                         m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2956                         break;
2957                     case llvm::Triple::COFF:
2958                         m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2959                         break;
2960                     case llvm::Triple::UnknownObjectFormat:
2961                         if (log)
2962                             log->Printf("error: failed to determine target architecture");
2963                         return false;
2964                 }
2965 
2966                 if (pointer_byte_size)
2967                 {
2968                     assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2969                 }
2970                 if (byte_order != eByteOrderInvalid)
2971                 {
2972                     assert (byte_order == m_process_arch.GetByteOrder());
2973                 }
2974                 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2975                 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2976                 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2977                 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2978             }
2979             return true;
2980         }
2981     }
2982     else
2983     {
2984         m_qProcessInfo_is_valid = eLazyBoolNo;
2985     }
2986 
2987     return false;
2988 }
2989 
2990 
2991 uint32_t
2992 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2993                                              ProcessInstanceInfoList &process_infos)
2994 {
2995     process_infos.Clear();
2996 
2997     if (m_supports_qfProcessInfo)
2998     {
2999         StreamString packet;
3000         packet.PutCString ("qfProcessInfo");
3001         if (!match_info.MatchAllProcesses())
3002         {
3003             packet.PutChar (':');
3004             const char *name = match_info.GetProcessInfo().GetName();
3005             bool has_name_match = false;
3006             if (name && name[0])
3007             {
3008                 has_name_match = true;
3009                 NameMatchType name_match_type = match_info.GetNameMatchType();
3010                 switch (name_match_type)
3011                 {
3012                 case eNameMatchIgnore:
3013                     has_name_match = false;
3014                     break;
3015 
3016                 case eNameMatchEquals:
3017                     packet.PutCString ("name_match:equals;");
3018                     break;
3019 
3020                 case eNameMatchContains:
3021                     packet.PutCString ("name_match:contains;");
3022                     break;
3023 
3024                 case eNameMatchStartsWith:
3025                     packet.PutCString ("name_match:starts_with;");
3026                     break;
3027 
3028                 case eNameMatchEndsWith:
3029                     packet.PutCString ("name_match:ends_with;");
3030                     break;
3031 
3032                 case eNameMatchRegularExpression:
3033                     packet.PutCString ("name_match:regex;");
3034                     break;
3035                 }
3036                 if (has_name_match)
3037                 {
3038                     packet.PutCString ("name:");
3039                     packet.PutBytesAsRawHex8(name, ::strlen(name));
3040                     packet.PutChar (';');
3041                 }
3042             }
3043 
3044             if (match_info.GetProcessInfo().ProcessIDIsValid())
3045                 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
3046             if (match_info.GetProcessInfo().ParentProcessIDIsValid())
3047                 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
3048             if (match_info.GetProcessInfo().UserIDIsValid())
3049                 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3050             if (match_info.GetProcessInfo().GroupIDIsValid())
3051                 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
3052             if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3053                 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3054             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3055                 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3056             if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3057                 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3058             if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3059             {
3060                 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3061                 const llvm::Triple &triple = match_arch.GetTriple();
3062                 packet.PutCString("triple:");
3063                 packet.PutCString(triple.getTriple().c_str());
3064                 packet.PutChar (';');
3065             }
3066         }
3067         StringExtractorGDBRemote response;
3068         // Increase timeout as the first qfProcessInfo packet takes a long time
3069         // on Android. The value of 1min was arrived at empirically.
3070         GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
3071         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
3072         {
3073             do
3074             {
3075                 ProcessInstanceInfo process_info;
3076                 if (!DecodeProcessInfoResponse (response, process_info))
3077                     break;
3078                 process_infos.Append(process_info);
3079                 response.GetStringRef().clear();
3080                 response.SetFilePos(0);
3081             } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
3082         }
3083         else
3084         {
3085             m_supports_qfProcessInfo = false;
3086             return 0;
3087         }
3088     }
3089     return process_infos.GetSize();
3090 
3091 }
3092 
3093 bool
3094 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3095 {
3096     if (m_supports_qUserName)
3097     {
3098         char packet[32];
3099         const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
3100         assert (packet_len < (int)sizeof(packet));
3101         StringExtractorGDBRemote response;
3102         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3103         {
3104             if (response.IsNormalResponse())
3105             {
3106                 // Make sure we parsed the right number of characters. The response is
3107                 // the hex encoded user name and should make up the entire packet.
3108                 // If there are any non-hex ASCII bytes, the length won't match below..
3109                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3110                     return true;
3111             }
3112         }
3113         else
3114         {
3115             m_supports_qUserName = false;
3116             return false;
3117         }
3118     }
3119     return false;
3120 
3121 }
3122 
3123 bool
3124 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3125 {
3126     if (m_supports_qGroupName)
3127     {
3128         char packet[32];
3129         const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
3130         assert (packet_len < (int)sizeof(packet));
3131         StringExtractorGDBRemote response;
3132         if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3133         {
3134             if (response.IsNormalResponse())
3135             {
3136                 // Make sure we parsed the right number of characters. The response is
3137                 // the hex encoded group name and should make up the entire packet.
3138                 // If there are any non-hex ASCII bytes, the length won't match below..
3139                 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3140                     return true;
3141             }
3142         }
3143         else
3144         {
3145             m_supports_qGroupName = false;
3146             return false;
3147         }
3148     }
3149     return false;
3150 }
3151 
3152 bool
3153 GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3154 {
3155     // Form non-stop packet request
3156     char packet[32];
3157     const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3158     assert(packet_len < (int)sizeof(packet));
3159 
3160     StringExtractorGDBRemote response;
3161     // Send to target
3162     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3163         if (response.IsOKResponse())
3164             return true;
3165 
3166     // Failed or not supported
3167     return false;
3168 
3169 }
3170 
3171 static void
3172 MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3173 {
3174     packet.Clear();
3175     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3176     uint32_t bytes_left = send_size;
3177     while (bytes_left > 0)
3178     {
3179         if (bytes_left >= 26)
3180         {
3181             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3182             bytes_left -= 26;
3183         }
3184         else
3185         {
3186             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3187             bytes_left = 0;
3188         }
3189     }
3190 }
3191 
3192 template<typename T>
3193 T calculate_standard_deviation(const std::vector<T> &v)
3194 {
3195     T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3196     T mean =  sum / (T)v.size();
3197     T accum = T(0);
3198     std::for_each (std::begin(v), std::end(v), [&](const T d) {
3199         T delta = d - mean;
3200         accum += delta * delta;
3201     });
3202 
3203     T stdev = sqrt(accum / (v.size()-1));
3204     return stdev;
3205 }
3206 
3207 void
3208 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
3209 {
3210     uint32_t i;
3211     TimeValue start_time, end_time;
3212     uint64_t total_time_nsec;
3213     if (SendSpeedTestPacket (0, 0))
3214     {
3215         StreamString packet;
3216         if (json)
3217             strm.Printf("{ \"packet_speeds\" : {\n    \"num_packets\" : %u,\n    \"results\" : [", num_packets);
3218         else
3219             strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3220         strm.Flush();
3221 
3222         uint32_t result_idx = 0;
3223         uint32_t send_size;
3224         std::vector<float> packet_times;
3225 
3226         for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3227         {
3228             for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3229             {
3230                 MakeSpeedTestPacket (packet, send_size, recv_size);
3231 
3232                 packet_times.clear();
3233                 // Test how long it takes to send 'num_packets' packets
3234                 start_time = TimeValue::Now();
3235                 for (i=0; i<num_packets; ++i)
3236                 {
3237                     TimeValue packet_start_time = TimeValue::Now();
3238                     StringExtractorGDBRemote response;
3239                     SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3240                     TimeValue packet_end_time = TimeValue::Now();
3241                     uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3242                     packet_times.push_back((float)packet_time_nsec);
3243                 }
3244                 end_time = TimeValue::Now();
3245                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3246 
3247                 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3248                 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3249                 float average_ms_per_packet = total_ms / num_packets;
3250                 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3251                 if (json)
3252                 {
3253                     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);
3254                     ++result_idx;
3255                 }
3256                 else
3257                 {
3258                     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",
3259                                  send_size,
3260                                  recv_size,
3261                                  total_time_nsec / TimeValue::NanoSecPerSec,
3262                                  total_time_nsec % TimeValue::NanoSecPerSec,
3263                                  packets_per_second,
3264                                  average_ms_per_packet,
3265                                  standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
3266                 }
3267                 strm.Flush();
3268             }
3269         }
3270 
3271         const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3272 
3273         const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3274         if (json)
3275             strm.Printf("\n    ]\n  },\n  \"download_speed\" : {\n    \"byte_size\" : %" PRIu64 ",\n    \"results\" : [", k_recv_amount);
3276         else
3277             strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3278         strm.Flush();
3279         send_size = 0;
3280         result_idx = 0;
3281         for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3282         {
3283             MakeSpeedTestPacket (packet, send_size, recv_size);
3284 
3285             // If we have a receive size, test how long it takes to receive 4MB of data
3286             if (recv_size > 0)
3287             {
3288                 start_time = TimeValue::Now();
3289                 uint32_t bytes_read = 0;
3290                 uint32_t packet_count = 0;
3291                 while (bytes_read < k_recv_amount)
3292                 {
3293                     StringExtractorGDBRemote response;
3294                     SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3295                     bytes_read += recv_size;
3296                     ++packet_count;
3297                 }
3298                 end_time = TimeValue::Now();
3299                 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3300                 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3301                 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3302                 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3303                 float average_ms_per_packet = total_ms / packet_count;
3304 
3305                 if (json)
3306                 {
3307                     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);
3308                     ++result_idx;
3309                 }
3310                 else
3311                 {
3312                     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",
3313                                  send_size,
3314                                  recv_size,
3315                                  packet_count,
3316                                  k_recv_amount_mb,
3317                                  total_time_nsec / TimeValue::NanoSecPerSec,
3318                                  total_time_nsec % TimeValue::NanoSecPerSec,
3319                                  mb_second,
3320                                  packets_per_second,
3321                                  average_ms_per_packet);
3322                 }
3323                 strm.Flush();
3324             }
3325         }
3326         if (json)
3327             strm.Printf("\n    ]\n  }\n}\n");
3328         else
3329             strm.EOL();
3330     }
3331 }
3332 
3333 bool
3334 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3335 {
3336     StreamString packet;
3337     packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3338     uint32_t bytes_left = send_size;
3339     while (bytes_left > 0)
3340     {
3341         if (bytes_left >= 26)
3342         {
3343             packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3344             bytes_left -= 26;
3345         }
3346         else
3347         {
3348             packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3349             bytes_left = 0;
3350         }
3351     }
3352 
3353     StringExtractorGDBRemote response;
3354     return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)  == PacketResult::Success;
3355 }
3356 
3357 bool
3358 GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3359                                                lldb::pid_t &pid,
3360                                                uint16_t &port,
3361                                                std::string &socket_name)
3362 {
3363     pid = LLDB_INVALID_PROCESS_ID;
3364     port = 0;
3365     socket_name.clear();
3366 
3367     StringExtractorGDBRemote response;
3368     StreamString stream;
3369     stream.PutCString("qLaunchGDBServer;");
3370     std::string hostname;
3371     if (remote_accept_hostname  && remote_accept_hostname[0])
3372         hostname = remote_accept_hostname;
3373     else
3374     {
3375         if (HostInfo::GetHostname(hostname))
3376         {
3377             // Make the GDB server we launch only accept connections from this host
3378             stream.Printf("host:%s;", hostname.c_str());
3379         }
3380         else
3381         {
3382             // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3383             stream.Printf("host:*;");
3384         }
3385     }
3386     const char *packet = stream.GetData();
3387     int packet_len = stream.GetSize();
3388 
3389     // give the process a few seconds to startup
3390     GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3391 
3392     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3393     {
3394         std::string name;
3395         std::string value;
3396         StringExtractor extractor;
3397         while (response.GetNameColonValue(name, value))
3398         {
3399             if (name.compare("port") == 0)
3400                 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
3401             else if (name.compare("pid") == 0)
3402                 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
3403             else if (name.compare("socket_name") == 0)
3404             {
3405                 extractor.GetStringRef().swap(value);
3406                 extractor.SetFilePos(0);
3407                 extractor.GetHexByteString(value);
3408 
3409                 socket_name = value;
3410             }
3411         }
3412         return true;
3413     }
3414     return false;
3415 }
3416 
3417 size_t
3418 GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
3419 {
3420     connection_urls.clear();
3421 
3422     StringExtractorGDBRemote response;
3423     if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
3424         return 0;
3425 
3426     StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
3427     if (!data)
3428         return 0;
3429 
3430     StructuredData::Array* array = data->GetAsArray();
3431     if (!array)
3432         return 0;
3433 
3434     for (size_t i = 0, count = array->GetSize(); i < count; ++i)
3435     {
3436         StructuredData::Dictionary* element = nullptr;
3437         if (!array->GetItemAtIndexAsDictionary(i, element))
3438             continue;
3439 
3440         uint16_t port = 0;
3441         if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
3442             port = port_osp->GetIntegerValue(0);
3443 
3444         std::string socket_name;
3445         if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
3446             socket_name = socket_name_osp->GetStringValue();
3447 
3448         if (port != 0 || !socket_name.empty())
3449             connection_urls.emplace_back(port, socket_name);
3450     }
3451     return connection_urls.size();
3452 }
3453 
3454 bool
3455 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3456 {
3457     StreamString stream;
3458     stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3459     const char *packet = stream.GetData();
3460     int packet_len = stream.GetSize();
3461 
3462     StringExtractorGDBRemote response;
3463     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3464     {
3465         if (response.IsOKResponse())
3466             return true;
3467     }
3468     return false;
3469 }
3470 
3471 bool
3472 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
3473 {
3474     if (m_curr_tid == tid)
3475         return true;
3476 
3477     char packet[32];
3478     int packet_len;
3479     if (tid == UINT64_MAX)
3480         packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
3481     else
3482         packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
3483     assert (packet_len + 1 < (int)sizeof(packet));
3484     StringExtractorGDBRemote response;
3485     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3486     {
3487         if (response.IsOKResponse())
3488         {
3489             m_curr_tid = tid;
3490             return true;
3491         }
3492 
3493         /*
3494          * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3495          * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3496          * give us pid and/or tid. Assume pid=tid=1 in such cases.
3497         */
3498         if (response.IsUnsupportedResponse() && IsConnected())
3499         {
3500             m_curr_tid = 1;
3501             return true;
3502         }
3503     }
3504     return false;
3505 }
3506 
3507 bool
3508 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
3509 {
3510     if (m_curr_tid_run == tid)
3511         return true;
3512 
3513     char packet[32];
3514     int packet_len;
3515     if (tid == UINT64_MAX)
3516         packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
3517     else
3518         packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3519 
3520     assert (packet_len + 1 < (int)sizeof(packet));
3521     StringExtractorGDBRemote response;
3522     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3523     {
3524         if (response.IsOKResponse())
3525         {
3526             m_curr_tid_run = tid;
3527             return true;
3528         }
3529 
3530         /*
3531          * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3532          * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3533          * give us pid and/or tid. Assume pid=tid=1 in such cases.
3534         */
3535         if (response.IsUnsupportedResponse() && IsConnected())
3536         {
3537             m_curr_tid_run = 1;
3538             return true;
3539         }
3540     }
3541     return false;
3542 }
3543 
3544 bool
3545 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3546 {
3547     if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
3548         return response.IsNormalResponse();
3549     return false;
3550 }
3551 
3552 bool
3553 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
3554 {
3555     if (m_supports_qThreadStopInfo)
3556     {
3557         char packet[256];
3558         int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3559         assert (packet_len < (int)sizeof(packet));
3560         if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3561         {
3562             if (response.IsUnsupportedResponse())
3563                 m_supports_qThreadStopInfo = false;
3564             else if (response.IsNormalResponse())
3565                 return true;
3566             else
3567                 return false;
3568         }
3569         else
3570         {
3571             m_supports_qThreadStopInfo = false;
3572         }
3573     }
3574     return false;
3575 }
3576 
3577 
3578 uint8_t
3579 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert,  addr_t addr, uint32_t length)
3580 {
3581     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3582     if (log)
3583         log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3584                      __FUNCTION__, insert ? "add" : "remove", addr);
3585 
3586     // Check if the stub is known not to support this breakpoint type
3587     if (!SupportsGDBStoppointPacket(type))
3588         return UINT8_MAX;
3589     // Construct the breakpoint packet
3590     char packet[64];
3591     const int packet_len = ::snprintf (packet,
3592                                        sizeof(packet),
3593                                        "%c%i,%" PRIx64 ",%x",
3594                                        insert ? 'Z' : 'z',
3595                                        type,
3596                                        addr,
3597                                        length);
3598     // Check we haven't overwritten the end of the packet buffer
3599     assert (packet_len + 1 < (int)sizeof(packet));
3600     StringExtractorGDBRemote response;
3601     // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
3602     response.SetResponseValidatorToOKErrorNotSupported();
3603     // Try to send the breakpoint packet, and check that it was correctly sent
3604     if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
3605     {
3606         // Receive and OK packet when the breakpoint successfully placed
3607         if (response.IsOKResponse())
3608             return 0;
3609 
3610         // Error while setting breakpoint, send back specific error
3611         if (response.IsErrorResponse())
3612             return response.GetError();
3613 
3614         // Empty packet informs us that breakpoint is not supported
3615         if (response.IsUnsupportedResponse())
3616         {
3617             // Disable this breakpoint type since it is unsupported
3618             switch (type)
3619             {
3620             case eBreakpointSoftware:   m_supports_z0 = false; break;
3621             case eBreakpointHardware:   m_supports_z1 = false; break;
3622             case eWatchpointWrite:      m_supports_z2 = false; break;
3623             case eWatchpointRead:       m_supports_z3 = false; break;
3624             case eWatchpointReadWrite:  m_supports_z4 = false; break;
3625             case eStoppointInvalid:     return UINT8_MAX;
3626             }
3627         }
3628     }
3629     // Signal generic failure
3630     return UINT8_MAX;
3631 }
3632 
3633 size_t
3634 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3635                                                    bool &sequence_mutex_unavailable)
3636 {
3637     Mutex::Locker locker;
3638     thread_ids.clear();
3639 
3640     if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
3641     {
3642         sequence_mutex_unavailable = false;
3643         StringExtractorGDBRemote response;
3644 
3645         PacketResult packet_result;
3646         for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3647              packet_result == PacketResult::Success && response.IsNormalResponse();
3648              packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
3649         {
3650             char ch = response.GetChar();
3651             if (ch == 'l')
3652                 break;
3653             if (ch == 'm')
3654             {
3655                 do
3656                 {
3657                     tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3658 
3659                     if (tid != LLDB_INVALID_THREAD_ID)
3660                     {
3661                         thread_ids.push_back (tid);
3662                     }
3663                     ch = response.GetChar();    // Skip the command separator
3664                 } while (ch == ',');            // Make sure we got a comma separator
3665             }
3666         }
3667 
3668         /*
3669          * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3670          * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3671          * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3672          * Assume pid=tid=1 in such cases.
3673         */
3674         if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3675         {
3676             thread_ids.push_back (1);
3677         }
3678     }
3679     else
3680     {
3681 #if defined (LLDB_CONFIGURATION_DEBUG)
3682         // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3683 #else
3684         Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3685         if (log)
3686             log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3687 #endif
3688         sequence_mutex_unavailable = true;
3689     }
3690     return thread_ids.size();
3691 }
3692 
3693 lldb::addr_t
3694 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3695 {
3696     if (!IsRunning())
3697     {
3698         StringExtractorGDBRemote response;
3699         if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3700         {
3701             if (response.IsNormalResponse())
3702                 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3703         }
3704     }
3705     return LLDB_INVALID_ADDRESS;
3706 }
3707 
3708 lldb_private::Error
3709 GDBRemoteCommunicationClient::RunShellCommand(const char *command,           // Shouldn't be NULL
3710                                               const FileSpec &working_dir,   // Pass empty FileSpec to use the current working directory
3711                                               int *status_ptr,               // Pass NULL if you don't want the process exit status
3712                                               int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
3713                                               std::string *command_output,   // Pass NULL if you don't want the command output
3714                                               uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
3715 {
3716     lldb_private::StreamString stream;
3717     stream.PutCString("qPlatform_shell:");
3718     stream.PutBytesAsRawHex8(command, strlen(command));
3719     stream.PutChar(',');
3720     stream.PutHex32(timeout_sec);
3721     if (working_dir)
3722     {
3723         std::string path{working_dir.GetPath(false)};
3724         stream.PutChar(',');
3725         stream.PutCStringAsRawHex8(path.c_str());
3726     }
3727     const char *packet = stream.GetData();
3728     int packet_len = stream.GetSize();
3729     StringExtractorGDBRemote response;
3730     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3731     {
3732         if (response.GetChar() != 'F')
3733             return Error("malformed reply");
3734         if (response.GetChar() != ',')
3735             return Error("malformed reply");
3736         uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3737         if (exitcode == UINT32_MAX)
3738             return Error("unable to run remote process");
3739         else if (status_ptr)
3740             *status_ptr = exitcode;
3741         if (response.GetChar() != ',')
3742             return Error("malformed reply");
3743         uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3744         if (signo_ptr)
3745             *signo_ptr = signo;
3746         if (response.GetChar() != ',')
3747             return Error("malformed reply");
3748         std::string output;
3749         response.GetEscapedBinaryData(output);
3750         if (command_output)
3751             command_output->assign(output);
3752         return Error();
3753     }
3754     return Error("unable to send packet");
3755 }
3756 
3757 Error
3758 GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3759                                             uint32_t file_permissions)
3760 {
3761     std::string path{file_spec.GetPath(false)};
3762     lldb_private::StreamString stream;
3763     stream.PutCString("qPlatform_mkdir:");
3764     stream.PutHex32(file_permissions);
3765     stream.PutChar(',');
3766     stream.PutCStringAsRawHex8(path.c_str());
3767     const char *packet = stream.GetData();
3768     int packet_len = stream.GetSize();
3769     StringExtractorGDBRemote response;
3770 
3771     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3772         return Error("failed to send '%s' packet", packet);
3773 
3774     if (response.GetChar() != 'F')
3775         return Error("invalid response to '%s' packet", packet);
3776 
3777     return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3778 }
3779 
3780 Error
3781 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3782                                                  uint32_t file_permissions)
3783 {
3784     std::string path{file_spec.GetPath(false)};
3785     lldb_private::StreamString stream;
3786     stream.PutCString("qPlatform_chmod:");
3787     stream.PutHex32(file_permissions);
3788     stream.PutChar(',');
3789     stream.PutCStringAsRawHex8(path.c_str());
3790     const char *packet = stream.GetData();
3791     int packet_len = stream.GetSize();
3792     StringExtractorGDBRemote response;
3793 
3794     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3795         return Error("failed to send '%s' packet", packet);
3796 
3797     if (response.GetChar() != 'F')
3798         return Error("invalid response to '%s' packet", packet);
3799 
3800     return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3801 }
3802 
3803 static uint64_t
3804 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3805                            uint64_t fail_result,
3806                            Error &error)
3807 {
3808     response.SetFilePos(0);
3809     if (response.GetChar() != 'F')
3810         return fail_result;
3811     int32_t result = response.GetS32 (-2);
3812     if (result == -2)
3813         return fail_result;
3814     if (response.GetChar() == ',')
3815     {
3816         int result_errno = response.GetS32 (-2);
3817         if (result_errno != -2)
3818             error.SetError(result_errno, eErrorTypePOSIX);
3819         else
3820             error.SetError(-1, eErrorTypeGeneric);
3821     }
3822     else
3823         error.Clear();
3824     return  result;
3825 }
3826 lldb::user_id_t
3827 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3828                                         uint32_t flags,
3829                                         mode_t mode,
3830                                         Error &error)
3831 {
3832     std::string path(file_spec.GetPath(false));
3833     lldb_private::StreamString stream;
3834     stream.PutCString("vFile:open:");
3835     if (path.empty())
3836         return UINT64_MAX;
3837     stream.PutCStringAsRawHex8(path.c_str());
3838     stream.PutChar(',');
3839     stream.PutHex32(flags);
3840     stream.PutChar(',');
3841     stream.PutHex32(mode);
3842     const char* packet = stream.GetData();
3843     int packet_len = stream.GetSize();
3844     StringExtractorGDBRemote response;
3845     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3846     {
3847         return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3848     }
3849     return UINT64_MAX;
3850 }
3851 
3852 bool
3853 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3854                                          Error &error)
3855 {
3856     lldb_private::StreamString stream;
3857     stream.Printf("vFile:close:%i", (int)fd);
3858     const char* packet = stream.GetData();
3859     int packet_len = stream.GetSize();
3860     StringExtractorGDBRemote response;
3861     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3862     {
3863         return ParseHostIOPacketResponse (response, -1, error) == 0;
3864     }
3865     return false;
3866 }
3867 
3868 // Extension of host I/O packets to get the file size.
3869 lldb::user_id_t
3870 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3871 {
3872     std::string path(file_spec.GetPath(false));
3873     lldb_private::StreamString stream;
3874     stream.PutCString("vFile:size:");
3875     stream.PutCStringAsRawHex8(path.c_str());
3876     const char* packet = stream.GetData();
3877     int packet_len = stream.GetSize();
3878     StringExtractorGDBRemote response;
3879     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3880     {
3881         if (response.GetChar() != 'F')
3882             return UINT64_MAX;
3883         uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3884         return retcode;
3885     }
3886     return UINT64_MAX;
3887 }
3888 
3889 Error
3890 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3891                                                  uint32_t &file_permissions)
3892 {
3893     std::string path{file_spec.GetPath(false)};
3894     Error error;
3895     lldb_private::StreamString stream;
3896     stream.PutCString("vFile:mode:");
3897     stream.PutCStringAsRawHex8(path.c_str());
3898     const char* packet = stream.GetData();
3899     int packet_len = stream.GetSize();
3900     StringExtractorGDBRemote response;
3901     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3902     {
3903         if (response.GetChar() != 'F')
3904         {
3905             error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3906         }
3907         else
3908         {
3909             const uint32_t mode = response.GetS32(-1);
3910             if (static_cast<int32_t>(mode) == -1)
3911             {
3912                 if (response.GetChar() == ',')
3913                 {
3914                     int response_errno = response.GetS32(-1);
3915                     if (response_errno > 0)
3916                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
3917                     else
3918                         error.SetErrorToGenericError();
3919                 }
3920                 else
3921                     error.SetErrorToGenericError();
3922             }
3923             else
3924             {
3925                 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3926             }
3927         }
3928     }
3929     else
3930     {
3931         error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3932     }
3933     return error;
3934 }
3935 
3936 uint64_t
3937 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3938                                         uint64_t offset,
3939                                         void *dst,
3940                                         uint64_t dst_len,
3941                                         Error &error)
3942 {
3943     lldb_private::StreamString stream;
3944     stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3945     const char* packet = stream.GetData();
3946     int packet_len = stream.GetSize();
3947     StringExtractorGDBRemote response;
3948     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3949     {
3950         if (response.GetChar() != 'F')
3951             return 0;
3952         uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3953         if (retcode == UINT32_MAX)
3954             return retcode;
3955         const char next = (response.Peek() ? *response.Peek() : 0);
3956         if (next == ',')
3957             return 0;
3958         if (next == ';')
3959         {
3960             response.GetChar(); // skip the semicolon
3961             std::string buffer;
3962             if (response.GetEscapedBinaryData(buffer))
3963             {
3964                 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3965                 if (data_to_write > 0)
3966                     memcpy(dst, &buffer[0], data_to_write);
3967                 return data_to_write;
3968             }
3969         }
3970     }
3971     return 0;
3972 }
3973 
3974 uint64_t
3975 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3976                                          uint64_t offset,
3977                                          const void* src,
3978                                          uint64_t src_len,
3979                                          Error &error)
3980 {
3981     lldb_private::StreamGDBRemote stream;
3982     stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3983     stream.PutEscapedBytes(src, src_len);
3984     const char* packet = stream.GetData();
3985     int packet_len = stream.GetSize();
3986     StringExtractorGDBRemote response;
3987     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3988     {
3989         if (response.GetChar() != 'F')
3990         {
3991             error.SetErrorStringWithFormat("write file failed");
3992             return 0;
3993         }
3994         uint64_t bytes_written = response.GetU64(UINT64_MAX);
3995         if (bytes_written == UINT64_MAX)
3996         {
3997             error.SetErrorToGenericError();
3998             if (response.GetChar() == ',')
3999             {
4000                 int response_errno = response.GetS32(-1);
4001                 if (response_errno > 0)
4002                     error.SetError(response_errno, lldb::eErrorTypePOSIX);
4003             }
4004             return 0;
4005         }
4006         return bytes_written;
4007     }
4008     else
4009     {
4010         error.SetErrorString ("failed to send vFile:pwrite packet");
4011     }
4012     return 0;
4013 }
4014 
4015 Error
4016 GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
4017 {
4018     std::string src_path{src.GetPath(false)},
4019                 dst_path{dst.GetPath(false)};
4020     Error error;
4021     lldb_private::StreamGDBRemote stream;
4022     stream.PutCString("vFile:symlink:");
4023     // the unix symlink() command reverses its parameters where the dst if first,
4024     // so we follow suit here
4025     stream.PutCStringAsRawHex8(dst_path.c_str());
4026     stream.PutChar(',');
4027     stream.PutCStringAsRawHex8(src_path.c_str());
4028     const char* packet = stream.GetData();
4029     int packet_len = stream.GetSize();
4030     StringExtractorGDBRemote response;
4031     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
4032     {
4033         if (response.GetChar() == 'F')
4034         {
4035             uint32_t result = response.GetU32(UINT32_MAX);
4036             if (result != 0)
4037             {
4038                 error.SetErrorToGenericError();
4039                 if (response.GetChar() == ',')
4040                 {
4041                     int response_errno = response.GetS32(-1);
4042                     if (response_errno > 0)
4043                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
4044                 }
4045             }
4046         }
4047         else
4048         {
4049             // Should have returned with 'F<result>[,<errno>]'
4050             error.SetErrorStringWithFormat("symlink failed");
4051         }
4052     }
4053     else
4054     {
4055         error.SetErrorString ("failed to send vFile:symlink packet");
4056     }
4057     return error;
4058 }
4059 
4060 Error
4061 GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
4062 {
4063     std::string path{file_spec.GetPath(false)};
4064     Error error;
4065     lldb_private::StreamGDBRemote stream;
4066     stream.PutCString("vFile:unlink:");
4067     // the unix symlink() command reverses its parameters where the dst if first,
4068     // so we follow suit here
4069     stream.PutCStringAsRawHex8(path.c_str());
4070     const char* packet = stream.GetData();
4071     int packet_len = stream.GetSize();
4072     StringExtractorGDBRemote response;
4073     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
4074     {
4075         if (response.GetChar() == 'F')
4076         {
4077             uint32_t result = response.GetU32(UINT32_MAX);
4078             if (result != 0)
4079             {
4080                 error.SetErrorToGenericError();
4081                 if (response.GetChar() == ',')
4082                 {
4083                     int response_errno = response.GetS32(-1);
4084                     if (response_errno > 0)
4085                         error.SetError(response_errno, lldb::eErrorTypePOSIX);
4086                 }
4087             }
4088         }
4089         else
4090         {
4091             // Should have returned with 'F<result>[,<errno>]'
4092             error.SetErrorStringWithFormat("unlink failed");
4093         }
4094     }
4095     else
4096     {
4097         error.SetErrorString ("failed to send vFile:unlink packet");
4098     }
4099     return error;
4100 }
4101 
4102 // Extension of host I/O packets to get whether a file exists.
4103 bool
4104 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4105 {
4106     std::string path(file_spec.GetPath(false));
4107     lldb_private::StreamString stream;
4108     stream.PutCString("vFile:exists:");
4109     stream.PutCStringAsRawHex8(path.c_str());
4110     const char* packet = stream.GetData();
4111     int packet_len = stream.GetSize();
4112     StringExtractorGDBRemote response;
4113     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
4114     {
4115         if (response.GetChar() != 'F')
4116             return false;
4117         if (response.GetChar() != ',')
4118             return false;
4119         bool retcode = (response.GetChar() != '0');
4120         return retcode;
4121     }
4122     return false;
4123 }
4124 
4125 bool
4126 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4127                                             uint64_t &high,
4128                                             uint64_t &low)
4129 {
4130     std::string path(file_spec.GetPath(false));
4131     lldb_private::StreamString stream;
4132     stream.PutCString("vFile:MD5:");
4133     stream.PutCStringAsRawHex8(path.c_str());
4134     const char* packet = stream.GetData();
4135     int packet_len = stream.GetSize();
4136     StringExtractorGDBRemote response;
4137     if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
4138     {
4139         if (response.GetChar() != 'F')
4140             return false;
4141         if (response.GetChar() != ',')
4142             return false;
4143         if (response.Peek() && *response.Peek() == 'x')
4144             return false;
4145         low = response.GetHexMaxU64(false, UINT64_MAX);
4146         high = response.GetHexMaxU64(false, UINT64_MAX);
4147         return true;
4148     }
4149     return false;
4150 }
4151 
4152 bool
4153 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4154 {
4155     // Some targets have issues with g/G packets and we need to avoid using them
4156     if (m_avoid_g_packets == eLazyBoolCalculate)
4157     {
4158         if (process)
4159         {
4160             m_avoid_g_packets = eLazyBoolNo;
4161             const ArchSpec &arch = process->GetTarget().GetArchitecture();
4162             if (arch.IsValid()
4163                 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4164                 && arch.GetTriple().getOS() == llvm::Triple::IOS
4165                 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
4166             {
4167                 m_avoid_g_packets = eLazyBoolYes;
4168                 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4169                 if (gdb_server_version != 0)
4170                 {
4171                     const char *gdb_server_name = GetGDBServerProgramName();
4172                     if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4173                     {
4174                         if (gdb_server_version >= 310)
4175                             m_avoid_g_packets = eLazyBoolNo;
4176                     }
4177                 }
4178             }
4179         }
4180     }
4181     return m_avoid_g_packets == eLazyBoolYes;
4182 }
4183 
4184 bool
4185 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4186 {
4187     Mutex::Locker locker;
4188     if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4189     {
4190         const bool thread_suffix_supported = GetThreadSuffixSupported();
4191 
4192         if (thread_suffix_supported || SetCurrentThread(tid))
4193         {
4194             char packet[64];
4195             int packet_len = 0;
4196             if (thread_suffix_supported)
4197                 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4198             else
4199                 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4200             assert (packet_len < ((int)sizeof(packet) - 1));
4201             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4202         }
4203     }
4204     return false;
4205 
4206 }
4207 
4208 
4209 bool
4210 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4211 {
4212     Mutex::Locker locker;
4213     if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4214     {
4215         const bool thread_suffix_supported = GetThreadSuffixSupported();
4216 
4217         if (thread_suffix_supported || SetCurrentThread(tid))
4218         {
4219             char packet[64];
4220             int packet_len = 0;
4221             // Get all registers in one packet
4222             if (thread_suffix_supported)
4223                 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4224             else
4225                 packet_len = ::snprintf (packet, sizeof(packet), "g");
4226             assert (packet_len < ((int)sizeof(packet) - 1));
4227             return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4228         }
4229     }
4230     return false;
4231 }
4232 bool
4233 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4234 {
4235     save_id = 0; // Set to invalid save ID
4236     if (m_supports_QSaveRegisterState == eLazyBoolNo)
4237         return false;
4238 
4239     m_supports_QSaveRegisterState = eLazyBoolYes;
4240     Mutex::Locker locker;
4241     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4242     {
4243         const bool thread_suffix_supported = GetThreadSuffixSupported();
4244         if (thread_suffix_supported || SetCurrentThread(tid))
4245         {
4246             char packet[256];
4247             if (thread_suffix_supported)
4248                 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4249             else
4250                 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
4251 
4252             StringExtractorGDBRemote response;
4253 
4254             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4255             {
4256                 if (response.IsUnsupportedResponse())
4257                 {
4258                     // This packet isn't supported, don't try calling it again
4259                     m_supports_QSaveRegisterState = eLazyBoolNo;
4260                 }
4261 
4262                 const uint32_t response_save_id = response.GetU32(0);
4263                 if (response_save_id != 0)
4264                 {
4265                     save_id = response_save_id;
4266                     return true;
4267                 }
4268             }
4269         }
4270     }
4271     return false;
4272 }
4273 
4274 bool
4275 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4276 {
4277     // We use the "m_supports_QSaveRegisterState" variable here because the
4278     // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4279     // order to be useful
4280     if (m_supports_QSaveRegisterState == eLazyBoolNo)
4281         return false;
4282 
4283     Mutex::Locker locker;
4284     if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4285     {
4286         const bool thread_suffix_supported = GetThreadSuffixSupported();
4287         if (thread_suffix_supported || SetCurrentThread(tid))
4288         {
4289             char packet[256];
4290             if (thread_suffix_supported)
4291                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4292             else
4293                 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4294 
4295             StringExtractorGDBRemote response;
4296 
4297             if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4298             {
4299                 if (response.IsOKResponse())
4300                 {
4301                     return true;
4302                 }
4303                 else if (response.IsUnsupportedResponse())
4304                 {
4305                     // This packet isn't supported, don't try calling this packet or
4306                     // QSaveRegisterState again...
4307                     m_supports_QSaveRegisterState = eLazyBoolNo;
4308                 }
4309             }
4310         }
4311     }
4312     return false;
4313 }
4314 
4315 bool
4316 GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
4317                                              const lldb_private::ArchSpec& arch_spec,
4318                                              ModuleSpec &module_spec)
4319 {
4320     if (!m_supports_qModuleInfo)
4321         return false;
4322 
4323     std::string module_path = module_file_spec.GetPath (false);
4324     if (module_path.empty ())
4325         return false;
4326 
4327     StreamString packet;
4328     packet.PutCString("qModuleInfo:");
4329     packet.PutCStringAsRawHex8(module_path.c_str());
4330     packet.PutCString(";");
4331     const auto& triple = arch_spec.GetTriple().getTriple();
4332     packet.PutCStringAsRawHex8(triple.c_str());
4333 
4334     StringExtractorGDBRemote response;
4335     if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4336         return false;
4337 
4338     if (response.IsErrorResponse ())
4339         return false;
4340 
4341     if (response.IsUnsupportedResponse ())
4342     {
4343         m_supports_qModuleInfo = false;
4344         return false;
4345     }
4346 
4347     std::string name;
4348     std::string value;
4349     bool success;
4350     StringExtractor extractor;
4351 
4352     module_spec.Clear ();
4353     module_spec.GetFileSpec () = module_file_spec;
4354 
4355     while (response.GetNameColonValue (name, value))
4356     {
4357         if (name == "uuid" || name == "md5")
4358         {
4359             extractor.GetStringRef ().swap (value);
4360             extractor.SetFilePos (0);
4361             extractor.GetHexByteString (value);
4362             module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4363         }
4364         else if (name == "triple")
4365         {
4366             extractor.GetStringRef ().swap (value);
4367             extractor.SetFilePos (0);
4368             extractor.GetHexByteString (value);
4369             module_spec.GetArchitecture().SetTriple (value.c_str ());
4370         }
4371         else if (name == "file_offset")
4372         {
4373             const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4374             if (success)
4375                 module_spec.SetObjectOffset (ival);
4376         }
4377         else if (name == "file_size")
4378         {
4379             const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4380             if (success)
4381                 module_spec.SetObjectSize (ival);
4382         }
4383         else if (name == "file_path")
4384         {
4385             extractor.GetStringRef ().swap (value);
4386             extractor.SetFilePos (0);
4387             extractor.GetHexByteString (value);
4388             module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
4389         }
4390     }
4391 
4392     return true;
4393 }
4394 
4395 // query the target remote for extended information using the qXfer packet
4396 //
4397 // example: object='features', annex='target.xml', out=<xml output>
4398 // return:  'true'  on success
4399 //          'false' on failure (err set)
4400 bool
4401 GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4402                                               const lldb_private::ConstString annex,
4403                                               std::string & out,
4404                                               lldb_private::Error & err) {
4405 
4406     std::stringstream output;
4407     StringExtractorGDBRemote chunk;
4408 
4409     uint64_t size = GetRemoteMaxPacketSize();
4410     if (size == 0)
4411         size = 0x1000;
4412     size = size - 1; // Leave space for the 'm' or 'l' character in the response
4413     int offset = 0;
4414     bool active = true;
4415 
4416     // loop until all data has been read
4417     while ( active ) {
4418 
4419         // send query extended feature packet
4420         std::stringstream packet;
4421         packet << "qXfer:"
4422                << object.AsCString("") << ":read:"
4423                << annex.AsCString("")  << ":"
4424                << std::hex << offset  << ","
4425                << std::hex << size;
4426 
4427         GDBRemoteCommunication::PacketResult res =
4428             SendPacketAndWaitForResponse( packet.str().c_str(),
4429                                           chunk,
4430                                           false );
4431 
4432         if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4433             err.SetErrorString( "Error sending $qXfer packet" );
4434             return false;
4435         }
4436 
4437         const std::string & str = chunk.GetStringRef( );
4438         if ( str.length() == 0 ) {
4439             // should have some data in chunk
4440             err.SetErrorString( "Empty response from $qXfer packet" );
4441             return false;
4442         }
4443 
4444         // check packet code
4445         switch ( str[0] ) {
4446             // last chunk
4447         case ( 'l' ):
4448             active = false;
4449             LLVM_FALLTHROUGH;
4450 
4451             // more chunks
4452         case ( 'm' ) :
4453             if ( str.length() > 1 )
4454                 output << &str[1];
4455             offset += size;
4456             break;
4457 
4458             // unknown chunk
4459         default:
4460             err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4461             return false;
4462         }
4463     }
4464 
4465     out = output.str( );
4466     err.Success( );
4467     return true;
4468 }
4469 
4470 // Notify the target that gdb is prepared to serve symbol lookup requests.
4471 //  packet: "qSymbol::"
4472 //  reply:
4473 //  OK                  The target does not need to look up any (more) symbols.
4474 //  qSymbol:<sym_name>  The target requests the value of symbol sym_name (hex encoded).
4475 //                      LLDB may provide the value by sending another qSymbol packet
4476 //                      in the form of"qSymbol:<sym_value>:<sym_name>".
4477 //
4478 //  Three examples:
4479 //
4480 //  lldb sends:    qSymbol::
4481 //  lldb receives: OK
4482 //     Remote gdb stub does not need to know the addresses of any symbols, lldb does not
4483 //     need to ask again in this session.
4484 //
4485 //  lldb sends:    qSymbol::
4486 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4487 //  lldb sends:    qSymbol::64697370617463685f71756575655f6f666673657473
4488 //  lldb receives: OK
4489 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb does not know
4490 //     the address at this time.  lldb needs to send qSymbol:: again when it has more
4491 //     solibs loaded.
4492 //
4493 //  lldb sends:    qSymbol::
4494 //  lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4495 //  lldb sends:    qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4496 //  lldb receives: OK
4497 //     Remote gdb stub asks for address of 'dispatch_queue_offsets'.  lldb says that it
4498 //     is at address 0x2bc97554.  Remote gdb stub sends 'OK' indicating that it does not
4499 //     need any more symbols.  lldb does not need to ask again in this session.
4500 
4501 void
4502 GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4503 {
4504     // Set to true once we've resolved a symbol to an address for the remote stub.
4505     // If we get an 'OK' response after this, the remote stub doesn't need any more
4506     // symbols and we can stop asking.
4507     bool symbol_response_provided = false;
4508 
4509     // Is this the inital qSymbol:: packet?
4510     bool first_qsymbol_query = true;
4511 
4512     if (m_supports_qSymbol && m_qSymbol_requests_done == false)
4513     {
4514         Mutex::Locker locker;
4515         if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4516         {
4517             StreamString packet;
4518             packet.PutCString ("qSymbol::");
4519             StringExtractorGDBRemote response;
4520             while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
4521             {
4522                 if (response.IsOKResponse())
4523                 {
4524                     if (symbol_response_provided || first_qsymbol_query)
4525                     {
4526                         m_qSymbol_requests_done = true;
4527                     }
4528 
4529                     // We are done serving symbols requests
4530                     return;
4531                 }
4532                 first_qsymbol_query = false;
4533 
4534                 if (response.IsUnsupportedResponse())
4535                 {
4536                     // qSymbol is not supported by the current GDB server we are connected to
4537                     m_supports_qSymbol = false;
4538                     return;
4539                 }
4540                 else
4541                 {
4542                     llvm::StringRef response_str(response.GetStringRef());
4543                     if (response_str.startswith("qSymbol:"))
4544                     {
4545                         response.SetFilePos(strlen("qSymbol:"));
4546                         std::string symbol_name;
4547                         if (response.GetHexByteString(symbol_name))
4548                         {
4549                             if (symbol_name.empty())
4550                                 return;
4551 
4552                             addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4553                             lldb_private::SymbolContextList sc_list;
4554                             if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
4555                             {
4556                                 const size_t num_scs = sc_list.GetSize();
4557                                 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
4558                                 {
4559                                     SymbolContext sc;
4560                                     if (sc_list.GetContextAtIndex(sc_idx, sc))
4561                                     {
4562                                         if (sc.symbol)
4563                                         {
4564                                             switch (sc.symbol->GetType())
4565                                             {
4566                                             case eSymbolTypeInvalid:
4567                                             case eSymbolTypeAbsolute:
4568                                             case eSymbolTypeUndefined:
4569                                             case eSymbolTypeSourceFile:
4570                                             case eSymbolTypeHeaderFile:
4571                                             case eSymbolTypeObjectFile:
4572                                             case eSymbolTypeCommonBlock:
4573                                             case eSymbolTypeBlock:
4574                                             case eSymbolTypeLocal:
4575                                             case eSymbolTypeParam:
4576                                             case eSymbolTypeVariable:
4577                                             case eSymbolTypeVariableType:
4578                                             case eSymbolTypeLineEntry:
4579                                             case eSymbolTypeLineHeader:
4580                                             case eSymbolTypeScopeBegin:
4581                                             case eSymbolTypeScopeEnd:
4582                                             case eSymbolTypeAdditional:
4583                                             case eSymbolTypeCompiler:
4584                                             case eSymbolTypeInstrumentation:
4585                                             case eSymbolTypeTrampoline:
4586                                                 break;
4587 
4588                                             case eSymbolTypeCode:
4589                                             case eSymbolTypeResolver:
4590                                             case eSymbolTypeData:
4591                                             case eSymbolTypeRuntime:
4592                                             case eSymbolTypeException:
4593                                             case eSymbolTypeObjCClass:
4594                                             case eSymbolTypeObjCMetaClass:
4595                                             case eSymbolTypeObjCIVar:
4596                                             case eSymbolTypeReExported:
4597                                                 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4598                                                 break;
4599                                             }
4600                                         }
4601                                     }
4602                                 }
4603                             }
4604                             // This is the normal path where our symbol lookup was successful and we want
4605                             // to send a packet with the new symbol value and see if another lookup needs to be
4606                             // done.
4607 
4608                             // Change "packet" to contain the requested symbol value and name
4609                             packet.Clear();
4610                             packet.PutCString("qSymbol:");
4611                             if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4612                             {
4613                                 packet.Printf("%" PRIx64, symbol_load_addr);
4614                                 symbol_response_provided = true;
4615                             }
4616                             else
4617                             {
4618                                 symbol_response_provided = false;
4619                             }
4620                             packet.PutCString(":");
4621                             packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4622                             continue; // go back to the while loop and send "packet" and wait for another response
4623                         }
4624                     }
4625                 }
4626             }
4627             // If we make it here, the symbol request packet response wasn't valid or
4628             // our symbol lookup failed so we must abort
4629             return;
4630 
4631         }
4632     }
4633 }
4634 
4635