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 Status ProcessMinidump::GetMemoryRegionInfo(lldb::addr_t load_addr,
338                                             MemoryRegionInfo &range_info) {
339   range_info = m_minidump_parser->GetMemoryRegionInfo(load_addr);
340   return Status();
341 }
342 
343 Status ProcessMinidump::GetMemoryRegions(
344     lldb_private::MemoryRegionInfos &region_list) {
345   region_list = m_minidump_parser->GetMemoryRegions();
346   return Status();
347 }
348 
349 void ProcessMinidump::Clear() { Process::m_thread_list.Clear(); }
350 
351 bool ProcessMinidump::UpdateThreadList(ThreadList &old_thread_list,
352                                        ThreadList &new_thread_list) {
353   for (const minidump::Thread &thread : m_thread_list) {
354     LocationDescriptor context_location = thread.Context;
355 
356     // If the minidump contains an exception context, use it
357     if (m_active_exception != nullptr &&
358         m_active_exception->ThreadId == thread.ThreadId) {
359       context_location = m_active_exception->ThreadContext;
360     }
361 
362     llvm::ArrayRef<uint8_t> context;
363     if (!m_is_wow64)
364       context = m_minidump_parser->GetThreadContext(context_location);
365     else
366       context = m_minidump_parser->GetThreadContextWow64(thread);
367 
368     lldb::ThreadSP thread_sp(new ThreadMinidump(*this, thread, context));
369     new_thread_list.AddThread(thread_sp);
370   }
371   return new_thread_list.GetSize(false) > 0;
372 }
373 
374 void ProcessMinidump::ReadModuleList() {
375   std::vector<const minidump::Module *> filtered_modules =
376       m_minidump_parser->GetFilteredModuleList();
377 
378   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
379 
380   for (auto module : filtered_modules) {
381     std::string name = cantFail(m_minidump_parser->GetMinidumpFile().getString(
382         module->ModuleNameRVA));
383     const uint64_t load_addr = module->BaseOfImage;
384     const uint64_t load_size = module->SizeOfImage;
385     LLDB_LOG(log, "found module: name: {0} {1:x10}-{2:x10} size: {3}", name,
386              load_addr, load_addr + load_size, load_size);
387 
388     // check if the process is wow64 - a 32 bit windows process running on a
389     // 64 bit windows
390     if (llvm::StringRef(name).endswith_lower("wow64.dll")) {
391       m_is_wow64 = true;
392     }
393 
394     const auto uuid = m_minidump_parser->GetModuleUUID(module);
395     auto file_spec = FileSpec(name, GetArchitecture().GetTriple());
396     ModuleSpec module_spec(file_spec, uuid);
397     module_spec.GetArchitecture() = GetArchitecture();
398     Status error;
399     // Try and find a module with a full UUID that matches. This function will
400     // add the module to the target if it finds one.
401     lldb::ModuleSP module_sp = GetTarget().GetOrCreateModule(module_spec,
402                                                      true /* notify */, &error);
403     if (!module_sp) {
404       // Try and find a module without specifying the UUID and only looking for
405       // the file given a basename. We then will look for a partial UUID match
406       // if we find any matches. This function will add the module to the
407       // target if it finds one, so we need to remove the module from the target
408       // if the UUID doesn't match during our manual UUID verification. This
409       // allows the "target.exec-search-paths" setting to specify one or more
410       // directories that contain executables that can be searched for matches.
411       ModuleSpec basename_module_spec(module_spec);
412       basename_module_spec.GetUUID().Clear();
413       basename_module_spec.GetFileSpec().GetDirectory().Clear();
414       module_sp = GetTarget().GetOrCreateModule(basename_module_spec,
415                                                 true /* notify */, &error);
416       if (module_sp) {
417         // We consider the module to be a match if the minidump UUID is a
418         // prefix of the actual UUID, or if either of the UUIDs are empty.
419         const auto dmp_bytes = uuid.GetBytes();
420         const auto mod_bytes = module_sp->GetUUID().GetBytes();
421         const bool match = dmp_bytes.empty() || mod_bytes.empty() ||
422             mod_bytes.take_front(dmp_bytes.size()) == dmp_bytes;
423         if (!match) {
424             GetTarget().GetImages().Remove(module_sp);
425             module_sp.reset();
426         }
427       }
428     }
429     if (module_sp) {
430       // Watch out for place holder modules that have different paths, but the
431       // same UUID. If the base address is different, create a new module. If
432       // we don't then we will end up setting the load address of a different
433       // PlaceholderObjectFile and an assertion will fire.
434       auto *objfile = module_sp->GetObjectFile();
435       if (objfile && objfile->GetPluginName() ==
436           PlaceholderObjectFile::GetStaticPluginName()) {
437         if (((PlaceholderObjectFile *)objfile)->GetBaseImageAddress() !=
438             load_addr)
439           module_sp.reset();
440       }
441     }
442     if (!module_sp) {
443       // We failed to locate a matching local object file. Fortunately, the
444       // minidump format encodes enough information about each module's memory
445       // range to allow us to create placeholder modules.
446       //
447       // This enables most LLDB functionality involving address-to-module
448       // translations (ex. identifing the module for a stack frame PC) and
449       // modules/sections commands (ex. target modules list, ...)
450       LLDB_LOG(log,
451                "Unable to locate the matching object file, creating a "
452                "placeholder module for: {0}",
453                name);
454 
455       module_sp = Module::CreateModuleFromObjectFile<PlaceholderObjectFile>(
456           module_spec, load_addr, load_size);
457       GetTarget().GetImages().Append(module_sp, true /* notify */);
458     }
459 
460     bool load_addr_changed = false;
461     module_sp->SetLoadAddress(GetTarget(), load_addr, false,
462                               load_addr_changed);
463   }
464 }
465 
466 bool ProcessMinidump::GetProcessInfo(ProcessInstanceInfo &info) {
467   info.Clear();
468   info.SetProcessID(GetID());
469   info.SetArchitecture(GetArchitecture());
470   lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
471   if (module_sp) {
472     const bool add_exe_file_as_first_arg = false;
473     info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
474                            add_exe_file_as_first_arg);
475   }
476   return true;
477 }
478 
479 // For minidumps there's no runtime generated code so we don't need JITLoader(s)
480 // Avoiding them will also speed up minidump loading since JITLoaders normally
481 // try to set up symbolic breakpoints, which in turn may force loading more
482 // debug information than needed.
483 JITLoaderList &ProcessMinidump::GetJITLoaders() {
484   if (!m_jit_loaders_up) {
485     m_jit_loaders_up = std::make_unique<JITLoaderList>();
486   }
487   return *m_jit_loaders_up;
488 }
489 
490 #define INIT_BOOL(VAR, LONG, SHORT, DESC) \
491     VAR(LLDB_OPT_SET_1, false, LONG, SHORT, DESC, false, true)
492 #define APPEND_OPT(VAR) \
493     m_option_group.Append(&VAR, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1)
494 
495 class CommandObjectProcessMinidumpDump : public CommandObjectParsed {
496 private:
497   OptionGroupOptions m_option_group;
498   OptionGroupBoolean m_dump_all;
499   OptionGroupBoolean m_dump_directory;
500   OptionGroupBoolean m_dump_linux_cpuinfo;
501   OptionGroupBoolean m_dump_linux_proc_status;
502   OptionGroupBoolean m_dump_linux_lsb_release;
503   OptionGroupBoolean m_dump_linux_cmdline;
504   OptionGroupBoolean m_dump_linux_environ;
505   OptionGroupBoolean m_dump_linux_auxv;
506   OptionGroupBoolean m_dump_linux_maps;
507   OptionGroupBoolean m_dump_linux_proc_stat;
508   OptionGroupBoolean m_dump_linux_proc_uptime;
509   OptionGroupBoolean m_dump_linux_proc_fd;
510   OptionGroupBoolean m_dump_linux_all;
511   OptionGroupBoolean m_fb_app_data;
512   OptionGroupBoolean m_fb_build_id;
513   OptionGroupBoolean m_fb_version;
514   OptionGroupBoolean m_fb_java_stack;
515   OptionGroupBoolean m_fb_dalvik;
516   OptionGroupBoolean m_fb_unwind;
517   OptionGroupBoolean m_fb_error_log;
518   OptionGroupBoolean m_fb_app_state;
519   OptionGroupBoolean m_fb_abort;
520   OptionGroupBoolean m_fb_thread;
521   OptionGroupBoolean m_fb_logcat;
522   OptionGroupBoolean m_fb_all;
523 
524   void SetDefaultOptionsIfNoneAreSet() {
525     if (m_dump_all.GetOptionValue().GetCurrentValue() ||
526         m_dump_linux_all.GetOptionValue().GetCurrentValue() ||
527         m_fb_all.GetOptionValue().GetCurrentValue() ||
528         m_dump_directory.GetOptionValue().GetCurrentValue() ||
529         m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue() ||
530         m_dump_linux_proc_status.GetOptionValue().GetCurrentValue() ||
531         m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue() ||
532         m_dump_linux_cmdline.GetOptionValue().GetCurrentValue() ||
533         m_dump_linux_environ.GetOptionValue().GetCurrentValue() ||
534         m_dump_linux_auxv.GetOptionValue().GetCurrentValue() ||
535         m_dump_linux_maps.GetOptionValue().GetCurrentValue() ||
536         m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue() ||
537         m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue() ||
538         m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue() ||
539         m_fb_app_data.GetOptionValue().GetCurrentValue() ||
540         m_fb_build_id.GetOptionValue().GetCurrentValue() ||
541         m_fb_version.GetOptionValue().GetCurrentValue() ||
542         m_fb_java_stack.GetOptionValue().GetCurrentValue() ||
543         m_fb_dalvik.GetOptionValue().GetCurrentValue() ||
544         m_fb_unwind.GetOptionValue().GetCurrentValue() ||
545         m_fb_error_log.GetOptionValue().GetCurrentValue() ||
546         m_fb_app_state.GetOptionValue().GetCurrentValue() ||
547         m_fb_abort.GetOptionValue().GetCurrentValue() ||
548         m_fb_thread.GetOptionValue().GetCurrentValue() ||
549         m_fb_logcat.GetOptionValue().GetCurrentValue())
550       return;
551     // If no options were set, then dump everything
552     m_dump_all.GetOptionValue().SetCurrentValue(true);
553   }
554   bool DumpAll() const {
555     return m_dump_all.GetOptionValue().GetCurrentValue();
556   }
557   bool DumpDirectory() const {
558     return DumpAll() ||
559         m_dump_directory.GetOptionValue().GetCurrentValue();
560   }
561   bool DumpLinux() const {
562     return DumpAll() || m_dump_linux_all.GetOptionValue().GetCurrentValue();
563   }
564   bool DumpLinuxCPUInfo() const {
565     return DumpLinux() ||
566         m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue();
567   }
568   bool DumpLinuxProcStatus() const {
569     return DumpLinux() ||
570         m_dump_linux_proc_status.GetOptionValue().GetCurrentValue();
571   }
572   bool DumpLinuxProcStat() const {
573     return DumpLinux() ||
574         m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue();
575   }
576   bool DumpLinuxLSBRelease() const {
577     return DumpLinux() ||
578         m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue();
579   }
580   bool DumpLinuxCMDLine() const {
581     return DumpLinux() ||
582         m_dump_linux_cmdline.GetOptionValue().GetCurrentValue();
583   }
584   bool DumpLinuxEnviron() const {
585     return DumpLinux() ||
586         m_dump_linux_environ.GetOptionValue().GetCurrentValue();
587   }
588   bool DumpLinuxAuxv() const {
589     return DumpLinux() ||
590         m_dump_linux_auxv.GetOptionValue().GetCurrentValue();
591   }
592   bool DumpLinuxMaps() const {
593     return DumpLinux() ||
594         m_dump_linux_maps.GetOptionValue().GetCurrentValue();
595   }
596   bool DumpLinuxProcUptime() const {
597     return DumpLinux() ||
598         m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue();
599   }
600   bool DumpLinuxProcFD() const {
601     return DumpLinux() ||
602         m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue();
603   }
604   bool DumpFacebook() const {
605     return DumpAll() || m_fb_all.GetOptionValue().GetCurrentValue();
606   }
607   bool DumpFacebookAppData() const {
608     return DumpFacebook() || m_fb_app_data.GetOptionValue().GetCurrentValue();
609   }
610   bool DumpFacebookBuildID() const {
611     return DumpFacebook() || m_fb_build_id.GetOptionValue().GetCurrentValue();
612   }
613   bool DumpFacebookVersionName() const {
614     return DumpFacebook() || m_fb_version.GetOptionValue().GetCurrentValue();
615   }
616   bool DumpFacebookJavaStack() const {
617     return DumpFacebook() || m_fb_java_stack.GetOptionValue().GetCurrentValue();
618   }
619   bool DumpFacebookDalvikInfo() const {
620     return DumpFacebook() || m_fb_dalvik.GetOptionValue().GetCurrentValue();
621   }
622   bool DumpFacebookUnwindSymbols() const {
623     return DumpFacebook() || m_fb_unwind.GetOptionValue().GetCurrentValue();
624   }
625   bool DumpFacebookErrorLog() const {
626     return DumpFacebook() || m_fb_error_log.GetOptionValue().GetCurrentValue();
627   }
628   bool DumpFacebookAppStateLog() const {
629     return DumpFacebook() || m_fb_app_state.GetOptionValue().GetCurrentValue();
630   }
631   bool DumpFacebookAbortReason() const {
632     return DumpFacebook() || m_fb_abort.GetOptionValue().GetCurrentValue();
633   }
634   bool DumpFacebookThreadName() const {
635     return DumpFacebook() || m_fb_thread.GetOptionValue().GetCurrentValue();
636   }
637   bool DumpFacebookLogcat() const {
638     return DumpFacebook() || m_fb_logcat.GetOptionValue().GetCurrentValue();
639   }
640 public:
641   CommandObjectProcessMinidumpDump(CommandInterpreter &interpreter)
642   : CommandObjectParsed(interpreter, "process plugin dump",
643       "Dump information from the minidump file.", nullptr),
644     m_option_group(),
645     INIT_BOOL(m_dump_all, "all", 'a',
646               "Dump the everything in the minidump."),
647     INIT_BOOL(m_dump_directory, "directory", 'd',
648               "Dump the minidump directory map."),
649     INIT_BOOL(m_dump_linux_cpuinfo, "cpuinfo", 'C',
650               "Dump linux /proc/cpuinfo."),
651     INIT_BOOL(m_dump_linux_proc_status, "status", 's',
652               "Dump linux /proc/<pid>/status."),
653     INIT_BOOL(m_dump_linux_lsb_release, "lsb-release", 'r',
654               "Dump linux /etc/lsb-release."),
655     INIT_BOOL(m_dump_linux_cmdline, "cmdline", 'c',
656               "Dump linux /proc/<pid>/cmdline."),
657     INIT_BOOL(m_dump_linux_environ, "environ", 'e',
658               "Dump linux /proc/<pid>/environ."),
659     INIT_BOOL(m_dump_linux_auxv, "auxv", 'x',
660               "Dump linux /proc/<pid>/auxv."),
661     INIT_BOOL(m_dump_linux_maps, "maps", 'm',
662               "Dump linux /proc/<pid>/maps."),
663     INIT_BOOL(m_dump_linux_proc_stat, "stat", 'S',
664               "Dump linux /proc/<pid>/stat."),
665     INIT_BOOL(m_dump_linux_proc_uptime, "uptime", 'u',
666               "Dump linux process uptime."),
667     INIT_BOOL(m_dump_linux_proc_fd, "fd", 'f',
668               "Dump linux /proc/<pid>/fd."),
669     INIT_BOOL(m_dump_linux_all, "linux", 'l',
670               "Dump all linux streams."),
671     INIT_BOOL(m_fb_app_data, "fb-app-data", 1,
672               "Dump Facebook application custom data."),
673     INIT_BOOL(m_fb_build_id, "fb-build-id", 2,
674               "Dump the Facebook build ID."),
675     INIT_BOOL(m_fb_version, "fb-version", 3,
676               "Dump Facebook application version string."),
677     INIT_BOOL(m_fb_java_stack, "fb-java-stack", 4,
678               "Dump Facebook java stack."),
679     INIT_BOOL(m_fb_dalvik, "fb-dalvik-info", 5,
680               "Dump Facebook Dalvik info."),
681     INIT_BOOL(m_fb_unwind, "fb-unwind-symbols", 6,
682               "Dump Facebook unwind symbols."),
683     INIT_BOOL(m_fb_error_log, "fb-error-log", 7,
684               "Dump Facebook error log."),
685     INIT_BOOL(m_fb_app_state, "fb-app-state-log", 8,
686               "Dump Facebook java stack."),
687     INIT_BOOL(m_fb_abort, "fb-abort-reason", 9,
688               "Dump Facebook abort reason."),
689     INIT_BOOL(m_fb_thread, "fb-thread-name", 10,
690               "Dump Facebook thread name."),
691     INIT_BOOL(m_fb_logcat, "fb-logcat", 11,
692               "Dump Facebook logcat."),
693     INIT_BOOL(m_fb_all, "facebook", 12, "Dump all Facebook streams.") {
694     APPEND_OPT(m_dump_all);
695     APPEND_OPT(m_dump_directory);
696     APPEND_OPT(m_dump_linux_cpuinfo);
697     APPEND_OPT(m_dump_linux_proc_status);
698     APPEND_OPT(m_dump_linux_lsb_release);
699     APPEND_OPT(m_dump_linux_cmdline);
700     APPEND_OPT(m_dump_linux_environ);
701     APPEND_OPT(m_dump_linux_auxv);
702     APPEND_OPT(m_dump_linux_maps);
703     APPEND_OPT(m_dump_linux_proc_stat);
704     APPEND_OPT(m_dump_linux_proc_uptime);
705     APPEND_OPT(m_dump_linux_proc_fd);
706     APPEND_OPT(m_dump_linux_all);
707     APPEND_OPT(m_fb_app_data);
708     APPEND_OPT(m_fb_build_id);
709     APPEND_OPT(m_fb_version);
710     APPEND_OPT(m_fb_java_stack);
711     APPEND_OPT(m_fb_dalvik);
712     APPEND_OPT(m_fb_unwind);
713     APPEND_OPT(m_fb_error_log);
714     APPEND_OPT(m_fb_app_state);
715     APPEND_OPT(m_fb_abort);
716     APPEND_OPT(m_fb_thread);
717     APPEND_OPT(m_fb_logcat);
718     APPEND_OPT(m_fb_all);
719     m_option_group.Finalize();
720   }
721 
722   ~CommandObjectProcessMinidumpDump() override {}
723 
724   Options *GetOptions() override { return &m_option_group; }
725 
726   bool DoExecute(Args &command, CommandReturnObject &result) override {
727     const size_t argc = command.GetArgumentCount();
728     if (argc > 0) {
729       result.AppendErrorWithFormat("'%s' take no arguments, only options",
730                                    m_cmd_name.c_str());
731       result.SetStatus(eReturnStatusFailed);
732       return false;
733     }
734     SetDefaultOptionsIfNoneAreSet();
735 
736     ProcessMinidump *process = static_cast<ProcessMinidump *>(
737         m_interpreter.GetExecutionContext().GetProcessPtr());
738     result.SetStatus(eReturnStatusSuccessFinishResult);
739     Stream &s = result.GetOutputStream();
740     MinidumpParser &minidump = *process->m_minidump_parser;
741     if (DumpDirectory()) {
742       s.Printf("RVA        SIZE       TYPE       StreamType\n");
743       s.Printf("---------- ---------- ---------- --------------------------\n");
744       for (const auto &stream_desc : minidump.GetMinidumpFile().streams())
745         s.Printf(
746             "0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)stream_desc.Location.RVA,
747             (uint32_t)stream_desc.Location.DataSize,
748             (unsigned)(StreamType)stream_desc.Type,
749             MinidumpParser::GetStreamTypeAsString(stream_desc.Type).data());
750       s.Printf("\n");
751     }
752     auto DumpTextStream = [&](StreamType stream_type,
753                               llvm::StringRef label) -> void {
754       auto bytes = minidump.GetStream(stream_type);
755       if (!bytes.empty()) {
756         if (label.empty())
757           label = MinidumpParser::GetStreamTypeAsString(stream_type);
758         s.Printf("%s:\n%s\n\n", label.data(), bytes.data());
759       }
760     };
761     auto DumpBinaryStream = [&](StreamType stream_type,
762                                 llvm::StringRef label) -> void {
763       auto bytes = minidump.GetStream(stream_type);
764       if (!bytes.empty()) {
765         if (label.empty())
766           label = MinidumpParser::GetStreamTypeAsString(stream_type);
767         s.Printf("%s:\n", label.data());
768         DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
769                            process->GetAddressByteSize());
770         DumpDataExtractor(data, &s, 0, lldb::eFormatBytesWithASCII, 1,
771                           bytes.size(), 16, 0, 0, 0);
772         s.Printf("\n\n");
773       }
774     };
775 
776     if (DumpLinuxCPUInfo())
777       DumpTextStream(StreamType::LinuxCPUInfo, "/proc/cpuinfo");
778     if (DumpLinuxProcStatus())
779       DumpTextStream(StreamType::LinuxProcStatus, "/proc/PID/status");
780     if (DumpLinuxLSBRelease())
781       DumpTextStream(StreamType::LinuxLSBRelease, "/etc/lsb-release");
782     if (DumpLinuxCMDLine())
783       DumpTextStream(StreamType::LinuxCMDLine, "/proc/PID/cmdline");
784     if (DumpLinuxEnviron())
785       DumpTextStream(StreamType::LinuxEnviron, "/proc/PID/environ");
786     if (DumpLinuxAuxv())
787       DumpBinaryStream(StreamType::LinuxAuxv, "/proc/PID/auxv");
788     if (DumpLinuxMaps())
789       DumpTextStream(StreamType::LinuxMaps, "/proc/PID/maps");
790     if (DumpLinuxProcStat())
791       DumpTextStream(StreamType::LinuxProcStat, "/proc/PID/stat");
792     if (DumpLinuxProcUptime())
793       DumpTextStream(StreamType::LinuxProcUptime, "uptime");
794     if (DumpLinuxProcFD())
795       DumpTextStream(StreamType::LinuxProcFD, "/proc/PID/fd");
796     if (DumpFacebookAppData())
797       DumpTextStream(StreamType::FacebookAppCustomData,
798                      "Facebook App Data");
799     if (DumpFacebookBuildID()) {
800       auto bytes = minidump.GetStream(StreamType::FacebookBuildID);
801       if (bytes.size() >= 4) {
802         DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
803                            process->GetAddressByteSize());
804         lldb::offset_t offset = 0;
805         uint32_t build_id = data.GetU32(&offset);
806         s.Printf("Facebook Build ID:\n");
807         s.Printf("%u\n", build_id);
808         s.Printf("\n");
809       }
810     }
811     if (DumpFacebookVersionName())
812       DumpTextStream(StreamType::FacebookAppVersionName,
813                      "Facebook Version String");
814     if (DumpFacebookJavaStack())
815       DumpTextStream(StreamType::FacebookJavaStack,
816                      "Facebook Java Stack");
817     if (DumpFacebookDalvikInfo())
818       DumpTextStream(StreamType::FacebookDalvikInfo,
819                      "Facebook Dalvik Info");
820     if (DumpFacebookUnwindSymbols())
821       DumpBinaryStream(StreamType::FacebookUnwindSymbols,
822                        "Facebook Unwind Symbols Bytes");
823     if (DumpFacebookErrorLog())
824       DumpTextStream(StreamType::FacebookDumpErrorLog,
825                      "Facebook Error Log");
826     if (DumpFacebookAppStateLog())
827       DumpTextStream(StreamType::FacebookAppStateLog,
828                      "Faceook Application State Log");
829     if (DumpFacebookAbortReason())
830       DumpTextStream(StreamType::FacebookAbortReason,
831                      "Facebook Abort Reason");
832     if (DumpFacebookThreadName())
833       DumpTextStream(StreamType::FacebookThreadName,
834                      "Facebook Thread Name");
835     if (DumpFacebookLogcat())
836       DumpTextStream(StreamType::FacebookLogcat,
837                      "Facebook Logcat");
838     return true;
839   }
840 };
841 
842 class CommandObjectMultiwordProcessMinidump : public CommandObjectMultiword {
843 public:
844   CommandObjectMultiwordProcessMinidump(CommandInterpreter &interpreter)
845     : CommandObjectMultiword(interpreter, "process plugin",
846           "Commands for operating on a ProcessMinidump process.",
847           "process plugin <subcommand> [<subcommand-options>]") {
848     LoadSubCommand("dump",
849         CommandObjectSP(new CommandObjectProcessMinidumpDump(interpreter)));
850   }
851 
852   ~CommandObjectMultiwordProcessMinidump() override {}
853 };
854 
855 CommandObject *ProcessMinidump::GetPluginCommandObject() {
856   if (!m_command_sp)
857     m_command_sp = std::make_shared<CommandObjectMultiwordProcessMinidump>(
858         GetTarget().GetDebugger().GetCommandInterpreter());
859   return m_command_sp.get();
860 }
861