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%llx,%s%s%s", 1219 (uint64_t)size, 1220 permissions & lldb::ePermissionsReadable ? "r" : "", 1221 permissions & lldb::ePermissionsWritable ? "w" : "", 1222 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1223 assert (packet_len < sizeof(packet)); 1224 StringExtractorGDBRemote response; 1225 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1226 { 1227 if (!response.IsErrorResponse()) 1228 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1229 } 1230 else 1231 { 1232 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1233 } 1234 } 1235 return LLDB_INVALID_ADDRESS; 1236 } 1237 1238 bool 1239 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 1240 { 1241 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1242 { 1243 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1244 char packet[64]; 1245 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr); 1246 assert (packet_len < sizeof(packet)); 1247 StringExtractorGDBRemote response; 1248 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1249 { 1250 if (response.IsOKResponse()) 1251 return true; 1252 } 1253 else 1254 { 1255 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1256 } 1257 } 1258 return false; 1259 } 1260 1261 bool 1262 GDBRemoteCommunicationClient::Detach () 1263 { 1264 return SendPacket ("D", 1) > 0; 1265 } 1266 1267 Error 1268 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 1269 lldb_private::MemoryRegionInfo ®ion_info) 1270 { 1271 Error error; 1272 region_info.Clear(); 1273 1274 if (m_supports_memory_region_info != eLazyBoolNo) 1275 { 1276 m_supports_memory_region_info = eLazyBoolYes; 1277 char packet[64]; 1278 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%llx", (uint64_t)addr); 1279 assert (packet_len < sizeof(packet)); 1280 StringExtractorGDBRemote response; 1281 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1282 { 1283 std::string name; 1284 std::string value; 1285 addr_t addr_value; 1286 bool success = true; 1287 bool saw_permissions = false; 1288 while (success && response.GetNameColonValue(name, value)) 1289 { 1290 if (name.compare ("start") == 0) 1291 { 1292 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 1293 if (success) 1294 region_info.GetRange().SetRangeBase(addr_value); 1295 } 1296 else if (name.compare ("size") == 0) 1297 { 1298 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success); 1299 if (success) 1300 region_info.GetRange().SetByteSize (addr_value); 1301 } 1302 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 1303 { 1304 saw_permissions = true; 1305 if (region_info.GetRange().Contains (addr)) 1306 { 1307 if (value.find('r') != std::string::npos) 1308 region_info.SetReadable (MemoryRegionInfo::eYes); 1309 else 1310 region_info.SetReadable (MemoryRegionInfo::eNo); 1311 1312 if (value.find('w') != std::string::npos) 1313 region_info.SetWritable (MemoryRegionInfo::eYes); 1314 else 1315 region_info.SetWritable (MemoryRegionInfo::eNo); 1316 1317 if (value.find('x') != std::string::npos) 1318 region_info.SetExecutable (MemoryRegionInfo::eYes); 1319 else 1320 region_info.SetExecutable (MemoryRegionInfo::eNo); 1321 } 1322 else 1323 { 1324 // The reported region does not contain this address -- we're looking at an unmapped page 1325 region_info.SetReadable (MemoryRegionInfo::eNo); 1326 region_info.SetWritable (MemoryRegionInfo::eNo); 1327 region_info.SetExecutable (MemoryRegionInfo::eNo); 1328 } 1329 } 1330 else if (name.compare ("error") == 0) 1331 { 1332 StringExtractorGDBRemote name_extractor; 1333 // Swap "value" over into "name_extractor" 1334 name_extractor.GetStringRef().swap(value); 1335 // Now convert the HEX bytes into a string value 1336 name_extractor.GetHexByteString (value); 1337 error.SetErrorString(value.c_str()); 1338 } 1339 } 1340 1341 // We got a valid address range back but no permissions -- which means this is an unmapped page 1342 if (region_info.GetRange().IsValid() && saw_permissions == false) 1343 { 1344 region_info.SetReadable (MemoryRegionInfo::eNo); 1345 region_info.SetWritable (MemoryRegionInfo::eNo); 1346 region_info.SetExecutable (MemoryRegionInfo::eNo); 1347 } 1348 } 1349 else 1350 { 1351 m_supports_memory_region_info = eLazyBoolNo; 1352 } 1353 } 1354 1355 if (m_supports_memory_region_info == eLazyBoolNo) 1356 { 1357 error.SetErrorString("qMemoryRegionInfo is not supported"); 1358 } 1359 if (error.Fail()) 1360 region_info.Clear(); 1361 return error; 1362 1363 } 1364 1365 Error 1366 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 1367 { 1368 Error error; 1369 1370 if (m_supports_watchpoint_support_info == eLazyBoolYes) 1371 { 1372 num = m_num_supported_hardware_watchpoints; 1373 return error; 1374 } 1375 1376 // Set num to 0 first. 1377 num = 0; 1378 if (m_supports_watchpoint_support_info != eLazyBoolNo) 1379 { 1380 char packet[64]; 1381 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1382 assert (packet_len < sizeof(packet)); 1383 StringExtractorGDBRemote response; 1384 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1385 { 1386 m_supports_watchpoint_support_info = eLazyBoolYes; 1387 std::string name; 1388 std::string value; 1389 while (response.GetNameColonValue(name, value)) 1390 { 1391 if (name.compare ("num") == 0) 1392 { 1393 num = Args::StringToUInt32(value.c_str(), 0, 0); 1394 m_num_supported_hardware_watchpoints = num; 1395 } 1396 } 1397 } 1398 else 1399 { 1400 m_supports_watchpoint_support_info = eLazyBoolNo; 1401 } 1402 } 1403 1404 if (m_supports_watchpoint_support_info == eLazyBoolNo) 1405 { 1406 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1407 } 1408 return error; 1409 1410 } 1411 1412 lldb_private::Error 1413 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after) 1414 { 1415 Error error(GetWatchpointSupportInfo(num)); 1416 if (error.Success()) 1417 error = GetWatchpointsTriggerAfterInstruction(after); 1418 return error; 1419 } 1420 1421 lldb_private::Error 1422 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after) 1423 { 1424 Error error; 1425 1426 // we assume watchpoints will happen after running the relevant opcode 1427 // and we only want to override this behavior if we have explicitly 1428 // received a qHostInfo telling us otherwise 1429 if (m_qHostInfo_is_valid != eLazyBoolYes) 1430 after = true; 1431 else 1432 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1433 return error; 1434 } 1435 1436 int 1437 GDBRemoteCommunicationClient::SetSTDIN (char const *path) 1438 { 1439 if (path && path[0]) 1440 { 1441 StreamString packet; 1442 packet.PutCString("QSetSTDIN:"); 1443 packet.PutBytesAsRawHex8(path, strlen(path)); 1444 1445 StringExtractorGDBRemote response; 1446 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1447 { 1448 if (response.IsOKResponse()) 1449 return 0; 1450 uint8_t error = response.GetError(); 1451 if (error) 1452 return error; 1453 } 1454 } 1455 return -1; 1456 } 1457 1458 int 1459 GDBRemoteCommunicationClient::SetSTDOUT (char const *path) 1460 { 1461 if (path && path[0]) 1462 { 1463 StreamString packet; 1464 packet.PutCString("QSetSTDOUT:"); 1465 packet.PutBytesAsRawHex8(path, strlen(path)); 1466 1467 StringExtractorGDBRemote response; 1468 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1469 { 1470 if (response.IsOKResponse()) 1471 return 0; 1472 uint8_t error = response.GetError(); 1473 if (error) 1474 return error; 1475 } 1476 } 1477 return -1; 1478 } 1479 1480 int 1481 GDBRemoteCommunicationClient::SetSTDERR (char const *path) 1482 { 1483 if (path && path[0]) 1484 { 1485 StreamString packet; 1486 packet.PutCString("QSetSTDERR:"); 1487 packet.PutBytesAsRawHex8(path, strlen(path)); 1488 1489 StringExtractorGDBRemote response; 1490 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1491 { 1492 if (response.IsOKResponse()) 1493 return 0; 1494 uint8_t error = response.GetError(); 1495 if (error) 1496 return error; 1497 } 1498 } 1499 return -1; 1500 } 1501 1502 int 1503 GDBRemoteCommunicationClient::SetWorkingDir (char const *path) 1504 { 1505 if (path && path[0]) 1506 { 1507 StreamString packet; 1508 packet.PutCString("QSetWorkingDir:"); 1509 packet.PutBytesAsRawHex8(path, strlen(path)); 1510 1511 StringExtractorGDBRemote response; 1512 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1513 { 1514 if (response.IsOKResponse()) 1515 return 0; 1516 uint8_t error = response.GetError(); 1517 if (error) 1518 return error; 1519 } 1520 } 1521 return -1; 1522 } 1523 1524 int 1525 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 1526 { 1527 char packet[32]; 1528 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1529 assert (packet_len < sizeof(packet)); 1530 StringExtractorGDBRemote response; 1531 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1532 { 1533 if (response.IsOKResponse()) 1534 return 0; 1535 uint8_t error = response.GetError(); 1536 if (error) 1537 return error; 1538 } 1539 return -1; 1540 } 1541 1542 bool 1543 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 1544 { 1545 if (response.IsNormalResponse()) 1546 { 1547 std::string name; 1548 std::string value; 1549 StringExtractor extractor; 1550 1551 while (response.GetNameColonValue(name, value)) 1552 { 1553 if (name.compare("pid") == 0) 1554 { 1555 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1556 } 1557 else if (name.compare("ppid") == 0) 1558 { 1559 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1560 } 1561 else if (name.compare("uid") == 0) 1562 { 1563 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1564 } 1565 else if (name.compare("euid") == 0) 1566 { 1567 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1568 } 1569 else if (name.compare("gid") == 0) 1570 { 1571 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1572 } 1573 else if (name.compare("egid") == 0) 1574 { 1575 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1576 } 1577 else if (name.compare("triple") == 0) 1578 { 1579 // The triple comes as ASCII hex bytes since it contains '-' chars 1580 extractor.GetStringRef().swap(value); 1581 extractor.SetFilePos(0); 1582 extractor.GetHexByteString (value); 1583 process_info.GetArchitecture ().SetTriple (value.c_str()); 1584 } 1585 else if (name.compare("name") == 0) 1586 { 1587 StringExtractor extractor; 1588 // The process name from ASCII hex bytes since we can't 1589 // control the characters in a process name 1590 extractor.GetStringRef().swap(value); 1591 extractor.SetFilePos(0); 1592 extractor.GetHexByteString (value); 1593 process_info.GetExecutableFile().SetFile (value.c_str(), false); 1594 } 1595 } 1596 1597 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1598 return true; 1599 } 1600 return false; 1601 } 1602 1603 bool 1604 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1605 { 1606 process_info.Clear(); 1607 1608 if (m_supports_qProcessInfoPID) 1609 { 1610 char packet[32]; 1611 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%llu", pid); 1612 assert (packet_len < sizeof(packet)); 1613 StringExtractorGDBRemote response; 1614 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1615 { 1616 return DecodeProcessInfoResponse (response, process_info); 1617 } 1618 else 1619 { 1620 m_supports_qProcessInfoPID = false; 1621 return false; 1622 } 1623 } 1624 return false; 1625 } 1626 1627 uint32_t 1628 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 1629 ProcessInstanceInfoList &process_infos) 1630 { 1631 process_infos.Clear(); 1632 1633 if (m_supports_qfProcessInfo) 1634 { 1635 StreamString packet; 1636 packet.PutCString ("qfProcessInfo"); 1637 if (!match_info.MatchAllProcesses()) 1638 { 1639 packet.PutChar (':'); 1640 const char *name = match_info.GetProcessInfo().GetName(); 1641 bool has_name_match = false; 1642 if (name && name[0]) 1643 { 1644 has_name_match = true; 1645 NameMatchType name_match_type = match_info.GetNameMatchType(); 1646 switch (name_match_type) 1647 { 1648 case eNameMatchIgnore: 1649 has_name_match = false; 1650 break; 1651 1652 case eNameMatchEquals: 1653 packet.PutCString ("name_match:equals;"); 1654 break; 1655 1656 case eNameMatchContains: 1657 packet.PutCString ("name_match:contains;"); 1658 break; 1659 1660 case eNameMatchStartsWith: 1661 packet.PutCString ("name_match:starts_with;"); 1662 break; 1663 1664 case eNameMatchEndsWith: 1665 packet.PutCString ("name_match:ends_with;"); 1666 break; 1667 1668 case eNameMatchRegularExpression: 1669 packet.PutCString ("name_match:regex;"); 1670 break; 1671 } 1672 if (has_name_match) 1673 { 1674 packet.PutCString ("name:"); 1675 packet.PutBytesAsRawHex8(name, ::strlen(name)); 1676 packet.PutChar (';'); 1677 } 1678 } 1679 1680 if (match_info.GetProcessInfo().ProcessIDIsValid()) 1681 packet.Printf("pid:%llu;",match_info.GetProcessInfo().GetProcessID()); 1682 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 1683 packet.Printf("parent_pid:%llu;",match_info.GetProcessInfo().GetParentProcessID()); 1684 if (match_info.GetProcessInfo().UserIDIsValid()) 1685 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 1686 if (match_info.GetProcessInfo().GroupIDIsValid()) 1687 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 1688 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 1689 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 1690 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 1691 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 1692 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 1693 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 1694 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 1695 { 1696 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 1697 const llvm::Triple &triple = match_arch.GetTriple(); 1698 packet.PutCString("triple:"); 1699 packet.PutCStringAsRawHex8(triple.getTriple().c_str()); 1700 packet.PutChar (';'); 1701 } 1702 } 1703 StringExtractorGDBRemote response; 1704 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1705 { 1706 do 1707 { 1708 ProcessInstanceInfo process_info; 1709 if (!DecodeProcessInfoResponse (response, process_info)) 1710 break; 1711 process_infos.Append(process_info); 1712 response.GetStringRef().clear(); 1713 response.SetFilePos(0); 1714 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false)); 1715 } 1716 else 1717 { 1718 m_supports_qfProcessInfo = false; 1719 return 0; 1720 } 1721 } 1722 return process_infos.GetSize(); 1723 1724 } 1725 1726 bool 1727 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 1728 { 1729 if (m_supports_qUserName) 1730 { 1731 char packet[32]; 1732 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 1733 assert (packet_len < sizeof(packet)); 1734 StringExtractorGDBRemote response; 1735 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1736 { 1737 if (response.IsNormalResponse()) 1738 { 1739 // Make sure we parsed the right number of characters. The response is 1740 // the hex encoded user name and should make up the entire packet. 1741 // If there are any non-hex ASCII bytes, the length won't match below.. 1742 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 1743 return true; 1744 } 1745 } 1746 else 1747 { 1748 m_supports_qUserName = false; 1749 return false; 1750 } 1751 } 1752 return false; 1753 1754 } 1755 1756 bool 1757 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 1758 { 1759 if (m_supports_qGroupName) 1760 { 1761 char packet[32]; 1762 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 1763 assert (packet_len < sizeof(packet)); 1764 StringExtractorGDBRemote response; 1765 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1766 { 1767 if (response.IsNormalResponse()) 1768 { 1769 // Make sure we parsed the right number of characters. The response is 1770 // the hex encoded group name and should make up the entire packet. 1771 // If there are any non-hex ASCII bytes, the length won't match below.. 1772 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 1773 return true; 1774 } 1775 } 1776 else 1777 { 1778 m_supports_qGroupName = false; 1779 return false; 1780 } 1781 } 1782 return false; 1783 } 1784 1785 void 1786 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets) 1787 { 1788 uint32_t i; 1789 TimeValue start_time, end_time; 1790 uint64_t total_time_nsec; 1791 float packets_per_second; 1792 if (SendSpeedTestPacket (0, 0)) 1793 { 1794 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2) 1795 { 1796 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2) 1797 { 1798 start_time = TimeValue::Now(); 1799 for (i=0; i<num_packets; ++i) 1800 { 1801 SendSpeedTestPacket (send_size, recv_size); 1802 } 1803 end_time = TimeValue::Now(); 1804 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 1805 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 1806 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %llu.%9.9llu sec for %f packets/sec.\n", 1807 num_packets, 1808 send_size, 1809 recv_size, 1810 total_time_nsec / TimeValue::NanoSecPerSec, 1811 total_time_nsec % TimeValue::NanoSecPerSec, 1812 packets_per_second); 1813 if (recv_size == 0) 1814 recv_size = 32; 1815 } 1816 if (send_size == 0) 1817 send_size = 32; 1818 } 1819 } 1820 else 1821 { 1822 start_time = TimeValue::Now(); 1823 for (i=0; i<num_packets; ++i) 1824 { 1825 GetCurrentProcessID (); 1826 } 1827 end_time = TimeValue::Now(); 1828 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 1829 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 1830 printf ("%u 'qC' packets packets in 0x%llu%9.9llu sec for %f packets/sec.\n", 1831 num_packets, 1832 total_time_nsec / TimeValue::NanoSecPerSec, 1833 total_time_nsec % TimeValue::NanoSecPerSec, 1834 packets_per_second); 1835 } 1836 } 1837 1838 bool 1839 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 1840 { 1841 StreamString packet; 1842 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 1843 uint32_t bytes_left = send_size; 1844 while (bytes_left > 0) 1845 { 1846 if (bytes_left >= 26) 1847 { 1848 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 1849 bytes_left -= 26; 1850 } 1851 else 1852 { 1853 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 1854 bytes_left = 0; 1855 } 1856 } 1857 1858 StringExtractorGDBRemote response; 1859 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0; 1860 return false; 1861 } 1862 1863 uint16_t 1864 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort () 1865 { 1866 StringExtractorGDBRemote response; 1867 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false)) 1868 { 1869 std::string name; 1870 std::string value; 1871 uint16_t port = 0; 1872 //lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1873 while (response.GetNameColonValue(name, value)) 1874 { 1875 if (name.size() == 4 && name.compare("port") == 0) 1876 port = Args::StringToUInt32(value.c_str(), 0, 0); 1877 // if (name.size() == 3 && name.compare("pid") == 0) 1878 // pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 1879 } 1880 return port; 1881 } 1882 return 0; 1883 } 1884 1885 bool 1886 GDBRemoteCommunicationClient::SetCurrentThread (int tid) 1887 { 1888 if (m_curr_tid == tid) 1889 return true; 1890 1891 char packet[32]; 1892 int packet_len; 1893 if (tid <= 0) 1894 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid); 1895 else 1896 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 1897 assert (packet_len + 1 < sizeof(packet)); 1898 StringExtractorGDBRemote response; 1899 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1900 { 1901 if (response.IsOKResponse()) 1902 { 1903 m_curr_tid = tid; 1904 return true; 1905 } 1906 } 1907 return false; 1908 } 1909 1910 bool 1911 GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid) 1912 { 1913 if (m_curr_tid_run == tid) 1914 return true; 1915 1916 char packet[32]; 1917 int packet_len; 1918 if (tid <= 0) 1919 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid); 1920 else 1921 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid); 1922 1923 assert (packet_len + 1 < sizeof(packet)); 1924 StringExtractorGDBRemote response; 1925 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1926 { 1927 if (response.IsOKResponse()) 1928 { 1929 m_curr_tid_run = tid; 1930 return true; 1931 } 1932 } 1933 return false; 1934 } 1935 1936 bool 1937 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 1938 { 1939 if (SendPacketAndWaitForResponse("?", 1, response, false)) 1940 return response.IsNormalResponse(); 1941 return false; 1942 } 1943 1944 bool 1945 GDBRemoteCommunicationClient::GetThreadStopInfo (uint32_t tid, StringExtractorGDBRemote &response) 1946 { 1947 if (m_supports_qThreadStopInfo) 1948 { 1949 char packet[256]; 1950 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%x", tid); 1951 assert (packet_len < sizeof(packet)); 1952 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1953 { 1954 if (response.IsNormalResponse()) 1955 return true; 1956 else 1957 return false; 1958 } 1959 else 1960 { 1961 m_supports_qThreadStopInfo = false; 1962 } 1963 } 1964 // if (SetCurrentThread (tid)) 1965 // return GetStopReply (response); 1966 return false; 1967 } 1968 1969 1970 uint8_t 1971 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 1972 { 1973 switch (type) 1974 { 1975 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break; 1976 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break; 1977 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break; 1978 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break; 1979 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break; 1980 default: return UINT8_MAX; 1981 } 1982 1983 char packet[64]; 1984 const int packet_len = ::snprintf (packet, 1985 sizeof(packet), 1986 "%c%i,%llx,%x", 1987 insert ? 'Z' : 'z', 1988 type, 1989 addr, 1990 length); 1991 1992 assert (packet_len + 1 < sizeof(packet)); 1993 StringExtractorGDBRemote response; 1994 if (SendPacketAndWaitForResponse(packet, packet_len, response, true)) 1995 { 1996 if (response.IsOKResponse()) 1997 return 0; 1998 else if (response.IsErrorResponse()) 1999 return response.GetError(); 2000 } 2001 else 2002 { 2003 switch (type) 2004 { 2005 case eBreakpointSoftware: m_supports_z0 = false; break; 2006 case eBreakpointHardware: m_supports_z1 = false; break; 2007 case eWatchpointWrite: m_supports_z2 = false; break; 2008 case eWatchpointRead: m_supports_z3 = false; break; 2009 case eWatchpointReadWrite: m_supports_z4 = false; break; 2010 default: break; 2011 } 2012 } 2013 2014 return UINT8_MAX; 2015 } 2016 2017 size_t 2018 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 2019 bool &sequence_mutex_unavailable) 2020 { 2021 Mutex::Locker locker; 2022 thread_ids.clear(); 2023 2024 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 2025 { 2026 sequence_mutex_unavailable = false; 2027 StringExtractorGDBRemote response; 2028 2029 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()); 2030 response.IsNormalResponse(); 2031 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ())) 2032 { 2033 char ch = response.GetChar(); 2034 if (ch == 'l') 2035 break; 2036 if (ch == 'm') 2037 { 2038 do 2039 { 2040 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 2041 2042 if (tid != LLDB_INVALID_THREAD_ID) 2043 { 2044 thread_ids.push_back (tid); 2045 } 2046 ch = response.GetChar(); // Skip the command separator 2047 } while (ch == ','); // Make sure we got a comma separator 2048 } 2049 } 2050 } 2051 else 2052 { 2053 #if defined (LLDB_CONFIGURATION_DEBUG) 2054 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 2055 #else 2056 LogSP log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2057 if (log) 2058 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 2059 #endif 2060 sequence_mutex_unavailable = true; 2061 } 2062 return thread_ids.size(); 2063 } 2064 2065 lldb::addr_t 2066 GDBRemoteCommunicationClient::GetShlibInfoAddr() 2067 { 2068 if (!IsRunning()) 2069 { 2070 StringExtractorGDBRemote response; 2071 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false)) 2072 { 2073 if (response.IsNormalResponse()) 2074 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2075 } 2076 } 2077 return LLDB_INVALID_ADDRESS; 2078 } 2079 2080