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/RangeMap.h" 21 #include "lldb/Core/Section.h" 22 #include "lldb/Host/FileSystem.h" 23 #include "lldb/Symbol/DWARFCallFrameInfo.h" 24 #include "lldb/Symbol/SymbolContext.h" 25 #include "lldb/Target/SectionLoadList.h" 26 #include "lldb/Target/Target.h" 27 #include "lldb/Utility/ArchSpec.h" 28 #include "lldb/Utility/DataBufferHeap.h" 29 #include "lldb/Utility/Log.h" 30 #include "lldb/Utility/Status.h" 31 #include "lldb/Utility/Stream.h" 32 #include "lldb/Utility/Timer.h" 33 34 #include "llvm/ADT/IntervalMap.h" 35 #include "llvm/ADT/PointerUnion.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/Object/Decompressor.h" 38 #include "llvm/Support/ARMBuildAttributes.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/MipsABIFlags.h" 42 43 #define CASE_AND_STREAM(s, def, width) \ 44 case def: \ 45 s->Printf("%-*s", width, #def); \ 46 break; 47 48 using namespace lldb; 49 using namespace lldb_private; 50 using namespace elf; 51 using namespace llvm::ELF; 52 53 namespace { 54 55 // ELF note owner definitions 56 const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD"; 57 const char *const LLDB_NT_OWNER_GNU = "GNU"; 58 const char *const LLDB_NT_OWNER_NETBSD = "NetBSD"; 59 const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD"; 60 const char *const LLDB_NT_OWNER_CSR = "csr"; 61 const char *const LLDB_NT_OWNER_ANDROID = "Android"; 62 const char *const LLDB_NT_OWNER_CORE = "CORE"; 63 const char *const LLDB_NT_OWNER_LINUX = "LINUX"; 64 65 // ELF note type definitions 66 const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01; 67 const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4; 68 69 const elf_word LLDB_NT_GNU_ABI_TAG = 0x01; 70 const elf_word LLDB_NT_GNU_ABI_SIZE = 16; 71 72 const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03; 73 74 const elf_word LLDB_NT_NETBSD_ABI_TAG = 0x01; 75 const elf_word LLDB_NT_NETBSD_ABI_SIZE = 4; 76 77 // GNU ABI note OS constants 78 const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00; 79 const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01; 80 const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02; 81 82 // LLDB_NT_OWNER_CORE and LLDB_NT_OWNER_LINUX note contants 83 #define NT_PRSTATUS 1 84 #define NT_PRFPREG 2 85 #define NT_PRPSINFO 3 86 #define NT_TASKSTRUCT 4 87 #define NT_AUXV 6 88 #define NT_SIGINFO 0x53494749 89 #define NT_FILE 0x46494c45 90 #define NT_PRXFPREG 0x46e62b7f 91 #define NT_PPC_VMX 0x100 92 #define NT_PPC_SPE 0x101 93 #define NT_PPC_VSX 0x102 94 #define NT_386_TLS 0x200 95 #define NT_386_IOPERM 0x201 96 #define NT_X86_XSTATE 0x202 97 #define NT_S390_HIGH_GPRS 0x300 98 #define NT_S390_TIMER 0x301 99 #define NT_S390_TODCMP 0x302 100 #define NT_S390_TODPREG 0x303 101 #define NT_S390_CTRS 0x304 102 #define NT_S390_PREFIX 0x305 103 #define NT_S390_LAST_BREAK 0x306 104 #define NT_S390_SYSTEM_CALL 0x307 105 #define NT_S390_TDB 0x308 106 #define NT_S390_VXRS_LOW 0x309 107 #define NT_S390_VXRS_HIGH 0x30a 108 #define NT_ARM_VFP 0x400 109 #define NT_ARM_TLS 0x401 110 #define NT_ARM_HW_BREAK 0x402 111 #define NT_ARM_HW_WATCH 0x403 112 #define NT_ARM_SYSTEM_CALL 0x404 113 #define NT_METAG_CBUF 0x500 114 #define NT_METAG_RPIPE 0x501 115 #define NT_METAG_TLS 0x502 116 117 //===----------------------------------------------------------------------===// 118 /// @class ELFRelocation 119 /// Generic wrapper for ELFRel and ELFRela. 120 /// 121 /// This helper class allows us to parse both ELFRel and ELFRela relocation 122 /// entries in a generic manner. 123 class ELFRelocation { 124 public: 125 /// Constructs an ELFRelocation entry with a personality as given by @p 126 /// type. 127 /// 128 /// @param type Either DT_REL or DT_RELA. Any other value is invalid. 129 ELFRelocation(unsigned type); 130 131 ~ELFRelocation(); 132 133 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset); 134 135 static unsigned RelocType32(const ELFRelocation &rel); 136 137 static unsigned RelocType64(const ELFRelocation &rel); 138 139 static unsigned RelocSymbol32(const ELFRelocation &rel); 140 141 static unsigned RelocSymbol64(const ELFRelocation &rel); 142 143 static unsigned RelocOffset32(const ELFRelocation &rel); 144 145 static unsigned RelocOffset64(const ELFRelocation &rel); 146 147 static unsigned RelocAddend32(const ELFRelocation &rel); 148 149 static unsigned RelocAddend64(const ELFRelocation &rel); 150 151 private: 152 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion; 153 154 RelocUnion reloc; 155 }; 156 157 ELFRelocation::ELFRelocation(unsigned type) { 158 if (type == DT_REL || type == SHT_REL) 159 reloc = new ELFRel(); 160 else if (type == DT_RELA || type == SHT_RELA) 161 reloc = new ELFRela(); 162 else { 163 assert(false && "unexpected relocation type"); 164 reloc = static_cast<ELFRel *>(NULL); 165 } 166 } 167 168 ELFRelocation::~ELFRelocation() { 169 if (reloc.is<ELFRel *>()) 170 delete reloc.get<ELFRel *>(); 171 else 172 delete reloc.get<ELFRela *>(); 173 } 174 175 bool ELFRelocation::Parse(const lldb_private::DataExtractor &data, 176 lldb::offset_t *offset) { 177 if (reloc.is<ELFRel *>()) 178 return reloc.get<ELFRel *>()->Parse(data, offset); 179 else 180 return reloc.get<ELFRela *>()->Parse(data, offset); 181 } 182 183 unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) { 184 if (rel.reloc.is<ELFRel *>()) 185 return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>()); 186 else 187 return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>()); 188 } 189 190 unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) { 191 if (rel.reloc.is<ELFRel *>()) 192 return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>()); 193 else 194 return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>()); 195 } 196 197 unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) { 198 if (rel.reloc.is<ELFRel *>()) 199 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>()); 200 else 201 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>()); 202 } 203 204 unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) { 205 if (rel.reloc.is<ELFRel *>()) 206 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>()); 207 else 208 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>()); 209 } 210 211 unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) { 212 if (rel.reloc.is<ELFRel *>()) 213 return rel.reloc.get<ELFRel *>()->r_offset; 214 else 215 return rel.reloc.get<ELFRela *>()->r_offset; 216 } 217 218 unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) { 219 if (rel.reloc.is<ELFRel *>()) 220 return rel.reloc.get<ELFRel *>()->r_offset; 221 else 222 return rel.reloc.get<ELFRela *>()->r_offset; 223 } 224 225 unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) { 226 if (rel.reloc.is<ELFRel *>()) 227 return 0; 228 else 229 return rel.reloc.get<ELFRela *>()->r_addend; 230 } 231 232 unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) { 233 if (rel.reloc.is<ELFRel *>()) 234 return 0; 235 else 236 return rel.reloc.get<ELFRela *>()->r_addend; 237 } 238 239 } // end anonymous namespace 240 241 static user_id_t SegmentID(size_t PHdrIndex) { return ~PHdrIndex; } 242 243 bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) { 244 // Read all fields. 245 if (data.GetU32(offset, &n_namesz, 3) == NULL) 246 return false; 247 248 // The name field is required to be nul-terminated, and n_namesz includes the 249 // terminating nul in observed implementations (contrary to the ELF-64 spec). 250 // A special case is needed for cores generated by some older Linux versions, 251 // which write a note named "CORE" without a nul terminator and n_namesz = 4. 252 if (n_namesz == 4) { 253 char buf[4]; 254 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4) 255 return false; 256 if (strncmp(buf, "CORE", 4) == 0) { 257 n_name = "CORE"; 258 *offset += 4; 259 return true; 260 } 261 } 262 263 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4)); 264 if (cstr == NULL) { 265 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS)); 266 if (log) 267 log->Printf("Failed to parse note name lacking nul terminator"); 268 269 return false; 270 } 271 n_name = cstr; 272 return true; 273 } 274 275 static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) { 276 const uint32_t dsp_rev = e_flags & 0xFF; 277 uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE; 278 switch (dsp_rev) { 279 // TODO(mg11) Support more variants 280 case 10: 281 kal_arch_variant = llvm::Triple::KalimbaSubArch_v3; 282 break; 283 case 14: 284 kal_arch_variant = llvm::Triple::KalimbaSubArch_v4; 285 break; 286 case 17: 287 case 20: 288 kal_arch_variant = llvm::Triple::KalimbaSubArch_v5; 289 break; 290 default: 291 break; 292 } 293 return kal_arch_variant; 294 } 295 296 static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) { 297 const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH; 298 uint32_t endian = header.e_ident[EI_DATA]; 299 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown; 300 uint32_t fileclass = header.e_ident[EI_CLASS]; 301 302 // If there aren't any elf flags available (e.g core elf file) then return 303 // default 304 // 32 or 64 bit arch (without any architecture revision) based on object file's class. 305 if (header.e_type == ET_CORE) { 306 switch (fileclass) { 307 case llvm::ELF::ELFCLASS32: 308 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el 309 : ArchSpec::eMIPSSubType_mips32; 310 case llvm::ELF::ELFCLASS64: 311 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el 312 : ArchSpec::eMIPSSubType_mips64; 313 default: 314 return arch_variant; 315 } 316 } 317 318 switch (mips_arch) { 319 case llvm::ELF::EF_MIPS_ARCH_1: 320 case llvm::ELF::EF_MIPS_ARCH_2: 321 case llvm::ELF::EF_MIPS_ARCH_32: 322 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el 323 : ArchSpec::eMIPSSubType_mips32; 324 case llvm::ELF::EF_MIPS_ARCH_32R2: 325 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el 326 : ArchSpec::eMIPSSubType_mips32r2; 327 case llvm::ELF::EF_MIPS_ARCH_32R6: 328 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el 329 : ArchSpec::eMIPSSubType_mips32r6; 330 case llvm::ELF::EF_MIPS_ARCH_3: 331 case llvm::ELF::EF_MIPS_ARCH_4: 332 case llvm::ELF::EF_MIPS_ARCH_5: 333 case llvm::ELF::EF_MIPS_ARCH_64: 334 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el 335 : ArchSpec::eMIPSSubType_mips64; 336 case llvm::ELF::EF_MIPS_ARCH_64R2: 337 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el 338 : ArchSpec::eMIPSSubType_mips64r2; 339 case llvm::ELF::EF_MIPS_ARCH_64R6: 340 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el 341 : ArchSpec::eMIPSSubType_mips64r6; 342 default: 343 break; 344 } 345 346 return arch_variant; 347 } 348 349 static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) { 350 if (header.e_machine == llvm::ELF::EM_MIPS) 351 return mipsVariantFromElfFlags(header); 352 353 return llvm::ELF::EM_CSR_KALIMBA == header.e_machine 354 ? kalimbaVariantFromElfFlags(header.e_flags) 355 : LLDB_INVALID_CPUTYPE; 356 } 357 358 //! The kalimba toolchain identifies a code section as being 359 //! one with the SHT_PROGBITS set in the section sh_type and the top 360 //! bit in the 32-bit address field set. 361 static lldb::SectionType 362 kalimbaSectionType(const elf::ELFHeader &header, 363 const elf::ELFSectionHeader §_hdr) { 364 if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) { 365 return eSectionTypeOther; 366 } 367 368 if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) { 369 return eSectionTypeZeroFill; 370 } 371 372 if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) { 373 const lldb::addr_t KAL_CODE_BIT = 1 << 31; 374 return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode 375 : eSectionTypeData; 376 } 377 378 return eSectionTypeOther; 379 } 380 381 // Arbitrary constant used as UUID prefix for core files. 382 const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C); 383 384 //------------------------------------------------------------------ 385 // Static methods. 386 //------------------------------------------------------------------ 387 void ObjectFileELF::Initialize() { 388 PluginManager::RegisterPlugin(GetPluginNameStatic(), 389 GetPluginDescriptionStatic(), CreateInstance, 390 CreateMemoryInstance, GetModuleSpecifications); 391 } 392 393 void ObjectFileELF::Terminate() { 394 PluginManager::UnregisterPlugin(CreateInstance); 395 } 396 397 lldb_private::ConstString ObjectFileELF::GetPluginNameStatic() { 398 static ConstString g_name("elf"); 399 return g_name; 400 } 401 402 const char *ObjectFileELF::GetPluginDescriptionStatic() { 403 return "ELF object file reader."; 404 } 405 406 ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp, 407 DataBufferSP &data_sp, 408 lldb::offset_t data_offset, 409 const lldb_private::FileSpec *file, 410 lldb::offset_t file_offset, 411 lldb::offset_t length) { 412 if (!data_sp) { 413 data_sp = MapFileData(*file, length, file_offset); 414 if (!data_sp) 415 return nullptr; 416 data_offset = 0; 417 } 418 419 assert(data_sp); 420 421 if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset)) 422 return nullptr; 423 424 const uint8_t *magic = data_sp->GetBytes() + data_offset; 425 if (!ELFHeader::MagicBytesMatch(magic)) 426 return nullptr; 427 428 // Update the data to contain the entire file if it doesn't already 429 if (data_sp->GetByteSize() < length) { 430 data_sp = MapFileData(*file, length, file_offset); 431 if (!data_sp) 432 return nullptr; 433 data_offset = 0; 434 magic = data_sp->GetBytes(); 435 } 436 437 unsigned address_size = ELFHeader::AddressSizeInBytes(magic); 438 if (address_size == 4 || address_size == 8) { 439 std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF( 440 module_sp, data_sp, data_offset, file, file_offset, length)); 441 ArchSpec spec = objfile_ap->GetArchitecture(); 442 if (spec && objfile_ap->SetModulesArchitecture(spec)) 443 return objfile_ap.release(); 444 } 445 446 return NULL; 447 } 448 449 ObjectFile *ObjectFileELF::CreateMemoryInstance( 450 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp, 451 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) { 452 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) { 453 const uint8_t *magic = data_sp->GetBytes(); 454 if (ELFHeader::MagicBytesMatch(magic)) { 455 unsigned address_size = ELFHeader::AddressSizeInBytes(magic); 456 if (address_size == 4 || address_size == 8) { 457 std::unique_ptr<ObjectFileELF> objfile_ap( 458 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr)); 459 ArchSpec spec = objfile_ap->GetArchitecture(); 460 if (spec && objfile_ap->SetModulesArchitecture(spec)) 461 return objfile_ap.release(); 462 } 463 } 464 } 465 return NULL; 466 } 467 468 bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp, 469 lldb::addr_t data_offset, 470 lldb::addr_t data_length) { 471 if (data_sp && 472 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) { 473 const uint8_t *magic = data_sp->GetBytes() + data_offset; 474 return ELFHeader::MagicBytesMatch(magic); 475 } 476 return false; 477 } 478 479 /* 480 * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c 481 * 482 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or 483 * code or tables extracted from it, as desired without restriction. 484 */ 485 static uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) { 486 static const uint32_t g_crc32_tab[] = { 487 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 488 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 489 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 490 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 491 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 492 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 493 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 494 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 495 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 496 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 497 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 498 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 499 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 500 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 501 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 502 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 503 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 504 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 505 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 506 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 507 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 508 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 509 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 510 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 511 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 512 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 513 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 514 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 515 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 516 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 517 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 518 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 519 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 520 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 521 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 522 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 523 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 524 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 525 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 526 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 527 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 528 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 529 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; 530 const uint8_t *p = (const uint8_t *)buf; 531 532 crc = crc ^ ~0U; 533 while (size--) 534 crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); 535 return crc ^ ~0U; 536 } 537 538 static uint32_t calc_gnu_debuglink_crc32(const void *buf, size_t size) { 539 return calc_crc32(0U, buf, size); 540 } 541 542 uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32( 543 const ProgramHeaderColl &program_headers, DataExtractor &object_data) { 544 545 uint32_t core_notes_crc = 0; 546 547 for (const ELFProgramHeader &H : program_headers) { 548 if (H.p_type == llvm::ELF::PT_NOTE) { 549 const elf_off ph_offset = H.p_offset; 550 const size_t ph_size = H.p_filesz; 551 552 DataExtractor segment_data; 553 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) { 554 // The ELF program header contained incorrect data, probably corefile 555 // is incomplete or corrupted. 556 break; 557 } 558 559 core_notes_crc = calc_crc32(core_notes_crc, segment_data.GetDataStart(), 560 segment_data.GetByteSize()); 561 } 562 } 563 564 return core_notes_crc; 565 } 566 567 static const char *OSABIAsCString(unsigned char osabi_byte) { 568 #define _MAKE_OSABI_CASE(x) \ 569 case x: \ 570 return #x 571 switch (osabi_byte) { 572 _MAKE_OSABI_CASE(ELFOSABI_NONE); 573 _MAKE_OSABI_CASE(ELFOSABI_HPUX); 574 _MAKE_OSABI_CASE(ELFOSABI_NETBSD); 575 _MAKE_OSABI_CASE(ELFOSABI_GNU); 576 _MAKE_OSABI_CASE(ELFOSABI_HURD); 577 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS); 578 _MAKE_OSABI_CASE(ELFOSABI_AIX); 579 _MAKE_OSABI_CASE(ELFOSABI_IRIX); 580 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD); 581 _MAKE_OSABI_CASE(ELFOSABI_TRU64); 582 _MAKE_OSABI_CASE(ELFOSABI_MODESTO); 583 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD); 584 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS); 585 _MAKE_OSABI_CASE(ELFOSABI_NSK); 586 _MAKE_OSABI_CASE(ELFOSABI_AROS); 587 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS); 588 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI); 589 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX); 590 _MAKE_OSABI_CASE(ELFOSABI_ARM); 591 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE); 592 default: 593 return "<unknown-osabi>"; 594 } 595 #undef _MAKE_OSABI_CASE 596 } 597 598 // 599 // WARNING : This function is being deprecated 600 // It's functionality has moved to ArchSpec::SetArchitecture This function is 601 // only being kept to validate the move. 602 // 603 // TODO : Remove this function 604 static bool GetOsFromOSABI(unsigned char osabi_byte, 605 llvm::Triple::OSType &ostype) { 606 switch (osabi_byte) { 607 case ELFOSABI_AIX: 608 ostype = llvm::Triple::OSType::AIX; 609 break; 610 case ELFOSABI_FREEBSD: 611 ostype = llvm::Triple::OSType::FreeBSD; 612 break; 613 case ELFOSABI_GNU: 614 ostype = llvm::Triple::OSType::Linux; 615 break; 616 case ELFOSABI_NETBSD: 617 ostype = llvm::Triple::OSType::NetBSD; 618 break; 619 case ELFOSABI_OPENBSD: 620 ostype = llvm::Triple::OSType::OpenBSD; 621 break; 622 case ELFOSABI_SOLARIS: 623 ostype = llvm::Triple::OSType::Solaris; 624 break; 625 default: 626 ostype = llvm::Triple::OSType::UnknownOS; 627 } 628 return ostype != llvm::Triple::OSType::UnknownOS; 629 } 630 631 size_t ObjectFileELF::GetModuleSpecifications( 632 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp, 633 lldb::offset_t data_offset, lldb::offset_t file_offset, 634 lldb::offset_t length, lldb_private::ModuleSpecList &specs) { 635 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES)); 636 637 const size_t initial_count = specs.GetSize(); 638 639 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) { 640 DataExtractor data; 641 data.SetData(data_sp); 642 elf::ELFHeader header; 643 lldb::offset_t header_offset = data_offset; 644 if (header.Parse(data, &header_offset)) { 645 if (data_sp) { 646 ModuleSpec spec(file); 647 648 const uint32_t sub_type = subTypeFromElfHeader(header); 649 spec.GetArchitecture().SetArchitecture( 650 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]); 651 652 if (spec.GetArchitecture().IsValid()) { 653 llvm::Triple::OSType ostype; 654 llvm::Triple::VendorType vendor; 655 llvm::Triple::OSType spec_ostype = 656 spec.GetArchitecture().GetTriple().getOS(); 657 658 if (log) 659 log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s", 660 __FUNCTION__, file.GetPath().c_str(), 661 OSABIAsCString(header.e_ident[EI_OSABI])); 662 663 // SetArchitecture should have set the vendor to unknown 664 vendor = spec.GetArchitecture().GetTriple().getVendor(); 665 assert(vendor == llvm::Triple::UnknownVendor); 666 UNUSED_IF_ASSERT_DISABLED(vendor); 667 668 // 669 // Validate it is ok to remove GetOsFromOSABI 670 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype); 671 assert(spec_ostype == ostype); 672 if (spec_ostype != llvm::Triple::OSType::UnknownOS) { 673 if (log) 674 log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type " 675 "from ELF header OSABI.", 676 __FUNCTION__, file.GetPath().c_str()); 677 } 678 679 data_sp = MapFileData(file, -1, file_offset); 680 if (data_sp) 681 data.SetData(data_sp); 682 // In case there is header extension in the section #0, the header we 683 // parsed above could have sentinel values for e_phnum, e_shnum, and 684 // e_shstrndx. In this case we need to reparse the header with a 685 // bigger data source to get the actual values. 686 if (header.HasHeaderExtension()) { 687 lldb::offset_t header_offset = data_offset; 688 header.Parse(data, &header_offset); 689 } 690 691 uint32_t gnu_debuglink_crc = 0; 692 std::string gnu_debuglink_file; 693 SectionHeaderColl section_headers; 694 lldb_private::UUID &uuid = spec.GetUUID(); 695 696 GetSectionHeaderInfo(section_headers, data, header, uuid, 697 gnu_debuglink_file, gnu_debuglink_crc, 698 spec.GetArchitecture()); 699 700 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple(); 701 702 if (log) 703 log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s " 704 "(architecture %s)", 705 __FUNCTION__, file.GetPath().c_str(), 706 spec_triple.getTriple().c_str(), 707 spec.GetArchitecture().GetArchitectureName()); 708 709 if (!uuid.IsValid()) { 710 uint32_t core_notes_crc = 0; 711 712 if (!gnu_debuglink_crc) { 713 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 714 lldb_private::Timer scoped_timer( 715 func_cat, 716 "Calculating module crc32 %s with size %" PRIu64 " KiB", 717 file.GetLastPathComponent().AsCString(), 718 (FileSystem::Instance().GetByteSize(file) - file_offset) / 719 1024); 720 721 // For core files - which usually don't happen to have a 722 // gnu_debuglink, and are pretty bulky - calculating whole 723 // contents crc32 would be too much of luxury. Thus we will need 724 // to fallback to something simpler. 725 if (header.e_type == llvm::ELF::ET_CORE) { 726 ProgramHeaderColl program_headers; 727 GetProgramHeaderInfo(program_headers, data, header); 728 729 core_notes_crc = 730 CalculateELFNotesSegmentsCRC32(program_headers, data); 731 } else { 732 gnu_debuglink_crc = calc_gnu_debuglink_crc32( 733 data.GetDataStart(), data.GetByteSize()); 734 } 735 } 736 using u32le = llvm::support::ulittle32_t; 737 if (gnu_debuglink_crc) { 738 // Use 4 bytes of crc from the .gnu_debuglink section. 739 u32le data(gnu_debuglink_crc); 740 uuid = UUID::fromData(&data, sizeof(data)); 741 } else if (core_notes_crc) { 742 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make 743 // it look different form .gnu_debuglink crc followed by 4 bytes 744 // of note segments crc. 745 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; 746 uuid = UUID::fromData(data, sizeof(data)); 747 } 748 } 749 750 specs.Append(spec); 751 } 752 } 753 } 754 } 755 756 return specs.GetSize() - initial_count; 757 } 758 759 //------------------------------------------------------------------ 760 // PluginInterface protocol 761 //------------------------------------------------------------------ 762 lldb_private::ConstString ObjectFileELF::GetPluginName() { 763 return GetPluginNameStatic(); 764 } 765 766 uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; } 767 //------------------------------------------------------------------ 768 // ObjectFile protocol 769 //------------------------------------------------------------------ 770 771 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp, 772 DataBufferSP &data_sp, lldb::offset_t data_offset, 773 const FileSpec *file, lldb::offset_t file_offset, 774 lldb::offset_t length) 775 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset), 776 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0), 777 m_program_headers(), m_section_headers(), m_dynamic_symbols(), 778 m_filespec_ap(), m_entry_point_address(), m_arch_spec() { 779 if (file) 780 m_file = *file; 781 ::memset(&m_header, 0, sizeof(m_header)); 782 } 783 784 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp, 785 DataBufferSP &header_data_sp, 786 const lldb::ProcessSP &process_sp, 787 addr_t header_addr) 788 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp), 789 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0), 790 m_program_headers(), m_section_headers(), m_dynamic_symbols(), 791 m_filespec_ap(), m_entry_point_address(), m_arch_spec() { 792 ::memset(&m_header, 0, sizeof(m_header)); 793 } 794 795 ObjectFileELF::~ObjectFileELF() {} 796 797 bool ObjectFileELF::IsExecutable() const { 798 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0); 799 } 800 801 bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value, 802 bool value_is_offset) { 803 ModuleSP module_sp = GetModule(); 804 if (module_sp) { 805 size_t num_loaded_sections = 0; 806 SectionList *section_list = GetSectionList(); 807 if (section_list) { 808 if (!value_is_offset) { 809 bool found_offset = false; 810 for (const ELFProgramHeader &H : ProgramHeaders()) { 811 if (H.p_type != PT_LOAD || H.p_offset != 0) 812 continue; 813 814 value = value - H.p_vaddr; 815 found_offset = true; 816 break; 817 } 818 if (!found_offset) 819 return false; 820 } 821 822 const size_t num_sections = section_list->GetSize(); 823 size_t sect_idx = 0; 824 825 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 826 // Iterate through the object file sections to find all of the sections 827 // that have SHF_ALLOC in their flag bits. 828 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); 829 if (section_sp->Test(SHF_ALLOC) || 830 section_sp->GetType() == eSectionTypeContainer) { 831 lldb::addr_t load_addr = section_sp->GetFileAddress(); 832 // We don't want to update the load address of a section with type 833 // eSectionTypeAbsoluteAddress as they already have the absolute load 834 // address already specified 835 if (section_sp->GetType() != eSectionTypeAbsoluteAddress) 836 load_addr += value; 837 838 // On 32-bit systems the load address have to fit into 4 bytes. The 839 // rest of the bytes are the overflow from the addition. 840 if (GetAddressByteSize() == 4) 841 load_addr &= 0xFFFFFFFF; 842 843 if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp, 844 load_addr)) 845 ++num_loaded_sections; 846 } 847 } 848 return num_loaded_sections > 0; 849 } 850 } 851 return false; 852 } 853 854 ByteOrder ObjectFileELF::GetByteOrder() const { 855 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB) 856 return eByteOrderBig; 857 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB) 858 return eByteOrderLittle; 859 return eByteOrderInvalid; 860 } 861 862 uint32_t ObjectFileELF::GetAddressByteSize() const { 863 return m_data.GetAddressByteSize(); 864 } 865 866 AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) { 867 Symtab *symtab = GetSymtab(); 868 if (!symtab) 869 return AddressClass::eUnknown; 870 871 // The address class is determined based on the symtab. Ask it from the 872 // object file what contains the symtab information. 873 ObjectFile *symtab_objfile = symtab->GetObjectFile(); 874 if (symtab_objfile != nullptr && symtab_objfile != this) 875 return symtab_objfile->GetAddressClass(file_addr); 876 877 auto res = ObjectFile::GetAddressClass(file_addr); 878 if (res != AddressClass::eCode) 879 return res; 880 881 auto ub = m_address_class_map.upper_bound(file_addr); 882 if (ub == m_address_class_map.begin()) { 883 // No entry in the address class map before the address. Return default 884 // address class for an address in a code section. 885 return AddressClass::eCode; 886 } 887 888 // Move iterator to the address class entry preceding address 889 --ub; 890 891 return ub->second; 892 } 893 894 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) { 895 return std::distance(m_section_headers.begin(), I); 896 } 897 898 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const { 899 return std::distance(m_section_headers.begin(), I); 900 } 901 902 bool ObjectFileELF::ParseHeader() { 903 lldb::offset_t offset = 0; 904 return m_header.Parse(m_data, &offset); 905 } 906 907 bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) { 908 // Need to parse the section list to get the UUIDs, so make sure that's been 909 // done. 910 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile) 911 return false; 912 913 using u32le = llvm::support::ulittle32_t; 914 if (m_uuid.IsValid()) { 915 // We have the full build id uuid. 916 *uuid = m_uuid; 917 return true; 918 } else if (GetType() == ObjectFile::eTypeCoreFile) { 919 uint32_t core_notes_crc = 0; 920 921 if (!ParseProgramHeaders()) 922 return false; 923 924 core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data); 925 926 if (core_notes_crc) { 927 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it look 928 // different form .gnu_debuglink crc - followed by 4 bytes of note 929 // segments crc. 930 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)}; 931 m_uuid = UUID::fromData(data, sizeof(data)); 932 } 933 } else { 934 if (!m_gnu_debuglink_crc) 935 m_gnu_debuglink_crc = 936 calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize()); 937 if (m_gnu_debuglink_crc) { 938 // Use 4 bytes of crc from the .gnu_debuglink section. 939 u32le data(m_gnu_debuglink_crc); 940 m_uuid = UUID::fromData(&data, sizeof(data)); 941 } 942 } 943 944 if (m_uuid.IsValid()) { 945 *uuid = m_uuid; 946 return true; 947 } 948 949 return false; 950 } 951 952 lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() { 953 FileSpecList file_spec_list; 954 955 if (!m_gnu_debuglink_file.empty()) { 956 FileSpec file_spec(m_gnu_debuglink_file); 957 file_spec_list.Append(file_spec); 958 } 959 return file_spec_list; 960 } 961 962 uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) { 963 size_t num_modules = ParseDependentModules(); 964 uint32_t num_specs = 0; 965 966 for (unsigned i = 0; i < num_modules; ++i) { 967 if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i))) 968 num_specs++; 969 } 970 971 return num_specs; 972 } 973 974 Address ObjectFileELF::GetImageInfoAddress(Target *target) { 975 if (!ParseDynamicSymbols()) 976 return Address(); 977 978 SectionList *section_list = GetSectionList(); 979 if (!section_list) 980 return Address(); 981 982 // Find the SHT_DYNAMIC (.dynamic) section. 983 SectionSP dynsym_section_sp( 984 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)); 985 if (!dynsym_section_sp) 986 return Address(); 987 assert(dynsym_section_sp->GetObjectFile() == this); 988 989 user_id_t dynsym_id = dynsym_section_sp->GetID(); 990 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id); 991 if (!dynsym_hdr) 992 return Address(); 993 994 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) { 995 ELFDynamic &symbol = m_dynamic_symbols[i]; 996 997 if (symbol.d_tag == DT_DEBUG) { 998 // Compute the offset as the number of previous entries plus the size of 999 // d_tag. 1000 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize(); 1001 return Address(dynsym_section_sp, offset); 1002 } 1003 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP 1004 // exists in non-PIE. 1005 else if ((symbol.d_tag == DT_MIPS_RLD_MAP || 1006 symbol.d_tag == DT_MIPS_RLD_MAP_REL) && 1007 target) { 1008 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize(); 1009 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target); 1010 if (dyn_base == LLDB_INVALID_ADDRESS) 1011 return Address(); 1012 1013 Status error; 1014 if (symbol.d_tag == DT_MIPS_RLD_MAP) { 1015 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer. 1016 Address addr; 1017 if (target->ReadPointerFromMemory(dyn_base + offset, false, error, 1018 addr)) 1019 return addr; 1020 } 1021 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) { 1022 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer, 1023 // relative to the address of the tag. 1024 uint64_t rel_offset; 1025 rel_offset = target->ReadUnsignedIntegerFromMemory( 1026 dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error); 1027 if (error.Success() && rel_offset != UINT64_MAX) { 1028 Address addr; 1029 addr_t debug_ptr_address = 1030 dyn_base + (offset - GetAddressByteSize()) + rel_offset; 1031 addr.SetOffset(debug_ptr_address); 1032 return addr; 1033 } 1034 } 1035 } 1036 } 1037 1038 return Address(); 1039 } 1040 1041 lldb_private::Address ObjectFileELF::GetEntryPointAddress() { 1042 if (m_entry_point_address.IsValid()) 1043 return m_entry_point_address; 1044 1045 if (!ParseHeader() || !IsExecutable()) 1046 return m_entry_point_address; 1047 1048 SectionList *section_list = GetSectionList(); 1049 addr_t offset = m_header.e_entry; 1050 1051 if (!section_list) 1052 m_entry_point_address.SetOffset(offset); 1053 else 1054 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list); 1055 return m_entry_point_address; 1056 } 1057 1058 //---------------------------------------------------------------------- 1059 // ParseDependentModules 1060 //---------------------------------------------------------------------- 1061 size_t ObjectFileELF::ParseDependentModules() { 1062 if (m_filespec_ap.get()) 1063 return m_filespec_ap->GetSize(); 1064 1065 m_filespec_ap.reset(new FileSpecList()); 1066 1067 if (!ParseSectionHeaders()) 1068 return 0; 1069 1070 SectionList *section_list = GetSectionList(); 1071 if (!section_list) 1072 return 0; 1073 1074 // Find the SHT_DYNAMIC section. 1075 Section *dynsym = 1076 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true) 1077 .get(); 1078 if (!dynsym) 1079 return 0; 1080 assert(dynsym->GetObjectFile() == this); 1081 1082 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID()); 1083 if (!header) 1084 return 0; 1085 // sh_link: section header index of string table used by entries in the 1086 // section. 1087 Section *dynstr = section_list->FindSectionByID(header->sh_link).get(); 1088 if (!dynstr) 1089 return 0; 1090 1091 DataExtractor dynsym_data; 1092 DataExtractor dynstr_data; 1093 if (ReadSectionData(dynsym, dynsym_data) && 1094 ReadSectionData(dynstr, dynstr_data)) { 1095 ELFDynamic symbol; 1096 const lldb::offset_t section_size = dynsym_data.GetByteSize(); 1097 lldb::offset_t offset = 0; 1098 1099 // The only type of entries we are concerned with are tagged DT_NEEDED, 1100 // yielding the name of a required library. 1101 while (offset < section_size) { 1102 if (!symbol.Parse(dynsym_data, &offset)) 1103 break; 1104 1105 if (symbol.d_tag != DT_NEEDED) 1106 continue; 1107 1108 uint32_t str_index = static_cast<uint32_t>(symbol.d_val); 1109 const char *lib_name = dynstr_data.PeekCStr(str_index); 1110 FileSpec file_spec(lib_name); 1111 FileSystem::Instance().Resolve(file_spec); 1112 m_filespec_ap->Append(file_spec); 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)) 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 bool ObjectFileELF::ParseProgramHeaders() { 1160 return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0; 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)) 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 llvm::StringRef 1707 ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const { 1708 size_t pos = symbol_name.find('@'); 1709 return symbol_name.substr(0, pos); 1710 } 1711 1712 //---------------------------------------------------------------------- 1713 // ParseSectionHeaders 1714 //---------------------------------------------------------------------- 1715 size_t ObjectFileELF::ParseSectionHeaders() { 1716 return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, 1717 m_gnu_debuglink_file, m_gnu_debuglink_crc, 1718 m_arch_spec); 1719 } 1720 1721 const ObjectFileELF::ELFSectionHeaderInfo * 1722 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) { 1723 if (!ParseSectionHeaders()) 1724 return NULL; 1725 1726 if (id < m_section_headers.size()) 1727 return &m_section_headers[id]; 1728 1729 return NULL; 1730 } 1731 1732 lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) { 1733 if (!name || !name[0] || !ParseSectionHeaders()) 1734 return 0; 1735 for (size_t i = 1; i < m_section_headers.size(); ++i) 1736 if (m_section_headers[i].section_name == ConstString(name)) 1737 return i; 1738 return 0; 1739 } 1740 1741 static SectionType GetSectionTypeFromName(llvm::StringRef Name) { 1742 return llvm::StringSwitch<SectionType>(Name) 1743 .Case(".ARM.exidx", eSectionTypeARMexidx) 1744 .Case(".ARM.extab", eSectionTypeARMextab) 1745 .Cases(".bss", ".tbss", eSectionTypeZeroFill) 1746 .Cases(".data", ".tdata", eSectionTypeData) 1747 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev) 1748 .Case(".debug_abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo) 1749 .Case(".debug_addr", eSectionTypeDWARFDebugAddr) 1750 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges) 1751 .Case(".debug_cu_index", eSectionTypeDWARFDebugCuIndex) 1752 .Case(".debug_frame", eSectionTypeDWARFDebugFrame) 1753 .Case(".debug_info", eSectionTypeDWARFDebugInfo) 1754 .Case(".debug_info.dwo", eSectionTypeDWARFDebugInfoDwo) 1755 .Cases(".debug_line", ".debug_line.dwo", eSectionTypeDWARFDebugLine) 1756 .Cases(".debug_line_str", ".debug_line_str.dwo", 1757 eSectionTypeDWARFDebugLineStr) 1758 .Cases(".debug_loc", ".debug_loc.dwo", eSectionTypeDWARFDebugLoc) 1759 .Cases(".debug_loclists", ".debug_loclists.dwo", 1760 eSectionTypeDWARFDebugLocLists) 1761 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo) 1762 .Cases(".debug_macro", ".debug_macro.dwo", eSectionTypeDWARFDebugMacro) 1763 .Case(".debug_names", eSectionTypeDWARFDebugNames) 1764 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames) 1765 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes) 1766 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges) 1767 .Case(".debug_rnglists", eSectionTypeDWARFDebugRngLists) 1768 .Case(".debug_str", eSectionTypeDWARFDebugStr) 1769 .Case(".debug_str.dwo", eSectionTypeDWARFDebugStrDwo) 1770 .Case(".debug_str_offsets", eSectionTypeDWARFDebugStrOffsets) 1771 .Case(".debug_str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo) 1772 .Case(".debug_types", eSectionTypeDWARFDebugTypes) 1773 .Case(".eh_frame", eSectionTypeEHFrame) 1774 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink) 1775 .Case(".gosymtab", eSectionTypeGoSymtab) 1776 .Case(".text", eSectionTypeCode) 1777 .Default(eSectionTypeOther); 1778 } 1779 1780 SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const { 1781 switch (H.sh_type) { 1782 case SHT_PROGBITS: 1783 if (H.sh_flags & SHF_EXECINSTR) 1784 return eSectionTypeCode; 1785 break; 1786 case SHT_SYMTAB: 1787 return eSectionTypeELFSymbolTable; 1788 case SHT_DYNSYM: 1789 return eSectionTypeELFDynamicSymbols; 1790 case SHT_RELA: 1791 case SHT_REL: 1792 return eSectionTypeELFRelocationEntries; 1793 case SHT_DYNAMIC: 1794 return eSectionTypeELFDynamicLinkInfo; 1795 } 1796 SectionType Type = GetSectionTypeFromName(H.section_name.GetStringRef()); 1797 if (Type == eSectionTypeOther) { 1798 // the kalimba toolchain assumes that ELF section names are free-form. 1799 // It does support linkscripts which (can) give rise to various 1800 // arbitrarily named sections being "Code" or "Data". 1801 Type = kalimbaSectionType(m_header, H); 1802 } 1803 return Type; 1804 } 1805 1806 static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) { 1807 switch (Type) { 1808 case eSectionTypeData: 1809 case eSectionTypeZeroFill: 1810 return arch.GetDataByteSize(); 1811 case eSectionTypeCode: 1812 return arch.GetCodeByteSize(); 1813 default: 1814 return 1; 1815 } 1816 } 1817 1818 static Permissions GetPermissions(const ELFSectionHeader &H) { 1819 Permissions Perm = Permissions(0); 1820 if (H.sh_flags & SHF_ALLOC) 1821 Perm |= ePermissionsReadable; 1822 if (H.sh_flags & SHF_WRITE) 1823 Perm |= ePermissionsWritable; 1824 if (H.sh_flags & SHF_EXECINSTR) 1825 Perm |= ePermissionsExecutable; 1826 return Perm; 1827 } 1828 1829 static Permissions GetPermissions(const ELFProgramHeader &H) { 1830 Permissions Perm = Permissions(0); 1831 if (H.p_flags & PF_R) 1832 Perm |= ePermissionsReadable; 1833 if (H.p_flags & PF_W) 1834 Perm |= ePermissionsWritable; 1835 if (H.p_flags & PF_X) 1836 Perm |= ePermissionsExecutable; 1837 return Perm; 1838 } 1839 1840 namespace { 1841 1842 using VMRange = lldb_private::Range<addr_t, addr_t>; 1843 1844 struct SectionAddressInfo { 1845 SectionSP Segment; 1846 VMRange Range; 1847 }; 1848 1849 // (Unlinked) ELF object files usually have 0 for every section address, meaning 1850 // we need to compute synthetic addresses in order for "file addresses" from 1851 // different sections to not overlap. This class handles that logic. 1852 class VMAddressProvider { 1853 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4, 1854 llvm::IntervalMapHalfOpenInfo<addr_t>>; 1855 1856 ObjectFile::Type ObjectType; 1857 addr_t NextVMAddress = 0; 1858 VMMap::Allocator Alloc; 1859 VMMap Segments = VMMap(Alloc); 1860 VMMap Sections = VMMap(Alloc); 1861 lldb_private::Log *Log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES); 1862 1863 VMRange GetVMRange(const ELFSectionHeader &H) { 1864 addr_t Address = H.sh_addr; 1865 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0; 1866 if (ObjectType == ObjectFile::Type::eTypeObjectFile && Segments.empty() && (H.sh_flags & SHF_ALLOC)) { 1867 NextVMAddress = 1868 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1)); 1869 Address = NextVMAddress; 1870 NextVMAddress += Size; 1871 } 1872 return VMRange(Address, Size); 1873 } 1874 1875 public: 1876 VMAddressProvider(ObjectFile::Type Type) : ObjectType(Type) {} 1877 1878 llvm::Optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) { 1879 if (H.p_memsz == 0) { 1880 LLDB_LOG(Log, 1881 "Ignoring zero-sized PT_LOAD segment. Corrupt object file?"); 1882 return llvm::None; 1883 } 1884 1885 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) { 1886 LLDB_LOG(Log, 1887 "Ignoring overlapping PT_LOAD segment. Corrupt object file?"); 1888 return llvm::None; 1889 } 1890 return VMRange(H.p_vaddr, H.p_memsz); 1891 } 1892 1893 llvm::Optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) { 1894 VMRange Range = GetVMRange(H); 1895 SectionSP Segment; 1896 auto It = Segments.find(Range.GetRangeBase()); 1897 if ((H.sh_flags & SHF_ALLOC) && It.valid()) { 1898 addr_t MaxSize; 1899 if (It.start() <= Range.GetRangeBase()) { 1900 MaxSize = It.stop() - Range.GetRangeBase(); 1901 Segment = *It; 1902 } else 1903 MaxSize = It.start() - Range.GetRangeBase(); 1904 if (Range.GetByteSize() > MaxSize) { 1905 LLDB_LOG(Log, "Shortening section crossing segment boundaries. " 1906 "Corrupt object file?"); 1907 Range.SetByteSize(MaxSize); 1908 } 1909 } 1910 if (Range.GetByteSize() > 0 && 1911 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) { 1912 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?"); 1913 return llvm::None; 1914 } 1915 if (Segment) 1916 Range.Slide(-Segment->GetFileAddress()); 1917 return SectionAddressInfo{Segment, Range}; 1918 } 1919 1920 void AddSegment(const VMRange &Range, SectionSP Seg) { 1921 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg)); 1922 } 1923 1924 void AddSection(SectionAddressInfo Info, SectionSP Sect) { 1925 if (Info.Range.GetByteSize() == 0) 1926 return; 1927 if (Info.Segment) 1928 Info.Range.Slide(Info.Segment->GetFileAddress()); 1929 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(), 1930 std::move(Sect)); 1931 } 1932 }; 1933 } 1934 1935 void ObjectFileELF::CreateSections(SectionList &unified_section_list) { 1936 if (m_sections_ap) 1937 return; 1938 1939 m_sections_ap = llvm::make_unique<SectionList>(); 1940 VMAddressProvider address_provider(CalculateType()); 1941 1942 size_t LoadID = 0; 1943 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) { 1944 const ELFProgramHeader &PHdr = EnumPHdr.value(); 1945 if (PHdr.p_type != PT_LOAD) 1946 continue; 1947 1948 auto InfoOr = address_provider.GetAddressInfo(PHdr); 1949 if (!InfoOr) 1950 continue; 1951 1952 ConstString Name(("PT_LOAD[" + llvm::Twine(LoadID++) + "]").str()); 1953 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1)); 1954 SectionSP Segment = std::make_shared<Section>( 1955 GetModule(), this, SegmentID(EnumPHdr.index()), Name, 1956 eSectionTypeContainer, InfoOr->GetRangeBase(), InfoOr->GetByteSize(), 1957 PHdr.p_offset, PHdr.p_filesz, Log2Align, /*flags*/ 0); 1958 Segment->SetPermissions(GetPermissions(PHdr)); 1959 m_sections_ap->AddSection(Segment); 1960 1961 address_provider.AddSegment(*InfoOr, std::move(Segment)); 1962 } 1963 1964 ParseSectionHeaders(); 1965 if (m_section_headers.empty()) 1966 return; 1967 1968 for (SectionHeaderCollIter I = std::next(m_section_headers.begin()); 1969 I != m_section_headers.end(); ++I) { 1970 const ELFSectionHeaderInfo &header = *I; 1971 1972 ConstString &name = I->section_name; 1973 const uint64_t file_size = 1974 header.sh_type == SHT_NOBITS ? 0 : header.sh_size; 1975 1976 auto InfoOr = address_provider.GetAddressInfo(header); 1977 if (!InfoOr) 1978 continue; 1979 1980 SectionType sect_type = GetSectionType(header); 1981 1982 const uint32_t target_bytes_size = 1983 GetTargetByteSize(sect_type, m_arch_spec); 1984 1985 elf::elf_xword log2align = 1986 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign); 1987 1988 SectionSP section_sp(new Section( 1989 InfoOr->Segment, GetModule(), // Module to which this section belongs. 1990 this, // ObjectFile to which this section belongs and should 1991 // read section data from. 1992 SectionIndex(I), // Section ID. 1993 name, // Section name. 1994 sect_type, // Section type. 1995 InfoOr->Range.GetRangeBase(), // VM address. 1996 InfoOr->Range.GetByteSize(), // VM size in bytes of this section. 1997 header.sh_offset, // Offset of this section in the file. 1998 file_size, // Size of the section as found in the file. 1999 log2align, // Alignment of the section 2000 header.sh_flags, // Flags for this section. 2001 target_bytes_size)); // Number of host bytes per target byte 2002 2003 section_sp->SetPermissions(GetPermissions(header)); 2004 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS); 2005 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_ap) 2006 .AddSection(section_sp); 2007 address_provider.AddSection(std::move(*InfoOr), std::move(section_sp)); 2008 } 2009 2010 // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the 2011 // unified section list. 2012 if (GetType() != eTypeDebugInfo) 2013 unified_section_list = *m_sections_ap; 2014 } 2015 2016 // Find the arm/aarch64 mapping symbol character in the given symbol name. 2017 // Mapping symbols have the form of "$<char>[.<any>]*". Additionally we 2018 // recognize cases when the mapping symbol prefixed by an arbitrary string 2019 // because if a symbol prefix added to each symbol in the object file with 2020 // objcopy then the mapping symbols are also prefixed. 2021 static char FindArmAarch64MappingSymbol(const char *symbol_name) { 2022 if (!symbol_name) 2023 return '\0'; 2024 2025 const char *dollar_pos = ::strchr(symbol_name, '$'); 2026 if (!dollar_pos || dollar_pos[1] == '\0') 2027 return '\0'; 2028 2029 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.') 2030 return dollar_pos[1]; 2031 return '\0'; 2032 } 2033 2034 #define STO_MIPS_ISA (3 << 6) 2035 #define STO_MICROMIPS (2 << 6) 2036 #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS) 2037 2038 // private 2039 unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id, 2040 SectionList *section_list, 2041 const size_t num_symbols, 2042 const DataExtractor &symtab_data, 2043 const DataExtractor &strtab_data) { 2044 ELFSymbol symbol; 2045 lldb::offset_t offset = 0; 2046 2047 static ConstString text_section_name(".text"); 2048 static ConstString init_section_name(".init"); 2049 static ConstString fini_section_name(".fini"); 2050 static ConstString ctors_section_name(".ctors"); 2051 static ConstString dtors_section_name(".dtors"); 2052 2053 static ConstString data_section_name(".data"); 2054 static ConstString rodata_section_name(".rodata"); 2055 static ConstString rodata1_section_name(".rodata1"); 2056 static ConstString data2_section_name(".data1"); 2057 static ConstString bss_section_name(".bss"); 2058 static ConstString opd_section_name(".opd"); // For ppc64 2059 2060 // On Android the oatdata and the oatexec symbols in the oat and odex files 2061 // covers the full .text section what causes issues with displaying unusable 2062 // symbol name to the user and very slow unwinding speed because the 2063 // instruction emulation based unwind plans try to emulate all instructions 2064 // in these symbols. Don't add these symbols to the symbol list as they have 2065 // no use for the debugger and they are causing a lot of trouble. Filtering 2066 // can't be restricted to Android because this special object file don't 2067 // contain the note section specifying the environment to Android but the 2068 // custom extension and file name makes it highly unlikely that this will 2069 // collide with anything else. 2070 ConstString file_extension = m_file.GetFileNameExtension(); 2071 bool skip_oatdata_oatexec = file_extension == ConstString(".oat") || 2072 file_extension == ConstString(".odex"); 2073 2074 ArchSpec arch = GetArchitecture(); 2075 ModuleSP module_sp(GetModule()); 2076 SectionList *module_section_list = 2077 module_sp ? module_sp->GetSectionList() : nullptr; 2078 2079 // Local cache to avoid doing a FindSectionByName for each symbol. The "const 2080 // char*" key must came from a ConstString object so they can be compared by 2081 // pointer 2082 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section; 2083 2084 unsigned i; 2085 for (i = 0; i < num_symbols; ++i) { 2086 if (!symbol.Parse(symtab_data, &offset)) 2087 break; 2088 2089 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name); 2090 if (!symbol_name) 2091 symbol_name = ""; 2092 2093 // No need to add non-section symbols that have no names 2094 if (symbol.getType() != STT_SECTION && 2095 (symbol_name == nullptr || symbol_name[0] == '\0')) 2096 continue; 2097 2098 // Skipping oatdata and oatexec sections if it is requested. See details 2099 // above the definition of skip_oatdata_oatexec for the reasons. 2100 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 || 2101 ::strcmp(symbol_name, "oatexec") == 0)) 2102 continue; 2103 2104 SectionSP symbol_section_sp; 2105 SymbolType symbol_type = eSymbolTypeInvalid; 2106 Elf64_Half shndx = symbol.st_shndx; 2107 2108 switch (shndx) { 2109 case SHN_ABS: 2110 symbol_type = eSymbolTypeAbsolute; 2111 break; 2112 case SHN_UNDEF: 2113 symbol_type = eSymbolTypeUndefined; 2114 break; 2115 default: 2116 symbol_section_sp = section_list->FindSectionByID(shndx); 2117 break; 2118 } 2119 2120 // If a symbol is undefined do not process it further even if it has a STT 2121 // type 2122 if (symbol_type != eSymbolTypeUndefined) { 2123 switch (symbol.getType()) { 2124 default: 2125 case STT_NOTYPE: 2126 // The symbol's type is not specified. 2127 break; 2128 2129 case STT_OBJECT: 2130 // The symbol is associated with a data object, such as a variable, an 2131 // array, etc. 2132 symbol_type = eSymbolTypeData; 2133 break; 2134 2135 case STT_FUNC: 2136 // The symbol is associated with a function or other executable code. 2137 symbol_type = eSymbolTypeCode; 2138 break; 2139 2140 case STT_SECTION: 2141 // The symbol is associated with a section. Symbol table entries of 2142 // this type exist primarily for relocation and normally have STB_LOCAL 2143 // binding. 2144 break; 2145 2146 case STT_FILE: 2147 // Conventionally, the symbol's name gives the name of the source file 2148 // associated with the object file. A file symbol has STB_LOCAL 2149 // binding, its section index is SHN_ABS, and it precedes the other 2150 // STB_LOCAL symbols for the file, if it is present. 2151 symbol_type = eSymbolTypeSourceFile; 2152 break; 2153 2154 case STT_GNU_IFUNC: 2155 // The symbol is associated with an indirect function. The actual 2156 // function will be resolved if it is referenced. 2157 symbol_type = eSymbolTypeResolver; 2158 break; 2159 } 2160 } 2161 2162 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) { 2163 if (symbol_section_sp) { 2164 const ConstString §_name = symbol_section_sp->GetName(); 2165 if (sect_name == text_section_name || sect_name == init_section_name || 2166 sect_name == fini_section_name || sect_name == ctors_section_name || 2167 sect_name == dtors_section_name) { 2168 symbol_type = eSymbolTypeCode; 2169 } else if (sect_name == data_section_name || 2170 sect_name == data2_section_name || 2171 sect_name == rodata_section_name || 2172 sect_name == rodata1_section_name || 2173 sect_name == bss_section_name) { 2174 symbol_type = eSymbolTypeData; 2175 } 2176 } 2177 } 2178 2179 int64_t symbol_value_offset = 0; 2180 uint32_t additional_flags = 0; 2181 2182 if (arch.IsValid()) { 2183 if (arch.GetMachine() == llvm::Triple::arm) { 2184 if (symbol.getBinding() == STB_LOCAL) { 2185 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name); 2186 if (symbol_type == eSymbolTypeCode) { 2187 switch (mapping_symbol) { 2188 case 'a': 2189 // $a[.<any>]* - marks an ARM instruction sequence 2190 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2191 break; 2192 case 'b': 2193 case 't': 2194 // $b[.<any>]* - marks a THUMB BL instruction sequence 2195 // $t[.<any>]* - marks a THUMB instruction sequence 2196 m_address_class_map[symbol.st_value] = 2197 AddressClass::eCodeAlternateISA; 2198 break; 2199 case 'd': 2200 // $d[.<any>]* - marks a data item sequence (e.g. lit pool) 2201 m_address_class_map[symbol.st_value] = AddressClass::eData; 2202 break; 2203 } 2204 } 2205 if (mapping_symbol) 2206 continue; 2207 } 2208 } else if (arch.GetMachine() == llvm::Triple::aarch64) { 2209 if (symbol.getBinding() == STB_LOCAL) { 2210 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name); 2211 if (symbol_type == eSymbolTypeCode) { 2212 switch (mapping_symbol) { 2213 case 'x': 2214 // $x[.<any>]* - marks an A64 instruction sequence 2215 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2216 break; 2217 case 'd': 2218 // $d[.<any>]* - marks a data item sequence (e.g. lit pool) 2219 m_address_class_map[symbol.st_value] = AddressClass::eData; 2220 break; 2221 } 2222 } 2223 if (mapping_symbol) 2224 continue; 2225 } 2226 } 2227 2228 if (arch.GetMachine() == llvm::Triple::arm) { 2229 if (symbol_type == eSymbolTypeCode) { 2230 if (symbol.st_value & 1) { 2231 // Subtracting 1 from the address effectively unsets the low order 2232 // bit, which results in the address actually pointing to the 2233 // beginning of the symbol. This delta will be used below in 2234 // conjunction with symbol.st_value to produce the final 2235 // symbol_value that we store in the symtab. 2236 symbol_value_offset = -1; 2237 m_address_class_map[symbol.st_value ^ 1] = 2238 AddressClass::eCodeAlternateISA; 2239 } else { 2240 // This address is ARM 2241 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2242 } 2243 } 2244 } 2245 2246 /* 2247 * MIPS: 2248 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for 2249 * MIPS). 2250 * This allows processor to switch between microMIPS and MIPS without any 2251 * need 2252 * for special mode-control register. However, apart from .debug_line, 2253 * none of 2254 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use 2255 * st_other 2256 * flag to check whether the symbol is microMIPS and then set the address 2257 * class 2258 * accordingly. 2259 */ 2260 const llvm::Triple::ArchType llvm_arch = arch.GetMachine(); 2261 if (llvm_arch == llvm::Triple::mips || 2262 llvm_arch == llvm::Triple::mipsel || 2263 llvm_arch == llvm::Triple::mips64 || 2264 llvm_arch == llvm::Triple::mips64el) { 2265 if (IS_MICROMIPS(symbol.st_other)) 2266 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA; 2267 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) { 2268 symbol.st_value = symbol.st_value & (~1ull); 2269 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA; 2270 } else { 2271 if (symbol_type == eSymbolTypeCode) 2272 m_address_class_map[symbol.st_value] = AddressClass::eCode; 2273 else if (symbol_type == eSymbolTypeData) 2274 m_address_class_map[symbol.st_value] = AddressClass::eData; 2275 else 2276 m_address_class_map[symbol.st_value] = AddressClass::eUnknown; 2277 } 2278 } 2279 } 2280 2281 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB 2282 // symbols. See above for more details. 2283 uint64_t symbol_value = symbol.st_value + symbol_value_offset; 2284 2285 if (symbol_section_sp == nullptr && shndx == SHN_ABS && 2286 symbol.st_size != 0) { 2287 // We don't have a section for a symbol with non-zero size. Create a new 2288 // section for it so the address range covered by the symbol is also 2289 // covered by the module (represented through the section list). It is 2290 // needed so module lookup for the addresses covered by this symbol will 2291 // be successfull. This case happens for absolute symbols. 2292 ConstString fake_section_name(std::string(".absolute.") + symbol_name); 2293 symbol_section_sp = 2294 std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name, 2295 eSectionTypeAbsoluteAddress, symbol_value, 2296 symbol.st_size, 0, 0, 0, SHF_ALLOC); 2297 2298 module_section_list->AddSection(symbol_section_sp); 2299 section_list->AddSection(symbol_section_sp); 2300 } 2301 2302 if (symbol_section_sp && 2303 CalculateType() != ObjectFile::Type::eTypeObjectFile) 2304 symbol_value -= symbol_section_sp->GetFileAddress(); 2305 2306 if (symbol_section_sp && module_section_list && 2307 module_section_list != section_list) { 2308 const ConstString §_name = symbol_section_sp->GetName(); 2309 auto section_it = section_name_to_section.find(sect_name.GetCString()); 2310 if (section_it == section_name_to_section.end()) 2311 section_it = 2312 section_name_to_section 2313 .emplace(sect_name.GetCString(), 2314 module_section_list->FindSectionByName(sect_name)) 2315 .first; 2316 if (section_it->second) 2317 symbol_section_sp = section_it->second; 2318 } 2319 2320 bool is_global = symbol.getBinding() == STB_GLOBAL; 2321 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags; 2322 bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z'); 2323 2324 llvm::StringRef symbol_ref(symbol_name); 2325 2326 // Symbol names may contain @VERSION suffixes. Find those and strip them 2327 // temporarily. 2328 size_t version_pos = symbol_ref.find('@'); 2329 bool has_suffix = version_pos != llvm::StringRef::npos; 2330 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos); 2331 Mangled mangled(ConstString(symbol_bare), is_mangled); 2332 2333 // Now append the suffix back to mangled and unmangled names. Only do it if 2334 // the demangling was successful (string is not empty). 2335 if (has_suffix) { 2336 llvm::StringRef suffix = symbol_ref.substr(version_pos); 2337 2338 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef(); 2339 if (!mangled_name.empty()) 2340 mangled.SetMangledName(ConstString((mangled_name + suffix).str())); 2341 2342 ConstString demangled = 2343 mangled.GetDemangledName(lldb::eLanguageTypeUnknown); 2344 llvm::StringRef demangled_name = demangled.GetStringRef(); 2345 if (!demangled_name.empty()) 2346 mangled.SetDemangledName(ConstString((demangled_name + suffix).str())); 2347 } 2348 2349 // In ELF all symbol should have a valid size but it is not true for some 2350 // function symbols coming from hand written assembly. As none of the 2351 // function symbol should have 0 size we try to calculate the size for 2352 // these symbols in the symtab with saying that their original size is not 2353 // valid. 2354 bool symbol_size_valid = 2355 symbol.st_size != 0 || symbol.getType() != STT_FUNC; 2356 2357 Symbol dc_symbol( 2358 i + start_id, // ID is the original symbol table index. 2359 mangled, 2360 symbol_type, // Type of this symbol 2361 is_global, // Is this globally visible? 2362 false, // Is this symbol debug info? 2363 false, // Is this symbol a trampoline? 2364 false, // Is this symbol artificial? 2365 AddressRange(symbol_section_sp, // Section in which this symbol is 2366 // defined or null. 2367 symbol_value, // Offset in section or symbol value. 2368 symbol.st_size), // Size in bytes of this symbol. 2369 symbol_size_valid, // Symbol size is valid 2370 has_suffix, // Contains linker annotations? 2371 flags); // Symbol flags. 2372 symtab->AddSymbol(dc_symbol); 2373 } 2374 return i; 2375 } 2376 2377 unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, 2378 user_id_t start_id, 2379 lldb_private::Section *symtab) { 2380 if (symtab->GetObjectFile() != this) { 2381 // If the symbol table section is owned by a different object file, have it 2382 // do the parsing. 2383 ObjectFileELF *obj_file_elf = 2384 static_cast<ObjectFileELF *>(symtab->GetObjectFile()); 2385 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab); 2386 } 2387 2388 // Get section list for this object file. 2389 SectionList *section_list = m_sections_ap.get(); 2390 if (!section_list) 2391 return 0; 2392 2393 user_id_t symtab_id = symtab->GetID(); 2394 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id); 2395 assert(symtab_hdr->sh_type == SHT_SYMTAB || 2396 symtab_hdr->sh_type == SHT_DYNSYM); 2397 2398 // sh_link: section header index of associated string table. 2399 user_id_t strtab_id = symtab_hdr->sh_link; 2400 Section *strtab = section_list->FindSectionByID(strtab_id).get(); 2401 2402 if (symtab && strtab) { 2403 assert(symtab->GetObjectFile() == this); 2404 assert(strtab->GetObjectFile() == this); 2405 2406 DataExtractor symtab_data; 2407 DataExtractor strtab_data; 2408 if (ReadSectionData(symtab, symtab_data) && 2409 ReadSectionData(strtab, strtab_data)) { 2410 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize; 2411 2412 return ParseSymbols(symbol_table, start_id, section_list, num_symbols, 2413 symtab_data, strtab_data); 2414 } 2415 } 2416 2417 return 0; 2418 } 2419 2420 size_t ObjectFileELF::ParseDynamicSymbols() { 2421 if (m_dynamic_symbols.size()) 2422 return m_dynamic_symbols.size(); 2423 2424 SectionList *section_list = GetSectionList(); 2425 if (!section_list) 2426 return 0; 2427 2428 // Find the SHT_DYNAMIC section. 2429 Section *dynsym = 2430 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true) 2431 .get(); 2432 if (!dynsym) 2433 return 0; 2434 assert(dynsym->GetObjectFile() == this); 2435 2436 ELFDynamic symbol; 2437 DataExtractor dynsym_data; 2438 if (ReadSectionData(dynsym, dynsym_data)) { 2439 const lldb::offset_t section_size = dynsym_data.GetByteSize(); 2440 lldb::offset_t cursor = 0; 2441 2442 while (cursor < section_size) { 2443 if (!symbol.Parse(dynsym_data, &cursor)) 2444 break; 2445 2446 m_dynamic_symbols.push_back(symbol); 2447 } 2448 } 2449 2450 return m_dynamic_symbols.size(); 2451 } 2452 2453 const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) { 2454 if (!ParseDynamicSymbols()) 2455 return NULL; 2456 2457 DynamicSymbolCollIter I = m_dynamic_symbols.begin(); 2458 DynamicSymbolCollIter E = m_dynamic_symbols.end(); 2459 for (; I != E; ++I) { 2460 ELFDynamic *symbol = &*I; 2461 2462 if (symbol->d_tag == tag) 2463 return symbol; 2464 } 2465 2466 return NULL; 2467 } 2468 2469 unsigned ObjectFileELF::PLTRelocationType() { 2470 // DT_PLTREL 2471 // This member specifies the type of relocation entry to which the 2472 // procedure linkage table refers. The d_val member holds DT_REL or 2473 // DT_RELA, as appropriate. All relocations in a procedure linkage table 2474 // must use the same relocation. 2475 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL); 2476 2477 if (symbol) 2478 return symbol->d_val; 2479 2480 return 0; 2481 } 2482 2483 // Returns the size of the normal plt entries and the offset of the first 2484 // normal plt entry. The 0th entry in the plt table is usually a resolution 2485 // entry which have different size in some architectures then the rest of the 2486 // plt entries. 2487 static std::pair<uint64_t, uint64_t> 2488 GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr, 2489 const ELFSectionHeader *plt_hdr) { 2490 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2491 2492 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 2493 // 16 bytes. So round the entsize up by the alignment if addralign is set. 2494 elf_xword plt_entsize = 2495 plt_hdr->sh_addralign 2496 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign) 2497 : plt_hdr->sh_entsize; 2498 2499 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly. 2500 // PLT entries relocation code in general requires multiple instruction and 2501 // should be greater than 4 bytes in most cases. Try to guess correct size 2502 // just in case. 2503 if (plt_entsize <= 4) { 2504 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the 2505 // size of the plt entries based on the number of entries and the size of 2506 // the plt section with the assumption that the size of the 0th entry is at 2507 // least as big as the size of the normal entries and it isn't much bigger 2508 // then that. 2509 if (plt_hdr->sh_addralign) 2510 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign / 2511 (num_relocations + 1) * plt_hdr->sh_addralign; 2512 else 2513 plt_entsize = plt_hdr->sh_size / (num_relocations + 1); 2514 } 2515 2516 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize; 2517 2518 return std::make_pair(plt_entsize, plt_offset); 2519 } 2520 2521 static unsigned ParsePLTRelocations( 2522 Symtab *symbol_table, user_id_t start_id, unsigned rel_type, 2523 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr, 2524 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr, 2525 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data, 2526 DataExtractor &symtab_data, DataExtractor &strtab_data) { 2527 ELFRelocation rel(rel_type); 2528 ELFSymbol symbol; 2529 lldb::offset_t offset = 0; 2530 2531 uint64_t plt_offset, plt_entsize; 2532 std::tie(plt_entsize, plt_offset) = 2533 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr); 2534 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2535 2536 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel); 2537 reloc_info_fn reloc_type; 2538 reloc_info_fn reloc_symbol; 2539 2540 if (hdr->Is32Bit()) { 2541 reloc_type = ELFRelocation::RelocType32; 2542 reloc_symbol = ELFRelocation::RelocSymbol32; 2543 } else { 2544 reloc_type = ELFRelocation::RelocType64; 2545 reloc_symbol = ELFRelocation::RelocSymbol64; 2546 } 2547 2548 unsigned slot_type = hdr->GetRelocationJumpSlotType(); 2549 unsigned i; 2550 for (i = 0; i < num_relocations; ++i) { 2551 if (!rel.Parse(rel_data, &offset)) 2552 break; 2553 2554 if (reloc_type(rel) != slot_type) 2555 continue; 2556 2557 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize; 2558 if (!symbol.Parse(symtab_data, &symbol_offset)) 2559 break; 2560 2561 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name); 2562 bool is_mangled = 2563 symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false; 2564 uint64_t plt_index = plt_offset + i * plt_entsize; 2565 2566 Symbol jump_symbol( 2567 i + start_id, // Symbol table index 2568 symbol_name, // symbol name. 2569 is_mangled, // is the symbol name mangled? 2570 eSymbolTypeTrampoline, // Type of this symbol 2571 false, // Is this globally visible? 2572 false, // Is this symbol debug info? 2573 true, // Is this symbol a trampoline? 2574 true, // Is this symbol artificial? 2575 plt_section_sp, // Section in which this symbol is defined or null. 2576 plt_index, // Offset in section or symbol value. 2577 plt_entsize, // Size in bytes of this symbol. 2578 true, // Size is valid 2579 false, // Contains linker annotations? 2580 0); // Symbol flags. 2581 2582 symbol_table->AddSymbol(jump_symbol); 2583 } 2584 2585 return i; 2586 } 2587 2588 unsigned 2589 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id, 2590 const ELFSectionHeaderInfo *rel_hdr, 2591 user_id_t rel_id) { 2592 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL); 2593 2594 // The link field points to the associated symbol table. 2595 user_id_t symtab_id = rel_hdr->sh_link; 2596 2597 // If the link field doesn't point to the appropriate symbol name table then 2598 // try to find it by name as some compiler don't fill in the link fields. 2599 if (!symtab_id) 2600 symtab_id = GetSectionIndexByName(".dynsym"); 2601 2602 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers 2603 // point that to the .got.plt or .got section instead of .plt. 2604 user_id_t plt_id = GetSectionIndexByName(".plt"); 2605 2606 if (!symtab_id || !plt_id) 2607 return 0; 2608 2609 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id); 2610 if (!plt_hdr) 2611 return 0; 2612 2613 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id); 2614 if (!sym_hdr) 2615 return 0; 2616 2617 SectionList *section_list = m_sections_ap.get(); 2618 if (!section_list) 2619 return 0; 2620 2621 Section *rel_section = section_list->FindSectionByID(rel_id).get(); 2622 if (!rel_section) 2623 return 0; 2624 2625 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id)); 2626 if (!plt_section_sp) 2627 return 0; 2628 2629 Section *symtab = section_list->FindSectionByID(symtab_id).get(); 2630 if (!symtab) 2631 return 0; 2632 2633 // sh_link points to associated string table. 2634 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get(); 2635 if (!strtab) 2636 return 0; 2637 2638 DataExtractor rel_data; 2639 if (!ReadSectionData(rel_section, rel_data)) 2640 return 0; 2641 2642 DataExtractor symtab_data; 2643 if (!ReadSectionData(symtab, symtab_data)) 2644 return 0; 2645 2646 DataExtractor strtab_data; 2647 if (!ReadSectionData(strtab, strtab_data)) 2648 return 0; 2649 2650 unsigned rel_type = PLTRelocationType(); 2651 if (!rel_type) 2652 return 0; 2653 2654 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header, 2655 rel_hdr, plt_hdr, sym_hdr, plt_section_sp, 2656 rel_data, symtab_data, strtab_data); 2657 } 2658 2659 unsigned ObjectFileELF::ApplyRelocations( 2660 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr, 2661 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr, 2662 DataExtractor &rel_data, DataExtractor &symtab_data, 2663 DataExtractor &debug_data, Section *rel_section) { 2664 ELFRelocation rel(rel_hdr->sh_type); 2665 lldb::addr_t offset = 0; 2666 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize; 2667 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel); 2668 reloc_info_fn reloc_type; 2669 reloc_info_fn reloc_symbol; 2670 2671 if (hdr->Is32Bit()) { 2672 reloc_type = ELFRelocation::RelocType32; 2673 reloc_symbol = ELFRelocation::RelocSymbol32; 2674 } else { 2675 reloc_type = ELFRelocation::RelocType64; 2676 reloc_symbol = ELFRelocation::RelocSymbol64; 2677 } 2678 2679 for (unsigned i = 0; i < num_relocations; ++i) { 2680 if (!rel.Parse(rel_data, &offset)) 2681 break; 2682 2683 Symbol *symbol = NULL; 2684 2685 if (hdr->Is32Bit()) { 2686 switch (reloc_type(rel)) { 2687 case R_386_32: 2688 case R_386_PC32: 2689 default: 2690 // FIXME: This asserts with this input: 2691 // 2692 // foo.cpp 2693 // int main(int argc, char **argv) { return 0; } 2694 // 2695 // clang++.exe --target=i686-unknown-linux-gnu -g -c foo.cpp -o foo.o 2696 // 2697 // and running this on the foo.o module. 2698 assert(false && "unexpected relocation type"); 2699 } 2700 } else { 2701 switch (reloc_type(rel)) { 2702 case R_AARCH64_ABS64: 2703 case R_X86_64_64: { 2704 symbol = symtab->FindSymbolByID(reloc_symbol(rel)); 2705 if (symbol) { 2706 addr_t value = symbol->GetAddressRef().GetFileAddress(); 2707 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer(); 2708 uint64_t *dst = reinterpret_cast<uint64_t *>( 2709 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() + 2710 ELFRelocation::RelocOffset64(rel)); 2711 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel); 2712 memcpy(dst, &val_offset, sizeof(uint64_t)); 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 && 2727 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN))) { 2728 Log *log = 2729 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES); 2730 log->Printf("Failed to apply debug info relocations"); 2731 break; 2732 } 2733 uint32_t truncated_addr = (value & 0xFFFFFFFF); 2734 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer(); 2735 uint32_t *dst = reinterpret_cast<uint32_t *>( 2736 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() + 2737 ELFRelocation::RelocOffset32(rel)); 2738 memcpy(dst, &truncated_addr, sizeof(uint32_t)); 2739 } 2740 break; 2741 } 2742 case R_X86_64_PC32: 2743 default: 2744 assert(false && "unexpected relocation type"); 2745 } 2746 } 2747 } 2748 2749 return 0; 2750 } 2751 2752 unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr, 2753 user_id_t rel_id, 2754 lldb_private::Symtab *thetab) { 2755 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL); 2756 2757 // Parse in the section list if needed. 2758 SectionList *section_list = GetSectionList(); 2759 if (!section_list) 2760 return 0; 2761 2762 user_id_t symtab_id = rel_hdr->sh_link; 2763 user_id_t debug_id = rel_hdr->sh_info; 2764 2765 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id); 2766 if (!symtab_hdr) 2767 return 0; 2768 2769 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id); 2770 if (!debug_hdr) 2771 return 0; 2772 2773 Section *rel = section_list->FindSectionByID(rel_id).get(); 2774 if (!rel) 2775 return 0; 2776 2777 Section *symtab = section_list->FindSectionByID(symtab_id).get(); 2778 if (!symtab) 2779 return 0; 2780 2781 Section *debug = section_list->FindSectionByID(debug_id).get(); 2782 if (!debug) 2783 return 0; 2784 2785 DataExtractor rel_data; 2786 DataExtractor symtab_data; 2787 DataExtractor debug_data; 2788 2789 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) && 2790 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) && 2791 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) { 2792 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr, 2793 rel_data, symtab_data, debug_data, debug); 2794 } 2795 2796 return 0; 2797 } 2798 2799 Symtab *ObjectFileELF::GetSymtab() { 2800 ModuleSP module_sp(GetModule()); 2801 if (!module_sp) 2802 return NULL; 2803 2804 // We always want to use the main object file so we (hopefully) only have one 2805 // cached copy of our symtab, dynamic sections, etc. 2806 ObjectFile *module_obj_file = module_sp->GetObjectFile(); 2807 if (module_obj_file && module_obj_file != this) 2808 return module_obj_file->GetSymtab(); 2809 2810 if (m_symtab_ap.get() == NULL) { 2811 SectionList *section_list = module_sp->GetSectionList(); 2812 if (!section_list) 2813 return NULL; 2814 2815 uint64_t symbol_id = 0; 2816 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 2817 2818 // Sharable objects and dynamic executables usually have 2 distinct symbol 2819 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a 2820 // smaller version of the symtab that only contains global symbols. The 2821 // information found in the dynsym is therefore also found in the symtab, 2822 // while the reverse is not necessarily true. 2823 Section *symtab = 2824 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get(); 2825 if (!symtab) { 2826 // The symtab section is non-allocable and can be stripped, so if it 2827 // doesn't exist then use the dynsym section which should always be 2828 // there. 2829 symtab = 2830 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true) 2831 .get(); 2832 } 2833 if (symtab) { 2834 m_symtab_ap.reset(new Symtab(symtab->GetObjectFile())); 2835 symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab); 2836 } 2837 2838 // DT_JMPREL 2839 // If present, this entry's d_ptr member holds the address of 2840 // relocation 2841 // entries associated solely with the procedure linkage table. 2842 // Separating 2843 // these relocation entries lets the dynamic linker ignore them during 2844 // process initialization, if lazy binding is enabled. If this entry is 2845 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must 2846 // also be present. 2847 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL); 2848 if (symbol) { 2849 // Synthesize trampoline symbols to help navigate the PLT. 2850 addr_t addr = symbol->d_ptr; 2851 Section *reloc_section = 2852 section_list->FindSectionContainingFileAddress(addr).get(); 2853 if (reloc_section) { 2854 user_id_t reloc_id = reloc_section->GetID(); 2855 const ELFSectionHeaderInfo *reloc_header = 2856 GetSectionHeaderByIndex(reloc_id); 2857 assert(reloc_header); 2858 2859 if (m_symtab_ap == nullptr) 2860 m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile())); 2861 2862 ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header, 2863 reloc_id); 2864 } 2865 } 2866 2867 DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo(); 2868 if (eh_frame) { 2869 if (m_symtab_ap == nullptr) 2870 m_symtab_ap.reset(new Symtab(this)); 2871 ParseUnwindSymbols(m_symtab_ap.get(), eh_frame); 2872 } 2873 2874 // If we still don't have any symtab then create an empty instance to avoid 2875 // do the section lookup next time. 2876 if (m_symtab_ap == nullptr) 2877 m_symtab_ap.reset(new Symtab(this)); 2878 2879 m_symtab_ap->CalculateSymbolSizes(); 2880 } 2881 2882 return m_symtab_ap.get(); 2883 } 2884 2885 void ObjectFileELF::RelocateSection(lldb_private::Section *section) 2886 { 2887 static const char *debug_prefix = ".debug"; 2888 2889 // Set relocated bit so we stop getting called, regardless of whether we 2890 // actually relocate. 2891 section->SetIsRelocated(true); 2892 2893 // We only relocate in ELF relocatable files 2894 if (CalculateType() != eTypeObjectFile) 2895 return; 2896 2897 const char *section_name = section->GetName().GetCString(); 2898 // Can't relocate that which can't be named 2899 if (section_name == nullptr) 2900 return; 2901 2902 // We don't relocate non-debug sections at the moment 2903 if (strncmp(section_name, debug_prefix, strlen(debug_prefix))) 2904 return; 2905 2906 // Relocation section names to look for 2907 std::string needle = std::string(".rel") + section_name; 2908 std::string needlea = std::string(".rela") + section_name; 2909 2910 for (SectionHeaderCollIter I = m_section_headers.begin(); 2911 I != m_section_headers.end(); ++I) { 2912 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) { 2913 const char *hay_name = I->section_name.GetCString(); 2914 if (hay_name == nullptr) 2915 continue; 2916 if (needle == hay_name || needlea == hay_name) { 2917 const ELFSectionHeader &reloc_header = *I; 2918 user_id_t reloc_id = SectionIndex(I); 2919 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab()); 2920 break; 2921 } 2922 } 2923 } 2924 } 2925 2926 void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table, 2927 DWARFCallFrameInfo *eh_frame) { 2928 SectionList *section_list = GetSectionList(); 2929 if (!section_list) 2930 return; 2931 2932 // First we save the new symbols into a separate list and add them to the 2933 // symbol table after we colleced all symbols we want to add. This is 2934 // neccessary because adding a new symbol invalidates the internal index of 2935 // the symtab what causing the next lookup to be slow because it have to 2936 // recalculate the index first. 2937 std::vector<Symbol> new_symbols; 2938 2939 eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols]( 2940 lldb::addr_t file_addr, uint32_t size, dw_offset_t) { 2941 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr); 2942 if (symbol) { 2943 if (!symbol->GetByteSizeIsValid()) { 2944 symbol->SetByteSize(size); 2945 symbol->SetSizeIsSynthesized(true); 2946 } 2947 } else { 2948 SectionSP section_sp = 2949 section_list->FindSectionContainingFileAddress(file_addr); 2950 if (section_sp) { 2951 addr_t offset = file_addr - section_sp->GetFileAddress(); 2952 const char *symbol_name = GetNextSyntheticSymbolName().GetCString(); 2953 uint64_t symbol_id = symbol_table->GetNumSymbols(); 2954 Symbol eh_symbol( 2955 symbol_id, // Symbol table index. 2956 symbol_name, // Symbol name. 2957 false, // Is the symbol name mangled? 2958 eSymbolTypeCode, // Type of this symbol. 2959 true, // Is this globally visible? 2960 false, // Is this symbol debug info? 2961 false, // Is this symbol a trampoline? 2962 true, // Is this symbol artificial? 2963 section_sp, // Section in which this symbol is defined or null. 2964 offset, // Offset in section or symbol value. 2965 0, // Size: Don't specify the size as an FDE can 2966 false, // Size is valid: cover multiple symbols. 2967 false, // Contains linker annotations? 2968 0); // Symbol flags. 2969 new_symbols.push_back(eh_symbol); 2970 } 2971 } 2972 return true; 2973 }); 2974 2975 for (const Symbol &s : new_symbols) 2976 symbol_table->AddSymbol(s); 2977 } 2978 2979 bool ObjectFileELF::IsStripped() { 2980 // TODO: determine this for ELF 2981 return false; 2982 } 2983 2984 //===----------------------------------------------------------------------===// 2985 // Dump 2986 // 2987 // Dump the specifics of the runtime file container (such as any headers 2988 // segments, sections, etc). 2989 //---------------------------------------------------------------------- 2990 void ObjectFileELF::Dump(Stream *s) { 2991 ModuleSP module_sp(GetModule()); 2992 if (!module_sp) { 2993 return; 2994 } 2995 2996 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 2997 s->Printf("%p: ", static_cast<void *>(this)); 2998 s->Indent(); 2999 s->PutCString("ObjectFileELF"); 3000 3001 ArchSpec header_arch = GetArchitecture(); 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 for (const auto &H : llvm::enumerate(m_program_headers)) { 3179 s->Format("[{0,2}] ", H.index()); 3180 ObjectFileELF::DumpELFProgramHeader(s, H.value()); 3181 s->EOL(); 3182 } 3183 } 3184 3185 //---------------------------------------------------------------------- 3186 // DumpELFSectionHeader 3187 // 3188 // Dump a single ELF section header to the specified output stream 3189 //---------------------------------------------------------------------- 3190 void ObjectFileELF::DumpELFSectionHeader(Stream *s, 3191 const ELFSectionHeaderInfo &sh) { 3192 s->Printf("%8.8x ", sh.sh_name); 3193 DumpELFSectionHeader_sh_type(s, sh.sh_type); 3194 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags); 3195 DumpELFSectionHeader_sh_flags(s, sh.sh_flags); 3196 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, 3197 sh.sh_offset, sh.sh_size); 3198 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info); 3199 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize); 3200 } 3201 3202 //---------------------------------------------------------------------- 3203 // DumpELFSectionHeader_sh_type 3204 // 3205 // Dump an token value for the ELF section header member sh_type which 3206 // describes the type of the section 3207 //---------------------------------------------------------------------- 3208 void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) { 3209 const int kStrWidth = 12; 3210 switch (sh_type) { 3211 CASE_AND_STREAM(s, SHT_NULL, kStrWidth); 3212 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth); 3213 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth); 3214 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth); 3215 CASE_AND_STREAM(s, SHT_RELA, kStrWidth); 3216 CASE_AND_STREAM(s, SHT_HASH, kStrWidth); 3217 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth); 3218 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth); 3219 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth); 3220 CASE_AND_STREAM(s, SHT_REL, kStrWidth); 3221 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth); 3222 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth); 3223 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth); 3224 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth); 3225 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth); 3226 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth); 3227 default: 3228 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, ""); 3229 break; 3230 } 3231 } 3232 3233 //---------------------------------------------------------------------- 3234 // DumpELFSectionHeader_sh_flags 3235 // 3236 // Dump an token value for the ELF section header member sh_flags 3237 //---------------------------------------------------------------------- 3238 void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, 3239 elf_xword sh_flags) { 3240 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ") 3241 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ') 3242 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ") 3243 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ') 3244 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " "); 3245 } 3246 3247 //---------------------------------------------------------------------- 3248 // DumpELFSectionHeaders 3249 // 3250 // Dump all of the ELF section header to the specified output stream 3251 //---------------------------------------------------------------------- 3252 void ObjectFileELF::DumpELFSectionHeaders(Stream *s) { 3253 if (!ParseSectionHeaders()) 3254 return; 3255 3256 s->PutCString("Section Headers\n"); 3257 s->PutCString("IDX name type flags " 3258 "addr offset size link info addralgn " 3259 "entsize Name\n"); 3260 s->PutCString("==== -------- ------------ -------------------------------- " 3261 "-------- -------- -------- -------- -------- -------- " 3262 "-------- ====================\n"); 3263 3264 uint32_t idx = 0; 3265 for (SectionHeaderCollConstIter I = m_section_headers.begin(); 3266 I != m_section_headers.end(); ++I, ++idx) { 3267 s->Printf("[%2u] ", idx); 3268 ObjectFileELF::DumpELFSectionHeader(s, *I); 3269 const char *section_name = I->section_name.AsCString(""); 3270 if (section_name) 3271 *s << ' ' << section_name << "\n"; 3272 } 3273 } 3274 3275 void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) { 3276 size_t num_modules = ParseDependentModules(); 3277 3278 if (num_modules > 0) { 3279 s->PutCString("Dependent Modules:\n"); 3280 for (unsigned i = 0; i < num_modules; ++i) { 3281 const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i); 3282 s->Printf(" %s\n", spec.GetFilename().GetCString()); 3283 } 3284 } 3285 } 3286 3287 ArchSpec ObjectFileELF::GetArchitecture() { 3288 if (!ParseHeader()) 3289 return ArchSpec(); 3290 3291 if (m_section_headers.empty()) { 3292 // Allow elf notes to be parsed which may affect the detected architecture. 3293 ParseSectionHeaders(); 3294 } 3295 3296 if (CalculateType() == eTypeCoreFile && 3297 m_arch_spec.TripleOSIsUnspecifiedUnknown()) { 3298 // Core files don't have section headers yet they have PT_NOTE program 3299 // headers that might shed more light on the architecture 3300 for (const elf::ELFProgramHeader &H : ProgramHeaders()) { 3301 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0) 3302 continue; 3303 DataExtractor data; 3304 if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) { 3305 UUID uuid; 3306 RefineModuleDetailsFromNote(data, m_arch_spec, uuid); 3307 } 3308 } 3309 } 3310 return m_arch_spec; 3311 } 3312 3313 ObjectFile::Type ObjectFileELF::CalculateType() { 3314 switch (m_header.e_type) { 3315 case llvm::ELF::ET_NONE: 3316 // 0 - No file type 3317 return eTypeUnknown; 3318 3319 case llvm::ELF::ET_REL: 3320 // 1 - Relocatable file 3321 return eTypeObjectFile; 3322 3323 case llvm::ELF::ET_EXEC: 3324 // 2 - Executable file 3325 return eTypeExecutable; 3326 3327 case llvm::ELF::ET_DYN: 3328 // 3 - Shared object file 3329 return eTypeSharedLibrary; 3330 3331 case ET_CORE: 3332 // 4 - Core file 3333 return eTypeCoreFile; 3334 3335 default: 3336 break; 3337 } 3338 return eTypeUnknown; 3339 } 3340 3341 ObjectFile::Strata ObjectFileELF::CalculateStrata() { 3342 switch (m_header.e_type) { 3343 case llvm::ELF::ET_NONE: 3344 // 0 - No file type 3345 return eStrataUnknown; 3346 3347 case llvm::ELF::ET_REL: 3348 // 1 - Relocatable file 3349 return eStrataUnknown; 3350 3351 case llvm::ELF::ET_EXEC: 3352 // 2 - Executable file 3353 // TODO: is there any way to detect that an executable is a kernel 3354 // related executable by inspecting the program headers, section headers, 3355 // symbols, or any other flag bits??? 3356 return eStrataUser; 3357 3358 case llvm::ELF::ET_DYN: 3359 // 3 - Shared object file 3360 // TODO: is there any way to detect that an shared library is a kernel 3361 // related executable by inspecting the program headers, section headers, 3362 // symbols, or any other flag bits??? 3363 return eStrataUnknown; 3364 3365 case ET_CORE: 3366 // 4 - Core file 3367 // TODO: is there any way to detect that an core file is a kernel 3368 // related executable by inspecting the program headers, section headers, 3369 // symbols, or any other flag bits??? 3370 return eStrataUnknown; 3371 3372 default: 3373 break; 3374 } 3375 return eStrataUnknown; 3376 } 3377 3378 size_t ObjectFileELF::ReadSectionData(Section *section, 3379 lldb::offset_t section_offset, void *dst, 3380 size_t dst_len) { 3381 // If some other objectfile owns this data, pass this to them. 3382 if (section->GetObjectFile() != this) 3383 return section->GetObjectFile()->ReadSectionData(section, section_offset, 3384 dst, dst_len); 3385 3386 if (!section->Test(SHF_COMPRESSED)) 3387 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len); 3388 3389 // For compressed sections we need to read to full data to be able to 3390 // decompress. 3391 DataExtractor data; 3392 ReadSectionData(section, data); 3393 return data.CopyData(section_offset, dst_len, dst); 3394 } 3395 3396 size_t ObjectFileELF::ReadSectionData(Section *section, 3397 DataExtractor §ion_data) { 3398 // If some other objectfile owns this data, pass this to them. 3399 if (section->GetObjectFile() != this) 3400 return section->GetObjectFile()->ReadSectionData(section, section_data); 3401 3402 size_t result = ObjectFile::ReadSectionData(section, section_data); 3403 if (result == 0 || !section->Test(SHF_COMPRESSED)) 3404 return result; 3405 3406 auto Decompressor = llvm::object::Decompressor::create( 3407 section->GetName().GetStringRef(), 3408 {reinterpret_cast<const char *>(section_data.GetDataStart()), 3409 size_t(section_data.GetByteSize())}, 3410 GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8); 3411 if (!Decompressor) { 3412 GetModule()->ReportWarning( 3413 "Unable to initialize decompressor for section '%s': %s", 3414 section->GetName().GetCString(), 3415 llvm::toString(Decompressor.takeError()).c_str()); 3416 section_data.Clear(); 3417 return 0; 3418 } 3419 3420 auto buffer_sp = 3421 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0); 3422 if (auto error = Decompressor->decompress( 3423 {reinterpret_cast<char *>(buffer_sp->GetBytes()), 3424 size_t(buffer_sp->GetByteSize())})) { 3425 GetModule()->ReportWarning( 3426 "Decompression of section '%s' failed: %s", 3427 section->GetName().GetCString(), 3428 llvm::toString(std::move(error)).c_str()); 3429 section_data.Clear(); 3430 return 0; 3431 } 3432 3433 section_data.SetData(buffer_sp); 3434 return buffer_sp->GetByteSize(); 3435 } 3436 3437 llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() { 3438 ParseProgramHeaders(); 3439 return m_program_headers; 3440 } 3441 3442 DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) { 3443 return DataExtractor(m_data, H.p_offset, H.p_filesz); 3444 } 3445 3446 bool ObjectFileELF::AnySegmentHasPhysicalAddress() { 3447 for (const ELFProgramHeader &H : ProgramHeaders()) { 3448 if (H.p_paddr != 0) 3449 return true; 3450 } 3451 return false; 3452 } 3453 3454 std::vector<ObjectFile::LoadableData> 3455 ObjectFileELF::GetLoadableData(Target &target) { 3456 // Create a list of loadable data from loadable segments, using physical 3457 // addresses if they aren't all null 3458 std::vector<LoadableData> loadables; 3459 bool should_use_paddr = AnySegmentHasPhysicalAddress(); 3460 for (const ELFProgramHeader &H : ProgramHeaders()) { 3461 LoadableData loadable; 3462 if (H.p_type != llvm::ELF::PT_LOAD) 3463 continue; 3464 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr; 3465 if (loadable.Dest == LLDB_INVALID_ADDRESS) 3466 continue; 3467 if (H.p_filesz == 0) 3468 continue; 3469 auto segment_data = GetSegmentData(H); 3470 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(), 3471 segment_data.GetByteSize()); 3472 loadables.push_back(loadable); 3473 } 3474 return loadables; 3475 } 3476