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