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