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