1 //===-- ProcessMinidump.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 "ProcessMinidump.h" 10 11 #include "ThreadMinidump.h" 12 13 #include "lldb/Core/DumpDataExtractor.h" 14 #include "lldb/Core/Module.h" 15 #include "lldb/Core/ModuleSpec.h" 16 #include "lldb/Core/PluginManager.h" 17 #include "lldb/Core/Section.h" 18 #include "lldb/Interpreter/CommandInterpreter.h" 19 #include "lldb/Interpreter/CommandObject.h" 20 #include "lldb/Interpreter/CommandObjectMultiword.h" 21 #include "lldb/Interpreter/CommandReturnObject.h" 22 #include "lldb/Interpreter/OptionArgParser.h" 23 #include "lldb/Interpreter/OptionGroupBoolean.h" 24 #include "lldb/Target/JITLoaderList.h" 25 #include "lldb/Target/MemoryRegionInfo.h" 26 #include "lldb/Target/SectionLoadList.h" 27 #include "lldb/Target/Target.h" 28 #include "lldb/Target/UnixSignals.h" 29 #include "lldb/Utility/LLDBAssert.h" 30 #include "lldb/Utility/LLDBLog.h" 31 #include "lldb/Utility/Log.h" 32 #include "lldb/Utility/State.h" 33 #include "llvm/BinaryFormat/Magic.h" 34 #include "llvm/Support/MemoryBuffer.h" 35 #include "llvm/Support/Threading.h" 36 37 #include "Plugins/Process/Utility/StopInfoMachException.h" 38 39 #include <memory> 40 #include <optional> 41 42 using namespace lldb; 43 using namespace lldb_private; 44 using namespace minidump; 45 46 LLDB_PLUGIN_DEFINE(ProcessMinidump) 47 48 namespace { 49 50 /// A minimal ObjectFile implementation providing a dummy object file for the 51 /// cases when the real module binary is not available. This allows the module 52 /// to show up in "image list" and symbols to be added to it. 53 class PlaceholderObjectFile : public ObjectFile { 54 public: 55 PlaceholderObjectFile(const lldb::ModuleSP &module_sp, 56 const ModuleSpec &module_spec, lldb::addr_t base, 57 lldb::addr_t size) 58 : ObjectFile(module_sp, &module_spec.GetFileSpec(), /*file_offset*/ 0, 59 /*length*/ 0, /*data_sp*/ nullptr, /*data_offset*/ 0), 60 m_arch(module_spec.GetArchitecture()), m_uuid(module_spec.GetUUID()), 61 m_base(base), m_size(size) { 62 m_symtab_up = std::make_unique<Symtab>(this); 63 } 64 65 static ConstString GetStaticPluginName() { 66 return ConstString("placeholder"); 67 } 68 llvm::StringRef GetPluginName() override { 69 return GetStaticPluginName().GetStringRef(); 70 } 71 bool ParseHeader() override { return true; } 72 Type CalculateType() override { return eTypeUnknown; } 73 Strata CalculateStrata() override { return eStrataUnknown; } 74 uint32_t GetDependentModules(FileSpecList &file_list) override { return 0; } 75 bool IsExecutable() const override { return false; } 76 ArchSpec GetArchitecture() override { return m_arch; } 77 UUID GetUUID() override { return m_uuid; } 78 void ParseSymtab(lldb_private::Symtab &symtab) override {} 79 bool IsStripped() override { return true; } 80 ByteOrder GetByteOrder() const override { return m_arch.GetByteOrder(); } 81 82 uint32_t GetAddressByteSize() const override { 83 return m_arch.GetAddressByteSize(); 84 } 85 86 Address GetBaseAddress() override { 87 return Address(m_sections_up->GetSectionAtIndex(0), 0); 88 } 89 90 void CreateSections(SectionList &unified_section_list) override { 91 m_sections_up = std::make_unique<SectionList>(); 92 auto section_sp = std::make_shared<Section>( 93 GetModule(), this, /*sect_id*/ 0, ConstString(".module_image"), 94 eSectionTypeOther, m_base, m_size, /*file_offset*/ 0, /*file_size*/ 0, 95 /*log2align*/ 0, /*flags*/ 0); 96 section_sp->SetPermissions(ePermissionsReadable | ePermissionsExecutable); 97 m_sections_up->AddSection(section_sp); 98 unified_section_list.AddSection(std::move(section_sp)); 99 } 100 101 bool SetLoadAddress(Target &target, addr_t value, 102 bool value_is_offset) override { 103 assert(!value_is_offset); 104 assert(value == m_base); 105 106 // Create sections if they haven't been created already. 107 GetModule()->GetSectionList(); 108 assert(m_sections_up->GetNumSections(0) == 1); 109 110 target.GetSectionLoadList().SetSectionLoadAddress( 111 m_sections_up->GetSectionAtIndex(0), m_base); 112 return true; 113 } 114 115 void Dump(Stream *s) override { 116 s->Format("Placeholder object file for {0} loaded at [{1:x}-{2:x})\n", 117 GetFileSpec(), m_base, m_base + m_size); 118 } 119 120 lldb::addr_t GetBaseImageAddress() const { return m_base; } 121 private: 122 ArchSpec m_arch; 123 UUID m_uuid; 124 lldb::addr_t m_base; 125 lldb::addr_t m_size; 126 }; 127 128 /// Duplicate the HashElfTextSection() from the breakpad sources. 129 /// 130 /// Breakpad, a Google crash log reporting tool suite, creates minidump files 131 /// for many different architectures. When using Breakpad to create ELF 132 /// minidumps, it will check for a GNU build ID when creating a minidump file 133 /// and if one doesn't exist in the file, it will say the UUID of the file is a 134 /// checksum of up to the first 4096 bytes of the .text section. Facebook also 135 /// uses breakpad and modified this hash to avoid collisions so we can 136 /// calculate and check for this as well. 137 /// 138 /// The breakpad code might end up hashing up to 15 bytes that immediately 139 /// follow the .text section in the file, so this code must do exactly what it 140 /// does so we can get an exact match for the UUID. 141 /// 142 /// \param[in] module_sp The module to grab the .text section from. 143 /// 144 /// \param[in,out] breakpad_uuid A vector that will receive the calculated 145 /// breakpad .text hash. 146 /// 147 /// \param[in,out] facebook_uuid A vector that will receive the calculated 148 /// facebook .text hash. 149 /// 150 void HashElfTextSection(ModuleSP module_sp, std::vector<uint8_t> &breakpad_uuid, 151 std::vector<uint8_t> &facebook_uuid) { 152 SectionList *sect_list = module_sp->GetSectionList(); 153 if (sect_list == nullptr) 154 return; 155 SectionSP sect_sp = sect_list->FindSectionByName(ConstString(".text")); 156 if (!sect_sp) 157 return; 158 constexpr size_t kMDGUIDSize = 16; 159 constexpr size_t kBreakpadPageSize = 4096; 160 // The breakpad code has a bug where it might access beyond the end of a 161 // .text section by up to 15 bytes, so we must ensure we round up to the 162 // next kMDGUIDSize byte boundary. 163 DataExtractor data; 164 const size_t text_size = sect_sp->GetFileSize(); 165 const size_t read_size = std::min<size_t>( 166 llvm::alignTo(text_size, kMDGUIDSize), kBreakpadPageSize); 167 sect_sp->GetObjectFile()->GetData(sect_sp->GetFileOffset(), read_size, data); 168 169 breakpad_uuid.assign(kMDGUIDSize, 0); 170 facebook_uuid.assign(kMDGUIDSize, 0); 171 172 // The only difference between the breakpad hash and the facebook hash is the 173 // hashing of the text section size into the hash prior to hashing the .text 174 // contents. 175 for (size_t i = 0; i < kMDGUIDSize; i++) 176 facebook_uuid[i] ^= text_size % 255; 177 178 // This code carefully duplicates how the hash was created in Breakpad 179 // sources, including the error where it might has an extra 15 bytes past the 180 // end of the .text section if the .text section is less than a page size in 181 // length. 182 const uint8_t *ptr = data.GetDataStart(); 183 const uint8_t *ptr_end = data.GetDataEnd(); 184 while (ptr < ptr_end) { 185 for (unsigned i = 0; i < kMDGUIDSize; i++) { 186 breakpad_uuid[i] ^= ptr[i]; 187 facebook_uuid[i] ^= ptr[i]; 188 } 189 ptr += kMDGUIDSize; 190 } 191 } 192 193 } // namespace 194 195 llvm::StringRef ProcessMinidump::GetPluginDescriptionStatic() { 196 return "Minidump plug-in."; 197 } 198 199 lldb::ProcessSP ProcessMinidump::CreateInstance(lldb::TargetSP target_sp, 200 lldb::ListenerSP listener_sp, 201 const FileSpec *crash_file, 202 bool can_connect) { 203 if (!crash_file || can_connect) 204 return nullptr; 205 206 lldb::ProcessSP process_sp; 207 // Read enough data for the Minidump header 208 constexpr size_t header_size = sizeof(Header); 209 auto DataPtr = FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(), 210 header_size, 0); 211 if (!DataPtr) 212 return nullptr; 213 214 lldbassert(DataPtr->GetByteSize() == header_size); 215 if (identify_magic(toStringRef(DataPtr->GetData())) != llvm::file_magic::minidump) 216 return nullptr; 217 218 auto AllData = 219 FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(), -1, 0); 220 if (!AllData) 221 return nullptr; 222 223 return std::make_shared<ProcessMinidump>(target_sp, listener_sp, *crash_file, 224 std::move(AllData)); 225 } 226 227 bool ProcessMinidump::CanDebug(lldb::TargetSP target_sp, 228 bool plugin_specified_by_name) { 229 return true; 230 } 231 232 ProcessMinidump::ProcessMinidump(lldb::TargetSP target_sp, 233 lldb::ListenerSP listener_sp, 234 const FileSpec &core_file, 235 DataBufferSP core_data) 236 : PostMortemProcess(target_sp, listener_sp), m_core_file(core_file), 237 m_core_data(std::move(core_data)), m_active_exception(nullptr), 238 m_is_wow64(false) {} 239 240 ProcessMinidump::~ProcessMinidump() { 241 Clear(); 242 // We need to call finalize on the process before destroying ourselves to 243 // make sure all of the broadcaster cleanup goes as planned. If we destruct 244 // this class, then Process::~Process() might have problems trying to fully 245 // destroy the broadcaster. 246 Finalize(); 247 } 248 249 void ProcessMinidump::Initialize() { 250 static llvm::once_flag g_once_flag; 251 252 llvm::call_once(g_once_flag, []() { 253 PluginManager::RegisterPlugin(GetPluginNameStatic(), 254 GetPluginDescriptionStatic(), 255 ProcessMinidump::CreateInstance); 256 }); 257 } 258 259 void ProcessMinidump::Terminate() { 260 PluginManager::UnregisterPlugin(ProcessMinidump::CreateInstance); 261 } 262 263 Status ProcessMinidump::DoLoadCore() { 264 auto expected_parser = MinidumpParser::Create(m_core_data); 265 if (!expected_parser) 266 return Status(expected_parser.takeError()); 267 m_minidump_parser = std::move(*expected_parser); 268 269 Status error; 270 271 // Do we support the minidump's architecture? 272 ArchSpec arch = GetArchitecture(); 273 switch (arch.GetMachine()) { 274 case llvm::Triple::x86: 275 case llvm::Triple::x86_64: 276 case llvm::Triple::arm: 277 case llvm::Triple::aarch64: 278 // Any supported architectures must be listed here and also supported in 279 // ThreadMinidump::CreateRegisterContextForFrame(). 280 break; 281 default: 282 error.SetErrorStringWithFormat("unsupported minidump architecture: %s", 283 arch.GetArchitectureName()); 284 return error; 285 } 286 GetTarget().SetArchitecture(arch, true /*set_platform*/); 287 288 m_thread_list = m_minidump_parser->GetThreads(); 289 m_active_exception = m_minidump_parser->GetExceptionStream(); 290 291 SetUnixSignals(UnixSignals::Create(GetArchitecture())); 292 293 ReadModuleList(); 294 if (ModuleSP module = GetTarget().GetExecutableModule()) 295 GetTarget().MergeArchitecture(module->GetArchitecture()); 296 std::optional<lldb::pid_t> pid = m_minidump_parser->GetPid(); 297 if (!pid) { 298 Debugger::ReportWarning("unable to retrieve process ID from minidump file, " 299 "setting process ID to 1", 300 GetTarget().GetDebugger().GetID()); 301 pid = 1; 302 } 303 SetID(*pid); 304 305 return error; 306 } 307 308 Status ProcessMinidump::DoDestroy() { return Status(); } 309 310 void ProcessMinidump::RefreshStateAfterStop() { 311 312 if (!m_active_exception) 313 return; 314 315 constexpr uint32_t BreakpadDumpRequested = 0xFFFFFFFF; 316 if (m_active_exception->ExceptionRecord.ExceptionCode == 317 BreakpadDumpRequested) { 318 // This "ExceptionCode" value is a sentinel that is sometimes used 319 // when generating a dump for a process that hasn't crashed. 320 321 // TODO: The definition and use of this "dump requested" constant 322 // in Breakpad are actually Linux-specific, and for similar use 323 // cases on Mac/Windows it defines different constants, referring 324 // to them as "simulated" exceptions; consider moving this check 325 // down to the OS-specific paths and checking each OS for its own 326 // constant. 327 return; 328 } 329 330 lldb::StopInfoSP stop_info; 331 lldb::ThreadSP stop_thread; 332 333 Process::m_thread_list.SetSelectedThreadByID(m_active_exception->ThreadId); 334 stop_thread = Process::m_thread_list.GetSelectedThread(); 335 ArchSpec arch = GetArchitecture(); 336 337 if (arch.GetTriple().getOS() == llvm::Triple::Linux) { 338 uint32_t signo = m_active_exception->ExceptionRecord.ExceptionCode; 339 340 if (signo == 0) { 341 // No stop. 342 return; 343 } 344 345 stop_info = StopInfo::CreateStopReasonWithSignal( 346 *stop_thread, signo); 347 } else if (arch.GetTriple().getVendor() == llvm::Triple::Apple) { 348 stop_info = StopInfoMachException::CreateStopReasonWithMachException( 349 *stop_thread, m_active_exception->ExceptionRecord.ExceptionCode, 2, 350 m_active_exception->ExceptionRecord.ExceptionFlags, 351 m_active_exception->ExceptionRecord.ExceptionAddress, 0); 352 } else { 353 std::string desc; 354 llvm::raw_string_ostream desc_stream(desc); 355 desc_stream << "Exception " 356 << llvm::format_hex( 357 m_active_exception->ExceptionRecord.ExceptionCode, 8) 358 << " encountered at address " 359 << llvm::format_hex( 360 m_active_exception->ExceptionRecord.ExceptionAddress, 8); 361 stop_info = StopInfo::CreateStopReasonWithException( 362 *stop_thread, desc_stream.str().c_str()); 363 } 364 365 stop_thread->SetStopInfo(stop_info); 366 } 367 368 bool ProcessMinidump::IsAlive() { return true; } 369 370 bool ProcessMinidump::WarnBeforeDetach() const { return false; } 371 372 size_t ProcessMinidump::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 373 Status &error) { 374 // Don't allow the caching that lldb_private::Process::ReadMemory does since 375 // we have it all cached in our dump file anyway. 376 return DoReadMemory(addr, buf, size, error); 377 } 378 379 size_t ProcessMinidump::DoReadMemory(lldb::addr_t addr, void *buf, size_t size, 380 Status &error) { 381 382 llvm::ArrayRef<uint8_t> mem = m_minidump_parser->GetMemory(addr, size); 383 if (mem.empty()) { 384 error.SetErrorString("could not parse memory info"); 385 return 0; 386 } 387 388 std::memcpy(buf, mem.data(), mem.size()); 389 return mem.size(); 390 } 391 392 ArchSpec ProcessMinidump::GetArchitecture() { 393 if (!m_is_wow64) { 394 return m_minidump_parser->GetArchitecture(); 395 } 396 397 llvm::Triple triple; 398 triple.setVendor(llvm::Triple::VendorType::UnknownVendor); 399 triple.setArch(llvm::Triple::ArchType::x86); 400 triple.setOS(llvm::Triple::OSType::Win32); 401 return ArchSpec(triple); 402 } 403 404 void ProcessMinidump::BuildMemoryRegions() { 405 if (m_memory_regions) 406 return; 407 m_memory_regions.emplace(); 408 bool is_complete; 409 std::tie(*m_memory_regions, is_complete) = 410 m_minidump_parser->BuildMemoryRegions(); 411 412 if (is_complete) 413 return; 414 415 MemoryRegionInfos to_add; 416 ModuleList &modules = GetTarget().GetImages(); 417 SectionLoadList &load_list = GetTarget().GetSectionLoadList(); 418 modules.ForEach([&](const ModuleSP &module_sp) { 419 SectionList *sections = module_sp->GetSectionList(); 420 for (size_t i = 0; i < sections->GetSize(); ++i) { 421 SectionSP section_sp = sections->GetSectionAtIndex(i); 422 addr_t load_addr = load_list.GetSectionLoadAddress(section_sp); 423 if (load_addr == LLDB_INVALID_ADDRESS) 424 continue; 425 MemoryRegionInfo::RangeType section_range(load_addr, 426 section_sp->GetByteSize()); 427 MemoryRegionInfo region = 428 MinidumpParser::GetMemoryRegionInfo(*m_memory_regions, load_addr); 429 if (region.GetMapped() != MemoryRegionInfo::eYes && 430 region.GetRange().GetRangeBase() <= section_range.GetRangeBase() && 431 section_range.GetRangeEnd() <= region.GetRange().GetRangeEnd()) { 432 to_add.emplace_back(); 433 to_add.back().GetRange() = section_range; 434 to_add.back().SetLLDBPermissions(section_sp->GetPermissions()); 435 to_add.back().SetMapped(MemoryRegionInfo::eYes); 436 to_add.back().SetName(module_sp->GetFileSpec().GetPath().c_str()); 437 } 438 } 439 return true; 440 }); 441 m_memory_regions->insert(m_memory_regions->end(), to_add.begin(), 442 to_add.end()); 443 llvm::sort(*m_memory_regions); 444 } 445 446 Status ProcessMinidump::DoGetMemoryRegionInfo(lldb::addr_t load_addr, 447 MemoryRegionInfo ®ion) { 448 BuildMemoryRegions(); 449 region = MinidumpParser::GetMemoryRegionInfo(*m_memory_regions, load_addr); 450 return Status(); 451 } 452 453 Status ProcessMinidump::GetMemoryRegions(MemoryRegionInfos ®ion_list) { 454 BuildMemoryRegions(); 455 region_list = *m_memory_regions; 456 return Status(); 457 } 458 459 void ProcessMinidump::Clear() { Process::m_thread_list.Clear(); } 460 461 bool ProcessMinidump::DoUpdateThreadList(ThreadList &old_thread_list, 462 ThreadList &new_thread_list) { 463 for (const minidump::Thread &thread : m_thread_list) { 464 LocationDescriptor context_location = thread.Context; 465 466 // If the minidump contains an exception context, use it 467 if (m_active_exception != nullptr && 468 m_active_exception->ThreadId == thread.ThreadId) { 469 context_location = m_active_exception->ThreadContext; 470 } 471 472 llvm::ArrayRef<uint8_t> context; 473 if (!m_is_wow64) 474 context = m_minidump_parser->GetThreadContext(context_location); 475 else 476 context = m_minidump_parser->GetThreadContextWow64(thread); 477 478 lldb::ThreadSP thread_sp(new ThreadMinidump(*this, thread, context)); 479 new_thread_list.AddThread(thread_sp); 480 } 481 return new_thread_list.GetSize(false) > 0; 482 } 483 484 ModuleSP ProcessMinidump::GetOrCreateModule(UUID minidump_uuid, 485 llvm::StringRef name, 486 ModuleSpec module_spec) { 487 Log *log = GetLog(LLDBLog::DynamicLoader); 488 Status error; 489 490 ModuleSP module_sp = 491 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error); 492 if (!module_sp) 493 return module_sp; 494 // We consider the module to be a match if the minidump UUID is a 495 // prefix of the actual UUID, or if either of the UUIDs are empty. 496 const auto dmp_bytes = minidump_uuid.GetBytes(); 497 const auto mod_bytes = module_sp->GetUUID().GetBytes(); 498 const bool match = dmp_bytes.empty() || mod_bytes.empty() || 499 mod_bytes.take_front(dmp_bytes.size()) == dmp_bytes; 500 if (match) { 501 LLDB_LOG(log, "Partial uuid match for {0}.", name); 502 return module_sp; 503 } 504 505 // Breakpad generates minindump files, and if there is no GNU build 506 // ID in the binary, it will calculate a UUID by hashing first 4096 507 // bytes of the .text section and using that as the UUID for a module 508 // in the minidump. Facebook uses a modified breakpad client that 509 // uses a slightly modified this hash to avoid collisions. Check for 510 // UUIDs from the minindump that match these cases and accept the 511 // module we find if they do match. 512 std::vector<uint8_t> breakpad_uuid; 513 std::vector<uint8_t> facebook_uuid; 514 HashElfTextSection(module_sp, breakpad_uuid, facebook_uuid); 515 if (dmp_bytes == llvm::ArrayRef<uint8_t>(breakpad_uuid)) { 516 LLDB_LOG(log, "Breakpad .text hash match for {0}.", name); 517 return module_sp; 518 } 519 if (dmp_bytes == llvm::ArrayRef<uint8_t>(facebook_uuid)) { 520 LLDB_LOG(log, "Facebook .text hash match for {0}.", name); 521 return module_sp; 522 } 523 // The UUID wasn't a partial match and didn't match the .text hash 524 // so remove the module from the target, we will need to create a 525 // placeholder object file. 526 GetTarget().GetImages().Remove(module_sp); 527 module_sp.reset(); 528 return module_sp; 529 } 530 531 void ProcessMinidump::ReadModuleList() { 532 std::vector<const minidump::Module *> filtered_modules = 533 m_minidump_parser->GetFilteredModuleList(); 534 535 Log *log = GetLog(LLDBLog::DynamicLoader); 536 537 for (auto module : filtered_modules) { 538 std::string name = cantFail(m_minidump_parser->GetMinidumpFile().getString( 539 module->ModuleNameRVA)); 540 const uint64_t load_addr = module->BaseOfImage; 541 const uint64_t load_size = module->SizeOfImage; 542 LLDB_LOG(log, "found module: name: {0} {1:x10}-{2:x10} size: {3}", name, 543 load_addr, load_addr + load_size, load_size); 544 545 // check if the process is wow64 - a 32 bit windows process running on a 546 // 64 bit windows 547 if (llvm::StringRef(name).endswith_insensitive("wow64.dll")) { 548 m_is_wow64 = true; 549 } 550 551 const auto uuid = m_minidump_parser->GetModuleUUID(module); 552 auto file_spec = FileSpec(name, GetArchitecture().GetTriple()); 553 ModuleSpec module_spec(file_spec, uuid); 554 module_spec.GetArchitecture() = GetArchitecture(); 555 Status error; 556 // Try and find a module with a full UUID that matches. This function will 557 // add the module to the target if it finds one. 558 lldb::ModuleSP module_sp = GetTarget().GetOrCreateModule(module_spec, 559 true /* notify */, &error); 560 if (module_sp) { 561 LLDB_LOG(log, "Full uuid match for {0}.", name); 562 } else { 563 // We couldn't find a module with an exactly-matching UUID. Sometimes 564 // a minidump UUID is only a partial match or is a hash. So try again 565 // without specifying the UUID, then again without specifying the 566 // directory if that fails. This will allow us to find modules with 567 // partial matches or hash UUIDs in user-provided sysroots or search 568 // directories (target.exec-search-paths). 569 ModuleSpec partial_module_spec = module_spec; 570 partial_module_spec.GetUUID().Clear(); 571 module_sp = GetOrCreateModule(uuid, name, partial_module_spec); 572 if (!module_sp) { 573 partial_module_spec.GetFileSpec().ClearDirectory(); 574 module_sp = GetOrCreateModule(uuid, name, partial_module_spec); 575 } 576 } 577 if (module_sp) { 578 // Watch out for place holder modules that have different paths, but the 579 // same UUID. If the base address is different, create a new module. If 580 // we don't then we will end up setting the load address of a different 581 // PlaceholderObjectFile and an assertion will fire. 582 auto *objfile = module_sp->GetObjectFile(); 583 if (objfile && 584 objfile->GetPluginName() == 585 PlaceholderObjectFile::GetStaticPluginName().GetStringRef()) { 586 if (((PlaceholderObjectFile *)objfile)->GetBaseImageAddress() != 587 load_addr) 588 module_sp.reset(); 589 } 590 } 591 if (!module_sp) { 592 // We failed to locate a matching local object file. Fortunately, the 593 // minidump format encodes enough information about each module's memory 594 // range to allow us to create placeholder modules. 595 // 596 // This enables most LLDB functionality involving address-to-module 597 // translations (ex. identifing the module for a stack frame PC) and 598 // modules/sections commands (ex. target modules list, ...) 599 LLDB_LOG(log, 600 "Unable to locate the matching object file, creating a " 601 "placeholder module for: {0}", 602 name); 603 604 module_sp = Module::CreateModuleFromObjectFile<PlaceholderObjectFile>( 605 module_spec, load_addr, load_size); 606 GetTarget().GetImages().Append(module_sp, true /* notify */); 607 } 608 609 bool load_addr_changed = false; 610 module_sp->SetLoadAddress(GetTarget(), load_addr, false, 611 load_addr_changed); 612 } 613 } 614 615 bool ProcessMinidump::GetProcessInfo(ProcessInstanceInfo &info) { 616 info.Clear(); 617 info.SetProcessID(GetID()); 618 info.SetArchitecture(GetArchitecture()); 619 lldb::ModuleSP module_sp = GetTarget().GetExecutableModule(); 620 if (module_sp) { 621 const bool add_exe_file_as_first_arg = false; 622 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(), 623 add_exe_file_as_first_arg); 624 } 625 return true; 626 } 627 628 // For minidumps there's no runtime generated code so we don't need JITLoader(s) 629 // Avoiding them will also speed up minidump loading since JITLoaders normally 630 // try to set up symbolic breakpoints, which in turn may force loading more 631 // debug information than needed. 632 JITLoaderList &ProcessMinidump::GetJITLoaders() { 633 if (!m_jit_loaders_up) { 634 m_jit_loaders_up = std::make_unique<JITLoaderList>(); 635 } 636 return *m_jit_loaders_up; 637 } 638 639 #define INIT_BOOL(VAR, LONG, SHORT, DESC) \ 640 VAR(LLDB_OPT_SET_1, false, LONG, SHORT, DESC, false, true) 641 #define APPEND_OPT(VAR) \ 642 m_option_group.Append(&VAR, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1) 643 644 class CommandObjectProcessMinidumpDump : public CommandObjectParsed { 645 private: 646 OptionGroupOptions m_option_group; 647 OptionGroupBoolean m_dump_all; 648 OptionGroupBoolean m_dump_directory; 649 OptionGroupBoolean m_dump_linux_cpuinfo; 650 OptionGroupBoolean m_dump_linux_proc_status; 651 OptionGroupBoolean m_dump_linux_lsb_release; 652 OptionGroupBoolean m_dump_linux_cmdline; 653 OptionGroupBoolean m_dump_linux_environ; 654 OptionGroupBoolean m_dump_linux_auxv; 655 OptionGroupBoolean m_dump_linux_maps; 656 OptionGroupBoolean m_dump_linux_proc_stat; 657 OptionGroupBoolean m_dump_linux_proc_uptime; 658 OptionGroupBoolean m_dump_linux_proc_fd; 659 OptionGroupBoolean m_dump_linux_all; 660 OptionGroupBoolean m_fb_app_data; 661 OptionGroupBoolean m_fb_build_id; 662 OptionGroupBoolean m_fb_version; 663 OptionGroupBoolean m_fb_java_stack; 664 OptionGroupBoolean m_fb_dalvik; 665 OptionGroupBoolean m_fb_unwind; 666 OptionGroupBoolean m_fb_error_log; 667 OptionGroupBoolean m_fb_app_state; 668 OptionGroupBoolean m_fb_abort; 669 OptionGroupBoolean m_fb_thread; 670 OptionGroupBoolean m_fb_logcat; 671 OptionGroupBoolean m_fb_all; 672 673 void SetDefaultOptionsIfNoneAreSet() { 674 if (m_dump_all.GetOptionValue().GetCurrentValue() || 675 m_dump_linux_all.GetOptionValue().GetCurrentValue() || 676 m_fb_all.GetOptionValue().GetCurrentValue() || 677 m_dump_directory.GetOptionValue().GetCurrentValue() || 678 m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue() || 679 m_dump_linux_proc_status.GetOptionValue().GetCurrentValue() || 680 m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue() || 681 m_dump_linux_cmdline.GetOptionValue().GetCurrentValue() || 682 m_dump_linux_environ.GetOptionValue().GetCurrentValue() || 683 m_dump_linux_auxv.GetOptionValue().GetCurrentValue() || 684 m_dump_linux_maps.GetOptionValue().GetCurrentValue() || 685 m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue() || 686 m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue() || 687 m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue() || 688 m_fb_app_data.GetOptionValue().GetCurrentValue() || 689 m_fb_build_id.GetOptionValue().GetCurrentValue() || 690 m_fb_version.GetOptionValue().GetCurrentValue() || 691 m_fb_java_stack.GetOptionValue().GetCurrentValue() || 692 m_fb_dalvik.GetOptionValue().GetCurrentValue() || 693 m_fb_unwind.GetOptionValue().GetCurrentValue() || 694 m_fb_error_log.GetOptionValue().GetCurrentValue() || 695 m_fb_app_state.GetOptionValue().GetCurrentValue() || 696 m_fb_abort.GetOptionValue().GetCurrentValue() || 697 m_fb_thread.GetOptionValue().GetCurrentValue() || 698 m_fb_logcat.GetOptionValue().GetCurrentValue()) 699 return; 700 // If no options were set, then dump everything 701 m_dump_all.GetOptionValue().SetCurrentValue(true); 702 } 703 bool DumpAll() const { 704 return m_dump_all.GetOptionValue().GetCurrentValue(); 705 } 706 bool DumpDirectory() const { 707 return DumpAll() || 708 m_dump_directory.GetOptionValue().GetCurrentValue(); 709 } 710 bool DumpLinux() const { 711 return DumpAll() || m_dump_linux_all.GetOptionValue().GetCurrentValue(); 712 } 713 bool DumpLinuxCPUInfo() const { 714 return DumpLinux() || 715 m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue(); 716 } 717 bool DumpLinuxProcStatus() const { 718 return DumpLinux() || 719 m_dump_linux_proc_status.GetOptionValue().GetCurrentValue(); 720 } 721 bool DumpLinuxProcStat() const { 722 return DumpLinux() || 723 m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue(); 724 } 725 bool DumpLinuxLSBRelease() const { 726 return DumpLinux() || 727 m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue(); 728 } 729 bool DumpLinuxCMDLine() const { 730 return DumpLinux() || 731 m_dump_linux_cmdline.GetOptionValue().GetCurrentValue(); 732 } 733 bool DumpLinuxEnviron() const { 734 return DumpLinux() || 735 m_dump_linux_environ.GetOptionValue().GetCurrentValue(); 736 } 737 bool DumpLinuxAuxv() const { 738 return DumpLinux() || 739 m_dump_linux_auxv.GetOptionValue().GetCurrentValue(); 740 } 741 bool DumpLinuxMaps() const { 742 return DumpLinux() || 743 m_dump_linux_maps.GetOptionValue().GetCurrentValue(); 744 } 745 bool DumpLinuxProcUptime() const { 746 return DumpLinux() || 747 m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue(); 748 } 749 bool DumpLinuxProcFD() const { 750 return DumpLinux() || 751 m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue(); 752 } 753 bool DumpFacebook() const { 754 return DumpAll() || m_fb_all.GetOptionValue().GetCurrentValue(); 755 } 756 bool DumpFacebookAppData() const { 757 return DumpFacebook() || m_fb_app_data.GetOptionValue().GetCurrentValue(); 758 } 759 bool DumpFacebookBuildID() const { 760 return DumpFacebook() || m_fb_build_id.GetOptionValue().GetCurrentValue(); 761 } 762 bool DumpFacebookVersionName() const { 763 return DumpFacebook() || m_fb_version.GetOptionValue().GetCurrentValue(); 764 } 765 bool DumpFacebookJavaStack() const { 766 return DumpFacebook() || m_fb_java_stack.GetOptionValue().GetCurrentValue(); 767 } 768 bool DumpFacebookDalvikInfo() const { 769 return DumpFacebook() || m_fb_dalvik.GetOptionValue().GetCurrentValue(); 770 } 771 bool DumpFacebookUnwindSymbols() const { 772 return DumpFacebook() || m_fb_unwind.GetOptionValue().GetCurrentValue(); 773 } 774 bool DumpFacebookErrorLog() const { 775 return DumpFacebook() || m_fb_error_log.GetOptionValue().GetCurrentValue(); 776 } 777 bool DumpFacebookAppStateLog() const { 778 return DumpFacebook() || m_fb_app_state.GetOptionValue().GetCurrentValue(); 779 } 780 bool DumpFacebookAbortReason() const { 781 return DumpFacebook() || m_fb_abort.GetOptionValue().GetCurrentValue(); 782 } 783 bool DumpFacebookThreadName() const { 784 return DumpFacebook() || m_fb_thread.GetOptionValue().GetCurrentValue(); 785 } 786 bool DumpFacebookLogcat() const { 787 return DumpFacebook() || m_fb_logcat.GetOptionValue().GetCurrentValue(); 788 } 789 public: 790 CommandObjectProcessMinidumpDump(CommandInterpreter &interpreter) 791 : CommandObjectParsed(interpreter, "process plugin dump", 792 "Dump information from the minidump file.", nullptr), 793 m_option_group(), 794 INIT_BOOL(m_dump_all, "all", 'a', 795 "Dump the everything in the minidump."), 796 INIT_BOOL(m_dump_directory, "directory", 'd', 797 "Dump the minidump directory map."), 798 INIT_BOOL(m_dump_linux_cpuinfo, "cpuinfo", 'C', 799 "Dump linux /proc/cpuinfo."), 800 INIT_BOOL(m_dump_linux_proc_status, "status", 's', 801 "Dump linux /proc/<pid>/status."), 802 INIT_BOOL(m_dump_linux_lsb_release, "lsb-release", 'r', 803 "Dump linux /etc/lsb-release."), 804 INIT_BOOL(m_dump_linux_cmdline, "cmdline", 'c', 805 "Dump linux /proc/<pid>/cmdline."), 806 INIT_BOOL(m_dump_linux_environ, "environ", 'e', 807 "Dump linux /proc/<pid>/environ."), 808 INIT_BOOL(m_dump_linux_auxv, "auxv", 'x', 809 "Dump linux /proc/<pid>/auxv."), 810 INIT_BOOL(m_dump_linux_maps, "maps", 'm', 811 "Dump linux /proc/<pid>/maps."), 812 INIT_BOOL(m_dump_linux_proc_stat, "stat", 'S', 813 "Dump linux /proc/<pid>/stat."), 814 INIT_BOOL(m_dump_linux_proc_uptime, "uptime", 'u', 815 "Dump linux process uptime."), 816 INIT_BOOL(m_dump_linux_proc_fd, "fd", 'f', 817 "Dump linux /proc/<pid>/fd."), 818 INIT_BOOL(m_dump_linux_all, "linux", 'l', 819 "Dump all linux streams."), 820 INIT_BOOL(m_fb_app_data, "fb-app-data", 1, 821 "Dump Facebook application custom data."), 822 INIT_BOOL(m_fb_build_id, "fb-build-id", 2, 823 "Dump the Facebook build ID."), 824 INIT_BOOL(m_fb_version, "fb-version", 3, 825 "Dump Facebook application version string."), 826 INIT_BOOL(m_fb_java_stack, "fb-java-stack", 4, 827 "Dump Facebook java stack."), 828 INIT_BOOL(m_fb_dalvik, "fb-dalvik-info", 5, 829 "Dump Facebook Dalvik info."), 830 INIT_BOOL(m_fb_unwind, "fb-unwind-symbols", 6, 831 "Dump Facebook unwind symbols."), 832 INIT_BOOL(m_fb_error_log, "fb-error-log", 7, 833 "Dump Facebook error log."), 834 INIT_BOOL(m_fb_app_state, "fb-app-state-log", 8, 835 "Dump Facebook java stack."), 836 INIT_BOOL(m_fb_abort, "fb-abort-reason", 9, 837 "Dump Facebook abort reason."), 838 INIT_BOOL(m_fb_thread, "fb-thread-name", 10, 839 "Dump Facebook thread name."), 840 INIT_BOOL(m_fb_logcat, "fb-logcat", 11, 841 "Dump Facebook logcat."), 842 INIT_BOOL(m_fb_all, "facebook", 12, "Dump all Facebook streams.") { 843 APPEND_OPT(m_dump_all); 844 APPEND_OPT(m_dump_directory); 845 APPEND_OPT(m_dump_linux_cpuinfo); 846 APPEND_OPT(m_dump_linux_proc_status); 847 APPEND_OPT(m_dump_linux_lsb_release); 848 APPEND_OPT(m_dump_linux_cmdline); 849 APPEND_OPT(m_dump_linux_environ); 850 APPEND_OPT(m_dump_linux_auxv); 851 APPEND_OPT(m_dump_linux_maps); 852 APPEND_OPT(m_dump_linux_proc_stat); 853 APPEND_OPT(m_dump_linux_proc_uptime); 854 APPEND_OPT(m_dump_linux_proc_fd); 855 APPEND_OPT(m_dump_linux_all); 856 APPEND_OPT(m_fb_app_data); 857 APPEND_OPT(m_fb_build_id); 858 APPEND_OPT(m_fb_version); 859 APPEND_OPT(m_fb_java_stack); 860 APPEND_OPT(m_fb_dalvik); 861 APPEND_OPT(m_fb_unwind); 862 APPEND_OPT(m_fb_error_log); 863 APPEND_OPT(m_fb_app_state); 864 APPEND_OPT(m_fb_abort); 865 APPEND_OPT(m_fb_thread); 866 APPEND_OPT(m_fb_logcat); 867 APPEND_OPT(m_fb_all); 868 m_option_group.Finalize(); 869 } 870 871 ~CommandObjectProcessMinidumpDump() override = default; 872 873 Options *GetOptions() override { return &m_option_group; } 874 875 bool DoExecute(Args &command, CommandReturnObject &result) override { 876 const size_t argc = command.GetArgumentCount(); 877 if (argc > 0) { 878 result.AppendErrorWithFormat("'%s' take no arguments, only options", 879 m_cmd_name.c_str()); 880 return false; 881 } 882 SetDefaultOptionsIfNoneAreSet(); 883 884 ProcessMinidump *process = static_cast<ProcessMinidump *>( 885 m_interpreter.GetExecutionContext().GetProcessPtr()); 886 result.SetStatus(eReturnStatusSuccessFinishResult); 887 Stream &s = result.GetOutputStream(); 888 MinidumpParser &minidump = *process->m_minidump_parser; 889 if (DumpDirectory()) { 890 s.Printf("RVA SIZE TYPE StreamType\n"); 891 s.Printf("---------- ---------- ---------- --------------------------\n"); 892 for (const auto &stream_desc : minidump.GetMinidumpFile().streams()) 893 s.Printf( 894 "0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)stream_desc.Location.RVA, 895 (uint32_t)stream_desc.Location.DataSize, 896 (unsigned)(StreamType)stream_desc.Type, 897 MinidumpParser::GetStreamTypeAsString(stream_desc.Type).data()); 898 s.Printf("\n"); 899 } 900 auto DumpTextStream = [&](StreamType stream_type, 901 llvm::StringRef label) -> void { 902 auto bytes = minidump.GetStream(stream_type); 903 if (!bytes.empty()) { 904 if (label.empty()) 905 label = MinidumpParser::GetStreamTypeAsString(stream_type); 906 s.Printf("%s:\n%s\n\n", label.data(), bytes.data()); 907 } 908 }; 909 auto DumpBinaryStream = [&](StreamType stream_type, 910 llvm::StringRef label) -> void { 911 auto bytes = minidump.GetStream(stream_type); 912 if (!bytes.empty()) { 913 if (label.empty()) 914 label = MinidumpParser::GetStreamTypeAsString(stream_type); 915 s.Printf("%s:\n", label.data()); 916 DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle, 917 process->GetAddressByteSize()); 918 DumpDataExtractor(data, &s, 0, lldb::eFormatBytesWithASCII, 1, 919 bytes.size(), 16, 0, 0, 0); 920 s.Printf("\n\n"); 921 } 922 }; 923 924 if (DumpLinuxCPUInfo()) 925 DumpTextStream(StreamType::LinuxCPUInfo, "/proc/cpuinfo"); 926 if (DumpLinuxProcStatus()) 927 DumpTextStream(StreamType::LinuxProcStatus, "/proc/PID/status"); 928 if (DumpLinuxLSBRelease()) 929 DumpTextStream(StreamType::LinuxLSBRelease, "/etc/lsb-release"); 930 if (DumpLinuxCMDLine()) 931 DumpTextStream(StreamType::LinuxCMDLine, "/proc/PID/cmdline"); 932 if (DumpLinuxEnviron()) 933 DumpTextStream(StreamType::LinuxEnviron, "/proc/PID/environ"); 934 if (DumpLinuxAuxv()) 935 DumpBinaryStream(StreamType::LinuxAuxv, "/proc/PID/auxv"); 936 if (DumpLinuxMaps()) 937 DumpTextStream(StreamType::LinuxMaps, "/proc/PID/maps"); 938 if (DumpLinuxProcStat()) 939 DumpTextStream(StreamType::LinuxProcStat, "/proc/PID/stat"); 940 if (DumpLinuxProcUptime()) 941 DumpTextStream(StreamType::LinuxProcUptime, "uptime"); 942 if (DumpLinuxProcFD()) 943 DumpTextStream(StreamType::LinuxProcFD, "/proc/PID/fd"); 944 if (DumpFacebookAppData()) 945 DumpTextStream(StreamType::FacebookAppCustomData, 946 "Facebook App Data"); 947 if (DumpFacebookBuildID()) { 948 auto bytes = minidump.GetStream(StreamType::FacebookBuildID); 949 if (bytes.size() >= 4) { 950 DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle, 951 process->GetAddressByteSize()); 952 lldb::offset_t offset = 0; 953 uint32_t build_id = data.GetU32(&offset); 954 s.Printf("Facebook Build ID:\n"); 955 s.Printf("%u\n", build_id); 956 s.Printf("\n"); 957 } 958 } 959 if (DumpFacebookVersionName()) 960 DumpTextStream(StreamType::FacebookAppVersionName, 961 "Facebook Version String"); 962 if (DumpFacebookJavaStack()) 963 DumpTextStream(StreamType::FacebookJavaStack, 964 "Facebook Java Stack"); 965 if (DumpFacebookDalvikInfo()) 966 DumpTextStream(StreamType::FacebookDalvikInfo, 967 "Facebook Dalvik Info"); 968 if (DumpFacebookUnwindSymbols()) 969 DumpBinaryStream(StreamType::FacebookUnwindSymbols, 970 "Facebook Unwind Symbols Bytes"); 971 if (DumpFacebookErrorLog()) 972 DumpTextStream(StreamType::FacebookDumpErrorLog, 973 "Facebook Error Log"); 974 if (DumpFacebookAppStateLog()) 975 DumpTextStream(StreamType::FacebookAppStateLog, 976 "Faceook Application State Log"); 977 if (DumpFacebookAbortReason()) 978 DumpTextStream(StreamType::FacebookAbortReason, 979 "Facebook Abort Reason"); 980 if (DumpFacebookThreadName()) 981 DumpTextStream(StreamType::FacebookThreadName, 982 "Facebook Thread Name"); 983 if (DumpFacebookLogcat()) 984 DumpTextStream(StreamType::FacebookLogcat, 985 "Facebook Logcat"); 986 return true; 987 } 988 }; 989 990 class CommandObjectMultiwordProcessMinidump : public CommandObjectMultiword { 991 public: 992 CommandObjectMultiwordProcessMinidump(CommandInterpreter &interpreter) 993 : CommandObjectMultiword(interpreter, "process plugin", 994 "Commands for operating on a ProcessMinidump process.", 995 "process plugin <subcommand> [<subcommand-options>]") { 996 LoadSubCommand("dump", 997 CommandObjectSP(new CommandObjectProcessMinidumpDump(interpreter))); 998 } 999 1000 ~CommandObjectMultiwordProcessMinidump() override = default; 1001 }; 1002 1003 CommandObject *ProcessMinidump::GetPluginCommandObject() { 1004 if (!m_command_sp) 1005 m_command_sp = std::make_shared<CommandObjectMultiwordProcessMinidump>( 1006 GetTarget().GetDebugger().GetCommandInterpreter()); 1007 return m_command_sp.get(); 1008 } 1009