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