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