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 #include <sys/stat.h> 15 16 // C++ Includes 17 #include <sstream> 18 19 // Other libraries and framework includes 20 #include "llvm/ADT/Triple.h" 21 #include "lldb/Interpreter/Args.h" 22 #include "lldb/Core/ConnectionFileDescriptor.h" 23 #include "lldb/Core/Log.h" 24 #include "lldb/Core/State.h" 25 #include "lldb/Core/StreamGDBRemote.h" 26 #include "lldb/Core/StreamString.h" 27 #include "lldb/Host/Endian.h" 28 #include "lldb/Host/Host.h" 29 #include "lldb/Host/TimeValue.h" 30 31 // Project includes 32 #include "Utility/StringExtractorGDBRemote.h" 33 #include "ProcessGDBRemote.h" 34 #include "ProcessGDBRemoteLog.h" 35 #include "lldb/Host/Config.h" 36 37 using namespace lldb; 38 using namespace lldb_private; 39 40 #ifdef LLDB_DISABLE_POSIX 41 #define SIGSTOP 17 42 #endif 43 44 //---------------------------------------------------------------------- 45 // GDBRemoteCommunicationClient constructor 46 //---------------------------------------------------------------------- 47 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) : 48 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform), 49 m_supports_not_sending_acks (eLazyBoolCalculate), 50 m_supports_thread_suffix (eLazyBoolCalculate), 51 m_supports_threads_in_stop_reply (eLazyBoolCalculate), 52 m_supports_vCont_all (eLazyBoolCalculate), 53 m_supports_vCont_any (eLazyBoolCalculate), 54 m_supports_vCont_c (eLazyBoolCalculate), 55 m_supports_vCont_C (eLazyBoolCalculate), 56 m_supports_vCont_s (eLazyBoolCalculate), 57 m_supports_vCont_S (eLazyBoolCalculate), 58 m_qHostInfo_is_valid (eLazyBoolCalculate), 59 m_qProcessInfo_is_valid (eLazyBoolCalculate), 60 m_supports_alloc_dealloc_memory (eLazyBoolCalculate), 61 m_supports_memory_region_info (eLazyBoolCalculate), 62 m_supports_watchpoint_support_info (eLazyBoolCalculate), 63 m_supports_detach_stay_stopped (eLazyBoolCalculate), 64 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate), 65 m_attach_or_wait_reply(eLazyBoolCalculate), 66 m_prepare_for_reg_writing_reply (eLazyBoolCalculate), 67 m_supports_p (eLazyBoolCalculate), 68 m_supports_QSaveRegisterState (eLazyBoolCalculate), 69 m_supports_qProcessInfoPID (true), 70 m_supports_qfProcessInfo (true), 71 m_supports_qUserName (true), 72 m_supports_qGroupName (true), 73 m_supports_qThreadStopInfo (true), 74 m_supports_z0 (true), 75 m_supports_z1 (true), 76 m_supports_z2 (true), 77 m_supports_z3 (true), 78 m_supports_z4 (true), 79 m_supports_QEnvironment (true), 80 m_supports_QEnvironmentHexEncoded (true), 81 m_curr_tid (LLDB_INVALID_THREAD_ID), 82 m_curr_tid_run (LLDB_INVALID_THREAD_ID), 83 m_num_supported_hardware_watchpoints (0), 84 m_async_mutex (Mutex::eMutexTypeRecursive), 85 m_async_packet_predicate (false), 86 m_async_packet (), 87 m_async_result (PacketResult::Success), 88 m_async_response (), 89 m_async_signal (-1), 90 m_thread_id_to_used_usec_map (), 91 m_host_arch(), 92 m_process_arch(), 93 m_os_version_major (UINT32_MAX), 94 m_os_version_minor (UINT32_MAX), 95 m_os_version_update (UINT32_MAX), 96 m_os_build (), 97 m_os_kernel (), 98 m_hostname (), 99 m_default_packet_timeout (0) 100 { 101 } 102 103 //---------------------------------------------------------------------- 104 // Destructor 105 //---------------------------------------------------------------------- 106 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() 107 { 108 if (IsConnected()) 109 Disconnect(); 110 } 111 112 bool 113 GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr) 114 { 115 ResetDiscoverableSettings(); 116 117 // Start the read thread after we send the handshake ack since if we 118 // fail to send the handshake ack, there is no reason to continue... 119 if (SendAck()) 120 { 121 // Wait for any responses that might have been queued up in the remote 122 // GDB server and flush them all 123 StringExtractorGDBRemote response; 124 PacketResult packet_result = PacketResult::Success; 125 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response 126 while (packet_result == PacketResult::Success) 127 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec); 128 129 // The return value from QueryNoAckModeSupported() is true if the packet 130 // was sent and _any_ response (including UNIMPLEMENTED) was received), 131 // or false if no response was received. This quickly tells us if we have 132 // a live connection to a remote GDB server... 133 if (QueryNoAckModeSupported()) 134 { 135 return true; 136 } 137 else 138 { 139 if (error_ptr) 140 error_ptr->SetErrorString("failed to get reply to handshake packet"); 141 } 142 } 143 else 144 { 145 if (error_ptr) 146 error_ptr->SetErrorString("failed to send the handshake ack"); 147 } 148 return false; 149 } 150 151 bool 152 GDBRemoteCommunicationClient::QueryNoAckModeSupported () 153 { 154 if (m_supports_not_sending_acks == eLazyBoolCalculate) 155 { 156 m_send_acks = true; 157 m_supports_not_sending_acks = eLazyBoolNo; 158 159 StringExtractorGDBRemote response; 160 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success) 161 { 162 if (response.IsOKResponse()) 163 { 164 m_send_acks = false; 165 m_supports_not_sending_acks = eLazyBoolYes; 166 } 167 return true; 168 } 169 } 170 return false; 171 } 172 173 void 174 GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported () 175 { 176 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) 177 { 178 m_supports_threads_in_stop_reply = eLazyBoolNo; 179 180 StringExtractorGDBRemote response; 181 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success) 182 { 183 if (response.IsOKResponse()) 184 m_supports_threads_in_stop_reply = eLazyBoolYes; 185 } 186 } 187 } 188 189 bool 190 GDBRemoteCommunicationClient::GetVAttachOrWaitSupported () 191 { 192 if (m_attach_or_wait_reply == eLazyBoolCalculate) 193 { 194 m_attach_or_wait_reply = eLazyBoolNo; 195 196 StringExtractorGDBRemote response; 197 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success) 198 { 199 if (response.IsOKResponse()) 200 m_attach_or_wait_reply = eLazyBoolYes; 201 } 202 } 203 if (m_attach_or_wait_reply == eLazyBoolYes) 204 return true; 205 else 206 return false; 207 } 208 209 bool 210 GDBRemoteCommunicationClient::GetSyncThreadStateSupported () 211 { 212 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) 213 { 214 m_prepare_for_reg_writing_reply = eLazyBoolNo; 215 216 StringExtractorGDBRemote response; 217 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success) 218 { 219 if (response.IsOKResponse()) 220 m_prepare_for_reg_writing_reply = eLazyBoolYes; 221 } 222 } 223 if (m_prepare_for_reg_writing_reply == eLazyBoolYes) 224 return true; 225 else 226 return false; 227 } 228 229 230 void 231 GDBRemoteCommunicationClient::ResetDiscoverableSettings() 232 { 233 m_supports_not_sending_acks = eLazyBoolCalculate; 234 m_supports_thread_suffix = eLazyBoolCalculate; 235 m_supports_threads_in_stop_reply = eLazyBoolCalculate; 236 m_supports_vCont_c = eLazyBoolCalculate; 237 m_supports_vCont_C = eLazyBoolCalculate; 238 m_supports_vCont_s = eLazyBoolCalculate; 239 m_supports_vCont_S = eLazyBoolCalculate; 240 m_supports_p = eLazyBoolCalculate; 241 m_supports_QSaveRegisterState = eLazyBoolCalculate; 242 m_qHostInfo_is_valid = eLazyBoolCalculate; 243 m_qProcessInfo_is_valid = eLazyBoolCalculate; 244 m_supports_alloc_dealloc_memory = eLazyBoolCalculate; 245 m_supports_memory_region_info = eLazyBoolCalculate; 246 m_prepare_for_reg_writing_reply = eLazyBoolCalculate; 247 m_attach_or_wait_reply = eLazyBoolCalculate; 248 249 m_supports_qProcessInfoPID = true; 250 m_supports_qfProcessInfo = true; 251 m_supports_qUserName = true; 252 m_supports_qGroupName = true; 253 m_supports_qThreadStopInfo = true; 254 m_supports_z0 = true; 255 m_supports_z1 = true; 256 m_supports_z2 = true; 257 m_supports_z3 = true; 258 m_supports_z4 = true; 259 m_supports_QEnvironment = true; 260 m_supports_QEnvironmentHexEncoded = true; 261 m_host_arch.Clear(); 262 m_process_arch.Clear(); 263 } 264 265 266 bool 267 GDBRemoteCommunicationClient::GetThreadSuffixSupported () 268 { 269 if (m_supports_thread_suffix == eLazyBoolCalculate) 270 { 271 StringExtractorGDBRemote response; 272 m_supports_thread_suffix = eLazyBoolNo; 273 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success) 274 { 275 if (response.IsOKResponse()) 276 m_supports_thread_suffix = eLazyBoolYes; 277 } 278 } 279 return m_supports_thread_suffix; 280 } 281 bool 282 GDBRemoteCommunicationClient::GetVContSupported (char flavor) 283 { 284 if (m_supports_vCont_c == eLazyBoolCalculate) 285 { 286 StringExtractorGDBRemote response; 287 m_supports_vCont_any = eLazyBoolNo; 288 m_supports_vCont_all = eLazyBoolNo; 289 m_supports_vCont_c = eLazyBoolNo; 290 m_supports_vCont_C = eLazyBoolNo; 291 m_supports_vCont_s = eLazyBoolNo; 292 m_supports_vCont_S = eLazyBoolNo; 293 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success) 294 { 295 const char *response_cstr = response.GetStringRef().c_str(); 296 if (::strstr (response_cstr, ";c")) 297 m_supports_vCont_c = eLazyBoolYes; 298 299 if (::strstr (response_cstr, ";C")) 300 m_supports_vCont_C = eLazyBoolYes; 301 302 if (::strstr (response_cstr, ";s")) 303 m_supports_vCont_s = eLazyBoolYes; 304 305 if (::strstr (response_cstr, ";S")) 306 m_supports_vCont_S = eLazyBoolYes; 307 308 if (m_supports_vCont_c == eLazyBoolYes && 309 m_supports_vCont_C == eLazyBoolYes && 310 m_supports_vCont_s == eLazyBoolYes && 311 m_supports_vCont_S == eLazyBoolYes) 312 { 313 m_supports_vCont_all = eLazyBoolYes; 314 } 315 316 if (m_supports_vCont_c == eLazyBoolYes || 317 m_supports_vCont_C == eLazyBoolYes || 318 m_supports_vCont_s == eLazyBoolYes || 319 m_supports_vCont_S == eLazyBoolYes) 320 { 321 m_supports_vCont_any = eLazyBoolYes; 322 } 323 } 324 } 325 326 switch (flavor) 327 { 328 case 'a': return m_supports_vCont_any; 329 case 'A': return m_supports_vCont_all; 330 case 'c': return m_supports_vCont_c; 331 case 'C': return m_supports_vCont_C; 332 case 's': return m_supports_vCont_s; 333 case 'S': return m_supports_vCont_S; 334 default: break; 335 } 336 return false; 337 } 338 339 // Check if the target supports 'p' packet. It sends out a 'p' 340 // packet and checks the response. A normal packet will tell us 341 // that support is available. 342 // 343 // Takes a valid thread ID because p needs to apply to a thread. 344 bool 345 GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid) 346 { 347 if (m_supports_p == eLazyBoolCalculate) 348 { 349 StringExtractorGDBRemote response; 350 m_supports_p = eLazyBoolNo; 351 char packet[256]; 352 if (GetThreadSuffixSupported()) 353 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid); 354 else 355 snprintf(packet, sizeof(packet), "p0"); 356 357 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 358 { 359 if (response.IsNormalResponse()) 360 m_supports_p = eLazyBoolYes; 361 } 362 } 363 return m_supports_p; 364 } 365 366 GDBRemoteCommunicationClient::PacketResult 367 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse 368 ( 369 const char *payload, 370 StringExtractorGDBRemote &response, 371 bool send_async 372 ) 373 { 374 return SendPacketAndWaitForResponse (payload, 375 ::strlen (payload), 376 response, 377 send_async); 378 } 379 380 GDBRemoteCommunicationClient::PacketResult 381 GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload, 382 size_t payload_length, 383 StringExtractorGDBRemote &response) 384 { 385 PacketResult packet_result = SendPacketNoLock (payload, payload_length); 386 if (packet_result == PacketResult::Success) 387 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()); 388 return packet_result; 389 } 390 391 GDBRemoteCommunicationClient::PacketResult 392 GDBRemoteCommunicationClient::SendPacketAndWaitForResponse 393 ( 394 const char *payload, 395 size_t payload_length, 396 StringExtractorGDBRemote &response, 397 bool send_async 398 ) 399 { 400 PacketResult packet_result = PacketResult::ErrorSendFailed; 401 Mutex::Locker locker; 402 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 403 size_t response_len = 0; 404 if (GetSequenceMutex (locker)) 405 { 406 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response); 407 } 408 else 409 { 410 if (send_async) 411 { 412 if (IsRunning()) 413 { 414 Mutex::Locker async_locker (m_async_mutex); 415 m_async_packet.assign(payload, payload_length); 416 m_async_packet_predicate.SetValue (true, eBroadcastNever); 417 418 if (log) 419 log->Printf ("async: async packet = %s", m_async_packet.c_str()); 420 421 bool timed_out = false; 422 if (SendInterrupt(locker, 2, timed_out)) 423 { 424 if (m_interrupt_sent) 425 { 426 m_interrupt_sent = false; 427 TimeValue timeout_time; 428 timeout_time = TimeValue::Now(); 429 timeout_time.OffsetWithSeconds (m_packet_timeout); 430 431 if (log) 432 log->Printf ("async: sent interrupt"); 433 434 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out)) 435 { 436 if (log) 437 log->Printf ("async: got response"); 438 439 // Swap the response buffer to avoid malloc and string copy 440 response.GetStringRef().swap (m_async_response.GetStringRef()); 441 response_len = response.GetStringRef().size(); 442 packet_result = m_async_result; 443 } 444 else 445 { 446 if (log) 447 log->Printf ("async: timed out waiting for response"); 448 } 449 450 // Make sure we wait until the continue packet has been sent again... 451 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out)) 452 { 453 if (log) 454 { 455 if (timed_out) 456 log->Printf ("async: timed out waiting for process to resume, but process was resumed"); 457 else 458 log->Printf ("async: async packet sent"); 459 } 460 } 461 else 462 { 463 if (log) 464 log->Printf ("async: timed out waiting for process to resume"); 465 } 466 } 467 else 468 { 469 // We had a racy condition where we went to send the interrupt 470 // yet we were able to get the lock, so the process must have 471 // just stopped? 472 if (log) 473 log->Printf ("async: got lock without sending interrupt"); 474 // Send the packet normally since we got the lock 475 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response); 476 } 477 } 478 else 479 { 480 if (log) 481 log->Printf ("async: failed to interrupt"); 482 } 483 } 484 else 485 { 486 if (log) 487 log->Printf ("async: not running, async is ignored"); 488 } 489 } 490 else 491 { 492 if (log) 493 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload); 494 } 495 } 496 return packet_result; 497 } 498 499 static const char *end_delimiter = "--end--;"; 500 static const int end_delimiter_len = 8; 501 502 std::string 503 GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData 504 ( ProcessGDBRemote *process, 505 StringExtractorGDBRemote& profileDataExtractor 506 ) 507 { 508 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 509 std::stringstream final_output; 510 std::string name, value; 511 512 // Going to assuming thread_used_usec comes first, else bail out. 513 while (profileDataExtractor.GetNameColonValue(name, value)) 514 { 515 if (name.compare("thread_used_id") == 0) 516 { 517 StringExtractor threadIDHexExtractor(value.c_str()); 518 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 519 520 bool has_used_usec = false; 521 uint32_t curr_used_usec = 0; 522 std::string usec_name, usec_value; 523 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 524 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) 525 { 526 if (usec_name.compare("thread_used_usec") == 0) 527 { 528 has_used_usec = true; 529 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0); 530 } 531 else 532 { 533 // We didn't find what we want, it is probably 534 // an older version. Bail out. 535 profileDataExtractor.SetFilePos(input_file_pos); 536 } 537 } 538 539 if (has_used_usec) 540 { 541 uint32_t prev_used_usec = 0; 542 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id); 543 if (iterator != m_thread_id_to_used_usec_map.end()) 544 { 545 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 546 } 547 548 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 549 // A good first time record is one that runs for at least 0.25 sec 550 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000); 551 bool good_subsequent_time = (prev_used_usec > 0) && 552 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id))); 553 554 if (good_first_time || good_subsequent_time) 555 { 556 // We try to avoid doing too many index id reservation, 557 // resulting in fast increase of index ids. 558 559 final_output << name << ":"; 560 int32_t index_id = process->AssignIndexIDToThread(thread_id); 561 final_output << index_id << ";"; 562 563 final_output << usec_name << ":" << usec_value << ";"; 564 } 565 else 566 { 567 // Skip past 'thread_used_name'. 568 std::string local_name, local_value; 569 profileDataExtractor.GetNameColonValue(local_name, local_value); 570 } 571 572 // Store current time as previous time so that they can be compared later. 573 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 574 } 575 else 576 { 577 // Bail out and use old string. 578 final_output << name << ":" << value << ";"; 579 } 580 } 581 else 582 { 583 final_output << name << ":" << value << ";"; 584 } 585 } 586 final_output << end_delimiter; 587 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 588 589 return final_output.str(); 590 } 591 592 StateType 593 GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse 594 ( 595 ProcessGDBRemote *process, 596 const char *payload, 597 size_t packet_length, 598 StringExtractorGDBRemote &response 599 ) 600 { 601 m_curr_tid = LLDB_INVALID_THREAD_ID; 602 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 603 if (log) 604 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__); 605 606 Mutex::Locker locker(m_sequence_mutex); 607 StateType state = eStateRunning; 608 609 BroadcastEvent(eBroadcastBitRunPacketSent, NULL); 610 m_public_is_running.SetValue (true, eBroadcastNever); 611 // Set the starting continue packet into "continue_packet". This packet 612 // may change if we are interrupted and we continue after an async packet... 613 std::string continue_packet(payload, packet_length); 614 615 bool got_async_packet = false; 616 617 while (state == eStateRunning) 618 { 619 if (!got_async_packet) 620 { 621 if (log) 622 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str()); 623 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success) 624 state = eStateInvalid; 625 626 m_private_is_running.SetValue (true, eBroadcastAlways); 627 } 628 629 got_async_packet = false; 630 631 if (log) 632 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str()); 633 634 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success) 635 { 636 if (response.Empty()) 637 state = eStateInvalid; 638 else 639 { 640 const char stop_type = response.GetChar(); 641 if (log) 642 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str()); 643 switch (stop_type) 644 { 645 case 'T': 646 case 'S': 647 { 648 if (process->GetStopID() == 0) 649 { 650 if (process->GetID() == LLDB_INVALID_PROCESS_ID) 651 { 652 lldb::pid_t pid = GetCurrentProcessID (); 653 if (pid != LLDB_INVALID_PROCESS_ID) 654 process->SetID (pid); 655 } 656 process->BuildDynamicRegisterInfo (true); 657 } 658 659 // Privately notify any internal threads that we have stopped 660 // in case we wanted to interrupt our process, yet we might 661 // send a packet and continue without returning control to the 662 // user. 663 m_private_is_running.SetValue (false, eBroadcastAlways); 664 665 const uint8_t signo = response.GetHexU8 (UINT8_MAX); 666 667 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue(); 668 if (continue_after_async || m_interrupt_sent) 669 { 670 // We sent an interrupt packet to stop the inferior process 671 // for an async signal or to send an async packet while running 672 // but we might have been single stepping and received the 673 // stop packet for the step instead of for the interrupt packet. 674 // Typically when an interrupt is sent a SIGINT or SIGSTOP 675 // is used, so if we get anything else, we need to try and 676 // get another stop reply packet that may have been sent 677 // due to sending the interrupt when the target is stopped 678 // which will just re-send a copy of the last stop reply 679 // packet. If we don't do this, then the reply for our 680 // async packet will be the repeat stop reply packet and cause 681 // a lot of trouble for us! 682 if (signo != SIGINT && signo != SIGSTOP) 683 { 684 continue_after_async = false; 685 686 // We didn't get a a SIGINT or SIGSTOP, so try for a 687 // very brief time (1 ms) to get another stop reply 688 // packet to make sure it doesn't get in the way 689 StringExtractorGDBRemote extra_stop_reply_packet; 690 uint32_t timeout_usec = 1000; 691 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success) 692 { 693 switch (extra_stop_reply_packet.GetChar()) 694 { 695 case 'T': 696 case 'S': 697 // We did get an extra stop reply, which means 698 // our interrupt didn't stop the target so we 699 // shouldn't continue after the async signal 700 // or packet is sent... 701 continue_after_async = false; 702 break; 703 } 704 } 705 } 706 } 707 708 if (m_async_signal != -1) 709 { 710 if (log) 711 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal)); 712 713 // Save off the async signal we are supposed to send 714 const int async_signal = m_async_signal; 715 // Clear the async signal member so we don't end up 716 // sending the signal multiple times... 717 m_async_signal = -1; 718 // Check which signal we stopped with 719 if (signo == async_signal) 720 { 721 if (log) 722 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo)); 723 724 // We already stopped with a signal that we wanted 725 // to stop with, so we are done 726 } 727 else 728 { 729 // We stopped with a different signal that the one 730 // we wanted to stop with, so now we must resume 731 // with the signal we want 732 char signal_packet[32]; 733 int signal_packet_len = 0; 734 signal_packet_len = ::snprintf (signal_packet, 735 sizeof (signal_packet), 736 "C%2.2x", 737 async_signal); 738 739 if (log) 740 log->Printf ("async: stopped with signal %s, resume with %s", 741 Host::GetSignalAsCString (signo), 742 Host::GetSignalAsCString (async_signal)); 743 744 // Set the continue packet to resume even if the 745 // interrupt didn't cause our stop (ignore continue_after_async) 746 continue_packet.assign(signal_packet, signal_packet_len); 747 continue; 748 } 749 } 750 else if (m_async_packet_predicate.GetValue()) 751 { 752 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS)); 753 754 // We are supposed to send an asynchronous packet while 755 // we are running. 756 m_async_response.Clear(); 757 if (m_async_packet.empty()) 758 { 759 m_async_result = PacketResult::ErrorSendFailed; 760 if (packet_log) 761 packet_log->Printf ("async: error: empty async packet"); 762 763 } 764 else 765 { 766 if (packet_log) 767 packet_log->Printf ("async: sending packet"); 768 769 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0], 770 m_async_packet.size(), 771 m_async_response, 772 false); 773 } 774 // Let the other thread that was trying to send the async 775 // packet know that the packet has been sent and response is 776 // ready... 777 m_async_packet_predicate.SetValue(false, eBroadcastAlways); 778 779 if (packet_log) 780 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async); 781 782 // Set the continue packet to resume if our interrupt 783 // for the async packet did cause the stop 784 if (continue_after_async) 785 { 786 // Reverting this for now as it is causing deadlocks 787 // in programs (<rdar://problem/11529853>). In the future 788 // we should check our thread list and "do the right thing" 789 // for new threads that show up while we stop and run async 790 // packets. Setting the packet to 'c' to continue all threads 791 // is the right thing to do 99.99% of the time because if a 792 // thread was single stepping, and we sent an interrupt, we 793 // will notice above that we didn't stop due to an interrupt 794 // but stopped due to stepping and we would _not_ continue. 795 continue_packet.assign (1, 'c'); 796 continue; 797 } 798 } 799 // Stop with signal and thread info 800 state = eStateStopped; 801 } 802 break; 803 804 case 'W': 805 case 'X': 806 // process exited 807 state = eStateExited; 808 break; 809 810 case 'O': 811 // STDOUT 812 { 813 got_async_packet = true; 814 std::string inferior_stdout; 815 inferior_stdout.reserve(response.GetBytesLeft () / 2); 816 char ch; 817 while ((ch = response.GetHexU8()) != '\0') 818 inferior_stdout.append(1, ch); 819 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size()); 820 } 821 break; 822 823 case 'A': 824 // Async miscellaneous reply. Right now, only profile data is coming through this channel. 825 { 826 got_async_packet = true; 827 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A' 828 if (m_partial_profile_data.length() > 0) 829 { 830 m_partial_profile_data.append(input); 831 input = m_partial_profile_data; 832 m_partial_profile_data.clear(); 833 } 834 835 size_t found, pos = 0, len = input.length(); 836 while ((found = input.find(end_delimiter, pos)) != std::string::npos) 837 { 838 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str()); 839 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor); 840 process->BroadcastAsyncProfileData (profile_data); 841 842 pos = found + end_delimiter_len; 843 } 844 845 if (pos < len) 846 { 847 // Last incomplete chunk. 848 m_partial_profile_data = input.substr(pos); 849 } 850 } 851 break; 852 853 case 'E': 854 // ERROR 855 state = eStateInvalid; 856 break; 857 858 default: 859 if (log) 860 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__); 861 state = eStateInvalid; 862 break; 863 } 864 } 865 } 866 else 867 { 868 if (log) 869 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__); 870 state = eStateInvalid; 871 } 872 } 873 if (log) 874 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state)); 875 response.SetFilePos(0); 876 m_private_is_running.SetValue (false, eBroadcastAlways); 877 m_public_is_running.SetValue (false, eBroadcastAlways); 878 return state; 879 } 880 881 bool 882 GDBRemoteCommunicationClient::SendAsyncSignal (int signo) 883 { 884 Mutex::Locker async_locker (m_async_mutex); 885 m_async_signal = signo; 886 bool timed_out = false; 887 Mutex::Locker locker; 888 if (SendInterrupt (locker, 1, timed_out)) 889 return true; 890 m_async_signal = -1; 891 return false; 892 } 893 894 // This function takes a mutex locker as a parameter in case the GetSequenceMutex 895 // actually succeeds. If it doesn't succeed in acquiring the sequence mutex 896 // (the expected result), then it will send the halt packet. If it does succeed 897 // then the caller that requested the interrupt will want to keep the sequence 898 // locked down so that no one else can send packets while the caller has control. 899 // This function usually gets called when we are running and need to stop the 900 // target. It can also be used when we are running and and we need to do something 901 // else (like read/write memory), so we need to interrupt the running process 902 // (gdb remote protocol requires this), and do what we need to do, then resume. 903 904 bool 905 GDBRemoteCommunicationClient::SendInterrupt 906 ( 907 Mutex::Locker& locker, 908 uint32_t seconds_to_wait_for_stop, 909 bool &timed_out 910 ) 911 { 912 timed_out = false; 913 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 914 915 if (IsRunning()) 916 { 917 // Only send an interrupt if our debugserver is running... 918 if (GetSequenceMutex (locker)) 919 { 920 if (log) 921 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt"); 922 } 923 else 924 { 925 // Someone has the mutex locked waiting for a response or for the 926 // inferior to stop, so send the interrupt on the down low... 927 char ctrl_c = '\x03'; 928 ConnectionStatus status = eConnectionStatusSuccess; 929 size_t bytes_written = Write (&ctrl_c, 1, status, NULL); 930 if (log) 931 log->PutCString("send packet: \\x03"); 932 if (bytes_written > 0) 933 { 934 m_interrupt_sent = true; 935 if (seconds_to_wait_for_stop) 936 { 937 TimeValue timeout; 938 if (seconds_to_wait_for_stop) 939 { 940 timeout = TimeValue::Now(); 941 timeout.OffsetWithSeconds (seconds_to_wait_for_stop); 942 } 943 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out)) 944 { 945 if (log) 946 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped"); 947 return true; 948 } 949 else 950 { 951 if (log) 952 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume"); 953 } 954 } 955 else 956 { 957 if (log) 958 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop..."); 959 return true; 960 } 961 } 962 else 963 { 964 if (log) 965 log->Printf ("SendInterrupt () - failed to write interrupt"); 966 } 967 return false; 968 } 969 } 970 else 971 { 972 if (log) 973 log->Printf ("SendInterrupt () - not running"); 974 } 975 return true; 976 } 977 978 lldb::pid_t 979 GDBRemoteCommunicationClient::GetCurrentProcessID () 980 { 981 StringExtractorGDBRemote response; 982 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success) 983 { 984 if (response.GetChar() == 'Q') 985 if (response.GetChar() == 'C') 986 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID); 987 } 988 return LLDB_INVALID_PROCESS_ID; 989 } 990 991 bool 992 GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str) 993 { 994 error_str.clear(); 995 StringExtractorGDBRemote response; 996 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success) 997 { 998 if (response.IsOKResponse()) 999 return true; 1000 if (response.GetChar() == 'E') 1001 { 1002 // A string the describes what failed when launching... 1003 error_str = response.GetStringRef().substr(1); 1004 } 1005 else 1006 { 1007 error_str.assign ("unknown error occurred launching process"); 1008 } 1009 } 1010 else 1011 { 1012 error_str.assign ("timed out waiting for app to launch"); 1013 } 1014 return false; 1015 } 1016 1017 int 1018 GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info) 1019 { 1020 // Since we don't get the send argv0 separate from the executable path, we need to 1021 // make sure to use the actual exectuable path found in the launch_info... 1022 std::vector<const char *> argv; 1023 FileSpec exe_file = launch_info.GetExecutableFile(); 1024 std::string exe_path; 1025 const char *arg = NULL; 1026 const Args &launch_args = launch_info.GetArguments(); 1027 if (exe_file) 1028 exe_path = exe_file.GetPath(); 1029 else 1030 { 1031 arg = launch_args.GetArgumentAtIndex(0); 1032 if (arg) 1033 exe_path = arg; 1034 } 1035 if (!exe_path.empty()) 1036 { 1037 argv.push_back(exe_path.c_str()); 1038 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i) 1039 { 1040 if (arg) 1041 argv.push_back(arg); 1042 } 1043 } 1044 if (!argv.empty()) 1045 { 1046 StreamString packet; 1047 packet.PutChar('A'); 1048 for (size_t i = 0, n = argv.size(); i < n; ++i) 1049 { 1050 arg = argv[i]; 1051 const int arg_len = strlen(arg); 1052 if (i > 0) 1053 packet.PutChar(','); 1054 packet.Printf("%i,%i,", arg_len * 2, (int)i); 1055 packet.PutBytesAsRawHex8 (arg, arg_len); 1056 } 1057 1058 StringExtractorGDBRemote response; 1059 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1060 { 1061 if (response.IsOKResponse()) 1062 return 0; 1063 uint8_t error = response.GetError(); 1064 if (error) 1065 return error; 1066 } 1067 } 1068 return -1; 1069 } 1070 1071 int 1072 GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value) 1073 { 1074 if (name_equal_value && name_equal_value[0]) 1075 { 1076 StreamString packet; 1077 bool send_hex_encoding = false; 1078 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p) 1079 { 1080 if (isprint(*p)) 1081 { 1082 switch (*p) 1083 { 1084 case '$': 1085 case '#': 1086 send_hex_encoding = true; 1087 break; 1088 default: 1089 break; 1090 } 1091 } 1092 else 1093 { 1094 // We have non printable characters, lets hex encode this... 1095 send_hex_encoding = true; 1096 } 1097 } 1098 1099 StringExtractorGDBRemote response; 1100 if (send_hex_encoding) 1101 { 1102 if (m_supports_QEnvironmentHexEncoded) 1103 { 1104 packet.PutCString("QEnvironmentHexEncoded:"); 1105 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value)); 1106 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1107 { 1108 if (response.IsOKResponse()) 1109 return 0; 1110 uint8_t error = response.GetError(); 1111 if (error) 1112 return error; 1113 if (response.IsUnsupportedResponse()) 1114 m_supports_QEnvironmentHexEncoded = false; 1115 } 1116 } 1117 1118 } 1119 else if (m_supports_QEnvironment) 1120 { 1121 packet.Printf("QEnvironment:%s", name_equal_value); 1122 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1123 { 1124 if (response.IsOKResponse()) 1125 return 0; 1126 uint8_t error = response.GetError(); 1127 if (error) 1128 return error; 1129 if (response.IsUnsupportedResponse()) 1130 m_supports_QEnvironment = false; 1131 } 1132 } 1133 } 1134 return -1; 1135 } 1136 1137 int 1138 GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch) 1139 { 1140 if (arch && arch[0]) 1141 { 1142 StreamString packet; 1143 packet.Printf("QLaunchArch:%s", arch); 1144 StringExtractorGDBRemote response; 1145 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1146 { 1147 if (response.IsOKResponse()) 1148 return 0; 1149 uint8_t error = response.GetError(); 1150 if (error) 1151 return error; 1152 } 1153 } 1154 return -1; 1155 } 1156 1157 bool 1158 GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major, 1159 uint32_t &minor, 1160 uint32_t &update) 1161 { 1162 if (GetHostInfo ()) 1163 { 1164 if (m_os_version_major != UINT32_MAX) 1165 { 1166 major = m_os_version_major; 1167 minor = m_os_version_minor; 1168 update = m_os_version_update; 1169 return true; 1170 } 1171 } 1172 return false; 1173 } 1174 1175 bool 1176 GDBRemoteCommunicationClient::GetOSBuildString (std::string &s) 1177 { 1178 if (GetHostInfo ()) 1179 { 1180 if (!m_os_build.empty()) 1181 { 1182 s = m_os_build; 1183 return true; 1184 } 1185 } 1186 s.clear(); 1187 return false; 1188 } 1189 1190 1191 bool 1192 GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s) 1193 { 1194 if (GetHostInfo ()) 1195 { 1196 if (!m_os_kernel.empty()) 1197 { 1198 s = m_os_kernel; 1199 return true; 1200 } 1201 } 1202 s.clear(); 1203 return false; 1204 } 1205 1206 bool 1207 GDBRemoteCommunicationClient::GetHostname (std::string &s) 1208 { 1209 if (GetHostInfo ()) 1210 { 1211 if (!m_hostname.empty()) 1212 { 1213 s = m_hostname; 1214 return true; 1215 } 1216 } 1217 s.clear(); 1218 return false; 1219 } 1220 1221 ArchSpec 1222 GDBRemoteCommunicationClient::GetSystemArchitecture () 1223 { 1224 if (GetHostInfo ()) 1225 return m_host_arch; 1226 return ArchSpec(); 1227 } 1228 1229 const lldb_private::ArchSpec & 1230 GDBRemoteCommunicationClient::GetProcessArchitecture () 1231 { 1232 if (m_qProcessInfo_is_valid == eLazyBoolCalculate) 1233 GetCurrentProcessInfo (); 1234 return m_process_arch; 1235 } 1236 1237 1238 bool 1239 GDBRemoteCommunicationClient::GetHostInfo (bool force) 1240 { 1241 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) 1242 { 1243 m_qHostInfo_is_valid = eLazyBoolNo; 1244 StringExtractorGDBRemote response; 1245 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success) 1246 { 1247 if (response.IsNormalResponse()) 1248 { 1249 std::string name; 1250 std::string value; 1251 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1252 uint32_t sub = 0; 1253 std::string arch_name; 1254 std::string os_name; 1255 std::string vendor_name; 1256 std::string triple; 1257 uint32_t pointer_byte_size = 0; 1258 StringExtractor extractor; 1259 ByteOrder byte_order = eByteOrderInvalid; 1260 uint32_t num_keys_decoded = 0; 1261 while (response.GetNameColonValue(name, value)) 1262 { 1263 if (name.compare("cputype") == 0) 1264 { 1265 // exception type in big endian hex 1266 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0); 1267 if (cpu != LLDB_INVALID_CPUTYPE) 1268 ++num_keys_decoded; 1269 } 1270 else if (name.compare("cpusubtype") == 0) 1271 { 1272 // exception count in big endian hex 1273 sub = Args::StringToUInt32 (value.c_str(), 0, 0); 1274 if (sub != 0) 1275 ++num_keys_decoded; 1276 } 1277 else if (name.compare("arch") == 0) 1278 { 1279 arch_name.swap (value); 1280 ++num_keys_decoded; 1281 } 1282 else if (name.compare("triple") == 0) 1283 { 1284 // The triple comes as ASCII hex bytes since it contains '-' chars 1285 extractor.GetStringRef().swap(value); 1286 extractor.SetFilePos(0); 1287 extractor.GetHexByteString (triple); 1288 ++num_keys_decoded; 1289 } 1290 else if (name.compare("os_build") == 0) 1291 { 1292 extractor.GetStringRef().swap(value); 1293 extractor.SetFilePos(0); 1294 extractor.GetHexByteString (m_os_build); 1295 ++num_keys_decoded; 1296 } 1297 else if (name.compare("hostname") == 0) 1298 { 1299 extractor.GetStringRef().swap(value); 1300 extractor.SetFilePos(0); 1301 extractor.GetHexByteString (m_hostname); 1302 ++num_keys_decoded; 1303 } 1304 else if (name.compare("os_kernel") == 0) 1305 { 1306 extractor.GetStringRef().swap(value); 1307 extractor.SetFilePos(0); 1308 extractor.GetHexByteString (m_os_kernel); 1309 ++num_keys_decoded; 1310 } 1311 else if (name.compare("ostype") == 0) 1312 { 1313 os_name.swap (value); 1314 ++num_keys_decoded; 1315 } 1316 else if (name.compare("vendor") == 0) 1317 { 1318 vendor_name.swap(value); 1319 ++num_keys_decoded; 1320 } 1321 else if (name.compare("endian") == 0) 1322 { 1323 ++num_keys_decoded; 1324 if (value.compare("little") == 0) 1325 byte_order = eByteOrderLittle; 1326 else if (value.compare("big") == 0) 1327 byte_order = eByteOrderBig; 1328 else if (value.compare("pdp") == 0) 1329 byte_order = eByteOrderPDP; 1330 else 1331 --num_keys_decoded; 1332 } 1333 else if (name.compare("ptrsize") == 0) 1334 { 1335 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0); 1336 if (pointer_byte_size != 0) 1337 ++num_keys_decoded; 1338 } 1339 else if (name.compare("os_version") == 0) 1340 { 1341 Args::StringToVersion (value.c_str(), 1342 m_os_version_major, 1343 m_os_version_minor, 1344 m_os_version_update); 1345 if (m_os_version_major != UINT32_MAX) 1346 ++num_keys_decoded; 1347 } 1348 else if (name.compare("watchpoint_exceptions_received") == 0) 1349 { 1350 ++num_keys_decoded; 1351 if (strcmp(value.c_str(),"before") == 0) 1352 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 1353 else if (strcmp(value.c_str(),"after") == 0) 1354 m_watchpoints_trigger_after_instruction = eLazyBoolYes; 1355 else 1356 --num_keys_decoded; 1357 } 1358 else if (name.compare("default_packet_timeout") == 0) 1359 { 1360 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0); 1361 if (m_default_packet_timeout > 0) 1362 { 1363 SetPacketTimeout(m_default_packet_timeout); 1364 ++num_keys_decoded; 1365 } 1366 } 1367 1368 } 1369 1370 if (num_keys_decoded > 0) 1371 m_qHostInfo_is_valid = eLazyBoolYes; 1372 1373 if (triple.empty()) 1374 { 1375 if (arch_name.empty()) 1376 { 1377 if (cpu != LLDB_INVALID_CPUTYPE) 1378 { 1379 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 1380 if (pointer_byte_size) 1381 { 1382 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1383 } 1384 if (byte_order != eByteOrderInvalid) 1385 { 1386 assert (byte_order == m_host_arch.GetByteOrder()); 1387 } 1388 1389 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0) 1390 { 1391 switch (m_host_arch.GetMachine()) 1392 { 1393 case llvm::Triple::arm: 1394 case llvm::Triple::thumb: 1395 os_name = "ios"; 1396 break; 1397 default: 1398 os_name = "macosx"; 1399 break; 1400 } 1401 } 1402 if (!vendor_name.empty()) 1403 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 1404 if (!os_name.empty()) 1405 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 1406 1407 } 1408 } 1409 else 1410 { 1411 std::string triple; 1412 triple += arch_name; 1413 if (!vendor_name.empty() || !os_name.empty()) 1414 { 1415 triple += '-'; 1416 if (vendor_name.empty()) 1417 triple += "unknown"; 1418 else 1419 triple += vendor_name; 1420 triple += '-'; 1421 if (os_name.empty()) 1422 triple += "unknown"; 1423 else 1424 triple += os_name; 1425 } 1426 m_host_arch.SetTriple (triple.c_str()); 1427 1428 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1429 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin) 1430 { 1431 switch (m_host_arch.GetMachine()) 1432 { 1433 case llvm::Triple::arm: 1434 case llvm::Triple::thumb: 1435 host_triple.setOS(llvm::Triple::IOS); 1436 break; 1437 default: 1438 host_triple.setOS(llvm::Triple::MacOSX); 1439 break; 1440 } 1441 } 1442 if (pointer_byte_size) 1443 { 1444 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1445 } 1446 if (byte_order != eByteOrderInvalid) 1447 { 1448 assert (byte_order == m_host_arch.GetByteOrder()); 1449 } 1450 1451 } 1452 } 1453 else 1454 { 1455 m_host_arch.SetTriple (triple.c_str()); 1456 if (pointer_byte_size) 1457 { 1458 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1459 } 1460 if (byte_order != eByteOrderInvalid) 1461 { 1462 assert (byte_order == m_host_arch.GetByteOrder()); 1463 } 1464 } 1465 } 1466 } 1467 } 1468 return m_qHostInfo_is_valid == eLazyBoolYes; 1469 } 1470 1471 int 1472 GDBRemoteCommunicationClient::SendAttach 1473 ( 1474 lldb::pid_t pid, 1475 StringExtractorGDBRemote& response 1476 ) 1477 { 1478 if (pid != LLDB_INVALID_PROCESS_ID) 1479 { 1480 char packet[64]; 1481 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid); 1482 assert (packet_len < (int)sizeof(packet)); 1483 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1484 { 1485 if (response.IsErrorResponse()) 1486 return response.GetError(); 1487 return 0; 1488 } 1489 } 1490 return -1; 1491 } 1492 1493 const lldb_private::ArchSpec & 1494 GDBRemoteCommunicationClient::GetHostArchitecture () 1495 { 1496 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1497 GetHostInfo (); 1498 return m_host_arch; 1499 } 1500 1501 uint32_t 1502 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout () 1503 { 1504 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1505 GetHostInfo (); 1506 return m_default_packet_timeout; 1507 } 1508 1509 addr_t 1510 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions) 1511 { 1512 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1513 { 1514 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1515 char packet[64]; 1516 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", 1517 (uint64_t)size, 1518 permissions & lldb::ePermissionsReadable ? "r" : "", 1519 permissions & lldb::ePermissionsWritable ? "w" : "", 1520 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1521 assert (packet_len < (int)sizeof(packet)); 1522 StringExtractorGDBRemote response; 1523 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1524 { 1525 if (!response.IsErrorResponse()) 1526 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1527 } 1528 else 1529 { 1530 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1531 } 1532 } 1533 return LLDB_INVALID_ADDRESS; 1534 } 1535 1536 bool 1537 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 1538 { 1539 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1540 { 1541 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1542 char packet[64]; 1543 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1544 assert (packet_len < (int)sizeof(packet)); 1545 StringExtractorGDBRemote response; 1546 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1547 { 1548 if (response.IsOKResponse()) 1549 return true; 1550 } 1551 else 1552 { 1553 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1554 } 1555 } 1556 return false; 1557 } 1558 1559 Error 1560 GDBRemoteCommunicationClient::Detach (bool keep_stopped) 1561 { 1562 Error error; 1563 1564 if (keep_stopped) 1565 { 1566 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) 1567 { 1568 char packet[64]; 1569 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1570 assert (packet_len < (int)sizeof(packet)); 1571 StringExtractorGDBRemote response; 1572 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1573 { 1574 m_supports_detach_stay_stopped = eLazyBoolYes; 1575 } 1576 else 1577 { 1578 m_supports_detach_stay_stopped = eLazyBoolNo; 1579 } 1580 } 1581 1582 if (m_supports_detach_stay_stopped == eLazyBoolNo) 1583 { 1584 error.SetErrorString("Stays stopped not supported by this target."); 1585 return error; 1586 } 1587 else 1588 { 1589 PacketResult packet_result = SendPacket ("D1", 2); 1590 if (packet_result != PacketResult::Success) 1591 error.SetErrorString ("Sending extended disconnect packet failed."); 1592 } 1593 } 1594 else 1595 { 1596 PacketResult packet_result = SendPacket ("D", 1); 1597 if (packet_result != PacketResult::Success) 1598 error.SetErrorString ("Sending disconnect packet failed."); 1599 } 1600 return error; 1601 } 1602 1603 Error 1604 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 1605 lldb_private::MemoryRegionInfo ®ion_info) 1606 { 1607 Error error; 1608 region_info.Clear(); 1609 1610 if (m_supports_memory_region_info != eLazyBoolNo) 1611 { 1612 m_supports_memory_region_info = eLazyBoolYes; 1613 char packet[64]; 1614 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1615 assert (packet_len < (int)sizeof(packet)); 1616 StringExtractorGDBRemote response; 1617 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1618 { 1619 std::string name; 1620 std::string value; 1621 addr_t addr_value; 1622 bool success = true; 1623 bool saw_permissions = false; 1624 while (success && response.GetNameColonValue(name, value)) 1625 { 1626 if (name.compare ("start") == 0) 1627 { 1628 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 1629 if (success) 1630 region_info.GetRange().SetRangeBase(addr_value); 1631 } 1632 else if (name.compare ("size") == 0) 1633 { 1634 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success); 1635 if (success) 1636 region_info.GetRange().SetByteSize (addr_value); 1637 } 1638 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 1639 { 1640 saw_permissions = true; 1641 if (region_info.GetRange().Contains (addr)) 1642 { 1643 if (value.find('r') != std::string::npos) 1644 region_info.SetReadable (MemoryRegionInfo::eYes); 1645 else 1646 region_info.SetReadable (MemoryRegionInfo::eNo); 1647 1648 if (value.find('w') != std::string::npos) 1649 region_info.SetWritable (MemoryRegionInfo::eYes); 1650 else 1651 region_info.SetWritable (MemoryRegionInfo::eNo); 1652 1653 if (value.find('x') != std::string::npos) 1654 region_info.SetExecutable (MemoryRegionInfo::eYes); 1655 else 1656 region_info.SetExecutable (MemoryRegionInfo::eNo); 1657 } 1658 else 1659 { 1660 // The reported region does not contain this address -- we're looking at an unmapped page 1661 region_info.SetReadable (MemoryRegionInfo::eNo); 1662 region_info.SetWritable (MemoryRegionInfo::eNo); 1663 region_info.SetExecutable (MemoryRegionInfo::eNo); 1664 } 1665 } 1666 else if (name.compare ("error") == 0) 1667 { 1668 StringExtractorGDBRemote name_extractor; 1669 // Swap "value" over into "name_extractor" 1670 name_extractor.GetStringRef().swap(value); 1671 // Now convert the HEX bytes into a string value 1672 name_extractor.GetHexByteString (value); 1673 error.SetErrorString(value.c_str()); 1674 } 1675 } 1676 1677 // We got a valid address range back but no permissions -- which means this is an unmapped page 1678 if (region_info.GetRange().IsValid() && saw_permissions == false) 1679 { 1680 region_info.SetReadable (MemoryRegionInfo::eNo); 1681 region_info.SetWritable (MemoryRegionInfo::eNo); 1682 region_info.SetExecutable (MemoryRegionInfo::eNo); 1683 } 1684 } 1685 else 1686 { 1687 m_supports_memory_region_info = eLazyBoolNo; 1688 } 1689 } 1690 1691 if (m_supports_memory_region_info == eLazyBoolNo) 1692 { 1693 error.SetErrorString("qMemoryRegionInfo is not supported"); 1694 } 1695 if (error.Fail()) 1696 region_info.Clear(); 1697 return error; 1698 1699 } 1700 1701 Error 1702 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 1703 { 1704 Error error; 1705 1706 if (m_supports_watchpoint_support_info == eLazyBoolYes) 1707 { 1708 num = m_num_supported_hardware_watchpoints; 1709 return error; 1710 } 1711 1712 // Set num to 0 first. 1713 num = 0; 1714 if (m_supports_watchpoint_support_info != eLazyBoolNo) 1715 { 1716 char packet[64]; 1717 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1718 assert (packet_len < (int)sizeof(packet)); 1719 StringExtractorGDBRemote response; 1720 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1721 { 1722 m_supports_watchpoint_support_info = eLazyBoolYes; 1723 std::string name; 1724 std::string value; 1725 while (response.GetNameColonValue(name, value)) 1726 { 1727 if (name.compare ("num") == 0) 1728 { 1729 num = Args::StringToUInt32(value.c_str(), 0, 0); 1730 m_num_supported_hardware_watchpoints = num; 1731 } 1732 } 1733 } 1734 else 1735 { 1736 m_supports_watchpoint_support_info = eLazyBoolNo; 1737 } 1738 } 1739 1740 if (m_supports_watchpoint_support_info == eLazyBoolNo) 1741 { 1742 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1743 } 1744 return error; 1745 1746 } 1747 1748 lldb_private::Error 1749 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after) 1750 { 1751 Error error(GetWatchpointSupportInfo(num)); 1752 if (error.Success()) 1753 error = GetWatchpointsTriggerAfterInstruction(after); 1754 return error; 1755 } 1756 1757 lldb_private::Error 1758 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after) 1759 { 1760 Error error; 1761 1762 // we assume watchpoints will happen after running the relevant opcode 1763 // and we only want to override this behavior if we have explicitly 1764 // received a qHostInfo telling us otherwise 1765 if (m_qHostInfo_is_valid != eLazyBoolYes) 1766 after = true; 1767 else 1768 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1769 return error; 1770 } 1771 1772 int 1773 GDBRemoteCommunicationClient::SetSTDIN (char const *path) 1774 { 1775 if (path && path[0]) 1776 { 1777 StreamString packet; 1778 packet.PutCString("QSetSTDIN:"); 1779 packet.PutBytesAsRawHex8(path, strlen(path)); 1780 1781 StringExtractorGDBRemote response; 1782 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1783 { 1784 if (response.IsOKResponse()) 1785 return 0; 1786 uint8_t error = response.GetError(); 1787 if (error) 1788 return error; 1789 } 1790 } 1791 return -1; 1792 } 1793 1794 int 1795 GDBRemoteCommunicationClient::SetSTDOUT (char const *path) 1796 { 1797 if (path && path[0]) 1798 { 1799 StreamString packet; 1800 packet.PutCString("QSetSTDOUT:"); 1801 packet.PutBytesAsRawHex8(path, strlen(path)); 1802 1803 StringExtractorGDBRemote response; 1804 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1805 { 1806 if (response.IsOKResponse()) 1807 return 0; 1808 uint8_t error = response.GetError(); 1809 if (error) 1810 return error; 1811 } 1812 } 1813 return -1; 1814 } 1815 1816 int 1817 GDBRemoteCommunicationClient::SetSTDERR (char const *path) 1818 { 1819 if (path && path[0]) 1820 { 1821 StreamString packet; 1822 packet.PutCString("QSetSTDERR:"); 1823 packet.PutBytesAsRawHex8(path, strlen(path)); 1824 1825 StringExtractorGDBRemote response; 1826 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1827 { 1828 if (response.IsOKResponse()) 1829 return 0; 1830 uint8_t error = response.GetError(); 1831 if (error) 1832 return error; 1833 } 1834 } 1835 return -1; 1836 } 1837 1838 bool 1839 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd) 1840 { 1841 StringExtractorGDBRemote response; 1842 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success) 1843 { 1844 if (response.IsUnsupportedResponse()) 1845 return false; 1846 if (response.IsErrorResponse()) 1847 return false; 1848 response.GetHexByteString (cwd); 1849 return !cwd.empty(); 1850 } 1851 return false; 1852 } 1853 1854 int 1855 GDBRemoteCommunicationClient::SetWorkingDir (char const *path) 1856 { 1857 if (path && path[0]) 1858 { 1859 StreamString packet; 1860 packet.PutCString("QSetWorkingDir:"); 1861 packet.PutBytesAsRawHex8(path, strlen(path)); 1862 1863 StringExtractorGDBRemote response; 1864 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1865 { 1866 if (response.IsOKResponse()) 1867 return 0; 1868 uint8_t error = response.GetError(); 1869 if (error) 1870 return error; 1871 } 1872 } 1873 return -1; 1874 } 1875 1876 int 1877 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 1878 { 1879 char packet[32]; 1880 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1881 assert (packet_len < (int)sizeof(packet)); 1882 StringExtractorGDBRemote response; 1883 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1884 { 1885 if (response.IsOKResponse()) 1886 return 0; 1887 uint8_t error = response.GetError(); 1888 if (error) 1889 return error; 1890 } 1891 return -1; 1892 } 1893 1894 bool 1895 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 1896 { 1897 if (response.IsNormalResponse()) 1898 { 1899 std::string name; 1900 std::string value; 1901 StringExtractor extractor; 1902 1903 while (response.GetNameColonValue(name, value)) 1904 { 1905 if (name.compare("pid") == 0) 1906 { 1907 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1908 } 1909 else if (name.compare("ppid") == 0) 1910 { 1911 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1912 } 1913 else if (name.compare("uid") == 0) 1914 { 1915 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1916 } 1917 else if (name.compare("euid") == 0) 1918 { 1919 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1920 } 1921 else if (name.compare("gid") == 0) 1922 { 1923 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1924 } 1925 else if (name.compare("egid") == 0) 1926 { 1927 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1928 } 1929 else if (name.compare("triple") == 0) 1930 { 1931 // The triple comes as ASCII hex bytes since it contains '-' chars 1932 extractor.GetStringRef().swap(value); 1933 extractor.SetFilePos(0); 1934 extractor.GetHexByteString (value); 1935 process_info.GetArchitecture ().SetTriple (value.c_str()); 1936 } 1937 else if (name.compare("name") == 0) 1938 { 1939 StringExtractor extractor; 1940 // The process name from ASCII hex bytes since we can't 1941 // control the characters in a process name 1942 extractor.GetStringRef().swap(value); 1943 extractor.SetFilePos(0); 1944 extractor.GetHexByteString (value); 1945 process_info.GetExecutableFile().SetFile (value.c_str(), false); 1946 } 1947 } 1948 1949 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1950 return true; 1951 } 1952 return false; 1953 } 1954 1955 bool 1956 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1957 { 1958 process_info.Clear(); 1959 1960 if (m_supports_qProcessInfoPID) 1961 { 1962 char packet[32]; 1963 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid); 1964 assert (packet_len < (int)sizeof(packet)); 1965 StringExtractorGDBRemote response; 1966 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1967 { 1968 return DecodeProcessInfoResponse (response, process_info); 1969 } 1970 else 1971 { 1972 m_supports_qProcessInfoPID = false; 1973 return false; 1974 } 1975 } 1976 return false; 1977 } 1978 1979 bool 1980 GDBRemoteCommunicationClient::GetCurrentProcessInfo () 1981 { 1982 if (m_qProcessInfo_is_valid == eLazyBoolYes) 1983 return true; 1984 if (m_qProcessInfo_is_valid == eLazyBoolNo) 1985 return false; 1986 1987 GetHostInfo (); 1988 1989 StringExtractorGDBRemote response; 1990 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success) 1991 { 1992 if (response.IsNormalResponse()) 1993 { 1994 std::string name; 1995 std::string value; 1996 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1997 uint32_t sub = 0; 1998 std::string arch_name; 1999 std::string os_name; 2000 std::string vendor_name; 2001 std::string triple; 2002 uint32_t pointer_byte_size = 0; 2003 StringExtractor extractor; 2004 ByteOrder byte_order = eByteOrderInvalid; 2005 uint32_t num_keys_decoded = 0; 2006 while (response.GetNameColonValue(name, value)) 2007 { 2008 if (name.compare("cputype") == 0) 2009 { 2010 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2011 if (cpu != LLDB_INVALID_CPUTYPE) 2012 ++num_keys_decoded; 2013 } 2014 else if (name.compare("cpusubtype") == 0) 2015 { 2016 sub = Args::StringToUInt32 (value.c_str(), 0, 16); 2017 if (sub != 0) 2018 ++num_keys_decoded; 2019 } 2020 else if (name.compare("ostype") == 0) 2021 { 2022 os_name.swap (value); 2023 ++num_keys_decoded; 2024 } 2025 else if (name.compare("vendor") == 0) 2026 { 2027 vendor_name.swap(value); 2028 ++num_keys_decoded; 2029 } 2030 else if (name.compare("endian") == 0) 2031 { 2032 ++num_keys_decoded; 2033 if (value.compare("little") == 0) 2034 byte_order = eByteOrderLittle; 2035 else if (value.compare("big") == 0) 2036 byte_order = eByteOrderBig; 2037 else if (value.compare("pdp") == 0) 2038 byte_order = eByteOrderPDP; 2039 else 2040 --num_keys_decoded; 2041 } 2042 else if (name.compare("ptrsize") == 0) 2043 { 2044 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16); 2045 if (pointer_byte_size != 0) 2046 ++num_keys_decoded; 2047 } 2048 } 2049 if (num_keys_decoded > 0) 2050 m_qProcessInfo_is_valid = eLazyBoolYes; 2051 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty()) 2052 { 2053 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 2054 if (pointer_byte_size) 2055 { 2056 assert (pointer_byte_size == m_process_arch.GetAddressByteSize()); 2057 } 2058 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2059 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 2060 return true; 2061 } 2062 } 2063 } 2064 else 2065 { 2066 m_qProcessInfo_is_valid = eLazyBoolNo; 2067 } 2068 2069 return false; 2070 } 2071 2072 2073 uint32_t 2074 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 2075 ProcessInstanceInfoList &process_infos) 2076 { 2077 process_infos.Clear(); 2078 2079 if (m_supports_qfProcessInfo) 2080 { 2081 StreamString packet; 2082 packet.PutCString ("qfProcessInfo"); 2083 if (!match_info.MatchAllProcesses()) 2084 { 2085 packet.PutChar (':'); 2086 const char *name = match_info.GetProcessInfo().GetName(); 2087 bool has_name_match = false; 2088 if (name && name[0]) 2089 { 2090 has_name_match = true; 2091 NameMatchType name_match_type = match_info.GetNameMatchType(); 2092 switch (name_match_type) 2093 { 2094 case eNameMatchIgnore: 2095 has_name_match = false; 2096 break; 2097 2098 case eNameMatchEquals: 2099 packet.PutCString ("name_match:equals;"); 2100 break; 2101 2102 case eNameMatchContains: 2103 packet.PutCString ("name_match:contains;"); 2104 break; 2105 2106 case eNameMatchStartsWith: 2107 packet.PutCString ("name_match:starts_with;"); 2108 break; 2109 2110 case eNameMatchEndsWith: 2111 packet.PutCString ("name_match:ends_with;"); 2112 break; 2113 2114 case eNameMatchRegularExpression: 2115 packet.PutCString ("name_match:regex;"); 2116 break; 2117 } 2118 if (has_name_match) 2119 { 2120 packet.PutCString ("name:"); 2121 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2122 packet.PutChar (';'); 2123 } 2124 } 2125 2126 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2127 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID()); 2128 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2129 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID()); 2130 if (match_info.GetProcessInfo().UserIDIsValid()) 2131 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 2132 if (match_info.GetProcessInfo().GroupIDIsValid()) 2133 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 2134 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2135 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 2136 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2137 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 2138 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2139 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 2140 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 2141 { 2142 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 2143 const llvm::Triple &triple = match_arch.GetTriple(); 2144 packet.PutCString("triple:"); 2145 packet.PutCStringAsRawHex8(triple.getTriple().c_str()); 2146 packet.PutChar (';'); 2147 } 2148 } 2149 StringExtractorGDBRemote response; 2150 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2151 { 2152 do 2153 { 2154 ProcessInstanceInfo process_info; 2155 if (!DecodeProcessInfoResponse (response, process_info)) 2156 break; 2157 process_infos.Append(process_info); 2158 response.GetStringRef().clear(); 2159 response.SetFilePos(0); 2160 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success); 2161 } 2162 else 2163 { 2164 m_supports_qfProcessInfo = false; 2165 return 0; 2166 } 2167 } 2168 return process_infos.GetSize(); 2169 2170 } 2171 2172 bool 2173 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 2174 { 2175 if (m_supports_qUserName) 2176 { 2177 char packet[32]; 2178 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 2179 assert (packet_len < (int)sizeof(packet)); 2180 StringExtractorGDBRemote response; 2181 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2182 { 2183 if (response.IsNormalResponse()) 2184 { 2185 // Make sure we parsed the right number of characters. The response is 2186 // the hex encoded user name and should make up the entire packet. 2187 // If there are any non-hex ASCII bytes, the length won't match below.. 2188 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2189 return true; 2190 } 2191 } 2192 else 2193 { 2194 m_supports_qUserName = false; 2195 return false; 2196 } 2197 } 2198 return false; 2199 2200 } 2201 2202 bool 2203 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 2204 { 2205 if (m_supports_qGroupName) 2206 { 2207 char packet[32]; 2208 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 2209 assert (packet_len < (int)sizeof(packet)); 2210 StringExtractorGDBRemote response; 2211 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2212 { 2213 if (response.IsNormalResponse()) 2214 { 2215 // Make sure we parsed the right number of characters. The response is 2216 // the hex encoded group name and should make up the entire packet. 2217 // If there are any non-hex ASCII bytes, the length won't match below.. 2218 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2219 return true; 2220 } 2221 } 2222 else 2223 { 2224 m_supports_qGroupName = false; 2225 return false; 2226 } 2227 } 2228 return false; 2229 } 2230 2231 void 2232 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets) 2233 { 2234 uint32_t i; 2235 TimeValue start_time, end_time; 2236 uint64_t total_time_nsec; 2237 float packets_per_second; 2238 if (SendSpeedTestPacket (0, 0)) 2239 { 2240 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2) 2241 { 2242 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2) 2243 { 2244 start_time = TimeValue::Now(); 2245 for (i=0; i<num_packets; ++i) 2246 { 2247 SendSpeedTestPacket (send_size, recv_size); 2248 } 2249 end_time = TimeValue::Now(); 2250 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 2251 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 2252 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n", 2253 num_packets, 2254 send_size, 2255 recv_size, 2256 total_time_nsec / TimeValue::NanoSecPerSec, 2257 total_time_nsec % TimeValue::NanoSecPerSec, 2258 packets_per_second); 2259 if (recv_size == 0) 2260 recv_size = 32; 2261 } 2262 if (send_size == 0) 2263 send_size = 32; 2264 } 2265 } 2266 else 2267 { 2268 start_time = TimeValue::Now(); 2269 for (i=0; i<num_packets; ++i) 2270 { 2271 GetCurrentProcessID (); 2272 } 2273 end_time = TimeValue::Now(); 2274 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 2275 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 2276 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n", 2277 num_packets, 2278 total_time_nsec / TimeValue::NanoSecPerSec, 2279 total_time_nsec % TimeValue::NanoSecPerSec, 2280 packets_per_second); 2281 } 2282 } 2283 2284 bool 2285 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 2286 { 2287 StreamString packet; 2288 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 2289 uint32_t bytes_left = send_size; 2290 while (bytes_left > 0) 2291 { 2292 if (bytes_left >= 26) 2293 { 2294 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2295 bytes_left -= 26; 2296 } 2297 else 2298 { 2299 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 2300 bytes_left = 0; 2301 } 2302 } 2303 2304 StringExtractorGDBRemote response; 2305 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success; 2306 } 2307 2308 uint16_t 2309 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname) 2310 { 2311 pid = LLDB_INVALID_PROCESS_ID; 2312 StringExtractorGDBRemote response; 2313 StreamString stream; 2314 stream.PutCString("qLaunchGDBServer;"); 2315 std::string hostname; 2316 if (remote_accept_hostname && remote_accept_hostname[0]) 2317 hostname = remote_accept_hostname; 2318 else 2319 { 2320 if (Host::GetHostname (hostname)) 2321 { 2322 // Make the GDB server we launch only accept connections from this host 2323 stream.Printf("host:%s;", hostname.c_str()); 2324 } 2325 else 2326 { 2327 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname 2328 stream.Printf("host:*;"); 2329 } 2330 } 2331 const char *packet = stream.GetData(); 2332 int packet_len = stream.GetSize(); 2333 2334 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2335 { 2336 std::string name; 2337 std::string value; 2338 uint16_t port = 0; 2339 while (response.GetNameColonValue(name, value)) 2340 { 2341 if (name.compare("port") == 0) 2342 port = Args::StringToUInt32(value.c_str(), 0, 0); 2343 else if (name.compare("pid") == 0) 2344 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 2345 } 2346 return port; 2347 } 2348 return 0; 2349 } 2350 2351 bool 2352 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid) 2353 { 2354 StreamString stream; 2355 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid); 2356 const char *packet = stream.GetData(); 2357 int packet_len = stream.GetSize(); 2358 2359 StringExtractorGDBRemote response; 2360 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2361 { 2362 if (response.IsOKResponse()) 2363 return true; 2364 } 2365 return false; 2366 } 2367 2368 bool 2369 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid) 2370 { 2371 if (m_curr_tid == tid) 2372 return true; 2373 2374 char packet[32]; 2375 int packet_len; 2376 if (tid == UINT64_MAX) 2377 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1"); 2378 else 2379 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid); 2380 assert (packet_len + 1 < (int)sizeof(packet)); 2381 StringExtractorGDBRemote response; 2382 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2383 { 2384 if (response.IsOKResponse()) 2385 { 2386 m_curr_tid = tid; 2387 return true; 2388 } 2389 } 2390 return false; 2391 } 2392 2393 bool 2394 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid) 2395 { 2396 if (m_curr_tid_run == tid) 2397 return true; 2398 2399 char packet[32]; 2400 int packet_len; 2401 if (tid == UINT64_MAX) 2402 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1"); 2403 else 2404 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid); 2405 2406 assert (packet_len + 1 < (int)sizeof(packet)); 2407 StringExtractorGDBRemote response; 2408 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2409 { 2410 if (response.IsOKResponse()) 2411 { 2412 m_curr_tid_run = tid; 2413 return true; 2414 } 2415 } 2416 return false; 2417 } 2418 2419 bool 2420 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 2421 { 2422 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success) 2423 return response.IsNormalResponse(); 2424 return false; 2425 } 2426 2427 bool 2428 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response) 2429 { 2430 if (m_supports_qThreadStopInfo) 2431 { 2432 char packet[256]; 2433 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2434 assert (packet_len < (int)sizeof(packet)); 2435 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2436 { 2437 if (response.IsUnsupportedResponse()) 2438 m_supports_qThreadStopInfo = false; 2439 else if (response.IsNormalResponse()) 2440 return true; 2441 else 2442 return false; 2443 } 2444 else 2445 { 2446 m_supports_qThreadStopInfo = false; 2447 } 2448 } 2449 return false; 2450 } 2451 2452 2453 uint8_t 2454 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 2455 { 2456 switch (type) 2457 { 2458 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break; 2459 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break; 2460 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break; 2461 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break; 2462 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break; 2463 } 2464 2465 char packet[64]; 2466 const int packet_len = ::snprintf (packet, 2467 sizeof(packet), 2468 "%c%i,%" PRIx64 ",%x", 2469 insert ? 'Z' : 'z', 2470 type, 2471 addr, 2472 length); 2473 2474 assert (packet_len + 1 < (int)sizeof(packet)); 2475 StringExtractorGDBRemote response; 2476 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success) 2477 { 2478 if (response.IsOKResponse()) 2479 return 0; 2480 else if (response.IsErrorResponse()) 2481 return response.GetError(); 2482 } 2483 else 2484 { 2485 switch (type) 2486 { 2487 case eBreakpointSoftware: m_supports_z0 = false; break; 2488 case eBreakpointHardware: m_supports_z1 = false; break; 2489 case eWatchpointWrite: m_supports_z2 = false; break; 2490 case eWatchpointRead: m_supports_z3 = false; break; 2491 case eWatchpointReadWrite: m_supports_z4 = false; break; 2492 } 2493 } 2494 2495 return UINT8_MAX; 2496 } 2497 2498 size_t 2499 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 2500 bool &sequence_mutex_unavailable) 2501 { 2502 Mutex::Locker locker; 2503 thread_ids.clear(); 2504 2505 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 2506 { 2507 sequence_mutex_unavailable = false; 2508 StringExtractorGDBRemote response; 2509 2510 PacketResult packet_result; 2511 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response); 2512 packet_result == PacketResult::Success && response.IsNormalResponse(); 2513 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response)) 2514 { 2515 char ch = response.GetChar(); 2516 if (ch == 'l') 2517 break; 2518 if (ch == 'm') 2519 { 2520 do 2521 { 2522 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2523 2524 if (tid != LLDB_INVALID_THREAD_ID) 2525 { 2526 thread_ids.push_back (tid); 2527 } 2528 ch = response.GetChar(); // Skip the command separator 2529 } while (ch == ','); // Make sure we got a comma separator 2530 } 2531 } 2532 } 2533 else 2534 { 2535 #if defined (LLDB_CONFIGURATION_DEBUG) 2536 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 2537 #else 2538 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2539 if (log) 2540 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 2541 #endif 2542 sequence_mutex_unavailable = true; 2543 } 2544 return thread_ids.size(); 2545 } 2546 2547 lldb::addr_t 2548 GDBRemoteCommunicationClient::GetShlibInfoAddr() 2549 { 2550 if (!IsRunning()) 2551 { 2552 StringExtractorGDBRemote response; 2553 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success) 2554 { 2555 if (response.IsNormalResponse()) 2556 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2557 } 2558 } 2559 return LLDB_INVALID_ADDRESS; 2560 } 2561 2562 lldb_private::Error 2563 GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL 2564 const char *working_dir, // Pass NULL to use the current working directory 2565 int *status_ptr, // Pass NULL if you don't want the process exit status 2566 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit 2567 std::string *command_output, // Pass NULL if you don't want the command output 2568 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish 2569 { 2570 lldb_private::StreamString stream; 2571 stream.PutCString("qPlatform_shell:"); 2572 stream.PutBytesAsRawHex8(command, strlen(command)); 2573 stream.PutChar(','); 2574 stream.PutHex32(timeout_sec); 2575 if (working_dir && *working_dir) 2576 { 2577 stream.PutChar(','); 2578 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 2579 } 2580 const char *packet = stream.GetData(); 2581 int packet_len = stream.GetSize(); 2582 StringExtractorGDBRemote response; 2583 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2584 { 2585 if (response.GetChar() != 'F') 2586 return Error("malformed reply"); 2587 if (response.GetChar() != ',') 2588 return Error("malformed reply"); 2589 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2590 if (exitcode == UINT32_MAX) 2591 return Error("unable to run remote process"); 2592 else if (status_ptr) 2593 *status_ptr = exitcode; 2594 if (response.GetChar() != ',') 2595 return Error("malformed reply"); 2596 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2597 if (signo_ptr) 2598 *signo_ptr = signo; 2599 if (response.GetChar() != ',') 2600 return Error("malformed reply"); 2601 std::string output; 2602 response.GetEscapedBinaryData(output); 2603 if (command_output) 2604 command_output->assign(output); 2605 return Error(); 2606 } 2607 return Error("unable to send packet"); 2608 } 2609 2610 Error 2611 GDBRemoteCommunicationClient::MakeDirectory (const char *path, 2612 uint32_t file_permissions) 2613 { 2614 lldb_private::StreamString stream; 2615 stream.PutCString("qPlatform_mkdir:"); 2616 stream.PutHex32(file_permissions); 2617 stream.PutChar(','); 2618 stream.PutBytesAsRawHex8(path, strlen(path)); 2619 const char *packet = stream.GetData(); 2620 int packet_len = stream.GetSize(); 2621 StringExtractorGDBRemote response; 2622 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2623 { 2624 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2625 } 2626 return Error(); 2627 2628 } 2629 2630 Error 2631 GDBRemoteCommunicationClient::SetFilePermissions (const char *path, 2632 uint32_t file_permissions) 2633 { 2634 lldb_private::StreamString stream; 2635 stream.PutCString("qPlatform_chmod:"); 2636 stream.PutHex32(file_permissions); 2637 stream.PutChar(','); 2638 stream.PutBytesAsRawHex8(path, strlen(path)); 2639 const char *packet = stream.GetData(); 2640 int packet_len = stream.GetSize(); 2641 StringExtractorGDBRemote response; 2642 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2643 { 2644 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2645 } 2646 return Error(); 2647 2648 } 2649 2650 static uint64_t 2651 ParseHostIOPacketResponse (StringExtractorGDBRemote &response, 2652 uint64_t fail_result, 2653 Error &error) 2654 { 2655 response.SetFilePos(0); 2656 if (response.GetChar() != 'F') 2657 return fail_result; 2658 int32_t result = response.GetS32 (-2); 2659 if (result == -2) 2660 return fail_result; 2661 if (response.GetChar() == ',') 2662 { 2663 int result_errno = response.GetS32 (-2); 2664 if (result_errno != -2) 2665 error.SetError(result_errno, eErrorTypePOSIX); 2666 else 2667 error.SetError(-1, eErrorTypeGeneric); 2668 } 2669 else 2670 error.Clear(); 2671 return result; 2672 } 2673 lldb::user_id_t 2674 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec, 2675 uint32_t flags, 2676 mode_t mode, 2677 Error &error) 2678 { 2679 lldb_private::StreamString stream; 2680 stream.PutCString("vFile:open:"); 2681 std::string path (file_spec.GetPath()); 2682 if (path.empty()) 2683 return UINT64_MAX; 2684 stream.PutCStringAsRawHex8(path.c_str()); 2685 stream.PutChar(','); 2686 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags); 2687 stream.PutHex32(posix_open_flags); 2688 stream.PutChar(','); 2689 stream.PutHex32(mode); 2690 const char* packet = stream.GetData(); 2691 int packet_len = stream.GetSize(); 2692 StringExtractorGDBRemote response; 2693 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2694 { 2695 return ParseHostIOPacketResponse (response, UINT64_MAX, error); 2696 } 2697 return UINT64_MAX; 2698 } 2699 2700 bool 2701 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd, 2702 Error &error) 2703 { 2704 lldb_private::StreamString stream; 2705 stream.Printf("vFile:close:%i", (int)fd); 2706 const char* packet = stream.GetData(); 2707 int packet_len = stream.GetSize(); 2708 StringExtractorGDBRemote response; 2709 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2710 { 2711 return ParseHostIOPacketResponse (response, -1, error) == 0; 2712 } 2713 return false; 2714 } 2715 2716 // Extension of host I/O packets to get the file size. 2717 lldb::user_id_t 2718 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec) 2719 { 2720 lldb_private::StreamString stream; 2721 stream.PutCString("vFile:size:"); 2722 std::string path (file_spec.GetPath()); 2723 stream.PutCStringAsRawHex8(path.c_str()); 2724 const char* packet = stream.GetData(); 2725 int packet_len = stream.GetSize(); 2726 StringExtractorGDBRemote response; 2727 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2728 { 2729 if (response.GetChar() != 'F') 2730 return UINT64_MAX; 2731 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 2732 return retcode; 2733 } 2734 return UINT64_MAX; 2735 } 2736 2737 Error 2738 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions) 2739 { 2740 Error error; 2741 lldb_private::StreamString stream; 2742 stream.PutCString("vFile:mode:"); 2743 stream.PutCStringAsRawHex8(path); 2744 const char* packet = stream.GetData(); 2745 int packet_len = stream.GetSize(); 2746 StringExtractorGDBRemote response; 2747 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2748 { 2749 if (response.GetChar() != 'F') 2750 { 2751 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet); 2752 } 2753 else 2754 { 2755 const uint32_t mode = response.GetS32(-1); 2756 if (mode == -1) 2757 { 2758 if (response.GetChar() == ',') 2759 { 2760 int response_errno = response.GetS32(-1); 2761 if (response_errno > 0) 2762 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2763 else 2764 error.SetErrorToGenericError(); 2765 } 2766 else 2767 error.SetErrorToGenericError(); 2768 } 2769 else 2770 { 2771 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO); 2772 } 2773 } 2774 } 2775 else 2776 { 2777 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet); 2778 } 2779 return error; 2780 } 2781 2782 uint64_t 2783 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd, 2784 uint64_t offset, 2785 void *dst, 2786 uint64_t dst_len, 2787 Error &error) 2788 { 2789 lldb_private::StreamString stream; 2790 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset); 2791 const char* packet = stream.GetData(); 2792 int packet_len = stream.GetSize(); 2793 StringExtractorGDBRemote response; 2794 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2795 { 2796 if (response.GetChar() != 'F') 2797 return 0; 2798 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 2799 if (retcode == UINT32_MAX) 2800 return retcode; 2801 const char next = (response.Peek() ? *response.Peek() : 0); 2802 if (next == ',') 2803 return 0; 2804 if (next == ';') 2805 { 2806 response.GetChar(); // skip the semicolon 2807 std::string buffer; 2808 if (response.GetEscapedBinaryData(buffer)) 2809 { 2810 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size()); 2811 if (data_to_write > 0) 2812 memcpy(dst, &buffer[0], data_to_write); 2813 return data_to_write; 2814 } 2815 } 2816 } 2817 return 0; 2818 } 2819 2820 uint64_t 2821 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd, 2822 uint64_t offset, 2823 const void* src, 2824 uint64_t src_len, 2825 Error &error) 2826 { 2827 lldb_private::StreamGDBRemote stream; 2828 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 2829 stream.PutEscapedBytes(src, src_len); 2830 const char* packet = stream.GetData(); 2831 int packet_len = stream.GetSize(); 2832 StringExtractorGDBRemote response; 2833 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2834 { 2835 if (response.GetChar() != 'F') 2836 { 2837 error.SetErrorStringWithFormat("write file failed"); 2838 return 0; 2839 } 2840 uint64_t bytes_written = response.GetU64(UINT64_MAX); 2841 if (bytes_written == UINT64_MAX) 2842 { 2843 error.SetErrorToGenericError(); 2844 if (response.GetChar() == ',') 2845 { 2846 int response_errno = response.GetS32(-1); 2847 if (response_errno > 0) 2848 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2849 } 2850 return 0; 2851 } 2852 return bytes_written; 2853 } 2854 else 2855 { 2856 error.SetErrorString ("failed to send vFile:pwrite packet"); 2857 } 2858 return 0; 2859 } 2860 2861 Error 2862 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst) 2863 { 2864 Error error; 2865 lldb_private::StreamGDBRemote stream; 2866 stream.PutCString("vFile:symlink:"); 2867 // the unix symlink() command reverses its parameters where the dst if first, 2868 // so we follow suit here 2869 stream.PutCStringAsRawHex8(dst); 2870 stream.PutChar(','); 2871 stream.PutCStringAsRawHex8(src); 2872 const char* packet = stream.GetData(); 2873 int packet_len = stream.GetSize(); 2874 StringExtractorGDBRemote response; 2875 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2876 { 2877 if (response.GetChar() == 'F') 2878 { 2879 uint32_t result = response.GetU32(UINT32_MAX); 2880 if (result != 0) 2881 { 2882 error.SetErrorToGenericError(); 2883 if (response.GetChar() == ',') 2884 { 2885 int response_errno = response.GetS32(-1); 2886 if (response_errno > 0) 2887 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2888 } 2889 } 2890 } 2891 else 2892 { 2893 // Should have returned with 'F<result>[,<errno>]' 2894 error.SetErrorStringWithFormat("symlink failed"); 2895 } 2896 } 2897 else 2898 { 2899 error.SetErrorString ("failed to send vFile:symlink packet"); 2900 } 2901 return error; 2902 } 2903 2904 Error 2905 GDBRemoteCommunicationClient::Unlink (const char *path) 2906 { 2907 Error error; 2908 lldb_private::StreamGDBRemote stream; 2909 stream.PutCString("vFile:unlink:"); 2910 // the unix symlink() command reverses its parameters where the dst if first, 2911 // so we follow suit here 2912 stream.PutCStringAsRawHex8(path); 2913 const char* packet = stream.GetData(); 2914 int packet_len = stream.GetSize(); 2915 StringExtractorGDBRemote response; 2916 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2917 { 2918 if (response.GetChar() == 'F') 2919 { 2920 uint32_t result = response.GetU32(UINT32_MAX); 2921 if (result != 0) 2922 { 2923 error.SetErrorToGenericError(); 2924 if (response.GetChar() == ',') 2925 { 2926 int response_errno = response.GetS32(-1); 2927 if (response_errno > 0) 2928 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2929 } 2930 } 2931 } 2932 else 2933 { 2934 // Should have returned with 'F<result>[,<errno>]' 2935 error.SetErrorStringWithFormat("unlink failed"); 2936 } 2937 } 2938 else 2939 { 2940 error.SetErrorString ("failed to send vFile:unlink packet"); 2941 } 2942 return error; 2943 } 2944 2945 // Extension of host I/O packets to get whether a file exists. 2946 bool 2947 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec) 2948 { 2949 lldb_private::StreamString stream; 2950 stream.PutCString("vFile:exists:"); 2951 std::string path (file_spec.GetPath()); 2952 stream.PutCStringAsRawHex8(path.c_str()); 2953 const char* packet = stream.GetData(); 2954 int packet_len = stream.GetSize(); 2955 StringExtractorGDBRemote response; 2956 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2957 { 2958 if (response.GetChar() != 'F') 2959 return false; 2960 if (response.GetChar() != ',') 2961 return false; 2962 bool retcode = (response.GetChar() != '0'); 2963 return retcode; 2964 } 2965 return false; 2966 } 2967 2968 bool 2969 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec, 2970 uint64_t &high, 2971 uint64_t &low) 2972 { 2973 lldb_private::StreamString stream; 2974 stream.PutCString("vFile:MD5:"); 2975 std::string path (file_spec.GetPath()); 2976 stream.PutCStringAsRawHex8(path.c_str()); 2977 const char* packet = stream.GetData(); 2978 int packet_len = stream.GetSize(); 2979 StringExtractorGDBRemote response; 2980 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2981 { 2982 if (response.GetChar() != 'F') 2983 return false; 2984 if (response.GetChar() != ',') 2985 return false; 2986 if (response.Peek() && *response.Peek() == 'x') 2987 return false; 2988 low = response.GetHexMaxU64(false, UINT64_MAX); 2989 high = response.GetHexMaxU64(false, UINT64_MAX); 2990 return true; 2991 } 2992 return false; 2993 } 2994 2995 bool 2996 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response) 2997 { 2998 Mutex::Locker locker; 2999 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet.")) 3000 { 3001 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3002 3003 if (thread_suffix_supported || SetCurrentThread(tid)) 3004 { 3005 char packet[64]; 3006 int packet_len = 0; 3007 if (thread_suffix_supported) 3008 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid); 3009 else 3010 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg); 3011 assert (packet_len < ((int)sizeof(packet) - 1)); 3012 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3013 } 3014 } 3015 return false; 3016 3017 } 3018 3019 3020 bool 3021 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response) 3022 { 3023 Mutex::Locker locker; 3024 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet.")) 3025 { 3026 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3027 3028 if (thread_suffix_supported || SetCurrentThread(tid)) 3029 { 3030 char packet[64]; 3031 int packet_len = 0; 3032 // Get all registers in one packet 3033 if (thread_suffix_supported) 3034 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid); 3035 else 3036 packet_len = ::snprintf (packet, sizeof(packet), "g"); 3037 assert (packet_len < ((int)sizeof(packet) - 1)); 3038 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3039 } 3040 } 3041 return false; 3042 } 3043 bool 3044 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id) 3045 { 3046 save_id = 0; // Set to invalid save ID 3047 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3048 return false; 3049 3050 m_supports_QSaveRegisterState = eLazyBoolYes; 3051 Mutex::Locker locker; 3052 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState.")) 3053 { 3054 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3055 if (thread_suffix_supported || SetCurrentThread(tid)) 3056 { 3057 char packet[256]; 3058 if (thread_suffix_supported) 3059 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid); 3060 else 3061 ::strncpy (packet, "QSaveRegisterState", sizeof(packet)); 3062 3063 StringExtractorGDBRemote response; 3064 3065 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3066 { 3067 if (response.IsUnsupportedResponse()) 3068 { 3069 // This packet isn't supported, don't try calling it again 3070 m_supports_QSaveRegisterState = eLazyBoolNo; 3071 } 3072 3073 const uint32_t response_save_id = response.GetU32(0); 3074 if (response_save_id != 0) 3075 { 3076 save_id = response_save_id; 3077 return true; 3078 } 3079 } 3080 } 3081 } 3082 return false; 3083 } 3084 3085 bool 3086 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id) 3087 { 3088 // We use the "m_supports_QSaveRegisterState" variable here becuase the 3089 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in 3090 // order to be useful 3091 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3092 return false; 3093 3094 Mutex::Locker locker; 3095 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState.")) 3096 { 3097 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3098 if (thread_suffix_supported || SetCurrentThread(tid)) 3099 { 3100 char packet[256]; 3101 if (thread_suffix_supported) 3102 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid); 3103 else 3104 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id); 3105 3106 StringExtractorGDBRemote response; 3107 3108 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3109 { 3110 if (response.IsOKResponse()) 3111 { 3112 return true; 3113 } 3114 else if (response.IsUnsupportedResponse()) 3115 { 3116 // This packet isn't supported, don't try calling this packet or 3117 // QSaveRegisterState again... 3118 m_supports_QSaveRegisterState = eLazyBoolNo; 3119 } 3120 } 3121 } 3122 } 3123 return false; 3124 } 3125