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