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