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 std::string distribution_id; 1258 uint32_t pointer_byte_size = 0; 1259 StringExtractor extractor; 1260 ByteOrder byte_order = eByteOrderInvalid; 1261 uint32_t num_keys_decoded = 0; 1262 while (response.GetNameColonValue(name, value)) 1263 { 1264 if (name.compare("cputype") == 0) 1265 { 1266 // exception type in big endian hex 1267 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0); 1268 if (cpu != LLDB_INVALID_CPUTYPE) 1269 ++num_keys_decoded; 1270 } 1271 else if (name.compare("cpusubtype") == 0) 1272 { 1273 // exception count in big endian hex 1274 sub = Args::StringToUInt32 (value.c_str(), 0, 0); 1275 if (sub != 0) 1276 ++num_keys_decoded; 1277 } 1278 else if (name.compare("arch") == 0) 1279 { 1280 arch_name.swap (value); 1281 ++num_keys_decoded; 1282 } 1283 else if (name.compare("triple") == 0) 1284 { 1285 // The triple comes as ASCII hex bytes since it contains '-' chars 1286 extractor.GetStringRef().swap(value); 1287 extractor.SetFilePos(0); 1288 extractor.GetHexByteString (triple); 1289 ++num_keys_decoded; 1290 } 1291 else if (name.compare ("distribution_id") == 0) 1292 { 1293 extractor.GetStringRef ().swap (value); 1294 extractor.SetFilePos (0); 1295 extractor.GetHexByteString (distribution_id); 1296 ++num_keys_decoded; 1297 } 1298 else if (name.compare("os_build") == 0) 1299 { 1300 extractor.GetStringRef().swap(value); 1301 extractor.SetFilePos(0); 1302 extractor.GetHexByteString (m_os_build); 1303 ++num_keys_decoded; 1304 } 1305 else if (name.compare("hostname") == 0) 1306 { 1307 extractor.GetStringRef().swap(value); 1308 extractor.SetFilePos(0); 1309 extractor.GetHexByteString (m_hostname); 1310 ++num_keys_decoded; 1311 } 1312 else if (name.compare("os_kernel") == 0) 1313 { 1314 extractor.GetStringRef().swap(value); 1315 extractor.SetFilePos(0); 1316 extractor.GetHexByteString (m_os_kernel); 1317 ++num_keys_decoded; 1318 } 1319 else if (name.compare("ostype") == 0) 1320 { 1321 os_name.swap (value); 1322 ++num_keys_decoded; 1323 } 1324 else if (name.compare("vendor") == 0) 1325 { 1326 vendor_name.swap(value); 1327 ++num_keys_decoded; 1328 } 1329 else if (name.compare("endian") == 0) 1330 { 1331 ++num_keys_decoded; 1332 if (value.compare("little") == 0) 1333 byte_order = eByteOrderLittle; 1334 else if (value.compare("big") == 0) 1335 byte_order = eByteOrderBig; 1336 else if (value.compare("pdp") == 0) 1337 byte_order = eByteOrderPDP; 1338 else 1339 --num_keys_decoded; 1340 } 1341 else if (name.compare("ptrsize") == 0) 1342 { 1343 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0); 1344 if (pointer_byte_size != 0) 1345 ++num_keys_decoded; 1346 } 1347 else if (name.compare("os_version") == 0) 1348 { 1349 Args::StringToVersion (value.c_str(), 1350 m_os_version_major, 1351 m_os_version_minor, 1352 m_os_version_update); 1353 if (m_os_version_major != UINT32_MAX) 1354 ++num_keys_decoded; 1355 } 1356 else if (name.compare("watchpoint_exceptions_received") == 0) 1357 { 1358 ++num_keys_decoded; 1359 if (strcmp(value.c_str(),"before") == 0) 1360 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 1361 else if (strcmp(value.c_str(),"after") == 0) 1362 m_watchpoints_trigger_after_instruction = eLazyBoolYes; 1363 else 1364 --num_keys_decoded; 1365 } 1366 else if (name.compare("default_packet_timeout") == 0) 1367 { 1368 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0); 1369 if (m_default_packet_timeout > 0) 1370 { 1371 SetPacketTimeout(m_default_packet_timeout); 1372 ++num_keys_decoded; 1373 } 1374 } 1375 1376 } 1377 1378 if (num_keys_decoded > 0) 1379 m_qHostInfo_is_valid = eLazyBoolYes; 1380 1381 if (triple.empty()) 1382 { 1383 if (arch_name.empty()) 1384 { 1385 if (cpu != LLDB_INVALID_CPUTYPE) 1386 { 1387 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 1388 if (pointer_byte_size) 1389 { 1390 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1391 } 1392 if (byte_order != eByteOrderInvalid) 1393 { 1394 assert (byte_order == m_host_arch.GetByteOrder()); 1395 } 1396 1397 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0) 1398 { 1399 switch (m_host_arch.GetMachine()) 1400 { 1401 case llvm::Triple::arm: 1402 case llvm::Triple::thumb: 1403 os_name = "ios"; 1404 break; 1405 default: 1406 os_name = "macosx"; 1407 break; 1408 } 1409 } 1410 if (!vendor_name.empty()) 1411 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 1412 if (!os_name.empty()) 1413 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 1414 1415 } 1416 } 1417 else 1418 { 1419 std::string triple; 1420 triple += arch_name; 1421 if (!vendor_name.empty() || !os_name.empty()) 1422 { 1423 triple += '-'; 1424 if (vendor_name.empty()) 1425 triple += "unknown"; 1426 else 1427 triple += vendor_name; 1428 triple += '-'; 1429 if (os_name.empty()) 1430 triple += "unknown"; 1431 else 1432 triple += os_name; 1433 } 1434 m_host_arch.SetTriple (triple.c_str()); 1435 1436 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1437 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin) 1438 { 1439 switch (m_host_arch.GetMachine()) 1440 { 1441 case llvm::Triple::arm: 1442 case llvm::Triple::thumb: 1443 host_triple.setOS(llvm::Triple::IOS); 1444 break; 1445 default: 1446 host_triple.setOS(llvm::Triple::MacOSX); 1447 break; 1448 } 1449 } 1450 if (pointer_byte_size) 1451 { 1452 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1453 } 1454 if (byte_order != eByteOrderInvalid) 1455 { 1456 assert (byte_order == m_host_arch.GetByteOrder()); 1457 } 1458 1459 } 1460 } 1461 else 1462 { 1463 m_host_arch.SetTriple (triple.c_str()); 1464 if (pointer_byte_size) 1465 { 1466 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 1467 } 1468 if (byte_order != eByteOrderInvalid) 1469 { 1470 assert (byte_order == m_host_arch.GetByteOrder()); 1471 } 1472 } 1473 if (!distribution_id.empty ()) 1474 m_host_arch.SetDistributionId (distribution_id.c_str ()); 1475 } 1476 } 1477 } 1478 return m_qHostInfo_is_valid == eLazyBoolYes; 1479 } 1480 1481 int 1482 GDBRemoteCommunicationClient::SendAttach 1483 ( 1484 lldb::pid_t pid, 1485 StringExtractorGDBRemote& response 1486 ) 1487 { 1488 if (pid != LLDB_INVALID_PROCESS_ID) 1489 { 1490 char packet[64]; 1491 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid); 1492 assert (packet_len < (int)sizeof(packet)); 1493 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1494 { 1495 if (response.IsErrorResponse()) 1496 return response.GetError(); 1497 return 0; 1498 } 1499 } 1500 return -1; 1501 } 1502 1503 const lldb_private::ArchSpec & 1504 GDBRemoteCommunicationClient::GetHostArchitecture () 1505 { 1506 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1507 GetHostInfo (); 1508 return m_host_arch; 1509 } 1510 1511 uint32_t 1512 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout () 1513 { 1514 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1515 GetHostInfo (); 1516 return m_default_packet_timeout; 1517 } 1518 1519 addr_t 1520 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions) 1521 { 1522 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1523 { 1524 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1525 char packet[64]; 1526 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", 1527 (uint64_t)size, 1528 permissions & lldb::ePermissionsReadable ? "r" : "", 1529 permissions & lldb::ePermissionsWritable ? "w" : "", 1530 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1531 assert (packet_len < (int)sizeof(packet)); 1532 StringExtractorGDBRemote response; 1533 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1534 { 1535 if (!response.IsErrorResponse()) 1536 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1537 } 1538 else 1539 { 1540 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1541 } 1542 } 1543 return LLDB_INVALID_ADDRESS; 1544 } 1545 1546 bool 1547 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 1548 { 1549 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1550 { 1551 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1552 char packet[64]; 1553 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1554 assert (packet_len < (int)sizeof(packet)); 1555 StringExtractorGDBRemote response; 1556 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1557 { 1558 if (response.IsOKResponse()) 1559 return true; 1560 } 1561 else 1562 { 1563 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1564 } 1565 } 1566 return false; 1567 } 1568 1569 Error 1570 GDBRemoteCommunicationClient::Detach (bool keep_stopped) 1571 { 1572 Error error; 1573 1574 if (keep_stopped) 1575 { 1576 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) 1577 { 1578 char packet[64]; 1579 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1580 assert (packet_len < (int)sizeof(packet)); 1581 StringExtractorGDBRemote response; 1582 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1583 { 1584 m_supports_detach_stay_stopped = eLazyBoolYes; 1585 } 1586 else 1587 { 1588 m_supports_detach_stay_stopped = eLazyBoolNo; 1589 } 1590 } 1591 1592 if (m_supports_detach_stay_stopped == eLazyBoolNo) 1593 { 1594 error.SetErrorString("Stays stopped not supported by this target."); 1595 return error; 1596 } 1597 else 1598 { 1599 PacketResult packet_result = SendPacket ("D1", 2); 1600 if (packet_result != PacketResult::Success) 1601 error.SetErrorString ("Sending extended disconnect packet failed."); 1602 } 1603 } 1604 else 1605 { 1606 PacketResult packet_result = SendPacket ("D", 1); 1607 if (packet_result != PacketResult::Success) 1608 error.SetErrorString ("Sending disconnect packet failed."); 1609 } 1610 return error; 1611 } 1612 1613 Error 1614 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 1615 lldb_private::MemoryRegionInfo ®ion_info) 1616 { 1617 Error error; 1618 region_info.Clear(); 1619 1620 if (m_supports_memory_region_info != eLazyBoolNo) 1621 { 1622 m_supports_memory_region_info = eLazyBoolYes; 1623 char packet[64]; 1624 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1625 assert (packet_len < (int)sizeof(packet)); 1626 StringExtractorGDBRemote response; 1627 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1628 { 1629 std::string name; 1630 std::string value; 1631 addr_t addr_value; 1632 bool success = true; 1633 bool saw_permissions = false; 1634 while (success && response.GetNameColonValue(name, value)) 1635 { 1636 if (name.compare ("start") == 0) 1637 { 1638 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 1639 if (success) 1640 region_info.GetRange().SetRangeBase(addr_value); 1641 } 1642 else if (name.compare ("size") == 0) 1643 { 1644 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success); 1645 if (success) 1646 region_info.GetRange().SetByteSize (addr_value); 1647 } 1648 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 1649 { 1650 saw_permissions = true; 1651 if (region_info.GetRange().Contains (addr)) 1652 { 1653 if (value.find('r') != std::string::npos) 1654 region_info.SetReadable (MemoryRegionInfo::eYes); 1655 else 1656 region_info.SetReadable (MemoryRegionInfo::eNo); 1657 1658 if (value.find('w') != std::string::npos) 1659 region_info.SetWritable (MemoryRegionInfo::eYes); 1660 else 1661 region_info.SetWritable (MemoryRegionInfo::eNo); 1662 1663 if (value.find('x') != std::string::npos) 1664 region_info.SetExecutable (MemoryRegionInfo::eYes); 1665 else 1666 region_info.SetExecutable (MemoryRegionInfo::eNo); 1667 } 1668 else 1669 { 1670 // The reported region does not contain this address -- we're looking at an unmapped page 1671 region_info.SetReadable (MemoryRegionInfo::eNo); 1672 region_info.SetWritable (MemoryRegionInfo::eNo); 1673 region_info.SetExecutable (MemoryRegionInfo::eNo); 1674 } 1675 } 1676 else if (name.compare ("error") == 0) 1677 { 1678 StringExtractorGDBRemote name_extractor; 1679 // Swap "value" over into "name_extractor" 1680 name_extractor.GetStringRef().swap(value); 1681 // Now convert the HEX bytes into a string value 1682 name_extractor.GetHexByteString (value); 1683 error.SetErrorString(value.c_str()); 1684 } 1685 } 1686 1687 // We got a valid address range back but no permissions -- which means this is an unmapped page 1688 if (region_info.GetRange().IsValid() && saw_permissions == false) 1689 { 1690 region_info.SetReadable (MemoryRegionInfo::eNo); 1691 region_info.SetWritable (MemoryRegionInfo::eNo); 1692 region_info.SetExecutable (MemoryRegionInfo::eNo); 1693 } 1694 } 1695 else 1696 { 1697 m_supports_memory_region_info = eLazyBoolNo; 1698 } 1699 } 1700 1701 if (m_supports_memory_region_info == eLazyBoolNo) 1702 { 1703 error.SetErrorString("qMemoryRegionInfo is not supported"); 1704 } 1705 if (error.Fail()) 1706 region_info.Clear(); 1707 return error; 1708 1709 } 1710 1711 Error 1712 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 1713 { 1714 Error error; 1715 1716 if (m_supports_watchpoint_support_info == eLazyBoolYes) 1717 { 1718 num = m_num_supported_hardware_watchpoints; 1719 return error; 1720 } 1721 1722 // Set num to 0 first. 1723 num = 0; 1724 if (m_supports_watchpoint_support_info != eLazyBoolNo) 1725 { 1726 char packet[64]; 1727 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1728 assert (packet_len < (int)sizeof(packet)); 1729 StringExtractorGDBRemote response; 1730 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1731 { 1732 m_supports_watchpoint_support_info = eLazyBoolYes; 1733 std::string name; 1734 std::string value; 1735 while (response.GetNameColonValue(name, value)) 1736 { 1737 if (name.compare ("num") == 0) 1738 { 1739 num = Args::StringToUInt32(value.c_str(), 0, 0); 1740 m_num_supported_hardware_watchpoints = num; 1741 } 1742 } 1743 } 1744 else 1745 { 1746 m_supports_watchpoint_support_info = eLazyBoolNo; 1747 } 1748 } 1749 1750 if (m_supports_watchpoint_support_info == eLazyBoolNo) 1751 { 1752 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1753 } 1754 return error; 1755 1756 } 1757 1758 lldb_private::Error 1759 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after) 1760 { 1761 Error error(GetWatchpointSupportInfo(num)); 1762 if (error.Success()) 1763 error = GetWatchpointsTriggerAfterInstruction(after); 1764 return error; 1765 } 1766 1767 lldb_private::Error 1768 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after) 1769 { 1770 Error error; 1771 1772 // we assume watchpoints will happen after running the relevant opcode 1773 // and we only want to override this behavior if we have explicitly 1774 // received a qHostInfo telling us otherwise 1775 if (m_qHostInfo_is_valid != eLazyBoolYes) 1776 after = true; 1777 else 1778 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1779 return error; 1780 } 1781 1782 int 1783 GDBRemoteCommunicationClient::SetSTDIN (char const *path) 1784 { 1785 if (path && path[0]) 1786 { 1787 StreamString packet; 1788 packet.PutCString("QSetSTDIN:"); 1789 packet.PutBytesAsRawHex8(path, strlen(path)); 1790 1791 StringExtractorGDBRemote response; 1792 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1793 { 1794 if (response.IsOKResponse()) 1795 return 0; 1796 uint8_t error = response.GetError(); 1797 if (error) 1798 return error; 1799 } 1800 } 1801 return -1; 1802 } 1803 1804 int 1805 GDBRemoteCommunicationClient::SetSTDOUT (char const *path) 1806 { 1807 if (path && path[0]) 1808 { 1809 StreamString packet; 1810 packet.PutCString("QSetSTDOUT:"); 1811 packet.PutBytesAsRawHex8(path, strlen(path)); 1812 1813 StringExtractorGDBRemote response; 1814 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1815 { 1816 if (response.IsOKResponse()) 1817 return 0; 1818 uint8_t error = response.GetError(); 1819 if (error) 1820 return error; 1821 } 1822 } 1823 return -1; 1824 } 1825 1826 int 1827 GDBRemoteCommunicationClient::SetSTDERR (char const *path) 1828 { 1829 if (path && path[0]) 1830 { 1831 StreamString packet; 1832 packet.PutCString("QSetSTDERR:"); 1833 packet.PutBytesAsRawHex8(path, strlen(path)); 1834 1835 StringExtractorGDBRemote response; 1836 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1837 { 1838 if (response.IsOKResponse()) 1839 return 0; 1840 uint8_t error = response.GetError(); 1841 if (error) 1842 return error; 1843 } 1844 } 1845 return -1; 1846 } 1847 1848 bool 1849 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd) 1850 { 1851 StringExtractorGDBRemote response; 1852 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success) 1853 { 1854 if (response.IsUnsupportedResponse()) 1855 return false; 1856 if (response.IsErrorResponse()) 1857 return false; 1858 response.GetHexByteString (cwd); 1859 return !cwd.empty(); 1860 } 1861 return false; 1862 } 1863 1864 int 1865 GDBRemoteCommunicationClient::SetWorkingDir (char const *path) 1866 { 1867 if (path && path[0]) 1868 { 1869 StreamString packet; 1870 packet.PutCString("QSetWorkingDir:"); 1871 packet.PutBytesAsRawHex8(path, strlen(path)); 1872 1873 StringExtractorGDBRemote response; 1874 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 1875 { 1876 if (response.IsOKResponse()) 1877 return 0; 1878 uint8_t error = response.GetError(); 1879 if (error) 1880 return error; 1881 } 1882 } 1883 return -1; 1884 } 1885 1886 int 1887 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 1888 { 1889 char packet[32]; 1890 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1891 assert (packet_len < (int)sizeof(packet)); 1892 StringExtractorGDBRemote response; 1893 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1894 { 1895 if (response.IsOKResponse()) 1896 return 0; 1897 uint8_t error = response.GetError(); 1898 if (error) 1899 return error; 1900 } 1901 return -1; 1902 } 1903 1904 bool 1905 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 1906 { 1907 if (response.IsNormalResponse()) 1908 { 1909 std::string name; 1910 std::string value; 1911 StringExtractor extractor; 1912 1913 while (response.GetNameColonValue(name, value)) 1914 { 1915 if (name.compare("pid") == 0) 1916 { 1917 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1918 } 1919 else if (name.compare("ppid") == 0) 1920 { 1921 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 1922 } 1923 else if (name.compare("uid") == 0) 1924 { 1925 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1926 } 1927 else if (name.compare("euid") == 0) 1928 { 1929 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1930 } 1931 else if (name.compare("gid") == 0) 1932 { 1933 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1934 } 1935 else if (name.compare("egid") == 0) 1936 { 1937 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 1938 } 1939 else if (name.compare("triple") == 0) 1940 { 1941 // The triple comes as ASCII hex bytes since it contains '-' chars 1942 extractor.GetStringRef().swap(value); 1943 extractor.SetFilePos(0); 1944 extractor.GetHexByteString (value); 1945 process_info.GetArchitecture ().SetTriple (value.c_str()); 1946 } 1947 else if (name.compare("name") == 0) 1948 { 1949 StringExtractor extractor; 1950 // The process name from ASCII hex bytes since we can't 1951 // control the characters in a process name 1952 extractor.GetStringRef().swap(value); 1953 extractor.SetFilePos(0); 1954 extractor.GetHexByteString (value); 1955 process_info.GetExecutableFile().SetFile (value.c_str(), false); 1956 } 1957 } 1958 1959 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1960 return true; 1961 } 1962 return false; 1963 } 1964 1965 bool 1966 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1967 { 1968 process_info.Clear(); 1969 1970 if (m_supports_qProcessInfoPID) 1971 { 1972 char packet[32]; 1973 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid); 1974 assert (packet_len < (int)sizeof(packet)); 1975 StringExtractorGDBRemote response; 1976 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1977 { 1978 return DecodeProcessInfoResponse (response, process_info); 1979 } 1980 else 1981 { 1982 m_supports_qProcessInfoPID = false; 1983 return false; 1984 } 1985 } 1986 return false; 1987 } 1988 1989 bool 1990 GDBRemoteCommunicationClient::GetCurrentProcessInfo () 1991 { 1992 if (m_qProcessInfo_is_valid == eLazyBoolYes) 1993 return true; 1994 if (m_qProcessInfo_is_valid == eLazyBoolNo) 1995 return false; 1996 1997 GetHostInfo (); 1998 1999 StringExtractorGDBRemote response; 2000 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success) 2001 { 2002 if (response.IsNormalResponse()) 2003 { 2004 std::string name; 2005 std::string value; 2006 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2007 uint32_t sub = 0; 2008 std::string arch_name; 2009 std::string os_name; 2010 std::string vendor_name; 2011 std::string triple; 2012 uint32_t pointer_byte_size = 0; 2013 StringExtractor extractor; 2014 ByteOrder byte_order = eByteOrderInvalid; 2015 uint32_t num_keys_decoded = 0; 2016 while (response.GetNameColonValue(name, value)) 2017 { 2018 if (name.compare("cputype") == 0) 2019 { 2020 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2021 if (cpu != LLDB_INVALID_CPUTYPE) 2022 ++num_keys_decoded; 2023 } 2024 else if (name.compare("cpusubtype") == 0) 2025 { 2026 sub = Args::StringToUInt32 (value.c_str(), 0, 16); 2027 if (sub != 0) 2028 ++num_keys_decoded; 2029 } 2030 else if (name.compare("ostype") == 0) 2031 { 2032 os_name.swap (value); 2033 ++num_keys_decoded; 2034 } 2035 else if (name.compare("vendor") == 0) 2036 { 2037 vendor_name.swap(value); 2038 ++num_keys_decoded; 2039 } 2040 else if (name.compare("endian") == 0) 2041 { 2042 ++num_keys_decoded; 2043 if (value.compare("little") == 0) 2044 byte_order = eByteOrderLittle; 2045 else if (value.compare("big") == 0) 2046 byte_order = eByteOrderBig; 2047 else if (value.compare("pdp") == 0) 2048 byte_order = eByteOrderPDP; 2049 else 2050 --num_keys_decoded; 2051 } 2052 else if (name.compare("ptrsize") == 0) 2053 { 2054 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16); 2055 if (pointer_byte_size != 0) 2056 ++num_keys_decoded; 2057 } 2058 } 2059 if (num_keys_decoded > 0) 2060 m_qProcessInfo_is_valid = eLazyBoolYes; 2061 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty()) 2062 { 2063 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 2064 if (pointer_byte_size) 2065 { 2066 assert (pointer_byte_size == m_process_arch.GetAddressByteSize()); 2067 } 2068 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2069 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 2070 return true; 2071 } 2072 } 2073 } 2074 else 2075 { 2076 m_qProcessInfo_is_valid = eLazyBoolNo; 2077 } 2078 2079 return false; 2080 } 2081 2082 2083 uint32_t 2084 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 2085 ProcessInstanceInfoList &process_infos) 2086 { 2087 process_infos.Clear(); 2088 2089 if (m_supports_qfProcessInfo) 2090 { 2091 StreamString packet; 2092 packet.PutCString ("qfProcessInfo"); 2093 if (!match_info.MatchAllProcesses()) 2094 { 2095 packet.PutChar (':'); 2096 const char *name = match_info.GetProcessInfo().GetName(); 2097 bool has_name_match = false; 2098 if (name && name[0]) 2099 { 2100 has_name_match = true; 2101 NameMatchType name_match_type = match_info.GetNameMatchType(); 2102 switch (name_match_type) 2103 { 2104 case eNameMatchIgnore: 2105 has_name_match = false; 2106 break; 2107 2108 case eNameMatchEquals: 2109 packet.PutCString ("name_match:equals;"); 2110 break; 2111 2112 case eNameMatchContains: 2113 packet.PutCString ("name_match:contains;"); 2114 break; 2115 2116 case eNameMatchStartsWith: 2117 packet.PutCString ("name_match:starts_with;"); 2118 break; 2119 2120 case eNameMatchEndsWith: 2121 packet.PutCString ("name_match:ends_with;"); 2122 break; 2123 2124 case eNameMatchRegularExpression: 2125 packet.PutCString ("name_match:regex;"); 2126 break; 2127 } 2128 if (has_name_match) 2129 { 2130 packet.PutCString ("name:"); 2131 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2132 packet.PutChar (';'); 2133 } 2134 } 2135 2136 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2137 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID()); 2138 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2139 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID()); 2140 if (match_info.GetProcessInfo().UserIDIsValid()) 2141 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 2142 if (match_info.GetProcessInfo().GroupIDIsValid()) 2143 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 2144 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2145 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 2146 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2147 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 2148 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2149 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 2150 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 2151 { 2152 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 2153 const llvm::Triple &triple = match_arch.GetTriple(); 2154 packet.PutCString("triple:"); 2155 packet.PutCStringAsRawHex8(triple.getTriple().c_str()); 2156 packet.PutChar (';'); 2157 } 2158 } 2159 StringExtractorGDBRemote response; 2160 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2161 { 2162 do 2163 { 2164 ProcessInstanceInfo process_info; 2165 if (!DecodeProcessInfoResponse (response, process_info)) 2166 break; 2167 process_infos.Append(process_info); 2168 response.GetStringRef().clear(); 2169 response.SetFilePos(0); 2170 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success); 2171 } 2172 else 2173 { 2174 m_supports_qfProcessInfo = false; 2175 return 0; 2176 } 2177 } 2178 return process_infos.GetSize(); 2179 2180 } 2181 2182 bool 2183 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 2184 { 2185 if (m_supports_qUserName) 2186 { 2187 char packet[32]; 2188 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 2189 assert (packet_len < (int)sizeof(packet)); 2190 StringExtractorGDBRemote response; 2191 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2192 { 2193 if (response.IsNormalResponse()) 2194 { 2195 // Make sure we parsed the right number of characters. The response is 2196 // the hex encoded user name and should make up the entire packet. 2197 // If there are any non-hex ASCII bytes, the length won't match below.. 2198 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2199 return true; 2200 } 2201 } 2202 else 2203 { 2204 m_supports_qUserName = false; 2205 return false; 2206 } 2207 } 2208 return false; 2209 2210 } 2211 2212 bool 2213 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 2214 { 2215 if (m_supports_qGroupName) 2216 { 2217 char packet[32]; 2218 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 2219 assert (packet_len < (int)sizeof(packet)); 2220 StringExtractorGDBRemote response; 2221 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2222 { 2223 if (response.IsNormalResponse()) 2224 { 2225 // Make sure we parsed the right number of characters. The response is 2226 // the hex encoded group name and should make up the entire packet. 2227 // If there are any non-hex ASCII bytes, the length won't match below.. 2228 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2229 return true; 2230 } 2231 } 2232 else 2233 { 2234 m_supports_qGroupName = false; 2235 return false; 2236 } 2237 } 2238 return false; 2239 } 2240 2241 void 2242 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets) 2243 { 2244 uint32_t i; 2245 TimeValue start_time, end_time; 2246 uint64_t total_time_nsec; 2247 float packets_per_second; 2248 if (SendSpeedTestPacket (0, 0)) 2249 { 2250 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2) 2251 { 2252 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2) 2253 { 2254 start_time = TimeValue::Now(); 2255 for (i=0; i<num_packets; ++i) 2256 { 2257 SendSpeedTestPacket (send_size, recv_size); 2258 } 2259 end_time = TimeValue::Now(); 2260 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 2261 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 2262 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n", 2263 num_packets, 2264 send_size, 2265 recv_size, 2266 total_time_nsec / TimeValue::NanoSecPerSec, 2267 total_time_nsec % TimeValue::NanoSecPerSec, 2268 packets_per_second); 2269 if (recv_size == 0) 2270 recv_size = 32; 2271 } 2272 if (send_size == 0) 2273 send_size = 32; 2274 } 2275 } 2276 else 2277 { 2278 start_time = TimeValue::Now(); 2279 for (i=0; i<num_packets; ++i) 2280 { 2281 GetCurrentProcessID (); 2282 } 2283 end_time = TimeValue::Now(); 2284 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 2285 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 2286 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n", 2287 num_packets, 2288 total_time_nsec / TimeValue::NanoSecPerSec, 2289 total_time_nsec % TimeValue::NanoSecPerSec, 2290 packets_per_second); 2291 } 2292 } 2293 2294 bool 2295 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 2296 { 2297 StreamString packet; 2298 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 2299 uint32_t bytes_left = send_size; 2300 while (bytes_left > 0) 2301 { 2302 if (bytes_left >= 26) 2303 { 2304 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2305 bytes_left -= 26; 2306 } 2307 else 2308 { 2309 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 2310 bytes_left = 0; 2311 } 2312 } 2313 2314 StringExtractorGDBRemote response; 2315 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success; 2316 } 2317 2318 uint16_t 2319 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname) 2320 { 2321 pid = LLDB_INVALID_PROCESS_ID; 2322 StringExtractorGDBRemote response; 2323 StreamString stream; 2324 stream.PutCString("qLaunchGDBServer;"); 2325 std::string hostname; 2326 if (remote_accept_hostname && remote_accept_hostname[0]) 2327 hostname = remote_accept_hostname; 2328 else 2329 { 2330 if (Host::GetHostname (hostname)) 2331 { 2332 // Make the GDB server we launch only accept connections from this host 2333 stream.Printf("host:%s;", hostname.c_str()); 2334 } 2335 else 2336 { 2337 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname 2338 stream.Printf("host:*;"); 2339 } 2340 } 2341 const char *packet = stream.GetData(); 2342 int packet_len = stream.GetSize(); 2343 2344 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2345 { 2346 std::string name; 2347 std::string value; 2348 uint16_t port = 0; 2349 while (response.GetNameColonValue(name, value)) 2350 { 2351 if (name.compare("port") == 0) 2352 port = Args::StringToUInt32(value.c_str(), 0, 0); 2353 else if (name.compare("pid") == 0) 2354 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 2355 } 2356 return port; 2357 } 2358 return 0; 2359 } 2360 2361 bool 2362 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid) 2363 { 2364 StreamString stream; 2365 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid); 2366 const char *packet = stream.GetData(); 2367 int packet_len = stream.GetSize(); 2368 2369 StringExtractorGDBRemote response; 2370 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2371 { 2372 if (response.IsOKResponse()) 2373 return true; 2374 } 2375 return false; 2376 } 2377 2378 bool 2379 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid) 2380 { 2381 if (m_curr_tid == tid) 2382 return true; 2383 2384 char packet[32]; 2385 int packet_len; 2386 if (tid == UINT64_MAX) 2387 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1"); 2388 else 2389 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid); 2390 assert (packet_len + 1 < (int)sizeof(packet)); 2391 StringExtractorGDBRemote response; 2392 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2393 { 2394 if (response.IsOKResponse()) 2395 { 2396 m_curr_tid = tid; 2397 return true; 2398 } 2399 } 2400 return false; 2401 } 2402 2403 bool 2404 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid) 2405 { 2406 if (m_curr_tid_run == tid) 2407 return true; 2408 2409 char packet[32]; 2410 int packet_len; 2411 if (tid == UINT64_MAX) 2412 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1"); 2413 else 2414 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid); 2415 2416 assert (packet_len + 1 < (int)sizeof(packet)); 2417 StringExtractorGDBRemote response; 2418 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2419 { 2420 if (response.IsOKResponse()) 2421 { 2422 m_curr_tid_run = tid; 2423 return true; 2424 } 2425 } 2426 return false; 2427 } 2428 2429 bool 2430 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 2431 { 2432 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success) 2433 return response.IsNormalResponse(); 2434 return false; 2435 } 2436 2437 bool 2438 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response) 2439 { 2440 if (m_supports_qThreadStopInfo) 2441 { 2442 char packet[256]; 2443 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2444 assert (packet_len < (int)sizeof(packet)); 2445 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2446 { 2447 if (response.IsUnsupportedResponse()) 2448 m_supports_qThreadStopInfo = false; 2449 else if (response.IsNormalResponse()) 2450 return true; 2451 else 2452 return false; 2453 } 2454 else 2455 { 2456 m_supports_qThreadStopInfo = false; 2457 } 2458 } 2459 return false; 2460 } 2461 2462 2463 uint8_t 2464 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 2465 { 2466 switch (type) 2467 { 2468 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break; 2469 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break; 2470 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break; 2471 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break; 2472 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break; 2473 } 2474 2475 char packet[64]; 2476 const int packet_len = ::snprintf (packet, 2477 sizeof(packet), 2478 "%c%i,%" PRIx64 ",%x", 2479 insert ? 'Z' : 'z', 2480 type, 2481 addr, 2482 length); 2483 2484 assert (packet_len + 1 < (int)sizeof(packet)); 2485 StringExtractorGDBRemote response; 2486 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success) 2487 { 2488 if (response.IsOKResponse()) 2489 return 0; 2490 else if (response.IsErrorResponse()) 2491 return response.GetError(); 2492 } 2493 else 2494 { 2495 switch (type) 2496 { 2497 case eBreakpointSoftware: m_supports_z0 = false; break; 2498 case eBreakpointHardware: m_supports_z1 = false; break; 2499 case eWatchpointWrite: m_supports_z2 = false; break; 2500 case eWatchpointRead: m_supports_z3 = false; break; 2501 case eWatchpointReadWrite: m_supports_z4 = false; break; 2502 } 2503 } 2504 2505 return UINT8_MAX; 2506 } 2507 2508 size_t 2509 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 2510 bool &sequence_mutex_unavailable) 2511 { 2512 Mutex::Locker locker; 2513 thread_ids.clear(); 2514 2515 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 2516 { 2517 sequence_mutex_unavailable = false; 2518 StringExtractorGDBRemote response; 2519 2520 PacketResult packet_result; 2521 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response); 2522 packet_result == PacketResult::Success && response.IsNormalResponse(); 2523 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response)) 2524 { 2525 char ch = response.GetChar(); 2526 if (ch == 'l') 2527 break; 2528 if (ch == 'm') 2529 { 2530 do 2531 { 2532 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2533 2534 if (tid != LLDB_INVALID_THREAD_ID) 2535 { 2536 thread_ids.push_back (tid); 2537 } 2538 ch = response.GetChar(); // Skip the command separator 2539 } while (ch == ','); // Make sure we got a comma separator 2540 } 2541 } 2542 } 2543 else 2544 { 2545 #if defined (LLDB_CONFIGURATION_DEBUG) 2546 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 2547 #else 2548 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2549 if (log) 2550 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 2551 #endif 2552 sequence_mutex_unavailable = true; 2553 } 2554 return thread_ids.size(); 2555 } 2556 2557 lldb::addr_t 2558 GDBRemoteCommunicationClient::GetShlibInfoAddr() 2559 { 2560 if (!IsRunning()) 2561 { 2562 StringExtractorGDBRemote response; 2563 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success) 2564 { 2565 if (response.IsNormalResponse()) 2566 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2567 } 2568 } 2569 return LLDB_INVALID_ADDRESS; 2570 } 2571 2572 lldb_private::Error 2573 GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL 2574 const char *working_dir, // Pass NULL to use the current working directory 2575 int *status_ptr, // Pass NULL if you don't want the process exit status 2576 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit 2577 std::string *command_output, // Pass NULL if you don't want the command output 2578 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish 2579 { 2580 lldb_private::StreamString stream; 2581 stream.PutCString("qPlatform_shell:"); 2582 stream.PutBytesAsRawHex8(command, strlen(command)); 2583 stream.PutChar(','); 2584 stream.PutHex32(timeout_sec); 2585 if (working_dir && *working_dir) 2586 { 2587 stream.PutChar(','); 2588 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 2589 } 2590 const char *packet = stream.GetData(); 2591 int packet_len = stream.GetSize(); 2592 StringExtractorGDBRemote response; 2593 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2594 { 2595 if (response.GetChar() != 'F') 2596 return Error("malformed reply"); 2597 if (response.GetChar() != ',') 2598 return Error("malformed reply"); 2599 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2600 if (exitcode == UINT32_MAX) 2601 return Error("unable to run remote process"); 2602 else if (status_ptr) 2603 *status_ptr = exitcode; 2604 if (response.GetChar() != ',') 2605 return Error("malformed reply"); 2606 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2607 if (signo_ptr) 2608 *signo_ptr = signo; 2609 if (response.GetChar() != ',') 2610 return Error("malformed reply"); 2611 std::string output; 2612 response.GetEscapedBinaryData(output); 2613 if (command_output) 2614 command_output->assign(output); 2615 return Error(); 2616 } 2617 return Error("unable to send packet"); 2618 } 2619 2620 Error 2621 GDBRemoteCommunicationClient::MakeDirectory (const char *path, 2622 uint32_t file_permissions) 2623 { 2624 lldb_private::StreamString stream; 2625 stream.PutCString("qPlatform_mkdir:"); 2626 stream.PutHex32(file_permissions); 2627 stream.PutChar(','); 2628 stream.PutBytesAsRawHex8(path, strlen(path)); 2629 const char *packet = stream.GetData(); 2630 int packet_len = stream.GetSize(); 2631 StringExtractorGDBRemote response; 2632 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2633 { 2634 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2635 } 2636 return Error(); 2637 2638 } 2639 2640 Error 2641 GDBRemoteCommunicationClient::SetFilePermissions (const char *path, 2642 uint32_t file_permissions) 2643 { 2644 lldb_private::StreamString stream; 2645 stream.PutCString("qPlatform_chmod:"); 2646 stream.PutHex32(file_permissions); 2647 stream.PutChar(','); 2648 stream.PutBytesAsRawHex8(path, strlen(path)); 2649 const char *packet = stream.GetData(); 2650 int packet_len = stream.GetSize(); 2651 StringExtractorGDBRemote response; 2652 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2653 { 2654 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2655 } 2656 return Error(); 2657 2658 } 2659 2660 static uint64_t 2661 ParseHostIOPacketResponse (StringExtractorGDBRemote &response, 2662 uint64_t fail_result, 2663 Error &error) 2664 { 2665 response.SetFilePos(0); 2666 if (response.GetChar() != 'F') 2667 return fail_result; 2668 int32_t result = response.GetS32 (-2); 2669 if (result == -2) 2670 return fail_result; 2671 if (response.GetChar() == ',') 2672 { 2673 int result_errno = response.GetS32 (-2); 2674 if (result_errno != -2) 2675 error.SetError(result_errno, eErrorTypePOSIX); 2676 else 2677 error.SetError(-1, eErrorTypeGeneric); 2678 } 2679 else 2680 error.Clear(); 2681 return result; 2682 } 2683 lldb::user_id_t 2684 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec, 2685 uint32_t flags, 2686 mode_t mode, 2687 Error &error) 2688 { 2689 lldb_private::StreamString stream; 2690 stream.PutCString("vFile:open:"); 2691 std::string path (file_spec.GetPath()); 2692 if (path.empty()) 2693 return UINT64_MAX; 2694 stream.PutCStringAsRawHex8(path.c_str()); 2695 stream.PutChar(','); 2696 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags); 2697 stream.PutHex32(posix_open_flags); 2698 stream.PutChar(','); 2699 stream.PutHex32(mode); 2700 const char* packet = stream.GetData(); 2701 int packet_len = stream.GetSize(); 2702 StringExtractorGDBRemote response; 2703 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2704 { 2705 return ParseHostIOPacketResponse (response, UINT64_MAX, error); 2706 } 2707 return UINT64_MAX; 2708 } 2709 2710 bool 2711 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd, 2712 Error &error) 2713 { 2714 lldb_private::StreamString stream; 2715 stream.Printf("vFile:close:%i", (int)fd); 2716 const char* packet = stream.GetData(); 2717 int packet_len = stream.GetSize(); 2718 StringExtractorGDBRemote response; 2719 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2720 { 2721 return ParseHostIOPacketResponse (response, -1, error) == 0; 2722 } 2723 return false; 2724 } 2725 2726 // Extension of host I/O packets to get the file size. 2727 lldb::user_id_t 2728 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec) 2729 { 2730 lldb_private::StreamString stream; 2731 stream.PutCString("vFile:size:"); 2732 std::string path (file_spec.GetPath()); 2733 stream.PutCStringAsRawHex8(path.c_str()); 2734 const char* packet = stream.GetData(); 2735 int packet_len = stream.GetSize(); 2736 StringExtractorGDBRemote response; 2737 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2738 { 2739 if (response.GetChar() != 'F') 2740 return UINT64_MAX; 2741 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 2742 return retcode; 2743 } 2744 return UINT64_MAX; 2745 } 2746 2747 Error 2748 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions) 2749 { 2750 Error error; 2751 lldb_private::StreamString stream; 2752 stream.PutCString("vFile:mode:"); 2753 stream.PutCStringAsRawHex8(path); 2754 const char* packet = stream.GetData(); 2755 int packet_len = stream.GetSize(); 2756 StringExtractorGDBRemote response; 2757 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2758 { 2759 if (response.GetChar() != 'F') 2760 { 2761 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet); 2762 } 2763 else 2764 { 2765 const uint32_t mode = response.GetS32(-1); 2766 if (mode == -1) 2767 { 2768 if (response.GetChar() == ',') 2769 { 2770 int response_errno = response.GetS32(-1); 2771 if (response_errno > 0) 2772 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2773 else 2774 error.SetErrorToGenericError(); 2775 } 2776 else 2777 error.SetErrorToGenericError(); 2778 } 2779 else 2780 { 2781 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO); 2782 } 2783 } 2784 } 2785 else 2786 { 2787 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet); 2788 } 2789 return error; 2790 } 2791 2792 uint64_t 2793 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd, 2794 uint64_t offset, 2795 void *dst, 2796 uint64_t dst_len, 2797 Error &error) 2798 { 2799 lldb_private::StreamString stream; 2800 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset); 2801 const char* packet = stream.GetData(); 2802 int packet_len = stream.GetSize(); 2803 StringExtractorGDBRemote response; 2804 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2805 { 2806 if (response.GetChar() != 'F') 2807 return 0; 2808 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 2809 if (retcode == UINT32_MAX) 2810 return retcode; 2811 const char next = (response.Peek() ? *response.Peek() : 0); 2812 if (next == ',') 2813 return 0; 2814 if (next == ';') 2815 { 2816 response.GetChar(); // skip the semicolon 2817 std::string buffer; 2818 if (response.GetEscapedBinaryData(buffer)) 2819 { 2820 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size()); 2821 if (data_to_write > 0) 2822 memcpy(dst, &buffer[0], data_to_write); 2823 return data_to_write; 2824 } 2825 } 2826 } 2827 return 0; 2828 } 2829 2830 uint64_t 2831 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd, 2832 uint64_t offset, 2833 const void* src, 2834 uint64_t src_len, 2835 Error &error) 2836 { 2837 lldb_private::StreamGDBRemote stream; 2838 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 2839 stream.PutEscapedBytes(src, src_len); 2840 const char* packet = stream.GetData(); 2841 int packet_len = stream.GetSize(); 2842 StringExtractorGDBRemote response; 2843 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2844 { 2845 if (response.GetChar() != 'F') 2846 { 2847 error.SetErrorStringWithFormat("write file failed"); 2848 return 0; 2849 } 2850 uint64_t bytes_written = response.GetU64(UINT64_MAX); 2851 if (bytes_written == UINT64_MAX) 2852 { 2853 error.SetErrorToGenericError(); 2854 if (response.GetChar() == ',') 2855 { 2856 int response_errno = response.GetS32(-1); 2857 if (response_errno > 0) 2858 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2859 } 2860 return 0; 2861 } 2862 return bytes_written; 2863 } 2864 else 2865 { 2866 error.SetErrorString ("failed to send vFile:pwrite packet"); 2867 } 2868 return 0; 2869 } 2870 2871 Error 2872 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst) 2873 { 2874 Error error; 2875 lldb_private::StreamGDBRemote stream; 2876 stream.PutCString("vFile:symlink:"); 2877 // the unix symlink() command reverses its parameters where the dst if first, 2878 // so we follow suit here 2879 stream.PutCStringAsRawHex8(dst); 2880 stream.PutChar(','); 2881 stream.PutCStringAsRawHex8(src); 2882 const char* packet = stream.GetData(); 2883 int packet_len = stream.GetSize(); 2884 StringExtractorGDBRemote response; 2885 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2886 { 2887 if (response.GetChar() == 'F') 2888 { 2889 uint32_t result = response.GetU32(UINT32_MAX); 2890 if (result != 0) 2891 { 2892 error.SetErrorToGenericError(); 2893 if (response.GetChar() == ',') 2894 { 2895 int response_errno = response.GetS32(-1); 2896 if (response_errno > 0) 2897 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2898 } 2899 } 2900 } 2901 else 2902 { 2903 // Should have returned with 'F<result>[,<errno>]' 2904 error.SetErrorStringWithFormat("symlink failed"); 2905 } 2906 } 2907 else 2908 { 2909 error.SetErrorString ("failed to send vFile:symlink packet"); 2910 } 2911 return error; 2912 } 2913 2914 Error 2915 GDBRemoteCommunicationClient::Unlink (const char *path) 2916 { 2917 Error error; 2918 lldb_private::StreamGDBRemote stream; 2919 stream.PutCString("vFile:unlink:"); 2920 // the unix symlink() command reverses its parameters where the dst if first, 2921 // so we follow suit here 2922 stream.PutCStringAsRawHex8(path); 2923 const char* packet = stream.GetData(); 2924 int packet_len = stream.GetSize(); 2925 StringExtractorGDBRemote response; 2926 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2927 { 2928 if (response.GetChar() == 'F') 2929 { 2930 uint32_t result = response.GetU32(UINT32_MAX); 2931 if (result != 0) 2932 { 2933 error.SetErrorToGenericError(); 2934 if (response.GetChar() == ',') 2935 { 2936 int response_errno = response.GetS32(-1); 2937 if (response_errno > 0) 2938 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2939 } 2940 } 2941 } 2942 else 2943 { 2944 // Should have returned with 'F<result>[,<errno>]' 2945 error.SetErrorStringWithFormat("unlink failed"); 2946 } 2947 } 2948 else 2949 { 2950 error.SetErrorString ("failed to send vFile:unlink packet"); 2951 } 2952 return error; 2953 } 2954 2955 // Extension of host I/O packets to get whether a file exists. 2956 bool 2957 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec) 2958 { 2959 lldb_private::StreamString stream; 2960 stream.PutCString("vFile:exists:"); 2961 std::string path (file_spec.GetPath()); 2962 stream.PutCStringAsRawHex8(path.c_str()); 2963 const char* packet = stream.GetData(); 2964 int packet_len = stream.GetSize(); 2965 StringExtractorGDBRemote response; 2966 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2967 { 2968 if (response.GetChar() != 'F') 2969 return false; 2970 if (response.GetChar() != ',') 2971 return false; 2972 bool retcode = (response.GetChar() != '0'); 2973 return retcode; 2974 } 2975 return false; 2976 } 2977 2978 bool 2979 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec, 2980 uint64_t &high, 2981 uint64_t &low) 2982 { 2983 lldb_private::StreamString stream; 2984 stream.PutCString("vFile:MD5:"); 2985 std::string path (file_spec.GetPath()); 2986 stream.PutCStringAsRawHex8(path.c_str()); 2987 const char* packet = stream.GetData(); 2988 int packet_len = stream.GetSize(); 2989 StringExtractorGDBRemote response; 2990 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2991 { 2992 if (response.GetChar() != 'F') 2993 return false; 2994 if (response.GetChar() != ',') 2995 return false; 2996 if (response.Peek() && *response.Peek() == 'x') 2997 return false; 2998 low = response.GetHexMaxU64(false, UINT64_MAX); 2999 high = response.GetHexMaxU64(false, UINT64_MAX); 3000 return true; 3001 } 3002 return false; 3003 } 3004 3005 bool 3006 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response) 3007 { 3008 Mutex::Locker locker; 3009 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet.")) 3010 { 3011 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3012 3013 if (thread_suffix_supported || SetCurrentThread(tid)) 3014 { 3015 char packet[64]; 3016 int packet_len = 0; 3017 if (thread_suffix_supported) 3018 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid); 3019 else 3020 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg); 3021 assert (packet_len < ((int)sizeof(packet) - 1)); 3022 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3023 } 3024 } 3025 return false; 3026 3027 } 3028 3029 3030 bool 3031 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response) 3032 { 3033 Mutex::Locker locker; 3034 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet.")) 3035 { 3036 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3037 3038 if (thread_suffix_supported || SetCurrentThread(tid)) 3039 { 3040 char packet[64]; 3041 int packet_len = 0; 3042 // Get all registers in one packet 3043 if (thread_suffix_supported) 3044 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid); 3045 else 3046 packet_len = ::snprintf (packet, sizeof(packet), "g"); 3047 assert (packet_len < ((int)sizeof(packet) - 1)); 3048 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3049 } 3050 } 3051 return false; 3052 } 3053 bool 3054 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id) 3055 { 3056 save_id = 0; // Set to invalid save ID 3057 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3058 return false; 3059 3060 m_supports_QSaveRegisterState = eLazyBoolYes; 3061 Mutex::Locker locker; 3062 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState.")) 3063 { 3064 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3065 if (thread_suffix_supported || SetCurrentThread(tid)) 3066 { 3067 char packet[256]; 3068 if (thread_suffix_supported) 3069 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid); 3070 else 3071 ::strncpy (packet, "QSaveRegisterState", sizeof(packet)); 3072 3073 StringExtractorGDBRemote response; 3074 3075 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3076 { 3077 if (response.IsUnsupportedResponse()) 3078 { 3079 // This packet isn't supported, don't try calling it again 3080 m_supports_QSaveRegisterState = eLazyBoolNo; 3081 } 3082 3083 const uint32_t response_save_id = response.GetU32(0); 3084 if (response_save_id != 0) 3085 { 3086 save_id = response_save_id; 3087 return true; 3088 } 3089 } 3090 } 3091 } 3092 return false; 3093 } 3094 3095 bool 3096 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id) 3097 { 3098 // We use the "m_supports_QSaveRegisterState" variable here becuase the 3099 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in 3100 // order to be useful 3101 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3102 return false; 3103 3104 Mutex::Locker locker; 3105 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState.")) 3106 { 3107 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3108 if (thread_suffix_supported || SetCurrentThread(tid)) 3109 { 3110 char packet[256]; 3111 if (thread_suffix_supported) 3112 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid); 3113 else 3114 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id); 3115 3116 StringExtractorGDBRemote response; 3117 3118 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3119 { 3120 if (response.IsOKResponse()) 3121 { 3122 return true; 3123 } 3124 else if (response.IsUnsupportedResponse()) 3125 { 3126 // This packet isn't supported, don't try calling this packet or 3127 // QSaveRegisterState again... 3128 m_supports_QSaveRegisterState = eLazyBoolNo; 3129 } 3130 } 3131 } 3132 } 3133 return false; 3134 } 3135