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