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