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