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