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