1 //===-- ProcessElfCore.cpp --------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 #include <stdlib.h> 12 13 // C++ Includes 14 #include <mutex> 15 16 // Other libraries and framework includes 17 #include "lldb/Core/PluginManager.h" 18 #include "lldb/Core/Module.h" 19 #include "lldb/Core/ModuleSpec.h" 20 #include "lldb/Core/Section.h" 21 #include "lldb/Core/State.h" 22 #include "lldb/Core/DataBufferHeap.h" 23 #include "lldb/Core/Log.h" 24 #include "lldb/Target/Target.h" 25 #include "lldb/Target/DynamicLoader.h" 26 #include "lldb/Target/UnixSignals.h" 27 28 #include "llvm/Support/ELF.h" 29 30 #include "Plugins/ObjectFile/ELF/ObjectFileELF.h" 31 #include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h" 32 33 // Project includes 34 #include "ProcessElfCore.h" 35 #include "ThreadElfCore.h" 36 37 using namespace lldb_private; 38 39 ConstString 40 ProcessElfCore::GetPluginNameStatic() 41 { 42 static ConstString g_name("elf-core"); 43 return g_name; 44 } 45 46 const char * 47 ProcessElfCore::GetPluginDescriptionStatic() 48 { 49 return "ELF core dump plug-in."; 50 } 51 52 void 53 ProcessElfCore::Terminate() 54 { 55 PluginManager::UnregisterPlugin (ProcessElfCore::CreateInstance); 56 } 57 58 59 lldb::ProcessSP 60 ProcessElfCore::CreateInstance (lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file) 61 { 62 lldb::ProcessSP process_sp; 63 if (crash_file) 64 { 65 // Read enough data for a ELF32 header or ELF64 header 66 const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr); 67 68 lldb::DataBufferSP data_sp (crash_file->ReadFileContents(0, header_size)); 69 if (data_sp && data_sp->GetByteSize() == header_size && 70 elf::ELFHeader::MagicBytesMatch (data_sp->GetBytes())) 71 { 72 elf::ELFHeader elf_header; 73 DataExtractor data(data_sp, lldb::eByteOrderLittle, 4); 74 lldb::offset_t data_offset = 0; 75 if (elf_header.Parse(data, &data_offset)) 76 { 77 if (elf_header.e_type == llvm::ELF::ET_CORE) 78 process_sp.reset(new ProcessElfCore (target_sp, listener_sp, *crash_file)); 79 } 80 } 81 } 82 return process_sp; 83 } 84 85 bool 86 ProcessElfCore::CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) 87 { 88 // For now we are just making sure the file exists for a given module 89 if (!m_core_module_sp && m_core_file.Exists()) 90 { 91 ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture()); 92 Error error (ModuleList::GetSharedModule (core_module_spec, m_core_module_sp, 93 NULL, NULL, NULL)); 94 if (m_core_module_sp) 95 { 96 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); 97 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile) 98 return true; 99 } 100 } 101 return false; 102 } 103 104 //---------------------------------------------------------------------- 105 // ProcessElfCore constructor 106 //---------------------------------------------------------------------- 107 ProcessElfCore::ProcessElfCore(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, 108 const FileSpec &core_file) : 109 Process (target_sp, listener_sp), 110 m_core_module_sp (), 111 m_core_file (core_file), 112 m_dyld_plugin_name (), 113 m_os(llvm::Triple::UnknownOS), 114 m_thread_data_valid(false), 115 m_thread_data(), 116 m_core_aranges () 117 { 118 } 119 120 //---------------------------------------------------------------------- 121 // Destructor 122 //---------------------------------------------------------------------- 123 ProcessElfCore::~ProcessElfCore() 124 { 125 Clear(); 126 // We need to call finalize on the process before destroying ourselves 127 // to make sure all of the broadcaster cleanup goes as planned. If we 128 // destruct this class, then Process::~Process() might have problems 129 // trying to fully destroy the broadcaster. 130 Finalize(); 131 } 132 133 //---------------------------------------------------------------------- 134 // PluginInterface 135 //---------------------------------------------------------------------- 136 ConstString 137 ProcessElfCore::GetPluginName() 138 { 139 return GetPluginNameStatic(); 140 } 141 142 uint32_t 143 ProcessElfCore::GetPluginVersion() 144 { 145 return 1; 146 } 147 148 lldb::addr_t 149 ProcessElfCore::AddAddressRangeFromLoadSegment(const elf::ELFProgramHeader *header) 150 { 151 lldb::addr_t addr = header->p_vaddr; 152 FileRange file_range (header->p_offset, header->p_filesz); 153 VMRangeToFileOffset::Entry range_entry(addr, header->p_memsz, file_range); 154 155 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back(); 156 if (last_entry && 157 last_entry->GetRangeEnd() == range_entry.GetRangeBase() && 158 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() && 159 last_entry->GetByteSize() == last_entry->data.GetByteSize()) 160 { 161 last_entry->SetRangeEnd (range_entry.GetRangeEnd()); 162 last_entry->data.SetRangeEnd (range_entry.data.GetRangeEnd()); 163 } 164 else 165 { 166 m_core_aranges.Append(range_entry); 167 } 168 169 return addr; 170 } 171 172 //---------------------------------------------------------------------- 173 // Process Control 174 //---------------------------------------------------------------------- 175 Error 176 ProcessElfCore::DoLoadCore () 177 { 178 Error error; 179 if (!m_core_module_sp) 180 { 181 error.SetErrorString ("invalid core module"); 182 return error; 183 } 184 185 ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile()); 186 if (core == NULL) 187 { 188 error.SetErrorString ("invalid core object file"); 189 return error; 190 } 191 192 const uint32_t num_segments = core->GetProgramHeaderCount(); 193 if (num_segments == 0) 194 { 195 error.SetErrorString ("core file has no segments"); 196 return error; 197 } 198 199 SetCanJIT(false); 200 201 m_thread_data_valid = true; 202 203 bool ranges_are_sorted = true; 204 lldb::addr_t vm_addr = 0; 205 /// Walk through segments and Thread and Address Map information. 206 /// PT_NOTE - Contains Thread and Register information 207 /// PT_LOAD - Contains a contiguous range of Process Address Space 208 for(uint32_t i = 1; i <= num_segments; i++) 209 { 210 const elf::ELFProgramHeader *header = core->GetProgramHeaderByIndex(i); 211 assert(header != NULL); 212 213 DataExtractor data = core->GetSegmentDataByIndex(i); 214 215 // Parse thread contexts and auxv structure 216 if (header->p_type == llvm::ELF::PT_NOTE) 217 ParseThreadContextsFromNoteSegment(header, data); 218 219 // PT_LOAD segments contains address map 220 if (header->p_type == llvm::ELF::PT_LOAD) 221 { 222 lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(header); 223 if (vm_addr > last_addr) 224 ranges_are_sorted = false; 225 vm_addr = last_addr; 226 } 227 } 228 229 if (!ranges_are_sorted) 230 m_core_aranges.Sort(); 231 232 // Even if the architecture is set in the target, we need to override 233 // it to match the core file which is always single arch. 234 ArchSpec arch (m_core_module_sp->GetArchitecture()); 235 if (arch.IsValid()) 236 GetTarget().SetArchitecture(arch); 237 238 SetUnixSignals(UnixSignals::Create(GetArchitecture())); 239 240 // Core files are useless without the main executable. See if we can locate the main 241 // executable using data we found in the core file notes. 242 lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 243 if (!exe_module_sp) 244 { 245 // The first entry in the NT_FILE might be our executable 246 if (!m_nt_file_entries.empty()) 247 { 248 ModuleSpec exe_module_spec; 249 exe_module_spec.GetArchitecture() = arch; 250 exe_module_spec.GetFileSpec().SetFile(m_nt_file_entries[0].path.GetCString(), false); 251 if (exe_module_spec.GetFileSpec()) 252 { 253 exe_module_sp = GetTarget().GetSharedModule(exe_module_spec); 254 if (exe_module_sp) 255 GetTarget().SetExecutableModule(exe_module_sp, false); 256 } 257 } 258 } 259 return error; 260 } 261 262 lldb_private::DynamicLoader * 263 ProcessElfCore::GetDynamicLoader () 264 { 265 if (m_dyld_ap.get() == NULL) 266 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString())); 267 return m_dyld_ap.get(); 268 } 269 270 bool 271 ProcessElfCore::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 272 { 273 const uint32_t num_threads = GetNumThreadContexts (); 274 if (!m_thread_data_valid) 275 return false; 276 277 for (lldb::tid_t tid = 0; tid < num_threads; ++tid) 278 { 279 const ThreadData &td = m_thread_data[tid]; 280 lldb::ThreadSP thread_sp(new ThreadElfCore (*this, td)); 281 new_thread_list.AddThread (thread_sp); 282 } 283 return new_thread_list.GetSize(false) > 0; 284 } 285 286 void 287 ProcessElfCore::RefreshStateAfterStop () 288 { 289 } 290 291 Error 292 ProcessElfCore::DoDestroy () 293 { 294 return Error(); 295 } 296 297 //------------------------------------------------------------------ 298 // Process Queries 299 //------------------------------------------------------------------ 300 301 bool 302 ProcessElfCore::IsAlive () 303 { 304 return true; 305 } 306 307 //------------------------------------------------------------------ 308 // Process Memory 309 //------------------------------------------------------------------ 310 size_t 311 ProcessElfCore::ReadMemory (lldb::addr_t addr, void *buf, size_t size, Error &error) 312 { 313 // Don't allow the caching that lldb_private::Process::ReadMemory does 314 // since in core files we have it all cached our our core file anyway. 315 return DoReadMemory (addr, buf, size, error); 316 } 317 318 size_t 319 ProcessElfCore::DoReadMemory (lldb::addr_t addr, void *buf, size_t size, Error &error) 320 { 321 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); 322 323 if (core_objfile == NULL) 324 return 0; 325 326 // Get the address range 327 const VMRangeToFileOffset::Entry *address_range = m_core_aranges.FindEntryThatContains (addr); 328 if (address_range == NULL || address_range->GetRangeEnd() < addr) 329 { 330 error.SetErrorStringWithFormat ("core file does not contain 0x%" PRIx64, addr); 331 return 0; 332 } 333 334 // Convert the address into core file offset 335 const lldb::addr_t offset = addr - address_range->GetRangeBase(); 336 const lldb::addr_t file_start = address_range->data.GetRangeBase(); 337 const lldb::addr_t file_end = address_range->data.GetRangeEnd(); 338 size_t bytes_to_read = size; // Number of bytes to read from the core file 339 size_t bytes_copied = 0; // Number of bytes actually read from the core file 340 size_t zero_fill_size = 0; // Padding 341 lldb::addr_t bytes_left = 0; // Number of bytes available in the core file from the given address 342 343 // Figure out how many on-disk bytes remain in this segment 344 // starting at the given offset 345 if (file_end > file_start + offset) 346 bytes_left = file_end - (file_start + offset); 347 348 // Figure out how many bytes we need to zero-fill if we are 349 // reading more bytes than available in the on-disk segment 350 if (bytes_to_read > bytes_left) 351 { 352 zero_fill_size = bytes_to_read - bytes_left; 353 bytes_to_read = bytes_left; 354 } 355 356 // If there is data available on the core file read it 357 if (bytes_to_read) 358 bytes_copied = core_objfile->CopyData(offset + file_start, bytes_to_read, buf); 359 360 assert(zero_fill_size <= size); 361 // Pad remaining bytes 362 if (zero_fill_size) 363 memset(((char *)buf) + bytes_copied, 0, zero_fill_size); 364 365 return bytes_copied + zero_fill_size; 366 } 367 368 void 369 ProcessElfCore::Clear() 370 { 371 m_thread_list.Clear(); 372 m_os = llvm::Triple::UnknownOS; 373 374 SetUnixSignals(std::make_shared<UnixSignals>()); 375 } 376 377 void 378 ProcessElfCore::Initialize() 379 { 380 static std::once_flag g_once_flag; 381 382 std::call_once(g_once_flag, []() 383 { 384 PluginManager::RegisterPlugin (GetPluginNameStatic(), 385 GetPluginDescriptionStatic(), CreateInstance); 386 }); 387 } 388 389 lldb::addr_t 390 ProcessElfCore::GetImageInfoAddress() 391 { 392 ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile(); 393 Address addr = obj_file->GetImageInfoAddress(&GetTarget()); 394 395 if (addr.IsValid()) 396 return addr.GetLoadAddress(&GetTarget()); 397 return LLDB_INVALID_ADDRESS; 398 } 399 400 /// Core files PT_NOTE segment descriptor types 401 enum { 402 NT_PRSTATUS = 1, 403 NT_FPREGSET, 404 NT_PRPSINFO, 405 NT_TASKSTRUCT, 406 NT_PLATFORM, 407 NT_AUXV, 408 NT_FILE = 0x46494c45 409 }; 410 411 namespace FREEBSD { 412 413 enum { 414 NT_PRSTATUS = 1, 415 NT_FPREGSET, 416 NT_PRPSINFO, 417 NT_THRMISC = 7, 418 NT_PROCSTAT_AUXV = 16, 419 NT_PPC_VMX = 0x100 420 }; 421 422 } 423 424 // Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details. 425 static void 426 ParseFreeBSDPrStatus(ThreadData &thread_data, DataExtractor &data, 427 ArchSpec &arch) 428 { 429 lldb::offset_t offset = 0; 430 bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 || 431 arch.GetMachine() == llvm::Triple::mips64 || 432 arch.GetMachine() == llvm::Triple::ppc64 || 433 arch.GetMachine() == llvm::Triple::x86_64); 434 int pr_version = data.GetU32(&offset); 435 436 Log *log (GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 437 if (log) 438 { 439 if (pr_version > 1) 440 log->Printf("FreeBSD PRSTATUS unexpected version %d", pr_version); 441 } 442 443 // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate 444 if (lp64) 445 offset += 32; 446 else 447 offset += 16; 448 449 thread_data.signo = data.GetU32(&offset); // pr_cursig 450 thread_data.tid = data.GetU32(&offset); // pr_pid 451 if (lp64) 452 offset += 4; 453 454 size_t len = data.GetByteSize() - offset; 455 thread_data.gpregset = DataExtractor(data, offset, len); 456 } 457 458 static void 459 ParseFreeBSDThrMisc(ThreadData &thread_data, DataExtractor &data) 460 { 461 lldb::offset_t offset = 0; 462 thread_data.name = data.GetCStr(&offset, 20); 463 } 464 465 /// Parse Thread context from PT_NOTE segment and store it in the thread list 466 /// Notes: 467 /// 1) A PT_NOTE segment is composed of one or more NOTE entries. 468 /// 2) NOTE Entry contains a standard header followed by variable size data. 469 /// (see ELFNote structure) 470 /// 3) A Thread Context in a core file usually described by 3 NOTE entries. 471 /// a) NT_PRSTATUS - Register context 472 /// b) NT_PRPSINFO - Process info(pid..) 473 /// c) NT_FPREGSET - Floating point registers 474 /// 4) The NOTE entries can be in any order 475 /// 5) If a core file contains multiple thread contexts then there is two data forms 476 /// a) Each thread context(2 or more NOTE entries) contained in its own segment (PT_NOTE) 477 /// b) All thread context is stored in a single segment(PT_NOTE). 478 /// This case is little tricker since while parsing we have to find where the 479 /// new thread starts. The current implementation marks beginning of 480 /// new thread when it finds NT_PRSTATUS or NT_PRPSINFO NOTE entry. 481 /// For case (b) there may be either one NT_PRPSINFO per thread, or a single 482 /// one that applies to all threads (depending on the platform type). 483 void 484 ProcessElfCore::ParseThreadContextsFromNoteSegment(const elf::ELFProgramHeader *segment_header, 485 DataExtractor segment_data) 486 { 487 assert(segment_header && segment_header->p_type == llvm::ELF::PT_NOTE); 488 489 lldb::offset_t offset = 0; 490 std::unique_ptr<ThreadData> thread_data(new ThreadData); 491 bool have_prstatus = false; 492 bool have_prpsinfo = false; 493 494 ArchSpec arch = GetArchitecture(); 495 ELFLinuxPrPsInfo prpsinfo; 496 ELFLinuxPrStatus prstatus; 497 size_t header_size; 498 size_t len; 499 500 // Loop through the NOTE entires in the segment 501 while (offset < segment_header->p_filesz) 502 { 503 ELFNote note = ELFNote(); 504 note.Parse(segment_data, &offset); 505 506 // Beginning of new thread 507 if ((note.n_type == NT_PRSTATUS && have_prstatus) || 508 (note.n_type == NT_PRPSINFO && have_prpsinfo)) 509 { 510 assert(thread_data->gpregset.GetByteSize() > 0); 511 // Add the new thread to thread list 512 m_thread_data.push_back(*thread_data); 513 *thread_data = ThreadData(); 514 have_prstatus = false; 515 have_prpsinfo = false; 516 } 517 518 size_t note_start, note_size; 519 note_start = offset; 520 note_size = llvm::alignTo(note.n_descsz, 4); 521 522 // Store the NOTE information in the current thread 523 DataExtractor note_data (segment_data, note_start, note_size); 524 note_data.SetAddressByteSize(m_core_module_sp->GetArchitecture().GetAddressByteSize()); 525 if (note.n_name == "FreeBSD") 526 { 527 m_os = llvm::Triple::FreeBSD; 528 switch (note.n_type) 529 { 530 case FREEBSD::NT_PRSTATUS: 531 have_prstatus = true; 532 ParseFreeBSDPrStatus(*thread_data, note_data, arch); 533 break; 534 case FREEBSD::NT_FPREGSET: 535 thread_data->fpregset = note_data; 536 break; 537 case FREEBSD::NT_PRPSINFO: 538 have_prpsinfo = true; 539 break; 540 case FREEBSD::NT_THRMISC: 541 ParseFreeBSDThrMisc(*thread_data, note_data); 542 break; 543 case FREEBSD::NT_PROCSTAT_AUXV: 544 // FIXME: FreeBSD sticks an int at the beginning of the note 545 m_auxv = DataExtractor(segment_data, note_start + 4, note_size - 4); 546 break; 547 case FREEBSD::NT_PPC_VMX: 548 thread_data->vregset = note_data; 549 break; 550 default: 551 break; 552 } 553 } 554 else if (note.n_name == "CORE") 555 { 556 switch (note.n_type) 557 { 558 case NT_PRSTATUS: 559 have_prstatus = true; 560 prstatus.Parse(note_data, arch); 561 thread_data->signo = prstatus.pr_cursig; 562 thread_data->tid = prstatus.pr_pid; 563 header_size = ELFLinuxPrStatus::GetSize(arch); 564 len = note_data.GetByteSize() - header_size; 565 thread_data->gpregset = DataExtractor(note_data, header_size, len); 566 break; 567 case NT_FPREGSET: 568 thread_data->fpregset = note_data; 569 break; 570 case NT_PRPSINFO: 571 have_prpsinfo = true; 572 prpsinfo.Parse(note_data, arch); 573 thread_data->name = prpsinfo.pr_fname; 574 SetID(prpsinfo.pr_pid); 575 break; 576 case NT_AUXV: 577 m_auxv = DataExtractor(note_data); 578 break; 579 case NT_FILE: 580 { 581 m_nt_file_entries.clear(); 582 lldb::offset_t offset = 0; 583 const uint64_t count = note_data.GetAddress(&offset); 584 note_data.GetAddress(&offset); // Skip page size 585 for (uint64_t i = 0; i<count; ++i) 586 { 587 NT_FILE_Entry entry; 588 entry.start = note_data.GetAddress(&offset); 589 entry.end = note_data.GetAddress(&offset); 590 entry.file_ofs = note_data.GetAddress(&offset); 591 m_nt_file_entries.push_back(entry); 592 } 593 for (uint64_t i = 0; i<count; ++i) 594 { 595 const char *path = note_data.GetCStr(&offset); 596 if (path && path[0]) 597 m_nt_file_entries[i].path.SetCString(path); 598 } 599 } 600 break; 601 default: 602 break; 603 } 604 } 605 606 offset += note_size; 607 } 608 // Add last entry in the note section 609 if (thread_data && thread_data->gpregset.GetByteSize() > 0) 610 { 611 m_thread_data.push_back(*thread_data); 612 } 613 } 614 615 uint32_t 616 ProcessElfCore::GetNumThreadContexts () 617 { 618 if (!m_thread_data_valid) 619 DoLoadCore(); 620 return m_thread_data.size(); 621 } 622 623 ArchSpec 624 ProcessElfCore::GetArchitecture() 625 { 626 ObjectFileELF *core_file = (ObjectFileELF *)(m_core_module_sp->GetObjectFile()); 627 ArchSpec arch; 628 core_file->GetArchitecture(arch); 629 return arch; 630 } 631 632 const lldb::DataBufferSP 633 ProcessElfCore::GetAuxvData() 634 { 635 const uint8_t *start = m_auxv.GetDataStart(); 636 size_t len = m_auxv.GetByteSize(); 637 lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len)); 638 return buffer; 639 } 640 641 bool 642 ProcessElfCore::GetProcessInfo(ProcessInstanceInfo &info) 643 { 644 info.Clear(); 645 info.SetProcessID(GetID()); 646 info.SetArchitecture(GetArchitecture()); 647 lldb::ModuleSP module_sp = GetTarget().GetExecutableModule(); 648 if (module_sp) 649 { 650 const bool add_exe_file_as_first_arg = false; 651 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(), add_exe_file_as_first_arg); 652 } 653 return true; 654 } 655