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