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