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 'A': 651 // Async miscellaneous reply. Right now, only profile data is coming through this channel. 652 { 653 const std::string& profile_data = response.GetStringRef(); 654 const char *data_cstr = profile_data.c_str(); 655 data_cstr++; // Move beyond 'A' 656 process->BroadcastAsyncProfileData (data_cstr, profile_data.size()-1); 657 } 658 break; 659 660 case 'E': 661 // ERROR 662 state = eStateInvalid; 663 break; 664 665 default: 666 if (log) 667 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__); 668 state = eStateInvalid; 669 break; 670 } 671 } 672 } 673 else 674 { 675 if (log) 676 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__); 677 state = eStateInvalid; 678 } 679 } 680 if (log) 681 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state)); 682 response.SetFilePos(0); 683 m_private_is_running.SetValue (false, eBroadcastAlways); 684 m_public_is_running.SetValue (false, eBroadcastAlways); 685 return state; 686 } 687 688 bool 689 GDBRemoteCommunicationClient::SendAsyncSignal (int signo) 690 { 691 Mutex::Locker async_locker (m_async_mutex); 692 m_async_signal = signo; 693 bool timed_out = false; 694 Mutex::Locker locker; 695 if (SendInterrupt (locker, 1, timed_out)) 696 return true; 697 m_async_signal = -1; 698 return false; 699 } 700 701 // This function takes a mutex locker as a parameter in case the GetSequenceMutex 702 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex 703 // (the expected result), then it will send the halt packet. If it does succeed 704 // then the caller that requested the interrupt will want to keep the sequence 705 // locked down so that no one else can send packets while the caller has control. 706 // This function usually gets called when we are running and need to stop the 707 // target. It can also be used when we are running and and we need to do something 708 // else (like read/write memory), so we need to interrupt the running process 709 // (gdb remote protocol requires this), and do what we need to do, then resume. 710 711 bool 712 GDBRemoteCommunicationClient::SendInterrupt 713 ( 714 Mutex::Locker& locker, 715 uint32_t seconds_to_wait_for_stop, 716 bool &timed_out 717 ) 718 { 719 timed_out = false; 720 LogSP log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 721 722 if (IsRunning()) 723 { 724 // Only send an interrupt if our debugserver is running... 725 if (GetSequenceMutex (locker)) 726 { 727 if (log) 728 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt"); 729 } 730 else 731 { 732 // Someone has the mutex locked waiting for a response or for the 733 // inferior to stop, so send the interrupt on the down low... 734 char ctrl_c = '\x03'; 735 ConnectionStatus status = eConnectionStatusSuccess; 736 size_t bytes_written = Write (&ctrl_c, 1, status, NULL); 737 if (log) 738 log->PutCString("send packet: \\x03"); 739 if (bytes_written > 0) 740 { 741 m_interrupt_sent = true; 742 if (seconds_to_wait_for_stop) 743 { 744 TimeValue timeout; 745 if (seconds_to_wait_for_stop) 746 { 747 timeout = TimeValue::Now(); 748 timeout.OffsetWithSeconds (seconds_to_wait_for_stop); 749 } 750 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out)) 751 { 752 if (log) 753 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped"); 754 return true; 755 } 756 else 757 { 758 if (log) 759 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume"); 760 } 761 } 762 else 763 { 764 if (log) 765 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop..."); 766 return true; 767 } 768 } 769 else 770 { 771 if (log) 772 log->Printf ("SendInterrupt () - failed to write interrupt"); 773 } 774 return false; 775 } 776 } 777 else 778 { 779 if (log) 780 log->Printf ("SendInterrupt () - not running"); 781 } 782 return true; 783 } 784 785 lldb::pid_t 786 GDBRemoteCommunicationClient::GetCurrentProcessID () 787 { 788 StringExtractorGDBRemote response; 789 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false)) 790 { 791 if (response.GetChar() == 'Q') 792 if (response.GetChar() == 'C') 793 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID); 794 } 795 return LLDB_INVALID_PROCESS_ID; 796 } 797 798 bool 799 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str) 800 { 801 error_str.clear(); 802 StringExtractorGDBRemote response; 803 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false)) 804 { 805 if (response.IsOKResponse()) 806 return true; 807 if (response.GetChar() == 'E') 808 { 809 // A string the describes what failed when launching... 810 error_str = response.GetStringRef().substr(1); 811 } 812 else 813 { 814 error_str.assign ("unknown error occurred launching process"); 815 } 816 } 817 else 818 { 819 error_str.assign ("timed out waiting for app to launch"); 820 } 821 return false; 822 } 823 824 int 825 GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[]) 826 { 827 if (argv && argv[0]) 828 { 829 StreamString packet; 830 packet.PutChar('A'); 831 const char *arg; 832 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i) 833 { 834 const int arg_len = strlen(arg); 835 if (i > 0) 836 packet.PutChar(','); 837 packet.Printf("%i,%i,", arg_len * 2, i); 838 packet.PutBytesAsRawHex8 (arg, arg_len); 839 } 840 841 StringExtractorGDBRemote response; 842 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 843 { 844 if (response.IsOKResponse()) 845 return 0; 846 uint8_t error = response.GetError(); 847 if (error) 848 return error; 849 } 850 } 851 return -1; 852 } 853 854 int 855 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value) 856 { 857 if (name_equal_value && name_equal_value[0]) 858 { 859 StreamString packet; 860 packet.Printf("QEnvironment:%s", name_equal_value); 861 StringExtractorGDBRemote response; 862 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 863 { 864 if (response.IsOKResponse()) 865 return 0; 866 uint8_t error = response.GetError(); 867 if (error) 868 return error; 869 } 870 } 871 return -1; 872 } 873 874 int 875 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch) 876 { 877 if (arch && arch[0]) 878 { 879 StreamString packet; 880 packet.Printf("QLaunchArch:%s", arch); 881 StringExtractorGDBRemote response; 882 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 883 { 884 if (response.IsOKResponse()) 885 return 0; 886 uint8_t error = response.GetError(); 887 if (error) 888 return error; 889 } 890 } 891 return -1; 892 } 893 894 bool 895 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major, 896 uint32_t &minor, 897 uint32_t &update) 898 { 899 if (GetHostInfo ()) 900 { 901 if (m_os_version_major != UINT32_MAX) 902 { 903 major = m_os_version_major; 904 minor = m_os_version_minor; 905 update = m_os_version_update; 906 return true; 907 } 908 } 909 return false; 910 } 911 912 bool 913 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s) 914 { 915 if (GetHostInfo ()) 916 { 917 if (!m_os_build.empty()) 918 { 919 s = m_os_build; 920 return true; 921 } 922 } 923 s.clear(); 924 return false; 925 } 926 927 928 bool 929 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s) 930 { 931 if (GetHostInfo ()) 932 { 933 if (!m_os_kernel.empty()) 934 { 935 s = m_os_kernel; 936 return true; 937 } 938 } 939 s.clear(); 940 return false; 941 } 942 943 bool 944 GDBRemoteCommunicationClient::GetHostname (std::string &s) 945 { 946 if (GetHostInfo ()) 947 { 948 if (!m_hostname.empty()) 949 { 950 s = m_hostname; 951 return true; 952 } 953 } 954 s.clear(); 955 return false; 956 } 957 958 ArchSpec 959 GDBRemoteCommunicationClient::GetSystemArchitecture () 960 { 961 if (GetHostInfo ()) 962 return m_host_arch; 963 return ArchSpec(); 964 } 965 966 967 bool 968 GDBRemoteCommunicationClient::GetHostInfo (bool force) 969 { 970 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) 971 { 972 m_qHostInfo_is_valid = eLazyBoolNo; 973 StringExtractorGDBRemote response; 974 if (SendPacketAndWaitForResponse ("qHostInfo", response, false)) 975 { 976 if (response.IsNormalResponse()) 977 { 978 std::string name; 979 std::string value; 980 uint32_t cpu = LLDB_INVALID_CPUTYPE; 981 uint32_t sub = 0; 982 std::string arch_name; 983 std::string os_name; 984 std::string vendor_name; 985 std::string triple; 986 uint32_t pointer_byte_size = 0; 987 StringExtractor extractor; 988 ByteOrder byte_order = eByteOrderInvalid; 989 uint32_t num_keys_decoded = 0; 990 while (response.GetNameColonValue(name, value)) 991 { 992 if (name.compare("cputype") == 0) 993 { 994 // exception type in big endian hex 995 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0); 996 if (cpu != LLDB_INVALID_CPUTYPE) 997 ++num_keys_decoded; 998 } 999 else if (name.compare("cpusubtype") == 0) 1000 { 1001 // exception count in big endian hex 1002 sub = Args::StringToUInt32 (value.c_str(), 0, 0); 1003 if (sub != 0) 1004 ++num_keys_decoded; 1005 } 1006 else if (name.compare("arch") == 0) 1007 { 1008 arch_name.swap (value); 1009 ++num_keys_decoded; 1010 } 1011 else if (name.compare("triple") == 0) 1012 { 1013 // The triple comes as ASCII hex bytes since it contains '-' chars 1014 extractor.GetStringRef().swap(value); 1015 extractor.SetFilePos(0); 1016 extractor.GetHexByteString (triple); 1017 ++num_keys_decoded; 1018 } 1019 else if (name.compare("os_build") == 0) 1020 { 1021 extractor.GetStringRef().swap(value); 1022 extractor.SetFilePos(0); 1023 extractor.GetHexByteString (m_os_build); 1024 ++num_keys_decoded; 1025 } 1026 else if (name.compare("hostname") == 0) 1027 { 1028 extractor.GetStringRef().swap(value); 1029 extractor.SetFilePos(0); 1030 extractor.GetHexByteString (m_hostname); 1031 ++num_keys_decoded; 1032 } 1033 else if (name.compare("os_kernel") == 0) 1034 { 1035 extractor.GetStringRef().swap(value); 1036 extractor.SetFilePos(0); 1037 extractor.GetHexByteString (m_os_kernel); 1038 ++num_keys_decoded; 1039 } 1040 else if (name.compare("ostype") == 0) 1041 { 1042 os_name.swap (value); 1043 ++num_keys_decoded; 1044 } 1045 else if (name.compare("vendor") == 0) 1046 { 1047 vendor_name.swap(value); 1048 ++num_keys_decoded; 1049 } 1050 else if (name.compare("endian") == 0) 1051 { 1052 ++num_keys_decoded; 1053 if (value.compare("little") == 0) 1054 byte_order = eByteOrderLittle; 1055 else if (value.compare("big") == 0) 1056 byte_order = eByteOrderBig; 1057 else if (value.compare("pdp") == 0) 1058 byte_order = eByteOrderPDP; 1059 else 1060 --num_keys_decoded; 1061 } 1062 else if (name.compare("ptrsize") == 0) 1063 { 1064 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0); 1065 if (pointer_byte_size != 0) 1066 ++num_keys_decoded; 1067 } 1068 else if (name.compare("os_version") == 0) 1069 { 1070 Args::StringToVersion (value.c_str(), 1071 m_os_version_major, 1072 m_os_version_minor, 1073 m_os_version_update); 1074 if (m_os_version_major != UINT32_MAX) 1075 ++num_keys_decoded; 1076 } 1077 else if (name.compare("watchpoint_exceptions_received") == 0) 1078 { 1079 ++num_keys_decoded; 1080 if (strcmp(value.c_str(),"before") == 0) 1081 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 1082 else if (strcmp(value.c_str(),"after") == 0) 1083 m_watchpoints_trigger_after_instruction = eLazyBoolYes; 1084 else 1085 --num_keys_decoded; 1086 } 1087 1088 } 1089 1090 if (num_keys_decoded > 0) 1091 m_qHostInfo_is_valid = eLazyBoolYes; 1092 1093 if (triple.empty()) 1094 { 1095 if (arch_name.empty()) 1096 { 1097 if (cpu != LLDB_INVALID_CPUTYPE) 1098 { 1099 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 1100 if (pointer_byte_size) 1101 { 1102 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1103 } 1104 if (byte_order != eByteOrderInvalid) 1105 { 1106 assert (byte_order == m_host_arch.GetByteOrder()); 1107 } 1108 1109 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0) 1110 { 1111 switch (m_host_arch.GetMachine()) 1112 { 1113 case llvm::Triple::arm: 1114 case llvm::Triple::thumb: 1115 os_name = "ios"; 1116 break; 1117 default: 1118 os_name = "macosx"; 1119 break; 1120 } 1121 } 1122 if (!vendor_name.empty()) 1123 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 1124 if (!os_name.empty()) 1125 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 1126 1127 } 1128 } 1129 else 1130 { 1131 std::string triple; 1132 triple += arch_name; 1133 if (!vendor_name.empty() || !os_name.empty()) 1134 { 1135 triple += '-'; 1136 if (vendor_name.empty()) 1137 triple += "unknown"; 1138 else 1139 triple += vendor_name; 1140 triple += '-'; 1141 if (os_name.empty()) 1142 triple += "unknown"; 1143 else 1144 triple += os_name; 1145 } 1146 m_host_arch.SetTriple (triple.c_str()); 1147 1148 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1149 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin) 1150 { 1151 switch (m_host_arch.GetMachine()) 1152 { 1153 case llvm::Triple::arm: 1154 case llvm::Triple::thumb: 1155 host_triple.setOS(llvm::Triple::IOS); 1156 break; 1157 default: 1158 host_triple.setOS(llvm::Triple::MacOSX); 1159 break; 1160 } 1161 } 1162 if (pointer_byte_size) 1163 { 1164 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1165 } 1166 if (byte_order != eByteOrderInvalid) 1167 { 1168 assert (byte_order == m_host_arch.GetByteOrder()); 1169 } 1170 1171 } 1172 } 1173 else 1174 { 1175 m_host_arch.SetTriple (triple.c_str()); 1176 if (pointer_byte_size) 1177 { 1178 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1179 } 1180 if (byte_order != eByteOrderInvalid) 1181 { 1182 assert (byte_order == m_host_arch.GetByteOrder()); 1183 } 1184 } 1185 } 1186 } 1187 } 1188 return m_qHostInfo_is_valid == eLazyBoolYes; 1189 } 1190 1191 int 1192 GDBRemoteCommunicationClient::SendAttach 1193 ( 1194 lldb::pid_t pid, 1195 StringExtractorGDBRemote& response 1196 ) 1197 { 1198 if (pid != LLDB_INVALID_PROCESS_ID) 1199 { 1200 char packet[64]; 1201 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid); 1202 assert (packet_len < sizeof(packet)); 1203 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1204 { 1205 if (response.IsErrorResponse()) 1206 return response.GetError(); 1207 return 0; 1208 } 1209 } 1210 return -1; 1211 } 1212 1213 const lldb_private::ArchSpec & 1214 GDBRemoteCommunicationClient::GetHostArchitecture () 1215 { 1216 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1217 GetHostInfo (); 1218 return m_host_arch; 1219 } 1220 1221 addr_t 1222 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions) 1223 { 1224 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1225 { 1226 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1227 char packet[64]; 1228 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", 1229 (uint64_t)size, 1230 permissions & lldb::ePermissionsReadable ? "r" : "", 1231 permissions & lldb::ePermissionsWritable ? "w" : "", 1232 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1233 assert (packet_len < sizeof(packet)); 1234 StringExtractorGDBRemote response; 1235 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1236 { 1237 if (!response.IsErrorResponse()) 1238 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1239 } 1240 else 1241 { 1242 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1243 } 1244 } 1245 return LLDB_INVALID_ADDRESS; 1246 } 1247 1248 bool 1249 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 1250 { 1251 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1252 { 1253 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1254 char packet[64]; 1255 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1256 assert (packet_len < sizeof(packet)); 1257 StringExtractorGDBRemote response; 1258 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1259 { 1260 if (response.IsOKResponse()) 1261 return true; 1262 } 1263 else 1264 { 1265 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1266 } 1267 } 1268 return false; 1269 } 1270 1271 bool 1272 GDBRemoteCommunicationClient::Detach () 1273 { 1274 return SendPacket ("D", 1) > 0; 1275 } 1276 1277 Error 1278 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 1279 lldb_private::MemoryRegionInfo ®ion_info) 1280 { 1281 Error error; 1282 region_info.Clear(); 1283 1284 if (m_supports_memory_region_info != eLazyBoolNo) 1285 { 1286 m_supports_memory_region_info = eLazyBoolYes; 1287 char packet[64]; 1288 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1289 assert (packet_len < sizeof(packet)); 1290 StringExtractorGDBRemote response; 1291 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1292 { 1293 std::string name; 1294 std::string value; 1295 addr_t addr_value; 1296 bool success = true; 1297 bool saw_permissions = false; 1298 while (success && response.GetNameColonValue(name, value)) 1299 { 1300 if (name.compare ("start") == 0) 1301 { 1302 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 1303 if (success) 1304 region_info.GetRange().SetRangeBase(addr_value); 1305 } 1306 else if (name.compare ("size") == 0) 1307 { 1308 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success); 1309 if (success) 1310 region_info.GetRange().SetByteSize (addr_value); 1311 } 1312 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 1313 { 1314 saw_permissions = true; 1315 if (region_info.GetRange().Contains (addr)) 1316 { 1317 if (value.find('r') != std::string::npos) 1318 region_info.SetReadable (MemoryRegionInfo::eYes); 1319 else 1320 region_info.SetReadable (MemoryRegionInfo::eNo); 1321 1322 if (value.find('w') != std::string::npos) 1323 region_info.SetWritable (MemoryRegionInfo::eYes); 1324 else 1325 region_info.SetWritable (MemoryRegionInfo::eNo); 1326 1327 if (value.find('x') != std::string::npos) 1328 region_info.SetExecutable (MemoryRegionInfo::eYes); 1329 else 1330 region_info.SetExecutable (MemoryRegionInfo::eNo); 1331 } 1332 else 1333 { 1334 // The reported region does not contain this address -- we're looking at an unmapped page 1335 region_info.SetReadable (MemoryRegionInfo::eNo); 1336 region_info.SetWritable (MemoryRegionInfo::eNo); 1337 region_info.SetExecutable (MemoryRegionInfo::eNo); 1338 } 1339 } 1340 else if (name.compare ("error") == 0) 1341 { 1342 StringExtractorGDBRemote name_extractor; 1343 // Swap "value" over into "name_extractor" 1344 name_extractor.GetStringRef().swap(value); 1345 // Now convert the HEX bytes into a string value 1346 name_extractor.GetHexByteString (value); 1347 error.SetErrorString(value.c_str()); 1348 } 1349 } 1350 1351 // We got a valid address range back but no permissions -- which means this is an unmapped page 1352 if (region_info.GetRange().IsValid() && saw_permissions == false) 1353 { 1354 region_info.SetReadable (MemoryRegionInfo::eNo); 1355 region_info.SetWritable (MemoryRegionInfo::eNo); 1356 region_info.SetExecutable (MemoryRegionInfo::eNo); 1357 } 1358 } 1359 else 1360 { 1361 m_supports_memory_region_info = eLazyBoolNo; 1362 } 1363 } 1364 1365 if (m_supports_memory_region_info == eLazyBoolNo) 1366 { 1367 error.SetErrorString("qMemoryRegionInfo is not supported"); 1368 } 1369 if (error.Fail()) 1370 region_info.Clear(); 1371 return error; 1372 1373 } 1374 1375 Error 1376 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 1377 { 1378 Error error; 1379 1380 if (m_supports_watchpoint_support_info == eLazyBoolYes) 1381 { 1382 num = m_num_supported_hardware_watchpoints; 1383 return error; 1384 } 1385 1386 // Set num to 0 first. 1387 num = 0; 1388 if (m_supports_watchpoint_support_info != eLazyBoolNo) 1389 { 1390 char packet[64]; 1391 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1392 assert (packet_len < sizeof(packet)); 1393 StringExtractorGDBRemote response; 1394 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1395 { 1396 m_supports_watchpoint_support_info = eLazyBoolYes; 1397 std::string name; 1398 std::string value; 1399 while (response.GetNameColonValue(name, value)) 1400 { 1401 if (name.compare ("num") == 0) 1402 { 1403 num = Args::StringToUInt32(value.c_str(), 0, 0); 1404 m_num_supported_hardware_watchpoints = num; 1405 } 1406 } 1407 } 1408 else 1409 { 1410 m_supports_watchpoint_support_info = eLazyBoolNo; 1411 } 1412 } 1413 1414 if (m_supports_watchpoint_support_info == eLazyBoolNo) 1415 { 1416 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1417 } 1418 return error; 1419 1420 } 1421 1422 lldb_private::Error 1423 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after) 1424 { 1425 Error error(GetWatchpointSupportInfo(num)); 1426 if (error.Success()) 1427 error = GetWatchpointsTriggerAfterInstruction(after); 1428 return error; 1429 } 1430 1431 lldb_private::Error 1432 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after) 1433 { 1434 Error error; 1435 1436 // we assume watchpoints will happen after running the relevant opcode 1437 // and we only want to override this behavior if we have explicitly 1438 // received a qHostInfo telling us otherwise 1439 if (m_qHostInfo_is_valid != eLazyBoolYes) 1440 after = true; 1441 else 1442 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1443 return error; 1444 } 1445 1446 int 1447 GDBRemoteCommunicationClient::SetSTDIN (char const *path) 1448 { 1449 if (path && path[0]) 1450 { 1451 StreamString packet; 1452 packet.PutCString("QSetSTDIN:"); 1453 packet.PutBytesAsRawHex8(path, strlen(path)); 1454 1455 StringExtractorGDBRemote response; 1456 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1457 { 1458 if (response.IsOKResponse()) 1459 return 0; 1460 uint8_t error = response.GetError(); 1461 if (error) 1462 return error; 1463 } 1464 } 1465 return -1; 1466 } 1467 1468 int 1469 GDBRemoteCommunicationClient::SetSTDOUT (char const *path) 1470 { 1471 if (path && path[0]) 1472 { 1473 StreamString packet; 1474 packet.PutCString("QSetSTDOUT:"); 1475 packet.PutBytesAsRawHex8(path, strlen(path)); 1476 1477 StringExtractorGDBRemote response; 1478 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1479 { 1480 if (response.IsOKResponse()) 1481 return 0; 1482 uint8_t error = response.GetError(); 1483 if (error) 1484 return error; 1485 } 1486 } 1487 return -1; 1488 } 1489 1490 int 1491 GDBRemoteCommunicationClient::SetSTDERR (char const *path) 1492 { 1493 if (path && path[0]) 1494 { 1495 StreamString packet; 1496 packet.PutCString("QSetSTDERR:"); 1497 packet.PutBytesAsRawHex8(path, strlen(path)); 1498 1499 StringExtractorGDBRemote response; 1500 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1501 { 1502 if (response.IsOKResponse()) 1503 return 0; 1504 uint8_t error = response.GetError(); 1505 if (error) 1506 return error; 1507 } 1508 } 1509 return -1; 1510 } 1511 1512 int 1513 GDBRemoteCommunicationClient::SetWorkingDir (char const *path) 1514 { 1515 if (path && path[0]) 1516 { 1517 StreamString packet; 1518 packet.PutCString("QSetWorkingDir:"); 1519 packet.PutBytesAsRawHex8(path, strlen(path)); 1520 1521 StringExtractorGDBRemote response; 1522 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1523 { 1524 if (response.IsOKResponse()) 1525 return 0; 1526 uint8_t error = response.GetError(); 1527 if (error) 1528 return error; 1529 } 1530 } 1531 return -1; 1532 } 1533 1534 int 1535 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 1536 { 1537 char packet[32]; 1538 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1539 assert (packet_len < sizeof(packet)); 1540 StringExtractorGDBRemote response; 1541 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1542 { 1543 if (response.IsOKResponse()) 1544 return 0; 1545 uint8_t error = response.GetError(); 1546 if (error) 1547 return error; 1548 } 1549 return -1; 1550 } 1551 1552 bool 1553 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 1554 { 1555 if (response.IsNormalResponse()) 1556 { 1557 std::string name; 1558 std::string value; 1559 StringExtractor extractor; 1560 1561 while (response.GetNameColonValue(name, value)) 1562 { 1563 if (name.compare("pid") == 0) 1564 { 1565 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1566 } 1567 else if (name.compare("ppid") == 0) 1568 { 1569 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1570 } 1571 else if (name.compare("uid") == 0) 1572 { 1573 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1574 } 1575 else if (name.compare("euid") == 0) 1576 { 1577 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1578 } 1579 else if (name.compare("gid") == 0) 1580 { 1581 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1582 } 1583 else if (name.compare("egid") == 0) 1584 { 1585 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1586 } 1587 else if (name.compare("triple") == 0) 1588 { 1589 // The triple comes as ASCII hex bytes since it contains '-' chars 1590 extractor.GetStringRef().swap(value); 1591 extractor.SetFilePos(0); 1592 extractor.GetHexByteString (value); 1593 process_info.GetArchitecture ().SetTriple (value.c_str()); 1594 } 1595 else if (name.compare("name") == 0) 1596 { 1597 StringExtractor extractor; 1598 // The process name from ASCII hex bytes since we can't 1599 // control the characters in a process name 1600 extractor.GetStringRef().swap(value); 1601 extractor.SetFilePos(0); 1602 extractor.GetHexByteString (value); 1603 process_info.GetExecutableFile().SetFile (value.c_str(), false); 1604 } 1605 } 1606 1607 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1608 return true; 1609 } 1610 return false; 1611 } 1612 1613 bool 1614 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1615 { 1616 process_info.Clear(); 1617 1618 if (m_supports_qProcessInfoPID) 1619 { 1620 char packet[32]; 1621 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid); 1622 assert (packet_len < sizeof(packet)); 1623 StringExtractorGDBRemote response; 1624 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1625 { 1626 return DecodeProcessInfoResponse (response, process_info); 1627 } 1628 else 1629 { 1630 m_supports_qProcessInfoPID = false; 1631 return false; 1632 } 1633 } 1634 return false; 1635 } 1636 1637 uint32_t 1638 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 1639 ProcessInstanceInfoList &process_infos) 1640 { 1641 process_infos.Clear(); 1642 1643 if (m_supports_qfProcessInfo) 1644 { 1645 StreamString packet; 1646 packet.PutCString ("qfProcessInfo"); 1647 if (!match_info.MatchAllProcesses()) 1648 { 1649 packet.PutChar (':'); 1650 const char *name = match_info.GetProcessInfo().GetName(); 1651 bool has_name_match = false; 1652 if (name && name[0]) 1653 { 1654 has_name_match = true; 1655 NameMatchType name_match_type = match_info.GetNameMatchType(); 1656 switch (name_match_type) 1657 { 1658 case eNameMatchIgnore: 1659 has_name_match = false; 1660 break; 1661 1662 case eNameMatchEquals: 1663 packet.PutCString ("name_match:equals;"); 1664 break; 1665 1666 case eNameMatchContains: 1667 packet.PutCString ("name_match:contains;"); 1668 break; 1669 1670 case eNameMatchStartsWith: 1671 packet.PutCString ("name_match:starts_with;"); 1672 break; 1673 1674 case eNameMatchEndsWith: 1675 packet.PutCString ("name_match:ends_with;"); 1676 break; 1677 1678 case eNameMatchRegularExpression: 1679 packet.PutCString ("name_match:regex;"); 1680 break; 1681 } 1682 if (has_name_match) 1683 { 1684 packet.PutCString ("name:"); 1685 packet.PutBytesAsRawHex8(name, ::strlen(name)); 1686 packet.PutChar (';'); 1687 } 1688 } 1689 1690 if (match_info.GetProcessInfo().ProcessIDIsValid()) 1691 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID()); 1692 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 1693 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID()); 1694 if (match_info.GetProcessInfo().UserIDIsValid()) 1695 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 1696 if (match_info.GetProcessInfo().GroupIDIsValid()) 1697 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 1698 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 1699 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 1700 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 1701 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 1702 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 1703 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 1704 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 1705 { 1706 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 1707 const llvm::Triple &triple = match_arch.GetTriple(); 1708 packet.PutCString("triple:"); 1709 packet.PutCStringAsRawHex8(triple.getTriple().c_str()); 1710 packet.PutChar (';'); 1711 } 1712 } 1713 StringExtractorGDBRemote response; 1714 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false)) 1715 { 1716 do 1717 { 1718 ProcessInstanceInfo process_info; 1719 if (!DecodeProcessInfoResponse (response, process_info)) 1720 break; 1721 process_infos.Append(process_info); 1722 response.GetStringRef().clear(); 1723 response.SetFilePos(0); 1724 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false)); 1725 } 1726 else 1727 { 1728 m_supports_qfProcessInfo = false; 1729 return 0; 1730 } 1731 } 1732 return process_infos.GetSize(); 1733 1734 } 1735 1736 bool 1737 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 1738 { 1739 if (m_supports_qUserName) 1740 { 1741 char packet[32]; 1742 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 1743 assert (packet_len < sizeof(packet)); 1744 StringExtractorGDBRemote response; 1745 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1746 { 1747 if (response.IsNormalResponse()) 1748 { 1749 // Make sure we parsed the right number of characters. The response is 1750 // the hex encoded user name and should make up the entire packet. 1751 // If there are any non-hex ASCII bytes, the length won't match below.. 1752 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 1753 return true; 1754 } 1755 } 1756 else 1757 { 1758 m_supports_qUserName = false; 1759 return false; 1760 } 1761 } 1762 return false; 1763 1764 } 1765 1766 bool 1767 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 1768 { 1769 if (m_supports_qGroupName) 1770 { 1771 char packet[32]; 1772 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 1773 assert (packet_len < sizeof(packet)); 1774 StringExtractorGDBRemote response; 1775 if (SendPacketAndWaitForResponse (packet, packet_len, response, false)) 1776 { 1777 if (response.IsNormalResponse()) 1778 { 1779 // Make sure we parsed the right number of characters. The response is 1780 // the hex encoded group name and should make up the entire packet. 1781 // If there are any non-hex ASCII bytes, the length won't match below.. 1782 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 1783 return true; 1784 } 1785 } 1786 else 1787 { 1788 m_supports_qGroupName = false; 1789 return false; 1790 } 1791 } 1792 return false; 1793 } 1794 1795 void 1796 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets) 1797 { 1798 uint32_t i; 1799 TimeValue start_time, end_time; 1800 uint64_t total_time_nsec; 1801 float packets_per_second; 1802 if (SendSpeedTestPacket (0, 0)) 1803 { 1804 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2) 1805 { 1806 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2) 1807 { 1808 start_time = TimeValue::Now(); 1809 for (i=0; i<num_packets; ++i) 1810 { 1811 SendSpeedTestPacket (send_size, recv_size); 1812 } 1813 end_time = TimeValue::Now(); 1814 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 1815 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 1816 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n", 1817 num_packets, 1818 send_size, 1819 recv_size, 1820 total_time_nsec / TimeValue::NanoSecPerSec, 1821 total_time_nsec % TimeValue::NanoSecPerSec, 1822 packets_per_second); 1823 if (recv_size == 0) 1824 recv_size = 32; 1825 } 1826 if (send_size == 0) 1827 send_size = 32; 1828 } 1829 } 1830 else 1831 { 1832 start_time = TimeValue::Now(); 1833 for (i=0; i<num_packets; ++i) 1834 { 1835 GetCurrentProcessID (); 1836 } 1837 end_time = TimeValue::Now(); 1838 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 1839 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 1840 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n", 1841 num_packets, 1842 total_time_nsec / TimeValue::NanoSecPerSec, 1843 total_time_nsec % TimeValue::NanoSecPerSec, 1844 packets_per_second); 1845 } 1846 } 1847 1848 bool 1849 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 1850 { 1851 StreamString packet; 1852 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 1853 uint32_t bytes_left = send_size; 1854 while (bytes_left > 0) 1855 { 1856 if (bytes_left >= 26) 1857 { 1858 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 1859 bytes_left -= 26; 1860 } 1861 else 1862 { 1863 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 1864 bytes_left = 0; 1865 } 1866 } 1867 1868 StringExtractorGDBRemote response; 1869 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0; 1870 return false; 1871 } 1872 1873 uint16_t 1874 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort () 1875 { 1876 StringExtractorGDBRemote response; 1877 if (SendPacketAndWaitForResponse("qLaunchGDBServer", strlen("qLaunchGDBServer"), response, false)) 1878 { 1879 std::string name; 1880 std::string value; 1881 uint16_t port = 0; 1882 //lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1883 while (response.GetNameColonValue(name, value)) 1884 { 1885 if (name.size() == 4 && name.compare("port") == 0) 1886 port = Args::StringToUInt32(value.c_str(), 0, 0); 1887 // if (name.size() == 3 && name.compare("pid") == 0) 1888 // pid = Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 1889 } 1890 return port; 1891 } 1892 return 0; 1893 } 1894 1895 bool 1896 GDBRemoteCommunicationClient::SetCurrentThread (int tid) 1897 { 1898 if (m_curr_tid == tid) 1899 return true; 1900 1901 char packet[32]; 1902 int packet_len; 1903 if (tid <= 0) 1904 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid); 1905 else 1906 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 1907 assert (packet_len + 1 < sizeof(packet)); 1908 StringExtractorGDBRemote response; 1909 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1910 { 1911 if (response.IsOKResponse()) 1912 { 1913 m_curr_tid = tid; 1914 return true; 1915 } 1916 } 1917 return false; 1918 } 1919 1920 bool 1921 GDBRemoteCommunicationClient::SetCurrentThreadForRun (int tid) 1922 { 1923 if (m_curr_tid_run == tid) 1924 return true; 1925 1926 char packet[32]; 1927 int packet_len; 1928 if (tid <= 0) 1929 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid); 1930 else 1931 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid); 1932 1933 assert (packet_len + 1 < sizeof(packet)); 1934 StringExtractorGDBRemote response; 1935 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1936 { 1937 if (response.IsOKResponse()) 1938 { 1939 m_curr_tid_run = tid; 1940 return true; 1941 } 1942 } 1943 return false; 1944 } 1945 1946 bool 1947 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 1948 { 1949 if (SendPacketAndWaitForResponse("?", 1, response, false)) 1950 return response.IsNormalResponse(); 1951 return false; 1952 } 1953 1954 bool 1955 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response) 1956 { 1957 if (m_supports_qThreadStopInfo) 1958 { 1959 char packet[256]; 1960 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 1961 assert (packet_len < sizeof(packet)); 1962 if (SendPacketAndWaitForResponse(packet, packet_len, response, false)) 1963 { 1964 if (response.IsNormalResponse()) 1965 return true; 1966 else 1967 return false; 1968 } 1969 else 1970 { 1971 m_supports_qThreadStopInfo = false; 1972 } 1973 } 1974 // if (SetCurrentThread (tid)) 1975 // return GetStopReply (response); 1976 return false; 1977 } 1978 1979 1980 uint8_t 1981 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 1982 { 1983 switch (type) 1984 { 1985 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break; 1986 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break; 1987 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break; 1988 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break; 1989 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break; 1990 } 1991 1992 char packet[64]; 1993 const int packet_len = ::snprintf (packet, 1994 sizeof(packet), 1995 "%c%i,%" PRIx64 ",%x", 1996 insert ? 'Z' : 'z', 1997 type, 1998 addr, 1999 length); 2000 2001 assert (packet_len + 1 < sizeof(packet)); 2002 StringExtractorGDBRemote response; 2003 if (SendPacketAndWaitForResponse(packet, packet_len, response, true)) 2004 { 2005 if (response.IsOKResponse()) 2006 return 0; 2007 else if (response.IsErrorResponse()) 2008 return response.GetError(); 2009 } 2010 else 2011 { 2012 switch (type) 2013 { 2014 case eBreakpointSoftware: m_supports_z0 = false; break; 2015 case eBreakpointHardware: m_supports_z1 = false; break; 2016 case eWatchpointWrite: m_supports_z2 = false; break; 2017 case eWatchpointRead: m_supports_z3 = false; break; 2018 case eWatchpointReadWrite: m_supports_z4 = false; break; 2019 } 2020 } 2021 2022 return UINT8_MAX; 2023 } 2024 2025 size_t 2026 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 2027 bool &sequence_mutex_unavailable) 2028 { 2029 Mutex::Locker locker; 2030 thread_ids.clear(); 2031 2032 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 2033 { 2034 sequence_mutex_unavailable = false; 2035 StringExtractorGDBRemote response; 2036 2037 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()); 2038 response.IsNormalResponse(); 2039 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ())) 2040 { 2041 char ch = response.GetChar(); 2042 if (ch == 'l') 2043 break; 2044 if (ch == 'm') 2045 { 2046 do 2047 { 2048 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 2049 2050 if (tid != LLDB_INVALID_THREAD_ID) 2051 { 2052 thread_ids.push_back (tid); 2053 } 2054 ch = response.GetChar(); // Skip the command separator 2055 } while (ch == ','); // Make sure we got a comma separator 2056 } 2057 } 2058 } 2059 else 2060 { 2061 #if defined (LLDB_CONFIGURATION_DEBUG) 2062 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 2063 #else 2064 LogSP log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2065 if (log) 2066 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 2067 #endif 2068 sequence_mutex_unavailable = true; 2069 } 2070 return thread_ids.size(); 2071 } 2072 2073 lldb::addr_t 2074 GDBRemoteCommunicationClient::GetShlibInfoAddr() 2075 { 2076 if (!IsRunning()) 2077 { 2078 StringExtractorGDBRemote response; 2079 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false)) 2080 { 2081 if (response.IsNormalResponse()) 2082 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2083 } 2084 } 2085 return LLDB_INVALID_ADDRESS; 2086 } 2087 2088