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