1 //===-- 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 #include <sstream>
16
17 // Other libraries and framework includes
18 #include "llvm/ADT/Triple.h"
19 #include "lldb/Interpreter/Args.h"
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/Endian.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/TimeValue.h"
27
28 // Project includes
29 #include "Utility/StringExtractorGDBRemote.h"
30 #include "ProcessGDBRemote.h"
31 #include "ProcessGDBRemoteLog.h"
32
33 using namespace lldb;
34 using namespace lldb_private;
35
36 //----------------------------------------------------------------------
37 // GDBRemoteCommunicationClient constructor
38 //----------------------------------------------------------------------
GDBRemoteCommunicationClient(bool is_platform)39 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
40 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
41 m_supports_not_sending_acks (eLazyBoolCalculate),
42 m_supports_thread_suffix (eLazyBoolCalculate),
43 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
44 m_supports_vCont_all (eLazyBoolCalculate),
45 m_supports_vCont_any (eLazyBoolCalculate),
46 m_supports_vCont_c (eLazyBoolCalculate),
47 m_supports_vCont_C (eLazyBoolCalculate),
48 m_supports_vCont_s (eLazyBoolCalculate),
49 m_supports_vCont_S (eLazyBoolCalculate),
50 m_qHostInfo_is_valid (eLazyBoolCalculate),
51 m_qProcessInfo_is_valid (eLazyBoolCalculate),
52 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
53 m_supports_memory_region_info (eLazyBoolCalculate),
54 m_supports_watchpoint_support_info (eLazyBoolCalculate),
55 m_supports_detach_stay_stopped (eLazyBoolCalculate),
56 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
57 m_attach_or_wait_reply(eLazyBoolCalculate),
58 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
59 m_supports_qProcessInfoPID (true),
60 m_supports_qfProcessInfo (true),
61 m_supports_qUserName (true),
62 m_supports_qGroupName (true),
63 m_supports_qThreadStopInfo (true),
64 m_supports_z0 (true),
65 m_supports_z1 (true),
66 m_supports_z2 (true),
67 m_supports_z3 (true),
68 m_supports_z4 (true),
69 m_curr_tid (LLDB_INVALID_THREAD_ID),
70 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
71 m_num_supported_hardware_watchpoints (0),
72 m_async_mutex (Mutex::eMutexTypeRecursive),
73 m_async_packet_predicate (false),
74 m_async_packet (),
75 m_async_response (),
76 m_async_signal (-1),
77 m_thread_id_to_used_usec_map (),
78 m_host_arch(),
79 m_process_arch(),
80 m_os_version_major (UINT32_MAX),
81 m_os_version_minor (UINT32_MAX),
82 m_os_version_update (UINT32_MAX)
83 {
84 }
85
86 //----------------------------------------------------------------------
87 // Destructor
88 //----------------------------------------------------------------------
~GDBRemoteCommunicationClient()89 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
90 {
91 if (IsConnected())
92 Disconnect();
93 }
94
95 bool
HandshakeWithServer(Error * error_ptr)96 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
97 {
98 // Start the read thread after we send the handshake ack since if we
99 // fail to send the handshake ack, there is no reason to continue...
100 if (SendAck())
101 return true;
102
103 if (error_ptr)
104 error_ptr->SetErrorString("failed to send the handshake ack");
105 return false;
106 }
107
108 void
QueryNoAckModeSupported()109 GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
110 {
111 if (m_supports_not_sending_acks == eLazyBoolCalculate)
112 {
113 m_send_acks = true;
114 m_supports_not_sending_acks = eLazyBoolNo;
115
116 StringExtractorGDBRemote response;
117 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
118 {
119 if (response.IsOKResponse())
120 {
121 m_send_acks = false;
122 m_supports_not_sending_acks = eLazyBoolYes;
123 }
124 }
125 }
126 }
127
128 void
GetListThreadsInStopReplySupported()129 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
130 {
131 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
132 {
133 m_supports_threads_in_stop_reply = eLazyBoolNo;
134
135 StringExtractorGDBRemote response;
136 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
137 {
138 if (response.IsOKResponse())
139 m_supports_threads_in_stop_reply = eLazyBoolYes;
140 }
141 }
142 }
143
144 bool
GetVAttachOrWaitSupported()145 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
146 {
147 if (m_attach_or_wait_reply == eLazyBoolCalculate)
148 {
149 m_attach_or_wait_reply = eLazyBoolNo;
150
151 StringExtractorGDBRemote response;
152 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
153 {
154 if (response.IsOKResponse())
155 m_attach_or_wait_reply = eLazyBoolYes;
156 }
157 }
158 if (m_attach_or_wait_reply == eLazyBoolYes)
159 return true;
160 else
161 return false;
162 }
163
164 bool
GetSyncThreadStateSupported()165 GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
166 {
167 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
168 {
169 m_prepare_for_reg_writing_reply = eLazyBoolNo;
170
171 StringExtractorGDBRemote response;
172 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
173 {
174 if (response.IsOKResponse())
175 m_prepare_for_reg_writing_reply = eLazyBoolYes;
176 }
177 }
178 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
179 return true;
180 else
181 return false;
182 }
183
184
185 void
ResetDiscoverableSettings()186 GDBRemoteCommunicationClient::ResetDiscoverableSettings()
187 {
188 m_supports_not_sending_acks = eLazyBoolCalculate;
189 m_supports_thread_suffix = eLazyBoolCalculate;
190 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
191 m_supports_vCont_c = eLazyBoolCalculate;
192 m_supports_vCont_C = eLazyBoolCalculate;
193 m_supports_vCont_s = eLazyBoolCalculate;
194 m_supports_vCont_S = eLazyBoolCalculate;
195 m_qHostInfo_is_valid = eLazyBoolCalculate;
196 m_qProcessInfo_is_valid = eLazyBoolCalculate;
197 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
198 m_supports_memory_region_info = eLazyBoolCalculate;
199 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
200 m_attach_or_wait_reply = eLazyBoolCalculate;
201
202 m_supports_qProcessInfoPID = true;
203 m_supports_qfProcessInfo = true;
204 m_supports_qUserName = true;
205 m_supports_qGroupName = true;
206 m_supports_qThreadStopInfo = true;
207 m_supports_z0 = true;
208 m_supports_z1 = true;
209 m_supports_z2 = true;
210 m_supports_z3 = true;
211 m_supports_z4 = true;
212 m_host_arch.Clear();
213 m_process_arch.Clear();
214 }
215
216
217 bool
GetThreadSuffixSupported()218 GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
219 {
220 if (m_supports_thread_suffix == eLazyBoolCalculate)
221 {
222 StringExtractorGDBRemote response;
223 m_supports_thread_suffix = eLazyBoolNo;
224 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
225 {
226 if (response.IsOKResponse())
227 m_supports_thread_suffix = eLazyBoolYes;
228 }
229 }
230 return m_supports_thread_suffix;
231 }
232 bool
GetVContSupported(char flavor)233 GDBRemoteCommunicationClient::GetVContSupported (char flavor)
234 {
235 if (m_supports_vCont_c == eLazyBoolCalculate)
236 {
237 StringExtractorGDBRemote response;
238 m_supports_vCont_any = eLazyBoolNo;
239 m_supports_vCont_all = eLazyBoolNo;
240 m_supports_vCont_c = eLazyBoolNo;
241 m_supports_vCont_C = eLazyBoolNo;
242 m_supports_vCont_s = eLazyBoolNo;
243 m_supports_vCont_S = eLazyBoolNo;
244 if (SendPacketAndWaitForResponse("vCont?", response, false))
245 {
246 const char *response_cstr = response.GetStringRef().c_str();
247 if (::strstr (response_cstr, ";c"))
248 m_supports_vCont_c = eLazyBoolYes;
249
250 if (::strstr (response_cstr, ";C"))
251 m_supports_vCont_C = eLazyBoolYes;
252
253 if (::strstr (response_cstr, ";s"))
254 m_supports_vCont_s = eLazyBoolYes;
255
256 if (::strstr (response_cstr, ";S"))
257 m_supports_vCont_S = eLazyBoolYes;
258
259 if (m_supports_vCont_c == eLazyBoolYes &&
260 m_supports_vCont_C == eLazyBoolYes &&
261 m_supports_vCont_s == eLazyBoolYes &&
262 m_supports_vCont_S == eLazyBoolYes)
263 {
264 m_supports_vCont_all = eLazyBoolYes;
265 }
266
267 if (m_supports_vCont_c == eLazyBoolYes ||
268 m_supports_vCont_C == eLazyBoolYes ||
269 m_supports_vCont_s == eLazyBoolYes ||
270 m_supports_vCont_S == eLazyBoolYes)
271 {
272 m_supports_vCont_any = eLazyBoolYes;
273 }
274 }
275 }
276
277 switch (flavor)
278 {
279 case 'a': return m_supports_vCont_any;
280 case 'A': return m_supports_vCont_all;
281 case 'c': return m_supports_vCont_c;
282 case 'C': return m_supports_vCont_C;
283 case 's': return m_supports_vCont_s;
284 case 'S': return m_supports_vCont_S;
285 default: break;
286 }
287 return false;
288 }
289
290
291 size_t
SendPacketAndWaitForResponse(const char * payload,StringExtractorGDBRemote & response,bool send_async)292 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
293 (
294 const char *payload,
295 StringExtractorGDBRemote &response,
296 bool send_async
297 )
298 {
299 return SendPacketAndWaitForResponse (payload,
300 ::strlen (payload),
301 response,
302 send_async);
303 }
304
305 size_t
SendPacketAndWaitForResponse(const char * payload,size_t payload_length,StringExtractorGDBRemote & response,bool send_async)306 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
307 (
308 const char *payload,
309 size_t payload_length,
310 StringExtractorGDBRemote &response,
311 bool send_async
312 )
313 {
314 Mutex::Locker locker;
315 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
316 size_t response_len = 0;
317 if (GetSequenceMutex (locker))
318 {
319 if (SendPacketNoLock (payload, payload_length))
320 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
321 else
322 {
323 if (log)
324 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
325 }
326 }
327 else
328 {
329 if (send_async)
330 {
331 if (IsRunning())
332 {
333 Mutex::Locker async_locker (m_async_mutex);
334 m_async_packet.assign(payload, payload_length);
335 m_async_packet_predicate.SetValue (true, eBroadcastNever);
336
337 if (log)
338 log->Printf ("async: async packet = %s", m_async_packet.c_str());
339
340 bool timed_out = false;
341 if (SendInterrupt(locker, 2, timed_out))
342 {
343 if (m_interrupt_sent)
344 {
345 m_interrupt_sent = false;
346 TimeValue timeout_time;
347 timeout_time = TimeValue::Now();
348 timeout_time.OffsetWithSeconds (m_packet_timeout);
349
350 if (log)
351 log->Printf ("async: sent interrupt");
352
353 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
354 {
355 if (log)
356 log->Printf ("async: got response");
357
358 // Swap the response buffer to avoid malloc and string copy
359 response.GetStringRef().swap (m_async_response.GetStringRef());
360 response_len = response.GetStringRef().size();
361 }
362 else
363 {
364 if (log)
365 log->Printf ("async: timed out waiting for response");
366 }
367
368 // Make sure we wait until the continue packet has been sent again...
369 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
370 {
371 if (log)
372 {
373 if (timed_out)
374 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
375 else
376 log->Printf ("async: async packet sent");
377 }
378 }
379 else
380 {
381 if (log)
382 log->Printf ("async: timed out waiting for process to resume");
383 }
384 }
385 else
386 {
387 // We had a racy condition where we went to send the interrupt
388 // yet we were able to get the lock, so the process must have
389 // just stopped?
390 if (log)
391 log->Printf ("async: got lock without sending interrupt");
392 // Send the packet normally since we got the lock
393 if (SendPacketNoLock (payload, payload_length))
394 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
395 else
396 {
397 if (log)
398 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
399 }
400 }
401 }
402 else
403 {
404 if (log)
405 log->Printf ("async: failed to interrupt");
406 }
407 }
408 else
409 {
410 if (log)
411 log->Printf ("async: not running, async is ignored");
412 }
413 }
414 else
415 {
416 if (log)
417 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
418 }
419 }
420 if (response_len == 0)
421 {
422 if (log)
423 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
424 }
425 return response_len;
426 }
427
428 static const char *end_delimiter = "--end--;";
429 static const int end_delimiter_len = 8;
430
431 std::string
HarmonizeThreadIdsForProfileData(ProcessGDBRemote * process,StringExtractorGDBRemote & profileDataExtractor)432 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
433 ( ProcessGDBRemote *process,
434 StringExtractorGDBRemote& profileDataExtractor
435 )
436 {
437 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
438 std::stringstream final_output;
439 std::string name, value;
440
441 // Going to assuming thread_used_usec comes first, else bail out.
442 while (profileDataExtractor.GetNameColonValue(name, value))
443 {
444 if (name.compare("thread_used_id") == 0)
445 {
446 StringExtractor threadIDHexExtractor(value.c_str());
447 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
448
449 bool has_used_usec = false;
450 uint32_t curr_used_usec = 0;
451 std::string usec_name, usec_value;
452 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
453 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
454 {
455 if (usec_name.compare("thread_used_usec") == 0)
456 {
457 has_used_usec = true;
458 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
459 }
460 else
461 {
462 // We didn't find what we want, it is probably
463 // an older version. Bail out.
464 profileDataExtractor.SetFilePos(input_file_pos);
465 }
466 }
467
468 if (has_used_usec)
469 {
470 uint32_t prev_used_usec = 0;
471 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
472 if (iterator != m_thread_id_to_used_usec_map.end())
473 {
474 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
475 }
476
477 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
478 // A good first time record is one that runs for at least 0.25 sec
479 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
480 bool good_subsequent_time = (prev_used_usec > 0) &&
481 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
482
483 if (good_first_time || good_subsequent_time)
484 {
485 // We try to avoid doing too many index id reservation,
486 // resulting in fast increase of index ids.
487
488 final_output << name << ":";
489 int32_t index_id = process->AssignIndexIDToThread(thread_id);
490 final_output << index_id << ";";
491
492 final_output << usec_name << ":" << usec_value << ";";
493 }
494 else
495 {
496 // Skip past 'thread_used_name'.
497 std::string local_name, local_value;
498 profileDataExtractor.GetNameColonValue(local_name, local_value);
499 }
500
501 // Store current time as previous time so that they can be compared later.
502 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
503 }
504 else
505 {
506 // Bail out and use old string.
507 final_output << name << ":" << value << ";";
508 }
509 }
510 else
511 {
512 final_output << name << ":" << value << ";";
513 }
514 }
515 final_output << end_delimiter;
516 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
517
518 return final_output.str();
519 }
520
521 StateType
SendContinuePacketAndWaitForResponse(ProcessGDBRemote * process,const char * payload,size_t packet_length,StringExtractorGDBRemote & response)522 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
523 (
524 ProcessGDBRemote *process,
525 const char *payload,
526 size_t packet_length,
527 StringExtractorGDBRemote &response
528 )
529 {
530 m_curr_tid = LLDB_INVALID_THREAD_ID;
531 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
532 if (log)
533 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
534
535 Mutex::Locker locker(m_sequence_mutex);
536 StateType state = eStateRunning;
537
538 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
539 m_public_is_running.SetValue (true, eBroadcastNever);
540 // Set the starting continue packet into "continue_packet". This packet
541 // may change if we are interrupted and we continue after an async packet...
542 std::string continue_packet(payload, packet_length);
543
544 bool got_async_packet = false;
545
546 while (state == eStateRunning)
547 {
548 if (!got_async_packet)
549 {
550 if (log)
551 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
552 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
553 state = eStateInvalid;
554
555 m_private_is_running.SetValue (true, eBroadcastAlways);
556 }
557
558 got_async_packet = false;
559
560 if (log)
561 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
562
563 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
564 {
565 if (response.Empty())
566 state = eStateInvalid;
567 else
568 {
569 const char stop_type = response.GetChar();
570 if (log)
571 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
572 switch (stop_type)
573 {
574 case 'T':
575 case 'S':
576 {
577 if (process->GetStopID() == 0)
578 {
579 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
580 {
581 lldb::pid_t pid = GetCurrentProcessID ();
582 if (pid != LLDB_INVALID_PROCESS_ID)
583 process->SetID (pid);
584 }
585 process->BuildDynamicRegisterInfo (true);
586 }
587
588 // Privately notify any internal threads that we have stopped
589 // in case we wanted to interrupt our process, yet we might
590 // send a packet and continue without returning control to the
591 // user.
592 m_private_is_running.SetValue (false, eBroadcastAlways);
593
594 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
595
596 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
597 if (continue_after_async || m_interrupt_sent)
598 {
599 // We sent an interrupt packet to stop the inferior process
600 // for an async signal or to send an async packet while running
601 // but we might have been single stepping and received the
602 // stop packet for the step instead of for the interrupt packet.
603 // Typically when an interrupt is sent a SIGINT or SIGSTOP
604 // is used, so if we get anything else, we need to try and
605 // get another stop reply packet that may have been sent
606 // due to sending the interrupt when the target is stopped
607 // which will just re-send a copy of the last stop reply
608 // packet. If we don't do this, then the reply for our
609 // async packet will be the repeat stop reply packet and cause
610 // a lot of trouble for us!
611 if (signo != SIGINT && signo != SIGSTOP)
612 {
613 continue_after_async = false;
614
615 // We didn't get a a SIGINT or SIGSTOP, so try for a
616 // very brief time (1 ms) to get another stop reply
617 // packet to make sure it doesn't get in the way
618 StringExtractorGDBRemote extra_stop_reply_packet;
619 uint32_t timeout_usec = 1000;
620 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
621 {
622 switch (extra_stop_reply_packet.GetChar())
623 {
624 case 'T':
625 case 'S':
626 // We did get an extra stop reply, which means
627 // our interrupt didn't stop the target so we
628 // shouldn't continue after the async signal
629 // or packet is sent...
630 continue_after_async = false;
631 break;
632 }
633 }
634 }
635 }
636
637 if (m_async_signal != -1)
638 {
639 if (log)
640 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
641
642 // Save off the async signal we are supposed to send
643 const int async_signal = m_async_signal;
644 // Clear the async signal member so we don't end up
645 // sending the signal multiple times...
646 m_async_signal = -1;
647 // Check which signal we stopped with
648 if (signo == async_signal)
649 {
650 if (log)
651 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
652
653 // We already stopped with a signal that we wanted
654 // to stop with, so we are done
655 }
656 else
657 {
658 // We stopped with a different signal that the one
659 // we wanted to stop with, so now we must resume
660 // with the signal we want
661 char signal_packet[32];
662 int signal_packet_len = 0;
663 signal_packet_len = ::snprintf (signal_packet,
664 sizeof (signal_packet),
665 "C%2.2x",
666 async_signal);
667
668 if (log)
669 log->Printf ("async: stopped with signal %s, resume with %s",
670 Host::GetSignalAsCString (signo),
671 Host::GetSignalAsCString (async_signal));
672
673 // Set the continue packet to resume even if the
674 // interrupt didn't cause our stop (ignore continue_after_async)
675 continue_packet.assign(signal_packet, signal_packet_len);
676 continue;
677 }
678 }
679 else if (m_async_packet_predicate.GetValue())
680 {
681 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
682
683 // We are supposed to send an asynchronous packet while
684 // we are running.
685 m_async_response.Clear();
686 if (m_async_packet.empty())
687 {
688 if (packet_log)
689 packet_log->Printf ("async: error: empty async packet");
690
691 }
692 else
693 {
694 if (packet_log)
695 packet_log->Printf ("async: sending packet");
696
697 SendPacketAndWaitForResponse (&m_async_packet[0],
698 m_async_packet.size(),
699 m_async_response,
700 false);
701 }
702 // Let the other thread that was trying to send the async
703 // packet know that the packet has been sent and response is
704 // ready...
705 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
706
707 if (packet_log)
708 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
709
710 // Set the continue packet to resume if our interrupt
711 // for the async packet did cause the stop
712 if (continue_after_async)
713 {
714 // Reverting this for now as it is causing deadlocks
715 // in programs (<rdar://problem/11529853>). In the future
716 // we should check our thread list and "do the right thing"
717 // for new threads that show up while we stop and run async
718 // packets. Setting the packet to 'c' to continue all threads
719 // is the right thing to do 99.99% of the time because if a
720 // thread was single stepping, and we sent an interrupt, we
721 // will notice above that we didn't stop due to an interrupt
722 // but stopped due to stepping and we would _not_ continue.
723 continue_packet.assign (1, 'c');
724 continue;
725 }
726 }
727 // Stop with signal and thread info
728 state = eStateStopped;
729 }
730 break;
731
732 case 'W':
733 case 'X':
734 // process exited
735 state = eStateExited;
736 break;
737
738 case 'O':
739 // STDOUT
740 {
741 got_async_packet = true;
742 std::string inferior_stdout;
743 inferior_stdout.reserve(response.GetBytesLeft () / 2);
744 char ch;
745 while ((ch = response.GetHexU8()) != '\0')
746 inferior_stdout.append(1, ch);
747 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
748 }
749 break;
750
751 case 'A':
752 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
753 {
754 got_async_packet = true;
755 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
756 if (m_partial_profile_data.length() > 0)
757 {
758 m_partial_profile_data.append(input);
759 input = m_partial_profile_data;
760 m_partial_profile_data.clear();
761 }
762
763 size_t found, pos = 0, len = input.length();
764 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
765 {
766 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
767 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
768 process->BroadcastAsyncProfileData (profile_data);
769
770 pos = found + end_delimiter_len;
771 }
772
773 if (pos < len)
774 {
775 // Last incomplete chunk.
776 m_partial_profile_data = input.substr(pos);
777 }
778 }
779 break;
780
781 case 'E':
782 // ERROR
783 state = eStateInvalid;
784 break;
785
786 default:
787 if (log)
788 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
789 state = eStateInvalid;
790 break;
791 }
792 }
793 }
794 else
795 {
796 if (log)
797 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
798 state = eStateInvalid;
799 }
800 }
801 if (log)
802 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
803 response.SetFilePos(0);
804 m_private_is_running.SetValue (false, eBroadcastAlways);
805 m_public_is_running.SetValue (false, eBroadcastAlways);
806 return state;
807 }
808
809 bool
SendAsyncSignal(int signo)810 GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
811 {
812 Mutex::Locker async_locker (m_async_mutex);
813 m_async_signal = signo;
814 bool timed_out = false;
815 Mutex::Locker locker;
816 if (SendInterrupt (locker, 1, timed_out))
817 return true;
818 m_async_signal = -1;
819 return false;
820 }
821
822 // This function takes a mutex locker as a parameter in case the GetSequenceMutex
823 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex
824 // (the expected result), then it will send the halt packet. If it does succeed
825 // then the caller that requested the interrupt will want to keep the sequence
826 // locked down so that no one else can send packets while the caller has control.
827 // This function usually gets called when we are running and need to stop the
828 // target. It can also be used when we are running and and we need to do something
829 // else (like read/write memory), so we need to interrupt the running process
830 // (gdb remote protocol requires this), and do what we need to do, then resume.
831
832 bool
SendInterrupt(Mutex::Locker & locker,uint32_t seconds_to_wait_for_stop,bool & timed_out)833 GDBRemoteCommunicationClient::SendInterrupt
834 (
835 Mutex::Locker& locker,
836 uint32_t seconds_to_wait_for_stop,
837 bool &timed_out
838 )
839 {
840 timed_out = false;
841 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
842
843 if (IsRunning())
844 {
845 // Only send an interrupt if our debugserver is running...
846 if (GetSequenceMutex (locker))
847 {
848 if (log)
849 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
850 }
851 else
852 {
853 // Someone has the mutex locked waiting for a response or for the
854 // inferior to stop, so send the interrupt on the down low...
855 char ctrl_c = '\x03';
856 ConnectionStatus status = eConnectionStatusSuccess;
857 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
858 if (log)
859 log->PutCString("send packet: \\x03");
860 if (bytes_written > 0)
861 {
862 m_interrupt_sent = true;
863 if (seconds_to_wait_for_stop)
864 {
865 TimeValue timeout;
866 if (seconds_to_wait_for_stop)
867 {
868 timeout = TimeValue::Now();
869 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
870 }
871 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
872 {
873 if (log)
874 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
875 return true;
876 }
877 else
878 {
879 if (log)
880 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
881 }
882 }
883 else
884 {
885 if (log)
886 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
887 return true;
888 }
889 }
890 else
891 {
892 if (log)
893 log->Printf ("SendInterrupt () - failed to write interrupt");
894 }
895 return false;
896 }
897 }
898 else
899 {
900 if (log)
901 log->Printf ("SendInterrupt () - not running");
902 }
903 return true;
904 }
905
906 lldb::pid_t
GetCurrentProcessID()907 GDBRemoteCommunicationClient::GetCurrentProcessID ()
908 {
909 StringExtractorGDBRemote response;
910 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
911 {
912 if (response.GetChar() == 'Q')
913 if (response.GetChar() == 'C')
914 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
915 }
916 return LLDB_INVALID_PROCESS_ID;
917 }
918
919 bool
GetLaunchSuccess(std::string & error_str)920 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
921 {
922 error_str.clear();
923 StringExtractorGDBRemote response;
924 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
925 {
926 if (response.IsOKResponse())
927 return true;
928 if (response.GetChar() == 'E')
929 {
930 // A string the describes what failed when launching...
931 error_str = response.GetStringRef().substr(1);
932 }
933 else
934 {
935 error_str.assign ("unknown error occurred launching process");
936 }
937 }
938 else
939 {
940 error_str.assign ("timed out waiting for app to launch");
941 }
942 return false;
943 }
944
945 int
SendArgumentsPacket(char const * argv[])946 GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
947 {
948 if (argv && argv[0])
949 {
950 StreamString packet;
951 packet.PutChar('A');
952 const char *arg;
953 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
954 {
955 const int arg_len = strlen(arg);
956 if (i > 0)
957 packet.PutChar(',');
958 packet.Printf("%i,%i,", arg_len * 2, i);
959 packet.PutBytesAsRawHex8 (arg, arg_len);
960 }
961
962 StringExtractorGDBRemote response;
963 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
964 {
965 if (response.IsOKResponse())
966 return 0;
967 uint8_t error = response.GetError();
968 if (error)
969 return error;
970 }
971 }
972 return -1;
973 }
974
975 int
SendEnvironmentPacket(char const * name_equal_value)976 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
977 {
978 if (name_equal_value && name_equal_value[0])
979 {
980 StreamString packet;
981 packet.Printf("QEnvironment:%s", name_equal_value);
982 StringExtractorGDBRemote response;
983 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
984 {
985 if (response.IsOKResponse())
986 return 0;
987 uint8_t error = response.GetError();
988 if (error)
989 return error;
990 }
991 }
992 return -1;
993 }
994
995 int
SendLaunchArchPacket(char const * arch)996 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
997 {
998 if (arch && arch[0])
999 {
1000 StreamString packet;
1001 packet.Printf("QLaunchArch:%s", arch);
1002 StringExtractorGDBRemote response;
1003 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1004 {
1005 if (response.IsOKResponse())
1006 return 0;
1007 uint8_t error = response.GetError();
1008 if (error)
1009 return error;
1010 }
1011 }
1012 return -1;
1013 }
1014
1015 bool
GetOSVersion(uint32_t & major,uint32_t & minor,uint32_t & update)1016 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1017 uint32_t &minor,
1018 uint32_t &update)
1019 {
1020 if (GetHostInfo ())
1021 {
1022 if (m_os_version_major != UINT32_MAX)
1023 {
1024 major = m_os_version_major;
1025 minor = m_os_version_minor;
1026 update = m_os_version_update;
1027 return true;
1028 }
1029 }
1030 return false;
1031 }
1032
1033 bool
GetOSBuildString(std::string & s)1034 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1035 {
1036 if (GetHostInfo ())
1037 {
1038 if (!m_os_build.empty())
1039 {
1040 s = m_os_build;
1041 return true;
1042 }
1043 }
1044 s.clear();
1045 return false;
1046 }
1047
1048
1049 bool
GetOSKernelDescription(std::string & s)1050 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1051 {
1052 if (GetHostInfo ())
1053 {
1054 if (!m_os_kernel.empty())
1055 {
1056 s = m_os_kernel;
1057 return true;
1058 }
1059 }
1060 s.clear();
1061 return false;
1062 }
1063
1064 bool
GetHostname(std::string & s)1065 GDBRemoteCommunicationClient::GetHostname (std::string &s)
1066 {
1067 if (GetHostInfo ())
1068 {
1069 if (!m_hostname.empty())
1070 {
1071 s = m_hostname;
1072 return true;
1073 }
1074 }
1075 s.clear();
1076 return false;
1077 }
1078
1079 ArchSpec
GetSystemArchitecture()1080 GDBRemoteCommunicationClient::GetSystemArchitecture ()
1081 {
1082 if (GetHostInfo ())
1083 return m_host_arch;
1084 return ArchSpec();
1085 }
1086
1087 const lldb_private::ArchSpec &
GetProcessArchitecture()1088 GDBRemoteCommunicationClient::GetProcessArchitecture ()
1089 {
1090 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1091 GetCurrentProcessInfo ();
1092 return m_process_arch;
1093 }
1094
1095
1096 bool
GetHostInfo(bool force)1097 GDBRemoteCommunicationClient::GetHostInfo (bool force)
1098 {
1099 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
1100 {
1101 m_qHostInfo_is_valid = eLazyBoolNo;
1102 StringExtractorGDBRemote response;
1103 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1104 {
1105 if (response.IsNormalResponse())
1106 {
1107 std::string name;
1108 std::string value;
1109 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1110 uint32_t sub = 0;
1111 std::string arch_name;
1112 std::string os_name;
1113 std::string vendor_name;
1114 std::string triple;
1115 uint32_t pointer_byte_size = 0;
1116 StringExtractor extractor;
1117 ByteOrder byte_order = eByteOrderInvalid;
1118 uint32_t num_keys_decoded = 0;
1119 while (response.GetNameColonValue(name, value))
1120 {
1121 if (name.compare("cputype") == 0)
1122 {
1123 // exception type in big endian hex
1124 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1125 if (cpu != LLDB_INVALID_CPUTYPE)
1126 ++num_keys_decoded;
1127 }
1128 else if (name.compare("cpusubtype") == 0)
1129 {
1130 // exception count in big endian hex
1131 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1132 if (sub != 0)
1133 ++num_keys_decoded;
1134 }
1135 else if (name.compare("arch") == 0)
1136 {
1137 arch_name.swap (value);
1138 ++num_keys_decoded;
1139 }
1140 else if (name.compare("triple") == 0)
1141 {
1142 // The triple comes as ASCII hex bytes since it contains '-' chars
1143 extractor.GetStringRef().swap(value);
1144 extractor.SetFilePos(0);
1145 extractor.GetHexByteString (triple);
1146 ++num_keys_decoded;
1147 }
1148 else if (name.compare("os_build") == 0)
1149 {
1150 extractor.GetStringRef().swap(value);
1151 extractor.SetFilePos(0);
1152 extractor.GetHexByteString (m_os_build);
1153 ++num_keys_decoded;
1154 }
1155 else if (name.compare("hostname") == 0)
1156 {
1157 extractor.GetStringRef().swap(value);
1158 extractor.SetFilePos(0);
1159 extractor.GetHexByteString (m_hostname);
1160 ++num_keys_decoded;
1161 }
1162 else if (name.compare("os_kernel") == 0)
1163 {
1164 extractor.GetStringRef().swap(value);
1165 extractor.SetFilePos(0);
1166 extractor.GetHexByteString (m_os_kernel);
1167 ++num_keys_decoded;
1168 }
1169 else if (name.compare("ostype") == 0)
1170 {
1171 os_name.swap (value);
1172 ++num_keys_decoded;
1173 }
1174 else if (name.compare("vendor") == 0)
1175 {
1176 vendor_name.swap(value);
1177 ++num_keys_decoded;
1178 }
1179 else if (name.compare("endian") == 0)
1180 {
1181 ++num_keys_decoded;
1182 if (value.compare("little") == 0)
1183 byte_order = eByteOrderLittle;
1184 else if (value.compare("big") == 0)
1185 byte_order = eByteOrderBig;
1186 else if (value.compare("pdp") == 0)
1187 byte_order = eByteOrderPDP;
1188 else
1189 --num_keys_decoded;
1190 }
1191 else if (name.compare("ptrsize") == 0)
1192 {
1193 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1194 if (pointer_byte_size != 0)
1195 ++num_keys_decoded;
1196 }
1197 else if (name.compare("os_version") == 0)
1198 {
1199 Args::StringToVersion (value.c_str(),
1200 m_os_version_major,
1201 m_os_version_minor,
1202 m_os_version_update);
1203 if (m_os_version_major != UINT32_MAX)
1204 ++num_keys_decoded;
1205 }
1206 else if (name.compare("watchpoint_exceptions_received") == 0)
1207 {
1208 ++num_keys_decoded;
1209 if (strcmp(value.c_str(),"before") == 0)
1210 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1211 else if (strcmp(value.c_str(),"after") == 0)
1212 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1213 else
1214 --num_keys_decoded;
1215 }
1216
1217 }
1218
1219 if (num_keys_decoded > 0)
1220 m_qHostInfo_is_valid = eLazyBoolYes;
1221
1222 if (triple.empty())
1223 {
1224 if (arch_name.empty())
1225 {
1226 if (cpu != LLDB_INVALID_CPUTYPE)
1227 {
1228 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1229 if (pointer_byte_size)
1230 {
1231 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1232 }
1233 if (byte_order != eByteOrderInvalid)
1234 {
1235 assert (byte_order == m_host_arch.GetByteOrder());
1236 }
1237
1238 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1239 {
1240 switch (m_host_arch.GetMachine())
1241 {
1242 case llvm::Triple::arm:
1243 case llvm::Triple::thumb:
1244 os_name = "ios";
1245 break;
1246 default:
1247 os_name = "macosx";
1248 break;
1249 }
1250 }
1251 if (!vendor_name.empty())
1252 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1253 if (!os_name.empty())
1254 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1255
1256 }
1257 }
1258 else
1259 {
1260 std::string triple;
1261 triple += arch_name;
1262 if (!vendor_name.empty() || !os_name.empty())
1263 {
1264 triple += '-';
1265 if (vendor_name.empty())
1266 triple += "unknown";
1267 else
1268 triple += vendor_name;
1269 triple += '-';
1270 if (os_name.empty())
1271 triple += "unknown";
1272 else
1273 triple += os_name;
1274 }
1275 m_host_arch.SetTriple (triple.c_str());
1276
1277 llvm::Triple &host_triple = m_host_arch.GetTriple();
1278 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1279 {
1280 switch (m_host_arch.GetMachine())
1281 {
1282 case llvm::Triple::arm:
1283 case llvm::Triple::thumb:
1284 host_triple.setOS(llvm::Triple::IOS);
1285 break;
1286 default:
1287 host_triple.setOS(llvm::Triple::MacOSX);
1288 break;
1289 }
1290 }
1291 if (pointer_byte_size)
1292 {
1293 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1294 }
1295 if (byte_order != eByteOrderInvalid)
1296 {
1297 assert (byte_order == m_host_arch.GetByteOrder());
1298 }
1299
1300 }
1301 }
1302 else
1303 {
1304 m_host_arch.SetTriple (triple.c_str());
1305 if (pointer_byte_size)
1306 {
1307 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1308 }
1309 if (byte_order != eByteOrderInvalid)
1310 {
1311 assert (byte_order == m_host_arch.GetByteOrder());
1312 }
1313 }
1314 }
1315 }
1316 }
1317 return m_qHostInfo_is_valid == eLazyBoolYes;
1318 }
1319
1320 int
SendAttach(lldb::pid_t pid,StringExtractorGDBRemote & response)1321 GDBRemoteCommunicationClient::SendAttach
1322 (
1323 lldb::pid_t pid,
1324 StringExtractorGDBRemote& response
1325 )
1326 {
1327 if (pid != LLDB_INVALID_PROCESS_ID)
1328 {
1329 char packet[64];
1330 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1331 assert (packet_len < (int)sizeof(packet));
1332 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1333 {
1334 if (response.IsErrorResponse())
1335 return response.GetError();
1336 return 0;
1337 }
1338 }
1339 return -1;
1340 }
1341
1342 const lldb_private::ArchSpec &
GetHostArchitecture()1343 GDBRemoteCommunicationClient::GetHostArchitecture ()
1344 {
1345 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1346 GetHostInfo ();
1347 return m_host_arch;
1348 }
1349
1350 addr_t
AllocateMemory(size_t size,uint32_t permissions)1351 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1352 {
1353 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1354 {
1355 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1356 char packet[64];
1357 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
1358 (uint64_t)size,
1359 permissions & lldb::ePermissionsReadable ? "r" : "",
1360 permissions & lldb::ePermissionsWritable ? "w" : "",
1361 permissions & lldb::ePermissionsExecutable ? "x" : "");
1362 assert (packet_len < (int)sizeof(packet));
1363 StringExtractorGDBRemote response;
1364 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1365 {
1366 if (!response.IsErrorResponse())
1367 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1368 }
1369 else
1370 {
1371 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1372 }
1373 }
1374 return LLDB_INVALID_ADDRESS;
1375 }
1376
1377 bool
DeallocateMemory(addr_t addr)1378 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1379 {
1380 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
1381 {
1382 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1383 char packet[64];
1384 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1385 assert (packet_len < (int)sizeof(packet));
1386 StringExtractorGDBRemote response;
1387 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1388 {
1389 if (response.IsOKResponse())
1390 return true;
1391 }
1392 else
1393 {
1394 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1395 }
1396 }
1397 return false;
1398 }
1399
1400 Error
Detach(bool keep_stopped)1401 GDBRemoteCommunicationClient::Detach (bool keep_stopped)
1402 {
1403 Error error;
1404
1405 if (keep_stopped)
1406 {
1407 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1408 {
1409 char packet[64];
1410 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1411 assert (packet_len < (int)sizeof(packet));
1412 StringExtractorGDBRemote response;
1413 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1414 {
1415 m_supports_detach_stay_stopped = eLazyBoolYes;
1416 }
1417 else
1418 {
1419 m_supports_detach_stay_stopped = eLazyBoolNo;
1420 }
1421 }
1422
1423 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1424 {
1425 error.SetErrorString("Stays stopped not supported by this target.");
1426 return error;
1427 }
1428 else
1429 {
1430 size_t num_sent = SendPacket ("D1", 2);
1431 if (num_sent == 0)
1432 error.SetErrorString ("Sending extended disconnect packet failed.");
1433 }
1434 }
1435 else
1436 {
1437 size_t num_sent = SendPacket ("D", 1);
1438 if (num_sent == 0)
1439 error.SetErrorString ("Sending disconnect packet failed.");
1440 }
1441 return error;
1442 }
1443
1444 Error
GetMemoryRegionInfo(lldb::addr_t addr,lldb_private::MemoryRegionInfo & region_info)1445 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1446 lldb_private::MemoryRegionInfo ®ion_info)
1447 {
1448 Error error;
1449 region_info.Clear();
1450
1451 if (m_supports_memory_region_info != eLazyBoolNo)
1452 {
1453 m_supports_memory_region_info = eLazyBoolYes;
1454 char packet[64];
1455 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1456 assert (packet_len < (int)sizeof(packet));
1457 StringExtractorGDBRemote response;
1458 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1459 {
1460 std::string name;
1461 std::string value;
1462 addr_t addr_value;
1463 bool success = true;
1464 bool saw_permissions = false;
1465 while (success && response.GetNameColonValue(name, value))
1466 {
1467 if (name.compare ("start") == 0)
1468 {
1469 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1470 if (success)
1471 region_info.GetRange().SetRangeBase(addr_value);
1472 }
1473 else if (name.compare ("size") == 0)
1474 {
1475 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1476 if (success)
1477 region_info.GetRange().SetByteSize (addr_value);
1478 }
1479 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
1480 {
1481 saw_permissions = true;
1482 if (region_info.GetRange().Contains (addr))
1483 {
1484 if (value.find('r') != std::string::npos)
1485 region_info.SetReadable (MemoryRegionInfo::eYes);
1486 else
1487 region_info.SetReadable (MemoryRegionInfo::eNo);
1488
1489 if (value.find('w') != std::string::npos)
1490 region_info.SetWritable (MemoryRegionInfo::eYes);
1491 else
1492 region_info.SetWritable (MemoryRegionInfo::eNo);
1493
1494 if (value.find('x') != std::string::npos)
1495 region_info.SetExecutable (MemoryRegionInfo::eYes);
1496 else
1497 region_info.SetExecutable (MemoryRegionInfo::eNo);
1498 }
1499 else
1500 {
1501 // The reported region does not contain this address -- we're looking at an unmapped page
1502 region_info.SetReadable (MemoryRegionInfo::eNo);
1503 region_info.SetWritable (MemoryRegionInfo::eNo);
1504 region_info.SetExecutable (MemoryRegionInfo::eNo);
1505 }
1506 }
1507 else if (name.compare ("error") == 0)
1508 {
1509 StringExtractorGDBRemote name_extractor;
1510 // Swap "value" over into "name_extractor"
1511 name_extractor.GetStringRef().swap(value);
1512 // Now convert the HEX bytes into a string value
1513 name_extractor.GetHexByteString (value);
1514 error.SetErrorString(value.c_str());
1515 }
1516 }
1517
1518 // We got a valid address range back but no permissions -- which means this is an unmapped page
1519 if (region_info.GetRange().IsValid() && saw_permissions == false)
1520 {
1521 region_info.SetReadable (MemoryRegionInfo::eNo);
1522 region_info.SetWritable (MemoryRegionInfo::eNo);
1523 region_info.SetExecutable (MemoryRegionInfo::eNo);
1524 }
1525 }
1526 else
1527 {
1528 m_supports_memory_region_info = eLazyBoolNo;
1529 }
1530 }
1531
1532 if (m_supports_memory_region_info == eLazyBoolNo)
1533 {
1534 error.SetErrorString("qMemoryRegionInfo is not supported");
1535 }
1536 if (error.Fail())
1537 region_info.Clear();
1538 return error;
1539
1540 }
1541
1542 Error
GetWatchpointSupportInfo(uint32_t & num)1543 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1544 {
1545 Error error;
1546
1547 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1548 {
1549 num = m_num_supported_hardware_watchpoints;
1550 return error;
1551 }
1552
1553 // Set num to 0 first.
1554 num = 0;
1555 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1556 {
1557 char packet[64];
1558 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1559 assert (packet_len < (int)sizeof(packet));
1560 StringExtractorGDBRemote response;
1561 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1562 {
1563 m_supports_watchpoint_support_info = eLazyBoolYes;
1564 std::string name;
1565 std::string value;
1566 while (response.GetNameColonValue(name, value))
1567 {
1568 if (name.compare ("num") == 0)
1569 {
1570 num = Args::StringToUInt32(value.c_str(), 0, 0);
1571 m_num_supported_hardware_watchpoints = num;
1572 }
1573 }
1574 }
1575 else
1576 {
1577 m_supports_watchpoint_support_info = eLazyBoolNo;
1578 }
1579 }
1580
1581 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1582 {
1583 error.SetErrorString("qWatchpointSupportInfo is not supported");
1584 }
1585 return error;
1586
1587 }
1588
1589 lldb_private::Error
GetWatchpointSupportInfo(uint32_t & num,bool & after)1590 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1591 {
1592 Error error(GetWatchpointSupportInfo(num));
1593 if (error.Success())
1594 error = GetWatchpointsTriggerAfterInstruction(after);
1595 return error;
1596 }
1597
1598 lldb_private::Error
GetWatchpointsTriggerAfterInstruction(bool & after)1599 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1600 {
1601 Error error;
1602
1603 // we assume watchpoints will happen after running the relevant opcode
1604 // and we only want to override this behavior if we have explicitly
1605 // received a qHostInfo telling us otherwise
1606 if (m_qHostInfo_is_valid != eLazyBoolYes)
1607 after = true;
1608 else
1609 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1610 return error;
1611 }
1612
1613 int
SetSTDIN(char const * path)1614 GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1615 {
1616 if (path && path[0])
1617 {
1618 StreamString packet;
1619 packet.PutCString("QSetSTDIN:");
1620 packet.PutBytesAsRawHex8(path, strlen(path));
1621
1622 StringExtractorGDBRemote response;
1623 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1624 {
1625 if (response.IsOKResponse())
1626 return 0;
1627 uint8_t error = response.GetError();
1628 if (error)
1629 return error;
1630 }
1631 }
1632 return -1;
1633 }
1634
1635 int
SetSTDOUT(char const * path)1636 GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1637 {
1638 if (path && path[0])
1639 {
1640 StreamString packet;
1641 packet.PutCString("QSetSTDOUT:");
1642 packet.PutBytesAsRawHex8(path, strlen(path));
1643
1644 StringExtractorGDBRemote response;
1645 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1646 {
1647 if (response.IsOKResponse())
1648 return 0;
1649 uint8_t error = response.GetError();
1650 if (error)
1651 return error;
1652 }
1653 }
1654 return -1;
1655 }
1656
1657 int
SetSTDERR(char const * path)1658 GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1659 {
1660 if (path && path[0])
1661 {
1662 StreamString packet;
1663 packet.PutCString("QSetSTDERR:");
1664 packet.PutBytesAsRawHex8(path, strlen(path));
1665
1666 StringExtractorGDBRemote response;
1667 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1668 {
1669 if (response.IsOKResponse())
1670 return 0;
1671 uint8_t error = response.GetError();
1672 if (error)
1673 return error;
1674 }
1675 }
1676 return -1;
1677 }
1678
1679 int
SetWorkingDir(char const * path)1680 GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1681 {
1682 if (path && path[0])
1683 {
1684 StreamString packet;
1685 packet.PutCString("QSetWorkingDir:");
1686 packet.PutBytesAsRawHex8(path, strlen(path));
1687
1688 StringExtractorGDBRemote response;
1689 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1690 {
1691 if (response.IsOKResponse())
1692 return 0;
1693 uint8_t error = response.GetError();
1694 if (error)
1695 return error;
1696 }
1697 }
1698 return -1;
1699 }
1700
1701 int
SetDisableASLR(bool enable)1702 GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1703 {
1704 char packet[32];
1705 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1706 assert (packet_len < (int)sizeof(packet));
1707 StringExtractorGDBRemote response;
1708 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1709 {
1710 if (response.IsOKResponse())
1711 return 0;
1712 uint8_t error = response.GetError();
1713 if (error)
1714 return error;
1715 }
1716 return -1;
1717 }
1718
1719 bool
DecodeProcessInfoResponse(StringExtractorGDBRemote & response,ProcessInstanceInfo & process_info)1720 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
1721 {
1722 if (response.IsNormalResponse())
1723 {
1724 std::string name;
1725 std::string value;
1726 StringExtractor extractor;
1727
1728 while (response.GetNameColonValue(name, value))
1729 {
1730 if (name.compare("pid") == 0)
1731 {
1732 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1733 }
1734 else if (name.compare("ppid") == 0)
1735 {
1736 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1737 }
1738 else if (name.compare("uid") == 0)
1739 {
1740 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1741 }
1742 else if (name.compare("euid") == 0)
1743 {
1744 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1745 }
1746 else if (name.compare("gid") == 0)
1747 {
1748 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1749 }
1750 else if (name.compare("egid") == 0)
1751 {
1752 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1753 }
1754 else if (name.compare("triple") == 0)
1755 {
1756 // The triple comes as ASCII hex bytes since it contains '-' chars
1757 extractor.GetStringRef().swap(value);
1758 extractor.SetFilePos(0);
1759 extractor.GetHexByteString (value);
1760 process_info.GetArchitecture ().SetTriple (value.c_str());
1761 }
1762 else if (name.compare("name") == 0)
1763 {
1764 StringExtractor extractor;
1765 // The process name from ASCII hex bytes since we can't
1766 // control the characters in a process name
1767 extractor.GetStringRef().swap(value);
1768 extractor.SetFilePos(0);
1769 extractor.GetHexByteString (value);
1770 process_info.GetExecutableFile().SetFile (value.c_str(), false);
1771 }
1772 }
1773
1774 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1775 return true;
1776 }
1777 return false;
1778 }
1779
1780 bool
GetProcessInfo(lldb::pid_t pid,ProcessInstanceInfo & process_info)1781 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1782 {
1783 process_info.Clear();
1784
1785 if (m_supports_qProcessInfoPID)
1786 {
1787 char packet[32];
1788 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
1789 assert (packet_len < (int)sizeof(packet));
1790 StringExtractorGDBRemote response;
1791 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1792 {
1793 return DecodeProcessInfoResponse (response, process_info);
1794 }
1795 else
1796 {
1797 m_supports_qProcessInfoPID = false;
1798 return false;
1799 }
1800 }
1801 return false;
1802 }
1803
1804 bool
GetCurrentProcessInfo()1805 GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1806 {
1807 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1808 return true;
1809 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1810 return false;
1811
1812 GetHostInfo ();
1813
1814 StringExtractorGDBRemote response;
1815 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1816 {
1817 if (response.IsNormalResponse())
1818 {
1819 std::string name;
1820 std::string value;
1821 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1822 uint32_t sub = 0;
1823 std::string arch_name;
1824 std::string os_name;
1825 std::string vendor_name;
1826 std::string triple;
1827 uint32_t pointer_byte_size = 0;
1828 StringExtractor extractor;
1829 ByteOrder byte_order = eByteOrderInvalid;
1830 uint32_t num_keys_decoded = 0;
1831 while (response.GetNameColonValue(name, value))
1832 {
1833 if (name.compare("cputype") == 0)
1834 {
1835 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1836 if (cpu != LLDB_INVALID_CPUTYPE)
1837 ++num_keys_decoded;
1838 }
1839 else if (name.compare("cpusubtype") == 0)
1840 {
1841 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1842 if (sub != 0)
1843 ++num_keys_decoded;
1844 }
1845 else if (name.compare("ostype") == 0)
1846 {
1847 os_name.swap (value);
1848 ++num_keys_decoded;
1849 }
1850 else if (name.compare("vendor") == 0)
1851 {
1852 vendor_name.swap(value);
1853 ++num_keys_decoded;
1854 }
1855 else if (name.compare("endian") == 0)
1856 {
1857 ++num_keys_decoded;
1858 if (value.compare("little") == 0)
1859 byte_order = eByteOrderLittle;
1860 else if (value.compare("big") == 0)
1861 byte_order = eByteOrderBig;
1862 else if (value.compare("pdp") == 0)
1863 byte_order = eByteOrderPDP;
1864 else
1865 --num_keys_decoded;
1866 }
1867 else if (name.compare("ptrsize") == 0)
1868 {
1869 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1870 if (pointer_byte_size != 0)
1871 ++num_keys_decoded;
1872 }
1873 }
1874 if (num_keys_decoded > 0)
1875 m_qProcessInfo_is_valid = eLazyBoolYes;
1876 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1877 {
1878 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1879 if (pointer_byte_size)
1880 {
1881 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1882 }
1883 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1884 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1885 return true;
1886 }
1887 }
1888 }
1889 else
1890 {
1891 m_qProcessInfo_is_valid = eLazyBoolNo;
1892 }
1893
1894 return false;
1895 }
1896
1897
1898 uint32_t
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)1899 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1900 ProcessInstanceInfoList &process_infos)
1901 {
1902 process_infos.Clear();
1903
1904 if (m_supports_qfProcessInfo)
1905 {
1906 StreamString packet;
1907 packet.PutCString ("qfProcessInfo");
1908 if (!match_info.MatchAllProcesses())
1909 {
1910 packet.PutChar (':');
1911 const char *name = match_info.GetProcessInfo().GetName();
1912 bool has_name_match = false;
1913 if (name && name[0])
1914 {
1915 has_name_match = true;
1916 NameMatchType name_match_type = match_info.GetNameMatchType();
1917 switch (name_match_type)
1918 {
1919 case eNameMatchIgnore:
1920 has_name_match = false;
1921 break;
1922
1923 case eNameMatchEquals:
1924 packet.PutCString ("name_match:equals;");
1925 break;
1926
1927 case eNameMatchContains:
1928 packet.PutCString ("name_match:contains;");
1929 break;
1930
1931 case eNameMatchStartsWith:
1932 packet.PutCString ("name_match:starts_with;");
1933 break;
1934
1935 case eNameMatchEndsWith:
1936 packet.PutCString ("name_match:ends_with;");
1937 break;
1938
1939 case eNameMatchRegularExpression:
1940 packet.PutCString ("name_match:regex;");
1941 break;
1942 }
1943 if (has_name_match)
1944 {
1945 packet.PutCString ("name:");
1946 packet.PutBytesAsRawHex8(name, ::strlen(name));
1947 packet.PutChar (';');
1948 }
1949 }
1950
1951 if (match_info.GetProcessInfo().ProcessIDIsValid())
1952 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
1953 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1954 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
1955 if (match_info.GetProcessInfo().UserIDIsValid())
1956 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1957 if (match_info.GetProcessInfo().GroupIDIsValid())
1958 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
1959 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1960 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1961 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1962 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1963 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1964 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1965 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1966 {
1967 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1968 const llvm::Triple &triple = match_arch.GetTriple();
1969 packet.PutCString("triple:");
1970 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1971 packet.PutChar (';');
1972 }
1973 }
1974 StringExtractorGDBRemote response;
1975 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1976 {
1977 do
1978 {
1979 ProcessInstanceInfo process_info;
1980 if (!DecodeProcessInfoResponse (response, process_info))
1981 break;
1982 process_infos.Append(process_info);
1983 response.GetStringRef().clear();
1984 response.SetFilePos(0);
1985 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1986 }
1987 else
1988 {
1989 m_supports_qfProcessInfo = false;
1990 return 0;
1991 }
1992 }
1993 return process_infos.GetSize();
1994
1995 }
1996
1997 bool
GetUserName(uint32_t uid,std::string & name)1998 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
1999 {
2000 if (m_supports_qUserName)
2001 {
2002 char packet[32];
2003 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
2004 assert (packet_len < (int)sizeof(packet));
2005 StringExtractorGDBRemote response;
2006 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2007 {
2008 if (response.IsNormalResponse())
2009 {
2010 // Make sure we parsed the right number of characters. The response is
2011 // the hex encoded user name and should make up the entire packet.
2012 // If there are any non-hex ASCII bytes, the length won't match below..
2013 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2014 return true;
2015 }
2016 }
2017 else
2018 {
2019 m_supports_qUserName = false;
2020 return false;
2021 }
2022 }
2023 return false;
2024
2025 }
2026
2027 bool
GetGroupName(uint32_t gid,std::string & name)2028 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2029 {
2030 if (m_supports_qGroupName)
2031 {
2032 char packet[32];
2033 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
2034 assert (packet_len < (int)sizeof(packet));
2035 StringExtractorGDBRemote response;
2036 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2037 {
2038 if (response.IsNormalResponse())
2039 {
2040 // Make sure we parsed the right number of characters. The response is
2041 // the hex encoded group name and should make up the entire packet.
2042 // If there are any non-hex ASCII bytes, the length won't match below..
2043 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2044 return true;
2045 }
2046 }
2047 else
2048 {
2049 m_supports_qGroupName = false;
2050 return false;
2051 }
2052 }
2053 return false;
2054 }
2055
2056 void
TestPacketSpeed(const uint32_t num_packets)2057 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2058 {
2059 uint32_t i;
2060 TimeValue start_time, end_time;
2061 uint64_t total_time_nsec;
2062 float packets_per_second;
2063 if (SendSpeedTestPacket (0, 0))
2064 {
2065 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2066 {
2067 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2068 {
2069 start_time = TimeValue::Now();
2070 for (i=0; i<num_packets; ++i)
2071 {
2072 SendSpeedTestPacket (send_size, recv_size);
2073 }
2074 end_time = TimeValue::Now();
2075 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2076 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2077 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2078 num_packets,
2079 send_size,
2080 recv_size,
2081 total_time_nsec / TimeValue::NanoSecPerSec,
2082 total_time_nsec % TimeValue::NanoSecPerSec,
2083 packets_per_second);
2084 if (recv_size == 0)
2085 recv_size = 32;
2086 }
2087 if (send_size == 0)
2088 send_size = 32;
2089 }
2090 }
2091 else
2092 {
2093 start_time = TimeValue::Now();
2094 for (i=0; i<num_packets; ++i)
2095 {
2096 GetCurrentProcessID ();
2097 }
2098 end_time = TimeValue::Now();
2099 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2100 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2101 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
2102 num_packets,
2103 total_time_nsec / TimeValue::NanoSecPerSec,
2104 total_time_nsec % TimeValue::NanoSecPerSec,
2105 packets_per_second);
2106 }
2107 }
2108
2109 bool
SendSpeedTestPacket(uint32_t send_size,uint32_t recv_size)2110 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2111 {
2112 StreamString packet;
2113 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2114 uint32_t bytes_left = send_size;
2115 while (bytes_left > 0)
2116 {
2117 if (bytes_left >= 26)
2118 {
2119 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2120 bytes_left -= 26;
2121 }
2122 else
2123 {
2124 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2125 bytes_left = 0;
2126 }
2127 }
2128
2129 StringExtractorGDBRemote response;
2130 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
2131 return false;
2132 }
2133
2134 uint16_t
LaunchGDBserverAndGetPort()2135 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort ()
2136 {
2137 StringExtractorGDBRemote response;
2138 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false))
2139 {
2140 std::string name;
2141 std::string value;
2142 uint16_t port = 0;
2143 //lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2144 while (response.GetNameColonValue(name, value))
2145 {
2146 if (name.size() == 4 && name.compare("port") == 0)
2147 port = Args::StringToUInt32(value.c_str(), 0, 0);
2148 // if (name.size() == 3 && name.compare("pid") == 0)
2149 // pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
2150 }
2151 return port;
2152 }
2153 return 0;
2154 }
2155
2156 bool
SetCurrentThread(uint64_t tid)2157 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
2158 {
2159 if (m_curr_tid == tid)
2160 return true;
2161
2162 char packet[32];
2163 int packet_len;
2164 if (tid == UINT64_MAX)
2165 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
2166 else
2167 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
2168 assert (packet_len + 1 < (int)sizeof(packet));
2169 StringExtractorGDBRemote response;
2170 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2171 {
2172 if (response.IsOKResponse())
2173 {
2174 m_curr_tid = tid;
2175 return true;
2176 }
2177 }
2178 return false;
2179 }
2180
2181 bool
SetCurrentThreadForRun(uint64_t tid)2182 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
2183 {
2184 if (m_curr_tid_run == tid)
2185 return true;
2186
2187 char packet[32];
2188 int packet_len;
2189 if (tid == UINT64_MAX)
2190 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
2191 else
2192 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2193
2194 assert (packet_len + 1 < (int)sizeof(packet));
2195 StringExtractorGDBRemote response;
2196 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2197 {
2198 if (response.IsOKResponse())
2199 {
2200 m_curr_tid_run = tid;
2201 return true;
2202 }
2203 }
2204 return false;
2205 }
2206
2207 bool
GetStopReply(StringExtractorGDBRemote & response)2208 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2209 {
2210 if (SendPacketAndWaitForResponse("?", 1, response, false))
2211 return response.IsNormalResponse();
2212 return false;
2213 }
2214
2215 bool
GetThreadStopInfo(lldb::tid_t tid,StringExtractorGDBRemote & response)2216 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
2217 {
2218 if (m_supports_qThreadStopInfo)
2219 {
2220 char packet[256];
2221 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2222 assert (packet_len < (int)sizeof(packet));
2223 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2224 {
2225 if (response.IsNormalResponse())
2226 return true;
2227 else
2228 return false;
2229 }
2230 else
2231 {
2232 m_supports_qThreadStopInfo = false;
2233 }
2234 }
2235 // if (SetCurrentThread (tid))
2236 // return GetStopReply (response);
2237 return false;
2238 }
2239
2240
2241 uint8_t
SendGDBStoppointTypePacket(GDBStoppointType type,bool insert,addr_t addr,uint32_t length)2242 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2243 {
2244 switch (type)
2245 {
2246 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2247 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2248 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2249 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2250 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
2251 }
2252
2253 char packet[64];
2254 const int packet_len = ::snprintf (packet,
2255 sizeof(packet),
2256 "%c%i,%" PRIx64 ",%x",
2257 insert ? 'Z' : 'z',
2258 type,
2259 addr,
2260 length);
2261
2262 assert (packet_len + 1 < (int)sizeof(packet));
2263 StringExtractorGDBRemote response;
2264 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2265 {
2266 if (response.IsOKResponse())
2267 return 0;
2268 else if (response.IsErrorResponse())
2269 return response.GetError();
2270 }
2271 else
2272 {
2273 switch (type)
2274 {
2275 case eBreakpointSoftware: m_supports_z0 = false; break;
2276 case eBreakpointHardware: m_supports_z1 = false; break;
2277 case eWatchpointWrite: m_supports_z2 = false; break;
2278 case eWatchpointRead: m_supports_z3 = false; break;
2279 case eWatchpointReadWrite: m_supports_z4 = false; break;
2280 }
2281 }
2282
2283 return UINT8_MAX;
2284 }
2285
2286 size_t
GetCurrentThreadIDs(std::vector<lldb::tid_t> & thread_ids,bool & sequence_mutex_unavailable)2287 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2288 bool &sequence_mutex_unavailable)
2289 {
2290 Mutex::Locker locker;
2291 thread_ids.clear();
2292
2293 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
2294 {
2295 sequence_mutex_unavailable = false;
2296 StringExtractorGDBRemote response;
2297
2298 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
2299 response.IsNormalResponse();
2300 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
2301 {
2302 char ch = response.GetChar();
2303 if (ch == 'l')
2304 break;
2305 if (ch == 'm')
2306 {
2307 do
2308 {
2309 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2310
2311 if (tid != LLDB_INVALID_THREAD_ID)
2312 {
2313 thread_ids.push_back (tid);
2314 }
2315 ch = response.GetChar(); // Skip the command separator
2316 } while (ch == ','); // Make sure we got a comma separator
2317 }
2318 }
2319 }
2320 else
2321 {
2322 #if defined (LLDB_CONFIGURATION_DEBUG)
2323 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2324 #else
2325 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2326 if (log)
2327 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
2328 #endif
2329 sequence_mutex_unavailable = true;
2330 }
2331 return thread_ids.size();
2332 }
2333
2334 lldb::addr_t
GetShlibInfoAddr()2335 GDBRemoteCommunicationClient::GetShlibInfoAddr()
2336 {
2337 if (!IsRunning())
2338 {
2339 StringExtractorGDBRemote response;
2340 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2341 {
2342 if (response.IsNormalResponse())
2343 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2344 }
2345 }
2346 return LLDB_INVALID_ADDRESS;
2347 }
2348
2349