1 //===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "GDBRemoteCommunicationClient.h"
21 // Other libraries and framework includes
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "lldb/Interpreter/Args.h"
25 #include "lldb/Core/Log.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/State.h"
28 #include "lldb/Core/StreamGDBRemote.h"
29 #include "lldb/Core/StreamString.h"
30 #include "lldb/Host/ConnectionFileDescriptor.h"
31 #include "lldb/Host/Endian.h"
32 #include "lldb/Host/Host.h"
33 #include "lldb/Host/HostInfo.h"
34 #include "lldb/Host/StringConvert.h"
35 #include "lldb/Host/TimeValue.h"
36 #include "lldb/Symbol/Symbol.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Target/MemoryRegionInfo.h"
39 #include "lldb/Target/UnixSignals.h"
42 #include "Utility/StringExtractorGDBRemote.h"
43 #include "ProcessGDBRemote.h"
44 #include "ProcessGDBRemoteLog.h"
45 #include "lldb/Host/Config.h"
47 #if defined (HAVE_LIBCOMPRESSION)
48 #include <compression.h>
52 using namespace lldb_private;
53 using namespace lldb_private::process_gdb_remote;
55 //----------------------------------------------------------------------
56 // GDBRemoteCommunicationClient constructor
57 //----------------------------------------------------------------------
58 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
59 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
60 m_supports_not_sending_acks (eLazyBoolCalculate),
61 m_supports_thread_suffix (eLazyBoolCalculate),
62 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
63 m_supports_vCont_all (eLazyBoolCalculate),
64 m_supports_vCont_any (eLazyBoolCalculate),
65 m_supports_vCont_c (eLazyBoolCalculate),
66 m_supports_vCont_C (eLazyBoolCalculate),
67 m_supports_vCont_s (eLazyBoolCalculate),
68 m_supports_vCont_S (eLazyBoolCalculate),
69 m_qHostInfo_is_valid (eLazyBoolCalculate),
70 m_curr_pid_is_valid (eLazyBoolCalculate),
71 m_qProcessInfo_is_valid (eLazyBoolCalculate),
72 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
73 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
74 m_supports_memory_region_info (eLazyBoolCalculate),
75 m_supports_watchpoint_support_info (eLazyBoolCalculate),
76 m_supports_detach_stay_stopped (eLazyBoolCalculate),
77 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
78 m_attach_or_wait_reply(eLazyBoolCalculate),
79 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
80 m_supports_p (eLazyBoolCalculate),
81 m_supports_x (eLazyBoolCalculate),
82 m_avoid_g_packets (eLazyBoolCalculate),
83 m_supports_QSaveRegisterState (eLazyBoolCalculate),
84 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
85 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
86 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
87 m_supports_qXfer_features_read (eLazyBoolCalculate),
88 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
89 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
90 m_supports_jLoadedDynamicLibrariesInfos (eLazyBoolCalculate),
91 m_supports_qProcessInfoPID (true),
92 m_supports_qfProcessInfo (true),
93 m_supports_qUserName (true),
94 m_supports_qGroupName (true),
95 m_supports_qThreadStopInfo (true),
100 m_supports_z4 (true),
101 m_supports_QEnvironment (true),
102 m_supports_QEnvironmentHexEncoded (true),
103 m_supports_qSymbol (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_async_mutex (Mutex::eMutexTypeRecursive),
110 m_async_packet_predicate (false),
112 m_async_result (PacketResult::Success),
115 m_interrupt_sent (false),
116 m_thread_id_to_used_usec_map (),
119 m_os_version_major (UINT32_MAX),
120 m_os_version_minor (UINT32_MAX),
121 m_os_version_update (UINT32_MAX),
126 m_gdb_server_version(UINT32_MAX),
127 m_default_packet_timeout (0),
128 m_max_packet_size (0)
132 //----------------------------------------------------------------------
134 //----------------------------------------------------------------------
135 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
142 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
144 ResetDiscoverableSettings(false);
146 // Start the read thread after we send the handshake ack since if we
147 // fail to send the handshake ack, there is no reason to continue...
150 // Wait for any responses that might have been queued up in the remote
151 // GDB server and flush them all
152 StringExtractorGDBRemote response;
153 PacketResult packet_result = PacketResult::Success;
154 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
155 while (packet_result == PacketResult::Success)
156 packet_result = ReadPacket (response, timeout_usec, false);
158 // The return value from QueryNoAckModeSupported() is true if the packet
159 // was sent and _any_ response (including UNIMPLEMENTED) was received),
160 // or false if no response was received. This quickly tells us if we have
161 // a live connection to a remote GDB server...
162 if (QueryNoAckModeSupported())
169 error_ptr->SetErrorString("failed to get reply to handshake packet");
175 error_ptr->SetErrorString("failed to send the handshake ack");
181 GDBRemoteCommunicationClient::GetEchoSupported ()
183 if (m_supports_qEcho == eLazyBoolCalculate)
185 GetRemoteQSupported();
187 return m_supports_qEcho == eLazyBoolYes;
192 GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
194 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
196 GetRemoteQSupported();
198 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
202 GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
204 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
206 GetRemoteQSupported();
208 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
212 GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
214 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
216 GetRemoteQSupported();
218 return m_supports_qXfer_libraries_read == eLazyBoolYes;
222 GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
224 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
226 GetRemoteQSupported();
228 return m_supports_qXfer_auxv_read == eLazyBoolYes;
232 GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
234 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
236 GetRemoteQSupported();
238 return m_supports_qXfer_features_read == eLazyBoolYes;
242 GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
244 if (m_max_packet_size == 0)
246 GetRemoteQSupported();
248 return m_max_packet_size;
252 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
254 if (m_supports_not_sending_acks == eLazyBoolCalculate)
257 m_supports_not_sending_acks = eLazyBoolNo;
259 // This is the first real packet that we'll send in a debug session and it may take a little
260 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
262 const uint32_t minimum_timeout = 6;
263 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
264 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
266 StringExtractorGDBRemote response;
267 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
269 if (response.IsOKResponse())
272 m_supports_not_sending_acks = eLazyBoolYes;
281 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
283 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
285 m_supports_threads_in_stop_reply = eLazyBoolNo;
287 StringExtractorGDBRemote response;
288 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
290 if (response.IsOKResponse())
291 m_supports_threads_in_stop_reply = eLazyBoolYes;
297 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
299 if (m_attach_or_wait_reply == eLazyBoolCalculate)
301 m_attach_or_wait_reply = eLazyBoolNo;
303 StringExtractorGDBRemote response;
304 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
306 if (response.IsOKResponse())
307 m_attach_or_wait_reply = eLazyBoolYes;
310 if (m_attach_or_wait_reply == eLazyBoolYes)
317 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
319 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
321 m_prepare_for_reg_writing_reply = eLazyBoolNo;
323 StringExtractorGDBRemote response;
324 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
326 if (response.IsOKResponse())
327 m_prepare_for_reg_writing_reply = eLazyBoolYes;
330 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
338 GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
340 if (did_exec == false)
342 // Hard reset everything, this is when we first connect to a GDB server
343 m_supports_not_sending_acks = eLazyBoolCalculate;
344 m_supports_thread_suffix = eLazyBoolCalculate;
345 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
346 m_supports_vCont_c = eLazyBoolCalculate;
347 m_supports_vCont_C = eLazyBoolCalculate;
348 m_supports_vCont_s = eLazyBoolCalculate;
349 m_supports_vCont_S = eLazyBoolCalculate;
350 m_supports_p = eLazyBoolCalculate;
351 m_supports_x = eLazyBoolCalculate;
352 m_supports_QSaveRegisterState = eLazyBoolCalculate;
353 m_qHostInfo_is_valid = eLazyBoolCalculate;
354 m_curr_pid_is_valid = eLazyBoolCalculate;
355 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
356 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
357 m_supports_memory_region_info = eLazyBoolCalculate;
358 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
359 m_attach_or_wait_reply = eLazyBoolCalculate;
360 m_avoid_g_packets = eLazyBoolCalculate;
361 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
362 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
363 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
364 m_supports_qXfer_features_read = eLazyBoolCalculate;
365 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
366 m_supports_qProcessInfoPID = true;
367 m_supports_qfProcessInfo = true;
368 m_supports_qUserName = true;
369 m_supports_qGroupName = true;
370 m_supports_qThreadStopInfo = true;
371 m_supports_z0 = true;
372 m_supports_z1 = true;
373 m_supports_z2 = true;
374 m_supports_z3 = true;
375 m_supports_z4 = true;
376 m_supports_QEnvironment = true;
377 m_supports_QEnvironmentHexEncoded = true;
378 m_supports_qSymbol = true;
380 m_os_version_major = UINT32_MAX;
381 m_os_version_minor = UINT32_MAX;
382 m_os_version_update = UINT32_MAX;
386 m_gdb_server_name.clear();
387 m_gdb_server_version = UINT32_MAX;
388 m_default_packet_timeout = 0;
389 m_max_packet_size = 0;
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();
399 GDBRemoteCommunicationClient::GetRemoteQSupported ()
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
409 // build the qSupported packet
410 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
412 packet.PutCString( "qSupported" );
413 for ( uint32_t i = 0; i < features.size( ); ++i )
415 packet.PutCString( i==0 ? ":" : ";");
416 packet.PutCString( features[i].c_str( ) );
419 StringExtractorGDBRemote response;
420 if (SendPacketAndWaitForResponse(packet.GetData(),
422 /*send_async=*/false) == PacketResult::Success)
424 const char *response_cstr = response.GetStringRef().c_str();
425 if (::strstr (response_cstr, "qXfer:auxv:read+"))
426 m_supports_qXfer_auxv_read = eLazyBoolYes;
427 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
428 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
429 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
431 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
432 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
434 if (::strstr (response_cstr, "qXfer:libraries:read+"))
435 m_supports_qXfer_libraries_read = eLazyBoolYes;
436 if (::strstr (response_cstr, "qXfer:features:read+"))
437 m_supports_qXfer_features_read = eLazyBoolYes;
440 // Look for a list of compressions in the features list e.g.
441 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
442 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
445 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
448 std::vector<std::string> supported_compressions;
449 compressions += sizeof ("SupportedCompressions=") - 1;
450 const char *end_of_compressions = strchr (compressions, ';');
451 if (end_of_compressions == NULL)
453 end_of_compressions = strchr (compressions, '\0');
455 const char *current_compression = compressions;
456 while (current_compression < end_of_compressions)
458 const char *next_compression_name = strchr (current_compression, ',');
459 const char *end_of_this_word = next_compression_name;
460 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
462 end_of_this_word = end_of_compressions;
465 if (end_of_this_word)
467 if (end_of_this_word == current_compression)
469 current_compression++;
473 std::string this_compression (current_compression, end_of_this_word - current_compression);
474 supported_compressions.push_back (this_compression);
475 current_compression = end_of_this_word + 1;
480 supported_compressions.push_back (current_compression);
481 current_compression = end_of_compressions;
485 if (supported_compressions.size() > 0)
487 MaybeEnableCompression (supported_compressions);
492 if (::strstr (response_cstr, "qEcho"))
493 m_supports_qEcho = eLazyBoolYes;
495 m_supports_qEcho = eLazyBoolNo;
497 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
500 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
501 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
502 if (m_max_packet_size == 0)
504 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
505 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
507 log->Printf ("Garbled PacketSize spec in qSupported response");
514 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
516 if (m_supports_thread_suffix == eLazyBoolCalculate)
518 StringExtractorGDBRemote response;
519 m_supports_thread_suffix = eLazyBoolNo;
520 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
522 if (response.IsOKResponse())
523 m_supports_thread_suffix = eLazyBoolYes;
526 return m_supports_thread_suffix;
529 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
531 if (m_supports_vCont_c == eLazyBoolCalculate)
533 StringExtractorGDBRemote response;
534 m_supports_vCont_any = eLazyBoolNo;
535 m_supports_vCont_all = eLazyBoolNo;
536 m_supports_vCont_c = eLazyBoolNo;
537 m_supports_vCont_C = eLazyBoolNo;
538 m_supports_vCont_s = eLazyBoolNo;
539 m_supports_vCont_S = eLazyBoolNo;
540 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
542 const char *response_cstr = response.GetStringRef().c_str();
543 if (::strstr (response_cstr, ";c"))
544 m_supports_vCont_c = eLazyBoolYes;
546 if (::strstr (response_cstr, ";C"))
547 m_supports_vCont_C = eLazyBoolYes;
549 if (::strstr (response_cstr, ";s"))
550 m_supports_vCont_s = eLazyBoolYes;
552 if (::strstr (response_cstr, ";S"))
553 m_supports_vCont_S = eLazyBoolYes;
555 if (m_supports_vCont_c == eLazyBoolYes &&
556 m_supports_vCont_C == eLazyBoolYes &&
557 m_supports_vCont_s == eLazyBoolYes &&
558 m_supports_vCont_S == eLazyBoolYes)
560 m_supports_vCont_all = eLazyBoolYes;
563 if (m_supports_vCont_c == eLazyBoolYes ||
564 m_supports_vCont_C == eLazyBoolYes ||
565 m_supports_vCont_s == eLazyBoolYes ||
566 m_supports_vCont_S == eLazyBoolYes)
568 m_supports_vCont_any = eLazyBoolYes;
575 case 'a': return m_supports_vCont_any;
576 case 'A': return m_supports_vCont_all;
577 case 'c': return m_supports_vCont_c;
578 case 'C': return m_supports_vCont_C;
579 case 's': return m_supports_vCont_s;
580 case 'S': return m_supports_vCont_S;
586 // Check if the target supports 'p' packet. It sends out a 'p'
587 // packet and checks the response. A normal packet will tell us
588 // that support is available.
590 // Takes a valid thread ID because p needs to apply to a thread.
592 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
594 if (m_supports_p == eLazyBoolCalculate)
596 StringExtractorGDBRemote response;
597 m_supports_p = eLazyBoolNo;
599 if (GetThreadSuffixSupported())
600 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
602 snprintf(packet, sizeof(packet), "p0");
604 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
606 if (response.IsNormalResponse())
607 m_supports_p = eLazyBoolYes;
613 StructuredData::ObjectSP
614 GDBRemoteCommunicationClient::GetThreadsInfo()
616 // Get information on all threads at one using the "jThreadsInfo" packet
617 StructuredData::ObjectSP object_sp;
619 if (m_supports_jThreadsInfo)
621 StringExtractorGDBRemote response;
622 m_supports_jThreadExtendedInfo = eLazyBoolNo;
623 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
625 if (response.IsUnsupportedResponse())
627 m_supports_jThreadsInfo = false;
629 else if (!response.Empty())
631 object_sp = StructuredData::ParseJSON (response.GetStringRef());
640 GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
642 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
644 StringExtractorGDBRemote response;
645 m_supports_jThreadExtendedInfo = eLazyBoolNo;
646 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
648 if (response.IsOKResponse())
650 m_supports_jThreadExtendedInfo = eLazyBoolYes;
654 return m_supports_jThreadExtendedInfo;
658 GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
660 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
662 StringExtractorGDBRemote response;
663 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
664 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
666 if (response.IsOKResponse())
668 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
672 return m_supports_jLoadedDynamicLibrariesInfos;
676 GDBRemoteCommunicationClient::GetxPacketSupported ()
678 if (m_supports_x == eLazyBoolCalculate)
680 StringExtractorGDBRemote response;
681 m_supports_x = eLazyBoolNo;
683 snprintf (packet, sizeof (packet), "x0,0");
684 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
686 if (response.IsOKResponse())
687 m_supports_x = eLazyBoolYes;
693 GDBRemoteCommunicationClient::PacketResult
694 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
696 const char *payload_prefix,
697 std::string &response_string
700 Mutex::Locker locker;
701 if (!GetSequenceMutex(locker,
702 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
704 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
706 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
708 return PacketResult::ErrorNoSequenceLock;
711 response_string = "";
712 std::string payload_prefix_str(payload_prefix);
713 unsigned int response_size = 0x1000;
714 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
715 response_size = GetRemoteMaxPacketSize();
718 for (unsigned int offset = 0; true; offset += response_size)
720 StringExtractorGDBRemote this_response;
722 char sizeDescriptor[128];
723 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
724 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
726 /*send_async=*/false);
727 if (result != PacketResult::Success)
730 const std::string &this_string = this_response.GetStringRef();
732 // Check for m or l as first character; l seems to mean this is the last chunk
733 char first_char = *this_string.c_str();
734 if (first_char != 'm' && first_char != 'l')
736 return PacketResult::ErrorReplyInvalid;
738 // Concatenate the result so far (skipping 'm' or 'l')
739 response_string.append(this_string, 1, std::string::npos);
740 if (first_char == 'l')
742 return PacketResult::Success;
746 GDBRemoteCommunicationClient::PacketResult
747 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
750 StringExtractorGDBRemote &response,
754 return SendPacketAndWaitForResponse (payload,
760 GDBRemoteCommunicationClient::PacketResult
761 GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
762 size_t payload_length,
763 StringExtractorGDBRemote &response)
765 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
766 if (packet_result == PacketResult::Success)
767 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
768 return packet_result;
771 GDBRemoteCommunicationClient::PacketResult
772 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
775 size_t payload_length,
776 StringExtractorGDBRemote &response,
780 PacketResult packet_result = PacketResult::ErrorSendFailed;
781 Mutex::Locker locker;
782 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
784 // In order to stop async notifications from being processed in the middle of the
785 // send/recieve sequence Hijack the broadcast. Then rebroadcast any events when we are done.
786 static Listener hijack_listener("lldb.NotifyHijacker");
787 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
789 if (GetSequenceMutex (locker))
791 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
799 Mutex::Locker async_locker (m_async_mutex);
800 m_async_packet.assign(payload, payload_length);
801 m_async_packet_predicate.SetValue (true, eBroadcastNever);
804 log->Printf ("async: async packet = %s", m_async_packet.c_str());
806 bool timed_out = false;
807 if (SendInterrupt(locker, 2, timed_out))
809 if (m_interrupt_sent)
811 m_interrupt_sent = false;
812 TimeValue timeout_time;
813 timeout_time = TimeValue::Now();
814 timeout_time.OffsetWithSeconds (m_packet_timeout);
817 log->Printf ("async: sent interrupt");
819 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
822 log->Printf ("async: got response");
824 // Swap the response buffer to avoid malloc and string copy
825 response.GetStringRef().swap (m_async_response.GetStringRef());
826 packet_result = m_async_result;
831 log->Printf ("async: timed out waiting for response");
834 // Make sure we wait until the continue packet has been sent again...
835 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
840 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
842 log->Printf ("async: async packet sent");
848 log->Printf ("async: timed out waiting for process to resume");
853 // We had a racy condition where we went to send the interrupt
854 // yet we were able to get the lock, so the process must have
857 log->Printf ("async: got lock without sending interrupt");
858 // Send the packet normally since we got the lock
859 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
865 log->Printf ("async: failed to interrupt");
871 log->Printf ("async: not running, async is ignored");
877 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
881 // Remove our Hijacking listner from the broadcast.
882 RestoreBroadcaster();
884 // If a notification event occured, rebroadcast since it can now be processed safely.
886 if (hijack_listener.GetNextEvent(event_sp))
887 BroadcastEvent(event_sp);
889 return packet_result;
892 static const char *end_delimiter = "--end--;";
893 static const int end_delimiter_len = 8;
896 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
897 ( ProcessGDBRemote *process,
898 StringExtractorGDBRemote& profileDataExtractor
901 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
902 std::stringstream final_output;
903 std::string name, value;
905 // Going to assuming thread_used_usec comes first, else bail out.
906 while (profileDataExtractor.GetNameColonValue(name, value))
908 if (name.compare("thread_used_id") == 0)
910 StringExtractor threadIDHexExtractor(value.c_str());
911 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
913 bool has_used_usec = false;
914 uint32_t curr_used_usec = 0;
915 std::string usec_name, usec_value;
916 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
917 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
919 if (usec_name.compare("thread_used_usec") == 0)
921 has_used_usec = true;
922 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
926 // We didn't find what we want, it is probably
927 // an older version. Bail out.
928 profileDataExtractor.SetFilePos(input_file_pos);
934 uint32_t prev_used_usec = 0;
935 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
936 if (iterator != m_thread_id_to_used_usec_map.end())
938 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
941 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
942 // A good first time record is one that runs for at least 0.25 sec
943 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
944 bool good_subsequent_time = (prev_used_usec > 0) &&
945 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
947 if (good_first_time || good_subsequent_time)
949 // We try to avoid doing too many index id reservation,
950 // resulting in fast increase of index ids.
952 final_output << name << ":";
953 int32_t index_id = process->AssignIndexIDToThread(thread_id);
954 final_output << index_id << ";";
956 final_output << usec_name << ":" << usec_value << ";";
960 // Skip past 'thread_used_name'.
961 std::string local_name, local_value;
962 profileDataExtractor.GetNameColonValue(local_name, local_value);
965 // Store current time as previous time so that they can be compared later.
966 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
970 // Bail out and use old string.
971 final_output << name << ":" << value << ";";
976 final_output << name << ":" << value << ";";
979 final_output << end_delimiter;
980 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
982 return final_output.str();
986 GDBRemoteCommunicationClient::SendvContPacket
988 ProcessGDBRemote *process,
990 size_t packet_length,
991 StringExtractorGDBRemote &response
995 m_curr_tid = LLDB_INVALID_THREAD_ID;
996 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
998 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1000 // we want to lock down packet sending while we continue
1001 Mutex::Locker locker(m_sequence_mutex);
1003 // here we broadcast this before we even send the packet!!
1004 // this signals doContinue() to exit
1005 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1007 // set the public state to running
1008 m_public_is_running.SetValue(true, eBroadcastNever);
1010 // Set the starting continue packet into "continue_packet". This packet
1011 // may change if we are interrupted and we continue after an async packet...
1012 std::string continue_packet(payload, packet_length);
1015 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1017 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1020 // set the private state to running and broadcast this
1021 m_private_is_running.SetValue(true, eBroadcastAlways);
1024 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1026 // wait for the response to the vCont
1027 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1029 if (response.IsOKResponse())
1037 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1039 ProcessGDBRemote *process,
1040 const char *payload,
1041 size_t packet_length,
1042 StringExtractorGDBRemote &response
1045 m_curr_tid = LLDB_INVALID_THREAD_ID;
1046 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1048 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1050 Mutex::Locker locker(m_sequence_mutex);
1051 StateType state = eStateRunning;
1053 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1054 m_public_is_running.SetValue (true, eBroadcastNever);
1055 // Set the starting continue packet into "continue_packet". This packet
1056 // may change if we are interrupted and we continue after an async packet...
1057 std::string continue_packet(payload, packet_length);
1059 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1060 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
1062 bool got_async_packet = false;
1064 while (state == eStateRunning)
1066 if (!got_async_packet)
1069 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
1070 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1071 state = eStateInvalid;
1073 m_interrupt_sent = false;
1075 m_private_is_running.SetValue (true, eBroadcastAlways);
1078 got_async_packet = false;
1081 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1083 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1085 if (response.Empty())
1086 state = eStateInvalid;
1089 const char stop_type = response.GetChar();
1091 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1097 if (process->GetStopID() == 0)
1099 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1101 lldb::pid_t pid = GetCurrentProcessID ();
1102 if (pid != LLDB_INVALID_PROCESS_ID)
1103 process->SetID (pid);
1105 process->BuildDynamicRegisterInfo (true);
1108 // Privately notify any internal threads that we have stopped
1109 // in case we wanted to interrupt our process, yet we might
1110 // send a packet and continue without returning control to the
1112 m_private_is_running.SetValue (false, eBroadcastAlways);
1114 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1116 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1117 if (continue_after_async || m_interrupt_sent)
1119 // We sent an interrupt packet to stop the inferior process
1120 // for an async signal or to send an async packet while running
1121 // but we might have been single stepping and received the
1122 // stop packet for the step instead of for the interrupt packet.
1123 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1124 // is used, so if we get anything else, we need to try and
1125 // get another stop reply packet that may have been sent
1126 // due to sending the interrupt when the target is stopped
1127 // which will just re-send a copy of the last stop reply
1128 // packet. If we don't do this, then the reply for our
1129 // async packet will be the repeat stop reply packet and cause
1130 // a lot of trouble for us!
1131 if (signo != sigint_signo && signo != sigstop_signo)
1133 continue_after_async = false;
1135 // We didn't get a SIGINT or SIGSTOP, so try for a
1136 // very brief time (1 ms) to get another stop reply
1137 // packet to make sure it doesn't get in the way
1138 StringExtractorGDBRemote extra_stop_reply_packet;
1139 uint32_t timeout_usec = 1000;
1140 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
1142 switch (extra_stop_reply_packet.GetChar())
1146 // We did get an extra stop reply, which means
1147 // our interrupt didn't stop the target so we
1148 // shouldn't continue after the async signal
1149 // or packet is sent...
1150 continue_after_async = false;
1157 if (m_async_signal != -1)
1160 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1162 // Save off the async signal we are supposed to send
1163 const int async_signal = m_async_signal;
1164 // Clear the async signal member so we don't end up
1165 // sending the signal multiple times...
1166 m_async_signal = -1;
1167 // Check which signal we stopped with
1168 if (signo == async_signal)
1171 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1173 // We already stopped with a signal that we wanted
1174 // to stop with, so we are done
1178 // We stopped with a different signal that the one
1179 // we wanted to stop with, so now we must resume
1180 // with the signal we want
1181 char signal_packet[32];
1182 int signal_packet_len = 0;
1183 signal_packet_len = ::snprintf (signal_packet,
1184 sizeof (signal_packet),
1189 log->Printf ("async: stopped with signal %s, resume with %s",
1190 Host::GetSignalAsCString (signo),
1191 Host::GetSignalAsCString (async_signal));
1193 // Set the continue packet to resume even if the
1194 // interrupt didn't cause our stop (ignore continue_after_async)
1195 continue_packet.assign(signal_packet, signal_packet_len);
1199 else if (m_async_packet_predicate.GetValue())
1201 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
1203 // We are supposed to send an asynchronous packet while
1205 m_async_response.Clear();
1206 if (m_async_packet.empty())
1208 m_async_result = PacketResult::ErrorSendFailed;
1210 packet_log->Printf ("async: error: empty async packet");
1216 packet_log->Printf ("async: sending packet");
1218 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1219 m_async_packet.size(),
1223 // Let the other thread that was trying to send the async
1224 // packet know that the packet has been sent and response is
1226 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1229 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
1231 // Set the continue packet to resume if our interrupt
1232 // for the async packet did cause the stop
1233 if (continue_after_async)
1235 // Reverting this for now as it is causing deadlocks
1236 // in programs (<rdar://problem/11529853>). In the future
1237 // we should check our thread list and "do the right thing"
1238 // for new threads that show up while we stop and run async
1239 // packets. Setting the packet to 'c' to continue all threads
1240 // is the right thing to do 99.99% of the time because if a
1241 // thread was single stepping, and we sent an interrupt, we
1242 // will notice above that we didn't stop due to an interrupt
1243 // but stopped due to stepping and we would _not_ continue.
1244 continue_packet.assign (1, 'c');
1248 // Stop with signal and thread info
1249 state = eStateStopped;
1256 state = eStateExited;
1262 got_async_packet = true;
1263 std::string inferior_stdout;
1264 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1266 while ((ch = response.GetHexU8()) != '\0')
1267 inferior_stdout.append(1, ch);
1268 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1273 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1275 got_async_packet = true;
1276 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1277 if (m_partial_profile_data.length() > 0)
1279 m_partial_profile_data.append(input);
1280 input = m_partial_profile_data;
1281 m_partial_profile_data.clear();
1284 size_t found, pos = 0, len = input.length();
1285 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1287 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
1288 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1289 process->BroadcastAsyncProfileData (profile_data);
1291 pos = found + end_delimiter_len;
1296 // Last incomplete chunk.
1297 m_partial_profile_data = input.substr(pos);
1304 state = eStateInvalid;
1309 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1310 state = eStateInvalid;
1318 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
1319 state = eStateInvalid;
1323 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1324 response.SetFilePos(0);
1325 m_private_is_running.SetValue (false, eBroadcastAlways);
1326 m_public_is_running.SetValue (false, eBroadcastAlways);
1331 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1333 Mutex::Locker async_locker (m_async_mutex);
1334 m_async_signal = signo;
1335 bool timed_out = false;
1336 Mutex::Locker locker;
1337 if (SendInterrupt (locker, 1, timed_out))
1339 m_async_signal = -1;
1343 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
1344 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1345 // (the expected result), then it will send the halt packet. If it does succeed
1346 // then the caller that requested the interrupt will want to keep the sequence
1347 // locked down so that no one else can send packets while the caller has control.
1348 // This function usually gets called when we are running and need to stop the
1349 // target. It can also be used when we are running and we need to do something
1350 // else (like read/write memory), so we need to interrupt the running process
1351 // (gdb remote protocol requires this), and do what we need to do, then resume.
1354 GDBRemoteCommunicationClient::SendInterrupt
1356 Mutex::Locker& locker,
1357 uint32_t seconds_to_wait_for_stop,
1362 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
1366 // Only send an interrupt if our debugserver is running...
1367 if (GetSequenceMutex (locker))
1370 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1374 // Someone has the mutex locked waiting for a response or for the
1375 // inferior to stop, so send the interrupt on the down low...
1376 char ctrl_c = '\x03';
1377 ConnectionStatus status = eConnectionStatusSuccess;
1378 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
1380 log->PutCString("send packet: \\x03");
1381 if (bytes_written > 0)
1383 m_interrupt_sent = true;
1384 if (seconds_to_wait_for_stop)
1387 if (seconds_to_wait_for_stop)
1389 timeout = TimeValue::Now();
1390 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1392 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1395 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
1401 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
1407 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
1414 log->Printf ("SendInterrupt () - failed to write interrupt");
1422 log->Printf ("SendInterrupt () - not running");
1428 GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
1430 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
1433 // First try to retrieve the pid via the qProcessInfo request.
1434 GetCurrentProcessInfo (allow_lazy);
1435 if (m_curr_pid_is_valid == eLazyBoolYes)
1437 // We really got it.
1442 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1443 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1444 // The gdb remote protocol documents $qC as returning the thread id, which newer
1445 // debugserver and lldb-gdbserver stubs return correctly.
1446 StringExtractorGDBRemote response;
1447 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
1449 if (response.GetChar() == 'Q')
1451 if (response.GetChar() == 'C')
1453 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1454 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
1456 m_curr_pid_is_valid = eLazyBoolYes;
1464 return LLDB_INVALID_PROCESS_ID;
1468 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1471 StringExtractorGDBRemote response;
1472 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
1474 if (response.IsOKResponse())
1476 if (response.GetChar() == 'E')
1478 // A string the describes what failed when launching...
1479 error_str = response.GetStringRef().substr(1);
1483 error_str.assign ("unknown error occurred launching process");
1488 error_str.assign ("timed out waiting for app to launch");
1494 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
1496 // Since we don't get the send argv0 separate from the executable path, we need to
1497 // make sure to use the actual executable path found in the launch_info...
1498 std::vector<const char *> argv;
1499 FileSpec exe_file = launch_info.GetExecutableFile();
1500 std::string exe_path;
1501 const char *arg = NULL;
1502 const Args &launch_args = launch_info.GetArguments();
1504 exe_path = exe_file.GetPath(false);
1507 arg = launch_args.GetArgumentAtIndex(0);
1511 if (!exe_path.empty())
1513 argv.push_back(exe_path.c_str());
1514 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1517 argv.push_back(arg);
1522 StreamString packet;
1523 packet.PutChar('A');
1524 for (size_t i = 0, n = argv.size(); i < n; ++i)
1527 const int arg_len = strlen(arg);
1529 packet.PutChar(',');
1530 packet.Printf("%i,%i,", arg_len * 2, (int)i);
1531 packet.PutBytesAsRawHex8 (arg, arg_len);
1534 StringExtractorGDBRemote response;
1535 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1537 if (response.IsOKResponse())
1539 uint8_t error = response.GetError();
1548 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1550 if (name_equal_value && name_equal_value[0])
1552 StreamString packet;
1553 bool send_hex_encoding = false;
1554 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
1562 send_hex_encoding = true;
1570 // We have non printable characters, lets hex encode this...
1571 send_hex_encoding = true;
1575 StringExtractorGDBRemote response;
1576 if (send_hex_encoding)
1578 if (m_supports_QEnvironmentHexEncoded)
1580 packet.PutCString("QEnvironmentHexEncoded:");
1581 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1582 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1584 if (response.IsOKResponse())
1586 uint8_t error = response.GetError();
1589 if (response.IsUnsupportedResponse())
1590 m_supports_QEnvironmentHexEncoded = false;
1595 else if (m_supports_QEnvironment)
1597 packet.Printf("QEnvironment:%s", name_equal_value);
1598 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1600 if (response.IsOKResponse())
1602 uint8_t error = response.GetError();
1605 if (response.IsUnsupportedResponse())
1606 m_supports_QEnvironment = false;
1614 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1616 if (arch && arch[0])
1618 StreamString packet;
1619 packet.Printf("QLaunchArch:%s", arch);
1620 StringExtractorGDBRemote response;
1621 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1623 if (response.IsOKResponse())
1625 uint8_t error = response.GetError();
1634 GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1636 if (data && *data != '\0')
1638 StreamString packet;
1639 packet.Printf("QSetProcessEvent:%s", data);
1640 StringExtractorGDBRemote response;
1641 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1643 if (response.IsOKResponse())
1646 *was_supported = true;
1649 else if (response.IsUnsupportedResponse())
1652 *was_supported = false;
1657 uint8_t error = response.GetError();
1659 *was_supported = true;
1669 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1675 if (m_os_version_major != UINT32_MAX)
1677 major = m_os_version_major;
1678 minor = m_os_version_minor;
1679 update = m_os_version_update;
1687 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1691 if (!m_os_build.empty())
1703 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1707 if (!m_os_kernel.empty())
1718 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1722 if (!m_hostname.empty())
1733 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1740 const lldb_private::ArchSpec &
1741 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1743 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1744 GetCurrentProcessInfo ();
1745 return m_process_arch;
1749 GDBRemoteCommunicationClient::GetGDBServerVersion()
1751 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1753 m_gdb_server_name.clear();
1754 m_gdb_server_version = 0;
1755 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1757 StringExtractorGDBRemote response;
1758 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1760 if (response.IsNormalResponse())
1764 bool success = false;
1765 while (response.GetNameColonValue(name, value))
1767 if (name.compare("name") == 0)
1770 m_gdb_server_name.swap(value);
1772 else if (name.compare("version") == 0)
1774 size_t dot_pos = value.find('.');
1775 if (dot_pos != std::string::npos)
1776 value[dot_pos] = '\0';
1777 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
1778 if (version != UINT32_MAX)
1781 m_gdb_server_version = version;
1786 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1790 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1794 GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1796 CompressionType avail_type = CompressionType::None;
1797 std::string avail_name;
1799 #if defined (HAVE_LIBCOMPRESSION)
1800 // libcompression is weak linked so test if compression_decode_buffer() is available
1801 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1803 for (auto compression : supported_compressions)
1805 if (compression == "lzfse")
1807 avail_type = CompressionType::LZFSE;
1808 avail_name = compression;
1815 #if defined (HAVE_LIBCOMPRESSION)
1816 // libcompression is weak linked so test if compression_decode_buffer() is available
1817 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1819 for (auto compression : supported_compressions)
1821 if (compression == "zlib-deflate")
1823 avail_type = CompressionType::ZlibDeflate;
1824 avail_name = compression;
1831 #if defined (HAVE_LIBZ)
1832 if (avail_type == CompressionType::None)
1834 for (auto compression : supported_compressions)
1836 if (compression == "zlib-deflate")
1838 avail_type = CompressionType::ZlibDeflate;
1839 avail_name = compression;
1846 #if defined (HAVE_LIBCOMPRESSION)
1847 // libcompression is weak linked so test if compression_decode_buffer() is available
1848 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1850 for (auto compression : supported_compressions)
1852 if (compression == "lz4")
1854 avail_type = CompressionType::LZ4;
1855 avail_name = compression;
1862 #if defined (HAVE_LIBCOMPRESSION)
1863 // libcompression is weak linked so test if compression_decode_buffer() is available
1864 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1866 for (auto compression : supported_compressions)
1868 if (compression == "lzma")
1870 avail_type = CompressionType::LZMA;
1871 avail_name = compression;
1878 if (avail_type != CompressionType::None)
1880 StringExtractorGDBRemote response;
1881 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1882 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1885 if (response.IsOKResponse())
1887 m_compression_type = avail_type;
1893 GDBRemoteCommunicationClient::GetGDBServerProgramName()
1895 if (GetGDBServerVersion())
1897 if (!m_gdb_server_name.empty())
1898 return m_gdb_server_name.c_str();
1904 GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1906 if (GetGDBServerVersion())
1907 return m_gdb_server_version;
1912 GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1914 StringExtractorGDBRemote response;
1915 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1918 if (!response.IsNormalResponse())
1921 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1922 tid = response.GetHexMaxU32(true, -1);
1928 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1930 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1932 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1934 m_qHostInfo_is_valid = eLazyBoolNo;
1935 StringExtractorGDBRemote response;
1936 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
1938 if (response.IsNormalResponse())
1942 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1944 std::string arch_name;
1945 std::string os_name;
1946 std::string vendor_name;
1948 std::string distribution_id;
1949 uint32_t pointer_byte_size = 0;
1950 StringExtractor extractor;
1951 ByteOrder byte_order = eByteOrderInvalid;
1952 uint32_t num_keys_decoded = 0;
1953 while (response.GetNameColonValue(name, value))
1955 if (name.compare("cputype") == 0)
1957 // exception type in big endian hex
1958 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1959 if (cpu != LLDB_INVALID_CPUTYPE)
1962 else if (name.compare("cpusubtype") == 0)
1964 // exception count in big endian hex
1965 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
1969 else if (name.compare("arch") == 0)
1971 arch_name.swap (value);
1974 else if (name.compare("triple") == 0)
1976 extractor.GetStringRef ().swap (value);
1977 extractor.SetFilePos(0);
1978 extractor.GetHexByteString (triple);
1981 else if (name.compare ("distribution_id") == 0)
1983 extractor.GetStringRef ().swap (value);
1984 extractor.SetFilePos (0);
1985 extractor.GetHexByteString (distribution_id);
1988 else if (name.compare("os_build") == 0)
1990 extractor.GetStringRef().swap(value);
1991 extractor.SetFilePos(0);
1992 extractor.GetHexByteString (m_os_build);
1995 else if (name.compare("hostname") == 0)
1997 extractor.GetStringRef().swap(value);
1998 extractor.SetFilePos(0);
1999 extractor.GetHexByteString (m_hostname);
2002 else if (name.compare("os_kernel") == 0)
2004 extractor.GetStringRef().swap(value);
2005 extractor.SetFilePos(0);
2006 extractor.GetHexByteString (m_os_kernel);
2009 else if (name.compare("ostype") == 0)
2011 os_name.swap (value);
2014 else if (name.compare("vendor") == 0)
2016 vendor_name.swap(value);
2019 else if (name.compare("endian") == 0)
2022 if (value.compare("little") == 0)
2023 byte_order = eByteOrderLittle;
2024 else if (value.compare("big") == 0)
2025 byte_order = eByteOrderBig;
2026 else if (value.compare("pdp") == 0)
2027 byte_order = eByteOrderPDP;
2031 else if (name.compare("ptrsize") == 0)
2033 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
2034 if (pointer_byte_size != 0)
2037 else if (name.compare("os_version") == 0)
2039 Args::StringToVersion (value.c_str(),
2042 m_os_version_update);
2043 if (m_os_version_major != UINT32_MAX)
2046 else if (name.compare("watchpoint_exceptions_received") == 0)
2049 if (strcmp(value.c_str(),"before") == 0)
2050 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2051 else if (strcmp(value.c_str(),"after") == 0)
2052 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2056 else if (name.compare("default_packet_timeout") == 0)
2058 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
2059 if (m_default_packet_timeout > 0)
2061 SetPacketTimeout(m_default_packet_timeout);
2068 if (num_keys_decoded > 0)
2069 m_qHostInfo_is_valid = eLazyBoolYes;
2073 if (arch_name.empty())
2075 if (cpu != LLDB_INVALID_CPUTYPE)
2077 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2078 if (pointer_byte_size)
2080 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2082 if (byte_order != eByteOrderInvalid)
2084 assert (byte_order == m_host_arch.GetByteOrder());
2087 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2089 switch (m_host_arch.GetMachine())
2091 case llvm::Triple::aarch64:
2092 case llvm::Triple::arm:
2093 case llvm::Triple::thumb:
2101 if (!vendor_name.empty())
2102 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2103 if (!os_name.empty())
2104 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2111 triple += arch_name;
2112 if (!vendor_name.empty() || !os_name.empty())
2115 if (vendor_name.empty())
2116 triple += "unknown";
2118 triple += vendor_name;
2120 if (os_name.empty())
2121 triple += "unknown";
2125 m_host_arch.SetTriple (triple.c_str());
2127 llvm::Triple &host_triple = m_host_arch.GetTriple();
2128 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2130 switch (m_host_arch.GetMachine())
2132 case llvm::Triple::aarch64:
2133 case llvm::Triple::arm:
2134 case llvm::Triple::thumb:
2135 host_triple.setOS(llvm::Triple::IOS);
2138 host_triple.setOS(llvm::Triple::MacOSX);
2142 if (pointer_byte_size)
2144 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2146 if (byte_order != eByteOrderInvalid)
2148 assert (byte_order == m_host_arch.GetByteOrder());
2155 m_host_arch.SetTriple (triple.c_str());
2156 if (pointer_byte_size)
2158 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2160 if (byte_order != eByteOrderInvalid)
2162 assert (byte_order == m_host_arch.GetByteOrder());
2166 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 ());
2168 if (!distribution_id.empty ())
2169 m_host_arch.SetDistributionId (distribution_id.c_str ());
2173 return m_qHostInfo_is_valid == eLazyBoolYes;
2177 GDBRemoteCommunicationClient::SendAttach
2180 StringExtractorGDBRemote& response
2183 if (pid != LLDB_INVALID_PROCESS_ID)
2186 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
2187 assert (packet_len < (int)sizeof(packet));
2188 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2190 if (response.IsErrorResponse())
2191 return response.GetError();
2199 GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2201 StreamString packet;
2202 packet.PutCString("I");
2203 packet.PutBytesAsRawHex8(data, data_len);
2204 StringExtractorGDBRemote response;
2205 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2209 return response.GetError();
2213 const lldb_private::ArchSpec &
2214 GDBRemoteCommunicationClient::GetHostArchitecture ()
2216 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2222 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2224 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2226 return m_default_packet_timeout;
2230 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2232 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
2234 m_supports_alloc_dealloc_memory = eLazyBoolYes;
2236 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
2238 permissions & lldb::ePermissionsReadable ? "r" : "",
2239 permissions & lldb::ePermissionsWritable ? "w" : "",
2240 permissions & lldb::ePermissionsExecutable ? "x" : "");
2241 assert (packet_len < (int)sizeof(packet));
2242 StringExtractorGDBRemote response;
2243 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2245 if (response.IsUnsupportedResponse())
2246 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2247 else if (!response.IsErrorResponse())
2248 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2252 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2255 return LLDB_INVALID_ADDRESS;
2259 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2261 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
2263 m_supports_alloc_dealloc_memory = eLazyBoolYes;
2265 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
2266 assert (packet_len < (int)sizeof(packet));
2267 StringExtractorGDBRemote response;
2268 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2270 if (response.IsUnsupportedResponse())
2271 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2272 else if (response.IsOKResponse())
2277 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2284 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
2290 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2293 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
2294 assert (packet_len < (int)sizeof(packet));
2295 StringExtractorGDBRemote response;
2296 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2298 m_supports_detach_stay_stopped = eLazyBoolYes;
2302 m_supports_detach_stay_stopped = eLazyBoolNo;
2306 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2308 error.SetErrorString("Stays stopped not supported by this target.");
2313 StringExtractorGDBRemote response;
2314 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
2315 if (packet_result != PacketResult::Success)
2316 error.SetErrorString ("Sending extended disconnect packet failed.");
2321 StringExtractorGDBRemote response;
2322 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
2323 if (packet_result != PacketResult::Success)
2324 error.SetErrorString ("Sending disconnect packet failed.");
2330 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2331 lldb_private::MemoryRegionInfo ®ion_info)
2334 region_info.Clear();
2336 if (m_supports_memory_region_info != eLazyBoolNo)
2338 m_supports_memory_region_info = eLazyBoolYes;
2340 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
2341 assert (packet_len < (int)sizeof(packet));
2342 StringExtractorGDBRemote response;
2343 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2348 bool success = true;
2349 bool saw_permissions = false;
2350 while (success && response.GetNameColonValue(name, value))
2352 if (name.compare ("start") == 0)
2354 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
2356 region_info.GetRange().SetRangeBase(addr_value);
2358 else if (name.compare ("size") == 0)
2360 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
2362 region_info.GetRange().SetByteSize (addr_value);
2364 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
2366 saw_permissions = true;
2367 if (region_info.GetRange().Contains (addr))
2369 if (value.find('r') != std::string::npos)
2370 region_info.SetReadable (MemoryRegionInfo::eYes);
2372 region_info.SetReadable (MemoryRegionInfo::eNo);
2374 if (value.find('w') != std::string::npos)
2375 region_info.SetWritable (MemoryRegionInfo::eYes);
2377 region_info.SetWritable (MemoryRegionInfo::eNo);
2379 if (value.find('x') != std::string::npos)
2380 region_info.SetExecutable (MemoryRegionInfo::eYes);
2382 region_info.SetExecutable (MemoryRegionInfo::eNo);
2386 // The reported region does not contain this address -- we're looking at an unmapped page
2387 region_info.SetReadable (MemoryRegionInfo::eNo);
2388 region_info.SetWritable (MemoryRegionInfo::eNo);
2389 region_info.SetExecutable (MemoryRegionInfo::eNo);
2392 else if (name.compare ("error") == 0)
2394 StringExtractorGDBRemote name_extractor;
2395 // Swap "value" over into "name_extractor"
2396 name_extractor.GetStringRef().swap(value);
2397 // Now convert the HEX bytes into a string value
2398 name_extractor.GetHexByteString (value);
2399 error.SetErrorString(value.c_str());
2403 // We got a valid address range back but no permissions -- which means this is an unmapped page
2404 if (region_info.GetRange().IsValid() && saw_permissions == false)
2406 region_info.SetReadable (MemoryRegionInfo::eNo);
2407 region_info.SetWritable (MemoryRegionInfo::eNo);
2408 region_info.SetExecutable (MemoryRegionInfo::eNo);
2413 m_supports_memory_region_info = eLazyBoolNo;
2417 if (m_supports_memory_region_info == eLazyBoolNo)
2419 error.SetErrorString("qMemoryRegionInfo is not supported");
2422 region_info.Clear();
2428 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2432 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2434 num = m_num_supported_hardware_watchpoints;
2438 // Set num to 0 first.
2440 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2443 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
2444 assert (packet_len < (int)sizeof(packet));
2445 StringExtractorGDBRemote response;
2446 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2448 m_supports_watchpoint_support_info = eLazyBoolYes;
2451 while (response.GetNameColonValue(name, value))
2453 if (name.compare ("num") == 0)
2455 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
2456 m_num_supported_hardware_watchpoints = num;
2462 m_supports_watchpoint_support_info = eLazyBoolNo;
2466 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2468 error.SetErrorString("qWatchpointSupportInfo is not supported");
2475 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2477 Error error(GetWatchpointSupportInfo(num));
2478 if (error.Success())
2479 error = GetWatchpointsTriggerAfterInstruction(after);
2484 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2488 // we assume watchpoints will happen after running the relevant opcode
2489 // and we only want to override this behavior if we have explicitly
2490 // received a qHostInfo telling us otherwise
2491 if (m_qHostInfo_is_valid != eLazyBoolYes)
2494 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2499 GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
2503 std::string path{file_spec.GetPath(false)};
2504 StreamString packet;
2505 packet.PutCString("QSetSTDIN:");
2506 packet.PutCStringAsRawHex8(path.c_str());
2508 StringExtractorGDBRemote response;
2509 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2511 if (response.IsOKResponse())
2513 uint8_t error = response.GetError();
2522 GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
2526 std::string path{file_spec.GetPath(false)};
2527 StreamString packet;
2528 packet.PutCString("QSetSTDOUT:");
2529 packet.PutCStringAsRawHex8(path.c_str());
2531 StringExtractorGDBRemote response;
2532 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2534 if (response.IsOKResponse())
2536 uint8_t error = response.GetError();
2545 GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
2549 std::string path{file_spec.GetPath(false)};
2550 StreamString packet;
2551 packet.PutCString("QSetSTDERR:");
2552 packet.PutCStringAsRawHex8(path.c_str());
2554 StringExtractorGDBRemote response;
2555 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2557 if (response.IsOKResponse())
2559 uint8_t error = response.GetError();
2568 GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
2570 StringExtractorGDBRemote response;
2571 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2573 if (response.IsUnsupportedResponse())
2575 if (response.IsErrorResponse())
2578 response.GetHexByteString(cwd);
2579 working_dir.SetFile(cwd, false, GetHostArchitecture());
2580 return !cwd.empty();
2586 GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
2590 std::string path{working_dir.GetPath(false)};
2591 StreamString packet;
2592 packet.PutCString("QSetWorkingDir:");
2593 packet.PutCStringAsRawHex8(path.c_str());
2595 StringExtractorGDBRemote response;
2596 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2598 if (response.IsOKResponse())
2600 uint8_t error = response.GetError();
2609 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2612 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2613 assert (packet_len < (int)sizeof(packet));
2614 StringExtractorGDBRemote response;
2615 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2617 if (response.IsOKResponse())
2619 uint8_t error = response.GetError();
2627 GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2630 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2631 assert (packet_len < (int)sizeof(packet));
2632 StringExtractorGDBRemote response;
2633 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2635 if (response.IsOKResponse())
2637 uint8_t error = response.GetError();
2646 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2648 if (response.IsNormalResponse())
2652 StringExtractor extractor;
2654 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2657 std::string os_type;
2659 while (response.GetNameColonValue(name, value))
2661 if (name.compare("pid") == 0)
2663 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2665 else if (name.compare("ppid") == 0)
2667 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2669 else if (name.compare("uid") == 0)
2671 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2673 else if (name.compare("euid") == 0)
2675 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2677 else if (name.compare("gid") == 0)
2679 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2681 else if (name.compare("egid") == 0)
2683 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2685 else if (name.compare("triple") == 0)
2687 StringExtractor extractor;
2688 extractor.GetStringRef().swap(value);
2689 extractor.SetFilePos(0);
2690 extractor.GetHexByteString (value);
2691 process_info.GetArchitecture ().SetTriple (value.c_str());
2693 else if (name.compare("name") == 0)
2695 StringExtractor extractor;
2696 // The process name from ASCII hex bytes since we can't
2697 // control the characters in a process name
2698 extractor.GetStringRef().swap(value);
2699 extractor.SetFilePos(0);
2700 extractor.GetHexByteString (value);
2701 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2703 else if (name.compare("cputype") == 0)
2705 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2707 else if (name.compare("cpusubtype") == 0)
2709 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2711 else if (name.compare("vendor") == 0)
2715 else if (name.compare("ostype") == 0)
2721 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2723 if (vendor == "apple")
2725 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2726 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2727 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2731 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2738 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2740 process_info.Clear();
2742 if (m_supports_qProcessInfoPID)
2745 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2746 assert (packet_len < (int)sizeof(packet));
2747 StringExtractorGDBRemote response;
2748 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2750 return DecodeProcessInfoResponse (response, process_info);
2754 m_supports_qProcessInfoPID = false;
2762 GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
2764 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2768 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2770 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2776 StringExtractorGDBRemote response;
2777 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2779 if (response.IsNormalResponse())
2783 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2785 std::string arch_name;
2786 std::string os_name;
2787 std::string vendor_name;
2789 uint32_t pointer_byte_size = 0;
2790 StringExtractor extractor;
2791 ByteOrder byte_order = eByteOrderInvalid;
2792 uint32_t num_keys_decoded = 0;
2793 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2794 while (response.GetNameColonValue(name, value))
2796 if (name.compare("cputype") == 0)
2798 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2799 if (cpu != LLDB_INVALID_CPUTYPE)
2802 else if (name.compare("cpusubtype") == 0)
2804 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2808 else if (name.compare("triple") == 0)
2810 StringExtractor extractor;
2811 extractor.GetStringRef().swap(value);
2812 extractor.SetFilePos(0);
2813 extractor.GetHexByteString (triple);
2816 else if (name.compare("ostype") == 0)
2818 os_name.swap (value);
2821 else if (name.compare("vendor") == 0)
2823 vendor_name.swap(value);
2826 else if (name.compare("endian") == 0)
2829 if (value.compare("little") == 0)
2830 byte_order = eByteOrderLittle;
2831 else if (value.compare("big") == 0)
2832 byte_order = eByteOrderBig;
2833 else if (value.compare("pdp") == 0)
2834 byte_order = eByteOrderPDP;
2838 else if (name.compare("ptrsize") == 0)
2840 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2841 if (pointer_byte_size != 0)
2844 else if (name.compare("pid") == 0)
2846 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
2847 if (pid != LLDB_INVALID_PROCESS_ID)
2851 if (num_keys_decoded > 0)
2852 m_qProcessInfo_is_valid = eLazyBoolYes;
2853 if (pid != LLDB_INVALID_PROCESS_ID)
2855 m_curr_pid_is_valid = eLazyBoolYes;
2859 // Set the ArchSpec from the triple if we have it.
2860 if (!triple.empty ())
2862 m_process_arch.SetTriple (triple.c_str ());
2863 if (pointer_byte_size)
2865 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2868 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2870 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2872 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2873 switch (triple.getObjectFormat()) {
2874 case llvm::Triple::MachO:
2875 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2877 case llvm::Triple::ELF:
2878 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2880 case llvm::Triple::COFF:
2881 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2883 case llvm::Triple::UnknownObjectFormat:
2885 log->Printf("error: failed to determine target architecture");
2889 if (pointer_byte_size)
2891 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2893 if (byte_order != eByteOrderInvalid)
2895 assert (byte_order == m_process_arch.GetByteOrder());
2897 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2898 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2899 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2900 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2907 m_qProcessInfo_is_valid = eLazyBoolNo;
2915 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2916 ProcessInstanceInfoList &process_infos)
2918 process_infos.Clear();
2920 if (m_supports_qfProcessInfo)
2922 StreamString packet;
2923 packet.PutCString ("qfProcessInfo");
2924 if (!match_info.MatchAllProcesses())
2926 packet.PutChar (':');
2927 const char *name = match_info.GetProcessInfo().GetName();
2928 bool has_name_match = false;
2929 if (name && name[0])
2931 has_name_match = true;
2932 NameMatchType name_match_type = match_info.GetNameMatchType();
2933 switch (name_match_type)
2935 case eNameMatchIgnore:
2936 has_name_match = false;
2939 case eNameMatchEquals:
2940 packet.PutCString ("name_match:equals;");
2943 case eNameMatchContains:
2944 packet.PutCString ("name_match:contains;");
2947 case eNameMatchStartsWith:
2948 packet.PutCString ("name_match:starts_with;");
2951 case eNameMatchEndsWith:
2952 packet.PutCString ("name_match:ends_with;");
2955 case eNameMatchRegularExpression:
2956 packet.PutCString ("name_match:regex;");
2961 packet.PutCString ("name:");
2962 packet.PutBytesAsRawHex8(name, ::strlen(name));
2963 packet.PutChar (';');
2967 if (match_info.GetProcessInfo().ProcessIDIsValid())
2968 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2969 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2970 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2971 if (match_info.GetProcessInfo().UserIDIsValid())
2972 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2973 if (match_info.GetProcessInfo().GroupIDIsValid())
2974 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2975 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2976 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2977 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2978 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2979 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2980 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2981 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2983 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2984 const llvm::Triple &triple = match_arch.GetTriple();
2985 packet.PutCString("triple:");
2986 packet.PutCString(triple.getTriple().c_str());
2987 packet.PutChar (';');
2990 StringExtractorGDBRemote response;
2991 // Increase timeout as the first qfProcessInfo packet takes a long time
2992 // on Android. The value of 1min was arrived at empirically.
2993 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
2994 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2998 ProcessInstanceInfo process_info;
2999 if (!DecodeProcessInfoResponse (response, process_info))
3001 process_infos.Append(process_info);
3002 response.GetStringRef().clear();
3003 response.SetFilePos(0);
3004 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
3008 m_supports_qfProcessInfo = false;
3012 return process_infos.GetSize();
3017 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3019 if (m_supports_qUserName)
3022 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
3023 assert (packet_len < (int)sizeof(packet));
3024 StringExtractorGDBRemote response;
3025 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3027 if (response.IsNormalResponse())
3029 // Make sure we parsed the right number of characters. The response is
3030 // the hex encoded user name and should make up the entire packet.
3031 // If there are any non-hex ASCII bytes, the length won't match below..
3032 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3038 m_supports_qUserName = false;
3047 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3049 if (m_supports_qGroupName)
3052 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
3053 assert (packet_len < (int)sizeof(packet));
3054 StringExtractorGDBRemote response;
3055 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3057 if (response.IsNormalResponse())
3059 // Make sure we parsed the right number of characters. The response is
3060 // the hex encoded group name and should make up the entire packet.
3061 // If there are any non-hex ASCII bytes, the length won't match below..
3062 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3068 m_supports_qGroupName = false;
3076 GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3078 // Form non-stop packet request
3080 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3081 assert(packet_len < (int)sizeof(packet));
3083 StringExtractorGDBRemote response;
3085 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3086 if (response.IsOKResponse())
3089 // Failed or not supported
3095 MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3098 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3099 uint32_t bytes_left = send_size;
3100 while (bytes_left > 0)
3102 if (bytes_left >= 26)
3104 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3109 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3115 template<typename T>
3116 T calculate_standard_deviation(const std::vector<T> &v)
3118 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3119 T mean = sum / (T)v.size();
3121 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3123 accum += delta * delta;
3126 T stdev = sqrt(accum / (v.size()-1));
3131 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
3134 TimeValue start_time, end_time;
3135 uint64_t total_time_nsec;
3136 if (SendSpeedTestPacket (0, 0))
3138 StreamString packet;
3140 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3142 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3145 uint32_t result_idx = 0;
3147 std::vector<float> packet_times;
3149 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3151 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3153 MakeSpeedTestPacket (packet, send_size, recv_size);
3155 packet_times.clear();
3156 // Test how long it takes to send 'num_packets' packets
3157 start_time = TimeValue::Now();
3158 for (i=0; i<num_packets; ++i)
3160 TimeValue packet_start_time = TimeValue::Now();
3161 StringExtractorGDBRemote response;
3162 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3163 TimeValue packet_end_time = TimeValue::Now();
3164 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3165 packet_times.push_back((float)packet_time_nsec);
3167 end_time = TimeValue::Now();
3168 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3170 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3171 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3172 float average_ms_per_packet = total_ms / num_packets;
3173 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3176 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);
3181 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",
3184 total_time_nsec / TimeValue::NanoSecPerSec,
3185 total_time_nsec % TimeValue::NanoSecPerSec,
3187 average_ms_per_packet,
3188 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
3194 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3196 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3198 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3200 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3204 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3206 MakeSpeedTestPacket (packet, send_size, recv_size);
3208 // If we have a receive size, test how long it takes to receive 4MB of data
3211 start_time = TimeValue::Now();
3212 uint32_t bytes_read = 0;
3213 uint32_t packet_count = 0;
3214 while (bytes_read < k_recv_amount)
3216 StringExtractorGDBRemote response;
3217 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3218 bytes_read += recv_size;
3221 end_time = TimeValue::Now();
3222 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3223 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3224 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3225 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3226 float average_ms_per_packet = total_ms / packet_count;
3230 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);
3235 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",
3240 total_time_nsec / TimeValue::NanoSecPerSec,
3241 total_time_nsec % TimeValue::NanoSecPerSec,
3244 average_ms_per_packet);
3250 strm.Printf("\n ]\n }\n}\n");
3257 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3259 StreamString packet;
3260 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3261 uint32_t bytes_left = send_size;
3262 while (bytes_left > 0)
3264 if (bytes_left >= 26)
3266 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3271 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3276 StringExtractorGDBRemote response;
3277 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
3281 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
3283 pid = LLDB_INVALID_PROCESS_ID;
3284 StringExtractorGDBRemote response;
3285 StreamString stream;
3286 stream.PutCString("qLaunchGDBServer;");
3287 std::string hostname;
3288 if (remote_accept_hostname && remote_accept_hostname[0])
3289 hostname = remote_accept_hostname;
3292 if (HostInfo::GetHostname(hostname))
3294 // Make the GDB server we launch only accept connections from this host
3295 stream.Printf("host:%s;", hostname.c_str());
3299 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3300 stream.Printf("host:*;");
3303 const char *packet = stream.GetData();
3304 int packet_len = stream.GetSize();
3306 // give the process a few seconds to startup
3307 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3309 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3314 while (response.GetNameColonValue(name, value))
3316 if (name.compare("port") == 0)
3317 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
3318 else if (name.compare("pid") == 0)
3319 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
3327 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3329 StreamString stream;
3330 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3331 const char *packet = stream.GetData();
3332 int packet_len = stream.GetSize();
3334 StringExtractorGDBRemote response;
3335 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3337 if (response.IsOKResponse())
3344 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
3346 if (m_curr_tid == tid)
3351 if (tid == UINT64_MAX)
3352 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
3354 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
3355 assert (packet_len + 1 < (int)sizeof(packet));
3356 StringExtractorGDBRemote response;
3357 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3359 if (response.IsOKResponse())
3369 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
3371 if (m_curr_tid_run == tid)
3376 if (tid == UINT64_MAX)
3377 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
3379 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3381 assert (packet_len + 1 < (int)sizeof(packet));
3382 StringExtractorGDBRemote response;
3383 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3385 if (response.IsOKResponse())
3387 m_curr_tid_run = tid;
3395 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3397 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
3398 return response.IsNormalResponse();
3403 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
3405 if (m_supports_qThreadStopInfo)
3408 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3409 assert (packet_len < (int)sizeof(packet));
3410 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3412 if (response.IsUnsupportedResponse())
3413 m_supports_qThreadStopInfo = false;
3414 else if (response.IsNormalResponse())
3421 m_supports_qThreadStopInfo = false;
3429 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3431 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3433 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3434 __FUNCTION__, insert ? "add" : "remove", addr);
3436 // Check if the stub is known not to support this breakpoint type
3437 if (!SupportsGDBStoppointPacket(type))
3439 // Construct the breakpoint packet
3441 const int packet_len = ::snprintf (packet,
3443 "%c%i,%" PRIx64 ",%x",
3448 // Check we haven't overwritten the end of the packet buffer
3449 assert (packet_len + 1 < (int)sizeof(packet));
3450 StringExtractorGDBRemote response;
3451 // Try to send the breakpoint packet, and check that it was correctly sent
3452 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
3454 // Receive and OK packet when the breakpoint successfully placed
3455 if (response.IsOKResponse())
3458 // Error while setting breakpoint, send back specific error
3459 if (response.IsErrorResponse())
3460 return response.GetError();
3462 // Empty packet informs us that breakpoint is not supported
3463 if (response.IsUnsupportedResponse())
3465 // Disable this breakpoint type since it is unsupported
3468 case eBreakpointSoftware: m_supports_z0 = false; break;
3469 case eBreakpointHardware: m_supports_z1 = false; break;
3470 case eWatchpointWrite: m_supports_z2 = false; break;
3471 case eWatchpointRead: m_supports_z3 = false; break;
3472 case eWatchpointReadWrite: m_supports_z4 = false; break;
3473 case eStoppointInvalid: return UINT8_MAX;
3477 // Signal generic failure
3482 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3483 bool &sequence_mutex_unavailable)
3485 Mutex::Locker locker;
3488 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
3490 sequence_mutex_unavailable = false;
3491 StringExtractorGDBRemote response;
3493 PacketResult packet_result;
3494 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3495 packet_result == PacketResult::Success && response.IsNormalResponse();
3496 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
3498 char ch = response.GetChar();
3505 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3507 if (tid != LLDB_INVALID_THREAD_ID)
3509 thread_ids.push_back (tid);
3511 ch = response.GetChar(); // Skip the command separator
3512 } while (ch == ','); // Make sure we got a comma separator
3518 #if defined (LLDB_CONFIGURATION_DEBUG)
3519 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3521 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3523 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3525 sequence_mutex_unavailable = true;
3527 return thread_ids.size();
3531 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3535 StringExtractorGDBRemote response;
3536 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3538 if (response.IsNormalResponse())
3539 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3542 return LLDB_INVALID_ADDRESS;
3546 GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3547 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3548 int *status_ptr, // Pass NULL if you don't want the process exit status
3549 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3550 std::string *command_output, // Pass NULL if you don't want the command output
3551 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
3553 lldb_private::StreamString stream;
3554 stream.PutCString("qPlatform_shell:");
3555 stream.PutBytesAsRawHex8(command, strlen(command));
3556 stream.PutChar(',');
3557 stream.PutHex32(timeout_sec);
3560 std::string path{working_dir.GetPath(false)};
3561 stream.PutChar(',');
3562 stream.PutCStringAsRawHex8(path.c_str());
3564 const char *packet = stream.GetData();
3565 int packet_len = stream.GetSize();
3566 StringExtractorGDBRemote response;
3567 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3569 if (response.GetChar() != 'F')
3570 return Error("malformed reply");
3571 if (response.GetChar() != ',')
3572 return Error("malformed reply");
3573 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3574 if (exitcode == UINT32_MAX)
3575 return Error("unable to run remote process");
3576 else if (status_ptr)
3577 *status_ptr = exitcode;
3578 if (response.GetChar() != ',')
3579 return Error("malformed reply");
3580 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3583 if (response.GetChar() != ',')
3584 return Error("malformed reply");
3586 response.GetEscapedBinaryData(output);
3588 command_output->assign(output);
3591 return Error("unable to send packet");
3595 GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3596 uint32_t file_permissions)
3598 std::string path{file_spec.GetPath(false)};
3599 lldb_private::StreamString stream;
3600 stream.PutCString("qPlatform_mkdir:");
3601 stream.PutHex32(file_permissions);
3602 stream.PutChar(',');
3603 stream.PutCStringAsRawHex8(path.c_str());
3604 const char *packet = stream.GetData();
3605 int packet_len = stream.GetSize();
3606 StringExtractorGDBRemote response;
3608 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3609 return Error("failed to send '%s' packet", packet);
3611 if (response.GetChar() != 'F')
3612 return Error("invalid response to '%s' packet", packet);
3614 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3618 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3619 uint32_t file_permissions)
3621 std::string path{file_spec.GetPath(false)};
3622 lldb_private::StreamString stream;
3623 stream.PutCString("qPlatform_chmod:");
3624 stream.PutHex32(file_permissions);
3625 stream.PutChar(',');
3626 stream.PutCStringAsRawHex8(path.c_str());
3627 const char *packet = stream.GetData();
3628 int packet_len = stream.GetSize();
3629 StringExtractorGDBRemote response;
3631 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3632 return Error("failed to send '%s' packet", packet);
3634 if (response.GetChar() != 'F')
3635 return Error("invalid response to '%s' packet", packet);
3637 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3641 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3642 uint64_t fail_result,
3645 response.SetFilePos(0);
3646 if (response.GetChar() != 'F')
3648 int32_t result = response.GetS32 (-2);
3651 if (response.GetChar() == ',')
3653 int result_errno = response.GetS32 (-2);
3654 if (result_errno != -2)
3655 error.SetError(result_errno, eErrorTypePOSIX);
3657 error.SetError(-1, eErrorTypeGeneric);
3664 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3669 std::string path(file_spec.GetPath(false));
3670 lldb_private::StreamString stream;
3671 stream.PutCString("vFile:open:");
3674 stream.PutCStringAsRawHex8(path.c_str());
3675 stream.PutChar(',');
3676 stream.PutHex32(flags);
3677 stream.PutChar(',');
3678 stream.PutHex32(mode);
3679 const char* packet = stream.GetData();
3680 int packet_len = stream.GetSize();
3681 StringExtractorGDBRemote response;
3682 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3684 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3690 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3693 lldb_private::StreamString stream;
3694 stream.Printf("vFile:close:%i", (int)fd);
3695 const char* packet = stream.GetData();
3696 int packet_len = stream.GetSize();
3697 StringExtractorGDBRemote response;
3698 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3700 return ParseHostIOPacketResponse (response, -1, error) == 0;
3705 // Extension of host I/O packets to get the file size.
3707 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3709 std::string path(file_spec.GetPath(false));
3710 lldb_private::StreamString stream;
3711 stream.PutCString("vFile:size:");
3712 stream.PutCStringAsRawHex8(path.c_str());
3713 const char* packet = stream.GetData();
3714 int packet_len = stream.GetSize();
3715 StringExtractorGDBRemote response;
3716 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3718 if (response.GetChar() != 'F')
3720 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3727 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3728 uint32_t &file_permissions)
3730 std::string path{file_spec.GetPath(false)};
3732 lldb_private::StreamString stream;
3733 stream.PutCString("vFile:mode:");
3734 stream.PutCStringAsRawHex8(path.c_str());
3735 const char* packet = stream.GetData();
3736 int packet_len = stream.GetSize();
3737 StringExtractorGDBRemote response;
3738 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3740 if (response.GetChar() != 'F')
3742 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3746 const uint32_t mode = response.GetS32(-1);
3747 if (static_cast<int32_t>(mode) == -1)
3749 if (response.GetChar() == ',')
3751 int response_errno = response.GetS32(-1);
3752 if (response_errno > 0)
3753 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3755 error.SetErrorToGenericError();
3758 error.SetErrorToGenericError();
3762 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3768 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3774 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3780 lldb_private::StreamString stream;
3781 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3782 const char* packet = stream.GetData();
3783 int packet_len = stream.GetSize();
3784 StringExtractorGDBRemote response;
3785 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3787 if (response.GetChar() != 'F')
3789 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3790 if (retcode == UINT32_MAX)
3792 const char next = (response.Peek() ? *response.Peek() : 0);
3797 response.GetChar(); // skip the semicolon
3799 if (response.GetEscapedBinaryData(buffer))
3801 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3802 if (data_to_write > 0)
3803 memcpy(dst, &buffer[0], data_to_write);
3804 return data_to_write;
3812 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3818 lldb_private::StreamGDBRemote stream;
3819 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3820 stream.PutEscapedBytes(src, src_len);
3821 const char* packet = stream.GetData();
3822 int packet_len = stream.GetSize();
3823 StringExtractorGDBRemote response;
3824 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3826 if (response.GetChar() != 'F')
3828 error.SetErrorStringWithFormat("write file failed");
3831 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3832 if (bytes_written == UINT64_MAX)
3834 error.SetErrorToGenericError();
3835 if (response.GetChar() == ',')
3837 int response_errno = response.GetS32(-1);
3838 if (response_errno > 0)
3839 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3843 return bytes_written;
3847 error.SetErrorString ("failed to send vFile:pwrite packet");
3853 GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
3855 std::string src_path{src.GetPath(false)},
3856 dst_path{dst.GetPath(false)};
3858 lldb_private::StreamGDBRemote stream;
3859 stream.PutCString("vFile:symlink:");
3860 // the unix symlink() command reverses its parameters where the dst if first,
3861 // so we follow suit here
3862 stream.PutCStringAsRawHex8(dst_path.c_str());
3863 stream.PutChar(',');
3864 stream.PutCStringAsRawHex8(src_path.c_str());
3865 const char* packet = stream.GetData();
3866 int packet_len = stream.GetSize();
3867 StringExtractorGDBRemote response;
3868 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3870 if (response.GetChar() == 'F')
3872 uint32_t result = response.GetU32(UINT32_MAX);
3875 error.SetErrorToGenericError();
3876 if (response.GetChar() == ',')
3878 int response_errno = response.GetS32(-1);
3879 if (response_errno > 0)
3880 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3886 // Should have returned with 'F<result>[,<errno>]'
3887 error.SetErrorStringWithFormat("symlink failed");
3892 error.SetErrorString ("failed to send vFile:symlink packet");
3898 GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
3900 std::string path{file_spec.GetPath(false)};
3902 lldb_private::StreamGDBRemote stream;
3903 stream.PutCString("vFile:unlink:");
3904 // the unix symlink() command reverses its parameters where the dst if first,
3905 // so we follow suit here
3906 stream.PutCStringAsRawHex8(path.c_str());
3907 const char* packet = stream.GetData();
3908 int packet_len = stream.GetSize();
3909 StringExtractorGDBRemote response;
3910 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3912 if (response.GetChar() == 'F')
3914 uint32_t result = response.GetU32(UINT32_MAX);
3917 error.SetErrorToGenericError();
3918 if (response.GetChar() == ',')
3920 int response_errno = response.GetS32(-1);
3921 if (response_errno > 0)
3922 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3928 // Should have returned with 'F<result>[,<errno>]'
3929 error.SetErrorStringWithFormat("unlink failed");
3934 error.SetErrorString ("failed to send vFile:unlink packet");
3939 // Extension of host I/O packets to get whether a file exists.
3941 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3943 std::string path(file_spec.GetPath(false));
3944 lldb_private::StreamString stream;
3945 stream.PutCString("vFile:exists:");
3946 stream.PutCStringAsRawHex8(path.c_str());
3947 const char* packet = stream.GetData();
3948 int packet_len = stream.GetSize();
3949 StringExtractorGDBRemote response;
3950 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3952 if (response.GetChar() != 'F')
3954 if (response.GetChar() != ',')
3956 bool retcode = (response.GetChar() != '0');
3963 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3967 std::string path(file_spec.GetPath(false));
3968 lldb_private::StreamString stream;
3969 stream.PutCString("vFile:MD5:");
3970 stream.PutCStringAsRawHex8(path.c_str());
3971 const char* packet = stream.GetData();
3972 int packet_len = stream.GetSize();
3973 StringExtractorGDBRemote response;
3974 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3976 if (response.GetChar() != 'F')
3978 if (response.GetChar() != ',')
3980 if (response.Peek() && *response.Peek() == 'x')
3982 low = response.GetHexMaxU64(false, UINT64_MAX);
3983 high = response.GetHexMaxU64(false, UINT64_MAX);
3990 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3992 // Some targets have issues with g/G packets and we need to avoid using them
3993 if (m_avoid_g_packets == eLazyBoolCalculate)
3997 m_avoid_g_packets = eLazyBoolNo;
3998 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4000 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4001 && arch.GetTriple().getOS() == llvm::Triple::IOS
4002 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
4004 m_avoid_g_packets = eLazyBoolYes;
4005 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4006 if (gdb_server_version != 0)
4008 const char *gdb_server_name = GetGDBServerProgramName();
4009 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4011 if (gdb_server_version >= 310)
4012 m_avoid_g_packets = eLazyBoolNo;
4018 return m_avoid_g_packets == eLazyBoolYes;
4022 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4024 Mutex::Locker locker;
4025 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4027 const bool thread_suffix_supported = GetThreadSuffixSupported();
4029 if (thread_suffix_supported || SetCurrentThread(tid))
4033 if (thread_suffix_supported)
4034 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4036 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4037 assert (packet_len < ((int)sizeof(packet) - 1));
4038 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4047 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4049 Mutex::Locker locker;
4050 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4052 const bool thread_suffix_supported = GetThreadSuffixSupported();
4054 if (thread_suffix_supported || SetCurrentThread(tid))
4058 // Get all registers in one packet
4059 if (thread_suffix_supported)
4060 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4062 packet_len = ::snprintf (packet, sizeof(packet), "g");
4063 assert (packet_len < ((int)sizeof(packet) - 1));
4064 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4070 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4072 save_id = 0; // Set to invalid save ID
4073 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4076 m_supports_QSaveRegisterState = eLazyBoolYes;
4077 Mutex::Locker locker;
4078 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4080 const bool thread_suffix_supported = GetThreadSuffixSupported();
4081 if (thread_suffix_supported || SetCurrentThread(tid))
4084 if (thread_suffix_supported)
4085 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4087 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
4089 StringExtractorGDBRemote response;
4091 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4093 if (response.IsUnsupportedResponse())
4095 // This packet isn't supported, don't try calling it again
4096 m_supports_QSaveRegisterState = eLazyBoolNo;
4099 const uint32_t response_save_id = response.GetU32(0);
4100 if (response_save_id != 0)
4102 save_id = response_save_id;
4112 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4114 // We use the "m_supports_QSaveRegisterState" variable here because the
4115 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4116 // order to be useful
4117 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4120 Mutex::Locker locker;
4121 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4123 const bool thread_suffix_supported = GetThreadSuffixSupported();
4124 if (thread_suffix_supported || SetCurrentThread(tid))
4127 if (thread_suffix_supported)
4128 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4130 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4132 StringExtractorGDBRemote response;
4134 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4136 if (response.IsOKResponse())
4140 else if (response.IsUnsupportedResponse())
4142 // This packet isn't supported, don't try calling this packet or
4143 // QSaveRegisterState again...
4144 m_supports_QSaveRegisterState = eLazyBoolNo;
4153 GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
4154 const lldb_private::ArchSpec& arch_spec,
4155 ModuleSpec &module_spec)
4157 std::string module_path = module_file_spec.GetPath (false);
4158 if (module_path.empty ())
4161 StreamString packet;
4162 packet.PutCString("qModuleInfo:");
4163 packet.PutCStringAsRawHex8(module_path.c_str());
4164 packet.PutCString(";");
4165 const auto& triple = arch_spec.GetTriple().getTriple();
4166 packet.PutCStringAsRawHex8(triple.c_str());
4168 StringExtractorGDBRemote response;
4169 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4172 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
4178 StringExtractor extractor;
4180 module_spec.Clear ();
4181 module_spec.GetFileSpec () = module_file_spec;
4183 while (response.GetNameColonValue (name, value))
4185 if (name == "uuid" || name == "md5")
4187 extractor.GetStringRef ().swap (value);
4188 extractor.SetFilePos (0);
4189 extractor.GetHexByteString (value);
4190 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4192 else if (name == "triple")
4194 extractor.GetStringRef ().swap (value);
4195 extractor.SetFilePos (0);
4196 extractor.GetHexByteString (value);
4197 module_spec.GetArchitecture().SetTriple (value.c_str ());
4199 else if (name == "file_offset")
4201 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4203 module_spec.SetObjectOffset (ival);
4205 else if (name == "file_size")
4207 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4209 module_spec.SetObjectSize (ival);
4211 else if (name == "file_path")
4213 extractor.GetStringRef ().swap (value);
4214 extractor.SetFilePos (0);
4215 extractor.GetHexByteString (value);
4216 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
4223 // query the target remote for extended information using the qXfer packet
4225 // example: object='features', annex='target.xml', out=<xml output>
4226 // return: 'true' on success
4227 // 'false' on failure (err set)
4229 GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4230 const lldb_private::ConstString annex,
4232 lldb_private::Error & err) {
4234 std::stringstream output;
4235 StringExtractorGDBRemote chunk;
4237 uint64_t size = GetRemoteMaxPacketSize();
4240 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4244 // loop until all data has been read
4247 // send query extended feature packet
4248 std::stringstream packet;
4250 << object.AsCString("") << ":read:"
4251 << annex.AsCString("") << ":"
4252 << std::hex << offset << ","
4253 << std::hex << size;
4255 GDBRemoteCommunication::PacketResult res =
4256 SendPacketAndWaitForResponse( packet.str().c_str(),
4260 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4261 err.SetErrorString( "Error sending $qXfer packet" );
4265 const std::string & str = chunk.GetStringRef( );
4266 if ( str.length() == 0 ) {
4267 // should have some data in chunk
4268 err.SetErrorString( "Empty response from $qXfer packet" );
4272 // check packet code
4277 // fall through intentional
4281 if ( str.length() > 1 )
4288 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4293 out = output.str( );
4298 // Notify the target that gdb is prepared to serve symbol lookup requests.
4299 // packet: "qSymbol::"
4301 // OK The target does not need to look up any (more) symbols.
4302 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4303 // LLDB may provide the value by sending another qSymbol packet
4304 // in the form of"qSymbol:<sym_value>:<sym_name>".
4307 GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4309 if (m_supports_qSymbol)
4311 Mutex::Locker locker;
4312 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4314 StreamString packet;
4315 packet.PutCString ("qSymbol::");
4318 StringExtractorGDBRemote response;
4319 if (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
4321 if (response.IsOKResponse())
4323 // We are done serving symbols requests
4327 if (response.IsUnsupportedResponse())
4329 // qSymbol is not supported by the current GDB server we are connected to
4330 m_supports_qSymbol = false;
4335 llvm::StringRef response_str(response.GetStringRef());
4336 if (response_str.startswith("qSymbol:"))
4338 response.SetFilePos(strlen("qSymbol:"));
4339 std::string symbol_name;
4340 if (response.GetHexByteString(symbol_name))
4342 if (symbol_name.empty())
4345 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4346 lldb_private::SymbolContextList sc_list;
4347 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
4349 const size_t num_scs = sc_list.GetSize();
4350 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
4353 if (sc_list.GetContextAtIndex(sc_idx, sc))
4357 switch (sc.symbol->GetType())
4359 case eSymbolTypeInvalid:
4360 case eSymbolTypeAbsolute:
4361 case eSymbolTypeUndefined:
4362 case eSymbolTypeSourceFile:
4363 case eSymbolTypeHeaderFile:
4364 case eSymbolTypeObjectFile:
4365 case eSymbolTypeCommonBlock:
4366 case eSymbolTypeBlock:
4367 case eSymbolTypeLocal:
4368 case eSymbolTypeParam:
4369 case eSymbolTypeVariable:
4370 case eSymbolTypeVariableType:
4371 case eSymbolTypeLineEntry:
4372 case eSymbolTypeLineHeader:
4373 case eSymbolTypeScopeBegin:
4374 case eSymbolTypeScopeEnd:
4375 case eSymbolTypeAdditional:
4376 case eSymbolTypeCompiler:
4377 case eSymbolTypeInstrumentation:
4378 case eSymbolTypeTrampoline:
4381 case eSymbolTypeCode:
4382 case eSymbolTypeResolver:
4383 case eSymbolTypeData:
4384 case eSymbolTypeRuntime:
4385 case eSymbolTypeException:
4386 case eSymbolTypeObjCClass:
4387 case eSymbolTypeObjCMetaClass:
4388 case eSymbolTypeObjCIVar:
4389 case eSymbolTypeReExported:
4390 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4397 // This is the normal path where our symbol lookup was successful and we want
4398 // to send a packet with the new symbol value and see if another lookup needs to be
4401 // Change "packet" to contain the requested symbol value and name
4403 packet.PutCString("qSymbol:");
4404 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4405 packet.Printf("%" PRIx64, symbol_load_addr);
4406 packet.PutCString(":");
4407 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4408 continue; // go back to the while loop and send "packet" and wait for another response
4414 // If we make it here, the symbol request packet response wasn't valid or
4415 // our symbol lookup failed so we must abort