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