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