1 //===- SyntheticSections.cpp ----------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains linker-synthesized sections. Currently, 11 // synthetic sections are created either output sections or input sections, 12 // but we are rewriting code so that all synthetic sections are created as 13 // input sections. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "SyntheticSections.h" 18 #include "Bits.h" 19 #include "Config.h" 20 #include "InputFiles.h" 21 #include "LinkerScript.h" 22 #include "OutputSections.h" 23 #include "Strings.h" 24 #include "SymbolTable.h" 25 #include "Symbols.h" 26 #include "Target.h" 27 #include "Writer.h" 28 #include "lld/Common/ErrorHandler.h" 29 #include "lld/Common/Memory.h" 30 #include "lld/Common/Threads.h" 31 #include "lld/Common/Version.h" 32 #include "llvm/BinaryFormat/Dwarf.h" 33 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h" 34 #include "llvm/Object/Decompressor.h" 35 #include "llvm/Object/ELFObjectFile.h" 36 #include "llvm/Support/Endian.h" 37 #include "llvm/Support/LEB128.h" 38 #include "llvm/Support/MD5.h" 39 #include "llvm/Support/RandomNumberGenerator.h" 40 #include "llvm/Support/SHA1.h" 41 #include "llvm/Support/xxhash.h" 42 #include <cstdlib> 43 #include <thread> 44 45 using namespace llvm; 46 using namespace llvm::dwarf; 47 using namespace llvm::ELF; 48 using namespace llvm::object; 49 using namespace llvm::support; 50 using namespace llvm::support::endian; 51 52 using namespace lld; 53 using namespace lld::elf; 54 55 constexpr size_t MergeNoTailSection::NumShards; 56 57 static void write32(void *Buf, uint32_t Val) { 58 endian::write32(Buf, Val, Config->Endianness); 59 } 60 61 uint64_t SyntheticSection::getVA() const { 62 if (OutputSection *Sec = getParent()) 63 return Sec->Addr + OutSecOff; 64 return 0; 65 } 66 67 // Returns an LLD version string. 68 static ArrayRef<uint8_t> getVersion() { 69 // Check LLD_VERSION first for ease of testing. 70 // You can get consitent output by using the environment variable. 71 // This is only for testing. 72 StringRef S = getenv("LLD_VERSION"); 73 if (S.empty()) 74 S = Saver.save(Twine("Linker: ") + getLLDVersion()); 75 76 // +1 to include the terminating '\0'. 77 return {(const uint8_t *)S.data(), S.size() + 1}; 78 } 79 80 // Creates a .comment section containing LLD version info. 81 // With this feature, you can identify LLD-generated binaries easily 82 // by "readelf --string-dump .comment <file>". 83 // The returned object is a mergeable string section. 84 MergeInputSection *elf::createCommentSection() { 85 return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1, 86 getVersion(), ".comment"); 87 } 88 89 // .MIPS.abiflags section. 90 template <class ELFT> 91 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags) 92 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"), 93 Flags(Flags) { 94 this->Entsize = sizeof(Elf_Mips_ABIFlags); 95 } 96 97 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) { 98 memcpy(Buf, &Flags, sizeof(Flags)); 99 } 100 101 template <class ELFT> 102 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() { 103 Elf_Mips_ABIFlags Flags = {}; 104 bool Create = false; 105 106 for (InputSectionBase *Sec : InputSections) { 107 if (Sec->Type != SHT_MIPS_ABIFLAGS) 108 continue; 109 Sec->Live = false; 110 Create = true; 111 112 std::string Filename = toString(Sec->File); 113 const size_t Size = Sec->Data.size(); 114 // Older version of BFD (such as the default FreeBSD linker) concatenate 115 // .MIPS.abiflags instead of merging. To allow for this case (or potential 116 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags 117 if (Size < sizeof(Elf_Mips_ABIFlags)) { 118 error(Filename + ": invalid size of .MIPS.abiflags section: got " + 119 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags))); 120 return nullptr; 121 } 122 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data()); 123 if (S->version != 0) { 124 error(Filename + ": unexpected .MIPS.abiflags version " + 125 Twine(S->version)); 126 return nullptr; 127 } 128 129 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just 130 // select the highest number of ISA/Rev/Ext. 131 Flags.isa_level = std::max(Flags.isa_level, S->isa_level); 132 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev); 133 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext); 134 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size); 135 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size); 136 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size); 137 Flags.ases |= S->ases; 138 Flags.flags1 |= S->flags1; 139 Flags.flags2 |= S->flags2; 140 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename); 141 }; 142 143 if (Create) 144 return make<MipsAbiFlagsSection<ELFT>>(Flags); 145 return nullptr; 146 } 147 148 // .MIPS.options section. 149 template <class ELFT> 150 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo) 151 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"), 152 Reginfo(Reginfo) { 153 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo); 154 } 155 156 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) { 157 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf); 158 Options->kind = ODK_REGINFO; 159 Options->size = getSize(); 160 161 if (!Config->Relocatable) 162 Reginfo.ri_gp_value = InX::MipsGot->getGp(); 163 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo)); 164 } 165 166 template <class ELFT> 167 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() { 168 // N64 ABI only. 169 if (!ELFT::Is64Bits) 170 return nullptr; 171 172 std::vector<InputSectionBase *> Sections; 173 for (InputSectionBase *Sec : InputSections) 174 if (Sec->Type == SHT_MIPS_OPTIONS) 175 Sections.push_back(Sec); 176 177 if (Sections.empty()) 178 return nullptr; 179 180 Elf_Mips_RegInfo Reginfo = {}; 181 for (InputSectionBase *Sec : Sections) { 182 Sec->Live = false; 183 184 std::string Filename = toString(Sec->File); 185 ArrayRef<uint8_t> D = Sec->Data; 186 187 while (!D.empty()) { 188 if (D.size() < sizeof(Elf_Mips_Options)) { 189 error(Filename + ": invalid size of .MIPS.options section"); 190 break; 191 } 192 193 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data()); 194 if (Opt->kind == ODK_REGINFO) { 195 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value) 196 error(Filename + ": unsupported non-zero ri_gp_value"); 197 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask; 198 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value; 199 break; 200 } 201 202 if (!Opt->size) 203 fatal(Filename + ": zero option descriptor size"); 204 D = D.slice(Opt->size); 205 } 206 }; 207 208 return make<MipsOptionsSection<ELFT>>(Reginfo); 209 } 210 211 // MIPS .reginfo section. 212 template <class ELFT> 213 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo) 214 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"), 215 Reginfo(Reginfo) { 216 this->Entsize = sizeof(Elf_Mips_RegInfo); 217 } 218 219 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) { 220 if (!Config->Relocatable) 221 Reginfo.ri_gp_value = InX::MipsGot->getGp(); 222 memcpy(Buf, &Reginfo, sizeof(Reginfo)); 223 } 224 225 template <class ELFT> 226 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() { 227 // Section should be alive for O32 and N32 ABIs only. 228 if (ELFT::Is64Bits) 229 return nullptr; 230 231 std::vector<InputSectionBase *> Sections; 232 for (InputSectionBase *Sec : InputSections) 233 if (Sec->Type == SHT_MIPS_REGINFO) 234 Sections.push_back(Sec); 235 236 if (Sections.empty()) 237 return nullptr; 238 239 Elf_Mips_RegInfo Reginfo = {}; 240 for (InputSectionBase *Sec : Sections) { 241 Sec->Live = false; 242 243 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) { 244 error(toString(Sec->File) + ": invalid size of .reginfo section"); 245 return nullptr; 246 } 247 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data()); 248 if (Config->Relocatable && R->ri_gp_value) 249 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value"); 250 251 Reginfo.ri_gprmask |= R->ri_gprmask; 252 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value; 253 }; 254 255 return make<MipsReginfoSection<ELFT>>(Reginfo); 256 } 257 258 InputSection *elf::createInterpSection() { 259 // StringSaver guarantees that the returned string ends with '\0'. 260 StringRef S = Saver.save(Config->DynamicLinker); 261 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1}; 262 263 auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents, 264 ".interp"); 265 Sec->Live = true; 266 return Sec; 267 } 268 269 Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, 270 uint64_t Size, InputSectionBase &Section) { 271 auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type, 272 Value, Size, &Section); 273 if (InX::SymTab) 274 InX::SymTab->addSymbol(S); 275 return S; 276 } 277 278 static size_t getHashSize() { 279 switch (Config->BuildId) { 280 case BuildIdKind::Fast: 281 return 8; 282 case BuildIdKind::Md5: 283 case BuildIdKind::Uuid: 284 return 16; 285 case BuildIdKind::Sha1: 286 return 20; 287 case BuildIdKind::Hexstring: 288 return Config->BuildIdVector.size(); 289 default: 290 llvm_unreachable("unknown BuildIdKind"); 291 } 292 } 293 294 BuildIdSection::BuildIdSection() 295 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"), 296 HashSize(getHashSize()) {} 297 298 void BuildIdSection::writeTo(uint8_t *Buf) { 299 write32(Buf, 4); // Name size 300 write32(Buf + 4, HashSize); // Content size 301 write32(Buf + 8, NT_GNU_BUILD_ID); // Type 302 memcpy(Buf + 12, "GNU", 4); // Name string 303 HashBuf = Buf + 16; 304 } 305 306 // Split one uint8 array into small pieces of uint8 arrays. 307 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr, 308 size_t ChunkSize) { 309 std::vector<ArrayRef<uint8_t>> Ret; 310 while (Arr.size() > ChunkSize) { 311 Ret.push_back(Arr.take_front(ChunkSize)); 312 Arr = Arr.drop_front(ChunkSize); 313 } 314 if (!Arr.empty()) 315 Ret.push_back(Arr); 316 return Ret; 317 } 318 319 // Computes a hash value of Data using a given hash function. 320 // In order to utilize multiple cores, we first split data into 1MB 321 // chunks, compute a hash for each chunk, and then compute a hash value 322 // of the hash values. 323 void BuildIdSection::computeHash( 324 llvm::ArrayRef<uint8_t> Data, 325 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) { 326 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024); 327 std::vector<uint8_t> Hashes(Chunks.size() * HashSize); 328 329 // Compute hash values. 330 parallelForEachN(0, Chunks.size(), [&](size_t I) { 331 HashFn(Hashes.data() + I * HashSize, Chunks[I]); 332 }); 333 334 // Write to the final output buffer. 335 HashFn(HashBuf, Hashes); 336 } 337 338 BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment) 339 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) { 340 this->Bss = true; 341 if (OutputSection *Sec = getParent()) 342 Sec->Alignment = std::max(Sec->Alignment, Alignment); 343 this->Size = Size; 344 } 345 346 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) { 347 switch (Config->BuildId) { 348 case BuildIdKind::Fast: 349 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 350 write64le(Dest, xxHash64(toStringRef(Arr))); 351 }); 352 break; 353 case BuildIdKind::Md5: 354 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 355 memcpy(Dest, MD5::hash(Arr).data(), 16); 356 }); 357 break; 358 case BuildIdKind::Sha1: 359 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 360 memcpy(Dest, SHA1::hash(Arr).data(), 20); 361 }); 362 break; 363 case BuildIdKind::Uuid: 364 if (auto EC = getRandomBytes(HashBuf, HashSize)) 365 error("entropy source failure: " + EC.message()); 366 break; 367 case BuildIdKind::Hexstring: 368 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size()); 369 break; 370 default: 371 llvm_unreachable("unknown BuildIdKind"); 372 } 373 } 374 375 EhFrameSection::EhFrameSection() 376 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {} 377 378 // Search for an existing CIE record or create a new one. 379 // CIE records from input object files are uniquified by their contents 380 // and where their relocations point to. 381 template <class ELFT, class RelTy> 382 CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) { 383 auto *Sec = cast<EhInputSection>(Cie.Sec); 384 if (read32(Cie.data().data() + 4, Config->Endianness) != 0) 385 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame"); 386 387 Symbol *Personality = nullptr; 388 unsigned FirstRelI = Cie.FirstRelocation; 389 if (FirstRelI != (unsigned)-1) 390 Personality = 391 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]); 392 393 // Search for an existing CIE by CIE contents/relocation target pair. 394 CieRecord *&Rec = CieMap[{Cie.data(), Personality}]; 395 396 // If not found, create a new one. 397 if (!Rec) { 398 Rec = make<CieRecord>(); 399 Rec->Cie = &Cie; 400 CieRecords.push_back(Rec); 401 } 402 return Rec; 403 } 404 405 // There is one FDE per function. Returns true if a given FDE 406 // points to a live function. 407 template <class ELFT, class RelTy> 408 bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) { 409 auto *Sec = cast<EhInputSection>(Fde.Sec); 410 unsigned FirstRelI = Fde.FirstRelocation; 411 412 // An FDE should point to some function because FDEs are to describe 413 // functions. That's however not always the case due to an issue of 414 // ld.gold with -r. ld.gold may discard only functions and leave their 415 // corresponding FDEs, which results in creating bad .eh_frame sections. 416 // To deal with that, we ignore such FDEs. 417 if (FirstRelI == (unsigned)-1) 418 return false; 419 420 const RelTy &Rel = Rels[FirstRelI]; 421 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel); 422 423 // FDEs for garbage-collected or merged-by-ICF sections are dead. 424 if (auto *D = dyn_cast<Defined>(&B)) 425 if (SectionBase *Sec = D->Section) 426 return Sec->Live; 427 return false; 428 } 429 430 // .eh_frame is a sequence of CIE or FDE records. In general, there 431 // is one CIE record per input object file which is followed by 432 // a list of FDEs. This function searches an existing CIE or create a new 433 // one and associates FDEs to the CIE. 434 template <class ELFT, class RelTy> 435 void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) { 436 DenseMap<size_t, CieRecord *> OffsetToCie; 437 for (EhSectionPiece &Piece : Sec->Pieces) { 438 // The empty record is the end marker. 439 if (Piece.Size == 4) 440 return; 441 442 size_t Offset = Piece.InputOff; 443 uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness); 444 if (ID == 0) { 445 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels); 446 continue; 447 } 448 449 uint32_t CieOffset = Offset + 4 - ID; 450 CieRecord *Rec = OffsetToCie[CieOffset]; 451 if (!Rec) 452 fatal(toString(Sec) + ": invalid CIE reference"); 453 454 if (!isFdeLive<ELFT>(Piece, Rels)) 455 continue; 456 Rec->Fdes.push_back(&Piece); 457 NumFdes++; 458 } 459 } 460 461 template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) { 462 auto *Sec = cast<EhInputSection>(C); 463 Sec->Parent = this; 464 465 Alignment = std::max(Alignment, Sec->Alignment); 466 Sections.push_back(Sec); 467 468 for (auto *DS : Sec->DependentSections) 469 DependentSections.push_back(DS); 470 471 // .eh_frame is a sequence of CIE or FDE records. This function 472 // splits it into pieces so that we can call 473 // SplitInputSection::getSectionPiece on the section. 474 Sec->split<ELFT>(); 475 if (Sec->Pieces.empty()) 476 return; 477 478 if (Sec->AreRelocsRela) 479 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>()); 480 else 481 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>()); 482 } 483 484 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) { 485 memcpy(Buf, D.data(), D.size()); 486 487 size_t Aligned = alignTo(D.size(), Config->Wordsize); 488 489 // Zero-clear trailing padding if it exists. 490 memset(Buf + D.size(), 0, Aligned - D.size()); 491 492 // Fix the size field. -4 since size does not include the size field itself. 493 write32(Buf, Aligned - 4); 494 } 495 496 void EhFrameSection::finalizeContents() { 497 if (this->Size) 498 return; // Already finalized. 499 500 size_t Off = 0; 501 for (CieRecord *Rec : CieRecords) { 502 Rec->Cie->OutputOff = Off; 503 Off += alignTo(Rec->Cie->Size, Config->Wordsize); 504 505 for (EhSectionPiece *Fde : Rec->Fdes) { 506 Fde->OutputOff = Off; 507 Off += alignTo(Fde->Size, Config->Wordsize); 508 } 509 } 510 511 // The LSB standard does not allow a .eh_frame section with zero 512 // Call Frame Information records. Therefore add a CIE record length 513 // 0 as a terminator if this .eh_frame section is empty. 514 if (Off == 0) 515 Off = 4; 516 517 this->Size = Off; 518 } 519 520 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table 521 // to get an FDE from an address to which FDE is applied. This function 522 // returns a list of such pairs. 523 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const { 524 uint8_t *Buf = getParent()->Loc + OutSecOff; 525 std::vector<FdeData> Ret; 526 527 for (CieRecord *Rec : CieRecords) { 528 uint8_t Enc = getFdeEncoding(Rec->Cie); 529 for (EhSectionPiece *Fde : Rec->Fdes) { 530 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc); 531 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff; 532 Ret.push_back({Pc, FdeVA}); 533 } 534 } 535 return Ret; 536 } 537 538 static uint64_t readFdeAddr(uint8_t *Buf, int Size) { 539 switch (Size) { 540 case DW_EH_PE_udata2: 541 return read16(Buf, Config->Endianness); 542 case DW_EH_PE_udata4: 543 return read32(Buf, Config->Endianness); 544 case DW_EH_PE_udata8: 545 return read64(Buf, Config->Endianness); 546 case DW_EH_PE_absptr: 547 return readUint(Buf); 548 } 549 fatal("unknown FDE size encoding"); 550 } 551 552 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to. 553 // We need it to create .eh_frame_hdr section. 554 uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff, 555 uint8_t Enc) const { 556 // The starting address to which this FDE applies is 557 // stored at FDE + 8 byte. 558 size_t Off = FdeOff + 8; 559 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7); 560 if ((Enc & 0x70) == DW_EH_PE_absptr) 561 return Addr; 562 if ((Enc & 0x70) == DW_EH_PE_pcrel) 563 return Addr + getParent()->Addr + Off; 564 fatal("unknown FDE size relative encoding"); 565 } 566 567 void EhFrameSection::writeTo(uint8_t *Buf) { 568 // Write CIE and FDE records. 569 for (CieRecord *Rec : CieRecords) { 570 size_t CieOffset = Rec->Cie->OutputOff; 571 writeCieFde(Buf + CieOffset, Rec->Cie->data()); 572 573 for (EhSectionPiece *Fde : Rec->Fdes) { 574 size_t Off = Fde->OutputOff; 575 writeCieFde(Buf + Off, Fde->data()); 576 577 // FDE's second word should have the offset to an associated CIE. 578 // Write it. 579 write32(Buf + Off + 4, Off + 4 - CieOffset); 580 } 581 } 582 583 // Apply relocations. .eh_frame section contents are not contiguous 584 // in the output buffer, but relocateAlloc() still works because 585 // getOffset() takes care of discontiguous section pieces. 586 for (EhInputSection *S : Sections) 587 S->relocateAlloc(Buf, nullptr); 588 } 589 590 GotSection::GotSection() 591 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 592 Target->GotEntrySize, ".got") {} 593 594 void GotSection::addEntry(Symbol &Sym) { 595 Sym.GotIndex = NumEntries; 596 ++NumEntries; 597 } 598 599 bool GotSection::addDynTlsEntry(Symbol &Sym) { 600 if (Sym.GlobalDynIndex != -1U) 601 return false; 602 Sym.GlobalDynIndex = NumEntries; 603 // Global Dynamic TLS entries take two GOT slots. 604 NumEntries += 2; 605 return true; 606 } 607 608 // Reserves TLS entries for a TLS module ID and a TLS block offset. 609 // In total it takes two GOT slots. 610 bool GotSection::addTlsIndex() { 611 if (TlsIndexOff != uint32_t(-1)) 612 return false; 613 TlsIndexOff = NumEntries * Config->Wordsize; 614 NumEntries += 2; 615 return true; 616 } 617 618 uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const { 619 return this->getVA() + B.GlobalDynIndex * Config->Wordsize; 620 } 621 622 uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const { 623 return B.GlobalDynIndex * Config->Wordsize; 624 } 625 626 void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; } 627 628 bool GotSection::empty() const { 629 // We need to emit a GOT even if it's empty if there's a relocation that is 630 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT 631 // (i.e. _GLOBAL_OFFSET_TABLE_). 632 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable; 633 } 634 635 void GotSection::writeTo(uint8_t *Buf) { 636 // Buf points to the start of this section's buffer, 637 // whereas InputSectionBase::relocateAlloc() expects its argument 638 // to point to the start of the output section. 639 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size); 640 } 641 642 MipsGotSection::MipsGotSection() 643 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16, 644 ".got") {} 645 646 void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) { 647 // For "true" local symbols which can be referenced from the same module 648 // only compiler creates two instructions for address loading: 649 // 650 // lw $8, 0($gp) # R_MIPS_GOT16 651 // addi $8, $8, 0 # R_MIPS_LO16 652 // 653 // The first instruction loads high 16 bits of the symbol address while 654 // the second adds an offset. That allows to reduce number of required 655 // GOT entries because only one global offset table entry is necessary 656 // for every 64 KBytes of local data. So for local symbols we need to 657 // allocate number of GOT entries to hold all required "page" addresses. 658 // 659 // All global symbols (hidden and regular) considered by compiler uniformly. 660 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation 661 // to load address of the symbol. So for each such symbol we need to 662 // allocate dedicated GOT entry to store its address. 663 // 664 // If a symbol is preemptible we need help of dynamic linker to get its 665 // final address. The corresponding GOT entries are allocated in the 666 // "global" part of GOT. Entries for non preemptible global symbol allocated 667 // in the "local" part of GOT. 668 // 669 // See "Global Offset Table" in Chapter 5: 670 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 671 if (Expr == R_MIPS_GOT_LOCAL_PAGE) { 672 // At this point we do not know final symbol value so to reduce number 673 // of allocated GOT entries do the following trick. Save all output 674 // sections referenced by GOT relocations. Then later in the `finalize` 675 // method calculate number of "pages" required to cover all saved output 676 // section and allocate appropriate number of GOT entries. 677 PageIndexMap.insert({Sym.getOutputSection(), 0}); 678 return; 679 } 680 if (Sym.isTls()) { 681 // GOT entries created for MIPS TLS relocations behave like 682 // almost GOT entries from other ABIs. They go to the end 683 // of the global offset table. 684 Sym.GotIndex = TlsEntries.size(); 685 TlsEntries.push_back(&Sym); 686 return; 687 } 688 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) { 689 if (S.isInGot() && !A) 690 return; 691 size_t NewIndex = Items.size(); 692 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second) 693 return; 694 Items.emplace_back(&S, A); 695 if (!A) 696 S.GotIndex = NewIndex; 697 }; 698 if (Sym.IsPreemptible) { 699 // Ignore addends for preemptible symbols. They got single GOT entry anyway. 700 AddEntry(Sym, 0, GlobalEntries); 701 Sym.IsInGlobalMipsGot = true; 702 } else if (Expr == R_MIPS_GOT_OFF32) { 703 AddEntry(Sym, Addend, LocalEntries32); 704 Sym.Is32BitMipsGot = true; 705 } else { 706 // Hold local GOT entries accessed via a 16-bit index separately. 707 // That allows to write them in the beginning of the GOT and keep 708 // their indexes as less as possible to escape relocation's overflow. 709 AddEntry(Sym, Addend, LocalEntries); 710 } 711 } 712 713 bool MipsGotSection::addDynTlsEntry(Symbol &Sym) { 714 if (Sym.GlobalDynIndex != -1U) 715 return false; 716 Sym.GlobalDynIndex = TlsEntries.size(); 717 // Global Dynamic TLS entries take two GOT slots. 718 TlsEntries.push_back(nullptr); 719 TlsEntries.push_back(&Sym); 720 return true; 721 } 722 723 // Reserves TLS entries for a TLS module ID and a TLS block offset. 724 // In total it takes two GOT slots. 725 bool MipsGotSection::addTlsIndex() { 726 if (TlsIndexOff != uint32_t(-1)) 727 return false; 728 TlsIndexOff = TlsEntries.size() * Config->Wordsize; 729 TlsEntries.push_back(nullptr); 730 TlsEntries.push_back(nullptr); 731 return true; 732 } 733 734 static uint64_t getMipsPageAddr(uint64_t Addr) { 735 return (Addr + 0x8000) & ~0xffff; 736 } 737 738 static uint64_t getMipsPageCount(uint64_t Size) { 739 return (Size + 0xfffe) / 0xffff + 1; 740 } 741 742 uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B, 743 int64_t Addend) const { 744 const OutputSection *OutSec = B.getOutputSection(); 745 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr); 746 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend)); 747 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff; 748 assert(Index < PageEntriesNum); 749 return (HeaderEntriesNum + Index) * Config->Wordsize; 750 } 751 752 uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B, 753 int64_t Addend) const { 754 // Calculate offset of the GOT entries block: TLS, global, local. 755 uint64_t Index = HeaderEntriesNum + PageEntriesNum; 756 if (B.isTls()) 757 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size(); 758 else if (B.IsInGlobalMipsGot) 759 Index += LocalEntries.size() + LocalEntries32.size(); 760 else if (B.Is32BitMipsGot) 761 Index += LocalEntries.size(); 762 // Calculate offset of the GOT entry in the block. 763 if (B.isInGot()) 764 Index += B.GotIndex; 765 else { 766 auto It = EntryIndexMap.find({&B, Addend}); 767 assert(It != EntryIndexMap.end()); 768 Index += It->second; 769 } 770 return Index * Config->Wordsize; 771 } 772 773 uint64_t MipsGotSection::getTlsOffset() const { 774 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize; 775 } 776 777 uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const { 778 return B.GlobalDynIndex * Config->Wordsize; 779 } 780 781 const Symbol *MipsGotSection::getFirstGlobalEntry() const { 782 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first; 783 } 784 785 unsigned MipsGotSection::getLocalEntriesNum() const { 786 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() + 787 LocalEntries32.size(); 788 } 789 790 void MipsGotSection::finalizeContents() { updateAllocSize(); } 791 792 bool MipsGotSection::updateAllocSize() { 793 PageEntriesNum = 0; 794 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) { 795 // For each output section referenced by GOT page relocations calculate 796 // and save into PageIndexMap an upper bound of MIPS GOT entries required 797 // to store page addresses of local symbols. We assume the worst case - 798 // each 64kb page of the output section has at least one GOT relocation 799 // against it. And take in account the case when the section intersects 800 // page boundaries. 801 P.second = PageEntriesNum; 802 PageEntriesNum += getMipsPageCount(P.first->Size); 803 } 804 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) * 805 Config->Wordsize; 806 return false; 807 } 808 809 bool MipsGotSection::empty() const { 810 // We add the .got section to the result for dynamic MIPS target because 811 // its address and properties are mentioned in the .dynamic section. 812 return Config->Relocatable; 813 } 814 815 uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); } 816 817 void MipsGotSection::writeTo(uint8_t *Buf) { 818 // Set the MSB of the second GOT slot. This is not required by any 819 // MIPS ABI documentation, though. 820 // 821 // There is a comment in glibc saying that "The MSB of got[1] of a 822 // gnu object is set to identify gnu objects," and in GNU gold it 823 // says "the second entry will be used by some runtime loaders". 824 // But how this field is being used is unclear. 825 // 826 // We are not really willing to mimic other linkers behaviors 827 // without understanding why they do that, but because all files 828 // generated by GNU tools have this special GOT value, and because 829 // we've been doing this for years, it is probably a safe bet to 830 // keep doing this for now. We really need to revisit this to see 831 // if we had to do this. 832 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1)); 833 Buf += HeaderEntriesNum * Config->Wordsize; 834 // Write 'page address' entries to the local part of the GOT. 835 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) { 836 size_t PageCount = getMipsPageCount(L.first->Size); 837 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr); 838 for (size_t PI = 0; PI < PageCount; ++PI) { 839 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize; 840 writeUint(Entry, FirstPageAddr + PI * 0x10000); 841 } 842 } 843 Buf += PageEntriesNum * Config->Wordsize; 844 auto AddEntry = [&](const GotEntry &SA) { 845 uint8_t *Entry = Buf; 846 Buf += Config->Wordsize; 847 const Symbol *Sym = SA.first; 848 uint64_t VA = Sym->getVA(SA.second); 849 if (Sym->StOther & STO_MIPS_MICROMIPS) 850 VA |= 1; 851 writeUint(Entry, VA); 852 }; 853 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry); 854 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry); 855 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry); 856 // Initialize TLS-related GOT entries. If the entry has a corresponding 857 // dynamic relocations, leave it initialized by zero. Write down adjusted 858 // TLS symbol's values otherwise. To calculate the adjustments use offsets 859 // for thread-local storage. 860 // https://www.linux-mips.org/wiki/NPTL 861 if (TlsIndexOff != -1U && !Config->Pic) 862 writeUint(Buf + TlsIndexOff, 1); 863 for (const Symbol *B : TlsEntries) { 864 if (!B || B->IsPreemptible) 865 continue; 866 uint64_t VA = B->getVA(); 867 if (B->GotIndex != -1U) { 868 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize; 869 writeUint(Entry, VA - 0x7000); 870 } 871 if (B->GlobalDynIndex != -1U) { 872 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize; 873 writeUint(Entry, 1); 874 Entry += Config->Wordsize; 875 writeUint(Entry, VA - 0x8000); 876 } 877 } 878 } 879 880 GotPltSection::GotPltSection() 881 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 882 Target->GotPltEntrySize, ".got.plt") {} 883 884 void GotPltSection::addEntry(Symbol &Sym) { 885 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size(); 886 Entries.push_back(&Sym); 887 } 888 889 size_t GotPltSection::getSize() const { 890 return (Target->GotPltHeaderEntriesNum + Entries.size()) * 891 Target->GotPltEntrySize; 892 } 893 894 void GotPltSection::writeTo(uint8_t *Buf) { 895 Target->writeGotPltHeader(Buf); 896 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize; 897 for (const Symbol *B : Entries) { 898 Target->writeGotPlt(Buf, *B); 899 Buf += Config->Wordsize; 900 } 901 } 902 903 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is 904 // part of the .got.plt 905 IgotPltSection::IgotPltSection() 906 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 907 Target->GotPltEntrySize, 908 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {} 909 910 void IgotPltSection::addEntry(Symbol &Sym) { 911 Sym.IsInIgot = true; 912 Sym.GotPltIndex = Entries.size(); 913 Entries.push_back(&Sym); 914 } 915 916 size_t IgotPltSection::getSize() const { 917 return Entries.size() * Target->GotPltEntrySize; 918 } 919 920 void IgotPltSection::writeTo(uint8_t *Buf) { 921 for (const Symbol *B : Entries) { 922 Target->writeIgotPlt(Buf, *B); 923 Buf += Config->Wordsize; 924 } 925 } 926 927 StringTableSection::StringTableSection(StringRef Name, bool Dynamic) 928 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name), 929 Dynamic(Dynamic) { 930 // ELF string tables start with a NUL byte. 931 addString(""); 932 } 933 934 // Adds a string to the string table. If HashIt is true we hash and check for 935 // duplicates. It is optional because the name of global symbols are already 936 // uniqued and hashing them again has a big cost for a small value: uniquing 937 // them with some other string that happens to be the same. 938 unsigned StringTableSection::addString(StringRef S, bool HashIt) { 939 if (HashIt) { 940 auto R = StringMap.insert(std::make_pair(S, this->Size)); 941 if (!R.second) 942 return R.first->second; 943 } 944 unsigned Ret = this->Size; 945 this->Size = this->Size + S.size() + 1; 946 Strings.push_back(S); 947 return Ret; 948 } 949 950 void StringTableSection::writeTo(uint8_t *Buf) { 951 for (StringRef S : Strings) { 952 memcpy(Buf, S.data(), S.size()); 953 Buf[S.size()] = '\0'; 954 Buf += S.size() + 1; 955 } 956 } 957 958 // Returns the number of version definition entries. Because the first entry 959 // is for the version definition itself, it is the number of versioned symbols 960 // plus one. Note that we don't support multiple versions yet. 961 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; } 962 963 template <class ELFT> 964 DynamicSection<ELFT>::DynamicSection() 965 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize, 966 ".dynamic") { 967 this->Entsize = ELFT::Is64Bits ? 16 : 8; 968 969 // .dynamic section is not writable on MIPS and on Fuchsia OS 970 // which passes -z rodynamic. 971 // See "Special Section" in Chapter 4 in the following document: 972 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 973 if (Config->EMachine == EM_MIPS || Config->ZRodynamic) 974 this->Flags = SHF_ALLOC; 975 976 // Add strings to .dynstr early so that .dynstr's size will be 977 // fixed early. 978 for (StringRef S : Config->FilterList) 979 addInt(DT_FILTER, InX::DynStrTab->addString(S)); 980 for (StringRef S : Config->AuxiliaryList) 981 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S)); 982 983 if (!Config->Rpath.empty()) 984 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, 985 InX::DynStrTab->addString(Config->Rpath)); 986 987 for (InputFile *File : SharedFiles) { 988 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File); 989 if (F->IsNeeded) 990 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName)); 991 } 992 if (!Config->SoName.empty()) 993 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName)); 994 } 995 996 template <class ELFT> 997 void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) { 998 Entries.push_back({Tag, Fn}); 999 } 1000 1001 template <class ELFT> 1002 void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) { 1003 Entries.push_back({Tag, [=] { return Val; }}); 1004 } 1005 1006 template <class ELFT> 1007 void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) { 1008 Entries.push_back( 1009 {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }}); 1010 } 1011 1012 template <class ELFT> 1013 void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) { 1014 Entries.push_back({Tag, [=] { return Sec->Addr; }}); 1015 } 1016 1017 template <class ELFT> 1018 void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) { 1019 Entries.push_back({Tag, [=] { return Sec->Size; }}); 1020 } 1021 1022 template <class ELFT> 1023 void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) { 1024 Entries.push_back({Tag, [=] { return Sym->getVA(); }}); 1025 } 1026 1027 // Add remaining entries to complete .dynamic contents. 1028 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { 1029 if (this->Size) 1030 return; // Already finalized. 1031 1032 // Set DT_FLAGS and DT_FLAGS_1. 1033 uint32_t DtFlags = 0; 1034 uint32_t DtFlags1 = 0; 1035 if (Config->Bsymbolic) 1036 DtFlags |= DF_SYMBOLIC; 1037 if (Config->ZNodelete) 1038 DtFlags1 |= DF_1_NODELETE; 1039 if (Config->ZNodlopen) 1040 DtFlags1 |= DF_1_NOOPEN; 1041 if (Config->ZNow) { 1042 DtFlags |= DF_BIND_NOW; 1043 DtFlags1 |= DF_1_NOW; 1044 } 1045 if (Config->ZOrigin) { 1046 DtFlags |= DF_ORIGIN; 1047 DtFlags1 |= DF_1_ORIGIN; 1048 } 1049 1050 if (DtFlags) 1051 addInt(DT_FLAGS, DtFlags); 1052 if (DtFlags1) 1053 addInt(DT_FLAGS_1, DtFlags1); 1054 1055 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We 1056 // need it for each process, so we don't write it for DSOs. The loader writes 1057 // the pointer into this entry. 1058 // 1059 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some 1060 // systems (currently only Fuchsia OS) provide other means to give the 1061 // debugger this information. Such systems may choose make .dynamic read-only. 1062 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG. 1063 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic) 1064 addInt(DT_DEBUG, 0); 1065 1066 this->Link = InX::DynStrTab->getParent()->SectionIndex; 1067 if (!InX::RelaDyn->empty()) { 1068 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn); 1069 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent()); 1070 1071 bool IsRela = Config->IsRela; 1072 addInt(IsRela ? DT_RELAENT : DT_RELENT, 1073 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)); 1074 1075 // MIPS dynamic loader does not support RELCOUNT tag. 1076 // The problem is in the tight relation between dynamic 1077 // relocations and GOT. So do not emit this tag on MIPS. 1078 if (Config->EMachine != EM_MIPS) { 1079 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount(); 1080 if (Config->ZCombreloc && NumRelativeRels) 1081 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels); 1082 } 1083 } 1084 // .rel[a].plt section usually consists of two parts, containing plt and 1085 // iplt relocations. It is possible to have only iplt relocations in the 1086 // output. In that case RelaPlt is empty and have zero offset, the same offset 1087 // as RelaIplt have. And we still want to emit proper dynamic tags for that 1088 // case, so here we always use RelaPlt as marker for the begining of 1089 // .rel[a].plt section. 1090 if (InX::RelaPlt->getParent()->Live) { 1091 addInSec(DT_JMPREL, InX::RelaPlt); 1092 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent()); 1093 switch (Config->EMachine) { 1094 case EM_MIPS: 1095 addInSec(DT_MIPS_PLTGOT, InX::GotPlt); 1096 break; 1097 case EM_SPARCV9: 1098 addInSec(DT_PLTGOT, InX::Plt); 1099 break; 1100 default: 1101 addInSec(DT_PLTGOT, InX::GotPlt); 1102 break; 1103 } 1104 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL); 1105 } 1106 1107 addInSec(DT_SYMTAB, InX::DynSymTab); 1108 addInt(DT_SYMENT, sizeof(Elf_Sym)); 1109 addInSec(DT_STRTAB, InX::DynStrTab); 1110 addInt(DT_STRSZ, InX::DynStrTab->getSize()); 1111 if (!Config->ZText) 1112 addInt(DT_TEXTREL, 0); 1113 if (InX::GnuHashTab) 1114 addInSec(DT_GNU_HASH, InX::GnuHashTab); 1115 if (InX::HashTab) 1116 addInSec(DT_HASH, InX::HashTab); 1117 1118 if (Out::PreinitArray) { 1119 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray); 1120 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray); 1121 } 1122 if (Out::InitArray) { 1123 addOutSec(DT_INIT_ARRAY, Out::InitArray); 1124 addSize(DT_INIT_ARRAYSZ, Out::InitArray); 1125 } 1126 if (Out::FiniArray) { 1127 addOutSec(DT_FINI_ARRAY, Out::FiniArray); 1128 addSize(DT_FINI_ARRAYSZ, Out::FiniArray); 1129 } 1130 1131 if (Symbol *B = Symtab->find(Config->Init)) 1132 if (B->isDefined()) 1133 addSym(DT_INIT, B); 1134 if (Symbol *B = Symtab->find(Config->Fini)) 1135 if (B->isDefined()) 1136 addSym(DT_FINI, B); 1137 1138 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0; 1139 if (HasVerNeed || In<ELFT>::VerDef) 1140 addInSec(DT_VERSYM, In<ELFT>::VerSym); 1141 if (In<ELFT>::VerDef) { 1142 addInSec(DT_VERDEF, In<ELFT>::VerDef); 1143 addInt(DT_VERDEFNUM, getVerDefNum()); 1144 } 1145 if (HasVerNeed) { 1146 addInSec(DT_VERNEED, In<ELFT>::VerNeed); 1147 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()); 1148 } 1149 1150 if (Config->EMachine == EM_MIPS) { 1151 addInt(DT_MIPS_RLD_VERSION, 1); 1152 addInt(DT_MIPS_FLAGS, RHF_NOTPOT); 1153 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase()); 1154 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()); 1155 1156 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); }); 1157 1158 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry()) 1159 addInt(DT_MIPS_GOTSYM, B->DynsymIndex); 1160 else 1161 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()); 1162 addInSec(DT_PLTGOT, InX::MipsGot); 1163 if (InX::MipsRldMap) 1164 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap); 1165 } 1166 1167 addInt(DT_NULL, 0); 1168 1169 getParent()->Link = this->Link; 1170 this->Size = Entries.size() * this->Entsize; 1171 } 1172 1173 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) { 1174 auto *P = reinterpret_cast<Elf_Dyn *>(Buf); 1175 1176 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) { 1177 P->d_tag = KV.first; 1178 P->d_un.d_val = KV.second(); 1179 ++P; 1180 } 1181 } 1182 1183 uint64_t DynamicReloc::getOffset() const { 1184 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec); 1185 } 1186 1187 int64_t DynamicReloc::getAddend() const { 1188 if (UseSymVA) 1189 return Sym->getVA(Addend); 1190 return Addend; 1191 } 1192 1193 uint32_t DynamicReloc::getSymIndex() const { 1194 if (Sym && !UseSymVA) 1195 return Sym->DynsymIndex; 1196 return 0; 1197 } 1198 1199 RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type, 1200 int32_t DynamicTag, 1201 int32_t SizeDynamicTag) 1202 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name), 1203 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {} 1204 1205 void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) { 1206 if (Reloc.Type == Target->RelativeRel) 1207 ++NumRelativeRelocs; 1208 Relocs.push_back(Reloc); 1209 } 1210 1211 void RelocationBaseSection::finalizeContents() { 1212 // If all relocations are R_*_RELATIVE they don't refer to any 1213 // dynamic symbol and we don't need a dynamic symbol table. If that 1214 // is the case, just use 0 as the link. 1215 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0; 1216 1217 // Set required output section properties. 1218 getParent()->Link = Link; 1219 } 1220 1221 template <class ELFT> 1222 static void encodeDynamicReloc(typename ELFT::Rela *P, 1223 const DynamicReloc &Rel) { 1224 if (Config->IsRela) 1225 P->r_addend = Rel.getAddend(); 1226 P->r_offset = Rel.getOffset(); 1227 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot) 1228 // The MIPS GOT section contains dynamic relocations that correspond to TLS 1229 // entries. These entries are placed after the global and local sections of 1230 // the GOT. At the point when we create these relocations, the size of the 1231 // global and local sections is unknown, so the offset that we store in the 1232 // TLS entry's DynamicReloc is relative to the start of the TLS section of 1233 // the GOT, rather than being relative to the start of the GOT. This line of 1234 // code adds the size of the global and local sections to the virtual 1235 // address computed by getOffset() in order to adjust it into the TLS 1236 // section. 1237 P->r_offset += InX::MipsGot->getTlsOffset(); 1238 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL); 1239 } 1240 1241 template <class ELFT> 1242 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort) 1243 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL, 1244 Config->IsRela ? DT_RELA : DT_REL, 1245 Config->IsRela ? DT_RELASZ : DT_RELSZ), 1246 Sort(Sort) { 1247 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1248 } 1249 1250 template <class ELFT, class RelTy> 1251 static bool compRelocations(const RelTy &A, const RelTy &B) { 1252 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel; 1253 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel; 1254 if (AIsRel != BIsRel) 1255 return AIsRel; 1256 1257 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL); 1258 } 1259 1260 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { 1261 uint8_t *BufBegin = Buf; 1262 for (const DynamicReloc &Rel : Relocs) { 1263 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel); 1264 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1265 } 1266 1267 if (Sort) { 1268 if (Config->IsRela) 1269 std::stable_sort((Elf_Rela *)BufBegin, 1270 (Elf_Rela *)BufBegin + Relocs.size(), 1271 compRelocations<ELFT, Elf_Rela>); 1272 else 1273 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(), 1274 compRelocations<ELFT, Elf_Rel>); 1275 } 1276 } 1277 1278 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() { 1279 return this->Entsize * Relocs.size(); 1280 } 1281 1282 template <class ELFT> 1283 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection( 1284 StringRef Name) 1285 : RelocationBaseSection( 1286 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL, 1287 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL, 1288 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) { 1289 this->Entsize = 1; 1290 } 1291 1292 template <class ELFT> 1293 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() { 1294 // This function computes the contents of an Android-format packed relocation 1295 // section. 1296 // 1297 // This format compresses relocations by using relocation groups to factor out 1298 // fields that are common between relocations and storing deltas from previous 1299 // relocations in SLEB128 format (which has a short representation for small 1300 // numbers). A good example of a relocation type with common fields is 1301 // R_*_RELATIVE, which is normally used to represent function pointers in 1302 // vtables. In the REL format, each relative relocation has the same r_info 1303 // field, and is only different from other relative relocations in terms of 1304 // the r_offset field. By sorting relocations by offset, grouping them by 1305 // r_info and representing each relocation with only the delta from the 1306 // previous offset, each 8-byte relocation can be compressed to as little as 1 1307 // byte (or less with run-length encoding). This relocation packer was able to 1308 // reduce the size of the relocation section in an Android Chromium DSO from 1309 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size. 1310 // 1311 // A relocation section consists of a header containing the literal bytes 1312 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two 1313 // elements are the total number of relocations in the section and an initial 1314 // r_offset value. The remaining elements define a sequence of relocation 1315 // groups. Each relocation group starts with a header consisting of the 1316 // following elements: 1317 // 1318 // - the number of relocations in the relocation group 1319 // - flags for the relocation group 1320 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta 1321 // for each relocation in the group. 1322 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info 1323 // field for each relocation in the group. 1324 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and 1325 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for 1326 // each relocation in the group. 1327 // 1328 // Following the relocation group header are descriptions of each of the 1329 // relocations in the group. They consist of the following elements: 1330 // 1331 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset 1332 // delta for this relocation. 1333 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info 1334 // field for this relocation. 1335 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and 1336 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for 1337 // this relocation. 1338 1339 size_t OldSize = RelocData.size(); 1340 1341 RelocData = {'A', 'P', 'S', '2'}; 1342 raw_svector_ostream OS(RelocData); 1343 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); }; 1344 1345 // The format header includes the number of relocations and the initial 1346 // offset (we set this to zero because the first relocation group will 1347 // perform the initial adjustment). 1348 Add(Relocs.size()); 1349 Add(0); 1350 1351 std::vector<Elf_Rela> Relatives, NonRelatives; 1352 1353 for (const DynamicReloc &Rel : Relocs) { 1354 Elf_Rela R; 1355 encodeDynamicReloc<ELFT>(&R, Rel); 1356 1357 if (R.getType(Config->IsMips64EL) == Target->RelativeRel) 1358 Relatives.push_back(R); 1359 else 1360 NonRelatives.push_back(R); 1361 } 1362 1363 std::sort(Relatives.begin(), Relatives.end(), 1364 [](const Elf_Rel &A, const Elf_Rel &B) { 1365 return A.r_offset < B.r_offset; 1366 }); 1367 1368 // Try to find groups of relative relocations which are spaced one word 1369 // apart from one another. These generally correspond to vtable entries. The 1370 // format allows these groups to be encoded using a sort of run-length 1371 // encoding, but each group will cost 7 bytes in addition to the offset from 1372 // the previous group, so it is only profitable to do this for groups of 1373 // size 8 or larger. 1374 std::vector<Elf_Rela> UngroupedRelatives; 1375 std::vector<std::vector<Elf_Rela>> RelativeGroups; 1376 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) { 1377 std::vector<Elf_Rela> Group; 1378 do { 1379 Group.push_back(*I++); 1380 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset); 1381 1382 if (Group.size() < 8) 1383 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(), 1384 Group.end()); 1385 else 1386 RelativeGroups.emplace_back(std::move(Group)); 1387 } 1388 1389 unsigned HasAddendIfRela = 1390 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0; 1391 1392 uint64_t Offset = 0; 1393 uint64_t Addend = 0; 1394 1395 // Emit the run-length encoding for the groups of adjacent relative 1396 // relocations. Each group is represented using two groups in the packed 1397 // format. The first is used to set the current offset to the start of the 1398 // group (and also encodes the first relocation), and the second encodes the 1399 // remaining relocations. 1400 for (std::vector<Elf_Rela> &G : RelativeGroups) { 1401 // The first relocation in the group. 1402 Add(1); 1403 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | 1404 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1405 Add(G[0].r_offset - Offset); 1406 Add(Target->RelativeRel); 1407 if (Config->IsRela) { 1408 Add(G[0].r_addend - Addend); 1409 Addend = G[0].r_addend; 1410 } 1411 1412 // The remaining relocations. 1413 Add(G.size() - 1); 1414 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | 1415 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1416 Add(Config->Wordsize); 1417 Add(Target->RelativeRel); 1418 if (Config->IsRela) { 1419 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) { 1420 Add(I->r_addend - Addend); 1421 Addend = I->r_addend; 1422 } 1423 } 1424 1425 Offset = G.back().r_offset; 1426 } 1427 1428 // Now the ungrouped relatives. 1429 if (!UngroupedRelatives.empty()) { 1430 Add(UngroupedRelatives.size()); 1431 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1432 Add(Target->RelativeRel); 1433 for (Elf_Rela &R : UngroupedRelatives) { 1434 Add(R.r_offset - Offset); 1435 Offset = R.r_offset; 1436 if (Config->IsRela) { 1437 Add(R.r_addend - Addend); 1438 Addend = R.r_addend; 1439 } 1440 } 1441 } 1442 1443 // Finally the non-relative relocations. 1444 std::sort(NonRelatives.begin(), NonRelatives.end(), 1445 [](const Elf_Rela &A, const Elf_Rela &B) { 1446 return A.r_offset < B.r_offset; 1447 }); 1448 if (!NonRelatives.empty()) { 1449 Add(NonRelatives.size()); 1450 Add(HasAddendIfRela); 1451 for (Elf_Rela &R : NonRelatives) { 1452 Add(R.r_offset - Offset); 1453 Offset = R.r_offset; 1454 Add(R.r_info); 1455 if (Config->IsRela) { 1456 Add(R.r_addend - Addend); 1457 Addend = R.r_addend; 1458 } 1459 } 1460 } 1461 1462 // Returns whether the section size changed. We need to keep recomputing both 1463 // section layout and the contents of this section until the size converges 1464 // because changing this section's size can affect section layout, which in 1465 // turn can affect the sizes of the LEB-encoded integers stored in this 1466 // section. 1467 return RelocData.size() != OldSize; 1468 } 1469 1470 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec) 1471 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0, 1472 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, 1473 Config->Wordsize, 1474 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"), 1475 StrTabSec(StrTabSec) {} 1476 1477 // Orders symbols according to their positions in the GOT, 1478 // in compliance with MIPS ABI rules. 1479 // See "Global Offset Table" in Chapter 5 in the following document 1480 // for detailed description: 1481 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1482 static bool sortMipsSymbols(const SymbolTableEntry &L, 1483 const SymbolTableEntry &R) { 1484 // Sort entries related to non-local preemptible symbols by GOT indexes. 1485 // All other entries go to the first part of GOT in arbitrary order. 1486 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot; 1487 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot; 1488 if (LIsInLocalGot || RIsInLocalGot) 1489 return !RIsInLocalGot; 1490 return L.Sym->GotIndex < R.Sym->GotIndex; 1491 } 1492 1493 void SymbolTableBaseSection::finalizeContents() { 1494 getParent()->Link = StrTabSec.getParent()->SectionIndex; 1495 1496 // If it is a .dynsym, there should be no local symbols, but we need 1497 // to do a few things for the dynamic linker. 1498 if (this->Type == SHT_DYNSYM) { 1499 // Section's Info field has the index of the first non-local symbol. 1500 // Because the first symbol entry is a null entry, 1 is the first. 1501 getParent()->Info = 1; 1502 1503 if (InX::GnuHashTab) { 1504 // NB: It also sorts Symbols to meet the GNU hash table requirements. 1505 InX::GnuHashTab->addSymbols(Symbols); 1506 } else if (Config->EMachine == EM_MIPS) { 1507 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols); 1508 } 1509 1510 size_t I = 0; 1511 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I; 1512 return; 1513 } 1514 } 1515 1516 // The ELF spec requires that all local symbols precede global symbols, so we 1517 // sort symbol entries in this function. (For .dynsym, we don't do that because 1518 // symbols for dynamic linking are inherently all globals.) 1519 void SymbolTableBaseSection::postThunkContents() { 1520 if (this->Type == SHT_DYNSYM) 1521 return; 1522 // move all local symbols before global symbols. 1523 auto It = std::stable_partition( 1524 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) { 1525 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL; 1526 }); 1527 size_t NumLocals = It - Symbols.begin(); 1528 getParent()->Info = NumLocals + 1; 1529 } 1530 1531 void SymbolTableBaseSection::addSymbol(Symbol *B) { 1532 // Adding a local symbol to a .dynsym is a bug. 1533 assert(this->Type != SHT_DYNSYM || !B->isLocal()); 1534 1535 bool HashIt = B->isLocal(); 1536 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)}); 1537 } 1538 1539 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) { 1540 // Initializes symbol lookup tables lazily. This is used only 1541 // for -r or -emit-relocs. 1542 llvm::call_once(OnceFlag, [&] { 1543 SymbolIndexMap.reserve(Symbols.size()); 1544 size_t I = 0; 1545 for (const SymbolTableEntry &E : Symbols) { 1546 if (E.Sym->Type == STT_SECTION) 1547 SectionIndexMap[E.Sym->getOutputSection()] = ++I; 1548 else 1549 SymbolIndexMap[E.Sym] = ++I; 1550 } 1551 }); 1552 1553 // Section symbols are mapped based on their output sections 1554 // to maintain their semantics. 1555 if (Sym->Type == STT_SECTION) 1556 return SectionIndexMap.lookup(Sym->getOutputSection()); 1557 return SymbolIndexMap.lookup(Sym); 1558 } 1559 1560 template <class ELFT> 1561 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec) 1562 : SymbolTableBaseSection(StrTabSec) { 1563 this->Entsize = sizeof(Elf_Sym); 1564 } 1565 1566 // Write the internal symbol table contents to the output symbol table. 1567 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { 1568 // The first entry is a null entry as per the ELF spec. 1569 memset(Buf, 0, sizeof(Elf_Sym)); 1570 Buf += sizeof(Elf_Sym); 1571 1572 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1573 1574 for (SymbolTableEntry &Ent : Symbols) { 1575 Symbol *Sym = Ent.Sym; 1576 1577 // Set st_info and st_other. 1578 ESym->st_other = 0; 1579 if (Sym->isLocal()) { 1580 ESym->setBindingAndType(STB_LOCAL, Sym->Type); 1581 } else { 1582 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type); 1583 ESym->setVisibility(Sym->Visibility); 1584 } 1585 1586 ESym->st_name = Ent.StrTabOffset; 1587 1588 // Set a section index. 1589 BssSection *CommonSec = nullptr; 1590 if (!Config->DefineCommon) 1591 if (auto *D = dyn_cast<Defined>(Sym)) 1592 CommonSec = dyn_cast_or_null<BssSection>(D->Section); 1593 if (CommonSec) 1594 ESym->st_shndx = SHN_COMMON; 1595 else if (const OutputSection *OutSec = Sym->getOutputSection()) 1596 ESym->st_shndx = OutSec->SectionIndex; 1597 else if (isa<Defined>(Sym)) 1598 ESym->st_shndx = SHN_ABS; 1599 else 1600 ESym->st_shndx = SHN_UNDEF; 1601 1602 // Copy symbol size if it is a defined symbol. st_size is not significant 1603 // for undefined symbols, so whether copying it or not is up to us if that's 1604 // the case. We'll leave it as zero because by not setting a value, we can 1605 // get the exact same outputs for two sets of input files that differ only 1606 // in undefined symbol size in DSOs. 1607 if (ESym->st_shndx == SHN_UNDEF) 1608 ESym->st_size = 0; 1609 else 1610 ESym->st_size = Sym->getSize(); 1611 1612 // st_value is usually an address of a symbol, but that has a 1613 // special meaining for uninstantiated common symbols (this can 1614 // occur if -r is given). 1615 if (CommonSec) 1616 ESym->st_value = CommonSec->Alignment; 1617 else 1618 ESym->st_value = Sym->getVA(); 1619 1620 ++ESym; 1621 } 1622 1623 // On MIPS we need to mark symbol which has a PLT entry and requires 1624 // pointer equality by STO_MIPS_PLT flag. That is necessary to help 1625 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs. 1626 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt 1627 if (Config->EMachine == EM_MIPS) { 1628 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1629 1630 for (SymbolTableEntry &Ent : Symbols) { 1631 Symbol *Sym = Ent.Sym; 1632 if (Sym->isInPlt() && Sym->NeedsPltAddr) 1633 ESym->st_other |= STO_MIPS_PLT; 1634 if (isMicroMips()) { 1635 // Set STO_MIPS_MICROMIPS flag and less-significant bit for 1636 // defined microMIPS symbols and shared symbols with PLT record. 1637 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) || 1638 (Sym->isShared() && Sym->NeedsPltAddr)) { 1639 if (StrTabSec.isDynamic()) 1640 ESym->st_value |= 1; 1641 ESym->st_other |= STO_MIPS_MICROMIPS; 1642 } 1643 } 1644 if (Config->Relocatable) 1645 if (auto *D = dyn_cast<Defined>(Sym)) 1646 if (isMipsPIC<ELFT>(D)) 1647 ESym->st_other |= STO_MIPS_PIC; 1648 ++ESym; 1649 } 1650 } 1651 } 1652 1653 // .hash and .gnu.hash sections contain on-disk hash tables that map 1654 // symbol names to their dynamic symbol table indices. Their purpose 1655 // is to help the dynamic linker resolve symbols quickly. If ELF files 1656 // don't have them, the dynamic linker has to do linear search on all 1657 // dynamic symbols, which makes programs slower. Therefore, a .hash 1658 // section is added to a DSO by default. A .gnu.hash is added if you 1659 // give the -hash-style=gnu or -hash-style=both option. 1660 // 1661 // The Unix semantics of resolving dynamic symbols is somewhat expensive. 1662 // Each ELF file has a list of DSOs that the ELF file depends on and a 1663 // list of dynamic symbols that need to be resolved from any of the 1664 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n) 1665 // where m is the number of DSOs and n is the number of dynamic 1666 // symbols. For modern large programs, both m and n are large. So 1667 // making each step faster by using hash tables substiantially 1668 // improves time to load programs. 1669 // 1670 // (Note that this is not the only way to design the shared library. 1671 // For instance, the Windows DLL takes a different approach. On 1672 // Windows, each dynamic symbol has a name of DLL from which the symbol 1673 // has to be resolved. That makes the cost of symbol resolution O(n). 1674 // This disables some hacky techniques you can use on Unix such as 1675 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.) 1676 // 1677 // Due to historical reasons, we have two different hash tables, .hash 1678 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new 1679 // and better version of .hash. .hash is just an on-disk hash table, but 1680 // .gnu.hash has a bloom filter in addition to a hash table to skip 1681 // DSOs very quickly. If you are sure that your dynamic linker knows 1682 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a 1683 // safe bet is to specify -hash-style=both for backward compatibilty. 1684 GnuHashTableSection::GnuHashTableSection() 1685 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") { 1686 } 1687 1688 void GnuHashTableSection::finalizeContents() { 1689 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 1690 1691 // Computes bloom filter size in word size. We want to allocate 8 1692 // bits for each symbol. It must be a power of two. 1693 if (Symbols.empty()) 1694 MaskWords = 1; 1695 else 1696 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize); 1697 1698 Size = 16; // Header 1699 Size += Config->Wordsize * MaskWords; // Bloom filter 1700 Size += NBuckets * 4; // Hash buckets 1701 Size += Symbols.size() * 4; // Hash values 1702 } 1703 1704 void GnuHashTableSection::writeTo(uint8_t *Buf) { 1705 // The output buffer is not guaranteed to be zero-cleared because we pre- 1706 // fill executable sections with trap instructions. This is a precaution 1707 // for that case, which happens only when -no-rosegment is given. 1708 memset(Buf, 0, Size); 1709 1710 // Write a header. 1711 write32(Buf, NBuckets); 1712 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size()); 1713 write32(Buf + 8, MaskWords); 1714 write32(Buf + 12, getShift2()); 1715 Buf += 16; 1716 1717 // Write a bloom filter and a hash table. 1718 writeBloomFilter(Buf); 1719 Buf += Config->Wordsize * MaskWords; 1720 writeHashTable(Buf); 1721 } 1722 1723 // This function writes a 2-bit bloom filter. This bloom filter alone 1724 // usually filters out 80% or more of all symbol lookups [1]. 1725 // The dynamic linker uses the hash table only when a symbol is not 1726 // filtered out by a bloom filter. 1727 // 1728 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2), 1729 // p.9, https://www.akkadia.org/drepper/dsohowto.pdf 1730 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) { 1731 const unsigned C = Config->Wordsize * 8; 1732 for (const Entry &Sym : Symbols) { 1733 size_t I = (Sym.Hash / C) & (MaskWords - 1); 1734 uint64_t Val = readUint(Buf + I * Config->Wordsize); 1735 Val |= uint64_t(1) << (Sym.Hash % C); 1736 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C); 1737 writeUint(Buf + I * Config->Wordsize, Val); 1738 } 1739 } 1740 1741 void GnuHashTableSection::writeHashTable(uint8_t *Buf) { 1742 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf); 1743 uint32_t OldBucket = -1; 1744 uint32_t *Values = Buckets + NBuckets; 1745 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) { 1746 // Write a hash value. It represents a sequence of chains that share the 1747 // same hash modulo value. The last element of each chain is terminated by 1748 // LSB 1. 1749 uint32_t Hash = I->Hash; 1750 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx; 1751 Hash = IsLastInChain ? Hash | 1 : Hash & ~1; 1752 write32(Values++, Hash); 1753 1754 if (I->BucketIdx == OldBucket) 1755 continue; 1756 // Write a hash bucket. Hash buckets contain indices in the following hash 1757 // value table. 1758 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex); 1759 OldBucket = I->BucketIdx; 1760 } 1761 } 1762 1763 static uint32_t hashGnu(StringRef Name) { 1764 uint32_t H = 5381; 1765 for (uint8_t C : Name) 1766 H = (H << 5) + H + C; 1767 return H; 1768 } 1769 1770 // Add symbols to this symbol hash table. Note that this function 1771 // destructively sort a given vector -- which is needed because 1772 // GNU-style hash table places some sorting requirements. 1773 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) { 1774 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce 1775 // its type correctly. 1776 std::vector<SymbolTableEntry>::iterator Mid = 1777 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) { 1778 // Shared symbols that this executable preempts are special. The dynamic 1779 // linker has to look them up, so they have to be in the hash table. 1780 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym)) 1781 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr; 1782 return !S.Sym->isDefined(); 1783 }); 1784 if (Mid == V.end()) 1785 return; 1786 1787 // We chose load factor 4 for the on-disk hash table. For each hash 1788 // collision, the dynamic linker will compare a uint32_t hash value. 1789 // Since the integer comparison is quite fast, we believe we can make 1790 // the load factor even larger. 4 is just a conservative choice. 1791 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1); 1792 1793 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) { 1794 Symbol *B = Ent.Sym; 1795 uint32_t Hash = hashGnu(B->getName()); 1796 uint32_t BucketIdx = Hash % NBuckets; 1797 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx}); 1798 } 1799 1800 std::stable_sort( 1801 Symbols.begin(), Symbols.end(), 1802 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; }); 1803 1804 V.erase(Mid, V.end()); 1805 for (const Entry &Ent : Symbols) 1806 V.push_back({Ent.Sym, Ent.StrTabOffset}); 1807 } 1808 1809 HashTableSection::HashTableSection() 1810 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") { 1811 this->Entsize = 4; 1812 } 1813 1814 void HashTableSection::finalizeContents() { 1815 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 1816 1817 unsigned NumEntries = 2; // nbucket and nchain. 1818 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries. 1819 1820 // Create as many buckets as there are symbols. 1821 NumEntries += InX::DynSymTab->getNumSymbols(); 1822 this->Size = NumEntries * 4; 1823 } 1824 1825 void HashTableSection::writeTo(uint8_t *Buf) { 1826 // See comment in GnuHashTableSection::writeTo. 1827 memset(Buf, 0, Size); 1828 1829 unsigned NumSymbols = InX::DynSymTab->getNumSymbols(); 1830 1831 uint32_t *P = reinterpret_cast<uint32_t *>(Buf); 1832 write32(P++, NumSymbols); // nbucket 1833 write32(P++, NumSymbols); // nchain 1834 1835 uint32_t *Buckets = P; 1836 uint32_t *Chains = P + NumSymbols; 1837 1838 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { 1839 Symbol *Sym = S.Sym; 1840 StringRef Name = Sym->getName(); 1841 unsigned I = Sym->DynsymIndex; 1842 uint32_t Hash = hashSysV(Name) % NumSymbols; 1843 Chains[I] = Buckets[Hash]; 1844 write32(Buckets + Hash, I); 1845 } 1846 } 1847 1848 PltSection::PltSection(size_t S) 1849 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"), 1850 HeaderSize(S) { 1851 // The PLT needs to be writable on SPARC as the dynamic linker will 1852 // modify the instructions in the PLT entries. 1853 if (Config->EMachine == EM_SPARCV9) 1854 this->Flags |= SHF_WRITE; 1855 } 1856 1857 void PltSection::writeTo(uint8_t *Buf) { 1858 // At beginning of PLT but not the IPLT, we have code to call the dynamic 1859 // linker to resolve dynsyms at runtime. Write such code. 1860 if (HeaderSize != 0) 1861 Target->writePltHeader(Buf); 1862 size_t Off = HeaderSize; 1863 // The IPlt is immediately after the Plt, account for this in RelOff 1864 unsigned PltOff = getPltRelocOff(); 1865 1866 for (auto &I : Entries) { 1867 const Symbol *B = I.first; 1868 unsigned RelOff = I.second + PltOff; 1869 uint64_t Got = B->getGotPltVA(); 1870 uint64_t Plt = this->getVA() + Off; 1871 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); 1872 Off += Target->PltEntrySize; 1873 } 1874 } 1875 1876 template <class ELFT> void PltSection::addEntry(Symbol &Sym) { 1877 Sym.PltIndex = Entries.size(); 1878 RelocationBaseSection *PltRelocSection = InX::RelaPlt; 1879 if (HeaderSize == 0) { 1880 PltRelocSection = InX::RelaIplt; 1881 Sym.IsInIplt = true; 1882 } 1883 unsigned RelOff = 1884 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset(); 1885 Entries.push_back(std::make_pair(&Sym, RelOff)); 1886 } 1887 1888 size_t PltSection::getSize() const { 1889 return HeaderSize + Entries.size() * Target->PltEntrySize; 1890 } 1891 1892 // Some architectures such as additional symbols in the PLT section. For 1893 // example ARM uses mapping symbols to aid disassembly 1894 void PltSection::addSymbols() { 1895 // The PLT may have symbols defined for the Header, the IPLT has no header 1896 if (HeaderSize != 0) 1897 Target->addPltHeaderSymbols(*this); 1898 size_t Off = HeaderSize; 1899 for (size_t I = 0; I < Entries.size(); ++I) { 1900 Target->addPltSymbols(*this, Off); 1901 Off += Target->PltEntrySize; 1902 } 1903 } 1904 1905 unsigned PltSection::getPltRelocOff() const { 1906 return (HeaderSize == 0) ? InX::Plt->getSize() : 0; 1907 } 1908 1909 // The string hash function for .gdb_index. 1910 static uint32_t computeGdbHash(StringRef S) { 1911 uint32_t H = 0; 1912 for (uint8_t C : S) 1913 H = H * 67 + tolower(C) - 113; 1914 return H; 1915 } 1916 1917 static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) { 1918 std::vector<GdbIndexChunk::CuEntry> Ret; 1919 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) 1920 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4}); 1921 return Ret; 1922 } 1923 1924 static std::vector<GdbIndexChunk::AddressEntry> 1925 readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) { 1926 std::vector<GdbIndexChunk::AddressEntry> Ret; 1927 1928 uint32_t CuIdx = 0; 1929 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) { 1930 DWARFAddressRangesVector Ranges; 1931 Cu->collectAddressRanges(Ranges); 1932 1933 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections(); 1934 for (DWARFAddressRange &R : Ranges) { 1935 InputSectionBase *S = Sections[R.SectionIndex]; 1936 if (!S || S == &InputSection::Discarded || !S->Live) 1937 continue; 1938 // Range list with zero size has no effect. 1939 if (R.LowPC == R.HighPC) 1940 continue; 1941 auto *IS = cast<InputSection>(S); 1942 uint64_t Offset = IS->getOffsetInFile(); 1943 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx}); 1944 } 1945 ++CuIdx; 1946 } 1947 return Ret; 1948 } 1949 1950 static std::vector<GdbIndexChunk::NameTypeEntry> 1951 readPubNamesAndTypes(DWARFContext &Dwarf) { 1952 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection(); 1953 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection(); 1954 1955 std::vector<GdbIndexChunk::NameTypeEntry> Ret; 1956 for (StringRef Sec : {Sec1, Sec2}) { 1957 DWARFDebugPubTable Table(Sec, Config->IsLE, true); 1958 for (const DWARFDebugPubTable::Set &Set : Table.getData()) { 1959 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) { 1960 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name)); 1961 Ret.push_back({S, Ent.Descriptor.toBits()}); 1962 } 1963 } 1964 } 1965 return Ret; 1966 } 1967 1968 static std::vector<InputSection *> getDebugInfoSections() { 1969 std::vector<InputSection *> Ret; 1970 for (InputSectionBase *S : InputSections) 1971 if (InputSection *IS = dyn_cast<InputSection>(S)) 1972 if (IS->Name == ".debug_info") 1973 Ret.push_back(IS); 1974 return Ret; 1975 } 1976 1977 void GdbIndexSection::fixCuIndex() { 1978 uint32_t Idx = 0; 1979 for (GdbIndexChunk &Chunk : Chunks) { 1980 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas) 1981 Ent.CuIndex += Idx; 1982 Idx += Chunk.CompilationUnits.size(); 1983 } 1984 } 1985 1986 std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() { 1987 std::vector<std::vector<uint32_t>> Ret; 1988 uint32_t Idx = 0; 1989 uint32_t Off = 0; 1990 1991 for (GdbIndexChunk &Chunk : Chunks) { 1992 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) { 1993 GdbSymbol *&Sym = Symbols[Ent.Name]; 1994 if (!Sym) { 1995 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()}); 1996 Off += Ent.Name.size() + 1; 1997 Ret.push_back({}); 1998 } 1999 2000 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains 2001 // duplicate entries, so we want to dedup them. 2002 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex]; 2003 uint32_t Val = (Ent.Type << 24) | Idx; 2004 if (Vec.empty() || Vec.back() != Val) 2005 Vec.push_back(Val); 2006 } 2007 Idx += Chunk.CompilationUnits.size(); 2008 } 2009 2010 StringPoolSize = Off; 2011 return Ret; 2012 } 2013 2014 template <class ELFT> GdbIndexSection *elf::createGdbIndex() { 2015 // Gather debug info to create a .gdb_index section. 2016 std::vector<InputSection *> Sections = getDebugInfoSections(); 2017 std::vector<GdbIndexChunk> Chunks(Sections.size()); 2018 2019 parallelForEachN(0, Chunks.size(), [&](size_t I) { 2020 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>(); 2021 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File)); 2022 2023 Chunks[I].DebugInfoSec = Sections[I]; 2024 Chunks[I].CompilationUnits = readCuList(Dwarf); 2025 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]); 2026 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf); 2027 }); 2028 2029 // .debug_gnu_pub{names,types} are useless in executables. 2030 // They are present in input object files solely for creating 2031 // a .gdb_index. So we can remove it from the output. 2032 for (InputSectionBase *S : InputSections) 2033 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes") 2034 S->Live = false; 2035 2036 // Create a .gdb_index and returns it. 2037 return make<GdbIndexSection>(std::move(Chunks)); 2038 } 2039 2040 static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) { 2041 size_t Ret = 0; 2042 for (const GdbIndexChunk &D : Arr) 2043 Ret += D.CompilationUnits.size(); 2044 return Ret; 2045 } 2046 2047 static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) { 2048 size_t Ret = 0; 2049 for (const GdbIndexChunk &D : Arr) 2050 Ret += D.AddressAreas.size(); 2051 return Ret; 2052 } 2053 2054 std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() { 2055 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3); 2056 if (Size < 1024) 2057 Size = 1024; 2058 2059 uint32_t Mask = Size - 1; 2060 std::vector<GdbSymbol *> Ret(Size); 2061 2062 for (auto &KV : Symbols) { 2063 GdbSymbol *Sym = KV.second; 2064 uint32_t I = Sym->NameHash & Mask; 2065 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1; 2066 2067 while (Ret[I]) 2068 I = (I + Step) & Mask; 2069 Ret[I] = Sym; 2070 } 2071 return Ret; 2072 } 2073 2074 GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C) 2075 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) { 2076 fixCuIndex(); 2077 CuVectors = createCuVectors(); 2078 GdbSymtab = createGdbSymtab(); 2079 2080 // Compute offsets early to know the section size. 2081 // Each chunk size needs to be in sync with what we write in writeTo. 2082 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16; 2083 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20; 2084 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8; 2085 2086 size_t Off = 0; 2087 for (ArrayRef<uint32_t> Vec : CuVectors) { 2088 CuVectorOffsets.push_back(Off); 2089 Off += (Vec.size() + 1) * 4; 2090 } 2091 StringPoolOffset = ConstantPoolOffset + Off; 2092 } 2093 2094 size_t GdbIndexSection::getSize() const { 2095 return StringPoolOffset + StringPoolSize; 2096 } 2097 2098 void GdbIndexSection::writeTo(uint8_t *Buf) { 2099 // Write the section header. 2100 write32le(Buf, 7); 2101 write32le(Buf + 4, CuListOffset); 2102 write32le(Buf + 8, CuTypesOffset); 2103 write32le(Buf + 12, CuTypesOffset); 2104 write32le(Buf + 16, SymtabOffset); 2105 write32le(Buf + 20, ConstantPoolOffset); 2106 Buf += 24; 2107 2108 // Write the CU list. 2109 for (GdbIndexChunk &D : Chunks) { 2110 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) { 2111 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset); 2112 write64le(Buf + 8, Cu.CuLength); 2113 Buf += 16; 2114 } 2115 } 2116 2117 // Write the address area. 2118 for (GdbIndexChunk &D : Chunks) { 2119 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) { 2120 uint64_t BaseAddr = 2121 E.Section->getParent()->Addr + E.Section->getOffset(0); 2122 write64le(Buf, BaseAddr + E.LowAddress); 2123 write64le(Buf + 8, BaseAddr + E.HighAddress); 2124 write32le(Buf + 16, E.CuIndex); 2125 Buf += 20; 2126 } 2127 } 2128 2129 // Write the symbol table. 2130 for (GdbSymbol *Sym : GdbSymtab) { 2131 if (Sym) { 2132 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset); 2133 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]); 2134 } 2135 Buf += 8; 2136 } 2137 2138 // Write the CU vectors. 2139 for (ArrayRef<uint32_t> Vec : CuVectors) { 2140 write32le(Buf, Vec.size()); 2141 Buf += 4; 2142 for (uint32_t Val : Vec) { 2143 write32le(Buf, Val); 2144 Buf += 4; 2145 } 2146 } 2147 2148 // Write the string pool. 2149 for (auto &KV : Symbols) { 2150 CachedHashStringRef S = KV.first; 2151 GdbSymbol *Sym = KV.second; 2152 size_t Off = Sym->NameOffset; 2153 memcpy(Buf + Off, S.val().data(), S.size()); 2154 Buf[Off + S.size()] = '\0'; 2155 } 2156 } 2157 2158 bool GdbIndexSection::empty() const { return !Out::DebugInfo; } 2159 2160 EhFrameHeader::EhFrameHeader() 2161 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {} 2162 2163 // .eh_frame_hdr contains a binary search table of pointers to FDEs. 2164 // Each entry of the search table consists of two values, 2165 // the starting PC from where FDEs covers, and the FDE's address. 2166 // It is sorted by PC. 2167 void EhFrameHeader::writeTo(uint8_t *Buf) { 2168 typedef EhFrameSection::FdeData FdeData; 2169 2170 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData(); 2171 2172 // Sort the FDE list by their PC and uniqueify. Usually there is only 2173 // one FDE for a PC (i.e. function), but if ICF merges two functions 2174 // into one, there can be more than one FDEs pointing to the address. 2175 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; }; 2176 std::stable_sort(Fdes.begin(), Fdes.end(), Less); 2177 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; }; 2178 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end()); 2179 2180 Buf[0] = 1; 2181 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4; 2182 Buf[2] = DW_EH_PE_udata4; 2183 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4; 2184 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4); 2185 write32(Buf + 8, Fdes.size()); 2186 Buf += 12; 2187 2188 uint64_t VA = this->getVA(); 2189 for (FdeData &Fde : Fdes) { 2190 write32(Buf, Fde.Pc - VA); 2191 write32(Buf + 4, Fde.FdeVA - VA); 2192 Buf += 8; 2193 } 2194 } 2195 2196 size_t EhFrameHeader::getSize() const { 2197 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs. 2198 return 12 + InX::EhFrame->NumFdes * 8; 2199 } 2200 2201 bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); } 2202 2203 template <class ELFT> 2204 VersionDefinitionSection<ELFT>::VersionDefinitionSection() 2205 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t), 2206 ".gnu.version_d") {} 2207 2208 static StringRef getFileDefName() { 2209 if (!Config->SoName.empty()) 2210 return Config->SoName; 2211 return Config->OutputFile; 2212 } 2213 2214 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() { 2215 FileDefNameOff = InX::DynStrTab->addString(getFileDefName()); 2216 for (VersionDefinition &V : Config->VersionDefinitions) 2217 V.NameOff = InX::DynStrTab->addString(V.Name); 2218 2219 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; 2220 2221 // sh_info should be set to the number of definitions. This fact is missed in 2222 // documentation, but confirmed by binutils community: 2223 // https://sourceware.org/ml/binutils/2014-11/msg00355.html 2224 getParent()->Info = getVerDefNum(); 2225 } 2226 2227 template <class ELFT> 2228 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index, 2229 StringRef Name, size_t NameOff) { 2230 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf); 2231 Verdef->vd_version = 1; 2232 Verdef->vd_cnt = 1; 2233 Verdef->vd_aux = sizeof(Elf_Verdef); 2234 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); 2235 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0); 2236 Verdef->vd_ndx = Index; 2237 Verdef->vd_hash = hashSysV(Name); 2238 2239 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef)); 2240 Verdaux->vda_name = NameOff; 2241 Verdaux->vda_next = 0; 2242 } 2243 2244 template <class ELFT> 2245 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) { 2246 writeOne(Buf, 1, getFileDefName(), FileDefNameOff); 2247 2248 for (VersionDefinition &V : Config->VersionDefinitions) { 2249 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); 2250 writeOne(Buf, V.Id, V.Name, V.NameOff); 2251 } 2252 2253 // Need to terminate the last version definition. 2254 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf); 2255 Verdef->vd_next = 0; 2256 } 2257 2258 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const { 2259 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum(); 2260 } 2261 2262 template <class ELFT> 2263 VersionTableSection<ELFT>::VersionTableSection() 2264 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t), 2265 ".gnu.version") { 2266 this->Entsize = sizeof(Elf_Versym); 2267 } 2268 2269 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() { 2270 // At the moment of june 2016 GNU docs does not mention that sh_link field 2271 // should be set, but Sun docs do. Also readelf relies on this field. 2272 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 2273 } 2274 2275 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const { 2276 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1); 2277 } 2278 2279 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) { 2280 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1; 2281 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { 2282 OutVersym->vs_index = S.Sym->VersionId; 2283 ++OutVersym; 2284 } 2285 } 2286 2287 template <class ELFT> bool VersionTableSection<ELFT>::empty() const { 2288 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty(); 2289 } 2290 2291 template <class ELFT> 2292 VersionNeedSection<ELFT>::VersionNeedSection() 2293 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t), 2294 ".gnu.version_r") { 2295 // Identifiers in verneed section start at 2 because 0 and 1 are reserved 2296 // for VER_NDX_LOCAL and VER_NDX_GLOBAL. 2297 // First identifiers are reserved by verdef section if it exist. 2298 NextIndex = getVerDefNum() + 1; 2299 } 2300 2301 template <class ELFT> 2302 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) { 2303 SharedFile<ELFT> &File = SS->getFile<ELFT>(); 2304 const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex]; 2305 if (!Ver) { 2306 SS->VersionId = VER_NDX_GLOBAL; 2307 return; 2308 } 2309 2310 // If we don't already know that we need an Elf_Verneed for this DSO, prepare 2311 // to create one by adding it to our needed list and creating a dynstr entry 2312 // for the soname. 2313 if (File.VerdefMap.empty()) 2314 Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)}); 2315 typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver]; 2316 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, 2317 // prepare to create one by allocating a version identifier and creating a 2318 // dynstr entry for the version name. 2319 if (NV.Index == 0) { 2320 NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() + 2321 Ver->getAux()->vda_name); 2322 NV.Index = NextIndex++; 2323 } 2324 SS->VersionId = NV.Index; 2325 } 2326 2327 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { 2328 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. 2329 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf); 2330 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size()); 2331 2332 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) { 2333 // Create an Elf_Verneed for this DSO. 2334 Verneed->vn_version = 1; 2335 Verneed->vn_cnt = P.first->VerdefMap.size(); 2336 Verneed->vn_file = P.second; 2337 Verneed->vn_aux = 2338 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed); 2339 Verneed->vn_next = sizeof(Elf_Verneed); 2340 ++Verneed; 2341 2342 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over 2343 // VerdefMap, which will only contain references to needed version 2344 // definitions. Each Elf_Vernaux is based on the information contained in 2345 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of 2346 // pointers, but is deterministic because the pointers refer to Elf_Verdef 2347 // data structures within a single input file. 2348 for (auto &NV : P.first->VerdefMap) { 2349 Vernaux->vna_hash = NV.first->vd_hash; 2350 Vernaux->vna_flags = 0; 2351 Vernaux->vna_other = NV.second.Index; 2352 Vernaux->vna_name = NV.second.StrTab; 2353 Vernaux->vna_next = sizeof(Elf_Vernaux); 2354 ++Vernaux; 2355 } 2356 2357 Vernaux[-1].vna_next = 0; 2358 } 2359 Verneed[-1].vn_next = 0; 2360 } 2361 2362 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() { 2363 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; 2364 getParent()->Info = Needed.size(); 2365 } 2366 2367 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const { 2368 unsigned Size = Needed.size() * sizeof(Elf_Verneed); 2369 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed) 2370 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux); 2371 return Size; 2372 } 2373 2374 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const { 2375 return getNeedNum() == 0; 2376 } 2377 2378 void MergeSyntheticSection::addSection(MergeInputSection *MS) { 2379 MS->Parent = this; 2380 Sections.push_back(MS); 2381 } 2382 2383 MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type, 2384 uint64_t Flags, uint32_t Alignment) 2385 : MergeSyntheticSection(Name, Type, Flags, Alignment), 2386 Builder(StringTableBuilder::RAW, Alignment) {} 2387 2388 size_t MergeTailSection::getSize() const { return Builder.getSize(); } 2389 2390 void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); } 2391 2392 void MergeTailSection::finalizeContents() { 2393 // Add all string pieces to the string table builder to create section 2394 // contents. 2395 for (MergeInputSection *Sec : Sections) 2396 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2397 if (Sec->Pieces[I].Live) 2398 Builder.add(Sec->getData(I)); 2399 2400 // Fix the string table content. After this, the contents will never change. 2401 Builder.finalize(); 2402 2403 // finalize() fixed tail-optimized strings, so we can now get 2404 // offsets of strings. Get an offset for each string and save it 2405 // to a corresponding StringPiece for easy access. 2406 for (MergeInputSection *Sec : Sections) 2407 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2408 if (Sec->Pieces[I].Live) 2409 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I)); 2410 } 2411 2412 void MergeNoTailSection::writeTo(uint8_t *Buf) { 2413 for (size_t I = 0; I < NumShards; ++I) 2414 Shards[I].write(Buf + ShardOffsets[I]); 2415 } 2416 2417 // This function is very hot (i.e. it can take several seconds to finish) 2418 // because sometimes the number of inputs is in an order of magnitude of 2419 // millions. So, we use multi-threading. 2420 // 2421 // For any strings S and T, we know S is not mergeable with T if S's hash 2422 // value is different from T's. If that's the case, we can safely put S and 2423 // T into different string builders without worrying about merge misses. 2424 // We do it in parallel. 2425 void MergeNoTailSection::finalizeContents() { 2426 // Initializes string table builders. 2427 for (size_t I = 0; I < NumShards; ++I) 2428 Shards.emplace_back(StringTableBuilder::RAW, Alignment); 2429 2430 // Concurrency level. Must be a power of 2 to avoid expensive modulo 2431 // operations in the following tight loop. 2432 size_t Concurrency = 1; 2433 if (ThreadsEnabled) 2434 Concurrency = 2435 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards); 2436 2437 // Add section pieces to the builders. 2438 parallelForEachN(0, Concurrency, [&](size_t ThreadId) { 2439 for (MergeInputSection *Sec : Sections) { 2440 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) { 2441 size_t ShardId = getShardId(Sec->Pieces[I].Hash); 2442 if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live) 2443 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I)); 2444 } 2445 } 2446 }); 2447 2448 // Compute an in-section offset for each shard. 2449 size_t Off = 0; 2450 for (size_t I = 0; I < NumShards; ++I) { 2451 Shards[I].finalizeInOrder(); 2452 if (Shards[I].getSize() > 0) 2453 Off = alignTo(Off, Alignment); 2454 ShardOffsets[I] = Off; 2455 Off += Shards[I].getSize(); 2456 } 2457 Size = Off; 2458 2459 // So far, section pieces have offsets from beginning of shards, but 2460 // we want offsets from beginning of the whole section. Fix them. 2461 parallelForEach(Sections, [&](MergeInputSection *Sec) { 2462 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2463 if (Sec->Pieces[I].Live) 2464 Sec->Pieces[I].OutputOff += 2465 ShardOffsets[getShardId(Sec->Pieces[I].Hash)]; 2466 }); 2467 } 2468 2469 static MergeSyntheticSection *createMergeSynthetic(StringRef Name, 2470 uint32_t Type, 2471 uint64_t Flags, 2472 uint32_t Alignment) { 2473 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2; 2474 if (ShouldTailMerge) 2475 return make<MergeTailSection>(Name, Type, Flags, Alignment); 2476 return make<MergeNoTailSection>(Name, Type, Flags, Alignment); 2477 } 2478 2479 // Debug sections may be compressed by zlib. Uncompress if exists. 2480 void elf::decompressSections() { 2481 parallelForEach(InputSections, [](InputSectionBase *Sec) { 2482 if (Sec->Live) 2483 Sec->maybeUncompress(); 2484 }); 2485 } 2486 2487 // This function scans over the inputsections to create mergeable 2488 // synthetic sections. 2489 // 2490 // It removes MergeInputSections from the input section array and adds 2491 // new synthetic sections at the location of the first input section 2492 // that it replaces. It then finalizes each synthetic section in order 2493 // to compute an output offset for each piece of each input section. 2494 void elf::mergeSections() { 2495 // splitIntoPieces needs to be called on each MergeInputSection 2496 // before calling finalizeContents(). Do that first. 2497 parallelForEach(InputSections, [](InputSectionBase *Sec) { 2498 if (Sec->Live) 2499 if (auto *S = dyn_cast<MergeInputSection>(Sec)) 2500 S->splitIntoPieces(); 2501 }); 2502 2503 std::vector<MergeSyntheticSection *> MergeSections; 2504 for (InputSectionBase *&S : InputSections) { 2505 MergeInputSection *MS = dyn_cast<MergeInputSection>(S); 2506 if (!MS) 2507 continue; 2508 2509 // We do not want to handle sections that are not alive, so just remove 2510 // them instead of trying to merge. 2511 if (!MS->Live) 2512 continue; 2513 2514 StringRef OutsecName = getOutputSectionName(MS); 2515 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize); 2516 2517 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { 2518 // While we could create a single synthetic section for two different 2519 // values of Entsize, it is better to take Entsize into consideration. 2520 // 2521 // With a single synthetic section no two pieces with different Entsize 2522 // could be equal, so we may as well have two sections. 2523 // 2524 // Using Entsize in here also allows us to propagate it to the synthetic 2525 // section. 2526 return Sec->Name == OutsecName && Sec->Flags == MS->Flags && 2527 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment; 2528 }); 2529 if (I == MergeSections.end()) { 2530 MergeSyntheticSection *Syn = 2531 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment); 2532 MergeSections.push_back(Syn); 2533 I = std::prev(MergeSections.end()); 2534 S = Syn; 2535 Syn->Entsize = MS->Entsize; 2536 } else { 2537 S = nullptr; 2538 } 2539 (*I)->addSection(MS); 2540 } 2541 for (auto *MS : MergeSections) 2542 MS->finalizeContents(); 2543 2544 std::vector<InputSectionBase *> &V = InputSections; 2545 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); 2546 } 2547 2548 MipsRldMapSection::MipsRldMapSection() 2549 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize, 2550 ".rld_map") {} 2551 2552 ARMExidxSentinelSection::ARMExidxSentinelSection() 2553 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX, 2554 Config->Wordsize, ".ARM.exidx") {} 2555 2556 // Write a terminating sentinel entry to the end of the .ARM.exidx table. 2557 // This section will have been sorted last in the .ARM.exidx table. 2558 // This table entry will have the form: 2559 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND | 2560 // The sentinel must have the PREL31 value of an address higher than any 2561 // address described by any other table entry. 2562 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) { 2563 assert(Highest); 2564 uint64_t S = 2565 Highest->getParent()->Addr + Highest->getOffset(Highest->getSize()); 2566 uint64_t P = getVA(); 2567 Target->relocateOne(Buf, R_ARM_PREL31, S - P); 2568 write32le(Buf + 4, 1); 2569 } 2570 2571 // The sentinel has to be removed if there are no other .ARM.exidx entries. 2572 bool ARMExidxSentinelSection::empty() const { 2573 OutputSection *OS = getParent(); 2574 for (auto *B : OS->SectionCommands) 2575 if (auto *ISD = dyn_cast<InputSectionDescription>(B)) 2576 for (auto *S : ISD->Sections) 2577 if (!isa<ARMExidxSentinelSection>(S)) 2578 return false; 2579 return true; 2580 } 2581 2582 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off) 2583 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 2584 Config->Wordsize, ".text.thunk") { 2585 this->Parent = OS; 2586 this->OutSecOff = Off; 2587 } 2588 2589 void ThunkSection::addThunk(Thunk *T) { 2590 uint64_t Off = alignTo(Size, T->Alignment); 2591 T->Offset = Off; 2592 Thunks.push_back(T); 2593 T->addSymbols(*this); 2594 Size = Off + T->size(); 2595 } 2596 2597 void ThunkSection::writeTo(uint8_t *Buf) { 2598 for (const Thunk *T : Thunks) 2599 T->writeTo(Buf + T->Offset, *this); 2600 } 2601 2602 InputSection *ThunkSection::getTargetInputSection() const { 2603 if (Thunks.empty()) 2604 return nullptr; 2605 const Thunk *T = Thunks.front(); 2606 return T->getTargetInputSection(); 2607 } 2608 2609 InputSection *InX::ARMAttributes; 2610 BssSection *InX::Bss; 2611 BssSection *InX::BssRelRo; 2612 BuildIdSection *InX::BuildId; 2613 EhFrameHeader *InX::EhFrameHdr; 2614 EhFrameSection *InX::EhFrame; 2615 SyntheticSection *InX::Dynamic; 2616 StringTableSection *InX::DynStrTab; 2617 SymbolTableBaseSection *InX::DynSymTab; 2618 InputSection *InX::Interp; 2619 GdbIndexSection *InX::GdbIndex; 2620 GotSection *InX::Got; 2621 GotPltSection *InX::GotPlt; 2622 GnuHashTableSection *InX::GnuHashTab; 2623 HashTableSection *InX::HashTab; 2624 IgotPltSection *InX::IgotPlt; 2625 MipsGotSection *InX::MipsGot; 2626 MipsRldMapSection *InX::MipsRldMap; 2627 PltSection *InX::Plt; 2628 PltSection *InX::Iplt; 2629 RelocationBaseSection *InX::RelaDyn; 2630 RelocationBaseSection *InX::RelaPlt; 2631 RelocationBaseSection *InX::RelaIplt; 2632 StringTableSection *InX::ShStrTab; 2633 StringTableSection *InX::StrTab; 2634 SymbolTableBaseSection *InX::SymTab; 2635 2636 template GdbIndexSection *elf::createGdbIndex<ELF32LE>(); 2637 template GdbIndexSection *elf::createGdbIndex<ELF32BE>(); 2638 template GdbIndexSection *elf::createGdbIndex<ELF64LE>(); 2639 template GdbIndexSection *elf::createGdbIndex<ELF64BE>(); 2640 2641 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *); 2642 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *); 2643 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *); 2644 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *); 2645 2646 template void PltSection::addEntry<ELF32LE>(Symbol &Sym); 2647 template void PltSection::addEntry<ELF32BE>(Symbol &Sym); 2648 template void PltSection::addEntry<ELF64LE>(Symbol &Sym); 2649 template void PltSection::addEntry<ELF64BE>(Symbol &Sym); 2650 2651 template class elf::MipsAbiFlagsSection<ELF32LE>; 2652 template class elf::MipsAbiFlagsSection<ELF32BE>; 2653 template class elf::MipsAbiFlagsSection<ELF64LE>; 2654 template class elf::MipsAbiFlagsSection<ELF64BE>; 2655 2656 template class elf::MipsOptionsSection<ELF32LE>; 2657 template class elf::MipsOptionsSection<ELF32BE>; 2658 template class elf::MipsOptionsSection<ELF64LE>; 2659 template class elf::MipsOptionsSection<ELF64BE>; 2660 2661 template class elf::MipsReginfoSection<ELF32LE>; 2662 template class elf::MipsReginfoSection<ELF32BE>; 2663 template class elf::MipsReginfoSection<ELF64LE>; 2664 template class elf::MipsReginfoSection<ELF64BE>; 2665 2666 template class elf::DynamicSection<ELF32LE>; 2667 template class elf::DynamicSection<ELF32BE>; 2668 template class elf::DynamicSection<ELF64LE>; 2669 template class elf::DynamicSection<ELF64BE>; 2670 2671 template class elf::RelocationSection<ELF32LE>; 2672 template class elf::RelocationSection<ELF32BE>; 2673 template class elf::RelocationSection<ELF64LE>; 2674 template class elf::RelocationSection<ELF64BE>; 2675 2676 template class elf::AndroidPackedRelocationSection<ELF32LE>; 2677 template class elf::AndroidPackedRelocationSection<ELF32BE>; 2678 template class elf::AndroidPackedRelocationSection<ELF64LE>; 2679 template class elf::AndroidPackedRelocationSection<ELF64BE>; 2680 2681 template class elf::SymbolTableSection<ELF32LE>; 2682 template class elf::SymbolTableSection<ELF32BE>; 2683 template class elf::SymbolTableSection<ELF64LE>; 2684 template class elf::SymbolTableSection<ELF64BE>; 2685 2686 template class elf::VersionTableSection<ELF32LE>; 2687 template class elf::VersionTableSection<ELF32BE>; 2688 template class elf::VersionTableSection<ELF64LE>; 2689 template class elf::VersionTableSection<ELF64BE>; 2690 2691 template class elf::VersionNeedSection<ELF32LE>; 2692 template class elf::VersionNeedSection<ELF32BE>; 2693 template class elf::VersionNeedSection<ELF64LE>; 2694 template class elf::VersionNeedSection<ELF64BE>; 2695 2696 template class elf::VersionDefinitionSection<ELF32LE>; 2697 template class elf::VersionDefinitionSection<ELF32BE>; 2698 template class elf::VersionDefinitionSection<ELF64LE>; 2699 template class elf::VersionDefinitionSection<ELF64BE>; 2700