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;
37 ConstString ProcessElfCore::GetPluginNameStatic() {
38 static ConstString g_name("elf-core");
42 const char *ProcessElfCore::GetPluginDescriptionStatic() {
43 return "ELF core dump plug-in.";
46 void ProcessElfCore::Terminate() {
47 PluginManager::UnregisterPlugin(ProcessElfCore::CreateInstance);
50 lldb::ProcessSP ProcessElfCore::CreateInstance(lldb::TargetSP target_sp,
51 lldb::ListenerSP listener_sp,
52 const FileSpec *crash_file) {
53 lldb::ProcessSP process_sp;
55 // Read enough data for a ELF32 header or ELF64 header Note: Here we care
56 // about e_type field only, so it is safe to ignore possible presence of
57 // the header extension.
58 const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr);
60 auto data_sp = FileSystem::Instance().CreateDataBuffer(
61 crash_file->GetPath(), header_size, 0);
62 if (data_sp && data_sp->GetByteSize() == header_size &&
63 elf::ELFHeader::MagicBytesMatch(data_sp->GetBytes())) {
64 elf::ELFHeader elf_header;
65 DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
66 lldb::offset_t data_offset = 0;
67 if (elf_header.Parse(data, &data_offset)) {
68 if (elf_header.e_type == llvm::ELF::ET_CORE)
69 process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp,
77 bool ProcessElfCore::CanDebug(lldb::TargetSP target_sp,
78 bool plugin_specified_by_name) {
79 // For now we are just making sure the file exists for a given module
80 if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) {
81 ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture());
82 Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp,
83 nullptr, nullptr, nullptr));
84 if (m_core_module_sp) {
85 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
86 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
93 // ProcessElfCore constructor
94 ProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp,
95 lldb::ListenerSP listener_sp,
96 const FileSpec &core_file)
97 : Process(target_sp, listener_sp), m_core_file(core_file) {}
100 ProcessElfCore::~ProcessElfCore() {
102 // We need to call finalize on the process before destroying ourselves to
103 // make sure all of the broadcaster cleanup goes as planned. If we destruct
104 // this class, then Process::~Process() might have problems trying to fully
105 // destroy the broadcaster.
110 ConstString ProcessElfCore::GetPluginName() { return GetPluginNameStatic(); }
112 uint32_t ProcessElfCore::GetPluginVersion() { return 1; }
114 lldb::addr_t ProcessElfCore::AddAddressRangeFromLoadSegment(
115 const elf::ELFProgramHeader &header) {
116 const lldb::addr_t addr = header.p_vaddr;
117 FileRange file_range(header.p_offset, header.p_filesz);
118 VMRangeToFileOffset::Entry range_entry(addr, header.p_memsz, file_range);
120 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
121 if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
122 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
123 last_entry->GetByteSize() == last_entry->data.GetByteSize()) {
124 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
125 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
127 m_core_aranges.Append(range_entry);
130 // Keep a separate map of permissions that that isn't coalesced so all ranges
132 const uint32_t permissions =
133 ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) |
134 ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) |
135 ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u);
137 m_core_range_infos.Append(
138 VMRangeToPermissions::Entry(addr, header.p_memsz, permissions));
144 Status ProcessElfCore::DoLoadCore() {
146 if (!m_core_module_sp) {
147 error.SetErrorString("invalid core module");
151 ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
152 if (core == nullptr) {
153 error.SetErrorString("invalid core object file");
157 llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders();
158 if (segments.size() == 0) {
159 error.SetErrorString("core file has no segments");
165 m_thread_data_valid = true;
167 bool ranges_are_sorted = true;
168 lldb::addr_t vm_addr = 0;
169 /// Walk through segments and Thread and Address Map information.
170 /// PT_NOTE - Contains Thread and Register information
171 /// PT_LOAD - Contains a contiguous range of Process Address Space
172 for (const elf::ELFProgramHeader &H : segments) {
173 DataExtractor data = core->GetSegmentData(H);
175 // Parse thread contexts and auxv structure
176 if (H.p_type == llvm::ELF::PT_NOTE) {
177 if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data))
178 return Status(std::move(error));
180 // PT_LOAD segments contains address map
181 if (H.p_type == llvm::ELF::PT_LOAD) {
182 lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(H);
183 if (vm_addr > last_addr)
184 ranges_are_sorted = false;
189 if (!ranges_are_sorted) {
190 m_core_aranges.Sort();
191 m_core_range_infos.Sort();
194 // Even if the architecture is set in the target, we need to override it to
195 // match the core file which is always single arch.
196 ArchSpec arch(m_core_module_sp->GetArchitecture());
198 ArchSpec target_arch = GetTarget().GetArchitecture();
199 ArchSpec core_arch(m_core_module_sp->GetArchitecture());
200 target_arch.MergeFrom(core_arch);
201 GetTarget().SetArchitecture(target_arch);
203 SetUnixSignals(UnixSignals::Create(GetArchitecture()));
205 // Ensure we found at least one thread that was stopped on a signal.
206 bool siginfo_signal_found = false;
207 bool prstatus_signal_found = false;
208 // Check we found a signal in a SIGINFO note.
209 for (const auto &thread_data : m_thread_data) {
210 if (thread_data.signo != 0)
211 siginfo_signal_found = true;
212 if (thread_data.prstatus_sig != 0)
213 prstatus_signal_found = true;
215 if (!siginfo_signal_found) {
216 // If we don't have signal from SIGINFO use the signal from each threads
218 if (prstatus_signal_found) {
219 for (auto &thread_data : m_thread_data)
220 thread_data.signo = thread_data.prstatus_sig;
221 } else if (m_thread_data.size() > 0) {
222 // If all else fails force the first thread to be SIGSTOP
223 m_thread_data.begin()->signo =
224 GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
228 // Core files are useless without the main executable. See if we can locate
229 // the main executable using data we found in the core file notes.
230 lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
231 if (!exe_module_sp) {
232 // The first entry in the NT_FILE might be our executable
233 if (!m_nt_file_entries.empty()) {
234 ModuleSpec exe_module_spec;
235 exe_module_spec.GetArchitecture() = arch;
236 exe_module_spec.GetFileSpec().SetFile(
237 m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native);
238 if (exe_module_spec.GetFileSpec()) {
239 exe_module_sp = GetTarget().GetOrCreateModule(exe_module_spec,
242 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo);
249 lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() {
250 if (m_dyld_up.get() == nullptr)
251 m_dyld_up.reset(DynamicLoader::FindPlugin(
252 this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString()));
253 return m_dyld_up.get();
256 bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list,
257 ThreadList &new_thread_list) {
258 const uint32_t num_threads = GetNumThreadContexts();
259 if (!m_thread_data_valid)
262 for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
263 const ThreadData &td = m_thread_data[tid];
264 lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
265 new_thread_list.AddThread(thread_sp);
267 return new_thread_list.GetSize(false) > 0;
270 void ProcessElfCore::RefreshStateAfterStop() {}
272 Status ProcessElfCore::DoDestroy() { return Status(); }
276 bool ProcessElfCore::IsAlive() { return true; }
279 size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
281 // Don't allow the caching that lldb_private::Process::ReadMemory does since
282 // in core files we have it all cached our our core file anyway.
283 return DoReadMemory(addr, buf, size, error);
286 Status ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr,
287 MemoryRegionInfo ®ion_info) {
289 const VMRangeToPermissions::Entry *permission_entry =
290 m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
291 if (permission_entry) {
292 if (permission_entry->Contains(load_addr)) {
293 region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
294 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
295 const Flags permissions(permission_entry->data);
296 region_info.SetReadable(permissions.Test(lldb::ePermissionsReadable)
297 ? MemoryRegionInfo::eYes
298 : MemoryRegionInfo::eNo);
299 region_info.SetWritable(permissions.Test(lldb::ePermissionsWritable)
300 ? MemoryRegionInfo::eYes
301 : MemoryRegionInfo::eNo);
302 region_info.SetExecutable(permissions.Test(lldb::ePermissionsExecutable)
303 ? MemoryRegionInfo::eYes
304 : MemoryRegionInfo::eNo);
305 region_info.SetMapped(MemoryRegionInfo::eYes);
306 } else if (load_addr < permission_entry->GetRangeBase()) {
307 region_info.GetRange().SetRangeBase(load_addr);
308 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
309 region_info.SetReadable(MemoryRegionInfo::eNo);
310 region_info.SetWritable(MemoryRegionInfo::eNo);
311 region_info.SetExecutable(MemoryRegionInfo::eNo);
312 region_info.SetMapped(MemoryRegionInfo::eNo);
317 region_info.GetRange().SetRangeBase(load_addr);
318 region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
319 region_info.SetReadable(MemoryRegionInfo::eNo);
320 region_info.SetWritable(MemoryRegionInfo::eNo);
321 region_info.SetExecutable(MemoryRegionInfo::eNo);
322 region_info.SetMapped(MemoryRegionInfo::eNo);
326 size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
328 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
330 if (core_objfile == nullptr)
333 // Get the address range
334 const VMRangeToFileOffset::Entry *address_range =
335 m_core_aranges.FindEntryThatContains(addr);
336 if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
337 error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64,
342 // Convert the address into core file offset
343 const lldb::addr_t offset = addr - address_range->GetRangeBase();
344 const lldb::addr_t file_start = address_range->data.GetRangeBase();
345 const lldb::addr_t file_end = address_range->data.GetRangeEnd();
346 size_t bytes_to_read = size; // Number of bytes to read from the core file
347 size_t bytes_copied = 0; // Number of bytes actually read from the core file
348 size_t zero_fill_size = 0; // Padding
349 lldb::addr_t bytes_left =
350 0; // Number of bytes available in the core file from the given address
352 // Don't proceed if core file doesn't contain the actual data for this
354 if (file_start == file_end)
357 // Figure out how many on-disk bytes remain in this segment starting at the
359 if (file_end > file_start + offset)
360 bytes_left = file_end - (file_start + offset);
362 // Figure out how many bytes we need to zero-fill if we are reading more
363 // bytes than available in the on-disk segment
364 if (bytes_to_read > bytes_left) {
365 zero_fill_size = bytes_to_read - bytes_left;
366 bytes_to_read = bytes_left;
369 // If there is data available on the core file read it
372 core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
374 assert(zero_fill_size <= size);
375 // Pad remaining bytes
377 memset(((char *)buf) + bytes_copied, 0, zero_fill_size);
379 return bytes_copied + zero_fill_size;
382 void ProcessElfCore::Clear() {
383 m_thread_list.Clear();
385 SetUnixSignals(std::make_shared<UnixSignals>());
388 void ProcessElfCore::Initialize() {
389 static llvm::once_flag g_once_flag;
391 llvm::call_once(g_once_flag, []() {
392 PluginManager::RegisterPlugin(GetPluginNameStatic(),
393 GetPluginDescriptionStatic(), CreateInstance);
397 lldb::addr_t ProcessElfCore::GetImageInfoAddress() {
398 ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
399 Address addr = obj_file->GetImageInfoAddress(&GetTarget());
402 return addr.GetLoadAddress(&GetTarget());
403 return LLDB_INVALID_ADDRESS;
406 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
407 static void ParseFreeBSDPrStatus(ThreadData &thread_data,
408 const DataExtractor &data,
409 const ArchSpec &arch) {
410 lldb::offset_t offset = 0;
411 bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
412 arch.GetMachine() == llvm::Triple::mips64 ||
413 arch.GetMachine() == llvm::Triple::ppc64 ||
414 arch.GetMachine() == llvm::Triple::x86_64);
415 int pr_version = data.GetU32(&offset);
417 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
420 log->Printf("FreeBSD PRSTATUS unexpected version %d", pr_version);
423 // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
429 thread_data.signo = data.GetU32(&offset); // pr_cursig
430 thread_data.tid = data.GetU32(&offset); // pr_pid
434 size_t len = data.GetByteSize() - offset;
435 thread_data.gpregset = DataExtractor(data, offset, len);
438 static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
441 uint32_t &cpi_siglwp,
443 lldb::offset_t offset = 0;
445 uint32_t version = data.GetU32(&offset);
447 return llvm::make_error<llvm::StringError>(
448 "Error parsing NetBSD core(5) notes: Unsupported procinfo version",
449 llvm::inconvertibleErrorCode());
451 uint32_t cpisize = data.GetU32(&offset);
452 if (cpisize != NETBSD::NT_PROCINFO_SIZE)
453 return llvm::make_error<llvm::StringError>(
454 "Error parsing NetBSD core(5) notes: Unsupported procinfo size",
455 llvm::inconvertibleErrorCode());
457 cpi_signo = data.GetU32(&offset); /* killing signal */
459 offset += NETBSD::NT_PROCINFO_CPI_SIGCODE_SIZE;
460 offset += NETBSD::NT_PROCINFO_CPI_SIGPEND_SIZE;
461 offset += NETBSD::NT_PROCINFO_CPI_SIGMASK_SIZE;
462 offset += NETBSD::NT_PROCINFO_CPI_SIGIGNORE_SIZE;
463 offset += NETBSD::NT_PROCINFO_CPI_SIGCATCH_SIZE;
464 cpi_pid = data.GetU32(&offset);
465 offset += NETBSD::NT_PROCINFO_CPI_PPID_SIZE;
466 offset += NETBSD::NT_PROCINFO_CPI_PGRP_SIZE;
467 offset += NETBSD::NT_PROCINFO_CPI_SID_SIZE;
468 offset += NETBSD::NT_PROCINFO_CPI_RUID_SIZE;
469 offset += NETBSD::NT_PROCINFO_CPI_EUID_SIZE;
470 offset += NETBSD::NT_PROCINFO_CPI_SVUID_SIZE;
471 offset += NETBSD::NT_PROCINFO_CPI_RGID_SIZE;
472 offset += NETBSD::NT_PROCINFO_CPI_EGID_SIZE;
473 offset += NETBSD::NT_PROCINFO_CPI_SVGID_SIZE;
474 cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
476 offset += NETBSD::NT_PROCINFO_CPI_NAME_SIZE;
477 cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
479 return llvm::Error::success();
482 static void ParseOpenBSDProcInfo(ThreadData &thread_data,
483 const DataExtractor &data) {
484 lldb::offset_t offset = 0;
486 int version = data.GetU32(&offset);
491 thread_data.signo = data.GetU32(&offset);
494 llvm::Expected<std::vector<CoreNote>>
495 ProcessElfCore::parseSegment(const DataExtractor &segment) {
496 lldb::offset_t offset = 0;
497 std::vector<CoreNote> result;
499 while (offset < segment.GetByteSize()) {
500 ELFNote note = ELFNote();
501 if (!note.Parse(segment, &offset))
502 return llvm::make_error<llvm::StringError>(
503 "Unable to parse note segment", llvm::inconvertibleErrorCode());
505 size_t note_start = offset;
506 size_t note_size = llvm::alignTo(note.n_descsz, 4);
507 DataExtractor note_data(segment, note_start, note_size);
509 result.push_back({note, note_data});
513 return std::move(result);
516 llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
517 bool have_prstatus = false;
518 bool have_prpsinfo = false;
519 ThreadData thread_data;
520 for (const auto ¬e : notes) {
521 if (note.info.n_name != "FreeBSD")
524 if ((note.info.n_type == FREEBSD::NT_PRSTATUS && have_prstatus) ||
525 (note.info.n_type == FREEBSD::NT_PRPSINFO && have_prpsinfo)) {
526 assert(thread_data.gpregset.GetByteSize() > 0);
527 // Add the new thread to thread list
528 m_thread_data.push_back(thread_data);
529 thread_data = ThreadData();
530 have_prstatus = false;
531 have_prpsinfo = false;
534 switch (note.info.n_type) {
535 case FREEBSD::NT_PRSTATUS:
536 have_prstatus = true;
537 ParseFreeBSDPrStatus(thread_data, note.data, GetArchitecture());
539 case FREEBSD::NT_PRPSINFO:
540 have_prpsinfo = true;
542 case FREEBSD::NT_THRMISC: {
543 lldb::offset_t offset = 0;
544 thread_data.name = note.data.GetCStr(&offset, 20);
547 case FREEBSD::NT_PROCSTAT_AUXV:
548 // FIXME: FreeBSD sticks an int at the beginning of the note
549 m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
552 thread_data.notes.push_back(note);
556 if (!have_prstatus) {
557 return llvm::make_error<llvm::StringError>(
558 "Could not find NT_PRSTATUS note in core file.",
559 llvm::inconvertibleErrorCode());
561 m_thread_data.push_back(thread_data);
562 return llvm::Error::success();
565 /// NetBSD specific Thread context from PT_NOTE segment
567 /// NetBSD ELF core files use notes to provide information about
568 /// the process's state. The note name is "NetBSD-CORE" for
569 /// information that is global to the process, and "NetBSD-CORE@nn",
570 /// where "nn" is the lwpid of the LWP that the information belongs
571 /// to (such as register state).
573 /// NetBSD uses the following note identifiers:
575 /// ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
576 /// Note is a "netbsd_elfcore_procinfo" structure.
577 /// ELF_NOTE_NETBSD_CORE_AUXV (value 2; since NetBSD 8.0)
578 /// Note is an array of AuxInfo structures.
580 /// NetBSD also uses ptrace(2) request numbers (the ones that exist in
581 /// machine-dependent space) to identify register info notes. The
582 /// info in such notes is in the same format that ptrace(2) would
583 /// export that information.
585 /// For more information see /usr/include/sys/exec_elf.h
587 llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
588 ThreadData thread_data;
589 bool had_nt_regs = false;
591 // To be extracted from struct netbsd_elfcore_procinfo
592 // Used to sanity check of the LWPs of the process
594 uint32_t signo; // killing signal
595 uint32_t siglwp; // LWP target of killing signal
598 for (const auto ¬e : notes) {
599 llvm::StringRef name = note.info.n_name;
601 if (name == "NetBSD-CORE") {
602 if (note.info.n_type == NETBSD::NT_PROCINFO) {
603 llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
608 } else if (note.info.n_type == NETBSD::NT_AUXV) {
611 } else if (name.consume_front("NetBSD-CORE@")) {
613 if (name.getAsInteger(10, tid))
614 return llvm::make_error<llvm::StringError>(
615 "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
617 llvm::inconvertibleErrorCode());
619 switch (GetArchitecture().GetMachine()) {
620 case llvm::Triple::aarch64: {
621 // Assume order PT_GETREGS, PT_GETFPREGS
622 if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
623 // If this is the next thread, push the previous one first.
625 m_thread_data.push_back(thread_data);
626 thread_data = ThreadData();
630 thread_data.gpregset = note.data;
631 thread_data.tid = tid;
632 if (thread_data.gpregset.GetByteSize() == 0)
633 return llvm::make_error<llvm::StringError>(
634 "Could not find general purpose registers note in core file.",
635 llvm::inconvertibleErrorCode());
637 } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
638 if (!had_nt_regs || tid != thread_data.tid)
639 return llvm::make_error<llvm::StringError>(
640 "Error parsing NetBSD core(5) notes: Unexpected order "
641 "of NOTEs PT_GETFPREG before PT_GETREG",
642 llvm::inconvertibleErrorCode());
643 thread_data.notes.push_back(note);
646 case llvm::Triple::x86_64: {
647 // Assume order PT_GETREGS, PT_GETFPREGS
648 if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
649 // If this is the next thread, push the previous one first.
651 m_thread_data.push_back(thread_data);
652 thread_data = ThreadData();
656 thread_data.gpregset = note.data;
657 thread_data.tid = tid;
658 if (thread_data.gpregset.GetByteSize() == 0)
659 return llvm::make_error<llvm::StringError>(
660 "Could not find general purpose registers note in core file.",
661 llvm::inconvertibleErrorCode());
663 } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
664 if (!had_nt_regs || tid != thread_data.tid)
665 return llvm::make_error<llvm::StringError>(
666 "Error parsing NetBSD core(5) notes: Unexpected order "
667 "of NOTEs PT_GETFPREG before PT_GETREG",
668 llvm::inconvertibleErrorCode());
669 thread_data.notes.push_back(note);
678 // Push the last thread.
680 m_thread_data.push_back(thread_data);
682 if (m_thread_data.empty())
683 return llvm::make_error<llvm::StringError>(
684 "Error parsing NetBSD core(5) notes: No threads information "
685 "specified in notes",
686 llvm::inconvertibleErrorCode());
688 if (m_thread_data.size() != nlwps)
689 return llvm::make_error<llvm::StringError>(
690 "Error parsing NetBSD core(5) notes: Mismatch between the number "
691 "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
693 llvm::inconvertibleErrorCode());
695 // Signal targeted at the whole process.
697 for (auto &data : m_thread_data)
700 // Signal destined for a particular LWP.
704 for (auto &data : m_thread_data) {
705 if (data.tid == siglwp) {
713 return llvm::make_error<llvm::StringError>(
714 "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP",
715 llvm::inconvertibleErrorCode());
718 return llvm::Error::success();
721 llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
722 ThreadData thread_data;
723 for (const auto ¬e : notes) {
724 // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
725 // match on the initial part of the string.
726 if (!llvm::StringRef(note.info.n_name).startswith("OpenBSD"))
729 switch (note.info.n_type) {
730 case OPENBSD::NT_PROCINFO:
731 ParseOpenBSDProcInfo(thread_data, note.data);
733 case OPENBSD::NT_AUXV:
736 case OPENBSD::NT_REGS:
737 thread_data.gpregset = note.data;
740 thread_data.notes.push_back(note);
744 if (thread_data.gpregset.GetByteSize() == 0) {
745 return llvm::make_error<llvm::StringError>(
746 "Could not find general purpose registers note in core file.",
747 llvm::inconvertibleErrorCode());
749 m_thread_data.push_back(thread_data);
750 return llvm::Error::success();
753 /// A description of a linux process usually contains the following NOTE
755 /// - NT_PRPSINFO - General process information like pid, uid, name, ...
756 /// - NT_SIGINFO - Information about the signal that terminated the process
757 /// - NT_AUXV - Process auxiliary vector
758 /// - NT_FILE - Files mapped into memory
760 /// Additionally, for each thread in the process the core file will contain at
761 /// least the NT_PRSTATUS note, containing the thread id and general purpose
762 /// registers. It may include additional notes for other register sets (floating
763 /// point and vector registers, ...). The tricky part here is that some of these
764 /// notes have "CORE" in their owner fields, while other set it to "LINUX".
765 llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
766 const ArchSpec &arch = GetArchitecture();
767 bool have_prstatus = false;
768 bool have_prpsinfo = false;
769 ThreadData thread_data;
770 for (const auto ¬e : notes) {
771 if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
774 if ((note.info.n_type == LINUX::NT_PRSTATUS && have_prstatus) ||
775 (note.info.n_type == LINUX::NT_PRPSINFO && have_prpsinfo)) {
776 assert(thread_data.gpregset.GetByteSize() > 0);
777 // Add the new thread to thread list
778 m_thread_data.push_back(thread_data);
779 thread_data = ThreadData();
780 have_prstatus = false;
781 have_prpsinfo = false;
784 switch (note.info.n_type) {
785 case LINUX::NT_PRSTATUS: {
786 have_prstatus = true;
787 ELFLinuxPrStatus prstatus;
788 Status status = prstatus.Parse(note.data, arch);
790 return status.ToError();
791 thread_data.prstatus_sig = prstatus.pr_cursig;
792 thread_data.tid = prstatus.pr_pid;
793 uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
794 size_t len = note.data.GetByteSize() - header_size;
795 thread_data.gpregset = DataExtractor(note.data, header_size, len);
798 case LINUX::NT_PRPSINFO: {
799 have_prpsinfo = true;
800 ELFLinuxPrPsInfo prpsinfo;
801 Status status = prpsinfo.Parse(note.data, arch);
803 return status.ToError();
804 thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
805 SetID(prpsinfo.pr_pid);
808 case LINUX::NT_SIGINFO: {
809 ELFLinuxSigInfo siginfo;
810 Status status = siginfo.Parse(note.data, arch);
812 return status.ToError();
813 thread_data.signo = siginfo.si_signo;
816 case LINUX::NT_FILE: {
817 m_nt_file_entries.clear();
818 lldb::offset_t offset = 0;
819 const uint64_t count = note.data.GetAddress(&offset);
820 note.data.GetAddress(&offset); // Skip page size
821 for (uint64_t i = 0; i < count; ++i) {
823 entry.start = note.data.GetAddress(&offset);
824 entry.end = note.data.GetAddress(&offset);
825 entry.file_ofs = note.data.GetAddress(&offset);
826 m_nt_file_entries.push_back(entry);
828 for (uint64_t i = 0; i < count; ++i) {
829 const char *path = note.data.GetCStr(&offset);
831 m_nt_file_entries[i].path.SetCString(path);
839 thread_data.notes.push_back(note);
843 // Add last entry in the note section
845 m_thread_data.push_back(thread_data);
846 return llvm::Error::success();
849 /// Parse Thread context from PT_NOTE segment and store it in the thread list
850 /// A note segment consists of one or more NOTE entries, but their types and
851 /// meaning differ depending on the OS.
852 llvm::Error ProcessElfCore::ParseThreadContextsFromNoteSegment(
853 const elf::ELFProgramHeader &segment_header, DataExtractor segment_data) {
854 assert(segment_header.p_type == llvm::ELF::PT_NOTE);
856 auto notes_or_error = parseSegment(segment_data);
858 return notes_or_error.takeError();
859 switch (GetArchitecture().GetTriple().getOS()) {
860 case llvm::Triple::FreeBSD:
861 return parseFreeBSDNotes(*notes_or_error);
862 case llvm::Triple::Linux:
863 return parseLinuxNotes(*notes_or_error);
864 case llvm::Triple::NetBSD:
865 return parseNetBSDNotes(*notes_or_error);
866 case llvm::Triple::OpenBSD:
867 return parseOpenBSDNotes(*notes_or_error);
869 return llvm::make_error<llvm::StringError>(
870 "Don't know how to parse core file. Unsupported OS.",
871 llvm::inconvertibleErrorCode());
875 uint32_t ProcessElfCore::GetNumThreadContexts() {
876 if (!m_thread_data_valid)
878 return m_thread_data.size();
881 ArchSpec ProcessElfCore::GetArchitecture() {
882 ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
884 ArchSpec target_arch = GetTarget().GetArchitecture();
885 arch.MergeFrom(target_arch);
887 // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
888 // files and this information can't be merged in from the target arch so we
889 // fail back to unconditionally returning the target arch in this config.
890 if (target_arch.IsMIPS()) {
897 DataExtractor ProcessElfCore::GetAuxvData() {
898 const uint8_t *start = m_auxv.GetDataStart();
899 size_t len = m_auxv.GetByteSize();
900 lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
901 return DataExtractor(buffer, GetByteOrder(), GetAddressByteSize());
904 bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
906 info.SetProcessID(GetID());
907 info.SetArchitecture(GetArchitecture());
908 lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
910 const bool add_exe_file_as_first_arg = false;
911 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
912 add_exe_file_as_first_arg);