blob: d4f6592f5bd132accb2f6a98374d1b9413b7bb5e [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
708bool
Greg Clayton58e26e02011-03-24 04:28:38 +0000709GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
710 uint32_t &minor,
711 uint32_t &update)
712{
713 if (GetHostInfo ())
714 {
715 if (m_os_version_major != UINT32_MAX)
716 {
717 major = m_os_version_major;
718 minor = m_os_version_minor;
719 update = m_os_version_update;
720 return true;
721 }
722 }
723 return false;
724}
725
726bool
727GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
728{
729 if (GetHostInfo ())
730 {
731 if (!m_os_build.empty())
732 {
733 s = m_os_build;
734 return true;
735 }
736 }
737 s.clear();
738 return false;
739}
740
741
742bool
743GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
744{
745 if (GetHostInfo ())
746 {
747 if (!m_os_kernel.empty())
748 {
749 s = m_os_kernel;
750 return true;
751 }
752 }
753 s.clear();
754 return false;
755}
756
757bool
758GDBRemoteCommunicationClient::GetHostname (std::string &s)
759{
760 if (GetHostInfo ())
761 {
762 if (!m_hostname.empty())
763 {
764 s = m_hostname;
765 return true;
766 }
767 }
768 s.clear();
769 return false;
770}
771
772ArchSpec
773GDBRemoteCommunicationClient::GetSystemArchitecture ()
774{
775 if (GetHostInfo ())
776 return m_host_arch;
777 return ArchSpec();
778}
779
780
781bool
Greg Clayton06d7cc82011-04-04 18:18:57 +0000782GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton61d043b2011-03-22 04:00:09 +0000783{
Greg Clayton06d7cc82011-04-04 18:18:57 +0000784 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +0000785 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000786 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton61d043b2011-03-22 04:00:09 +0000787 StringExtractorGDBRemote response;
788 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
789 {
790 if (response.IsUnsupportedResponse())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000791 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000792 return false;
Greg Clayton61d043b2011-03-22 04:00:09 +0000793 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000794 else if (response.IsNormalResponse())
Greg Claytoncb8977d2011-03-23 00:09:55 +0000795 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000796 std::string name;
797 std::string value;
798 uint32_t cpu = LLDB_INVALID_CPUTYPE;
799 uint32_t sub = 0;
800 std::string arch_name;
801 std::string os_name;
802 std::string vendor_name;
803 std::string triple;
804 uint32_t pointer_byte_size = 0;
805 StringExtractor extractor;
806 ByteOrder byte_order = eByteOrderInvalid;
807 uint32_t num_keys_decoded = 0;
808 while (response.GetNameColonValue(name, value))
Greg Claytoncb8977d2011-03-23 00:09:55 +0000809 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000810 if (name.compare("cputype") == 0)
Greg Clayton58e26e02011-03-24 04:28:38 +0000811 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000812 // exception type in big endian hex
813 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
814 if (cpu != LLDB_INVALID_CPUTYPE)
815 ++num_keys_decoded;
816 }
817 else if (name.compare("cpusubtype") == 0)
818 {
819 // exception count in big endian hex
820 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
821 if (sub != 0)
822 ++num_keys_decoded;
823 }
824 else if (name.compare("arch") == 0)
825 {
826 arch_name.swap (value);
827 ++num_keys_decoded;
828 }
829 else if (name.compare("triple") == 0)
830 {
831 // The triple comes as ASCII hex bytes since it contains '-' chars
832 extractor.GetStringRef().swap(value);
833 extractor.SetFilePos(0);
834 extractor.GetHexByteString (triple);
835 ++num_keys_decoded;
836 }
837 else if (name.compare("os_build") == 0)
838 {
839 extractor.GetStringRef().swap(value);
840 extractor.SetFilePos(0);
841 extractor.GetHexByteString (m_os_build);
842 ++num_keys_decoded;
843 }
844 else if (name.compare("hostname") == 0)
845 {
846 extractor.GetStringRef().swap(value);
847 extractor.SetFilePos(0);
848 extractor.GetHexByteString (m_hostname);
849 ++num_keys_decoded;
850 }
851 else if (name.compare("os_kernel") == 0)
852 {
853 extractor.GetStringRef().swap(value);
854 extractor.SetFilePos(0);
855 extractor.GetHexByteString (m_os_kernel);
856 ++num_keys_decoded;
857 }
858 else if (name.compare("ostype") == 0)
859 {
860 os_name.swap (value);
861 ++num_keys_decoded;
862 }
863 else if (name.compare("vendor") == 0)
864 {
865 vendor_name.swap(value);
866 ++num_keys_decoded;
867 }
868 else if (name.compare("endian") == 0)
869 {
870 ++num_keys_decoded;
871 if (value.compare("little") == 0)
872 byte_order = eByteOrderLittle;
873 else if (value.compare("big") == 0)
874 byte_order = eByteOrderBig;
875 else if (value.compare("pdp") == 0)
876 byte_order = eByteOrderPDP;
877 else
878 --num_keys_decoded;
879 }
880 else if (name.compare("ptrsize") == 0)
881 {
882 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
883 if (pointer_byte_size != 0)
884 ++num_keys_decoded;
885 }
886 else if (name.compare("os_version") == 0)
887 {
888 Args::StringToVersion (value.c_str(),
889 m_os_version_major,
890 m_os_version_minor,
891 m_os_version_update);
892 if (m_os_version_major != UINT32_MAX)
893 ++num_keys_decoded;
894 }
895 }
896
897 if (num_keys_decoded > 0)
898 m_qHostInfo_is_valid = eLazyBoolYes;
899
900 if (triple.empty())
901 {
902 if (arch_name.empty())
903 {
904 if (cpu != LLDB_INVALID_CPUTYPE)
905 {
906 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
907 if (pointer_byte_size)
908 {
909 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
910 }
911 if (byte_order != eByteOrderInvalid)
912 {
913 assert (byte_order == m_host_arch.GetByteOrder());
914 }
915 if (!vendor_name.empty())
916 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
917 if (!os_name.empty())
918 m_host_arch.GetTriple().setVendorName (llvm::StringRef (os_name));
919
920 }
921 }
922 else
923 {
924 std::string triple;
925 triple += arch_name;
926 triple += '-';
927 if (vendor_name.empty())
928 triple += "unknown";
929 else
930 triple += vendor_name;
931 triple += '-';
932 if (os_name.empty())
933 triple += "unknown";
934 else
935 triple += os_name;
Greg Claytonf15996e2011-04-07 22:46:35 +0000936 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Clayton58e26e02011-03-24 04:28:38 +0000937 if (pointer_byte_size)
938 {
939 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
940 }
941 if (byte_order != eByteOrderInvalid)
942 {
943 assert (byte_order == m_host_arch.GetByteOrder());
944 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000945
Greg Clayton58e26e02011-03-24 04:28:38 +0000946 }
947 }
948 else
949 {
Greg Claytonf15996e2011-04-07 22:46:35 +0000950 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Claytoncb8977d2011-03-23 00:09:55 +0000951 if (pointer_byte_size)
952 {
953 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
954 }
955 if (byte_order != eByteOrderInvalid)
956 {
957 assert (byte_order == m_host_arch.GetByteOrder());
958 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000959 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000960 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000961 }
962 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000963 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton61d043b2011-03-22 04:00:09 +0000964}
965
966int
967GDBRemoteCommunicationClient::SendAttach
968(
969 lldb::pid_t pid,
970 StringExtractorGDBRemote& response
971)
972{
973 if (pid != LLDB_INVALID_PROCESS_ID)
974 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000975 char packet[64];
976 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", pid);
977 assert (packet_len < sizeof(packet));
978 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +0000979 {
980 if (response.IsErrorResponse())
981 return response.GetError();
982 return 0;
983 }
984 }
985 return -1;
986}
987
988const lldb_private::ArchSpec &
989GDBRemoteCommunicationClient::GetHostArchitecture ()
990{
Greg Clayton24bc5d92011-03-30 18:16:51 +0000991 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +0000992 GetHostInfo ();
Greg Claytoncb8977d2011-03-23 00:09:55 +0000993 return m_host_arch;
Greg Clayton61d043b2011-03-22 04:00:09 +0000994}
995
996addr_t
997GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
998{
999 char packet[64];
Greg Clayton24bc5d92011-03-30 18:16:51 +00001000 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
1001 permissions & lldb::ePermissionsReadable ? "r" : "",
1002 permissions & lldb::ePermissionsWritable ? "w" : "",
1003 permissions & lldb::ePermissionsExecutable ? "x" : "");
1004 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001005 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001006 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001007 {
1008 if (!response.IsErrorResponse())
1009 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1010 }
1011 return LLDB_INVALID_ADDRESS;
1012}
1013
1014bool
1015GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1016{
1017 char packet[64];
Greg Clayton24bc5d92011-03-30 18:16:51 +00001018 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
1019 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001020 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001021 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001022 {
1023 if (response.IsOKResponse())
1024 return true;
1025 }
1026 return false;
1027}
1028
1029int
1030GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1031{
1032 if (path && path[0])
1033 {
1034 StreamString packet;
1035 packet.PutCString("QSetSTDIN:");
1036 packet.PutBytesAsRawHex8(path, strlen(path));
1037
1038 StringExtractorGDBRemote response;
1039 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1040 {
1041 if (response.IsOKResponse())
1042 return 0;
1043 uint8_t error = response.GetError();
1044 if (error)
1045 return error;
1046 }
1047 }
1048 return -1;
1049}
1050
1051int
1052GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1053{
1054 if (path && path[0])
1055 {
1056 StreamString packet;
1057 packet.PutCString("QSetSTDOUT:");
1058 packet.PutBytesAsRawHex8(path, strlen(path));
1059
1060 StringExtractorGDBRemote response;
1061 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1062 {
1063 if (response.IsOKResponse())
1064 return 0;
1065 uint8_t error = response.GetError();
1066 if (error)
1067 return error;
1068 }
1069 }
1070 return -1;
1071}
1072
1073int
1074GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1075{
1076 if (path && path[0])
1077 {
1078 StreamString packet;
1079 packet.PutCString("QSetSTDERR:");
1080 packet.PutBytesAsRawHex8(path, strlen(path));
1081
1082 StringExtractorGDBRemote response;
1083 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1084 {
1085 if (response.IsOKResponse())
1086 return 0;
1087 uint8_t error = response.GetError();
1088 if (error)
1089 return error;
1090 }
1091 }
1092 return -1;
1093}
1094
1095int
1096GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1097{
1098 if (path && path[0])
1099 {
1100 StreamString packet;
1101 packet.PutCString("QSetWorkingDir:");
1102 packet.PutBytesAsRawHex8(path, strlen(path));
1103
1104 StringExtractorGDBRemote response;
1105 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1106 {
1107 if (response.IsOKResponse())
1108 return 0;
1109 uint8_t error = response.GetError();
1110 if (error)
1111 return error;
1112 }
1113 }
1114 return -1;
1115}
1116
1117int
1118GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1119{
Greg Clayton24bc5d92011-03-30 18:16:51 +00001120 char packet[32];
1121 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1122 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001123 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001124 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001125 {
1126 if (response.IsOKResponse())
1127 return 0;
1128 uint8_t error = response.GetError();
1129 if (error)
1130 return error;
1131 }
1132 return -1;
1133}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001134
1135bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001136GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001137{
1138 if (response.IsNormalResponse())
1139 {
1140 std::string name;
1141 std::string value;
1142 StringExtractor extractor;
1143
1144 while (response.GetNameColonValue(name, value))
1145 {
1146 if (name.compare("pid") == 0)
1147 {
1148 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1149 }
1150 else if (name.compare("ppid") == 0)
1151 {
1152 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1153 }
1154 else if (name.compare("uid") == 0)
1155 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001156 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001157 }
1158 else if (name.compare("euid") == 0)
1159 {
1160 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1161 }
1162 else if (name.compare("gid") == 0)
1163 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001164 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001165 }
1166 else if (name.compare("egid") == 0)
1167 {
1168 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1169 }
1170 else if (name.compare("triple") == 0)
1171 {
1172 // The triple comes as ASCII hex bytes since it contains '-' chars
1173 extractor.GetStringRef().swap(value);
1174 extractor.SetFilePos(0);
1175 extractor.GetHexByteString (value);
Greg Claytonf15996e2011-04-07 22:46:35 +00001176 process_info.GetArchitecture ().SetTriple (value.c_str(), NULL);
Greg Clayton24bc5d92011-03-30 18:16:51 +00001177 }
1178 else if (name.compare("name") == 0)
1179 {
1180 StringExtractor extractor;
1181 // The the process name from ASCII hex bytes since we can't
1182 // control the characters in a process name
1183 extractor.GetStringRef().swap(value);
1184 extractor.SetFilePos(0);
1185 extractor.GetHexByteString (value);
Greg Claytonff39f742011-04-01 00:29:43 +00001186 process_info.SetName (value.c_str());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001187 }
1188 }
1189
1190 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1191 return true;
1192 }
1193 return false;
1194}
1195
1196bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001197GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001198{
1199 process_info.Clear();
1200
1201 if (m_supports_qProcessInfoPID)
1202 {
1203 char packet[32];
1204 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%i", pid);
1205 assert (packet_len < sizeof(packet));
1206 StringExtractorGDBRemote response;
1207 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1208 {
1209 if (response.IsUnsupportedResponse())
1210 {
1211 m_supports_qProcessInfoPID = false;
1212 return false;
1213 }
1214
1215 return DecodeProcessInfoResponse (response, process_info);
1216 }
1217 }
1218 return false;
1219}
1220
1221uint32_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001222GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1223 ProcessInstanceInfoList &process_infos)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001224{
1225 process_infos.Clear();
1226
1227 if (m_supports_qfProcessInfo)
1228 {
1229 StreamString packet;
1230 packet.PutCString ("qfProcessInfo");
1231 if (!match_info.MatchAllProcesses())
1232 {
1233 packet.PutChar (':');
1234 const char *name = match_info.GetProcessInfo().GetName();
1235 bool has_name_match = false;
1236 if (name && name[0])
1237 {
1238 has_name_match = true;
1239 NameMatchType name_match_type = match_info.GetNameMatchType();
1240 switch (name_match_type)
1241 {
1242 case eNameMatchIgnore:
1243 has_name_match = false;
1244 break;
1245
1246 case eNameMatchEquals:
1247 packet.PutCString ("name_match:equals;");
1248 break;
1249
1250 case eNameMatchContains:
1251 packet.PutCString ("name_match:contains;");
1252 break;
1253
1254 case eNameMatchStartsWith:
1255 packet.PutCString ("name_match:starts_with;");
1256 break;
1257
1258 case eNameMatchEndsWith:
1259 packet.PutCString ("name_match:ends_with;");
1260 break;
1261
1262 case eNameMatchRegularExpression:
1263 packet.PutCString ("name_match:regex;");
1264 break;
1265 }
1266 if (has_name_match)
1267 {
1268 packet.PutCString ("name:");
1269 packet.PutBytesAsRawHex8(name, ::strlen(name));
1270 packet.PutChar (';');
1271 }
1272 }
1273
1274 if (match_info.GetProcessInfo().ProcessIDIsValid())
1275 packet.Printf("pid:%u;",match_info.GetProcessInfo().GetProcessID());
1276 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1277 packet.Printf("parent_pid:%u;",match_info.GetProcessInfo().GetParentProcessID());
Greg Claytonb72d0f02011-04-12 05:54:46 +00001278 if (match_info.GetProcessInfo().UserIDIsValid())
1279 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1280 if (match_info.GetProcessInfo().GroupIDIsValid())
1281 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001282 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1283 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1284 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1285 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1286 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1287 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1288 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1289 {
1290 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1291 const llvm::Triple &triple = match_arch.GetTriple();
1292 packet.PutCString("triple:");
1293 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1294 packet.PutChar (';');
1295 }
1296 }
1297 StringExtractorGDBRemote response;
1298 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1299 {
1300 if (response.IsUnsupportedResponse())
1301 {
1302 m_supports_qfProcessInfo = false;
1303 return 0;
1304 }
1305
1306 do
1307 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001308 ProcessInstanceInfo process_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001309 if (!DecodeProcessInfoResponse (response, process_info))
1310 break;
1311 process_infos.Append(process_info);
1312 response.GetStringRef().clear();
1313 response.SetFilePos(0);
1314 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1315 }
1316 }
1317 return process_infos.GetSize();
1318
1319}
1320
1321bool
1322GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
1323{
1324 if (m_supports_qUserName)
1325 {
1326 char packet[32];
1327 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
1328 assert (packet_len < sizeof(packet));
1329 StringExtractorGDBRemote response;
1330 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1331 {
1332 if (response.IsUnsupportedResponse())
1333 {
1334 m_supports_qUserName = false;
1335 return false;
1336 }
1337
1338 if (response.IsNormalResponse())
1339 {
1340 // Make sure we parsed the right number of characters. The response is
1341 // the hex encoded user name and should make up the entire packet.
1342 // If there are any non-hex ASCII bytes, the length won't match below..
1343 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1344 return true;
1345 }
1346 }
1347 }
1348 return false;
1349
1350}
1351
1352bool
1353GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
1354{
1355 if (m_supports_qGroupName)
1356 {
1357 char packet[32];
1358 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
1359 assert (packet_len < sizeof(packet));
1360 StringExtractorGDBRemote response;
1361 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1362 {
1363 if (response.IsUnsupportedResponse())
1364 {
1365 m_supports_qGroupName = false;
1366 return false;
1367 }
1368
1369 if (response.IsNormalResponse())
1370 {
1371 // Make sure we parsed the right number of characters. The response is
1372 // the hex encoded group name and should make up the entire packet.
1373 // If there are any non-hex ASCII bytes, the length won't match below..
1374 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1375 return true;
1376 }
1377 }
1378 }
1379 return false;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001380}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001381
Greg Clayton06d7cc82011-04-04 18:18:57 +00001382void
1383GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
1384{
1385 uint32_t i;
1386 TimeValue start_time, end_time;
1387 uint64_t total_time_nsec;
1388 float packets_per_second;
1389 if (SendSpeedTestPacket (0, 0))
1390 {
1391 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
1392 {
1393 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
1394 {
1395 start_time = TimeValue::Now();
1396 for (i=0; i<num_packets; ++i)
1397 {
1398 SendSpeedTestPacket (send_size, recv_size);
1399 }
1400 end_time = TimeValue::Now();
1401 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001402 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecondPerSecond;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001403 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %llu.%09.9llu sec for %f packets/sec.\n",
1404 num_packets,
1405 send_size,
1406 recv_size,
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001407 total_time_nsec / TimeValue::NanoSecondPerSecond,
1408 total_time_nsec % TimeValue::NanoSecondPerSecond,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001409 packets_per_second);
1410 if (recv_size == 0)
1411 recv_size = 32;
1412 }
1413 if (send_size == 0)
1414 send_size = 32;
1415 }
1416 }
1417 else
1418 {
1419 start_time = TimeValue::Now();
1420 for (i=0; i<num_packets; ++i)
1421 {
1422 GetCurrentProcessID ();
1423 }
1424 end_time = TimeValue::Now();
1425 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001426 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecondPerSecond;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001427 printf ("%u 'qC' packets packets in 0x%llu%09.9llu sec for %f packets/sec.\n",
1428 num_packets,
Stephen Wilsonbaf01e02011-04-07 10:27:22 +00001429 total_time_nsec / TimeValue::NanoSecondPerSecond,
1430 total_time_nsec % TimeValue::NanoSecondPerSecond,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001431 packets_per_second);
1432 }
1433}
1434
1435bool
1436GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
1437{
1438 StreamString packet;
1439 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
1440 uint32_t bytes_left = send_size;
1441 while (bytes_left > 0)
1442 {
1443 if (bytes_left >= 26)
1444 {
1445 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
1446 bytes_left -= 26;
1447 }
1448 else
1449 {
1450 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
1451 bytes_left = 0;
1452 }
1453 }
1454
1455 StringExtractorGDBRemote response;
1456 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1457 {
1458 if (response.IsUnsupportedResponse())
1459 return false;
1460 return true;
1461 }
1462 return false;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001463}
Greg Claytonb72d0f02011-04-12 05:54:46 +00001464
1465uint16_t
1466GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
1467{
1468 StringExtractorGDBRemote response;
1469 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
1470 {
1471 std::string name;
1472 std::string value;
1473 uint16_t port = 0;
1474 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1475 while (response.GetNameColonValue(name, value))
1476 {
1477 if (name.size() == 4 && name.compare("port") == 0)
1478 port = Args::StringToUInt32(value.c_str(), 0, 0);
1479 if (name.size() == 3 && name.compare("pid") == 0)
1480 pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
1481 }
1482 return port;
1483 }
1484 return 0;
1485}
1486
1487bool
1488GDBRemoteCommunicationClient::SetCurrentThread (int tid)
1489{
1490 if (m_curr_tid == tid)
1491 return true;
1492
1493 char packet[32];
1494 int packet_len;
1495 if (tid <= 0)
1496 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
1497 else
1498 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1499 assert (packet_len + 1 < sizeof(packet));
1500 StringExtractorGDBRemote response;
1501 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1502 {
1503 if (response.IsOKResponse())
1504 {
1505 m_curr_tid = tid;
1506 return true;
1507 }
1508 }
1509 return false;
1510}
1511
1512bool
1513GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid)
1514{
1515 if (m_curr_tid_run == tid)
1516 return true;
1517
1518 char packet[32];
1519 int packet_len;
1520 if (tid <= 0)
1521 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
1522 else
1523 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
1524
1525 assert (packet_len + 1 < sizeof(packet));
1526 StringExtractorGDBRemote response;
1527 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1528 {
1529 if (response.IsOKResponse())
1530 {
1531 m_curr_tid_run = tid;
1532 return true;
1533 }
1534 }
1535 return false;
1536}
1537
1538bool
1539GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
1540{
1541 if (SendPacketAndWaitForResponse("?", 1, response, false))
1542 return response.IsNormalResponse();
1543 return false;
1544}
1545
1546bool
1547GDBRemoteCommunicationClient::GetThreadStopInfo (uint32_t tid, StringExtractorGDBRemote &response)
1548{
1549 if (m_supports_qThreadStopInfo)
1550 {
1551 char packet[256];
1552 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%x", tid);
1553 assert (packet_len < sizeof(packet));
1554 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1555 {
1556 if (response.IsUnsupportedResponse())
1557 m_supports_qThreadStopInfo = false;
1558 else if (response.IsNormalResponse())
1559 return true;
1560 else
1561 return false;
1562 }
1563 }
1564 if (SetCurrentThread (tid))
1565 return GetStopReply (response);
1566 return false;
1567}
1568
1569
1570uint8_t
1571GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
1572{
1573 switch (type)
1574 {
1575 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
1576 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
1577 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
1578 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
1579 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
1580 default: return UINT8_MAX;
1581 }
1582
1583 char packet[64];
1584 const int packet_len = ::snprintf (packet,
1585 sizeof(packet),
1586 "%c%i,%llx,%x",
1587 insert ? 'Z' : 'z',
1588 type,
1589 addr,
1590 length);
1591
1592 assert (packet_len + 1 < sizeof(packet));
1593 StringExtractorGDBRemote response;
1594 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
1595 {
1596 if (response.IsOKResponse())
1597 return 0;
1598 if (response.IsUnsupportedResponse())
1599 {
1600 switch (type)
1601 {
1602 case eBreakpointSoftware: m_supports_z0 = false; break;
1603 case eBreakpointHardware: m_supports_z1 = false; break;
1604 case eWatchpointWrite: m_supports_z2 = false; break;
1605 case eWatchpointRead: m_supports_z3 = false; break;
1606 case eWatchpointReadWrite: m_supports_z4 = false; break;
1607 default: break;
1608 }
1609 }
1610 else if (response.IsErrorResponse())
1611 return response.GetError();
1612 }
1613 return UINT8_MAX;
1614}