LLDB mainline
ProcessMinidump.cpp
Go to the documentation of this file.
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
14#include "lldb/Core/Module.h"
17#include "lldb/Core/Section.h"
28#include "lldb/Target/Target.h"
33#include "lldb/Utility/Log.h"
34#include "lldb/Utility/State.h"
35#include "llvm/BinaryFormat/Magic.h"
36#include "llvm/Support/MemoryBuffer.h"
37
41
42#include <memory>
43#include <optional>
44
45using namespace lldb;
46using namespace lldb_private;
47using namespace minidump;
48
50
51namespace {
52
53/// Duplicate the HashElfTextSection() from the breakpad sources.
54///
55/// Breakpad, a Google crash log reporting tool suite, creates minidump files
56/// for many different architectures. When using Breakpad to create ELF
57/// minidumps, it will check for a GNU build ID when creating a minidump file
58/// and if one doesn't exist in the file, it will say the UUID of the file is a
59/// checksum of up to the first 4096 bytes of the .text section. Facebook also
60/// uses breakpad and modified this hash to avoid collisions so we can
61/// calculate and check for this as well.
62///
63/// The breakpad code might end up hashing up to 15 bytes that immediately
64/// follow the .text section in the file, so this code must do exactly what it
65/// does so we can get an exact match for the UUID.
66///
67/// \param[in] module_sp The module to grab the .text section from.
68///
69/// \param[in,out] breakpad_uuid A vector that will receive the calculated
70/// breakpad .text hash.
71///
72/// \param[in,out] facebook_uuid A vector that will receive the calculated
73/// facebook .text hash.
74///
75void HashElfTextSection(ModuleSP module_sp, std::vector<uint8_t> &breakpad_uuid,
76 std::vector<uint8_t> &facebook_uuid) {
77 SectionList *sect_list = module_sp->GetSectionList();
78 if (sect_list == nullptr)
79 return;
80 SectionSP sect_sp = sect_list->FindSectionByName(".text");
81 if (!sect_sp)
82 return;
83 constexpr size_t kMDGUIDSize = 16;
84 constexpr size_t kBreakpadPageSize = 4096;
85 // The breakpad code has a bug where it might access beyond the end of a
86 // .text section by up to 15 bytes, so we must ensure we round up to the
87 // next kMDGUIDSize byte boundary.
88 DataExtractorSP extractor_sp;
89 const size_t text_size = sect_sp->GetFileSize();
90 const size_t read_size = std::min<size_t>(
91 llvm::alignTo(text_size, kMDGUIDSize), kBreakpadPageSize);
92 sect_sp->GetObjectFile()->GetData(sect_sp->GetFileOffset(), read_size,
93 extractor_sp);
94
95 breakpad_uuid.assign(kMDGUIDSize, 0);
96 facebook_uuid.assign(kMDGUIDSize, 0);
97
98 // The only difference between the breakpad hash and the facebook hash is the
99 // hashing of the text section size into the hash prior to hashing the .text
100 // contents.
101 for (size_t i = 0; i < kMDGUIDSize; i++)
102 facebook_uuid[i] ^= text_size % 255;
103
104 // This code carefully duplicates how the hash was created in Breakpad
105 // sources, including the error where it might has an extra 15 bytes past the
106 // end of the .text section if the .text section is less than a page size in
107 // length.
108 const uint8_t *ptr = extractor_sp->GetDataStart();
109 const uint8_t *ptr_end = extractor_sp->GetDataEnd();
110 while (ptr < ptr_end) {
111 for (unsigned i = 0; i < kMDGUIDSize; i++) {
112 breakpad_uuid[i] ^= ptr[i];
113 facebook_uuid[i] ^= ptr[i];
114 }
115 ptr += kMDGUIDSize;
116 }
117}
118
119} // namespace
120
122 return "Minidump plug-in.";
123}
124
126 lldb::ListenerSP listener_sp,
127 const FileSpec *crash_file,
128 bool can_connect) {
129 if (!crash_file || can_connect)
130 return nullptr;
131
132 lldb::ProcessSP process_sp;
133 // Read enough data for the Minidump header
134 constexpr size_t header_size = sizeof(Header);
135 auto DataPtr = FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(),
136 header_size, 0);
137 if (!DataPtr)
138 return nullptr;
139
140 lldbassert(DataPtr->GetByteSize() == header_size);
141 if (identify_magic(toStringRef(DataPtr->GetData())) != llvm::file_magic::minidump)
142 return nullptr;
143
144 auto AllData =
145 FileSystem::Instance().CreateDataBuffer(crash_file->GetPath(), -1, 0);
146 if (!AllData)
147 return nullptr;
148
149 return std::make_shared<ProcessMinidump>(target_sp, listener_sp, *crash_file,
150 std::move(AllData));
151}
152
154 bool plugin_specified_by_name) {
155 return true;
156}
157
159 lldb::ListenerSP listener_sp,
160 const FileSpec &core_file,
161 DataBufferSP core_data)
162 : PostMortemProcess(target_sp, listener_sp, core_file),
163 m_core_data(std::move(core_data)), m_is_wow64(false) {}
164
166 Clear();
167 // We need to call finalize on the process before destroying ourselves to
168 // make sure all of the broadcaster cleanup goes as planned. If we destruct
169 // this class, then Process::~Process() might have problems trying to fully
170 // destroy the broadcaster.
171 Finalize(true /* destructing */);
172}
173
179
183
185 auto expected_parser = MinidumpParser::Create(m_core_data);
186 if (!expected_parser)
187 return Status::FromError(expected_parser.takeError());
188 m_minidump_parser = std::move(*expected_parser);
189
191
192 // Do we support the minidump's architecture?
193 ArchSpec arch = GetArchitecture();
194 switch (arch.GetMachine()) {
195 case llvm::Triple::x86:
196 case llvm::Triple::x86_64:
197 case llvm::Triple::arm:
198 case llvm::Triple::aarch64:
199 // Any supported architectures must be listed here and also supported in
200 // ThreadMinidump::CreateRegisterContextForFrame().
201 break;
202 default:
204 "unsupported minidump architecture: %s", arch.GetArchitectureName());
205 return error;
206 }
207 GetTarget().SetArchitecture(arch, true /*set_platform*/);
208
209 m_thread_list = m_minidump_parser->GetThreads();
210 auto exception_stream_it = m_minidump_parser->GetExceptionStreams();
211 for (auto exception_stream_or_err : exception_stream_it) {
212 // If we can't read an exception stream skip it
213 // We should probably serve a warning
214 if (!exception_stream_or_err) {
216 exception_stream_or_err.takeError(),
217 "failed to read exception stream: {0}");
218 continue;
219 }
220 const llvm::minidump::ExceptionStream &exception_stream =
221 *exception_stream_or_err;
222
224 .try_emplace(exception_stream.ThreadId, exception_stream)
225 .second) {
227 "Duplicate exception stream for tid {0}", exception_stream.ThreadId);
228 }
229 }
230
232
234 if (ModuleSP module = GetTarget().GetExecutableModule())
235 GetTarget().MergeArchitecture(module->GetArchitecture());
236 std::optional<lldb::pid_t> pid = m_minidump_parser->GetPid();
237 if (!pid) {
238 Debugger::ReportWarning("unable to retrieve process ID from minidump file, "
239 "setting process ID to 1",
240 GetTarget().GetDebugger().GetID());
241 pid = 1;
242 }
243 SetID(*pid);
244
245 return error;
246}
247
249
251
252 for (const auto &[_, exception_stream] : m_exceptions_by_tid) {
253 constexpr uint32_t BreakpadDumpRequested = 0xFFFFFFFF;
254 if (exception_stream.ExceptionRecord.ExceptionCode ==
255 BreakpadDumpRequested) {
256 // This "ExceptionCode" value is a sentinel that is sometimes used
257 // when generating a dump for a process that hasn't crashed.
258
259 // TODO: The definition and use of this "dump requested" constant
260 // in Breakpad are actually Linux-specific, and for similar use
261 // cases on Mac/Windows it defines different constants, referring
262 // to them as "simulated" exceptions; consider moving this check
263 // down to the OS-specific paths and checking each OS for its own
264 // constant.
265 return;
266 }
267
268 lldb::StopInfoSP stop_info;
269 lldb::ThreadSP stop_thread;
270
271 Process::m_thread_list.SetSelectedThreadByID(exception_stream.ThreadId);
272 stop_thread = Process::m_thread_list.GetSelectedThread();
273 ArchSpec arch = GetArchitecture();
274
275 if (arch.GetTriple().getOS() == llvm::Triple::Linux) {
276 uint32_t signo = exception_stream.ExceptionRecord.ExceptionCode;
277 if (signo == 0) {
278 // No stop.
279 return;
280 }
281 const char *description = nullptr;
282 if (exception_stream.ExceptionRecord.ExceptionFlags ==
283 llvm::minidump::Exception::LLDB_FLAG)
284 description = reinterpret_cast<const char *>(
285 exception_stream.ExceptionRecord.ExceptionInformation);
286
287 llvm::StringRef description_str(description,
288 Exception::MaxParameterBytes);
290 *stop_thread, signo, description_str.str().c_str());
291 } else if (arch.GetTriple().getVendor() == llvm::Triple::Apple) {
293 *stop_thread, exception_stream.ExceptionRecord.ExceptionCode, 2,
294 exception_stream.ExceptionRecord.ExceptionFlags,
295 exception_stream.ExceptionRecord.ExceptionAddress, 0);
296 } else {
297 std::string desc;
298 llvm::raw_string_ostream desc_stream(desc);
299 desc_stream << "Exception "
300 << llvm::format_hex(
301 exception_stream.ExceptionRecord.ExceptionCode, 8)
302 << " encountered at address "
303 << llvm::format_hex(
304 exception_stream.ExceptionRecord.ExceptionAddress, 8);
305 stop_info =
306 StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
307 }
308
309 stop_thread->SetStopInfo(stop_info);
310 }
311}
312
313bool ProcessMinidump::IsAlive() { return true; }
314
315bool ProcessMinidump::WarnBeforeDetach() const { return false; }
316
318 void *buf, size_t size, Status &error) {
319 lldb::addr_t addr = process_addr.GetValue();
320 // Don't allow the caching that lldb_private::Process::ReadMemory does since
321 // we have it all cached in our dump file anyway.
322 return DoReadMemory(addr, buf, size, error);
323}
324
326 void *buf, size_t size, Status &error) {
327 lldb::addr_t addr = process_addr.GetValue();
328
329 llvm::Expected<llvm::ArrayRef<uint8_t>> mem_maybe =
330 m_minidump_parser->GetMemory(addr, size);
331 if (!mem_maybe) {
332 error = Status::FromError(mem_maybe.takeError());
333 return 0;
334 }
335
336 llvm::ArrayRef<uint8_t> mem = *mem_maybe;
337
338 std::memcpy(buf, mem.data(), mem.size());
339 return mem.size();
340}
341
343 if (!m_is_wow64) {
344 return m_minidump_parser->GetArchitecture();
345 }
346
347 llvm::Triple triple;
348 triple.setVendor(llvm::Triple::VendorType::UnknownVendor);
349 triple.setArch(llvm::Triple::ArchType::x86);
350 triple.setOS(llvm::Triple::OSType::Win32);
351 return ArchSpec(triple);
352}
353
355 std::optional<llvm::ArrayRef<uint8_t>> auxv =
356 m_minidump_parser->GetStream(StreamType::LinuxAuxv);
357 if (!auxv)
358 return DataExtractor();
359
360 return DataExtractor(auxv->data(), auxv->size(), GetByteOrder(),
362}
363
365 std::optional<llvm::ArrayRef<uint8_t>> lldb_generated_section =
366 m_minidump_parser->GetRawStream(StreamType::LLDBGenerated);
367 return lldb_generated_section.has_value();
368}
369
371 // This is a workaround for the dynamic loader not playing nice in issue
372 // #119598. The specific reason we use the dynamic loader is to get the TLS
373 // info sections, which we can assume are not being written to the minidump
374 // unless it's an LLDB generate minidump.
375 if (IsLLDBMinidump())
377 return nullptr;
378}
379
382 return;
383 m_memory_regions.emplace();
384 bool is_complete;
385 std::tie(*m_memory_regions, is_complete) =
386 m_minidump_parser->BuildMemoryRegions();
387
388 if (is_complete)
389 return;
390
391 MemoryRegionInfos to_add;
392 ModuleList &modules = GetTarget().GetImages();
393 Target &target = GetTarget();
394 modules.ForEach([&](const ModuleSP &module_sp) {
395 SectionList *sections = module_sp->GetSectionList();
396 for (size_t i = 0; i < sections->GetSize(); ++i) {
397 SectionSP section_sp = sections->GetSectionAtIndex(i);
398 addr_t load_addr = target.GetSectionLoadAddress(section_sp);
399 if (load_addr == LLDB_INVALID_ADDRESS)
400 continue;
401 MemoryRegionInfo::RangeType section_range(load_addr,
402 section_sp->GetByteSize());
403 MemoryRegionInfo region =
405 if (region.GetMapped() != eLazyBoolYes &&
406 region.GetRange().GetRangeBase() <= section_range.GetRangeBase() &&
407 section_range.GetRangeEnd() <= region.GetRange().GetRangeEnd()) {
408 to_add.emplace_back();
409 to_add.back().GetRange() = section_range;
410 to_add.back().SetLLDBPermissions(section_sp->GetPermissions());
411 to_add.back().SetMapped(eLazyBoolYes);
412 to_add.back().SetName(module_sp->GetFileSpec().GetPath().c_str());
413 }
414 }
416 });
417 m_memory_regions->insert(m_memory_regions->end(), to_add.begin(),
418 to_add.end());
419 llvm::sort(*m_memory_regions);
420}
421
428
431 region_list = *m_memory_regions;
432 return Status();
433}
434
436
438 ThreadList &new_thread_list) {
439 for (const minidump::Thread &thread : m_thread_list) {
440 LocationDescriptor context_location = thread.Context;
441
442 // If the minidump contains an exception context, use it
443 if (auto it = m_exceptions_by_tid.find(thread.ThreadId);
444 it != m_exceptions_by_tid.end())
445 context_location = it->second.ThreadContext;
446
447 llvm::ArrayRef<uint8_t> context;
448 if (!m_is_wow64)
449 context = m_minidump_parser->GetThreadContext(context_location);
450 else
451 context = m_minidump_parser->GetThreadContextWow64(thread);
452
453 lldb::ThreadSP thread_sp(new ThreadMinidump(*this, thread, context));
454 new_thread_list.AddThread(thread_sp);
455 }
456 return new_thread_list.GetSize(false) > 0;
457}
458
460 llvm::StringRef name,
461 ModuleSpec module_spec) {
464
465 ModuleSP module_sp =
466 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
467 if (!module_sp)
468 return module_sp;
469 // We consider the module to be a match if the minidump UUID is a
470 // prefix of the actual UUID, or if either of the UUIDs are empty.
471 const auto dmp_bytes = minidump_uuid.GetBytes();
472 const auto mod_bytes = module_sp->GetUUID().GetBytes();
473 const bool match = dmp_bytes.empty() || mod_bytes.empty() ||
474 mod_bytes.take_front(dmp_bytes.size()) == dmp_bytes;
475 if (match) {
476 LLDB_LOG(log, "Partial uuid match for {0}.", name);
477 return module_sp;
478 }
479
480 // Breakpad generates minindump files, and if there is no GNU build
481 // ID in the binary, it will calculate a UUID by hashing first 4096
482 // bytes of the .text section and using that as the UUID for a module
483 // in the minidump. Facebook uses a modified breakpad client that
484 // uses a slightly modified this hash to avoid collisions. Check for
485 // UUIDs from the minindump that match these cases and accept the
486 // module we find if they do match.
487 std::vector<uint8_t> breakpad_uuid;
488 std::vector<uint8_t> facebook_uuid;
489 HashElfTextSection(module_sp, breakpad_uuid, facebook_uuid);
490 if (dmp_bytes == llvm::ArrayRef<uint8_t>(breakpad_uuid)) {
491 LLDB_LOG(log, "Breakpad .text hash match for {0}.", name);
492 return module_sp;
493 }
494 if (dmp_bytes == llvm::ArrayRef<uint8_t>(facebook_uuid)) {
495 LLDB_LOG(log, "Facebook .text hash match for {0}.", name);
496 return module_sp;
497 }
498 // The UUID wasn't a partial match and didn't match the .text hash
499 // so remove the module from the target, we will need to create a
500 // placeholder object file.
501 GetTarget().GetImages().Remove(module_sp);
502 module_sp.reset();
503 return module_sp;
504}
505
507 std::vector<const minidump::Module *> filtered_modules =
508 m_minidump_parser->GetFilteredModuleList();
509
511
512 for (auto module : filtered_modules) {
513 std::string name = cantFail(m_minidump_parser->GetMinidumpFile().getString(
514 module->ModuleNameRVA));
515 const uint64_t load_addr = module->BaseOfImage;
516 const uint64_t load_size = module->SizeOfImage;
517 LLDB_LOG(log, "found module: name: {0} {1:x10}-{2:x10} size: {3}", name,
518 load_addr, load_addr + load_size, load_size);
519
520 // check if the process is wow64 - a 32 bit windows process running on a
521 // 64 bit windows
522 if (llvm::StringRef(name).ends_with_insensitive("wow64.dll")) {
523 m_is_wow64 = true;
524 }
525
526 const auto uuid = m_minidump_parser->GetModuleUUID(module);
527 auto file_spec = FileSpec(name, GetArchitecture().GetTriple());
528 ModuleSpec module_spec(file_spec, uuid);
529 module_spec.GetArchitecture() = GetArchitecture();
531 // Try and find a module with a full UUID that matches. This function will
532 // add the module to the target if it finds one.
533 lldb::ModuleSP module_sp = GetTarget().GetOrCreateModule(module_spec,
534 true /* notify */, &error);
535 if (module_sp) {
536 LLDB_LOG(log, "Full uuid match for {0}.", name);
537 } else {
538 // We couldn't find a module with an exactly-matching UUID. Sometimes
539 // a minidump UUID is only a partial match or is a hash. So try again
540 // without specifying the UUID, then again without specifying the
541 // directory if that fails. This will allow us to find modules with
542 // partial matches or hash UUIDs in user-provided sysroots or search
543 // directories (target.exec-search-paths).
544 ModuleSpec partial_module_spec = module_spec;
545 partial_module_spec.GetUUID().Clear();
546 module_sp = GetOrCreateModule(uuid, name, partial_module_spec);
547 if (!module_sp) {
548 partial_module_spec.GetFileSpec().ClearDirectory();
549 module_sp = GetOrCreateModule(uuid, name, partial_module_spec);
550 }
551 }
552 if (module_sp) {
553 // Watch out for place holder modules that have different paths, but the
554 // same UUID. If the base address is different, create a new module. If
555 // we don't then we will end up setting the load address of a different
556 // ObjectFilePlaceholder and an assertion will fire.
557 auto *objfile = module_sp->GetObjectFile();
558 if (objfile &&
559 objfile->GetPluginName() ==
561 if (((ObjectFilePlaceholder *)objfile)->GetBaseImageAddress() !=
562 load_addr)
563 module_sp.reset();
564 }
565 }
566 if (!module_sp) {
567 // We failed to locate a matching local object file. Fortunately, the
568 // minidump format encodes enough information about each module's memory
569 // range to allow us to create placeholder modules.
570 //
571 // This enables most LLDB functionality involving address-to-module
572 // translations (ex. identifing the module for a stack frame PC) and
573 // modules/sections commands (ex. target modules list, ...)
574 LLDB_LOG(log,
575 "Unable to locate the matching object file, creating a "
576 "placeholder module for: {0}",
577 name);
578
580 module_spec, load_addr, load_size);
581 // If we haven't loaded a main executable yet, set the first module to be
582 // main executable
583 if (!GetTarget().GetExecutableModule())
584 GetTarget().SetExecutableModule(module_sp);
585 else
586 GetTarget().GetImages().Append(module_sp, true /* notify */);
587 }
588
589 bool load_addr_changed = false;
590 module_sp->SetLoadAddress(GetTarget(), load_addr, false,
591 load_addr_changed);
592 }
593}
594
596 info.Clear();
597 info.SetProcessID(GetID());
600 if (module_sp) {
601 const bool add_exe_file_as_first_arg = false;
602 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
603 add_exe_file_as_first_arg);
604 }
605 return true;
606}
607
608// For minidumps there's no runtime generated code so we don't need JITLoader(s)
609// Avoiding them will also speed up minidump loading since JITLoaders normally
610// try to set up symbolic breakpoints, which in turn may force loading more
611// debug information than needed.
613 if (!m_jit_loaders_up) {
614 m_jit_loaders_up = std::make_unique<JITLoaderList>();
615 }
616 return *m_jit_loaders_up;
617}
618
619#define INIT_BOOL(VAR, LONG, SHORT, DESC) \
620 VAR(LLDB_OPT_SET_1, false, LONG, SHORT, DESC, false, true)
621#define APPEND_OPT(VAR) \
622 m_option_group.Append(&VAR, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1)
623
625private:
652
654 if (m_dump_all.GetOptionValue().GetCurrentValue() ||
655 m_dump_linux_all.GetOptionValue().GetCurrentValue() ||
656 m_fb_all.GetOptionValue().GetCurrentValue() ||
657 m_dump_directory.GetOptionValue().GetCurrentValue() ||
658 m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue() ||
659 m_dump_linux_proc_status.GetOptionValue().GetCurrentValue() ||
660 m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue() ||
661 m_dump_linux_cmdline.GetOptionValue().GetCurrentValue() ||
662 m_dump_linux_environ.GetOptionValue().GetCurrentValue() ||
663 m_dump_linux_auxv.GetOptionValue().GetCurrentValue() ||
664 m_dump_linux_maps.GetOptionValue().GetCurrentValue() ||
665 m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue() ||
666 m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue() ||
667 m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue() ||
668 m_fb_app_data.GetOptionValue().GetCurrentValue() ||
669 m_fb_build_id.GetOptionValue().GetCurrentValue() ||
670 m_fb_version.GetOptionValue().GetCurrentValue() ||
671 m_fb_java_stack.GetOptionValue().GetCurrentValue() ||
672 m_fb_dalvik.GetOptionValue().GetCurrentValue() ||
673 m_fb_unwind.GetOptionValue().GetCurrentValue() ||
674 m_fb_error_log.GetOptionValue().GetCurrentValue() ||
675 m_fb_app_state.GetOptionValue().GetCurrentValue() ||
676 m_fb_abort.GetOptionValue().GetCurrentValue() ||
677 m_fb_thread.GetOptionValue().GetCurrentValue() ||
678 m_fb_logcat.GetOptionValue().GetCurrentValue())
679 return;
680 // If no options were set, then dump everything
681 m_dump_all.GetOptionValue().SetCurrentValue(true);
682 }
683 bool DumpAll() const {
684 return m_dump_all.GetOptionValue().GetCurrentValue();
685 }
686 bool DumpDirectory() const {
687 return DumpAll() ||
688 m_dump_directory.GetOptionValue().GetCurrentValue();
689 }
690 bool DumpLinux() const {
691 return DumpAll() || m_dump_linux_all.GetOptionValue().GetCurrentValue();
692 }
693 bool DumpLinuxCPUInfo() const {
694 return DumpLinux() ||
695 m_dump_linux_cpuinfo.GetOptionValue().GetCurrentValue();
696 }
697 bool DumpLinuxProcStatus() const {
698 return DumpLinux() ||
699 m_dump_linux_proc_status.GetOptionValue().GetCurrentValue();
700 }
701 bool DumpLinuxProcStat() const {
702 return DumpLinux() ||
703 m_dump_linux_proc_stat.GetOptionValue().GetCurrentValue();
704 }
705 bool DumpLinuxLSBRelease() const {
706 return DumpLinux() ||
707 m_dump_linux_lsb_release.GetOptionValue().GetCurrentValue();
708 }
709 bool DumpLinuxCMDLine() const {
710 return DumpLinux() ||
711 m_dump_linux_cmdline.GetOptionValue().GetCurrentValue();
712 }
713 bool DumpLinuxEnviron() const {
714 return DumpLinux() ||
715 m_dump_linux_environ.GetOptionValue().GetCurrentValue();
716 }
717 bool DumpLinuxAuxv() const {
718 return DumpLinux() ||
719 m_dump_linux_auxv.GetOptionValue().GetCurrentValue();
720 }
721 bool DumpLinuxMaps() const {
722 return DumpLinux() ||
723 m_dump_linux_maps.GetOptionValue().GetCurrentValue();
724 }
725 bool DumpLinuxProcUptime() const {
726 return DumpLinux() ||
727 m_dump_linux_proc_uptime.GetOptionValue().GetCurrentValue();
728 }
729 bool DumpLinuxProcFD() const {
730 return DumpLinux() ||
731 m_dump_linux_proc_fd.GetOptionValue().GetCurrentValue();
732 }
733 bool DumpFacebook() const {
734 return DumpAll() || m_fb_all.GetOptionValue().GetCurrentValue();
735 }
736 bool DumpFacebookAppData() const {
737 return DumpFacebook() || m_fb_app_data.GetOptionValue().GetCurrentValue();
738 }
739 bool DumpFacebookBuildID() const {
740 return DumpFacebook() || m_fb_build_id.GetOptionValue().GetCurrentValue();
741 }
743 return DumpFacebook() || m_fb_version.GetOptionValue().GetCurrentValue();
744 }
746 return DumpFacebook() || m_fb_java_stack.GetOptionValue().GetCurrentValue();
747 }
749 return DumpFacebook() || m_fb_dalvik.GetOptionValue().GetCurrentValue();
750 }
752 return DumpFacebook() || m_fb_unwind.GetOptionValue().GetCurrentValue();
753 }
754 bool DumpFacebookErrorLog() const {
755 return DumpFacebook() || m_fb_error_log.GetOptionValue().GetCurrentValue();
756 }
758 return DumpFacebook() || m_fb_app_state.GetOptionValue().GetCurrentValue();
759 }
761 return DumpFacebook() || m_fb_abort.GetOptionValue().GetCurrentValue();
762 }
764 return DumpFacebook() || m_fb_thread.GetOptionValue().GetCurrentValue();
765 }
766 bool DumpFacebookLogcat() const {
767 return DumpFacebook() || m_fb_logcat.GetOptionValue().GetCurrentValue();
768 }
769public:
771 : CommandObjectParsed(interpreter, "process plugin dump",
772 "Dump information from the minidump file.", nullptr),
774 INIT_BOOL(m_dump_all, "all", 'a',
775 "Dump the everything in the minidump."),
776 INIT_BOOL(m_dump_directory, "directory", 'd',
777 "Dump the minidump directory map."),
778 INIT_BOOL(m_dump_linux_cpuinfo, "cpuinfo", 'C',
779 "Dump linux /proc/cpuinfo."),
780 INIT_BOOL(m_dump_linux_proc_status, "status", 's',
781 "Dump linux /proc/<pid>/status."),
782 INIT_BOOL(m_dump_linux_lsb_release, "lsb-release", 'r',
783 "Dump linux /etc/lsb-release."),
784 INIT_BOOL(m_dump_linux_cmdline, "cmdline", 'c',
785 "Dump linux /proc/<pid>/cmdline."),
786 INIT_BOOL(m_dump_linux_environ, "environ", 'e',
787 "Dump linux /proc/<pid>/environ."),
788 INIT_BOOL(m_dump_linux_auxv, "auxv", 'x',
789 "Dump linux /proc/<pid>/auxv."),
790 INIT_BOOL(m_dump_linux_maps, "maps", 'm',
791 "Dump linux /proc/<pid>/maps."),
793 "Dump linux /proc/<pid>/stat."),
794 INIT_BOOL(m_dump_linux_proc_uptime, "uptime", 'u',
795 "Dump linux process uptime."),
797 "Dump linux /proc/<pid>/fd."),
798 INIT_BOOL(m_dump_linux_all, "linux", 'l',
799 "Dump all linux streams."),
800 INIT_BOOL(m_fb_app_data, "fb-app-data", 1,
801 "Dump Facebook application custom data."),
802 INIT_BOOL(m_fb_build_id, "fb-build-id", 2,
803 "Dump the Facebook build ID."),
804 INIT_BOOL(m_fb_version, "fb-version", 3,
805 "Dump Facebook application version string."),
806 INIT_BOOL(m_fb_java_stack, "fb-java-stack", 4,
807 "Dump Facebook java stack."),
808 INIT_BOOL(m_fb_dalvik, "fb-dalvik-info", 5,
809 "Dump Facebook Dalvik info."),
810 INIT_BOOL(m_fb_unwind, "fb-unwind-symbols", 6,
811 "Dump Facebook unwind symbols."),
812 INIT_BOOL(m_fb_error_log, "fb-error-log", 7,
813 "Dump Facebook error log."),
814 INIT_BOOL(m_fb_app_state, "fb-app-state-log", 8,
815 "Dump Facebook java stack."),
816 INIT_BOOL(m_fb_abort, "fb-abort-reason", 9,
817 "Dump Facebook abort reason."),
818 INIT_BOOL(m_fb_thread, "fb-thread-name", 10,
819 "Dump Facebook thread name."),
820 INIT_BOOL(m_fb_logcat, "fb-logcat", 11,
821 "Dump Facebook logcat."),
822 INIT_BOOL(m_fb_all, "facebook", 12, "Dump all Facebook streams.") {
848 m_option_group.Finalize();
849 }
850
852
853 Options *GetOptions() override { return &m_option_group; }
854
855 void DoExecute(Args &command, CommandReturnObject &result) override {
856 const size_t argc = command.GetArgumentCount();
857 if (argc > 0) {
858 result.AppendErrorWithFormat("'%s' take no arguments, only options",
859 m_cmd_name.c_str());
860 return;
861 }
863
864 ProcessMinidump *process = static_cast<ProcessMinidump *>(
865 m_interpreter.GetExecutionContext().GetProcessPtr());
867 Stream &s = result.GetOutputStream();
869 if (DumpDirectory()) {
870 s.Printf("RVA SIZE TYPE StreamType\n");
871 s.Printf("---------- ---------- ---------- --------------------------\n");
872 for (const auto &stream_desc : minidump.GetMinidumpFile().streams())
873 s.Printf(
874 "0x%8.8x 0x%8.8x 0x%8.8x %s\n", (uint32_t)stream_desc.Location.RVA,
875 (uint32_t)stream_desc.Location.DataSize,
876 (unsigned)(StreamType)stream_desc.Type,
877 MinidumpParser::GetStreamTypeAsString(stream_desc.Type).data());
878 s.Printf("\n");
879 }
880 auto DumpTextStream = [&](StreamType stream_type,
881 llvm::StringRef label) -> void {
882 auto bytes = minidump.GetStream(stream_type);
883 if (!bytes.empty()) {
884 if (label.empty())
885 label = MinidumpParser::GetStreamTypeAsString(stream_type);
886 s.Printf("%s:\n%s\n\n", label.data(), bytes.data());
887 }
888 };
889 auto DumpBinaryStream = [&](StreamType stream_type,
890 llvm::StringRef label) -> void {
891 auto bytes = minidump.GetStream(stream_type);
892 if (!bytes.empty()) {
893 if (label.empty())
894 label = MinidumpParser::GetStreamTypeAsString(stream_type);
895 s.Printf("%s:\n", label.data());
896 DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
897 process->GetAddressByteSize());
899 bytes.size(), 16, 0, 0, 0);
900 s.Printf("\n\n");
901 }
902 };
903
904 if (DumpLinuxCPUInfo())
905 DumpTextStream(StreamType::LinuxCPUInfo, "/proc/cpuinfo");
907 DumpTextStream(StreamType::LinuxProcStatus, "/proc/PID/status");
909 DumpTextStream(StreamType::LinuxLSBRelease, "/etc/lsb-release");
910 if (DumpLinuxCMDLine())
911 DumpTextStream(StreamType::LinuxCMDLine, "/proc/PID/cmdline");
912 if (DumpLinuxEnviron())
913 DumpTextStream(StreamType::LinuxEnviron, "/proc/PID/environ");
914 if (DumpLinuxAuxv())
915 DumpBinaryStream(StreamType::LinuxAuxv, "/proc/PID/auxv");
916 if (DumpLinuxMaps())
917 DumpTextStream(StreamType::LinuxMaps, "/proc/PID/maps");
918 if (DumpLinuxProcStat())
919 DumpTextStream(StreamType::LinuxProcStat, "/proc/PID/stat");
921 DumpTextStream(StreamType::LinuxProcUptime, "uptime");
922 if (DumpLinuxProcFD())
923 DumpTextStream(StreamType::LinuxProcFD, "/proc/PID/fd");
925 DumpTextStream(StreamType::FacebookAppCustomData,
926 "Facebook App Data");
927 if (DumpFacebookBuildID()) {
928 auto bytes = minidump.GetStream(StreamType::FacebookBuildID);
929 if (bytes.size() >= 4) {
930 DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
931 process->GetAddressByteSize());
932 lldb::offset_t offset = 0;
933 uint32_t build_id = data.GetU32(&offset);
934 s.Printf("Facebook Build ID:\n");
935 s.Printf("%u\n", build_id);
936 s.Printf("\n");
937 }
938 }
940 DumpTextStream(StreamType::FacebookAppVersionName,
941 "Facebook Version String");
943 DumpTextStream(StreamType::FacebookJavaStack,
944 "Facebook Java Stack");
946 DumpTextStream(StreamType::FacebookDalvikInfo,
947 "Facebook Dalvik Info");
949 DumpBinaryStream(StreamType::FacebookUnwindSymbols,
950 "Facebook Unwind Symbols Bytes");
952 DumpTextStream(StreamType::FacebookDumpErrorLog,
953 "Facebook Error Log");
955 DumpTextStream(StreamType::FacebookAppStateLog,
956 "Faceook Application State Log");
958 DumpTextStream(StreamType::FacebookAbortReason,
959 "Facebook Abort Reason");
961 DumpTextStream(StreamType::FacebookThreadName,
962 "Facebook Thread Name");
963 if (DumpFacebookLogcat())
964 DumpTextStream(StreamType::FacebookLogcat, "Facebook Logcat");
965 }
966};
967
969public:
971 : CommandObjectMultiword(interpreter, "process plugin",
972 "Commands for operating on a ProcessMinidump process.",
973 "process plugin <subcommand> [<subcommand-options>]") {
974 LoadSubCommand("dump",
976 }
977
979};
980
982 if (!m_command_sp)
983 m_command_sp = std::make_shared<CommandObjectMultiwordProcessMinidump>(
984 GetTarget().GetDebugger().GetCommandInterpreter());
985 return m_command_sp.get();
986}
static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_PLUGIN_DEFINE(PluginName)
#define INIT_BOOL(VAR, LONG, SHORT, DESC)
#define APPEND_OPT(VAR)
CommandObjectMultiwordProcessMinidump(CommandInterpreter &interpreter)
~CommandObjectMultiwordProcessMinidump() override=default
OptionGroupBoolean m_dump_linux_lsb_release
OptionGroupBoolean m_dump_linux_proc_uptime
OptionGroupBoolean m_dump_linux_proc_status
CommandObjectProcessMinidumpDump(CommandInterpreter &interpreter)
~CommandObjectProcessMinidumpDump() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
A minimal ObjectFile implementation providing a dummy object file for the cases when the real module ...
static llvm::StringRef GetPluginNameStatic()
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:881
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:740
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandInterpreter & m_interpreter
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
An data extractor class.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
A file utility class.
Definition FileSpec.h:56
void ClearDirectory()
Clear the directory in this object.
Definition FileSpec.cpp:373
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
Class used by the Process to hold a list of its JITLoaders.
Range< lldb::addr_t, lldb::addr_t > RangeType
A collection class for Module objects.
Definition ModuleList.h:125
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
void ForEach(std::function< IterationAction(const lldb::ModuleSP &module_sp)> const &callback) const
Applies 'callback' to each module in this ModuleList.
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
static lldb::ModuleSP CreateModuleFromObjectFile(Args &&...args)
Definition Module.h:136
A command line option parsing protocol class.
Definition Options.h:58
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
PostMortemProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
void SetArchitecture(const ArchSpec &arch)
Definition ProcessInfo.h:64
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:68
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:544
lldb::JITLoaderListUP m_jit_loaders_up
Definition Process.h:3537
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3918
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3928
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:549
friend class Target
Definition Process.h:366
uint32_t GetAddressByteSize() const
Definition Process.cpp:3932
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3109
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:564
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3509
friend class DynamicLoader
Definition Process.h:363
friend class ThreadList
Definition Process.h:367
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1259
size_t GetSize() const
Definition Section.h:77
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
static lldb::StopInfoSP CreateStopReasonWithMachException(Thread &thread, uint32_t exc_type, uint32_t exc_data_count, uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code, bool pc_already_adjusted=true, bool adjust_pc_if_needed=false)
static lldb::StopInfoSP CreateStopReasonWithSignal(Thread &thread, int signo, const char *description=nullptr, std::optional< int > code=std::nullopt)
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp)
Definition Target.cpp:6048
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2450
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1787
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1625
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1254
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1658
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition Target.cpp:1878
void AddThread(const lldb::ThreadSP &thread_sp)
uint32_t GetSize(bool can_update=true)
Represents UUID's of various sizes.
Definition UUID.h:27
llvm::ArrayRef< uint8_t > GetBytes() const
Definition UUID.h:66
void Clear()
Definition UUID.h:62
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
static MemoryRegionInfo GetMemoryRegionInfo(const MemoryRegionInfos &regions, lldb::addr_t load_addr)
static llvm::Expected< MinidumpParser > Create(const lldb::DataBufferSP &data_buf_sp)
static llvm::StringRef GetStreamTypeAsString(StreamType stream_type)
bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
bool GetProcessInfo(ProcessInstanceInfo &info) override
static llvm::StringRef GetPluginNameStatic()
ProcessMinidump(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file, lldb::DataBufferSP code_data)
bool IsAlive() override
Check if a process is still alive.
lldb::ModuleSP GetOrCreateModule(lldb_private::UUID minidump_uuid, llvm::StringRef name, lldb_private::ModuleSpec module_spec)
CommandObject * GetPluginCommandObject() override
Return a multi-word command object that can be used to expose plug-in specific commands.
Status GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) override
Obtain all the mapped memory regions within this process.
size_t DoReadMemory(const ProcessAddress &addr, void *buf, size_t size, Status &error) override
Actually do the reading of memory from a process.
std::optional< MemoryRegionInfos > m_memory_regions
static llvm::StringRef GetPluginDescriptionStatic()
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
bool WarnBeforeDetach() const override
Before lldb detaches from a process, it warns the user that they are about to lose their debug sessio...
llvm::ArrayRef< minidump::Thread > m_thread_list
lldb_private::DataExtractor GetAuxvData() override
std::unordered_map< uint32_t, const minidump::ExceptionStream > m_exceptions_by_tid
DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
Status DoGetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) override
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
std::optional< MinidumpParser > m_minidump_parser
size_t ReadMemory(const ProcessAddress &addr, void *buf, size_t size, Status &error) override
Read of memory from a process.
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
lldb::offset_t DumpDataExtractor(const DataExtractor &DE, Stream *s, lldb::offset_t offset, lldb::Format item_format, size_t item_byte_size, size_t item_count, size_t num_per_line, uint64_t base_addr, uint32_t item_bit_size, uint32_t item_bit_offset, ExecutionContextScope *exe_scope=nullptr, bool show_memory_tags=false)
Dumps item_count objects into the stream s.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
@ eFormatBytesWithASCII
uint64_t offset_t
Definition lldb-types.h:86
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusSuccessFinishResult
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
BaseType GetRangeBase() const
Definition RangeMap.h:45
BaseType GetRangeEnd() const
Definition RangeMap.h:78