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