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