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