1 //===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include <stdlib.h>
11 
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.reset(
70               new ProcessElfCore(target_sp, listener_sp, *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   const uint32_t num_segments = core->GetProgramHeaderCount();
166   if (num_segments == 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 (uint32_t i = 1; i <= num_segments; i++) {
181     const elf::ELFProgramHeader *header = core->GetProgramHeaderByIndex(i);
182     assert(header != NULL);
183 
184     DataExtractor data = core->GetSegmentDataByIndex(i);
185 
186     // Parse thread contexts and auxv structure
187     if (header->p_type == llvm::ELF::PT_NOTE) {
188       if (llvm::Error error = ParseThreadContextsFromNoteSegment(header, data))
189         return Status(std::move(error));
190     }
191     // PT_LOAD segments contains address map
192     if (header->p_type == llvm::ELF::PT_LOAD) {
193       lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(header);
194       if (vm_addr > last_addr)
195         ranges_are_sorted = false;
196       vm_addr = last_addr;
197     }
198   }
199 
200   if (!ranges_are_sorted) {
201     m_core_aranges.Sort();
202     m_core_range_infos.Sort();
203   }
204 
205   // Even if the architecture is set in the target, we need to override it to
206   // match the core file which is always single arch.
207   ArchSpec arch(m_core_module_sp->GetArchitecture());
208 
209   ArchSpec target_arch = GetTarget().GetArchitecture();
210   ArchSpec core_arch(m_core_module_sp->GetArchitecture());
211   target_arch.MergeFrom(core_arch);
212   GetTarget().SetArchitecture(target_arch);
213 
214   SetUnixSignals(UnixSignals::Create(GetArchitecture()));
215 
216   // Ensure we found at least one thread that was stopped on a signal.
217   bool siginfo_signal_found = false;
218   bool prstatus_signal_found = false;
219   // Check we found a signal in a SIGINFO note.
220   for (const auto &thread_data : m_thread_data) {
221     if (thread_data.signo != 0)
222       siginfo_signal_found = true;
223     if (thread_data.prstatus_sig != 0)
224       prstatus_signal_found = true;
225   }
226   if (!siginfo_signal_found) {
227     // If we don't have signal from SIGINFO use the signal from each threads
228     // PRSTATUS note.
229     if (prstatus_signal_found) {
230       for (auto &thread_data : m_thread_data)
231         thread_data.signo = thread_data.prstatus_sig;
232     } else if (m_thread_data.size() > 0) {
233       // If all else fails force the first thread to be SIGSTOP
234       m_thread_data.begin()->signo =
235           GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
236     }
237   }
238 
239   // Core files are useless without the main executable. See if we can locate
240   // the main executable using data we found in the core file notes.
241   lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
242   if (!exe_module_sp) {
243     // The first entry in the NT_FILE might be our executable
244     if (!m_nt_file_entries.empty()) {
245       ModuleSpec exe_module_spec;
246       exe_module_spec.GetArchitecture() = arch;
247       exe_module_spec.GetFileSpec().SetFile(
248           m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native);
249       if (exe_module_spec.GetFileSpec()) {
250         exe_module_sp = GetTarget().GetSharedModule(exe_module_spec);
251         if (exe_module_sp)
252           GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo);
253       }
254     }
255   }
256   return error;
257 }
258 
259 lldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() {
260   if (m_dyld_ap.get() == NULL)
261     m_dyld_ap.reset(DynamicLoader::FindPlugin(
262         this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString()));
263   return m_dyld_ap.get();
264 }
265 
266 bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list,
267                                       ThreadList &new_thread_list) {
268   const uint32_t num_threads = GetNumThreadContexts();
269   if (!m_thread_data_valid)
270     return false;
271 
272   for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
273     const ThreadData &td = m_thread_data[tid];
274     lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
275     new_thread_list.AddThread(thread_sp);
276   }
277   return new_thread_list.GetSize(false) > 0;
278 }
279 
280 void ProcessElfCore::RefreshStateAfterStop() {}
281 
282 Status ProcessElfCore::DoDestroy() { return Status(); }
283 
284 //------------------------------------------------------------------
285 // Process Queries
286 //------------------------------------------------------------------
287 
288 bool ProcessElfCore::IsAlive() { return true; }
289 
290 //------------------------------------------------------------------
291 // Process Memory
292 //------------------------------------------------------------------
293 size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
294                                   Status &error) {
295   // Don't allow the caching that lldb_private::Process::ReadMemory does since
296   // in core files we have it all cached our our core file anyway.
297   return DoReadMemory(addr, buf, size, error);
298 }
299 
300 Status ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr,
301                                            MemoryRegionInfo &region_info) {
302   region_info.Clear();
303   const VMRangeToPermissions::Entry *permission_entry =
304       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
305   if (permission_entry) {
306     if (permission_entry->Contains(load_addr)) {
307       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
308       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
309       const Flags permissions(permission_entry->data);
310       region_info.SetReadable(permissions.Test(lldb::ePermissionsReadable)
311                                   ? MemoryRegionInfo::eYes
312                                   : MemoryRegionInfo::eNo);
313       region_info.SetWritable(permissions.Test(lldb::ePermissionsWritable)
314                                   ? MemoryRegionInfo::eYes
315                                   : MemoryRegionInfo::eNo);
316       region_info.SetExecutable(permissions.Test(lldb::ePermissionsExecutable)
317                                     ? MemoryRegionInfo::eYes
318                                     : MemoryRegionInfo::eNo);
319       region_info.SetMapped(MemoryRegionInfo::eYes);
320     } else if (load_addr < permission_entry->GetRangeBase()) {
321       region_info.GetRange().SetRangeBase(load_addr);
322       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
323       region_info.SetReadable(MemoryRegionInfo::eNo);
324       region_info.SetWritable(MemoryRegionInfo::eNo);
325       region_info.SetExecutable(MemoryRegionInfo::eNo);
326       region_info.SetMapped(MemoryRegionInfo::eNo);
327     }
328     return Status();
329   }
330 
331   region_info.GetRange().SetRangeBase(load_addr);
332   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
333   region_info.SetReadable(MemoryRegionInfo::eNo);
334   region_info.SetWritable(MemoryRegionInfo::eNo);
335   region_info.SetExecutable(MemoryRegionInfo::eNo);
336   region_info.SetMapped(MemoryRegionInfo::eNo);
337   return Status();
338 }
339 
340 size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
341                                     Status &error) {
342   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
343 
344   if (core_objfile == NULL)
345     return 0;
346 
347   // Get the address range
348   const VMRangeToFileOffset::Entry *address_range =
349       m_core_aranges.FindEntryThatContains(addr);
350   if (address_range == NULL || address_range->GetRangeEnd() < addr) {
351     error.SetErrorStringWithFormat("core file does not contain 0x%" PRIx64,
352                                    addr);
353     return 0;
354   }
355 
356   // Convert the address into core file offset
357   const lldb::addr_t offset = addr - address_range->GetRangeBase();
358   const lldb::addr_t file_start = address_range->data.GetRangeBase();
359   const lldb::addr_t file_end = address_range->data.GetRangeEnd();
360   size_t bytes_to_read = size; // Number of bytes to read from the core file
361   size_t bytes_copied = 0;   // Number of bytes actually read from the core file
362   size_t zero_fill_size = 0; // Padding
363   lldb::addr_t bytes_left =
364       0; // Number of bytes available in the core file from the given address
365 
366   // Don't proceed if core file doesn't contain the actual data for this
367   // address range.
368   if (file_start == file_end)
369     return 0;
370 
371   // Figure out how many on-disk bytes remain in this segment starting at the
372   // given offset
373   if (file_end > file_start + offset)
374     bytes_left = file_end - (file_start + offset);
375 
376   // Figure out how many bytes we need to zero-fill if we are reading more
377   // bytes than available in the on-disk segment
378   if (bytes_to_read > bytes_left) {
379     zero_fill_size = bytes_to_read - bytes_left;
380     bytes_to_read = bytes_left;
381   }
382 
383   // If there is data available on the core file read it
384   if (bytes_to_read)
385     bytes_copied =
386         core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
387 
388   assert(zero_fill_size <= size);
389   // Pad remaining bytes
390   if (zero_fill_size)
391     memset(((char *)buf) + bytes_copied, 0, zero_fill_size);
392 
393   return bytes_copied + zero_fill_size;
394 }
395 
396 void ProcessElfCore::Clear() {
397   m_thread_list.Clear();
398 
399   SetUnixSignals(std::make_shared<UnixSignals>());
400 }
401 
402 void ProcessElfCore::Initialize() {
403   static llvm::once_flag g_once_flag;
404 
405   llvm::call_once(g_once_flag, []() {
406     PluginManager::RegisterPlugin(GetPluginNameStatic(),
407                                   GetPluginDescriptionStatic(), CreateInstance);
408   });
409 }
410 
411 lldb::addr_t ProcessElfCore::GetImageInfoAddress() {
412   ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
413   Address addr = obj_file->GetImageInfoAddress(&GetTarget());
414 
415   if (addr.IsValid())
416     return addr.GetLoadAddress(&GetTarget());
417   return LLDB_INVALID_ADDRESS;
418 }
419 
420 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
421 static void ParseFreeBSDPrStatus(ThreadData &thread_data,
422                                  const DataExtractor &data,
423                                  const ArchSpec &arch) {
424   lldb::offset_t offset = 0;
425   bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
426                arch.GetMachine() == llvm::Triple::mips64 ||
427                arch.GetMachine() == llvm::Triple::ppc64 ||
428                arch.GetMachine() == llvm::Triple::x86_64);
429   int pr_version = data.GetU32(&offset);
430 
431   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
432   if (log) {
433     if (pr_version > 1)
434       log->Printf("FreeBSD PRSTATUS unexpected version %d", pr_version);
435   }
436 
437   // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
438   if (lp64)
439     offset += 32;
440   else
441     offset += 16;
442 
443   thread_data.signo = data.GetU32(&offset); // pr_cursig
444   thread_data.tid = data.GetU32(&offset);   // pr_pid
445   if (lp64)
446     offset += 4;
447 
448   size_t len = data.GetByteSize() - offset;
449   thread_data.gpregset = DataExtractor(data, offset, len);
450 }
451 
452 static void ParseNetBSDProcInfo(ThreadData &thread_data,
453                                 const DataExtractor &data) {
454   lldb::offset_t offset = 0;
455 
456   int version = data.GetU32(&offset);
457   if (version != 1)
458     return;
459 
460   offset += 4;
461   thread_data.signo = data.GetU32(&offset);
462 }
463 
464 static void ParseOpenBSDProcInfo(ThreadData &thread_data,
465                                  const DataExtractor &data) {
466   lldb::offset_t offset = 0;
467 
468   int version = data.GetU32(&offset);
469   if (version != 1)
470     return;
471 
472   offset += 4;
473   thread_data.signo = data.GetU32(&offset);
474 }
475 
476 llvm::Expected<std::vector<CoreNote>>
477 ProcessElfCore::parseSegment(const DataExtractor &segment) {
478   lldb::offset_t offset = 0;
479   std::vector<CoreNote> result;
480 
481   while (offset < segment.GetByteSize()) {
482     ELFNote note = ELFNote();
483     if (!note.Parse(segment, &offset))
484       return llvm::make_error<llvm::StringError>(
485           "Unable to parse note segment", llvm::inconvertibleErrorCode());
486 
487     size_t note_start = offset;
488     size_t note_size = llvm::alignTo(note.n_descsz, 4);
489     DataExtractor note_data(segment, note_start, note_size);
490 
491     result.push_back({note, note_data});
492     offset += note_size;
493   }
494 
495   return std::move(result);
496 }
497 
498 llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
499   bool have_prstatus = false;
500   bool have_prpsinfo = false;
501   ThreadData thread_data;
502   for (const auto &note : notes) {
503     if (note.info.n_name != "FreeBSD")
504       continue;
505 
506     if ((note.info.n_type == FREEBSD::NT_PRSTATUS && have_prstatus) ||
507         (note.info.n_type == FREEBSD::NT_PRPSINFO && have_prpsinfo)) {
508       assert(thread_data.gpregset.GetByteSize() > 0);
509       // Add the new thread to thread list
510       m_thread_data.push_back(thread_data);
511       thread_data = ThreadData();
512       have_prstatus = false;
513       have_prpsinfo = false;
514     }
515 
516     switch (note.info.n_type) {
517     case FREEBSD::NT_PRSTATUS:
518       have_prstatus = true;
519       ParseFreeBSDPrStatus(thread_data, note.data, GetArchitecture());
520       break;
521     case FREEBSD::NT_PRPSINFO:
522       have_prpsinfo = true;
523       break;
524     case FREEBSD::NT_THRMISC: {
525       lldb::offset_t offset = 0;
526       thread_data.name = note.data.GetCStr(&offset, 20);
527       break;
528     }
529     case FREEBSD::NT_PROCSTAT_AUXV:
530       // FIXME: FreeBSD sticks an int at the beginning of the note
531       m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
532       break;
533     default:
534       thread_data.notes.push_back(note);
535       break;
536     }
537   }
538   if (!have_prstatus) {
539     return llvm::make_error<llvm::StringError>(
540         "Could not find NT_PRSTATUS note in core file.",
541         llvm::inconvertibleErrorCode());
542   }
543   m_thread_data.push_back(thread_data);
544   return llvm::Error::success();
545 }
546 
547 llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
548   ThreadData thread_data;
549   for (const auto &note : notes) {
550     // NetBSD per-thread information is stored in notes named "NetBSD-CORE@nnn"
551     // so match on the initial part of the string.
552     if (!llvm::StringRef(note.info.n_name).startswith("NetBSD-CORE"))
553       continue;
554 
555     switch (note.info.n_type) {
556     case NETBSD::NT_PROCINFO:
557       ParseNetBSDProcInfo(thread_data, note.data);
558       break;
559     case NETBSD::NT_AUXV:
560       m_auxv = note.data;
561       break;
562 
563     case NETBSD::NT_AMD64_REGS:
564       if (GetArchitecture().GetMachine() == llvm::Triple::x86_64)
565         thread_data.gpregset = note.data;
566       break;
567     default:
568       thread_data.notes.push_back(note);
569       break;
570     }
571   }
572   if (thread_data.gpregset.GetByteSize() == 0) {
573     return llvm::make_error<llvm::StringError>(
574         "Could not find general purpose registers note in core file.",
575         llvm::inconvertibleErrorCode());
576   }
577   m_thread_data.push_back(thread_data);
578   return llvm::Error::success();
579 }
580 
581 llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
582   ThreadData thread_data;
583   for (const auto &note : notes) {
584     // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
585     // match on the initial part of the string.
586     if (!llvm::StringRef(note.info.n_name).startswith("OpenBSD"))
587       continue;
588 
589     switch (note.info.n_type) {
590     case OPENBSD::NT_PROCINFO:
591       ParseOpenBSDProcInfo(thread_data, note.data);
592       break;
593     case OPENBSD::NT_AUXV:
594       m_auxv = note.data;
595       break;
596     case OPENBSD::NT_REGS:
597       thread_data.gpregset = note.data;
598       break;
599     default:
600       thread_data.notes.push_back(note);
601       break;
602     }
603   }
604   if (thread_data.gpregset.GetByteSize() == 0) {
605     return llvm::make_error<llvm::StringError>(
606         "Could not find general purpose registers note in core file.",
607         llvm::inconvertibleErrorCode());
608   }
609   m_thread_data.push_back(thread_data);
610   return llvm::Error::success();
611 }
612 
613 /// A description of a linux process usually contains the following NOTE
614 /// entries:
615 /// - NT_PRPSINFO - General process information like pid, uid, name, ...
616 /// - NT_SIGINFO - Information about the signal that terminated the process
617 /// - NT_AUXV - Process auxiliary vector
618 /// - NT_FILE - Files mapped into memory
619 ///
620 /// Additionally, for each thread in the process the core file will contain at
621 /// least the NT_PRSTATUS note, containing the thread id and general purpose
622 /// registers. It may include additional notes for other register sets (floating
623 /// point and vector registers, ...). The tricky part here is that some of these
624 /// notes have "CORE" in their owner fields, while other set it to "LINUX".
625 llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
626   const ArchSpec &arch = GetArchitecture();
627   bool have_prstatus = false;
628   bool have_prpsinfo = false;
629   ThreadData thread_data;
630   for (const auto &note : notes) {
631     if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
632       continue;
633 
634     if ((note.info.n_type == LINUX::NT_PRSTATUS && have_prstatus) ||
635         (note.info.n_type == LINUX::NT_PRPSINFO && have_prpsinfo)) {
636       assert(thread_data.gpregset.GetByteSize() > 0);
637       // Add the new thread to thread list
638       m_thread_data.push_back(thread_data);
639       thread_data = ThreadData();
640       have_prstatus = false;
641       have_prpsinfo = false;
642     }
643 
644     switch (note.info.n_type) {
645     case LINUX::NT_PRSTATUS: {
646       have_prstatus = true;
647       ELFLinuxPrStatus prstatus;
648       Status status = prstatus.Parse(note.data, arch);
649       if (status.Fail())
650         return status.ToError();
651       thread_data.prstatus_sig = prstatus.pr_cursig;
652       thread_data.tid = prstatus.pr_pid;
653       uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
654       size_t len = note.data.GetByteSize() - header_size;
655       thread_data.gpregset = DataExtractor(note.data, header_size, len);
656       break;
657     }
658     case LINUX::NT_PRPSINFO: {
659       have_prpsinfo = true;
660       ELFLinuxPrPsInfo prpsinfo;
661       Status status = prpsinfo.Parse(note.data, arch);
662       if (status.Fail())
663         return status.ToError();
664       thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
665       SetID(prpsinfo.pr_pid);
666       break;
667     }
668     case LINUX::NT_SIGINFO: {
669       ELFLinuxSigInfo siginfo;
670       Status status = siginfo.Parse(note.data, arch);
671       if (status.Fail())
672         return status.ToError();
673       thread_data.signo = siginfo.si_signo;
674       break;
675     }
676     case LINUX::NT_FILE: {
677       m_nt_file_entries.clear();
678       lldb::offset_t offset = 0;
679       const uint64_t count = note.data.GetAddress(&offset);
680       note.data.GetAddress(&offset); // Skip page size
681       for (uint64_t i = 0; i < count; ++i) {
682         NT_FILE_Entry entry;
683         entry.start = note.data.GetAddress(&offset);
684         entry.end = note.data.GetAddress(&offset);
685         entry.file_ofs = note.data.GetAddress(&offset);
686         m_nt_file_entries.push_back(entry);
687       }
688       for (uint64_t i = 0; i < count; ++i) {
689         const char *path = note.data.GetCStr(&offset);
690         if (path && path[0])
691           m_nt_file_entries[i].path.SetCString(path);
692       }
693       break;
694     }
695     case LINUX::NT_AUXV:
696       m_auxv = note.data;
697       break;
698     default:
699       thread_data.notes.push_back(note);
700       break;
701     }
702   }
703   // Add last entry in the note section
704   if (have_prstatus)
705     m_thread_data.push_back(thread_data);
706   return llvm::Error::success();
707 }
708 
709 /// Parse Thread context from PT_NOTE segment and store it in the thread list
710 /// A note segment consists of one or more NOTE entries, but their types and
711 /// meaning differ depending on the OS.
712 llvm::Error ProcessElfCore::ParseThreadContextsFromNoteSegment(
713     const elf::ELFProgramHeader *segment_header, DataExtractor segment_data) {
714   assert(segment_header && segment_header->p_type == llvm::ELF::PT_NOTE);
715 
716   auto notes_or_error = parseSegment(segment_data);
717   if(!notes_or_error)
718     return notes_or_error.takeError();
719   switch (GetArchitecture().GetTriple().getOS()) {
720   case llvm::Triple::FreeBSD:
721     return parseFreeBSDNotes(*notes_or_error);
722   case llvm::Triple::Linux:
723     return parseLinuxNotes(*notes_or_error);
724   case llvm::Triple::NetBSD:
725     return parseNetBSDNotes(*notes_or_error);
726   case llvm::Triple::OpenBSD:
727     return parseOpenBSDNotes(*notes_or_error);
728   default:
729     return llvm::make_error<llvm::StringError>(
730         "Don't know how to parse core file. Unsupported OS.",
731         llvm::inconvertibleErrorCode());
732   }
733 }
734 
735 uint32_t ProcessElfCore::GetNumThreadContexts() {
736   if (!m_thread_data_valid)
737     DoLoadCore();
738   return m_thread_data.size();
739 }
740 
741 ArchSpec ProcessElfCore::GetArchitecture() {
742   ArchSpec arch;
743   m_core_module_sp->GetObjectFile()->GetArchitecture(arch);
744 
745   ArchSpec target_arch = GetTarget().GetArchitecture();
746   arch.MergeFrom(target_arch);
747 
748   // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
749   // files and this information can't be merged in from the target arch so we
750   // fail back to unconditionally returning the target arch in this config.
751   if (target_arch.IsMIPS()) {
752     return target_arch;
753   }
754 
755   return arch;
756 }
757 
758 const lldb::DataBufferSP ProcessElfCore::GetAuxvData() {
759   const uint8_t *start = m_auxv.GetDataStart();
760   size_t len = m_auxv.GetByteSize();
761   lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
762   return buffer;
763 }
764 
765 bool ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) {
766   info.Clear();
767   info.SetProcessID(GetID());
768   info.SetArchitecture(GetArchitecture());
769   lldb::ModuleSP module_sp = GetTarget().GetExecutableModule();
770   if (module_sp) {
771     const bool add_exe_file_as_first_arg = false;
772     info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
773                            add_exe_file_as_first_arg);
774   }
775   return true;
776 }
777