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