1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Host/Config.h" 10 11 #include <errno.h> 12 #include <stdlib.h> 13 #ifndef LLDB_DISABLE_POSIX 14 #include <netinet/in.h> 15 #include <sys/mman.h> 16 #include <sys/socket.h> 17 #include <unistd.h> 18 #endif 19 #include <sys/stat.h> 20 #include <sys/types.h> 21 #include <time.h> 22 23 #include <algorithm> 24 #include <csignal> 25 #include <map> 26 #include <memory> 27 #include <mutex> 28 #include <sstream> 29 30 #include "lldb/Breakpoint/Watchpoint.h" 31 #include "lldb/Core/Debugger.h" 32 #include "lldb/Core/Module.h" 33 #include "lldb/Core/ModuleSpec.h" 34 #include "lldb/Core/PluginManager.h" 35 #include "lldb/Core/StreamFile.h" 36 #include "lldb/Core/Value.h" 37 #include "lldb/DataFormatters/FormatManager.h" 38 #include "lldb/Host/ConnectionFileDescriptor.h" 39 #include "lldb/Host/FileSystem.h" 40 #include "lldb/Host/HostThread.h" 41 #include "lldb/Host/PosixApi.h" 42 #include "lldb/Host/PseudoTerminal.h" 43 #include "lldb/Host/StringConvert.h" 44 #include "lldb/Host/ThreadLauncher.h" 45 #include "lldb/Host/XML.h" 46 #include "lldb/Interpreter/CommandInterpreter.h" 47 #include "lldb/Interpreter/CommandObject.h" 48 #include "lldb/Interpreter/CommandObjectMultiword.h" 49 #include "lldb/Interpreter/CommandReturnObject.h" 50 #include "lldb/Interpreter/OptionArgParser.h" 51 #include "lldb/Interpreter/OptionGroupBoolean.h" 52 #include "lldb/Interpreter/OptionGroupUInt64.h" 53 #include "lldb/Interpreter/OptionValueProperties.h" 54 #include "lldb/Interpreter/Options.h" 55 #include "lldb/Interpreter/Property.h" 56 #include "lldb/Symbol/LocateSymbolFile.h" 57 #include "lldb/Symbol/ObjectFile.h" 58 #include "lldb/Target/ABI.h" 59 #include "lldb/Target/DynamicLoader.h" 60 #include "lldb/Target/MemoryRegionInfo.h" 61 #include "lldb/Target/SystemRuntime.h" 62 #include "lldb/Target/Target.h" 63 #include "lldb/Target/TargetList.h" 64 #include "lldb/Target/ThreadPlanCallFunction.h" 65 #include "lldb/Utility/Args.h" 66 #include "lldb/Utility/CleanUp.h" 67 #include "lldb/Utility/FileSpec.h" 68 #include "lldb/Utility/Reproducer.h" 69 #include "lldb/Utility/State.h" 70 #include "lldb/Utility/StreamString.h" 71 #include "lldb/Utility/Timer.h" 72 73 #include "GDBRemoteRegisterContext.h" 74 #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h" 75 #include "Plugins/Process/Utility/GDBRemoteSignals.h" 76 #include "Plugins/Process/Utility/InferiorCallPOSIX.h" 77 #include "Plugins/Process/Utility/StopInfoMachException.h" 78 #include "ProcessGDBRemote.h" 79 #include "ProcessGDBRemoteLog.h" 80 #include "ThreadGDBRemote.h" 81 #include "lldb/Host/Host.h" 82 #include "lldb/Utility/StringExtractorGDBRemote.h" 83 84 #include "llvm/ADT/StringSwitch.h" 85 #include "llvm/Support/Threading.h" 86 #include "llvm/Support/raw_ostream.h" 87 88 #define DEBUGSERVER_BASENAME "debugserver" 89 using namespace llvm; 90 using namespace lldb; 91 using namespace lldb_private; 92 using namespace lldb_private::process_gdb_remote; 93 94 namespace lldb { 95 // Provide a function that can easily dump the packet history if we know a 96 // ProcessGDBRemote * value (which we can get from logs or from debugging). We 97 // need the function in the lldb namespace so it makes it into the final 98 // executable since the LLDB shared library only exports stuff in the lldb 99 // namespace. This allows you to attach with a debugger and call this function 100 // and get the packet history dumped to a file. 101 void DumpProcessGDBRemotePacketHistory(void *p, const char *path) { 102 StreamFile strm; 103 Status error = FileSystem::Instance().Open(strm.GetFile(), FileSpec(path), 104 File::eOpenOptionWrite | 105 File::eOpenOptionCanCreate); 106 if (error.Success()) 107 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm); 108 } 109 } // namespace lldb 110 111 namespace { 112 113 static constexpr PropertyDefinition g_properties[] = { 114 {"packet-timeout", 115 OptionValue::eTypeUInt64, 116 true, 117 5 118 #if defined(__has_feature) 119 #if __has_feature(address_sanitizer) 120 * 2 121 #endif 122 #endif 123 , 124 nullptr, 125 {}, 126 "Specify the default packet timeout in seconds."}, 127 {"target-definition-file", 128 OptionValue::eTypeFileSpec, 129 true, 130 0, 131 nullptr, 132 {}, 133 "The file that provides the description for remote target registers."}, 134 {"use-libraries-svr4", 135 OptionValue::eTypeBoolean, 136 true, 137 false, 138 nullptr, 139 {}, 140 "If true, the libraries-svr4 feature will be used to get a hold of the " 141 "process's loaded modules."}}; 142 143 enum { 144 ePropertyPacketTimeout, 145 ePropertyTargetDefinitionFile, 146 ePropertyUseSVR4 147 }; 148 149 class PluginProperties : public Properties { 150 public: 151 static ConstString GetSettingName() { 152 return ProcessGDBRemote::GetPluginNameStatic(); 153 } 154 155 PluginProperties() : Properties() { 156 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); 157 m_collection_sp->Initialize(g_properties); 158 } 159 160 ~PluginProperties() override {} 161 162 uint64_t GetPacketTimeout() { 163 const uint32_t idx = ePropertyPacketTimeout; 164 return m_collection_sp->GetPropertyAtIndexAsUInt64( 165 nullptr, idx, g_properties[idx].default_uint_value); 166 } 167 168 bool SetPacketTimeout(uint64_t timeout) { 169 const uint32_t idx = ePropertyPacketTimeout; 170 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout); 171 } 172 173 FileSpec GetTargetDefinitionFile() const { 174 const uint32_t idx = ePropertyTargetDefinitionFile; 175 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 176 } 177 178 bool GetUseSVR4() const { 179 const uint32_t idx = ePropertyUseSVR4; 180 return m_collection_sp->GetPropertyAtIndexAsBoolean( 181 nullptr, idx, g_properties[idx].default_uint_value != 0); 182 } 183 }; 184 185 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP; 186 187 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() { 188 static ProcessKDPPropertiesSP g_settings_sp; 189 if (!g_settings_sp) 190 g_settings_sp = std::make_shared<PluginProperties>(); 191 return g_settings_sp; 192 } 193 194 class ProcessGDBRemoteProvider 195 : public repro::Provider<ProcessGDBRemoteProvider> { 196 public: 197 struct Info { 198 static const char *name; 199 static const char *file; 200 }; 201 202 ProcessGDBRemoteProvider(const FileSpec &directory) : Provider(directory) { 203 } 204 205 raw_ostream *GetHistoryStream() { 206 FileSpec history_file = GetRoot().CopyByAppendingPathComponent(Info::file); 207 208 std::error_code EC; 209 m_stream_up = llvm::make_unique<raw_fd_ostream>(history_file.GetPath(), EC, 210 sys::fs::OpenFlags::F_Text); 211 return m_stream_up.get(); 212 } 213 214 void SetCallback(std::function<void()> callback) { 215 m_callback = std::move(callback); 216 } 217 218 void Keep() override { m_callback(); } 219 220 void Discard() override { m_callback(); } 221 222 static char ID; 223 224 private: 225 std::function<void()> m_callback; 226 std::unique_ptr<raw_fd_ostream> m_stream_up; 227 }; 228 229 char ProcessGDBRemoteProvider::ID = 0; 230 const char *ProcessGDBRemoteProvider::Info::name = "gdb-remote"; 231 const char *ProcessGDBRemoteProvider::Info::file = "gdb-remote.yaml"; 232 233 } // namespace 234 235 // TODO Randomly assigning a port is unsafe. We should get an unused 236 // ephemeral port from the kernel and make sure we reserve it before passing it 237 // to debugserver. 238 239 #if defined(__APPLE__) 240 #define LOW_PORT (IPPORT_RESERVED) 241 #define HIGH_PORT (IPPORT_HIFIRSTAUTO) 242 #else 243 #define LOW_PORT (1024u) 244 #define HIGH_PORT (49151u) 245 #endif 246 247 #if defined(__APPLE__) && \ 248 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) 249 static bool rand_initialized = false; 250 251 static inline uint16_t get_random_port() { 252 if (!rand_initialized) { 253 time_t seed = time(NULL); 254 255 rand_initialized = true; 256 srand(seed); 257 } 258 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT; 259 } 260 #endif 261 262 ConstString ProcessGDBRemote::GetPluginNameStatic() { 263 static ConstString g_name("gdb-remote"); 264 return g_name; 265 } 266 267 const char *ProcessGDBRemote::GetPluginDescriptionStatic() { 268 return "GDB Remote protocol based debugging plug-in."; 269 } 270 271 void ProcessGDBRemote::Terminate() { 272 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance); 273 } 274 275 lldb::ProcessSP 276 ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp, 277 ListenerSP listener_sp, 278 const FileSpec *crash_file_path) { 279 lldb::ProcessSP process_sp; 280 if (crash_file_path == nullptr) 281 process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp); 282 return process_sp; 283 } 284 285 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp, 286 bool plugin_specified_by_name) { 287 if (plugin_specified_by_name) 288 return true; 289 290 // For now we are just making sure the file exists for a given module 291 Module *exe_module = target_sp->GetExecutableModulePointer(); 292 if (exe_module) { 293 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 294 // We can't debug core files... 295 switch (exe_objfile->GetType()) { 296 case ObjectFile::eTypeInvalid: 297 case ObjectFile::eTypeCoreFile: 298 case ObjectFile::eTypeDebugInfo: 299 case ObjectFile::eTypeObjectFile: 300 case ObjectFile::eTypeSharedLibrary: 301 case ObjectFile::eTypeStubLibrary: 302 case ObjectFile::eTypeJIT: 303 return false; 304 case ObjectFile::eTypeExecutable: 305 case ObjectFile::eTypeDynamicLinker: 306 case ObjectFile::eTypeUnknown: 307 break; 308 } 309 return FileSystem::Instance().Exists(exe_module->GetFileSpec()); 310 } 311 // However, if there is no executable module, we return true since we might 312 // be preparing to attach. 313 return true; 314 } 315 316 // ProcessGDBRemote constructor 317 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, 318 ListenerSP listener_sp) 319 : Process(target_sp, listener_sp), 320 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(), 321 m_register_info(), 322 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"), 323 m_async_listener_sp( 324 Listener::MakeListener("lldb.process.gdb-remote.async-listener")), 325 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(), 326 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(), 327 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(), 328 m_max_memory_size(0), m_remote_stub_max_memory_size(0), 329 m_addr_to_mmap_size(), m_thread_create_bp_sp(), 330 m_waiting_for_attach(false), m_destroy_tried_resuming(false), 331 m_command_sp(), m_breakpoint_pc_offset(0), 332 m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false), 333 m_allow_flash_writes(false), m_erased_flash_ranges() { 334 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, 335 "async thread should exit"); 336 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, 337 "async thread continue"); 338 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit, 339 "async thread did exit"); 340 341 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { 342 ProcessGDBRemoteProvider &provider = 343 g->GetOrCreate<ProcessGDBRemoteProvider>(); 344 // Set the history stream to the stream owned by the provider. 345 m_gdb_comm.SetHistoryStream(provider.GetHistoryStream()); 346 // Make sure to clear the stream again when we're finished. 347 provider.SetCallback([&]() { m_gdb_comm.SetHistoryStream(nullptr); }); 348 } 349 350 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC)); 351 352 const uint32_t async_event_mask = 353 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; 354 355 if (m_async_listener_sp->StartListeningForEvents( 356 &m_async_broadcaster, async_event_mask) != async_event_mask) { 357 if (log) 358 log->Printf("ProcessGDBRemote::%s failed to listen for " 359 "m_async_broadcaster events", 360 __FUNCTION__); 361 } 362 363 const uint32_t gdb_event_mask = 364 Communication::eBroadcastBitReadThreadDidExit | 365 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify; 366 if (m_async_listener_sp->StartListeningForEvents( 367 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) { 368 if (log) 369 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", 370 __FUNCTION__); 371 } 372 373 const uint64_t timeout_seconds = 374 GetGlobalPluginProperties()->GetPacketTimeout(); 375 if (timeout_seconds > 0) 376 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); 377 } 378 379 // Destructor 380 ProcessGDBRemote::~ProcessGDBRemote() { 381 // m_mach_process.UnregisterNotificationCallbacks (this); 382 Clear(); 383 // We need to call finalize on the process before destroying ourselves to 384 // make sure all of the broadcaster cleanup goes as planned. If we destruct 385 // this class, then Process::~Process() might have problems trying to fully 386 // destroy the broadcaster. 387 Finalize(); 388 389 // The general Finalize is going to try to destroy the process and that 390 // SHOULD shut down the async thread. However, if we don't kill it it will 391 // get stranded and its connection will go away so when it wakes up it will 392 // crash. So kill it for sure here. 393 StopAsyncThread(); 394 KillDebugserverProcess(); 395 } 396 397 // PluginInterface 398 ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); } 399 400 uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; } 401 402 bool ProcessGDBRemote::ParsePythonTargetDefinition( 403 const FileSpec &target_definition_fspec) { 404 ScriptInterpreter *interpreter = 405 GetTarget().GetDebugger().GetScriptInterpreter(); 406 Status error; 407 StructuredData::ObjectSP module_object_sp( 408 interpreter->LoadPluginModule(target_definition_fspec, error)); 409 if (module_object_sp) { 410 StructuredData::DictionarySP target_definition_sp( 411 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), 412 "gdb-server-target-definition", error)); 413 414 if (target_definition_sp) { 415 StructuredData::ObjectSP target_object( 416 target_definition_sp->GetValueForKey("host-info")); 417 if (target_object) { 418 if (auto host_info_dict = target_object->GetAsDictionary()) { 419 StructuredData::ObjectSP triple_value = 420 host_info_dict->GetValueForKey("triple"); 421 if (auto triple_string_value = triple_value->GetAsString()) { 422 std::string triple_string = triple_string_value->GetValue(); 423 ArchSpec host_arch(triple_string.c_str()); 424 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) { 425 GetTarget().SetArchitecture(host_arch); 426 } 427 } 428 } 429 } 430 m_breakpoint_pc_offset = 0; 431 StructuredData::ObjectSP breakpoint_pc_offset_value = 432 target_definition_sp->GetValueForKey("breakpoint-pc-offset"); 433 if (breakpoint_pc_offset_value) { 434 if (auto breakpoint_pc_int_value = 435 breakpoint_pc_offset_value->GetAsInteger()) 436 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue(); 437 } 438 439 if (m_register_info.SetRegisterInfo(*target_definition_sp, 440 GetTarget().GetArchitecture()) > 0) { 441 return true; 442 } 443 } 444 } 445 return false; 446 } 447 448 // If the remote stub didn't give us eh_frame or DWARF register numbers for a 449 // register, see if the ABI can provide them. 450 // DWARF and eh_frame register numbers are defined as a part of the ABI. 451 static void AugmentRegisterInfoViaABI(RegisterInfo ®_info, 452 ConstString reg_name, ABISP abi_sp) { 453 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM || 454 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) { 455 if (abi_sp) { 456 RegisterInfo abi_reg_info; 457 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) { 458 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM && 459 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) { 460 reg_info.kinds[eRegisterKindEHFrame] = 461 abi_reg_info.kinds[eRegisterKindEHFrame]; 462 } 463 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM && 464 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) { 465 reg_info.kinds[eRegisterKindDWARF] = 466 abi_reg_info.kinds[eRegisterKindDWARF]; 467 } 468 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM && 469 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) { 470 reg_info.kinds[eRegisterKindGeneric] = 471 abi_reg_info.kinds[eRegisterKindGeneric]; 472 } 473 } 474 } 475 } 476 } 477 478 static size_t SplitCommaSeparatedRegisterNumberString( 479 const llvm::StringRef &comma_separated_regiter_numbers, 480 std::vector<uint32_t> ®nums, int base) { 481 regnums.clear(); 482 std::pair<llvm::StringRef, llvm::StringRef> value_pair; 483 value_pair.second = comma_separated_regiter_numbers; 484 do { 485 value_pair = value_pair.second.split(','); 486 if (!value_pair.first.empty()) { 487 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(), 488 LLDB_INVALID_REGNUM, base); 489 if (reg != LLDB_INVALID_REGNUM) 490 regnums.push_back(reg); 491 } 492 } while (!value_pair.second.empty()); 493 return regnums.size(); 494 } 495 496 void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) { 497 if (!force && m_register_info.GetNumRegisters() > 0) 498 return; 499 500 m_register_info.Clear(); 501 502 // Check if qHostInfo specified a specific packet timeout for this 503 // connection. If so then lets update our setting so the user knows what the 504 // timeout is and can see it. 505 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout(); 506 if (host_packet_timeout > std::chrono::seconds(0)) { 507 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count()); 508 } 509 510 // Register info search order: 511 // 1 - Use the target definition python file if one is specified. 512 // 2 - If the target definition doesn't have any of the info from the 513 // target.xml (registers) then proceed to read the target.xml. 514 // 3 - Fall back on the qRegisterInfo packets. 515 516 FileSpec target_definition_fspec = 517 GetGlobalPluginProperties()->GetTargetDefinitionFile(); 518 if (!FileSystem::Instance().Exists(target_definition_fspec)) { 519 // If the filename doesn't exist, it may be a ~ not having been expanded - 520 // try to resolve it. 521 FileSystem::Instance().Resolve(target_definition_fspec); 522 } 523 if (target_definition_fspec) { 524 // See if we can get register definitions from a python file 525 if (ParsePythonTargetDefinition(target_definition_fspec)) { 526 return; 527 } else { 528 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); 529 stream_sp->Printf("ERROR: target description file %s failed to parse.\n", 530 target_definition_fspec.GetPath().c_str()); 531 } 532 } 533 534 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 535 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture(); 536 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); 537 538 // Use the process' architecture instead of the host arch, if available 539 ArchSpec arch_to_use; 540 if (remote_process_arch.IsValid()) 541 arch_to_use = remote_process_arch; 542 else 543 arch_to_use = remote_host_arch; 544 545 if (!arch_to_use.IsValid()) 546 arch_to_use = target_arch; 547 548 if (GetGDBServerRegisterInfo(arch_to_use)) 549 return; 550 551 char packet[128]; 552 uint32_t reg_offset = 0; 553 uint32_t reg_num = 0; 554 for (StringExtractorGDBRemote::ResponseType response_type = 555 StringExtractorGDBRemote::eResponse; 556 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) { 557 const int packet_len = 558 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num); 559 assert(packet_len < (int)sizeof(packet)); 560 UNUSED_IF_ASSERT_DISABLED(packet_len); 561 StringExtractorGDBRemote response; 562 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) == 563 GDBRemoteCommunication::PacketResult::Success) { 564 response_type = response.GetResponseType(); 565 if (response_type == StringExtractorGDBRemote::eResponse) { 566 llvm::StringRef name; 567 llvm::StringRef value; 568 ConstString reg_name; 569 ConstString alt_name; 570 ConstString set_name; 571 std::vector<uint32_t> value_regs; 572 std::vector<uint32_t> invalidate_regs; 573 std::vector<uint8_t> dwarf_opcode_bytes; 574 RegisterInfo reg_info = { 575 nullptr, // Name 576 nullptr, // Alt name 577 0, // byte size 578 reg_offset, // offset 579 eEncodingUint, // encoding 580 eFormatHex, // format 581 { 582 LLDB_INVALID_REGNUM, // eh_frame reg num 583 LLDB_INVALID_REGNUM, // DWARF reg num 584 LLDB_INVALID_REGNUM, // generic reg num 585 reg_num, // process plugin reg num 586 reg_num // native register number 587 }, 588 nullptr, 589 nullptr, 590 nullptr, // Dwarf expression opcode bytes pointer 591 0 // Dwarf expression opcode bytes length 592 }; 593 594 while (response.GetNameColonValue(name, value)) { 595 if (name.equals("name")) { 596 reg_name.SetString(value); 597 } else if (name.equals("alt-name")) { 598 alt_name.SetString(value); 599 } else if (name.equals("bitsize")) { 600 value.getAsInteger(0, reg_info.byte_size); 601 reg_info.byte_size /= CHAR_BIT; 602 } else if (name.equals("offset")) { 603 if (value.getAsInteger(0, reg_offset)) 604 reg_offset = UINT32_MAX; 605 } else if (name.equals("encoding")) { 606 const Encoding encoding = Args::StringToEncoding(value); 607 if (encoding != eEncodingInvalid) 608 reg_info.encoding = encoding; 609 } else if (name.equals("format")) { 610 Format format = eFormatInvalid; 611 if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr) 612 .Success()) 613 reg_info.format = format; 614 else { 615 reg_info.format = 616 llvm::StringSwitch<Format>(value) 617 .Case("binary", eFormatBinary) 618 .Case("decimal", eFormatDecimal) 619 .Case("hex", eFormatHex) 620 .Case("float", eFormatFloat) 621 .Case("vector-sint8", eFormatVectorOfSInt8) 622 .Case("vector-uint8", eFormatVectorOfUInt8) 623 .Case("vector-sint16", eFormatVectorOfSInt16) 624 .Case("vector-uint16", eFormatVectorOfUInt16) 625 .Case("vector-sint32", eFormatVectorOfSInt32) 626 .Case("vector-uint32", eFormatVectorOfUInt32) 627 .Case("vector-float32", eFormatVectorOfFloat32) 628 .Case("vector-uint64", eFormatVectorOfUInt64) 629 .Case("vector-uint128", eFormatVectorOfUInt128) 630 .Default(eFormatInvalid); 631 } 632 } else if (name.equals("set")) { 633 set_name.SetString(value); 634 } else if (name.equals("gcc") || name.equals("ehframe")) { 635 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame])) 636 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM; 637 } else if (name.equals("dwarf")) { 638 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF])) 639 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM; 640 } else if (name.equals("generic")) { 641 reg_info.kinds[eRegisterKindGeneric] = 642 Args::StringToGenericRegister(value); 643 } else if (name.equals("container-regs")) { 644 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16); 645 } else if (name.equals("invalidate-regs")) { 646 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16); 647 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) { 648 size_t dwarf_opcode_len = value.size() / 2; 649 assert(dwarf_opcode_len > 0); 650 651 dwarf_opcode_bytes.resize(dwarf_opcode_len); 652 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; 653 654 StringExtractor opcode_extractor(value); 655 uint32_t ret_val = 656 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); 657 assert(dwarf_opcode_len == ret_val); 658 UNUSED_IF_ASSERT_DISABLED(ret_val); 659 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); 660 } 661 } 662 663 reg_info.byte_offset = reg_offset; 664 assert(reg_info.byte_size != 0); 665 reg_offset += reg_info.byte_size; 666 if (!value_regs.empty()) { 667 value_regs.push_back(LLDB_INVALID_REGNUM); 668 reg_info.value_regs = value_regs.data(); 669 } 670 if (!invalidate_regs.empty()) { 671 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 672 reg_info.invalidate_regs = invalidate_regs.data(); 673 } 674 675 // We have to make a temporary ABI here, and not use the GetABI because 676 // this code gets called in DidAttach, when the target architecture 677 // (and consequently the ABI we'll get from the process) may be wrong. 678 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use); 679 680 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use); 681 682 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 683 } else { 684 break; // ensure exit before reg_num is incremented 685 } 686 } else { 687 break; 688 } 689 } 690 691 if (m_register_info.GetNumRegisters() > 0) { 692 m_register_info.Finalize(GetTarget().GetArchitecture()); 693 return; 694 } 695 696 // We didn't get anything if the accumulated reg_num is zero. See if we are 697 // debugging ARM and fill with a hard coded register set until we can get an 698 // updated debugserver down on the devices. On the other hand, if the 699 // accumulated reg_num is positive, see if we can add composite registers to 700 // the existing primordial ones. 701 bool from_scratch = (m_register_info.GetNumRegisters() == 0); 702 703 if (!target_arch.IsValid()) { 704 if (arch_to_use.IsValid() && 705 (arch_to_use.GetMachine() == llvm::Triple::arm || 706 arch_to_use.GetMachine() == llvm::Triple::thumb) && 707 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple) 708 m_register_info.HardcodeARMRegisters(from_scratch); 709 } else if (target_arch.GetMachine() == llvm::Triple::arm || 710 target_arch.GetMachine() == llvm::Triple::thumb) { 711 m_register_info.HardcodeARMRegisters(from_scratch); 712 } 713 714 // At this point, we can finalize our register info. 715 m_register_info.Finalize(GetTarget().GetArchitecture()); 716 } 717 718 Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) { 719 return WillLaunchOrAttach(); 720 } 721 722 Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) { 723 return WillLaunchOrAttach(); 724 } 725 726 Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name, 727 bool wait_for_launch) { 728 return WillLaunchOrAttach(); 729 } 730 731 Status ProcessGDBRemote::DoConnectRemote(Stream *strm, 732 llvm::StringRef remote_url) { 733 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 734 Status error(WillLaunchOrAttach()); 735 736 if (error.Fail()) 737 return error; 738 739 error = ConnectToDebugserver(remote_url); 740 741 if (error.Fail()) 742 return error; 743 StartAsyncThread(); 744 745 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 746 if (pid == LLDB_INVALID_PROCESS_ID) { 747 // We don't have a valid process ID, so note that we are connected and 748 // could now request to launch or attach, or get remote process listings... 749 SetPrivateState(eStateConnected); 750 } else { 751 // We have a valid process 752 SetID(pid); 753 GetThreadList(); 754 StringExtractorGDBRemote response; 755 if (m_gdb_comm.GetStopReply(response)) { 756 SetLastStopPacket(response); 757 758 // '?' Packets must be handled differently in non-stop mode 759 if (GetTarget().GetNonStopModeEnabled()) 760 HandleStopReplySequence(); 761 762 Target &target = GetTarget(); 763 if (!target.GetArchitecture().IsValid()) { 764 if (m_gdb_comm.GetProcessArchitecture().IsValid()) { 765 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 766 } else { 767 if (m_gdb_comm.GetHostArchitecture().IsValid()) { 768 target.SetArchitecture(m_gdb_comm.GetHostArchitecture()); 769 } 770 } 771 } 772 773 const StateType state = SetThreadStopInfo(response); 774 if (state != eStateInvalid) { 775 SetPrivateState(state); 776 } else 777 error.SetErrorStringWithFormat( 778 "Process %" PRIu64 " was reported after connecting to " 779 "'%s', but state was not stopped: %s", 780 pid, remote_url.str().c_str(), StateAsCString(state)); 781 } else 782 error.SetErrorStringWithFormat("Process %" PRIu64 783 " was reported after connecting to '%s', " 784 "but no stop reply packet was received", 785 pid, remote_url.str().c_str()); 786 } 787 788 if (log) 789 log->Printf("ProcessGDBRemote::%s pid %" PRIu64 790 ": normalizing target architecture initial triple: %s " 791 "(GetTarget().GetArchitecture().IsValid() %s, " 792 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)", 793 __FUNCTION__, GetID(), 794 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(), 795 GetTarget().GetArchitecture().IsValid() ? "true" : "false", 796 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false"); 797 798 if (error.Success() && !GetTarget().GetArchitecture().IsValid() && 799 m_gdb_comm.GetHostArchitecture().IsValid()) { 800 // Prefer the *process'* architecture over that of the *host*, if 801 // available. 802 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 803 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 804 else 805 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture()); 806 } 807 808 if (log) 809 log->Printf("ProcessGDBRemote::%s pid %" PRIu64 810 ": normalized target architecture triple: %s", 811 __FUNCTION__, GetID(), 812 GetTarget().GetArchitecture().GetTriple().getTriple().c_str()); 813 814 if (error.Success()) { 815 PlatformSP platform_sp = GetTarget().GetPlatform(); 816 if (platform_sp && platform_sp->IsConnected()) 817 SetUnixSignals(platform_sp->GetUnixSignals()); 818 else 819 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture())); 820 } 821 822 return error; 823 } 824 825 Status ProcessGDBRemote::WillLaunchOrAttach() { 826 Status error; 827 m_stdio_communication.Clear(); 828 return error; 829 } 830 831 // Process Control 832 Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module, 833 ProcessLaunchInfo &launch_info) { 834 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 835 Status error; 836 837 if (log) 838 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__); 839 840 uint32_t launch_flags = launch_info.GetFlags().Get(); 841 FileSpec stdin_file_spec{}; 842 FileSpec stdout_file_spec{}; 843 FileSpec stderr_file_spec{}; 844 FileSpec working_dir = launch_info.GetWorkingDirectory(); 845 846 const FileAction *file_action; 847 file_action = launch_info.GetFileActionForFD(STDIN_FILENO); 848 if (file_action) { 849 if (file_action->GetAction() == FileAction::eFileActionOpen) 850 stdin_file_spec = file_action->GetFileSpec(); 851 } 852 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO); 853 if (file_action) { 854 if (file_action->GetAction() == FileAction::eFileActionOpen) 855 stdout_file_spec = file_action->GetFileSpec(); 856 } 857 file_action = launch_info.GetFileActionForFD(STDERR_FILENO); 858 if (file_action) { 859 if (file_action->GetAction() == FileAction::eFileActionOpen) 860 stderr_file_spec = file_action->GetFileSpec(); 861 } 862 863 if (log) { 864 if (stdin_file_spec || stdout_file_spec || stderr_file_spec) 865 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via " 866 "launch_info: stdin=%s, stdout=%s, stderr=%s", 867 __FUNCTION__, 868 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 869 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 870 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>"); 871 else 872 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info", 873 __FUNCTION__); 874 } 875 876 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 877 if (stdin_file_spec || disable_stdio) { 878 // the inferior will be reading stdin from the specified file or stdio is 879 // completely disabled 880 m_stdin_forward = false; 881 } else { 882 m_stdin_forward = true; 883 } 884 885 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 886 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | 887 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP | 888 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 889 // ::LogSetLogFile ("/dev/stdout"); 890 891 ObjectFile *object_file = exe_module->GetObjectFile(); 892 if (object_file) { 893 error = EstablishConnectionIfNeeded(launch_info); 894 if (error.Success()) { 895 PseudoTerminal pty; 896 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 897 898 PlatformSP platform_sp(GetTarget().GetPlatform()); 899 if (disable_stdio) { 900 // set to /dev/null unless redirected to a file above 901 if (!stdin_file_spec) 902 stdin_file_spec.SetFile(FileSystem::DEV_NULL, 903 FileSpec::Style::native); 904 if (!stdout_file_spec) 905 stdout_file_spec.SetFile(FileSystem::DEV_NULL, 906 FileSpec::Style::native); 907 if (!stderr_file_spec) 908 stderr_file_spec.SetFile(FileSystem::DEV_NULL, 909 FileSpec::Style::native); 910 } else if (platform_sp && platform_sp->IsHost()) { 911 // If the debugserver is local and we aren't disabling STDIO, lets use 912 // a pseudo terminal to instead of relying on the 'O' packets for stdio 913 // since 'O' packets can really slow down debugging if the inferior 914 // does a lot of output. 915 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) && 916 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, nullptr, 0)) { 917 FileSpec slave_name{pty.GetSlaveName(nullptr, 0)}; 918 919 if (!stdin_file_spec) 920 stdin_file_spec = slave_name; 921 922 if (!stdout_file_spec) 923 stdout_file_spec = slave_name; 924 925 if (!stderr_file_spec) 926 stderr_file_spec = slave_name; 927 } 928 if (log) 929 log->Printf( 930 "ProcessGDBRemote::%s adjusted STDIO paths for local platform " 931 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s", 932 __FUNCTION__, 933 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 934 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 935 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>"); 936 } 937 938 if (log) 939 log->Printf("ProcessGDBRemote::%s final STDIO paths after all " 940 "adjustments: stdin=%s, stdout=%s, stderr=%s", 941 __FUNCTION__, 942 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 943 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 944 stderr_file_spec ? stderr_file_spec.GetCString() 945 : "<null>"); 946 947 if (stdin_file_spec) 948 m_gdb_comm.SetSTDIN(stdin_file_spec); 949 if (stdout_file_spec) 950 m_gdb_comm.SetSTDOUT(stdout_file_spec); 951 if (stderr_file_spec) 952 m_gdb_comm.SetSTDERR(stderr_file_spec); 953 954 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR); 955 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError); 956 957 m_gdb_comm.SendLaunchArchPacket( 958 GetTarget().GetArchitecture().GetArchitectureName()); 959 960 const char *launch_event_data = launch_info.GetLaunchEventData(); 961 if (launch_event_data != nullptr && *launch_event_data != '\0') 962 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data); 963 964 if (working_dir) { 965 m_gdb_comm.SetWorkingDir(working_dir); 966 } 967 968 // Send the environment and the program + arguments after we connect 969 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment()); 970 971 { 972 // Scope for the scoped timeout object 973 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 974 std::chrono::seconds(10)); 975 976 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info); 977 if (arg_packet_err == 0) { 978 std::string error_str; 979 if (m_gdb_comm.GetLaunchSuccess(error_str)) { 980 SetID(m_gdb_comm.GetCurrentProcessID()); 981 } else { 982 error.SetErrorString(error_str.c_str()); 983 } 984 } else { 985 error.SetErrorStringWithFormat("'A' packet returned an error: %i", 986 arg_packet_err); 987 } 988 } 989 990 if (GetID() == LLDB_INVALID_PROCESS_ID) { 991 if (log) 992 log->Printf("failed to connect to debugserver: %s", 993 error.AsCString()); 994 KillDebugserverProcess(); 995 return error; 996 } 997 998 StringExtractorGDBRemote response; 999 if (m_gdb_comm.GetStopReply(response)) { 1000 SetLastStopPacket(response); 1001 // '?' Packets must be handled differently in non-stop mode 1002 if (GetTarget().GetNonStopModeEnabled()) 1003 HandleStopReplySequence(); 1004 1005 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture(); 1006 1007 if (process_arch.IsValid()) { 1008 GetTarget().MergeArchitecture(process_arch); 1009 } else { 1010 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture(); 1011 if (host_arch.IsValid()) 1012 GetTarget().MergeArchitecture(host_arch); 1013 } 1014 1015 SetPrivateState(SetThreadStopInfo(response)); 1016 1017 if (!disable_stdio) { 1018 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd) 1019 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor()); 1020 } 1021 } 1022 } else { 1023 if (log) 1024 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 1025 } 1026 } else { 1027 // Set our user ID to an invalid process ID. 1028 SetID(LLDB_INVALID_PROCESS_ID); 1029 error.SetErrorStringWithFormat( 1030 "failed to get object file from '%s' for arch %s", 1031 exe_module->GetFileSpec().GetFilename().AsCString(), 1032 exe_module->GetArchitecture().GetArchitectureName()); 1033 } 1034 return error; 1035 } 1036 1037 Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) { 1038 Status error; 1039 // Only connect if we have a valid connect URL 1040 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1041 1042 if (!connect_url.empty()) { 1043 if (log) 1044 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, 1045 connect_url.str().c_str()); 1046 std::unique_ptr<ConnectionFileDescriptor> conn_up( 1047 new ConnectionFileDescriptor()); 1048 if (conn_up) { 1049 const uint32_t max_retry_count = 50; 1050 uint32_t retry_count = 0; 1051 while (!m_gdb_comm.IsConnected()) { 1052 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) { 1053 m_gdb_comm.SetConnection(conn_up.release()); 1054 break; 1055 } else if (error.WasInterrupted()) { 1056 // If we were interrupted, don't keep retrying. 1057 break; 1058 } 1059 1060 retry_count++; 1061 1062 if (retry_count >= max_retry_count) 1063 break; 1064 1065 usleep(100000); 1066 } 1067 } 1068 } 1069 1070 if (!m_gdb_comm.IsConnected()) { 1071 if (error.Success()) 1072 error.SetErrorString("not connected to remote gdb server"); 1073 return error; 1074 } 1075 1076 // Start the communications read thread so all incoming data can be parsed 1077 // into packets and queued as they arrive. 1078 if (GetTarget().GetNonStopModeEnabled()) 1079 m_gdb_comm.StartReadThread(); 1080 1081 // We always seem to be able to open a connection to a local port so we need 1082 // to make sure we can then send data to it. If we can't then we aren't 1083 // actually connected to anything, so try and do the handshake with the 1084 // remote GDB server and make sure that goes alright. 1085 if (!m_gdb_comm.HandshakeWithServer(&error)) { 1086 m_gdb_comm.Disconnect(); 1087 if (error.Success()) 1088 error.SetErrorString("not connected to remote gdb server"); 1089 return error; 1090 } 1091 1092 // Send $QNonStop:1 packet on startup if required 1093 if (GetTarget().GetNonStopModeEnabled()) 1094 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true)); 1095 1096 m_gdb_comm.GetEchoSupported(); 1097 m_gdb_comm.GetThreadSuffixSupported(); 1098 m_gdb_comm.GetListThreadsInStopReplySupported(); 1099 m_gdb_comm.GetHostInfo(); 1100 m_gdb_comm.GetVContSupported('c'); 1101 m_gdb_comm.GetVAttachOrWaitSupported(); 1102 m_gdb_comm.EnableErrorStringInPacket(); 1103 1104 // Ask the remote server for the default thread id 1105 if (GetTarget().GetNonStopModeEnabled()) 1106 m_gdb_comm.GetDefaultThreadId(m_initial_tid); 1107 1108 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount(); 1109 for (size_t idx = 0; idx < num_cmds; idx++) { 1110 StringExtractorGDBRemote response; 1111 m_gdb_comm.SendPacketAndWaitForResponse( 1112 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); 1113 } 1114 return error; 1115 } 1116 1117 void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) { 1118 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1119 if (log) 1120 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__); 1121 if (GetID() != LLDB_INVALID_PROCESS_ID) { 1122 BuildDynamicRegisterInfo(false); 1123 1124 // See if the GDB server supports the qHostInfo information 1125 1126 // See if the GDB server supports the qProcessInfo packet, if so prefer 1127 // that over the Host information as it will be more specific to our 1128 // process. 1129 1130 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); 1131 if (remote_process_arch.IsValid()) { 1132 process_arch = remote_process_arch; 1133 if (log) 1134 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, " 1135 "using %s %s", 1136 __FUNCTION__, 1137 process_arch.GetArchitectureName() 1138 ? process_arch.GetArchitectureName() 1139 : "<null>", 1140 process_arch.GetTriple().getTriple().c_str() 1141 ? process_arch.GetTriple().getTriple().c_str() 1142 : "<null>"); 1143 } else { 1144 process_arch = m_gdb_comm.GetHostArchitecture(); 1145 if (log) 1146 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process " 1147 "architecture, using gdb-remote host architecture %s %s", 1148 __FUNCTION__, 1149 process_arch.GetArchitectureName() 1150 ? process_arch.GetArchitectureName() 1151 : "<null>", 1152 process_arch.GetTriple().getTriple().c_str() 1153 ? process_arch.GetTriple().getTriple().c_str() 1154 : "<null>"); 1155 } 1156 1157 if (process_arch.IsValid()) { 1158 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 1159 if (target_arch.IsValid()) { 1160 if (log) 1161 log->Printf( 1162 "ProcessGDBRemote::%s analyzing target arch, currently %s %s", 1163 __FUNCTION__, 1164 target_arch.GetArchitectureName() 1165 ? target_arch.GetArchitectureName() 1166 : "<null>", 1167 target_arch.GetTriple().getTriple().c_str() 1168 ? target_arch.GetTriple().getTriple().c_str() 1169 : "<null>"); 1170 1171 // If the remote host is ARM and we have apple as the vendor, then 1172 // ARM executables and shared libraries can have mixed ARM 1173 // architectures. 1174 // You can have an armv6 executable, and if the host is armv7, then the 1175 // system will load the best possible architecture for all shared 1176 // libraries it has, so we really need to take the remote host 1177 // architecture as our defacto architecture in this case. 1178 1179 if ((process_arch.GetMachine() == llvm::Triple::arm || 1180 process_arch.GetMachine() == llvm::Triple::thumb) && 1181 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) { 1182 GetTarget().SetArchitecture(process_arch); 1183 if (log) 1184 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, " 1185 "setting target arch to %s %s", 1186 __FUNCTION__, 1187 process_arch.GetArchitectureName() 1188 ? process_arch.GetArchitectureName() 1189 : "<null>", 1190 process_arch.GetTriple().getTriple().c_str() 1191 ? process_arch.GetTriple().getTriple().c_str() 1192 : "<null>"); 1193 } else { 1194 // Fill in what is missing in the triple 1195 const llvm::Triple &remote_triple = process_arch.GetTriple(); 1196 llvm::Triple new_target_triple = target_arch.GetTriple(); 1197 if (new_target_triple.getVendorName().size() == 0) { 1198 new_target_triple.setVendor(remote_triple.getVendor()); 1199 1200 if (new_target_triple.getOSName().size() == 0) { 1201 new_target_triple.setOS(remote_triple.getOS()); 1202 1203 if (new_target_triple.getEnvironmentName().size() == 0) 1204 new_target_triple.setEnvironment( 1205 remote_triple.getEnvironment()); 1206 } 1207 1208 ArchSpec new_target_arch = target_arch; 1209 new_target_arch.SetTriple(new_target_triple); 1210 GetTarget().SetArchitecture(new_target_arch); 1211 } 1212 } 1213 1214 if (log) 1215 log->Printf("ProcessGDBRemote::%s final target arch after " 1216 "adjustments for remote architecture: %s %s", 1217 __FUNCTION__, 1218 target_arch.GetArchitectureName() 1219 ? target_arch.GetArchitectureName() 1220 : "<null>", 1221 target_arch.GetTriple().getTriple().c_str() 1222 ? target_arch.GetTriple().getTriple().c_str() 1223 : "<null>"); 1224 } else { 1225 // The target doesn't have a valid architecture yet, set it from the 1226 // architecture we got from the remote GDB server 1227 GetTarget().SetArchitecture(process_arch); 1228 } 1229 } 1230 1231 // Find out which StructuredDataPlugins are supported by the debug monitor. 1232 // These plugins transmit data over async $J packets. 1233 auto supported_packets_array = 1234 m_gdb_comm.GetSupportedStructuredDataPlugins(); 1235 if (supported_packets_array) 1236 MapSupportedStructuredDataPlugins(*supported_packets_array); 1237 } 1238 } 1239 1240 void ProcessGDBRemote::DidLaunch() { 1241 ArchSpec process_arch; 1242 DidLaunchOrAttach(process_arch); 1243 } 1244 1245 Status ProcessGDBRemote::DoAttachToProcessWithID( 1246 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) { 1247 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1248 Status error; 1249 1250 if (log) 1251 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__); 1252 1253 // Clear out and clean up from any current state 1254 Clear(); 1255 if (attach_pid != LLDB_INVALID_PROCESS_ID) { 1256 error = EstablishConnectionIfNeeded(attach_info); 1257 if (error.Success()) { 1258 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); 1259 1260 char packet[64]; 1261 const int packet_len = 1262 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid); 1263 SetID(attach_pid); 1264 m_async_broadcaster.BroadcastEvent( 1265 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len)); 1266 } else 1267 SetExitStatus(-1, error.AsCString()); 1268 } 1269 1270 return error; 1271 } 1272 1273 Status ProcessGDBRemote::DoAttachToProcessWithName( 1274 const char *process_name, const ProcessAttachInfo &attach_info) { 1275 Status error; 1276 // Clear out and clean up from any current state 1277 Clear(); 1278 1279 if (process_name && process_name[0]) { 1280 error = EstablishConnectionIfNeeded(attach_info); 1281 if (error.Success()) { 1282 StreamString packet; 1283 1284 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); 1285 1286 if (attach_info.GetWaitForLaunch()) { 1287 if (!m_gdb_comm.GetVAttachOrWaitSupported()) { 1288 packet.PutCString("vAttachWait"); 1289 } else { 1290 if (attach_info.GetIgnoreExisting()) 1291 packet.PutCString("vAttachWait"); 1292 else 1293 packet.PutCString("vAttachOrWait"); 1294 } 1295 } else 1296 packet.PutCString("vAttachName"); 1297 packet.PutChar(';'); 1298 packet.PutBytesAsRawHex8(process_name, strlen(process_name), 1299 endian::InlHostByteOrder(), 1300 endian::InlHostByteOrder()); 1301 1302 m_async_broadcaster.BroadcastEvent( 1303 eBroadcastBitAsyncContinue, 1304 new EventDataBytes(packet.GetString().data(), packet.GetSize())); 1305 1306 } else 1307 SetExitStatus(-1, error.AsCString()); 1308 } 1309 return error; 1310 } 1311 1312 lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options, 1313 Status &error) { 1314 return m_gdb_comm.SendStartTracePacket(options, error); 1315 } 1316 1317 Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) { 1318 return m_gdb_comm.SendStopTracePacket(uid, thread_id); 1319 } 1320 1321 Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id, 1322 llvm::MutableArrayRef<uint8_t> &buffer, 1323 size_t offset) { 1324 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset); 1325 } 1326 1327 Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id, 1328 llvm::MutableArrayRef<uint8_t> &buffer, 1329 size_t offset) { 1330 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset); 1331 } 1332 1333 Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid, 1334 TraceOptions &options) { 1335 return m_gdb_comm.SendGetTraceConfigPacket(uid, options); 1336 } 1337 1338 void ProcessGDBRemote::DidExit() { 1339 // When we exit, disconnect from the GDB server communications 1340 m_gdb_comm.Disconnect(); 1341 } 1342 1343 void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) { 1344 // If you can figure out what the architecture is, fill it in here. 1345 process_arch.Clear(); 1346 DidLaunchOrAttach(process_arch); 1347 } 1348 1349 Status ProcessGDBRemote::WillResume() { 1350 m_continue_c_tids.clear(); 1351 m_continue_C_tids.clear(); 1352 m_continue_s_tids.clear(); 1353 m_continue_S_tids.clear(); 1354 m_jstopinfo_sp.reset(); 1355 m_jthreadsinfo_sp.reset(); 1356 return Status(); 1357 } 1358 1359 Status ProcessGDBRemote::DoResume() { 1360 Status error; 1361 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1362 if (log) 1363 log->Printf("ProcessGDBRemote::Resume()"); 1364 1365 ListenerSP listener_sp( 1366 Listener::MakeListener("gdb-remote.resume-packet-sent")); 1367 if (listener_sp->StartListeningForEvents( 1368 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) { 1369 listener_sp->StartListeningForEvents( 1370 &m_async_broadcaster, 1371 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 1372 1373 const size_t num_threads = GetThreadList().GetSize(); 1374 1375 StreamString continue_packet; 1376 bool continue_packet_error = false; 1377 if (m_gdb_comm.HasAnyVContSupport()) { 1378 if (!GetTarget().GetNonStopModeEnabled() && 1379 (m_continue_c_tids.size() == num_threads || 1380 (m_continue_c_tids.empty() && m_continue_C_tids.empty() && 1381 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) { 1382 // All threads are continuing, just send a "c" packet 1383 continue_packet.PutCString("c"); 1384 } else { 1385 continue_packet.PutCString("vCont"); 1386 1387 if (!m_continue_c_tids.empty()) { 1388 if (m_gdb_comm.GetVContSupported('c')) { 1389 for (tid_collection::const_iterator 1390 t_pos = m_continue_c_tids.begin(), 1391 t_end = m_continue_c_tids.end(); 1392 t_pos != t_end; ++t_pos) 1393 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos); 1394 } else 1395 continue_packet_error = true; 1396 } 1397 1398 if (!continue_packet_error && !m_continue_C_tids.empty()) { 1399 if (m_gdb_comm.GetVContSupported('C')) { 1400 for (tid_sig_collection::const_iterator 1401 s_pos = m_continue_C_tids.begin(), 1402 s_end = m_continue_C_tids.end(); 1403 s_pos != s_end; ++s_pos) 1404 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, 1405 s_pos->first); 1406 } else 1407 continue_packet_error = true; 1408 } 1409 1410 if (!continue_packet_error && !m_continue_s_tids.empty()) { 1411 if (m_gdb_comm.GetVContSupported('s')) { 1412 for (tid_collection::const_iterator 1413 t_pos = m_continue_s_tids.begin(), 1414 t_end = m_continue_s_tids.end(); 1415 t_pos != t_end; ++t_pos) 1416 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos); 1417 } else 1418 continue_packet_error = true; 1419 } 1420 1421 if (!continue_packet_error && !m_continue_S_tids.empty()) { 1422 if (m_gdb_comm.GetVContSupported('S')) { 1423 for (tid_sig_collection::const_iterator 1424 s_pos = m_continue_S_tids.begin(), 1425 s_end = m_continue_S_tids.end(); 1426 s_pos != s_end; ++s_pos) 1427 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, 1428 s_pos->first); 1429 } else 1430 continue_packet_error = true; 1431 } 1432 1433 if (continue_packet_error) 1434 continue_packet.Clear(); 1435 } 1436 } else 1437 continue_packet_error = true; 1438 1439 if (continue_packet_error) { 1440 // Either no vCont support, or we tried to use part of the vCont packet 1441 // that wasn't supported by the remote GDB server. We need to try and 1442 // make a simple packet that can do our continue 1443 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1444 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1445 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1446 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1447 if (num_continue_c_tids > 0) { 1448 if (num_continue_c_tids == num_threads) { 1449 // All threads are resuming... 1450 m_gdb_comm.SetCurrentThreadForRun(-1); 1451 continue_packet.PutChar('c'); 1452 continue_packet_error = false; 1453 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 && 1454 num_continue_s_tids == 0 && num_continue_S_tids == 0) { 1455 // Only one thread is continuing 1456 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front()); 1457 continue_packet.PutChar('c'); 1458 continue_packet_error = false; 1459 } 1460 } 1461 1462 if (continue_packet_error && num_continue_C_tids > 0) { 1463 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1464 num_continue_C_tids > 0 && num_continue_s_tids == 0 && 1465 num_continue_S_tids == 0) { 1466 const int continue_signo = m_continue_C_tids.front().second; 1467 // Only one thread is continuing 1468 if (num_continue_C_tids > 1) { 1469 // More that one thread with a signal, yet we don't have vCont 1470 // support and we are being asked to resume each thread with a 1471 // signal, we need to make sure they are all the same signal, or we 1472 // can't issue the continue accurately with the current support... 1473 if (num_continue_C_tids > 1) { 1474 continue_packet_error = false; 1475 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) { 1476 if (m_continue_C_tids[i].second != continue_signo) 1477 continue_packet_error = true; 1478 } 1479 } 1480 if (!continue_packet_error) 1481 m_gdb_comm.SetCurrentThreadForRun(-1); 1482 } else { 1483 // Set the continue thread ID 1484 continue_packet_error = false; 1485 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first); 1486 } 1487 if (!continue_packet_error) { 1488 // Add threads continuing with the same signo... 1489 continue_packet.Printf("C%2.2x", continue_signo); 1490 } 1491 } 1492 } 1493 1494 if (continue_packet_error && num_continue_s_tids > 0) { 1495 if (num_continue_s_tids == num_threads) { 1496 // All threads are resuming... 1497 m_gdb_comm.SetCurrentThreadForRun(-1); 1498 1499 // If in Non-Stop-Mode use vCont when stepping 1500 if (GetTarget().GetNonStopModeEnabled()) { 1501 if (m_gdb_comm.GetVContSupported('s')) 1502 continue_packet.PutCString("vCont;s"); 1503 else 1504 continue_packet.PutChar('s'); 1505 } else 1506 continue_packet.PutChar('s'); 1507 1508 continue_packet_error = false; 1509 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && 1510 num_continue_s_tids == 1 && num_continue_S_tids == 0) { 1511 // Only one thread is stepping 1512 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front()); 1513 continue_packet.PutChar('s'); 1514 continue_packet_error = false; 1515 } 1516 } 1517 1518 if (!continue_packet_error && num_continue_S_tids > 0) { 1519 if (num_continue_S_tids == num_threads) { 1520 const int step_signo = m_continue_S_tids.front().second; 1521 // Are all threads trying to step with the same signal? 1522 continue_packet_error = false; 1523 if (num_continue_S_tids > 1) { 1524 for (size_t i = 1; i < num_threads; ++i) { 1525 if (m_continue_S_tids[i].second != step_signo) 1526 continue_packet_error = true; 1527 } 1528 } 1529 if (!continue_packet_error) { 1530 // Add threads stepping with the same signo... 1531 m_gdb_comm.SetCurrentThreadForRun(-1); 1532 continue_packet.Printf("S%2.2x", step_signo); 1533 } 1534 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && 1535 num_continue_s_tids == 0 && num_continue_S_tids == 1) { 1536 // Only one thread is stepping with signal 1537 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first); 1538 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1539 continue_packet_error = false; 1540 } 1541 } 1542 } 1543 1544 if (continue_packet_error) { 1545 error.SetErrorString("can't make continue packet for this resume"); 1546 } else { 1547 EventSP event_sp; 1548 if (!m_async_thread.IsJoinable()) { 1549 error.SetErrorString("Trying to resume but the async thread is dead."); 1550 if (log) 1551 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the " 1552 "async thread is dead."); 1553 return error; 1554 } 1555 1556 m_async_broadcaster.BroadcastEvent( 1557 eBroadcastBitAsyncContinue, 1558 new EventDataBytes(continue_packet.GetString().data(), 1559 continue_packet.GetSize())); 1560 1561 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) { 1562 error.SetErrorString("Resume timed out."); 1563 if (log) 1564 log->Printf("ProcessGDBRemote::DoResume: Resume timed out."); 1565 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) { 1566 error.SetErrorString("Broadcast continue, but the async thread was " 1567 "killed before we got an ack back."); 1568 if (log) 1569 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the " 1570 "async thread was killed before we got an ack back."); 1571 return error; 1572 } 1573 } 1574 } 1575 1576 return error; 1577 } 1578 1579 void ProcessGDBRemote::HandleStopReplySequence() { 1580 while (true) { 1581 // Send vStopped 1582 StringExtractorGDBRemote response; 1583 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false); 1584 1585 // OK represents end of signal list 1586 if (response.IsOKResponse()) 1587 break; 1588 1589 // If not OK or a normal packet we have a problem 1590 if (!response.IsNormalResponse()) 1591 break; 1592 1593 SetLastStopPacket(response); 1594 } 1595 } 1596 1597 void ProcessGDBRemote::ClearThreadIDList() { 1598 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1599 m_thread_ids.clear(); 1600 m_thread_pcs.clear(); 1601 } 1602 1603 size_t 1604 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) { 1605 m_thread_ids.clear(); 1606 size_t comma_pos; 1607 lldb::tid_t tid; 1608 while ((comma_pos = value.find(',')) != std::string::npos) { 1609 value[comma_pos] = '\0'; 1610 // thread in big endian hex 1611 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1612 if (tid != LLDB_INVALID_THREAD_ID) 1613 m_thread_ids.push_back(tid); 1614 value.erase(0, comma_pos + 1); 1615 } 1616 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1617 if (tid != LLDB_INVALID_THREAD_ID) 1618 m_thread_ids.push_back(tid); 1619 return m_thread_ids.size(); 1620 } 1621 1622 size_t 1623 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) { 1624 m_thread_pcs.clear(); 1625 size_t comma_pos; 1626 lldb::addr_t pc; 1627 while ((comma_pos = value.find(',')) != std::string::npos) { 1628 value[comma_pos] = '\0'; 1629 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16); 1630 if (pc != LLDB_INVALID_ADDRESS) 1631 m_thread_pcs.push_back(pc); 1632 value.erase(0, comma_pos + 1); 1633 } 1634 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16); 1635 if (pc != LLDB_INVALID_THREAD_ID) 1636 m_thread_pcs.push_back(pc); 1637 return m_thread_pcs.size(); 1638 } 1639 1640 bool ProcessGDBRemote::UpdateThreadIDList() { 1641 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1642 1643 if (m_jthreadsinfo_sp) { 1644 // If we have the JSON threads info, we can get the thread list from that 1645 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 1646 if (thread_infos && thread_infos->GetSize() > 0) { 1647 m_thread_ids.clear(); 1648 m_thread_pcs.clear(); 1649 thread_infos->ForEach([this](StructuredData::Object *object) -> bool { 1650 StructuredData::Dictionary *thread_dict = object->GetAsDictionary(); 1651 if (thread_dict) { 1652 // Set the thread stop info from the JSON dictionary 1653 SetThreadStopInfo(thread_dict); 1654 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1655 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid)) 1656 m_thread_ids.push_back(tid); 1657 } 1658 return true; // Keep iterating through all thread_info objects 1659 }); 1660 } 1661 if (!m_thread_ids.empty()) 1662 return true; 1663 } else { 1664 // See if we can get the thread IDs from the current stop reply packets 1665 // that might contain a "threads" key/value pair 1666 1667 // Lock the thread stack while we access it 1668 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 1669 std::unique_lock<std::recursive_mutex> stop_stack_lock( 1670 m_last_stop_packet_mutex, std::defer_lock); 1671 if (stop_stack_lock.try_lock()) { 1672 // Get the number of stop packets on the stack 1673 int nItems = m_stop_packet_stack.size(); 1674 // Iterate over them 1675 for (int i = 0; i < nItems; i++) { 1676 // Get the thread stop info 1677 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i]; 1678 const std::string &stop_info_str = stop_info.GetStringRef(); 1679 1680 m_thread_pcs.clear(); 1681 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:"); 1682 if (thread_pcs_pos != std::string::npos) { 1683 const size_t start = thread_pcs_pos + strlen(";thread-pcs:"); 1684 const size_t end = stop_info_str.find(';', start); 1685 if (end != std::string::npos) { 1686 std::string value = stop_info_str.substr(start, end - start); 1687 UpdateThreadPCsFromStopReplyThreadsValue(value); 1688 } 1689 } 1690 1691 const size_t threads_pos = stop_info_str.find(";threads:"); 1692 if (threads_pos != std::string::npos) { 1693 const size_t start = threads_pos + strlen(";threads:"); 1694 const size_t end = stop_info_str.find(';', start); 1695 if (end != std::string::npos) { 1696 std::string value = stop_info_str.substr(start, end - start); 1697 if (UpdateThreadIDsFromStopReplyThreadsValue(value)) 1698 return true; 1699 } 1700 } 1701 } 1702 } 1703 } 1704 1705 bool sequence_mutex_unavailable = false; 1706 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable); 1707 if (sequence_mutex_unavailable) { 1708 return false; // We just didn't get the list 1709 } 1710 return true; 1711 } 1712 1713 bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list, 1714 ThreadList &new_thread_list) { 1715 // locker will keep a mutex locked until it goes out of scope 1716 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD)); 1717 LLDB_LOGV(log, "pid = {0}", GetID()); 1718 1719 size_t num_thread_ids = m_thread_ids.size(); 1720 // The "m_thread_ids" thread ID list should always be updated after each stop 1721 // reply packet, but in case it isn't, update it here. 1722 if (num_thread_ids == 0) { 1723 if (!UpdateThreadIDList()) 1724 return false; 1725 num_thread_ids = m_thread_ids.size(); 1726 } 1727 1728 ThreadList old_thread_list_copy(old_thread_list); 1729 if (num_thread_ids > 0) { 1730 for (size_t i = 0; i < num_thread_ids; ++i) { 1731 tid_t tid = m_thread_ids[i]; 1732 ThreadSP thread_sp( 1733 old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); 1734 if (!thread_sp) { 1735 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); 1736 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.", 1737 thread_sp.get(), thread_sp->GetID()); 1738 } else { 1739 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.", 1740 thread_sp.get(), thread_sp->GetID()); 1741 } 1742 1743 SetThreadPc(thread_sp, i); 1744 new_thread_list.AddThreadSortedByIndexID(thread_sp); 1745 } 1746 } 1747 1748 // Whatever that is left in old_thread_list_copy are not present in 1749 // new_thread_list. Remove non-existent threads from internal id table. 1750 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); 1751 for (size_t i = 0; i < old_num_thread_ids; i++) { 1752 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false)); 1753 if (old_thread_sp) { 1754 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); 1755 m_thread_id_to_index_id_map.erase(old_thread_id); 1756 } 1757 } 1758 1759 return true; 1760 } 1761 1762 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) { 1763 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && 1764 GetByteOrder() != eByteOrderInvalid) { 1765 ThreadGDBRemote *gdb_thread = 1766 static_cast<ThreadGDBRemote *>(thread_sp.get()); 1767 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext()); 1768 if (reg_ctx_sp) { 1769 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber( 1770 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 1771 if (pc_regnum != LLDB_INVALID_REGNUM) { 1772 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]); 1773 } 1774 } 1775 } 1776 } 1777 1778 bool ProcessGDBRemote::GetThreadStopInfoFromJSON( 1779 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) { 1780 // See if we got thread stop infos for all threads via the "jThreadsInfo" 1781 // packet 1782 if (thread_infos_sp) { 1783 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray(); 1784 if (thread_infos) { 1785 lldb::tid_t tid; 1786 const size_t n = thread_infos->GetSize(); 1787 for (size_t i = 0; i < n; ++i) { 1788 StructuredData::Dictionary *thread_dict = 1789 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 1790 if (thread_dict) { 1791 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>( 1792 "tid", tid, LLDB_INVALID_THREAD_ID)) { 1793 if (tid == thread->GetID()) 1794 return (bool)SetThreadStopInfo(thread_dict); 1795 } 1796 } 1797 } 1798 } 1799 } 1800 return false; 1801 } 1802 1803 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) { 1804 // See if we got thread stop infos for all threads via the "jThreadsInfo" 1805 // packet 1806 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp)) 1807 return true; 1808 1809 // See if we got thread stop info for any threads valid stop info reasons 1810 // threads via the "jstopinfo" packet stop reply packet key/value pair? 1811 if (m_jstopinfo_sp) { 1812 // If we have "jstopinfo" then we have stop descriptions for all threads 1813 // that have stop reasons, and if there is no entry for a thread, then it 1814 // has no stop reason. 1815 thread->GetRegisterContext()->InvalidateIfNeeded(true); 1816 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) { 1817 thread->SetStopInfo(StopInfoSP()); 1818 } 1819 return true; 1820 } 1821 1822 // Fall back to using the qThreadStopInfo packet 1823 StringExtractorGDBRemote stop_packet; 1824 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet)) 1825 return SetThreadStopInfo(stop_packet) == eStateStopped; 1826 return false; 1827 } 1828 1829 ThreadSP ProcessGDBRemote::SetThreadStopInfo( 1830 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map, 1831 uint8_t signo, const std::string &thread_name, const std::string &reason, 1832 const std::string &description, uint32_t exc_type, 1833 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr, 1834 bool queue_vars_valid, // Set to true if queue_name, queue_kind and 1835 // queue_serial are valid 1836 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t, 1837 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) { 1838 ThreadSP thread_sp; 1839 if (tid != LLDB_INVALID_THREAD_ID) { 1840 // Scope for "locker" below 1841 { 1842 // m_thread_list_real does have its own mutex, but we need to hold onto 1843 // the mutex between the call to m_thread_list_real.FindThreadByID(...) 1844 // and the m_thread_list_real.AddThread(...) so it doesn't change on us 1845 std::lock_guard<std::recursive_mutex> guard( 1846 m_thread_list_real.GetMutex()); 1847 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); 1848 1849 if (!thread_sp) { 1850 // Create the thread if we need to 1851 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); 1852 m_thread_list_real.AddThread(thread_sp); 1853 } 1854 } 1855 1856 if (thread_sp) { 1857 ThreadGDBRemote *gdb_thread = 1858 static_cast<ThreadGDBRemote *>(thread_sp.get()); 1859 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true); 1860 1861 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid); 1862 if (iter != m_thread_ids.end()) { 1863 SetThreadPc(thread_sp, iter - m_thread_ids.begin()); 1864 } 1865 1866 for (const auto &pair : expedited_register_map) { 1867 StringExtractor reg_value_extractor; 1868 reg_value_extractor.GetStringRef() = pair.second; 1869 DataBufferSP buffer_sp(new DataBufferHeap( 1870 reg_value_extractor.GetStringRef().size() / 2, 0)); 1871 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc'); 1872 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData()); 1873 } 1874 1875 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str()); 1876 1877 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr); 1878 // Check if the GDB server was able to provide the queue name, kind and 1879 // serial number 1880 if (queue_vars_valid) 1881 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, 1882 queue_serial, dispatch_queue_t, 1883 associated_with_dispatch_queue); 1884 else 1885 gdb_thread->ClearQueueInfo(); 1886 1887 gdb_thread->SetAssociatedWithLibdispatchQueue( 1888 associated_with_dispatch_queue); 1889 1890 if (dispatch_queue_t != LLDB_INVALID_ADDRESS) 1891 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t); 1892 1893 // Make sure we update our thread stop reason just once 1894 if (!thread_sp->StopInfoIsUpToDate()) { 1895 thread_sp->SetStopInfo(StopInfoSP()); 1896 // If there's a memory thread backed by this thread, we need to use it 1897 // to calculate StopInfo. 1898 if (ThreadSP memory_thread_sp = 1899 m_thread_list.GetBackingThread(thread_sp)) 1900 thread_sp = memory_thread_sp; 1901 1902 if (exc_type != 0) { 1903 const size_t exc_data_size = exc_data.size(); 1904 1905 thread_sp->SetStopInfo( 1906 StopInfoMachException::CreateStopReasonWithMachException( 1907 *thread_sp, exc_type, exc_data_size, 1908 exc_data_size >= 1 ? exc_data[0] : 0, 1909 exc_data_size >= 2 ? exc_data[1] : 0, 1910 exc_data_size >= 3 ? exc_data[2] : 0)); 1911 } else { 1912 bool handled = false; 1913 bool did_exec = false; 1914 if (!reason.empty()) { 1915 if (reason == "trace") { 1916 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1917 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() 1918 ->GetBreakpointSiteList() 1919 .FindByAddress(pc); 1920 1921 // If the current pc is a breakpoint site then the StopInfo 1922 // should be set to Breakpoint Otherwise, it will be set to 1923 // Trace. 1924 if (bp_site_sp && 1925 bp_site_sp->ValidForThisThread(thread_sp.get())) { 1926 thread_sp->SetStopInfo( 1927 StopInfo::CreateStopReasonWithBreakpointSiteID( 1928 *thread_sp, bp_site_sp->GetID())); 1929 } else 1930 thread_sp->SetStopInfo( 1931 StopInfo::CreateStopReasonToTrace(*thread_sp)); 1932 handled = true; 1933 } else if (reason == "breakpoint") { 1934 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1935 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() 1936 ->GetBreakpointSiteList() 1937 .FindByAddress(pc); 1938 if (bp_site_sp) { 1939 // If the breakpoint is for this thread, then we'll report the 1940 // hit, but if it is for another thread, we can just report no 1941 // reason. We don't need to worry about stepping over the 1942 // breakpoint here, that will be taken care of when the thread 1943 // resumes and notices that there's a breakpoint under the pc. 1944 handled = true; 1945 if (bp_site_sp->ValidForThisThread(thread_sp.get())) { 1946 thread_sp->SetStopInfo( 1947 StopInfo::CreateStopReasonWithBreakpointSiteID( 1948 *thread_sp, bp_site_sp->GetID())); 1949 } else { 1950 StopInfoSP invalid_stop_info_sp; 1951 thread_sp->SetStopInfo(invalid_stop_info_sp); 1952 } 1953 } 1954 } else if (reason == "trap") { 1955 // Let the trap just use the standard signal stop reason below... 1956 } else if (reason == "watchpoint") { 1957 StringExtractor desc_extractor(description.c_str()); 1958 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1959 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32); 1960 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1961 watch_id_t watch_id = LLDB_INVALID_WATCH_ID; 1962 if (wp_addr != LLDB_INVALID_ADDRESS) { 1963 WatchpointSP wp_sp; 1964 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore(); 1965 if ((core >= ArchSpec::kCore_mips_first && 1966 core <= ArchSpec::kCore_mips_last) || 1967 (core >= ArchSpec::eCore_arm_generic && 1968 core <= ArchSpec::eCore_arm_aarch64)) 1969 wp_sp = GetTarget().GetWatchpointList().FindByAddress( 1970 wp_hit_addr); 1971 if (!wp_sp) 1972 wp_sp = 1973 GetTarget().GetWatchpointList().FindByAddress(wp_addr); 1974 if (wp_sp) { 1975 wp_sp->SetHardwareIndex(wp_index); 1976 watch_id = wp_sp->GetID(); 1977 } 1978 } 1979 if (watch_id == LLDB_INVALID_WATCH_ID) { 1980 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet( 1981 GDBR_LOG_WATCHPOINTS)); 1982 if (log) 1983 log->Printf("failed to find watchpoint"); 1984 } 1985 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID( 1986 *thread_sp, watch_id, wp_hit_addr)); 1987 handled = true; 1988 } else if (reason == "exception") { 1989 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( 1990 *thread_sp, description.c_str())); 1991 handled = true; 1992 } else if (reason == "exec") { 1993 did_exec = true; 1994 thread_sp->SetStopInfo( 1995 StopInfo::CreateStopReasonWithExec(*thread_sp)); 1996 handled = true; 1997 } 1998 } else if (!signo) { 1999 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 2000 lldb::BreakpointSiteSP bp_site_sp = 2001 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( 2002 pc); 2003 2004 // If the current pc is a breakpoint site then the StopInfo should 2005 // be set to Breakpoint even though the remote stub did not set it 2006 // as such. This can happen when the thread is involuntarily 2007 // interrupted (e.g. due to stops on other threads) just as it is 2008 // about to execute the breakpoint instruction. 2009 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) { 2010 thread_sp->SetStopInfo( 2011 StopInfo::CreateStopReasonWithBreakpointSiteID( 2012 *thread_sp, bp_site_sp->GetID())); 2013 handled = true; 2014 } 2015 } 2016 2017 if (!handled && signo && !did_exec) { 2018 if (signo == SIGTRAP) { 2019 // Currently we are going to assume SIGTRAP means we are either 2020 // hitting a breakpoint or hardware single stepping. 2021 handled = true; 2022 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + 2023 m_breakpoint_pc_offset; 2024 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() 2025 ->GetBreakpointSiteList() 2026 .FindByAddress(pc); 2027 2028 if (bp_site_sp) { 2029 // If the breakpoint is for this thread, then we'll report the 2030 // hit, but if it is for another thread, we can just report no 2031 // reason. We don't need to worry about stepping over the 2032 // breakpoint here, that will be taken care of when the thread 2033 // resumes and notices that there's a breakpoint under the pc. 2034 if (bp_site_sp->ValidForThisThread(thread_sp.get())) { 2035 if (m_breakpoint_pc_offset != 0) 2036 thread_sp->GetRegisterContext()->SetPC(pc); 2037 thread_sp->SetStopInfo( 2038 StopInfo::CreateStopReasonWithBreakpointSiteID( 2039 *thread_sp, bp_site_sp->GetID())); 2040 } else { 2041 StopInfoSP invalid_stop_info_sp; 2042 thread_sp->SetStopInfo(invalid_stop_info_sp); 2043 } 2044 } else { 2045 // If we were stepping then assume the stop was the result of 2046 // the trace. If we were not stepping then report the SIGTRAP. 2047 // FIXME: We are still missing the case where we single step 2048 // over a trap instruction. 2049 if (thread_sp->GetTemporaryResumeState() == eStateStepping) 2050 thread_sp->SetStopInfo( 2051 StopInfo::CreateStopReasonToTrace(*thread_sp)); 2052 else 2053 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( 2054 *thread_sp, signo, description.c_str())); 2055 } 2056 } 2057 if (!handled) 2058 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( 2059 *thread_sp, signo, description.c_str())); 2060 } 2061 2062 if (!description.empty()) { 2063 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo()); 2064 if (stop_info_sp) { 2065 const char *stop_info_desc = stop_info_sp->GetDescription(); 2066 if (!stop_info_desc || !stop_info_desc[0]) 2067 stop_info_sp->SetDescription(description.c_str()); 2068 } else { 2069 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( 2070 *thread_sp, description.c_str())); 2071 } 2072 } 2073 } 2074 } 2075 } 2076 } 2077 return thread_sp; 2078 } 2079 2080 lldb::ThreadSP 2081 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) { 2082 static ConstString g_key_tid("tid"); 2083 static ConstString g_key_name("name"); 2084 static ConstString g_key_reason("reason"); 2085 static ConstString g_key_metype("metype"); 2086 static ConstString g_key_medata("medata"); 2087 static ConstString g_key_qaddr("qaddr"); 2088 static ConstString g_key_dispatch_queue_t("dispatch_queue_t"); 2089 static ConstString g_key_associated_with_dispatch_queue( 2090 "associated_with_dispatch_queue"); 2091 static ConstString g_key_queue_name("qname"); 2092 static ConstString g_key_queue_kind("qkind"); 2093 static ConstString g_key_queue_serial_number("qserialnum"); 2094 static ConstString g_key_registers("registers"); 2095 static ConstString g_key_memory("memory"); 2096 static ConstString g_key_address("address"); 2097 static ConstString g_key_bytes("bytes"); 2098 static ConstString g_key_description("description"); 2099 static ConstString g_key_signal("signal"); 2100 2101 // Stop with signal and thread info 2102 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2103 uint8_t signo = 0; 2104 std::string value; 2105 std::string thread_name; 2106 std::string reason; 2107 std::string description; 2108 uint32_t exc_type = 0; 2109 std::vector<addr_t> exc_data; 2110 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2111 ExpeditedRegisterMap expedited_register_map; 2112 bool queue_vars_valid = false; 2113 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2114 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2115 std::string queue_name; 2116 QueueKind queue_kind = eQueueKindUnknown; 2117 uint64_t queue_serial_number = 0; 2118 // Iterate through all of the thread dictionary key/value pairs from the 2119 // structured data dictionary 2120 2121 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name, 2122 &signo, &reason, &description, &exc_type, &exc_data, 2123 &thread_dispatch_qaddr, &queue_vars_valid, 2124 &associated_with_dispatch_queue, &dispatch_queue_t, 2125 &queue_name, &queue_kind, &queue_serial_number]( 2126 ConstString key, 2127 StructuredData::Object *object) -> bool { 2128 if (key == g_key_tid) { 2129 // thread in big endian hex 2130 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID); 2131 } else if (key == g_key_metype) { 2132 // exception type in big endian hex 2133 exc_type = object->GetIntegerValue(0); 2134 } else if (key == g_key_medata) { 2135 // exception data in big endian hex 2136 StructuredData::Array *array = object->GetAsArray(); 2137 if (array) { 2138 array->ForEach([&exc_data](StructuredData::Object *object) -> bool { 2139 exc_data.push_back(object->GetIntegerValue()); 2140 return true; // Keep iterating through all array items 2141 }); 2142 } 2143 } else if (key == g_key_name) { 2144 thread_name = object->GetStringValue(); 2145 } else if (key == g_key_qaddr) { 2146 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS); 2147 } else if (key == g_key_queue_name) { 2148 queue_vars_valid = true; 2149 queue_name = object->GetStringValue(); 2150 } else if (key == g_key_queue_kind) { 2151 std::string queue_kind_str = object->GetStringValue(); 2152 if (queue_kind_str == "serial") { 2153 queue_vars_valid = true; 2154 queue_kind = eQueueKindSerial; 2155 } else if (queue_kind_str == "concurrent") { 2156 queue_vars_valid = true; 2157 queue_kind = eQueueKindConcurrent; 2158 } 2159 } else if (key == g_key_queue_serial_number) { 2160 queue_serial_number = object->GetIntegerValue(0); 2161 if (queue_serial_number != 0) 2162 queue_vars_valid = true; 2163 } else if (key == g_key_dispatch_queue_t) { 2164 dispatch_queue_t = object->GetIntegerValue(0); 2165 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS) 2166 queue_vars_valid = true; 2167 } else if (key == g_key_associated_with_dispatch_queue) { 2168 queue_vars_valid = true; 2169 bool associated = object->GetBooleanValue(); 2170 if (associated) 2171 associated_with_dispatch_queue = eLazyBoolYes; 2172 else 2173 associated_with_dispatch_queue = eLazyBoolNo; 2174 } else if (key == g_key_reason) { 2175 reason = object->GetStringValue(); 2176 } else if (key == g_key_description) { 2177 description = object->GetStringValue(); 2178 } else if (key == g_key_registers) { 2179 StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); 2180 2181 if (registers_dict) { 2182 registers_dict->ForEach( 2183 [&expedited_register_map](ConstString key, 2184 StructuredData::Object *object) -> bool { 2185 const uint32_t reg = 2186 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10); 2187 if (reg != UINT32_MAX) 2188 expedited_register_map[reg] = object->GetStringValue(); 2189 return true; // Keep iterating through all array items 2190 }); 2191 } 2192 } else if (key == g_key_memory) { 2193 StructuredData::Array *array = object->GetAsArray(); 2194 if (array) { 2195 array->ForEach([this](StructuredData::Object *object) -> bool { 2196 StructuredData::Dictionary *mem_cache_dict = 2197 object->GetAsDictionary(); 2198 if (mem_cache_dict) { 2199 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2200 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>( 2201 "address", mem_cache_addr)) { 2202 if (mem_cache_addr != LLDB_INVALID_ADDRESS) { 2203 llvm::StringRef str; 2204 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) { 2205 StringExtractor bytes(str); 2206 bytes.SetFilePos(0); 2207 2208 const size_t byte_size = bytes.GetStringRef().size() / 2; 2209 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); 2210 const size_t bytes_copied = 2211 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2212 if (bytes_copied == byte_size) 2213 m_memory_cache.AddL1CacheData(mem_cache_addr, 2214 data_buffer_sp); 2215 } 2216 } 2217 } 2218 } 2219 return true; // Keep iterating through all array items 2220 }); 2221 } 2222 2223 } else if (key == g_key_signal) 2224 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER); 2225 return true; // Keep iterating through all dictionary key/value pairs 2226 }); 2227 2228 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name, 2229 reason, description, exc_type, exc_data, 2230 thread_dispatch_qaddr, queue_vars_valid, 2231 associated_with_dispatch_queue, dispatch_queue_t, 2232 queue_name, queue_kind, queue_serial_number); 2233 } 2234 2235 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) { 2236 stop_packet.SetFilePos(0); 2237 const char stop_type = stop_packet.GetChar(); 2238 switch (stop_type) { 2239 case 'T': 2240 case 'S': { 2241 // This is a bit of a hack, but is is required. If we did exec, we need to 2242 // clear our thread lists and also know to rebuild our dynamic register 2243 // info before we lookup and threads and populate the expedited register 2244 // values so we need to know this right away so we can cleanup and update 2245 // our registers. 2246 const uint32_t stop_id = GetStopID(); 2247 if (stop_id == 0) { 2248 // Our first stop, make sure we have a process ID, and also make sure we 2249 // know about our registers 2250 if (GetID() == LLDB_INVALID_PROCESS_ID) { 2251 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 2252 if (pid != LLDB_INVALID_PROCESS_ID) 2253 SetID(pid); 2254 } 2255 BuildDynamicRegisterInfo(true); 2256 } 2257 // Stop with signal and thread info 2258 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2259 const uint8_t signo = stop_packet.GetHexU8(); 2260 llvm::StringRef key; 2261 llvm::StringRef value; 2262 std::string thread_name; 2263 std::string reason; 2264 std::string description; 2265 uint32_t exc_type = 0; 2266 std::vector<addr_t> exc_data; 2267 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2268 bool queue_vars_valid = 2269 false; // says if locals below that start with "queue_" are valid 2270 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2271 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2272 std::string queue_name; 2273 QueueKind queue_kind = eQueueKindUnknown; 2274 uint64_t queue_serial_number = 0; 2275 ExpeditedRegisterMap expedited_register_map; 2276 while (stop_packet.GetNameColonValue(key, value)) { 2277 if (key.compare("metype") == 0) { 2278 // exception type in big endian hex 2279 value.getAsInteger(16, exc_type); 2280 } else if (key.compare("medata") == 0) { 2281 // exception data in big endian hex 2282 uint64_t x; 2283 value.getAsInteger(16, x); 2284 exc_data.push_back(x); 2285 } else if (key.compare("thread") == 0) { 2286 // thread in big endian hex 2287 if (value.getAsInteger(16, tid)) 2288 tid = LLDB_INVALID_THREAD_ID; 2289 } else if (key.compare("threads") == 0) { 2290 std::lock_guard<std::recursive_mutex> guard( 2291 m_thread_list_real.GetMutex()); 2292 2293 m_thread_ids.clear(); 2294 // A comma separated list of all threads in the current 2295 // process that includes the thread for this stop reply packet 2296 lldb::tid_t tid; 2297 while (!value.empty()) { 2298 llvm::StringRef tid_str; 2299 std::tie(tid_str, value) = value.split(','); 2300 if (tid_str.getAsInteger(16, tid)) 2301 tid = LLDB_INVALID_THREAD_ID; 2302 m_thread_ids.push_back(tid); 2303 } 2304 } else if (key.compare("thread-pcs") == 0) { 2305 m_thread_pcs.clear(); 2306 // A comma separated list of all threads in the current 2307 // process that includes the thread for this stop reply packet 2308 lldb::addr_t pc; 2309 while (!value.empty()) { 2310 llvm::StringRef pc_str; 2311 std::tie(pc_str, value) = value.split(','); 2312 if (pc_str.getAsInteger(16, pc)) 2313 pc = LLDB_INVALID_ADDRESS; 2314 m_thread_pcs.push_back(pc); 2315 } 2316 } else if (key.compare("jstopinfo") == 0) { 2317 StringExtractor json_extractor(value); 2318 std::string json; 2319 // Now convert the HEX bytes into a string value 2320 json_extractor.GetHexByteString(json); 2321 2322 // This JSON contains thread IDs and thread stop info for all threads. 2323 // It doesn't contain expedited registers, memory or queue info. 2324 m_jstopinfo_sp = StructuredData::ParseJSON(json); 2325 } else if (key.compare("hexname") == 0) { 2326 StringExtractor name_extractor(value); 2327 std::string name; 2328 // Now convert the HEX bytes into a string value 2329 name_extractor.GetHexByteString(thread_name); 2330 } else if (key.compare("name") == 0) { 2331 thread_name = value; 2332 } else if (key.compare("qaddr") == 0) { 2333 value.getAsInteger(16, thread_dispatch_qaddr); 2334 } else if (key.compare("dispatch_queue_t") == 0) { 2335 queue_vars_valid = true; 2336 value.getAsInteger(16, dispatch_queue_t); 2337 } else if (key.compare("qname") == 0) { 2338 queue_vars_valid = true; 2339 StringExtractor name_extractor(value); 2340 // Now convert the HEX bytes into a string value 2341 name_extractor.GetHexByteString(queue_name); 2342 } else if (key.compare("qkind") == 0) { 2343 queue_kind = llvm::StringSwitch<QueueKind>(value) 2344 .Case("serial", eQueueKindSerial) 2345 .Case("concurrent", eQueueKindConcurrent) 2346 .Default(eQueueKindUnknown); 2347 queue_vars_valid = queue_kind != eQueueKindUnknown; 2348 } else if (key.compare("qserialnum") == 0) { 2349 if (!value.getAsInteger(0, queue_serial_number)) 2350 queue_vars_valid = true; 2351 } else if (key.compare("reason") == 0) { 2352 reason = value; 2353 } else if (key.compare("description") == 0) { 2354 StringExtractor desc_extractor(value); 2355 // Now convert the HEX bytes into a string value 2356 desc_extractor.GetHexByteString(description); 2357 } else if (key.compare("memory") == 0) { 2358 // Expedited memory. GDB servers can choose to send back expedited 2359 // memory that can populate the L1 memory cache in the process so that 2360 // things like the frame pointer backchain can be expedited. This will 2361 // help stack backtracing be more efficient by not having to send as 2362 // many memory read requests down the remote GDB server. 2363 2364 // Key/value pair format: memory:<addr>=<bytes>; 2365 // <addr> is a number whose base will be interpreted by the prefix: 2366 // "0x[0-9a-fA-F]+" for hex 2367 // "0[0-7]+" for octal 2368 // "[1-9]+" for decimal 2369 // <bytes> is native endian ASCII hex bytes just like the register 2370 // values 2371 llvm::StringRef addr_str, bytes_str; 2372 std::tie(addr_str, bytes_str) = value.split('='); 2373 if (!addr_str.empty() && !bytes_str.empty()) { 2374 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2375 if (!addr_str.getAsInteger(0, mem_cache_addr)) { 2376 StringExtractor bytes(bytes_str); 2377 const size_t byte_size = bytes.GetBytesLeft() / 2; 2378 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); 2379 const size_t bytes_copied = 2380 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2381 if (bytes_copied == byte_size) 2382 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); 2383 } 2384 } 2385 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || 2386 key.compare("awatch") == 0) { 2387 // Support standard GDB remote stop reply packet 'TAAwatch:addr' 2388 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS; 2389 value.getAsInteger(16, wp_addr); 2390 2391 WatchpointSP wp_sp = 2392 GetTarget().GetWatchpointList().FindByAddress(wp_addr); 2393 uint32_t wp_index = LLDB_INVALID_INDEX32; 2394 2395 if (wp_sp) 2396 wp_index = wp_sp->GetHardwareIndex(); 2397 2398 reason = "watchpoint"; 2399 StreamString ostr; 2400 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index); 2401 description = ostr.GetString(); 2402 } else if (key.compare("library") == 0) { 2403 LoadModules(); 2404 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { 2405 uint32_t reg = UINT32_MAX; 2406 if (!key.getAsInteger(16, reg)) 2407 expedited_register_map[reg] = std::move(value); 2408 } 2409 } 2410 2411 if (tid == LLDB_INVALID_THREAD_ID) { 2412 // A thread id may be invalid if the response is old style 'S' packet 2413 // which does not provide the 2414 // thread information. So update the thread list and choose the first 2415 // one. 2416 UpdateThreadIDList(); 2417 2418 if (!m_thread_ids.empty()) { 2419 tid = m_thread_ids.front(); 2420 } 2421 } 2422 2423 ThreadSP thread_sp = SetThreadStopInfo( 2424 tid, expedited_register_map, signo, thread_name, reason, description, 2425 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, 2426 associated_with_dispatch_queue, dispatch_queue_t, queue_name, 2427 queue_kind, queue_serial_number); 2428 2429 return eStateStopped; 2430 } break; 2431 2432 case 'W': 2433 case 'X': 2434 // process exited 2435 return eStateExited; 2436 2437 default: 2438 break; 2439 } 2440 return eStateInvalid; 2441 } 2442 2443 void ProcessGDBRemote::RefreshStateAfterStop() { 2444 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 2445 2446 m_thread_ids.clear(); 2447 m_thread_pcs.clear(); 2448 // Set the thread stop info. It might have a "threads" key whose value is a 2449 // list of all thread IDs in the current process, so m_thread_ids might get 2450 // set. 2451 2452 // Scope for the lock 2453 { 2454 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2455 if (m_thread_ids.empty()) { 2456 // No, we need to fetch the thread list manually 2457 UpdateThreadIDList(); 2458 } 2459 // We might set some stop info's so make sure the thread list is up to 2460 // date before we do that or we might overwrite what was computed here. 2461 UpdateThreadListIfNeeded(); 2462 2463 // Lock the thread stack while we access it 2464 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex); 2465 // Get the number of stop packets on the stack 2466 int nItems = m_stop_packet_stack.size(); 2467 // Iterate over them 2468 for (int i = 0; i < nItems; i++) { 2469 // Get the thread stop info 2470 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i]; 2471 // Process thread stop info 2472 SetThreadStopInfo(stop_info); 2473 } 2474 // Clear the thread stop stack 2475 m_stop_packet_stack.clear(); 2476 } 2477 2478 // If we have queried for a default thread id 2479 if (m_initial_tid != LLDB_INVALID_THREAD_ID) { 2480 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2481 m_initial_tid = LLDB_INVALID_THREAD_ID; 2482 } 2483 2484 // Let all threads recover from stopping and do any clean up based on the 2485 // previous thread state (if any). 2486 m_thread_list_real.RefreshStateAfterStop(); 2487 } 2488 2489 Status ProcessGDBRemote::DoHalt(bool &caused_stop) { 2490 Status error; 2491 2492 if (m_public_state.GetValue() == eStateAttaching) { 2493 // We are being asked to halt during an attach. We need to just close our 2494 // file handle and debugserver will go away, and we can be done... 2495 m_gdb_comm.Disconnect(); 2496 } else 2497 caused_stop = m_gdb_comm.Interrupt(); 2498 return error; 2499 } 2500 2501 Status ProcessGDBRemote::DoDetach(bool keep_stopped) { 2502 Status error; 2503 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2504 if (log) 2505 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2506 2507 error = m_gdb_comm.Detach(keep_stopped); 2508 if (log) { 2509 if (error.Success()) 2510 log->PutCString( 2511 "ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2512 else 2513 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s", 2514 error.AsCString() ? error.AsCString() : "<unknown error>"); 2515 } 2516 2517 if (!error.Success()) 2518 return error; 2519 2520 // Sleep for one second to let the process get all detached... 2521 StopAsyncThread(); 2522 2523 SetPrivateState(eStateDetached); 2524 ResumePrivateStateThread(); 2525 2526 // KillDebugserverProcess (); 2527 return error; 2528 } 2529 2530 Status ProcessGDBRemote::DoDestroy() { 2531 Status error; 2532 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2533 if (log) 2534 log->Printf("ProcessGDBRemote::DoDestroy()"); 2535 2536 // There is a bug in older iOS debugservers where they don't shut down the 2537 // process they are debugging properly. If the process is sitting at a 2538 // breakpoint or an exception, this can cause problems with restarting. So 2539 // we check to see if any of our threads are stopped at a breakpoint, and if 2540 // so we remove all the breakpoints, resume the process, and THEN destroy it 2541 // again. 2542 // 2543 // Note, we don't have a good way to test the version of debugserver, but I 2544 // happen to know that the set of all the iOS debugservers which don't 2545 // support GetThreadSuffixSupported() and that of the debugservers with this 2546 // bug are equal. There really should be a better way to test this! 2547 // 2548 // We also use m_destroy_tried_resuming to make sure we only do this once, if 2549 // we resume and then halt and get called here to destroy again and we're 2550 // still at a breakpoint or exception, then we should just do the straight- 2551 // forward kill. 2552 // 2553 // And of course, if we weren't able to stop the process by the time we get 2554 // here, it isn't necessary (or helpful) to do any of this. 2555 2556 if (!m_gdb_comm.GetThreadSuffixSupported() && 2557 m_public_state.GetValue() != eStateRunning) { 2558 PlatformSP platform_sp = GetTarget().GetPlatform(); 2559 2560 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 2561 if (platform_sp && platform_sp->GetName() && 2562 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) { 2563 if (m_destroy_tried_resuming) { 2564 if (log) 2565 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to " 2566 "destroy once already, not doing it again."); 2567 } else { 2568 // At present, the plans are discarded and the breakpoints disabled 2569 // Process::Destroy, but we really need it to happen here and it 2570 // doesn't matter if we do it twice. 2571 m_thread_list.DiscardThreadPlans(); 2572 DisableAllBreakpointSites(); 2573 2574 bool stop_looks_like_crash = false; 2575 ThreadList &threads = GetThreadList(); 2576 2577 { 2578 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2579 2580 size_t num_threads = threads.GetSize(); 2581 for (size_t i = 0; i < num_threads; i++) { 2582 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2583 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2584 StopReason reason = eStopReasonInvalid; 2585 if (stop_info_sp) 2586 reason = stop_info_sp->GetStopReason(); 2587 if (reason == eStopReasonBreakpoint || 2588 reason == eStopReasonException) { 2589 if (log) 2590 log->Printf( 2591 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 2592 " stopped with reason: %s.", 2593 thread_sp->GetProtocolID(), stop_info_sp->GetDescription()); 2594 stop_looks_like_crash = true; 2595 break; 2596 } 2597 } 2598 } 2599 2600 if (stop_looks_like_crash) { 2601 if (log) 2602 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a " 2603 "breakpoint, continue and then kill."); 2604 m_destroy_tried_resuming = true; 2605 2606 // If we are going to run again before killing, it would be good to 2607 // suspend all the threads before resuming so they won't get into 2608 // more trouble. Sadly, for the threads stopped with the breakpoint 2609 // or exception, the exception doesn't get cleared if it is 2610 // suspended, so we do have to run the risk of letting those threads 2611 // proceed a bit. 2612 2613 { 2614 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2615 2616 size_t num_threads = threads.GetSize(); 2617 for (size_t i = 0; i < num_threads; i++) { 2618 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2619 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2620 StopReason reason = eStopReasonInvalid; 2621 if (stop_info_sp) 2622 reason = stop_info_sp->GetStopReason(); 2623 if (reason != eStopReasonBreakpoint && 2624 reason != eStopReasonException) { 2625 if (log) 2626 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending " 2627 "thread: 0x%4.4" PRIx64 " before running.", 2628 thread_sp->GetProtocolID()); 2629 thread_sp->SetResumeState(eStateSuspended); 2630 } 2631 } 2632 } 2633 Resume(); 2634 return Destroy(false); 2635 } 2636 } 2637 } 2638 } 2639 2640 // Interrupt if our inferior is running... 2641 int exit_status = SIGABRT; 2642 std::string exit_string; 2643 2644 if (m_gdb_comm.IsConnected()) { 2645 if (m_public_state.GetValue() != eStateAttaching) { 2646 StringExtractorGDBRemote response; 2647 bool send_async = true; 2648 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm, 2649 std::chrono::seconds(3)); 2650 2651 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) == 2652 GDBRemoteCommunication::PacketResult::Success) { 2653 char packet_cmd = response.GetChar(0); 2654 2655 if (packet_cmd == 'W' || packet_cmd == 'X') { 2656 #if defined(__APPLE__) 2657 // For Native processes on Mac OS X, we launch through the Host 2658 // Platform, then hand the process off to debugserver, which becomes 2659 // the parent process through "PT_ATTACH". Then when we go to kill 2660 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then 2661 // we call waitpid which returns with no error and the correct 2662 // status. But amusingly enough that doesn't seem to actually reap 2663 // the process, but instead it is left around as a Zombie. Probably 2664 // the kernel is in the process of switching ownership back to lldb 2665 // which was the original parent, and gets confused in the handoff. 2666 // Anyway, so call waitpid here to finally reap it. 2667 PlatformSP platform_sp(GetTarget().GetPlatform()); 2668 if (platform_sp && platform_sp->IsHost()) { 2669 int status; 2670 ::pid_t reap_pid; 2671 reap_pid = waitpid(GetID(), &status, WNOHANG); 2672 if (log) 2673 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status); 2674 } 2675 #endif 2676 SetLastStopPacket(response); 2677 ClearThreadIDList(); 2678 exit_status = response.GetHexU8(); 2679 } else { 2680 if (log) 2681 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response " 2682 "to k packet: %s", 2683 response.GetStringRef().c_str()); 2684 exit_string.assign("got unexpected response to k packet: "); 2685 exit_string.append(response.GetStringRef()); 2686 } 2687 } else { 2688 if (log) 2689 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2690 exit_string.assign("failed to send the k packet"); 2691 } 2692 } else { 2693 if (log) 2694 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while " 2695 "attaching"); 2696 exit_string.assign("killed or interrupted while attaching."); 2697 } 2698 } else { 2699 // If we missed setting the exit status on the way out, do it here. 2700 // NB set exit status can be called multiple times, the first one sets the 2701 // status. 2702 exit_string.assign("destroying when not connected to debugserver"); 2703 } 2704 2705 SetExitStatus(exit_status, exit_string.c_str()); 2706 2707 StopAsyncThread(); 2708 KillDebugserverProcess(); 2709 return error; 2710 } 2711 2712 void ProcessGDBRemote::SetLastStopPacket( 2713 const StringExtractorGDBRemote &response) { 2714 const bool did_exec = 2715 response.GetStringRef().find(";reason:exec;") != std::string::npos; 2716 if (did_exec) { 2717 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2718 if (log) 2719 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2720 2721 m_thread_list_real.Clear(); 2722 m_thread_list.Clear(); 2723 BuildDynamicRegisterInfo(true); 2724 m_gdb_comm.ResetDiscoverableSettings(did_exec); 2725 } 2726 2727 // Scope the lock 2728 { 2729 // Lock the thread stack while we access it 2730 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex); 2731 2732 // We are are not using non-stop mode, there can only be one last stop 2733 // reply packet, so clear the list. 2734 if (!GetTarget().GetNonStopModeEnabled()) 2735 m_stop_packet_stack.clear(); 2736 2737 // Add this stop packet to the stop packet stack This stack will get popped 2738 // and examined when we switch to the Stopped state 2739 m_stop_packet_stack.push_back(response); 2740 } 2741 } 2742 2743 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { 2744 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); 2745 } 2746 2747 // Process Queries 2748 2749 bool ProcessGDBRemote::IsAlive() { 2750 return m_gdb_comm.IsConnected() && Process::IsAlive(); 2751 } 2752 2753 addr_t ProcessGDBRemote::GetImageInfoAddress() { 2754 // request the link map address via the $qShlibInfoAddr packet 2755 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2756 2757 // the loaded module list can also provides a link map address 2758 if (addr == LLDB_INVALID_ADDRESS) { 2759 LoadedModuleInfoList list; 2760 if (GetLoadedModuleList(list).Success()) 2761 addr = list.m_link_map; 2762 } 2763 2764 return addr; 2765 } 2766 2767 void ProcessGDBRemote::WillPublicStop() { 2768 // See if the GDB remote client supports the JSON threads info. If so, we 2769 // gather stop info for all threads, expedited registers, expedited memory, 2770 // runtime queue information (iOS and MacOSX only), and more. Expediting 2771 // memory will help stack backtracing be much faster. Expediting registers 2772 // will make sure we don't have to read the thread registers for GPRs. 2773 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2774 2775 if (m_jthreadsinfo_sp) { 2776 // Now set the stop info for each thread and also expedite any registers 2777 // and memory that was in the jThreadsInfo response. 2778 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2779 if (thread_infos) { 2780 const size_t n = thread_infos->GetSize(); 2781 for (size_t i = 0; i < n; ++i) { 2782 StructuredData::Dictionary *thread_dict = 2783 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2784 if (thread_dict) 2785 SetThreadStopInfo(thread_dict); 2786 } 2787 } 2788 } 2789 } 2790 2791 // Process Memory 2792 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, 2793 Status &error) { 2794 GetMaxMemorySize(); 2795 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2796 // M and m packets take 2 bytes for 1 byte of memory 2797 size_t max_memory_size = 2798 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; 2799 if (size > max_memory_size) { 2800 // Keep memory read sizes down to a sane limit. This function will be 2801 // called multiple times in order to complete the task by 2802 // lldb_private::Process so it is ok to do this. 2803 size = max_memory_size; 2804 } 2805 2806 char packet[64]; 2807 int packet_len; 2808 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, 2809 binary_memory_read ? 'x' : 'm', (uint64_t)addr, 2810 (uint64_t)size); 2811 assert(packet_len + 1 < (int)sizeof(packet)); 2812 UNUSED_IF_ASSERT_DISABLED(packet_len); 2813 StringExtractorGDBRemote response; 2814 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) == 2815 GDBRemoteCommunication::PacketResult::Success) { 2816 if (response.IsNormalResponse()) { 2817 error.Clear(); 2818 if (binary_memory_read) { 2819 // The lower level GDBRemoteCommunication packet receive layer has 2820 // already de-quoted any 0x7d character escaping that was present in 2821 // the packet 2822 2823 size_t data_received_size = response.GetBytesLeft(); 2824 if (data_received_size > size) { 2825 // Don't write past the end of BUF if the remote debug server gave us 2826 // too much data for some reason. 2827 data_received_size = size; 2828 } 2829 memcpy(buf, response.GetStringRef().data(), data_received_size); 2830 return data_received_size; 2831 } else { 2832 return response.GetHexBytes( 2833 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd'); 2834 } 2835 } else if (response.IsErrorResponse()) 2836 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2837 else if (response.IsUnsupportedResponse()) 2838 error.SetErrorStringWithFormat( 2839 "GDB server does not support reading memory"); 2840 else 2841 error.SetErrorStringWithFormat( 2842 "unexpected response to GDB server memory read packet '%s': '%s'", 2843 packet, response.GetStringRef().c_str()); 2844 } else { 2845 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2846 } 2847 return 0; 2848 } 2849 2850 Status ProcessGDBRemote::WriteObjectFile( 2851 std::vector<ObjectFile::LoadableData> entries) { 2852 Status error; 2853 // Sort the entries by address because some writes, like those to flash 2854 // memory, must happen in order of increasing address. 2855 std::stable_sort( 2856 std::begin(entries), std::end(entries), 2857 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { 2858 return a.Dest < b.Dest; 2859 }); 2860 m_allow_flash_writes = true; 2861 error = Process::WriteObjectFile(entries); 2862 if (error.Success()) 2863 error = FlashDone(); 2864 else 2865 // Even though some of the writing failed, try to send a flash done if some 2866 // of the writing succeeded so the flash state is reset to normal, but 2867 // don't stomp on the error status that was set in the write failure since 2868 // that's the one we want to report back. 2869 FlashDone(); 2870 m_allow_flash_writes = false; 2871 return error; 2872 } 2873 2874 bool ProcessGDBRemote::HasErased(FlashRange range) { 2875 auto size = m_erased_flash_ranges.GetSize(); 2876 for (size_t i = 0; i < size; ++i) 2877 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) 2878 return true; 2879 return false; 2880 } 2881 2882 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { 2883 Status status; 2884 2885 MemoryRegionInfo region; 2886 status = GetMemoryRegionInfo(addr, region); 2887 if (!status.Success()) 2888 return status; 2889 2890 // The gdb spec doesn't say if erasures are allowed across multiple regions, 2891 // but we'll disallow it to be safe and to keep the logic simple by worring 2892 // about only one region's block size. DoMemoryWrite is this function's 2893 // primary user, and it can easily keep writes within a single memory region 2894 if (addr + size > region.GetRange().GetRangeEnd()) { 2895 status.SetErrorString("Unable to erase flash in multiple regions"); 2896 return status; 2897 } 2898 2899 uint64_t blocksize = region.GetBlocksize(); 2900 if (blocksize == 0) { 2901 status.SetErrorString("Unable to erase flash because blocksize is 0"); 2902 return status; 2903 } 2904 2905 // Erasures can only be done on block boundary adresses, so round down addr 2906 // and round up size 2907 lldb::addr_t block_start_addr = addr - (addr % blocksize); 2908 size += (addr - block_start_addr); 2909 if ((size % blocksize) != 0) 2910 size += (blocksize - size % blocksize); 2911 2912 FlashRange range(block_start_addr, size); 2913 2914 if (HasErased(range)) 2915 return status; 2916 2917 // We haven't erased the entire range, but we may have erased part of it. 2918 // (e.g., block A is already erased and range starts in A and ends in B). So, 2919 // adjust range if necessary to exclude already erased blocks. 2920 if (!m_erased_flash_ranges.IsEmpty()) { 2921 // Assuming that writes and erasures are done in increasing addr order, 2922 // because that is a requirement of the vFlashWrite command. Therefore, we 2923 // only need to look at the last range in the list for overlap. 2924 const auto &last_range = *m_erased_flash_ranges.Back(); 2925 if (range.GetRangeBase() < last_range.GetRangeEnd()) { 2926 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); 2927 // overlap will be less than range.GetByteSize() or else HasErased() 2928 // would have been true 2929 range.SetByteSize(range.GetByteSize() - overlap); 2930 range.SetRangeBase(range.GetRangeBase() + overlap); 2931 } 2932 } 2933 2934 StreamString packet; 2935 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), 2936 (uint64_t)range.GetByteSize()); 2937 2938 StringExtractorGDBRemote response; 2939 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2940 true) == 2941 GDBRemoteCommunication::PacketResult::Success) { 2942 if (response.IsOKResponse()) { 2943 m_erased_flash_ranges.Insert(range, true); 2944 } else { 2945 if (response.IsErrorResponse()) 2946 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64, 2947 addr); 2948 else if (response.IsUnsupportedResponse()) 2949 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2950 else 2951 status.SetErrorStringWithFormat( 2952 "unexpected response to GDB server flash erase packet '%s': '%s'", 2953 packet.GetData(), response.GetStringRef().c_str()); 2954 } 2955 } else { 2956 status.SetErrorStringWithFormat("failed to send packet: '%s'", 2957 packet.GetData()); 2958 } 2959 return status; 2960 } 2961 2962 Status ProcessGDBRemote::FlashDone() { 2963 Status status; 2964 // If we haven't erased any blocks, then we must not have written anything 2965 // either, so there is no need to actually send a vFlashDone command 2966 if (m_erased_flash_ranges.IsEmpty()) 2967 return status; 2968 StringExtractorGDBRemote response; 2969 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) == 2970 GDBRemoteCommunication::PacketResult::Success) { 2971 if (response.IsOKResponse()) { 2972 m_erased_flash_ranges.Clear(); 2973 } else { 2974 if (response.IsErrorResponse()) 2975 status.SetErrorStringWithFormat("flash done failed"); 2976 else if (response.IsUnsupportedResponse()) 2977 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2978 else 2979 status.SetErrorStringWithFormat( 2980 "unexpected response to GDB server flash done packet: '%s'", 2981 response.GetStringRef().c_str()); 2982 } 2983 } else { 2984 status.SetErrorStringWithFormat("failed to send flash done packet"); 2985 } 2986 return status; 2987 } 2988 2989 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, 2990 size_t size, Status &error) { 2991 GetMaxMemorySize(); 2992 // M and m packets take 2 bytes for 1 byte of memory 2993 size_t max_memory_size = m_max_memory_size / 2; 2994 if (size > max_memory_size) { 2995 // Keep memory read sizes down to a sane limit. This function will be 2996 // called multiple times in order to complete the task by 2997 // lldb_private::Process so it is ok to do this. 2998 size = max_memory_size; 2999 } 3000 3001 StreamGDBRemote packet; 3002 3003 MemoryRegionInfo region; 3004 Status region_status = GetMemoryRegionInfo(addr, region); 3005 3006 bool is_flash = 3007 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; 3008 3009 if (is_flash) { 3010 if (!m_allow_flash_writes) { 3011 error.SetErrorString("Writing to flash memory is not allowed"); 3012 return 0; 3013 } 3014 // Keep the write within a flash memory region 3015 if (addr + size > region.GetRange().GetRangeEnd()) 3016 size = region.GetRange().GetRangeEnd() - addr; 3017 // Flash memory must be erased before it can be written 3018 error = FlashErase(addr, size); 3019 if (!error.Success()) 3020 return 0; 3021 packet.Printf("vFlashWrite:%" PRIx64 ":", addr); 3022 packet.PutEscapedBytes(buf, size); 3023 } else { 3024 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 3025 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), 3026 endian::InlHostByteOrder()); 3027 } 3028 StringExtractorGDBRemote response; 3029 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 3030 true) == 3031 GDBRemoteCommunication::PacketResult::Success) { 3032 if (response.IsOKResponse()) { 3033 error.Clear(); 3034 return size; 3035 } else if (response.IsErrorResponse()) 3036 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, 3037 addr); 3038 else if (response.IsUnsupportedResponse()) 3039 error.SetErrorStringWithFormat( 3040 "GDB server does not support writing memory"); 3041 else 3042 error.SetErrorStringWithFormat( 3043 "unexpected response to GDB server memory write packet '%s': '%s'", 3044 packet.GetData(), response.GetStringRef().c_str()); 3045 } else { 3046 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3047 packet.GetData()); 3048 } 3049 return 0; 3050 } 3051 3052 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, 3053 uint32_t permissions, 3054 Status &error) { 3055 Log *log( 3056 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS)); 3057 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 3058 3059 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { 3060 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); 3061 if (allocated_addr != LLDB_INVALID_ADDRESS || 3062 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) 3063 return allocated_addr; 3064 } 3065 3066 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { 3067 // Call mmap() to create memory in the inferior.. 3068 unsigned prot = 0; 3069 if (permissions & lldb::ePermissionsReadable) 3070 prot |= eMmapProtRead; 3071 if (permissions & lldb::ePermissionsWritable) 3072 prot |= eMmapProtWrite; 3073 if (permissions & lldb::ePermissionsExecutable) 3074 prot |= eMmapProtExec; 3075 3076 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 3077 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 3078 m_addr_to_mmap_size[allocated_addr] = size; 3079 else { 3080 allocated_addr = LLDB_INVALID_ADDRESS; 3081 if (log) 3082 log->Printf("ProcessGDBRemote::%s no direct stub support for memory " 3083 "allocation, and InferiorCallMmap also failed - is stub " 3084 "missing register context save/restore capability?", 3085 __FUNCTION__); 3086 } 3087 } 3088 3089 if (allocated_addr == LLDB_INVALID_ADDRESS) 3090 error.SetErrorStringWithFormat( 3091 "unable to allocate %" PRIu64 " bytes of memory with permissions %s", 3092 (uint64_t)size, GetPermissionsAsCString(permissions)); 3093 else 3094 error.Clear(); 3095 return allocated_addr; 3096 } 3097 3098 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr, 3099 MemoryRegionInfo ®ion_info) { 3100 3101 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); 3102 return error; 3103 } 3104 3105 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { 3106 3107 Status error(m_gdb_comm.GetWatchpointSupportInfo(num)); 3108 return error; 3109 } 3110 3111 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { 3112 Status error(m_gdb_comm.GetWatchpointSupportInfo( 3113 num, after, GetTarget().GetArchitecture())); 3114 return error; 3115 } 3116 3117 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { 3118 Status error; 3119 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 3120 3121 switch (supported) { 3122 case eLazyBoolCalculate: 3123 // We should never be deallocating memory without allocating memory first 3124 // so we should never get eLazyBoolCalculate 3125 error.SetErrorString( 3126 "tried to deallocate memory without ever allocating memory"); 3127 break; 3128 3129 case eLazyBoolYes: 3130 if (!m_gdb_comm.DeallocateMemory(addr)) 3131 error.SetErrorStringWithFormat( 3132 "unable to deallocate memory at 0x%" PRIx64, addr); 3133 break; 3134 3135 case eLazyBoolNo: 3136 // Call munmap() to deallocate memory in the inferior.. 3137 { 3138 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 3139 if (pos != m_addr_to_mmap_size.end() && 3140 InferiorCallMunmap(this, addr, pos->second)) 3141 m_addr_to_mmap_size.erase(pos); 3142 else 3143 error.SetErrorStringWithFormat( 3144 "unable to deallocate memory at 0x%" PRIx64, addr); 3145 } 3146 break; 3147 } 3148 3149 return error; 3150 } 3151 3152 // Process STDIO 3153 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, 3154 Status &error) { 3155 if (m_stdio_communication.IsConnected()) { 3156 ConnectionStatus status; 3157 m_stdio_communication.Write(src, src_len, status, nullptr); 3158 } else if (m_stdin_forward) { 3159 m_gdb_comm.SendStdinNotification(src, src_len); 3160 } 3161 return 0; 3162 } 3163 3164 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { 3165 Status error; 3166 assert(bp_site != nullptr); 3167 3168 // Get logging info 3169 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3170 user_id_t site_id = bp_site->GetID(); 3171 3172 // Get the breakpoint address 3173 const addr_t addr = bp_site->GetLoadAddress(); 3174 3175 // Log that a breakpoint was requested 3176 if (log) 3177 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3178 ") address = 0x%" PRIx64, 3179 site_id, (uint64_t)addr); 3180 3181 // Breakpoint already exists and is enabled 3182 if (bp_site->IsEnabled()) { 3183 if (log) 3184 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3185 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", 3186 site_id, (uint64_t)addr); 3187 return error; 3188 } 3189 3190 // Get the software breakpoint trap opcode size 3191 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3192 3193 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this 3194 // breakpoint type is supported by the remote stub. These are set to true by 3195 // default, and later set to false only after we receive an unimplemented 3196 // response when sending a breakpoint packet. This means initially that 3197 // unless we were specifically instructed to use a hardware breakpoint, LLDB 3198 // will attempt to set a software breakpoint. HardwareRequired() also queries 3199 // a boolean variable which indicates if the user specifically asked for 3200 // hardware breakpoints. If true then we will skip over software 3201 // breakpoints. 3202 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && 3203 (!bp_site->HardwareRequired())) { 3204 // Try to send off a software breakpoint packet ($Z0) 3205 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3206 eBreakpointSoftware, true, addr, bp_op_size); 3207 if (error_no == 0) { 3208 // The breakpoint was placed successfully 3209 bp_site->SetEnabled(true); 3210 bp_site->SetType(BreakpointSite::eExternal); 3211 return error; 3212 } 3213 3214 // SendGDBStoppointTypePacket() will return an error if it was unable to 3215 // set this breakpoint. We need to differentiate between a error specific 3216 // to placing this breakpoint or if we have learned that this breakpoint 3217 // type is unsupported. To do this, we must test the support boolean for 3218 // this breakpoint type to see if it now indicates that this breakpoint 3219 // type is unsupported. If they are still supported then we should return 3220 // with the error code. If they are now unsupported, then we would like to 3221 // fall through and try another form of breakpoint. 3222 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { 3223 if (error_no != UINT8_MAX) 3224 error.SetErrorStringWithFormat( 3225 "error: %d sending the breakpoint request", errno); 3226 else 3227 error.SetErrorString("error sending the breakpoint request"); 3228 return error; 3229 } 3230 3231 // We reach here when software breakpoints have been found to be 3232 // unsupported. For future calls to set a breakpoint, we will not attempt 3233 // to set a breakpoint with a type that is known not to be supported. 3234 if (log) 3235 log->Printf("Software breakpoints are unsupported"); 3236 3237 // So we will fall through and try a hardware breakpoint 3238 } 3239 3240 // The process of setting a hardware breakpoint is much the same as above. 3241 // We check the supported boolean for this breakpoint type, and if it is 3242 // thought to be supported then we will try to set this breakpoint with a 3243 // hardware breakpoint. 3244 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3245 // Try to send off a hardware breakpoint packet ($Z1) 3246 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3247 eBreakpointHardware, true, addr, bp_op_size); 3248 if (error_no == 0) { 3249 // The breakpoint was placed successfully 3250 bp_site->SetEnabled(true); 3251 bp_site->SetType(BreakpointSite::eHardware); 3252 return error; 3253 } 3254 3255 // Check if the error was something other then an unsupported breakpoint 3256 // type 3257 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3258 // Unable to set this hardware breakpoint 3259 if (error_no != UINT8_MAX) 3260 error.SetErrorStringWithFormat( 3261 "error: %d sending the hardware breakpoint request " 3262 "(hardware breakpoint resources might be exhausted or unavailable)", 3263 error_no); 3264 else 3265 error.SetErrorString("error sending the hardware breakpoint request " 3266 "(hardware breakpoint resources " 3267 "might be exhausted or unavailable)"); 3268 return error; 3269 } 3270 3271 // We will reach here when the stub gives an unsupported response to a 3272 // hardware breakpoint 3273 if (log) 3274 log->Printf("Hardware breakpoints are unsupported"); 3275 3276 // Finally we will falling through to a #trap style breakpoint 3277 } 3278 3279 // Don't fall through when hardware breakpoints were specifically requested 3280 if (bp_site->HardwareRequired()) { 3281 error.SetErrorString("hardware breakpoints are not supported"); 3282 return error; 3283 } 3284 3285 // As a last resort we want to place a manual breakpoint. An instruction is 3286 // placed into the process memory using memory write packets. 3287 return EnableSoftwareBreakpoint(bp_site); 3288 } 3289 3290 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { 3291 Status error; 3292 assert(bp_site != nullptr); 3293 addr_t addr = bp_site->GetLoadAddress(); 3294 user_id_t site_id = bp_site->GetID(); 3295 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3296 if (log) 3297 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3298 ") addr = 0x%8.8" PRIx64, 3299 site_id, (uint64_t)addr); 3300 3301 if (bp_site->IsEnabled()) { 3302 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3303 3304 BreakpointSite::Type bp_type = bp_site->GetType(); 3305 switch (bp_type) { 3306 case BreakpointSite::eSoftware: 3307 error = DisableSoftwareBreakpoint(bp_site); 3308 break; 3309 3310 case BreakpointSite::eHardware: 3311 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, 3312 addr, bp_op_size)) 3313 error.SetErrorToGenericError(); 3314 break; 3315 3316 case BreakpointSite::eExternal: { 3317 GDBStoppointType stoppoint_type; 3318 if (bp_site->IsHardware()) 3319 stoppoint_type = eBreakpointHardware; 3320 else 3321 stoppoint_type = eBreakpointSoftware; 3322 3323 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, 3324 bp_op_size)) 3325 error.SetErrorToGenericError(); 3326 } break; 3327 } 3328 if (error.Success()) 3329 bp_site->SetEnabled(false); 3330 } else { 3331 if (log) 3332 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3333 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3334 site_id, (uint64_t)addr); 3335 return error; 3336 } 3337 3338 if (error.Success()) 3339 error.SetErrorToGenericError(); 3340 return error; 3341 } 3342 3343 // Pre-requisite: wp != NULL. 3344 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { 3345 assert(wp); 3346 bool watch_read = wp->WatchpointRead(); 3347 bool watch_write = wp->WatchpointWrite(); 3348 3349 // watch_read and watch_write cannot both be false. 3350 assert(watch_read || watch_write); 3351 if (watch_read && watch_write) 3352 return eWatchpointReadWrite; 3353 else if (watch_read) 3354 return eWatchpointRead; 3355 else // Must be watch_write, then. 3356 return eWatchpointWrite; 3357 } 3358 3359 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { 3360 Status error; 3361 if (wp) { 3362 user_id_t watchID = wp->GetID(); 3363 addr_t addr = wp->GetLoadAddress(); 3364 Log *log( 3365 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3366 if (log) 3367 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", 3368 watchID); 3369 if (wp->IsEnabled()) { 3370 if (log) 3371 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 3372 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 3373 watchID, (uint64_t)addr); 3374 return error; 3375 } 3376 3377 GDBStoppointType type = GetGDBStoppointType(wp); 3378 // Pass down an appropriate z/Z packet... 3379 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) { 3380 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, 3381 wp->GetByteSize()) == 0) { 3382 wp->SetEnabled(true, notify); 3383 return error; 3384 } else 3385 error.SetErrorString("sending gdb watchpoint packet failed"); 3386 } else 3387 error.SetErrorString("watchpoints not supported"); 3388 } else { 3389 error.SetErrorString("Watchpoint argument was NULL."); 3390 } 3391 if (error.Success()) 3392 error.SetErrorToGenericError(); 3393 return error; 3394 } 3395 3396 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { 3397 Status error; 3398 if (wp) { 3399 user_id_t watchID = wp->GetID(); 3400 3401 Log *log( 3402 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3403 3404 addr_t addr = wp->GetLoadAddress(); 3405 3406 if (log) 3407 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3408 ") addr = 0x%8.8" PRIx64, 3409 watchID, (uint64_t)addr); 3410 3411 if (!wp->IsEnabled()) { 3412 if (log) 3413 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3414 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3415 watchID, (uint64_t)addr); 3416 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling 3417 // attempt might come from the user-supplied actions, we'll route it in 3418 // order for the watchpoint object to intelligently process this action. 3419 wp->SetEnabled(false, notify); 3420 return error; 3421 } 3422 3423 if (wp->IsHardware()) { 3424 GDBStoppointType type = GetGDBStoppointType(wp); 3425 // Pass down an appropriate z/Z packet... 3426 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, 3427 wp->GetByteSize()) == 0) { 3428 wp->SetEnabled(false, notify); 3429 return error; 3430 } else 3431 error.SetErrorString("sending gdb watchpoint packet failed"); 3432 } 3433 // TODO: clear software watchpoints if we implement them 3434 } else { 3435 error.SetErrorString("Watchpoint argument was NULL."); 3436 } 3437 if (error.Success()) 3438 error.SetErrorToGenericError(); 3439 return error; 3440 } 3441 3442 void ProcessGDBRemote::Clear() { 3443 m_thread_list_real.Clear(); 3444 m_thread_list.Clear(); 3445 } 3446 3447 Status ProcessGDBRemote::DoSignal(int signo) { 3448 Status error; 3449 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3450 if (log) 3451 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo); 3452 3453 if (!m_gdb_comm.SendAsyncSignal(signo)) 3454 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3455 return error; 3456 } 3457 3458 Status ProcessGDBRemote::ConnectToReplayServer(repro::Loader *loader) { 3459 if (!loader) 3460 return Status("No loader provided."); 3461 3462 // Construct replay history path. 3463 FileSpec history_file = loader->GetFile<ProcessGDBRemoteProvider::Info>(); 3464 if (!history_file) 3465 return Status("No provider for gdb-remote."); 3466 3467 // Enable replay mode. 3468 m_replay_mode = true; 3469 3470 // Load replay history. 3471 if (auto error = m_gdb_replay_server.LoadReplayHistory(history_file)) 3472 return Status("Unable to load replay history"); 3473 3474 // Make a local connection. 3475 if (auto error = GDBRemoteCommunication::ConnectLocally(m_gdb_comm, 3476 m_gdb_replay_server)) 3477 return Status("Unable to connect to replay server"); 3478 3479 // Start server thread. 3480 m_gdb_replay_server.StartAsyncThread(); 3481 3482 // Start client thread. 3483 StartAsyncThread(); 3484 3485 // Do the usual setup. 3486 return ConnectToDebugserver(""); 3487 } 3488 3489 Status 3490 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { 3491 // Make sure we aren't already connected? 3492 if (m_gdb_comm.IsConnected()) 3493 return Status(); 3494 3495 PlatformSP platform_sp(GetTarget().GetPlatform()); 3496 if (platform_sp && !platform_sp->IsHost()) 3497 return Status("Lost debug server connection"); 3498 3499 if (repro::Loader *loader = repro::Reproducer::Instance().GetLoader()) 3500 return ConnectToReplayServer(loader); 3501 3502 auto error = LaunchAndConnectToDebugserver(process_info); 3503 if (error.Fail()) { 3504 const char *error_string = error.AsCString(); 3505 if (error_string == nullptr) 3506 error_string = "unable to launch " DEBUGSERVER_BASENAME; 3507 } 3508 return error; 3509 } 3510 #if !defined(_WIN32) 3511 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 3512 #endif 3513 3514 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3515 static bool SetCloexecFlag(int fd) { 3516 #if defined(FD_CLOEXEC) 3517 int flags = ::fcntl(fd, F_GETFD); 3518 if (flags == -1) 3519 return false; 3520 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); 3521 #else 3522 return false; 3523 #endif 3524 } 3525 #endif 3526 3527 Status ProcessGDBRemote::LaunchAndConnectToDebugserver( 3528 const ProcessInfo &process_info) { 3529 using namespace std::placeholders; // For _1, _2, etc. 3530 3531 Status error; 3532 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { 3533 // If we locate debugserver, keep that located version around 3534 static FileSpec g_debugserver_file_spec; 3535 3536 ProcessLaunchInfo debugserver_launch_info; 3537 // Make debugserver run in its own session so signals generated by special 3538 // terminal key sequences (^C) don't affect debugserver. 3539 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3540 3541 const std::weak_ptr<ProcessGDBRemote> this_wp = 3542 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this()); 3543 debugserver_launch_info.SetMonitorProcessCallback( 3544 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false); 3545 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3546 3547 int communication_fd = -1; 3548 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3549 // Use a socketpair on non-Windows systems for security and performance 3550 // reasons. 3551 int sockets[2]; /* the pair of socket descriptors */ 3552 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { 3553 error.SetErrorToErrno(); 3554 return error; 3555 } 3556 3557 int our_socket = sockets[0]; 3558 int gdb_socket = sockets[1]; 3559 CleanUp cleanup_our(close, our_socket); 3560 CleanUp cleanup_gdb(close, gdb_socket); 3561 3562 // Don't let any child processes inherit our communication socket 3563 SetCloexecFlag(our_socket); 3564 communication_fd = gdb_socket; 3565 #endif 3566 3567 error = m_gdb_comm.StartDebugserverProcess( 3568 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, 3569 nullptr, nullptr, communication_fd); 3570 3571 if (error.Success()) 3572 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3573 else 3574 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3575 3576 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3577 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3578 // Our process spawned correctly, we can now set our connection to use 3579 // our end of the socket pair 3580 cleanup_our.disable(); 3581 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true)); 3582 #endif 3583 StartAsyncThread(); 3584 } 3585 3586 if (error.Fail()) { 3587 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3588 3589 if (log) 3590 log->Printf("failed to start debugserver process: %s", 3591 error.AsCString()); 3592 return error; 3593 } 3594 3595 if (m_gdb_comm.IsConnected()) { 3596 // Finish the connection process by doing the handshake without 3597 // connecting (send NULL URL) 3598 error = ConnectToDebugserver(""); 3599 } else { 3600 error.SetErrorString("connection failed"); 3601 } 3602 } 3603 return error; 3604 } 3605 3606 bool ProcessGDBRemote::MonitorDebugserverProcess( 3607 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, 3608 bool exited, // True if the process did exit 3609 int signo, // Zero for no signal 3610 int exit_status // Exit value of process if signal is zero 3611 ) { 3612 // "debugserver_pid" argument passed in is the process ID for debugserver 3613 // that we are tracking... 3614 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3615 const bool handled = true; 3616 3617 if (log) 3618 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 3619 ", signo=%i (0x%x), exit_status=%i)", 3620 __FUNCTION__, debugserver_pid, signo, signo, exit_status); 3621 3622 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); 3623 if (log) 3624 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__, 3625 static_cast<void *>(process_sp.get())); 3626 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) 3627 return handled; 3628 3629 // Sleep for a half a second to make sure our inferior process has time to 3630 // set its exit status before we set it incorrectly when both the debugserver 3631 // and the inferior process shut down. 3632 usleep(500000); 3633 // If our process hasn't yet exited, debugserver might have died. If the 3634 // process did exit, then we are reaping it. 3635 const StateType state = process_sp->GetState(); 3636 3637 if (state != eStateInvalid && state != eStateUnloaded && 3638 state != eStateExited && state != eStateDetached) { 3639 char error_str[1024]; 3640 if (signo) { 3641 const char *signal_cstr = 3642 process_sp->GetUnixSignals()->GetSignalAsCString(signo); 3643 if (signal_cstr) 3644 ::snprintf(error_str, sizeof(error_str), 3645 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3646 else 3647 ::snprintf(error_str, sizeof(error_str), 3648 DEBUGSERVER_BASENAME " died with signal %i", signo); 3649 } else { 3650 ::snprintf(error_str, sizeof(error_str), 3651 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", 3652 exit_status); 3653 } 3654 3655 process_sp->SetExitStatus(-1, error_str); 3656 } 3657 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3658 // longer has a debugserver instance 3659 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3660 return handled; 3661 } 3662 3663 void ProcessGDBRemote::KillDebugserverProcess() { 3664 m_gdb_comm.Disconnect(); 3665 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3666 Host::Kill(m_debugserver_pid, SIGINT); 3667 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3668 } 3669 } 3670 3671 void ProcessGDBRemote::Initialize() { 3672 static llvm::once_flag g_once_flag; 3673 3674 llvm::call_once(g_once_flag, []() { 3675 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3676 GetPluginDescriptionStatic(), CreateInstance, 3677 DebuggerInitialize); 3678 }); 3679 } 3680 3681 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3682 if (!PluginManager::GetSettingForProcessPlugin( 3683 debugger, PluginProperties::GetSettingName())) { 3684 const bool is_global_setting = true; 3685 PluginManager::CreateSettingForProcessPlugin( 3686 debugger, GetGlobalPluginProperties()->GetValueProperties(), 3687 ConstString("Properties for the gdb-remote process plug-in."), 3688 is_global_setting); 3689 } 3690 } 3691 3692 bool ProcessGDBRemote::StartAsyncThread() { 3693 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3694 3695 if (log) 3696 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__); 3697 3698 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3699 if (!m_async_thread.IsJoinable()) { 3700 // Create a thread that watches our internal state and controls which 3701 // events make it to clients (into the DCProcess event queue). 3702 3703 m_async_thread = ThreadLauncher::LaunchThread( 3704 "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, 3705 nullptr); 3706 } else if (log) 3707 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was " 3708 "already running.", 3709 __FUNCTION__); 3710 3711 return m_async_thread.IsJoinable(); 3712 } 3713 3714 void ProcessGDBRemote::StopAsyncThread() { 3715 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3716 3717 if (log) 3718 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__); 3719 3720 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3721 if (m_async_thread.IsJoinable()) { 3722 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3723 3724 // This will shut down the async thread. 3725 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3726 3727 // Stop the stdio thread 3728 m_async_thread.Join(nullptr); 3729 m_async_thread.Reset(); 3730 } else if (log) 3731 log->Printf( 3732 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3733 __FUNCTION__); 3734 } 3735 3736 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) { 3737 // get the packet at a string 3738 const std::string &pkt = packet.GetStringRef(); 3739 // skip %stop: 3740 StringExtractorGDBRemote stop_info(pkt.c_str() + 5); 3741 3742 // pass as a thread stop info packet 3743 SetLastStopPacket(stop_info); 3744 3745 // check for more stop reasons 3746 HandleStopReplySequence(); 3747 3748 // if the process is stopped then we need to fake a resume so that we can 3749 // stop properly with the new break. This is possible due to 3750 // SetPrivateState() broadcasting the state change as a side effect. 3751 if (GetPrivateState() == lldb::StateType::eStateStopped) { 3752 SetPrivateState(lldb::StateType::eStateRunning); 3753 } 3754 3755 // since we have some stopped packets we can halt the process 3756 SetPrivateState(lldb::StateType::eStateStopped); 3757 3758 return true; 3759 } 3760 3761 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) { 3762 ProcessGDBRemote *process = (ProcessGDBRemote *)arg; 3763 3764 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3765 if (log) 3766 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3767 ") thread starting...", 3768 __FUNCTION__, arg, process->GetID()); 3769 3770 EventSP event_sp; 3771 bool done = false; 3772 while (!done) { 3773 if (log) 3774 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3775 ") listener.WaitForEvent (NULL, event_sp)...", 3776 __FUNCTION__, arg, process->GetID()); 3777 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { 3778 const uint32_t event_type = event_sp->GetType(); 3779 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) { 3780 if (log) 3781 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3782 ") Got an event of type: %d...", 3783 __FUNCTION__, arg, process->GetID(), event_type); 3784 3785 switch (event_type) { 3786 case eBroadcastBitAsyncContinue: { 3787 const EventDataBytes *continue_packet = 3788 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3789 3790 if (continue_packet) { 3791 const char *continue_cstr = 3792 (const char *)continue_packet->GetBytes(); 3793 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3794 if (log) 3795 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3796 ") got eBroadcastBitAsyncContinue: %s", 3797 __FUNCTION__, arg, process->GetID(), continue_cstr); 3798 3799 if (::strstr(continue_cstr, "vAttach") == nullptr) 3800 process->SetPrivateState(eStateRunning); 3801 StringExtractorGDBRemote response; 3802 3803 // If in Non-Stop-Mode 3804 if (process->GetTarget().GetNonStopModeEnabled()) { 3805 // send the vCont packet 3806 if (!process->GetGDBRemote().SendvContPacket( 3807 llvm::StringRef(continue_cstr, continue_cstr_len), 3808 response)) { 3809 // Something went wrong 3810 done = true; 3811 break; 3812 } 3813 } 3814 // If in All-Stop-Mode 3815 else { 3816 StateType stop_state = 3817 process->GetGDBRemote().SendContinuePacketAndWaitForResponse( 3818 *process, *process->GetUnixSignals(), 3819 llvm::StringRef(continue_cstr, continue_cstr_len), 3820 response); 3821 3822 // We need to immediately clear the thread ID list so we are sure 3823 // to get a valid list of threads. The thread ID list might be 3824 // contained within the "response", or the stop reply packet that 3825 // caused the stop. So clear it now before we give the stop reply 3826 // packet to the process using the 3827 // process->SetLastStopPacket()... 3828 process->ClearThreadIDList(); 3829 3830 switch (stop_state) { 3831 case eStateStopped: 3832 case eStateCrashed: 3833 case eStateSuspended: 3834 process->SetLastStopPacket(response); 3835 process->SetPrivateState(stop_state); 3836 break; 3837 3838 case eStateExited: { 3839 process->SetLastStopPacket(response); 3840 process->ClearThreadIDList(); 3841 response.SetFilePos(1); 3842 3843 int exit_status = response.GetHexU8(); 3844 std::string desc_string; 3845 if (response.GetBytesLeft() > 0 && 3846 response.GetChar('-') == ';') { 3847 llvm::StringRef desc_str; 3848 llvm::StringRef desc_token; 3849 while (response.GetNameColonValue(desc_token, desc_str)) { 3850 if (desc_token != "description") 3851 continue; 3852 StringExtractor extractor(desc_str); 3853 extractor.GetHexByteString(desc_string); 3854 } 3855 } 3856 process->SetExitStatus(exit_status, desc_string.c_str()); 3857 done = true; 3858 break; 3859 } 3860 case eStateInvalid: { 3861 // Check to see if we were trying to attach and if we got back 3862 // the "E87" error code from debugserver -- this indicates that 3863 // the process is not debuggable. Return a slightly more 3864 // helpful error message about why the attach failed. 3865 if (::strstr(continue_cstr, "vAttach") != nullptr && 3866 response.GetError() == 0x87) { 3867 process->SetExitStatus(-1, "cannot attach to process due to " 3868 "System Integrity Protection"); 3869 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3870 response.GetStatus().Fail()) { 3871 process->SetExitStatus(-1, response.GetStatus().AsCString()); 3872 } else { 3873 process->SetExitStatus(-1, "lost connection"); 3874 } 3875 break; 3876 } 3877 3878 default: 3879 process->SetPrivateState(stop_state); 3880 break; 3881 } // switch(stop_state) 3882 } // else // if in All-stop-mode 3883 } // if (continue_packet) 3884 } // case eBroadcastBitAysncContinue 3885 break; 3886 3887 case eBroadcastBitAsyncThreadShouldExit: 3888 if (log) 3889 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3890 ") got eBroadcastBitAsyncThreadShouldExit...", 3891 __FUNCTION__, arg, process->GetID()); 3892 done = true; 3893 break; 3894 3895 default: 3896 if (log) 3897 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3898 ") got unknown event 0x%8.8x", 3899 __FUNCTION__, arg, process->GetID(), event_type); 3900 done = true; 3901 break; 3902 } 3903 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) { 3904 switch (event_type) { 3905 case Communication::eBroadcastBitReadThreadDidExit: 3906 process->SetExitStatus(-1, "lost connection"); 3907 done = true; 3908 break; 3909 3910 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: { 3911 lldb_private::Event *event = event_sp.get(); 3912 const EventDataBytes *continue_packet = 3913 EventDataBytes::GetEventDataFromEvent(event); 3914 StringExtractorGDBRemote notify( 3915 (const char *)continue_packet->GetBytes()); 3916 // Hand this over to the process to handle 3917 process->HandleNotifyPacket(notify); 3918 break; 3919 } 3920 3921 default: 3922 if (log) 3923 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3924 ") got unknown event 0x%8.8x", 3925 __FUNCTION__, arg, process->GetID(), event_type); 3926 done = true; 3927 break; 3928 } 3929 } 3930 } else { 3931 if (log) 3932 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3933 ") listener.WaitForEvent (NULL, event_sp) => false", 3934 __FUNCTION__, arg, process->GetID()); 3935 done = true; 3936 } 3937 } 3938 3939 if (log) 3940 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3941 ") thread exiting...", 3942 __FUNCTION__, arg, process->GetID()); 3943 3944 return {}; 3945 } 3946 3947 // uint32_t 3948 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3949 // &matches, std::vector<lldb::pid_t> &pids) 3950 //{ 3951 // // If we are planning to launch the debugserver remotely, then we need to 3952 // fire up a debugserver 3953 // // process and ask it for the list of processes. But if we are local, we 3954 // can let the Host do it. 3955 // if (m_local_debugserver) 3956 // { 3957 // return Host::ListProcessesMatchingName (name, matches, pids); 3958 // } 3959 // else 3960 // { 3961 // // FIXME: Implement talking to the remote debugserver. 3962 // return 0; 3963 // } 3964 // 3965 //} 3966 // 3967 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3968 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3969 lldb::user_id_t break_loc_id) { 3970 // I don't think I have to do anything here, just make sure I notice the new 3971 // thread when it starts to 3972 // run so I can stop it if that's what I want to do. 3973 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3974 if (log) 3975 log->Printf("Hit New Thread Notification breakpoint."); 3976 return false; 3977 } 3978 3979 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3980 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3981 LLDB_LOG(log, "Check if need to update ignored signals"); 3982 3983 // QPassSignals package is not supported by the server, there is no way we 3984 // can ignore any signals on server side. 3985 if (!m_gdb_comm.GetQPassSignalsSupported()) 3986 return Status(); 3987 3988 // No signals, nothing to send. 3989 if (m_unix_signals_sp == nullptr) 3990 return Status(); 3991 3992 // Signals' version hasn't changed, no need to send anything. 3993 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3994 if (new_signals_version == m_last_signals_version) { 3995 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3996 m_last_signals_version); 3997 return Status(); 3998 } 3999 4000 auto signals_to_ignore = 4001 m_unix_signals_sp->GetFilteredSignals(false, false, false); 4002 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 4003 4004 LLDB_LOG(log, 4005 "Signals' version changed. old version={0}, new version={1}, " 4006 "signals ignored={2}, update result={3}", 4007 m_last_signals_version, new_signals_version, 4008 signals_to_ignore.size(), error); 4009 4010 if (error.Success()) 4011 m_last_signals_version = new_signals_version; 4012 4013 return error; 4014 } 4015 4016 bool ProcessGDBRemote::StartNoticingNewThreads() { 4017 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 4018 if (m_thread_create_bp_sp) { 4019 if (log && log->GetVerbose()) 4020 log->Printf("Enabled noticing new thread breakpoint."); 4021 m_thread_create_bp_sp->SetEnabled(true); 4022 } else { 4023 PlatformSP platform_sp(GetTarget().GetPlatform()); 4024 if (platform_sp) { 4025 m_thread_create_bp_sp = 4026 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 4027 if (m_thread_create_bp_sp) { 4028 if (log && log->GetVerbose()) 4029 log->Printf( 4030 "Successfully created new thread notification breakpoint %i", 4031 m_thread_create_bp_sp->GetID()); 4032 m_thread_create_bp_sp->SetCallback( 4033 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 4034 } else { 4035 if (log) 4036 log->Printf("Failed to create new thread notification breakpoint."); 4037 } 4038 } 4039 } 4040 return m_thread_create_bp_sp.get() != nullptr; 4041 } 4042 4043 bool ProcessGDBRemote::StopNoticingNewThreads() { 4044 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 4045 if (log && log->GetVerbose()) 4046 log->Printf("Disabling new thread notification breakpoint."); 4047 4048 if (m_thread_create_bp_sp) 4049 m_thread_create_bp_sp->SetEnabled(false); 4050 4051 return true; 4052 } 4053 4054 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 4055 if (m_dyld_up.get() == nullptr) 4056 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 4057 return m_dyld_up.get(); 4058 } 4059 4060 Status ProcessGDBRemote::SendEventData(const char *data) { 4061 int return_value; 4062 bool was_supported; 4063 4064 Status error; 4065 4066 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 4067 if (return_value != 0) { 4068 if (!was_supported) 4069 error.SetErrorString("Sending events is not supported for this process."); 4070 else 4071 error.SetErrorStringWithFormat("Error sending event data: %d.", 4072 return_value); 4073 } 4074 return error; 4075 } 4076 4077 DataExtractor ProcessGDBRemote::GetAuxvData() { 4078 DataBufferSP buf; 4079 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 4080 std::string response_string; 4081 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", 4082 response_string) == 4083 GDBRemoteCommunication::PacketResult::Success) 4084 buf = std::make_shared<DataBufferHeap>(response_string.c_str(), 4085 response_string.length()); 4086 } 4087 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 4088 } 4089 4090 StructuredData::ObjectSP 4091 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 4092 StructuredData::ObjectSP object_sp; 4093 4094 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 4095 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4096 SystemRuntime *runtime = GetSystemRuntime(); 4097 if (runtime) { 4098 runtime->AddThreadExtendedInfoPacketHints(args_dict); 4099 } 4100 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 4101 4102 StreamString packet; 4103 packet << "jThreadExtendedInfo:"; 4104 args_dict->Dump(packet, false); 4105 4106 // FIXME the final character of a JSON dictionary, '}', is the escape 4107 // character in gdb-remote binary mode. lldb currently doesn't escape 4108 // these characters in its packet output -- so we add the quoted version of 4109 // the } character here manually in case we talk to a debugserver which un- 4110 // escapes the characters at packet read time. 4111 packet << (char)(0x7d ^ 0x20); 4112 4113 StringExtractorGDBRemote response; 4114 response.SetResponseValidatorToJSON(); 4115 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4116 false) == 4117 GDBRemoteCommunication::PacketResult::Success) { 4118 StringExtractorGDBRemote::ResponseType response_type = 4119 response.GetResponseType(); 4120 if (response_type == StringExtractorGDBRemote::eResponse) { 4121 if (!response.Empty()) { 4122 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4123 } 4124 } 4125 } 4126 } 4127 return object_sp; 4128 } 4129 4130 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4131 lldb::addr_t image_list_address, lldb::addr_t image_count) { 4132 4133 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4134 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 4135 image_list_address); 4136 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 4137 4138 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4139 } 4140 4141 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 4142 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4143 4144 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 4145 4146 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4147 } 4148 4149 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4150 const std::vector<lldb::addr_t> &load_addresses) { 4151 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4152 StructuredData::ArraySP addresses(new StructuredData::Array); 4153 4154 for (auto addr : load_addresses) { 4155 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr)); 4156 addresses->AddItem(addr_sp); 4157 } 4158 4159 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 4160 4161 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4162 } 4163 4164 StructuredData::ObjectSP 4165 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 4166 StructuredData::ObjectSP args_dict) { 4167 StructuredData::ObjectSP object_sp; 4168 4169 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 4170 // Scope for the scoped timeout object 4171 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 4172 std::chrono::seconds(10)); 4173 4174 StreamString packet; 4175 packet << "jGetLoadedDynamicLibrariesInfos:"; 4176 args_dict->Dump(packet, false); 4177 4178 // FIXME the final character of a JSON dictionary, '}', is the escape 4179 // character in gdb-remote binary mode. lldb currently doesn't escape 4180 // these characters in its packet output -- so we add the quoted version of 4181 // the } character here manually in case we talk to a debugserver which un- 4182 // escapes the characters at packet read time. 4183 packet << (char)(0x7d ^ 0x20); 4184 4185 StringExtractorGDBRemote response; 4186 response.SetResponseValidatorToJSON(); 4187 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4188 false) == 4189 GDBRemoteCommunication::PacketResult::Success) { 4190 StringExtractorGDBRemote::ResponseType response_type = 4191 response.GetResponseType(); 4192 if (response_type == StringExtractorGDBRemote::eResponse) { 4193 if (!response.Empty()) { 4194 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4195 } 4196 } 4197 } 4198 } 4199 return object_sp; 4200 } 4201 4202 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 4203 StructuredData::ObjectSP object_sp; 4204 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4205 4206 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 4207 StreamString packet; 4208 packet << "jGetSharedCacheInfo:"; 4209 args_dict->Dump(packet, false); 4210 4211 // FIXME the final character of a JSON dictionary, '}', is the escape 4212 // character in gdb-remote binary mode. lldb currently doesn't escape 4213 // these characters in its packet output -- so we add the quoted version of 4214 // the } character here manually in case we talk to a debugserver which un- 4215 // escapes the characters at packet read time. 4216 packet << (char)(0x7d ^ 0x20); 4217 4218 StringExtractorGDBRemote response; 4219 response.SetResponseValidatorToJSON(); 4220 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4221 false) == 4222 GDBRemoteCommunication::PacketResult::Success) { 4223 StringExtractorGDBRemote::ResponseType response_type = 4224 response.GetResponseType(); 4225 if (response_type == StringExtractorGDBRemote::eResponse) { 4226 if (!response.Empty()) { 4227 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4228 } 4229 } 4230 } 4231 } 4232 return object_sp; 4233 } 4234 4235 Status ProcessGDBRemote::ConfigureStructuredData( 4236 ConstString type_name, const StructuredData::ObjectSP &config_sp) { 4237 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 4238 } 4239 4240 // Establish the largest memory read/write payloads we should use. If the 4241 // remote stub has a max packet size, stay under that size. 4242 // 4243 // If the remote stub's max packet size is crazy large, use a reasonable 4244 // largeish default. 4245 // 4246 // If the remote stub doesn't advertise a max packet size, use a conservative 4247 // default. 4248 4249 void ProcessGDBRemote::GetMaxMemorySize() { 4250 const uint64_t reasonable_largeish_default = 128 * 1024; 4251 const uint64_t conservative_default = 512; 4252 4253 if (m_max_memory_size == 0) { 4254 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4255 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 4256 // Save the stub's claimed maximum packet size 4257 m_remote_stub_max_memory_size = stub_max_size; 4258 4259 // Even if the stub says it can support ginormous packets, don't exceed 4260 // our reasonable largeish default packet size. 4261 if (stub_max_size > reasonable_largeish_default) { 4262 stub_max_size = reasonable_largeish_default; 4263 } 4264 4265 // Memory packet have other overheads too like Maddr,size:#NN Instead of 4266 // calculating the bytes taken by size and addr every time, we take a 4267 // maximum guess here. 4268 if (stub_max_size > 70) 4269 stub_max_size -= 32 + 32 + 6; 4270 else { 4271 // In unlikely scenario that max packet size is less then 70, we will 4272 // hope that data being written is small enough to fit. 4273 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 4274 GDBR_LOG_COMM | GDBR_LOG_MEMORY)); 4275 if (log) 4276 log->Warning("Packet size is too small. " 4277 "LLDB may face problems while writing memory"); 4278 } 4279 4280 m_max_memory_size = stub_max_size; 4281 } else { 4282 m_max_memory_size = conservative_default; 4283 } 4284 } 4285 } 4286 4287 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 4288 uint64_t user_specified_max) { 4289 if (user_specified_max != 0) { 4290 GetMaxMemorySize(); 4291 4292 if (m_remote_stub_max_memory_size != 0) { 4293 if (m_remote_stub_max_memory_size < user_specified_max) { 4294 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 4295 // packet size too 4296 // big, go as big 4297 // as the remote stub says we can go. 4298 } else { 4299 m_max_memory_size = user_specified_max; // user's packet size is good 4300 } 4301 } else { 4302 m_max_memory_size = 4303 user_specified_max; // user's packet size is probably fine 4304 } 4305 } 4306 } 4307 4308 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4309 const ArchSpec &arch, 4310 ModuleSpec &module_spec) { 4311 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 4312 4313 const ModuleCacheKey key(module_file_spec.GetPath(), 4314 arch.GetTriple().getTriple()); 4315 auto cached = m_cached_module_specs.find(key); 4316 if (cached != m_cached_module_specs.end()) { 4317 module_spec = cached->second; 4318 return bool(module_spec); 4319 } 4320 4321 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4322 if (log) 4323 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s", 4324 __FUNCTION__, module_file_spec.GetPath().c_str(), 4325 arch.GetTriple().getTriple().c_str()); 4326 return false; 4327 } 4328 4329 if (log) { 4330 StreamString stream; 4331 module_spec.Dump(stream); 4332 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4333 __FUNCTION__, module_file_spec.GetPath().c_str(), 4334 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4335 } 4336 4337 m_cached_module_specs[key] = module_spec; 4338 return true; 4339 } 4340 4341 void ProcessGDBRemote::PrefetchModuleSpecs( 4342 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4343 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4344 if (module_specs) { 4345 for (const FileSpec &spec : module_file_specs) 4346 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4347 triple.getTriple())] = ModuleSpec(); 4348 for (const ModuleSpec &spec : *module_specs) 4349 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4350 triple.getTriple())] = spec; 4351 } 4352 } 4353 4354 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4355 return m_gdb_comm.GetOSVersion(); 4356 } 4357 4358 namespace { 4359 4360 typedef std::vector<std::string> stringVec; 4361 4362 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4363 struct RegisterSetInfo { 4364 ConstString name; 4365 }; 4366 4367 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4368 4369 struct GdbServerTargetInfo { 4370 std::string arch; 4371 std::string osabi; 4372 stringVec includes; 4373 RegisterSetMap reg_set_map; 4374 }; 4375 4376 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info, 4377 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp, 4378 uint32_t &cur_reg_num, uint32_t ®_offset) { 4379 if (!feature_node) 4380 return false; 4381 4382 feature_node.ForEachChildElementWithName( 4383 "reg", 4384 [&target_info, &dyn_reg_info, &cur_reg_num, ®_offset, 4385 &abi_sp](const XMLNode ®_node) -> bool { 4386 std::string gdb_group; 4387 std::string gdb_type; 4388 ConstString reg_name; 4389 ConstString alt_name; 4390 ConstString set_name; 4391 std::vector<uint32_t> value_regs; 4392 std::vector<uint32_t> invalidate_regs; 4393 std::vector<uint8_t> dwarf_opcode_bytes; 4394 bool encoding_set = false; 4395 bool format_set = false; 4396 RegisterInfo reg_info = { 4397 nullptr, // Name 4398 nullptr, // Alt name 4399 0, // byte size 4400 reg_offset, // offset 4401 eEncodingUint, // encoding 4402 eFormatHex, // format 4403 { 4404 LLDB_INVALID_REGNUM, // eh_frame reg num 4405 LLDB_INVALID_REGNUM, // DWARF reg num 4406 LLDB_INVALID_REGNUM, // generic reg num 4407 cur_reg_num, // process plugin reg num 4408 cur_reg_num // native register number 4409 }, 4410 nullptr, 4411 nullptr, 4412 nullptr, // Dwarf Expression opcode bytes pointer 4413 0 // Dwarf Expression opcode bytes length 4414 }; 4415 4416 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4417 ®_name, &alt_name, &set_name, &value_regs, 4418 &invalidate_regs, &encoding_set, &format_set, 4419 ®_info, ®_offset, &dwarf_opcode_bytes]( 4420 const llvm::StringRef &name, 4421 const llvm::StringRef &value) -> bool { 4422 if (name == "name") { 4423 reg_name.SetString(value); 4424 } else if (name == "bitsize") { 4425 reg_info.byte_size = 4426 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; 4427 } else if (name == "type") { 4428 gdb_type = value.str(); 4429 } else if (name == "group") { 4430 gdb_group = value.str(); 4431 } else if (name == "regnum") { 4432 const uint32_t regnum = 4433 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4434 if (regnum != LLDB_INVALID_REGNUM) { 4435 reg_info.kinds[eRegisterKindProcessPlugin] = regnum; 4436 } 4437 } else if (name == "offset") { 4438 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4439 } else if (name == "altname") { 4440 alt_name.SetString(value); 4441 } else if (name == "encoding") { 4442 encoding_set = true; 4443 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4444 } else if (name == "format") { 4445 format_set = true; 4446 Format format = eFormatInvalid; 4447 if (OptionArgParser::ToFormat(value.data(), format, nullptr) 4448 .Success()) 4449 reg_info.format = format; 4450 else if (value == "vector-sint8") 4451 reg_info.format = eFormatVectorOfSInt8; 4452 else if (value == "vector-uint8") 4453 reg_info.format = eFormatVectorOfUInt8; 4454 else if (value == "vector-sint16") 4455 reg_info.format = eFormatVectorOfSInt16; 4456 else if (value == "vector-uint16") 4457 reg_info.format = eFormatVectorOfUInt16; 4458 else if (value == "vector-sint32") 4459 reg_info.format = eFormatVectorOfSInt32; 4460 else if (value == "vector-uint32") 4461 reg_info.format = eFormatVectorOfUInt32; 4462 else if (value == "vector-float32") 4463 reg_info.format = eFormatVectorOfFloat32; 4464 else if (value == "vector-uint64") 4465 reg_info.format = eFormatVectorOfUInt64; 4466 else if (value == "vector-uint128") 4467 reg_info.format = eFormatVectorOfUInt128; 4468 } else if (name == "group_id") { 4469 const uint32_t set_id = 4470 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4471 RegisterSetMap::const_iterator pos = 4472 target_info.reg_set_map.find(set_id); 4473 if (pos != target_info.reg_set_map.end()) 4474 set_name = pos->second.name; 4475 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4476 reg_info.kinds[eRegisterKindEHFrame] = 4477 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4478 } else if (name == "dwarf_regnum") { 4479 reg_info.kinds[eRegisterKindDWARF] = 4480 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4481 } else if (name == "generic") { 4482 reg_info.kinds[eRegisterKindGeneric] = 4483 Args::StringToGenericRegister(value); 4484 } else if (name == "value_regnums") { 4485 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); 4486 } else if (name == "invalidate_regnums") { 4487 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); 4488 } else if (name == "dynamic_size_dwarf_expr_bytes") { 4489 StringExtractor opcode_extractor; 4490 std::string opcode_string = value.str(); 4491 size_t dwarf_opcode_len = opcode_string.length() / 2; 4492 assert(dwarf_opcode_len > 0); 4493 4494 dwarf_opcode_bytes.resize(dwarf_opcode_len); 4495 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; 4496 opcode_extractor.GetStringRef().swap(opcode_string); 4497 uint32_t ret_val = 4498 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); 4499 assert(dwarf_opcode_len == ret_val); 4500 UNUSED_IF_ASSERT_DISABLED(ret_val); 4501 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); 4502 } else { 4503 printf("unhandled attribute %s = %s\n", name.data(), value.data()); 4504 } 4505 return true; // Keep iterating through all attributes 4506 }); 4507 4508 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4509 if (gdb_type.find("int") == 0) { 4510 reg_info.format = eFormatHex; 4511 reg_info.encoding = eEncodingUint; 4512 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4513 reg_info.format = eFormatAddressInfo; 4514 reg_info.encoding = eEncodingUint; 4515 } else if (gdb_type == "i387_ext" || gdb_type == "float") { 4516 reg_info.format = eFormatFloat; 4517 reg_info.encoding = eEncodingIEEE754; 4518 } 4519 } 4520 4521 // Only update the register set name if we didn't get a "reg_set" 4522 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4523 // attribute. 4524 if (!set_name) { 4525 if (!gdb_group.empty()) { 4526 set_name.SetCString(gdb_group.c_str()); 4527 } else { 4528 // If no register group name provided anywhere, 4529 // we'll create a 'general' register set 4530 set_name.SetCString("general"); 4531 } 4532 } 4533 4534 reg_info.byte_offset = reg_offset; 4535 assert(reg_info.byte_size != 0); 4536 reg_offset += reg_info.byte_size; 4537 if (!value_regs.empty()) { 4538 value_regs.push_back(LLDB_INVALID_REGNUM); 4539 reg_info.value_regs = value_regs.data(); 4540 } 4541 if (!invalidate_regs.empty()) { 4542 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 4543 reg_info.invalidate_regs = invalidate_regs.data(); 4544 } 4545 4546 ++cur_reg_num; 4547 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp); 4548 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); 4549 4550 return true; // Keep iterating through all "reg" elements 4551 }); 4552 return true; 4553 } 4554 4555 } // namespace 4556 4557 // This method fetches a register description feature xml file from 4558 // the remote stub and adds registers/register groupsets/architecture 4559 // information to the current process. It will call itself recursively 4560 // for nested register definition files. It returns true if it was able 4561 // to fetch and parse an xml file. 4562 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use, 4563 std::string xml_filename, 4564 uint32_t &cur_reg_num, 4565 uint32_t ®_offset) { 4566 // request the target xml file 4567 std::string raw; 4568 lldb_private::Status lldberr; 4569 if (!m_gdb_comm.ReadExtFeature(ConstString("features"), 4570 ConstString(xml_filename.c_str()), 4571 raw, lldberr)) { 4572 return false; 4573 } 4574 4575 XMLDocument xml_document; 4576 4577 if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) { 4578 GdbServerTargetInfo target_info; 4579 std::vector<XMLNode> feature_nodes; 4580 4581 // The top level feature XML file will start with a <target> tag. 4582 XMLNode target_node = xml_document.GetRootElement("target"); 4583 if (target_node) { 4584 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4585 const XMLNode &node) -> bool { 4586 llvm::StringRef name = node.GetName(); 4587 if (name == "architecture") { 4588 node.GetElementText(target_info.arch); 4589 } else if (name == "osabi") { 4590 node.GetElementText(target_info.osabi); 4591 } else if (name == "xi:include" || name == "include") { 4592 llvm::StringRef href = node.GetAttributeValue("href"); 4593 if (!href.empty()) 4594 target_info.includes.push_back(href.str()); 4595 } else if (name == "feature") { 4596 feature_nodes.push_back(node); 4597 } else if (name == "groups") { 4598 node.ForEachChildElementWithName( 4599 "group", [&target_info](const XMLNode &node) -> bool { 4600 uint32_t set_id = UINT32_MAX; 4601 RegisterSetInfo set_info; 4602 4603 node.ForEachAttribute( 4604 [&set_id, &set_info](const llvm::StringRef &name, 4605 const llvm::StringRef &value) -> bool { 4606 if (name == "id") 4607 set_id = StringConvert::ToUInt32(value.data(), 4608 UINT32_MAX, 0); 4609 if (name == "name") 4610 set_info.name = ConstString(value); 4611 return true; // Keep iterating through all attributes 4612 }); 4613 4614 if (set_id != UINT32_MAX) 4615 target_info.reg_set_map[set_id] = set_info; 4616 return true; // Keep iterating through all "group" elements 4617 }); 4618 } 4619 return true; // Keep iterating through all children of the target_node 4620 }); 4621 } else { 4622 // In an included XML feature file, we're already "inside" the <target> 4623 // tag of the initial XML file; this included file will likely only have 4624 // a <feature> tag. Need to check for any more included files in this 4625 // <feature> element. 4626 XMLNode feature_node = xml_document.GetRootElement("feature"); 4627 if (feature_node) { 4628 feature_nodes.push_back(feature_node); 4629 feature_node.ForEachChildElement([&target_info]( 4630 const XMLNode &node) -> bool { 4631 llvm::StringRef name = node.GetName(); 4632 if (name == "xi:include" || name == "include") { 4633 llvm::StringRef href = node.GetAttributeValue("href"); 4634 if (!href.empty()) 4635 target_info.includes.push_back(href.str()); 4636 } 4637 return true; 4638 }); 4639 } 4640 } 4641 4642 // If the target.xml includes an architecture entry like 4643 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4644 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board) 4645 // use that if we don't have anything better. 4646 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4647 if (target_info.arch == "i386:x86-64") { 4648 // We don't have any information about vendor or OS. 4649 arch_to_use.SetTriple("x86_64--"); 4650 GetTarget().MergeArchitecture(arch_to_use); 4651 } 4652 4653 // SEGGER J-Link jtag boards send this very-generic arch name, 4654 // we'll need to use this if we have absolutely nothing better 4655 // to work with or the register definitions won't be accepted. 4656 if (target_info.arch == "arm") { 4657 arch_to_use.SetTriple("arm--"); 4658 GetTarget().MergeArchitecture(arch_to_use); 4659 } 4660 } 4661 4662 if (arch_to_use.IsValid()) { 4663 // Don't use Process::GetABI, this code gets called from DidAttach, and 4664 // in that context we haven't set the Target's architecture yet, so the 4665 // ABI is also potentially incorrect. 4666 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use); 4667 for (auto &feature_node : feature_nodes) { 4668 ParseRegisters(feature_node, target_info, this->m_register_info, 4669 abi_to_use_sp, cur_reg_num, reg_offset); 4670 } 4671 4672 for (const auto &include : target_info.includes) { 4673 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, 4674 cur_reg_num, reg_offset); 4675 } 4676 } 4677 } else { 4678 return false; 4679 } 4680 return true; 4681 } 4682 4683 // query the target of gdb-remote for extended target information returns 4684 // true on success (got register definitions), false on failure (did not). 4685 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4686 // Make sure LLDB has an XML parser it can use first 4687 if (!XMLDocument::XMLEnabled()) 4688 return false; 4689 4690 // check that we have extended feature read support 4691 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4692 return false; 4693 4694 uint32_t cur_reg_num = 0; 4695 uint32_t reg_offset = 0; 4696 if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset)) 4697 this->m_register_info.Finalize(arch_to_use); 4698 4699 return m_register_info.GetNumRegisters() > 0; 4700 } 4701 4702 Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { 4703 // Make sure LLDB has an XML parser it can use first 4704 if (!XMLDocument::XMLEnabled()) 4705 return Status(0, ErrorType::eErrorTypeGeneric); 4706 4707 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS); 4708 if (log) 4709 log->Printf("ProcessGDBRemote::%s", __FUNCTION__); 4710 4711 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4712 bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4(); 4713 4714 // check that we have extended feature read support 4715 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4716 list.clear(); 4717 4718 // request the loaded library list 4719 std::string raw; 4720 lldb_private::Status lldberr; 4721 4722 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""), 4723 raw, lldberr)) 4724 return Status(0, ErrorType::eErrorTypeGeneric); 4725 4726 // parse the xml file in memory 4727 if (log) 4728 log->Printf("parsing: %s", raw.c_str()); 4729 XMLDocument doc; 4730 4731 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4732 return Status(0, ErrorType::eErrorTypeGeneric); 4733 4734 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4735 if (!root_element) 4736 return Status(); 4737 4738 // main link map structure 4739 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); 4740 if (!main_lm.empty()) { 4741 list.m_link_map = 4742 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); 4743 } 4744 4745 root_element.ForEachChildElementWithName( 4746 "library", [log, &list](const XMLNode &library) -> bool { 4747 4748 LoadedModuleInfoList::LoadedModuleInfo module; 4749 4750 library.ForEachAttribute( 4751 [&module](const llvm::StringRef &name, 4752 const llvm::StringRef &value) -> bool { 4753 4754 if (name == "name") 4755 module.set_name(value.str()); 4756 else if (name == "lm") { 4757 // the address of the link_map struct. 4758 module.set_link_map(StringConvert::ToUInt64( 4759 value.data(), LLDB_INVALID_ADDRESS, 0)); 4760 } else if (name == "l_addr") { 4761 // the displacement as read from the field 'l_addr' of the 4762 // link_map struct. 4763 module.set_base(StringConvert::ToUInt64( 4764 value.data(), LLDB_INVALID_ADDRESS, 0)); 4765 // base address is always a displacement, not an absolute 4766 // value. 4767 module.set_base_is_offset(true); 4768 } else if (name == "l_ld") { 4769 // the memory address of the libraries PT_DYAMIC section. 4770 module.set_dynamic(StringConvert::ToUInt64( 4771 value.data(), LLDB_INVALID_ADDRESS, 0)); 4772 } 4773 4774 return true; // Keep iterating over all properties of "library" 4775 }); 4776 4777 if (log) { 4778 std::string name; 4779 lldb::addr_t lm = 0, base = 0, ld = 0; 4780 bool base_is_offset; 4781 4782 module.get_name(name); 4783 module.get_link_map(lm); 4784 module.get_base(base); 4785 module.get_base_is_offset(base_is_offset); 4786 module.get_dynamic(ld); 4787 4788 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 4789 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 4790 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 4791 name.c_str()); 4792 } 4793 4794 list.add(module); 4795 return true; // Keep iterating over all "library" elements in the root 4796 // node 4797 }); 4798 4799 if (log) 4800 log->Printf("found %" PRId32 " modules in total", 4801 (int)list.m_list.size()); 4802 } else if (comm.GetQXferLibrariesReadSupported()) { 4803 list.clear(); 4804 4805 // request the loaded library list 4806 std::string raw; 4807 lldb_private::Status lldberr; 4808 4809 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw, 4810 lldberr)) 4811 return Status(0, ErrorType::eErrorTypeGeneric); 4812 4813 if (log) 4814 log->Printf("parsing: %s", raw.c_str()); 4815 XMLDocument doc; 4816 4817 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4818 return Status(0, ErrorType::eErrorTypeGeneric); 4819 4820 XMLNode root_element = doc.GetRootElement("library-list"); 4821 if (!root_element) 4822 return Status(); 4823 4824 root_element.ForEachChildElementWithName( 4825 "library", [log, &list](const XMLNode &library) -> bool { 4826 LoadedModuleInfoList::LoadedModuleInfo module; 4827 4828 llvm::StringRef name = library.GetAttributeValue("name"); 4829 module.set_name(name.str()); 4830 4831 // The base address of a given library will be the address of its 4832 // first section. Most remotes send only one section for Windows 4833 // targets for example. 4834 const XMLNode §ion = 4835 library.FindFirstChildElementWithName("section"); 4836 llvm::StringRef address = section.GetAttributeValue("address"); 4837 module.set_base( 4838 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); 4839 // These addresses are absolute values. 4840 module.set_base_is_offset(false); 4841 4842 if (log) { 4843 std::string name; 4844 lldb::addr_t base = 0; 4845 bool base_is_offset; 4846 module.get_name(name); 4847 module.get_base(base); 4848 module.get_base_is_offset(base_is_offset); 4849 4850 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 4851 (base_is_offset ? "offset" : "absolute"), name.c_str()); 4852 } 4853 4854 list.add(module); 4855 return true; // Keep iterating over all "library" elements in the root 4856 // node 4857 }); 4858 4859 if (log) 4860 log->Printf("found %" PRId32 " modules in total", 4861 (int)list.m_list.size()); 4862 } else { 4863 return Status(0, ErrorType::eErrorTypeGeneric); 4864 } 4865 4866 return Status(); 4867 } 4868 4869 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 4870 lldb::addr_t link_map, 4871 lldb::addr_t base_addr, 4872 bool value_is_offset) { 4873 DynamicLoader *loader = GetDynamicLoader(); 4874 if (!loader) 4875 return nullptr; 4876 4877 return loader->LoadModuleAtAddress(file, link_map, base_addr, 4878 value_is_offset); 4879 } 4880 4881 size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) { 4882 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4883 4884 // request a list of loaded libraries from GDBServer 4885 if (GetLoadedModuleList(module_list).Fail()) 4886 return 0; 4887 4888 // get a list of all the modules 4889 ModuleList new_modules; 4890 4891 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) { 4892 std::string mod_name; 4893 lldb::addr_t mod_base; 4894 lldb::addr_t link_map; 4895 bool mod_base_is_offset; 4896 4897 bool valid = true; 4898 valid &= modInfo.get_name(mod_name); 4899 valid &= modInfo.get_base(mod_base); 4900 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 4901 if (!valid) 4902 continue; 4903 4904 if (!modInfo.get_link_map(link_map)) 4905 link_map = LLDB_INVALID_ADDRESS; 4906 4907 FileSpec file(mod_name); 4908 FileSystem::Instance().Resolve(file); 4909 lldb::ModuleSP module_sp = 4910 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 4911 4912 if (module_sp.get()) 4913 new_modules.Append(module_sp); 4914 } 4915 4916 if (new_modules.GetSize() > 0) { 4917 ModuleList removed_modules; 4918 Target &target = GetTarget(); 4919 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4920 4921 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 4922 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 4923 4924 bool found = false; 4925 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 4926 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 4927 found = true; 4928 } 4929 4930 // The main executable will never be included in libraries-svr4, don't 4931 // remove it 4932 if (!found && 4933 loaded_module.get() != target.GetExecutableModulePointer()) { 4934 removed_modules.Append(loaded_module); 4935 } 4936 } 4937 4938 loaded_modules.Remove(removed_modules); 4939 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 4940 4941 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 4942 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 4943 if (!obj) 4944 return true; 4945 4946 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 4947 return true; 4948 4949 lldb::ModuleSP module_copy_sp = module_sp; 4950 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 4951 return false; 4952 }); 4953 4954 loaded_modules.AppendIfNeeded(new_modules); 4955 m_process->GetTarget().ModulesDidLoad(new_modules); 4956 } 4957 4958 return new_modules.GetSize(); 4959 } 4960 4961 size_t ProcessGDBRemote::LoadModules() { 4962 LoadedModuleInfoList module_list; 4963 return LoadModules(module_list); 4964 } 4965 4966 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 4967 bool &is_loaded, 4968 lldb::addr_t &load_addr) { 4969 is_loaded = false; 4970 load_addr = LLDB_INVALID_ADDRESS; 4971 4972 std::string file_path = file.GetPath(false); 4973 if (file_path.empty()) 4974 return Status("Empty file name specified"); 4975 4976 StreamString packet; 4977 packet.PutCString("qFileLoadAddress:"); 4978 packet.PutStringAsRawHex8(file_path); 4979 4980 StringExtractorGDBRemote response; 4981 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4982 false) != 4983 GDBRemoteCommunication::PacketResult::Success) 4984 return Status("Sending qFileLoadAddress packet failed"); 4985 4986 if (response.IsErrorResponse()) { 4987 if (response.GetError() == 1) { 4988 // The file is not loaded into the inferior 4989 is_loaded = false; 4990 load_addr = LLDB_INVALID_ADDRESS; 4991 return Status(); 4992 } 4993 4994 return Status( 4995 "Fetching file load address from remote server returned an error"); 4996 } 4997 4998 if (response.IsNormalResponse()) { 4999 is_loaded = true; 5000 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 5001 return Status(); 5002 } 5003 5004 return Status( 5005 "Unknown error happened during sending the load address packet"); 5006 } 5007 5008 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 5009 // We must call the lldb_private::Process::ModulesDidLoad () first before we 5010 // do anything 5011 Process::ModulesDidLoad(module_list); 5012 5013 // After loading shared libraries, we can ask our remote GDB server if it 5014 // needs any symbols. 5015 m_gdb_comm.ServeSymbolLookups(this); 5016 } 5017 5018 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 5019 AppendSTDOUT(out.data(), out.size()); 5020 } 5021 5022 static const char *end_delimiter = "--end--;"; 5023 static const int end_delimiter_len = 8; 5024 5025 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 5026 std::string input = data.str(); // '1' to move beyond 'A' 5027 if (m_partial_profile_data.length() > 0) { 5028 m_partial_profile_data.append(input); 5029 input = m_partial_profile_data; 5030 m_partial_profile_data.clear(); 5031 } 5032 5033 size_t found, pos = 0, len = input.length(); 5034 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 5035 StringExtractorGDBRemote profileDataExtractor( 5036 input.substr(pos, found).c_str()); 5037 std::string profile_data = 5038 HarmonizeThreadIdsForProfileData(profileDataExtractor); 5039 BroadcastAsyncProfileData(profile_data); 5040 5041 pos = found + end_delimiter_len; 5042 } 5043 5044 if (pos < len) { 5045 // Last incomplete chunk. 5046 m_partial_profile_data = input.substr(pos); 5047 } 5048 } 5049 5050 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 5051 StringExtractorGDBRemote &profileDataExtractor) { 5052 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 5053 std::string output; 5054 llvm::raw_string_ostream output_stream(output); 5055 llvm::StringRef name, value; 5056 5057 // Going to assuming thread_used_usec comes first, else bail out. 5058 while (profileDataExtractor.GetNameColonValue(name, value)) { 5059 if (name.compare("thread_used_id") == 0) { 5060 StringExtractor threadIDHexExtractor(value); 5061 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 5062 5063 bool has_used_usec = false; 5064 uint32_t curr_used_usec = 0; 5065 llvm::StringRef usec_name, usec_value; 5066 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 5067 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 5068 if (usec_name.equals("thread_used_usec")) { 5069 has_used_usec = true; 5070 usec_value.getAsInteger(0, curr_used_usec); 5071 } else { 5072 // We didn't find what we want, it is probably an older version. Bail 5073 // out. 5074 profileDataExtractor.SetFilePos(input_file_pos); 5075 } 5076 } 5077 5078 if (has_used_usec) { 5079 uint32_t prev_used_usec = 0; 5080 std::map<uint64_t, uint32_t>::iterator iterator = 5081 m_thread_id_to_used_usec_map.find(thread_id); 5082 if (iterator != m_thread_id_to_used_usec_map.end()) { 5083 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 5084 } 5085 5086 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 5087 // A good first time record is one that runs for at least 0.25 sec 5088 bool good_first_time = 5089 (prev_used_usec == 0) && (real_used_usec > 250000); 5090 bool good_subsequent_time = 5091 (prev_used_usec > 0) && 5092 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 5093 5094 if (good_first_time || good_subsequent_time) { 5095 // We try to avoid doing too many index id reservation, resulting in 5096 // fast increase of index ids. 5097 5098 output_stream << name << ":"; 5099 int32_t index_id = AssignIndexIDToThread(thread_id); 5100 output_stream << index_id << ";"; 5101 5102 output_stream << usec_name << ":" << usec_value << ";"; 5103 } else { 5104 // Skip past 'thread_used_name'. 5105 llvm::StringRef local_name, local_value; 5106 profileDataExtractor.GetNameColonValue(local_name, local_value); 5107 } 5108 5109 // Store current time as previous time so that they can be compared 5110 // later. 5111 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 5112 } else { 5113 // Bail out and use old string. 5114 output_stream << name << ":" << value << ";"; 5115 } 5116 } else { 5117 output_stream << name << ":" << value << ";"; 5118 } 5119 } 5120 output_stream << end_delimiter; 5121 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 5122 5123 return output_stream.str(); 5124 } 5125 5126 void ProcessGDBRemote::HandleStopReply() { 5127 if (GetStopID() != 0) 5128 return; 5129 5130 if (GetID() == LLDB_INVALID_PROCESS_ID) { 5131 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 5132 if (pid != LLDB_INVALID_PROCESS_ID) 5133 SetID(pid); 5134 } 5135 BuildDynamicRegisterInfo(true); 5136 } 5137 5138 static const char *const s_async_json_packet_prefix = "JSON-async:"; 5139 5140 static StructuredData::ObjectSP 5141 ParseStructuredDataPacket(llvm::StringRef packet) { 5142 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 5143 5144 if (!packet.consume_front(s_async_json_packet_prefix)) { 5145 if (log) { 5146 log->Printf( 5147 "GDBRemoteCommunicationClientBase::%s() received $J packet " 5148 "but was not a StructuredData packet: packet starts with " 5149 "%s", 5150 __FUNCTION__, 5151 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 5152 } 5153 return StructuredData::ObjectSP(); 5154 } 5155 5156 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 5157 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet); 5158 if (log) { 5159 if (json_sp) { 5160 StreamString json_str; 5161 json_sp->Dump(json_str); 5162 json_str.Flush(); 5163 log->Printf("ProcessGDBRemote::%s() " 5164 "received Async StructuredData packet: %s", 5165 __FUNCTION__, json_str.GetData()); 5166 } else { 5167 log->Printf("ProcessGDBRemote::%s" 5168 "() received StructuredData packet:" 5169 " parse failure", 5170 __FUNCTION__); 5171 } 5172 } 5173 return json_sp; 5174 } 5175 5176 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5177 auto structured_data_sp = ParseStructuredDataPacket(data); 5178 if (structured_data_sp) 5179 RouteAsyncStructuredData(structured_data_sp); 5180 } 5181 5182 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5183 public: 5184 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5185 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5186 "Tests packet speeds of various sizes to determine " 5187 "the performance characteristics of the GDB remote " 5188 "connection. ", 5189 nullptr), 5190 m_option_group(), 5191 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5192 "The number of packets to send of each varying size " 5193 "(default is 1000).", 5194 1000), 5195 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5196 "The maximum number of bytes to send in a packet. Sizes " 5197 "increase in powers of 2 while the size is less than or " 5198 "equal to this option value. (default 1024).", 5199 1024), 5200 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5201 "The maximum number of bytes to receive in a packet. Sizes " 5202 "increase in powers of 2 while the size is less than or " 5203 "equal to this option value. (default 1024).", 5204 1024), 5205 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5206 "Print the output as JSON data for easy parsing.", false, true) { 5207 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5208 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5209 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5210 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5211 m_option_group.Finalize(); 5212 } 5213 5214 ~CommandObjectProcessGDBRemoteSpeedTest() override {} 5215 5216 Options *GetOptions() override { return &m_option_group; } 5217 5218 bool DoExecute(Args &command, CommandReturnObject &result) override { 5219 const size_t argc = command.GetArgumentCount(); 5220 if (argc == 0) { 5221 ProcessGDBRemote *process = 5222 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5223 .GetProcessPtr(); 5224 if (process) { 5225 StreamSP output_stream_sp( 5226 m_interpreter.GetDebugger().GetAsyncOutputStream()); 5227 result.SetImmediateOutputStream(output_stream_sp); 5228 5229 const uint32_t num_packets = 5230 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5231 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5232 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5233 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5234 const uint64_t k_recv_amount = 5235 4 * 1024 * 1024; // Receive amount in bytes 5236 process->GetGDBRemote().TestPacketSpeed( 5237 num_packets, max_send, max_recv, k_recv_amount, json, 5238 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5239 result.SetStatus(eReturnStatusSuccessFinishResult); 5240 return true; 5241 } 5242 } else { 5243 result.AppendErrorWithFormat("'%s' takes no arguments", 5244 m_cmd_name.c_str()); 5245 } 5246 result.SetStatus(eReturnStatusFailed); 5247 return false; 5248 } 5249 5250 protected: 5251 OptionGroupOptions m_option_group; 5252 OptionGroupUInt64 m_num_packets; 5253 OptionGroupUInt64 m_max_send; 5254 OptionGroupUInt64 m_max_recv; 5255 OptionGroupBoolean m_json; 5256 }; 5257 5258 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5259 private: 5260 public: 5261 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5262 : CommandObjectParsed(interpreter, "process plugin packet history", 5263 "Dumps the packet history buffer. ", nullptr) {} 5264 5265 ~CommandObjectProcessGDBRemotePacketHistory() override {} 5266 5267 bool DoExecute(Args &command, CommandReturnObject &result) override { 5268 const size_t argc = command.GetArgumentCount(); 5269 if (argc == 0) { 5270 ProcessGDBRemote *process = 5271 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5272 .GetProcessPtr(); 5273 if (process) { 5274 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 5275 result.SetStatus(eReturnStatusSuccessFinishResult); 5276 return true; 5277 } 5278 } else { 5279 result.AppendErrorWithFormat("'%s' takes no arguments", 5280 m_cmd_name.c_str()); 5281 } 5282 result.SetStatus(eReturnStatusFailed); 5283 return false; 5284 } 5285 }; 5286 5287 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5288 private: 5289 public: 5290 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5291 : CommandObjectParsed( 5292 interpreter, "process plugin packet xfer-size", 5293 "Maximum size that lldb will try to read/write one one chunk.", 5294 nullptr) {} 5295 5296 ~CommandObjectProcessGDBRemotePacketXferSize() override {} 5297 5298 bool DoExecute(Args &command, CommandReturnObject &result) override { 5299 const size_t argc = command.GetArgumentCount(); 5300 if (argc == 0) { 5301 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5302 "amount to be transferred when " 5303 "reading/writing", 5304 m_cmd_name.c_str()); 5305 result.SetStatus(eReturnStatusFailed); 5306 return false; 5307 } 5308 5309 ProcessGDBRemote *process = 5310 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5311 if (process) { 5312 const char *packet_size = command.GetArgumentAtIndex(0); 5313 errno = 0; 5314 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5315 if (errno == 0 && user_specified_max != 0) { 5316 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5317 result.SetStatus(eReturnStatusSuccessFinishResult); 5318 return true; 5319 } 5320 } 5321 result.SetStatus(eReturnStatusFailed); 5322 return false; 5323 } 5324 }; 5325 5326 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5327 private: 5328 public: 5329 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5330 : CommandObjectParsed(interpreter, "process plugin packet send", 5331 "Send a custom packet through the GDB remote " 5332 "protocol and print the answer. " 5333 "The packet header and footer will automatically " 5334 "be added to the packet prior to sending and " 5335 "stripped from the result.", 5336 nullptr) {} 5337 5338 ~CommandObjectProcessGDBRemotePacketSend() override {} 5339 5340 bool DoExecute(Args &command, CommandReturnObject &result) override { 5341 const size_t argc = command.GetArgumentCount(); 5342 if (argc == 0) { 5343 result.AppendErrorWithFormat( 5344 "'%s' takes a one or more packet content arguments", 5345 m_cmd_name.c_str()); 5346 result.SetStatus(eReturnStatusFailed); 5347 return false; 5348 } 5349 5350 ProcessGDBRemote *process = 5351 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5352 if (process) { 5353 for (size_t i = 0; i < argc; ++i) { 5354 const char *packet_cstr = command.GetArgumentAtIndex(0); 5355 bool send_async = true; 5356 StringExtractorGDBRemote response; 5357 process->GetGDBRemote().SendPacketAndWaitForResponse( 5358 packet_cstr, response, send_async); 5359 result.SetStatus(eReturnStatusSuccessFinishResult); 5360 Stream &output_strm = result.GetOutputStream(); 5361 output_strm.Printf(" packet: %s\n", packet_cstr); 5362 std::string &response_str = response.GetStringRef(); 5363 5364 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5365 response_str = process->HarmonizeThreadIdsForProfileData(response); 5366 } 5367 5368 if (response_str.empty()) 5369 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5370 else 5371 output_strm.Printf("response: %s\n", response.GetStringRef().c_str()); 5372 } 5373 } 5374 return true; 5375 } 5376 }; 5377 5378 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5379 private: 5380 public: 5381 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5382 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5383 "Send a qRcmd packet through the GDB remote protocol " 5384 "and print the response." 5385 "The argument passed to this command will be hex " 5386 "encoded into a valid 'qRcmd' packet, sent and the " 5387 "response will be printed.") {} 5388 5389 ~CommandObjectProcessGDBRemotePacketMonitor() override {} 5390 5391 bool DoExecute(llvm::StringRef command, 5392 CommandReturnObject &result) override { 5393 if (command.empty()) { 5394 result.AppendErrorWithFormat("'%s' takes a command string argument", 5395 m_cmd_name.c_str()); 5396 result.SetStatus(eReturnStatusFailed); 5397 return false; 5398 } 5399 5400 ProcessGDBRemote *process = 5401 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5402 if (process) { 5403 StreamString packet; 5404 packet.PutCString("qRcmd,"); 5405 packet.PutBytesAsRawHex8(command.data(), command.size()); 5406 5407 bool send_async = true; 5408 StringExtractorGDBRemote response; 5409 Stream &output_strm = result.GetOutputStream(); 5410 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5411 packet.GetString(), response, send_async, 5412 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5413 result.SetStatus(eReturnStatusSuccessFinishResult); 5414 output_strm.Printf(" packet: %s\n", packet.GetData()); 5415 const std::string &response_str = response.GetStringRef(); 5416 5417 if (response_str.empty()) 5418 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5419 else 5420 output_strm.Printf("response: %s\n", response.GetStringRef().c_str()); 5421 } 5422 return true; 5423 } 5424 }; 5425 5426 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5427 private: 5428 public: 5429 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5430 : CommandObjectMultiword(interpreter, "process plugin packet", 5431 "Commands that deal with GDB remote packets.", 5432 nullptr) { 5433 LoadSubCommand( 5434 "history", 5435 CommandObjectSP( 5436 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5437 LoadSubCommand( 5438 "send", CommandObjectSP( 5439 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5440 LoadSubCommand( 5441 "monitor", 5442 CommandObjectSP( 5443 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5444 LoadSubCommand( 5445 "xfer-size", 5446 CommandObjectSP( 5447 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5448 LoadSubCommand("speed-test", 5449 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5450 interpreter))); 5451 } 5452 5453 ~CommandObjectProcessGDBRemotePacket() override {} 5454 }; 5455 5456 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5457 public: 5458 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5459 : CommandObjectMultiword( 5460 interpreter, "process plugin", 5461 "Commands for operating on a ProcessGDBRemote process.", 5462 "process plugin <subcommand> [<subcommand-options>]") { 5463 LoadSubCommand( 5464 "packet", 5465 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5466 } 5467 5468 ~CommandObjectMultiwordProcessGDBRemote() override {} 5469 }; 5470 5471 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5472 if (!m_command_sp) 5473 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5474 GetTarget().GetDebugger().GetCommandInterpreter()); 5475 return m_command_sp.get(); 5476 } 5477