1 //===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <stdlib.h>
10 
11 #include <memory>
12 #include <mutex>
13 
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"
25 
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/Support/Threading.h"
28 
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"
34 
35 using namespace lldb_private;
36 namespace ELF = llvm::ELF;
37 
38 ConstString ProcessElfCore::GetPluginNameStatic() {
39   static ConstString g_name("elf-core");
40   return g_name;
41 }
42 
43 const char *ProcessElfCore::GetPluginDescriptionStatic() {
44   return "ELF core dump plug-in.";
45 }
46 
47 void ProcessElfCore::Terminate() {
48   PluginManager::UnregisterPlugin(ProcessElfCore::CreateInstance);
49 }
50 
51 lldb::ProcessSP ProcessElfCore::CreateInstance(lldb::TargetSP target_sp,
52                                                lldb::ListenerSP listener_sp,
53                                                const FileSpec *crash_file) {
54   lldb::ProcessSP process_sp;
55   if (crash_file) {
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);
60 
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,
71                                                         *crash_file);
72       }
73     }
74   }
75   return process_sp;
76 }
77 
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)
88         return true;
89     }
90   }
91   return false;
92 }
93 
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) {}
99 
100 // Destructor
101 ProcessElfCore::~ProcessElfCore() {
102   Clear();
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.
107   Finalize();
108 }
109 
110 // PluginInterface
111 ConstString ProcessElfCore::GetPluginName() { return GetPluginNameStatic(); }
112 
113 uint32_t ProcessElfCore::GetPluginVersion() { return 1; }
114 
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);
120 
121   VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
122   if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
123       last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
124       last_entry->GetByteSize() == last_entry->data.GetByteSize()) {
125     last_entry->SetRangeEnd(range_entry.GetRangeEnd());
126     last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
127   } else {
128     m_core_aranges.Append(range_entry);
129   }
130 
131   // Keep a separate map of permissions that that isn't coalesced so all ranges
132   // are maintained.
133   const uint32_t permissions =
134       ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) |
135       ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) |
136       ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u);
137 
138   m_core_range_infos.Append(
139       VMRangeToPermissions::Entry(addr, header.p_memsz, permissions));
140 
141   return addr;
142 }
143 
144 // Process Control
145 Status ProcessElfCore::DoLoadCore() {
146   Status error;
147   if (!m_core_module_sp) {
148     error.SetErrorString("invalid core module");
149     return error;
150   }
151 
152   ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
153   if (core == nullptr) {
154     error.SetErrorString("invalid core object file");
155     return error;
156   }
157 
158   llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders();
159   if (segments.size() == 0) {
160     error.SetErrorString("core file has no segments");
161     return error;
162   }
163 
164   SetCanJIT(false);
165 
166   m_thread_data_valid = true;
167 
168   bool ranges_are_sorted = true;
169   lldb::addr_t vm_addr = 0;
170   /// Walk through segments and Thread and Address Map information.
171   /// PT_NOTE - Contains Thread and Register information
172   /// PT_LOAD - Contains a contiguous range of Process Address Space
173   for (const elf::ELFProgramHeader &H : segments) {
174     DataExtractor data = core->GetSegmentData(H);
175 
176     // Parse thread contexts and auxv structure
177     if (H.p_type == llvm::ELF::PT_NOTE) {
178       if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data))
179         return Status(std::move(error));
180     }
181     // PT_LOAD segments contains address map
182     if (H.p_type == llvm::ELF::PT_LOAD) {
183       lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(H);
184       if (vm_addr > last_addr)
185         ranges_are_sorted = false;
186       vm_addr = last_addr;
187     }
188   }
189 
190   if (!ranges_are_sorted) {
191     m_core_aranges.Sort();
192     m_core_range_infos.Sort();
193   }
194 
195   // Even if the architecture is set in the target, we need to override it to
196   // match the core file which is always single arch.
197   ArchSpec arch(m_core_module_sp->GetArchitecture());
198 
199   ArchSpec target_arch = GetTarget().GetArchitecture();
200   ArchSpec core_arch(m_core_module_sp->GetArchitecture());
201   target_arch.MergeFrom(core_arch);
202   GetTarget().SetArchitecture(target_arch);
203 
204   SetUnixSignals(UnixSignals::Create(GetArchitecture()));
205 
206   // Ensure we found at least one thread that was stopped on a signal.
207   bool siginfo_signal_found = false;
208   bool prstatus_signal_found = false;
209   // Check we found a signal in a SIGINFO note.
210   for (const auto &thread_data : m_thread_data) {
211     if (thread_data.signo != 0)
212       siginfo_signal_found = true;
213     if (thread_data.prstatus_sig != 0)
214       prstatus_signal_found = true;
215   }
216   if (!siginfo_signal_found) {
217     // If we don't have signal from SIGINFO use the signal from each threads
218     // PRSTATUS note.
219     if (prstatus_signal_found) {
220       for (auto &thread_data : m_thread_data)
221         thread_data.signo = thread_data.prstatus_sig;
222     } else if (m_thread_data.size() > 0) {
223       // If all else fails force the first thread to be SIGSTOP
224       m_thread_data.begin()->signo =
225           GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
226     }
227   }
228 
229   // Core files are useless without the main executable. See if we can locate
230   // the main executable using data we found in the core file notes.
231   lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
232   if (!exe_module_sp) {
233     // The first entry in the NT_FILE might be our executable
234     if (!m_nt_file_entries.empty()) {
235       ModuleSpec exe_module_spec;
236       exe_module_spec.GetArchitecture() = arch;
237       exe_module_spec.GetFileSpec().SetFile(
238           m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native);
239       if (exe_module_spec.GetFileSpec()) {
240         exe_module_sp = GetTarget().GetOrCreateModule(exe_module_spec,
241                                                       true /* notify */);
242         if (exe_module_sp)
243           GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo);
244       }
245     }
246   }
247   return error;
248 }
249 
250 lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() {
251   if (m_dyld_up.get() == nullptr)
252     m_dyld_up.reset(DynamicLoader::FindPlugin(
253         this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString()));
254   return m_dyld_up.get();
255 }
256 
257 bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list,
258                                       ThreadList &new_thread_list) {
259   const uint32_t num_threads = GetNumThreadContexts();
260   if (!m_thread_data_valid)
261     return false;
262 
263   for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
264     const ThreadData &td = m_thread_data[tid];
265     lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
266     new_thread_list.AddThread(thread_sp);
267   }
268   return new_thread_list.GetSize(false) > 0;
269 }
270 
271 void ProcessElfCore::RefreshStateAfterStop() {}
272 
273 Status ProcessElfCore::DoDestroy() { return Status(); }
274 
275 // Process Queries
276 
277 bool ProcessElfCore::IsAlive() { return true; }
278 
279 // Process Memory
280 size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
281                                   Status &error) {
282   // Don't allow the caching that lldb_private::Process::ReadMemory does since
283   // in core files we have it all cached our our core file anyway.
284   return DoReadMemory(addr, buf, size, error);
285 }
286 
287 Status ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr,
288                                            MemoryRegionInfo &region_info) {
289   region_info.Clear();
290   const VMRangeToPermissions::Entry *permission_entry =
291       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
292   if (permission_entry) {
293     if (permission_entry->Contains(load_addr)) {
294       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
295       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
296       const Flags permissions(permission_entry->data);
297       region_info.SetReadable(permissions.Test(lldb::ePermissionsReadable)
298                                   ? MemoryRegionInfo::eYes
299                                   : MemoryRegionInfo::eNo);
300       region_info.SetWritable(permissions.Test(lldb::ePermissionsWritable)
301                                   ? MemoryRegionInfo::eYes
302                                   : MemoryRegionInfo::eNo);
303       region_info.SetExecutable(permissions.Test(lldb::ePermissionsExecutable)
304                                     ? MemoryRegionInfo::eYes
305                                     : MemoryRegionInfo::eNo);
306       region_info.SetMapped(MemoryRegionInfo::eYes);
307     } else if (load_addr < permission_entry->GetRangeBase()) {
308       region_info.GetRange().SetRangeBase(load_addr);
309       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
310       region_info.SetReadable(MemoryRegionInfo::eNo);
311       region_info.SetWritable(MemoryRegionInfo::eNo);
312       region_info.SetExecutable(MemoryRegionInfo::eNo);
313       region_info.SetMapped(MemoryRegionInfo::eNo);
314     }
315     return Status();
316   }
317 
318   region_info.GetRange().SetRangeBase(load_addr);
319   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
320   region_info.SetReadable(MemoryRegionInfo::eNo);
321   region_info.SetWritable(MemoryRegionInfo::eNo);
322   region_info.SetExecutable(MemoryRegionInfo::eNo);
323   region_info.SetMapped(MemoryRegionInfo::eNo);
324   return Status();
325 }
326 
327 size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
328                                     Status &error) {
329   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
330 
331   if (core_objfile == nullptr)
332     return 0;
333 
334   // Get the address range
335   const VMRangeToFileOffset::Entry *address_range =
336       m_core_aranges.FindEntryThatContains(addr);
337   if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
338     error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64,
339                                    addr);
340     return 0;
341   }
342 
343   // Convert the address into core file offset
344   const lldb::addr_t offset = addr - address_range->GetRangeBase();
345   const lldb::addr_t file_start = address_range->data.GetRangeBase();
346   const lldb::addr_t file_end = address_range->data.GetRangeEnd();
347   size_t bytes_to_read = size; // Number of bytes to read from the core file
348   size_t bytes_copied = 0;   // Number of bytes actually read from the core file
349   size_t zero_fill_size = 0; // Padding
350   lldb::addr_t bytes_left =
351       0; // Number of bytes available in the core file from the given address
352 
353   // Don't proceed if core file doesn't contain the actual data for this
354   // address range.
355   if (file_start == file_end)
356     return 0;
357 
358   // Figure out how many on-disk bytes remain in this segment starting at the
359   // given offset
360   if (file_end > file_start + offset)
361     bytes_left = file_end - (file_start + offset);
362 
363   // Figure out how many bytes we need to zero-fill if we are reading more
364   // bytes than available in the on-disk segment
365   if (bytes_to_read > bytes_left) {
366     zero_fill_size = bytes_to_read - bytes_left;
367     bytes_to_read = bytes_left;
368   }
369 
370   // If there is data available on the core file read it
371   if (bytes_to_read)
372     bytes_copied =
373         core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
374 
375   assert(zero_fill_size <= size);
376   // Pad remaining bytes
377   if (zero_fill_size)
378     memset(((char *)buf) + bytes_copied, 0, zero_fill_size);
379 
380   return bytes_copied + zero_fill_size;
381 }
382 
383 void ProcessElfCore::Clear() {
384   m_thread_list.Clear();
385 
386   SetUnixSignals(std::make_shared<UnixSignals>());
387 }
388 
389 void ProcessElfCore::Initialize() {
390   static llvm::once_flag g_once_flag;
391 
392   llvm::call_once(g_once_flag, []() {
393     PluginManager::RegisterPlugin(GetPluginNameStatic(),
394                                   GetPluginDescriptionStatic(), CreateInstance);
395   });
396 }
397 
398 lldb::addr_t ProcessElfCore::GetImageInfoAddress() {
399   ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
400   Address addr = obj_file->GetImageInfoAddress(&GetTarget());
401 
402   if (addr.IsValid())
403     return addr.GetLoadAddress(&GetTarget());
404   return LLDB_INVALID_ADDRESS;
405 }
406 
407 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
408 static void ParseFreeBSDPrStatus(ThreadData &thread_data,
409                                  const DataExtractor &data,
410                                  const ArchSpec &arch) {
411   lldb::offset_t offset = 0;
412   bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
413                arch.GetMachine() == llvm::Triple::mips64 ||
414                arch.GetMachine() == llvm::Triple::ppc64 ||
415                arch.GetMachine() == llvm::Triple::x86_64);
416   int pr_version = data.GetU32(&offset);
417 
418   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
419   if (log) {
420     if (pr_version > 1)
421       LLDB_LOGF(log, "FreeBSD PRSTATUS unexpected version %d", pr_version);
422   }
423 
424   // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
425   if (lp64)
426     offset += 32;
427   else
428     offset += 16;
429 
430   thread_data.signo = data.GetU32(&offset); // pr_cursig
431   thread_data.tid = data.GetU32(&offset);   // pr_pid
432   if (lp64)
433     offset += 4;
434 
435   size_t len = data.GetByteSize() - offset;
436   thread_data.gpregset = DataExtractor(data, offset, len);
437 }
438 
439 static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
440                                        uint32_t &cpi_nlwps,
441                                        uint32_t &cpi_signo,
442                                        uint32_t &cpi_siglwp,
443                                        uint32_t &cpi_pid) {
444   lldb::offset_t offset = 0;
445 
446   uint32_t version = data.GetU32(&offset);
447   if (version != 1)
448     return llvm::make_error<llvm::StringError>(
449         "Error parsing NetBSD core(5) notes: Unsupported procinfo version",
450         llvm::inconvertibleErrorCode());
451 
452   uint32_t cpisize = data.GetU32(&offset);
453   if (cpisize != NETBSD::NT_PROCINFO_SIZE)
454     return llvm::make_error<llvm::StringError>(
455         "Error parsing NetBSD core(5) notes: Unsupported procinfo size",
456         llvm::inconvertibleErrorCode());
457 
458   cpi_signo = data.GetU32(&offset); /* killing signal */
459 
460   offset += NETBSD::NT_PROCINFO_CPI_SIGCODE_SIZE;
461   offset += NETBSD::NT_PROCINFO_CPI_SIGPEND_SIZE;
462   offset += NETBSD::NT_PROCINFO_CPI_SIGMASK_SIZE;
463   offset += NETBSD::NT_PROCINFO_CPI_SIGIGNORE_SIZE;
464   offset += NETBSD::NT_PROCINFO_CPI_SIGCATCH_SIZE;
465   cpi_pid = data.GetU32(&offset);
466   offset += NETBSD::NT_PROCINFO_CPI_PPID_SIZE;
467   offset += NETBSD::NT_PROCINFO_CPI_PGRP_SIZE;
468   offset += NETBSD::NT_PROCINFO_CPI_SID_SIZE;
469   offset += NETBSD::NT_PROCINFO_CPI_RUID_SIZE;
470   offset += NETBSD::NT_PROCINFO_CPI_EUID_SIZE;
471   offset += NETBSD::NT_PROCINFO_CPI_SVUID_SIZE;
472   offset += NETBSD::NT_PROCINFO_CPI_RGID_SIZE;
473   offset += NETBSD::NT_PROCINFO_CPI_EGID_SIZE;
474   offset += NETBSD::NT_PROCINFO_CPI_SVGID_SIZE;
475   cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
476 
477   offset += NETBSD::NT_PROCINFO_CPI_NAME_SIZE;
478   cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
479 
480   return llvm::Error::success();
481 }
482 
483 static void ParseOpenBSDProcInfo(ThreadData &thread_data,
484                                  const DataExtractor &data) {
485   lldb::offset_t offset = 0;
486 
487   int version = data.GetU32(&offset);
488   if (version != 1)
489     return;
490 
491   offset += 4;
492   thread_data.signo = data.GetU32(&offset);
493 }
494 
495 llvm::Expected<std::vector<CoreNote>>
496 ProcessElfCore::parseSegment(const DataExtractor &segment) {
497   lldb::offset_t offset = 0;
498   std::vector<CoreNote> result;
499 
500   while (offset < segment.GetByteSize()) {
501     ELFNote note = ELFNote();
502     if (!note.Parse(segment, &offset))
503       return llvm::make_error<llvm::StringError>(
504           "Unable to parse note segment", llvm::inconvertibleErrorCode());
505 
506     size_t note_start = offset;
507     size_t note_size = llvm::alignTo(note.n_descsz, 4);
508     DataExtractor note_data(segment, note_start, note_size);
509 
510     result.push_back({note, note_data});
511     offset += note_size;
512   }
513 
514   return std::move(result);
515 }
516 
517 llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
518   bool have_prstatus = false;
519   bool have_prpsinfo = false;
520   ThreadData thread_data;
521   for (const auto &note : notes) {
522     if (note.info.n_name != "FreeBSD")
523       continue;
524 
525     if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
526         (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
527       assert(thread_data.gpregset.GetByteSize() > 0);
528       // Add the new thread to thread list
529       m_thread_data.push_back(thread_data);
530       thread_data = ThreadData();
531       have_prstatus = false;
532       have_prpsinfo = false;
533     }
534 
535     switch (note.info.n_type) {
536     case ELF::NT_PRSTATUS:
537       have_prstatus = true;
538       ParseFreeBSDPrStatus(thread_data, note.data, GetArchitecture());
539       break;
540     case ELF::NT_PRPSINFO:
541       have_prpsinfo = true;
542       break;
543     case ELF::NT_FREEBSD_THRMISC: {
544       lldb::offset_t offset = 0;
545       thread_data.name = note.data.GetCStr(&offset, 20);
546       break;
547     }
548     case ELF::NT_FREEBSD_PROCSTAT_AUXV:
549       // FIXME: FreeBSD sticks an int at the beginning of the note
550       m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
551       break;
552     default:
553       thread_data.notes.push_back(note);
554       break;
555     }
556   }
557   if (!have_prstatus) {
558     return llvm::make_error<llvm::StringError>(
559         "Could not find NT_PRSTATUS note in core file.",
560         llvm::inconvertibleErrorCode());
561   }
562   m_thread_data.push_back(thread_data);
563   return llvm::Error::success();
564 }
565 
566 /// NetBSD specific Thread context from PT_NOTE segment
567 ///
568 /// NetBSD ELF core files use notes to provide information about
569 /// the process's state.  The note name is "NetBSD-CORE" for
570 /// information that is global to the process, and "NetBSD-CORE@nn",
571 /// where "nn" is the lwpid of the LWP that the information belongs
572 /// to (such as register state).
573 ///
574 /// NetBSD uses the following note identifiers:
575 ///
576 ///      ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
577 ///             Note is a "netbsd_elfcore_procinfo" structure.
578 ///      ELF_NOTE_NETBSD_CORE_AUXV     (value 2; since NetBSD 8.0)
579 ///             Note is an array of AuxInfo structures.
580 ///
581 /// NetBSD also uses ptrace(2) request numbers (the ones that exist in
582 /// machine-dependent space) to identify register info notes.  The
583 /// info in such notes is in the same format that ptrace(2) would
584 /// export that information.
585 ///
586 /// For more information see /usr/include/sys/exec_elf.h
587 ///
588 llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
589   ThreadData thread_data;
590   bool had_nt_regs = false;
591 
592   // To be extracted from struct netbsd_elfcore_procinfo
593   // Used to sanity check of the LWPs of the process
594   uint32_t nlwps = 0;
595   uint32_t signo;  // killing signal
596   uint32_t siglwp; // LWP target of killing signal
597   uint32_t pr_pid;
598 
599   for (const auto &note : notes) {
600     llvm::StringRef name = note.info.n_name;
601 
602     if (name == "NetBSD-CORE") {
603       if (note.info.n_type == NETBSD::NT_PROCINFO) {
604         llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
605                                                 siglwp, pr_pid);
606         if (error)
607           return error;
608         SetID(pr_pid);
609       } else if (note.info.n_type == NETBSD::NT_AUXV) {
610         m_auxv = note.data;
611       }
612     } else if (name.consume_front("NetBSD-CORE@")) {
613       lldb::tid_t tid;
614       if (name.getAsInteger(10, tid))
615         return llvm::make_error<llvm::StringError>(
616             "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
617             "to integer",
618             llvm::inconvertibleErrorCode());
619 
620       switch (GetArchitecture().GetMachine()) {
621       case llvm::Triple::aarch64: {
622         // Assume order PT_GETREGS, PT_GETFPREGS
623         if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
624           // If this is the next thread, push the previous one first.
625           if (had_nt_regs) {
626             m_thread_data.push_back(thread_data);
627             thread_data = ThreadData();
628             had_nt_regs = false;
629           }
630 
631           thread_data.gpregset = note.data;
632           thread_data.tid = tid;
633           if (thread_data.gpregset.GetByteSize() == 0)
634             return llvm::make_error<llvm::StringError>(
635                 "Could not find general purpose registers note in core file.",
636                 llvm::inconvertibleErrorCode());
637           had_nt_regs = true;
638         } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
639           if (!had_nt_regs || tid != thread_data.tid)
640             return llvm::make_error<llvm::StringError>(
641                 "Error parsing NetBSD core(5) notes: Unexpected order "
642                 "of NOTEs PT_GETFPREG before PT_GETREG",
643                 llvm::inconvertibleErrorCode());
644           thread_data.notes.push_back(note);
645         }
646       } break;
647       case llvm::Triple::x86_64: {
648         // Assume order PT_GETREGS, PT_GETFPREGS
649         if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
650           // If this is the next thread, push the previous one first.
651           if (had_nt_regs) {
652             m_thread_data.push_back(thread_data);
653             thread_data = ThreadData();
654             had_nt_regs = false;
655           }
656 
657           thread_data.gpregset = note.data;
658           thread_data.tid = tid;
659           if (thread_data.gpregset.GetByteSize() == 0)
660             return llvm::make_error<llvm::StringError>(
661                 "Could not find general purpose registers note in core file.",
662                 llvm::inconvertibleErrorCode());
663           had_nt_regs = true;
664         } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
665           if (!had_nt_regs || tid != thread_data.tid)
666             return llvm::make_error<llvm::StringError>(
667                 "Error parsing NetBSD core(5) notes: Unexpected order "
668                 "of NOTEs PT_GETFPREG before PT_GETREG",
669                 llvm::inconvertibleErrorCode());
670           thread_data.notes.push_back(note);
671         }
672       } break;
673       default:
674         break;
675       }
676     }
677   }
678 
679   // Push the last thread.
680   if (had_nt_regs)
681     m_thread_data.push_back(thread_data);
682 
683   if (m_thread_data.empty())
684     return llvm::make_error<llvm::StringError>(
685         "Error parsing NetBSD core(5) notes: No threads information "
686         "specified in notes",
687         llvm::inconvertibleErrorCode());
688 
689   if (m_thread_data.size() != nlwps)
690     return llvm::make_error<llvm::StringError>(
691         "Error parsing NetBSD core(5) notes: Mismatch between the number "
692         "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
693         "by MD notes",
694         llvm::inconvertibleErrorCode());
695 
696   // Signal targeted at the whole process.
697   if (siglwp == 0) {
698     for (auto &data : m_thread_data)
699       data.signo = signo;
700   }
701   // Signal destined for a particular LWP.
702   else {
703     bool passed = false;
704 
705     for (auto &data : m_thread_data) {
706       if (data.tid == siglwp) {
707         data.signo = signo;
708         passed = true;
709         break;
710       }
711     }
712 
713     if (!passed)
714       return llvm::make_error<llvm::StringError>(
715           "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP",
716           llvm::inconvertibleErrorCode());
717   }
718 
719   return llvm::Error::success();
720 }
721 
722 llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
723   ThreadData thread_data;
724   for (const auto &note : notes) {
725     // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
726     // match on the initial part of the string.
727     if (!llvm::StringRef(note.info.n_name).startswith("OpenBSD"))
728       continue;
729 
730     switch (note.info.n_type) {
731     case OPENBSD::NT_PROCINFO:
732       ParseOpenBSDProcInfo(thread_data, note.data);
733       break;
734     case OPENBSD::NT_AUXV:
735       m_auxv = note.data;
736       break;
737     case OPENBSD::NT_REGS:
738       thread_data.gpregset = note.data;
739       break;
740     default:
741       thread_data.notes.push_back(note);
742       break;
743     }
744   }
745   if (thread_data.gpregset.GetByteSize() == 0) {
746     return llvm::make_error<llvm::StringError>(
747         "Could not find general purpose registers note in core file.",
748         llvm::inconvertibleErrorCode());
749   }
750   m_thread_data.push_back(thread_data);
751   return llvm::Error::success();
752 }
753 
754 /// A description of a linux process usually contains the following NOTE
755 /// entries:
756 /// - NT_PRPSINFO - General process information like pid, uid, name, ...
757 /// - NT_SIGINFO - Information about the signal that terminated the process
758 /// - NT_AUXV - Process auxiliary vector
759 /// - NT_FILE - Files mapped into memory
760 ///
761 /// Additionally, for each thread in the process the core file will contain at
762 /// least the NT_PRSTATUS note, containing the thread id and general purpose
763 /// registers. It may include additional notes for other register sets (floating
764 /// point and vector registers, ...). The tricky part here is that some of these
765 /// notes have "CORE" in their owner fields, while other set it to "LINUX".
766 llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
767   const ArchSpec &arch = GetArchitecture();
768   bool have_prstatus = false;
769   bool have_prpsinfo = false;
770   ThreadData thread_data;
771   for (const auto &note : notes) {
772     if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
773       continue;
774 
775     if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
776         (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
777       assert(thread_data.gpregset.GetByteSize() > 0);
778       // Add the new thread to thread list
779       m_thread_data.push_back(thread_data);
780       thread_data = ThreadData();
781       have_prstatus = false;
782       have_prpsinfo = false;
783     }
784 
785     switch (note.info.n_type) {
786     case ELF::NT_PRSTATUS: {
787       have_prstatus = true;
788       ELFLinuxPrStatus prstatus;
789       Status status = prstatus.Parse(note.data, arch);
790       if (status.Fail())
791         return status.ToError();
792       thread_data.prstatus_sig = prstatus.pr_cursig;
793       thread_data.tid = prstatus.pr_pid;
794       uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
795       size_t len = note.data.GetByteSize() - header_size;
796       thread_data.gpregset = DataExtractor(note.data, header_size, len);
797       break;
798     }
799     case ELF::NT_PRPSINFO: {
800       have_prpsinfo = true;
801       ELFLinuxPrPsInfo prpsinfo;
802       Status status = prpsinfo.Parse(note.data, arch);
803       if (status.Fail())
804         return status.ToError();
805       thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
806       SetID(prpsinfo.pr_pid);
807       break;
808     }
809     case ELF::NT_SIGINFO: {
810       ELFLinuxSigInfo siginfo;
811       Status status = siginfo.Parse(note.data, arch);
812       if (status.Fail())
813         return status.ToError();
814       thread_data.signo = siginfo.si_signo;
815       break;
816     }
817     case ELF::NT_FILE: {
818       m_nt_file_entries.clear();
819       lldb::offset_t offset = 0;
820       const uint64_t count = note.data.GetAddress(&offset);
821       note.data.GetAddress(&offset); // Skip page size
822       for (uint64_t i = 0; i < count; ++i) {
823         NT_FILE_Entry entry;
824         entry.start = note.data.GetAddress(&offset);
825         entry.end = note.data.GetAddress(&offset);
826         entry.file_ofs = note.data.GetAddress(&offset);
827         m_nt_file_entries.push_back(entry);
828       }
829       for (uint64_t i = 0; i < count; ++i) {
830         const char *path = note.data.GetCStr(&offset);
831         if (path && path[0])
832           m_nt_file_entries[i].path.SetCString(path);
833       }
834       break;
835     }
836     case ELF::NT_AUXV:
837       m_auxv = note.data;
838       break;
839     default:
840       thread_data.notes.push_back(note);
841       break;
842     }
843   }
844   // Add last entry in the note section
845   if (have_prstatus)
846     m_thread_data.push_back(thread_data);
847   return llvm::Error::success();
848 }
849 
850 /// Parse Thread context from PT_NOTE segment and store it in the thread list
851 /// A note segment consists of one or more NOTE entries, but their types and
852 /// meaning differ depending on the OS.
853 llvm::Error ProcessElfCore::ParseThreadContextsFromNoteSegment(
854     const elf::ELFProgramHeader &segment_header, DataExtractor segment_data) {
855   assert(segment_header.p_type == llvm::ELF::PT_NOTE);
856 
857   auto notes_or_error = parseSegment(segment_data);
858   if(!notes_or_error)
859     return notes_or_error.takeError();
860   switch (GetArchitecture().GetTriple().getOS()) {
861   case llvm::Triple::FreeBSD:
862     return parseFreeBSDNotes(*notes_or_error);
863   case llvm::Triple::Linux:
864     return parseLinuxNotes(*notes_or_error);
865   case llvm::Triple::NetBSD:
866     return parseNetBSDNotes(*notes_or_error);
867   case llvm::Triple::OpenBSD:
868     return parseOpenBSDNotes(*notes_or_error);
869   default:
870     return llvm::make_error<llvm::StringError>(
871         "Don't know how to parse core file. Unsupported OS.",
872         llvm::inconvertibleErrorCode());
873   }
874 }
875 
876 uint32_t ProcessElfCore::GetNumThreadContexts() {
877   if (!m_thread_data_valid)
878     DoLoadCore();
879   return m_thread_data.size();
880 }
881 
882 ArchSpec ProcessElfCore::GetArchitecture() {
883   ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
884 
885   ArchSpec target_arch = GetTarget().GetArchitecture();
886   arch.MergeFrom(target_arch);
887 
888   // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
889   // files and this information can't be merged in from the target arch so we
890   // fail back to unconditionally returning the target arch in this config.
891   if (target_arch.IsMIPS()) {
892     return target_arch;
893   }
894 
895   return arch;
896 }
897 
898 DataExtractor ProcessElfCore::GetAuxvData() {
899   const uint8_t *start = m_auxv.GetDataStart();
900   size_t len = m_auxv.GetByteSize();
901   lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
902   return DataExtractor(buffer, GetByteOrder(), GetAddressByteSize());
903 }
904 
905 bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
906   info.Clear();
907   info.SetProcessID(GetID());
908   info.SetArchitecture(GetArchitecture());
909   lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
910   if (module_sp) {
911     const bool add_exe_file_as_first_arg = false;
912     info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
913                            add_exe_file_as_first_arg);
914   }
915   return true;
916 }
917