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