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