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