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