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/Triple.h"
21 #include "lldb/Interpreter/Args.h"
22 #include "lldb/Core/ConnectionFileDescriptor.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/Endian.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/TimeValue.h"
32 #include "Utility/StringExtractorGDBRemote.h"
33 #include "ProcessGDBRemote.h"
34 #include "ProcessGDBRemoteLog.h"
35 #include "lldb/Host/Config.h"
38 using namespace lldb_private;
40 #ifdef LLDB_DISABLE_POSIX
44 //----------------------------------------------------------------------
45 // GDBRemoteCommunicationClient constructor
46 //----------------------------------------------------------------------
47 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
48 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
49 m_supports_not_sending_acks (eLazyBoolCalculate),
50 m_supports_thread_suffix (eLazyBoolCalculate),
51 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
52 m_supports_vCont_all (eLazyBoolCalculate),
53 m_supports_vCont_any (eLazyBoolCalculate),
54 m_supports_vCont_c (eLazyBoolCalculate),
55 m_supports_vCont_C (eLazyBoolCalculate),
56 m_supports_vCont_s (eLazyBoolCalculate),
57 m_supports_vCont_S (eLazyBoolCalculate),
58 m_qHostInfo_is_valid (eLazyBoolCalculate),
59 m_qProcessInfo_is_valid (eLazyBoolCalculate),
60 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
61 m_supports_memory_region_info (eLazyBoolCalculate),
62 m_supports_watchpoint_support_info (eLazyBoolCalculate),
63 m_supports_detach_stay_stopped (eLazyBoolCalculate),
64 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
65 m_attach_or_wait_reply(eLazyBoolCalculate),
66 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
67 m_supports_p (eLazyBoolCalculate),
68 m_supports_QSaveRegisterState (eLazyBoolCalculate),
69 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
70 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
71 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
72 m_supports_qProcessInfoPID (true),
73 m_supports_qfProcessInfo (true),
74 m_supports_qUserName (true),
75 m_supports_qGroupName (true),
76 m_supports_qThreadStopInfo (true),
82 m_supports_QEnvironment (true),
83 m_supports_QEnvironmentHexEncoded (true),
84 m_curr_tid (LLDB_INVALID_THREAD_ID),
85 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
86 m_num_supported_hardware_watchpoints (0),
87 m_async_mutex (Mutex::eMutexTypeRecursive),
88 m_async_packet_predicate (false),
90 m_async_result (PacketResult::Success),
93 m_thread_id_to_used_usec_map (),
96 m_os_version_major (UINT32_MAX),
97 m_os_version_minor (UINT32_MAX),
98 m_os_version_update (UINT32_MAX),
102 m_default_packet_timeout (0),
103 m_max_packet_size (0)
107 //----------------------------------------------------------------------
109 //----------------------------------------------------------------------
110 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
117 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
119 ResetDiscoverableSettings();
121 // Start the read thread after we send the handshake ack since if we
122 // fail to send the handshake ack, there is no reason to continue...
125 // Wait for any responses that might have been queued up in the remote
126 // GDB server and flush them all
127 StringExtractorGDBRemote response;
128 PacketResult packet_result = PacketResult::Success;
129 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
130 while (packet_result == PacketResult::Success)
131 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
133 // The return value from QueryNoAckModeSupported() is true if the packet
134 // was sent and _any_ response (including UNIMPLEMENTED) was received),
135 // or false if no response was received. This quickly tells us if we have
136 // a live connection to a remote GDB server...
137 if (QueryNoAckModeSupported())
140 // Set above line to "#if 1" to test packet speed if remote GDB server
141 // supports the qSpeedTest packet...
142 TestPacketSpeed(10000);
149 error_ptr->SetErrorString("failed to get reply to handshake packet");
155 error_ptr->SetErrorString("failed to send the handshake ack");
161 GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
163 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
165 GetRemoteQSupported();
167 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
171 GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
173 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
175 GetRemoteQSupported();
177 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
181 GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
183 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
185 GetRemoteQSupported();
187 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
191 GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
193 if (m_max_packet_size == 0)
195 GetRemoteQSupported();
197 return m_max_packet_size;
201 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
203 if (m_supports_not_sending_acks == eLazyBoolCalculate)
206 m_supports_not_sending_acks = eLazyBoolNo;
208 StringExtractorGDBRemote response;
209 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
211 if (response.IsOKResponse())
214 m_supports_not_sending_acks = eLazyBoolYes;
223 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
225 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
227 m_supports_threads_in_stop_reply = eLazyBoolNo;
229 StringExtractorGDBRemote response;
230 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
232 if (response.IsOKResponse())
233 m_supports_threads_in_stop_reply = eLazyBoolYes;
239 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
241 if (m_attach_or_wait_reply == eLazyBoolCalculate)
243 m_attach_or_wait_reply = eLazyBoolNo;
245 StringExtractorGDBRemote response;
246 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
248 if (response.IsOKResponse())
249 m_attach_or_wait_reply = eLazyBoolYes;
252 if (m_attach_or_wait_reply == eLazyBoolYes)
259 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
261 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
263 m_prepare_for_reg_writing_reply = eLazyBoolNo;
265 StringExtractorGDBRemote response;
266 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
268 if (response.IsOKResponse())
269 m_prepare_for_reg_writing_reply = eLazyBoolYes;
272 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
280 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
282 m_supports_not_sending_acks = eLazyBoolCalculate;
283 m_supports_thread_suffix = eLazyBoolCalculate;
284 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
285 m_supports_vCont_c = eLazyBoolCalculate;
286 m_supports_vCont_C = eLazyBoolCalculate;
287 m_supports_vCont_s = eLazyBoolCalculate;
288 m_supports_vCont_S = eLazyBoolCalculate;
289 m_supports_p = eLazyBoolCalculate;
290 m_supports_QSaveRegisterState = eLazyBoolCalculate;
291 m_qHostInfo_is_valid = eLazyBoolCalculate;
292 m_qProcessInfo_is_valid = eLazyBoolCalculate;
293 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
294 m_supports_memory_region_info = eLazyBoolCalculate;
295 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
296 m_attach_or_wait_reply = eLazyBoolCalculate;
297 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
298 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
301 m_supports_qProcessInfoPID = true;
302 m_supports_qfProcessInfo = true;
303 m_supports_qUserName = true;
304 m_supports_qGroupName = true;
305 m_supports_qThreadStopInfo = true;
306 m_supports_z0 = true;
307 m_supports_z1 = true;
308 m_supports_z2 = true;
309 m_supports_z3 = true;
310 m_supports_z4 = true;
311 m_supports_QEnvironment = true;
312 m_supports_QEnvironmentHexEncoded = true;
314 m_process_arch.Clear();
316 m_max_packet_size = 0;
320 GDBRemoteCommunicationClient::GetRemoteQSupported ()
322 // Clear out any capabilities we expect to see in the qSupported response
323 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
324 m_supports_qXfer_libraries_read = eLazyBoolNo;
325 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
326 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
328 StringExtractorGDBRemote response;
329 if (SendPacketAndWaitForResponse("qSupported",
331 /*send_async=*/false) == PacketResult::Success)
333 const char *response_cstr = response.GetStringRef().c_str();
334 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
335 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
336 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
338 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
339 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
341 if (::strstr (response_cstr, "qXfer:libraries:read+"))
342 m_supports_qXfer_libraries_read = eLazyBoolYes;
344 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
347 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
348 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
349 if (m_max_packet_size == 0)
351 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
352 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
354 log->Printf ("Garbled PacketSize spec in qSupported response");
361 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
363 if (m_supports_thread_suffix == eLazyBoolCalculate)
365 StringExtractorGDBRemote response;
366 m_supports_thread_suffix = eLazyBoolNo;
367 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
369 if (response.IsOKResponse())
370 m_supports_thread_suffix = eLazyBoolYes;
373 return m_supports_thread_suffix;
376 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
378 if (m_supports_vCont_c == eLazyBoolCalculate)
380 StringExtractorGDBRemote response;
381 m_supports_vCont_any = eLazyBoolNo;
382 m_supports_vCont_all = eLazyBoolNo;
383 m_supports_vCont_c = eLazyBoolNo;
384 m_supports_vCont_C = eLazyBoolNo;
385 m_supports_vCont_s = eLazyBoolNo;
386 m_supports_vCont_S = eLazyBoolNo;
387 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
389 const char *response_cstr = response.GetStringRef().c_str();
390 if (::strstr (response_cstr, ";c"))
391 m_supports_vCont_c = eLazyBoolYes;
393 if (::strstr (response_cstr, ";C"))
394 m_supports_vCont_C = eLazyBoolYes;
396 if (::strstr (response_cstr, ";s"))
397 m_supports_vCont_s = eLazyBoolYes;
399 if (::strstr (response_cstr, ";S"))
400 m_supports_vCont_S = eLazyBoolYes;
402 if (m_supports_vCont_c == eLazyBoolYes &&
403 m_supports_vCont_C == eLazyBoolYes &&
404 m_supports_vCont_s == eLazyBoolYes &&
405 m_supports_vCont_S == eLazyBoolYes)
407 m_supports_vCont_all = eLazyBoolYes;
410 if (m_supports_vCont_c == eLazyBoolYes ||
411 m_supports_vCont_C == eLazyBoolYes ||
412 m_supports_vCont_s == eLazyBoolYes ||
413 m_supports_vCont_S == eLazyBoolYes)
415 m_supports_vCont_any = eLazyBoolYes;
422 case 'a': return m_supports_vCont_any;
423 case 'A': return m_supports_vCont_all;
424 case 'c': return m_supports_vCont_c;
425 case 'C': return m_supports_vCont_C;
426 case 's': return m_supports_vCont_s;
427 case 'S': return m_supports_vCont_S;
433 // Check if the target supports 'p' packet. It sends out a 'p'
434 // packet and checks the response. A normal packet will tell us
435 // that support is available.
437 // Takes a valid thread ID because p needs to apply to a thread.
439 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
441 if (m_supports_p == eLazyBoolCalculate)
443 StringExtractorGDBRemote response;
444 m_supports_p = eLazyBoolNo;
446 if (GetThreadSuffixSupported())
447 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
449 snprintf(packet, sizeof(packet), "p0");
451 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
453 if (response.IsNormalResponse())
454 m_supports_p = eLazyBoolYes;
460 GDBRemoteCommunicationClient::PacketResult
461 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
463 const char *payload_prefix,
464 std::string &response_string
467 Mutex::Locker locker;
468 if (!GetSequenceMutex(locker,
469 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
471 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
473 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
475 return PacketResult::ErrorNoSequenceLock;
478 response_string = "";
479 std::string payload_prefix_str(payload_prefix);
480 unsigned int response_size = 0x1000;
481 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
482 response_size = GetRemoteMaxPacketSize();
485 for (unsigned int offset = 0; true; offset += response_size)
487 StringExtractorGDBRemote this_response;
489 char sizeDescriptor[128];
490 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
491 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
493 /*send_async=*/false);
494 if (result != PacketResult::Success)
497 const std::string &this_string = this_response.GetStringRef();
499 // Check for m or l as first character; l seems to mean this is the last chunk
500 char first_char = *this_string.c_str();
501 if (first_char != 'm' && first_char != 'l')
503 return PacketResult::ErrorReplyInvalid;
506 const char *s = this_string.c_str() + 1;
508 // Concatenate the result so far
509 response_string += s;
510 if (first_char == 'l')
512 return PacketResult::Success;
516 GDBRemoteCommunicationClient::PacketResult
517 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
520 StringExtractorGDBRemote &response,
524 return SendPacketAndWaitForResponse (payload,
530 GDBRemoteCommunicationClient::PacketResult
531 GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
532 size_t payload_length,
533 StringExtractorGDBRemote &response)
535 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
536 if (packet_result == PacketResult::Success)
537 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
538 return packet_result;
541 GDBRemoteCommunicationClient::PacketResult
542 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
545 size_t payload_length,
546 StringExtractorGDBRemote &response,
550 PacketResult packet_result = PacketResult::ErrorSendFailed;
551 Mutex::Locker locker;
552 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
553 size_t response_len = 0;
554 if (GetSequenceMutex (locker))
556 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
564 Mutex::Locker async_locker (m_async_mutex);
565 m_async_packet.assign(payload, payload_length);
566 m_async_packet_predicate.SetValue (true, eBroadcastNever);
569 log->Printf ("async: async packet = %s", m_async_packet.c_str());
571 bool timed_out = false;
572 if (SendInterrupt(locker, 2, timed_out))
574 if (m_interrupt_sent)
576 m_interrupt_sent = false;
577 TimeValue timeout_time;
578 timeout_time = TimeValue::Now();
579 timeout_time.OffsetWithSeconds (m_packet_timeout);
582 log->Printf ("async: sent interrupt");
584 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
587 log->Printf ("async: got response");
589 // Swap the response buffer to avoid malloc and string copy
590 response.GetStringRef().swap (m_async_response.GetStringRef());
591 response_len = response.GetStringRef().size();
592 packet_result = m_async_result;
597 log->Printf ("async: timed out waiting for response");
600 // Make sure we wait until the continue packet has been sent again...
601 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
606 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
608 log->Printf ("async: async packet sent");
614 log->Printf ("async: timed out waiting for process to resume");
619 // We had a racy condition where we went to send the interrupt
620 // yet we were able to get the lock, so the process must have
623 log->Printf ("async: got lock without sending interrupt");
624 // Send the packet normally since we got the lock
625 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
631 log->Printf ("async: failed to interrupt");
637 log->Printf ("async: not running, async is ignored");
643 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
646 return packet_result;
649 static const char *end_delimiter = "--end--;";
650 static const int end_delimiter_len = 8;
653 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
654 ( ProcessGDBRemote *process,
655 StringExtractorGDBRemote& profileDataExtractor
658 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
659 std::stringstream final_output;
660 std::string name, value;
662 // Going to assuming thread_used_usec comes first, else bail out.
663 while (profileDataExtractor.GetNameColonValue(name, value))
665 if (name.compare("thread_used_id") == 0)
667 StringExtractor threadIDHexExtractor(value.c_str());
668 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
670 bool has_used_usec = false;
671 uint32_t curr_used_usec = 0;
672 std::string usec_name, usec_value;
673 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
674 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
676 if (usec_name.compare("thread_used_usec") == 0)
678 has_used_usec = true;
679 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
683 // We didn't find what we want, it is probably
684 // an older version. Bail out.
685 profileDataExtractor.SetFilePos(input_file_pos);
691 uint32_t prev_used_usec = 0;
692 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
693 if (iterator != m_thread_id_to_used_usec_map.end())
695 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
698 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
699 // A good first time record is one that runs for at least 0.25 sec
700 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
701 bool good_subsequent_time = (prev_used_usec > 0) &&
702 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
704 if (good_first_time || good_subsequent_time)
706 // We try to avoid doing too many index id reservation,
707 // resulting in fast increase of index ids.
709 final_output << name << ":";
710 int32_t index_id = process->AssignIndexIDToThread(thread_id);
711 final_output << index_id << ";";
713 final_output << usec_name << ":" << usec_value << ";";
717 // Skip past 'thread_used_name'.
718 std::string local_name, local_value;
719 profileDataExtractor.GetNameColonValue(local_name, local_value);
722 // Store current time as previous time so that they can be compared later.
723 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
727 // Bail out and use old string.
728 final_output << name << ":" << value << ";";
733 final_output << name << ":" << value << ";";
736 final_output << end_delimiter;
737 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
739 return final_output.str();
743 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
745 ProcessGDBRemote *process,
747 size_t packet_length,
748 StringExtractorGDBRemote &response
751 m_curr_tid = LLDB_INVALID_THREAD_ID;
752 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
754 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
756 Mutex::Locker locker(m_sequence_mutex);
757 StateType state = eStateRunning;
759 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
760 m_public_is_running.SetValue (true, eBroadcastNever);
761 // Set the starting continue packet into "continue_packet". This packet
762 // may change if we are interrupted and we continue after an async packet...
763 std::string continue_packet(payload, packet_length);
765 bool got_async_packet = false;
767 while (state == eStateRunning)
769 if (!got_async_packet)
772 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
773 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
774 state = eStateInvalid;
776 m_private_is_running.SetValue (true, eBroadcastAlways);
779 got_async_packet = false;
782 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
784 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
786 if (response.Empty())
787 state = eStateInvalid;
790 const char stop_type = response.GetChar();
792 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
798 if (process->GetStopID() == 0)
800 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
802 lldb::pid_t pid = GetCurrentProcessID ();
803 if (pid != LLDB_INVALID_PROCESS_ID)
804 process->SetID (pid);
806 process->BuildDynamicRegisterInfo (true);
809 // Privately notify any internal threads that we have stopped
810 // in case we wanted to interrupt our process, yet we might
811 // send a packet and continue without returning control to the
813 m_private_is_running.SetValue (false, eBroadcastAlways);
815 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
817 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
818 if (continue_after_async || m_interrupt_sent)
820 // We sent an interrupt packet to stop the inferior process
821 // for an async signal or to send an async packet while running
822 // but we might have been single stepping and received the
823 // stop packet for the step instead of for the interrupt packet.
824 // Typically when an interrupt is sent a SIGINT or SIGSTOP
825 // is used, so if we get anything else, we need to try and
826 // get another stop reply packet that may have been sent
827 // due to sending the interrupt when the target is stopped
828 // which will just re-send a copy of the last stop reply
829 // packet. If we don't do this, then the reply for our
830 // async packet will be the repeat stop reply packet and cause
831 // a lot of trouble for us!
832 if (signo != SIGINT && signo != SIGSTOP)
834 continue_after_async = false;
836 // We didn't get a a SIGINT or SIGSTOP, so try for a
837 // very brief time (1 ms) to get another stop reply
838 // packet to make sure it doesn't get in the way
839 StringExtractorGDBRemote extra_stop_reply_packet;
840 uint32_t timeout_usec = 1000;
841 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
843 switch (extra_stop_reply_packet.GetChar())
847 // We did get an extra stop reply, which means
848 // our interrupt didn't stop the target so we
849 // shouldn't continue after the async signal
850 // or packet is sent...
851 continue_after_async = false;
858 if (m_async_signal != -1)
861 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
863 // Save off the async signal we are supposed to send
864 const int async_signal = m_async_signal;
865 // Clear the async signal member so we don't end up
866 // sending the signal multiple times...
868 // Check which signal we stopped with
869 if (signo == async_signal)
872 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
874 // We already stopped with a signal that we wanted
875 // to stop with, so we are done
879 // We stopped with a different signal that the one
880 // we wanted to stop with, so now we must resume
881 // with the signal we want
882 char signal_packet[32];
883 int signal_packet_len = 0;
884 signal_packet_len = ::snprintf (signal_packet,
885 sizeof (signal_packet),
890 log->Printf ("async: stopped with signal %s, resume with %s",
891 Host::GetSignalAsCString (signo),
892 Host::GetSignalAsCString (async_signal));
894 // Set the continue packet to resume even if the
895 // interrupt didn't cause our stop (ignore continue_after_async)
896 continue_packet.assign(signal_packet, signal_packet_len);
900 else if (m_async_packet_predicate.GetValue())
902 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
904 // We are supposed to send an asynchronous packet while
906 m_async_response.Clear();
907 if (m_async_packet.empty())
909 m_async_result = PacketResult::ErrorSendFailed;
911 packet_log->Printf ("async: error: empty async packet");
917 packet_log->Printf ("async: sending packet");
919 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
920 m_async_packet.size(),
924 // Let the other thread that was trying to send the async
925 // packet know that the packet has been sent and response is
927 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
930 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
932 // Set the continue packet to resume if our interrupt
933 // for the async packet did cause the stop
934 if (continue_after_async)
936 // Reverting this for now as it is causing deadlocks
937 // in programs (<rdar://problem/11529853>). In the future
938 // we should check our thread list and "do the right thing"
939 // for new threads that show up while we stop and run async
940 // packets. Setting the packet to 'c' to continue all threads
941 // is the right thing to do 99.99% of the time because if a
942 // thread was single stepping, and we sent an interrupt, we
943 // will notice above that we didn't stop due to an interrupt
944 // but stopped due to stepping and we would _not_ continue.
945 continue_packet.assign (1, 'c');
949 // Stop with signal and thread info
950 state = eStateStopped;
957 state = eStateExited;
963 got_async_packet = true;
964 std::string inferior_stdout;
965 inferior_stdout.reserve(response.GetBytesLeft () / 2);
967 while ((ch = response.GetHexU8()) != '\0')
968 inferior_stdout.append(1, ch);
969 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
974 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
976 got_async_packet = true;
977 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
978 if (m_partial_profile_data.length() > 0)
980 m_partial_profile_data.append(input);
981 input = m_partial_profile_data;
982 m_partial_profile_data.clear();
985 size_t found, pos = 0, len = input.length();
986 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
988 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
989 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
990 process->BroadcastAsyncProfileData (profile_data);
992 pos = found + end_delimiter_len;
997 // Last incomplete chunk.
998 m_partial_profile_data = input.substr(pos);
1005 state = eStateInvalid;
1010 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1011 state = eStateInvalid;
1019 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1020 state = eStateInvalid;
1024 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1025 response.SetFilePos(0);
1026 m_private_is_running.SetValue (false, eBroadcastAlways);
1027 m_public_is_running.SetValue (false, eBroadcastAlways);
1032 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1034 Mutex::Locker async_locker (m_async_mutex);
1035 m_async_signal = signo;
1036 bool timed_out = false;
1037 Mutex::Locker locker;
1038 if (SendInterrupt (locker, 1, timed_out))
1040 m_async_signal = -1;
1044 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
1045 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1046 // (the expected result), then it will send the halt packet. If it does succeed
1047 // then the caller that requested the interrupt will want to keep the sequence
1048 // locked down so that no one else can send packets while the caller has control.
1049 // This function usually gets called when we are running and need to stop the
1050 // target. It can also be used when we are running and and we need to do something
1051 // else (like read/write memory), so we need to interrupt the running process
1052 // (gdb remote protocol requires this), and do what we need to do, then resume.
1055 GDBRemoteCommunicationClient::SendInterrupt
1057 Mutex::Locker& locker,
1058 uint32_t seconds_to_wait_for_stop,
1063 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
1067 // Only send an interrupt if our debugserver is running...
1068 if (GetSequenceMutex (locker))
1071 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1075 // Someone has the mutex locked waiting for a response or for the
1076 // inferior to stop, so send the interrupt on the down low...
1077 char ctrl_c = '\x03';
1078 ConnectionStatus status = eConnectionStatusSuccess;
1079 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
1081 log->PutCString("send packet: \\x03");
1082 if (bytes_written > 0)
1084 m_interrupt_sent = true;
1085 if (seconds_to_wait_for_stop)
1088 if (seconds_to_wait_for_stop)
1090 timeout = TimeValue::Now();
1091 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1093 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1096 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
1102 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
1108 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
1115 log->Printf ("SendInterrupt () - failed to write interrupt");
1123 log->Printf ("SendInterrupt () - not running");
1129 GDBRemoteCommunicationClient::GetCurrentProcessID ()
1131 StringExtractorGDBRemote response;
1132 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
1134 if (response.GetChar() == 'Q')
1135 if (response.GetChar() == 'C')
1136 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1138 return LLDB_INVALID_PROCESS_ID;
1142 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1145 StringExtractorGDBRemote response;
1146 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
1148 if (response.IsOKResponse())
1150 if (response.GetChar() == 'E')
1152 // A string the describes what failed when launching...
1153 error_str = response.GetStringRef().substr(1);
1157 error_str.assign ("unknown error occurred launching process");
1162 error_str.assign ("timed out waiting for app to launch");
1168 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
1170 // Since we don't get the send argv0 separate from the executable path, we need to
1171 // make sure to use the actual exectuable path found in the launch_info...
1172 std::vector<const char *> argv;
1173 FileSpec exe_file = launch_info.GetExecutableFile();
1174 std::string exe_path;
1175 const char *arg = NULL;
1176 const Args &launch_args = launch_info.GetArguments();
1178 exe_path = exe_file.GetPath();
1181 arg = launch_args.GetArgumentAtIndex(0);
1185 if (!exe_path.empty())
1187 argv.push_back(exe_path.c_str());
1188 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1191 argv.push_back(arg);
1196 StreamString packet;
1197 packet.PutChar('A');
1198 for (size_t i = 0, n = argv.size(); i < n; ++i)
1201 const int arg_len = strlen(arg);
1203 packet.PutChar(',');
1204 packet.Printf("%i,%i,", arg_len * 2, (int)i);
1205 packet.PutBytesAsRawHex8 (arg, arg_len);
1208 StringExtractorGDBRemote response;
1209 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1211 if (response.IsOKResponse())
1213 uint8_t error = response.GetError();
1222 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1224 if (name_equal_value && name_equal_value[0])
1226 StreamString packet;
1227 bool send_hex_encoding = false;
1228 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
1236 send_hex_encoding = true;
1244 // We have non printable characters, lets hex encode this...
1245 send_hex_encoding = true;
1249 StringExtractorGDBRemote response;
1250 if (send_hex_encoding)
1252 if (m_supports_QEnvironmentHexEncoded)
1254 packet.PutCString("QEnvironmentHexEncoded:");
1255 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1256 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1258 if (response.IsOKResponse())
1260 uint8_t error = response.GetError();
1263 if (response.IsUnsupportedResponse())
1264 m_supports_QEnvironmentHexEncoded = false;
1269 else if (m_supports_QEnvironment)
1271 packet.Printf("QEnvironment:%s", name_equal_value);
1272 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1274 if (response.IsOKResponse())
1276 uint8_t error = response.GetError();
1279 if (response.IsUnsupportedResponse())
1280 m_supports_QEnvironment = false;
1288 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1290 if (arch && arch[0])
1292 StreamString packet;
1293 packet.Printf("QLaunchArch:%s", arch);
1294 StringExtractorGDBRemote response;
1295 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1297 if (response.IsOKResponse())
1299 uint8_t error = response.GetError();
1308 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1314 if (m_os_version_major != UINT32_MAX)
1316 major = m_os_version_major;
1317 minor = m_os_version_minor;
1318 update = m_os_version_update;
1326 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1330 if (!m_os_build.empty())
1342 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1346 if (!m_os_kernel.empty())
1357 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1361 if (!m_hostname.empty())
1372 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1379 const lldb_private::ArchSpec &
1380 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1382 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1383 GetCurrentProcessInfo ();
1384 return m_process_arch;
1389 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1391 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1393 m_qHostInfo_is_valid = eLazyBoolNo;
1394 StringExtractorGDBRemote response;
1395 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
1397 if (response.IsNormalResponse())
1401 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1403 std::string arch_name;
1404 std::string os_name;
1405 std::string vendor_name;
1407 std::string distribution_id;
1408 uint32_t pointer_byte_size = 0;
1409 StringExtractor extractor;
1410 ByteOrder byte_order = eByteOrderInvalid;
1411 uint32_t num_keys_decoded = 0;
1412 while (response.GetNameColonValue(name, value))
1414 if (name.compare("cputype") == 0)
1416 // exception type in big endian hex
1417 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1418 if (cpu != LLDB_INVALID_CPUTYPE)
1421 else if (name.compare("cpusubtype") == 0)
1423 // exception count in big endian hex
1424 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1428 else if (name.compare("arch") == 0)
1430 arch_name.swap (value);
1433 else if (name.compare("triple") == 0)
1435 // The triple comes as ASCII hex bytes since it contains '-' chars
1436 extractor.GetStringRef().swap(value);
1437 extractor.SetFilePos(0);
1438 extractor.GetHexByteString (triple);
1441 else if (name.compare ("distribution_id") == 0)
1443 extractor.GetStringRef ().swap (value);
1444 extractor.SetFilePos (0);
1445 extractor.GetHexByteString (distribution_id);
1448 else if (name.compare("os_build") == 0)
1450 extractor.GetStringRef().swap(value);
1451 extractor.SetFilePos(0);
1452 extractor.GetHexByteString (m_os_build);
1455 else if (name.compare("hostname") == 0)
1457 extractor.GetStringRef().swap(value);
1458 extractor.SetFilePos(0);
1459 extractor.GetHexByteString (m_hostname);
1462 else if (name.compare("os_kernel") == 0)
1464 extractor.GetStringRef().swap(value);
1465 extractor.SetFilePos(0);
1466 extractor.GetHexByteString (m_os_kernel);
1469 else if (name.compare("ostype") == 0)
1471 os_name.swap (value);
1474 else if (name.compare("vendor") == 0)
1476 vendor_name.swap(value);
1479 else if (name.compare("endian") == 0)
1482 if (value.compare("little") == 0)
1483 byte_order = eByteOrderLittle;
1484 else if (value.compare("big") == 0)
1485 byte_order = eByteOrderBig;
1486 else if (value.compare("pdp") == 0)
1487 byte_order = eByteOrderPDP;
1491 else if (name.compare("ptrsize") == 0)
1493 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1494 if (pointer_byte_size != 0)
1497 else if (name.compare("os_version") == 0)
1499 Args::StringToVersion (value.c_str(),
1502 m_os_version_update);
1503 if (m_os_version_major != UINT32_MAX)
1506 else if (name.compare("watchpoint_exceptions_received") == 0)
1509 if (strcmp(value.c_str(),"before") == 0)
1510 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1511 else if (strcmp(value.c_str(),"after") == 0)
1512 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1516 else if (name.compare("default_packet_timeout") == 0)
1518 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1519 if (m_default_packet_timeout > 0)
1521 SetPacketTimeout(m_default_packet_timeout);
1528 if (num_keys_decoded > 0)
1529 m_qHostInfo_is_valid = eLazyBoolYes;
1533 if (arch_name.empty())
1535 if (cpu != LLDB_INVALID_CPUTYPE)
1537 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1538 if (pointer_byte_size)
1540 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1542 if (byte_order != eByteOrderInvalid)
1544 assert (byte_order == m_host_arch.GetByteOrder());
1547 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1549 switch (m_host_arch.GetMachine())
1551 case llvm::Triple::arm:
1552 case llvm::Triple::thumb:
1560 if (!vendor_name.empty())
1561 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1562 if (!os_name.empty())
1563 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1570 triple += arch_name;
1571 if (!vendor_name.empty() || !os_name.empty())
1574 if (vendor_name.empty())
1575 triple += "unknown";
1577 triple += vendor_name;
1579 if (os_name.empty())
1580 triple += "unknown";
1584 m_host_arch.SetTriple (triple.c_str());
1586 llvm::Triple &host_triple = m_host_arch.GetTriple();
1587 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1589 switch (m_host_arch.GetMachine())
1591 case llvm::Triple::arm:
1592 case llvm::Triple::thumb:
1593 host_triple.setOS(llvm::Triple::IOS);
1596 host_triple.setOS(llvm::Triple::MacOSX);
1600 if (pointer_byte_size)
1602 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1604 if (byte_order != eByteOrderInvalid)
1606 assert (byte_order == m_host_arch.GetByteOrder());
1613 m_host_arch.SetTriple (triple.c_str());
1614 if (pointer_byte_size)
1616 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1618 if (byte_order != eByteOrderInvalid)
1620 assert (byte_order == m_host_arch.GetByteOrder());
1623 if (!distribution_id.empty ())
1624 m_host_arch.SetDistributionId (distribution_id.c_str ());
1628 return m_qHostInfo_is_valid == eLazyBoolYes;
1632 GDBRemoteCommunicationClient::SendAttach
1635 StringExtractorGDBRemote& response
1638 if (pid != LLDB_INVALID_PROCESS_ID)
1641 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1642 assert (packet_len < (int)sizeof(packet));
1643 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1645 if (response.IsErrorResponse())
1646 return response.GetError();
1653 const lldb_private::ArchSpec &
1654 GDBRemoteCommunicationClient::GetHostArchitecture ()
1656 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1662 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1664 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1666 return m_default_packet_timeout;
1670 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1672 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1674 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1676 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1678 permissions & lldb::ePermissionsReadable ? "r" : "",
1679 permissions & lldb::ePermissionsWritable ? "w" : "",
1680 permissions & lldb::ePermissionsExecutable ? "x" : "");
1681 assert (packet_len < (int)sizeof(packet));
1682 StringExtractorGDBRemote response;
1683 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1685 if (!response.IsErrorResponse())
1686 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1690 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1693 return LLDB_INVALID_ADDRESS;
1697 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1699 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1701 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1703 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1704 assert (packet_len < (int)sizeof(packet));
1705 StringExtractorGDBRemote response;
1706 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1708 if (response.IsOKResponse())
1713 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1720 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1726 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1729 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1730 assert (packet_len < (int)sizeof(packet));
1731 StringExtractorGDBRemote response;
1732 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1734 m_supports_detach_stay_stopped = eLazyBoolYes;
1738 m_supports_detach_stay_stopped = eLazyBoolNo;
1742 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1744 error.SetErrorString("Stays stopped not supported by this target.");
1749 PacketResult packet_result = SendPacket ("D1", 2);
1750 if (packet_result != PacketResult::Success)
1751 error.SetErrorString ("Sending extended disconnect packet failed.");
1756 PacketResult packet_result = SendPacket ("D", 1);
1757 if (packet_result != PacketResult::Success)
1758 error.SetErrorString ("Sending disconnect packet failed.");
1764 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1765 lldb_private::MemoryRegionInfo ®ion_info)
1768 region_info.Clear();
1770 if (m_supports_memory_region_info != eLazyBoolNo)
1772 m_supports_memory_region_info = eLazyBoolYes;
1774 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1775 assert (packet_len < (int)sizeof(packet));
1776 StringExtractorGDBRemote response;
1777 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1782 bool success = true;
1783 bool saw_permissions = false;
1784 while (success && response.GetNameColonValue(name, value))
1786 if (name.compare ("start") == 0)
1788 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1790 region_info.GetRange().SetRangeBase(addr_value);
1792 else if (name.compare ("size") == 0)
1794 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1796 region_info.GetRange().SetByteSize (addr_value);
1798 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1800 saw_permissions = true;
1801 if (region_info.GetRange().Contains (addr))
1803 if (value.find('r') != std::string::npos)
1804 region_info.SetReadable (MemoryRegionInfo::eYes);
1806 region_info.SetReadable (MemoryRegionInfo::eNo);
1808 if (value.find('w') != std::string::npos)
1809 region_info.SetWritable (MemoryRegionInfo::eYes);
1811 region_info.SetWritable (MemoryRegionInfo::eNo);
1813 if (value.find('x') != std::string::npos)
1814 region_info.SetExecutable (MemoryRegionInfo::eYes);
1816 region_info.SetExecutable (MemoryRegionInfo::eNo);
1820 // The reported region does not contain this address -- we're looking at an unmapped page
1821 region_info.SetReadable (MemoryRegionInfo::eNo);
1822 region_info.SetWritable (MemoryRegionInfo::eNo);
1823 region_info.SetExecutable (MemoryRegionInfo::eNo);
1826 else if (name.compare ("error") == 0)
1828 StringExtractorGDBRemote name_extractor;
1829 // Swap "value" over into "name_extractor"
1830 name_extractor.GetStringRef().swap(value);
1831 // Now convert the HEX bytes into a string value
1832 name_extractor.GetHexByteString (value);
1833 error.SetErrorString(value.c_str());
1837 // We got a valid address range back but no permissions -- which means this is an unmapped page
1838 if (region_info.GetRange().IsValid() && saw_permissions == false)
1840 region_info.SetReadable (MemoryRegionInfo::eNo);
1841 region_info.SetWritable (MemoryRegionInfo::eNo);
1842 region_info.SetExecutable (MemoryRegionInfo::eNo);
1847 m_supports_memory_region_info = eLazyBoolNo;
1851 if (m_supports_memory_region_info == eLazyBoolNo)
1853 error.SetErrorString("qMemoryRegionInfo is not supported");
1856 region_info.Clear();
1862 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1866 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1868 num = m_num_supported_hardware_watchpoints;
1872 // Set num to 0 first.
1874 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1877 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1878 assert (packet_len < (int)sizeof(packet));
1879 StringExtractorGDBRemote response;
1880 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1882 m_supports_watchpoint_support_info = eLazyBoolYes;
1885 while (response.GetNameColonValue(name, value))
1887 if (name.compare ("num") == 0)
1889 num = Args::StringToUInt32(value.c_str(), 0, 0);
1890 m_num_supported_hardware_watchpoints = num;
1896 m_supports_watchpoint_support_info = eLazyBoolNo;
1900 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1902 error.SetErrorString("qWatchpointSupportInfo is not supported");
1909 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1911 Error error(GetWatchpointSupportInfo(num));
1912 if (error.Success())
1913 error = GetWatchpointsTriggerAfterInstruction(after);
1918 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1922 // we assume watchpoints will happen after running the relevant opcode
1923 // and we only want to override this behavior if we have explicitly
1924 // received a qHostInfo telling us otherwise
1925 if (m_qHostInfo_is_valid != eLazyBoolYes)
1928 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1933 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1935 if (path && path[0])
1937 StreamString packet;
1938 packet.PutCString("QSetSTDIN:");
1939 packet.PutBytesAsRawHex8(path, strlen(path));
1941 StringExtractorGDBRemote response;
1942 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1944 if (response.IsOKResponse())
1946 uint8_t error = response.GetError();
1955 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1957 if (path && path[0])
1959 StreamString packet;
1960 packet.PutCString("QSetSTDOUT:");
1961 packet.PutBytesAsRawHex8(path, strlen(path));
1963 StringExtractorGDBRemote response;
1964 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1966 if (response.IsOKResponse())
1968 uint8_t error = response.GetError();
1977 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1979 if (path && path[0])
1981 StreamString packet;
1982 packet.PutCString("QSetSTDERR:");
1983 packet.PutBytesAsRawHex8(path, strlen(path));
1985 StringExtractorGDBRemote response;
1986 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1988 if (response.IsOKResponse())
1990 uint8_t error = response.GetError();
1999 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2001 StringExtractorGDBRemote response;
2002 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
2004 if (response.IsUnsupportedResponse())
2006 if (response.IsErrorResponse())
2008 response.GetHexByteString (cwd);
2009 return !cwd.empty();
2015 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2017 if (path && path[0])
2019 StreamString packet;
2020 packet.PutCString("QSetWorkingDir:");
2021 packet.PutBytesAsRawHex8(path, strlen(path));
2023 StringExtractorGDBRemote response;
2024 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2026 if (response.IsOKResponse())
2028 uint8_t error = response.GetError();
2037 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2040 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
2041 assert (packet_len < (int)sizeof(packet));
2042 StringExtractorGDBRemote response;
2043 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2045 if (response.IsOKResponse())
2047 uint8_t error = response.GetError();
2055 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
2057 if (response.IsNormalResponse())
2061 StringExtractor extractor;
2063 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2066 std::string os_type;
2068 while (response.GetNameColonValue(name, value))
2070 if (name.compare("pid") == 0)
2072 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2074 else if (name.compare("ppid") == 0)
2076 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2078 else if (name.compare("uid") == 0)
2080 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2082 else if (name.compare("euid") == 0)
2084 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2086 else if (name.compare("gid") == 0)
2088 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2090 else if (name.compare("egid") == 0)
2092 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2094 else if (name.compare("triple") == 0)
2096 // The triple comes as ASCII hex bytes since it contains '-' chars
2097 extractor.GetStringRef().swap(value);
2098 extractor.SetFilePos(0);
2099 extractor.GetHexByteString (value);
2100 process_info.GetArchitecture ().SetTriple (value.c_str());
2102 else if (name.compare("name") == 0)
2104 StringExtractor extractor;
2105 // The process name from ASCII hex bytes since we can't
2106 // control the characters in a process name
2107 extractor.GetStringRef().swap(value);
2108 extractor.SetFilePos(0);
2109 extractor.GetHexByteString (value);
2110 process_info.GetExecutableFile().SetFile (value.c_str(), false);
2112 else if (name.compare("cputype") == 0)
2114 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2116 else if (name.compare("cpusubtype") == 0)
2118 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2120 else if (name.compare("vendor") == 0)
2124 else if (name.compare("ostype") == 0)
2130 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2132 if (vendor == "apple")
2134 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2135 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2136 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2140 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2147 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
2149 process_info.Clear();
2151 if (m_supports_qProcessInfoPID)
2154 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
2155 assert (packet_len < (int)sizeof(packet));
2156 StringExtractorGDBRemote response;
2157 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2159 return DecodeProcessInfoResponse (response, process_info);
2163 m_supports_qProcessInfoPID = false;
2171 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2173 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2175 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2180 StringExtractorGDBRemote response;
2181 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
2183 if (response.IsNormalResponse())
2187 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2189 std::string arch_name;
2190 std::string os_name;
2191 std::string vendor_name;
2193 uint32_t pointer_byte_size = 0;
2194 StringExtractor extractor;
2195 ByteOrder byte_order = eByteOrderInvalid;
2196 uint32_t num_keys_decoded = 0;
2197 while (response.GetNameColonValue(name, value))
2199 if (name.compare("cputype") == 0)
2201 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2202 if (cpu != LLDB_INVALID_CPUTYPE)
2205 else if (name.compare("cpusubtype") == 0)
2207 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2211 else if (name.compare("ostype") == 0)
2213 os_name.swap (value);
2216 else if (name.compare("vendor") == 0)
2218 vendor_name.swap(value);
2221 else if (name.compare("endian") == 0)
2224 if (value.compare("little") == 0)
2225 byte_order = eByteOrderLittle;
2226 else if (value.compare("big") == 0)
2227 byte_order = eByteOrderBig;
2228 else if (value.compare("pdp") == 0)
2229 byte_order = eByteOrderPDP;
2233 else if (name.compare("ptrsize") == 0)
2235 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2236 if (pointer_byte_size != 0)
2240 if (num_keys_decoded > 0)
2241 m_qProcessInfo_is_valid = eLazyBoolYes;
2242 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2244 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2245 if (pointer_byte_size)
2247 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2249 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2250 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2257 m_qProcessInfo_is_valid = eLazyBoolNo;
2265 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2266 ProcessInstanceInfoList &process_infos)
2268 process_infos.Clear();
2270 if (m_supports_qfProcessInfo)
2272 StreamString packet;
2273 packet.PutCString ("qfProcessInfo");
2274 if (!match_info.MatchAllProcesses())
2276 packet.PutChar (':');
2277 const char *name = match_info.GetProcessInfo().GetName();
2278 bool has_name_match = false;
2279 if (name && name[0])
2281 has_name_match = true;
2282 NameMatchType name_match_type = match_info.GetNameMatchType();
2283 switch (name_match_type)
2285 case eNameMatchIgnore:
2286 has_name_match = false;
2289 case eNameMatchEquals:
2290 packet.PutCString ("name_match:equals;");
2293 case eNameMatchContains:
2294 packet.PutCString ("name_match:contains;");
2297 case eNameMatchStartsWith:
2298 packet.PutCString ("name_match:starts_with;");
2301 case eNameMatchEndsWith:
2302 packet.PutCString ("name_match:ends_with;");
2305 case eNameMatchRegularExpression:
2306 packet.PutCString ("name_match:regex;");
2311 packet.PutCString ("name:");
2312 packet.PutBytesAsRawHex8(name, ::strlen(name));
2313 packet.PutChar (';');
2317 if (match_info.GetProcessInfo().ProcessIDIsValid())
2318 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
2319 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2320 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
2321 if (match_info.GetProcessInfo().UserIDIsValid())
2322 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2323 if (match_info.GetProcessInfo().GroupIDIsValid())
2324 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
2325 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2326 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2327 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2328 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2329 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2330 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2331 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2333 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2334 const llvm::Triple &triple = match_arch.GetTriple();
2335 packet.PutCString("triple:");
2336 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2337 packet.PutChar (';');
2340 StringExtractorGDBRemote response;
2341 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2345 ProcessInstanceInfo process_info;
2346 if (!DecodeProcessInfoResponse (response, process_info))
2348 process_infos.Append(process_info);
2349 response.GetStringRef().clear();
2350 response.SetFilePos(0);
2351 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
2355 m_supports_qfProcessInfo = false;
2359 return process_infos.GetSize();
2364 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2366 if (m_supports_qUserName)
2369 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2370 assert (packet_len < (int)sizeof(packet));
2371 StringExtractorGDBRemote response;
2372 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2374 if (response.IsNormalResponse())
2376 // Make sure we parsed the right number of characters. The response is
2377 // the hex encoded user name and should make up the entire packet.
2378 // If there are any non-hex ASCII bytes, the length won't match below..
2379 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2385 m_supports_qUserName = false;
2394 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2396 if (m_supports_qGroupName)
2399 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2400 assert (packet_len < (int)sizeof(packet));
2401 StringExtractorGDBRemote response;
2402 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2404 if (response.IsNormalResponse())
2406 // Make sure we parsed the right number of characters. The response is
2407 // the hex encoded group name and should make up the entire packet.
2408 // If there are any non-hex ASCII bytes, the length won't match below..
2409 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2415 m_supports_qGroupName = false;
2423 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2426 TimeValue start_time, end_time;
2427 uint64_t total_time_nsec;
2428 if (SendSpeedTestPacket (0, 0))
2430 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2431 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 };
2432 const size_t k_num_send_sizes = sizeof(g_send_sizes)/sizeof(uint32_t);
2433 const size_t k_num_recv_sizes = sizeof(g_recv_sizes)/sizeof(uint32_t);
2434 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2435 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
2437 const uint32_t send_size = g_send_sizes[send_idx];
2438 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
2440 const uint32_t recv_size = g_recv_sizes[recv_idx];
2441 StreamString packet;
2442 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2443 uint32_t bytes_left = send_size;
2444 while (bytes_left > 0)
2446 if (bytes_left >= 26)
2448 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2453 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2458 start_time = TimeValue::Now();
2461 for (i=0; i<num_packets; ++i)
2463 StringExtractorGDBRemote response;
2464 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2469 uint32_t bytes_read = 0;
2470 while (bytes_read < k_recv_amount)
2472 StringExtractorGDBRemote response;
2473 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2474 bytes_read += recv_size;
2477 end_time = TimeValue::Now();
2478 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2481 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2482 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2486 total_time_nsec / TimeValue::NanoSecPerSec,
2487 total_time_nsec % TimeValue::NanoSecPerSec,
2488 packets_per_second);
2492 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2493 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2497 total_time_nsec / TimeValue::NanoSecPerSec,
2498 total_time_nsec % TimeValue::NanoSecPerSec,
2507 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2509 StreamString packet;
2510 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2511 uint32_t bytes_left = send_size;
2512 while (bytes_left > 0)
2514 if (bytes_left >= 26)
2516 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2521 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2526 StringExtractorGDBRemote response;
2527 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
2531 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
2533 pid = LLDB_INVALID_PROCESS_ID;
2534 StringExtractorGDBRemote response;
2535 StreamString stream;
2536 stream.PutCString("qLaunchGDBServer;");
2537 std::string hostname;
2538 if (remote_accept_hostname && remote_accept_hostname[0])
2539 hostname = remote_accept_hostname;
2542 if (Host::GetHostname (hostname))
2544 // Make the GDB server we launch only accept connections from this host
2545 stream.Printf("host:%s;", hostname.c_str());
2549 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2550 stream.Printf("host:*;");
2553 const char *packet = stream.GetData();
2554 int packet_len = stream.GetSize();
2556 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2561 while (response.GetNameColonValue(name, value))
2563 if (name.compare("port") == 0)
2564 port = Args::StringToUInt32(value.c_str(), 0, 0);
2565 else if (name.compare("pid") == 0)
2566 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2574 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2576 StreamString stream;
2577 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2578 const char *packet = stream.GetData();
2579 int packet_len = stream.GetSize();
2581 StringExtractorGDBRemote response;
2582 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2584 if (response.IsOKResponse())
2591 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2593 if (m_curr_tid == tid)
2598 if (tid == UINT64_MAX)
2599 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2601 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2602 assert (packet_len + 1 < (int)sizeof(packet));
2603 StringExtractorGDBRemote response;
2604 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2606 if (response.IsOKResponse())
2616 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2618 if (m_curr_tid_run == tid)
2623 if (tid == UINT64_MAX)
2624 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2626 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2628 assert (packet_len + 1 < (int)sizeof(packet));
2629 StringExtractorGDBRemote response;
2630 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2632 if (response.IsOKResponse())
2634 m_curr_tid_run = tid;
2642 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2644 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
2645 return response.IsNormalResponse();
2650 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2652 if (m_supports_qThreadStopInfo)
2655 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2656 assert (packet_len < (int)sizeof(packet));
2657 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2659 if (response.IsUnsupportedResponse())
2660 m_supports_qThreadStopInfo = false;
2661 else if (response.IsNormalResponse())
2668 m_supports_qThreadStopInfo = false;
2676 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2678 // Check if the stub is known not to support this breakpoint type
2679 if (!SupportsGDBStoppointPacket(type))
2681 // Construct the breakpoint packet
2683 const int packet_len = ::snprintf (packet,
2685 "%c%i,%" PRIx64 ",%x",
2690 // Check we havent overwritten the end of the packet buffer
2691 assert (packet_len + 1 < (int)sizeof(packet));
2692 StringExtractorGDBRemote response;
2693 // Try to send the breakpoint packet, and check that it was correctly sent
2694 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
2696 // Receive and OK packet when the breakpoint successfully placed
2697 if (response.IsOKResponse())
2700 // Error while setting breakpoint, send back specific error
2701 if (response.IsErrorResponse())
2702 return response.GetError();
2704 // Empty packet informs us that breakpoint is not supported
2705 if (response.IsUnsupportedResponse())
2707 // Disable this breakpoint type since it is unsupported
2710 case eBreakpointSoftware: m_supports_z0 = false; break;
2711 case eBreakpointHardware: m_supports_z1 = false; break;
2712 case eWatchpointWrite: m_supports_z2 = false; break;
2713 case eWatchpointRead: m_supports_z3 = false; break;
2714 case eWatchpointReadWrite: m_supports_z4 = false; break;
2718 // Signal generic faliure
2723 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2724 bool &sequence_mutex_unavailable)
2726 Mutex::Locker locker;
2729 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2731 sequence_mutex_unavailable = false;
2732 StringExtractorGDBRemote response;
2734 PacketResult packet_result;
2735 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2736 packet_result == PacketResult::Success && response.IsNormalResponse();
2737 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
2739 char ch = response.GetChar();
2746 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2748 if (tid != LLDB_INVALID_THREAD_ID)
2750 thread_ids.push_back (tid);
2752 ch = response.GetChar(); // Skip the command separator
2753 } while (ch == ','); // Make sure we got a comma separator
2759 #if defined (LLDB_CONFIGURATION_DEBUG)
2760 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2762 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2764 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
2766 sequence_mutex_unavailable = true;
2768 return thread_ids.size();
2772 GDBRemoteCommunicationClient::GetShlibInfoAddr()
2776 StringExtractorGDBRemote response;
2777 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
2779 if (response.IsNormalResponse())
2780 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2783 return LLDB_INVALID_ADDRESS;
2787 GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2788 const char *working_dir, // Pass NULL to use the current working directory
2789 int *status_ptr, // Pass NULL if you don't want the process exit status
2790 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2791 std::string *command_output, // Pass NULL if you don't want the command output
2792 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2794 lldb_private::StreamString stream;
2795 stream.PutCString("qPlatform_shell:");
2796 stream.PutBytesAsRawHex8(command, strlen(command));
2797 stream.PutChar(',');
2798 stream.PutHex32(timeout_sec);
2799 if (working_dir && *working_dir)
2801 stream.PutChar(',');
2802 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2804 const char *packet = stream.GetData();
2805 int packet_len = stream.GetSize();
2806 StringExtractorGDBRemote response;
2807 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2809 if (response.GetChar() != 'F')
2810 return Error("malformed reply");
2811 if (response.GetChar() != ',')
2812 return Error("malformed reply");
2813 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2814 if (exitcode == UINT32_MAX)
2815 return Error("unable to run remote process");
2816 else if (status_ptr)
2817 *status_ptr = exitcode;
2818 if (response.GetChar() != ',')
2819 return Error("malformed reply");
2820 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2823 if (response.GetChar() != ',')
2824 return Error("malformed reply");
2826 response.GetEscapedBinaryData(output);
2828 command_output->assign(output);
2831 return Error("unable to send packet");
2835 GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2836 uint32_t file_permissions)
2838 lldb_private::StreamString stream;
2839 stream.PutCString("qPlatform_mkdir:");
2840 stream.PutHex32(file_permissions);
2841 stream.PutChar(',');
2842 stream.PutBytesAsRawHex8(path, strlen(path));
2843 const char *packet = stream.GetData();
2844 int packet_len = stream.GetSize();
2845 StringExtractorGDBRemote response;
2846 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2848 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2855 GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2856 uint32_t file_permissions)
2858 lldb_private::StreamString stream;
2859 stream.PutCString("qPlatform_chmod:");
2860 stream.PutHex32(file_permissions);
2861 stream.PutChar(',');
2862 stream.PutBytesAsRawHex8(path, strlen(path));
2863 const char *packet = stream.GetData();
2864 int packet_len = stream.GetSize();
2865 StringExtractorGDBRemote response;
2866 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2868 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2875 ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2876 uint64_t fail_result,
2879 response.SetFilePos(0);
2880 if (response.GetChar() != 'F')
2882 int32_t result = response.GetS32 (-2);
2885 if (response.GetChar() == ',')
2887 int result_errno = response.GetS32 (-2);
2888 if (result_errno != -2)
2889 error.SetError(result_errno, eErrorTypePOSIX);
2891 error.SetError(-1, eErrorTypeGeneric);
2898 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2903 lldb_private::StreamString stream;
2904 stream.PutCString("vFile:open:");
2905 std::string path (file_spec.GetPath());
2908 stream.PutCStringAsRawHex8(path.c_str());
2909 stream.PutChar(',');
2910 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2911 stream.PutHex32(posix_open_flags);
2912 stream.PutChar(',');
2913 stream.PutHex32(mode);
2914 const char* packet = stream.GetData();
2915 int packet_len = stream.GetSize();
2916 StringExtractorGDBRemote response;
2917 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2919 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2925 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2928 lldb_private::StreamString stream;
2929 stream.Printf("vFile:close:%i", (int)fd);
2930 const char* packet = stream.GetData();
2931 int packet_len = stream.GetSize();
2932 StringExtractorGDBRemote response;
2933 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2935 return ParseHostIOPacketResponse (response, -1, error) == 0;
2940 // Extension of host I/O packets to get the file size.
2942 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2944 lldb_private::StreamString stream;
2945 stream.PutCString("vFile:size:");
2946 std::string path (file_spec.GetPath());
2947 stream.PutCStringAsRawHex8(path.c_str());
2948 const char* packet = stream.GetData();
2949 int packet_len = stream.GetSize();
2950 StringExtractorGDBRemote response;
2951 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2953 if (response.GetChar() != 'F')
2955 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2962 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
2965 lldb_private::StreamString stream;
2966 stream.PutCString("vFile:mode:");
2967 stream.PutCStringAsRawHex8(path);
2968 const char* packet = stream.GetData();
2969 int packet_len = stream.GetSize();
2970 StringExtractorGDBRemote response;
2971 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2973 if (response.GetChar() != 'F')
2975 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2979 const uint32_t mode = response.GetS32(-1);
2982 if (response.GetChar() == ',')
2984 int response_errno = response.GetS32(-1);
2985 if (response_errno > 0)
2986 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2988 error.SetErrorToGenericError();
2991 error.SetErrorToGenericError();
2995 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3001 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3007 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3013 lldb_private::StreamString stream;
3014 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3015 const char* packet = stream.GetData();
3016 int packet_len = stream.GetSize();
3017 StringExtractorGDBRemote response;
3018 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3020 if (response.GetChar() != 'F')
3022 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3023 if (retcode == UINT32_MAX)
3025 const char next = (response.Peek() ? *response.Peek() : 0);
3030 response.GetChar(); // skip the semicolon
3032 if (response.GetEscapedBinaryData(buffer))
3034 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3035 if (data_to_write > 0)
3036 memcpy(dst, &buffer[0], data_to_write);
3037 return data_to_write;
3045 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3051 lldb_private::StreamGDBRemote stream;
3052 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3053 stream.PutEscapedBytes(src, src_len);
3054 const char* packet = stream.GetData();
3055 int packet_len = stream.GetSize();
3056 StringExtractorGDBRemote response;
3057 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3059 if (response.GetChar() != 'F')
3061 error.SetErrorStringWithFormat("write file failed");
3064 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3065 if (bytes_written == UINT64_MAX)
3067 error.SetErrorToGenericError();
3068 if (response.GetChar() == ',')
3070 int response_errno = response.GetS32(-1);
3071 if (response_errno > 0)
3072 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3076 return bytes_written;
3080 error.SetErrorString ("failed to send vFile:pwrite packet");
3086 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3089 lldb_private::StreamGDBRemote stream;
3090 stream.PutCString("vFile:symlink:");
3091 // the unix symlink() command reverses its parameters where the dst if first,
3092 // so we follow suit here
3093 stream.PutCStringAsRawHex8(dst);
3094 stream.PutChar(',');
3095 stream.PutCStringAsRawHex8(src);
3096 const char* packet = stream.GetData();
3097 int packet_len = stream.GetSize();
3098 StringExtractorGDBRemote response;
3099 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3101 if (response.GetChar() == 'F')
3103 uint32_t result = response.GetU32(UINT32_MAX);
3106 error.SetErrorToGenericError();
3107 if (response.GetChar() == ',')
3109 int response_errno = response.GetS32(-1);
3110 if (response_errno > 0)
3111 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3117 // Should have returned with 'F<result>[,<errno>]'
3118 error.SetErrorStringWithFormat("symlink failed");
3123 error.SetErrorString ("failed to send vFile:symlink packet");
3129 GDBRemoteCommunicationClient::Unlink (const char *path)
3132 lldb_private::StreamGDBRemote stream;
3133 stream.PutCString("vFile:unlink:");
3134 // the unix symlink() command reverses its parameters where the dst if first,
3135 // so we follow suit here
3136 stream.PutCStringAsRawHex8(path);
3137 const char* packet = stream.GetData();
3138 int packet_len = stream.GetSize();
3139 StringExtractorGDBRemote response;
3140 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3142 if (response.GetChar() == 'F')
3144 uint32_t result = response.GetU32(UINT32_MAX);
3147 error.SetErrorToGenericError();
3148 if (response.GetChar() == ',')
3150 int response_errno = response.GetS32(-1);
3151 if (response_errno > 0)
3152 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3158 // Should have returned with 'F<result>[,<errno>]'
3159 error.SetErrorStringWithFormat("unlink failed");
3164 error.SetErrorString ("failed to send vFile:unlink packet");
3169 // Extension of host I/O packets to get whether a file exists.
3171 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3173 lldb_private::StreamString stream;
3174 stream.PutCString("vFile:exists:");
3175 std::string path (file_spec.GetPath());
3176 stream.PutCStringAsRawHex8(path.c_str());
3177 const char* packet = stream.GetData();
3178 int packet_len = stream.GetSize();
3179 StringExtractorGDBRemote response;
3180 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3182 if (response.GetChar() != 'F')
3184 if (response.GetChar() != ',')
3186 bool retcode = (response.GetChar() != '0');
3193 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3197 lldb_private::StreamString stream;
3198 stream.PutCString("vFile:MD5:");
3199 std::string path (file_spec.GetPath());
3200 stream.PutCStringAsRawHex8(path.c_str());
3201 const char* packet = stream.GetData();
3202 int packet_len = stream.GetSize();
3203 StringExtractorGDBRemote response;
3204 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3206 if (response.GetChar() != 'F')
3208 if (response.GetChar() != ',')
3210 if (response.Peek() && *response.Peek() == 'x')
3212 low = response.GetHexMaxU64(false, UINT64_MAX);
3213 high = response.GetHexMaxU64(false, UINT64_MAX);
3220 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3222 Mutex::Locker locker;
3223 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3225 const bool thread_suffix_supported = GetThreadSuffixSupported();
3227 if (thread_suffix_supported || SetCurrentThread(tid))
3231 if (thread_suffix_supported)
3232 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3234 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3235 assert (packet_len < ((int)sizeof(packet) - 1));
3236 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3245 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3247 Mutex::Locker locker;
3248 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3250 const bool thread_suffix_supported = GetThreadSuffixSupported();
3252 if (thread_suffix_supported || SetCurrentThread(tid))
3256 // Get all registers in one packet
3257 if (thread_suffix_supported)
3258 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3260 packet_len = ::snprintf (packet, sizeof(packet), "g");
3261 assert (packet_len < ((int)sizeof(packet) - 1));
3262 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
3268 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3270 save_id = 0; // Set to invalid save ID
3271 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3274 m_supports_QSaveRegisterState = eLazyBoolYes;
3275 Mutex::Locker locker;
3276 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3278 const bool thread_suffix_supported = GetThreadSuffixSupported();
3279 if (thread_suffix_supported || SetCurrentThread(tid))
3282 if (thread_suffix_supported)
3283 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3285 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3287 StringExtractorGDBRemote response;
3289 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3291 if (response.IsUnsupportedResponse())
3293 // This packet isn't supported, don't try calling it again
3294 m_supports_QSaveRegisterState = eLazyBoolNo;
3297 const uint32_t response_save_id = response.GetU32(0);
3298 if (response_save_id != 0)
3300 save_id = response_save_id;
3310 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3312 // We use the "m_supports_QSaveRegisterState" variable here becuase the
3313 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3314 // order to be useful
3315 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3318 Mutex::Locker locker;
3319 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3321 const bool thread_suffix_supported = GetThreadSuffixSupported();
3322 if (thread_suffix_supported || SetCurrentThread(tid))
3325 if (thread_suffix_supported)
3326 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3328 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3330 StringExtractorGDBRemote response;
3332 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
3334 if (response.IsOKResponse())
3338 else if (response.IsUnsupportedResponse())
3340 // This packet isn't supported, don't try calling this packet or
3341 // QSaveRegisterState again...
3342 m_supports_QSaveRegisterState = eLazyBoolNo;