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