1139749Simp//===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===// 2113584Ssimokawa// 3103285Sikob// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4103285Sikob// See https://llvm.org/LICENSE.txt for license information. 5103285Sikob// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6103285Sikob// 7103285Sikob//===----------------------------------------------------------------------===// 8103285Sikob 9103285Sikob#include <stdlib.h> 10103285Sikob 11103285Sikob#include <memory> 12103285Sikob#include <mutex> 13103285Sikob 14103285Sikob#include "lldb/Core/Module.h" 15103285Sikob#include "lldb/Core/ModuleSpec.h" 16103285Sikob#include "lldb/Core/PluginManager.h" 17103285Sikob#include "lldb/Core/Section.h" 18103285Sikob#include "lldb/Target/DynamicLoader.h" 19103285Sikob#include "lldb/Target/MemoryRegionInfo.h" 20103285Sikob#include "lldb/Target/Target.h" 21103285Sikob#include "lldb/Target/UnixSignals.h" 22103285Sikob#include "lldb/Utility/DataBufferHeap.h" 23103285Sikob#include "lldb/Utility/Log.h" 24103285Sikob#include "lldb/Utility/State.h" 25103285Sikob 26103285Sikob#include "llvm/BinaryFormat/ELF.h" 27103285Sikob#include "llvm/Support/Threading.h" 28103285Sikob 29103285Sikob#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h" 30103285Sikob#include "Plugins/ObjectFile/ELF/ObjectFileELF.h" 31103285Sikob#include "Plugins/Process/elf-core/RegisterUtilities.h" 32103285Sikob#include "ProcessElfCore.h" 33272214Skan#include "ThreadElfCore.h" 34103285Sikob 35103285Sikobusing namespace lldb_private; 36103285Sikobnamespace ELF = llvm::ELF; 37103285Sikob 38103285SikobConstString ProcessElfCore::GetPluginNameStatic() { 39103285Sikob static ConstString g_name("elf-core"); 40103285Sikob return g_name; 41113584Ssimokawa} 42170374Ssimokawa 43170374Ssimokawaconst char *ProcessElfCore::GetPluginDescriptionStatic() { 44113584Ssimokawa return "ELF core dump plug-in."; 45103285Sikob} 46103285Sikob 47169130Ssimokawavoid ProcessElfCore::Terminate() { 48169130Ssimokawa PluginManager::UnregisterPlugin(ProcessElfCore::CreateInstance); 49272214Skan} 50129585Sdfr 51103285Sikoblldb::ProcessSP ProcessElfCore::CreateInstance(lldb::TargetSP target_sp, 52129585Sdfr lldb::ListenerSP listener_sp, 53129585Sdfr const FileSpec *crash_file) { 54129585Sdfr lldb::ProcessSP process_sp; 55129585Sdfr if (crash_file) { 56103285Sikob // Read enough data for a ELF32 header or ELF64 header Note: Here we care 57103285Sikob // about e_type field only, so it is safe to ignore possible presence of 58103285Sikob // the header extension. 59272214Skan const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr); 60103285Sikob 61106810Ssimokawa auto data_sp = FileSystem::Instance().CreateDataBuffer( 62129585Sdfr crash_file->GetPath(), header_size, 0); 63103285Sikob if (data_sp && data_sp->GetByteSize() == header_size && 64103285Sikob elf::ELFHeader::MagicBytesMatch(data_sp->GetBytes())) { 65103285Sikob elf::ELFHeader elf_header; 66110193Ssimokawa DataExtractor data(data_sp, lldb::eByteOrderLittle, 4); 67103285Sikob lldb::offset_t data_offset = 0; 68109645Ssimokawa if (elf_header.Parse(data, &data_offset)) { 69103285Sikob if (elf_header.e_type == llvm::ELF::ET_CORE) 70130585Sphk process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp, 71103285Sikob *crash_file); 72103285Sikob } 73109645Ssimokawa } 74103285Sikob } 75103285Sikob return process_sp; 76103285Sikob} 77109645Ssimokawa 78103285Sikobbool ProcessElfCore::CanDebug(lldb::TargetSP target_sp, 79103285Sikob bool plugin_specified_by_name) { 80103285Sikob // For now we are just making sure the file exists for a given module 81124169Ssimokawa if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) { 82124169Ssimokawa ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture()); 83103285Sikob Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp, 84103285Sikob nullptr, nullptr, nullptr)); 85103285Sikob if (m_core_module_sp) { 86103285Sikob ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); 87103285Sikob if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile) 88103285Sikob return true; 89103285Sikob } 90103285Sikob } 91103285Sikob return false; 92103285Sikob} 93170374Ssimokawa 94103285Sikob// ProcessElfCore constructor 95103285SikobProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp, 96272214Skan lldb::ListenerSP listener_sp, 97103285Sikob const FileSpec &core_file) 98103285Sikob : Process(target_sp, listener_sp), m_core_file(core_file) {} 99129585Sdfr 100272214Skan// Destructor 101103285SikobProcessElfCore::~ProcessElfCore() { 102103285Sikob Clear(); 103103285Sikob // We need to call finalize on the process before destroying ourselves to 104103285Sikob // make sure all of the broadcaster cleanup goes as planned. If we destruct 105103285Sikob // this class, then Process::~Process() might have problems trying to fully 106103285Sikob // destroy the broadcaster. 107103285Sikob Finalize(); 108103285Sikob} 109129585Sdfr 110169806Ssimokawa// PluginInterface 111116978SsimokawaConstString ProcessElfCore::GetPluginName() { return GetPluginNameStatic(); } 112103285Sikob 113103285Sikobuint32_t ProcessElfCore::GetPluginVersion() { return 1; } 114103285Sikob 115103285Sikoblldb::addr_t ProcessElfCore::AddAddressRangeFromLoadSegment( 116103285Sikob const elf::ELFProgramHeader &header) { 117103285Sikob const lldb::addr_t addr = header.p_vaddr; 118103285Sikob FileRange file_range(header.p_offset, header.p_filesz); 119103285Sikob VMRangeToFileOffset::Entry range_entry(addr, header.p_memsz, file_range); 120103285Sikob 121103285Sikob // Only add to m_core_aranges if the file size is non zero. Some core files 122109814Ssimokawa // have PT_LOAD segments for all address ranges, but set f_filesz to zero for 123103285Sikob // the .text sections since they can be retrieved from the object files. 124103285Sikob if (header.p_filesz > 0) { 125169130Ssimokawa VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back(); 126171457Ssimokawa if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() && 127171513Ssimokawa last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() && 128103285Sikob last_entry->GetByteSize() == last_entry->data.GetByteSize()) { 129110193Ssimokawa last_entry->SetRangeEnd(range_entry.GetRangeEnd()); 130103285Sikob last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd()); 131103285Sikob } else { 132272214Skan m_core_aranges.Append(range_entry); 133103285Sikob } 134129585Sdfr } 135116376Ssimokawa // Keep a separate map of permissions that that isn't coalesced so all ranges 136116376Ssimokawa // are maintained. 137116376Ssimokawa const uint32_t permissions = 138103285Sikob ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) | 139103285Sikob ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) | 140108853Ssimokawa ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u); 141110193Ssimokawa 142110193Ssimokawa m_core_range_infos.Append( 143170374Ssimokawa VMRangeToPermissions::Entry(addr, header.p_memsz, permissions)); 144272214Skan 145124169Ssimokawa return addr; 146129585Sdfr} 147130585Sphk 148124169Ssimokawa// Process Control 149124169SsimokawaStatus ProcessElfCore::DoLoadCore() { 150124169Ssimokawa Status error; 151124169Ssimokawa if (!m_core_module_sp) { 152124169Ssimokawa error.SetErrorString("invalid core module"); 153124169Ssimokawa return error; 154124169Ssimokawa } 155129585Sdfr 156129585Sdfr ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile()); 157103285Sikob if (core == nullptr) { 158113584Ssimokawa error.SetErrorString("invalid core object file"); 159170374Ssimokawa return error; 160170374Ssimokawa } 161170374Ssimokawa 162170374Ssimokawa llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders(); 163103285Sikob if (segments.size() == 0) { 164272214Skan error.SetErrorString("core file has no segments"); 165103285Sikob return error; 166170374Ssimokawa } 167170374Ssimokawa 168170374Ssimokawa SetCanJIT(false); 169170374Ssimokawa 170170374Ssimokawa m_thread_data_valid = true; 171109645Ssimokawa 172109645Ssimokawa bool ranges_are_sorted = true; 173109645Ssimokawa lldb::addr_t vm_addr = 0; 174109645Ssimokawa /// Walk through segments and Thread and Address Map information. 175109645Ssimokawa /// PT_NOTE - Contains Thread and Register information 176109645Ssimokawa /// PT_LOAD - Contains a contiguous range of Process Address Space 177109645Ssimokawa for (const elf::ELFProgramHeader &H : segments) { 178109645Ssimokawa DataExtractor data = core->GetSegmentData(H); 179109645Ssimokawa 180109645Ssimokawa // Parse thread contexts and auxv structure 181109645Ssimokawa if (H.p_type == llvm::ELF::PT_NOTE) { 182109645Ssimokawa if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data)) 183109645Ssimokawa return Status(std::move(error)); 184109645Ssimokawa } 185272214Skan // PT_LOAD segments contains address map 186118293Ssimokawa if (H.p_type == llvm::ELF::PT_LOAD) { 187169130Ssimokawa lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(H); 188109645Ssimokawa if (vm_addr > last_addr) 189109645Ssimokawa ranges_are_sorted = false; 190109645Ssimokawa vm_addr = last_addr; 191113584Ssimokawa } 192109645Ssimokawa } 193109645Ssimokawa 194109645Ssimokawa if (!ranges_are_sorted) { 195109645Ssimokawa m_core_aranges.Sort(); 196109645Ssimokawa m_core_range_infos.Sort(); 197109890Ssimokawa } 198109645Ssimokawa 199109645Ssimokawa // Even if the architecture is set in the target, we need to override it to 200109645Ssimokawa // match the core file which is always single arch. 201124169Ssimokawa ArchSpec arch(m_core_module_sp->GetArchitecture()); 202109645Ssimokawa 203109645Ssimokawa ArchSpec target_arch = GetTarget().GetArchitecture(); 204272214Skan ArchSpec core_arch(m_core_module_sp->GetArchitecture()); 205113584Ssimokawa target_arch.MergeFrom(core_arch); 206111942Ssimokawa GetTarget().SetArchitecture(target_arch); 207109645Ssimokawa 208109645Ssimokawa SetUnixSignals(UnixSignals::Create(GetArchitecture())); 209109645Ssimokawa 210111942Ssimokawa // Ensure we found at least one thread that was stopped on a signal. 211109645Ssimokawa bool siginfo_signal_found = false; 212109645Ssimokawa bool prstatus_signal_found = false; 213272214Skan // Check we found a signal in a SIGINFO note. 214120660Ssimokawa for (const auto &thread_data : m_thread_data) { 215120660Ssimokawa if (thread_data.signo != 0) 216169130Ssimokawa siginfo_signal_found = true; 217109645Ssimokawa if (thread_data.prstatus_sig != 0) 218109645Ssimokawa prstatus_signal_found = true; 219169130Ssimokawa } 220109645Ssimokawa if (!siginfo_signal_found) { 221109645Ssimokawa // If we don't have signal from SIGINFO use the signal from each threads 222272214Skan // PRSTATUS note. 223103285Sikob if (prstatus_signal_found) { 224103285Sikob for (auto &thread_data : m_thread_data) 225103285Sikob thread_data.signo = thread_data.prstatus_sig; 226110577Ssimokawa } else if (m_thread_data.size() > 0) { 227113584Ssimokawa // If all else fails force the first thread to be SIGSTOP 228170374Ssimokawa m_thread_data.begin()->signo = 229170374Ssimokawa GetUnixSignals()->GetSignalNumberFromName("SIGSTOP"); 230170374Ssimokawa } 231170374Ssimokawa } 232170374Ssimokawa 233170374Ssimokawa // Core files are useless without the main executable. See if we can locate 234170374Ssimokawa // the main executable using data we found in the core file notes. 235170374Ssimokawa lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 236170374Ssimokawa if (!exe_module_sp) { 237170374Ssimokawa // The first entry in the NT_FILE might be our executable 238169119Ssimokawa if (!m_nt_file_entries.empty()) { 239167632Ssimokawa ModuleSpec exe_module_spec; 240103285Sikob exe_module_spec.GetArchitecture() = arch; 241120660Ssimokawa exe_module_spec.GetFileSpec().SetFile( 242129585Sdfr m_nt_file_entries[0].path.GetCString(), FileSpec::Style::native); 243129585Sdfr if (exe_module_spec.GetFileSpec()) { 244129585Sdfr exe_module_sp = GetTarget().GetOrCreateModule(exe_module_spec, 245103285Sikob true /* notify */); 246103285Sikob if (exe_module_sp) 247103285Sikob GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsNo); 248169119Ssimokawa } 249110269Ssimokawa } 250103285Sikob } 251120660Ssimokawa return error; 252120660Ssimokawa} 253120660Ssimokawa 254120660Ssimokawalldb_private::DynamicLoader *ProcessElfCore::GetDynamicLoader() { 255120660Ssimokawa if (m_dyld_up.get() == nullptr) 256120660Ssimokawa m_dyld_up.reset(DynamicLoader::FindPlugin( 257129585Sdfr this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString())); 258120660Ssimokawa return m_dyld_up.get(); 259120660Ssimokawa} 260129585Sdfr 261124169Ssimokawabool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list, 262272214Skan ThreadList &new_thread_list) { 263272214Skan const uint32_t num_threads = GetNumThreadContexts(); 264272214Skan if (!m_thread_data_valid) 265124169Ssimokawa return false; 266124169Ssimokawa 267124169Ssimokawa for (lldb::tid_t tid = 0; tid < num_threads; ++tid) { 268124169Ssimokawa const ThreadData &td = m_thread_data[tid]; 269124169Ssimokawa lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td)); 270124169Ssimokawa new_thread_list.AddThread(thread_sp); 271124169Ssimokawa } 272169130Ssimokawa return new_thread_list.GetSize(false) > 0; 273169130Ssimokawa} 274169130Ssimokawa 275272214Skanvoid ProcessElfCore::RefreshStateAfterStop() {} 276169117Ssimokawa 277129585SdfrStatus ProcessElfCore::DoDestroy() { return Status(); } 278124169Ssimokawa 279124169Ssimokawa// Process Queries 280170374Ssimokawa 281170374Ssimokawabool ProcessElfCore::IsAlive() { return true; } 282124169Ssimokawa 283124169Ssimokawa// Process Memory 284124169Ssimokawasize_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 285129585Sdfr Status &error) { 286124169Ssimokawa // Don't allow the caching that lldb_private::Process::ReadMemory does since 287124169Ssimokawa // in core files we have it all cached our our core file anyway. 288124169Ssimokawa return DoReadMemory(addr, buf, size, error); 289148868Srwatson} 290170374Ssimokawa 291103285SikobStatus ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr, 292103285Sikob MemoryRegionInfo ®ion_info) { 293103285Sikob region_info.Clear(); 294170400Ssimokawa const VMRangeToPermissions::Entry *permission_entry = 295103285Sikob m_core_range_infos.FindEntryThatContainsOrFollows(load_addr); 296272214Skan if (permission_entry) { 297103285Sikob if (permission_entry->Contains(load_addr)) { 298170374Ssimokawa region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase()); 299111615Ssimokawa region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd()); 300110195Ssimokawa const Flags permissions(permission_entry->data); 301110269Ssimokawa 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