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