1 //===-- ObjectFileELF.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 "ObjectFileELF.h" 10 11 #include <algorithm> 12 #include <cassert> 13 #include <unordered_map> 14 15 #include "lldb/Core/FileSpecList.h" 16 #include "lldb/Core/Module.h" 17 #include "lldb/Core/ModuleSpec.h" 18 #include "lldb/Core/PluginManager.h" 19 #include "lldb/Core/Progress.h" 20 #include "lldb/Core/Section.h" 21 #include "lldb/Host/FileSystem.h" 22 #include "lldb/Host/LZMA.h" 23 #include "lldb/Symbol/DWARFCallFrameInfo.h" 24 #include "lldb/Symbol/SymbolContext.h" 25 #include "lldb/Target/SectionLoadList.h" 26 #include "lldb/Target/Target.h" 27 #include "lldb/Utility/ArchSpec.h" 28 #include "lldb/Utility/DataBufferHeap.h" 29 #include "lldb/Utility/LLDBLog.h" 30 #include "lldb/Utility/Log.h" 31 #include "lldb/Utility/RangeMap.h" 32 #include "lldb/Utility/Status.h" 33 #include "lldb/Utility/Stream.h" 34 #include "lldb/Utility/Timer.h" 35 #include "llvm/ADT/IntervalMap.h" 36 #include "llvm/ADT/PointerUnion.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/BinaryFormat/ELF.h" 39 #include "llvm/Object/Decompressor.h" 40 #include "llvm/Support/ARMBuildAttributes.h" 41 #include "llvm/Support/CRC.h" 42 #include "llvm/Support/FormatVariadic.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/MemoryBuffer.h" 45 #include "llvm/Support/MipsABIFlags.h" 46 47 #define CASE_AND_STREAM(s, def, width) \ 48 case def: \ 49 s->Printf("%-*s", width, #def); \ 50 break; 51 52 using namespace lldb; 53 using namespace lldb_private; 54 using namespace elf; 55 using namespace llvm::ELF; 56 57 LLDB_PLUGIN_DEFINE(ObjectFileELF) 58 59 // ELF note owner definitions 60 static const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD"; 61 static const char *const LLDB_NT_OWNER_GNU = "GNU"; 62 static const char *const LLDB_NT_OWNER_NETBSD = "NetBSD"; 63 static const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE"; 64 static const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD"; 65 static const char *const LLDB_NT_OWNER_ANDROID = "Android"; 66 static const char *const LLDB_NT_OWNER_CORE = "CORE"; 67 static const char *const LLDB_NT_OWNER_LINUX = "LINUX"; 68 69 // ELF note type definitions 70 static const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01; 71 static const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4; 72 73 static const elf_word LLDB_NT_GNU_ABI_TAG = 0x01; 74 static const elf_word LLDB_NT_GNU_ABI_SIZE = 16; 75 76 static const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03; 77 78 static const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1; 79 static const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4; 80 static const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7; 81 static const elf_word LLDB_NT_NETBSD_PROCINFO = 1; 82 83 // GNU ABI note OS constants 84 static const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00; 85 static const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01; 86 static const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02; 87 88 namespace { 89 90 //===----------------------------------------------------------------------===// 91 /// \class ELFRelocation 92 /// Generic wrapper for ELFRel and ELFRela. 93 /// 94 /// This helper class allows us to parse both ELFRel and ELFRela relocation 95 /// entries in a generic manner. 96 class ELFRelocation { 97 public: 98 /// Constructs an ELFRelocation entry with a personality as given by @p 99 /// type. 100 /// 101 /// \param type Either DT_REL or DT_RELA. Any other value is invalid. 102 ELFRelocation(unsigned type); 103 104 ~ELFRelocation(); 105 106 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); 107 108 static unsigned RelocType32(const ELFRelocation &rel); 109 110 static unsigned RelocType64(const ELFRelocation &rel); 111 112 static unsigned RelocSymbol32(const ELFRelocation &rel); 113 114 static unsigned RelocSymbol64(const ELFRelocation &rel); 115 116 static unsigned RelocOffset32(const ELFRelocation &rel); 117 118 static unsigned RelocOffset64(const ELFRelocation &rel); 119 120 static unsigned RelocAddend32(const ELFRelocation &rel); 121 122 static unsigned RelocAddend64(const ELFRelocation &rel); 123 124 private: 125 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion; 126 127 RelocUnion reloc; 128 }; 129 } // end anonymous namespace 130 131 ELFRelocation::ELFRelocation(unsigned type) { 132 if (type == DT_REL || type == SHT_REL) 133 reloc = new ELFRel(); 134 else if (type == DT_RELA || type == SHT_RELA) 135 reloc = new ELFRela(); 136 else { 137 assert(false && "unexpected relocation type"); 138 reloc = static_cast<ELFRel *>(nullptr); 139 } 140 } 141 142 ELFRelocation::~ELFRelocation() { 143 if (reloc.is<ELFRel *>()) 144 delete reloc.get<ELFRel *>(); 145 else 146 delete reloc.get<ELFRela *>(); 147 } 148 149 bool ELFRelocation::Parse(const lldb_private::DataExtractor &data, 150 lldb::offset_t *offset) { 151 if (reloc.is<ELFRel *>()) 152 return reloc.get<ELFRel *>()->Parse(data, offset); 153 else 154 return reloc.get<ELFRela *>()->Parse(data, offset); 155 } 156 157 unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) { 158 if (rel.reloc.is<ELFRel *>()) 159 return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>()); 160 else 161 return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>()); 162 } 163 164 unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) { 165 if (rel.reloc.is<ELFRel *>()) 166 return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>()); 167 else 168 return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>()); 169 } 170 171 unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) { 172 if (rel.reloc.is<ELFRel *>()) 173 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>()); 174 else 175 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>()); 176 } 177 178 unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) { 179 if (rel.reloc.is<ELFRel *>()) 180 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>()); 181 else 182 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>()); 183 } 184 185 unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) { 186 if (rel.reloc.is<ELFRel *>()) 187 return rel.reloc.get<ELFRel *>()->r_offset; 188 else 189 return rel.reloc.get<ELFRela *>()->r_offset; 190 } 191 192 unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) { 193 if (rel.reloc.is<ELFRel *>()) 194 return rel.reloc.get<ELFRel *>()->r_offset; 195 else 196 return rel.reloc.get<ELFRela *>()->r_offset; 197 } 198 199 unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) { 200 if (rel.reloc.is<ELFRel *>()) 201 return 0; 202 else 203 return rel.reloc.get<ELFRela *>()->r_addend; 204 } 205 206 unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) { 207 if (rel.reloc.is<ELFRel *>()) 208 return 0; 209 else 210 return rel.reloc.get<ELFRela *>()->r_addend; 211 } 212 213 static user_id_t SegmentID(size_t PHdrIndex) { 214 return ~user_id_t(PHdrIndex); 215 } 216 217 bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) { 218 // Read all fields. 219 if (data.GetU32(offset, &n_namesz, 3) == nullptr) 220 return false; 221 222 // The name field is required to be nul-terminated, and n_namesz includes the 223 // terminating nul in observed implementations (contrary to the ELF-64 spec). 224 // A special case is needed for cores generated by some older Linux versions, 225 // which write a note named "CORE" without a nul terminator and n_namesz = 4. 226 if (n_namesz == 4) { 227 char buf[4]; 228 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4) 229 return false; 230 if (strncmp(buf, "CORE", 4) == 0) { 231 n_name = "CORE"; 232 *offset += 4; 233 return true; 234 } 235 } 236 237 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4)); 238 if (cstr == nullptr) { 239 Log *log = GetLog(LLDBLog::Symbols); 240 LLDB_LOGF(log, "Failed to parse note name lacking nul terminator"); 241 242 return false; 243 } 244 n_name = cstr; 245 return true; 246 } 247 248 static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) { 249 const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH; 250 uint32_t endian = header.e_ident[EI_DATA]; 251 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown; 252 uint32_t fileclass = header.e_ident[EI_CLASS]; 253 254 // If there aren't any elf flags available (e.g core elf file) then return 255 // default 256 // 32 or 64 bit arch (without any architecture revision) based on object file's class. 257 if (header.e_type == ET_CORE) { 258 switch (fileclass) { 259 case llvm::ELF::ELFCLASS32: 260 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el 261 : ArchSpec::eMIPSSubType_mips32; 262 case llvm::ELF::ELFCLASS64: 263 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el 264 : ArchSpec::eMIPSSubType_mips64; 265 default: 266 return arch_variant; 267 } 268 } 269 270 switch (mips_arch) { 271 case llvm::ELF::EF_MIPS_ARCH_1: 272 case llvm::ELF::EF_MIPS_ARCH_2: 273 case llvm::ELF::EF_MIPS_ARCH_32: 274 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el 275 : ArchSpec::eMIPSSubType_mips32; 276 case llvm::ELF::EF_MIPS_ARCH_32R2: 277 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el 278 : ArchSpec::eMIPSSubType_mips32r2; 279 case llvm::ELF::EF_MIPS_ARCH_32R6: 280 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el 281 : ArchSpec::eMIPSSubType_mips32r6; 282 case llvm::ELF::EF_MIPS_ARCH_3: 283 case llvm::ELF::EF_MIPS_ARCH_4: 284 case llvm::ELF::EF_MIPS_ARCH_5: 285 case llvm::ELF::EF_MIPS_ARCH_64: 286 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el 287 : ArchSpec::eMIPSSubType_mips64; 288 case llvm::ELF::EF_MIPS_ARCH_64R2: 289 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el 290 : ArchSpec::eMIPSSubType_mips64r2; 291 case llvm::ELF::EF_MIPS_ARCH_64R6: 292 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el 293 : ArchSpec::eMIPSSubType_mips64r6; 294 default: 295 break; 296 } 297 298 return arch_variant; 299 } 300 301 static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header) { 302 uint32_t fileclass = header.e_ident[EI_CLASS]; 303 switch (fileclass) { 304 case llvm::ELF::ELFCLASS32: 305 return ArchSpec::eRISCVSubType_riscv32; 306 case llvm::ELF::ELFCLASS64: 307 return ArchSpec::eRISCVSubType_riscv64; 308 default: 309 return ArchSpec::eRISCVSubType_unknown; 310 } 311 } 312 313 static uint32_t ppc64VariantFromElfFlags(const elf::ELFHeader &header) { 314 uint32_t endian = header.e_ident[EI_DATA]; 315 if (endian == ELFDATA2LSB) 316 return ArchSpec::eCore_ppc64le_generic; 317 else 318 return ArchSpec::eCore_ppc64_generic; 319 } 320 321 static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) { 322 if (header.e_machine == llvm::ELF::EM_MIPS) 323 return mipsVariantFromElfFlags(header); 324 else if (header.e_machine == llvm::ELF::EM_PPC64) 325 return ppc64VariantFromElfFlags(header); 326 else if (header.e_machine == llvm::ELF::EM_RISCV) 327 return riscvVariantFromElfFlags(header); 328 329 return LLDB_INVALID_CPUTYPE; 330 } 331 332 char ObjectFileELF::ID; 333 334 // Arbitrary constant used as UUID prefix for core files. 335 const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C); 336 337 // Static methods. 338 void ObjectFileELF::Initialize() { 339 PluginManager::RegisterPlugin(GetPluginNameStatic(), 340 GetPluginDescriptionStatic(), CreateInstance, 341 CreateMemoryInstance, GetModuleSpecifications); 342 } 343 344 void ObjectFileELF::Terminate() { 345 PluginManager::UnregisterPlugin(CreateInstance); 346 } 347 348 ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp, 349 DataBufferSP data_sp, 350 lldb::offset_t data_offset, 351 const lldb_private::FileSpec *file, 352 lldb::offset_t file_offset, 353 lldb::offset_t length) { 354 bool mapped_writable = false; 355 if (!data_sp) { 356 data_sp = MapFileDataWritable(*file, length, file_offset); 357 if (!data_sp) 358 return nullptr; 359 data_offset = 0; 360 mapped_writable = true; 361 } 362 363 assert(data_sp); 364 365 if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset)) 366 return nullptr; 367 368 const uint8_t *magic = data_sp->GetBytes() + data_offset; 369 if (!ELFHeader::MagicBytesMatch(magic)) 370 return nullptr; 371 372 // Update the data to contain the entire file if it doesn't already 373 if (data_sp->GetByteSize() < length) { 374 data_sp = MapFileDataWritable(*file, length, file_offset); 375 if (!data_sp) 376 return nullptr; 377 data_offset = 0; 378 mapped_writable = true; 379 magic = data_sp->GetBytes(); 380 } 381 382 // If we didn't map the data as writable take ownership of the buffer. 383 if (!mapped_writable) { 384 data_sp = std::make_shared<DataBufferHeap>(data_sp->GetBytes(), 385 data_sp->GetByteSize()); 386 data_offset = 0; 387 magic = data_sp->GetBytes(); 388 } 389 390 unsigned address_size = ELFHeader::AddressSizeInBytes(magic); 391 if (address_size == 4 || address_size == 8) { 392 std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF( 393 module_sp, data_sp, data_offset, file, file_offset, length)); 394 ArchSpec spec = objfile_up->GetArchitecture(); 395 if (spec && objfile_up->SetModulesArchitecture(spec)) 396 return objfile_up.release(); 397 } 398 399 return nullptr; 400 } 401 402 ObjectFile *ObjectFileELF::CreateMemoryInstance( 403 const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp, 404 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) { 405 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) { 406 const uint8_t *magic = data_sp->GetBytes(); 407 if (ELFHeader::MagicBytesMatch(magic)) { 408 unsigned address_size = ELFHeader::AddressSizeInBytes(magic); 409 if (address_size == 4 || address_size == 8) { 410 std::unique_ptr<ObjectFileELF> objfile_up( 411 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr)); 412 ArchSpec spec = objfile_up->GetArchitecture(); 413 if (spec && objfile_up->SetModulesArchitecture(spec)) 414 return objfile_up.release(); 415 } 416 } 417 } 418 return nullptr; 419 } 420 421 bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp, 422 lldb::addr_t data_offset, 423 lldb::addr_t data_length) { 424 if (data_sp && 425 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) { 426 const uint8_t *magic = data_sp->GetBytes() + data_offset; 427 return ELFHeader::MagicBytesMatch(magic); 428 } 429 return false; 430 } 431 432 static uint32_t calc_crc32(uint32_t init, const DataExtractor &data) { 433 return llvm::crc32( 434 init, llvm::makeArrayRef(data.GetDataStart(), data.GetByteSize())); 435 } 436 437 uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32( 438 const ProgramHeaderColl &program_headers, DataExtractor &object_data) { 439 440 uint32_t core_notes_crc = 0; 441 442 for (const ELFProgramHeader &H : program_headers) { 443 if (H.p_type == llvm::ELF::PT_NOTE) { 444 const elf_off ph_offset = H.p_offset; 445 const size_t ph_size = H.p_filesz; 446 447 DataExtractor segment_data; 448 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) { 449 // The ELF program header contained incorrect data, probably corefile 450 // is incomplete or corrupted. 451 break; 452 } 453 454 core_notes_crc = calc_crc32(core_notes_crc, segment_data); 455 } 456 } 457 458 return core_notes_crc; 459 } 460 461 static const char *OSABIAsCString(unsigned char osabi_byte) { 462 #define _MAKE_OSABI_CASE(x) \ 463 case x: \ 464 return #x 465 switch (osabi_byte) { 466 _MAKE_OSABI_CASE(ELFOSABI_NONE); 467 _MAKE_OSABI_CASE(ELFOSABI_HPUX); 468 _MAKE_OSABI_CASE(ELFOSABI_NETBSD); 469 _MAKE_OSABI_CASE(ELFOSABI_GNU); 470 _MAKE_OSABI_CASE(ELFOSABI_HURD); 471 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS); 472 _MAKE_OSABI_CASE(ELFOSABI_AIX); 473 _MAKE_OSABI_CASE(ELFOSABI_IRIX); 474 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD); 475 _MAKE_OSABI_CASE(ELFOSABI_TRU64); 476 _MAKE_OSABI_CASE(ELFOSABI_MODESTO); 477 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD); 478 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS); 479 _MAKE_OSABI_CASE(ELFOSABI_NSK); 480 _MAKE_OSABI_CASE(ELFOSABI_AROS); 481 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS); 482 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI); 483 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX); 484 _MAKE_OSABI_CASE(ELFOSABI_ARM); 485 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE); 486 default: 487 return "<unknown-osabi>"; 488 } 489 #undef _MAKE_OSABI_CASE 490 } 491 492 // 493 // WARNING : This function is being deprecated 494 // It's functionality has moved to ArchSpec::SetArchitecture This function is 495 // only being kept to validate the move. 496 // 497 // TODO : Remove this function 498 static bool GetOsFromOSABI(unsigned char osabi_byte, 499 llvm::Triple::OSType &ostype) { 500 switch (osabi_byte) { 501 case ELFOSABI_AIX: 502 ostype = llvm::Triple::OSType::AIX; 503 break; 504 case ELFOSABI_FREEBSD: 505 ostype = llvm::Triple::OSType::FreeBSD; 506 break; 507 case ELFOSABI_GNU: 508 ostype = llvm::Triple::OSType::Linux; 509 break; 510 case ELFOSABI_NETBSD: 511 ostype = llvm::Triple::OSType::NetBSD; 512 break; 513 case ELFOSABI_OPENBSD: 514 ostype = llvm::Triple::OSType::OpenBSD; 515 break; 516 case ELFOSABI_SOLARIS: 517 ostype = llvm::Triple::OSType::Solaris; 518 break; 519 default: 520 ostype = llvm::Triple::OSType::UnknownOS; 521 } 522 return ostype != llvm::Triple::OSType::UnknownOS; 523 } 524 525 size_t ObjectFileELF::GetModuleSpecifications( 526 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp, 527 lldb::offset_t data_offset, lldb::offset_t file_offset, 528 lldb::offset_t length, lldb_private::ModuleSpecList &specs) { 529 Log *log = GetLog(LLDBLog::Modules); 530 531 const size_t initial_count = specs.GetSize(); 532 533 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) { 534 DataExtractor data; 535 data.SetData(data_sp); 536 elf::ELFHeader header; 537 lldb::offset_t header_offset = data_offset; 538 if (header.Parse(data, &header_offset)) { 539 if (data_sp) { 540 ModuleSpec spec(file); 541 542 const uint32_t sub_type = subTypeFromElfHeader(header); 543 spec.GetArchitecture().SetArchitecture( 544 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]); 545 546 if (spec.GetArchitecture().IsValid()) { 547 llvm::Triple::OSType ostype; 548 llvm::Triple::VendorType vendor; 549 llvm::Triple::OSType spec_ostype = 550 spec.GetArchitecture().GetTriple().getOS(); 551 552 LLDB_LOGF(log, "ObjectFileELF::%s file '%s' module OSABI: %s", 553 __FUNCTION__, file.GetPath().c_str(), 554 OSABIAsCString(header.e_ident[EI_OSABI])); 555 556 // SetArchitecture should have set the vendor to unknown 557 vendor = spec.GetArchitecture().GetTriple().getVendor(); 558 assert(vendor == llvm::Triple::UnknownVendor); 559 UNUSED_IF_ASSERT_DISABLED(vendor); 560 561 // 562 // Validate it is ok to remove GetOsFromOSABI 563 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype); 564 assert(spec_ostype == ostype); 565 if (spec_ostype != llvm::Triple::OSType::UnknownOS) { 566 LLDB_LOGF(log, 567 "ObjectFileELF::%s file '%s' set ELF module OS type " 568 "from ELF header OSABI.", 569 __FUNCTION__, file.GetPath().c_str()); 570 } 571 572 if (data_sp->GetByteSize() < length) 573 data_sp = MapFileData(file, -1, file_offset); 574 if (data_sp) 575 data.SetData(data_sp); 576 // In case there is header extension in the section #0, the header we 577 // parsed above could have sentinel values for e_phnum, e_shnum, and 578 // e_shstrndx. In this case we need to reparse the header with a 579 // bigger data source to get the actual values. 580 if (header.HasHeaderExtension()) { 581 lldb::offset_t header_offset = data_offset; 582 header.Parse(data, &header_offset); 583 } 584 585 uint32_t gnu_debuglink_crc = 0; 586 std::string gnu_debuglink_file; 587 SectionHeaderColl section_headers; 588 lldb_private::UUID &uuid = spec.GetUUID(); 589 590 GetSectionHeaderInfo(section_headers, data, header, uuid, 591 gnu_debuglink_file, gnu_debuglink_crc, 592 spec.GetArchitecture()); 593 594 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple(); 595 596 LLDB_LOGF(log, 597 "ObjectFileELF::%s file '%s' module set to triple: %s " 598 "(architecture %s)", 599 __FUNCTION__, file.GetPath().c_str(), 600 spec_triple.getTriple().c_str(), 601 spec.GetArchitecture().GetArchitectureName()); 602 603 if (!uuid.IsValid()) { 604 uint32_t core_notes_crc = 0; 605 606 if (!gnu_debuglink_crc) { 607 LLDB_SCOPED_TIMERF( 608 "Calculating module crc32 %s with size %" PRIu64 " KiB", 609 file.GetLastPathComponent().AsCString(), 610 (length - file_offset) / 1024); 611 612 // For core files - which usually don't happen to have a 613 // gnu_debuglink, and are pretty bulky - calculating whole 614 // contents crc32 would be too much of luxury. Thus we will need 615 // to fallback to something simpler. 616 if (header.e_type == llvm::ELF::ET_CORE) { 617 ProgramHeaderColl program_headers; 618 GetProgramHeaderInfo(program_headers, data, header); 619 620 core_notes_crc = 621 CalculateELFNotesSegmentsCRC32(program_headers, data); 622 } else { 623 gnu_debuglink_crc = calc_crc32(0, data); 624 } 625 } 626 using u32le = llvm::support::ulittle32_t; 627 if (gnu_debuglink_crc) { 628 // Use 4 bytes of crc from the .gnu_debuglink section. 629 u32le data(gnu_debuglink_crc); 630 uuid = UUID(&data, sizeof(data)); 631 } else if (core_notes_crc) { 632 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make 633 // it look different form .gnu_debuglink crc followed by 4 bytes 634 // of note segments crc. 635 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; 636 uuid = UUID(data, sizeof(data)); 637 } 638 } 639 640 specs.Append(spec); 641 } 642 } 643 } 644 } 645 646 return specs.GetSize() - initial_count; 647 } 648 649 // ObjectFile protocol 650 651 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp, 652 DataBufferSP data_sp, lldb::offset_t data_offset, 653 const FileSpec *file, lldb::offset_t file_offset, 654 lldb::offset_t length) 655 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset) { 656 if (file) 657 m_file = *file; 658 } 659 660 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp, 661 DataBufferSP header_data_sp, 662 const lldb::ProcessSP &process_sp, 663 addr_t header_addr) 664 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp) {} 665 666 bool ObjectFileELF::IsExecutable() const { 667 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0); 668 } 669 670 bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value, 671 bool value_is_offset) { 672 ModuleSP module_sp = GetModule(); 673 if (module_sp) { 674 size_t num_loaded_sections = 0; 675 SectionList *section_list = GetSectionList(); 676 if (section_list) { 677 if (!value_is_offset) { 678 addr_t base = GetBaseAddress().GetFileAddress(); 679 if (base == LLDB_INVALID_ADDRESS) 680 return false; 681 value -= base; 682 } 683 684 const size_t num_sections = section_list->GetSize(); 685 size_t sect_idx = 0; 686 687 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 688 // Iterate through the object file sections to find all of the sections 689 // that have SHF_ALLOC in their flag bits. 690 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); 691 if (section_sp->Test(SHF_ALLOC) || 692 section_sp->GetType() == eSectionTypeContainer) { 693 lldb::addr_t load_addr = section_sp->GetFileAddress(); 694 // We don't want to update the load address of a section with type 695 // eSectionTypeAbsoluteAddress as they already have the absolute load 696 // address already specified 697 if (section_sp->GetType() != eSectionTypeAbsoluteAddress) 698 load_addr += value; 699 700 // On 32-bit systems the load address have to fit into 4 bytes. The 701 // rest of the bytes are the overflow from the addition. 702 if (GetAddressByteSize() == 4) 703 load_addr &= 0xFFFFFFFF; 704 705 if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp, 706 load_addr)) 707 ++num_loaded_sections; 708 } 709 } 710 return num_loaded_sections > 0; 711 } 712 } 713 return false; 714 } 715 716 ByteOrder ObjectFileELF::GetByteOrder() const { 717 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB) 718 return eByteOrderBig; 719 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB) 720 return eByteOrderLittle; 721 return eByteOrderInvalid; 722 } 723 724 uint32_t ObjectFileELF::GetAddressByteSize() const { 725 return m_data.GetAddressByteSize(); 726 } 727 728 AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) { 729 Symtab *symtab = GetSymtab(); 730 if (!symtab) 731 return AddressClass::eUnknown; 732 733 // The address class is determined based on the symtab. Ask it from the 734 // object file what contains the symtab information. 735 ObjectFile *symtab_objfile = symtab->GetObjectFile(); 736 if (symtab_objfile != nullptr && symtab_objfile != this) 737 return symtab_objfile->GetAddressClass(file_addr); 738 739 auto res = ObjectFile::GetAddressClass(file_addr); 740 if (res != AddressClass::eCode) 741 return res; 742 743 auto ub = m_address_class_map.upper_bound(file_addr); 744 if (ub == m_address_class_map.begin()) { 745 // No entry in the address class map before the address. Return default 746 // address class for an address in a code section. 747 return AddressClass::eCode; 748 } 749 750 // Move iterator to the address class entry preceding address 751 --ub; 752 753 return ub->second; 754 } 755 756 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) { 757 return std::distance(m_section_headers.begin(), I); 758 } 759 760 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const { 761 return std::distance(m_section_headers.begin(), I); 762 } 763 764 bool ObjectFileELF::ParseHeader() { 765 lldb::offset_t offset = 0; 766 return m_header.Parse(m_data, &offset); 767 } 768 769 UUID ObjectFileELF::GetUUID() { 770 // Need to parse the section list to get the UUIDs, so make sure that's been 771 // done. 772 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile) 773 return UUID(); 774 775 if (!m_uuid) { 776 using u32le = llvm::support::ulittle32_t; 777 if (GetType() == ObjectFile::eTypeCoreFile) { 778 uint32_t core_notes_crc = 0; 779 780 if (!ParseProgramHeaders()) 781 return UUID(); 782 783 core_notes_crc = 784 CalculateELFNotesSegmentsCRC32(m_program_headers, m_data); 785 786 if (core_notes_crc) { 787 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it 788 // look different form .gnu_debuglink crc - followed by 4 bytes of note 789 // segments crc. 790 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; 791 m_uuid = UUID(data, sizeof(data)); 792 } 793 } else { 794 if (!m_gnu_debuglink_crc) 795 m_gnu_debuglink_crc = calc_crc32(0, m_data); 796 if (m_gnu_debuglink_crc) { 797 // Use 4 bytes of crc from the .gnu_debuglink section. 798 u32le data(m_gnu_debuglink_crc); 799 m_uuid = UUID(&data, sizeof(data)); 800 } 801 } 802 } 803 804 return m_uuid; 805 } 806 807 llvm::Optional<FileSpec> ObjectFileELF::GetDebugLink() { 808 if (m_gnu_debuglink_file.empty()) 809 return llvm::None; 810 return FileSpec(m_gnu_debuglink_file); 811 } 812 813 uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) { 814 size_t num_modules = ParseDependentModules(); 815 uint32_t num_specs = 0; 816 817 for (unsigned i = 0; i < num_modules; ++i) { 818 if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i))) 819 num_specs++; 820 } 821 822 return num_specs; 823 } 824 825 Address ObjectFileELF::GetImageInfoAddress(Target *target) { 826 if (!ParseDynamicSymbols()) 827 return Address(); 828 829 SectionList *section_list = GetSectionList(); 830 if (!section_list) 831 return Address(); 832 833 // Find the SHT_DYNAMIC (.dynamic) section. 834 SectionSP dynsym_section_sp( 835 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)); 836 if (!dynsym_section_sp) 837 return Address(); 838 assert(dynsym_section_sp->GetObjectFile() == this); 839 840 user_id_t dynsym_id = dynsym_section_sp->GetID(); 841 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id); 842 if (!dynsym_hdr) 843 return Address(); 844 845 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) { 846 ELFDynamic &symbol = m_dynamic_symbols[i]; 847 848 if (symbol.d_tag == DT_DEBUG) { 849 // Compute the offset as the number of previous entries plus the size of 850 // d_tag. 851 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize(); 852 return Address(dynsym_section_sp, offset); 853 } 854 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP 855 // exists in non-PIE. 856 else if ((symbol.d_tag == DT_MIPS_RLD_MAP || 857 symbol.d_tag == DT_MIPS_RLD_MAP_REL) && 858 target) { 859 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize(); 860 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target); 861 if (dyn_base == LLDB_INVALID_ADDRESS) 862 return Address(); 863 864 Status error; 865 if (symbol.d_tag == DT_MIPS_RLD_MAP) { 866 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer. 867 Address addr; 868 if (target->ReadPointerFromMemory(dyn_base + offset, error, addr, true)) 869 return addr; 870 } 871 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) { 872 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer, 873 // relative to the address of the tag. 874 uint64_t rel_offset; 875 rel_offset = target->ReadUnsignedIntegerFromMemory( 876 dyn_base + offset, GetAddressByteSize(), UINT64_MAX, error, true); 877 if (error.Success() && rel_offset != UINT64_MAX) { 878 Address addr; 879 addr_t debug_ptr_address = 880 dyn_base + (offset - GetAddressByteSize()) + rel_offset; 881 addr.SetOffset(debug_ptr_address); 882 return addr; 883 } 884 } 885 } 886 } 887 888 return Address(); 889 } 890 891 lldb_private::Address ObjectFileELF::GetEntryPointAddress() { 892 if (m_entry_point_address.IsValid()) 893 return m_entry_point_address; 894 895 if (!ParseHeader() || !IsExecutable()) 896 return m_entry_point_address; 897 898 SectionList *section_list = GetSectionList(); 899 addr_t offset = m_header.e_entry; 900 901 if (!section_list) 902 m_entry_point_address.SetOffset(offset); 903 else 904 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list); 905 return m_entry_point_address; 906 } 907 908 Address ObjectFileELF::GetBaseAddress() { 909 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) { 910 const ELFProgramHeader &H = EnumPHdr.value(); 911 if (H.p_type != PT_LOAD) 912 continue; 913 914 return Address( 915 GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0); 916 } 917 return LLDB_INVALID_ADDRESS; 918 } 919 920 // ParseDependentModules 921 size_t ObjectFileELF::ParseDependentModules() { 922 if (m_filespec_up) 923 return m_filespec_up->GetSize(); 924 925 m_filespec_up = std::make_unique<FileSpecList>(); 926 927 if (!ParseSectionHeaders()) 928 return 0; 929 930 SectionList *section_list = GetSectionList(); 931 if (!section_list) 932 return 0; 933 934 // Find the SHT_DYNAMIC section. 935 Section *dynsym = 936 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true) 937 .get(); 938 if (!dynsym) 939 return 0; 940 assert(dynsym->GetObjectFile() == this); 941 942 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID()); 943 if (!header) 944 return 0; 945 // sh_link: section header index of string table used by entries in the 946 // section. 947 Section *dynstr = section_list->FindSectionByID(header->sh_link).get(); 948 if (!dynstr) 949 return 0; 950 951 DataExtractor dynsym_data; 952 DataExtractor dynstr_data; 953 if (ReadSectionData(dynsym, dynsym_data) && 954 ReadSectionData(dynstr, dynstr_data)) { 955 ELFDynamic symbol; 956 const lldb::offset_t section_size = dynsym_data.GetByteSize(); 957 lldb::offset_t offset = 0; 958 959 // The only type of entries we are concerned with are tagged DT_NEEDED, 960 // yielding the name of a required library. 961 while (offset < section_size) { 962 if (!symbol.Parse(dynsym_data, &offset)) 963 break; 964 965 if (symbol.d_tag != DT_NEEDED) 966 continue; 967 968 uint32_t str_index = static_cast<uint32_t>(symbol.d_val); 969 const char *lib_name = dynstr_data.PeekCStr(str_index); 970 FileSpec file_spec(lib_name); 971 FileSystem::Instance().Resolve(file_spec); 972 m_filespec_up->Append(file_spec); 973 } 974 } 975 976 return m_filespec_up->GetSize(); 977 } 978 979 // GetProgramHeaderInfo 980 size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers, 981 DataExtractor &object_data, 982 const ELFHeader &header) { 983 // We have already parsed the program headers 984 if (!program_headers.empty()) 985 return program_headers.size(); 986 987 // If there are no program headers to read we are done. 988 if (header.e_phnum == 0) 989 return 0; 990 991 program_headers.resize(header.e_phnum); 992 if (program_headers.size() != header.e_phnum) 993 return 0; 994 995 const size_t ph_size = header.e_phnum * header.e_phentsize; 996 const elf_off ph_offset = header.e_phoff; 997 DataExtractor data; 998 if (data.SetData(object_data, ph_offset, ph_size) != ph_size) 999 return 0; 1000 1001 uint32_t idx; 1002 lldb::offset_t offset; 1003 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) { 1004 if (!program_headers[idx].Parse(data, &offset)) 1005 break; 1006 } 1007 1008 if (idx < program_headers.size()) 1009 program_headers.resize(idx); 1010 1011 return program_headers.size(); 1012 } 1013 1014 // ParseProgramHeaders 1015 bool ObjectFileELF::ParseProgramHeaders() { 1016 return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0; 1017 } 1018 1019 lldb_private::Status 1020 ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data, 1021 lldb_private::ArchSpec &arch_spec, 1022 lldb_private::UUID &uuid) { 1023 Log *log = GetLog(LLDBLog::Modules); 1024 Status error; 1025 1026 lldb::offset_t offset = 0; 1027 1028 while (true) { 1029 // Parse the note header. If this fails, bail out. 1030 const lldb::offset_t note_offset = offset; 1031 ELFNote note = ELFNote(); 1032 if (!note.Parse(data, &offset)) { 1033 // We're done. 1034 return error; 1035 } 1036 1037 LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32, 1038 __FUNCTION__, note.n_name.c_str(), note.n_type); 1039 1040 // Process FreeBSD ELF notes. 1041 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) && 1042 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) && 1043 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) { 1044 // Pull out the min version info. 1045 uint32_t version_info; 1046 if (data.GetU32(&offset, &version_info, 1) == nullptr) { 1047 error.SetErrorString("failed to read FreeBSD ABI note payload"); 1048 return error; 1049 } 1050 1051 // Convert the version info into a major/minor number. 1052 const uint32_t version_major = version_info / 100000; 1053 const uint32_t version_minor = (version_info / 1000) % 100; 1054 1055 char os_name[32]; 1056 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32, 1057 version_major, version_minor); 1058 1059 // Set the elf OS version to FreeBSD. Also clear the vendor. 1060 arch_spec.GetTriple().setOSName(os_name); 1061 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); 1062 1063 LLDB_LOGF(log, 1064 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32 1065 ".%" PRIu32, 1066 __FUNCTION__, version_major, version_minor, 1067 static_cast<uint32_t>(version_info % 1000)); 1068 } 1069 // Process GNU ELF notes. 1070 else if (note.n_name == LLDB_NT_OWNER_GNU) { 1071 switch (note.n_type) { 1072 case LLDB_NT_GNU_ABI_TAG: 1073 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) { 1074 // Pull out the min OS version supporting the ABI. 1075 uint32_t version_info[4]; 1076 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) == 1077 nullptr) { 1078 error.SetErrorString("failed to read GNU ABI note payload"); 1079 return error; 1080 } 1081 1082 // Set the OS per the OS field. 1083 switch (version_info[0]) { 1084 case LLDB_NT_GNU_ABI_OS_LINUX: 1085 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1086 arch_spec.GetTriple().setVendor( 1087 llvm::Triple::VendorType::UnknownVendor); 1088 LLDB_LOGF(log, 1089 "ObjectFileELF::%s detected Linux, min version %" PRIu32 1090 ".%" PRIu32 ".%" PRIu32, 1091 __FUNCTION__, version_info[1], version_info[2], 1092 version_info[3]); 1093 // FIXME we have the minimal version number, we could be propagating 1094 // that. version_info[1] = OS Major, version_info[2] = OS Minor, 1095 // version_info[3] = Revision. 1096 break; 1097 case LLDB_NT_GNU_ABI_OS_HURD: 1098 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS); 1099 arch_spec.GetTriple().setVendor( 1100 llvm::Triple::VendorType::UnknownVendor); 1101 LLDB_LOGF(log, 1102 "ObjectFileELF::%s detected Hurd (unsupported), min " 1103 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32, 1104 __FUNCTION__, version_info[1], version_info[2], 1105 version_info[3]); 1106 break; 1107 case LLDB_NT_GNU_ABI_OS_SOLARIS: 1108 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris); 1109 arch_spec.GetTriple().setVendor( 1110 llvm::Triple::VendorType::UnknownVendor); 1111 LLDB_LOGF(log, 1112 "ObjectFileELF::%s detected Solaris, min version %" PRIu32 1113 ".%" PRIu32 ".%" PRIu32, 1114 __FUNCTION__, version_info[1], version_info[2], 1115 version_info[3]); 1116 break; 1117 default: 1118 LLDB_LOGF(log, 1119 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32 1120 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32, 1121 __FUNCTION__, version_info[0], version_info[1], 1122 version_info[2], version_info[3]); 1123 break; 1124 } 1125 } 1126 break; 1127 1128 case LLDB_NT_GNU_BUILD_ID_TAG: 1129 // Only bother processing this if we don't already have the uuid set. 1130 if (!uuid.IsValid()) { 1131 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a 1132 // build-id of a different length. Accept it as long as it's at least 1133 // 4 bytes as it will be better than our own crc32. 1134 if (note.n_descsz >= 4) { 1135 if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) { 1136 // Save the build id as the UUID for the module. 1137 uuid = UUID(buf, note.n_descsz); 1138 } else { 1139 error.SetErrorString("failed to read GNU_BUILD_ID note payload"); 1140 return error; 1141 } 1142 } 1143 } 1144 break; 1145 } 1146 if (arch_spec.IsMIPS() && 1147 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) 1148 // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform 1149 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1150 } 1151 // Process NetBSD ELF executables and shared libraries 1152 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) && 1153 (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) && 1154 (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) && 1155 (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) { 1156 // Pull out the version info. 1157 uint32_t version_info; 1158 if (data.GetU32(&offset, &version_info, 1) == nullptr) { 1159 error.SetErrorString("failed to read NetBSD ABI note payload"); 1160 return error; 1161 } 1162 // Convert the version info into a major/minor/patch number. 1163 // #define __NetBSD_Version__ MMmmrrpp00 1164 // 1165 // M = major version 1166 // m = minor version; a minor number of 99 indicates current. 1167 // r = 0 (since NetBSD 3.0 not used) 1168 // p = patchlevel 1169 const uint32_t version_major = version_info / 100000000; 1170 const uint32_t version_minor = (version_info % 100000000) / 1000000; 1171 const uint32_t version_patch = (version_info % 10000) / 100; 1172 // Set the elf OS version to NetBSD. Also clear the vendor. 1173 arch_spec.GetTriple().setOSName( 1174 llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor, 1175 version_patch).str()); 1176 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); 1177 } 1178 // Process NetBSD ELF core(5) notes 1179 else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) && 1180 (note.n_type == LLDB_NT_NETBSD_PROCINFO)) { 1181 // Set the elf OS version to NetBSD. Also clear the vendor. 1182 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD); 1183 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); 1184 } 1185 // Process OpenBSD ELF notes. 1186 else if (note.n_name == LLDB_NT_OWNER_OPENBSD) { 1187 // Set the elf OS version to OpenBSD. Also clear the vendor. 1188 arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD); 1189 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor); 1190 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) { 1191 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1192 arch_spec.GetTriple().setEnvironment( 1193 llvm::Triple::EnvironmentType::Android); 1194 } else if (note.n_name == LLDB_NT_OWNER_LINUX) { 1195 // This is sometimes found in core files and usually contains extended 1196 // register info 1197 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1198 } else if (note.n_name == LLDB_NT_OWNER_CORE) { 1199 // Parse the NT_FILE to look for stuff in paths to shared libraries 1200 // The contents look like this in a 64 bit ELF core file: 1201 // 1202 // count = 0x000000000000000a (10) 1203 // page_size = 0x0000000000001000 (4096) 1204 // Index start end file_ofs path 1205 // ===== ------------------ ------------------ ------------------ ------------------------------------- 1206 // [ 0] 0x0000000000401000 0x0000000000000000 /tmp/a.out 1207 // [ 1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out 1208 // [ 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out 1209 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so 1210 // [ 4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so 1211 // [ 5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so 1212 // [ 6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so 1213 // [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so 1214 // [ 8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so 1215 // [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so 1216 // 1217 // In the 32 bit ELFs the count, page_size, start, end, file_ofs are 1218 // uint32_t. 1219 // 1220 // For reference: see readelf source code (in binutils). 1221 if (note.n_type == NT_FILE) { 1222 uint64_t count = data.GetAddress(&offset); 1223 const char *cstr; 1224 data.GetAddress(&offset); // Skip page size 1225 offset += count * 3 * 1226 data.GetAddressByteSize(); // Skip all start/end/file_ofs 1227 for (size_t i = 0; i < count; ++i) { 1228 cstr = data.GetCStr(&offset); 1229 if (cstr == nullptr) { 1230 error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read " 1231 "at an offset after the end " 1232 "(GetCStr returned nullptr)", 1233 __FUNCTION__); 1234 return error; 1235 } 1236 llvm::StringRef path(cstr); 1237 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) { 1238 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1239 break; 1240 } 1241 } 1242 if (arch_spec.IsMIPS() && 1243 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) 1244 // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some 1245 // cases (e.g. compile with -nostdlib) Hence set OS to Linux 1246 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux); 1247 } 1248 } 1249 1250 // Calculate the offset of the next note just in case "offset" has been 1251 // used to poke at the contents of the note data 1252 offset = note_offset + note.GetByteSize(); 1253 } 1254 1255 return error; 1256 } 1257 1258 void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length, 1259 ArchSpec &arch_spec) { 1260 lldb::offset_t Offset = 0; 1261 1262 uint8_t FormatVersion = data.GetU8(&Offset); 1263 if (FormatVersion != llvm::ELFAttrs::Format_Version) 1264 return; 1265 1266 Offset = Offset + sizeof(uint32_t); // Section Length 1267 llvm::StringRef VendorName = data.GetCStr(&Offset); 1268 1269 if (VendorName != "aeabi") 1270 return; 1271 1272 if (arch_spec.GetTriple().getEnvironment() == 1273 llvm::Triple::UnknownEnvironment) 1274 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI); 1275 1276 while (Offset < length) { 1277 uint8_t Tag = data.GetU8(&Offset); 1278 uint32_t Size = data.GetU32(&Offset); 1279 1280 if (Tag != llvm::ARMBuildAttrs::File || Size == 0) 1281 continue; 1282 1283 while (Offset < length) { 1284 uint64_t Tag = data.GetULEB128(&Offset); 1285 switch (Tag) { 1286 default: 1287 if (Tag < 32) 1288 data.GetULEB128(&Offset); 1289 else if (Tag % 2 == 0) 1290 data.GetULEB128(&Offset); 1291 else 1292 data.GetCStr(&Offset); 1293 1294 break; 1295 1296 case llvm::ARMBuildAttrs::CPU_raw_name: 1297 case llvm::ARMBuildAttrs::CPU_name: 1298 data.GetCStr(&Offset); 1299 1300 break; 1301 1302 case llvm::ARMBuildAttrs::ABI_VFP_args: { 1303 uint64_t VFPArgs = data.GetULEB128(&Offset); 1304 1305 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) { 1306 if (arch_spec.GetTriple().getEnvironment() == 1307 llvm::Triple::UnknownEnvironment || 1308 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF) 1309 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI); 1310 1311 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float); 1312 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) { 1313 if (arch_spec.GetTriple().getEnvironment() == 1314 llvm::Triple::UnknownEnvironment || 1315 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI) 1316 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF); 1317 1318 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float); 1319 } 1320 1321 break; 1322 } 1323 } 1324 } 1325 } 1326 } 1327 1328 // GetSectionHeaderInfo 1329 size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl §ion_headers, 1330 DataExtractor &object_data, 1331 const elf::ELFHeader &header, 1332 lldb_private::UUID &uuid, 1333 std::string &gnu_debuglink_file, 1334 uint32_t &gnu_debuglink_crc, 1335 ArchSpec &arch_spec) { 1336 // Don't reparse the section headers if we already did that. 1337 if (!section_headers.empty()) 1338 return section_headers.size(); 1339 1340 // Only initialize the arch_spec to okay defaults if they're not already set. 1341 // We'll refine this with note data as we parse the notes. 1342 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) { 1343 llvm::Triple::OSType ostype; 1344 llvm::Triple::OSType spec_ostype; 1345 const uint32_t sub_type = subTypeFromElfHeader(header); 1346 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type, 1347 header.e_ident[EI_OSABI]); 1348 1349 // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is 1350 // determined based on EI_OSABI flag and the info extracted from ELF notes 1351 // (see RefineModuleDetailsFromNote). However in some cases that still 1352 // might be not enough: for example a shared library might not have any 1353 // notes at all and have EI_OSABI flag set to System V, as result the OS 1354 // will be set to UnknownOS. 1355 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype); 1356 spec_ostype = arch_spec.GetTriple().getOS(); 1357 assert(spec_ostype == ostype); 1358 UNUSED_IF_ASSERT_DISABLED(spec_ostype); 1359 } 1360 1361 if (arch_spec.GetMachine() == llvm::Triple::mips || 1362 arch_spec.GetMachine() == llvm::Triple::mipsel || 1363 arch_spec.GetMachine() == llvm::Triple::mips64 || 1364 arch_spec.GetMachine() == llvm::Triple::mips64el) { 1365 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) { 1366 case llvm::ELF::EF_MIPS_MICROMIPS: 1367 arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips); 1368 break; 1369 case llvm::ELF::EF_MIPS_ARCH_ASE_M16: 1370 arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16); 1371 break; 1372 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX: 1373 arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx); 1374 break; 1375 default: 1376 break; 1377 } 1378 } 1379 1380 if (arch_spec.GetMachine() == llvm::Triple::arm || 1381 arch_spec.GetMachine() == llvm::Triple::thumb) { 1382 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT) 1383 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float); 1384 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT) 1385 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float); 1386 } 1387 1388 if (arch_spec.GetMachine() == llvm::Triple::riscv32 || 1389 arch_spec.GetMachine() == llvm::Triple::riscv64) { 1390 uint32_t flags = arch_spec.GetFlags(); 1391 1392 if (header.e_flags & llvm::ELF::EF_RISCV_RVC) 1393 flags |= ArchSpec::eRISCV_rvc; 1394 if (header.e_flags & llvm::ELF::EF_RISCV_RVE) 1395 flags |= ArchSpec::eRISCV_rve; 1396 1397 if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) == 1398 llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) 1399 flags |= ArchSpec::eRISCV_float_abi_single; 1400 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) == 1401 llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) 1402 flags |= ArchSpec::eRISCV_float_abi_double; 1403 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) == 1404 llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) 1405 flags |= ArchSpec::eRISCV_float_abi_quad; 1406 1407 arch_spec.SetFlags(flags); 1408 } 1409 1410 // If there are no section headers we are done. 1411 if (header.e_shnum == 0) 1412 return 0; 1413 1414 Log *log = GetLog(LLDBLog::Modules); 1415 1416 section_headers.resize(header.e_shnum); 1417 if (section_headers.size() != header.e_shnum) 1418 return 0; 1419 1420 const size_t sh_size = header.e_shnum * header.e_shentsize; 1421 const elf_off sh_offset = header.e_shoff; 1422 DataExtractor sh_data; 1423 if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size) 1424 return 0; 1425 1426 uint32_t idx; 1427 lldb::offset_t offset; 1428 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) { 1429 if (!section_headers[idx].Parse(sh_data, &offset)) 1430 break; 1431 } 1432 if (idx < section_headers.size()) 1433 section_headers.resize(idx); 1434 1435 const unsigned strtab_idx = header.e_shstrndx; 1436 if (strtab_idx && strtab_idx < section_headers.size()) { 1437 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx]; 1438 const size_t byte_size = sheader.sh_size; 1439 const Elf64_Off offset = sheader.sh_offset; 1440 lldb_private::DataExtractor shstr_data; 1441 1442 if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) { 1443 for (SectionHeaderCollIter I = section_headers.begin(); 1444 I != section_headers.end(); ++I) { 1445 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink"); 1446 const ELFSectionHeaderInfo &sheader = *I; 1447 const uint64_t section_size = 1448 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size; 1449 ConstString name(shstr_data.PeekCStr(I->sh_name)); 1450 1451 I->section_name = name; 1452 1453 if (arch_spec.IsMIPS()) { 1454 uint32_t arch_flags = arch_spec.GetFlags(); 1455 DataExtractor data; 1456 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) { 1457 1458 if (section_size && (data.SetData(object_data, sheader.sh_offset, 1459 section_size) == section_size)) { 1460 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section 1461 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0 1462 arch_flags |= data.GetU32(&offset); 1463 1464 // The floating point ABI is at offset 7 1465 offset = 7; 1466 switch (data.GetU8(&offset)) { 1467 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY: 1468 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY; 1469 break; 1470 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE: 1471 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE; 1472 break; 1473 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE: 1474 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE; 1475 break; 1476 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT: 1477 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT; 1478 break; 1479 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64: 1480 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64; 1481 break; 1482 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX: 1483 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX; 1484 break; 1485 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64: 1486 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64; 1487 break; 1488 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A: 1489 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A; 1490 break; 1491 } 1492 } 1493 } 1494 // Settings appropriate ArchSpec ABI Flags 1495 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) { 1496 case llvm::ELF::EF_MIPS_ABI_O32: 1497 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32; 1498 break; 1499 case EF_MIPS_ABI_O64: 1500 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64; 1501 break; 1502 case EF_MIPS_ABI_EABI32: 1503 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32; 1504 break; 1505 case EF_MIPS_ABI_EABI64: 1506 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64; 1507 break; 1508 default: 1509 // ABI Mask doesn't cover N32 and N64 ABI. 1510 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64) 1511 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64; 1512 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2) 1513 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32; 1514 break; 1515 } 1516 arch_spec.SetFlags(arch_flags); 1517 } 1518 1519 if (arch_spec.GetMachine() == llvm::Triple::arm || 1520 arch_spec.GetMachine() == llvm::Triple::thumb) { 1521 DataExtractor data; 1522 1523 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 && 1524 data.SetData(object_data, sheader.sh_offset, section_size) == section_size) 1525 ParseARMAttributes(data, section_size, arch_spec); 1526 } 1527 1528 if (name == g_sect_name_gnu_debuglink) { 1529 DataExtractor data; 1530 if (section_size && (data.SetData(object_data, sheader.sh_offset, 1531 section_size) == section_size)) { 1532 lldb::offset_t gnu_debuglink_offset = 0; 1533 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset); 1534 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4); 1535 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1); 1536 } 1537 } 1538 1539 // Process ELF note section entries. 1540 bool is_note_header = (sheader.sh_type == SHT_NOTE); 1541 1542 // The section header ".note.android.ident" is stored as a 1543 // PROGBITS type header but it is actually a note header. 1544 static ConstString g_sect_name_android_ident(".note.android.ident"); 1545 if (!is_note_header && name == g_sect_name_android_ident) 1546 is_note_header = true; 1547 1548 if (is_note_header) { 1549 // Allow notes to refine module info. 1550 DataExtractor data; 1551 if (section_size && (data.SetData(object_data, sheader.sh_offset, 1552 section_size) == section_size)) { 1553 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid); 1554 if (error.Fail()) { 1555 LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s", 1556 __FUNCTION__, error.AsCString()); 1557 } 1558 } 1559 } 1560 } 1561 1562 // Make any unknown triple components to be unspecified unknowns. 1563 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor) 1564 arch_spec.GetTriple().setVendorName(llvm::StringRef()); 1565 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS) 1566 arch_spec.GetTriple().setOSName(llvm::StringRef()); 1567 1568 return section_headers.size(); 1569 } 1570 } 1571 1572 section_headers.clear(); 1573 return 0; 1574 } 1575 1576 llvm::StringRef 1577 ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const { 1578 size_t pos = symbol_name.find('@'); 1579 return symbol_name.substr(0, pos); 1580 } 1581 1582 // ParseSectionHeaders 1583 size_t ObjectFileELF::ParseSectionHeaders() { 1584 return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, 1585 m_gnu_debuglink_file, m_gnu_debuglink_crc, 1586 m_arch_spec); 1587 } 1588 1589 const ObjectFileELF::ELFSectionHeaderInfo * 1590 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) { 1591 if (!ParseSectionHeaders()) 1592 return nullptr; 1593 1594 if (id < m_section_headers.size()) 1595 return &m_section_headers[id]; 1596 1597 return nullptr; 1598 } 1599 1600 lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) { 1601 if (!name || !name[0] || !ParseSectionHeaders()) 1602 return 0; 1603 for (size_t i = 1; i < m_section_headers.size(); ++i) 1604 if (m_section_headers[i].section_name == ConstString(name)) 1605 return i; 1606 return 0; 1607 } 1608 1609 static SectionType GetSectionTypeFromName(llvm::StringRef Name) { 1610 if (Name.consume_front(".debug_")) { 1611 return llvm::StringSwitch<SectionType>(Name) 1612 .Case("abbrev", eSectionTypeDWARFDebugAbbrev) 1613 .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo) 1614 .Case("addr", eSectionTypeDWARFDebugAddr) 1615 .Case("aranges", eSectionTypeDWARFDebugAranges) 1616 .Case("cu_index", eSectionTypeDWARFDebugCuIndex) 1617 .Case("frame", eSectionTypeDWARFDebugFrame) 1618 .Case("info", eSectionTypeDWARFDebugInfo) 1619 .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo) 1620 .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine) 1621 .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr) 1622 .Case("loc", eSectionTypeDWARFDebugLoc) 1623 .Case("loc.dwo", eSectionTypeDWARFDebugLocDwo) 1624 .Case("loclists", eSectionTypeDWARFDebugLocLists) 1625 .Case("loclists.dwo", eSectionTypeDWARFDebugLocListsDwo) 1626 .Case("macinfo", eSectionTypeDWARFDebugMacInfo) 1627 .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro) 1628 .Case("names", eSectionTypeDWARFDebugNames) 1629 .Case("pubnames", eSectionTypeDWARFDebugPubNames) 1630 .Case("pubtypes", eSectionTypeDWARFDebugPubTypes) 1631 .Case("ranges", eSectionTypeDWARFDebugRanges) 1632 .Case("rnglists", eSectionTypeDWARFDebugRngLists) 1633 .Case("rnglists.dwo", eSectionTypeDWARFDebugRngListsDwo) 1634 .Case("str", eSectionTypeDWARFDebugStr) 1635 .Case("str.dwo", eSectionTypeDWARFDebugStrDwo) 1636 .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets) 1637 .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo) 1638 .Case("tu_index", eSectionTypeDWARFDebugTuIndex) 1639 .Case("types", eSectionTypeDWARFDebugTypes) 1640 .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo) 1641 .Default(eSectionTypeOther); 1642 } 1643 return llvm::StringSwitch<SectionType>(Name) 1644 .Case(".ARM.exidx", eSectionTypeARMexidx) 1645 .Case(".ARM.extab", eSectionTypeARMextab) 1646 .Cases(".bss", ".tbss", eSectionTypeZeroFill) 1647 .Cases(".data", ".tdata", eSectionTypeData) 1648 .Case(".eh_frame", eSectionTypeEHFrame) 1649 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink) 1650 .Case(".gosymtab", eSectionTypeGoSymtab) 1651 .Case(".text", eSectionTypeCode) 1652 .Default(eSectionTypeOther); 1653 } 1654 1655 SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const { 1656 switch (H.sh_type) { 1657 case SHT_PROGBITS: 1658 if (H.sh_flags & SHF_EXECINSTR) 1659 return eSectionTypeCode; 1660 break; 1661 case SHT_SYMTAB: 1662 return eSectionTypeELFSymbolTable; 1663 case SHT_DYNSYM: 1664 return eSectionTypeELFDynamicSymbols; 1665 case SHT_RELA: 1666 case SHT_REL: 1667 return eSectionTypeELFRelocationEntries; 1668 case SHT_DYNAMIC: 1669 return eSectionTypeELFDynamicLinkInfo; 1670 } 1671 return GetSectionTypeFromName(H.section_name.GetStringRef()); 1672 } 1673 1674 static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) { 1675 switch (Type) { 1676 case eSectionTypeData: 1677 case eSectionTypeZeroFill: 1678 return arch.GetDataByteSize(); 1679 case eSectionTypeCode: 1680 return arch.GetCodeByteSize(); 1681 default: 1682 return 1; 1683 } 1684 } 1685 1686 static Permissions GetPermissions(const ELFSectionHeader &H) { 1687 Permissions Perm = Permissions(0); 1688 if (H.sh_flags & SHF_ALLOC) 1689 Perm |= ePermissionsReadable; 1690 if (H.sh_flags & SHF_WRITE) 1691 Perm |= ePermissionsWritable; 1692 if (H.sh_flags & SHF_EXECINSTR) 1693 Perm |= ePermissionsExecutable; 1694 return Perm; 1695 } 1696 1697 static Permissions GetPermissions(const ELFProgramHeader &H) { 1698 Permissions Perm = Permissions(0); 1699 if (H.p_flags & PF_R) 1700 Perm |= ePermissionsReadable; 1701 if (H.p_flags & PF_W) 1702 Perm |= ePermissionsWritable; 1703 if (H.p_flags & PF_X) 1704 Perm |= ePermissionsExecutable; 1705 return Perm; 1706 } 1707 1708 namespace { 1709 1710 using VMRange = lldb_private::Range<addr_t, addr_t>; 1711 1712 struct SectionAddressInfo { 1713 SectionSP Segment; 1714 VMRange Range; 1715 }; 1716 1717 // (Unlinked) ELF object files usually have 0 for every section address, meaning 1718 // we need to compute synthetic addresses in order for "file addresses" from 1719 // different sections to not overlap. This class handles that logic. 1720 class VMAddressProvider { 1721 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4, 1722 llvm::IntervalMapHalfOpenInfo<addr_t>>; 1723 1724 ObjectFile::Type ObjectType; 1725 addr_t NextVMAddress = 0; 1726 VMMap::Allocator Alloc; 1727 VMMap Segments{Alloc}; 1728 VMMap Sections{Alloc}; 1729 lldb_private::Log *Log = GetLog(LLDBLog::Modules); 1730 size_t SegmentCount = 0; 1731 std::string SegmentName; 1732 1733 VMRange GetVMRange(const ELFSectionHeader &H) { 1734 addr_t Address = H.sh_addr; 1735 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0; 1736 if (ObjectType == ObjectFile::Type::eTypeObjectFile && Segments.empty() && (H.sh_flags & SHF_ALLOC)) { 1737 NextVMAddress = 1738 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1)); 1739 Address = NextVMAddress; 1740 NextVMAddress += Size; 1741 } 1742 return VMRange(Address, Size); 1743 } 1744 1745 public: 1746 VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName) 1747 : ObjectType(Type), SegmentName(std::string(SegmentName)) {} 1748 1749 std::string GetNextSegmentName() const { 1750 return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str(); 1751 } 1752 1753 llvm::Optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) { 1754 if (H.p_memsz == 0) { 1755 LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?", 1756 SegmentName); 1757 return llvm::None; 1758 } 1759 1760 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) { 1761 LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?", 1762 SegmentName); 1763 return llvm::None; 1764 } 1765 return VMRange(H.p_vaddr, H.p_memsz); 1766 } 1767 1768 llvm::Optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) { 1769 VMRange Range = GetVMRange(H); 1770 SectionSP Segment; 1771 auto It = Segments.find(Range.GetRangeBase()); 1772 if ((H.sh_flags & SHF_ALLOC) && It.valid()) { 1773 addr_t MaxSize; 1774 if (It.start() <= Range.GetRangeBase()) { 1775 MaxSize = It.stop() - Range.GetRangeBase(); 1776 Segment = *It; 1777 } else 1778 MaxSize = It.start() - Range.GetRangeBase(); 1779 if (Range.GetByteSize() > MaxSize) { 1780 LLDB_LOG(Log, "Shortening section crossing segment boundaries. " 1781 "Corrupt object file?"); 1782 Range.SetByteSize(MaxSize); 1783 } 1784 } 1785 if (Range.GetByteSize() > 0 && 1786 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) { 1787 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?"); 1788 return llvm::None; 1789 } 1790 if (Segment) 1791 Range.Slide(-Segment->GetFileAddress()); 1792 return SectionAddressInfo{Segment, Range}; 1793 } 1794 1795 void AddSegment(const VMRange &Range, SectionSP Seg) { 1796 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg)); 1797 ++SegmentCount; 1798 } 1799 1800 void AddSection(SectionAddressInfo Info, SectionSP Sect) { 1801 if (Info.Range.GetByteSize() == 0) 1802 return; 1803 if (Info.Segment) 1804 Info.Range.Slide(Info.Segment->GetFileAddress()); 1805 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(), 1806 std::move(Sect)); 1807 } 1808 }; 1809 } 1810 1811 void ObjectFileELF::CreateSections(SectionList &unified_section_list) { 1812 if (m_sections_up) 1813 return; 1814 1815 m_sections_up = std::make_unique<SectionList>(); 1816 VMAddressProvider regular_provider(GetType(), "PT_LOAD"); 1817 VMAddressProvider tls_provider(GetType(), "PT_TLS"); 1818 1819 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) { 1820 const ELFProgramHeader &PHdr = EnumPHdr.value(); 1821 if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS) 1822 continue; 1823 1824 VMAddressProvider &provider = 1825 PHdr.p_type == PT_TLS ? tls_provider : regular_provider; 1826 auto InfoOr = provider.GetAddressInfo(PHdr); 1827 if (!InfoOr) 1828 continue; 1829 1830 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1)); 1831 SectionSP Segment = std::make_shared<Section>( 1832 GetModule(), this, SegmentID(EnumPHdr.index()), 1833 ConstString(provider.GetNextSegmentName()), eSectionTypeContainer, 1834 InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset, 1835 PHdr.p_filesz, Log2Align, /*flags*/ 0); 1836 Segment->SetPermissions(GetPermissions(PHdr)); 1837 Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS); 1838 m_sections_up->AddSection(Segment); 1839 1840 provider.AddSegment(*InfoOr, std::move(Segment)); 1841 } 1842 1843 ParseSectionHeaders(); 1844 if (m_section_headers.empty()) 1845 return; 1846 1847 for (SectionHeaderCollIter I = std::next(m_section_headers.begin()); 1848 I != m_section_headers.end(); ++I) { 1849 const ELFSectionHeaderInfo &header = *I; 1850 1851 ConstString &name = I->section_name; 1852 const uint64_t file_size = 1853 header.sh_type == SHT_NOBITS ? 0 : header.sh_size; 1854 1855 VMAddressProvider &provider = 1856 header.sh_flags & SHF_TLS ? tls_provider : regular_provider; 1857 auto InfoOr = provider.GetAddressInfo(header); 1858 if (!InfoOr) 1859 continue; 1860 1861 SectionType sect_type = GetSectionType(header); 1862 1863 const uint32_t target_bytes_size = 1864 GetTargetByteSize(sect_type, m_arch_spec); 1865 1866 elf::elf_xword log2align = 1867 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign); 1868 1869 SectionSP section_sp(new Section( 1870 InfoOr->Segment, GetModule(), // Module to which this section belongs. 1871 this, // ObjectFile to which this section belongs and should 1872 // read section data from. 1873 SectionIndex(I), // Section ID. 1874 name, // Section name. 1875 sect_type, // Section type. 1876 InfoOr->Range.GetRangeBase(), // VM address. 1877 InfoOr->Range.GetByteSize(), // VM size in bytes of this section. 1878 header.sh_offset, // Offset of this section in the file. 1879 file_size, // Size of the section as found in the file. 1880 log2align, // Alignment of the section 1881 header.sh_flags, // Flags for this section. 1882 target_bytes_size)); // Number of host bytes per target byte 1883 1884 section_sp->SetPermissions(GetPermissions(header)); 1885 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS); 1886 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up) 1887 .AddSection(section_sp); 1888 provider.AddSection(std::move(*InfoOr), std::move(section_sp)); 1889 } 1890 1891 // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the 1892 // unified section list. 1893 if (GetType() != eTypeDebugInfo) 1894 unified_section_list = *m_sections_up; 1895 1896 // If there's a .gnu_debugdata section, we'll try to read the .symtab that's 1897 // embedded in there and replace the one in the original object file (if any). 1898 // If there's none in the orignal object file, we add it to it. 1899 if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) { 1900 if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) { 1901 if (SectionSP symtab_section_sp = 1902 gdd_objfile_section_list->FindSectionByType( 1903 eSectionTypeELFSymbolTable, true)) { 1904 SectionSP module_section_sp = unified_section_list.FindSectionByType( 1905 eSectionTypeELFSymbolTable, true); 1906 if (module_section_sp) 1907 unified_section_list.ReplaceSection(module_section_sp->GetID(), 1908 symtab_section_sp); 1909 else 1910 unified_section_list.AddSection(symtab_section_sp); 1911 } 1912 } 1913 } 1914 } 1915 1916 std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() { 1917 if (m_gnu_debug_data_object_file != nullptr) 1918 return m_gnu_debug_data_object_file; 1919 1920 SectionSP section = 1921 GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata")); 1922 if (!section) 1923 return nullptr; 1924 1925 if (!lldb_private::lzma::isAvailable()) { 1926 GetModule()->ReportWarning( 1927 "No LZMA support found for reading .gnu_debugdata section"); 1928 return nullptr; 1929 } 1930 1931 // Uncompress the data 1932 DataExtractor data; 1933 section->GetSectionData(data); 1934 llvm::SmallVector<uint8_t, 0> uncompressedData; 1935 auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData); 1936 if (err) { 1937 GetModule()->ReportWarning( 1938 "An error occurred while decompression the section %s: %s", 1939 section->GetName().AsCString(), llvm::toString(std::move(err)).c_str()); 1940 return nullptr; 1941 } 1942 1943 // Construct ObjectFileELF object from decompressed buffer 1944 DataBufferSP gdd_data_buf( 1945 new DataBufferHeap(uncompressedData.data(), uncompressedData.size())); 1946 auto fspec = GetFileSpec().CopyByAppendingPathComponent( 1947 llvm::StringRef("gnu_debugdata")); 1948 m_gnu_debug_data_object_file.reset(new ObjectFileELF( 1949 GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize())); 1950 1951 // This line is essential; otherwise a breakpoint can be set but not hit. 1952 m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo); 1953 1954 ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture(); 1955 if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec)) 1956 return m_gnu_debug_data_object_file; 1957 1958 return nullptr; 1959 } 1960 1961 // Find the arm/aarch64 mapping symbol character in the given symbol name. 1962 // Mapping symbols have the form of "$<char>[.<any>]*". Additionally we 1963 // recognize cases when the mapping symbol prefixed by an arbitrary string 1964 // because if a symbol prefix added to each symbol in the object file with 1965 // objcopy then the mapping symbols are also prefixed. 1966 static char FindArmAarch64MappingSymbol(const char *symbol_name) { 1967 if (!symbol_name) 1968 return '\0'; 1969 1970 const char *dollar_pos = ::strchr(symbol_name, '$'); 1971 if (!dollar_pos || dollar_pos[1] == '\0') 1972 return '\0'; 1973 1974 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.') 1975 return dollar_pos[1]; 1976 return '\0'; 1977 } 1978 1979 #define STO_MIPS_ISA (3 << 6) 1980 #define STO_MICROMIPS (2 << 6) 1981 #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS) 1982 1983 // private 1984 unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id, 1985 SectionList *section_list, 1986 const size_t num_symbols, 1987 const DataExtractor &symtab_data, 1988 const DataExtractor &strtab_data) { 1989 ELFSymbol symbol; 1990 lldb::offset_t offset = 0; 1991 1992 static ConstString text_section_name(".text"); 1993 static ConstString init_section_name(".init"); 1994 static ConstString fini_section_name(".fini"); 1995 static ConstString ctors_section_name(".ctors"); 1996 static ConstString dtors_section_name(".dtors"); 1997 1998 static ConstString data_section_name(".data"); 1999 static ConstString rodata_section_name(".rodata"); 2000 static ConstString rodata1_section_name(".rodata1"); 2001 static ConstString data2_section_name(".data1"); 2002 static ConstString bss_section_name(".bss"); 2003 static ConstString opd_section_name(".opd"); // For ppc64 2004 2005 // On Android the oatdata and the oatexec symbols in the oat and odex files 2006 // covers the full .text section what causes issues with displaying unusable 2007 // symbol name to the user and very slow unwinding speed because the 2008 // instruction emulation based unwind plans try to emulate all instructions 2009 // in these symbols. Don't add these symbols to the symbol list as they have 2010 // no use for the debugger and they are causing a lot of trouble. Filtering 2011 // can't be restricted to Android because this special object file don't 2012 // contain the note section specifying the environment to Android but the 2013 // custom extension and file name makes it highly unlikely that this will 2014 // collide with anything else. 2015 ConstString file_extension = m_file.GetFileNameExtension(); 2016 bool skip_oatdata_oatexec = 2017 file_extension == ".oat" || file_extension == ".odex"; 2018 2019 ArchSpec arch = GetArchitecture(); 2020 ModuleSP module_sp(GetModule()); 2021 SectionList *module_section_list = 2022 module_sp ? module_sp->GetSectionList() : nullptr; 2023 2024 // Local cache to avoid doing a FindSectionByName for each symbol. The "const 2025 // char*" key must came from a ConstString object so they can be compared by 2026 // pointer 2027 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section; 2028 2029 unsigned i; 2030 for (i = 0; i < num_symbols; ++i) { 2031 if (!symbol.Parse(symtab_data, &offset)) 2032 break; 2033 2034 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name); 2035 if (!symbol_name) 2036 symbol_name = ""; 2037 2038 // No need to add non-section symbols that have no names 2039 if (symbol.getType() != STT_SECTION && 2040 (symbol_name == nullptr || symbol_name[0] == '\0')) 2041 continue; 2042 2043 // Skipping oatdata and oatexec sections if it is requested. See details 2044 // above the definition of skip_oatdata_oatexec for the reasons. 2045 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 || 2046 ::strcmp(symbol_name, "oatexec") == 0)) 2047 continue; 2048 2049 SectionSP symbol_section_sp; 2050 SymbolType symbol_type = eSymbolTypeInvalid; 2051 Elf64_Half shndx = symbol.st_shndx; 2052 2053 switch (shndx) { 2054 case SHN_ABS: 2055 symbol_type = eSymbolTypeAbsolute; 2056 break; 2057 case SHN_UNDEF: 2058 symbol_type = eSymbolTypeUndefined; 2059 break; 2060 default: 2061 symbol_section_sp = section_list->FindSectionByID(shndx); 2062 break; 2063 } 2064 2065 // If a symbol is undefined do not process it further even if it has a STT 2066 // type 2067 if (symbol_type != eSymbolTypeUndefined) { 2068 switch (symbol.getType()) { 2069 default: 2070 case STT_NOTYPE: 2071 // The symbol's type is not specified. 2072 break; 2073 2074 case STT_OBJECT: 2075 // The symbol is associated with a data object, such as a variable, an 2076 // array, etc. 2077 symbol_type = eSymbolTypeData; 2078 break; 2079 2080 case STT_FUNC: 2081 // The symbol is associated with a function or other executable code. 2082 symbol_type = eSymbolTypeCode; 2083 break; 2084 2085 case STT_SECTION: 2086 // The symbol is associated with a section. Symbol table entries of 2087 // this type exist primarily for relocation and normally have STB_LOCAL 2088 // binding. 2089 break; 2090 2091 case STT_FILE: 2092 // Conventionally, the symbol's name gives the name of the source file 2093 // associated with the object file. A file symbol has STB_LOCAL 2094 // binding, its section index is SHN_ABS, and it precedes the other 2095 // STB_LOCAL symbols for the file, if it is present. 2096 symbol_type = eSymbolTypeSourceFile; 2097 break; 2098 2099 case STT_GNU_IFUNC: 2100 // The symbol is associated with an indirect function. The actual 2101 // function will be resolved if it is referenced. 2102 symbol_type = eSymbolTypeResolver; 2103 break; 2104 } 2105 } 2106 2107 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) { 2108 if (symbol_section_sp) { 2109 ConstString sect_name = symbol_section_sp->GetName(); 2110 if (sect_name == text_section_name || sect_name == init_section_name || 2111 sect_name == fini_section_name || sect_name == ctors_section_name || 2112 sect_name == dtors_section_name) { 2113 symbol_type = eSymbolTypeCode; 2114 } else if (sect_name == data_section_name || 2115 sect_name == data2_section_name || 2116 sect_name == rodata_section_name || 2117 sect_name == rodata1_section_name || 2118 sect_name == bss_section_name) { 2119 symbol_type = eSymbolTypeData; 2120 } 2121 } 2122 } 2123 2124 int64_t symbol_value_offset = 0; 2125 uint32_t additional_flags = 0; 2126 2127 if (arch.IsValid()) { 2128 if (arch.GetMachine() == llvm::Triple::arm) { 2129 if (symbol.getBinding() == STB_LOCAL) { 2130 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name); 2131 if (symbol_type == eSymbolTypeCode) { 2132 switch (mapping_symbol) { 2133 case 'a': 2134 // $a[.<any>]* - marks an ARM instruction sequence 2135 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2136 break; 2137 case 'b': 2138 case 't': 2139 // $b[.<any>]* - marks a THUMB BL instruction sequence 2140 // $t[.<any>]* - marks a THUMB instruction sequence 2141 m_address_class_map[symbol.st_value] = 2142 AddressClass::eCodeAlternateISA; 2143 break; 2144 case 'd': 2145 // $d[.<any>]* - marks a data item sequence (e.g. lit pool) 2146 m_address_class_map[symbol.st_value] = AddressClass::eData; 2147 break; 2148 } 2149 } 2150 if (mapping_symbol) 2151 continue; 2152 } 2153 } else if (arch.GetMachine() == llvm::Triple::aarch64) { 2154 if (symbol.getBinding() == STB_LOCAL) { 2155 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name); 2156 if (symbol_type == eSymbolTypeCode) { 2157 switch (mapping_symbol) { 2158 case 'x': 2159 // $x[.<any>]* - marks an A64 instruction sequence 2160 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2161 break; 2162 case 'd': 2163 // $d[.<any>]* - marks a data item sequence (e.g. lit pool) 2164 m_address_class_map[symbol.st_value] = AddressClass::eData; 2165 break; 2166 } 2167 } 2168 if (mapping_symbol) 2169 continue; 2170 } 2171 } 2172 2173 if (arch.GetMachine() == llvm::Triple::arm) { 2174 if (symbol_type == eSymbolTypeCode) { 2175 if (symbol.st_value & 1) { 2176 // Subtracting 1 from the address effectively unsets the low order 2177 // bit, which results in the address actually pointing to the 2178 // beginning of the symbol. This delta will be used below in 2179 // conjunction with symbol.st_value to produce the final 2180 // symbol_value that we store in the symtab. 2181 symbol_value_offset = -1; 2182 m_address_class_map[symbol.st_value ^ 1] = 2183 AddressClass::eCodeAlternateISA; 2184 } else { 2185 // This address is ARM 2186 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2187 } 2188 } 2189 } 2190 2191 /* 2192 * MIPS: 2193 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for 2194 * MIPS). 2195 * This allows processor to switch between microMIPS and MIPS without any 2196 * need 2197 * for special mode-control register. However, apart from .debug_line, 2198 * none of 2199 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use 2200 * st_other 2201 * flag to check whether the symbol is microMIPS and then set the address 2202 * class 2203 * accordingly. 2204 */ 2205 if (arch.IsMIPS()) { 2206 if (IS_MICROMIPS(symbol.st_other)) 2207 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA; 2208 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) { 2209 symbol.st_value = symbol.st_value & (~1ull); 2210 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA; 2211 } else { 2212 if (symbol_type == eSymbolTypeCode) 2213 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2214 else if (symbol_type == eSymbolTypeData) 2215 m_address_class_map[symbol.st_value] = AddressClass::eData; 2216 else 2217 m_address_class_map[symbol.st_value] = AddressClass::eUnknown; 2218 } 2219 } 2220 } 2221 2222 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB 2223 // symbols. See above for more details. 2224 uint64_t symbol_value = symbol.st_value + symbol_value_offset; 2225 2226 if (symbol_section_sp && 2227 CalculateType() != ObjectFile::Type::eTypeObjectFile) 2228 symbol_value -= symbol_section_sp->GetFileAddress(); 2229 2230 if (symbol_section_sp && module_section_list && 2231 module_section_list != section_list) { 2232 ConstString sect_name = symbol_section_sp->GetName(); 2233 auto section_it = section_name_to_section.find(sect_name.GetCString()); 2234 if (section_it == section_name_to_section.end()) 2235 section_it = 2236 section_name_to_section 2237 .emplace(sect_name.GetCString(), 2238 module_section_list->FindSectionByName(sect_name)) 2239 .first; 2240 if (section_it->second) 2241 symbol_section_sp = section_it->second; 2242 } 2243 2244 bool is_global = symbol.getBinding() == STB_GLOBAL; 2245 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags; 2246 llvm::StringRef symbol_ref(symbol_name); 2247 2248 // Symbol names may contain @VERSION suffixes. Find those and strip them 2249 // temporarily. 2250 size_t version_pos = symbol_ref.find('@'); 2251 bool has_suffix = version_pos != llvm::StringRef::npos; 2252 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos); 2253 Mangled mangled(symbol_bare); 2254 2255 // Now append the suffix back to mangled and unmangled names. Only do it if 2256 // the demangling was successful (string is not empty). 2257 if (has_suffix) { 2258 llvm::StringRef suffix = symbol_ref.substr(version_pos); 2259 2260 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef(); 2261 if (!mangled_name.empty()) 2262 mangled.SetMangledName(ConstString((mangled_name + suffix).str())); 2263 2264 ConstString demangled = mangled.GetDemangledName(); 2265 llvm::StringRef demangled_name = demangled.GetStringRef(); 2266 if (!demangled_name.empty()) 2267 mangled.SetDemangledName(ConstString((demangled_name + suffix).str())); 2268 } 2269 2270 // In ELF all symbol should have a valid size but it is not true for some 2271 // function symbols coming from hand written assembly. As none of the 2272 // function symbol should have 0 size we try to calculate the size for 2273 // these symbols in the symtab with saying that their original size is not 2274 // valid. 2275 bool symbol_size_valid = 2276 symbol.st_size != 0 || symbol.getType() != STT_FUNC; 2277 2278 Symbol dc_symbol( 2279 i + start_id, // ID is the original symbol table index. 2280 mangled, 2281 symbol_type, // Type of this symbol 2282 is_global, // Is this globally visible? 2283 false, // Is this symbol debug info? 2284 false, // Is this symbol a trampoline? 2285 false, // Is this symbol artificial? 2286 AddressRange(symbol_section_sp, // Section in which this symbol is 2287 // defined or null. 2288 symbol_value, // Offset in section or symbol value. 2289 symbol.st_size), // Size in bytes of this symbol. 2290 symbol_size_valid, // Symbol size is valid 2291 has_suffix, // Contains linker annotations? 2292 flags); // Symbol flags. 2293 if (symbol.getBinding() == STB_WEAK) 2294 dc_symbol.SetIsWeak(true); 2295 symtab->AddSymbol(dc_symbol); 2296 } 2297 return i; 2298 } 2299 2300 unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, 2301 user_id_t start_id, 2302 lldb_private::Section *symtab) { 2303 if (symtab->GetObjectFile() != this) { 2304 // If the symbol table section is owned by a different object file, have it 2305 // do the parsing. 2306 ObjectFileELF *obj_file_elf = 2307 static_cast<ObjectFileELF *>(symtab->GetObjectFile()); 2308 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab); 2309 } 2310 2311 // Get section list for this object file. 2312 SectionList *section_list = m_sections_up.get(); 2313 if (!section_list) 2314 return 0; 2315 2316 user_id_t symtab_id = symtab->GetID(); 2317 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id); 2318 assert(symtab_hdr->sh_type == SHT_SYMTAB || 2319 symtab_hdr->sh_type == SHT_DYNSYM); 2320 2321 // sh_link: section header index of associated string table. 2322 user_id_t strtab_id = symtab_hdr->sh_link; 2323 Section *strtab = section_list->FindSectionByID(strtab_id).get(); 2324 2325 if (symtab && strtab) { 2326 assert(symtab->GetObjectFile() == this); 2327 assert(strtab->GetObjectFile() == this); 2328 2329 DataExtractor symtab_data; 2330 DataExtractor strtab_data; 2331 if (ReadSectionData(symtab, symtab_data) && 2332 ReadSectionData(strtab, strtab_data)) { 2333 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize; 2334 2335 return ParseSymbols(symbol_table, start_id, section_list, num_symbols, 2336 symtab_data, strtab_data); 2337 } 2338 } 2339 2340 return 0; 2341 } 2342 2343 size_t ObjectFileELF::ParseDynamicSymbols() { 2344 if (m_dynamic_symbols.size()) 2345 return m_dynamic_symbols.size(); 2346 2347 SectionList *section_list = GetSectionList(); 2348 if (!section_list) 2349 return 0; 2350 2351 // Find the SHT_DYNAMIC section. 2352 Section *dynsym = 2353 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true) 2354 .get(); 2355 if (!dynsym) 2356 return 0; 2357 assert(dynsym->GetObjectFile() == this); 2358 2359 ELFDynamic symbol; 2360 DataExtractor dynsym_data; 2361 if (ReadSectionData(dynsym, dynsym_data)) { 2362 const lldb::offset_t section_size = dynsym_data.GetByteSize(); 2363 lldb::offset_t cursor = 0; 2364 2365 while (cursor < section_size) { 2366 if (!symbol.Parse(dynsym_data, &cursor)) 2367 break; 2368 2369 m_dynamic_symbols.push_back(symbol); 2370 } 2371 } 2372 2373 return m_dynamic_symbols.size(); 2374 } 2375 2376 const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) { 2377 if (!ParseDynamicSymbols()) 2378 return nullptr; 2379 2380 DynamicSymbolCollIter I = m_dynamic_symbols.begin(); 2381 DynamicSymbolCollIter E = m_dynamic_symbols.end(); 2382 for (; I != E; ++I) { 2383 ELFDynamic *symbol = &*I; 2384 2385 if (symbol->d_tag == tag) 2386 return symbol; 2387 } 2388 2389 return nullptr; 2390 } 2391 2392 unsigned ObjectFileELF::PLTRelocationType() { 2393 // DT_PLTREL 2394 // This member specifies the type of relocation entry to which the 2395 // procedure linkage table refers. The d_val member holds DT_REL or 2396 // DT_RELA, as appropriate. All relocations in a procedure linkage table 2397 // must use the same relocation. 2398 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL); 2399 2400 if (symbol) 2401 return symbol->d_val; 2402 2403 return 0; 2404 } 2405 2406 // Returns the size of the normal plt entries and the offset of the first 2407 // normal plt entry. The 0th entry in the plt table is usually a resolution 2408 // entry which have different size in some architectures then the rest of the 2409 // plt entries. 2410 static std::pair<uint64_t, uint64_t> 2411 GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr, 2412 const ELFSectionHeader *plt_hdr) { 2413 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2414 2415 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 2416 // 16 bytes. So round the entsize up by the alignment if addralign is set. 2417 elf_xword plt_entsize = 2418 plt_hdr->sh_addralign 2419 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign) 2420 : plt_hdr->sh_entsize; 2421 2422 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly. 2423 // PLT entries relocation code in general requires multiple instruction and 2424 // should be greater than 4 bytes in most cases. Try to guess correct size 2425 // just in case. 2426 if (plt_entsize <= 4) { 2427 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the 2428 // size of the plt entries based on the number of entries and the size of 2429 // the plt section with the assumption that the size of the 0th entry is at 2430 // least as big as the size of the normal entries and it isn't much bigger 2431 // then that. 2432 if (plt_hdr->sh_addralign) 2433 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign / 2434 (num_relocations + 1) * plt_hdr->sh_addralign; 2435 else 2436 plt_entsize = plt_hdr->sh_size / (num_relocations + 1); 2437 } 2438 2439 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize; 2440 2441 return std::make_pair(plt_entsize, plt_offset); 2442 } 2443 2444 static unsigned ParsePLTRelocations( 2445 Symtab *symbol_table, user_id_t start_id, unsigned rel_type, 2446 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr, 2447 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr, 2448 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data, 2449 DataExtractor &symtab_data, DataExtractor &strtab_data) { 2450 ELFRelocation rel(rel_type); 2451 ELFSymbol symbol; 2452 lldb::offset_t offset = 0; 2453 2454 uint64_t plt_offset, plt_entsize; 2455 std::tie(plt_entsize, plt_offset) = 2456 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr); 2457 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2458 2459 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel); 2460 reloc_info_fn reloc_type; 2461 reloc_info_fn reloc_symbol; 2462 2463 if (hdr->Is32Bit()) { 2464 reloc_type = ELFRelocation::RelocType32; 2465 reloc_symbol = ELFRelocation::RelocSymbol32; 2466 } else { 2467 reloc_type = ELFRelocation::RelocType64; 2468 reloc_symbol = ELFRelocation::RelocSymbol64; 2469 } 2470 2471 unsigned slot_type = hdr->GetRelocationJumpSlotType(); 2472 unsigned i; 2473 for (i = 0; i < num_relocations; ++i) { 2474 if (!rel.Parse(rel_data, &offset)) 2475 break; 2476 2477 if (reloc_type(rel) != slot_type) 2478 continue; 2479 2480 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize; 2481 if (!symbol.Parse(symtab_data, &symbol_offset)) 2482 break; 2483 2484 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name); 2485 uint64_t plt_index = plt_offset + i * plt_entsize; 2486 2487 Symbol jump_symbol( 2488 i + start_id, // Symbol table index 2489 symbol_name, // symbol name. 2490 eSymbolTypeTrampoline, // Type of this symbol 2491 false, // Is this globally visible? 2492 false, // Is this symbol debug info? 2493 true, // Is this symbol a trampoline? 2494 true, // Is this symbol artificial? 2495 plt_section_sp, // Section in which this symbol is defined or null. 2496 plt_index, // Offset in section or symbol value. 2497 plt_entsize, // Size in bytes of this symbol. 2498 true, // Size is valid 2499 false, // Contains linker annotations? 2500 0); // Symbol flags. 2501 2502 symbol_table->AddSymbol(jump_symbol); 2503 } 2504 2505 return i; 2506 } 2507 2508 unsigned 2509 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id, 2510 const ELFSectionHeaderInfo *rel_hdr, 2511 user_id_t rel_id) { 2512 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL); 2513 2514 // The link field points to the associated symbol table. 2515 user_id_t symtab_id = rel_hdr->sh_link; 2516 2517 // If the link field doesn't point to the appropriate symbol name table then 2518 // try to find it by name as some compiler don't fill in the link fields. 2519 if (!symtab_id) 2520 symtab_id = GetSectionIndexByName(".dynsym"); 2521 2522 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers 2523 // point that to the .got.plt or .got section instead of .plt. 2524 user_id_t plt_id = GetSectionIndexByName(".plt"); 2525 2526 if (!symtab_id || !plt_id) 2527 return 0; 2528 2529 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id); 2530 if (!plt_hdr) 2531 return 0; 2532 2533 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id); 2534 if (!sym_hdr) 2535 return 0; 2536 2537 SectionList *section_list = m_sections_up.get(); 2538 if (!section_list) 2539 return 0; 2540 2541 Section *rel_section = section_list->FindSectionByID(rel_id).get(); 2542 if (!rel_section) 2543 return 0; 2544 2545 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id)); 2546 if (!plt_section_sp) 2547 return 0; 2548 2549 Section *symtab = section_list->FindSectionByID(symtab_id).get(); 2550 if (!symtab) 2551 return 0; 2552 2553 // sh_link points to associated string table. 2554 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get(); 2555 if (!strtab) 2556 return 0; 2557 2558 DataExtractor rel_data; 2559 if (!ReadSectionData(rel_section, rel_data)) 2560 return 0; 2561 2562 DataExtractor symtab_data; 2563 if (!ReadSectionData(symtab, symtab_data)) 2564 return 0; 2565 2566 DataExtractor strtab_data; 2567 if (!ReadSectionData(strtab, strtab_data)) 2568 return 0; 2569 2570 unsigned rel_type = PLTRelocationType(); 2571 if (!rel_type) 2572 return 0; 2573 2574 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header, 2575 rel_hdr, plt_hdr, sym_hdr, plt_section_sp, 2576 rel_data, symtab_data, strtab_data); 2577 } 2578 2579 unsigned ObjectFileELF::ApplyRelocations( 2580 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr, 2581 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr, 2582 DataExtractor &rel_data, DataExtractor &symtab_data, 2583 DataExtractor &debug_data, Section *rel_section) { 2584 ELFRelocation rel(rel_hdr->sh_type); 2585 lldb::addr_t offset = 0; 2586 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2587 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel); 2588 reloc_info_fn reloc_type; 2589 reloc_info_fn reloc_symbol; 2590 2591 if (hdr->Is32Bit()) { 2592 reloc_type = ELFRelocation::RelocType32; 2593 reloc_symbol = ELFRelocation::RelocSymbol32; 2594 } else { 2595 reloc_type = ELFRelocation::RelocType64; 2596 reloc_symbol = ELFRelocation::RelocSymbol64; 2597 } 2598 2599 for (unsigned i = 0; i < num_relocations; ++i) { 2600 if (!rel.Parse(rel_data, &offset)) 2601 break; 2602 2603 Symbol *symbol = nullptr; 2604 2605 if (hdr->Is32Bit()) { 2606 switch (reloc_type(rel)) { 2607 case R_386_32: 2608 case R_386_PC32: 2609 default: 2610 // FIXME: This asserts with this input: 2611 // 2612 // foo.cpp 2613 // int main(int argc, char **argv) { return 0; } 2614 // 2615 // clang++.exe --target=i686-unknown-linux-gnu -g -c foo.cpp -o foo.o 2616 // 2617 // and running this on the foo.o module. 2618 assert(false && "unexpected relocation type"); 2619 } 2620 } else { 2621 switch (reloc_type(rel)) { 2622 case R_AARCH64_ABS64: 2623 case R_X86_64_64: { 2624 symbol = symtab->FindSymbolByID(reloc_symbol(rel)); 2625 if (symbol) { 2626 addr_t value = symbol->GetAddressRef().GetFileAddress(); 2627 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer(); 2628 // ObjectFileELF creates a WritableDataBuffer in CreateInstance. 2629 WritableDataBuffer *data_buffer = 2630 llvm::cast<WritableDataBuffer>(data_buffer_sp.get()); 2631 uint64_t *dst = reinterpret_cast<uint64_t *>( 2632 data_buffer->GetBytes() + rel_section->GetFileOffset() + 2633 ELFRelocation::RelocOffset64(rel)); 2634 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel); 2635 memcpy(dst, &val_offset, sizeof(uint64_t)); 2636 } 2637 break; 2638 } 2639 case R_X86_64_32: 2640 case R_X86_64_32S: 2641 case R_AARCH64_ABS32: { 2642 symbol = symtab->FindSymbolByID(reloc_symbol(rel)); 2643 if (symbol) { 2644 addr_t value = symbol->GetAddressRef().GetFileAddress(); 2645 value += ELFRelocation::RelocAddend32(rel); 2646 if ((reloc_type(rel) == R_X86_64_32 && (value > UINT32_MAX)) || 2647 (reloc_type(rel) == R_X86_64_32S && 2648 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN)) || 2649 (reloc_type(rel) == R_AARCH64_ABS32 && 2650 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN))) { 2651 Log *log = GetLog(LLDBLog::Modules); 2652 LLDB_LOGF(log, "Failed to apply debug info relocations"); 2653 break; 2654 } 2655 uint32_t truncated_addr = (value & 0xFFFFFFFF); 2656 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer(); 2657 // ObjectFileELF creates a WritableDataBuffer in CreateInstance. 2658 WritableDataBuffer *data_buffer = 2659 llvm::cast<WritableDataBuffer>(data_buffer_sp.get()); 2660 uint32_t *dst = reinterpret_cast<uint32_t *>( 2661 data_buffer->GetBytes() + rel_section->GetFileOffset() + 2662 ELFRelocation::RelocOffset32(rel)); 2663 memcpy(dst, &truncated_addr, sizeof(uint32_t)); 2664 } 2665 break; 2666 } 2667 case R_X86_64_PC32: 2668 default: 2669 assert(false && "unexpected relocation type"); 2670 } 2671 } 2672 } 2673 2674 return 0; 2675 } 2676 2677 unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr, 2678 user_id_t rel_id, 2679 lldb_private::Symtab *thetab) { 2680 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL); 2681 2682 // Parse in the section list if needed. 2683 SectionList *section_list = GetSectionList(); 2684 if (!section_list) 2685 return 0; 2686 2687 user_id_t symtab_id = rel_hdr->sh_link; 2688 user_id_t debug_id = rel_hdr->sh_info; 2689 2690 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id); 2691 if (!symtab_hdr) 2692 return 0; 2693 2694 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id); 2695 if (!debug_hdr) 2696 return 0; 2697 2698 Section *rel = section_list->FindSectionByID(rel_id).get(); 2699 if (!rel) 2700 return 0; 2701 2702 Section *symtab = section_list->FindSectionByID(symtab_id).get(); 2703 if (!symtab) 2704 return 0; 2705 2706 Section *debug = section_list->FindSectionByID(debug_id).get(); 2707 if (!debug) 2708 return 0; 2709 2710 DataExtractor rel_data; 2711 DataExtractor symtab_data; 2712 DataExtractor debug_data; 2713 2714 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) && 2715 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) && 2716 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) { 2717 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr, 2718 rel_data, symtab_data, debug_data, debug); 2719 } 2720 2721 return 0; 2722 } 2723 2724 void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) { 2725 ModuleSP module_sp(GetModule()); 2726 if (!module_sp) 2727 return; 2728 2729 Progress progress( 2730 llvm::formatv("Parsing symbol table for {0}", 2731 m_file.GetFilename().AsCString("<Unknown>"))); 2732 ElapsedTime elapsed(module_sp->GetSymtabParseTime()); 2733 2734 // We always want to use the main object file so we (hopefully) only have one 2735 // cached copy of our symtab, dynamic sections, etc. 2736 ObjectFile *module_obj_file = module_sp->GetObjectFile(); 2737 if (module_obj_file && module_obj_file != this) 2738 return module_obj_file->ParseSymtab(lldb_symtab); 2739 2740 SectionList *section_list = module_sp->GetSectionList(); 2741 if (!section_list) 2742 return; 2743 2744 uint64_t symbol_id = 0; 2745 2746 // Sharable objects and dynamic executables usually have 2 distinct symbol 2747 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a 2748 // smaller version of the symtab that only contains global symbols. The 2749 // information found in the dynsym is therefore also found in the symtab, 2750 // while the reverse is not necessarily true. 2751 Section *symtab = 2752 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get(); 2753 if (symtab) 2754 symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, symtab); 2755 2756 // The symtab section is non-allocable and can be stripped, while the 2757 // .dynsym section which should always be always be there. To support the 2758 // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo 2759 // section, nomatter if .symtab was already parsed or not. This is because 2760 // minidebuginfo normally removes the .symtab symbols which have their 2761 // matching .dynsym counterparts. 2762 if (!symtab || 2763 GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) { 2764 Section *dynsym = 2765 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true) 2766 .get(); 2767 if (dynsym) 2768 symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, dynsym); 2769 } 2770 2771 // DT_JMPREL 2772 // If present, this entry's d_ptr member holds the address of 2773 // relocation 2774 // entries associated solely with the procedure linkage table. 2775 // Separating 2776 // these relocation entries lets the dynamic linker ignore them during 2777 // process initialization, if lazy binding is enabled. If this entry is 2778 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must 2779 // also be present. 2780 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL); 2781 if (symbol) { 2782 // Synthesize trampoline symbols to help navigate the PLT. 2783 addr_t addr = symbol->d_ptr; 2784 Section *reloc_section = 2785 section_list->FindSectionContainingFileAddress(addr).get(); 2786 if (reloc_section) { 2787 user_id_t reloc_id = reloc_section->GetID(); 2788 const ELFSectionHeaderInfo *reloc_header = 2789 GetSectionHeaderByIndex(reloc_id); 2790 if (reloc_header) 2791 ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id); 2792 } 2793 } 2794 2795 if (DWARFCallFrameInfo *eh_frame = 2796 GetModule()->GetUnwindTable().GetEHFrameInfo()) { 2797 ParseUnwindSymbols(&lldb_symtab, eh_frame); 2798 } 2799 2800 // In the event that there's no symbol entry for the entry point we'll 2801 // artificially create one. We delegate to the symtab object the figuring 2802 // out of the proper size, this will usually make it span til the next 2803 // symbol it finds in the section. This means that if there are missing 2804 // symbols the entry point might span beyond its function definition. 2805 // We're fine with this as it doesn't make it worse than not having a 2806 // symbol entry at all. 2807 if (CalculateType() == eTypeExecutable) { 2808 ArchSpec arch = GetArchitecture(); 2809 auto entry_point_addr = GetEntryPointAddress(); 2810 bool is_valid_entry_point = 2811 entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset(); 2812 addr_t entry_point_file_addr = entry_point_addr.GetFileAddress(); 2813 if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress( 2814 entry_point_file_addr)) { 2815 uint64_t symbol_id = lldb_symtab.GetNumSymbols(); 2816 // Don't set the name for any synthetic symbols, the Symbol 2817 // object will generate one if needed when the name is accessed 2818 // via accessors. 2819 SectionSP section_sp = entry_point_addr.GetSection(); 2820 Symbol symbol( 2821 /*symID=*/symbol_id, 2822 /*name=*/llvm::StringRef(), // Name will be auto generated. 2823 /*type=*/eSymbolTypeCode, 2824 /*external=*/true, 2825 /*is_debug=*/false, 2826 /*is_trampoline=*/false, 2827 /*is_artificial=*/true, 2828 /*section_sp=*/section_sp, 2829 /*offset=*/0, 2830 /*size=*/0, // FDE can span multiple symbols so don't use its size. 2831 /*size_is_valid=*/false, 2832 /*contains_linker_annotations=*/false, 2833 /*flags=*/0); 2834 // When the entry point is arm thumb we need to explicitly set its 2835 // class address to reflect that. This is important because expression 2836 // evaluation relies on correctly setting a breakpoint at this 2837 // address. 2838 if (arch.GetMachine() == llvm::Triple::arm && 2839 (entry_point_file_addr & 1)) { 2840 symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1); 2841 m_address_class_map[entry_point_file_addr ^ 1] = 2842 AddressClass::eCodeAlternateISA; 2843 } else { 2844 m_address_class_map[entry_point_file_addr] = AddressClass::eCode; 2845 } 2846 lldb_symtab.AddSymbol(symbol); 2847 } 2848 } 2849 } 2850 2851 void ObjectFileELF::RelocateSection(lldb_private::Section *section) 2852 { 2853 static const char *debug_prefix = ".debug"; 2854 2855 // Set relocated bit so we stop getting called, regardless of whether we 2856 // actually relocate. 2857 section->SetIsRelocated(true); 2858 2859 // We only relocate in ELF relocatable files 2860 if (CalculateType() != eTypeObjectFile) 2861 return; 2862 2863 const char *section_name = section->GetName().GetCString(); 2864 // Can't relocate that which can't be named 2865 if (section_name == nullptr) 2866 return; 2867 2868 // We don't relocate non-debug sections at the moment 2869 if (strncmp(section_name, debug_prefix, strlen(debug_prefix))) 2870 return; 2871 2872 // Relocation section names to look for 2873 std::string needle = std::string(".rel") + section_name; 2874 std::string needlea = std::string(".rela") + section_name; 2875 2876 for (SectionHeaderCollIter I = m_section_headers.begin(); 2877 I != m_section_headers.end(); ++I) { 2878 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) { 2879 const char *hay_name = I->section_name.GetCString(); 2880 if (hay_name == nullptr) 2881 continue; 2882 if (needle == hay_name || needlea == hay_name) { 2883 const ELFSectionHeader &reloc_header = *I; 2884 user_id_t reloc_id = SectionIndex(I); 2885 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab()); 2886 break; 2887 } 2888 } 2889 } 2890 } 2891 2892 void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table, 2893 DWARFCallFrameInfo *eh_frame) { 2894 SectionList *section_list = GetSectionList(); 2895 if (!section_list) 2896 return; 2897 2898 // First we save the new symbols into a separate list and add them to the 2899 // symbol table after we collected all symbols we want to add. This is 2900 // neccessary because adding a new symbol invalidates the internal index of 2901 // the symtab what causing the next lookup to be slow because it have to 2902 // recalculate the index first. 2903 std::vector<Symbol> new_symbols; 2904 2905 size_t num_symbols = symbol_table->GetNumSymbols(); 2906 uint64_t last_symbol_id = 2907 num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0; 2908 eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size, 2909 dw_offset_t) { 2910 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr); 2911 if (symbol) { 2912 if (!symbol->GetByteSizeIsValid()) { 2913 symbol->SetByteSize(size); 2914 symbol->SetSizeIsSynthesized(true); 2915 } 2916 } else { 2917 SectionSP section_sp = 2918 section_list->FindSectionContainingFileAddress(file_addr); 2919 if (section_sp) { 2920 addr_t offset = file_addr - section_sp->GetFileAddress(); 2921 uint64_t symbol_id = ++last_symbol_id; 2922 // Don't set the name for any synthetic symbols, the Symbol 2923 // object will generate one if needed when the name is accessed 2924 // via accessors. 2925 Symbol eh_symbol( 2926 /*symID=*/symbol_id, 2927 /*name=*/llvm::StringRef(), // Name will be auto generated. 2928 /*type=*/eSymbolTypeCode, 2929 /*external=*/true, 2930 /*is_debug=*/false, 2931 /*is_trampoline=*/false, 2932 /*is_artificial=*/true, 2933 /*section_sp=*/section_sp, 2934 /*offset=*/offset, 2935 /*size=*/0, // FDE can span multiple symbols so don't use its size. 2936 /*size_is_valid=*/false, 2937 /*contains_linker_annotations=*/false, 2938 /*flags=*/0); 2939 new_symbols.push_back(eh_symbol); 2940 } 2941 } 2942 return true; 2943 }); 2944 2945 for (const Symbol &s : new_symbols) 2946 symbol_table->AddSymbol(s); 2947 } 2948 2949 bool ObjectFileELF::IsStripped() { 2950 // TODO: determine this for ELF 2951 return false; 2952 } 2953 2954 //===----------------------------------------------------------------------===// 2955 // Dump 2956 // 2957 // Dump the specifics of the runtime file container (such as any headers 2958 // segments, sections, etc). 2959 void ObjectFileELF::Dump(Stream *s) { 2960 ModuleSP module_sp(GetModule()); 2961 if (!module_sp) { 2962 return; 2963 } 2964 2965 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 2966 s->Printf("%p: ", static_cast<void *>(this)); 2967 s->Indent(); 2968 s->PutCString("ObjectFileELF"); 2969 2970 ArchSpec header_arch = GetArchitecture(); 2971 2972 *s << ", file = '" << m_file 2973 << "', arch = " << header_arch.GetArchitectureName() << "\n"; 2974 2975 DumpELFHeader(s, m_header); 2976 s->EOL(); 2977 DumpELFProgramHeaders(s); 2978 s->EOL(); 2979 DumpELFSectionHeaders(s); 2980 s->EOL(); 2981 SectionList *section_list = GetSectionList(); 2982 if (section_list) 2983 section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true, 2984 UINT32_MAX); 2985 Symtab *symtab = GetSymtab(); 2986 if (symtab) 2987 symtab->Dump(s, nullptr, eSortOrderNone); 2988 s->EOL(); 2989 DumpDependentModules(s); 2990 s->EOL(); 2991 } 2992 2993 // DumpELFHeader 2994 // 2995 // Dump the ELF header to the specified output stream 2996 void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) { 2997 s->PutCString("ELF Header\n"); 2998 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]); 2999 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1], 3000 header.e_ident[EI_MAG1]); 3001 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2], 3002 header.e_ident[EI_MAG2]); 3003 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3], 3004 header.e_ident[EI_MAG3]); 3005 3006 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]); 3007 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]); 3008 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]); 3009 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]); 3010 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]); 3011 3012 s->Printf("e_type = 0x%4.4x ", header.e_type); 3013 DumpELFHeader_e_type(s, header.e_type); 3014 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine); 3015 s->Printf("e_version = 0x%8.8x\n", header.e_version); 3016 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry); 3017 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff); 3018 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff); 3019 s->Printf("e_flags = 0x%8.8x\n", header.e_flags); 3020 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize); 3021 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize); 3022 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum); 3023 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize); 3024 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum); 3025 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx); 3026 } 3027 3028 // DumpELFHeader_e_type 3029 // 3030 // Dump an token value for the ELF header member e_type 3031 void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) { 3032 switch (e_type) { 3033 case ET_NONE: 3034 *s << "ET_NONE"; 3035 break; 3036 case ET_REL: 3037 *s << "ET_REL"; 3038 break; 3039 case ET_EXEC: 3040 *s << "ET_EXEC"; 3041 break; 3042 case ET_DYN: 3043 *s << "ET_DYN"; 3044 break; 3045 case ET_CORE: 3046 *s << "ET_CORE"; 3047 break; 3048 default: 3049 break; 3050 } 3051 } 3052 3053 // DumpELFHeader_e_ident_EI_DATA 3054 // 3055 // Dump an token value for the ELF header member e_ident[EI_DATA] 3056 void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, 3057 unsigned char ei_data) { 3058 switch (ei_data) { 3059 case ELFDATANONE: 3060 *s << "ELFDATANONE"; 3061 break; 3062 case ELFDATA2LSB: 3063 *s << "ELFDATA2LSB - Little Endian"; 3064 break; 3065 case ELFDATA2MSB: 3066 *s << "ELFDATA2MSB - Big Endian"; 3067 break; 3068 default: 3069 break; 3070 } 3071 } 3072 3073 // DumpELFProgramHeader 3074 // 3075 // Dump a single ELF program header to the specified output stream 3076 void ObjectFileELF::DumpELFProgramHeader(Stream *s, 3077 const ELFProgramHeader &ph) { 3078 DumpELFProgramHeader_p_type(s, ph.p_type); 3079 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset, 3080 ph.p_vaddr, ph.p_paddr); 3081 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz, 3082 ph.p_flags); 3083 3084 DumpELFProgramHeader_p_flags(s, ph.p_flags); 3085 s->Printf(") %8.8" PRIx64, ph.p_align); 3086 } 3087 3088 // DumpELFProgramHeader_p_type 3089 // 3090 // Dump an token value for the ELF program header member p_type which describes 3091 // the type of the program header 3092 void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) { 3093 const int kStrWidth = 15; 3094 switch (p_type) { 3095 CASE_AND_STREAM(s, PT_NULL, kStrWidth); 3096 CASE_AND_STREAM(s, PT_LOAD, kStrWidth); 3097 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth); 3098 CASE_AND_STREAM(s, PT_INTERP, kStrWidth); 3099 CASE_AND_STREAM(s, PT_NOTE, kStrWidth); 3100 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth); 3101 CASE_AND_STREAM(s, PT_PHDR, kStrWidth); 3102 CASE_AND_STREAM(s, PT_TLS, kStrWidth); 3103 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth); 3104 default: 3105 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, ""); 3106 break; 3107 } 3108 } 3109 3110 // DumpELFProgramHeader_p_flags 3111 // 3112 // Dump an token value for the ELF program header member p_flags 3113 void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) { 3114 *s << ((p_flags & PF_X) ? "PF_X" : " ") 3115 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ') 3116 << ((p_flags & PF_W) ? "PF_W" : " ") 3117 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ') 3118 << ((p_flags & PF_R) ? "PF_R" : " "); 3119 } 3120 3121 // DumpELFProgramHeaders 3122 // 3123 // Dump all of the ELF program header to the specified output stream 3124 void ObjectFileELF::DumpELFProgramHeaders(Stream *s) { 3125 if (!ParseProgramHeaders()) 3126 return; 3127 3128 s->PutCString("Program Headers\n"); 3129 s->PutCString("IDX p_type p_offset p_vaddr p_paddr " 3130 "p_filesz p_memsz p_flags p_align\n"); 3131 s->PutCString("==== --------------- -------- -------- -------- " 3132 "-------- -------- ------------------------- --------\n"); 3133 3134 for (const auto &H : llvm::enumerate(m_program_headers)) { 3135 s->Format("[{0,2}] ", H.index()); 3136 ObjectFileELF::DumpELFProgramHeader(s, H.value()); 3137 s->EOL(); 3138 } 3139 } 3140 3141 // DumpELFSectionHeader 3142 // 3143 // Dump a single ELF section header to the specified output stream 3144 void ObjectFileELF::DumpELFSectionHeader(Stream *s, 3145 const ELFSectionHeaderInfo &sh) { 3146 s->Printf("%8.8x ", sh.sh_name); 3147 DumpELFSectionHeader_sh_type(s, sh.sh_type); 3148 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags); 3149 DumpELFSectionHeader_sh_flags(s, sh.sh_flags); 3150 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, 3151 sh.sh_offset, sh.sh_size); 3152 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info); 3153 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize); 3154 } 3155 3156 // DumpELFSectionHeader_sh_type 3157 // 3158 // Dump an token value for the ELF section header member sh_type which 3159 // describes the type of the section 3160 void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) { 3161 const int kStrWidth = 12; 3162 switch (sh_type) { 3163 CASE_AND_STREAM(s, SHT_NULL, kStrWidth); 3164 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth); 3165 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth); 3166 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth); 3167 CASE_AND_STREAM(s, SHT_RELA, kStrWidth); 3168 CASE_AND_STREAM(s, SHT_HASH, kStrWidth); 3169 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth); 3170 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth); 3171 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth); 3172 CASE_AND_STREAM(s, SHT_REL, kStrWidth); 3173 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth); 3174 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth); 3175 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth); 3176 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth); 3177 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth); 3178 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth); 3179 default: 3180 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, ""); 3181 break; 3182 } 3183 } 3184 3185 // DumpELFSectionHeader_sh_flags 3186 // 3187 // Dump an token value for the ELF section header member sh_flags 3188 void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, 3189 elf_xword sh_flags) { 3190 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ") 3191 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ') 3192 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ") 3193 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ') 3194 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " "); 3195 } 3196 3197 // DumpELFSectionHeaders 3198 // 3199 // Dump all of the ELF section header to the specified output stream 3200 void ObjectFileELF::DumpELFSectionHeaders(Stream *s) { 3201 if (!ParseSectionHeaders()) 3202 return; 3203 3204 s->PutCString("Section Headers\n"); 3205 s->PutCString("IDX name type flags " 3206 "addr offset size link info addralgn " 3207 "entsize Name\n"); 3208 s->PutCString("==== -------- ------------ -------------------------------- " 3209 "-------- -------- -------- -------- -------- -------- " 3210 "-------- ====================\n"); 3211 3212 uint32_t idx = 0; 3213 for (SectionHeaderCollConstIter I = m_section_headers.begin(); 3214 I != m_section_headers.end(); ++I, ++idx) { 3215 s->Printf("[%2u] ", idx); 3216 ObjectFileELF::DumpELFSectionHeader(s, *I); 3217 const char *section_name = I->section_name.AsCString(""); 3218 if (section_name) 3219 *s << ' ' << section_name << "\n"; 3220 } 3221 } 3222 3223 void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) { 3224 size_t num_modules = ParseDependentModules(); 3225 3226 if (num_modules > 0) { 3227 s->PutCString("Dependent Modules:\n"); 3228 for (unsigned i = 0; i < num_modules; ++i) { 3229 const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i); 3230 s->Printf(" %s\n", spec.GetFilename().GetCString()); 3231 } 3232 } 3233 } 3234 3235 ArchSpec ObjectFileELF::GetArchitecture() { 3236 if (!ParseHeader()) 3237 return ArchSpec(); 3238 3239 if (m_section_headers.empty()) { 3240 // Allow elf notes to be parsed which may affect the detected architecture. 3241 ParseSectionHeaders(); 3242 } 3243 3244 if (CalculateType() == eTypeCoreFile && 3245 !m_arch_spec.TripleOSWasSpecified()) { 3246 // Core files don't have section headers yet they have PT_NOTE program 3247 // headers that might shed more light on the architecture 3248 for (const elf::ELFProgramHeader &H : ProgramHeaders()) { 3249 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0) 3250 continue; 3251 DataExtractor data; 3252 if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) { 3253 UUID uuid; 3254 RefineModuleDetailsFromNote(data, m_arch_spec, uuid); 3255 } 3256 } 3257 } 3258 return m_arch_spec; 3259 } 3260 3261 ObjectFile::Type ObjectFileELF::CalculateType() { 3262 switch (m_header.e_type) { 3263 case llvm::ELF::ET_NONE: 3264 // 0 - No file type 3265 return eTypeUnknown; 3266 3267 case llvm::ELF::ET_REL: 3268 // 1 - Relocatable file 3269 return eTypeObjectFile; 3270 3271 case llvm::ELF::ET_EXEC: 3272 // 2 - Executable file 3273 return eTypeExecutable; 3274 3275 case llvm::ELF::ET_DYN: 3276 // 3 - Shared object file 3277 return eTypeSharedLibrary; 3278 3279 case ET_CORE: 3280 // 4 - Core file 3281 return eTypeCoreFile; 3282 3283 default: 3284 break; 3285 } 3286 return eTypeUnknown; 3287 } 3288 3289 ObjectFile::Strata ObjectFileELF::CalculateStrata() { 3290 switch (m_header.e_type) { 3291 case llvm::ELF::ET_NONE: 3292 // 0 - No file type 3293 return eStrataUnknown; 3294 3295 case llvm::ELF::ET_REL: 3296 // 1 - Relocatable file 3297 return eStrataUnknown; 3298 3299 case llvm::ELF::ET_EXEC: 3300 // 2 - Executable file 3301 // TODO: is there any way to detect that an executable is a kernel 3302 // related executable by inspecting the program headers, section headers, 3303 // symbols, or any other flag bits??? 3304 return eStrataUser; 3305 3306 case llvm::ELF::ET_DYN: 3307 // 3 - Shared object file 3308 // TODO: is there any way to detect that an shared library is a kernel 3309 // related executable by inspecting the program headers, section headers, 3310 // symbols, or any other flag bits??? 3311 return eStrataUnknown; 3312 3313 case ET_CORE: 3314 // 4 - Core file 3315 // TODO: is there any way to detect that an core file is a kernel 3316 // related executable by inspecting the program headers, section headers, 3317 // symbols, or any other flag bits??? 3318 return eStrataUnknown; 3319 3320 default: 3321 break; 3322 } 3323 return eStrataUnknown; 3324 } 3325 3326 size_t ObjectFileELF::ReadSectionData(Section *section, 3327 lldb::offset_t section_offset, void *dst, 3328 size_t dst_len) { 3329 // If some other objectfile owns this data, pass this to them. 3330 if (section->GetObjectFile() != this) 3331 return section->GetObjectFile()->ReadSectionData(section, section_offset, 3332 dst, dst_len); 3333 3334 if (!section->Test(SHF_COMPRESSED)) 3335 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len); 3336 3337 // For compressed sections we need to read to full data to be able to 3338 // decompress. 3339 DataExtractor data; 3340 ReadSectionData(section, data); 3341 return data.CopyData(section_offset, dst_len, dst); 3342 } 3343 3344 size_t ObjectFileELF::ReadSectionData(Section *section, 3345 DataExtractor §ion_data) { 3346 // If some other objectfile owns this data, pass this to them. 3347 if (section->GetObjectFile() != this) 3348 return section->GetObjectFile()->ReadSectionData(section, section_data); 3349 3350 size_t result = ObjectFile::ReadSectionData(section, section_data); 3351 if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED)) 3352 return result; 3353 3354 auto Decompressor = llvm::object::Decompressor::create( 3355 section->GetName().GetStringRef(), 3356 {reinterpret_cast<const char *>(section_data.GetDataStart()), 3357 size_t(section_data.GetByteSize())}, 3358 GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8); 3359 if (!Decompressor) { 3360 GetModule()->ReportWarning( 3361 "Unable to initialize decompressor for section '%s': %s", 3362 section->GetName().GetCString(), 3363 llvm::toString(Decompressor.takeError()).c_str()); 3364 section_data.Clear(); 3365 return 0; 3366 } 3367 3368 auto buffer_sp = 3369 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0); 3370 if (auto error = Decompressor->decompress( 3371 {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) { 3372 GetModule()->ReportWarning( 3373 "Decompression of section '%s' failed: %s", 3374 section->GetName().GetCString(), 3375 llvm::toString(std::move(error)).c_str()); 3376 section_data.Clear(); 3377 return 0; 3378 } 3379 3380 section_data.SetData(buffer_sp); 3381 return buffer_sp->GetByteSize(); 3382 } 3383 3384 llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() { 3385 ParseProgramHeaders(); 3386 return m_program_headers; 3387 } 3388 3389 DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) { 3390 return DataExtractor(m_data, H.p_offset, H.p_filesz); 3391 } 3392 3393 bool ObjectFileELF::AnySegmentHasPhysicalAddress() { 3394 for (const ELFProgramHeader &H : ProgramHeaders()) { 3395 if (H.p_paddr != 0) 3396 return true; 3397 } 3398 return false; 3399 } 3400 3401 std::vector<ObjectFile::LoadableData> 3402 ObjectFileELF::GetLoadableData(Target &target) { 3403 // Create a list of loadable data from loadable segments, using physical 3404 // addresses if they aren't all null 3405 std::vector<LoadableData> loadables; 3406 bool should_use_paddr = AnySegmentHasPhysicalAddress(); 3407 for (const ELFProgramHeader &H : ProgramHeaders()) { 3408 LoadableData loadable; 3409 if (H.p_type != llvm::ELF::PT_LOAD) 3410 continue; 3411 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr; 3412 if (loadable.Dest == LLDB_INVALID_ADDRESS) 3413 continue; 3414 if (H.p_filesz == 0) 3415 continue; 3416 auto segment_data = GetSegmentData(H); 3417 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(), 3418 segment_data.GetByteSize()); 3419 loadables.push_back(loadable); 3420 } 3421 return loadables; 3422 } 3423 3424 lldb::WritableDataBufferSP 3425 ObjectFileELF::MapFileDataWritable(const FileSpec &file, uint64_t Size, 3426 uint64_t Offset) { 3427 return FileSystem::Instance().CreateWritableDataBuffer(file.GetPath(), Size, 3428 Offset); 3429 } 3430