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.IsErrorResponse()) 1885 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1886 } 1887 else 1888 { 1889 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1890 } 1891 } 1892 return LLDB_INVALID_ADDRESS; 1893 } 1894 1895 bool 1896 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 1897 { 1898 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 1899 { 1900 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1901 char packet[64]; 1902 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1903 assert (packet_len < (int)sizeof(packet)); 1904 StringExtractorGDBRemote response; 1905 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1906 { 1907 if (response.IsOKResponse()) 1908 return true; 1909 } 1910 else 1911 { 1912 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1913 } 1914 } 1915 return false; 1916 } 1917 1918 Error 1919 GDBRemoteCommunicationClient::Detach (bool keep_stopped) 1920 { 1921 Error error; 1922 1923 if (keep_stopped) 1924 { 1925 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) 1926 { 1927 char packet[64]; 1928 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1929 assert (packet_len < (int)sizeof(packet)); 1930 StringExtractorGDBRemote response; 1931 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1932 { 1933 m_supports_detach_stay_stopped = eLazyBoolYes; 1934 } 1935 else 1936 { 1937 m_supports_detach_stay_stopped = eLazyBoolNo; 1938 } 1939 } 1940 1941 if (m_supports_detach_stay_stopped == eLazyBoolNo) 1942 { 1943 error.SetErrorString("Stays stopped not supported by this target."); 1944 return error; 1945 } 1946 else 1947 { 1948 StringExtractorGDBRemote response; 1949 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false); 1950 if (packet_result != PacketResult::Success) 1951 error.SetErrorString ("Sending extended disconnect packet failed."); 1952 } 1953 } 1954 else 1955 { 1956 StringExtractorGDBRemote response; 1957 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false); 1958 if (packet_result != PacketResult::Success) 1959 error.SetErrorString ("Sending disconnect packet failed."); 1960 } 1961 return error; 1962 } 1963 1964 Error 1965 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 1966 lldb_private::MemoryRegionInfo ®ion_info) 1967 { 1968 Error error; 1969 region_info.Clear(); 1970 1971 if (m_supports_memory_region_info != eLazyBoolNo) 1972 { 1973 m_supports_memory_region_info = eLazyBoolYes; 1974 char packet[64]; 1975 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1976 assert (packet_len < (int)sizeof(packet)); 1977 StringExtractorGDBRemote response; 1978 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 1979 { 1980 std::string name; 1981 std::string value; 1982 addr_t addr_value; 1983 bool success = true; 1984 bool saw_permissions = false; 1985 while (success && response.GetNameColonValue(name, value)) 1986 { 1987 if (name.compare ("start") == 0) 1988 { 1989 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 1990 if (success) 1991 region_info.GetRange().SetRangeBase(addr_value); 1992 } 1993 else if (name.compare ("size") == 0) 1994 { 1995 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success); 1996 if (success) 1997 region_info.GetRange().SetByteSize (addr_value); 1998 } 1999 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 2000 { 2001 saw_permissions = true; 2002 if (region_info.GetRange().Contains (addr)) 2003 { 2004 if (value.find('r') != std::string::npos) 2005 region_info.SetReadable (MemoryRegionInfo::eYes); 2006 else 2007 region_info.SetReadable (MemoryRegionInfo::eNo); 2008 2009 if (value.find('w') != std::string::npos) 2010 region_info.SetWritable (MemoryRegionInfo::eYes); 2011 else 2012 region_info.SetWritable (MemoryRegionInfo::eNo); 2013 2014 if (value.find('x') != std::string::npos) 2015 region_info.SetExecutable (MemoryRegionInfo::eYes); 2016 else 2017 region_info.SetExecutable (MemoryRegionInfo::eNo); 2018 } 2019 else 2020 { 2021 // The reported region does not contain this address -- we're looking at an unmapped page 2022 region_info.SetReadable (MemoryRegionInfo::eNo); 2023 region_info.SetWritable (MemoryRegionInfo::eNo); 2024 region_info.SetExecutable (MemoryRegionInfo::eNo); 2025 } 2026 } 2027 else if (name.compare ("error") == 0) 2028 { 2029 StringExtractorGDBRemote name_extractor; 2030 // Swap "value" over into "name_extractor" 2031 name_extractor.GetStringRef().swap(value); 2032 // Now convert the HEX bytes into a string value 2033 name_extractor.GetHexByteString (value); 2034 error.SetErrorString(value.c_str()); 2035 } 2036 } 2037 2038 // We got a valid address range back but no permissions -- which means this is an unmapped page 2039 if (region_info.GetRange().IsValid() && saw_permissions == false) 2040 { 2041 region_info.SetReadable (MemoryRegionInfo::eNo); 2042 region_info.SetWritable (MemoryRegionInfo::eNo); 2043 region_info.SetExecutable (MemoryRegionInfo::eNo); 2044 } 2045 } 2046 else 2047 { 2048 m_supports_memory_region_info = eLazyBoolNo; 2049 } 2050 } 2051 2052 if (m_supports_memory_region_info == eLazyBoolNo) 2053 { 2054 error.SetErrorString("qMemoryRegionInfo is not supported"); 2055 } 2056 if (error.Fail()) 2057 region_info.Clear(); 2058 return error; 2059 2060 } 2061 2062 Error 2063 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 2064 { 2065 Error error; 2066 2067 if (m_supports_watchpoint_support_info == eLazyBoolYes) 2068 { 2069 num = m_num_supported_hardware_watchpoints; 2070 return error; 2071 } 2072 2073 // Set num to 0 first. 2074 num = 0; 2075 if (m_supports_watchpoint_support_info != eLazyBoolNo) 2076 { 2077 char packet[64]; 2078 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 2079 assert (packet_len < (int)sizeof(packet)); 2080 StringExtractorGDBRemote response; 2081 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2082 { 2083 m_supports_watchpoint_support_info = eLazyBoolYes; 2084 std::string name; 2085 std::string value; 2086 while (response.GetNameColonValue(name, value)) 2087 { 2088 if (name.compare ("num") == 0) 2089 { 2090 num = Args::StringToUInt32(value.c_str(), 0, 0); 2091 m_num_supported_hardware_watchpoints = num; 2092 } 2093 } 2094 } 2095 else 2096 { 2097 m_supports_watchpoint_support_info = eLazyBoolNo; 2098 } 2099 } 2100 2101 if (m_supports_watchpoint_support_info == eLazyBoolNo) 2102 { 2103 error.SetErrorString("qWatchpointSupportInfo is not supported"); 2104 } 2105 return error; 2106 2107 } 2108 2109 lldb_private::Error 2110 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after) 2111 { 2112 Error error(GetWatchpointSupportInfo(num)); 2113 if (error.Success()) 2114 error = GetWatchpointsTriggerAfterInstruction(after); 2115 return error; 2116 } 2117 2118 lldb_private::Error 2119 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after) 2120 { 2121 Error error; 2122 2123 // we assume watchpoints will happen after running the relevant opcode 2124 // and we only want to override this behavior if we have explicitly 2125 // received a qHostInfo telling us otherwise 2126 if (m_qHostInfo_is_valid != eLazyBoolYes) 2127 after = true; 2128 else 2129 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 2130 return error; 2131 } 2132 2133 int 2134 GDBRemoteCommunicationClient::SetSTDIN (char const *path) 2135 { 2136 if (path && path[0]) 2137 { 2138 StreamString packet; 2139 packet.PutCString("QSetSTDIN:"); 2140 packet.PutBytesAsRawHex8(path, strlen(path)); 2141 2142 StringExtractorGDBRemote response; 2143 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2144 { 2145 if (response.IsOKResponse()) 2146 return 0; 2147 uint8_t error = response.GetError(); 2148 if (error) 2149 return error; 2150 } 2151 } 2152 return -1; 2153 } 2154 2155 int 2156 GDBRemoteCommunicationClient::SetSTDOUT (char const *path) 2157 { 2158 if (path && path[0]) 2159 { 2160 StreamString packet; 2161 packet.PutCString("QSetSTDOUT:"); 2162 packet.PutBytesAsRawHex8(path, strlen(path)); 2163 2164 StringExtractorGDBRemote response; 2165 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2166 { 2167 if (response.IsOKResponse()) 2168 return 0; 2169 uint8_t error = response.GetError(); 2170 if (error) 2171 return error; 2172 } 2173 } 2174 return -1; 2175 } 2176 2177 int 2178 GDBRemoteCommunicationClient::SetSTDERR (char const *path) 2179 { 2180 if (path && path[0]) 2181 { 2182 StreamString packet; 2183 packet.PutCString("QSetSTDERR:"); 2184 packet.PutBytesAsRawHex8(path, strlen(path)); 2185 2186 StringExtractorGDBRemote response; 2187 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2188 { 2189 if (response.IsOKResponse()) 2190 return 0; 2191 uint8_t error = response.GetError(); 2192 if (error) 2193 return error; 2194 } 2195 } 2196 return -1; 2197 } 2198 2199 bool 2200 GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd) 2201 { 2202 StringExtractorGDBRemote response; 2203 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success) 2204 { 2205 if (response.IsUnsupportedResponse()) 2206 return false; 2207 if (response.IsErrorResponse()) 2208 return false; 2209 response.GetHexByteString (cwd); 2210 return !cwd.empty(); 2211 } 2212 return false; 2213 } 2214 2215 int 2216 GDBRemoteCommunicationClient::SetWorkingDir (char const *path) 2217 { 2218 if (path && path[0]) 2219 { 2220 StreamString packet; 2221 packet.PutCString("QSetWorkingDir:"); 2222 packet.PutBytesAsRawHex8(path, strlen(path)); 2223 2224 StringExtractorGDBRemote response; 2225 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2226 { 2227 if (response.IsOKResponse()) 2228 return 0; 2229 uint8_t error = response.GetError(); 2230 if (error) 2231 return error; 2232 } 2233 } 2234 return -1; 2235 } 2236 2237 int 2238 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 2239 { 2240 char packet[32]; 2241 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 2242 assert (packet_len < (int)sizeof(packet)); 2243 StringExtractorGDBRemote response; 2244 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2245 { 2246 if (response.IsOKResponse()) 2247 return 0; 2248 uint8_t error = response.GetError(); 2249 if (error) 2250 return error; 2251 } 2252 return -1; 2253 } 2254 2255 bool 2256 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 2257 { 2258 if (response.IsNormalResponse()) 2259 { 2260 std::string name; 2261 std::string value; 2262 StringExtractor extractor; 2263 2264 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2265 uint32_t sub = 0; 2266 std::string vendor; 2267 std::string os_type; 2268 2269 while (response.GetNameColonValue(name, value)) 2270 { 2271 if (name.compare("pid") == 0) 2272 { 2273 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 2274 } 2275 else if (name.compare("ppid") == 0) 2276 { 2277 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 2278 } 2279 else if (name.compare("uid") == 0) 2280 { 2281 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 2282 } 2283 else if (name.compare("euid") == 0) 2284 { 2285 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 2286 } 2287 else if (name.compare("gid") == 0) 2288 { 2289 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 2290 } 2291 else if (name.compare("egid") == 0) 2292 { 2293 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0)); 2294 } 2295 else if (name.compare("triple") == 0) 2296 { 2297 // The triple comes as ASCII hex bytes since it contains '-' chars 2298 extractor.GetStringRef().swap(value); 2299 extractor.SetFilePos(0); 2300 extractor.GetHexByteString (value); 2301 process_info.GetArchitecture ().SetTriple (value.c_str()); 2302 } 2303 else if (name.compare("name") == 0) 2304 { 2305 StringExtractor extractor; 2306 // The process name from ASCII hex bytes since we can't 2307 // control the characters in a process name 2308 extractor.GetStringRef().swap(value); 2309 extractor.SetFilePos(0); 2310 extractor.GetHexByteString (value); 2311 process_info.GetExecutableFile().SetFile (value.c_str(), false); 2312 } 2313 else if (name.compare("cputype") == 0) 2314 { 2315 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2316 } 2317 else if (name.compare("cpusubtype") == 0) 2318 { 2319 sub = Args::StringToUInt32 (value.c_str(), 0, 16); 2320 } 2321 else if (name.compare("vendor") == 0) 2322 { 2323 vendor = value; 2324 } 2325 else if (name.compare("ostype") == 0) 2326 { 2327 os_type = value; 2328 } 2329 } 2330 2331 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) 2332 { 2333 if (vendor == "apple") 2334 { 2335 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub); 2336 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor)); 2337 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type)); 2338 } 2339 } 2340 2341 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 2342 return true; 2343 } 2344 return false; 2345 } 2346 2347 bool 2348 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 2349 { 2350 process_info.Clear(); 2351 2352 if (m_supports_qProcessInfoPID) 2353 { 2354 char packet[32]; 2355 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid); 2356 assert (packet_len < (int)sizeof(packet)); 2357 StringExtractorGDBRemote response; 2358 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2359 { 2360 return DecodeProcessInfoResponse (response, process_info); 2361 } 2362 else 2363 { 2364 m_supports_qProcessInfoPID = false; 2365 return false; 2366 } 2367 } 2368 return false; 2369 } 2370 2371 bool 2372 GDBRemoteCommunicationClient::GetCurrentProcessInfo () 2373 { 2374 if (m_qProcessInfo_is_valid == eLazyBoolYes) 2375 return true; 2376 if (m_qProcessInfo_is_valid == eLazyBoolNo) 2377 return false; 2378 2379 GetHostInfo (); 2380 2381 StringExtractorGDBRemote response; 2382 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success) 2383 { 2384 if (response.IsNormalResponse()) 2385 { 2386 std::string name; 2387 std::string value; 2388 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2389 uint32_t sub = 0; 2390 std::string arch_name; 2391 std::string os_name; 2392 std::string vendor_name; 2393 std::string triple; 2394 uint32_t pointer_byte_size = 0; 2395 StringExtractor extractor; 2396 uint32_t num_keys_decoded = 0; 2397 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2398 while (response.GetNameColonValue(name, value)) 2399 { 2400 if (name.compare("cputype") == 0) 2401 { 2402 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2403 if (cpu != LLDB_INVALID_CPUTYPE) 2404 ++num_keys_decoded; 2405 } 2406 else if (name.compare("cpusubtype") == 0) 2407 { 2408 sub = Args::StringToUInt32 (value.c_str(), 0, 16); 2409 if (sub != 0) 2410 ++num_keys_decoded; 2411 } 2412 else if (name.compare("ostype") == 0) 2413 { 2414 os_name.swap (value); 2415 ++num_keys_decoded; 2416 } 2417 else if (name.compare("vendor") == 0) 2418 { 2419 vendor_name.swap(value); 2420 ++num_keys_decoded; 2421 } 2422 else if (name.compare("endian") == 0) 2423 { 2424 if (value.compare("little") == 0 || 2425 value.compare("big") == 0 || 2426 value.compare("pdp") == 0) 2427 ++num_keys_decoded; 2428 } 2429 else if (name.compare("ptrsize") == 0) 2430 { 2431 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16); 2432 if (pointer_byte_size != 0) 2433 ++num_keys_decoded; 2434 } 2435 else if (name.compare("pid") == 0) 2436 { 2437 pid = Args::StringToUInt64(value.c_str(), 0, 16); 2438 if (pid != LLDB_INVALID_PROCESS_ID) 2439 ++num_keys_decoded; 2440 } 2441 } 2442 if (num_keys_decoded > 0) 2443 m_qProcessInfo_is_valid = eLazyBoolYes; 2444 if (pid != LLDB_INVALID_PROCESS_ID) 2445 { 2446 m_curr_pid_is_valid = eLazyBoolYes; 2447 m_curr_pid = pid; 2448 } 2449 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty()) 2450 { 2451 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 2452 if (pointer_byte_size) 2453 { 2454 assert (pointer_byte_size == m_process_arch.GetAddressByteSize()); 2455 } 2456 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name)); 2457 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2458 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 2459 } 2460 return true; 2461 } 2462 } 2463 else 2464 { 2465 m_qProcessInfo_is_valid = eLazyBoolNo; 2466 } 2467 2468 return false; 2469 } 2470 2471 2472 uint32_t 2473 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 2474 ProcessInstanceInfoList &process_infos) 2475 { 2476 process_infos.Clear(); 2477 2478 if (m_supports_qfProcessInfo) 2479 { 2480 StreamString packet; 2481 packet.PutCString ("qfProcessInfo"); 2482 if (!match_info.MatchAllProcesses()) 2483 { 2484 packet.PutChar (':'); 2485 const char *name = match_info.GetProcessInfo().GetName(); 2486 bool has_name_match = false; 2487 if (name && name[0]) 2488 { 2489 has_name_match = true; 2490 NameMatchType name_match_type = match_info.GetNameMatchType(); 2491 switch (name_match_type) 2492 { 2493 case eNameMatchIgnore: 2494 has_name_match = false; 2495 break; 2496 2497 case eNameMatchEquals: 2498 packet.PutCString ("name_match:equals;"); 2499 break; 2500 2501 case eNameMatchContains: 2502 packet.PutCString ("name_match:contains;"); 2503 break; 2504 2505 case eNameMatchStartsWith: 2506 packet.PutCString ("name_match:starts_with;"); 2507 break; 2508 2509 case eNameMatchEndsWith: 2510 packet.PutCString ("name_match:ends_with;"); 2511 break; 2512 2513 case eNameMatchRegularExpression: 2514 packet.PutCString ("name_match:regex;"); 2515 break; 2516 } 2517 if (has_name_match) 2518 { 2519 packet.PutCString ("name:"); 2520 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2521 packet.PutChar (';'); 2522 } 2523 } 2524 2525 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2526 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID()); 2527 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2528 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID()); 2529 if (match_info.GetProcessInfo().UserIDIsValid()) 2530 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 2531 if (match_info.GetProcessInfo().GroupIDIsValid()) 2532 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 2533 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2534 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 2535 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2536 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 2537 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2538 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 2539 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 2540 { 2541 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 2542 const llvm::Triple &triple = match_arch.GetTriple(); 2543 packet.PutCString("triple:"); 2544 packet.PutCStringAsRawHex8(triple.getTriple().c_str()); 2545 packet.PutChar (';'); 2546 } 2547 } 2548 StringExtractorGDBRemote response; 2549 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2550 { 2551 do 2552 { 2553 ProcessInstanceInfo process_info; 2554 if (!DecodeProcessInfoResponse (response, process_info)) 2555 break; 2556 process_infos.Append(process_info); 2557 response.GetStringRef().clear(); 2558 response.SetFilePos(0); 2559 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success); 2560 } 2561 else 2562 { 2563 m_supports_qfProcessInfo = false; 2564 return 0; 2565 } 2566 } 2567 return process_infos.GetSize(); 2568 2569 } 2570 2571 bool 2572 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 2573 { 2574 if (m_supports_qUserName) 2575 { 2576 char packet[32]; 2577 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 2578 assert (packet_len < (int)sizeof(packet)); 2579 StringExtractorGDBRemote response; 2580 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2581 { 2582 if (response.IsNormalResponse()) 2583 { 2584 // Make sure we parsed the right number of characters. The response is 2585 // the hex encoded user name and should make up the entire packet. 2586 // If there are any non-hex ASCII bytes, the length won't match below.. 2587 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2588 return true; 2589 } 2590 } 2591 else 2592 { 2593 m_supports_qUserName = false; 2594 return false; 2595 } 2596 } 2597 return false; 2598 2599 } 2600 2601 bool 2602 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 2603 { 2604 if (m_supports_qGroupName) 2605 { 2606 char packet[32]; 2607 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 2608 assert (packet_len < (int)sizeof(packet)); 2609 StringExtractorGDBRemote response; 2610 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2611 { 2612 if (response.IsNormalResponse()) 2613 { 2614 // Make sure we parsed the right number of characters. The response is 2615 // the hex encoded group name and should make up the entire packet. 2616 // If there are any non-hex ASCII bytes, the length won't match below.. 2617 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 2618 return true; 2619 } 2620 } 2621 else 2622 { 2623 m_supports_qGroupName = false; 2624 return false; 2625 } 2626 } 2627 return false; 2628 } 2629 2630 void 2631 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets) 2632 { 2633 uint32_t i; 2634 TimeValue start_time, end_time; 2635 uint64_t total_time_nsec; 2636 if (SendSpeedTestPacket (0, 0)) 2637 { 2638 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 }; 2639 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 }; 2640 const size_t k_num_send_sizes = sizeof(g_send_sizes)/sizeof(uint32_t); 2641 const size_t k_num_recv_sizes = sizeof(g_recv_sizes)/sizeof(uint32_t); 2642 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB 2643 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx) 2644 { 2645 const uint32_t send_size = g_send_sizes[send_idx]; 2646 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx) 2647 { 2648 const uint32_t recv_size = g_recv_sizes[recv_idx]; 2649 StreamString packet; 2650 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 2651 uint32_t bytes_left = send_size; 2652 while (bytes_left > 0) 2653 { 2654 if (bytes_left >= 26) 2655 { 2656 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2657 bytes_left -= 26; 2658 } 2659 else 2660 { 2661 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 2662 bytes_left = 0; 2663 } 2664 } 2665 2666 start_time = TimeValue::Now(); 2667 if (recv_size == 0) 2668 { 2669 for (i=0; i<num_packets; ++i) 2670 { 2671 StringExtractorGDBRemote response; 2672 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false); 2673 } 2674 } 2675 else 2676 { 2677 uint32_t bytes_read = 0; 2678 while (bytes_read < k_recv_amount) 2679 { 2680 StringExtractorGDBRemote response; 2681 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false); 2682 bytes_read += recv_size; 2683 } 2684 } 2685 end_time = TimeValue::Now(); 2686 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 2687 if (recv_size == 0) 2688 { 2689 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 2690 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n", 2691 num_packets, 2692 send_size, 2693 recv_size, 2694 total_time_nsec / TimeValue::NanoSecPerSec, 2695 total_time_nsec % TimeValue::NanoSecPerSec, 2696 packets_per_second); 2697 } 2698 else 2699 { 2700 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0); 2701 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n", 2702 num_packets, 2703 send_size, 2704 recv_size, 2705 total_time_nsec / TimeValue::NanoSecPerSec, 2706 total_time_nsec % TimeValue::NanoSecPerSec, 2707 mb_second); 2708 } 2709 } 2710 } 2711 } 2712 } 2713 2714 bool 2715 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 2716 { 2717 StreamString packet; 2718 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 2719 uint32_t bytes_left = send_size; 2720 while (bytes_left > 0) 2721 { 2722 if (bytes_left >= 26) 2723 { 2724 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2725 bytes_left -= 26; 2726 } 2727 else 2728 { 2729 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 2730 bytes_left = 0; 2731 } 2732 } 2733 2734 StringExtractorGDBRemote response; 2735 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success; 2736 } 2737 2738 uint16_t 2739 GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname) 2740 { 2741 pid = LLDB_INVALID_PROCESS_ID; 2742 StringExtractorGDBRemote response; 2743 StreamString stream; 2744 stream.PutCString("qLaunchGDBServer;"); 2745 std::string hostname; 2746 if (remote_accept_hostname && remote_accept_hostname[0]) 2747 hostname = remote_accept_hostname; 2748 else 2749 { 2750 if (Host::GetHostname (hostname)) 2751 { 2752 // Make the GDB server we launch only accept connections from this host 2753 stream.Printf("host:%s;", hostname.c_str()); 2754 } 2755 else 2756 { 2757 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname 2758 stream.Printf("host:*;"); 2759 } 2760 } 2761 const char *packet = stream.GetData(); 2762 int packet_len = stream.GetSize(); 2763 2764 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2765 { 2766 std::string name; 2767 std::string value; 2768 uint16_t port = 0; 2769 while (response.GetNameColonValue(name, value)) 2770 { 2771 if (name.compare("port") == 0) 2772 port = Args::StringToUInt32(value.c_str(), 0, 0); 2773 else if (name.compare("pid") == 0) 2774 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 2775 } 2776 return port; 2777 } 2778 return 0; 2779 } 2780 2781 bool 2782 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid) 2783 { 2784 StreamString stream; 2785 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid); 2786 const char *packet = stream.GetData(); 2787 int packet_len = stream.GetSize(); 2788 2789 StringExtractorGDBRemote response; 2790 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2791 { 2792 if (response.IsOKResponse()) 2793 return true; 2794 } 2795 return false; 2796 } 2797 2798 bool 2799 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid) 2800 { 2801 if (m_curr_tid == tid) 2802 return true; 2803 2804 char packet[32]; 2805 int packet_len; 2806 if (tid == UINT64_MAX) 2807 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1"); 2808 else 2809 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid); 2810 assert (packet_len + 1 < (int)sizeof(packet)); 2811 StringExtractorGDBRemote response; 2812 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2813 { 2814 if (response.IsOKResponse()) 2815 { 2816 m_curr_tid = tid; 2817 return true; 2818 } 2819 } 2820 return false; 2821 } 2822 2823 bool 2824 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid) 2825 { 2826 if (m_curr_tid_run == tid) 2827 return true; 2828 2829 char packet[32]; 2830 int packet_len; 2831 if (tid == UINT64_MAX) 2832 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1"); 2833 else 2834 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid); 2835 2836 assert (packet_len + 1 < (int)sizeof(packet)); 2837 StringExtractorGDBRemote response; 2838 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2839 { 2840 if (response.IsOKResponse()) 2841 { 2842 m_curr_tid_run = tid; 2843 return true; 2844 } 2845 } 2846 return false; 2847 } 2848 2849 bool 2850 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 2851 { 2852 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success) 2853 return response.IsNormalResponse(); 2854 return false; 2855 } 2856 2857 bool 2858 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response) 2859 { 2860 if (m_supports_qThreadStopInfo) 2861 { 2862 char packet[256]; 2863 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2864 assert (packet_len < (int)sizeof(packet)); 2865 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 2866 { 2867 if (response.IsUnsupportedResponse()) 2868 m_supports_qThreadStopInfo = false; 2869 else if (response.IsNormalResponse()) 2870 return true; 2871 else 2872 return false; 2873 } 2874 else 2875 { 2876 m_supports_qThreadStopInfo = false; 2877 } 2878 } 2879 return false; 2880 } 2881 2882 2883 uint8_t 2884 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 2885 { 2886 // Check if the stub is known not to support this breakpoint type 2887 if (!SupportsGDBStoppointPacket(type)) 2888 return UINT8_MAX; 2889 // Construct the breakpoint packet 2890 char packet[64]; 2891 const int packet_len = ::snprintf (packet, 2892 sizeof(packet), 2893 "%c%i,%" PRIx64 ",%x", 2894 insert ? 'Z' : 'z', 2895 type, 2896 addr, 2897 length); 2898 // Check we havent overwritten the end of the packet buffer 2899 assert (packet_len + 1 < (int)sizeof(packet)); 2900 StringExtractorGDBRemote response; 2901 // Try to send the breakpoint packet, and check that it was correctly sent 2902 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success) 2903 { 2904 // Receive and OK packet when the breakpoint successfully placed 2905 if (response.IsOKResponse()) 2906 return 0; 2907 2908 // Error while setting breakpoint, send back specific error 2909 if (response.IsErrorResponse()) 2910 return response.GetError(); 2911 2912 // Empty packet informs us that breakpoint is not supported 2913 if (response.IsUnsupportedResponse()) 2914 { 2915 // Disable this breakpoint type since it is unsupported 2916 switch (type) 2917 { 2918 case eBreakpointSoftware: m_supports_z0 = false; break; 2919 case eBreakpointHardware: m_supports_z1 = false; break; 2920 case eWatchpointWrite: m_supports_z2 = false; break; 2921 case eWatchpointRead: m_supports_z3 = false; break; 2922 case eWatchpointReadWrite: m_supports_z4 = false; break; 2923 } 2924 } 2925 } 2926 // Signal generic faliure 2927 return UINT8_MAX; 2928 } 2929 2930 size_t 2931 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 2932 bool &sequence_mutex_unavailable) 2933 { 2934 Mutex::Locker locker; 2935 thread_ids.clear(); 2936 2937 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 2938 { 2939 sequence_mutex_unavailable = false; 2940 StringExtractorGDBRemote response; 2941 2942 PacketResult packet_result; 2943 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response); 2944 packet_result == PacketResult::Success && response.IsNormalResponse(); 2945 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response)) 2946 { 2947 char ch = response.GetChar(); 2948 if (ch == 'l') 2949 break; 2950 if (ch == 'm') 2951 { 2952 do 2953 { 2954 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2955 2956 if (tid != LLDB_INVALID_THREAD_ID) 2957 { 2958 thread_ids.push_back (tid); 2959 } 2960 ch = response.GetChar(); // Skip the command separator 2961 } while (ch == ','); // Make sure we got a comma separator 2962 } 2963 } 2964 } 2965 else 2966 { 2967 #if defined (LLDB_CONFIGURATION_DEBUG) 2968 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 2969 #else 2970 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2971 if (log) 2972 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 2973 #endif 2974 sequence_mutex_unavailable = true; 2975 } 2976 return thread_ids.size(); 2977 } 2978 2979 lldb::addr_t 2980 GDBRemoteCommunicationClient::GetShlibInfoAddr() 2981 { 2982 if (!IsRunning()) 2983 { 2984 StringExtractorGDBRemote response; 2985 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success) 2986 { 2987 if (response.IsNormalResponse()) 2988 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2989 } 2990 } 2991 return LLDB_INVALID_ADDRESS; 2992 } 2993 2994 lldb_private::Error 2995 GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL 2996 const char *working_dir, // Pass NULL to use the current working directory 2997 int *status_ptr, // Pass NULL if you don't want the process exit status 2998 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit 2999 std::string *command_output, // Pass NULL if you don't want the command output 3000 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish 3001 { 3002 lldb_private::StreamString stream; 3003 stream.PutCString("qPlatform_shell:"); 3004 stream.PutBytesAsRawHex8(command, strlen(command)); 3005 stream.PutChar(','); 3006 stream.PutHex32(timeout_sec); 3007 if (working_dir && *working_dir) 3008 { 3009 stream.PutChar(','); 3010 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir)); 3011 } 3012 const char *packet = stream.GetData(); 3013 int packet_len = stream.GetSize(); 3014 StringExtractorGDBRemote response; 3015 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3016 { 3017 if (response.GetChar() != 'F') 3018 return Error("malformed reply"); 3019 if (response.GetChar() != ',') 3020 return Error("malformed reply"); 3021 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 3022 if (exitcode == UINT32_MAX) 3023 return Error("unable to run remote process"); 3024 else if (status_ptr) 3025 *status_ptr = exitcode; 3026 if (response.GetChar() != ',') 3027 return Error("malformed reply"); 3028 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 3029 if (signo_ptr) 3030 *signo_ptr = signo; 3031 if (response.GetChar() != ',') 3032 return Error("malformed reply"); 3033 std::string output; 3034 response.GetEscapedBinaryData(output); 3035 if (command_output) 3036 command_output->assign(output); 3037 return Error(); 3038 } 3039 return Error("unable to send packet"); 3040 } 3041 3042 Error 3043 GDBRemoteCommunicationClient::MakeDirectory (const char *path, 3044 uint32_t file_permissions) 3045 { 3046 lldb_private::StreamString stream; 3047 stream.PutCString("qPlatform_mkdir:"); 3048 stream.PutHex32(file_permissions); 3049 stream.PutChar(','); 3050 stream.PutBytesAsRawHex8(path, strlen(path)); 3051 const char *packet = stream.GetData(); 3052 int packet_len = stream.GetSize(); 3053 StringExtractorGDBRemote response; 3054 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3055 { 3056 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 3057 } 3058 return Error(); 3059 3060 } 3061 3062 Error 3063 GDBRemoteCommunicationClient::SetFilePermissions (const char *path, 3064 uint32_t file_permissions) 3065 { 3066 lldb_private::StreamString stream; 3067 stream.PutCString("qPlatform_chmod:"); 3068 stream.PutHex32(file_permissions); 3069 stream.PutChar(','); 3070 stream.PutBytesAsRawHex8(path, strlen(path)); 3071 const char *packet = stream.GetData(); 3072 int packet_len = stream.GetSize(); 3073 StringExtractorGDBRemote response; 3074 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3075 { 3076 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 3077 } 3078 return Error(); 3079 3080 } 3081 3082 static uint64_t 3083 ParseHostIOPacketResponse (StringExtractorGDBRemote &response, 3084 uint64_t fail_result, 3085 Error &error) 3086 { 3087 response.SetFilePos(0); 3088 if (response.GetChar() != 'F') 3089 return fail_result; 3090 int32_t result = response.GetS32 (-2); 3091 if (result == -2) 3092 return fail_result; 3093 if (response.GetChar() == ',') 3094 { 3095 int result_errno = response.GetS32 (-2); 3096 if (result_errno != -2) 3097 error.SetError(result_errno, eErrorTypePOSIX); 3098 else 3099 error.SetError(-1, eErrorTypeGeneric); 3100 } 3101 else 3102 error.Clear(); 3103 return result; 3104 } 3105 lldb::user_id_t 3106 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec, 3107 uint32_t flags, 3108 mode_t mode, 3109 Error &error) 3110 { 3111 lldb_private::StreamString stream; 3112 stream.PutCString("vFile:open:"); 3113 std::string path (file_spec.GetPath()); 3114 if (path.empty()) 3115 return UINT64_MAX; 3116 stream.PutCStringAsRawHex8(path.c_str()); 3117 stream.PutChar(','); 3118 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags); 3119 stream.PutHex32(posix_open_flags); 3120 stream.PutChar(','); 3121 stream.PutHex32(mode); 3122 const char* packet = stream.GetData(); 3123 int packet_len = stream.GetSize(); 3124 StringExtractorGDBRemote response; 3125 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3126 { 3127 return ParseHostIOPacketResponse (response, UINT64_MAX, error); 3128 } 3129 return UINT64_MAX; 3130 } 3131 3132 bool 3133 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd, 3134 Error &error) 3135 { 3136 lldb_private::StreamString stream; 3137 stream.Printf("vFile:close:%i", (int)fd); 3138 const char* packet = stream.GetData(); 3139 int packet_len = stream.GetSize(); 3140 StringExtractorGDBRemote response; 3141 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3142 { 3143 return ParseHostIOPacketResponse (response, -1, error) == 0; 3144 } 3145 return false; 3146 } 3147 3148 // Extension of host I/O packets to get the file size. 3149 lldb::user_id_t 3150 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec) 3151 { 3152 lldb_private::StreamString stream; 3153 stream.PutCString("vFile:size:"); 3154 std::string path (file_spec.GetPath()); 3155 stream.PutCStringAsRawHex8(path.c_str()); 3156 const char* packet = stream.GetData(); 3157 int packet_len = stream.GetSize(); 3158 StringExtractorGDBRemote response; 3159 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3160 { 3161 if (response.GetChar() != 'F') 3162 return UINT64_MAX; 3163 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 3164 return retcode; 3165 } 3166 return UINT64_MAX; 3167 } 3168 3169 Error 3170 GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions) 3171 { 3172 Error error; 3173 lldb_private::StreamString stream; 3174 stream.PutCString("vFile:mode:"); 3175 stream.PutCStringAsRawHex8(path); 3176 const char* packet = stream.GetData(); 3177 int packet_len = stream.GetSize(); 3178 StringExtractorGDBRemote response; 3179 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3180 { 3181 if (response.GetChar() != 'F') 3182 { 3183 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet); 3184 } 3185 else 3186 { 3187 const uint32_t mode = response.GetS32(-1); 3188 if (static_cast<int32_t>(mode) == -1) 3189 { 3190 if (response.GetChar() == ',') 3191 { 3192 int response_errno = response.GetS32(-1); 3193 if (response_errno > 0) 3194 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3195 else 3196 error.SetErrorToGenericError(); 3197 } 3198 else 3199 error.SetErrorToGenericError(); 3200 } 3201 else 3202 { 3203 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO); 3204 } 3205 } 3206 } 3207 else 3208 { 3209 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet); 3210 } 3211 return error; 3212 } 3213 3214 uint64_t 3215 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd, 3216 uint64_t offset, 3217 void *dst, 3218 uint64_t dst_len, 3219 Error &error) 3220 { 3221 lldb_private::StreamString stream; 3222 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset); 3223 const char* packet = stream.GetData(); 3224 int packet_len = stream.GetSize(); 3225 StringExtractorGDBRemote response; 3226 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3227 { 3228 if (response.GetChar() != 'F') 3229 return 0; 3230 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 3231 if (retcode == UINT32_MAX) 3232 return retcode; 3233 const char next = (response.Peek() ? *response.Peek() : 0); 3234 if (next == ',') 3235 return 0; 3236 if (next == ';') 3237 { 3238 response.GetChar(); // skip the semicolon 3239 std::string buffer; 3240 if (response.GetEscapedBinaryData(buffer)) 3241 { 3242 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size()); 3243 if (data_to_write > 0) 3244 memcpy(dst, &buffer[0], data_to_write); 3245 return data_to_write; 3246 } 3247 } 3248 } 3249 return 0; 3250 } 3251 3252 uint64_t 3253 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd, 3254 uint64_t offset, 3255 const void* src, 3256 uint64_t src_len, 3257 Error &error) 3258 { 3259 lldb_private::StreamGDBRemote stream; 3260 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 3261 stream.PutEscapedBytes(src, src_len); 3262 const char* packet = stream.GetData(); 3263 int packet_len = stream.GetSize(); 3264 StringExtractorGDBRemote response; 3265 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3266 { 3267 if (response.GetChar() != 'F') 3268 { 3269 error.SetErrorStringWithFormat("write file failed"); 3270 return 0; 3271 } 3272 uint64_t bytes_written = response.GetU64(UINT64_MAX); 3273 if (bytes_written == UINT64_MAX) 3274 { 3275 error.SetErrorToGenericError(); 3276 if (response.GetChar() == ',') 3277 { 3278 int response_errno = response.GetS32(-1); 3279 if (response_errno > 0) 3280 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3281 } 3282 return 0; 3283 } 3284 return bytes_written; 3285 } 3286 else 3287 { 3288 error.SetErrorString ("failed to send vFile:pwrite packet"); 3289 } 3290 return 0; 3291 } 3292 3293 Error 3294 GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst) 3295 { 3296 Error error; 3297 lldb_private::StreamGDBRemote stream; 3298 stream.PutCString("vFile:symlink:"); 3299 // the unix symlink() command reverses its parameters where the dst if first, 3300 // so we follow suit here 3301 stream.PutCStringAsRawHex8(dst); 3302 stream.PutChar(','); 3303 stream.PutCStringAsRawHex8(src); 3304 const char* packet = stream.GetData(); 3305 int packet_len = stream.GetSize(); 3306 StringExtractorGDBRemote response; 3307 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3308 { 3309 if (response.GetChar() == 'F') 3310 { 3311 uint32_t result = response.GetU32(UINT32_MAX); 3312 if (result != 0) 3313 { 3314 error.SetErrorToGenericError(); 3315 if (response.GetChar() == ',') 3316 { 3317 int response_errno = response.GetS32(-1); 3318 if (response_errno > 0) 3319 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3320 } 3321 } 3322 } 3323 else 3324 { 3325 // Should have returned with 'F<result>[,<errno>]' 3326 error.SetErrorStringWithFormat("symlink failed"); 3327 } 3328 } 3329 else 3330 { 3331 error.SetErrorString ("failed to send vFile:symlink packet"); 3332 } 3333 return error; 3334 } 3335 3336 Error 3337 GDBRemoteCommunicationClient::Unlink (const char *path) 3338 { 3339 Error error; 3340 lldb_private::StreamGDBRemote stream; 3341 stream.PutCString("vFile:unlink:"); 3342 // the unix symlink() command reverses its parameters where the dst if first, 3343 // so we follow suit here 3344 stream.PutCStringAsRawHex8(path); 3345 const char* packet = stream.GetData(); 3346 int packet_len = stream.GetSize(); 3347 StringExtractorGDBRemote response; 3348 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3349 { 3350 if (response.GetChar() == 'F') 3351 { 3352 uint32_t result = response.GetU32(UINT32_MAX); 3353 if (result != 0) 3354 { 3355 error.SetErrorToGenericError(); 3356 if (response.GetChar() == ',') 3357 { 3358 int response_errno = response.GetS32(-1); 3359 if (response_errno > 0) 3360 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3361 } 3362 } 3363 } 3364 else 3365 { 3366 // Should have returned with 'F<result>[,<errno>]' 3367 error.SetErrorStringWithFormat("unlink failed"); 3368 } 3369 } 3370 else 3371 { 3372 error.SetErrorString ("failed to send vFile:unlink packet"); 3373 } 3374 return error; 3375 } 3376 3377 // Extension of host I/O packets to get whether a file exists. 3378 bool 3379 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec) 3380 { 3381 lldb_private::StreamString stream; 3382 stream.PutCString("vFile:exists:"); 3383 std::string path (file_spec.GetPath()); 3384 stream.PutCStringAsRawHex8(path.c_str()); 3385 const char* packet = stream.GetData(); 3386 int packet_len = stream.GetSize(); 3387 StringExtractorGDBRemote response; 3388 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3389 { 3390 if (response.GetChar() != 'F') 3391 return false; 3392 if (response.GetChar() != ',') 3393 return false; 3394 bool retcode = (response.GetChar() != '0'); 3395 return retcode; 3396 } 3397 return false; 3398 } 3399 3400 bool 3401 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec, 3402 uint64_t &high, 3403 uint64_t &low) 3404 { 3405 lldb_private::StreamString stream; 3406 stream.PutCString("vFile:MD5:"); 3407 std::string path (file_spec.GetPath()); 3408 stream.PutCStringAsRawHex8(path.c_str()); 3409 const char* packet = stream.GetData(); 3410 int packet_len = stream.GetSize(); 3411 StringExtractorGDBRemote response; 3412 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3413 { 3414 if (response.GetChar() != 'F') 3415 return false; 3416 if (response.GetChar() != ',') 3417 return false; 3418 if (response.Peek() && *response.Peek() == 'x') 3419 return false; 3420 low = response.GetHexMaxU64(false, UINT64_MAX); 3421 high = response.GetHexMaxU64(false, UINT64_MAX); 3422 return true; 3423 } 3424 return false; 3425 } 3426 3427 bool 3428 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process) 3429 { 3430 // Some targets have issues with g/G packets and we need to avoid using them 3431 if (m_avoid_g_packets == eLazyBoolCalculate) 3432 { 3433 if (process) 3434 { 3435 m_avoid_g_packets = eLazyBoolNo; 3436 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3437 if (arch.IsValid() 3438 && arch.GetTriple().getVendor() == llvm::Triple::Apple 3439 && arch.GetTriple().getOS() == llvm::Triple::IOS 3440 && arch.GetTriple().getArch() == llvm::Triple::arm64) 3441 { 3442 m_avoid_g_packets = eLazyBoolYes; 3443 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3444 if (gdb_server_version != 0) 3445 { 3446 const char *gdb_server_name = GetGDBServerProgramName(); 3447 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) 3448 { 3449 if (gdb_server_version >= 310) 3450 m_avoid_g_packets = eLazyBoolNo; 3451 } 3452 } 3453 } 3454 } 3455 } 3456 return m_avoid_g_packets == eLazyBoolYes; 3457 } 3458 3459 bool 3460 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response) 3461 { 3462 Mutex::Locker locker; 3463 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet.")) 3464 { 3465 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3466 3467 if (thread_suffix_supported || SetCurrentThread(tid)) 3468 { 3469 char packet[64]; 3470 int packet_len = 0; 3471 if (thread_suffix_supported) 3472 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid); 3473 else 3474 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg); 3475 assert (packet_len < ((int)sizeof(packet) - 1)); 3476 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3477 } 3478 } 3479 return false; 3480 3481 } 3482 3483 3484 bool 3485 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response) 3486 { 3487 Mutex::Locker locker; 3488 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet.")) 3489 { 3490 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3491 3492 if (thread_suffix_supported || SetCurrentThread(tid)) 3493 { 3494 char packet[64]; 3495 int packet_len = 0; 3496 // Get all registers in one packet 3497 if (thread_suffix_supported) 3498 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid); 3499 else 3500 packet_len = ::snprintf (packet, sizeof(packet), "g"); 3501 assert (packet_len < ((int)sizeof(packet) - 1)); 3502 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 3503 } 3504 } 3505 return false; 3506 } 3507 bool 3508 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id) 3509 { 3510 save_id = 0; // Set to invalid save ID 3511 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3512 return false; 3513 3514 m_supports_QSaveRegisterState = eLazyBoolYes; 3515 Mutex::Locker locker; 3516 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState.")) 3517 { 3518 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3519 if (thread_suffix_supported || SetCurrentThread(tid)) 3520 { 3521 char packet[256]; 3522 if (thread_suffix_supported) 3523 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid); 3524 else 3525 ::strncpy (packet, "QSaveRegisterState", sizeof(packet)); 3526 3527 StringExtractorGDBRemote response; 3528 3529 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3530 { 3531 if (response.IsUnsupportedResponse()) 3532 { 3533 // This packet isn't supported, don't try calling it again 3534 m_supports_QSaveRegisterState = eLazyBoolNo; 3535 } 3536 3537 const uint32_t response_save_id = response.GetU32(0); 3538 if (response_save_id != 0) 3539 { 3540 save_id = response_save_id; 3541 return true; 3542 } 3543 } 3544 } 3545 } 3546 return false; 3547 } 3548 3549 bool 3550 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id) 3551 { 3552 // We use the "m_supports_QSaveRegisterState" variable here becuase the 3553 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in 3554 // order to be useful 3555 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3556 return false; 3557 3558 Mutex::Locker locker; 3559 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState.")) 3560 { 3561 const bool thread_suffix_supported = GetThreadSuffixSupported(); 3562 if (thread_suffix_supported || SetCurrentThread(tid)) 3563 { 3564 char packet[256]; 3565 if (thread_suffix_supported) 3566 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid); 3567 else 3568 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id); 3569 3570 StringExtractorGDBRemote response; 3571 3572 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 3573 { 3574 if (response.IsOKResponse()) 3575 { 3576 return true; 3577 } 3578 else if (response.IsUnsupportedResponse()) 3579 { 3580 // This packet isn't supported, don't try calling this packet or 3581 // QSaveRegisterState again... 3582 m_supports_QSaveRegisterState = eLazyBoolNo; 3583 } 3584 } 3585 } 3586 } 3587 return false; 3588 } 3589