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