blob: f8eb8de7bb8801b7f393cbbd6a35a0207ef634d1 [file] [log] [blame]
Greg Clayton61d043b2011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
14// C++ Includes
15// Other libraries and framework includes
16#include "llvm/ADT/Triple.h"
17#include "lldb/Interpreter/Args.h"
18#include "lldb/Core/ConnectionFileDescriptor.h"
19#include "lldb/Core/Log.h"
20#include "lldb/Core/State.h"
21#include "lldb/Core/StreamString.h"
22#include "lldb/Host/Endian.h"
23#include "lldb/Host/Host.h"
24#include "lldb/Host/TimeValue.h"
25
26// Project includes
27#include "Utility/StringExtractorGDBRemote.h"
28#include "ProcessGDBRemote.h"
29#include "ProcessGDBRemoteLog.h"
30
31using namespace lldb;
32using namespace lldb_private;
33
34//----------------------------------------------------------------------
35// GDBRemoteCommunicationClient constructor
36//----------------------------------------------------------------------
Greg Claytonb72d0f02011-04-12 05:54:46 +000037GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
38 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton61d043b2011-03-22 04:00:09 +000039 m_supports_not_sending_acks (eLazyBoolCalculate),
40 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton61d043b2011-03-22 04:00:09 +000041 m_supports_vCont_all (eLazyBoolCalculate),
42 m_supports_vCont_any (eLazyBoolCalculate),
43 m_supports_vCont_c (eLazyBoolCalculate),
44 m_supports_vCont_C (eLazyBoolCalculate),
45 m_supports_vCont_s (eLazyBoolCalculate),
46 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton24bc5d92011-03-30 18:16:51 +000047 m_qHostInfo_is_valid (eLazyBoolCalculate),
48 m_supports_qProcessInfoPID (true),
49 m_supports_qfProcessInfo (true),
50 m_supports_qUserName (true),
51 m_supports_qGroupName (true),
Greg Claytonb72d0f02011-04-12 05:54:46 +000052 m_supports_qThreadStopInfo (true),
53 m_supports_z0 (true),
54 m_supports_z1 (true),
55 m_supports_z2 (true),
56 m_supports_z3 (true),
57 m_supports_z4 (true),
58 m_curr_tid (LLDB_INVALID_THREAD_ID),
59 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Greg Clayton61d043b2011-03-22 04:00:09 +000060 m_async_mutex (Mutex::eMutexTypeRecursive),
61 m_async_packet_predicate (false),
62 m_async_packet (),
63 m_async_response (),
64 m_async_signal (-1),
Greg Clayton58e26e02011-03-24 04:28:38 +000065 m_host_arch(),
66 m_os_version_major (UINT32_MAX),
67 m_os_version_minor (UINT32_MAX),
68 m_os_version_update (UINT32_MAX)
Greg Clayton61d043b2011-03-22 04:00:09 +000069{
70 m_rx_packet_listener.StartListeningForEvents(this,
71 Communication::eBroadcastBitPacketAvailable |
72 Communication::eBroadcastBitReadThreadDidExit);
73}
74
75//----------------------------------------------------------------------
76// Destructor
77//----------------------------------------------------------------------
78GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
79{
80 m_rx_packet_listener.StopListeningForEvents(this,
81 Communication::eBroadcastBitPacketAvailable |
82 Communication::eBroadcastBitReadThreadDidExit);
83 if (IsConnected())
84 {
85 StopReadThread();
86 Disconnect();
87 }
88}
89
90bool
Greg Clayton58e26e02011-03-24 04:28:38 +000091GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
92{
93 // Start the read thread after we send the handshake ack since if we
94 // fail to send the handshake ack, there is no reason to continue...
95 if (SendAck())
96 return StartReadThread (error_ptr);
97
98 if (error_ptr)
99 error_ptr->SetErrorString("failed to send the handshake ack");
100 return false;
101}
102
103void
104GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton61d043b2011-03-22 04:00:09 +0000105{
106 if (m_supports_not_sending_acks == eLazyBoolCalculate)
107 {
Greg Clayton58e26e02011-03-24 04:28:38 +0000108 m_send_acks = true;
Greg Clayton61d043b2011-03-22 04:00:09 +0000109 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton58e26e02011-03-24 04:28:38 +0000110
111 StringExtractorGDBRemote response;
Greg Clayton61d043b2011-03-22 04:00:09 +0000112 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
113 {
114 if (response.IsOKResponse())
Greg Clayton58e26e02011-03-24 04:28:38 +0000115 {
116 m_send_acks = false;
Greg Clayton61d043b2011-03-22 04:00:09 +0000117 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton58e26e02011-03-24 04:28:38 +0000118 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000119 }
120 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000121}
122
123void
124GDBRemoteCommunicationClient::ResetDiscoverableSettings()
125{
126 m_supports_not_sending_acks = eLazyBoolCalculate;
127 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton61d043b2011-03-22 04:00:09 +0000128 m_supports_vCont_c = eLazyBoolCalculate;
129 m_supports_vCont_C = eLazyBoolCalculate;
130 m_supports_vCont_s = eLazyBoolCalculate;
131 m_supports_vCont_S = eLazyBoolCalculate;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000132 m_qHostInfo_is_valid = eLazyBoolCalculate;
133 m_supports_qProcessInfoPID = true;
134 m_supports_qfProcessInfo = true;
135 m_supports_qUserName = true;
136 m_supports_qGroupName = true;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000137 m_supports_qThreadStopInfo = true;
138 m_supports_z0 = true;
139 m_supports_z1 = true;
140 m_supports_z2 = true;
141 m_supports_z3 = true;
142 m_supports_z4 = true;
Greg Claytoncb8977d2011-03-23 00:09:55 +0000143 m_host_arch.Clear();
Greg Clayton61d043b2011-03-22 04:00:09 +0000144}
145
146
147bool
148GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
149{
150 if (m_supports_thread_suffix == eLazyBoolCalculate)
151 {
152 StringExtractorGDBRemote response;
153 m_supports_thread_suffix = eLazyBoolNo;
154 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
155 {
156 if (response.IsOKResponse())
157 m_supports_thread_suffix = eLazyBoolYes;
158 }
159 }
160 return m_supports_thread_suffix;
161}
162bool
163GDBRemoteCommunicationClient::GetVContSupported (char flavor)
164{
165 if (m_supports_vCont_c == eLazyBoolCalculate)
166 {
167 StringExtractorGDBRemote response;
168 m_supports_vCont_any = eLazyBoolNo;
169 m_supports_vCont_all = eLazyBoolNo;
170 m_supports_vCont_c = eLazyBoolNo;
171 m_supports_vCont_C = eLazyBoolNo;
172 m_supports_vCont_s = eLazyBoolNo;
173 m_supports_vCont_S = eLazyBoolNo;
174 if (SendPacketAndWaitForResponse("vCont?", response, false))
175 {
176 const char *response_cstr = response.GetStringRef().c_str();
177 if (::strstr (response_cstr, ";c"))
178 m_supports_vCont_c = eLazyBoolYes;
179
180 if (::strstr (response_cstr, ";C"))
181 m_supports_vCont_C = eLazyBoolYes;
182
183 if (::strstr (response_cstr, ";s"))
184 m_supports_vCont_s = eLazyBoolYes;
185
186 if (::strstr (response_cstr, ";S"))
187 m_supports_vCont_S = eLazyBoolYes;
188
189 if (m_supports_vCont_c == eLazyBoolYes &&
190 m_supports_vCont_C == eLazyBoolYes &&
191 m_supports_vCont_s == eLazyBoolYes &&
192 m_supports_vCont_S == eLazyBoolYes)
193 {
194 m_supports_vCont_all = eLazyBoolYes;
195 }
196
197 if (m_supports_vCont_c == eLazyBoolYes ||
198 m_supports_vCont_C == eLazyBoolYes ||
199 m_supports_vCont_s == eLazyBoolYes ||
200 m_supports_vCont_S == eLazyBoolYes)
201 {
202 m_supports_vCont_any = eLazyBoolYes;
203 }
204 }
205 }
206
207 switch (flavor)
208 {
209 case 'a': return m_supports_vCont_any;
210 case 'A': return m_supports_vCont_all;
211 case 'c': return m_supports_vCont_c;
212 case 'C': return m_supports_vCont_C;
213 case 's': return m_supports_vCont_s;
214 case 'S': return m_supports_vCont_S;
215 default: break;
216 }
217 return false;
218}
219
220
221size_t
222GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
223(
224 const char *payload,
225 StringExtractorGDBRemote &response,
226 bool send_async
227)
228{
229 return SendPacketAndWaitForResponse (payload,
230 ::strlen (payload),
231 response,
232 send_async);
233}
234
235size_t
236GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
237(
238 const char *payload,
239 size_t payload_length,
240 StringExtractorGDBRemote &response,
241 bool send_async
242)
243{
244 Mutex::Locker locker;
245 TimeValue timeout_time;
246 timeout_time = TimeValue::Now();
247 timeout_time.OffsetWithSeconds (m_packet_timeout);
248 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
249
250 if (GetSequenceMutex (locker))
251 {
252 if (SendPacketNoLock (payload, strlen(payload)))
253 return WaitForPacketNoLock (response, &timeout_time);
254 }
255 else
256 {
257 if (send_async)
258 {
259 Mutex::Locker async_locker (m_async_mutex);
260 m_async_packet.assign(payload, payload_length);
261 m_async_packet_predicate.SetValue (true, eBroadcastNever);
262
263 if (log)
264 log->Printf ("async: async packet = %s", m_async_packet.c_str());
265
266 bool timed_out = false;
267 bool sent_interrupt = false;
268 if (SendInterrupt(locker, 2, sent_interrupt, timed_out))
269 {
270 if (sent_interrupt)
271 {
272 if (log)
273 log->Printf ("async: sent interrupt");
274 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
275 {
276 if (log)
277 log->Printf ("async: got response");
278 response = m_async_response;
279 return response.GetStringRef().size();
280 }
281 else
282 {
283 if (log)
284 log->Printf ("async: timed out waiting for response");
285 }
286
287 // Make sure we wait until the continue packet has been sent again...
288 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
289 {
290 if (log)
291 log->Printf ("async: timed out waiting for process to resume");
292 }
293 }
294 else
295 {
296 // We had a racy condition where we went to send the interrupt
297 // yet we were able to get the loc
298 }
299 }
300 else
301 {
302 if (log)
303 log->Printf ("async: failed to interrupt");
304 }
305 }
306 else
307 {
308 if (log)
309 log->Printf ("mutex taken and send_async == false, aborting packet");
310 }
311 }
312 return 0;
313}
314
315//template<typename _Tp>
316//class ScopedValueChanger
317//{
318//public:
319// // Take a value reference and the value to assign it to when this class
320// // instance goes out of scope.
321// ScopedValueChanger (_Tp &value_ref, _Tp value) :
322// m_value_ref (value_ref),
323// m_value (value)
324// {
325// }
326//
327// // This object is going out of scope, change the value pointed to by
328// // m_value_ref to the value we got during construction which was stored in
329// // m_value;
330// ~ScopedValueChanger ()
331// {
332// m_value_ref = m_value;
333// }
334//protected:
335// _Tp &m_value_ref; // A reference to the value we will change when this object destructs
336// _Tp m_value; // The value to assign to m_value_ref when this goes out of scope.
337//};
338
339StateType
340GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
341(
342 ProcessGDBRemote *process,
343 const char *payload,
344 size_t packet_length,
345 StringExtractorGDBRemote &response
346)
347{
348 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
349 if (log)
350 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
351
352 Mutex::Locker locker(m_sequence_mutex);
353 StateType state = eStateRunning;
354
355 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
356 m_public_is_running.SetValue (true, eBroadcastNever);
357 // Set the starting continue packet into "continue_packet". This packet
358 // make change if we are interrupted and we continue after an async packet...
359 std::string continue_packet(payload, packet_length);
360
361 while (state == eStateRunning)
362 {
363 if (log)
364 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
365 if (SendPacket(continue_packet.c_str(), continue_packet.size()) == 0)
366 state = eStateInvalid;
367
368 m_private_is_running.SetValue (true, eBroadcastNever);
369
370 if (log)
371 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%.*s)", __FUNCTION__);
372
373 if (WaitForPacket (response, (TimeValue*)NULL))
374 {
375 if (response.Empty())
376 state = eStateInvalid;
377 else
378 {
379 const char stop_type = response.GetChar();
380 if (log)
381 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
382 switch (stop_type)
383 {
384 case 'T':
385 case 'S':
386 if (process->GetStopID() == 0)
387 {
388 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
389 {
390 lldb::pid_t pid = GetCurrentProcessID ();
391 if (pid != LLDB_INVALID_PROCESS_ID)
392 process->SetID (pid);
393 }
394 process->BuildDynamicRegisterInfo (true);
395 }
396
397 // Privately notify any internal threads that we have stopped
398 // in case we wanted to interrupt our process, yet we might
399 // send a packet and continue without returning control to the
400 // user.
401 m_private_is_running.SetValue (false, eBroadcastAlways);
402 if (m_async_signal != -1)
403 {
404 if (log)
405 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
406
407 // Save off the async signal we are supposed to send
408 const int async_signal = m_async_signal;
409 // Clear the async signal member so we don't end up
410 // sending the signal multiple times...
411 m_async_signal = -1;
412 // Check which signal we stopped with
413 uint8_t signo = response.GetHexU8(255);
414 if (signo == async_signal)
415 {
416 if (log)
417 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
418
419 // We already stopped with a signal that we wanted
420 // to stop with, so we are done
421 response.SetFilePos (0);
422 }
423 else
424 {
425 // We stopped with a different signal that the one
426 // we wanted to stop with, so now we must resume
427 // with the signal we want
428 char signal_packet[32];
429 int signal_packet_len = 0;
430 signal_packet_len = ::snprintf (signal_packet,
431 sizeof (signal_packet),
432 "C%2.2x",
433 async_signal);
434
435 if (log)
436 log->Printf ("async: stopped with signal %s, resume with %s",
437 Host::GetSignalAsCString (signo),
438 Host::GetSignalAsCString (async_signal));
439
440 // Set the continue packet to resume...
441 continue_packet.assign(signal_packet, signal_packet_len);
442 continue;
443 }
444 }
445 else if (m_async_packet_predicate.GetValue())
446 {
447 // We are supposed to send an asynchronous packet while
448 // we are running.
449 m_async_response.Clear();
450 if (m_async_packet.empty())
451 {
452 if (log)
453 log->Printf ("async: error: empty async packet");
454
455 }
456 else
457 {
458 if (log)
459 log->Printf ("async: sending packet: %s",
460 m_async_packet.c_str());
461
462 SendPacketAndWaitForResponse (&m_async_packet[0],
463 m_async_packet.size(),
464 m_async_response,
465 false);
466 }
467 // Let the other thread that was trying to send the async
468 // packet know that the packet has been sent and response is
469 // ready...
470 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
471
472 // Set the continue packet to resume...
473 continue_packet.assign (1, 'c');
474 continue;
475 }
476 // Stop with signal and thread info
477 state = eStateStopped;
478 break;
479
480 case 'W':
481 case 'X':
482 // process exited
483 state = eStateExited;
484 break;
485
486 case 'O':
487 // STDOUT
488 {
489 std::string inferior_stdout;
490 inferior_stdout.reserve(response.GetBytesLeft () / 2);
491 char ch;
492 while ((ch = response.GetHexU8()) != '\0')
493 inferior_stdout.append(1, ch);
494 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
495 }
496 break;
497
498 case 'E':
499 // ERROR
500 state = eStateInvalid;
501 break;
502
503 default:
504 if (log)
505 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
506 state = eStateInvalid;
507 break;
508 }
509 }
510 }
511 else
512 {
513 if (log)
514 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
515 state = eStateInvalid;
516 }
517 }
518 if (log)
519 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
520 response.SetFilePos(0);
521 m_private_is_running.SetValue (false, eBroadcastAlways);
522 m_public_is_running.SetValue (false, eBroadcastAlways);
523 return state;
524}
525
526bool
527GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
528{
529 m_async_signal = signo;
530 bool timed_out = false;
531 bool sent_interrupt = false;
532 Mutex::Locker locker;
533 if (SendInterrupt (locker, 1, sent_interrupt, timed_out))
534 return true;
535 m_async_signal = -1;
536 return false;
537}
538
539// This function takes a mutex locker as a parameter in case the GetSequenceMutex
540// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
541// (the expected result), then it will send the halt packet. If it does succeed
542// then the caller that requested the interrupt will want to keep the sequence
543// locked down so that no one else can send packets while the caller has control.
544// This function usually gets called when we are running and need to stop the
545// target. It can also be used when we are running and and we need to do something
546// else (like read/write memory), so we need to interrupt the running process
547// (gdb remote protocol requires this), and do what we need to do, then resume.
548
549bool
550GDBRemoteCommunicationClient::SendInterrupt
551(
552 Mutex::Locker& locker,
553 uint32_t seconds_to_wait_for_stop,
554 bool &sent_interrupt,
555 bool &timed_out
556)
557{
558 sent_interrupt = false;
559 timed_out = false;
560 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
561
562 if (IsRunning())
563 {
564 // Only send an interrupt if our debugserver is running...
565 if (GetSequenceMutex (locker) == false)
566 {
567 // Someone has the mutex locked waiting for a response or for the
568 // inferior to stop, so send the interrupt on the down low...
569 char ctrl_c = '\x03';
570 ConnectionStatus status = eConnectionStatusSuccess;
571 TimeValue timeout;
572 if (seconds_to_wait_for_stop)
573 {
574 timeout = TimeValue::Now();
575 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
576 }
577 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
578 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS | GDBR_LOG_PROCESS, "send packet: \\x03");
579 if (bytes_written > 0)
580 {
581 sent_interrupt = true;
582 if (seconds_to_wait_for_stop)
583 {
584 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
585 {
586 if (log)
587 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, private state stopped", __FUNCTION__);
588 return true;
589 }
590 else
591 {
592 if (log)
593 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, timed out wating for async thread resume", __FUNCTION__);
594 }
595 }
596 else
597 {
598 if (log)
599 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, not waiting for stop...", __FUNCTION__);
600 return true;
601 }
602 }
603 else
604 {
605 if (log)
606 log->Printf ("GDBRemoteCommunicationClient::%s () - failed to write interrupt", __FUNCTION__);
607 }
608 return false;
609 }
610 else
611 {
612 if (log)
613 log->Printf ("GDBRemoteCommunicationClient::%s () - got sequence mutex without having to interrupt", __FUNCTION__);
614 }
615 }
616 return true;
617}
618
619lldb::pid_t
620GDBRemoteCommunicationClient::GetCurrentProcessID ()
621{
622 StringExtractorGDBRemote response;
623 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
624 {
625 if (response.GetChar() == 'Q')
626 if (response.GetChar() == 'C')
627 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
628 }
629 return LLDB_INVALID_PROCESS_ID;
630}
631
632bool
633GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
634{
635 error_str.clear();
636 StringExtractorGDBRemote response;
637 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
638 {
639 if (response.IsOKResponse())
640 return true;
641 if (response.GetChar() == 'E')
642 {
643 // A string the describes what failed when launching...
644 error_str = response.GetStringRef().substr(1);
645 }
646 else
647 {
648 error_str.assign ("unknown error occurred launching process");
649 }
650 }
651 else
652 {
653 error_str.assign ("failed to send the qLaunchSuccess packet");
654 }
655 return false;
656}
657
658int
659GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
660{
661 if (argv && argv[0])
662 {
663 StreamString packet;
664 packet.PutChar('A');
665 const char *arg;
666 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
667 {
668 const int arg_len = strlen(arg);
669 if (i > 0)
670 packet.PutChar(',');
671 packet.Printf("%i,%i,", arg_len * 2, i);
672 packet.PutBytesAsRawHex8 (arg, arg_len);
673 }
674
675 StringExtractorGDBRemote response;
676 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
677 {
678 if (response.IsOKResponse())
679 return 0;
680 uint8_t error = response.GetError();
681 if (error)
682 return error;
683 }
684 }
685 return -1;
686}
687
688int
689GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
690{
691 if (name_equal_value && name_equal_value[0])
692 {
693 StreamString packet;
694 packet.Printf("QEnvironment:%s", name_equal_value);
695 StringExtractorGDBRemote response;
696 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
697 {
698 if (response.IsOKResponse())
699 return 0;
700 uint8_t error = response.GetError();
701 if (error)
702 return error;
703 }
704 }
705 return -1;
706}
707
Greg Claytona4582402011-05-08 04:53:50 +0000708int
709GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
710{
711 if (arch && arch[0])
712 {
713 StreamString packet;
714 packet.Printf("QLaunchArch:%s", arch);
715 StringExtractorGDBRemote response;
716 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
717 {
718 if (response.IsOKResponse())
719 return 0;
720 uint8_t error = response.GetError();
721 if (error)
722 return error;
723 }
724 }
725 return -1;
726}
727
Greg Clayton61d043b2011-03-22 04:00:09 +0000728bool
Greg Clayton58e26e02011-03-24 04:28:38 +0000729GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
730 uint32_t &minor,
731 uint32_t &update)
732{
733 if (GetHostInfo ())
734 {
735 if (m_os_version_major != UINT32_MAX)
736 {
737 major = m_os_version_major;
738 minor = m_os_version_minor;
739 update = m_os_version_update;
740 return true;
741 }
742 }
743 return false;
744}
745
746bool
747GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
748{
749 if (GetHostInfo ())
750 {
751 if (!m_os_build.empty())
752 {
753 s = m_os_build;
754 return true;
755 }
756 }
757 s.clear();
758 return false;
759}
760
761
762bool
763GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
764{
765 if (GetHostInfo ())
766 {
767 if (!m_os_kernel.empty())
768 {
769 s = m_os_kernel;
770 return true;
771 }
772 }
773 s.clear();
774 return false;
775}
776
777bool
778GDBRemoteCommunicationClient::GetHostname (std::string &s)
779{
780 if (GetHostInfo ())
781 {
782 if (!m_hostname.empty())
783 {
784 s = m_hostname;
785 return true;
786 }
787 }
788 s.clear();
789 return false;
790}
791
792ArchSpec
793GDBRemoteCommunicationClient::GetSystemArchitecture ()
794{
795 if (GetHostInfo ())
796 return m_host_arch;
797 return ArchSpec();
798}
799
800
801bool
Greg Clayton06d7cc82011-04-04 18:18:57 +0000802GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton61d043b2011-03-22 04:00:09 +0000803{
Greg Clayton06d7cc82011-04-04 18:18:57 +0000804 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +0000805 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000806 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton61d043b2011-03-22 04:00:09 +0000807 StringExtractorGDBRemote response;
808 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
809 {
810 if (response.IsUnsupportedResponse())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000811 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000812 return false;
Greg Clayton61d043b2011-03-22 04:00:09 +0000813 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000814 else if (response.IsNormalResponse())
Greg Claytoncb8977d2011-03-23 00:09:55 +0000815 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000816 std::string name;
817 std::string value;
818 uint32_t cpu = LLDB_INVALID_CPUTYPE;
819 uint32_t sub = 0;
820 std::string arch_name;
821 std::string os_name;
822 std::string vendor_name;
823 std::string triple;
824 uint32_t pointer_byte_size = 0;
825 StringExtractor extractor;
826 ByteOrder byte_order = eByteOrderInvalid;
827 uint32_t num_keys_decoded = 0;
828 while (response.GetNameColonValue(name, value))
Greg Claytoncb8977d2011-03-23 00:09:55 +0000829 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000830 if (name.compare("cputype") == 0)
Greg Clayton58e26e02011-03-24 04:28:38 +0000831 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000832 // exception type in big endian hex
833 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
834 if (cpu != LLDB_INVALID_CPUTYPE)
835 ++num_keys_decoded;
836 }
837 else if (name.compare("cpusubtype") == 0)
838 {
839 // exception count in big endian hex
840 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
841 if (sub != 0)
842 ++num_keys_decoded;
843 }
844 else if (name.compare("arch") == 0)
845 {
846 arch_name.swap (value);
847 ++num_keys_decoded;
848 }
849 else if (name.compare("triple") == 0)
850 {
851 // The triple comes as ASCII hex bytes since it contains '-' chars
852 extractor.GetStringRef().swap(value);
853 extractor.SetFilePos(0);
854 extractor.GetHexByteString (triple);
855 ++num_keys_decoded;
856 }
857 else if (name.compare("os_build") == 0)
858 {
859 extractor.GetStringRef().swap(value);
860 extractor.SetFilePos(0);
861 extractor.GetHexByteString (m_os_build);
862 ++num_keys_decoded;
863 }
864 else if (name.compare("hostname") == 0)
865 {
866 extractor.GetStringRef().swap(value);
867 extractor.SetFilePos(0);
868 extractor.GetHexByteString (m_hostname);
869 ++num_keys_decoded;
870 }
871 else if (name.compare("os_kernel") == 0)
872 {
873 extractor.GetStringRef().swap(value);
874 extractor.SetFilePos(0);
875 extractor.GetHexByteString (m_os_kernel);
876 ++num_keys_decoded;
877 }
878 else if (name.compare("ostype") == 0)
879 {
880 os_name.swap (value);
881 ++num_keys_decoded;
882 }
883 else if (name.compare("vendor") == 0)
884 {
885 vendor_name.swap(value);
886 ++num_keys_decoded;
887 }
888 else if (name.compare("endian") == 0)
889 {
890 ++num_keys_decoded;
891 if (value.compare("little") == 0)
892 byte_order = eByteOrderLittle;
893 else if (value.compare("big") == 0)
894 byte_order = eByteOrderBig;
895 else if (value.compare("pdp") == 0)
896 byte_order = eByteOrderPDP;
897 else
898 --num_keys_decoded;
899 }
900 else if (name.compare("ptrsize") == 0)
901 {
902 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
903 if (pointer_byte_size != 0)
904 ++num_keys_decoded;
905 }
906 else if (name.compare("os_version") == 0)
907 {
908 Args::StringToVersion (value.c_str(),
909 m_os_version_major,
910 m_os_version_minor,
911 m_os_version_update);
912 if (m_os_version_major != UINT32_MAX)
913 ++num_keys_decoded;
914 }
915 }
916
917 if (num_keys_decoded > 0)
918 m_qHostInfo_is_valid = eLazyBoolYes;
919
920 if (triple.empty())
921 {
922 if (arch_name.empty())
923 {
924 if (cpu != LLDB_INVALID_CPUTYPE)
925 {
926 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
927 if (pointer_byte_size)
928 {
929 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
930 }
931 if (byte_order != eByteOrderInvalid)
932 {
933 assert (byte_order == m_host_arch.GetByteOrder());
934 }
935 if (!vendor_name.empty())
936 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
937 if (!os_name.empty())
938 m_host_arch.GetTriple().setVendorName (llvm::StringRef (os_name));
939
940 }
941 }
942 else
943 {
944 std::string triple;
945 triple += arch_name;
946 triple += '-';
947 if (vendor_name.empty())
948 triple += "unknown";
949 else
950 triple += vendor_name;
951 triple += '-';
952 if (os_name.empty())
953 triple += "unknown";
954 else
955 triple += os_name;
Greg Claytonf15996e2011-04-07 22:46:35 +0000956 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Clayton58e26e02011-03-24 04:28:38 +0000957 if (pointer_byte_size)
958 {
959 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
960 }
961 if (byte_order != eByteOrderInvalid)
962 {
963 assert (byte_order == m_host_arch.GetByteOrder());
964 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000965
Greg Clayton58e26e02011-03-24 04:28:38 +0000966 }
967 }
968 else
969 {
Greg Claytonf15996e2011-04-07 22:46:35 +0000970 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Claytoncb8977d2011-03-23 00:09:55 +0000971 if (pointer_byte_size)
972 {
973 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
974 }
975 if (byte_order != eByteOrderInvalid)
976 {
977 assert (byte_order == m_host_arch.GetByteOrder());
978 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000979 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000980 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000981 }
982 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000983 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton61d043b2011-03-22 04:00:09 +0000984}
985
986int
987GDBRemoteCommunicationClient::SendAttach
988(
989 lldb::pid_t pid,
990 StringExtractorGDBRemote& response
991)
992{
993 if (pid != LLDB_INVALID_PROCESS_ID)
994 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000995 char packet[64];
996 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", pid);
997 assert (packet_len < sizeof(packet));
998 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +0000999 {
1000 if (response.IsErrorResponse())
1001 return response.GetError();
1002 return 0;
1003 }
1004 }
1005 return -1;
1006}
1007
1008const lldb_private::ArchSpec &
1009GDBRemoteCommunicationClient::GetHostArchitecture ()
1010{
Greg Clayton24bc5d92011-03-30 18:16:51 +00001011 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +00001012 GetHostInfo ();
Greg Claytoncb8977d2011-03-23 00:09:55 +00001013 return m_host_arch;
Greg Clayton61d043b2011-03-22 04:00:09 +00001014}
1015
1016addr_t
1017GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1018{
1019 char packet[64];
Greg Clayton24bc5d92011-03-30 18:16:51 +00001020 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
1021 permissions & lldb::ePermissionsReadable ? "r" : "",
1022 permissions & lldb::ePermissionsWritable ? "w" : "",
1023 permissions & lldb::ePermissionsExecutable ? "x" : "");
1024 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001025 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001026 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001027 {
1028 if (!response.IsErrorResponse())
1029 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1030 }
1031 return LLDB_INVALID_ADDRESS;
1032}
1033
1034bool
1035GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1036{
1037 char packet[64];
Greg Clayton24bc5d92011-03-30 18:16:51 +00001038 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
1039 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001040 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001041 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001042 {
1043 if (response.IsOKResponse())
1044 return true;
1045 }
1046 return false;
1047}
1048
1049int
1050GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1051{
1052 if (path && path[0])
1053 {
1054 StreamString packet;
1055 packet.PutCString("QSetSTDIN:");
1056 packet.PutBytesAsRawHex8(path, strlen(path));
1057
1058 StringExtractorGDBRemote response;
1059 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1060 {
1061 if (response.IsOKResponse())
1062 return 0;
1063 uint8_t error = response.GetError();
1064 if (error)
1065 return error;
1066 }
1067 }
1068 return -1;
1069}
1070
1071int
1072GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1073{
1074 if (path && path[0])
1075 {
1076 StreamString packet;
1077 packet.PutCString("QSetSTDOUT:");
1078 packet.PutBytesAsRawHex8(path, strlen(path));
1079
1080 StringExtractorGDBRemote response;
1081 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1082 {
1083 if (response.IsOKResponse())
1084 return 0;
1085 uint8_t error = response.GetError();
1086 if (error)
1087 return error;
1088 }
1089 }
1090 return -1;
1091}
1092
1093int
1094GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1095{
1096 if (path && path[0])
1097 {
1098 StreamString packet;
1099 packet.PutCString("QSetSTDERR:");
1100 packet.PutBytesAsRawHex8(path, strlen(path));
1101
1102 StringExtractorGDBRemote response;
1103 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1104 {
1105 if (response.IsOKResponse())
1106 return 0;
1107 uint8_t error = response.GetError();
1108 if (error)
1109 return error;
1110 }
1111 }
1112 return -1;
1113}
1114
1115int
1116GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1117{
1118 if (path && path[0])
1119 {
1120 StreamString packet;
1121 packet.PutCString("QSetWorkingDir:");
1122 packet.PutBytesAsRawHex8(path, strlen(path));
1123
1124 StringExtractorGDBRemote response;
1125 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1126 {
1127 if (response.IsOKResponse())
1128 return 0;
1129 uint8_t error = response.GetError();
1130 if (error)
1131 return error;
1132 }
1133 }
1134 return -1;
1135}
1136
1137int
1138GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1139{
Greg Clayton24bc5d92011-03-30 18:16:51 +00001140 char packet[32];
1141 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1142 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001143 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001144 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001145 {
1146 if (response.IsOKResponse())
1147 return 0;
1148 uint8_t error = response.GetError();
1149 if (error)
1150 return error;
1151 }
1152 return -1;
1153}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001154
1155bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001156GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001157{
1158 if (response.IsNormalResponse())
1159 {
1160 std::string name;
1161 std::string value;
1162 StringExtractor extractor;
1163
1164 while (response.GetNameColonValue(name, value))
1165 {
1166 if (name.compare("pid") == 0)
1167 {
1168 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1169 }
1170 else if (name.compare("ppid") == 0)
1171 {
1172 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1173 }
1174 else if (name.compare("uid") == 0)
1175 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001176 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001177 }
1178 else if (name.compare("euid") == 0)
1179 {
1180 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1181 }
1182 else if (name.compare("gid") == 0)
1183 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001184 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001185 }
1186 else if (name.compare("egid") == 0)
1187 {
1188 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1189 }
1190 else if (name.compare("triple") == 0)
1191 {
1192 // The triple comes as ASCII hex bytes since it contains '-' chars
1193 extractor.GetStringRef().swap(value);
1194 extractor.SetFilePos(0);
1195 extractor.GetHexByteString (value);
Greg Claytonf15996e2011-04-07 22:46:35 +00001196 process_info.GetArchitecture ().SetTriple (value.c_str(), NULL);
Greg Clayton24bc5d92011-03-30 18:16:51 +00001197 }
1198 else if (name.compare("name") == 0)
1199 {
1200 StringExtractor extractor;
1201 // The the process name from ASCII hex bytes since we can't
1202 // control the characters in a process name
1203 extractor.GetStringRef().swap(value);
1204 extractor.SetFilePos(0);
1205 extractor.GetHexByteString (value);
Greg Claytonff39f742011-04-01 00:29:43 +00001206 process_info.SetName (value.c_str());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001207 }
1208 }
1209
1210 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1211 return true;
1212 }
1213 return false;
1214}
1215
1216bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001217GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001218{
1219 process_info.Clear();
1220
1221 if (m_supports_qProcessInfoPID)
1222 {
1223 char packet[32];
1224 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%i", pid);
1225 assert (packet_len < sizeof(packet));
1226 StringExtractorGDBRemote response;
1227 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1228 {
1229 if (response.IsUnsupportedResponse())
1230 {
1231 m_supports_qProcessInfoPID = false;
1232 return false;
1233 }
1234
1235 return DecodeProcessInfoResponse (response, process_info);
1236 }
1237 }
1238 return false;
1239}
1240
1241uint32_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001242GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1243 ProcessInstanceInfoList &process_infos)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001244{
1245 process_infos.Clear();
1246
1247 if (m_supports_qfProcessInfo)
1248 {
1249 StreamString packet;
1250 packet.PutCString ("qfProcessInfo");
1251 if (!match_info.MatchAllProcesses())
1252 {
1253 packet.PutChar (':');
1254 const char *name = match_info.GetProcessInfo().GetName();
1255 bool has_name_match = false;
1256 if (name && name[0])
1257 {
1258 has_name_match = true;
1259 NameMatchType name_match_type = match_info.GetNameMatchType();
1260 switch (name_match_type)
1261 {
1262 case eNameMatchIgnore:
1263 has_name_match = false;
1264 break;
1265
1266 case eNameMatchEquals:
1267 packet.PutCString ("name_match:equals;");
1268 break;
1269
1270 case eNameMatchContains:
1271 packet.PutCString ("name_match:contains;");
1272 break;
1273
1274 case eNameMatchStartsWith:
1275 packet.PutCString ("name_match:starts_with;");
1276 break;
1277
1278 case eNameMatchEndsWith:
1279 packet.PutCString ("name_match:ends_with;");
1280 break;
1281
1282 case eNameMatchRegularExpression:
1283 packet.PutCString ("name_match:regex;");
1284 break;
1285 }
1286 if (has_name_match)
1287 {
1288 packet.PutCString ("name:");
1289 packet.PutBytesAsRawHex8(name, ::strlen(name));
1290 packet.PutChar (';');
1291 }
1292 }
1293
1294 if (match_info.GetProcessInfo().ProcessIDIsValid())
1295 packet.Printf("pid:%u;",match_info.GetProcessInfo().GetProcessID());
1296 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1297 packet.Printf("parent_pid:%u;",match_info.GetProcessInfo().GetParentProcessID());
Greg Claytonb72d0f02011-04-12 05:54:46 +00001298 if (match_info.GetProcessInfo().UserIDIsValid())
1299 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1300 if (match_info.GetProcessInfo().GroupIDIsValid())
1301 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001302 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1303 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1304 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1305 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1306 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1307 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1308 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1309 {
1310 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1311 const llvm::Triple &triple = match_arch.GetTriple();
1312 packet.PutCString("triple:");
1313 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1314 packet.PutChar (';');
1315 }
1316 }
1317 StringExtractorGDBRemote response;
1318 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1319 {
1320 if (response.IsUnsupportedResponse())
1321 {
1322 m_supports_qfProcessInfo = false;
1323 return 0;
1324 }
1325
1326 do
1327 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001328 ProcessInstanceInfo process_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001329 if (!DecodeProcessInfoResponse (response, process_info))
1330 break;
1331 process_infos.Append(process_info);
1332 response.GetStringRef().clear();
1333 response.SetFilePos(0);
1334 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1335 }
1336 }
1337 return process_infos.GetSize();
1338
1339}
1340
1341bool
1342GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
1343{
1344 if (m_supports_qUserName)
1345 {
1346 char packet[32];
1347 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
1348 assert (packet_len < sizeof(packet));
1349 StringExtractorGDBRemote response;
1350 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1351 {
1352 if (response.IsUnsupportedResponse())
1353 {
1354 m_supports_qUserName = false;
1355 return false;
1356 }
1357
1358 if (response.IsNormalResponse())
1359 {
1360 // Make sure we parsed the right number of characters. The response is
1361 // the hex encoded user name and should make up the entire packet.
1362 // If there are any non-hex ASCII bytes, the length won't match below..
1363 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1364 return true;
1365 }
1366 }
1367 }
1368 return false;
1369
1370}
1371
1372bool
1373GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
1374{
1375 if (m_supports_qGroupName)
1376 {
1377 char packet[32];
1378 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
1379 assert (packet_len < sizeof(packet));
1380 StringExtractorGDBRemote response;
1381 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1382 {
1383 if (response.IsUnsupportedResponse())
1384 {
1385 m_supports_qGroupName = false;
1386 return false;
1387 }
1388
1389 if (response.IsNormalResponse())
1390 {
1391 // Make sure we parsed the right number of characters. The response is
1392 // the hex encoded group name and should make up the entire packet.
1393 // If there are any non-hex ASCII bytes, the length won't match below..
1394 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1395 return true;
1396 }
1397 }
1398 }
1399 return false;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001400}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001401
Greg Clayton06d7cc82011-04-04 18:18:57 +00001402void
1403GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
1404{
1405 uint32_t i;
1406 TimeValue start_time, end_time;
1407 uint64_t total_time_nsec;
1408 float packets_per_second;
1409 if (SendSpeedTestPacket (0, 0))
1410 {
1411 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
1412 {
1413 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
1414 {
1415 start_time = TimeValue::Now();
1416 for (i=0; i<num_packets; ++i)
1417 {
1418 SendSpeedTestPacket (send_size, recv_size);
1419 }
1420 end_time = TimeValue::Now();
1421 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001422 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecondPerSecond;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001423 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %llu.%09.9llu sec for %f packets/sec.\n",
1424 num_packets,
1425 send_size,
1426 recv_size,
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001427 total_time_nsec / TimeValue::NanoSecondPerSecond,
1428 total_time_nsec % TimeValue::NanoSecondPerSecond,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001429 packets_per_second);
1430 if (recv_size == 0)
1431 recv_size = 32;
1432 }
1433 if (send_size == 0)
1434 send_size = 32;
1435 }
1436 }
1437 else
1438 {
1439 start_time = TimeValue::Now();
1440 for (i=0; i<num_packets; ++i)
1441 {
1442 GetCurrentProcessID ();
1443 }
1444 end_time = TimeValue::Now();
1445 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001446 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecondPerSecond;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001447 printf ("%u 'qC' packets packets in 0x%llu%09.9llu sec for %f packets/sec.\n",
1448 num_packets,
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001449 total_time_nsec / TimeValue::NanoSecondPerSecond,
1450 total_time_nsec % TimeValue::NanoSecondPerSecond,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001451 packets_per_second);
1452 }
1453}
1454
1455bool
1456GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
1457{
1458 StreamString packet;
1459 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
1460 uint32_t bytes_left = send_size;
1461 while (bytes_left > 0)
1462 {
1463 if (bytes_left >= 26)
1464 {
1465 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
1466 bytes_left -= 26;
1467 }
1468 else
1469 {
1470 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
1471 bytes_left = 0;
1472 }
1473 }
1474
1475 StringExtractorGDBRemote response;
1476 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1477 {
1478 if (response.IsUnsupportedResponse())
1479 return false;
1480 return true;
1481 }
1482 return false;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001483}
Greg Claytonb72d0f02011-04-12 05:54:46 +00001484
1485uint16_t
1486GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
1487{
1488 StringExtractorGDBRemote response;
1489 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
1490 {
1491 std::string name;
1492 std::string value;
1493 uint16_t port = 0;
1494 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1495 while (response.GetNameColonValue(name, value))
1496 {
1497 if (name.size() == 4 && name.compare("port") == 0)
1498 port = Args::StringToUInt32(value.c_str(), 0, 0);
1499 if (name.size() == 3 && name.compare("pid") == 0)
1500 pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
1501 }
1502 return port;
1503 }
1504 return 0;
1505}
1506
1507bool
1508GDBRemoteCommunicationClient::SetCurrentThread (int tid)
1509{
1510 if (m_curr_tid == tid)
1511 return true;
1512
1513 char packet[32];
1514 int packet_len;
1515 if (tid <= 0)
1516 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
1517 else
1518 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1519 assert (packet_len + 1 < sizeof(packet));
1520 StringExtractorGDBRemote response;
1521 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1522 {
1523 if (response.IsOKResponse())
1524 {
1525 m_curr_tid = tid;
1526 return true;
1527 }
1528 }
1529 return false;
1530}
1531
1532bool
1533GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid)
1534{
1535 if (m_curr_tid_run == tid)
1536 return true;
1537
1538 char packet[32];
1539 int packet_len;
1540 if (tid <= 0)
1541 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
1542 else
1543 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
1544
1545 assert (packet_len + 1 < sizeof(packet));
1546 StringExtractorGDBRemote response;
1547 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1548 {
1549 if (response.IsOKResponse())
1550 {
1551 m_curr_tid_run = tid;
1552 return true;
1553 }
1554 }
1555 return false;
1556}
1557
1558bool
1559GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
1560{
1561 if (SendPacketAndWaitForResponse("?", 1, response, false))
1562 return response.IsNormalResponse();
1563 return false;
1564}
1565
1566bool
1567GDBRemoteCommunicationClient::GetThreadStopInfo (uint32_t tid, StringExtractorGDBRemote &response)
1568{
1569 if (m_supports_qThreadStopInfo)
1570 {
1571 char packet[256];
1572 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%x", tid);
1573 assert (packet_len < sizeof(packet));
1574 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1575 {
1576 if (response.IsUnsupportedResponse())
1577 m_supports_qThreadStopInfo = false;
1578 else if (response.IsNormalResponse())
1579 return true;
1580 else
1581 return false;
1582 }
1583 }
1584 if (SetCurrentThread (tid))
1585 return GetStopReply (response);
1586 return false;
1587}
1588
1589
1590uint8_t
1591GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
1592{
1593 switch (type)
1594 {
1595 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
1596 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
1597 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
1598 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
1599 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
1600 default: return UINT8_MAX;
1601 }
1602
1603 char packet[64];
1604 const int packet_len = ::snprintf (packet,
1605 sizeof(packet),
1606 "%c%i,%llx,%x",
1607 insert ? 'Z' : 'z',
1608 type,
1609 addr,
1610 length);
1611
1612 assert (packet_len + 1 < sizeof(packet));
1613 StringExtractorGDBRemote response;
1614 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
1615 {
1616 if (response.IsOKResponse())
1617 return 0;
1618 if (response.IsUnsupportedResponse())
1619 {
1620 switch (type)
1621 {
1622 case eBreakpointSoftware: m_supports_z0 = false; break;
1623 case eBreakpointHardware: m_supports_z1 = false; break;
1624 case eWatchpointWrite: m_supports_z2 = false; break;
1625 case eWatchpointRead: m_supports_z3 = false; break;
1626 case eWatchpointReadWrite: m_supports_z4 = false; break;
1627 default: break;
1628 }
1629 }
1630 else if (response.IsErrorResponse())
1631 return response.GetError();
1632 }
1633 return UINT8_MAX;
1634}