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_qProcessInfoPID (true),
91 m_supports_qfProcessInfo (true),
92 m_supports_qUserName (true),
93 m_supports_qGroupName (true),
94 m_supports_qThreadStopInfo (true),
100 m_supports_QEnvironment (true),
101 m_supports_QEnvironmentHexEncoded (true),
102 m_supports_qSymbol (true),
103 m_supports_jThreadsInfo (true),
104 m_curr_pid (LLDB_INVALID_PROCESS_ID),
105 m_curr_tid (LLDB_INVALID_THREAD_ID),
106 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
107 m_num_supported_hardware_watchpoints (0),
108 m_async_mutex (Mutex::eMutexTypeRecursive),
109 m_async_packet_predicate (false),
111 m_async_result (PacketResult::Success),
114 m_interrupt_sent (false),
115 m_thread_id_to_used_usec_map (),
118 m_os_version_major (UINT32_MAX),
119 m_os_version_minor (UINT32_MAX),
120 m_os_version_update (UINT32_MAX),
125 m_gdb_server_version(UINT32_MAX),
126 m_default_packet_timeout (0),
127 m_max_packet_size (0)
131 //----------------------------------------------------------------------
133 //----------------------------------------------------------------------
134 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
141 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
143 ResetDiscoverableSettings(false);
145 // Start the read thread after we send the handshake ack since if we
146 // fail to send the handshake ack, there is no reason to continue...
149 // Wait for any responses that might have been queued up in the remote
150 // GDB server and flush them all
151 StringExtractorGDBRemote response;
152 PacketResult packet_result = PacketResult::Success;
153 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
154 while (packet_result == PacketResult::Success)
155 packet_result = ReadPacket (response, timeout_usec, false);
157 // The return value from QueryNoAckModeSupported() is true if the packet
158 // was sent and _any_ response (including UNIMPLEMENTED) was received),
159 // or false if no response was received. This quickly tells us if we have
160 // a live connection to a remote GDB server...
161 if (QueryNoAckModeSupported())
168 error_ptr->SetErrorString("failed to get reply to handshake packet");
174 error_ptr->SetErrorString("failed to send the handshake ack");
180 GDBRemoteCommunicationClient::GetEchoSupported ()
182 if (m_supports_qEcho == eLazyBoolCalculate)
184 GetRemoteQSupported();
186 return m_supports_qEcho == eLazyBoolYes;
191 GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
193 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
195 GetRemoteQSupported();
197 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
201 GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
203 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
205 GetRemoteQSupported();
207 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
211 GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
213 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
215 GetRemoteQSupported();
217 return m_supports_qXfer_libraries_read == eLazyBoolYes;
221 GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
223 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
225 GetRemoteQSupported();
227 return m_supports_qXfer_auxv_read == eLazyBoolYes;
231 GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
233 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
235 GetRemoteQSupported();
237 return m_supports_qXfer_features_read == eLazyBoolYes;
241 GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
243 if (m_max_packet_size == 0)
245 GetRemoteQSupported();
247 return m_max_packet_size;
251 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
253 if (m_supports_not_sending_acks == eLazyBoolCalculate)
256 m_supports_not_sending_acks = eLazyBoolNo;
258 // This is the first real packet that we'll send in a debug session and it may take a little
259 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
261 const uint32_t minimum_timeout = 6;
262 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
263 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
265 StringExtractorGDBRemote response;
266 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
268 if (response.IsOKResponse())
271 m_supports_not_sending_acks = eLazyBoolYes;
280 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
282 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
284 m_supports_threads_in_stop_reply = eLazyBoolNo;
286 StringExtractorGDBRemote response;
287 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
289 if (response.IsOKResponse())
290 m_supports_threads_in_stop_reply = eLazyBoolYes;
296 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
298 if (m_attach_or_wait_reply == eLazyBoolCalculate)
300 m_attach_or_wait_reply = eLazyBoolNo;
302 StringExtractorGDBRemote response;
303 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
305 if (response.IsOKResponse())
306 m_attach_or_wait_reply = eLazyBoolYes;
309 if (m_attach_or_wait_reply == eLazyBoolYes)
316 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
318 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
320 m_prepare_for_reg_writing_reply = eLazyBoolNo;
322 StringExtractorGDBRemote response;
323 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
325 if (response.IsOKResponse())
326 m_prepare_for_reg_writing_reply = eLazyBoolYes;
329 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
337 GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
339 if (did_exec == false)
341 // Hard reset everything, this is when we first connect to a GDB server
342 m_supports_not_sending_acks = eLazyBoolCalculate;
343 m_supports_thread_suffix = eLazyBoolCalculate;
344 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
345 m_supports_vCont_c = eLazyBoolCalculate;
346 m_supports_vCont_C = eLazyBoolCalculate;
347 m_supports_vCont_s = eLazyBoolCalculate;
348 m_supports_vCont_S = eLazyBoolCalculate;
349 m_supports_p = eLazyBoolCalculate;
350 m_supports_x = eLazyBoolCalculate;
351 m_supports_QSaveRegisterState = eLazyBoolCalculate;
352 m_qHostInfo_is_valid = eLazyBoolCalculate;
353 m_curr_pid_is_valid = eLazyBoolCalculate;
354 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
355 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
356 m_supports_memory_region_info = eLazyBoolCalculate;
357 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
358 m_attach_or_wait_reply = eLazyBoolCalculate;
359 m_avoid_g_packets = eLazyBoolCalculate;
360 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
361 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
362 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
363 m_supports_qXfer_features_read = eLazyBoolCalculate;
364 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
365 m_supports_qProcessInfoPID = true;
366 m_supports_qfProcessInfo = true;
367 m_supports_qUserName = true;
368 m_supports_qGroupName = true;
369 m_supports_qThreadStopInfo = true;
370 m_supports_z0 = true;
371 m_supports_z1 = true;
372 m_supports_z2 = true;
373 m_supports_z3 = true;
374 m_supports_z4 = true;
375 m_supports_QEnvironment = true;
376 m_supports_QEnvironmentHexEncoded = true;
377 m_supports_qSymbol = true;
379 m_os_version_major = UINT32_MAX;
380 m_os_version_minor = UINT32_MAX;
381 m_os_version_update = UINT32_MAX;
385 m_gdb_server_name.clear();
386 m_gdb_server_version = UINT32_MAX;
387 m_default_packet_timeout = 0;
388 m_max_packet_size = 0;
391 // These flags should be reset when we first connect to a GDB server
392 // and when our inferior process execs
393 m_qProcessInfo_is_valid = eLazyBoolCalculate;
394 m_process_arch.Clear();
398 GDBRemoteCommunicationClient::GetRemoteQSupported ()
400 // Clear out any capabilities we expect to see in the qSupported response
401 m_supports_qXfer_auxv_read = eLazyBoolNo;
402 m_supports_qXfer_libraries_read = eLazyBoolNo;
403 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
404 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
405 m_supports_qXfer_features_read = eLazyBoolNo;
406 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
408 // build the qSupported packet
409 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
411 packet.PutCString( "qSupported" );
412 for ( uint32_t i = 0; i < features.size( ); ++i )
414 packet.PutCString( i==0 ? ":" : ";");
415 packet.PutCString( features[i].c_str( ) );
418 StringExtractorGDBRemote response;
419 if (SendPacketAndWaitForResponse(packet.GetData(),
421 /*send_async=*/false) == PacketResult::Success)
423 const char *response_cstr = response.GetStringRef().c_str();
424 if (::strstr (response_cstr, "qXfer:auxv:read+"))
425 m_supports_qXfer_auxv_read = eLazyBoolYes;
426 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
427 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
428 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
430 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
431 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
433 if (::strstr (response_cstr, "qXfer:libraries:read+"))
434 m_supports_qXfer_libraries_read = eLazyBoolYes;
435 if (::strstr (response_cstr, "qXfer:features:read+"))
436 m_supports_qXfer_features_read = eLazyBoolYes;
439 // Look for a list of compressions in the features list e.g.
440 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
441 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
444 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
447 std::vector<std::string> supported_compressions;
448 compressions += sizeof ("SupportedCompressions=") - 1;
449 const char *end_of_compressions = strchr (compressions, ';');
450 if (end_of_compressions == NULL)
452 end_of_compressions = strchr (compressions, '\0');
454 const char *current_compression = compressions;
455 while (current_compression < end_of_compressions)
457 const char *next_compression_name = strchr (current_compression, ',');
458 const char *end_of_this_word = next_compression_name;
459 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
461 end_of_this_word = end_of_compressions;
464 if (end_of_this_word)
466 if (end_of_this_word == current_compression)
468 current_compression++;
472 std::string this_compression (current_compression, end_of_this_word - current_compression);
473 supported_compressions.push_back (this_compression);
474 current_compression = end_of_this_word + 1;
479 supported_compressions.push_back (current_compression);
480 current_compression = end_of_compressions;
484 if (supported_compressions.size() > 0)
486 MaybeEnableCompression (supported_compressions);
491 if (::strstr (response_cstr, "qEcho"))
492 m_supports_qEcho = eLazyBoolYes;
494 m_supports_qEcho = eLazyBoolNo;
496 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
499 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
500 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
501 if (m_max_packet_size == 0)
503 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
504 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
506 log->Printf ("Garbled PacketSize spec in qSupported response");
513 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
515 if (m_supports_thread_suffix == eLazyBoolCalculate)
517 StringExtractorGDBRemote response;
518 m_supports_thread_suffix = eLazyBoolNo;
519 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
521 if (response.IsOKResponse())
522 m_supports_thread_suffix = eLazyBoolYes;
525 return m_supports_thread_suffix;
528 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
530 if (m_supports_vCont_c == eLazyBoolCalculate)
532 StringExtractorGDBRemote response;
533 m_supports_vCont_any = eLazyBoolNo;
534 m_supports_vCont_all = eLazyBoolNo;
535 m_supports_vCont_c = eLazyBoolNo;
536 m_supports_vCont_C = eLazyBoolNo;
537 m_supports_vCont_s = eLazyBoolNo;
538 m_supports_vCont_S = eLazyBoolNo;
539 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
541 const char *response_cstr = response.GetStringRef().c_str();
542 if (::strstr (response_cstr, ";c"))
543 m_supports_vCont_c = eLazyBoolYes;
545 if (::strstr (response_cstr, ";C"))
546 m_supports_vCont_C = eLazyBoolYes;
548 if (::strstr (response_cstr, ";s"))
549 m_supports_vCont_s = eLazyBoolYes;
551 if (::strstr (response_cstr, ";S"))
552 m_supports_vCont_S = eLazyBoolYes;
554 if (m_supports_vCont_c == eLazyBoolYes &&
555 m_supports_vCont_C == eLazyBoolYes &&
556 m_supports_vCont_s == eLazyBoolYes &&
557 m_supports_vCont_S == eLazyBoolYes)
559 m_supports_vCont_all = eLazyBoolYes;
562 if (m_supports_vCont_c == eLazyBoolYes ||
563 m_supports_vCont_C == eLazyBoolYes ||
564 m_supports_vCont_s == eLazyBoolYes ||
565 m_supports_vCont_S == eLazyBoolYes)
567 m_supports_vCont_any = eLazyBoolYes;
574 case 'a': return m_supports_vCont_any;
575 case 'A': return m_supports_vCont_all;
576 case 'c': return m_supports_vCont_c;
577 case 'C': return m_supports_vCont_C;
578 case 's': return m_supports_vCont_s;
579 case 'S': return m_supports_vCont_S;
585 // Check if the target supports 'p' packet. It sends out a 'p'
586 // packet and checks the response. A normal packet will tell us
587 // that support is available.
589 // Takes a valid thread ID because p needs to apply to a thread.
591 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
593 if (m_supports_p == eLazyBoolCalculate)
595 StringExtractorGDBRemote response;
596 m_supports_p = eLazyBoolNo;
598 if (GetThreadSuffixSupported())
599 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
601 snprintf(packet, sizeof(packet), "p0");
603 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
605 if (response.IsNormalResponse())
606 m_supports_p = eLazyBoolYes;
612 StructuredData::ObjectSP
613 GDBRemoteCommunicationClient::GetThreadsInfo()
615 // Get information on all threads at one using the "jThreadsInfo" packet
616 StructuredData::ObjectSP object_sp;
618 if (m_supports_jThreadsInfo)
620 StringExtractorGDBRemote response;
621 m_supports_jThreadExtendedInfo = eLazyBoolNo;
622 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
624 if (response.IsUnsupportedResponse())
626 m_supports_jThreadsInfo = false;
628 else if (!response.Empty())
630 object_sp = StructuredData::ParseJSON (response.GetStringRef());
639 GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
641 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
643 StringExtractorGDBRemote response;
644 m_supports_jThreadExtendedInfo = eLazyBoolNo;
645 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
647 if (response.IsOKResponse())
649 m_supports_jThreadExtendedInfo = eLazyBoolYes;
653 return m_supports_jThreadExtendedInfo;
657 GDBRemoteCommunicationClient::GetxPacketSupported ()
659 if (m_supports_x == eLazyBoolCalculate)
661 StringExtractorGDBRemote response;
662 m_supports_x = eLazyBoolNo;
664 snprintf (packet, sizeof (packet), "x0,0");
665 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
667 if (response.IsOKResponse())
668 m_supports_x = eLazyBoolYes;
674 GDBRemoteCommunicationClient::PacketResult
675 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
677 const char *payload_prefix,
678 std::string &response_string
681 Mutex::Locker locker;
682 if (!GetSequenceMutex(locker,
683 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
685 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
687 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
689 return PacketResult::ErrorNoSequenceLock;
692 response_string = "";
693 std::string payload_prefix_str(payload_prefix);
694 unsigned int response_size = 0x1000;
695 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
696 response_size = GetRemoteMaxPacketSize();
699 for (unsigned int offset = 0; true; offset += response_size)
701 StringExtractorGDBRemote this_response;
703 char sizeDescriptor[128];
704 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
705 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
707 /*send_async=*/false);
708 if (result != PacketResult::Success)
711 const std::string &this_string = this_response.GetStringRef();
713 // Check for m or l as first character; l seems to mean this is the last chunk
714 char first_char = *this_string.c_str();
715 if (first_char != 'm' && first_char != 'l')
717 return PacketResult::ErrorReplyInvalid;
719 // Concatenate the result so far (skipping 'm' or 'l')
720 response_string.append(this_string, 1, std::string::npos);
721 if (first_char == 'l')
723 return PacketResult::Success;
727 GDBRemoteCommunicationClient::PacketResult
728 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
731 StringExtractorGDBRemote &response,
735 return SendPacketAndWaitForResponse (payload,
741 GDBRemoteCommunicationClient::PacketResult
742 GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
743 size_t payload_length,
744 StringExtractorGDBRemote &response)
746 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
747 if (packet_result == PacketResult::Success)
748 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
749 return packet_result;
752 GDBRemoteCommunicationClient::PacketResult
753 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
756 size_t payload_length,
757 StringExtractorGDBRemote &response,
761 PacketResult packet_result = PacketResult::ErrorSendFailed;
762 Mutex::Locker locker;
763 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
765 // In order to stop async notifications from being processed in the middle of the
766 // send/recieve sequence Hijack the broadcast. Then rebroadcast any events when we are done.
767 static Listener hijack_listener("lldb.NotifyHijacker");
768 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
770 if (GetSequenceMutex (locker))
772 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
780 Mutex::Locker async_locker (m_async_mutex);
781 m_async_packet.assign(payload, payload_length);
782 m_async_packet_predicate.SetValue (true, eBroadcastNever);
785 log->Printf ("async: async packet = %s", m_async_packet.c_str());
787 bool timed_out = false;
788 if (SendInterrupt(locker, 2, timed_out))
790 if (m_interrupt_sent)
792 m_interrupt_sent = false;
793 TimeValue timeout_time;
794 timeout_time = TimeValue::Now();
795 timeout_time.OffsetWithSeconds (m_packet_timeout);
798 log->Printf ("async: sent interrupt");
800 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
803 log->Printf ("async: got response");
805 // Swap the response buffer to avoid malloc and string copy
806 response.GetStringRef().swap (m_async_response.GetStringRef());
807 packet_result = m_async_result;
812 log->Printf ("async: timed out waiting for response");
815 // Make sure we wait until the continue packet has been sent again...
816 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
821 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
823 log->Printf ("async: async packet sent");
829 log->Printf ("async: timed out waiting for process to resume");
834 // We had a racy condition where we went to send the interrupt
835 // yet we were able to get the lock, so the process must have
838 log->Printf ("async: got lock without sending interrupt");
839 // Send the packet normally since we got the lock
840 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
846 log->Printf ("async: failed to interrupt");
852 log->Printf ("async: not running, async is ignored");
858 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
862 // Remove our Hijacking listner from the broadcast.
863 RestoreBroadcaster();
865 // If a notification event occured, rebroadcast since it can now be processed safely.
867 if (hijack_listener.GetNextEvent(event_sp))
868 BroadcastEvent(event_sp);
870 return packet_result;
873 static const char *end_delimiter = "--end--;";
874 static const int end_delimiter_len = 8;
877 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
878 ( ProcessGDBRemote *process,
879 StringExtractorGDBRemote& profileDataExtractor
882 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
883 std::stringstream final_output;
884 std::string name, value;
886 // Going to assuming thread_used_usec comes first, else bail out.
887 while (profileDataExtractor.GetNameColonValue(name, value))
889 if (name.compare("thread_used_id") == 0)
891 StringExtractor threadIDHexExtractor(value.c_str());
892 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
894 bool has_used_usec = false;
895 uint32_t curr_used_usec = 0;
896 std::string usec_name, usec_value;
897 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
898 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
900 if (usec_name.compare("thread_used_usec") == 0)
902 has_used_usec = true;
903 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
907 // We didn't find what we want, it is probably
908 // an older version. Bail out.
909 profileDataExtractor.SetFilePos(input_file_pos);
915 uint32_t prev_used_usec = 0;
916 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
917 if (iterator != m_thread_id_to_used_usec_map.end())
919 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
922 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
923 // A good first time record is one that runs for at least 0.25 sec
924 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
925 bool good_subsequent_time = (prev_used_usec > 0) &&
926 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
928 if (good_first_time || good_subsequent_time)
930 // We try to avoid doing too many index id reservation,
931 // resulting in fast increase of index ids.
933 final_output << name << ":";
934 int32_t index_id = process->AssignIndexIDToThread(thread_id);
935 final_output << index_id << ";";
937 final_output << usec_name << ":" << usec_value << ";";
941 // Skip past 'thread_used_name'.
942 std::string local_name, local_value;
943 profileDataExtractor.GetNameColonValue(local_name, local_value);
946 // Store current time as previous time so that they can be compared later.
947 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
951 // Bail out and use old string.
952 final_output << name << ":" << value << ";";
957 final_output << name << ":" << value << ";";
960 final_output << end_delimiter;
961 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
963 return final_output.str();
967 GDBRemoteCommunicationClient::SendvContPacket
969 ProcessGDBRemote *process,
971 size_t packet_length,
972 StringExtractorGDBRemote &response
976 m_curr_tid = LLDB_INVALID_THREAD_ID;
977 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
979 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
981 // we want to lock down packet sending while we continue
982 Mutex::Locker locker(m_sequence_mutex);
984 // here we broadcast this before we even send the packet!!
985 // this signals doContinue() to exit
986 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
988 // set the public state to running
989 m_public_is_running.SetValue(true, eBroadcastNever);
991 // Set the starting continue packet into "continue_packet". This packet
992 // may change if we are interrupted and we continue after an async packet...
993 std::string continue_packet(payload, packet_length);
996 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
998 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1001 // set the private state to running and broadcast this
1002 m_private_is_running.SetValue(true, eBroadcastAlways);
1005 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1007 // wait for the response to the vCont
1008 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1010 if (response.IsOKResponse())
1018 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1020 ProcessGDBRemote *process,
1021 const char *payload,
1022 size_t packet_length,
1023 StringExtractorGDBRemote &response
1026 m_curr_tid = LLDB_INVALID_THREAD_ID;
1027 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1029 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1031 Mutex::Locker locker(m_sequence_mutex);
1032 StateType state = eStateRunning;
1034 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1035 m_public_is_running.SetValue (true, eBroadcastNever);
1036 // Set the starting continue packet into "continue_packet". This packet
1037 // may change if we are interrupted and we continue after an async packet...
1038 std::string continue_packet(payload, packet_length);
1040 const auto sigstop_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGSTOP");
1041 const auto sigint_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGINT");
1043 bool got_async_packet = false;
1045 while (state == eStateRunning)
1047 if (!got_async_packet)
1050 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
1051 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1052 state = eStateInvalid;
1054 m_interrupt_sent = false;
1056 m_private_is_running.SetValue (true, eBroadcastAlways);
1059 got_async_packet = false;
1062 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1064 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1066 if (response.Empty())
1067 state = eStateInvalid;
1070 const char stop_type = response.GetChar();
1072 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1078 if (process->GetStopID() == 0)
1080 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1082 lldb::pid_t pid = GetCurrentProcessID ();
1083 if (pid != LLDB_INVALID_PROCESS_ID)
1084 process->SetID (pid);
1086 process->BuildDynamicRegisterInfo (true);
1089 // Privately notify any internal threads that we have stopped
1090 // in case we wanted to interrupt our process, yet we might
1091 // send a packet and continue without returning control to the
1093 m_private_is_running.SetValue (false, eBroadcastAlways);
1095 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1097 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1098 if (continue_after_async || m_interrupt_sent)
1100 // We sent an interrupt packet to stop the inferior process
1101 // for an async signal or to send an async packet while running
1102 // but we might have been single stepping and received the
1103 // stop packet for the step instead of for the interrupt packet.
1104 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1105 // is used, so if we get anything else, we need to try and
1106 // get another stop reply packet that may have been sent
1107 // due to sending the interrupt when the target is stopped
1108 // which will just re-send a copy of the last stop reply
1109 // packet. If we don't do this, then the reply for our
1110 // async packet will be the repeat stop reply packet and cause
1111 // a lot of trouble for us!
1112 if (signo != sigint_signo && signo != sigstop_signo)
1114 continue_after_async = false;
1116 // We didn't get a SIGINT or SIGSTOP, so try for a
1117 // very brief time (1 ms) to get another stop reply
1118 // packet to make sure it doesn't get in the way
1119 StringExtractorGDBRemote extra_stop_reply_packet;
1120 uint32_t timeout_usec = 1000;
1121 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
1123 switch (extra_stop_reply_packet.GetChar())
1127 // We did get an extra stop reply, which means
1128 // our interrupt didn't stop the target so we
1129 // shouldn't continue after the async signal
1130 // or packet is sent...
1131 continue_after_async = false;
1138 if (m_async_signal != -1)
1141 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1143 // Save off the async signal we are supposed to send
1144 const int async_signal = m_async_signal;
1145 // Clear the async signal member so we don't end up
1146 // sending the signal multiple times...
1147 m_async_signal = -1;
1148 // Check which signal we stopped with
1149 if (signo == async_signal)
1152 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1154 // We already stopped with a signal that we wanted
1155 // to stop with, so we are done
1159 // We stopped with a different signal that the one
1160 // we wanted to stop with, so now we must resume
1161 // with the signal we want
1162 char signal_packet[32];
1163 int signal_packet_len = 0;
1164 signal_packet_len = ::snprintf (signal_packet,
1165 sizeof (signal_packet),
1170 log->Printf ("async: stopped with signal %s, resume with %s",
1171 Host::GetSignalAsCString (signo),
1172 Host::GetSignalAsCString (async_signal));
1174 // Set the continue packet to resume even if the
1175 // interrupt didn't cause our stop (ignore continue_after_async)
1176 continue_packet.assign(signal_packet, signal_packet_len);
1180 else if (m_async_packet_predicate.GetValue())
1182 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
1184 // We are supposed to send an asynchronous packet while
1186 m_async_response.Clear();
1187 if (m_async_packet.empty())
1189 m_async_result = PacketResult::ErrorSendFailed;
1191 packet_log->Printf ("async: error: empty async packet");
1197 packet_log->Printf ("async: sending packet");
1199 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1200 m_async_packet.size(),
1204 // Let the other thread that was trying to send the async
1205 // packet know that the packet has been sent and response is
1207 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1210 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
1212 // Set the continue packet to resume if our interrupt
1213 // for the async packet did cause the stop
1214 if (continue_after_async)
1216 // Reverting this for now as it is causing deadlocks
1217 // in programs (<rdar://problem/11529853>). In the future
1218 // we should check our thread list and "do the right thing"
1219 // for new threads that show up while we stop and run async
1220 // packets. Setting the packet to 'c' to continue all threads
1221 // is the right thing to do 99.99% of the time because if a
1222 // thread was single stepping, and we sent an interrupt, we
1223 // will notice above that we didn't stop due to an interrupt
1224 // but stopped due to stepping and we would _not_ continue.
1225 continue_packet.assign (1, 'c');
1229 // Stop with signal and thread info
1230 state = eStateStopped;
1237 state = eStateExited;
1243 got_async_packet = true;
1244 std::string inferior_stdout;
1245 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1247 while ((ch = response.GetHexU8()) != '\0')
1248 inferior_stdout.append(1, ch);
1249 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1254 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1256 got_async_packet = true;
1257 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1258 if (m_partial_profile_data.length() > 0)
1260 m_partial_profile_data.append(input);
1261 input = m_partial_profile_data;
1262 m_partial_profile_data.clear();
1265 size_t found, pos = 0, len = input.length();
1266 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1268 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
1269 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1270 process->BroadcastAsyncProfileData (profile_data);
1272 pos = found + end_delimiter_len;
1277 // Last incomplete chunk.
1278 m_partial_profile_data = input.substr(pos);
1285 state = eStateInvalid;
1290 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1291 state = eStateInvalid;
1299 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
1300 state = eStateInvalid;
1304 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1305 response.SetFilePos(0);
1306 m_private_is_running.SetValue (false, eBroadcastAlways);
1307 m_public_is_running.SetValue (false, eBroadcastAlways);
1312 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1314 Mutex::Locker async_locker (m_async_mutex);
1315 m_async_signal = signo;
1316 bool timed_out = false;
1317 Mutex::Locker locker;
1318 if (SendInterrupt (locker, 1, timed_out))
1320 m_async_signal = -1;
1324 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
1325 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1326 // (the expected result), then it will send the halt packet. If it does succeed
1327 // then the caller that requested the interrupt will want to keep the sequence
1328 // locked down so that no one else can send packets while the caller has control.
1329 // This function usually gets called when we are running and need to stop the
1330 // target. It can also be used when we are running and we need to do something
1331 // else (like read/write memory), so we need to interrupt the running process
1332 // (gdb remote protocol requires this), and do what we need to do, then resume.
1335 GDBRemoteCommunicationClient::SendInterrupt
1337 Mutex::Locker& locker,
1338 uint32_t seconds_to_wait_for_stop,
1343 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
1347 // Only send an interrupt if our debugserver is running...
1348 if (GetSequenceMutex (locker))
1351 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1355 // Someone has the mutex locked waiting for a response or for the
1356 // inferior to stop, so send the interrupt on the down low...
1357 char ctrl_c = '\x03';
1358 ConnectionStatus status = eConnectionStatusSuccess;
1359 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
1361 log->PutCString("send packet: \\x03");
1362 if (bytes_written > 0)
1364 m_interrupt_sent = true;
1365 if (seconds_to_wait_for_stop)
1368 if (seconds_to_wait_for_stop)
1370 timeout = TimeValue::Now();
1371 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1373 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1376 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
1382 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
1388 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
1395 log->Printf ("SendInterrupt () - failed to write interrupt");
1403 log->Printf ("SendInterrupt () - not running");
1409 GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
1411 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
1414 // First try to retrieve the pid via the qProcessInfo request.
1415 GetCurrentProcessInfo (allow_lazy);
1416 if (m_curr_pid_is_valid == eLazyBoolYes)
1418 // We really got it.
1423 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1424 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1425 // The gdb remote protocol documents $qC as returning the thread id, which newer
1426 // debugserver and lldb-gdbserver stubs return correctly.
1427 StringExtractorGDBRemote response;
1428 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
1430 if (response.GetChar() == 'Q')
1432 if (response.GetChar() == 'C')
1434 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1435 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
1437 m_curr_pid_is_valid = eLazyBoolYes;
1445 return LLDB_INVALID_PROCESS_ID;
1449 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1452 StringExtractorGDBRemote response;
1453 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
1455 if (response.IsOKResponse())
1457 if (response.GetChar() == 'E')
1459 // A string the describes what failed when launching...
1460 error_str = response.GetStringRef().substr(1);
1464 error_str.assign ("unknown error occurred launching process");
1469 error_str.assign ("timed out waiting for app to launch");
1475 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
1477 // Since we don't get the send argv0 separate from the executable path, we need to
1478 // make sure to use the actual executable path found in the launch_info...
1479 std::vector<const char *> argv;
1480 FileSpec exe_file = launch_info.GetExecutableFile();
1481 std::string exe_path;
1482 const char *arg = NULL;
1483 const Args &launch_args = launch_info.GetArguments();
1485 exe_path = exe_file.GetPath(false);
1488 arg = launch_args.GetArgumentAtIndex(0);
1492 if (!exe_path.empty())
1494 argv.push_back(exe_path.c_str());
1495 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1498 argv.push_back(arg);
1503 StreamString packet;
1504 packet.PutChar('A');
1505 for (size_t i = 0, n = argv.size(); i < n; ++i)
1508 const int arg_len = strlen(arg);
1510 packet.PutChar(',');
1511 packet.Printf("%i,%i,", arg_len * 2, (int)i);
1512 packet.PutBytesAsRawHex8 (arg, arg_len);
1515 StringExtractorGDBRemote response;
1516 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1518 if (response.IsOKResponse())
1520 uint8_t error = response.GetError();
1529 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1531 if (name_equal_value && name_equal_value[0])
1533 StreamString packet;
1534 bool send_hex_encoding = false;
1535 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
1543 send_hex_encoding = true;
1551 // We have non printable characters, lets hex encode this...
1552 send_hex_encoding = true;
1556 StringExtractorGDBRemote response;
1557 if (send_hex_encoding)
1559 if (m_supports_QEnvironmentHexEncoded)
1561 packet.PutCString("QEnvironmentHexEncoded:");
1562 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1563 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1565 if (response.IsOKResponse())
1567 uint8_t error = response.GetError();
1570 if (response.IsUnsupportedResponse())
1571 m_supports_QEnvironmentHexEncoded = false;
1576 else if (m_supports_QEnvironment)
1578 packet.Printf("QEnvironment:%s", name_equal_value);
1579 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1581 if (response.IsOKResponse())
1583 uint8_t error = response.GetError();
1586 if (response.IsUnsupportedResponse())
1587 m_supports_QEnvironment = false;
1595 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1597 if (arch && arch[0])
1599 StreamString packet;
1600 packet.Printf("QLaunchArch:%s", arch);
1601 StringExtractorGDBRemote response;
1602 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1604 if (response.IsOKResponse())
1606 uint8_t error = response.GetError();
1615 GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1617 if (data && *data != '\0')
1619 StreamString packet;
1620 packet.Printf("QSetProcessEvent:%s", data);
1621 StringExtractorGDBRemote response;
1622 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1624 if (response.IsOKResponse())
1627 *was_supported = true;
1630 else if (response.IsUnsupportedResponse())
1633 *was_supported = false;
1638 uint8_t error = response.GetError();
1640 *was_supported = true;
1650 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1656 if (m_os_version_major != UINT32_MAX)
1658 major = m_os_version_major;
1659 minor = m_os_version_minor;
1660 update = m_os_version_update;
1668 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1672 if (!m_os_build.empty())
1684 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1688 if (!m_os_kernel.empty())
1699 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1703 if (!m_hostname.empty())
1714 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1721 const lldb_private::ArchSpec &
1722 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1724 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1725 GetCurrentProcessInfo ();
1726 return m_process_arch;
1730 GDBRemoteCommunicationClient::GetGDBServerVersion()
1732 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1734 m_gdb_server_name.clear();
1735 m_gdb_server_version = 0;
1736 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1738 StringExtractorGDBRemote response;
1739 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1741 if (response.IsNormalResponse())
1745 bool success = false;
1746 while (response.GetNameColonValue(name, value))
1748 if (name.compare("name") == 0)
1751 m_gdb_server_name.swap(value);
1753 else if (name.compare("version") == 0)
1755 size_t dot_pos = value.find('.');
1756 if (dot_pos != std::string::npos)
1757 value[dot_pos] = '\0';
1758 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
1759 if (version != UINT32_MAX)
1762 m_gdb_server_version = version;
1767 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1771 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1775 GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1777 CompressionType avail_type = CompressionType::None;
1778 std::string avail_name;
1780 #if defined (HAVE_LIBCOMPRESSION)
1781 // libcompression is weak linked so test if compression_decode_buffer() is available
1782 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1784 for (auto compression : supported_compressions)
1786 if (compression == "lzfse")
1788 avail_type = CompressionType::LZFSE;
1789 avail_name = compression;
1796 #if defined (HAVE_LIBCOMPRESSION)
1797 // libcompression is weak linked so test if compression_decode_buffer() is available
1798 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1800 for (auto compression : supported_compressions)
1802 if (compression == "zlib-deflate")
1804 avail_type = CompressionType::ZlibDeflate;
1805 avail_name = compression;
1812 #if defined (HAVE_LIBZ)
1813 if (avail_type == CompressionType::None)
1815 for (auto compression : supported_compressions)
1817 if (compression == "zlib-deflate")
1819 avail_type = CompressionType::ZlibDeflate;
1820 avail_name = compression;
1827 #if defined (HAVE_LIBCOMPRESSION)
1828 // libcompression is weak linked so test if compression_decode_buffer() is available
1829 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1831 for (auto compression : supported_compressions)
1833 if (compression == "lz4")
1835 avail_type = CompressionType::LZ4;
1836 avail_name = compression;
1843 #if defined (HAVE_LIBCOMPRESSION)
1844 // libcompression is weak linked so test if compression_decode_buffer() is available
1845 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1847 for (auto compression : supported_compressions)
1849 if (compression == "lzma")
1851 avail_type = CompressionType::LZMA;
1852 avail_name = compression;
1859 if (avail_type != CompressionType::None)
1861 StringExtractorGDBRemote response;
1862 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1863 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1866 if (response.IsOKResponse())
1868 m_compression_type = avail_type;
1874 GDBRemoteCommunicationClient::GetGDBServerProgramName()
1876 if (GetGDBServerVersion())
1878 if (!m_gdb_server_name.empty())
1879 return m_gdb_server_name.c_str();
1885 GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1887 if (GetGDBServerVersion())
1888 return m_gdb_server_version;
1893 GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1895 StringExtractorGDBRemote response;
1896 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1899 if (!response.IsNormalResponse())
1902 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1903 tid = response.GetHexMaxU32(true, -1);
1909 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1911 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1913 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1915 m_qHostInfo_is_valid = eLazyBoolNo;
1916 StringExtractorGDBRemote response;
1917 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
1919 if (response.IsNormalResponse())
1923 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1925 std::string arch_name;
1926 std::string os_name;
1927 std::string vendor_name;
1929 std::string distribution_id;
1930 uint32_t pointer_byte_size = 0;
1931 StringExtractor extractor;
1932 ByteOrder byte_order = eByteOrderInvalid;
1933 uint32_t num_keys_decoded = 0;
1934 while (response.GetNameColonValue(name, value))
1936 if (name.compare("cputype") == 0)
1938 // exception type in big endian hex
1939 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1940 if (cpu != LLDB_INVALID_CPUTYPE)
1943 else if (name.compare("cpusubtype") == 0)
1945 // exception count in big endian hex
1946 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
1950 else if (name.compare("arch") == 0)
1952 arch_name.swap (value);
1955 else if (name.compare("triple") == 0)
1957 extractor.GetStringRef ().swap (value);
1958 extractor.SetFilePos(0);
1959 extractor.GetHexByteString (triple);
1962 else if (name.compare ("distribution_id") == 0)
1964 extractor.GetStringRef ().swap (value);
1965 extractor.SetFilePos (0);
1966 extractor.GetHexByteString (distribution_id);
1969 else if (name.compare("os_build") == 0)
1971 extractor.GetStringRef().swap(value);
1972 extractor.SetFilePos(0);
1973 extractor.GetHexByteString (m_os_build);
1976 else if (name.compare("hostname") == 0)
1978 extractor.GetStringRef().swap(value);
1979 extractor.SetFilePos(0);
1980 extractor.GetHexByteString (m_hostname);
1983 else if (name.compare("os_kernel") == 0)
1985 extractor.GetStringRef().swap(value);
1986 extractor.SetFilePos(0);
1987 extractor.GetHexByteString (m_os_kernel);
1990 else if (name.compare("ostype") == 0)
1992 os_name.swap (value);
1995 else if (name.compare("vendor") == 0)
1997 vendor_name.swap(value);
2000 else if (name.compare("endian") == 0)
2003 if (value.compare("little") == 0)
2004 byte_order = eByteOrderLittle;
2005 else if (value.compare("big") == 0)
2006 byte_order = eByteOrderBig;
2007 else if (value.compare("pdp") == 0)
2008 byte_order = eByteOrderPDP;
2012 else if (name.compare("ptrsize") == 0)
2014 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
2015 if (pointer_byte_size != 0)
2018 else if (name.compare("os_version") == 0)
2020 Args::StringToVersion (value.c_str(),
2023 m_os_version_update);
2024 if (m_os_version_major != UINT32_MAX)
2027 else if (name.compare("watchpoint_exceptions_received") == 0)
2030 if (strcmp(value.c_str(),"before") == 0)
2031 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2032 else if (strcmp(value.c_str(),"after") == 0)
2033 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2037 else if (name.compare("default_packet_timeout") == 0)
2039 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
2040 if (m_default_packet_timeout > 0)
2042 SetPacketTimeout(m_default_packet_timeout);
2049 if (num_keys_decoded > 0)
2050 m_qHostInfo_is_valid = eLazyBoolYes;
2054 if (arch_name.empty())
2056 if (cpu != LLDB_INVALID_CPUTYPE)
2058 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2059 if (pointer_byte_size)
2061 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2063 if (byte_order != eByteOrderInvalid)
2065 assert (byte_order == m_host_arch.GetByteOrder());
2068 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2070 switch (m_host_arch.GetMachine())
2072 case llvm::Triple::aarch64:
2073 case llvm::Triple::arm:
2074 case llvm::Triple::thumb:
2082 if (!vendor_name.empty())
2083 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2084 if (!os_name.empty())
2085 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2092 triple += arch_name;
2093 if (!vendor_name.empty() || !os_name.empty())
2096 if (vendor_name.empty())
2097 triple += "unknown";
2099 triple += vendor_name;
2101 if (os_name.empty())
2102 triple += "unknown";
2106 m_host_arch.SetTriple (triple.c_str());
2108 llvm::Triple &host_triple = m_host_arch.GetTriple();
2109 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2111 switch (m_host_arch.GetMachine())
2113 case llvm::Triple::aarch64:
2114 case llvm::Triple::arm:
2115 case llvm::Triple::thumb:
2116 host_triple.setOS(llvm::Triple::IOS);
2119 host_triple.setOS(llvm::Triple::MacOSX);
2123 if (pointer_byte_size)
2125 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2127 if (byte_order != eByteOrderInvalid)
2129 assert (byte_order == m_host_arch.GetByteOrder());
2136 m_host_arch.SetTriple (triple.c_str());
2137 if (pointer_byte_size)
2139 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2141 if (byte_order != eByteOrderInvalid)
2143 assert (byte_order == m_host_arch.GetByteOrder());
2147 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 ());
2149 if (!distribution_id.empty ())
2150 m_host_arch.SetDistributionId (distribution_id.c_str ());
2154 return m_qHostInfo_is_valid == eLazyBoolYes;
2158 GDBRemoteCommunicationClient::SendAttach
2161 StringExtractorGDBRemote& response
2164 if (pid != LLDB_INVALID_PROCESS_ID)
2167 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
2168 assert (packet_len < (int)sizeof(packet));
2169 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2171 if (response.IsErrorResponse())
2172 return response.GetError();
2180 GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2182 StreamString packet;
2183 packet.PutCString("I");
2184 packet.PutBytesAsRawHex8(data, data_len);
2185 StringExtractorGDBRemote response;
2186 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2190 return response.GetError();
2194 const lldb_private::ArchSpec &
2195 GDBRemoteCommunicationClient::GetHostArchitecture ()
2197 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2203 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2205 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2207 return m_default_packet_timeout;
2211 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2213 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
2215 m_supports_alloc_dealloc_memory = eLazyBoolYes;
2217 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
2219 permissions & lldb::ePermissionsReadable ? "r" : "",
2220 permissions & lldb::ePermissionsWritable ? "w" : "",
2221 permissions & lldb::ePermissionsExecutable ? "x" : "");
2222 assert (packet_len < (int)sizeof(packet));
2223 StringExtractorGDBRemote response;
2224 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2226 if (response.IsUnsupportedResponse())
2227 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2228 else if (!response.IsErrorResponse())
2229 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2233 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2236 return LLDB_INVALID_ADDRESS;
2240 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2242 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
2244 m_supports_alloc_dealloc_memory = eLazyBoolYes;
2246 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
2247 assert (packet_len < (int)sizeof(packet));
2248 StringExtractorGDBRemote response;
2249 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2251 if (response.IsUnsupportedResponse())
2252 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2253 else if (response.IsOKResponse())
2258 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2265 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
2271 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2274 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
2275 assert (packet_len < (int)sizeof(packet));
2276 StringExtractorGDBRemote response;
2277 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2279 m_supports_detach_stay_stopped = eLazyBoolYes;
2283 m_supports_detach_stay_stopped = eLazyBoolNo;
2287 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2289 error.SetErrorString("Stays stopped not supported by this target.");
2294 StringExtractorGDBRemote response;
2295 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
2296 if (packet_result != PacketResult::Success)
2297 error.SetErrorString ("Sending extended disconnect packet failed.");
2302 StringExtractorGDBRemote response;
2303 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
2304 if (packet_result != PacketResult::Success)
2305 error.SetErrorString ("Sending disconnect packet failed.");
2311 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2312 lldb_private::MemoryRegionInfo ®ion_info)
2315 region_info.Clear();
2317 if (m_supports_memory_region_info != eLazyBoolNo)
2319 m_supports_memory_region_info = eLazyBoolYes;
2321 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
2322 assert (packet_len < (int)sizeof(packet));
2323 StringExtractorGDBRemote response;
2324 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2329 bool success = true;
2330 bool saw_permissions = false;
2331 while (success && response.GetNameColonValue(name, value))
2333 if (name.compare ("start") == 0)
2335 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
2337 region_info.GetRange().SetRangeBase(addr_value);
2339 else if (name.compare ("size") == 0)
2341 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
2343 region_info.GetRange().SetByteSize (addr_value);
2345 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
2347 saw_permissions = true;
2348 if (region_info.GetRange().Contains (addr))
2350 if (value.find('r') != std::string::npos)
2351 region_info.SetReadable (MemoryRegionInfo::eYes);
2353 region_info.SetReadable (MemoryRegionInfo::eNo);
2355 if (value.find('w') != std::string::npos)
2356 region_info.SetWritable (MemoryRegionInfo::eYes);
2358 region_info.SetWritable (MemoryRegionInfo::eNo);
2360 if (value.find('x') != std::string::npos)
2361 region_info.SetExecutable (MemoryRegionInfo::eYes);
2363 region_info.SetExecutable (MemoryRegionInfo::eNo);
2367 // The reported region does not contain this address -- we're looking at an unmapped page
2368 region_info.SetReadable (MemoryRegionInfo::eNo);
2369 region_info.SetWritable (MemoryRegionInfo::eNo);
2370 region_info.SetExecutable (MemoryRegionInfo::eNo);
2373 else if (name.compare ("error") == 0)
2375 StringExtractorGDBRemote name_extractor;
2376 // Swap "value" over into "name_extractor"
2377 name_extractor.GetStringRef().swap(value);
2378 // Now convert the HEX bytes into a string value
2379 name_extractor.GetHexByteString (value);
2380 error.SetErrorString(value.c_str());
2384 // We got a valid address range back but no permissions -- which means this is an unmapped page
2385 if (region_info.GetRange().IsValid() && saw_permissions == false)
2387 region_info.SetReadable (MemoryRegionInfo::eNo);
2388 region_info.SetWritable (MemoryRegionInfo::eNo);
2389 region_info.SetExecutable (MemoryRegionInfo::eNo);
2394 m_supports_memory_region_info = eLazyBoolNo;
2398 if (m_supports_memory_region_info == eLazyBoolNo)
2400 error.SetErrorString("qMemoryRegionInfo is not supported");
2403 region_info.Clear();
2409 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2413 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2415 num = m_num_supported_hardware_watchpoints;
2419 // Set num to 0 first.
2421 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2424 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
2425 assert (packet_len < (int)sizeof(packet));
2426 StringExtractorGDBRemote response;
2427 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2429 m_supports_watchpoint_support_info = eLazyBoolYes;
2432 while (response.GetNameColonValue(name, value))
2434 if (name.compare ("num") == 0)
2436 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
2437 m_num_supported_hardware_watchpoints = num;
2443 m_supports_watchpoint_support_info = eLazyBoolNo;
2447 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2449 error.SetErrorString("qWatchpointSupportInfo is not supported");
2456 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2458 Error error(GetWatchpointSupportInfo(num));
2459 if (error.Success())
2460 error = GetWatchpointsTriggerAfterInstruction(after);
2465 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2469 // we assume watchpoints will happen after running the relevant opcode
2470 // and we only want to override this behavior if we have explicitly
2471 // received a qHostInfo telling us otherwise
2472 if (m_qHostInfo_is_valid != eLazyBoolYes)
2475 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2480 GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
2484 std::string path{file_spec.GetPath(false)};
2485 StreamString packet;
2486 packet.PutCString("QSetSTDIN:");
2487 packet.PutCStringAsRawHex8(path.c_str());
2489 StringExtractorGDBRemote response;
2490 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2492 if (response.IsOKResponse())
2494 uint8_t error = response.GetError();
2503 GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
2507 std::string path{file_spec.GetPath(false)};
2508 StreamString packet;
2509 packet.PutCString("QSetSTDOUT:");
2510 packet.PutCStringAsRawHex8(path.c_str());
2512 StringExtractorGDBRemote response;
2513 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2515 if (response.IsOKResponse())
2517 uint8_t error = response.GetError();
2526 GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
2530 std::string path{file_spec.GetPath(false)};
2531 StreamString packet;
2532 packet.PutCString("QSetSTDERR:");
2533 packet.PutCStringAsRawHex8(path.c_str());
2535 StringExtractorGDBRemote response;
2536 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2538 if (response.IsOKResponse())
2540 uint8_t error = response.GetError();
2549 GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
2551 StringExtractorGDBRemote response;
2552 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2554 if (response.IsUnsupportedResponse())
2556 if (response.IsErrorResponse())
2559 response.GetHexByteString(cwd);
2560 working_dir.SetFile(cwd, false, GetHostArchitecture());
2561 return !cwd.empty();
2567 GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
2571 std::string path{working_dir.GetPath(false)};
2572 StreamString packet;
2573 packet.PutCString("QSetWorkingDir:");
2574 packet.PutCStringAsRawHex8(path.c_str());
2576 StringExtractorGDBRemote response;
2577 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2579 if (response.IsOKResponse())
2581 uint8_t error = response.GetError();
2590 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2593 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2594 assert (packet_len < (int)sizeof(packet));
2595 StringExtractorGDBRemote response;
2596 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2598 if (response.IsOKResponse())
2600 uint8_t error = response.GetError();
2608 GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2611 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2612 assert (packet_len < (int)sizeof(packet));
2613 StringExtractorGDBRemote response;
2614 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2616 if (response.IsOKResponse())
2618 uint8_t error = response.GetError();
2627 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2629 if (response.IsNormalResponse())
2633 StringExtractor extractor;
2635 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2638 std::string os_type;
2640 while (response.GetNameColonValue(name, value))
2642 if (name.compare("pid") == 0)
2644 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2646 else if (name.compare("ppid") == 0)
2648 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2650 else if (name.compare("uid") == 0)
2652 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2654 else if (name.compare("euid") == 0)
2656 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2658 else if (name.compare("gid") == 0)
2660 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2662 else if (name.compare("egid") == 0)
2664 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
2666 else if (name.compare("triple") == 0)
2668 StringExtractor extractor;
2669 extractor.GetStringRef().swap(value);
2670 extractor.SetFilePos(0);
2671 extractor.GetHexByteString (value);
2672 process_info.GetArchitecture ().SetTriple (value.c_str());
2674 else if (name.compare("name") == 0)
2676 StringExtractor extractor;
2677 // The process name from ASCII hex bytes since we can't
2678 // control the characters in a process name
2679 extractor.GetStringRef().swap(value);
2680 extractor.SetFilePos(0);
2681 extractor.GetHexByteString (value);
2682 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2684 else if (name.compare("cputype") == 0)
2686 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2688 else if (name.compare("cpusubtype") == 0)
2690 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2692 else if (name.compare("vendor") == 0)
2696 else if (name.compare("ostype") == 0)
2702 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2704 if (vendor == "apple")
2706 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2707 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2708 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2712 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2719 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2721 process_info.Clear();
2723 if (m_supports_qProcessInfoPID)
2726 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2727 assert (packet_len < (int)sizeof(packet));
2728 StringExtractorGDBRemote response;
2729 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2731 return DecodeProcessInfoResponse (response, process_info);
2735 m_supports_qProcessInfoPID = false;
2743 GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
2745 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2749 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2751 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2757 StringExtractorGDBRemote response;
2758 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2760 if (response.IsNormalResponse())
2764 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2766 std::string arch_name;
2767 std::string os_name;
2768 std::string vendor_name;
2770 uint32_t pointer_byte_size = 0;
2771 StringExtractor extractor;
2772 ByteOrder byte_order = eByteOrderInvalid;
2773 uint32_t num_keys_decoded = 0;
2774 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2775 while (response.GetNameColonValue(name, value))
2777 if (name.compare("cputype") == 0)
2779 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2780 if (cpu != LLDB_INVALID_CPUTYPE)
2783 else if (name.compare("cpusubtype") == 0)
2785 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2789 else if (name.compare("triple") == 0)
2791 StringExtractor extractor;
2792 extractor.GetStringRef().swap(value);
2793 extractor.SetFilePos(0);
2794 extractor.GetHexByteString (triple);
2797 else if (name.compare("ostype") == 0)
2799 os_name.swap (value);
2802 else if (name.compare("vendor") == 0)
2804 vendor_name.swap(value);
2807 else if (name.compare("endian") == 0)
2810 if (value.compare("little") == 0)
2811 byte_order = eByteOrderLittle;
2812 else if (value.compare("big") == 0)
2813 byte_order = eByteOrderBig;
2814 else if (value.compare("pdp") == 0)
2815 byte_order = eByteOrderPDP;
2819 else if (name.compare("ptrsize") == 0)
2821 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2822 if (pointer_byte_size != 0)
2825 else if (name.compare("pid") == 0)
2827 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
2828 if (pid != LLDB_INVALID_PROCESS_ID)
2832 if (num_keys_decoded > 0)
2833 m_qProcessInfo_is_valid = eLazyBoolYes;
2834 if (pid != LLDB_INVALID_PROCESS_ID)
2836 m_curr_pid_is_valid = eLazyBoolYes;
2840 // Set the ArchSpec from the triple if we have it.
2841 if (!triple.empty ())
2843 m_process_arch.SetTriple (triple.c_str ());
2844 if (pointer_byte_size)
2846 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2849 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2851 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2853 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2854 switch (triple.getObjectFormat()) {
2855 case llvm::Triple::MachO:
2856 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2858 case llvm::Triple::ELF:
2859 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2861 case llvm::Triple::COFF:
2862 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2864 case llvm::Triple::UnknownObjectFormat:
2866 log->Printf("error: failed to determine target architecture");
2870 if (pointer_byte_size)
2872 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2874 if (byte_order != eByteOrderInvalid)
2876 assert (byte_order == m_process_arch.GetByteOrder());
2878 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2879 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2880 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2881 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2888 m_qProcessInfo_is_valid = eLazyBoolNo;
2896 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2897 ProcessInstanceInfoList &process_infos)
2899 process_infos.Clear();
2901 if (m_supports_qfProcessInfo)
2903 StreamString packet;
2904 packet.PutCString ("qfProcessInfo");
2905 if (!match_info.MatchAllProcesses())
2907 packet.PutChar (':');
2908 const char *name = match_info.GetProcessInfo().GetName();
2909 bool has_name_match = false;
2910 if (name && name[0])
2912 has_name_match = true;
2913 NameMatchType name_match_type = match_info.GetNameMatchType();
2914 switch (name_match_type)
2916 case eNameMatchIgnore:
2917 has_name_match = false;
2920 case eNameMatchEquals:
2921 packet.PutCString ("name_match:equals;");
2924 case eNameMatchContains:
2925 packet.PutCString ("name_match:contains;");
2928 case eNameMatchStartsWith:
2929 packet.PutCString ("name_match:starts_with;");
2932 case eNameMatchEndsWith:
2933 packet.PutCString ("name_match:ends_with;");
2936 case eNameMatchRegularExpression:
2937 packet.PutCString ("name_match:regex;");
2942 packet.PutCString ("name:");
2943 packet.PutBytesAsRawHex8(name, ::strlen(name));
2944 packet.PutChar (';');
2948 if (match_info.GetProcessInfo().ProcessIDIsValid())
2949 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2950 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2951 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2952 if (match_info.GetProcessInfo().UserIDIsValid())
2953 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2954 if (match_info.GetProcessInfo().GroupIDIsValid())
2955 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2956 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2957 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2958 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2959 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2960 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2961 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2962 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2964 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2965 const llvm::Triple &triple = match_arch.GetTriple();
2966 packet.PutCString("triple:");
2967 packet.PutCString(triple.getTriple().c_str());
2968 packet.PutChar (';');
2971 StringExtractorGDBRemote response;
2972 // Increase timeout as the first qfProcessInfo packet takes a long time
2973 // on Android. The value of 1min was arrived at empirically.
2974 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
2975 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2979 ProcessInstanceInfo process_info;
2980 if (!DecodeProcessInfoResponse (response, process_info))
2982 process_infos.Append(process_info);
2983 response.GetStringRef().clear();
2984 response.SetFilePos(0);
2985 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2989 m_supports_qfProcessInfo = false;
2993 return process_infos.GetSize();
2998 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3000 if (m_supports_qUserName)
3003 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
3004 assert (packet_len < (int)sizeof(packet));
3005 StringExtractorGDBRemote response;
3006 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3008 if (response.IsNormalResponse())
3010 // Make sure we parsed the right number of characters. The response is
3011 // the hex encoded user name and should make up the entire packet.
3012 // If there are any non-hex ASCII bytes, the length won't match below..
3013 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3019 m_supports_qUserName = false;
3028 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3030 if (m_supports_qGroupName)
3033 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
3034 assert (packet_len < (int)sizeof(packet));
3035 StringExtractorGDBRemote response;
3036 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
3038 if (response.IsNormalResponse())
3040 // Make sure we parsed the right number of characters. The response is
3041 // the hex encoded group name and should make up the entire packet.
3042 // If there are any non-hex ASCII bytes, the length won't match below..
3043 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3049 m_supports_qGroupName = false;
3057 GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3059 // Form non-stop packet request
3061 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3062 assert(packet_len < (int)sizeof(packet));
3064 StringExtractorGDBRemote response;
3066 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3067 if (response.IsOKResponse())
3070 // Failed or not supported
3076 MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3079 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3080 uint32_t bytes_left = send_size;
3081 while (bytes_left > 0)
3083 if (bytes_left >= 26)
3085 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3090 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3096 template<typename T>
3097 T calculate_standard_deviation(const std::vector<T> &v)
3099 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3100 T mean = sum / (T)v.size();
3102 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3104 accum += delta * delta;
3107 T stdev = sqrt(accum / (v.size()-1));
3112 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
3115 TimeValue start_time, end_time;
3116 uint64_t total_time_nsec;
3117 if (SendSpeedTestPacket (0, 0))
3119 StreamString packet;
3121 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3123 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3126 uint32_t result_idx = 0;
3128 std::vector<float> packet_times;
3130 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3132 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3134 MakeSpeedTestPacket (packet, send_size, recv_size);
3136 packet_times.clear();
3137 // Test how long it takes to send 'num_packets' packets
3138 start_time = TimeValue::Now();
3139 for (i=0; i<num_packets; ++i)
3141 TimeValue packet_start_time = TimeValue::Now();
3142 StringExtractorGDBRemote response;
3143 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3144 TimeValue packet_end_time = TimeValue::Now();
3145 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3146 packet_times.push_back((float)packet_time_nsec);
3148 end_time = TimeValue::Now();
3149 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3151 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3152 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3153 float average_ms_per_packet = total_ms / num_packets;
3154 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3157 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);
3162 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",
3165 total_time_nsec / TimeValue::NanoSecPerSec,
3166 total_time_nsec % TimeValue::NanoSecPerSec,
3168 average_ms_per_packet,
3169 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
3175 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3177 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3179 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3181 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3185 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3187 MakeSpeedTestPacket (packet, send_size, recv_size);
3189 // If we have a receive size, test how long it takes to receive 4MB of data
3192 start_time = TimeValue::Now();
3193 uint32_t bytes_read = 0;
3194 uint32_t packet_count = 0;
3195 while (bytes_read < k_recv_amount)
3197 StringExtractorGDBRemote response;
3198 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3199 bytes_read += recv_size;
3202 end_time = TimeValue::Now();
3203 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3204 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3205 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3206 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3207 float average_ms_per_packet = total_ms / packet_count;
3211 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);
3216 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",
3221 total_time_nsec / TimeValue::NanoSecPerSec,
3222 total_time_nsec % TimeValue::NanoSecPerSec,
3225 average_ms_per_packet);
3231 strm.Printf("\n ]\n }\n}\n");
3238 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3240 StreamString packet;
3241 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3242 uint32_t bytes_left = send_size;
3243 while (bytes_left > 0)
3245 if (bytes_left >= 26)
3247 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3252 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3257 StringExtractorGDBRemote response;
3258 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
3262 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
3264 pid = LLDB_INVALID_PROCESS_ID;
3265 StringExtractorGDBRemote response;
3266 StreamString stream;
3267 stream.PutCString("qLaunchGDBServer;");
3268 std::string hostname;
3269 if (remote_accept_hostname && remote_accept_hostname[0])
3270 hostname = remote_accept_hostname;
3273 if (HostInfo::GetHostname(hostname))
3275 // Make the GDB server we launch only accept connections from this host
3276 stream.Printf("host:%s;", hostname.c_str());
3280 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3281 stream.Printf("host:*;");
3284 const char *packet = stream.GetData();
3285 int packet_len = stream.GetSize();
3287 // give the process a few seconds to startup
3288 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3290 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3295 while (response.GetNameColonValue(name, value))
3297 if (name.compare("port") == 0)
3298 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
3299 else if (name.compare("pid") == 0)
3300 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
3308 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3310 StreamString stream;
3311 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3312 const char *packet = stream.GetData();
3313 int packet_len = stream.GetSize();
3315 StringExtractorGDBRemote response;
3316 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3318 if (response.IsOKResponse())
3325 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
3327 if (m_curr_tid == tid)
3332 if (tid == UINT64_MAX)
3333 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
3335 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
3336 assert (packet_len + 1 < (int)sizeof(packet));
3337 StringExtractorGDBRemote response;
3338 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3340 if (response.IsOKResponse())
3350 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
3352 if (m_curr_tid_run == tid)
3357 if (tid == UINT64_MAX)
3358 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
3360 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3362 assert (packet_len + 1 < (int)sizeof(packet));
3363 StringExtractorGDBRemote response;
3364 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3366 if (response.IsOKResponse())
3368 m_curr_tid_run = tid;
3376 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3378 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
3379 return response.IsNormalResponse();
3384 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
3386 if (m_supports_qThreadStopInfo)
3389 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
3390 assert (packet_len < (int)sizeof(packet));
3391 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3393 if (response.IsUnsupportedResponse())
3394 m_supports_qThreadStopInfo = false;
3395 else if (response.IsNormalResponse())
3402 m_supports_qThreadStopInfo = false;
3410 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3412 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3414 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3415 __FUNCTION__, insert ? "add" : "remove", addr);
3417 // Check if the stub is known not to support this breakpoint type
3418 if (!SupportsGDBStoppointPacket(type))
3420 // Construct the breakpoint packet
3422 const int packet_len = ::snprintf (packet,
3424 "%c%i,%" PRIx64 ",%x",
3429 // Check we haven't overwritten the end of the packet buffer
3430 assert (packet_len + 1 < (int)sizeof(packet));
3431 StringExtractorGDBRemote response;
3432 // Try to send the breakpoint packet, and check that it was correctly sent
3433 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
3435 // Receive and OK packet when the breakpoint successfully placed
3436 if (response.IsOKResponse())
3439 // Error while setting breakpoint, send back specific error
3440 if (response.IsErrorResponse())
3441 return response.GetError();
3443 // Empty packet informs us that breakpoint is not supported
3444 if (response.IsUnsupportedResponse())
3446 // Disable this breakpoint type since it is unsupported
3449 case eBreakpointSoftware: m_supports_z0 = false; break;
3450 case eBreakpointHardware: m_supports_z1 = false; break;
3451 case eWatchpointWrite: m_supports_z2 = false; break;
3452 case eWatchpointRead: m_supports_z3 = false; break;
3453 case eWatchpointReadWrite: m_supports_z4 = false; break;
3454 case eStoppointInvalid: return UINT8_MAX;
3458 // Signal generic failure
3463 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3464 bool &sequence_mutex_unavailable)
3466 Mutex::Locker locker;
3469 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
3471 sequence_mutex_unavailable = false;
3472 StringExtractorGDBRemote response;
3474 PacketResult packet_result;
3475 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3476 packet_result == PacketResult::Success && response.IsNormalResponse();
3477 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
3479 char ch = response.GetChar();
3486 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3488 if (tid != LLDB_INVALID_THREAD_ID)
3490 thread_ids.push_back (tid);
3492 ch = response.GetChar(); // Skip the command separator
3493 } while (ch == ','); // Make sure we got a comma separator
3499 #if defined (LLDB_CONFIGURATION_DEBUG)
3500 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3502 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3504 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3506 sequence_mutex_unavailable = true;
3508 return thread_ids.size();
3512 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3516 StringExtractorGDBRemote response;
3517 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3519 if (response.IsNormalResponse())
3520 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3523 return LLDB_INVALID_ADDRESS;
3527 GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3528 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3529 int *status_ptr, // Pass NULL if you don't want the process exit status
3530 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3531 std::string *command_output, // Pass NULL if you don't want the command output
3532 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
3534 lldb_private::StreamString stream;
3535 stream.PutCString("qPlatform_shell:");
3536 stream.PutBytesAsRawHex8(command, strlen(command));
3537 stream.PutChar(',');
3538 stream.PutHex32(timeout_sec);
3541 std::string path{working_dir.GetPath(false)};
3542 stream.PutChar(',');
3543 stream.PutCStringAsRawHex8(path.c_str());
3545 const char *packet = stream.GetData();
3546 int packet_len = stream.GetSize();
3547 StringExtractorGDBRemote response;
3548 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3550 if (response.GetChar() != 'F')
3551 return Error("malformed reply");
3552 if (response.GetChar() != ',')
3553 return Error("malformed reply");
3554 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3555 if (exitcode == UINT32_MAX)
3556 return Error("unable to run remote process");
3557 else if (status_ptr)
3558 *status_ptr = exitcode;
3559 if (response.GetChar() != ',')
3560 return Error("malformed reply");
3561 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3564 if (response.GetChar() != ',')
3565 return Error("malformed reply");
3567 response.GetEscapedBinaryData(output);
3569 command_output->assign(output);
3572 return Error("unable to send packet");
3576 GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3577 uint32_t file_permissions)
3579 std::string path{file_spec.GetPath(false)};
3580 lldb_private::StreamString stream;
3581 stream.PutCString("qPlatform_mkdir:");
3582 stream.PutHex32(file_permissions);
3583 stream.PutChar(',');
3584 stream.PutCStringAsRawHex8(path.c_str());
3585 const char *packet = stream.GetData();
3586 int packet_len = stream.GetSize();
3587 StringExtractorGDBRemote response;
3589 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3590 return Error("failed to send '%s' packet", packet);
3592 if (response.GetChar() != 'F')
3593 return Error("invalid response to '%s' packet", packet);
3595 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3599 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3600 uint32_t file_permissions)
3602 std::string path{file_spec.GetPath(false)};
3603 lldb_private::StreamString stream;
3604 stream.PutCString("qPlatform_chmod:");
3605 stream.PutHex32(file_permissions);
3606 stream.PutChar(',');
3607 stream.PutCStringAsRawHex8(path.c_str());
3608 const char *packet = stream.GetData();
3609 int packet_len = stream.GetSize();
3610 StringExtractorGDBRemote response;
3612 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3613 return Error("failed to send '%s' packet", packet);
3615 if (response.GetChar() != 'F')
3616 return Error("invalid response to '%s' packet", packet);
3618 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
3622 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3623 uint64_t fail_result,
3626 response.SetFilePos(0);
3627 if (response.GetChar() != 'F')
3629 int32_t result = response.GetS32 (-2);
3632 if (response.GetChar() == ',')
3634 int result_errno = response.GetS32 (-2);
3635 if (result_errno != -2)
3636 error.SetError(result_errno, eErrorTypePOSIX);
3638 error.SetError(-1, eErrorTypeGeneric);
3645 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3650 std::string path(file_spec.GetPath(false));
3651 lldb_private::StreamString stream;
3652 stream.PutCString("vFile:open:");
3655 stream.PutCStringAsRawHex8(path.c_str());
3656 stream.PutChar(',');
3657 stream.PutHex32(flags);
3658 stream.PutChar(',');
3659 stream.PutHex32(mode);
3660 const char* packet = stream.GetData();
3661 int packet_len = stream.GetSize();
3662 StringExtractorGDBRemote response;
3663 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3665 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3671 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3674 lldb_private::StreamString stream;
3675 stream.Printf("vFile:close:%i", (int)fd);
3676 const char* packet = stream.GetData();
3677 int packet_len = stream.GetSize();
3678 StringExtractorGDBRemote response;
3679 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3681 return ParseHostIOPacketResponse (response, -1, error) == 0;
3686 // Extension of host I/O packets to get the file size.
3688 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3690 std::string path(file_spec.GetPath(false));
3691 lldb_private::StreamString stream;
3692 stream.PutCString("vFile:size:");
3693 stream.PutCStringAsRawHex8(path.c_str());
3694 const char* packet = stream.GetData();
3695 int packet_len = stream.GetSize();
3696 StringExtractorGDBRemote response;
3697 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3699 if (response.GetChar() != 'F')
3701 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3708 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3709 uint32_t &file_permissions)
3711 std::string path{file_spec.GetPath(false)};
3713 lldb_private::StreamString stream;
3714 stream.PutCString("vFile:mode:");
3715 stream.PutCStringAsRawHex8(path.c_str());
3716 const char* packet = stream.GetData();
3717 int packet_len = stream.GetSize();
3718 StringExtractorGDBRemote response;
3719 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3721 if (response.GetChar() != 'F')
3723 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3727 const uint32_t mode = response.GetS32(-1);
3728 if (static_cast<int32_t>(mode) == -1)
3730 if (response.GetChar() == ',')
3732 int response_errno = response.GetS32(-1);
3733 if (response_errno > 0)
3734 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3736 error.SetErrorToGenericError();
3739 error.SetErrorToGenericError();
3743 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3749 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3755 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3761 lldb_private::StreamString stream;
3762 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3763 const char* packet = stream.GetData();
3764 int packet_len = stream.GetSize();
3765 StringExtractorGDBRemote response;
3766 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3768 if (response.GetChar() != 'F')
3770 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3771 if (retcode == UINT32_MAX)
3773 const char next = (response.Peek() ? *response.Peek() : 0);
3778 response.GetChar(); // skip the semicolon
3780 if (response.GetEscapedBinaryData(buffer))
3782 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3783 if (data_to_write > 0)
3784 memcpy(dst, &buffer[0], data_to_write);
3785 return data_to_write;
3793 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3799 lldb_private::StreamGDBRemote stream;
3800 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3801 stream.PutEscapedBytes(src, src_len);
3802 const char* packet = stream.GetData();
3803 int packet_len = stream.GetSize();
3804 StringExtractorGDBRemote response;
3805 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3807 if (response.GetChar() != 'F')
3809 error.SetErrorStringWithFormat("write file failed");
3812 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3813 if (bytes_written == UINT64_MAX)
3815 error.SetErrorToGenericError();
3816 if (response.GetChar() == ',')
3818 int response_errno = response.GetS32(-1);
3819 if (response_errno > 0)
3820 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3824 return bytes_written;
3828 error.SetErrorString ("failed to send vFile:pwrite packet");
3834 GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
3836 std::string src_path{src.GetPath(false)},
3837 dst_path{dst.GetPath(false)};
3839 lldb_private::StreamGDBRemote stream;
3840 stream.PutCString("vFile:symlink:");
3841 // the unix symlink() command reverses its parameters where the dst if first,
3842 // so we follow suit here
3843 stream.PutCStringAsRawHex8(dst_path.c_str());
3844 stream.PutChar(',');
3845 stream.PutCStringAsRawHex8(src_path.c_str());
3846 const char* packet = stream.GetData();
3847 int packet_len = stream.GetSize();
3848 StringExtractorGDBRemote response;
3849 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3851 if (response.GetChar() == 'F')
3853 uint32_t result = response.GetU32(UINT32_MAX);
3856 error.SetErrorToGenericError();
3857 if (response.GetChar() == ',')
3859 int response_errno = response.GetS32(-1);
3860 if (response_errno > 0)
3861 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3867 // Should have returned with 'F<result>[,<errno>]'
3868 error.SetErrorStringWithFormat("symlink failed");
3873 error.SetErrorString ("failed to send vFile:symlink packet");
3879 GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
3881 std::string path{file_spec.GetPath(false)};
3883 lldb_private::StreamGDBRemote stream;
3884 stream.PutCString("vFile:unlink:");
3885 // the unix symlink() command reverses its parameters where the dst if first,
3886 // so we follow suit here
3887 stream.PutCStringAsRawHex8(path.c_str());
3888 const char* packet = stream.GetData();
3889 int packet_len = stream.GetSize();
3890 StringExtractorGDBRemote response;
3891 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3893 if (response.GetChar() == 'F')
3895 uint32_t result = response.GetU32(UINT32_MAX);
3898 error.SetErrorToGenericError();
3899 if (response.GetChar() == ',')
3901 int response_errno = response.GetS32(-1);
3902 if (response_errno > 0)
3903 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3909 // Should have returned with 'F<result>[,<errno>]'
3910 error.SetErrorStringWithFormat("unlink failed");
3915 error.SetErrorString ("failed to send vFile:unlink packet");
3920 // Extension of host I/O packets to get whether a file exists.
3922 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3924 std::string path(file_spec.GetPath(false));
3925 lldb_private::StreamString stream;
3926 stream.PutCString("vFile:exists:");
3927 stream.PutCStringAsRawHex8(path.c_str());
3928 const char* packet = stream.GetData();
3929 int packet_len = stream.GetSize();
3930 StringExtractorGDBRemote response;
3931 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3933 if (response.GetChar() != 'F')
3935 if (response.GetChar() != ',')
3937 bool retcode = (response.GetChar() != '0');
3944 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3948 std::string path(file_spec.GetPath(false));
3949 lldb_private::StreamString stream;
3950 stream.PutCString("vFile:MD5:");
3951 stream.PutCStringAsRawHex8(path.c_str());
3952 const char* packet = stream.GetData();
3953 int packet_len = stream.GetSize();
3954 StringExtractorGDBRemote response;
3955 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3957 if (response.GetChar() != 'F')
3959 if (response.GetChar() != ',')
3961 if (response.Peek() && *response.Peek() == 'x')
3963 low = response.GetHexMaxU64(false, UINT64_MAX);
3964 high = response.GetHexMaxU64(false, UINT64_MAX);
3971 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3973 // Some targets have issues with g/G packets and we need to avoid using them
3974 if (m_avoid_g_packets == eLazyBoolCalculate)
3978 m_avoid_g_packets = eLazyBoolNo;
3979 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3981 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3982 && arch.GetTriple().getOS() == llvm::Triple::IOS
3983 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
3985 m_avoid_g_packets = eLazyBoolYes;
3986 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3987 if (gdb_server_version != 0)
3989 const char *gdb_server_name = GetGDBServerProgramName();
3990 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3992 if (gdb_server_version >= 310)
3993 m_avoid_g_packets = eLazyBoolNo;
3999 return m_avoid_g_packets == eLazyBoolYes;
4003 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4005 Mutex::Locker locker;
4006 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4008 const bool thread_suffix_supported = GetThreadSuffixSupported();
4010 if (thread_suffix_supported || SetCurrentThread(tid))
4014 if (thread_suffix_supported)
4015 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4017 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4018 assert (packet_len < ((int)sizeof(packet) - 1));
4019 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4028 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4030 Mutex::Locker locker;
4031 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4033 const bool thread_suffix_supported = GetThreadSuffixSupported();
4035 if (thread_suffix_supported || SetCurrentThread(tid))
4039 // Get all registers in one packet
4040 if (thread_suffix_supported)
4041 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4043 packet_len = ::snprintf (packet, sizeof(packet), "g");
4044 assert (packet_len < ((int)sizeof(packet) - 1));
4045 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
4051 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4053 save_id = 0; // Set to invalid save ID
4054 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4057 m_supports_QSaveRegisterState = eLazyBoolYes;
4058 Mutex::Locker locker;
4059 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4061 const bool thread_suffix_supported = GetThreadSuffixSupported();
4062 if (thread_suffix_supported || SetCurrentThread(tid))
4065 if (thread_suffix_supported)
4066 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4068 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
4070 StringExtractorGDBRemote response;
4072 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4074 if (response.IsUnsupportedResponse())
4076 // This packet isn't supported, don't try calling it again
4077 m_supports_QSaveRegisterState = eLazyBoolNo;
4080 const uint32_t response_save_id = response.GetU32(0);
4081 if (response_save_id != 0)
4083 save_id = response_save_id;
4093 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4095 // We use the "m_supports_QSaveRegisterState" variable here because the
4096 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4097 // order to be useful
4098 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4101 Mutex::Locker locker;
4102 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4104 const bool thread_suffix_supported = GetThreadSuffixSupported();
4105 if (thread_suffix_supported || SetCurrentThread(tid))
4108 if (thread_suffix_supported)
4109 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4111 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4113 StringExtractorGDBRemote response;
4115 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
4117 if (response.IsOKResponse())
4121 else if (response.IsUnsupportedResponse())
4123 // This packet isn't supported, don't try calling this packet or
4124 // QSaveRegisterState again...
4125 m_supports_QSaveRegisterState = eLazyBoolNo;
4134 GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
4135 const lldb_private::ArchSpec& arch_spec,
4136 ModuleSpec &module_spec)
4138 std::string module_path = module_file_spec.GetPath (false);
4139 if (module_path.empty ())
4142 StreamString packet;
4143 packet.PutCString("qModuleInfo:");
4144 packet.PutCStringAsRawHex8(module_path.c_str());
4145 packet.PutCString(";");
4146 const auto& triple = arch_spec.GetTriple().getTriple();
4147 packet.PutCStringAsRawHex8(triple.c_str());
4149 StringExtractorGDBRemote response;
4150 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4153 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
4159 StringExtractor extractor;
4161 module_spec.Clear ();
4162 module_spec.GetFileSpec () = module_file_spec;
4164 while (response.GetNameColonValue (name, value))
4166 if (name == "uuid" || name == "md5")
4168 extractor.GetStringRef ().swap (value);
4169 extractor.SetFilePos (0);
4170 extractor.GetHexByteString (value);
4171 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4173 else if (name == "triple")
4175 extractor.GetStringRef ().swap (value);
4176 extractor.SetFilePos (0);
4177 extractor.GetHexByteString (value);
4178 module_spec.GetArchitecture().SetTriple (value.c_str ());
4180 else if (name == "file_offset")
4182 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4184 module_spec.SetObjectOffset (ival);
4186 else if (name == "file_size")
4188 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4190 module_spec.SetObjectSize (ival);
4192 else if (name == "file_path")
4194 extractor.GetStringRef ().swap (value);
4195 extractor.SetFilePos (0);
4196 extractor.GetHexByteString (value);
4197 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
4204 // query the target remote for extended information using the qXfer packet
4206 // example: object='features', annex='target.xml', out=<xml output>
4207 // return: 'true' on success
4208 // 'false' on failure (err set)
4210 GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4211 const lldb_private::ConstString annex,
4213 lldb_private::Error & err) {
4215 std::stringstream output;
4216 StringExtractorGDBRemote chunk;
4218 uint64_t size = GetRemoteMaxPacketSize();
4221 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4225 // loop until all data has been read
4228 // send query extended feature packet
4229 std::stringstream packet;
4231 << object.AsCString("") << ":read:"
4232 << annex.AsCString("") << ":"
4233 << std::hex << offset << ","
4234 << std::hex << size;
4236 GDBRemoteCommunication::PacketResult res =
4237 SendPacketAndWaitForResponse( packet.str().c_str(),
4241 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4242 err.SetErrorString( "Error sending $qXfer packet" );
4246 const std::string & str = chunk.GetStringRef( );
4247 if ( str.length() == 0 ) {
4248 // should have some data in chunk
4249 err.SetErrorString( "Empty response from $qXfer packet" );
4253 // check packet code
4258 // fall through intentional
4262 if ( str.length() > 1 )
4269 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4274 out = output.str( );
4279 // Notify the target that gdb is prepared to serve symbol lookup requests.
4280 // packet: "qSymbol::"
4282 // OK The target does not need to look up any (more) symbols.
4283 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4284 // LLDB may provide the value by sending another qSymbol packet
4285 // in the form of"qSymbol:<sym_value>:<sym_name>".
4288 GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4290 if (m_supports_qSymbol)
4292 Mutex::Locker locker;
4293 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4295 StreamString packet;
4296 packet.PutCString ("qSymbol::");
4299 StringExtractorGDBRemote response;
4300 if (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
4302 if (response.IsOKResponse())
4304 // We are done serving symbols requests
4308 if (response.IsUnsupportedResponse())
4310 // qSymbol is not supported by the current GDB server we are connected to
4311 m_supports_qSymbol = false;
4316 llvm::StringRef response_str(response.GetStringRef());
4317 if (response_str.startswith("qSymbol:"))
4319 response.SetFilePos(strlen("qSymbol:"));
4320 std::string symbol_name;
4321 if (response.GetHexByteString(symbol_name))
4323 if (symbol_name.empty())
4326 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4327 lldb_private::SymbolContextList sc_list;
4328 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
4330 const size_t num_scs = sc_list.GetSize();
4331 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
4334 if (sc_list.GetContextAtIndex(sc_idx, sc))
4338 switch (sc.symbol->GetType())
4340 case eSymbolTypeInvalid:
4341 case eSymbolTypeAbsolute:
4342 case eSymbolTypeUndefined:
4343 case eSymbolTypeSourceFile:
4344 case eSymbolTypeHeaderFile:
4345 case eSymbolTypeObjectFile:
4346 case eSymbolTypeCommonBlock:
4347 case eSymbolTypeBlock:
4348 case eSymbolTypeLocal:
4349 case eSymbolTypeParam:
4350 case eSymbolTypeVariable:
4351 case eSymbolTypeVariableType:
4352 case eSymbolTypeLineEntry:
4353 case eSymbolTypeLineHeader:
4354 case eSymbolTypeScopeBegin:
4355 case eSymbolTypeScopeEnd:
4356 case eSymbolTypeAdditional:
4357 case eSymbolTypeCompiler:
4358 case eSymbolTypeInstrumentation:
4359 case eSymbolTypeTrampoline:
4362 case eSymbolTypeCode:
4363 case eSymbolTypeResolver:
4364 case eSymbolTypeData:
4365 case eSymbolTypeRuntime:
4366 case eSymbolTypeException:
4367 case eSymbolTypeObjCClass:
4368 case eSymbolTypeObjCMetaClass:
4369 case eSymbolTypeObjCIVar:
4370 case eSymbolTypeReExported:
4371 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4378 // This is the normal path where our symbol lookup was successful and we want
4379 // to send a packet with the new symbol value and see if another lookup needs to be
4382 // Change "packet" to contain the requested symbol value and name
4384 packet.PutCString("qSymbol:");
4385 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4386 packet.Printf("%" PRIx64, symbol_load_addr);
4387 packet.PutCString(":");
4388 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4389 continue; // go back to the while loop and send "packet" and wait for another response
4395 // If we make it here, the symbol request packet response wasn't valid or
4396 // our symbol lookup failed so we must abort