blob: 85f56dd3ffb75b3e09ba4f2f1d12b0d7a3ea6f01 [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),
Greg Clayton2f085c62011-05-15 01:25:55 +000048 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton24bc5d92011-03-30 18:16:51 +000049 m_supports_qProcessInfoPID (true),
50 m_supports_qfProcessInfo (true),
51 m_supports_qUserName (true),
52 m_supports_qGroupName (true),
Greg Claytonb72d0f02011-04-12 05:54:46 +000053 m_supports_qThreadStopInfo (true),
54 m_supports_z0 (true),
55 m_supports_z1 (true),
56 m_supports_z2 (true),
57 m_supports_z3 (true),
58 m_supports_z4 (true),
59 m_curr_tid (LLDB_INVALID_THREAD_ID),
60 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Greg Clayton61d043b2011-03-22 04:00:09 +000061 m_async_mutex (Mutex::eMutexTypeRecursive),
62 m_async_packet_predicate (false),
63 m_async_packet (),
64 m_async_response (),
65 m_async_signal (-1),
Greg Clayton58e26e02011-03-24 04:28:38 +000066 m_host_arch(),
67 m_os_version_major (UINT32_MAX),
68 m_os_version_minor (UINT32_MAX),
69 m_os_version_update (UINT32_MAX)
Greg Clayton61d043b2011-03-22 04:00:09 +000070{
Greg Clayton61d043b2011-03-22 04:00:09 +000071}
72
73//----------------------------------------------------------------------
74// Destructor
75//----------------------------------------------------------------------
76GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
77{
Greg Clayton61d043b2011-03-22 04:00:09 +000078 if (IsConnected())
Greg Clayton61d043b2011-03-22 04:00:09 +000079 Disconnect();
Greg Clayton61d043b2011-03-22 04:00:09 +000080}
81
82bool
Greg Clayton58e26e02011-03-24 04:28:38 +000083GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
84{
85 // Start the read thread after we send the handshake ack since if we
86 // fail to send the handshake ack, there is no reason to continue...
87 if (SendAck())
Greg Clayton63afdb02011-06-17 01:22:15 +000088 return true;
Greg Clayton58e26e02011-03-24 04:28:38 +000089
90 if (error_ptr)
91 error_ptr->SetErrorString("failed to send the handshake ack");
92 return false;
93}
94
95void
96GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton61d043b2011-03-22 04:00:09 +000097{
98 if (m_supports_not_sending_acks == eLazyBoolCalculate)
99 {
Greg Clayton58e26e02011-03-24 04:28:38 +0000100 m_send_acks = true;
Greg Clayton61d043b2011-03-22 04:00:09 +0000101 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton58e26e02011-03-24 04:28:38 +0000102
103 StringExtractorGDBRemote response;
Greg Clayton61d043b2011-03-22 04:00:09 +0000104 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
105 {
106 if (response.IsOKResponse())
Greg Clayton58e26e02011-03-24 04:28:38 +0000107 {
108 m_send_acks = false;
Greg Clayton61d043b2011-03-22 04:00:09 +0000109 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton58e26e02011-03-24 04:28:38 +0000110 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000111 }
112 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000113}
114
115void
116GDBRemoteCommunicationClient::ResetDiscoverableSettings()
117{
118 m_supports_not_sending_acks = eLazyBoolCalculate;
119 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton61d043b2011-03-22 04:00:09 +0000120 m_supports_vCont_c = eLazyBoolCalculate;
121 m_supports_vCont_C = eLazyBoolCalculate;
122 m_supports_vCont_s = eLazyBoolCalculate;
123 m_supports_vCont_S = eLazyBoolCalculate;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000124 m_qHostInfo_is_valid = eLazyBoolCalculate;
Greg Clayton2f085c62011-05-15 01:25:55 +0000125 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton989816b2011-05-14 01:50:35 +0000126
Greg Clayton24bc5d92011-03-30 18:16:51 +0000127 m_supports_qProcessInfoPID = true;
128 m_supports_qfProcessInfo = true;
129 m_supports_qUserName = true;
130 m_supports_qGroupName = true;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000131 m_supports_qThreadStopInfo = true;
132 m_supports_z0 = true;
133 m_supports_z1 = true;
134 m_supports_z2 = true;
135 m_supports_z3 = true;
136 m_supports_z4 = true;
Greg Claytoncb8977d2011-03-23 00:09:55 +0000137 m_host_arch.Clear();
Greg Clayton61d043b2011-03-22 04:00:09 +0000138}
139
140
141bool
142GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
143{
144 if (m_supports_thread_suffix == eLazyBoolCalculate)
145 {
146 StringExtractorGDBRemote response;
147 m_supports_thread_suffix = eLazyBoolNo;
148 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
149 {
150 if (response.IsOKResponse())
151 m_supports_thread_suffix = eLazyBoolYes;
152 }
153 }
154 return m_supports_thread_suffix;
155}
156bool
157GDBRemoteCommunicationClient::GetVContSupported (char flavor)
158{
159 if (m_supports_vCont_c == eLazyBoolCalculate)
160 {
161 StringExtractorGDBRemote response;
162 m_supports_vCont_any = eLazyBoolNo;
163 m_supports_vCont_all = eLazyBoolNo;
164 m_supports_vCont_c = eLazyBoolNo;
165 m_supports_vCont_C = eLazyBoolNo;
166 m_supports_vCont_s = eLazyBoolNo;
167 m_supports_vCont_S = eLazyBoolNo;
168 if (SendPacketAndWaitForResponse("vCont?", response, false))
169 {
170 const char *response_cstr = response.GetStringRef().c_str();
171 if (::strstr (response_cstr, ";c"))
172 m_supports_vCont_c = eLazyBoolYes;
173
174 if (::strstr (response_cstr, ";C"))
175 m_supports_vCont_C = eLazyBoolYes;
176
177 if (::strstr (response_cstr, ";s"))
178 m_supports_vCont_s = eLazyBoolYes;
179
180 if (::strstr (response_cstr, ";S"))
181 m_supports_vCont_S = eLazyBoolYes;
182
183 if (m_supports_vCont_c == eLazyBoolYes &&
184 m_supports_vCont_C == eLazyBoolYes &&
185 m_supports_vCont_s == eLazyBoolYes &&
186 m_supports_vCont_S == eLazyBoolYes)
187 {
188 m_supports_vCont_all = eLazyBoolYes;
189 }
190
191 if (m_supports_vCont_c == eLazyBoolYes ||
192 m_supports_vCont_C == eLazyBoolYes ||
193 m_supports_vCont_s == eLazyBoolYes ||
194 m_supports_vCont_S == eLazyBoolYes)
195 {
196 m_supports_vCont_any = eLazyBoolYes;
197 }
198 }
199 }
200
201 switch (flavor)
202 {
203 case 'a': return m_supports_vCont_any;
204 case 'A': return m_supports_vCont_all;
205 case 'c': return m_supports_vCont_c;
206 case 'C': return m_supports_vCont_C;
207 case 's': return m_supports_vCont_s;
208 case 'S': return m_supports_vCont_S;
209 default: break;
210 }
211 return false;
212}
213
214
215size_t
216GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
217(
218 const char *payload,
219 StringExtractorGDBRemote &response,
220 bool send_async
221)
222{
223 return SendPacketAndWaitForResponse (payload,
224 ::strlen (payload),
225 response,
226 send_async);
227}
228
229size_t
230GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
231(
232 const char *payload,
233 size_t payload_length,
234 StringExtractorGDBRemote &response,
235 bool send_async
236)
237{
238 Mutex::Locker locker;
Greg Clayton61d043b2011-03-22 04:00:09 +0000239 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton801417e2011-07-07 01:59:51 +0000240 size_t response_len = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000241 if (GetSequenceMutex (locker))
242 {
Greg Clayton139da722011-05-20 03:15:54 +0000243 if (SendPacketNoLock (payload, payload_length))
Greg Clayton801417e2011-07-07 01:59:51 +0000244 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
245 else
246 {
247 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000248 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton801417e2011-07-07 01:59:51 +0000249 }
Greg Clayton61d043b2011-03-22 04:00:09 +0000250 }
251 else
252 {
253 if (send_async)
254 {
255 Mutex::Locker async_locker (m_async_mutex);
256 m_async_packet.assign(payload, payload_length);
257 m_async_packet_predicate.SetValue (true, eBroadcastNever);
258
259 if (log)
260 log->Printf ("async: async packet = %s", m_async_packet.c_str());
261
262 bool timed_out = false;
263 bool sent_interrupt = false;
264 if (SendInterrupt(locker, 2, sent_interrupt, timed_out))
265 {
266 if (sent_interrupt)
267 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000268 TimeValue timeout_time;
269 timeout_time = TimeValue::Now();
270 timeout_time.OffsetWithSeconds (m_packet_timeout);
271
Greg Clayton61d043b2011-03-22 04:00:09 +0000272 if (log)
273 log->Printf ("async: sent interrupt");
Greg Clayton801417e2011-07-07 01:59:51 +0000274
Greg Clayton61d043b2011-03-22 04:00:09 +0000275 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
276 {
277 if (log)
278 log->Printf ("async: got response");
Greg Clayton801417e2011-07-07 01:59:51 +0000279
280 // Swap the response buffer to avoid malloc and string copy
281 response.GetStringRef().swap (m_async_response.GetStringRef());
282 response_len = response.GetStringRef().size();
Greg Clayton61d043b2011-03-22 04:00:09 +0000283 }
284 else
285 {
286 if (log)
287 log->Printf ("async: timed out waiting for response");
288 }
289
290 // Make sure we wait until the continue packet has been sent again...
291 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
292 {
Greg Claytonb7669b32011-10-27 22:04:16 +0000293 if (log)
294 {
295 if (timed_out)
296 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
297 else
298 log->Printf ("async: async packet sent");
299 }
300 }
301 else
302 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000303 if (log)
304 log->Printf ("async: timed out waiting for process to resume");
305 }
306 }
307 else
308 {
309 // We had a racy condition where we went to send the interrupt
Greg Clayton801417e2011-07-07 01:59:51 +0000310 // yet we were able to get the lock
311 if (log)
312 log->Printf ("async: got lock but failed to send interrupt");
Greg Clayton61d043b2011-03-22 04:00:09 +0000313 }
314 }
315 else
316 {
317 if (log)
318 log->Printf ("async: failed to interrupt");
319 }
320 }
321 else
322 {
323 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000324 log->Printf("error: packet mutex taken and send_async == false, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton61d043b2011-03-22 04:00:09 +0000325 }
326 }
Greg Clayton801417e2011-07-07 01:59:51 +0000327 if (response_len == 0)
328 {
329 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000330 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton801417e2011-07-07 01:59:51 +0000331 }
332 return response_len;
Greg Clayton61d043b2011-03-22 04:00:09 +0000333}
334
335//template<typename _Tp>
336//class ScopedValueChanger
337//{
338//public:
339// // Take a value reference and the value to assign it to when this class
340// // instance goes out of scope.
341// ScopedValueChanger (_Tp &value_ref, _Tp value) :
342// m_value_ref (value_ref),
343// m_value (value)
344// {
345// }
346//
347// // This object is going out of scope, change the value pointed to by
348// // m_value_ref to the value we got during construction which was stored in
349// // m_value;
350// ~ScopedValueChanger ()
351// {
352// m_value_ref = m_value;
353// }
354//protected:
355// _Tp &m_value_ref; // A reference to the value we will change when this object destructs
356// _Tp m_value; // The value to assign to m_value_ref when this goes out of scope.
357//};
358
359StateType
360GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
361(
362 ProcessGDBRemote *process,
363 const char *payload,
364 size_t packet_length,
365 StringExtractorGDBRemote &response
366)
367{
368 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
369 if (log)
370 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
371
372 Mutex::Locker locker(m_sequence_mutex);
373 StateType state = eStateRunning;
374
375 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
376 m_public_is_running.SetValue (true, eBroadcastNever);
377 // Set the starting continue packet into "continue_packet". This packet
378 // make change if we are interrupted and we continue after an async packet...
379 std::string continue_packet(payload, packet_length);
380
Greg Clayton628cead2011-05-19 03:54:16 +0000381 bool got_stdout = false;
382
Greg Clayton61d043b2011-03-22 04:00:09 +0000383 while (state == eStateRunning)
384 {
Greg Clayton628cead2011-05-19 03:54:16 +0000385 if (!got_stdout)
386 {
387 if (log)
388 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
389 if (SendPacket(continue_packet.c_str(), continue_packet.size()) == 0)
390 state = eStateInvalid;
Greg Clayton61d043b2011-03-22 04:00:09 +0000391
Greg Claytonb7669b32011-10-27 22:04:16 +0000392 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Clayton628cead2011-05-19 03:54:16 +0000393 }
394
395 got_stdout = false;
Greg Clayton61d043b2011-03-22 04:00:09 +0000396
397 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000398 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +0000399
Greg Clayton63afdb02011-06-17 01:22:15 +0000400 if (WaitForPacketWithTimeoutMicroSeconds (response, UINT32_MAX))
Greg Clayton61d043b2011-03-22 04:00:09 +0000401 {
402 if (response.Empty())
403 state = eStateInvalid;
404 else
405 {
406 const char stop_type = response.GetChar();
407 if (log)
408 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
409 switch (stop_type)
410 {
411 case 'T':
412 case 'S':
413 if (process->GetStopID() == 0)
414 {
415 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
416 {
417 lldb::pid_t pid = GetCurrentProcessID ();
418 if (pid != LLDB_INVALID_PROCESS_ID)
419 process->SetID (pid);
420 }
421 process->BuildDynamicRegisterInfo (true);
422 }
423
424 // Privately notify any internal threads that we have stopped
425 // in case we wanted to interrupt our process, yet we might
426 // send a packet and continue without returning control to the
427 // user.
428 m_private_is_running.SetValue (false, eBroadcastAlways);
429 if (m_async_signal != -1)
430 {
431 if (log)
432 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
433
434 // Save off the async signal we are supposed to send
435 const int async_signal = m_async_signal;
436 // Clear the async signal member so we don't end up
437 // sending the signal multiple times...
438 m_async_signal = -1;
439 // Check which signal we stopped with
440 uint8_t signo = response.GetHexU8(255);
441 if (signo == async_signal)
442 {
443 if (log)
444 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
445
446 // We already stopped with a signal that we wanted
447 // to stop with, so we are done
448 response.SetFilePos (0);
449 }
450 else
451 {
452 // We stopped with a different signal that the one
453 // we wanted to stop with, so now we must resume
454 // with the signal we want
455 char signal_packet[32];
456 int signal_packet_len = 0;
457 signal_packet_len = ::snprintf (signal_packet,
458 sizeof (signal_packet),
459 "C%2.2x",
460 async_signal);
461
462 if (log)
463 log->Printf ("async: stopped with signal %s, resume with %s",
464 Host::GetSignalAsCString (signo),
465 Host::GetSignalAsCString (async_signal));
466
467 // Set the continue packet to resume...
468 continue_packet.assign(signal_packet, signal_packet_len);
469 continue;
470 }
471 }
472 else if (m_async_packet_predicate.GetValue())
473 {
474 // We are supposed to send an asynchronous packet while
475 // we are running.
476 m_async_response.Clear();
477 if (m_async_packet.empty())
478 {
479 if (log)
480 log->Printf ("async: error: empty async packet");
481
482 }
483 else
484 {
485 if (log)
486 log->Printf ("async: sending packet: %s",
487 m_async_packet.c_str());
488
489 SendPacketAndWaitForResponse (&m_async_packet[0],
490 m_async_packet.size(),
491 m_async_response,
492 false);
493 }
494 // Let the other thread that was trying to send the async
495 // packet know that the packet has been sent and response is
496 // ready...
497 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
498
499 // Set the continue packet to resume...
500 continue_packet.assign (1, 'c');
501 continue;
502 }
503 // Stop with signal and thread info
504 state = eStateStopped;
505 break;
506
507 case 'W':
508 case 'X':
509 // process exited
510 state = eStateExited;
511 break;
512
513 case 'O':
514 // STDOUT
515 {
Greg Clayton628cead2011-05-19 03:54:16 +0000516 got_stdout = true;
Greg Clayton61d043b2011-03-22 04:00:09 +0000517 std::string inferior_stdout;
518 inferior_stdout.reserve(response.GetBytesLeft () / 2);
519 char ch;
520 while ((ch = response.GetHexU8()) != '\0')
521 inferior_stdout.append(1, ch);
522 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
523 }
524 break;
525
526 case 'E':
527 // ERROR
528 state = eStateInvalid;
529 break;
530
531 default:
532 if (log)
533 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
534 state = eStateInvalid;
535 break;
536 }
537 }
538 }
539 else
540 {
541 if (log)
542 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
543 state = eStateInvalid;
544 }
545 }
546 if (log)
547 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
548 response.SetFilePos(0);
549 m_private_is_running.SetValue (false, eBroadcastAlways);
550 m_public_is_running.SetValue (false, eBroadcastAlways);
551 return state;
552}
553
554bool
555GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
556{
557 m_async_signal = signo;
558 bool timed_out = false;
559 bool sent_interrupt = false;
560 Mutex::Locker locker;
561 if (SendInterrupt (locker, 1, sent_interrupt, timed_out))
562 return true;
563 m_async_signal = -1;
564 return false;
565}
566
567// This function takes a mutex locker as a parameter in case the GetSequenceMutex
568// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
569// (the expected result), then it will send the halt packet. If it does succeed
570// then the caller that requested the interrupt will want to keep the sequence
571// locked down so that no one else can send packets while the caller has control.
572// This function usually gets called when we are running and need to stop the
573// target. It can also be used when we are running and and we need to do something
574// else (like read/write memory), so we need to interrupt the running process
575// (gdb remote protocol requires this), and do what we need to do, then resume.
576
577bool
578GDBRemoteCommunicationClient::SendInterrupt
579(
580 Mutex::Locker& locker,
581 uint32_t seconds_to_wait_for_stop,
582 bool &sent_interrupt,
583 bool &timed_out
584)
585{
586 sent_interrupt = false;
587 timed_out = false;
588 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
589
590 if (IsRunning())
591 {
592 // Only send an interrupt if our debugserver is running...
593 if (GetSequenceMutex (locker) == false)
594 {
595 // Someone has the mutex locked waiting for a response or for the
596 // inferior to stop, so send the interrupt on the down low...
597 char ctrl_c = '\x03';
598 ConnectionStatus status = eConnectionStatusSuccess;
599 TimeValue timeout;
600 if (seconds_to_wait_for_stop)
601 {
602 timeout = TimeValue::Now();
603 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
604 }
605 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
606 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS | GDBR_LOG_PROCESS, "send packet: \\x03");
607 if (bytes_written > 0)
608 {
609 sent_interrupt = true;
610 if (seconds_to_wait_for_stop)
611 {
612 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
613 {
614 if (log)
615 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, private state stopped", __FUNCTION__);
616 return true;
617 }
618 else
619 {
620 if (log)
621 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, timed out wating for async thread resume", __FUNCTION__);
622 }
623 }
624 else
625 {
626 if (log)
627 log->Printf ("GDBRemoteCommunicationClient::%s () - sent interrupt, not waiting for stop...", __FUNCTION__);
628 return true;
629 }
630 }
631 else
632 {
633 if (log)
634 log->Printf ("GDBRemoteCommunicationClient::%s () - failed to write interrupt", __FUNCTION__);
635 }
636 return false;
637 }
638 else
639 {
640 if (log)
641 log->Printf ("GDBRemoteCommunicationClient::%s () - got sequence mutex without having to interrupt", __FUNCTION__);
642 }
643 }
644 return true;
645}
646
647lldb::pid_t
648GDBRemoteCommunicationClient::GetCurrentProcessID ()
649{
650 StringExtractorGDBRemote response;
651 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
652 {
653 if (response.GetChar() == 'Q')
654 if (response.GetChar() == 'C')
655 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
656 }
657 return LLDB_INVALID_PROCESS_ID;
658}
659
660bool
661GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
662{
663 error_str.clear();
664 StringExtractorGDBRemote response;
665 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
666 {
667 if (response.IsOKResponse())
668 return true;
669 if (response.GetChar() == 'E')
670 {
671 // A string the describes what failed when launching...
672 error_str = response.GetStringRef().substr(1);
673 }
674 else
675 {
676 error_str.assign ("unknown error occurred launching process");
677 }
678 }
679 else
680 {
681 error_str.assign ("failed to send the qLaunchSuccess packet");
682 }
683 return false;
684}
685
686int
687GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
688{
689 if (argv && argv[0])
690 {
691 StreamString packet;
692 packet.PutChar('A');
693 const char *arg;
694 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
695 {
696 const int arg_len = strlen(arg);
697 if (i > 0)
698 packet.PutChar(',');
699 packet.Printf("%i,%i,", arg_len * 2, i);
700 packet.PutBytesAsRawHex8 (arg, arg_len);
701 }
702
703 StringExtractorGDBRemote response;
704 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
705 {
706 if (response.IsOKResponse())
707 return 0;
708 uint8_t error = response.GetError();
709 if (error)
710 return error;
711 }
712 }
713 return -1;
714}
715
716int
717GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
718{
719 if (name_equal_value && name_equal_value[0])
720 {
721 StreamString packet;
722 packet.Printf("QEnvironment:%s", name_equal_value);
723 StringExtractorGDBRemote response;
724 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
725 {
726 if (response.IsOKResponse())
727 return 0;
728 uint8_t error = response.GetError();
729 if (error)
730 return error;
731 }
732 }
733 return -1;
734}
735
Greg Claytona4582402011-05-08 04:53:50 +0000736int
737GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
738{
739 if (arch && arch[0])
740 {
741 StreamString packet;
742 packet.Printf("QLaunchArch:%s", arch);
743 StringExtractorGDBRemote response;
744 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
745 {
746 if (response.IsOKResponse())
747 return 0;
748 uint8_t error = response.GetError();
749 if (error)
750 return error;
751 }
752 }
753 return -1;
754}
755
Greg Clayton61d043b2011-03-22 04:00:09 +0000756bool
Greg Clayton58e26e02011-03-24 04:28:38 +0000757GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
758 uint32_t &minor,
759 uint32_t &update)
760{
761 if (GetHostInfo ())
762 {
763 if (m_os_version_major != UINT32_MAX)
764 {
765 major = m_os_version_major;
766 minor = m_os_version_minor;
767 update = m_os_version_update;
768 return true;
769 }
770 }
771 return false;
772}
773
774bool
775GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
776{
777 if (GetHostInfo ())
778 {
779 if (!m_os_build.empty())
780 {
781 s = m_os_build;
782 return true;
783 }
784 }
785 s.clear();
786 return false;
787}
788
789
790bool
791GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
792{
793 if (GetHostInfo ())
794 {
795 if (!m_os_kernel.empty())
796 {
797 s = m_os_kernel;
798 return true;
799 }
800 }
801 s.clear();
802 return false;
803}
804
805bool
806GDBRemoteCommunicationClient::GetHostname (std::string &s)
807{
808 if (GetHostInfo ())
809 {
810 if (!m_hostname.empty())
811 {
812 s = m_hostname;
813 return true;
814 }
815 }
816 s.clear();
817 return false;
818}
819
820ArchSpec
821GDBRemoteCommunicationClient::GetSystemArchitecture ()
822{
823 if (GetHostInfo ())
824 return m_host_arch;
825 return ArchSpec();
826}
827
828
829bool
Greg Clayton06d7cc82011-04-04 18:18:57 +0000830GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton61d043b2011-03-22 04:00:09 +0000831{
Greg Clayton06d7cc82011-04-04 18:18:57 +0000832 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +0000833 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000834 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton61d043b2011-03-22 04:00:09 +0000835 StringExtractorGDBRemote response;
836 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
837 {
Greg Clayton5b53e8e2011-05-15 23:46:54 +0000838 if (response.IsNormalResponse())
Greg Claytoncb8977d2011-03-23 00:09:55 +0000839 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000840 std::string name;
841 std::string value;
842 uint32_t cpu = LLDB_INVALID_CPUTYPE;
843 uint32_t sub = 0;
844 std::string arch_name;
845 std::string os_name;
846 std::string vendor_name;
847 std::string triple;
848 uint32_t pointer_byte_size = 0;
849 StringExtractor extractor;
850 ByteOrder byte_order = eByteOrderInvalid;
851 uint32_t num_keys_decoded = 0;
852 while (response.GetNameColonValue(name, value))
Greg Claytoncb8977d2011-03-23 00:09:55 +0000853 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000854 if (name.compare("cputype") == 0)
Greg Clayton58e26e02011-03-24 04:28:38 +0000855 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000856 // exception type in big endian hex
857 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
858 if (cpu != LLDB_INVALID_CPUTYPE)
859 ++num_keys_decoded;
860 }
861 else if (name.compare("cpusubtype") == 0)
862 {
863 // exception count in big endian hex
864 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
865 if (sub != 0)
866 ++num_keys_decoded;
867 }
868 else if (name.compare("arch") == 0)
869 {
870 arch_name.swap (value);
871 ++num_keys_decoded;
872 }
873 else if (name.compare("triple") == 0)
874 {
875 // The triple comes as ASCII hex bytes since it contains '-' chars
876 extractor.GetStringRef().swap(value);
877 extractor.SetFilePos(0);
878 extractor.GetHexByteString (triple);
879 ++num_keys_decoded;
880 }
881 else if (name.compare("os_build") == 0)
882 {
883 extractor.GetStringRef().swap(value);
884 extractor.SetFilePos(0);
885 extractor.GetHexByteString (m_os_build);
886 ++num_keys_decoded;
887 }
888 else if (name.compare("hostname") == 0)
889 {
890 extractor.GetStringRef().swap(value);
891 extractor.SetFilePos(0);
892 extractor.GetHexByteString (m_hostname);
893 ++num_keys_decoded;
894 }
895 else if (name.compare("os_kernel") == 0)
896 {
897 extractor.GetStringRef().swap(value);
898 extractor.SetFilePos(0);
899 extractor.GetHexByteString (m_os_kernel);
900 ++num_keys_decoded;
901 }
902 else if (name.compare("ostype") == 0)
903 {
904 os_name.swap (value);
905 ++num_keys_decoded;
906 }
907 else if (name.compare("vendor") == 0)
908 {
909 vendor_name.swap(value);
910 ++num_keys_decoded;
911 }
912 else if (name.compare("endian") == 0)
913 {
914 ++num_keys_decoded;
915 if (value.compare("little") == 0)
916 byte_order = eByteOrderLittle;
917 else if (value.compare("big") == 0)
918 byte_order = eByteOrderBig;
919 else if (value.compare("pdp") == 0)
920 byte_order = eByteOrderPDP;
921 else
922 --num_keys_decoded;
923 }
924 else if (name.compare("ptrsize") == 0)
925 {
926 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
927 if (pointer_byte_size != 0)
928 ++num_keys_decoded;
929 }
930 else if (name.compare("os_version") == 0)
931 {
932 Args::StringToVersion (value.c_str(),
933 m_os_version_major,
934 m_os_version_minor,
935 m_os_version_update);
936 if (m_os_version_major != UINT32_MAX)
937 ++num_keys_decoded;
938 }
939 }
940
941 if (num_keys_decoded > 0)
942 m_qHostInfo_is_valid = eLazyBoolYes;
943
944 if (triple.empty())
945 {
946 if (arch_name.empty())
947 {
948 if (cpu != LLDB_INVALID_CPUTYPE)
949 {
950 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
951 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 }
959 if (!vendor_name.empty())
960 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
961 if (!os_name.empty())
Greg Clayton89798cc2011-09-15 00:21:03 +0000962 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton24bc5d92011-03-30 18:16:51 +0000963
964 }
965 }
966 else
967 {
968 std::string triple;
969 triple += arch_name;
970 triple += '-';
971 if (vendor_name.empty())
972 triple += "unknown";
973 else
974 triple += vendor_name;
975 triple += '-';
976 if (os_name.empty())
977 triple += "unknown";
978 else
979 triple += os_name;
Greg Claytonf15996e2011-04-07 22:46:35 +0000980 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Clayton58e26e02011-03-24 04:28:38 +0000981 if (pointer_byte_size)
982 {
983 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
984 }
985 if (byte_order != eByteOrderInvalid)
986 {
987 assert (byte_order == m_host_arch.GetByteOrder());
988 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000989
Greg Clayton58e26e02011-03-24 04:28:38 +0000990 }
991 }
992 else
993 {
Greg Claytonf15996e2011-04-07 22:46:35 +0000994 m_host_arch.SetTriple (triple.c_str(), NULL);
Greg Claytoncb8977d2011-03-23 00:09:55 +0000995 if (pointer_byte_size)
996 {
997 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
998 }
999 if (byte_order != eByteOrderInvalid)
1000 {
1001 assert (byte_order == m_host_arch.GetByteOrder());
1002 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001003 }
Greg Claytoncb8977d2011-03-23 00:09:55 +00001004 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001005 }
1006 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001007 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton61d043b2011-03-22 04:00:09 +00001008}
1009
1010int
1011GDBRemoteCommunicationClient::SendAttach
1012(
1013 lldb::pid_t pid,
1014 StringExtractorGDBRemote& response
1015)
1016{
1017 if (pid != LLDB_INVALID_PROCESS_ID)
1018 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001019 char packet[64];
1020 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", pid);
1021 assert (packet_len < sizeof(packet));
1022 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001023 {
1024 if (response.IsErrorResponse())
1025 return response.GetError();
1026 return 0;
1027 }
1028 }
1029 return -1;
1030}
1031
1032const lldb_private::ArchSpec &
1033GDBRemoteCommunicationClient::GetHostArchitecture ()
1034{
Greg Clayton24bc5d92011-03-30 18:16:51 +00001035 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton61d043b2011-03-22 04:00:09 +00001036 GetHostInfo ();
Greg Claytoncb8977d2011-03-23 00:09:55 +00001037 return m_host_arch;
Greg Clayton61d043b2011-03-22 04:00:09 +00001038}
1039
1040addr_t
1041GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1042{
Greg Clayton2f085c62011-05-15 01:25:55 +00001043 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton61d043b2011-03-22 04:00:09 +00001044 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001045 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton989816b2011-05-14 01:50:35 +00001046 char packet[64];
1047 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
1048 permissions & lldb::ePermissionsReadable ? "r" : "",
1049 permissions & lldb::ePermissionsWritable ? "w" : "",
1050 permissions & lldb::ePermissionsExecutable ? "x" : "");
1051 assert (packet_len < sizeof(packet));
1052 StringExtractorGDBRemote response;
1053 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1054 {
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001055 if (!response.IsErrorResponse())
Greg Clayton989816b2011-05-14 01:50:35 +00001056 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1057 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001058 else
1059 {
1060 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1061 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001062 }
1063 return LLDB_INVALID_ADDRESS;
1064}
1065
1066bool
1067GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1068{
Greg Clayton2f085c62011-05-15 01:25:55 +00001069 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton61d043b2011-03-22 04:00:09 +00001070 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001071 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton989816b2011-05-14 01:50:35 +00001072 char packet[64];
1073 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
1074 assert (packet_len < sizeof(packet));
1075 StringExtractorGDBRemote response;
1076 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1077 {
1078 if (response.IsOKResponse())
1079 return true;
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001080 }
1081 else
1082 {
1083 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton989816b2011-05-14 01:50:35 +00001084 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001085 }
1086 return false;
1087}
1088
1089int
1090GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1091{
1092 if (path && path[0])
1093 {
1094 StreamString packet;
1095 packet.PutCString("QSetSTDIN:");
1096 packet.PutBytesAsRawHex8(path, strlen(path));
1097
1098 StringExtractorGDBRemote response;
1099 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1100 {
1101 if (response.IsOKResponse())
1102 return 0;
1103 uint8_t error = response.GetError();
1104 if (error)
1105 return error;
1106 }
1107 }
1108 return -1;
1109}
1110
1111int
1112GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1113{
1114 if (path && path[0])
1115 {
1116 StreamString packet;
1117 packet.PutCString("QSetSTDOUT:");
1118 packet.PutBytesAsRawHex8(path, strlen(path));
1119
1120 StringExtractorGDBRemote response;
1121 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1122 {
1123 if (response.IsOKResponse())
1124 return 0;
1125 uint8_t error = response.GetError();
1126 if (error)
1127 return error;
1128 }
1129 }
1130 return -1;
1131}
1132
1133int
1134GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1135{
1136 if (path && path[0])
1137 {
1138 StreamString packet;
1139 packet.PutCString("QSetSTDERR:");
1140 packet.PutBytesAsRawHex8(path, strlen(path));
1141
1142 StringExtractorGDBRemote response;
1143 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1144 {
1145 if (response.IsOKResponse())
1146 return 0;
1147 uint8_t error = response.GetError();
1148 if (error)
1149 return error;
1150 }
1151 }
1152 return -1;
1153}
1154
1155int
1156GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1157{
1158 if (path && path[0])
1159 {
1160 StreamString packet;
1161 packet.PutCString("QSetWorkingDir:");
1162 packet.PutBytesAsRawHex8(path, strlen(path));
1163
1164 StringExtractorGDBRemote response;
1165 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1166 {
1167 if (response.IsOKResponse())
1168 return 0;
1169 uint8_t error = response.GetError();
1170 if (error)
1171 return error;
1172 }
1173 }
1174 return -1;
1175}
1176
1177int
1178GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1179{
Greg Clayton24bc5d92011-03-30 18:16:51 +00001180 char packet[32];
1181 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1182 assert (packet_len < sizeof(packet));
Greg Clayton61d043b2011-03-22 04:00:09 +00001183 StringExtractorGDBRemote response;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001184 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton61d043b2011-03-22 04:00:09 +00001185 {
1186 if (response.IsOKResponse())
1187 return 0;
1188 uint8_t error = response.GetError();
1189 if (error)
1190 return error;
1191 }
1192 return -1;
1193}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001194
1195bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001196GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001197{
1198 if (response.IsNormalResponse())
1199 {
1200 std::string name;
1201 std::string value;
1202 StringExtractor extractor;
1203
1204 while (response.GetNameColonValue(name, value))
1205 {
1206 if (name.compare("pid") == 0)
1207 {
1208 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1209 }
1210 else if (name.compare("ppid") == 0)
1211 {
1212 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1213 }
1214 else if (name.compare("uid") == 0)
1215 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001216 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001217 }
1218 else if (name.compare("euid") == 0)
1219 {
1220 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1221 }
1222 else if (name.compare("gid") == 0)
1223 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001224 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton24bc5d92011-03-30 18:16:51 +00001225 }
1226 else if (name.compare("egid") == 0)
1227 {
1228 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1229 }
1230 else if (name.compare("triple") == 0)
1231 {
1232 // The triple comes as ASCII hex bytes since it contains '-' chars
1233 extractor.GetStringRef().swap(value);
1234 extractor.SetFilePos(0);
1235 extractor.GetHexByteString (value);
Greg Claytonf15996e2011-04-07 22:46:35 +00001236 process_info.GetArchitecture ().SetTriple (value.c_str(), NULL);
Greg Clayton24bc5d92011-03-30 18:16:51 +00001237 }
1238 else if (name.compare("name") == 0)
1239 {
1240 StringExtractor extractor;
1241 // The the process name from ASCII hex bytes since we can't
1242 // control the characters in a process name
1243 extractor.GetStringRef().swap(value);
1244 extractor.SetFilePos(0);
1245 extractor.GetHexByteString (value);
Greg Claytonff39f742011-04-01 00:29:43 +00001246 process_info.SetName (value.c_str());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001247 }
1248 }
1249
1250 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1251 return true;
1252 }
1253 return false;
1254}
1255
1256bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001257GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001258{
1259 process_info.Clear();
1260
1261 if (m_supports_qProcessInfoPID)
1262 {
1263 char packet[32];
1264 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%i", pid);
1265 assert (packet_len < sizeof(packet));
1266 StringExtractorGDBRemote response;
1267 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1268 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001269 return DecodeProcessInfoResponse (response, process_info);
1270 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001271 else
1272 {
1273 m_supports_qProcessInfoPID = false;
1274 return false;
1275 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001276 }
1277 return false;
1278}
1279
1280uint32_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001281GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1282 ProcessInstanceInfoList &process_infos)
Greg Clayton24bc5d92011-03-30 18:16:51 +00001283{
1284 process_infos.Clear();
1285
1286 if (m_supports_qfProcessInfo)
1287 {
1288 StreamString packet;
1289 packet.PutCString ("qfProcessInfo");
1290 if (!match_info.MatchAllProcesses())
1291 {
1292 packet.PutChar (':');
1293 const char *name = match_info.GetProcessInfo().GetName();
1294 bool has_name_match = false;
1295 if (name && name[0])
1296 {
1297 has_name_match = true;
1298 NameMatchType name_match_type = match_info.GetNameMatchType();
1299 switch (name_match_type)
1300 {
1301 case eNameMatchIgnore:
1302 has_name_match = false;
1303 break;
1304
1305 case eNameMatchEquals:
1306 packet.PutCString ("name_match:equals;");
1307 break;
1308
1309 case eNameMatchContains:
1310 packet.PutCString ("name_match:contains;");
1311 break;
1312
1313 case eNameMatchStartsWith:
1314 packet.PutCString ("name_match:starts_with;");
1315 break;
1316
1317 case eNameMatchEndsWith:
1318 packet.PutCString ("name_match:ends_with;");
1319 break;
1320
1321 case eNameMatchRegularExpression:
1322 packet.PutCString ("name_match:regex;");
1323 break;
1324 }
1325 if (has_name_match)
1326 {
1327 packet.PutCString ("name:");
1328 packet.PutBytesAsRawHex8(name, ::strlen(name));
1329 packet.PutChar (';');
1330 }
1331 }
1332
1333 if (match_info.GetProcessInfo().ProcessIDIsValid())
1334 packet.Printf("pid:%u;",match_info.GetProcessInfo().GetProcessID());
1335 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1336 packet.Printf("parent_pid:%u;",match_info.GetProcessInfo().GetParentProcessID());
Greg Claytonb72d0f02011-04-12 05:54:46 +00001337 if (match_info.GetProcessInfo().UserIDIsValid())
1338 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1339 if (match_info.GetProcessInfo().GroupIDIsValid())
1340 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton24bc5d92011-03-30 18:16:51 +00001341 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1342 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1343 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1344 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1345 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1346 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1347 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1348 {
1349 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1350 const llvm::Triple &triple = match_arch.GetTriple();
1351 packet.PutCString("triple:");
1352 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1353 packet.PutChar (';');
1354 }
1355 }
1356 StringExtractorGDBRemote response;
1357 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1358 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001359 do
1360 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001361 ProcessInstanceInfo process_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001362 if (!DecodeProcessInfoResponse (response, process_info))
1363 break;
1364 process_infos.Append(process_info);
1365 response.GetStringRef().clear();
1366 response.SetFilePos(0);
1367 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1368 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001369 else
1370 {
1371 m_supports_qfProcessInfo = false;
1372 return 0;
1373 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001374 }
1375 return process_infos.GetSize();
1376
1377}
1378
1379bool
1380GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
1381{
1382 if (m_supports_qUserName)
1383 {
1384 char packet[32];
1385 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
1386 assert (packet_len < sizeof(packet));
1387 StringExtractorGDBRemote response;
1388 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1389 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001390 if (response.IsNormalResponse())
1391 {
1392 // Make sure we parsed the right number of characters. The response is
1393 // the hex encoded user name and should make up the entire packet.
1394 // If there are any non-hex ASCII bytes, the length won't match below..
1395 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1396 return true;
1397 }
1398 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001399 else
1400 {
1401 m_supports_qUserName = false;
1402 return false;
1403 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001404 }
1405 return false;
1406
1407}
1408
1409bool
1410GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
1411{
1412 if (m_supports_qGroupName)
1413 {
1414 char packet[32];
1415 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
1416 assert (packet_len < sizeof(packet));
1417 StringExtractorGDBRemote response;
1418 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1419 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001420 if (response.IsNormalResponse())
1421 {
1422 // Make sure we parsed the right number of characters. The response is
1423 // the hex encoded group name and should make up the entire packet.
1424 // If there are any non-hex ASCII bytes, the length won't match below..
1425 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
1426 return true;
1427 }
1428 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001429 else
1430 {
1431 m_supports_qGroupName = false;
1432 return false;
1433 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00001434 }
1435 return false;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001436}
Greg Clayton24bc5d92011-03-30 18:16:51 +00001437
Greg Clayton06d7cc82011-04-04 18:18:57 +00001438void
1439GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
1440{
1441 uint32_t i;
1442 TimeValue start_time, end_time;
1443 uint64_t total_time_nsec;
1444 float packets_per_second;
1445 if (SendSpeedTestPacket (0, 0))
1446 {
1447 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
1448 {
1449 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
1450 {
1451 start_time = TimeValue::Now();
1452 for (i=0; i<num_packets; ++i)
1453 {
1454 SendSpeedTestPacket (send_size, recv_size);
1455 }
1456 end_time = TimeValue::Now();
1457 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourne20fe30c2011-06-18 23:52:14 +00001458 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Greg Clayton153ccd72011-08-10 02:10:13 +00001459 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %llu.%9.9llu sec for %f packets/sec.\n",
Greg Clayton06d7cc82011-04-04 18:18:57 +00001460 num_packets,
1461 send_size,
1462 recv_size,
Peter Collingbourne20fe30c2011-06-18 23:52:14 +00001463 total_time_nsec / TimeValue::NanoSecPerSec,
1464 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001465 packets_per_second);
1466 if (recv_size == 0)
1467 recv_size = 32;
1468 }
1469 if (send_size == 0)
1470 send_size = 32;
1471 }
1472 }
1473 else
1474 {
1475 start_time = TimeValue::Now();
1476 for (i=0; i<num_packets; ++i)
1477 {
1478 GetCurrentProcessID ();
1479 }
1480 end_time = TimeValue::Now();
1481 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourne20fe30c2011-06-18 23:52:14 +00001482 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Greg Clayton153ccd72011-08-10 02:10:13 +00001483 printf ("%u 'qC' packets packets in 0x%llu%9.9llu sec for %f packets/sec.\n",
Greg Clayton06d7cc82011-04-04 18:18:57 +00001484 num_packets,
Peter Collingbourne20fe30c2011-06-18 23:52:14 +00001485 total_time_nsec / TimeValue::NanoSecPerSec,
1486 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton06d7cc82011-04-04 18:18:57 +00001487 packets_per_second);
1488 }
1489}
1490
1491bool
1492GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
1493{
1494 StreamString packet;
1495 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
1496 uint32_t bytes_left = send_size;
1497 while (bytes_left > 0)
1498 {
1499 if (bytes_left >= 26)
1500 {
1501 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
1502 bytes_left -= 26;
1503 }
1504 else
1505 {
1506 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
1507 bytes_left = 0;
1508 }
1509 }
1510
1511 StringExtractorGDBRemote response;
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001512 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton06d7cc82011-04-04 18:18:57 +00001513 return false;
Greg Clayton24bc5d92011-03-30 18:16:51 +00001514}
Greg Claytonb72d0f02011-04-12 05:54:46 +00001515
1516uint16_t
1517GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
1518{
1519 StringExtractorGDBRemote response;
1520 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
1521 {
1522 std::string name;
1523 std::string value;
1524 uint16_t port = 0;
1525 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1526 while (response.GetNameColonValue(name, value))
1527 {
1528 if (name.size() == 4 && name.compare("port") == 0)
1529 port = Args::StringToUInt32(value.c_str(), 0, 0);
1530 if (name.size() == 3 && name.compare("pid") == 0)
1531 pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
1532 }
1533 return port;
1534 }
1535 return 0;
1536}
1537
1538bool
1539GDBRemoteCommunicationClient::SetCurrentThread (int tid)
1540{
1541 if (m_curr_tid == tid)
1542 return true;
1543
1544 char packet[32];
1545 int packet_len;
1546 if (tid <= 0)
1547 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
1548 else
1549 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1550 assert (packet_len + 1 < sizeof(packet));
1551 StringExtractorGDBRemote response;
1552 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1553 {
1554 if (response.IsOKResponse())
1555 {
1556 m_curr_tid = tid;
1557 return true;
1558 }
1559 }
1560 return false;
1561}
1562
1563bool
1564GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid)
1565{
1566 if (m_curr_tid_run == tid)
1567 return true;
1568
1569 char packet[32];
1570 int packet_len;
1571 if (tid <= 0)
1572 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
1573 else
1574 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
1575
1576 assert (packet_len + 1 < sizeof(packet));
1577 StringExtractorGDBRemote response;
1578 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1579 {
1580 if (response.IsOKResponse())
1581 {
1582 m_curr_tid_run = tid;
1583 return true;
1584 }
1585 }
1586 return false;
1587}
1588
1589bool
1590GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
1591{
1592 if (SendPacketAndWaitForResponse("?", 1, response, false))
1593 return response.IsNormalResponse();
1594 return false;
1595}
1596
1597bool
1598GDBRemoteCommunicationClient::GetThreadStopInfo (uint32_t tid, StringExtractorGDBRemote &response)
1599{
1600 if (m_supports_qThreadStopInfo)
1601 {
1602 char packet[256];
1603 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%x", tid);
1604 assert (packet_len < sizeof(packet));
1605 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
1606 {
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001607 if (response.IsNormalResponse())
Greg Claytonb72d0f02011-04-12 05:54:46 +00001608 return true;
1609 else
1610 return false;
1611 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001612 else
1613 {
1614 m_supports_qThreadStopInfo = false;
1615 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001616 }
Greg Clayton139da722011-05-20 03:15:54 +00001617// if (SetCurrentThread (tid))
1618// return GetStopReply (response);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001619 return false;
1620}
1621
1622
1623uint8_t
1624GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
1625{
1626 switch (type)
1627 {
1628 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
1629 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
1630 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
1631 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
1632 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
1633 default: return UINT8_MAX;
1634 }
1635
1636 char packet[64];
1637 const int packet_len = ::snprintf (packet,
1638 sizeof(packet),
1639 "%c%i,%llx,%x",
1640 insert ? 'Z' : 'z',
1641 type,
1642 addr,
1643 length);
1644
1645 assert (packet_len + 1 < sizeof(packet));
1646 StringExtractorGDBRemote response;
1647 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
1648 {
1649 if (response.IsOKResponse())
1650 return 0;
Greg Claytonb72d0f02011-04-12 05:54:46 +00001651 else if (response.IsErrorResponse())
1652 return response.GetError();
1653 }
Greg Clayton5b53e8e2011-05-15 23:46:54 +00001654 else
1655 {
1656 switch (type)
1657 {
1658 case eBreakpointSoftware: m_supports_z0 = false; break;
1659 case eBreakpointHardware: m_supports_z1 = false; break;
1660 case eWatchpointWrite: m_supports_z2 = false; break;
1661 case eWatchpointRead: m_supports_z3 = false; break;
1662 case eWatchpointReadWrite: m_supports_z4 = false; break;
1663 default: break;
1664 }
1665 }
1666
Greg Claytonb72d0f02011-04-12 05:54:46 +00001667 return UINT8_MAX;
1668}
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001669
1670size_t
1671GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
1672 bool &sequence_mutex_unavailable)
1673{
1674 Mutex::Locker locker;
1675 thread_ids.clear();
1676
1677 if (GetSequenceMutex (locker))
1678 {
1679 sequence_mutex_unavailable = false;
1680 StringExtractorGDBRemote response;
1681
Greg Clayton63afdb02011-06-17 01:22:15 +00001682 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001683 response.IsNormalResponse();
Greg Clayton63afdb02011-06-17 01:22:15 +00001684 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001685 {
1686 char ch = response.GetChar();
1687 if (ch == 'l')
1688 break;
1689 if (ch == 'm')
1690 {
1691 do
1692 {
1693 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1694
1695 if (tid != LLDB_INVALID_THREAD_ID)
1696 {
1697 thread_ids.push_back (tid);
1698 }
1699 ch = response.GetChar(); // Skip the command separator
1700 } while (ch == ','); // Make sure we got a comma separator
1701 }
1702 }
1703 }
1704 else
1705 {
1706 sequence_mutex_unavailable = true;
1707 }
1708 return thread_ids.size();
1709}