1 //===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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/Target/DynamicLoader.h"
19 #include "lldb/Target/MemoryRegionInfo.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/UnixSignals.h"
22 #include "lldb/Utility/DataBufferHeap.h"
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/State.h"
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/Support/Threading.h"
29 #include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
30 #include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
31 #include "Plugins/Process/elf-core/RegisterUtilities.h"
32 #include "ProcessElfCore.h"
33 #include "ThreadElfCore.h"
35 using namespace lldb_private;
36 namespace ELF = llvm::ELF;
38 ConstString ProcessElfCore::GetPluginNameStatic() {
39 static ConstString g_name("elf-core");
43 const char *ProcessElfCore::GetPluginDescriptionStatic() {
44 return "ELF core dump plug-in.";
47 void ProcessElfCore::Terminate() {
48 PluginManager::UnregisterPlugin(ProcessElfCore::CreateInstance);
51 lldb::ProcessSP ProcessElfCore::CreateInstance(lldb::TargetSP target_sp,
52 lldb::ListenerSP listener_sp,
53 const FileSpec *crash_file) {
54 lldb::ProcessSP process_sp;
56 // Read enough data for a ELF32 header or ELF64 header Note: Here we care
57 // about e_type field only, so it is safe to ignore possible presence of
58 // the header extension.
59 const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr);
61 auto data_sp = FileSystem::Instance().CreateDataBuffer(
62 crash_file->GetPath(), header_size, 0);
63 if (data_sp && data_sp->GetByteSize() == header_size &&
64 elf::ELFHeader::MagicBytesMatch(data_sp->GetBytes())) {
65 elf::ELFHeader elf_header;
66 DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
67 lldb::offset_t data_offset = 0;
68 if (elf_header.Parse(data, &data_offset)) {
69 if (elf_header.e_type == llvm::ELF::ET_CORE)
70 process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp,
78 bool ProcessElfCore::CanDebug(lldb::TargetSP target_sp,
79 bool plugin_specified_by_name) {
80 // For now we are just making sure the file exists for a given module
81 if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) {
82 ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture());
83 Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp,
84 nullptr, nullptr, nullptr));
85 if (m_core_module_sp) {
86 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
87 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
94 // ProcessElfCore constructor
95 ProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp,
96 lldb::ListenerSP listener_sp,
97 const FileSpec &core_file)
98 : Process(target_sp, listener_sp), m_core_file(core_file) {}
101 ProcessElfCore::~ProcessElfCore() {
103 // We need to call finalize on the process before destroying ourselves to
104 // make sure all of the broadcaster cleanup goes as planned. If we destruct
105 // this class, then Process::~Process() might have problems trying to fully
106 // destroy the broadcaster.
111 ConstString ProcessElfCore::GetPluginName() { return GetPluginNameStatic(); }
113 uint32_t ProcessElfCore::GetPluginVersion() { return 1; }
115 lldb::addr_t ProcessElfCore::AddAddressRangeFromLoadSegment(
116 const elf::ELFProgramHeader &header) {
117 const lldb::addr_t addr = header.p_vaddr;
118 FileRange file_range(header.p_offset, header.p_filesz);
119 VMRangeToFileOffset::Entry range_entry(addr, header.p_memsz, file_range);
121 // Only add to m_core_aranges if the file size is non zero. Some core files
122 // have PT_LOAD segments for all address ranges, but set f_filesz to zero for
123 // the .text sections since they can be retrieved from the object files.
124 if (header.p_filesz > 0) {
125 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
126 if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
127 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
128 last_entry->GetByteSize() == last_entry->data.GetByteSize()) {
129 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
130 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
132 m_core_aranges.Append(range_entry);
135 // Keep a separate map of permissions that that isn't coalesced so all ranges
137 const uint32_t permissions =
138 ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) |
139 ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) |
140 ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u);
142 m_core_range_infos.Append(
143 VMRangeToPermissions::Entry(addr, header.p_memsz, permissions));
149 Status ProcessElfCore::DoLoadCore() {
151 if (!m_core_module_sp) {
152 error.SetErrorString("invalid core module");
156 ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
157 if (core == nullptr) {
158 error.SetErrorString("invalid core object file");
162 llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders();
163 if (segments.size() == 0) {
164 error.SetErrorString("core file has no segments");
170 m_thread_data_valid = true;
172 bool ranges_are_sorted = true;
173 lldb::addr_t vm_addr = 0;
174 /// Walk through segments and Thread and Address Map information.
175 /// PT_NOTE - Contains Thread and Register information
176 /// PT_LOAD - Contains a contiguous range of Process Address Space
177 for (const elf::ELFProgramHeader &H : segments) {
178 DataExtractor data = core->GetSegmentData(H);
180 // Parse thread contexts and auxv structure
181 if (H.p_type == llvm::ELF::PT_NOTE) {
182 if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data))
183 return Status(std::move(error));
185 // PT_LOAD segments contains address map
186 if (H.p_type == llvm::ELF::PT_LOAD) {
187 lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(H);
188 if (vm_addr > last_addr)
189 ranges_are_sorted = false;
194 if (!ranges_are_sorted) {
195 m_core_aranges.Sort();
196 m_core_range_infos.Sort();
199 // Even if the architecture is set in the target, we need to override it to
200 // match the core file which is always single arch.
201 ArchSpec arch(m_core_module_sp->GetArchitecture());
203 ArchSpec target_arch = GetTarget().GetArchitecture();
204 ArchSpec core_arch(m_core_module_sp->GetArchitecture());
205 target_arch.MergeFrom(core_arch);
206 GetTarget().SetArchitecture(target_arch);
208 SetUnixSignals(UnixSignals::Create(GetArchitecture()));
210 // Ensure we found at least one thread that was stopped on a signal.
211 bool siginfo_signal_found = false;
212 bool prstatus_signal_found = false;
213 // Check we found a signal in a SIGINFO note.
214 for (const auto &thread_data : m_thread_data) {
215 if (thread_data.signo != 0)
216 siginfo_signal_found = true;
217 if (thread_data.prstatus_sig != 0)
218 prstatus_signal_found = true;
220 if (!siginfo_signal_found) {
221 // If we don't have signal from SIGINFO use the signal from each threads
223 if (prstatus_signal_found) {
224 for (auto &thread_data : m_thread_data)
225 thread_data.signo = thread_data.prstatus_sig;
226 } else if (m_thread_data.size() > 0) {
227 // If all else fails force the first thread to be SIGSTOP
228 m_thread_data.begin()->signo =
229 GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
233 // Core files are useless without the main executable. See if we can locate
234 // the main executable using data we found in the core file notes.
235 lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
236 if (!exe_module_sp) {
237 // The first entry in the NT_FILE might be our executable
238 if (!m_nt_file_entries.empty()) {
239 ModuleSpec exe_module_spec;
240 exe_module_spec.GetArchitecture() = arch;
241 exe_module_spec.GetFileSpec().SetFile(
242 m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native);
243 if (exe_module_spec.GetFileSpec()) {
244 exe_module_sp = GetTarget().GetOrCreateModule(exe_module_spec,
247 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo);
254 lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() {
255 if (m_dyld_up.get() == nullptr)
256 m_dyld_up.reset(DynamicLoader::FindPlugin(
257 this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString()));
258 return m_dyld_up.get();
261 bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list,
262 ThreadList &new_thread_list) {
263 const uint32_t num_threads = GetNumThreadContexts();
264 if (!m_thread_data_valid)
267 for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
268 const ThreadData &td = m_thread_data[tid];
269 lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
270 new_thread_list.AddThread(thread_sp);
272 return new_thread_list.GetSize(false) > 0;
275 void ProcessElfCore::RefreshStateAfterStop() {}
277 Status ProcessElfCore::DoDestroy() { return Status(); }
281 bool ProcessElfCore::IsAlive() { return true; }
284 size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
286 // Don't allow the caching that lldb_private::Process::ReadMemory does since
287 // in core files we have it all cached our our core file anyway.
288 return DoReadMemory(addr, buf, size, error);
291 Status ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr,
292 MemoryRegionInfo ®ion_info) {
294 const VMRangeToPermissions::Entry *permission_entry =
295 m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
296 if (permission_entry) {
297 if (permission_entry->Contains(load_addr)) {
298 region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
299 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
300 const Flags permissions(permission_entry->data);
301 region_info.SetReadable(permissions.Test(lldb::ePermissionsReadable)
302 ? MemoryRegionInfo::eYes
303 : MemoryRegionInfo::eNo);
304 region_info.SetWritable(permissions.Test(lldb::ePermissionsWritable)
305 ? MemoryRegionInfo::eYes
306 : MemoryRegionInfo::eNo);
307 region_info.SetExecutable(permissions.Test(lldb::ePermissionsExecutable)
308 ? MemoryRegionInfo::eYes
309 : MemoryRegionInfo::eNo);
310 region_info.SetMapped(MemoryRegionInfo::eYes);
311 } else if (load_addr < permission_entry->GetRangeBase()) {
312 region_info.GetRange().SetRangeBase(load_addr);
313 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
314 region_info.SetReadable(MemoryRegionInfo::eNo);
315 region_info.SetWritable(MemoryRegionInfo::eNo);
316 region_info.SetExecutable(MemoryRegionInfo::eNo);
317 region_info.SetMapped(MemoryRegionInfo::eNo);
322 region_info.GetRange().SetRangeBase(load_addr);
323 region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
324 region_info.SetReadable(MemoryRegionInfo::eNo);
325 region_info.SetWritable(MemoryRegionInfo::eNo);
326 region_info.SetExecutable(MemoryRegionInfo::eNo);
327 region_info.SetMapped(MemoryRegionInfo::eNo);
331 size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
333 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
335 if (core_objfile == nullptr)
338 // Get the address range
339 const VMRangeToFileOffset::Entry *address_range =
340 m_core_aranges.FindEntryThatContains(addr);
341 if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
342 error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64,
347 // Convert the address into core file offset
348 const lldb::addr_t offset = addr - address_range->GetRangeBase();
349 const lldb::addr_t file_start = address_range->data.GetRangeBase();
350 const lldb::addr_t file_end = address_range->data.GetRangeEnd();
351 size_t bytes_to_read = size; // Number of bytes to read from the core file
352 size_t bytes_copied = 0; // Number of bytes actually read from the core file
353 size_t zero_fill_size = 0; // Padding
354 lldb::addr_t bytes_left =
355 0; // Number of bytes available in the core file from the given address
357 // Don't proceed if core file doesn't contain the actual data for this
359 if (file_start == file_end)
362 // Figure out how many on-disk bytes remain in this segment starting at the
364 if (file_end > file_start + offset)
365 bytes_left = file_end - (file_start + offset);
367 // Figure out how many bytes we need to zero-fill if we are reading more
368 // bytes than available in the on-disk segment
369 if (bytes_to_read > bytes_left) {
370 zero_fill_size = bytes_to_read - bytes_left;
371 bytes_to_read = bytes_left;
374 // If there is data available on the core file read it
377 core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
379 assert(zero_fill_size <= size);
380 // Pad remaining bytes
382 memset(((char *)buf) + bytes_copied, 0, zero_fill_size);
384 return bytes_copied + zero_fill_size;
387 void ProcessElfCore::Clear() {
388 m_thread_list.Clear();
390 SetUnixSignals(std::make_shared<UnixSignals>());
393 void ProcessElfCore::Initialize() {
394 static llvm::once_flag g_once_flag;
396 llvm::call_once(g_once_flag, []() {
397 PluginManager::RegisterPlugin(GetPluginNameStatic(),
398 GetPluginDescriptionStatic(), CreateInstance);
402 lldb::addr_t ProcessElfCore::GetImageInfoAddress() {
403 ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
404 Address addr = obj_file->GetImageInfoAddress(&GetTarget());
407 return addr.GetLoadAddress(&GetTarget());
408 return LLDB_INVALID_ADDRESS;
411 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
412 static void ParseFreeBSDPrStatus(ThreadData &thread_data,
413 const DataExtractor &data,
414 const ArchSpec &arch) {
415 lldb::offset_t offset = 0;
416 bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
417 arch.GetMachine() == llvm::Triple::mips64 ||
418 arch.GetMachine() == llvm::Triple::ppc64 ||
419 arch.GetMachine() == llvm::Triple::x86_64);
420 int pr_version = data.GetU32(&offset);
422 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
425 LLDB_LOGF(log, "FreeBSD PRSTATUS unexpected version %d", pr_version);
428 // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
434 thread_data.signo = data.GetU32(&offset); // pr_cursig
435 thread_data.tid = data.GetU32(&offset); // pr_pid
439 size_t len = data.GetByteSize() - offset;
440 thread_data.gpregset = DataExtractor(data, offset, len);
443 static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
446 uint32_t &cpi_siglwp,
448 lldb::offset_t offset = 0;
450 uint32_t version = data.GetU32(&offset);
452 return llvm::make_error<llvm::StringError>(
453 "Error parsing NetBSD core(5) notes: Unsupported procinfo version",
454 llvm::inconvertibleErrorCode());
456 uint32_t cpisize = data.GetU32(&offset);
457 if (cpisize != NETBSD::NT_PROCINFO_SIZE)
458 return llvm::make_error<llvm::StringError>(
459 "Error parsing NetBSD core(5) notes: Unsupported procinfo size",
460 llvm::inconvertibleErrorCode());
462 cpi_signo = data.GetU32(&offset); /* killing signal */
464 offset += NETBSD::NT_PROCINFO_CPI_SIGCODE_SIZE;
465 offset += NETBSD::NT_PROCINFO_CPI_SIGPEND_SIZE;
466 offset += NETBSD::NT_PROCINFO_CPI_SIGMASK_SIZE;
467 offset += NETBSD::NT_PROCINFO_CPI_SIGIGNORE_SIZE;
468 offset += NETBSD::NT_PROCINFO_CPI_SIGCATCH_SIZE;
469 cpi_pid = data.GetU32(&offset);
470 offset += NETBSD::NT_PROCINFO_CPI_PPID_SIZE;
471 offset += NETBSD::NT_PROCINFO_CPI_PGRP_SIZE;
472 offset += NETBSD::NT_PROCINFO_CPI_SID_SIZE;
473 offset += NETBSD::NT_PROCINFO_CPI_RUID_SIZE;
474 offset += NETBSD::NT_PROCINFO_CPI_EUID_SIZE;
475 offset += NETBSD::NT_PROCINFO_CPI_SVUID_SIZE;
476 offset += NETBSD::NT_PROCINFO_CPI_RGID_SIZE;
477 offset += NETBSD::NT_PROCINFO_CPI_EGID_SIZE;
478 offset += NETBSD::NT_PROCINFO_CPI_SVGID_SIZE;
479 cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
481 offset += NETBSD::NT_PROCINFO_CPI_NAME_SIZE;
482 cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
484 return llvm::Error::success();
487 static void ParseOpenBSDProcInfo(ThreadData &thread_data,
488 const DataExtractor &data) {
489 lldb::offset_t offset = 0;
491 int version = data.GetU32(&offset);
496 thread_data.signo = data.GetU32(&offset);
499 llvm::Expected<std::vector<CoreNote>>
500 ProcessElfCore::parseSegment(const DataExtractor &segment) {
501 lldb::offset_t offset = 0;
502 std::vector<CoreNote> result;
504 while (offset < segment.GetByteSize()) {
505 ELFNote note = ELFNote();
506 if (!note.Parse(segment, &offset))
507 return llvm::make_error<llvm::StringError>(
508 "Unable to parse note segment", llvm::inconvertibleErrorCode());
510 size_t note_start = offset;
511 size_t note_size = llvm::alignTo(note.n_descsz, 4);
512 DataExtractor note_data(segment, note_start, note_size);
514 result.push_back({note, note_data});
518 return std::move(result);
521 llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
522 bool have_prstatus = false;
523 bool have_prpsinfo = false;
524 ThreadData thread_data;
525 for (const auto ¬e : notes) {
526 if (note.info.n_name != "FreeBSD")
529 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
530 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
531 assert(thread_data.gpregset.GetByteSize() > 0);
532 // Add the new thread to thread list
533 m_thread_data.push_back(thread_data);
534 thread_data = ThreadData();
535 have_prstatus = false;
536 have_prpsinfo = false;
539 switch (note.info.n_type) {
540 case ELF::NT_PRSTATUS:
541 have_prstatus = true;
542 ParseFreeBSDPrStatus(thread_data, note.data, GetArchitecture());
544 case ELF::NT_PRPSINFO:
545 have_prpsinfo = true;
547 case ELF::NT_FREEBSD_THRMISC: {
548 lldb::offset_t offset = 0;
549 thread_data.name = note.data.GetCStr(&offset, 20);
552 case ELF::NT_FREEBSD_PROCSTAT_AUXV:
553 // FIXME: FreeBSD sticks an int at the beginning of the note
554 m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
557 thread_data.notes.push_back(note);
561 if (!have_prstatus) {
562 return llvm::make_error<llvm::StringError>(
563 "Could not find NT_PRSTATUS note in core file.",
564 llvm::inconvertibleErrorCode());
566 m_thread_data.push_back(thread_data);
567 return llvm::Error::success();
570 /// NetBSD specific Thread context from PT_NOTE segment
572 /// NetBSD ELF core files use notes to provide information about
573 /// the process's state. The note name is "NetBSD-CORE" for
574 /// information that is global to the process, and "NetBSD-CORE@nn",
575 /// where "nn" is the lwpid of the LWP that the information belongs
576 /// to (such as register state).
578 /// NetBSD uses the following note identifiers:
580 /// ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
581 /// Note is a "netbsd_elfcore_procinfo" structure.
582 /// ELF_NOTE_NETBSD_CORE_AUXV (value 2; since NetBSD 8.0)
583 /// Note is an array of AuxInfo structures.
585 /// NetBSD also uses ptrace(2) request numbers (the ones that exist in
586 /// machine-dependent space) to identify register info notes. The
587 /// info in such notes is in the same format that ptrace(2) would
588 /// export that information.
590 /// For more information see /usr/include/sys/exec_elf.h
592 llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
593 ThreadData thread_data;
594 bool had_nt_regs = false;
596 // To be extracted from struct netbsd_elfcore_procinfo
597 // Used to sanity check of the LWPs of the process
599 uint32_t signo; // killing signal
600 uint32_t siglwp; // LWP target of killing signal
603 for (const auto ¬e : notes) {
604 llvm::StringRef name = note.info.n_name;
606 if (name == "NetBSD-CORE") {
607 if (note.info.n_type == NETBSD::NT_PROCINFO) {
608 llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
613 } else if (note.info.n_type == NETBSD::NT_AUXV) {
616 } else if (name.consume_front("NetBSD-CORE@")) {
618 if (name.getAsInteger(10, tid))
619 return llvm::make_error<llvm::StringError>(
620 "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
622 llvm::inconvertibleErrorCode());
624 switch (GetArchitecture().GetMachine()) {
625 case llvm::Triple::aarch64: {
626 // Assume order PT_GETREGS, PT_GETFPREGS
627 if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
628 // If this is the next thread, push the previous one first.
630 m_thread_data.push_back(thread_data);
631 thread_data = ThreadData();
635 thread_data.gpregset = note.data;
636 thread_data.tid = tid;
637 if (thread_data.gpregset.GetByteSize() == 0)
638 return llvm::make_error<llvm::StringError>(
639 "Could not find general purpose registers note in core file.",
640 llvm::inconvertibleErrorCode());
642 } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
643 if (!had_nt_regs || tid != thread_data.tid)
644 return llvm::make_error<llvm::StringError>(
645 "Error parsing NetBSD core(5) notes: Unexpected order "
646 "of NOTEs PT_GETFPREG before PT_GETREG",
647 llvm::inconvertibleErrorCode());
648 thread_data.notes.push_back(note);
651 case llvm::Triple::x86_64: {
652 // Assume order PT_GETREGS, PT_GETFPREGS
653 if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
654 // If this is the next thread, push the previous one first.
656 m_thread_data.push_back(thread_data);
657 thread_data = ThreadData();
661 thread_data.gpregset = note.data;
662 thread_data.tid = tid;
663 if (thread_data.gpregset.GetByteSize() == 0)
664 return llvm::make_error<llvm::StringError>(
665 "Could not find general purpose registers note in core file.",
666 llvm::inconvertibleErrorCode());
668 } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
669 if (!had_nt_regs || tid != thread_data.tid)
670 return llvm::make_error<llvm::StringError>(
671 "Error parsing NetBSD core(5) notes: Unexpected order "
672 "of NOTEs PT_GETFPREG before PT_GETREG",
673 llvm::inconvertibleErrorCode());
674 thread_data.notes.push_back(note);
683 // Push the last thread.
685 m_thread_data.push_back(thread_data);
687 if (m_thread_data.empty())
688 return llvm::make_error<llvm::StringError>(
689 "Error parsing NetBSD core(5) notes: No threads information "
690 "specified in notes",
691 llvm::inconvertibleErrorCode());
693 if (m_thread_data.size() != nlwps)
694 return llvm::make_error<llvm::StringError>(
695 "Error parsing NetBSD core(5) notes: Mismatch between the number "
696 "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
698 llvm::inconvertibleErrorCode());
700 // Signal targeted at the whole process.
702 for (auto &data : m_thread_data)
705 // Signal destined for a particular LWP.
709 for (auto &data : m_thread_data) {
710 if (data.tid == siglwp) {
718 return llvm::make_error<llvm::StringError>(
719 "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP",
720 llvm::inconvertibleErrorCode());
723 return llvm::Error::success();
726 llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
727 ThreadData thread_data;
728 for (const auto ¬e : notes) {
729 // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
730 // match on the initial part of the string.
731 if (!llvm::StringRef(note.info.n_name).startswith("OpenBSD"))
734 switch (note.info.n_type) {
735 case OPENBSD::NT_PROCINFO:
736 ParseOpenBSDProcInfo(thread_data, note.data);
738 case OPENBSD::NT_AUXV:
741 case OPENBSD::NT_REGS:
742 thread_data.gpregset = note.data;
745 thread_data.notes.push_back(note);
749 if (thread_data.gpregset.GetByteSize() == 0) {
750 return llvm::make_error<llvm::StringError>(
751 "Could not find general purpose registers note in core file.",
752 llvm::inconvertibleErrorCode());
754 m_thread_data.push_back(thread_data);
755 return llvm::Error::success();
758 /// A description of a linux process usually contains the following NOTE
760 /// - NT_PRPSINFO - General process information like pid, uid, name, ...
761 /// - NT_SIGINFO - Information about the signal that terminated the process
762 /// - NT_AUXV - Process auxiliary vector
763 /// - NT_FILE - Files mapped into memory
765 /// Additionally, for each thread in the process the core file will contain at
766 /// least the NT_PRSTATUS note, containing the thread id and general purpose
767 /// registers. It may include additional notes for other register sets (floating
768 /// point and vector registers, ...). The tricky part here is that some of these
769 /// notes have "CORE" in their owner fields, while other set it to "LINUX".
770 llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
771 const ArchSpec &arch = GetArchitecture();
772 bool have_prstatus = false;
773 bool have_prpsinfo = false;
774 ThreadData thread_data;
775 for (const auto ¬e : notes) {
776 if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
779 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
780 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
781 assert(thread_data.gpregset.GetByteSize() > 0);
782 // Add the new thread to thread list
783 m_thread_data.push_back(thread_data);
784 thread_data = ThreadData();
785 have_prstatus = false;
786 have_prpsinfo = false;
789 switch (note.info.n_type) {
790 case ELF::NT_PRSTATUS: {
791 have_prstatus = true;
792 ELFLinuxPrStatus prstatus;
793 Status status = prstatus.Parse(note.data, arch);
795 return status.ToError();
796 thread_data.prstatus_sig = prstatus.pr_cursig;
797 thread_data.tid = prstatus.pr_pid;
798 uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
799 size_t len = note.data.GetByteSize() - header_size;
800 thread_data.gpregset = DataExtractor(note.data, header_size, len);
803 case ELF::NT_PRPSINFO: {
804 have_prpsinfo = true;
805 ELFLinuxPrPsInfo prpsinfo;
806 Status status = prpsinfo.Parse(note.data, arch);
808 return status.ToError();
809 thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
810 SetID(prpsinfo.pr_pid);
813 case ELF::NT_SIGINFO: {
814 ELFLinuxSigInfo siginfo;
815 Status status = siginfo.Parse(note.data, arch);
817 return status.ToError();
818 thread_data.signo = siginfo.si_signo;
822 m_nt_file_entries.clear();
823 lldb::offset_t offset = 0;
824 const uint64_t count = note.data.GetAddress(&offset);
825 note.data.GetAddress(&offset); // Skip page size
826 for (uint64_t i = 0; i < count; ++i) {
828 entry.start = note.data.GetAddress(&offset);
829 entry.end = note.data.GetAddress(&offset);
830 entry.file_ofs = note.data.GetAddress(&offset);
831 m_nt_file_entries.push_back(entry);
833 for (uint64_t i = 0; i < count; ++i) {
834 const char *path = note.data.GetCStr(&offset);
836 m_nt_file_entries[i].path.SetCString(path);
844 thread_data.notes.push_back(note);
848 // Add last entry in the note section
850 m_thread_data.push_back(thread_data);
851 return llvm::Error::success();
854 /// Parse Thread context from PT_NOTE segment and store it in the thread list
855 /// A note segment consists of one or more NOTE entries, but their types and
856 /// meaning differ depending on the OS.
857 llvm::Error ProcessElfCore::ParseThreadContextsFromNoteSegment(
858 const elf::ELFProgramHeader &segment_header, DataExtractor segment_data) {
859 assert(segment_header.p_type == llvm::ELF::PT_NOTE);
861 auto notes_or_error = parseSegment(segment_data);
863 return notes_or_error.takeError();
864 switch (GetArchitecture().GetTriple().getOS()) {
865 case llvm::Triple::FreeBSD:
866 return parseFreeBSDNotes(*notes_or_error);
867 case llvm::Triple::Linux:
868 return parseLinuxNotes(*notes_or_error);
869 case llvm::Triple::NetBSD:
870 return parseNetBSDNotes(*notes_or_error);
871 case llvm::Triple::OpenBSD:
872 return parseOpenBSDNotes(*notes_or_error);
874 return llvm::make_error<llvm::StringError>(
875 "Don't know how to parse core file. Unsupported OS.",
876 llvm::inconvertibleErrorCode());
880 uint32_t ProcessElfCore::GetNumThreadContexts() {
881 if (!m_thread_data_valid)
883 return m_thread_data.size();
886 ArchSpec ProcessElfCore::GetArchitecture() {
887 ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
889 ArchSpec target_arch = GetTarget().GetArchitecture();
890 arch.MergeFrom(target_arch);
892 // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
893 // files and this information can't be merged in from the target arch so we
894 // fail back to unconditionally returning the target arch in this config.
895 if (target_arch.IsMIPS()) {
902 DataExtractor ProcessElfCore::GetAuxvData() {
903 const uint8_t *start = m_auxv.GetDataStart();
904 size_t len = m_auxv.GetByteSize();
905 lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
906 return DataExtractor(buffer, GetByteOrder(), GetAddressByteSize());
909 bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
911 info.SetProcessID(GetID());
912 info.SetArchitecture(GetArchitecture());
913 lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
915 const bool add_exe_file_as_first_arg = false;
916 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
917 add_exe_file_as_first_arg);