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