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"
19 // Other libraries and framework includes
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "lldb/Interpreter/Args.h"
23 #include "lldb/Core/Log.h"
24 #include "lldb/Core/State.h"
25 #include "lldb/Core/StreamGDBRemote.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Host/ConnectionFileDescriptor.h"
28 #include "lldb/Host/Endian.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Host/HostInfo.h"
31 #include "lldb/Host/TimeValue.h"
32 #include "lldb/Target/Target.h"
35 #include "Utility/StringExtractorGDBRemote.h"
36 #include "ProcessGDBRemote.h"
37 #include "ProcessGDBRemoteLog.h"
38 #include "lldb/Host/Config.h"
41 using namespace lldb_private;
43 #if defined(LLDB_DISABLE_POSIX) && !defined(SIGSTOP)
47 //----------------------------------------------------------------------
48 // GDBRemoteCommunicationClient constructor
49 //----------------------------------------------------------------------
50 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
51 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
52 m_supports_not_sending_acks (eLazyBoolCalculate),
53 m_supports_thread_suffix (eLazyBoolCalculate),
54 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
55 m_supports_vCont_all (eLazyBoolCalculate),
56 m_supports_vCont_any (eLazyBoolCalculate),
57 m_supports_vCont_c (eLazyBoolCalculate),
58 m_supports_vCont_C (eLazyBoolCalculate),
59 m_supports_vCont_s (eLazyBoolCalculate),
60 m_supports_vCont_S (eLazyBoolCalculate),
61 m_qHostInfo_is_valid (eLazyBoolCalculate),
62 m_curr_pid_is_valid (eLazyBoolCalculate),
63 m_qProcessInfo_is_valid (eLazyBoolCalculate),
64 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
65 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
66 m_supports_memory_region_info (eLazyBoolCalculate),
67 m_supports_watchpoint_support_info (eLazyBoolCalculate),
68 m_supports_detach_stay_stopped (eLazyBoolCalculate),
69 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
70 m_attach_or_wait_reply(eLazyBoolCalculate),
71 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
72 m_supports_p (eLazyBoolCalculate),
73 m_supports_x (eLazyBoolCalculate),
74 m_avoid_g_packets (eLazyBoolCalculate),
75 m_supports_QSaveRegisterState (eLazyBoolCalculate),
76 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
77 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
78 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
79 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
80 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
81 m_supports_qProcessInfoPID (true),
82 m_supports_qfProcessInfo (true),
83 m_supports_qUserName (true),
84 m_supports_qGroupName (true),
85 m_supports_qThreadStopInfo (true),
91 m_supports_QEnvironment (true),
92 m_supports_QEnvironmentHexEncoded (true),
93 m_curr_pid (LLDB_INVALID_PROCESS_ID),
94 m_curr_tid (LLDB_INVALID_THREAD_ID),
95 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
96 m_num_supported_hardware_watchpoints (0),
97 m_async_mutex (Mutex::eMutexTypeRecursive),
98 m_async_packet_predicate (false),
100 m_async_result (PacketResult::Success),
103 m_interrupt_sent (false),
104 m_thread_id_to_used_usec_map (),
107 m_os_version_major (UINT32_MAX),
108 m_os_version_minor (UINT32_MAX),
109 m_os_version_update (UINT32_MAX),
114 m_gdb_server_version(UINT32_MAX),
115 m_default_packet_timeout (0),
116 m_max_packet_size (0)
120 //----------------------------------------------------------------------
122 //----------------------------------------------------------------------
123 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
130 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
132 ResetDiscoverableSettings();
134 // Start the read thread after we send the handshake ack since if we
135 // fail to send the handshake ack, there is no reason to continue...
138 // Wait for any responses that might have been queued up in the remote
139 // GDB server and flush them all
140 StringExtractorGDBRemote response;
141 PacketResult packet_result = PacketResult::Success;
142 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
143 while (packet_result == PacketResult::Success)
144 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
146 // The return value from QueryNoAckModeSupported() is true if the packet
147 // was sent and _any_ response (including UNIMPLEMENTED) was received),
148 // or false if no response was received. This quickly tells us if we have
149 // a live connection to a remote GDB server...
150 if (QueryNoAckModeSupported())
153 // Set above line to "#if 1" to test packet speed if remote GDB server
154 // supports the qSpeedTest packet...
155 TestPacketSpeed(10000);
162 error_ptr->SetErrorString("failed to get reply to handshake packet");
168 error_ptr->SetErrorString("failed to send the handshake ack");
174 GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
176 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
178 GetRemoteQSupported();
180 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
184 GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
186 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
188 GetRemoteQSupported();
190 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
194 GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
196 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
198 GetRemoteQSupported();
200 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
204 GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
206 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
208 GetRemoteQSupported();
210 return (m_supports_qXfer_auxv_read == eLazyBoolYes);
214 GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
216 if (m_max_packet_size == 0)
218 GetRemoteQSupported();
220 return m_max_packet_size;
224 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
226 if (m_supports_not_sending_acks == eLazyBoolCalculate)
229 m_supports_not_sending_acks = eLazyBoolNo;
231 // This is the first real packet that we'll send in a debug session and it may take a little
232 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
234 const uint32_t minimum_timeout = 6;
235 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
236 SetPacketTimeout (std::max (old_timeout, minimum_timeout));
238 StringExtractorGDBRemote response;
239 PacketResult packet_send_result = SendPacketAndWaitForResponse("QStartNoAckMode", response, false);
240 SetPacketTimeout (old_timeout);
242 if (packet_send_result == PacketResult::Success)
244 if (response.IsOKResponse())
247 m_supports_not_sending_acks = eLazyBoolYes;
256 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
258 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
260 m_supports_threads_in_stop_reply = eLazyBoolNo;
262 StringExtractorGDBRemote response;
263 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
265 if (response.IsOKResponse())
266 m_supports_threads_in_stop_reply = eLazyBoolYes;
272 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
274 if (m_attach_or_wait_reply == eLazyBoolCalculate)
276 m_attach_or_wait_reply = eLazyBoolNo;
278 StringExtractorGDBRemote response;
279 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
281 if (response.IsOKResponse())
282 m_attach_or_wait_reply = eLazyBoolYes;
285 if (m_attach_or_wait_reply == eLazyBoolYes)
292 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
294 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
296 m_prepare_for_reg_writing_reply = eLazyBoolNo;
298 StringExtractorGDBRemote response;
299 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
301 if (response.IsOKResponse())
302 m_prepare_for_reg_writing_reply = eLazyBoolYes;
305 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
313 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
315 m_supports_not_sending_acks = eLazyBoolCalculate;
316 m_supports_thread_suffix = eLazyBoolCalculate;
317 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
318 m_supports_vCont_c = eLazyBoolCalculate;
319 m_supports_vCont_C = eLazyBoolCalculate;
320 m_supports_vCont_s = eLazyBoolCalculate;
321 m_supports_vCont_S = eLazyBoolCalculate;
322 m_supports_p = eLazyBoolCalculate;
323 m_supports_x = eLazyBoolCalculate;
324 m_supports_QSaveRegisterState = eLazyBoolCalculate;
325 m_qHostInfo_is_valid = eLazyBoolCalculate;
326 m_curr_pid_is_valid = eLazyBoolCalculate;
327 m_qProcessInfo_is_valid = eLazyBoolCalculate;
328 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
329 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
330 m_supports_memory_region_info = eLazyBoolCalculate;
331 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
332 m_attach_or_wait_reply = eLazyBoolCalculate;
333 m_avoid_g_packets = eLazyBoolCalculate;
334 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
335 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
336 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
337 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
339 m_supports_qProcessInfoPID = true;
340 m_supports_qfProcessInfo = true;
341 m_supports_qUserName = true;
342 m_supports_qGroupName = true;
343 m_supports_qThreadStopInfo = true;
344 m_supports_z0 = true;
345 m_supports_z1 = true;
346 m_supports_z2 = true;
347 m_supports_z3 = true;
348 m_supports_z4 = true;
349 m_supports_QEnvironment = true;
350 m_supports_QEnvironmentHexEncoded = true;
353 m_process_arch.Clear();
354 m_os_version_major = UINT32_MAX;
355 m_os_version_minor = UINT32_MAX;
356 m_os_version_update = UINT32_MAX;
360 m_gdb_server_name.clear();
361 m_gdb_server_version = UINT32_MAX;
362 m_default_packet_timeout = 0;
364 m_max_packet_size = 0;
368 GDBRemoteCommunicationClient::GetRemoteQSupported ()
370 // Clear out any capabilities we expect to see in the qSupported response
371 m_supports_qXfer_auxv_read = eLazyBoolNo;
372 m_supports_qXfer_libraries_read = eLazyBoolNo;
373 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
374 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
375 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
377 StringExtractorGDBRemote response;
378 if (SendPacketAndWaitForResponse("qSupported",
380 /*send_async=*/false) == PacketResult::Success)
382 const char *response_cstr = response.GetStringRef().c_str();
383 if (::strstr (response_cstr, "qXfer:auxv:read+"))
384 m_supports_qXfer_auxv_read = eLazyBoolYes;
385 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
386 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
387 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
389 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
390 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
392 if (::strstr (response_cstr, "qXfer:libraries:read+"))
393 m_supports_qXfer_libraries_read = eLazyBoolYes;
395 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
398 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
399 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
400 if (m_max_packet_size == 0)
402 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
403 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
405 log->Printf ("Garbled PacketSize spec in qSupported response");
412 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
414 if (m_supports_thread_suffix == eLazyBoolCalculate)
416 StringExtractorGDBRemote response;
417 m_supports_thread_suffix = eLazyBoolNo;
418 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
420 if (response.IsOKResponse())
421 m_supports_thread_suffix = eLazyBoolYes;
424 return m_supports_thread_suffix;
427 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
429 if (m_supports_vCont_c == eLazyBoolCalculate)
431 StringExtractorGDBRemote response;
432 m_supports_vCont_any = eLazyBoolNo;
433 m_supports_vCont_all = eLazyBoolNo;
434 m_supports_vCont_c = eLazyBoolNo;
435 m_supports_vCont_C = eLazyBoolNo;
436 m_supports_vCont_s = eLazyBoolNo;
437 m_supports_vCont_S = eLazyBoolNo;
438 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
440 const char *response_cstr = response.GetStringRef().c_str();
441 if (::strstr (response_cstr, ";c"))
442 m_supports_vCont_c = eLazyBoolYes;
444 if (::strstr (response_cstr, ";C"))
445 m_supports_vCont_C = eLazyBoolYes;
447 if (::strstr (response_cstr, ";s"))
448 m_supports_vCont_s = eLazyBoolYes;
450 if (::strstr (response_cstr, ";S"))
451 m_supports_vCont_S = eLazyBoolYes;
453 if (m_supports_vCont_c == eLazyBoolYes &&
454 m_supports_vCont_C == eLazyBoolYes &&
455 m_supports_vCont_s == eLazyBoolYes &&
456 m_supports_vCont_S == eLazyBoolYes)
458 m_supports_vCont_all = eLazyBoolYes;
461 if (m_supports_vCont_c == eLazyBoolYes ||
462 m_supports_vCont_C == eLazyBoolYes ||
463 m_supports_vCont_s == eLazyBoolYes ||
464 m_supports_vCont_S == eLazyBoolYes)
466 m_supports_vCont_any = eLazyBoolYes;
473 case 'a': return m_supports_vCont_any;
474 case 'A': return m_supports_vCont_all;
475 case 'c': return m_supports_vCont_c;
476 case 'C': return m_supports_vCont_C;
477 case 's': return m_supports_vCont_s;
478 case 'S': return m_supports_vCont_S;
484 // Check if the target supports 'p' packet. It sends out a 'p'
485 // packet and checks the response. A normal packet will tell us
486 // that support is available.
488 // Takes a valid thread ID because p needs to apply to a thread.
490 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
492 if (m_supports_p == eLazyBoolCalculate)
494 StringExtractorGDBRemote response;
495 m_supports_p = eLazyBoolNo;
497 if (GetThreadSuffixSupported())
498 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
500 snprintf(packet, sizeof(packet), "p0");
502 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
504 if (response.IsNormalResponse())
505 m_supports_p = eLazyBoolYes;
512 GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
514 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
516 StringExtractorGDBRemote response;
517 m_supports_jThreadExtendedInfo = eLazyBoolNo;
518 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
520 if (response.IsOKResponse())
522 m_supports_jThreadExtendedInfo = eLazyBoolYes;
526 return m_supports_jThreadExtendedInfo;
530 GDBRemoteCommunicationClient::GetxPacketSupported ()
532 if (m_supports_x == eLazyBoolCalculate)
534 StringExtractorGDBRemote response;
535 m_supports_x = eLazyBoolNo;
537 snprintf (packet, sizeof (packet), "x0,0");
538 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
540 if (response.IsOKResponse())
541 m_supports_x = eLazyBoolYes;
547 GDBRemoteCommunicationClient::PacketResult
548 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
550 const char *payload_prefix,
551 std::string &response_string
554 Mutex::Locker locker;
555 if (!GetSequenceMutex(locker,
556 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
558 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
560 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
562 return PacketResult::ErrorNoSequenceLock;
565 response_string = "";
566 std::string payload_prefix_str(payload_prefix);
567 unsigned int response_size = 0x1000;
568 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
569 response_size = GetRemoteMaxPacketSize();
572 for (unsigned int offset = 0; true; offset += response_size)
574 StringExtractorGDBRemote this_response;
576 char sizeDescriptor[128];
577 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
578 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
580 /*send_async=*/false);
581 if (result != PacketResult::Success)
584 const std::string &this_string = this_response.GetStringRef();
586 // Check for m or l as first character; l seems to mean this is the last chunk
587 char first_char = *this_string.c_str();
588 if (first_char != 'm' && first_char != 'l')
590 return PacketResult::ErrorReplyInvalid;
592 // Concatenate the result so far (skipping 'm' or 'l')
593 response_string.append(this_string, 1, std::string::npos);
594 if (first_char == 'l')
596 return PacketResult::Success;
600 GDBRemoteCommunicationClient::PacketResult
601 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
604 StringExtractorGDBRemote &response,
608 return SendPacketAndWaitForResponse (payload,
614 GDBRemoteCommunicationClient::PacketResult
615 GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
616 size_t payload_length,
617 StringExtractorGDBRemote &response)
619 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
620 if (packet_result == PacketResult::Success)
621 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
622 return packet_result;
625 GDBRemoteCommunicationClient::PacketResult
626 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
629 size_t payload_length,
630 StringExtractorGDBRemote &response,
634 PacketResult packet_result = PacketResult::ErrorSendFailed;
635 Mutex::Locker locker;
636 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
637 if (GetSequenceMutex (locker))
639 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
647 Mutex::Locker async_locker (m_async_mutex);
648 m_async_packet.assign(payload, payload_length);
649 m_async_packet_predicate.SetValue (true, eBroadcastNever);
652 log->Printf ("async: async packet = %s", m_async_packet.c_str());
654 bool timed_out = false;
655 if (SendInterrupt(locker, 2, timed_out))
657 if (m_interrupt_sent)
659 m_interrupt_sent = false;
660 TimeValue timeout_time;
661 timeout_time = TimeValue::Now();
662 timeout_time.OffsetWithSeconds (m_packet_timeout);
665 log->Printf ("async: sent interrupt");
667 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
670 log->Printf ("async: got response");
672 // Swap the response buffer to avoid malloc and string copy
673 response.GetStringRef().swap (m_async_response.GetStringRef());
674 packet_result = m_async_result;
679 log->Printf ("async: timed out waiting for response");
682 // Make sure we wait until the continue packet has been sent again...
683 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
688 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
690 log->Printf ("async: async packet sent");
696 log->Printf ("async: timed out waiting for process to resume");
701 // We had a racy condition where we went to send the interrupt
702 // yet we were able to get the lock, so the process must have
705 log->Printf ("async: got lock without sending interrupt");
706 // Send the packet normally since we got the lock
707 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
713 log->Printf ("async: failed to interrupt");
719 log->Printf ("async: not running, async is ignored");
725 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
728 return packet_result;
731 static const char *end_delimiter = "--end--;";
732 static const int end_delimiter_len = 8;
735 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
736 ( ProcessGDBRemote *process,
737 StringExtractorGDBRemote& profileDataExtractor
740 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
741 std::stringstream final_output;
742 std::string name, value;
744 // Going to assuming thread_used_usec comes first, else bail out.
745 while (profileDataExtractor.GetNameColonValue(name, value))
747 if (name.compare("thread_used_id") == 0)
749 StringExtractor threadIDHexExtractor(value.c_str());
750 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
752 bool has_used_usec = false;
753 uint32_t curr_used_usec = 0;
754 std::string usec_name, usec_value;
755 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
756 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
758 if (usec_name.compare("thread_used_usec") == 0)
760 has_used_usec = true;
761 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
765 // We didn't find what we want, it is probably
766 // an older version. Bail out.
767 profileDataExtractor.SetFilePos(input_file_pos);
773 uint32_t prev_used_usec = 0;
774 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
775 if (iterator != m_thread_id_to_used_usec_map.end())
777 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
780 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
781 // A good first time record is one that runs for at least 0.25 sec
782 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
783 bool good_subsequent_time = (prev_used_usec > 0) &&
784 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
786 if (good_first_time || good_subsequent_time)
788 // We try to avoid doing too many index id reservation,
789 // resulting in fast increase of index ids.
791 final_output << name << ":";
792 int32_t index_id = process->AssignIndexIDToThread(thread_id);
793 final_output << index_id << ";";
795 final_output << usec_name << ":" << usec_value << ";";
799 // Skip past 'thread_used_name'.
800 std::string local_name, local_value;
801 profileDataExtractor.GetNameColonValue(local_name, local_value);
804 // Store current time as previous time so that they can be compared later.
805 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
809 // Bail out and use old string.
810 final_output << name << ":" << value << ";";
815 final_output << name << ":" << value << ";";
818 final_output << end_delimiter;
819 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
821 return final_output.str();
825 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
827 ProcessGDBRemote *process,
829 size_t packet_length,
830 StringExtractorGDBRemote &response
833 m_curr_tid = LLDB_INVALID_THREAD_ID;
834 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
836 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
838 Mutex::Locker locker(m_sequence_mutex);
839 StateType state = eStateRunning;
841 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
842 m_public_is_running.SetValue (true, eBroadcastNever);
843 // Set the starting continue packet into "continue_packet". This packet
844 // may change if we are interrupted and we continue after an async packet...
845 std::string continue_packet(payload, packet_length);
847 bool got_async_packet = false;
849 while (state == eStateRunning)
851 if (!got_async_packet)
854 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
855 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
856 state = eStateInvalid;
858 m_interrupt_sent = false;
860 m_private_is_running.SetValue (true, eBroadcastAlways);
863 got_async_packet = false;
866 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
868 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
870 if (response.Empty())
871 state = eStateInvalid;
874 const char stop_type = response.GetChar();
876 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
882 if (process->GetStopID() == 0)
884 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
886 lldb::pid_t pid = GetCurrentProcessID ();
887 if (pid != LLDB_INVALID_PROCESS_ID)
888 process->SetID (pid);
890 process->BuildDynamicRegisterInfo (true);
893 // Privately notify any internal threads that we have stopped
894 // in case we wanted to interrupt our process, yet we might
895 // send a packet and continue without returning control to the
897 m_private_is_running.SetValue (false, eBroadcastAlways);
899 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
901 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
902 if (continue_after_async || m_interrupt_sent)
904 // We sent an interrupt packet to stop the inferior process
905 // for an async signal or to send an async packet while running
906 // but we might have been single stepping and received the
907 // stop packet for the step instead of for the interrupt packet.
908 // Typically when an interrupt is sent a SIGINT or SIGSTOP
909 // is used, so if we get anything else, we need to try and
910 // get another stop reply packet that may have been sent
911 // due to sending the interrupt when the target is stopped
912 // which will just re-send a copy of the last stop reply
913 // packet. If we don't do this, then the reply for our
914 // async packet will be the repeat stop reply packet and cause
915 // a lot of trouble for us!
916 if (signo != SIGINT && signo != SIGSTOP)
918 continue_after_async = false;
920 // We didn't get a a SIGINT or SIGSTOP, so try for a
921 // very brief time (1 ms) to get another stop reply
922 // packet to make sure it doesn't get in the way
923 StringExtractorGDBRemote extra_stop_reply_packet;
924 uint32_t timeout_usec = 1000;
925 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
927 switch (extra_stop_reply_packet.GetChar())
931 // We did get an extra stop reply, which means
932 // our interrupt didn't stop the target so we
933 // shouldn't continue after the async signal
934 // or packet is sent...
935 continue_after_async = false;
942 if (m_async_signal != -1)
945 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
947 // Save off the async signal we are supposed to send
948 const int async_signal = m_async_signal;
949 // Clear the async signal member so we don't end up
950 // sending the signal multiple times...
952 // Check which signal we stopped with
953 if (signo == async_signal)
956 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
958 // We already stopped with a signal that we wanted
959 // to stop with, so we are done
963 // We stopped with a different signal that the one
964 // we wanted to stop with, so now we must resume
965 // with the signal we want
966 char signal_packet[32];
967 int signal_packet_len = 0;
968 signal_packet_len = ::snprintf (signal_packet,
969 sizeof (signal_packet),
974 log->Printf ("async: stopped with signal %s, resume with %s",
975 Host::GetSignalAsCString (signo),
976 Host::GetSignalAsCString (async_signal));
978 // Set the continue packet to resume even if the
979 // interrupt didn't cause our stop (ignore continue_after_async)
980 continue_packet.assign(signal_packet, signal_packet_len);
984 else if (m_async_packet_predicate.GetValue())
986 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
988 // We are supposed to send an asynchronous packet while
990 m_async_response.Clear();
991 if (m_async_packet.empty())
993 m_async_result = PacketResult::ErrorSendFailed;
995 packet_log->Printf ("async: error: empty async packet");
1001 packet_log->Printf ("async: sending packet");
1003 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1004 m_async_packet.size(),
1008 // Let the other thread that was trying to send the async
1009 // packet know that the packet has been sent and response is
1011 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1014 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
1016 // Set the continue packet to resume if our interrupt
1017 // for the async packet did cause the stop
1018 if (continue_after_async)
1020 // Reverting this for now as it is causing deadlocks
1021 // in programs (<rdar://problem/11529853>). In the future
1022 // we should check our thread list and "do the right thing"
1023 // for new threads that show up while we stop and run async
1024 // packets. Setting the packet to 'c' to continue all threads
1025 // is the right thing to do 99.99% of the time because if a
1026 // thread was single stepping, and we sent an interrupt, we
1027 // will notice above that we didn't stop due to an interrupt
1028 // but stopped due to stepping and we would _not_ continue.
1029 continue_packet.assign (1, 'c');
1033 // Stop with signal and thread info
1034 state = eStateStopped;
1041 state = eStateExited;
1047 got_async_packet = true;
1048 std::string inferior_stdout;
1049 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1051 while ((ch = response.GetHexU8()) != '\0')
1052 inferior_stdout.append(1, ch);
1053 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1058 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1060 got_async_packet = true;
1061 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1062 if (m_partial_profile_data.length() > 0)
1064 m_partial_profile_data.append(input);
1065 input = m_partial_profile_data;
1066 m_partial_profile_data.clear();
1069 size_t found, pos = 0, len = input.length();
1070 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1072 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
1073 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1074 process->BroadcastAsyncProfileData (profile_data);
1076 pos = found + end_delimiter_len;
1081 // Last incomplete chunk.
1082 m_partial_profile_data = input.substr(pos);
1089 state = eStateInvalid;
1094 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1095 state = eStateInvalid;
1103 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1104 state = eStateInvalid;
1108 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1109 response.SetFilePos(0);
1110 m_private_is_running.SetValue (false, eBroadcastAlways);
1111 m_public_is_running.SetValue (false, eBroadcastAlways);
1116 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1118 Mutex::Locker async_locker (m_async_mutex);
1119 m_async_signal = signo;
1120 bool timed_out = false;
1121 Mutex::Locker locker;
1122 if (SendInterrupt (locker, 1, timed_out))
1124 m_async_signal = -1;
1128 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
1129 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1130 // (the expected result), then it will send the halt packet. If it does succeed
1131 // then the caller that requested the interrupt will want to keep the sequence
1132 // locked down so that no one else can send packets while the caller has control.
1133 // This function usually gets called when we are running and need to stop the
1134 // target. It can also be used when we are running and we need to do something
1135 // else (like read/write memory), so we need to interrupt the running process
1136 // (gdb remote protocol requires this), and do what we need to do, then resume.
1139 GDBRemoteCommunicationClient::SendInterrupt
1141 Mutex::Locker& locker,
1142 uint32_t seconds_to_wait_for_stop,
1147 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
1151 // Only send an interrupt if our debugserver is running...
1152 if (GetSequenceMutex (locker))
1155 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1159 // Someone has the mutex locked waiting for a response or for the
1160 // inferior to stop, so send the interrupt on the down low...
1161 char ctrl_c = '\x03';
1162 ConnectionStatus status = eConnectionStatusSuccess;
1163 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
1165 log->PutCString("send packet: \\x03");
1166 if (bytes_written > 0)
1168 m_interrupt_sent = true;
1169 if (seconds_to_wait_for_stop)
1172 if (seconds_to_wait_for_stop)
1174 timeout = TimeValue::Now();
1175 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1177 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1180 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
1186 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
1192 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
1199 log->Printf ("SendInterrupt () - failed to write interrupt");
1207 log->Printf ("SendInterrupt () - not running");
1213 GDBRemoteCommunicationClient::GetCurrentProcessID ()
1215 if (m_curr_pid_is_valid == eLazyBoolYes)
1218 // First try to retrieve the pid via the qProcessInfo request.
1219 GetCurrentProcessInfo ();
1220 if (m_curr_pid_is_valid == eLazyBoolYes)
1222 // We really got it.
1227 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1228 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1229 // The gdb remote protocol documents $qC as returning the thread id, which newer
1230 // debugserver and lldb-gdbserver stubs return correctly.
1231 StringExtractorGDBRemote response;
1232 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
1234 if (response.GetChar() == 'Q')
1236 if (response.GetChar() == 'C')
1238 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1239 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
1241 m_curr_pid_is_valid = eLazyBoolYes;
1249 return LLDB_INVALID_PROCESS_ID;
1253 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1256 StringExtractorGDBRemote response;
1257 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
1259 if (response.IsOKResponse())
1261 if (response.GetChar() == 'E')
1263 // A string the describes what failed when launching...
1264 error_str = response.GetStringRef().substr(1);
1268 error_str.assign ("unknown error occurred launching process");
1273 error_str.assign ("timed out waiting for app to launch");
1279 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
1281 // Since we don't get the send argv0 separate from the executable path, we need to
1282 // make sure to use the actual executable path found in the launch_info...
1283 std::vector<const char *> argv;
1284 FileSpec exe_file = launch_info.GetExecutableFile();
1285 std::string exe_path;
1286 const char *arg = NULL;
1287 const Args &launch_args = launch_info.GetArguments();
1289 exe_path = exe_file.GetPath();
1292 arg = launch_args.GetArgumentAtIndex(0);
1296 if (!exe_path.empty())
1298 argv.push_back(exe_path.c_str());
1299 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1302 argv.push_back(arg);
1307 StreamString packet;
1308 packet.PutChar('A');
1309 for (size_t i = 0, n = argv.size(); i < n; ++i)
1312 const int arg_len = strlen(arg);
1314 packet.PutChar(',');
1315 packet.Printf("%i,%i,", arg_len * 2, (int)i);
1316 packet.PutBytesAsRawHex8 (arg, arg_len);
1319 StringExtractorGDBRemote response;
1320 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1322 if (response.IsOKResponse())
1324 uint8_t error = response.GetError();
1333 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1335 if (name_equal_value && name_equal_value[0])
1337 StreamString packet;
1338 bool send_hex_encoding = false;
1339 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
1347 send_hex_encoding = true;
1355 // We have non printable characters, lets hex encode this...
1356 send_hex_encoding = true;
1360 StringExtractorGDBRemote response;
1361 if (send_hex_encoding)
1363 if (m_supports_QEnvironmentHexEncoded)
1365 packet.PutCString("QEnvironmentHexEncoded:");
1366 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1367 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1369 if (response.IsOKResponse())
1371 uint8_t error = response.GetError();
1374 if (response.IsUnsupportedResponse())
1375 m_supports_QEnvironmentHexEncoded = false;
1380 else if (m_supports_QEnvironment)
1382 packet.Printf("QEnvironment:%s", name_equal_value);
1383 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1385 if (response.IsOKResponse())
1387 uint8_t error = response.GetError();
1390 if (response.IsUnsupportedResponse())
1391 m_supports_QEnvironment = false;
1399 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1401 if (arch && arch[0])
1403 StreamString packet;
1404 packet.Printf("QLaunchArch:%s", arch);
1405 StringExtractorGDBRemote response;
1406 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1408 if (response.IsOKResponse())
1410 uint8_t error = response.GetError();
1419 GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1421 if (data && *data != '\0')
1423 StreamString packet;
1424 packet.Printf("QSetProcessEvent:%s", data);
1425 StringExtractorGDBRemote response;
1426 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1428 if (response.IsOKResponse())
1431 *was_supported = true;
1434 else if (response.IsUnsupportedResponse())
1437 *was_supported = false;
1442 uint8_t error = response.GetError();
1444 *was_supported = true;
1454 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1460 if (m_os_version_major != UINT32_MAX)
1462 major = m_os_version_major;
1463 minor = m_os_version_minor;
1464 update = m_os_version_update;
1472 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1476 if (!m_os_build.empty())
1488 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1492 if (!m_os_kernel.empty())
1503 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1507 if (!m_hostname.empty())
1518 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1525 const lldb_private::ArchSpec &
1526 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1528 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1529 GetCurrentProcessInfo ();
1530 return m_process_arch;
1534 GDBRemoteCommunicationClient::GetGDBServerVersion()
1536 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1538 m_gdb_server_name.clear();
1539 m_gdb_server_version = 0;
1540 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1542 StringExtractorGDBRemote response;
1543 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1545 if (response.IsNormalResponse())
1549 bool success = false;
1550 while (response.GetNameColonValue(name, value))
1552 if (name.compare("name") == 0)
1555 m_gdb_server_name.swap(value);
1557 else if (name.compare("version") == 0)
1559 size_t dot_pos = value.find('.');
1560 if (dot_pos != std::string::npos)
1561 value[dot_pos] = '\0';
1562 const uint32_t version = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
1563 if (version != UINT32_MAX)
1566 m_gdb_server_version = version;
1571 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1575 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1579 GDBRemoteCommunicationClient::GetGDBServerProgramName()
1581 if (GetGDBServerVersion())
1583 if (!m_gdb_server_name.empty())
1584 return m_gdb_server_name.c_str();
1590 GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1592 if (GetGDBServerVersion())
1593 return m_gdb_server_version;
1598 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1600 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1602 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1604 m_qHostInfo_is_valid = eLazyBoolNo;
1605 StringExtractorGDBRemote response;
1606 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
1608 if (response.IsNormalResponse())
1612 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1614 std::string arch_name;
1615 std::string os_name;
1616 std::string vendor_name;
1618 std::string distribution_id;
1619 uint32_t pointer_byte_size = 0;
1620 StringExtractor extractor;
1621 ByteOrder byte_order = eByteOrderInvalid;
1622 uint32_t num_keys_decoded = 0;
1623 while (response.GetNameColonValue(name, value))
1625 if (name.compare("cputype") == 0)
1627 // exception type in big endian hex
1628 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1629 if (cpu != LLDB_INVALID_CPUTYPE)
1632 else if (name.compare("cpusubtype") == 0)
1634 // exception count in big endian hex
1635 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1639 else if (name.compare("arch") == 0)
1641 arch_name.swap (value);
1644 else if (name.compare("triple") == 0)
1646 extractor.GetStringRef ().swap (value);
1647 extractor.SetFilePos(0);
1648 extractor.GetHexByteString (triple);
1651 else if (name.compare ("distribution_id") == 0)
1653 extractor.GetStringRef ().swap (value);
1654 extractor.SetFilePos (0);
1655 extractor.GetHexByteString (distribution_id);
1658 else if (name.compare("os_build") == 0)
1660 extractor.GetStringRef().swap(value);
1661 extractor.SetFilePos(0);
1662 extractor.GetHexByteString (m_os_build);
1665 else if (name.compare("hostname") == 0)
1667 extractor.GetStringRef().swap(value);
1668 extractor.SetFilePos(0);
1669 extractor.GetHexByteString (m_hostname);
1672 else if (name.compare("os_kernel") == 0)
1674 extractor.GetStringRef().swap(value);
1675 extractor.SetFilePos(0);
1676 extractor.GetHexByteString (m_os_kernel);
1679 else if (name.compare("ostype") == 0)
1681 os_name.swap (value);
1684 else if (name.compare("vendor") == 0)
1686 vendor_name.swap(value);
1689 else if (name.compare("endian") == 0)
1692 if (value.compare("little") == 0)
1693 byte_order = eByteOrderLittle;
1694 else if (value.compare("big") == 0)
1695 byte_order = eByteOrderBig;
1696 else if (value.compare("pdp") == 0)
1697 byte_order = eByteOrderPDP;
1701 else if (name.compare("ptrsize") == 0)
1703 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1704 if (pointer_byte_size != 0)
1707 else if (name.compare("os_version") == 0)
1709 Args::StringToVersion (value.c_str(),
1712 m_os_version_update);
1713 if (m_os_version_major != UINT32_MAX)
1716 else if (name.compare("watchpoint_exceptions_received") == 0)
1719 if (strcmp(value.c_str(),"before") == 0)
1720 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1721 else if (strcmp(value.c_str(),"after") == 0)
1722 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1726 else if (name.compare("default_packet_timeout") == 0)
1728 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1729 if (m_default_packet_timeout > 0)
1731 SetPacketTimeout(m_default_packet_timeout);
1738 if (num_keys_decoded > 0)
1739 m_qHostInfo_is_valid = eLazyBoolYes;
1743 if (arch_name.empty())
1745 if (cpu != LLDB_INVALID_CPUTYPE)
1747 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1748 if (pointer_byte_size)
1750 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1752 if (byte_order != eByteOrderInvalid)
1754 assert (byte_order == m_host_arch.GetByteOrder());
1757 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1759 switch (m_host_arch.GetMachine())
1761 case llvm::Triple::aarch64:
1762 case llvm::Triple::arm:
1763 case llvm::Triple::thumb:
1771 if (!vendor_name.empty())
1772 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1773 if (!os_name.empty())
1774 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1781 triple += arch_name;
1782 if (!vendor_name.empty() || !os_name.empty())
1785 if (vendor_name.empty())
1786 triple += "unknown";
1788 triple += vendor_name;
1790 if (os_name.empty())
1791 triple += "unknown";
1795 m_host_arch.SetTriple (triple.c_str());
1797 llvm::Triple &host_triple = m_host_arch.GetTriple();
1798 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1800 switch (m_host_arch.GetMachine())
1802 case llvm::Triple::aarch64:
1803 case llvm::Triple::arm:
1804 case llvm::Triple::thumb:
1805 host_triple.setOS(llvm::Triple::IOS);
1808 host_triple.setOS(llvm::Triple::MacOSX);
1812 if (pointer_byte_size)
1814 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1816 if (byte_order != eByteOrderInvalid)
1818 assert (byte_order == m_host_arch.GetByteOrder());
1825 m_host_arch.SetTriple (triple.c_str());
1826 if (pointer_byte_size)
1828 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1830 if (byte_order != eByteOrderInvalid)
1832 assert (byte_order == m_host_arch.GetByteOrder());
1836 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 ());
1838 if (!distribution_id.empty ())
1839 m_host_arch.SetDistributionId (distribution_id.c_str ());
1843 return m_qHostInfo_is_valid == eLazyBoolYes;
1847 GDBRemoteCommunicationClient::SendAttach
1850 StringExtractorGDBRemote& response
1853 if (pid != LLDB_INVALID_PROCESS_ID)
1856 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1857 assert (packet_len < (int)sizeof(packet));
1858 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1860 if (response.IsErrorResponse())
1861 return response.GetError();
1868 const lldb_private::ArchSpec &
1869 GDBRemoteCommunicationClient::GetHostArchitecture ()
1871 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1877 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1879 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1881 return m_default_packet_timeout;
1885 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1887 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1889 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1891 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1893 permissions & lldb::ePermissionsReadable ? "r" : "",
1894 permissions & lldb::ePermissionsWritable ? "w" : "",
1895 permissions & lldb::ePermissionsExecutable ? "x" : "");
1896 assert (packet_len < (int)sizeof(packet));
1897 StringExtractorGDBRemote response;
1898 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1900 if (response.IsUnsupportedResponse())
1901 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1902 else if (!response.IsErrorResponse())
1903 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1907 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1910 return LLDB_INVALID_ADDRESS;
1914 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1916 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1918 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1920 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1921 assert (packet_len < (int)sizeof(packet));
1922 StringExtractorGDBRemote response;
1923 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1925 if (response.IsUnsupportedResponse())
1926 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1927 else if (response.IsOKResponse())
1932 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1939 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1945 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1948 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1949 assert (packet_len < (int)sizeof(packet));
1950 StringExtractorGDBRemote response;
1951 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1953 m_supports_detach_stay_stopped = eLazyBoolYes;
1957 m_supports_detach_stay_stopped = eLazyBoolNo;
1961 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1963 error.SetErrorString("Stays stopped not supported by this target.");
1968 StringExtractorGDBRemote response;
1969 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
1970 if (packet_result != PacketResult::Success)
1971 error.SetErrorString ("Sending extended disconnect packet failed.");
1976 StringExtractorGDBRemote response;
1977 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
1978 if (packet_result != PacketResult::Success)
1979 error.SetErrorString ("Sending disconnect packet failed.");
1985 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1986 lldb_private::MemoryRegionInfo ®ion_info)
1989 region_info.Clear();
1991 if (m_supports_memory_region_info != eLazyBoolNo)
1993 m_supports_memory_region_info = eLazyBoolYes;
1995 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1996 assert (packet_len < (int)sizeof(packet));
1997 StringExtractorGDBRemote response;
1998 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2003 bool success = true;
2004 bool saw_permissions = false;
2005 while (success && response.GetNameColonValue(name, value))
2007 if (name.compare ("start") == 0)
2009 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
2011 region_info.GetRange().SetRangeBase(addr_value);
2013 else if (name.compare ("size") == 0)
2015 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
2017 region_info.GetRange().SetByteSize (addr_value);
2019 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
2021 saw_permissions = true;
2022 if (region_info.GetRange().Contains (addr))
2024 if (value.find('r') != std::string::npos)
2025 region_info.SetReadable (MemoryRegionInfo::eYes);
2027 region_info.SetReadable (MemoryRegionInfo::eNo);
2029 if (value.find('w') != std::string::npos)
2030 region_info.SetWritable (MemoryRegionInfo::eYes);
2032 region_info.SetWritable (MemoryRegionInfo::eNo);
2034 if (value.find('x') != std::string::npos)
2035 region_info.SetExecutable (MemoryRegionInfo::eYes);
2037 region_info.SetExecutable (MemoryRegionInfo::eNo);
2041 // The reported region does not contain this address -- we're looking at an unmapped page
2042 region_info.SetReadable (MemoryRegionInfo::eNo);
2043 region_info.SetWritable (MemoryRegionInfo::eNo);
2044 region_info.SetExecutable (MemoryRegionInfo::eNo);
2047 else if (name.compare ("error") == 0)
2049 StringExtractorGDBRemote name_extractor;
2050 // Swap "value" over into "name_extractor"
2051 name_extractor.GetStringRef().swap(value);
2052 // Now convert the HEX bytes into a string value
2053 name_extractor.GetHexByteString (value);
2054 error.SetErrorString(value.c_str());
2058 // We got a valid address range back but no permissions -- which means this is an unmapped page
2059 if (region_info.GetRange().IsValid() && saw_permissions == false)
2061 region_info.SetReadable (MemoryRegionInfo::eNo);
2062 region_info.SetWritable (MemoryRegionInfo::eNo);
2063 region_info.SetExecutable (MemoryRegionInfo::eNo);
2068 m_supports_memory_region_info = eLazyBoolNo;
2072 if (m_supports_memory_region_info == eLazyBoolNo)
2074 error.SetErrorString("qMemoryRegionInfo is not supported");
2077 region_info.Clear();
2083 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2087 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2089 num = m_num_supported_hardware_watchpoints;
2093 // Set num to 0 first.
2095 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2098 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
2099 assert (packet_len < (int)sizeof(packet));
2100 StringExtractorGDBRemote response;
2101 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2103 m_supports_watchpoint_support_info = eLazyBoolYes;
2106 while (response.GetNameColonValue(name, value))
2108 if (name.compare ("num") == 0)
2110 num = Args::StringToUInt32(value.c_str(), 0, 0);
2111 m_num_supported_hardware_watchpoints = num;
2117 m_supports_watchpoint_support_info = eLazyBoolNo;
2121 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2123 error.SetErrorString("qWatchpointSupportInfo is not supported");
2130 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2132 Error error(GetWatchpointSupportInfo(num));
2133 if (error.Success())
2134 error = GetWatchpointsTriggerAfterInstruction(after);
2139 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2143 // we assume watchpoints will happen after running the relevant opcode
2144 // and we only want to override this behavior if we have explicitly
2145 // received a qHostInfo telling us otherwise
2146 if (m_qHostInfo_is_valid != eLazyBoolYes)
2149 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2154 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2156 if (path && path[0])
2158 StreamString packet;
2159 packet.PutCString("QSetSTDIN:");
2160 packet.PutBytesAsRawHex8(path, strlen(path));
2162 StringExtractorGDBRemote response;
2163 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2165 if (response.IsOKResponse())
2167 uint8_t error = response.GetError();
2176 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2178 if (path && path[0])
2180 StreamString packet;
2181 packet.PutCString("QSetSTDOUT:");
2182 packet.PutBytesAsRawHex8(path, strlen(path));
2184 StringExtractorGDBRemote response;
2185 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2187 if (response.IsOKResponse())
2189 uint8_t error = response.GetError();
2198 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2200 if (path && path[0])
2202 StreamString packet;
2203 packet.PutCString("QSetSTDERR:");
2204 packet.PutBytesAsRawHex8(path, strlen(path));
2206 StringExtractorGDBRemote response;
2207 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2209 if (response.IsOKResponse())
2211 uint8_t error = response.GetError();
2220 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2222 StringExtractorGDBRemote response;
2223 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2225 if (response.IsUnsupportedResponse())
2227 if (response.IsErrorResponse())
2229 response.GetHexByteString (cwd);
2230 return !cwd.empty();
2236 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2238 if (path && path[0])
2240 StreamString packet;
2241 packet.PutCString("QSetWorkingDir:");
2242 packet.PutBytesAsRawHex8(path, strlen(path));
2244 StringExtractorGDBRemote response;
2245 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2247 if (response.IsOKResponse())
2249 uint8_t error = response.GetError();
2258 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2261 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2262 assert (packet_len < (int)sizeof(packet));
2263 StringExtractorGDBRemote response;
2264 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2266 if (response.IsOKResponse())
2268 uint8_t error = response.GetError();
2276 GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2279 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2280 assert (packet_len < (int)sizeof(packet));
2281 StringExtractorGDBRemote response;
2282 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2284 if (response.IsOKResponse())
2286 uint8_t error = response.GetError();
2295 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2297 if (response.IsNormalResponse())
2301 StringExtractor extractor;
2303 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2306 std::string os_type;
2308 while (response.GetNameColonValue(name, value))
2310 if (name.compare("pid") == 0)
2312 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2314 else if (name.compare("ppid") == 0)
2316 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2318 else if (name.compare("uid") == 0)
2320 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2322 else if (name.compare("euid") == 0)
2324 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2326 else if (name.compare("gid") == 0)
2328 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2330 else if (name.compare("egid") == 0)
2332 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2334 else if (name.compare("triple") == 0)
2336 StringExtractor extractor;
2337 extractor.GetStringRef().swap(value);
2338 extractor.SetFilePos(0);
2339 extractor.GetHexByteString (value);
2340 process_info.GetArchitecture ().SetTriple (value.c_str());
2342 else if (name.compare("name") == 0)
2344 StringExtractor extractor;
2345 // The process name from ASCII hex bytes since we can't
2346 // control the characters in a process name
2347 extractor.GetStringRef().swap(value);
2348 extractor.SetFilePos(0);
2349 extractor.GetHexByteString (value);
2350 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2352 else if (name.compare("cputype") == 0)
2354 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2356 else if (name.compare("cpusubtype") == 0)
2358 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2360 else if (name.compare("vendor") == 0)
2364 else if (name.compare("ostype") == 0)
2370 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2372 if (vendor == "apple")
2374 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2375 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2376 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2380 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2387 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2389 process_info.Clear();
2391 if (m_supports_qProcessInfoPID)
2394 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2395 assert (packet_len < (int)sizeof(packet));
2396 StringExtractorGDBRemote response;
2397 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2399 return DecodeProcessInfoResponse (response, process_info);
2403 m_supports_qProcessInfoPID = false;
2411 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2413 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2415 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2417 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2422 StringExtractorGDBRemote response;
2423 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2425 if (response.IsNormalResponse())
2429 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2431 std::string arch_name;
2432 std::string os_name;
2433 std::string vendor_name;
2435 uint32_t pointer_byte_size = 0;
2436 StringExtractor extractor;
2437 ByteOrder byte_order = eByteOrderInvalid;
2438 uint32_t num_keys_decoded = 0;
2439 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2440 while (response.GetNameColonValue(name, value))
2442 if (name.compare("cputype") == 0)
2444 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2445 if (cpu != LLDB_INVALID_CPUTYPE)
2448 else if (name.compare("cpusubtype") == 0)
2450 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2454 else if (name.compare("triple") == 0)
2456 StringExtractor extractor;
2457 extractor.GetStringRef().swap(value);
2458 extractor.SetFilePos(0);
2459 extractor.GetHexByteString (triple);
2462 else if (name.compare("ostype") == 0)
2464 os_name.swap (value);
2467 else if (name.compare("vendor") == 0)
2469 vendor_name.swap(value);
2472 else if (name.compare("endian") == 0)
2475 if (value.compare("little") == 0)
2476 byte_order = eByteOrderLittle;
2477 else if (value.compare("big") == 0)
2478 byte_order = eByteOrderBig;
2479 else if (value.compare("pdp") == 0)
2480 byte_order = eByteOrderPDP;
2484 else if (name.compare("ptrsize") == 0)
2486 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2487 if (pointer_byte_size != 0)
2490 else if (name.compare("pid") == 0)
2492 pid = Args::StringToUInt64(value.c_str(), 0, 16);
2493 if (pid != LLDB_INVALID_PROCESS_ID)
2497 if (num_keys_decoded > 0)
2498 m_qProcessInfo_is_valid = eLazyBoolYes;
2499 if (pid != LLDB_INVALID_PROCESS_ID)
2501 m_curr_pid_is_valid = eLazyBoolYes;
2505 // Set the ArchSpec from the triple if we have it.
2506 if (!triple.empty ())
2508 m_process_arch.SetTriple (triple.c_str ());
2509 if (pointer_byte_size)
2511 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2514 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2516 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2518 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2519 switch (triple.getObjectFormat()) {
2520 case llvm::Triple::MachO:
2521 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2523 case llvm::Triple::ELF:
2524 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2526 case llvm::Triple::COFF:
2527 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2529 case llvm::Triple::UnknownObjectFormat:
2531 log->Printf("error: failed to determine target architecture");
2535 if (pointer_byte_size)
2537 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2539 if (byte_order != eByteOrderInvalid)
2541 assert (byte_order == m_process_arch.GetByteOrder());
2543 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2544 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
2545 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2546 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2553 m_qProcessInfo_is_valid = eLazyBoolNo;
2561 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2562 ProcessInstanceInfoList &process_infos)
2564 process_infos.Clear();
2566 if (m_supports_qfProcessInfo)
2568 StreamString packet;
2569 packet.PutCString ("qfProcessInfo");
2570 if (!match_info.MatchAllProcesses())
2572 packet.PutChar (':');
2573 const char *name = match_info.GetProcessInfo().GetName();
2574 bool has_name_match = false;
2575 if (name && name[0])
2577 has_name_match = true;
2578 NameMatchType name_match_type = match_info.GetNameMatchType();
2579 switch (name_match_type)
2581 case eNameMatchIgnore:
2582 has_name_match = false;
2585 case eNameMatchEquals:
2586 packet.PutCString ("name_match:equals;");
2589 case eNameMatchContains:
2590 packet.PutCString ("name_match:contains;");
2593 case eNameMatchStartsWith:
2594 packet.PutCString ("name_match:starts_with;");
2597 case eNameMatchEndsWith:
2598 packet.PutCString ("name_match:ends_with;");
2601 case eNameMatchRegularExpression:
2602 packet.PutCString ("name_match:regex;");
2607 packet.PutCString ("name:");
2608 packet.PutBytesAsRawHex8(name, ::strlen(name));
2609 packet.PutChar (';');
2613 if (match_info.GetProcessInfo().ProcessIDIsValid())
2614 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2615 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2616 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2617 if (match_info.GetProcessInfo().UserIDIsValid())
2618 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2619 if (match_info.GetProcessInfo().GroupIDIsValid())
2620 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2621 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2622 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2623 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2624 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2625 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2626 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2627 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2629 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2630 const llvm::Triple &triple = match_arch.GetTriple();
2631 packet.PutCString("triple:");
2632 packet.PutCString(triple.getTriple().c_str());
2633 packet.PutChar (';');
2636 StringExtractorGDBRemote response;
2637 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2641 ProcessInstanceInfo process_info;
2642 if (!DecodeProcessInfoResponse (response, process_info))
2644 process_infos.Append(process_info);
2645 response.GetStringRef().clear();
2646 response.SetFilePos(0);
2647 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2651 m_supports_qfProcessInfo = false;
2655 return process_infos.GetSize();
2660 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2662 if (m_supports_qUserName)
2665 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2666 assert (packet_len < (int)sizeof(packet));
2667 StringExtractorGDBRemote response;
2668 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2670 if (response.IsNormalResponse())
2672 // Make sure we parsed the right number of characters. The response is
2673 // the hex encoded user name and should make up the entire packet.
2674 // If there are any non-hex ASCII bytes, the length won't match below..
2675 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2681 m_supports_qUserName = false;
2690 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2692 if (m_supports_qGroupName)
2695 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2696 assert (packet_len < (int)sizeof(packet));
2697 StringExtractorGDBRemote response;
2698 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2700 if (response.IsNormalResponse())
2702 // Make sure we parsed the right number of characters. The response is
2703 // the hex encoded group name and should make up the entire packet.
2704 // If there are any non-hex ASCII bytes, the length won't match below..
2705 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2711 m_supports_qGroupName = false;
2719 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2722 TimeValue start_time, end_time;
2723 uint64_t total_time_nsec;
2724 if (SendSpeedTestPacket (0, 0))
2726 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2727 static uint32_t g_recv_sizes[] = { 0, 64, 128, 512, 1024 }; //, 4*1024, 8*1024, 16*1024, 32*1024, 48*1024, 64*1024, 96*1024, 128*1024 };
2728 const size_t k_num_send_sizes = llvm::array_lengthof(g_send_sizes);
2729 const size_t k_num_recv_sizes = llvm::array_lengthof(g_recv_sizes);
2730 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2731 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
2733 const uint32_t send_size = g_send_sizes[send_idx];
2734 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
2736 const uint32_t recv_size = g_recv_sizes[recv_idx];
2737 StreamString packet;
2738 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2739 uint32_t bytes_left = send_size;
2740 while (bytes_left > 0)
2742 if (bytes_left >= 26)
2744 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2749 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2754 start_time = TimeValue::Now();
2757 for (i=0; i<num_packets; ++i)
2759 StringExtractorGDBRemote response;
2760 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2765 uint32_t bytes_read = 0;
2766 while (bytes_read < k_recv_amount)
2768 StringExtractorGDBRemote response;
2769 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2770 bytes_read += recv_size;
2773 end_time = TimeValue::Now();
2774 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2777 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2778 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2782 total_time_nsec / TimeValue::NanoSecPerSec,
2783 total_time_nsec % TimeValue::NanoSecPerSec,
2784 packets_per_second);
2788 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2789 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2793 total_time_nsec / TimeValue::NanoSecPerSec,
2794 total_time_nsec % TimeValue::NanoSecPerSec,
2803 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2805 StreamString packet;
2806 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2807 uint32_t bytes_left = send_size;
2808 while (bytes_left > 0)
2810 if (bytes_left >= 26)
2812 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2817 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2822 StringExtractorGDBRemote response;
2823 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
2827 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
2829 pid = LLDB_INVALID_PROCESS_ID;
2830 StringExtractorGDBRemote response;
2831 StreamString stream;
2832 stream.PutCString("qLaunchGDBServer;");
2833 std::string hostname;
2834 if (remote_accept_hostname && remote_accept_hostname[0])
2835 hostname = remote_accept_hostname;
2838 if (HostInfo::GetHostname(hostname))
2840 // Make the GDB server we launch only accept connections from this host
2841 stream.Printf("host:%s;", hostname.c_str());
2845 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2846 stream.Printf("host:*;");
2849 const char *packet = stream.GetData();
2850 int packet_len = stream.GetSize();
2852 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2857 while (response.GetNameColonValue(name, value))
2859 if (name.compare("port") == 0)
2860 port = Args::StringToUInt32(value.c_str(), 0, 0);
2861 else if (name.compare("pid") == 0)
2862 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2870 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2872 StreamString stream;
2873 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2874 const char *packet = stream.GetData();
2875 int packet_len = stream.GetSize();
2877 StringExtractorGDBRemote response;
2878 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2880 if (response.IsOKResponse())
2887 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2889 if (m_curr_tid == tid)
2894 if (tid == UINT64_MAX)
2895 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2897 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2898 assert (packet_len + 1 < (int)sizeof(packet));
2899 StringExtractorGDBRemote response;
2900 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2902 if (response.IsOKResponse())
2912 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2914 if (m_curr_tid_run == tid)
2919 if (tid == UINT64_MAX)
2920 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2922 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2924 assert (packet_len + 1 < (int)sizeof(packet));
2925 StringExtractorGDBRemote response;
2926 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2928 if (response.IsOKResponse())
2930 m_curr_tid_run = tid;
2938 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2940 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
2941 return response.IsNormalResponse();
2946 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2948 if (m_supports_qThreadStopInfo)
2951 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2952 assert (packet_len < (int)sizeof(packet));
2953 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2955 if (response.IsUnsupportedResponse())
2956 m_supports_qThreadStopInfo = false;
2957 else if (response.IsNormalResponse())
2964 m_supports_qThreadStopInfo = false;
2972 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2974 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2976 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2977 __FUNCTION__, insert ? "add" : "remove", addr);
2979 // Check if the stub is known not to support this breakpoint type
2980 if (!SupportsGDBStoppointPacket(type))
2982 // Construct the breakpoint packet
2984 const int packet_len = ::snprintf (packet,
2986 "%c%i,%" PRIx64 ",%x",
2991 // Check we haven't overwritten the end of the packet buffer
2992 assert (packet_len + 1 < (int)sizeof(packet));
2993 StringExtractorGDBRemote response;
2994 // Try to send the breakpoint packet, and check that it was correctly sent
2995 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
2997 // Receive and OK packet when the breakpoint successfully placed
2998 if (response.IsOKResponse())
3001 // Error while setting breakpoint, send back specific error
3002 if (response.IsErrorResponse())
3003 return response.GetError();
3005 // Empty packet informs us that breakpoint is not supported
3006 if (response.IsUnsupportedResponse())
3008 // Disable this breakpoint type since it is unsupported
3011 case eBreakpointSoftware: m_supports_z0 = false; break;
3012 case eBreakpointHardware: m_supports_z1 = false; break;
3013 case eWatchpointWrite: m_supports_z2 = false; break;
3014 case eWatchpointRead: m_supports_z3 = false; break;
3015 case eWatchpointReadWrite: m_supports_z4 = false; break;
3019 // Signal generic failure
3024 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3025 bool &sequence_mutex_unavailable)
3027 Mutex::Locker locker;
3030 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
3032 sequence_mutex_unavailable = false;
3033 StringExtractorGDBRemote response;
3035 PacketResult packet_result;
3036 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3037 packet_result == PacketResult::Success && response.IsNormalResponse();
3038 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
3040 char ch = response.GetChar();
3047 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3049 if (tid != LLDB_INVALID_THREAD_ID)
3051 thread_ids.push_back (tid);
3053 ch = response.GetChar(); // Skip the command separator
3054 } while (ch == ','); // Make sure we got a comma separator
3060 #if defined (LLDB_CONFIGURATION_DEBUG)
3061 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3063 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3065 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
3067 sequence_mutex_unavailable = true;
3069 return thread_ids.size();
3073 GDBRemoteCommunicationClient::GetShlibInfoAddr()
3077 StringExtractorGDBRemote response;
3078 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
3080 if (response.IsNormalResponse())
3081 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3084 return LLDB_INVALID_ADDRESS;
3088 GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
3089 const char *working_dir, // Pass NULL to use the current working directory
3090 int *status_ptr, // Pass NULL if you don't want the process exit status
3091 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3092 std::string *command_output, // Pass NULL if you don't want the command output
3093 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
3095 lldb_private::StreamString stream;
3096 stream.PutCString("qPlatform_shell:");
3097 stream.PutBytesAsRawHex8(command, strlen(command));
3098 stream.PutChar(',');
3099 stream.PutHex32(timeout_sec);
3100 if (working_dir && *working_dir)
3102 stream.PutChar(',');
3103 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
3105 const char *packet = stream.GetData();
3106 int packet_len = stream.GetSize();
3107 StringExtractorGDBRemote response;
3108 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3110 if (response.GetChar() != 'F')
3111 return Error("malformed reply");
3112 if (response.GetChar() != ',')
3113 return Error("malformed reply");
3114 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3115 if (exitcode == UINT32_MAX)
3116 return Error("unable to run remote process");
3117 else if (status_ptr)
3118 *status_ptr = exitcode;
3119 if (response.GetChar() != ',')
3120 return Error("malformed reply");
3121 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3124 if (response.GetChar() != ',')
3125 return Error("malformed reply");
3127 response.GetEscapedBinaryData(output);
3129 command_output->assign(output);
3132 return Error("unable to send packet");
3136 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
3137 uint32_t file_permissions)
3139 lldb_private::StreamString stream;
3140 stream.PutCString("qPlatform_mkdir:");
3141 stream.PutHex32(file_permissions);
3142 stream.PutChar(',');
3143 stream.PutBytesAsRawHex8(path, strlen(path));
3144 const char *packet = stream.GetData();
3145 int packet_len = stream.GetSize();
3146 StringExtractorGDBRemote response;
3147 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3149 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3156 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
3157 uint32_t file_permissions)
3159 lldb_private::StreamString stream;
3160 stream.PutCString("qPlatform_chmod:");
3161 stream.PutHex32(file_permissions);
3162 stream.PutChar(',');
3163 stream.PutBytesAsRawHex8(path, strlen(path));
3164 const char *packet = stream.GetData();
3165 int packet_len = stream.GetSize();
3166 StringExtractorGDBRemote response;
3167 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3169 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3176 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3177 uint64_t fail_result,
3180 response.SetFilePos(0);
3181 if (response.GetChar() != 'F')
3183 int32_t result = response.GetS32 (-2);
3186 if (response.GetChar() == ',')
3188 int result_errno = response.GetS32 (-2);
3189 if (result_errno != -2)
3190 error.SetError(result_errno, eErrorTypePOSIX);
3192 error.SetError(-1, eErrorTypeGeneric);
3199 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3204 lldb_private::StreamString stream;
3205 stream.PutCString("vFile:open:");
3206 std::string path (file_spec.GetPath());
3209 stream.PutCStringAsRawHex8(path.c_str());
3210 stream.PutChar(',');
3211 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
3212 stream.PutHex32(posix_open_flags);
3213 stream.PutChar(',');
3214 stream.PutHex32(mode);
3215 const char* packet = stream.GetData();
3216 int packet_len = stream.GetSize();
3217 StringExtractorGDBRemote response;
3218 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3220 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3226 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3229 lldb_private::StreamString stream;
3230 stream.Printf("vFile:close:%i", (int)fd);
3231 const char* packet = stream.GetData();
3232 int packet_len = stream.GetSize();
3233 StringExtractorGDBRemote response;
3234 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3236 return ParseHostIOPacketResponse (response, -1, error) == 0;
3241 // Extension of host I/O packets to get the file size.
3243 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3245 lldb_private::StreamString stream;
3246 stream.PutCString("vFile:size:");
3247 std::string path (file_spec.GetPath());
3248 stream.PutCStringAsRawHex8(path.c_str());
3249 const char* packet = stream.GetData();
3250 int packet_len = stream.GetSize();
3251 StringExtractorGDBRemote response;
3252 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3254 if (response.GetChar() != 'F')
3256 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3263 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
3266 lldb_private::StreamString stream;
3267 stream.PutCString("vFile:mode:");
3268 stream.PutCStringAsRawHex8(path);
3269 const char* packet = stream.GetData();
3270 int packet_len = stream.GetSize();
3271 StringExtractorGDBRemote response;
3272 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3274 if (response.GetChar() != 'F')
3276 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
3280 const uint32_t mode = response.GetS32(-1);
3281 if (static_cast<int32_t>(mode) == -1)
3283 if (response.GetChar() == ',')
3285 int response_errno = response.GetS32(-1);
3286 if (response_errno > 0)
3287 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3289 error.SetErrorToGenericError();
3292 error.SetErrorToGenericError();
3296 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3302 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3308 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3314 lldb_private::StreamString stream;
3315 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3316 const char* packet = stream.GetData();
3317 int packet_len = stream.GetSize();
3318 StringExtractorGDBRemote response;
3319 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3321 if (response.GetChar() != 'F')
3323 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3324 if (retcode == UINT32_MAX)
3326 const char next = (response.Peek() ? *response.Peek() : 0);
3331 response.GetChar(); // skip the semicolon
3333 if (response.GetEscapedBinaryData(buffer))
3335 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3336 if (data_to_write > 0)
3337 memcpy(dst, &buffer[0], data_to_write);
3338 return data_to_write;
3346 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3352 lldb_private::StreamGDBRemote stream;
3353 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3354 stream.PutEscapedBytes(src, src_len);
3355 const char* packet = stream.GetData();
3356 int packet_len = stream.GetSize();
3357 StringExtractorGDBRemote response;
3358 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3360 if (response.GetChar() != 'F')
3362 error.SetErrorStringWithFormat("write file failed");
3365 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3366 if (bytes_written == UINT64_MAX)
3368 error.SetErrorToGenericError();
3369 if (response.GetChar() == ',')
3371 int response_errno = response.GetS32(-1);
3372 if (response_errno > 0)
3373 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3377 return bytes_written;
3381 error.SetErrorString ("failed to send vFile:pwrite packet");
3387 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3390 lldb_private::StreamGDBRemote stream;
3391 stream.PutCString("vFile:symlink:");
3392 // the unix symlink() command reverses its parameters where the dst if first,
3393 // so we follow suit here
3394 stream.PutCStringAsRawHex8(dst);
3395 stream.PutChar(',');
3396 stream.PutCStringAsRawHex8(src);
3397 const char* packet = stream.GetData();
3398 int packet_len = stream.GetSize();
3399 StringExtractorGDBRemote response;
3400 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3402 if (response.GetChar() == 'F')
3404 uint32_t result = response.GetU32(UINT32_MAX);
3407 error.SetErrorToGenericError();
3408 if (response.GetChar() == ',')
3410 int response_errno = response.GetS32(-1);
3411 if (response_errno > 0)
3412 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3418 // Should have returned with 'F<result>[,<errno>]'
3419 error.SetErrorStringWithFormat("symlink failed");
3424 error.SetErrorString ("failed to send vFile:symlink packet");
3430 GDBRemoteCommunicationClient::Unlink (const char *path)
3433 lldb_private::StreamGDBRemote stream;
3434 stream.PutCString("vFile:unlink:");
3435 // the unix symlink() command reverses its parameters where the dst if first,
3436 // so we follow suit here
3437 stream.PutCStringAsRawHex8(path);
3438 const char* packet = stream.GetData();
3439 int packet_len = stream.GetSize();
3440 StringExtractorGDBRemote response;
3441 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3443 if (response.GetChar() == 'F')
3445 uint32_t result = response.GetU32(UINT32_MAX);
3448 error.SetErrorToGenericError();
3449 if (response.GetChar() == ',')
3451 int response_errno = response.GetS32(-1);
3452 if (response_errno > 0)
3453 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3459 // Should have returned with 'F<result>[,<errno>]'
3460 error.SetErrorStringWithFormat("unlink failed");
3465 error.SetErrorString ("failed to send vFile:unlink packet");
3470 // Extension of host I/O packets to get whether a file exists.
3472 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3474 lldb_private::StreamString stream;
3475 stream.PutCString("vFile:exists:");
3476 std::string path (file_spec.GetPath());
3477 stream.PutCStringAsRawHex8(path.c_str());
3478 const char* packet = stream.GetData();
3479 int packet_len = stream.GetSize();
3480 StringExtractorGDBRemote response;
3481 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3483 if (response.GetChar() != 'F')
3485 if (response.GetChar() != ',')
3487 bool retcode = (response.GetChar() != '0');
3494 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3498 lldb_private::StreamString stream;
3499 stream.PutCString("vFile:MD5:");
3500 std::string path (file_spec.GetPath());
3501 stream.PutCStringAsRawHex8(path.c_str());
3502 const char* packet = stream.GetData();
3503 int packet_len = stream.GetSize();
3504 StringExtractorGDBRemote response;
3505 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3507 if (response.GetChar() != 'F')
3509 if (response.GetChar() != ',')
3511 if (response.Peek() && *response.Peek() == 'x')
3513 low = response.GetHexMaxU64(false, UINT64_MAX);
3514 high = response.GetHexMaxU64(false, UINT64_MAX);
3521 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3523 // Some targets have issues with g/G packets and we need to avoid using them
3524 if (m_avoid_g_packets == eLazyBoolCalculate)
3528 m_avoid_g_packets = eLazyBoolNo;
3529 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3531 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3532 && arch.GetTriple().getOS() == llvm::Triple::IOS
3533 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
3535 m_avoid_g_packets = eLazyBoolYes;
3536 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3537 if (gdb_server_version != 0)
3539 const char *gdb_server_name = GetGDBServerProgramName();
3540 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3542 if (gdb_server_version >= 310)
3543 m_avoid_g_packets = eLazyBoolNo;
3549 return m_avoid_g_packets == eLazyBoolYes;
3553 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3555 Mutex::Locker locker;
3556 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3558 const bool thread_suffix_supported = GetThreadSuffixSupported();
3560 if (thread_suffix_supported || SetCurrentThread(tid))
3564 if (thread_suffix_supported)
3565 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3567 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3568 assert (packet_len < ((int)sizeof(packet) - 1));
3569 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3578 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3580 Mutex::Locker locker;
3581 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3583 const bool thread_suffix_supported = GetThreadSuffixSupported();
3585 if (thread_suffix_supported || SetCurrentThread(tid))
3589 // Get all registers in one packet
3590 if (thread_suffix_supported)
3591 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3593 packet_len = ::snprintf (packet, sizeof(packet), "g");
3594 assert (packet_len < ((int)sizeof(packet) - 1));
3595 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3601 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3603 save_id = 0; // Set to invalid save ID
3604 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3607 m_supports_QSaveRegisterState = eLazyBoolYes;
3608 Mutex::Locker locker;
3609 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3611 const bool thread_suffix_supported = GetThreadSuffixSupported();
3612 if (thread_suffix_supported || SetCurrentThread(tid))
3615 if (thread_suffix_supported)
3616 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3618 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3620 StringExtractorGDBRemote response;
3622 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3624 if (response.IsUnsupportedResponse())
3626 // This packet isn't supported, don't try calling it again
3627 m_supports_QSaveRegisterState = eLazyBoolNo;
3630 const uint32_t response_save_id = response.GetU32(0);
3631 if (response_save_id != 0)
3633 save_id = response_save_id;
3643 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3645 // We use the "m_supports_QSaveRegisterState" variable here because the
3646 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3647 // order to be useful
3648 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3651 Mutex::Locker locker;
3652 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3654 const bool thread_suffix_supported = GetThreadSuffixSupported();
3655 if (thread_suffix_supported || SetCurrentThread(tid))
3658 if (thread_suffix_supported)
3659 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3661 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3663 StringExtractorGDBRemote response;
3665 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3667 if (response.IsOKResponse())
3671 else if (response.IsUnsupportedResponse())
3673 // This packet isn't supported, don't try calling this packet or
3674 // QSaveRegisterState again...
3675 m_supports_QSaveRegisterState = eLazyBoolNo;