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