xref: /llvm-project/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp (revision 536abf827b481f78a0879b02202fb9a3ffe3a908)
1 //===-- ProcessElfCore.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 <cstddef>
10 #include <cstdlib>
11 
12 #include <memory>
13 #include <mutex>
14 #include <tuple>
15 
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Target/ABI.h"
21 #include "lldb/Target/DynamicLoader.h"
22 #include "lldb/Target/MemoryRegionInfo.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/UnixSignals.h"
25 #include "lldb/Utility/DataBufferHeap.h"
26 #include "lldb/Utility/LLDBLog.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/State.h"
29 
30 #include "llvm/BinaryFormat/ELF.h"
31 #include "llvm/Support/Threading.h"
32 
33 #include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
34 #include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
35 #include "Plugins/Process/elf-core/RegisterUtilities.h"
36 #include "ProcessElfCore.h"
37 #include "ThreadElfCore.h"
38 
39 using namespace lldb_private;
40 namespace ELF = llvm::ELF;
41 
42 LLDB_PLUGIN_DEFINE(ProcessElfCore)
43 
44 llvm::StringRef ProcessElfCore::GetPluginDescriptionStatic() {
45   return "ELF core dump plug-in.";
46 }
47 
48 void ProcessElfCore::Terminate() {
49   PluginManager::UnregisterPlugin(ProcessElfCore::CreateInstance);
50 }
51 
52 lldb::ProcessSP ProcessElfCore::CreateInstance(lldb::TargetSP target_sp,
53                                                lldb::ListenerSP listener_sp,
54                                                const FileSpec *crash_file,
55                                                bool can_connect) {
56   lldb::ProcessSP process_sp;
57   if (crash_file && !can_connect) {
58     // Read enough data for an ELF32 header or ELF64 header Note: Here we care
59     // about e_type field only, so it is safe to ignore possible presence of
60     // the header extension.
61     const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr);
62 
63     auto data_sp = FileSystem::Instance().CreateDataBuffer(
64         crash_file->GetPath(), header_size, 0);
65     if (data_sp && data_sp->GetByteSize() == header_size &&
66         elf::ELFHeader::MagicBytesMatch(data_sp->GetBytes())) {
67       elf::ELFHeader elf_header;
68       DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
69       lldb::offset_t data_offset = 0;
70       if (elf_header.Parse(data, &data_offset)) {
71         // Check whether we're dealing with a raw FreeBSD "full memory dump"
72         // ELF vmcore that needs to be handled via FreeBSDKernel plugin instead.
73         if (elf_header.e_ident[7] == 0xFF && elf_header.e_version == 0)
74           return process_sp;
75         if (elf_header.e_type == llvm::ELF::ET_CORE)
76           process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp,
77                                                         *crash_file);
78       }
79     }
80   }
81   return process_sp;
82 }
83 
84 bool ProcessElfCore::CanDebug(lldb::TargetSP target_sp,
85                               bool plugin_specified_by_name) {
86   // For now we are just making sure the file exists for a given module
87   if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) {
88     ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture());
89     Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp,
90                                              nullptr, nullptr, nullptr));
91     if (m_core_module_sp) {
92       ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
93       if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
94         return true;
95     }
96   }
97   return false;
98 }
99 
100 // ProcessElfCore constructor
101 ProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp,
102                                lldb::ListenerSP listener_sp,
103                                const FileSpec &core_file)
104     : PostMortemProcess(target_sp, listener_sp, core_file) {}
105 
106 // Destructor
107 ProcessElfCore::~ProcessElfCore() {
108   Clear();
109   // We need to call finalize on the process before destroying ourselves to
110   // make sure all of the broadcaster cleanup goes as planned. If we destruct
111   // this class, then Process::~Process() might have problems trying to fully
112   // destroy the broadcaster.
113   Finalize(true /* destructing */);
114 }
115 
116 lldb::addr_t ProcessElfCore::AddAddressRangeFromLoadSegment(
117     const elf::ELFProgramHeader &header) {
118   const lldb::addr_t addr = header.p_vaddr;
119   FileRange file_range(header.p_offset, header.p_filesz);
120   VMRangeToFileOffset::Entry range_entry(addr, header.p_memsz, file_range);
121 
122   // Only add to m_core_aranges if the file size is non zero. Some core files
123   // have PT_LOAD segments for all address ranges, but set f_filesz to zero for
124   // the .text sections since they can be retrieved from the object files.
125   if (header.p_filesz > 0) {
126     VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
127     if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
128         last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
129         last_entry->GetByteSize() == last_entry->data.GetByteSize()) {
130       last_entry->SetRangeEnd(range_entry.GetRangeEnd());
131       last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
132     } else {
133       m_core_aranges.Append(range_entry);
134     }
135   }
136   // Keep a separate map of permissions that isn't coalesced so all ranges
137   // are maintained.
138   const uint32_t permissions =
139       ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) |
140       ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) |
141       ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u);
142 
143   m_core_range_infos.Append(
144       VMRangeToPermissions::Entry(addr, header.p_memsz, permissions));
145 
146   return addr;
147 }
148 
149 lldb::addr_t ProcessElfCore::AddAddressRangeFromMemoryTagSegment(
150     const elf::ELFProgramHeader &header) {
151   // If lldb understood multiple kinds of tag segments we would record the type
152   // of the segment here also. As long as there is only 1 type lldb looks for,
153   // there is no need.
154   FileRange file_range(header.p_offset, header.p_filesz);
155   m_core_tag_ranges.Append(
156       VMRangeToFileOffset::Entry(header.p_vaddr, header.p_memsz, file_range));
157 
158   return header.p_vaddr;
159 }
160 
161 // Process Control
162 Status ProcessElfCore::DoLoadCore() {
163   Status error;
164   if (!m_core_module_sp) {
165     error.SetErrorString("invalid core module");
166     return error;
167   }
168 
169   ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
170   if (core == nullptr) {
171     error.SetErrorString("invalid core object file");
172     return error;
173   }
174 
175   llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders();
176   if (segments.size() == 0) {
177     error.SetErrorString("core file has no segments");
178     return error;
179   }
180 
181   SetCanJIT(false);
182 
183   m_thread_data_valid = true;
184 
185   bool ranges_are_sorted = true;
186   lldb::addr_t vm_addr = 0;
187   lldb::addr_t tag_addr = 0;
188   /// Walk through segments and Thread and Address Map information.
189   /// PT_NOTE - Contains Thread and Register information
190   /// PT_LOAD - Contains a contiguous range of Process Address Space
191   /// PT_AARCH64_MEMTAG_MTE - Contains AArch64 MTE memory tags for a range of
192   ///                         Process Address Space.
193   for (const elf::ELFProgramHeader &H : segments) {
194     DataExtractor data = core->GetSegmentData(H);
195 
196     // Parse thread contexts and auxv structure
197     if (H.p_type == llvm::ELF::PT_NOTE) {
198       if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data))
199         return Status(std::move(error));
200     }
201     // PT_LOAD segments contains address map
202     if (H.p_type == llvm::ELF::PT_LOAD) {
203       lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(H);
204       if (vm_addr > last_addr)
205         ranges_are_sorted = false;
206       vm_addr = last_addr;
207     } else if (H.p_type == llvm::ELF::PT_AARCH64_MEMTAG_MTE) {
208       lldb::addr_t last_addr = AddAddressRangeFromMemoryTagSegment(H);
209       if (tag_addr > last_addr)
210         ranges_are_sorted = false;
211       tag_addr = last_addr;
212     }
213   }
214 
215   // We need to update uuid after address range is populated.
216   UpdateBuildIdForNTFileEntries();
217 
218   if (!ranges_are_sorted) {
219     m_core_aranges.Sort();
220     m_core_range_infos.Sort();
221     m_core_tag_ranges.Sort();
222   }
223 
224   // Even if the architecture is set in the target, we need to override it to
225   // match the core file which is always single arch.
226   ArchSpec arch(m_core_module_sp->GetArchitecture());
227 
228   ArchSpec target_arch = GetTarget().GetArchitecture();
229   ArchSpec core_arch(m_core_module_sp->GetArchitecture());
230   target_arch.MergeFrom(core_arch);
231   GetTarget().SetArchitecture(target_arch);
232 
233   SetUnixSignals(UnixSignals::Create(GetArchitecture()));
234 
235   // Ensure we found at least one thread that was stopped on a signal.
236   bool siginfo_signal_found = false;
237   bool prstatus_signal_found = false;
238   // Check we found a signal in a SIGINFO note.
239   for (const auto &thread_data : m_thread_data) {
240     if (thread_data.signo != 0)
241       siginfo_signal_found = true;
242     if (thread_data.prstatus_sig != 0)
243       prstatus_signal_found = true;
244   }
245   if (!siginfo_signal_found) {
246     // If we don't have signal from SIGINFO use the signal from each threads
247     // PRSTATUS note.
248     if (prstatus_signal_found) {
249       for (auto &thread_data : m_thread_data)
250         thread_data.signo = thread_data.prstatus_sig;
251     } else if (m_thread_data.size() > 0) {
252       // If all else fails force the first thread to be SIGSTOP
253       m_thread_data.begin()->signo =
254           GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
255     }
256   }
257 
258   // Core files are useless without the main executable. See if we can locate
259   // the main executable using data we found in the core file notes.
260   lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
261   if (!exe_module_sp) {
262     // The first entry in the NT_FILE might be our executable
263     if (!m_nt_file_entries.empty()) {
264       ModuleSpec exe_module_spec;
265       exe_module_spec.GetArchitecture() = arch;
266       exe_module_spec.GetUUID() = m_nt_file_entries[0].uuid;
267       exe_module_spec.GetFileSpec().SetFile(m_nt_file_entries[0].path,
268                                             FileSpec::Style::native);
269       if (exe_module_spec.GetFileSpec()) {
270         exe_module_sp =
271             GetTarget().GetOrCreateModule(exe_module_spec, true /* notify */);
272         if (exe_module_sp)
273           GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo);
274       }
275     }
276   }
277   return error;
278 }
279 
280 void ProcessElfCore::UpdateBuildIdForNTFileEntries() {
281   if (!m_nt_file_entries.empty()) {
282     for (NT_FILE_Entry &entry : m_nt_file_entries) {
283       std::optional<UUID> uuid = FindBuildId(entry);
284       if (uuid)
285         entry.uuid = uuid.value();
286     }
287   }
288 }
289 
290 lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() {
291   if (m_dyld_up.get() == nullptr)
292     m_dyld_up.reset(DynamicLoader::FindPlugin(
293         this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic()));
294   return m_dyld_up.get();
295 }
296 
297 bool ProcessElfCore::DoUpdateThreadList(ThreadList &old_thread_list,
298                                         ThreadList &new_thread_list) {
299   const uint32_t num_threads = GetNumThreadContexts();
300   if (!m_thread_data_valid)
301     return false;
302 
303   for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
304     const ThreadData &td = m_thread_data[tid];
305     lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
306     new_thread_list.AddThread(thread_sp);
307   }
308   return new_thread_list.GetSize(false) > 0;
309 }
310 
311 void ProcessElfCore::RefreshStateAfterStop() {}
312 
313 Status ProcessElfCore::DoDestroy() { return Status(); }
314 
315 // Process Queries
316 
317 bool ProcessElfCore::IsAlive() { return true; }
318 
319 // Process Memory
320 size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
321                                   Status &error) {
322   if (lldb::ABISP abi_sp = GetABI())
323     addr = abi_sp->FixAnyAddress(addr);
324 
325   // Don't allow the caching that lldb_private::Process::ReadMemory does since
326   // in core files we have it all cached our our core file anyway.
327   return DoReadMemory(addr, buf, size, error);
328 }
329 
330 Status ProcessElfCore::DoGetMemoryRegionInfo(lldb::addr_t load_addr,
331                                              MemoryRegionInfo &region_info) {
332   region_info.Clear();
333   const VMRangeToPermissions::Entry *permission_entry =
334       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
335   if (permission_entry) {
336     if (permission_entry->Contains(load_addr)) {
337       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
338       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
339       const Flags permissions(permission_entry->data);
340       region_info.SetReadable(permissions.Test(lldb::ePermissionsReadable)
341                                   ? MemoryRegionInfo::eYes
342                                   : MemoryRegionInfo::eNo);
343       region_info.SetWritable(permissions.Test(lldb::ePermissionsWritable)
344                                   ? MemoryRegionInfo::eYes
345                                   : MemoryRegionInfo::eNo);
346       region_info.SetExecutable(permissions.Test(lldb::ePermissionsExecutable)
347                                     ? MemoryRegionInfo::eYes
348                                     : MemoryRegionInfo::eNo);
349       region_info.SetMapped(MemoryRegionInfo::eYes);
350 
351       // A region is memory tagged if there is a memory tag segment that covers
352       // the exact same range.
353       region_info.SetMemoryTagged(MemoryRegionInfo::eNo);
354       const VMRangeToFileOffset::Entry *tag_entry =
355           m_core_tag_ranges.FindEntryStartsAt(permission_entry->GetRangeBase());
356       if (tag_entry &&
357           tag_entry->GetRangeEnd() == permission_entry->GetRangeEnd())
358         region_info.SetMemoryTagged(MemoryRegionInfo::eYes);
359     } else if (load_addr < permission_entry->GetRangeBase()) {
360       region_info.GetRange().SetRangeBase(load_addr);
361       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
362       region_info.SetReadable(MemoryRegionInfo::eNo);
363       region_info.SetWritable(MemoryRegionInfo::eNo);
364       region_info.SetExecutable(MemoryRegionInfo::eNo);
365       region_info.SetMapped(MemoryRegionInfo::eNo);
366       region_info.SetMemoryTagged(MemoryRegionInfo::eNo);
367     }
368     return Status();
369   }
370 
371   region_info.GetRange().SetRangeBase(load_addr);
372   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
373   region_info.SetReadable(MemoryRegionInfo::eNo);
374   region_info.SetWritable(MemoryRegionInfo::eNo);
375   region_info.SetExecutable(MemoryRegionInfo::eNo);
376   region_info.SetMapped(MemoryRegionInfo::eNo);
377   region_info.SetMemoryTagged(MemoryRegionInfo::eNo);
378   return Status();
379 }
380 
381 size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
382                                     Status &error) {
383   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
384 
385   if (core_objfile == nullptr)
386     return 0;
387 
388   // Get the address range
389   const VMRangeToFileOffset::Entry *address_range =
390       m_core_aranges.FindEntryThatContains(addr);
391   if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
392     error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64,
393                                    addr);
394     return 0;
395   }
396 
397   // Convert the address into core file offset
398   const lldb::addr_t offset = addr - address_range->GetRangeBase();
399   const lldb::addr_t file_start = address_range->data.GetRangeBase();
400   const lldb::addr_t file_end = address_range->data.GetRangeEnd();
401   size_t bytes_to_read = size; // Number of bytes to read from the core file
402   size_t bytes_copied = 0;   // Number of bytes actually read from the core file
403   lldb::addr_t bytes_left =
404       0; // Number of bytes available in the core file from the given address
405 
406   // Don't proceed if core file doesn't contain the actual data for this
407   // address range.
408   if (file_start == file_end)
409     return 0;
410 
411   // Figure out how many on-disk bytes remain in this segment starting at the
412   // given offset
413   if (file_end > file_start + offset)
414     bytes_left = file_end - (file_start + offset);
415 
416   if (bytes_to_read > bytes_left)
417     bytes_to_read = bytes_left;
418 
419   // If there is data available on the core file read it
420   if (bytes_to_read)
421     bytes_copied =
422         core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
423 
424   return bytes_copied;
425 }
426 
427 llvm::Expected<std::vector<lldb::addr_t>>
428 ProcessElfCore::ReadMemoryTags(lldb::addr_t addr, size_t len) {
429   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
430   if (core_objfile == nullptr)
431     return llvm::createStringError(llvm::inconvertibleErrorCode(),
432                                    "No core object file.");
433 
434   llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
435       GetMemoryTagManager();
436   if (!tag_manager_or_err)
437     return tag_manager_or_err.takeError();
438 
439   // LLDB only supports AArch64 MTE tag segments so we do not need to worry
440   // about the segment type here. If you got here then you must have a tag
441   // manager (meaning you are debugging AArch64) and all the segments in this
442   // list will have had type PT_AARCH64_MEMTAG_MTE.
443   const VMRangeToFileOffset::Entry *tag_entry =
444       m_core_tag_ranges.FindEntryThatContains(addr);
445   // If we don't have a tag segment or the range asked for extends outside the
446   // segment.
447   if (!tag_entry || (addr + len) >= tag_entry->GetRangeEnd())
448     return llvm::createStringError(llvm::inconvertibleErrorCode(),
449                                    "No tag segment that covers this range.");
450 
451   const MemoryTagManager *tag_manager = *tag_manager_or_err;
452   return tag_manager->UnpackTagsFromCoreFileSegment(
453       [core_objfile](lldb::offset_t offset, size_t length, void *dst) {
454         return core_objfile->CopyData(offset, length, dst);
455       },
456       tag_entry->GetRangeBase(), tag_entry->data.GetRangeBase(), addr, len);
457 }
458 
459 void ProcessElfCore::Clear() {
460   m_thread_list.Clear();
461 
462   SetUnixSignals(std::make_shared<UnixSignals>());
463 }
464 
465 void ProcessElfCore::Initialize() {
466   static llvm::once_flag g_once_flag;
467 
468   llvm::call_once(g_once_flag, []() {
469     PluginManager::RegisterPlugin(GetPluginNameStatic(),
470                                   GetPluginDescriptionStatic(), CreateInstance);
471   });
472 }
473 
474 lldb::addr_t ProcessElfCore::GetImageInfoAddress() {
475   ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
476   Address addr = obj_file->GetImageInfoAddress(&GetTarget());
477 
478   if (addr.IsValid())
479     return addr.GetLoadAddress(&GetTarget());
480   return LLDB_INVALID_ADDRESS;
481 }
482 
483 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
484 static void ParseFreeBSDPrStatus(ThreadData &thread_data,
485                                  const DataExtractor &data,
486                                  bool lp64) {
487   lldb::offset_t offset = 0;
488   int pr_version = data.GetU32(&offset);
489 
490   Log *log = GetLog(LLDBLog::Process);
491   if (log) {
492     if (pr_version > 1)
493       LLDB_LOGF(log, "FreeBSD PRSTATUS unexpected version %d", pr_version);
494   }
495 
496   // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
497   if (lp64)
498     offset += 32;
499   else
500     offset += 16;
501 
502   thread_data.signo = data.GetU32(&offset); // pr_cursig
503   thread_data.tid = data.GetU32(&offset);   // pr_pid
504   if (lp64)
505     offset += 4;
506 
507   size_t len = data.GetByteSize() - offset;
508   thread_data.gpregset = DataExtractor(data, offset, len);
509 }
510 
511 // Parse a FreeBSD NT_PRPSINFO note - see FreeBSD sys/procfs.h for details.
512 static void ParseFreeBSDPrPsInfo(ProcessElfCore &process,
513                                  const DataExtractor &data,
514                                  bool lp64) {
515   lldb::offset_t offset = 0;
516   int pr_version = data.GetU32(&offset);
517 
518   Log *log = GetLog(LLDBLog::Process);
519   if (log) {
520     if (pr_version > 1)
521       LLDB_LOGF(log, "FreeBSD PRPSINFO unexpected version %d", pr_version);
522   }
523 
524   // Skip pr_psinfosz, pr_fname, pr_psargs
525   offset += 108;
526   if (lp64)
527     offset += 4;
528 
529   process.SetID(data.GetU32(&offset)); // pr_pid
530 }
531 
532 static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
533                                        uint32_t &cpi_nlwps,
534                                        uint32_t &cpi_signo,
535                                        uint32_t &cpi_siglwp,
536                                        uint32_t &cpi_pid) {
537   lldb::offset_t offset = 0;
538 
539   uint32_t version = data.GetU32(&offset);
540   if (version != 1)
541     return llvm::make_error<llvm::StringError>(
542         "Error parsing NetBSD core(5) notes: Unsupported procinfo version",
543         llvm::inconvertibleErrorCode());
544 
545   uint32_t cpisize = data.GetU32(&offset);
546   if (cpisize != NETBSD::NT_PROCINFO_SIZE)
547     return llvm::make_error<llvm::StringError>(
548         "Error parsing NetBSD core(5) notes: Unsupported procinfo size",
549         llvm::inconvertibleErrorCode());
550 
551   cpi_signo = data.GetU32(&offset); /* killing signal */
552 
553   offset += NETBSD::NT_PROCINFO_CPI_SIGCODE_SIZE;
554   offset += NETBSD::NT_PROCINFO_CPI_SIGPEND_SIZE;
555   offset += NETBSD::NT_PROCINFO_CPI_SIGMASK_SIZE;
556   offset += NETBSD::NT_PROCINFO_CPI_SIGIGNORE_SIZE;
557   offset += NETBSD::NT_PROCINFO_CPI_SIGCATCH_SIZE;
558   cpi_pid = data.GetU32(&offset);
559   offset += NETBSD::NT_PROCINFO_CPI_PPID_SIZE;
560   offset += NETBSD::NT_PROCINFO_CPI_PGRP_SIZE;
561   offset += NETBSD::NT_PROCINFO_CPI_SID_SIZE;
562   offset += NETBSD::NT_PROCINFO_CPI_RUID_SIZE;
563   offset += NETBSD::NT_PROCINFO_CPI_EUID_SIZE;
564   offset += NETBSD::NT_PROCINFO_CPI_SVUID_SIZE;
565   offset += NETBSD::NT_PROCINFO_CPI_RGID_SIZE;
566   offset += NETBSD::NT_PROCINFO_CPI_EGID_SIZE;
567   offset += NETBSD::NT_PROCINFO_CPI_SVGID_SIZE;
568   cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
569 
570   offset += NETBSD::NT_PROCINFO_CPI_NAME_SIZE;
571   cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
572 
573   return llvm::Error::success();
574 }
575 
576 static void ParseOpenBSDProcInfo(ThreadData &thread_data,
577                                  const DataExtractor &data) {
578   lldb::offset_t offset = 0;
579 
580   int version = data.GetU32(&offset);
581   if (version != 1)
582     return;
583 
584   offset += 4;
585   thread_data.signo = data.GetU32(&offset);
586 }
587 
588 llvm::Expected<std::vector<CoreNote>>
589 ProcessElfCore::parseSegment(const DataExtractor &segment) {
590   lldb::offset_t offset = 0;
591   std::vector<CoreNote> result;
592 
593   while (offset < segment.GetByteSize()) {
594     ELFNote note = ELFNote();
595     if (!note.Parse(segment, &offset))
596       return llvm::make_error<llvm::StringError>(
597           "Unable to parse note segment", llvm::inconvertibleErrorCode());
598 
599     size_t note_start = offset;
600     size_t note_size = llvm::alignTo(note.n_descsz, 4);
601 
602     result.push_back({note, DataExtractor(segment, note_start, note_size)});
603     offset += note_size;
604   }
605 
606   return std::move(result);
607 }
608 
609 llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
610   ArchSpec arch = GetArchitecture();
611   bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
612                arch.GetMachine() == llvm::Triple::mips64 ||
613                arch.GetMachine() == llvm::Triple::ppc64 ||
614                arch.GetMachine() == llvm::Triple::x86_64);
615   bool have_prstatus = false;
616   bool have_prpsinfo = false;
617   ThreadData thread_data;
618   for (const auto &note : notes) {
619     if (note.info.n_name != "FreeBSD")
620       continue;
621 
622     if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
623         (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
624       assert(thread_data.gpregset.GetByteSize() > 0);
625       // Add the new thread to thread list
626       m_thread_data.push_back(thread_data);
627       thread_data = ThreadData();
628       have_prstatus = false;
629       have_prpsinfo = false;
630     }
631 
632     switch (note.info.n_type) {
633     case ELF::NT_PRSTATUS:
634       have_prstatus = true;
635       ParseFreeBSDPrStatus(thread_data, note.data, lp64);
636       break;
637     case ELF::NT_PRPSINFO:
638       have_prpsinfo = true;
639       ParseFreeBSDPrPsInfo(*this, note.data, lp64);
640       break;
641     case ELF::NT_FREEBSD_THRMISC: {
642       lldb::offset_t offset = 0;
643       thread_data.name = note.data.GetCStr(&offset, 20);
644       break;
645     }
646     case ELF::NT_FREEBSD_PROCSTAT_AUXV:
647       // FIXME: FreeBSD sticks an int at the beginning of the note
648       m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
649       break;
650     default:
651       thread_data.notes.push_back(note);
652       break;
653     }
654   }
655   if (!have_prstatus) {
656     return llvm::make_error<llvm::StringError>(
657         "Could not find NT_PRSTATUS note in core file.",
658         llvm::inconvertibleErrorCode());
659   }
660   m_thread_data.push_back(thread_data);
661   return llvm::Error::success();
662 }
663 
664 /// NetBSD specific Thread context from PT_NOTE segment
665 ///
666 /// NetBSD ELF core files use notes to provide information about
667 /// the process's state.  The note name is "NetBSD-CORE" for
668 /// information that is global to the process, and "NetBSD-CORE@nn",
669 /// where "nn" is the lwpid of the LWP that the information belongs
670 /// to (such as register state).
671 ///
672 /// NetBSD uses the following note identifiers:
673 ///
674 ///      ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
675 ///             Note is a "netbsd_elfcore_procinfo" structure.
676 ///      ELF_NOTE_NETBSD_CORE_AUXV     (value 2; since NetBSD 8.0)
677 ///             Note is an array of AuxInfo structures.
678 ///
679 /// NetBSD also uses ptrace(2) request numbers (the ones that exist in
680 /// machine-dependent space) to identify register info notes.  The
681 /// info in such notes is in the same format that ptrace(2) would
682 /// export that information.
683 ///
684 /// For more information see /usr/include/sys/exec_elf.h
685 ///
686 llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
687   ThreadData thread_data;
688   bool had_nt_regs = false;
689 
690   // To be extracted from struct netbsd_elfcore_procinfo
691   // Used to sanity check of the LWPs of the process
692   uint32_t nlwps = 0;
693   uint32_t signo = 0;  // killing signal
694   uint32_t siglwp = 0; // LWP target of killing signal
695   uint32_t pr_pid = 0;
696 
697   for (const auto &note : notes) {
698     llvm::StringRef name = note.info.n_name;
699 
700     if (name == "NetBSD-CORE") {
701       if (note.info.n_type == NETBSD::NT_PROCINFO) {
702         llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
703                                                 siglwp, pr_pid);
704         if (error)
705           return error;
706         SetID(pr_pid);
707       } else if (note.info.n_type == NETBSD::NT_AUXV) {
708         m_auxv = note.data;
709       }
710     } else if (name.consume_front("NetBSD-CORE@")) {
711       lldb::tid_t tid;
712       if (name.getAsInteger(10, tid))
713         return llvm::make_error<llvm::StringError>(
714             "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
715             "to integer",
716             llvm::inconvertibleErrorCode());
717 
718       switch (GetArchitecture().GetMachine()) {
719       case llvm::Triple::aarch64: {
720         // Assume order PT_GETREGS, PT_GETFPREGS
721         if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
722           // If this is the next thread, push the previous one first.
723           if (had_nt_regs) {
724             m_thread_data.push_back(thread_data);
725             thread_data = ThreadData();
726             had_nt_regs = false;
727           }
728 
729           thread_data.gpregset = note.data;
730           thread_data.tid = tid;
731           if (thread_data.gpregset.GetByteSize() == 0)
732             return llvm::make_error<llvm::StringError>(
733                 "Could not find general purpose registers note in core file.",
734                 llvm::inconvertibleErrorCode());
735           had_nt_regs = true;
736         } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
737           if (!had_nt_regs || tid != thread_data.tid)
738             return llvm::make_error<llvm::StringError>(
739                 "Error parsing NetBSD core(5) notes: Unexpected order "
740                 "of NOTEs PT_GETFPREG before PT_GETREG",
741                 llvm::inconvertibleErrorCode());
742           thread_data.notes.push_back(note);
743         }
744       } break;
745       case llvm::Triple::x86: {
746         // Assume order PT_GETREGS, PT_GETFPREGS
747         if (note.info.n_type == NETBSD::I386::NT_REGS) {
748           // If this is the next thread, push the previous one first.
749           if (had_nt_regs) {
750             m_thread_data.push_back(thread_data);
751             thread_data = ThreadData();
752             had_nt_regs = false;
753           }
754 
755           thread_data.gpregset = note.data;
756           thread_data.tid = tid;
757           if (thread_data.gpregset.GetByteSize() == 0)
758             return llvm::make_error<llvm::StringError>(
759                 "Could not find general purpose registers note in core file.",
760                 llvm::inconvertibleErrorCode());
761           had_nt_regs = true;
762         } else if (note.info.n_type == NETBSD::I386::NT_FPREGS) {
763           if (!had_nt_regs || tid != thread_data.tid)
764             return llvm::make_error<llvm::StringError>(
765                 "Error parsing NetBSD core(5) notes: Unexpected order "
766                 "of NOTEs PT_GETFPREG before PT_GETREG",
767                 llvm::inconvertibleErrorCode());
768           thread_data.notes.push_back(note);
769         }
770       } break;
771       case llvm::Triple::x86_64: {
772         // Assume order PT_GETREGS, PT_GETFPREGS
773         if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
774           // If this is the next thread, push the previous one first.
775           if (had_nt_regs) {
776             m_thread_data.push_back(thread_data);
777             thread_data = ThreadData();
778             had_nt_regs = false;
779           }
780 
781           thread_data.gpregset = note.data;
782           thread_data.tid = tid;
783           if (thread_data.gpregset.GetByteSize() == 0)
784             return llvm::make_error<llvm::StringError>(
785                 "Could not find general purpose registers note in core file.",
786                 llvm::inconvertibleErrorCode());
787           had_nt_regs = true;
788         } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
789           if (!had_nt_regs || tid != thread_data.tid)
790             return llvm::make_error<llvm::StringError>(
791                 "Error parsing NetBSD core(5) notes: Unexpected order "
792                 "of NOTEs PT_GETFPREG before PT_GETREG",
793                 llvm::inconvertibleErrorCode());
794           thread_data.notes.push_back(note);
795         }
796       } break;
797       default:
798         break;
799       }
800     }
801   }
802 
803   // Push the last thread.
804   if (had_nt_regs)
805     m_thread_data.push_back(thread_data);
806 
807   if (m_thread_data.empty())
808     return llvm::make_error<llvm::StringError>(
809         "Error parsing NetBSD core(5) notes: No threads information "
810         "specified in notes",
811         llvm::inconvertibleErrorCode());
812 
813   if (m_thread_data.size() != nlwps)
814     return llvm::make_error<llvm::StringError>(
815         "Error parsing NetBSD core(5) notes: Mismatch between the number "
816         "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
817         "by MD notes",
818         llvm::inconvertibleErrorCode());
819 
820   // Signal targeted at the whole process.
821   if (siglwp == 0) {
822     for (auto &data : m_thread_data)
823       data.signo = signo;
824   }
825   // Signal destined for a particular LWP.
826   else {
827     bool passed = false;
828 
829     for (auto &data : m_thread_data) {
830       if (data.tid == siglwp) {
831         data.signo = signo;
832         passed = true;
833         break;
834       }
835     }
836 
837     if (!passed)
838       return llvm::make_error<llvm::StringError>(
839           "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP",
840           llvm::inconvertibleErrorCode());
841   }
842 
843   return llvm::Error::success();
844 }
845 
846 llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
847   ThreadData thread_data = {};
848   for (const auto &note : notes) {
849     // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
850     // match on the initial part of the string.
851     if (!llvm::StringRef(note.info.n_name).starts_with("OpenBSD"))
852       continue;
853 
854     switch (note.info.n_type) {
855     case OPENBSD::NT_PROCINFO:
856       ParseOpenBSDProcInfo(thread_data, note.data);
857       break;
858     case OPENBSD::NT_AUXV:
859       m_auxv = note.data;
860       break;
861     case OPENBSD::NT_REGS:
862       thread_data.gpregset = note.data;
863       break;
864     default:
865       thread_data.notes.push_back(note);
866       break;
867     }
868   }
869   if (thread_data.gpregset.GetByteSize() == 0) {
870     return llvm::make_error<llvm::StringError>(
871         "Could not find general purpose registers note in core file.",
872         llvm::inconvertibleErrorCode());
873   }
874   m_thread_data.push_back(thread_data);
875   return llvm::Error::success();
876 }
877 
878 /// A description of a linux process usually contains the following NOTE
879 /// entries:
880 /// - NT_PRPSINFO - General process information like pid, uid, name, ...
881 /// - NT_SIGINFO - Information about the signal that terminated the process
882 /// - NT_AUXV - Process auxiliary vector
883 /// - NT_FILE - Files mapped into memory
884 ///
885 /// Additionally, for each thread in the process the core file will contain at
886 /// least the NT_PRSTATUS note, containing the thread id and general purpose
887 /// registers. It may include additional notes for other register sets (floating
888 /// point and vector registers, ...). The tricky part here is that some of these
889 /// notes have "CORE" in their owner fields, while other set it to "LINUX".
890 llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
891   const ArchSpec &arch = GetArchitecture();
892   bool have_prstatus = false;
893   bool have_prpsinfo = false;
894   ThreadData thread_data;
895   for (const auto &note : notes) {
896     if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
897       continue;
898 
899     if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
900         (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
901       assert(thread_data.gpregset.GetByteSize() > 0);
902       // Add the new thread to thread list
903       m_thread_data.push_back(thread_data);
904       thread_data = ThreadData();
905       have_prstatus = false;
906       have_prpsinfo = false;
907     }
908 
909     switch (note.info.n_type) {
910     case ELF::NT_PRSTATUS: {
911       have_prstatus = true;
912       ELFLinuxPrStatus prstatus;
913       Status status = prstatus.Parse(note.data, arch);
914       if (status.Fail())
915         return status.ToError();
916       thread_data.prstatus_sig = prstatus.pr_cursig;
917       thread_data.tid = prstatus.pr_pid;
918       uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
919       size_t len = note.data.GetByteSize() - header_size;
920       thread_data.gpregset = DataExtractor(note.data, header_size, len);
921       break;
922     }
923     case ELF::NT_PRPSINFO: {
924       have_prpsinfo = true;
925       ELFLinuxPrPsInfo prpsinfo;
926       Status status = prpsinfo.Parse(note.data, arch);
927       if (status.Fail())
928         return status.ToError();
929       thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
930       SetID(prpsinfo.pr_pid);
931       break;
932     }
933     case ELF::NT_SIGINFO: {
934       ELFLinuxSigInfo siginfo;
935       Status status = siginfo.Parse(note.data, arch);
936       if (status.Fail())
937         return status.ToError();
938       thread_data.signo = siginfo.si_signo;
939       thread_data.code = siginfo.si_code;
940       break;
941     }
942     case ELF::NT_FILE: {
943       m_nt_file_entries.clear();
944       lldb::offset_t offset = 0;
945       const uint64_t count = note.data.GetAddress(&offset);
946       note.data.GetAddress(&offset); // Skip page size
947       for (uint64_t i = 0; i < count; ++i) {
948         NT_FILE_Entry entry;
949         entry.start = note.data.GetAddress(&offset);
950         entry.end = note.data.GetAddress(&offset);
951         entry.file_ofs = note.data.GetAddress(&offset);
952         m_nt_file_entries.push_back(entry);
953       }
954       for (uint64_t i = 0; i < count; ++i) {
955         const char *path = note.data.GetCStr(&offset);
956         if (path && path[0])
957           m_nt_file_entries[i].path.assign(path);
958       }
959       break;
960     }
961     case ELF::NT_AUXV:
962       m_auxv = note.data;
963       break;
964     default:
965       thread_data.notes.push_back(note);
966       break;
967     }
968   }
969   // Add last entry in the note section
970   if (have_prstatus)
971     m_thread_data.push_back(thread_data);
972   return llvm::Error::success();
973 }
974 
975 /// Parse Thread context from PT_NOTE segment and store it in the thread list
976 /// A note segment consists of one or more NOTE entries, but their types and
977 /// meaning differ depending on the OS.
978 llvm::Error ProcessElfCore::ParseThreadContextsFromNoteSegment(
979     const elf::ELFProgramHeader &segment_header,
980     const DataExtractor &segment_data) {
981   assert(segment_header.p_type == llvm::ELF::PT_NOTE);
982 
983   auto notes_or_error = parseSegment(segment_data);
984   if(!notes_or_error)
985     return notes_or_error.takeError();
986   switch (GetArchitecture().GetTriple().getOS()) {
987   case llvm::Triple::FreeBSD:
988     return parseFreeBSDNotes(*notes_or_error);
989   case llvm::Triple::Linux:
990     return parseLinuxNotes(*notes_or_error);
991   case llvm::Triple::NetBSD:
992     return parseNetBSDNotes(*notes_or_error);
993   case llvm::Triple::OpenBSD:
994     return parseOpenBSDNotes(*notes_or_error);
995   default:
996     return llvm::make_error<llvm::StringError>(
997         "Don't know how to parse core file. Unsupported OS.",
998         llvm::inconvertibleErrorCode());
999   }
1000 }
1001 
1002 bool ProcessElfCore::IsElf(const NT_FILE_Entry entry) {
1003   size_t size = strlen(llvm::ELF::ElfMagic);
1004   uint8_t buf[size];
1005   Status error;
1006   size_t byte_read = ReadMemory(entry.start, buf, size, error);
1007   if (byte_read == size)
1008     return memcmp(llvm::ELF::ElfMagic, buf, size) == 0;
1009   else
1010     return false;
1011 }
1012 
1013 std::optional<UUID> ProcessElfCore::FindBuildId(const NT_FILE_Entry entry) {
1014   if (!IsElf(entry))
1015     return std::nullopt;
1016   // Build ID is stored in the ELF file as a section named ".note.gnu.build-id"
1017   uint8_t gnu_build_id_bytes[8] = {0x03, 0x00, 0x00, 0x00,
1018                                    0x47, 0x4e, 0x55, 0x00};
1019   lldb::addr_t gnu_build_id_addr =
1020       FindInMemory(entry.start, entry.end, gnu_build_id_bytes, 8);
1021   if (gnu_build_id_addr == LLDB_INVALID_ADDRESS)
1022     return std::nullopt;
1023   uint8_t buf[36];
1024   Status error;
1025   size_t byte_read = ReadMemory(gnu_build_id_addr - 8, buf, 36, error);
1026   // .note.gnu.build-id starts with 04 00 00 00 {id_byte_size} 00 00 00 03 00 00
1027   // 00 47 4e 55 00
1028   if (byte_read == 36) {
1029     if (buf[0] == 0x04) {
1030       return UUID(llvm::ArrayRef<uint8_t>(buf + 16, buf[4] /*byte size*/));
1031     }
1032   }
1033   return std::nullopt;
1034 }
1035 
1036 uint32_t ProcessElfCore::GetNumThreadContexts() {
1037   if (!m_thread_data_valid)
1038     DoLoadCore();
1039   return m_thread_data.size();
1040 }
1041 
1042 ArchSpec ProcessElfCore::GetArchitecture() {
1043   ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
1044 
1045   ArchSpec target_arch = GetTarget().GetArchitecture();
1046   arch.MergeFrom(target_arch);
1047 
1048   // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
1049   // files and this information can't be merged in from the target arch so we
1050   // fail back to unconditionally returning the target arch in this config.
1051   if (target_arch.IsMIPS()) {
1052     return target_arch;
1053   }
1054 
1055   return arch;
1056 }
1057 
1058 DataExtractor ProcessElfCore::GetAuxvData() {
1059   const uint8_t *start = m_auxv.GetDataStart();
1060   size_t len = m_auxv.GetByteSize();
1061   lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
1062   return DataExtractor(buffer, GetByteOrder(), GetAddressByteSize());
1063 }
1064 
1065 bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
1066   info.Clear();
1067   info.SetProcessID(GetID());
1068   info.SetArchitecture(GetArchitecture());
1069   lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
1070   if (module_sp) {
1071     const bool add_exe_file_as_first_arg = false;
1072     info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
1073                            add_exe_file_as_first_arg);
1074   }
1075   return true;
1076 }
1077