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"
17 // Other libraries and framework includes
18 #include "llvm/ADT/Triple.h"
19 #include "lldb/Interpreter/Args.h"
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/Endian.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/TimeValue.h"
29 #include "Utility/StringExtractorGDBRemote.h"
30 #include "ProcessGDBRemote.h"
31 #include "ProcessGDBRemoteLog.h"
34 using namespace lldb_private;
36 //----------------------------------------------------------------------
37 // GDBRemoteCommunicationClient constructor
38 //----------------------------------------------------------------------
39 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
40 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
41 m_supports_not_sending_acks (eLazyBoolCalculate),
42 m_supports_thread_suffix (eLazyBoolCalculate),
43 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
44 m_supports_vCont_all (eLazyBoolCalculate),
45 m_supports_vCont_any (eLazyBoolCalculate),
46 m_supports_vCont_c (eLazyBoolCalculate),
47 m_supports_vCont_C (eLazyBoolCalculate),
48 m_supports_vCont_s (eLazyBoolCalculate),
49 m_supports_vCont_S (eLazyBoolCalculate),
50 m_qHostInfo_is_valid (eLazyBoolCalculate),
51 m_qProcessInfo_is_valid (eLazyBoolCalculate),
52 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
53 m_supports_memory_region_info (eLazyBoolCalculate),
54 m_supports_watchpoint_support_info (eLazyBoolCalculate),
55 m_supports_detach_stay_stopped (eLazyBoolCalculate),
56 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
57 m_attach_or_wait_reply(eLazyBoolCalculate),
58 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
59 m_supports_qProcessInfoPID (true),
60 m_supports_qfProcessInfo (true),
61 m_supports_qUserName (true),
62 m_supports_qGroupName (true),
63 m_supports_qThreadStopInfo (true),
69 m_curr_tid (LLDB_INVALID_THREAD_ID),
70 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
71 m_num_supported_hardware_watchpoints (0),
72 m_async_mutex (Mutex::eMutexTypeRecursive),
73 m_async_packet_predicate (false),
77 m_thread_id_to_used_usec_map (),
80 m_os_version_major (UINT32_MAX),
81 m_os_version_minor (UINT32_MAX),
82 m_os_version_update (UINT32_MAX)
86 //----------------------------------------------------------------------
88 //----------------------------------------------------------------------
89 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
96 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
98 // Start the read thread after we send the handshake ack since if we
99 // fail to send the handshake ack, there is no reason to continue...
104 error_ptr->SetErrorString("failed to send the handshake ack");
109 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
111 if (m_supports_not_sending_acks == eLazyBoolCalculate)
114 m_supports_not_sending_acks = eLazyBoolNo;
116 StringExtractorGDBRemote response;
117 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
119 if (response.IsOKResponse())
122 m_supports_not_sending_acks = eLazyBoolYes;
129 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
131 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
133 m_supports_threads_in_stop_reply = eLazyBoolNo;
135 StringExtractorGDBRemote response;
136 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
138 if (response.IsOKResponse())
139 m_supports_threads_in_stop_reply = eLazyBoolYes;
145 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
147 if (m_attach_or_wait_reply == eLazyBoolCalculate)
149 m_attach_or_wait_reply = eLazyBoolNo;
151 StringExtractorGDBRemote response;
152 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
154 if (response.IsOKResponse())
155 m_attach_or_wait_reply = eLazyBoolYes;
158 if (m_attach_or_wait_reply == eLazyBoolYes)
165 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
167 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
169 m_prepare_for_reg_writing_reply = eLazyBoolNo;
171 StringExtractorGDBRemote response;
172 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
174 if (response.IsOKResponse())
175 m_prepare_for_reg_writing_reply = eLazyBoolYes;
178 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
186 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
188 m_supports_not_sending_acks = eLazyBoolCalculate;
189 m_supports_thread_suffix = eLazyBoolCalculate;
190 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
191 m_supports_vCont_c = eLazyBoolCalculate;
192 m_supports_vCont_C = eLazyBoolCalculate;
193 m_supports_vCont_s = eLazyBoolCalculate;
194 m_supports_vCont_S = eLazyBoolCalculate;
195 m_qHostInfo_is_valid = eLazyBoolCalculate;
196 m_qProcessInfo_is_valid = eLazyBoolCalculate;
197 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
198 m_supports_memory_region_info = eLazyBoolCalculate;
199 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
200 m_attach_or_wait_reply = eLazyBoolCalculate;
202 m_supports_qProcessInfoPID = true;
203 m_supports_qfProcessInfo = true;
204 m_supports_qUserName = true;
205 m_supports_qGroupName = true;
206 m_supports_qThreadStopInfo = true;
207 m_supports_z0 = true;
208 m_supports_z1 = true;
209 m_supports_z2 = true;
210 m_supports_z3 = true;
211 m_supports_z4 = true;
213 m_process_arch.Clear();
218 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
220 if (m_supports_thread_suffix == eLazyBoolCalculate)
222 StringExtractorGDBRemote response;
223 m_supports_thread_suffix = eLazyBoolNo;
224 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
226 if (response.IsOKResponse())
227 m_supports_thread_suffix = eLazyBoolYes;
230 return m_supports_thread_suffix;
233 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
235 if (m_supports_vCont_c == eLazyBoolCalculate)
237 StringExtractorGDBRemote response;
238 m_supports_vCont_any = eLazyBoolNo;
239 m_supports_vCont_all = eLazyBoolNo;
240 m_supports_vCont_c = eLazyBoolNo;
241 m_supports_vCont_C = eLazyBoolNo;
242 m_supports_vCont_s = eLazyBoolNo;
243 m_supports_vCont_S = eLazyBoolNo;
244 if (SendPacketAndWaitForResponse("vCont?", response, false))
246 const char *response_cstr = response.GetStringRef().c_str();
247 if (::strstr (response_cstr, ";c"))
248 m_supports_vCont_c = eLazyBoolYes;
250 if (::strstr (response_cstr, ";C"))
251 m_supports_vCont_C = eLazyBoolYes;
253 if (::strstr (response_cstr, ";s"))
254 m_supports_vCont_s = eLazyBoolYes;
256 if (::strstr (response_cstr, ";S"))
257 m_supports_vCont_S = eLazyBoolYes;
259 if (m_supports_vCont_c == eLazyBoolYes &&
260 m_supports_vCont_C == eLazyBoolYes &&
261 m_supports_vCont_s == eLazyBoolYes &&
262 m_supports_vCont_S == eLazyBoolYes)
264 m_supports_vCont_all = eLazyBoolYes;
267 if (m_supports_vCont_c == eLazyBoolYes ||
268 m_supports_vCont_C == eLazyBoolYes ||
269 m_supports_vCont_s == eLazyBoolYes ||
270 m_supports_vCont_S == eLazyBoolYes)
272 m_supports_vCont_any = eLazyBoolYes;
279 case 'a': return m_supports_vCont_any;
280 case 'A': return m_supports_vCont_all;
281 case 'c': return m_supports_vCont_c;
282 case 'C': return m_supports_vCont_C;
283 case 's': return m_supports_vCont_s;
284 case 'S': return m_supports_vCont_S;
292 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
295 StringExtractorGDBRemote &response,
299 return SendPacketAndWaitForResponse (payload,
306 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
309 size_t payload_length,
310 StringExtractorGDBRemote &response,
314 Mutex::Locker locker;
315 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
316 size_t response_len = 0;
317 if (GetSequenceMutex (locker))
319 if (SendPacketNoLock (payload, payload_length))
320 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
324 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
333 Mutex::Locker async_locker (m_async_mutex);
334 m_async_packet.assign(payload, payload_length);
335 m_async_packet_predicate.SetValue (true, eBroadcastNever);
338 log->Printf ("async: async packet = %s", m_async_packet.c_str());
340 bool timed_out = false;
341 if (SendInterrupt(locker, 2, timed_out))
343 if (m_interrupt_sent)
345 m_interrupt_sent = false;
346 TimeValue timeout_time;
347 timeout_time = TimeValue::Now();
348 timeout_time.OffsetWithSeconds (m_packet_timeout);
351 log->Printf ("async: sent interrupt");
353 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
356 log->Printf ("async: got response");
358 // Swap the response buffer to avoid malloc and string copy
359 response.GetStringRef().swap (m_async_response.GetStringRef());
360 response_len = response.GetStringRef().size();
365 log->Printf ("async: timed out waiting for response");
368 // Make sure we wait until the continue packet has been sent again...
369 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
374 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
376 log->Printf ("async: async packet sent");
382 log->Printf ("async: timed out waiting for process to resume");
387 // We had a racy condition where we went to send the interrupt
388 // yet we were able to get the lock, so the process must have
391 log->Printf ("async: got lock without sending interrupt");
392 // Send the packet normally since we got the lock
393 if (SendPacketNoLock (payload, payload_length))
394 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
398 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
405 log->Printf ("async: failed to interrupt");
411 log->Printf ("async: not running, async is ignored");
417 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
420 if (response_len == 0)
423 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
428 static const char *end_delimiter = "--end--;";
429 static const int end_delimiter_len = 8;
432 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
433 ( ProcessGDBRemote *process,
434 StringExtractorGDBRemote& profileDataExtractor
437 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
438 std::stringstream final_output;
439 std::string name, value;
441 // Going to assuming thread_used_usec comes first, else bail out.
442 while (profileDataExtractor.GetNameColonValue(name, value))
444 if (name.compare("thread_used_id") == 0)
446 StringExtractor threadIDHexExtractor(value.c_str());
447 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
449 bool has_used_usec = false;
450 uint32_t curr_used_usec = 0;
451 std::string usec_name, usec_value;
452 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
453 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
455 if (usec_name.compare("thread_used_usec") == 0)
457 has_used_usec = true;
458 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
462 // We didn't find what we want, it is probably
463 // an older version. Bail out.
464 profileDataExtractor.SetFilePos(input_file_pos);
470 uint32_t prev_used_usec = 0;
471 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
472 if (iterator != m_thread_id_to_used_usec_map.end())
474 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
477 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
478 // A good first time record is one that runs for at least 0.25 sec
479 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
480 bool good_subsequent_time = (prev_used_usec > 0) &&
481 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
483 if (good_first_time || good_subsequent_time)
485 // We try to avoid doing too many index id reservation,
486 // resulting in fast increase of index ids.
488 final_output << name << ":";
489 int32_t index_id = process->AssignIndexIDToThread(thread_id);
490 final_output << index_id << ";";
492 final_output << usec_name << ":" << usec_value << ";";
496 // Skip past 'thread_used_name'.
497 std::string local_name, local_value;
498 profileDataExtractor.GetNameColonValue(local_name, local_value);
501 // Store current time as previous time so that they can be compared later.
502 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
506 // Bail out and use old string.
507 final_output << name << ":" << value << ";";
512 final_output << name << ":" << value << ";";
515 final_output << end_delimiter;
516 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
518 return final_output.str();
522 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
524 ProcessGDBRemote *process,
526 size_t packet_length,
527 StringExtractorGDBRemote &response
530 m_curr_tid = LLDB_INVALID_THREAD_ID;
531 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
533 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
535 Mutex::Locker locker(m_sequence_mutex);
536 StateType state = eStateRunning;
538 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
539 m_public_is_running.SetValue (true, eBroadcastNever);
540 // Set the starting continue packet into "continue_packet". This packet
541 // may change if we are interrupted and we continue after an async packet...
542 std::string continue_packet(payload, packet_length);
544 bool got_async_packet = false;
546 while (state == eStateRunning)
548 if (!got_async_packet)
551 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
552 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
553 state = eStateInvalid;
555 m_private_is_running.SetValue (true, eBroadcastAlways);
558 got_async_packet = false;
561 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
563 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
565 if (response.Empty())
566 state = eStateInvalid;
569 const char stop_type = response.GetChar();
571 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
577 if (process->GetStopID() == 0)
579 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
581 lldb::pid_t pid = GetCurrentProcessID ();
582 if (pid != LLDB_INVALID_PROCESS_ID)
583 process->SetID (pid);
585 process->BuildDynamicRegisterInfo (true);
588 // Privately notify any internal threads that we have stopped
589 // in case we wanted to interrupt our process, yet we might
590 // send a packet and continue without returning control to the
592 m_private_is_running.SetValue (false, eBroadcastAlways);
594 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
596 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
597 if (continue_after_async || m_interrupt_sent)
599 // We sent an interrupt packet to stop the inferior process
600 // for an async signal or to send an async packet while running
601 // but we might have been single stepping and received the
602 // stop packet for the step instead of for the interrupt packet.
603 // Typically when an interrupt is sent a SIGINT or SIGSTOP
604 // is used, so if we get anything else, we need to try and
605 // get another stop reply packet that may have been sent
606 // due to sending the interrupt when the target is stopped
607 // which will just re-send a copy of the last stop reply
608 // packet. If we don't do this, then the reply for our
609 // async packet will be the repeat stop reply packet and cause
610 // a lot of trouble for us!
611 if (signo != SIGINT && signo != SIGSTOP)
613 continue_after_async = false;
615 // We didn't get a a SIGINT or SIGSTOP, so try for a
616 // very brief time (1 ms) to get another stop reply
617 // packet to make sure it doesn't get in the way
618 StringExtractorGDBRemote extra_stop_reply_packet;
619 uint32_t timeout_usec = 1000;
620 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
622 switch (extra_stop_reply_packet.GetChar())
626 // We did get an extra stop reply, which means
627 // our interrupt didn't stop the target so we
628 // shouldn't continue after the async signal
629 // or packet is sent...
630 continue_after_async = false;
637 if (m_async_signal != -1)
640 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
642 // Save off the async signal we are supposed to send
643 const int async_signal = m_async_signal;
644 // Clear the async signal member so we don't end up
645 // sending the signal multiple times...
647 // Check which signal we stopped with
648 if (signo == async_signal)
651 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
653 // We already stopped with a signal that we wanted
654 // to stop with, so we are done
658 // We stopped with a different signal that the one
659 // we wanted to stop with, so now we must resume
660 // with the signal we want
661 char signal_packet[32];
662 int signal_packet_len = 0;
663 signal_packet_len = ::snprintf (signal_packet,
664 sizeof (signal_packet),
669 log->Printf ("async: stopped with signal %s, resume with %s",
670 Host::GetSignalAsCString (signo),
671 Host::GetSignalAsCString (async_signal));
673 // Set the continue packet to resume even if the
674 // interrupt didn't cause our stop (ignore continue_after_async)
675 continue_packet.assign(signal_packet, signal_packet_len);
679 else if (m_async_packet_predicate.GetValue())
681 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
683 // We are supposed to send an asynchronous packet while
685 m_async_response.Clear();
686 if (m_async_packet.empty())
689 packet_log->Printf ("async: error: empty async packet");
695 packet_log->Printf ("async: sending packet");
697 SendPacketAndWaitForResponse (&m_async_packet[0],
698 m_async_packet.size(),
702 // Let the other thread that was trying to send the async
703 // packet know that the packet has been sent and response is
705 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
708 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
710 // Set the continue packet to resume if our interrupt
711 // for the async packet did cause the stop
712 if (continue_after_async)
714 // Reverting this for now as it is causing deadlocks
715 // in programs (<rdar://problem/11529853>). In the future
716 // we should check our thread list and "do the right thing"
717 // for new threads that show up while we stop and run async
718 // packets. Setting the packet to 'c' to continue all threads
719 // is the right thing to do 99.99% of the time because if a
720 // thread was single stepping, and we sent an interrupt, we
721 // will notice above that we didn't stop due to an interrupt
722 // but stopped due to stepping and we would _not_ continue.
723 continue_packet.assign (1, 'c');
727 // Stop with signal and thread info
728 state = eStateStopped;
735 state = eStateExited;
741 got_async_packet = true;
742 std::string inferior_stdout;
743 inferior_stdout.reserve(response.GetBytesLeft () / 2);
745 while ((ch = response.GetHexU8()) != '\0')
746 inferior_stdout.append(1, ch);
747 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
752 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
754 got_async_packet = true;
755 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
756 if (m_partial_profile_data.length() > 0)
758 m_partial_profile_data.append(input);
759 input = m_partial_profile_data;
760 m_partial_profile_data.clear();
763 size_t found, pos = 0, len = input.length();
764 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
766 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
767 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
768 process->BroadcastAsyncProfileData (profile_data);
770 pos = found + end_delimiter_len;
775 // Last incomplete chunk.
776 m_partial_profile_data = input.substr(pos);
783 state = eStateInvalid;
788 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
789 state = eStateInvalid;
797 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
798 state = eStateInvalid;
802 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
803 response.SetFilePos(0);
804 m_private_is_running.SetValue (false, eBroadcastAlways);
805 m_public_is_running.SetValue (false, eBroadcastAlways);
810 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
812 Mutex::Locker async_locker (m_async_mutex);
813 m_async_signal = signo;
814 bool timed_out = false;
815 Mutex::Locker locker;
816 if (SendInterrupt (locker, 1, timed_out))
822 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
823 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
824 // (the expected result), then it will send the halt packet. If it does succeed
825 // then the caller that requested the interrupt will want to keep the sequence
826 // locked down so that no one else can send packets while the caller has control.
827 // This function usually gets called when we are running and need to stop the
828 // target. It can also be used when we are running and and we need to do something
829 // else (like read/write memory), so we need to interrupt the running process
830 // (gdb remote protocol requires this), and do what we need to do, then resume.
833 GDBRemoteCommunicationClient::SendInterrupt
835 Mutex::Locker& locker,
836 uint32_t seconds_to_wait_for_stop,
841 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
845 // Only send an interrupt if our debugserver is running...
846 if (GetSequenceMutex (locker))
849 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
853 // Someone has the mutex locked waiting for a response or for the
854 // inferior to stop, so send the interrupt on the down low...
855 char ctrl_c = '\x03';
856 ConnectionStatus status = eConnectionStatusSuccess;
857 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
859 log->PutCString("send packet: \\x03");
860 if (bytes_written > 0)
862 m_interrupt_sent = true;
863 if (seconds_to_wait_for_stop)
866 if (seconds_to_wait_for_stop)
868 timeout = TimeValue::Now();
869 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
871 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
874 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
880 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
886 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
893 log->Printf ("SendInterrupt () - failed to write interrupt");
901 log->Printf ("SendInterrupt () - not running");
907 GDBRemoteCommunicationClient::GetCurrentProcessID ()
909 StringExtractorGDBRemote response;
910 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
912 if (response.GetChar() == 'Q')
913 if (response.GetChar() == 'C')
914 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
916 return LLDB_INVALID_PROCESS_ID;
920 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
923 StringExtractorGDBRemote response;
924 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
926 if (response.IsOKResponse())
928 if (response.GetChar() == 'E')
930 // A string the describes what failed when launching...
931 error_str = response.GetStringRef().substr(1);
935 error_str.assign ("unknown error occurred launching process");
940 error_str.assign ("timed out waiting for app to launch");
946 GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
953 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
955 const int arg_len = strlen(arg);
958 packet.Printf("%i,%i,", arg_len * 2, i);
959 packet.PutBytesAsRawHex8 (arg, arg_len);
962 StringExtractorGDBRemote response;
963 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
965 if (response.IsOKResponse())
967 uint8_t error = response.GetError();
976 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
978 if (name_equal_value && name_equal_value[0])
981 packet.Printf("QEnvironment:%s", name_equal_value);
982 StringExtractorGDBRemote response;
983 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
985 if (response.IsOKResponse())
987 uint8_t error = response.GetError();
996 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1000 StreamString packet;
1001 packet.Printf("QLaunchArch:%s", arch);
1002 StringExtractorGDBRemote response;
1003 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1005 if (response.IsOKResponse())
1007 uint8_t error = response.GetError();
1016 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1022 if (m_os_version_major != UINT32_MAX)
1024 major = m_os_version_major;
1025 minor = m_os_version_minor;
1026 update = m_os_version_update;
1034 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1038 if (!m_os_build.empty())
1050 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1054 if (!m_os_kernel.empty())
1065 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1069 if (!m_hostname.empty())
1080 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1087 const lldb_private::ArchSpec &
1088 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1090 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1091 GetCurrentProcessInfo ();
1092 return m_process_arch;
1097 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1099 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1101 m_qHostInfo_is_valid = eLazyBoolNo;
1102 StringExtractorGDBRemote response;
1103 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1105 if (response.IsNormalResponse())
1109 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1111 std::string arch_name;
1112 std::string os_name;
1113 std::string vendor_name;
1115 uint32_t pointer_byte_size = 0;
1116 StringExtractor extractor;
1117 ByteOrder byte_order = eByteOrderInvalid;
1118 uint32_t num_keys_decoded = 0;
1119 while (response.GetNameColonValue(name, value))
1121 if (name.compare("cputype") == 0)
1123 // exception type in big endian hex
1124 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1125 if (cpu != LLDB_INVALID_CPUTYPE)
1128 else if (name.compare("cpusubtype") == 0)
1130 // exception count in big endian hex
1131 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1135 else if (name.compare("arch") == 0)
1137 arch_name.swap (value);
1140 else if (name.compare("triple") == 0)
1142 // The triple comes as ASCII hex bytes since it contains '-' chars
1143 extractor.GetStringRef().swap(value);
1144 extractor.SetFilePos(0);
1145 extractor.GetHexByteString (triple);
1148 else if (name.compare("os_build") == 0)
1150 extractor.GetStringRef().swap(value);
1151 extractor.SetFilePos(0);
1152 extractor.GetHexByteString (m_os_build);
1155 else if (name.compare("hostname") == 0)
1157 extractor.GetStringRef().swap(value);
1158 extractor.SetFilePos(0);
1159 extractor.GetHexByteString (m_hostname);
1162 else if (name.compare("os_kernel") == 0)
1164 extractor.GetStringRef().swap(value);
1165 extractor.SetFilePos(0);
1166 extractor.GetHexByteString (m_os_kernel);
1169 else if (name.compare("ostype") == 0)
1171 os_name.swap (value);
1174 else if (name.compare("vendor") == 0)
1176 vendor_name.swap(value);
1179 else if (name.compare("endian") == 0)
1182 if (value.compare("little") == 0)
1183 byte_order = eByteOrderLittle;
1184 else if (value.compare("big") == 0)
1185 byte_order = eByteOrderBig;
1186 else if (value.compare("pdp") == 0)
1187 byte_order = eByteOrderPDP;
1191 else if (name.compare("ptrsize") == 0)
1193 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1194 if (pointer_byte_size != 0)
1197 else if (name.compare("os_version") == 0)
1199 Args::StringToVersion (value.c_str(),
1202 m_os_version_update);
1203 if (m_os_version_major != UINT32_MAX)
1206 else if (name.compare("watchpoint_exceptions_received") == 0)
1209 if (strcmp(value.c_str(),"before") == 0)
1210 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1211 else if (strcmp(value.c_str(),"after") == 0)
1212 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1219 if (num_keys_decoded > 0)
1220 m_qHostInfo_is_valid = eLazyBoolYes;
1224 if (arch_name.empty())
1226 if (cpu != LLDB_INVALID_CPUTYPE)
1228 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1229 if (pointer_byte_size)
1231 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1233 if (byte_order != eByteOrderInvalid)
1235 assert (byte_order == m_host_arch.GetByteOrder());
1238 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1240 switch (m_host_arch.GetMachine())
1242 case llvm::Triple::arm:
1243 case llvm::Triple::thumb:
1251 if (!vendor_name.empty())
1252 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1253 if (!os_name.empty())
1254 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1261 triple += arch_name;
1262 if (!vendor_name.empty() || !os_name.empty())
1265 if (vendor_name.empty())
1266 triple += "unknown";
1268 triple += vendor_name;
1270 if (os_name.empty())
1271 triple += "unknown";
1275 m_host_arch.SetTriple (triple.c_str());
1277 llvm::Triple &host_triple = m_host_arch.GetTriple();
1278 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1280 switch (m_host_arch.GetMachine())
1282 case llvm::Triple::arm:
1283 case llvm::Triple::thumb:
1284 host_triple.setOS(llvm::Triple::IOS);
1287 host_triple.setOS(llvm::Triple::MacOSX);
1291 if (pointer_byte_size)
1293 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1295 if (byte_order != eByteOrderInvalid)
1297 assert (byte_order == m_host_arch.GetByteOrder());
1304 m_host_arch.SetTriple (triple.c_str());
1305 if (pointer_byte_size)
1307 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1309 if (byte_order != eByteOrderInvalid)
1311 assert (byte_order == m_host_arch.GetByteOrder());
1317 return m_qHostInfo_is_valid == eLazyBoolYes;
1321 GDBRemoteCommunicationClient::SendAttach
1324 StringExtractorGDBRemote& response
1327 if (pid != LLDB_INVALID_PROCESS_ID)
1330 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1331 assert (packet_len < (int)sizeof(packet));
1332 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1334 if (response.IsErrorResponse())
1335 return response.GetError();
1342 const lldb_private::ArchSpec &
1343 GDBRemoteCommunicationClient::GetHostArchitecture ()
1345 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1351 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1353 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1355 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1357 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1359 permissions & lldb::ePermissionsReadable ? "r" : "",
1360 permissions & lldb::ePermissionsWritable ? "w" : "",
1361 permissions & lldb::ePermissionsExecutable ? "x" : "");
1362 assert (packet_len < (int)sizeof(packet));
1363 StringExtractorGDBRemote response;
1364 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1366 if (!response.IsErrorResponse())
1367 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1371 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1374 return LLDB_INVALID_ADDRESS;
1378 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1380 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1382 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1384 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1385 assert (packet_len < (int)sizeof(packet));
1386 StringExtractorGDBRemote response;
1387 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1389 if (response.IsOKResponse())
1394 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1401 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1407 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1410 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1411 assert (packet_len < (int)sizeof(packet));
1412 StringExtractorGDBRemote response;
1413 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1415 m_supports_detach_stay_stopped = eLazyBoolYes;
1419 m_supports_detach_stay_stopped = eLazyBoolNo;
1423 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1425 error.SetErrorString("Stays stopped not supported by this target.");
1430 size_t num_sent = SendPacket ("D1", 2);
1432 error.SetErrorString ("Sending extended disconnect packet failed.");
1437 size_t num_sent = SendPacket ("D", 1);
1439 error.SetErrorString ("Sending disconnect packet failed.");
1445 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1446 lldb_private::MemoryRegionInfo ®ion_info)
1449 region_info.Clear();
1451 if (m_supports_memory_region_info != eLazyBoolNo)
1453 m_supports_memory_region_info = eLazyBoolYes;
1455 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1456 assert (packet_len < (int)sizeof(packet));
1457 StringExtractorGDBRemote response;
1458 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1463 bool success = true;
1464 bool saw_permissions = false;
1465 while (success && response.GetNameColonValue(name, value))
1467 if (name.compare ("start") == 0)
1469 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1471 region_info.GetRange().SetRangeBase(addr_value);
1473 else if (name.compare ("size") == 0)
1475 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1477 region_info.GetRange().SetByteSize (addr_value);
1479 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1481 saw_permissions = true;
1482 if (region_info.GetRange().Contains (addr))
1484 if (value.find('r') != std::string::npos)
1485 region_info.SetReadable (MemoryRegionInfo::eYes);
1487 region_info.SetReadable (MemoryRegionInfo::eNo);
1489 if (value.find('w') != std::string::npos)
1490 region_info.SetWritable (MemoryRegionInfo::eYes);
1492 region_info.SetWritable (MemoryRegionInfo::eNo);
1494 if (value.find('x') != std::string::npos)
1495 region_info.SetExecutable (MemoryRegionInfo::eYes);
1497 region_info.SetExecutable (MemoryRegionInfo::eNo);
1501 // The reported region does not contain this address -- we're looking at an unmapped page
1502 region_info.SetReadable (MemoryRegionInfo::eNo);
1503 region_info.SetWritable (MemoryRegionInfo::eNo);
1504 region_info.SetExecutable (MemoryRegionInfo::eNo);
1507 else if (name.compare ("error") == 0)
1509 StringExtractorGDBRemote name_extractor;
1510 // Swap "value" over into "name_extractor"
1511 name_extractor.GetStringRef().swap(value);
1512 // Now convert the HEX bytes into a string value
1513 name_extractor.GetHexByteString (value);
1514 error.SetErrorString(value.c_str());
1518 // We got a valid address range back but no permissions -- which means this is an unmapped page
1519 if (region_info.GetRange().IsValid() && saw_permissions == false)
1521 region_info.SetReadable (MemoryRegionInfo::eNo);
1522 region_info.SetWritable (MemoryRegionInfo::eNo);
1523 region_info.SetExecutable (MemoryRegionInfo::eNo);
1528 m_supports_memory_region_info = eLazyBoolNo;
1532 if (m_supports_memory_region_info == eLazyBoolNo)
1534 error.SetErrorString("qMemoryRegionInfo is not supported");
1537 region_info.Clear();
1543 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1547 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1549 num = m_num_supported_hardware_watchpoints;
1553 // Set num to 0 first.
1555 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1558 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1559 assert (packet_len < (int)sizeof(packet));
1560 StringExtractorGDBRemote response;
1561 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1563 m_supports_watchpoint_support_info = eLazyBoolYes;
1566 while (response.GetNameColonValue(name, value))
1568 if (name.compare ("num") == 0)
1570 num = Args::StringToUInt32(value.c_str(), 0, 0);
1571 m_num_supported_hardware_watchpoints = num;
1577 m_supports_watchpoint_support_info = eLazyBoolNo;
1581 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1583 error.SetErrorString("qWatchpointSupportInfo is not supported");
1590 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1592 Error error(GetWatchpointSupportInfo(num));
1593 if (error.Success())
1594 error = GetWatchpointsTriggerAfterInstruction(after);
1599 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1603 // we assume watchpoints will happen after running the relevant opcode
1604 // and we only want to override this behavior if we have explicitly
1605 // received a qHostInfo telling us otherwise
1606 if (m_qHostInfo_is_valid != eLazyBoolYes)
1609 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1614 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1616 if (path && path[0])
1618 StreamString packet;
1619 packet.PutCString("QSetSTDIN:");
1620 packet.PutBytesAsRawHex8(path, strlen(path));
1622 StringExtractorGDBRemote response;
1623 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1625 if (response.IsOKResponse())
1627 uint8_t error = response.GetError();
1636 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1638 if (path && path[0])
1640 StreamString packet;
1641 packet.PutCString("QSetSTDOUT:");
1642 packet.PutBytesAsRawHex8(path, strlen(path));
1644 StringExtractorGDBRemote response;
1645 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1647 if (response.IsOKResponse())
1649 uint8_t error = response.GetError();
1658 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1660 if (path && path[0])
1662 StreamString packet;
1663 packet.PutCString("QSetSTDERR:");
1664 packet.PutBytesAsRawHex8(path, strlen(path));
1666 StringExtractorGDBRemote response;
1667 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1669 if (response.IsOKResponse())
1671 uint8_t error = response.GetError();
1680 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1682 if (path && path[0])
1684 StreamString packet;
1685 packet.PutCString("QSetWorkingDir:");
1686 packet.PutBytesAsRawHex8(path, strlen(path));
1688 StringExtractorGDBRemote response;
1689 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1691 if (response.IsOKResponse())
1693 uint8_t error = response.GetError();
1702 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1705 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1706 assert (packet_len < (int)sizeof(packet));
1707 StringExtractorGDBRemote response;
1708 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1710 if (response.IsOKResponse())
1712 uint8_t error = response.GetError();
1720 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
1722 if (response.IsNormalResponse())
1726 StringExtractor extractor;
1728 while (response.GetNameColonValue(name, value))
1730 if (name.compare("pid") == 0)
1732 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1734 else if (name.compare("ppid") == 0)
1736 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1738 else if (name.compare("uid") == 0)
1740 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1742 else if (name.compare("euid") == 0)
1744 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1746 else if (name.compare("gid") == 0)
1748 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1750 else if (name.compare("egid") == 0)
1752 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1754 else if (name.compare("triple") == 0)
1756 // The triple comes as ASCII hex bytes since it contains '-' chars
1757 extractor.GetStringRef().swap(value);
1758 extractor.SetFilePos(0);
1759 extractor.GetHexByteString (value);
1760 process_info.GetArchitecture ().SetTriple (value.c_str());
1762 else if (name.compare("name") == 0)
1764 StringExtractor extractor;
1765 // The process name from ASCII hex bytes since we can't
1766 // control the characters in a process name
1767 extractor.GetStringRef().swap(value);
1768 extractor.SetFilePos(0);
1769 extractor.GetHexByteString (value);
1770 process_info.GetExecutableFile().SetFile (value.c_str(), false);
1774 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1781 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1783 process_info.Clear();
1785 if (m_supports_qProcessInfoPID)
1788 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
1789 assert (packet_len < (int)sizeof(packet));
1790 StringExtractorGDBRemote response;
1791 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1793 return DecodeProcessInfoResponse (response, process_info);
1797 m_supports_qProcessInfoPID = false;
1805 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1807 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1809 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1814 StringExtractorGDBRemote response;
1815 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1817 if (response.IsNormalResponse())
1821 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1823 std::string arch_name;
1824 std::string os_name;
1825 std::string vendor_name;
1827 uint32_t pointer_byte_size = 0;
1828 StringExtractor extractor;
1829 ByteOrder byte_order = eByteOrderInvalid;
1830 uint32_t num_keys_decoded = 0;
1831 while (response.GetNameColonValue(name, value))
1833 if (name.compare("cputype") == 0)
1835 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1836 if (cpu != LLDB_INVALID_CPUTYPE)
1839 else if (name.compare("cpusubtype") == 0)
1841 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1845 else if (name.compare("ostype") == 0)
1847 os_name.swap (value);
1850 else if (name.compare("vendor") == 0)
1852 vendor_name.swap(value);
1855 else if (name.compare("endian") == 0)
1858 if (value.compare("little") == 0)
1859 byte_order = eByteOrderLittle;
1860 else if (value.compare("big") == 0)
1861 byte_order = eByteOrderBig;
1862 else if (value.compare("pdp") == 0)
1863 byte_order = eByteOrderPDP;
1867 else if (name.compare("ptrsize") == 0)
1869 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1870 if (pointer_byte_size != 0)
1874 if (num_keys_decoded > 0)
1875 m_qProcessInfo_is_valid = eLazyBoolYes;
1876 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1878 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1879 if (pointer_byte_size)
1881 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1883 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1884 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1891 m_qProcessInfo_is_valid = eLazyBoolNo;
1899 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1900 ProcessInstanceInfoList &process_infos)
1902 process_infos.Clear();
1904 if (m_supports_qfProcessInfo)
1906 StreamString packet;
1907 packet.PutCString ("qfProcessInfo");
1908 if (!match_info.MatchAllProcesses())
1910 packet.PutChar (':');
1911 const char *name = match_info.GetProcessInfo().GetName();
1912 bool has_name_match = false;
1913 if (name && name[0])
1915 has_name_match = true;
1916 NameMatchType name_match_type = match_info.GetNameMatchType();
1917 switch (name_match_type)
1919 case eNameMatchIgnore:
1920 has_name_match = false;
1923 case eNameMatchEquals:
1924 packet.PutCString ("name_match:equals;");
1927 case eNameMatchContains:
1928 packet.PutCString ("name_match:contains;");
1931 case eNameMatchStartsWith:
1932 packet.PutCString ("name_match:starts_with;");
1935 case eNameMatchEndsWith:
1936 packet.PutCString ("name_match:ends_with;");
1939 case eNameMatchRegularExpression:
1940 packet.PutCString ("name_match:regex;");
1945 packet.PutCString ("name:");
1946 packet.PutBytesAsRawHex8(name, ::strlen(name));
1947 packet.PutChar (';');
1951 if (match_info.GetProcessInfo().ProcessIDIsValid())
1952 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
1953 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1954 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
1955 if (match_info.GetProcessInfo().UserIDIsValid())
1956 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1957 if (match_info.GetProcessInfo().GroupIDIsValid())
1958 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
1959 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1960 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1961 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1962 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1963 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1964 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1965 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1967 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1968 const llvm::Triple &triple = match_arch.GetTriple();
1969 packet.PutCString("triple:");
1970 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1971 packet.PutChar (';');
1974 StringExtractorGDBRemote response;
1975 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1979 ProcessInstanceInfo process_info;
1980 if (!DecodeProcessInfoResponse (response, process_info))
1982 process_infos.Append(process_info);
1983 response.GetStringRef().clear();
1984 response.SetFilePos(0);
1985 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1989 m_supports_qfProcessInfo = false;
1993 return process_infos.GetSize();
1998 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2000 if (m_supports_qUserName)
2003 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2004 assert (packet_len < (int)sizeof(packet));
2005 StringExtractorGDBRemote response;
2006 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2008 if (response.IsNormalResponse())
2010 // Make sure we parsed the right number of characters. The response is
2011 // the hex encoded user name and should make up the entire packet.
2012 // If there are any non-hex ASCII bytes, the length won't match below..
2013 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2019 m_supports_qUserName = false;
2028 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2030 if (m_supports_qGroupName)
2033 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2034 assert (packet_len < (int)sizeof(packet));
2035 StringExtractorGDBRemote response;
2036 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2038 if (response.IsNormalResponse())
2040 // Make sure we parsed the right number of characters. The response is
2041 // the hex encoded group name and should make up the entire packet.
2042 // If there are any non-hex ASCII bytes, the length won't match below..
2043 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2049 m_supports_qGroupName = false;
2057 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2060 TimeValue start_time, end_time;
2061 uint64_t total_time_nsec;
2062 float packets_per_second;
2063 if (SendSpeedTestPacket (0, 0))
2065 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2067 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2069 start_time = TimeValue::Now();
2070 for (i=0; i<num_packets; ++i)
2072 SendSpeedTestPacket (send_size, recv_size);
2074 end_time = TimeValue::Now();
2075 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2076 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2077 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2081 total_time_nsec / TimeValue::NanoSecPerSec,
2082 total_time_nsec % TimeValue::NanoSecPerSec,
2083 packets_per_second);
2093 start_time = TimeValue::Now();
2094 for (i=0; i<num_packets; ++i)
2096 GetCurrentProcessID ();
2098 end_time = TimeValue::Now();
2099 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2100 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2101 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
2103 total_time_nsec / TimeValue::NanoSecPerSec,
2104 total_time_nsec % TimeValue::NanoSecPerSec,
2105 packets_per_second);
2110 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2112 StreamString packet;
2113 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2114 uint32_t bytes_left = send_size;
2115 while (bytes_left > 0)
2117 if (bytes_left >= 26)
2119 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2124 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2129 StringExtractorGDBRemote response;
2130 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
2135 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
2137 StringExtractorGDBRemote response;
2138 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
2143 //lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2144 while (response.GetNameColonValue(name, value))
2146 if (name.size() == 4 && name.compare("port") == 0)
2147 port = Args::StringToUInt32(value.c_str(), 0, 0);
2148 // if (name.size() == 3 && name.compare("pid") == 0)
2149 // pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2157 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2159 if (m_curr_tid == tid)
2164 if (tid == UINT64_MAX)
2165 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2167 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2168 assert (packet_len + 1 < (int)sizeof(packet));
2169 StringExtractorGDBRemote response;
2170 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2172 if (response.IsOKResponse())
2182 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2184 if (m_curr_tid_run == tid)
2189 if (tid == UINT64_MAX)
2190 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2192 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2194 assert (packet_len + 1 < (int)sizeof(packet));
2195 StringExtractorGDBRemote response;
2196 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2198 if (response.IsOKResponse())
2200 m_curr_tid_run = tid;
2208 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2210 if (SendPacketAndWaitForResponse("?", 1, response, false))
2211 return response.IsNormalResponse();
2216 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2218 if (m_supports_qThreadStopInfo)
2221 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2222 assert (packet_len < (int)sizeof(packet));
2223 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2225 if (response.IsNormalResponse())
2232 m_supports_qThreadStopInfo = false;
2235 // if (SetCurrentThread (tid))
2236 // return GetStopReply (response);
2242 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2246 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2247 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2248 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2249 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2250 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
2254 const int packet_len = ::snprintf (packet,
2256 "%c%i,%" PRIx64 ",%x",
2262 assert (packet_len + 1 < (int)sizeof(packet));
2263 StringExtractorGDBRemote response;
2264 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2266 if (response.IsOKResponse())
2268 else if (response.IsErrorResponse())
2269 return response.GetError();
2275 case eBreakpointSoftware: m_supports_z0 = false; break;
2276 case eBreakpointHardware: m_supports_z1 = false; break;
2277 case eWatchpointWrite: m_supports_z2 = false; break;
2278 case eWatchpointRead: m_supports_z3 = false; break;
2279 case eWatchpointReadWrite: m_supports_z4 = false; break;
2287 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2288 bool &sequence_mutex_unavailable)
2290 Mutex::Locker locker;
2293 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2295 sequence_mutex_unavailable = false;
2296 StringExtractorGDBRemote response;
2298 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
2299 response.IsNormalResponse();
2300 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
2302 char ch = response.GetChar();
2309 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2311 if (tid != LLDB_INVALID_THREAD_ID)
2313 thread_ids.push_back (tid);
2315 ch = response.GetChar(); // Skip the command separator
2316 } while (ch == ','); // Make sure we got a comma separator
2322 #if defined (LLDB_CONFIGURATION_DEBUG)
2323 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2325 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2327 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
2329 sequence_mutex_unavailable = true;
2331 return thread_ids.size();
2335 GDBRemoteCommunicationClient::GetShlibInfoAddr()
2339 StringExtractorGDBRemote response;
2340 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2342 if (response.IsNormalResponse())
2343 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2346 return LLDB_INVALID_ADDRESS;