1 //===- SyntheticSections.cpp ----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains linker-synthesized sections. Currently, 10 // synthetic sections are created either output sections or input sections, 11 // but we are rewriting code so that all synthetic sections are created as 12 // input sections. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "SyntheticSections.h" 17 #include "Config.h" 18 #include "InputFiles.h" 19 #include "LinkerScript.h" 20 #include "OutputSections.h" 21 #include "SymbolTable.h" 22 #include "Symbols.h" 23 #include "Target.h" 24 #include "Writer.h" 25 #include "lld/Common/ErrorHandler.h" 26 #include "lld/Common/Memory.h" 27 #include "lld/Common/Strings.h" 28 #include "lld/Common/Threads.h" 29 #include "lld/Common/Version.h" 30 #include "llvm/ADT/SetOperations.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/BinaryFormat/Dwarf.h" 33 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h" 34 #include "llvm/Object/ELFObjectFile.h" 35 #include "llvm/Support/Compression.h" 36 #include "llvm/Support/Endian.h" 37 #include "llvm/Support/LEB128.h" 38 #include "llvm/Support/MD5.h" 39 #include <cstdlib> 40 #include <thread> 41 42 using namespace llvm; 43 using namespace llvm::dwarf; 44 using namespace llvm::ELF; 45 using namespace llvm::object; 46 using namespace llvm::support; 47 48 using namespace lld; 49 using namespace lld::elf; 50 51 using llvm::support::endian::read32le; 52 using llvm::support::endian::write32le; 53 using llvm::support::endian::write64le; 54 55 constexpr size_t MergeNoTailSection::NumShards; 56 57 static uint64_t readUint(uint8_t *Buf) { 58 return Config->Is64 ? read64(Buf) : read32(Buf); 59 } 60 61 static void writeUint(uint8_t *Buf, uint64_t Val) { 62 if (Config->Is64) 63 write64(Buf, Val); 64 else 65 write32(Buf, Val); 66 } 67 68 // Returns an LLD version string. 69 static ArrayRef<uint8_t> getVersion() { 70 // Check LLD_VERSION first for ease of testing. 71 // You can get consistent output by using the environment variable. 72 // This is only for testing. 73 StringRef S = getenv("LLD_VERSION"); 74 if (S.empty()) 75 S = Saver.save(Twine("Linker: ") + getLLDVersion()); 76 77 // +1 to include the terminating '\0'. 78 return {(const uint8_t *)S.data(), S.size() + 1}; 79 } 80 81 // Creates a .comment section containing LLD version info. 82 // With this feature, you can identify LLD-generated binaries easily 83 // by "readelf --string-dump .comment <file>". 84 // The returned object is a mergeable string section. 85 MergeInputSection *elf::createCommentSection() { 86 return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1, 87 getVersion(), ".comment"); 88 } 89 90 // .MIPS.abiflags section. 91 template <class ELFT> 92 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags) 93 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"), 94 Flags(Flags) { 95 this->Entsize = sizeof(Elf_Mips_ABIFlags); 96 } 97 98 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) { 99 memcpy(Buf, &Flags, sizeof(Flags)); 100 } 101 102 template <class ELFT> 103 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() { 104 Elf_Mips_ABIFlags Flags = {}; 105 bool Create = false; 106 107 for (InputSectionBase *Sec : InputSections) { 108 if (Sec->Type != SHT_MIPS_ABIFLAGS) 109 continue; 110 Sec->Live = false; 111 Create = true; 112 113 std::string Filename = toString(Sec->File); 114 const size_t Size = Sec->data().size(); 115 // Older version of BFD (such as the default FreeBSD linker) concatenate 116 // .MIPS.abiflags instead of merging. To allow for this case (or potential 117 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags 118 if (Size < sizeof(Elf_Mips_ABIFlags)) { 119 error(Filename + ": invalid size of .MIPS.abiflags section: got " + 120 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags))); 121 return nullptr; 122 } 123 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data()); 124 if (S->version != 0) { 125 error(Filename + ": unexpected .MIPS.abiflags version " + 126 Twine(S->version)); 127 return nullptr; 128 } 129 130 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just 131 // select the highest number of ISA/Rev/Ext. 132 Flags.isa_level = std::max(Flags.isa_level, S->isa_level); 133 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev); 134 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext); 135 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size); 136 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size); 137 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size); 138 Flags.ases |= S->ases; 139 Flags.flags1 |= S->flags1; 140 Flags.flags2 |= S->flags2; 141 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename); 142 }; 143 144 if (Create) 145 return make<MipsAbiFlagsSection<ELFT>>(Flags); 146 return nullptr; 147 } 148 149 // .MIPS.options section. 150 template <class ELFT> 151 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo) 152 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"), 153 Reginfo(Reginfo) { 154 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo); 155 } 156 157 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) { 158 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf); 159 Options->kind = ODK_REGINFO; 160 Options->size = getSize(); 161 162 if (!Config->Relocatable) 163 Reginfo.ri_gp_value = In.MipsGot->getGp(); 164 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo)); 165 } 166 167 template <class ELFT> 168 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() { 169 // N64 ABI only. 170 if (!ELFT::Is64Bits) 171 return nullptr; 172 173 std::vector<InputSectionBase *> Sections; 174 for (InputSectionBase *Sec : InputSections) 175 if (Sec->Type == SHT_MIPS_OPTIONS) 176 Sections.push_back(Sec); 177 178 if (Sections.empty()) 179 return nullptr; 180 181 Elf_Mips_RegInfo Reginfo = {}; 182 for (InputSectionBase *Sec : Sections) { 183 Sec->Live = false; 184 185 std::string Filename = toString(Sec->File); 186 ArrayRef<uint8_t> D = Sec->data(); 187 188 while (!D.empty()) { 189 if (D.size() < sizeof(Elf_Mips_Options)) { 190 error(Filename + ": invalid size of .MIPS.options section"); 191 break; 192 } 193 194 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data()); 195 if (Opt->kind == ODK_REGINFO) { 196 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask; 197 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value; 198 break; 199 } 200 201 if (!Opt->size) 202 fatal(Filename + ": zero option descriptor size"); 203 D = D.slice(Opt->size); 204 } 205 }; 206 207 return make<MipsOptionsSection<ELFT>>(Reginfo); 208 } 209 210 // MIPS .reginfo section. 211 template <class ELFT> 212 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo) 213 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"), 214 Reginfo(Reginfo) { 215 this->Entsize = sizeof(Elf_Mips_RegInfo); 216 } 217 218 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) { 219 if (!Config->Relocatable) 220 Reginfo.ri_gp_value = In.MipsGot->getGp(); 221 memcpy(Buf, &Reginfo, sizeof(Reginfo)); 222 } 223 224 template <class ELFT> 225 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() { 226 // Section should be alive for O32 and N32 ABIs only. 227 if (ELFT::Is64Bits) 228 return nullptr; 229 230 std::vector<InputSectionBase *> Sections; 231 for (InputSectionBase *Sec : InputSections) 232 if (Sec->Type == SHT_MIPS_REGINFO) 233 Sections.push_back(Sec); 234 235 if (Sections.empty()) 236 return nullptr; 237 238 Elf_Mips_RegInfo Reginfo = {}; 239 for (InputSectionBase *Sec : Sections) { 240 Sec->Live = false; 241 242 if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) { 243 error(toString(Sec->File) + ": invalid size of .reginfo section"); 244 return nullptr; 245 } 246 247 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data()); 248 Reginfo.ri_gprmask |= R->ri_gprmask; 249 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value; 250 }; 251 252 return make<MipsReginfoSection<ELFT>>(Reginfo); 253 } 254 255 InputSection *elf::createInterpSection() { 256 // StringSaver guarantees that the returned string ends with '\0'. 257 StringRef S = Saver.save(Config->DynamicLinker); 258 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1}; 259 260 auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents, 261 ".interp"); 262 Sec->Live = true; 263 return Sec; 264 } 265 266 Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, 267 uint64_t Size, InputSectionBase &Section) { 268 auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type, 269 Value, Size, &Section); 270 if (In.SymTab) 271 In.SymTab->addSymbol(S); 272 return S; 273 } 274 275 static size_t getHashSize() { 276 switch (Config->BuildId) { 277 case BuildIdKind::Fast: 278 return 8; 279 case BuildIdKind::Md5: 280 case BuildIdKind::Uuid: 281 return 16; 282 case BuildIdKind::Sha1: 283 return 20; 284 case BuildIdKind::Hexstring: 285 return Config->BuildIdVector.size(); 286 default: 287 llvm_unreachable("unknown BuildIdKind"); 288 } 289 } 290 291 BuildIdSection::BuildIdSection() 292 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"), 293 HashSize(getHashSize()) {} 294 295 void BuildIdSection::writeTo(uint8_t *Buf) { 296 write32(Buf, 4); // Name size 297 write32(Buf + 4, HashSize); // Content size 298 write32(Buf + 8, NT_GNU_BUILD_ID); // Type 299 memcpy(Buf + 12, "GNU", 4); // Name string 300 HashBuf = Buf + 16; 301 } 302 303 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) { 304 assert(Buf.size() == HashSize); 305 memcpy(HashBuf, Buf.data(), HashSize); 306 } 307 308 BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment) 309 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) { 310 this->Bss = true; 311 this->Size = Size; 312 } 313 314 EhFrameSection::EhFrameSection() 315 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {} 316 317 // Search for an existing CIE record or create a new one. 318 // CIE records from input object files are uniquified by their contents 319 // and where their relocations point to. 320 template <class ELFT, class RelTy> 321 CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) { 322 Symbol *Personality = nullptr; 323 unsigned FirstRelI = Cie.FirstRelocation; 324 if (FirstRelI != (unsigned)-1) 325 Personality = 326 &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]); 327 328 // Search for an existing CIE by CIE contents/relocation target pair. 329 CieRecord *&Rec = CieMap[{Cie.data(), Personality}]; 330 331 // If not found, create a new one. 332 if (!Rec) { 333 Rec = make<CieRecord>(); 334 Rec->Cie = &Cie; 335 CieRecords.push_back(Rec); 336 } 337 return Rec; 338 } 339 340 // There is one FDE per function. Returns true if a given FDE 341 // points to a live function. 342 template <class ELFT, class RelTy> 343 bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) { 344 auto *Sec = cast<EhInputSection>(Fde.Sec); 345 unsigned FirstRelI = Fde.FirstRelocation; 346 347 // An FDE should point to some function because FDEs are to describe 348 // functions. That's however not always the case due to an issue of 349 // ld.gold with -r. ld.gold may discard only functions and leave their 350 // corresponding FDEs, which results in creating bad .eh_frame sections. 351 // To deal with that, we ignore such FDEs. 352 if (FirstRelI == (unsigned)-1) 353 return false; 354 355 const RelTy &Rel = Rels[FirstRelI]; 356 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel); 357 358 // FDEs for garbage-collected or merged-by-ICF sections are dead. 359 if (auto *D = dyn_cast<Defined>(&B)) 360 if (SectionBase *Sec = D->Section) 361 return Sec->Live; 362 return false; 363 } 364 365 // .eh_frame is a sequence of CIE or FDE records. In general, there 366 // is one CIE record per input object file which is followed by 367 // a list of FDEs. This function searches an existing CIE or create a new 368 // one and associates FDEs to the CIE. 369 template <class ELFT, class RelTy> 370 void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) { 371 OffsetToCie.clear(); 372 for (EhSectionPiece &Piece : Sec->Pieces) { 373 // The empty record is the end marker. 374 if (Piece.Size == 4) 375 return; 376 377 size_t Offset = Piece.InputOff; 378 uint32_t ID = read32(Piece.data().data() + 4); 379 if (ID == 0) { 380 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels); 381 continue; 382 } 383 384 uint32_t CieOffset = Offset + 4 - ID; 385 CieRecord *Rec = OffsetToCie[CieOffset]; 386 if (!Rec) 387 fatal(toString(Sec) + ": invalid CIE reference"); 388 389 if (!isFdeLive<ELFT>(Piece, Rels)) 390 continue; 391 Rec->Fdes.push_back(&Piece); 392 NumFdes++; 393 } 394 } 395 396 template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) { 397 auto *Sec = cast<EhInputSection>(C); 398 Sec->Parent = this; 399 400 Alignment = std::max(Alignment, Sec->Alignment); 401 Sections.push_back(Sec); 402 403 for (auto *DS : Sec->DependentSections) 404 DependentSections.push_back(DS); 405 406 if (Sec->Pieces.empty()) 407 return; 408 409 if (Sec->AreRelocsRela) 410 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>()); 411 else 412 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>()); 413 } 414 415 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) { 416 memcpy(Buf, D.data(), D.size()); 417 418 size_t Aligned = alignTo(D.size(), Config->Wordsize); 419 420 // Zero-clear trailing padding if it exists. 421 memset(Buf + D.size(), 0, Aligned - D.size()); 422 423 // Fix the size field. -4 since size does not include the size field itself. 424 write32(Buf, Aligned - 4); 425 } 426 427 void EhFrameSection::finalizeContents() { 428 assert(!this->Size); // Not finalized. 429 size_t Off = 0; 430 for (CieRecord *Rec : CieRecords) { 431 Rec->Cie->OutputOff = Off; 432 Off += alignTo(Rec->Cie->Size, Config->Wordsize); 433 434 for (EhSectionPiece *Fde : Rec->Fdes) { 435 Fde->OutputOff = Off; 436 Off += alignTo(Fde->Size, Config->Wordsize); 437 } 438 } 439 440 // The LSB standard does not allow a .eh_frame section with zero 441 // Call Frame Information records. glibc unwind-dw2-fde.c 442 // classify_object_over_fdes expects there is a CIE record length 0 as a 443 // terminator. Thus we add one unconditionally. 444 Off += 4; 445 446 this->Size = Off; 447 } 448 449 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table 450 // to get an FDE from an address to which FDE is applied. This function 451 // returns a list of such pairs. 452 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const { 453 uint8_t *Buf = Out::BufferStart + getParent()->Offset + OutSecOff; 454 std::vector<FdeData> Ret; 455 456 uint64_t VA = In.EhFrameHdr->getVA(); 457 for (CieRecord *Rec : CieRecords) { 458 uint8_t Enc = getFdeEncoding(Rec->Cie); 459 for (EhSectionPiece *Fde : Rec->Fdes) { 460 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc); 461 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff; 462 if (!isInt<32>(Pc - VA)) 463 fatal(toString(Fde->Sec) + ": PC offset is too large: 0x" + 464 Twine::utohexstr(Pc - VA)); 465 Ret.push_back({uint32_t(Pc - VA), uint32_t(FdeVA - VA)}); 466 } 467 } 468 469 // Sort the FDE list by their PC and uniqueify. Usually there is only 470 // one FDE for a PC (i.e. function), but if ICF merges two functions 471 // into one, there can be more than one FDEs pointing to the address. 472 auto Less = [](const FdeData &A, const FdeData &B) { 473 return A.PcRel < B.PcRel; 474 }; 475 llvm::stable_sort(Ret, Less); 476 auto Eq = [](const FdeData &A, const FdeData &B) { 477 return A.PcRel == B.PcRel; 478 }; 479 Ret.erase(std::unique(Ret.begin(), Ret.end(), Eq), Ret.end()); 480 481 return Ret; 482 } 483 484 static uint64_t readFdeAddr(uint8_t *Buf, int Size) { 485 switch (Size) { 486 case DW_EH_PE_udata2: 487 return read16(Buf); 488 case DW_EH_PE_sdata2: 489 return (int16_t)read16(Buf); 490 case DW_EH_PE_udata4: 491 return read32(Buf); 492 case DW_EH_PE_sdata4: 493 return (int32_t)read32(Buf); 494 case DW_EH_PE_udata8: 495 case DW_EH_PE_sdata8: 496 return read64(Buf); 497 case DW_EH_PE_absptr: 498 return readUint(Buf); 499 } 500 fatal("unknown FDE size encoding"); 501 } 502 503 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to. 504 // We need it to create .eh_frame_hdr section. 505 uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff, 506 uint8_t Enc) const { 507 // The starting address to which this FDE applies is 508 // stored at FDE + 8 byte. 509 size_t Off = FdeOff + 8; 510 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0xf); 511 if ((Enc & 0x70) == DW_EH_PE_absptr) 512 return Addr; 513 if ((Enc & 0x70) == DW_EH_PE_pcrel) 514 return Addr + getParent()->Addr + Off; 515 fatal("unknown FDE size relative encoding"); 516 } 517 518 void EhFrameSection::writeTo(uint8_t *Buf) { 519 // Write CIE and FDE records. 520 for (CieRecord *Rec : CieRecords) { 521 size_t CieOffset = Rec->Cie->OutputOff; 522 writeCieFde(Buf + CieOffset, Rec->Cie->data()); 523 524 for (EhSectionPiece *Fde : Rec->Fdes) { 525 size_t Off = Fde->OutputOff; 526 writeCieFde(Buf + Off, Fde->data()); 527 528 // FDE's second word should have the offset to an associated CIE. 529 // Write it. 530 write32(Buf + Off + 4, Off + 4 - CieOffset); 531 } 532 } 533 534 // Apply relocations. .eh_frame section contents are not contiguous 535 // in the output buffer, but relocateAlloc() still works because 536 // getOffset() takes care of discontiguous section pieces. 537 for (EhInputSection *S : Sections) 538 S->relocateAlloc(Buf, nullptr); 539 540 if (In.EhFrameHdr && In.EhFrameHdr->getParent()) 541 In.EhFrameHdr->write(); 542 } 543 544 GotSection::GotSection() 545 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 546 Target->GotEntrySize, ".got") { 547 // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the 548 // .got. If there are no references to .TOC. in the symbol table, 549 // ElfSym::GlobalOffsetTable will not be defined and we won't need to save 550 // .TOC. in the .got. When it is defined, we increase NumEntries by the number 551 // of entries used to emit ElfSym::GlobalOffsetTable. 552 if (ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt) 553 NumEntries += Target->GotHeaderEntriesNum; 554 } 555 556 void GotSection::addEntry(Symbol &Sym) { 557 Sym.GotIndex = NumEntries; 558 ++NumEntries; 559 } 560 561 bool GotSection::addDynTlsEntry(Symbol &Sym) { 562 if (Sym.GlobalDynIndex != -1U) 563 return false; 564 Sym.GlobalDynIndex = NumEntries; 565 // Global Dynamic TLS entries take two GOT slots. 566 NumEntries += 2; 567 return true; 568 } 569 570 // Reserves TLS entries for a TLS module ID and a TLS block offset. 571 // In total it takes two GOT slots. 572 bool GotSection::addTlsIndex() { 573 if (TlsIndexOff != uint32_t(-1)) 574 return false; 575 TlsIndexOff = NumEntries * Config->Wordsize; 576 NumEntries += 2; 577 return true; 578 } 579 580 uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const { 581 return this->getVA() + B.GlobalDynIndex * Config->Wordsize; 582 } 583 584 uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const { 585 return B.GlobalDynIndex * Config->Wordsize; 586 } 587 588 void GotSection::finalizeContents() { 589 Size = NumEntries * Config->Wordsize; 590 } 591 592 bool GotSection::isNeeded() const { 593 // We need to emit a GOT even if it's empty if there's a relocation that is 594 // relative to GOT(such as GOTOFFREL). 595 return NumEntries || HasGotOffRel; 596 } 597 598 void GotSection::writeTo(uint8_t *Buf) { 599 // Buf points to the start of this section's buffer, 600 // whereas InputSectionBase::relocateAlloc() expects its argument 601 // to point to the start of the output section. 602 Target->writeGotHeader(Buf); 603 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size); 604 } 605 606 static uint64_t getMipsPageAddr(uint64_t Addr) { 607 return (Addr + 0x8000) & ~0xffff; 608 } 609 610 static uint64_t getMipsPageCount(uint64_t Size) { 611 return (Size + 0xfffe) / 0xffff + 1; 612 } 613 614 MipsGotSection::MipsGotSection() 615 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16, 616 ".got") {} 617 618 void MipsGotSection::addEntry(InputFile &File, Symbol &Sym, int64_t Addend, 619 RelExpr Expr) { 620 FileGot &G = getGot(File); 621 if (Expr == R_MIPS_GOT_LOCAL_PAGE) { 622 if (const OutputSection *OS = Sym.getOutputSection()) 623 G.PagesMap.insert({OS, {}}); 624 else 625 G.Local16.insert({{nullptr, getMipsPageAddr(Sym.getVA(Addend))}, 0}); 626 } else if (Sym.isTls()) 627 G.Tls.insert({&Sym, 0}); 628 else if (Sym.IsPreemptible && Expr == R_ABS) 629 G.Relocs.insert({&Sym, 0}); 630 else if (Sym.IsPreemptible) 631 G.Global.insert({&Sym, 0}); 632 else if (Expr == R_MIPS_GOT_OFF32) 633 G.Local32.insert({{&Sym, Addend}, 0}); 634 else 635 G.Local16.insert({{&Sym, Addend}, 0}); 636 } 637 638 void MipsGotSection::addDynTlsEntry(InputFile &File, Symbol &Sym) { 639 getGot(File).DynTlsSymbols.insert({&Sym, 0}); 640 } 641 642 void MipsGotSection::addTlsIndex(InputFile &File) { 643 getGot(File).DynTlsSymbols.insert({nullptr, 0}); 644 } 645 646 size_t MipsGotSection::FileGot::getEntriesNum() const { 647 return getPageEntriesNum() + Local16.size() + Global.size() + Relocs.size() + 648 Tls.size() + DynTlsSymbols.size() * 2; 649 } 650 651 size_t MipsGotSection::FileGot::getPageEntriesNum() const { 652 size_t Num = 0; 653 for (const std::pair<const OutputSection *, FileGot::PageBlock> &P : PagesMap) 654 Num += P.second.Count; 655 return Num; 656 } 657 658 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const { 659 size_t Count = getPageEntriesNum() + Local16.size() + Global.size(); 660 // If there are relocation-only entries in the GOT, TLS entries 661 // are allocated after them. TLS entries should be addressable 662 // by 16-bit index so count both reloc-only and TLS entries. 663 if (!Tls.empty() || !DynTlsSymbols.empty()) 664 Count += Relocs.size() + Tls.size() + DynTlsSymbols.size() * 2; 665 return Count; 666 } 667 668 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &F) { 669 if (!F.MipsGotIndex.hasValue()) { 670 Gots.emplace_back(); 671 Gots.back().File = &F; 672 F.MipsGotIndex = Gots.size() - 1; 673 } 674 return Gots[*F.MipsGotIndex]; 675 } 676 677 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *F, 678 const Symbol &Sym, 679 int64_t Addend) const { 680 const FileGot &G = Gots[*F->MipsGotIndex]; 681 uint64_t Index = 0; 682 if (const OutputSection *OutSec = Sym.getOutputSection()) { 683 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr); 684 uint64_t SymAddr = getMipsPageAddr(Sym.getVA(Addend)); 685 Index = G.PagesMap.lookup(OutSec).FirstIndex + (SymAddr - SecAddr) / 0xffff; 686 } else { 687 Index = G.Local16.lookup({nullptr, getMipsPageAddr(Sym.getVA(Addend))}); 688 } 689 return Index * Config->Wordsize; 690 } 691 692 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *F, const Symbol &S, 693 int64_t Addend) const { 694 const FileGot &G = Gots[*F->MipsGotIndex]; 695 Symbol *Sym = const_cast<Symbol *>(&S); 696 if (Sym->isTls()) 697 return G.Tls.lookup(Sym) * Config->Wordsize; 698 if (Sym->IsPreemptible) 699 return G.Global.lookup(Sym) * Config->Wordsize; 700 return G.Local16.lookup({Sym, Addend}) * Config->Wordsize; 701 } 702 703 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *F) const { 704 const FileGot &G = Gots[*F->MipsGotIndex]; 705 return G.DynTlsSymbols.lookup(nullptr) * Config->Wordsize; 706 } 707 708 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *F, 709 const Symbol &S) const { 710 const FileGot &G = Gots[*F->MipsGotIndex]; 711 Symbol *Sym = const_cast<Symbol *>(&S); 712 return G.DynTlsSymbols.lookup(Sym) * Config->Wordsize; 713 } 714 715 const Symbol *MipsGotSection::getFirstGlobalEntry() const { 716 if (Gots.empty()) 717 return nullptr; 718 const FileGot &PrimGot = Gots.front(); 719 if (!PrimGot.Global.empty()) 720 return PrimGot.Global.front().first; 721 if (!PrimGot.Relocs.empty()) 722 return PrimGot.Relocs.front().first; 723 return nullptr; 724 } 725 726 unsigned MipsGotSection::getLocalEntriesNum() const { 727 if (Gots.empty()) 728 return HeaderEntriesNum; 729 return HeaderEntriesNum + Gots.front().getPageEntriesNum() + 730 Gots.front().Local16.size(); 731 } 732 733 bool MipsGotSection::tryMergeGots(FileGot &Dst, FileGot &Src, bool IsPrimary) { 734 FileGot Tmp = Dst; 735 set_union(Tmp.PagesMap, Src.PagesMap); 736 set_union(Tmp.Local16, Src.Local16); 737 set_union(Tmp.Global, Src.Global); 738 set_union(Tmp.Relocs, Src.Relocs); 739 set_union(Tmp.Tls, Src.Tls); 740 set_union(Tmp.DynTlsSymbols, Src.DynTlsSymbols); 741 742 size_t Count = IsPrimary ? HeaderEntriesNum : 0; 743 Count += Tmp.getIndexedEntriesNum(); 744 745 if (Count * Config->Wordsize > Config->MipsGotSize) 746 return false; 747 748 std::swap(Tmp, Dst); 749 return true; 750 } 751 752 void MipsGotSection::finalizeContents() { updateAllocSize(); } 753 754 bool MipsGotSection::updateAllocSize() { 755 Size = HeaderEntriesNum * Config->Wordsize; 756 for (const FileGot &G : Gots) 757 Size += G.getEntriesNum() * Config->Wordsize; 758 return false; 759 } 760 761 void MipsGotSection::build() { 762 if (Gots.empty()) 763 return; 764 765 std::vector<FileGot> MergedGots(1); 766 767 // For each GOT move non-preemptible symbols from the `Global` 768 // to `Local16` list. Preemptible symbol might become non-preemptible 769 // one if, for example, it gets a related copy relocation. 770 for (FileGot &Got : Gots) { 771 for (auto &P: Got.Global) 772 if (!P.first->IsPreemptible) 773 Got.Local16.insert({{P.first, 0}, 0}); 774 Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) { 775 return !P.first->IsPreemptible; 776 }); 777 } 778 779 // For each GOT remove "reloc-only" entry if there is "global" 780 // entry for the same symbol. And add local entries which indexed 781 // using 32-bit value at the end of 16-bit entries. 782 for (FileGot &Got : Gots) { 783 Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) { 784 return Got.Global.count(P.first); 785 }); 786 set_union(Got.Local16, Got.Local32); 787 Got.Local32.clear(); 788 } 789 790 // Evaluate number of "reloc-only" entries in the resulting GOT. 791 // To do that put all unique "reloc-only" and "global" entries 792 // from all GOTs to the future primary GOT. 793 FileGot *PrimGot = &MergedGots.front(); 794 for (FileGot &Got : Gots) { 795 set_union(PrimGot->Relocs, Got.Global); 796 set_union(PrimGot->Relocs, Got.Relocs); 797 Got.Relocs.clear(); 798 } 799 800 // Evaluate number of "page" entries in each GOT. 801 for (FileGot &Got : Gots) { 802 for (std::pair<const OutputSection *, FileGot::PageBlock> &P : 803 Got.PagesMap) { 804 const OutputSection *OS = P.first; 805 uint64_t SecSize = 0; 806 for (BaseCommand *Cmd : OS->SectionCommands) { 807 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd)) 808 for (InputSection *IS : ISD->Sections) { 809 uint64_t Off = alignTo(SecSize, IS->Alignment); 810 SecSize = Off + IS->getSize(); 811 } 812 } 813 P.second.Count = getMipsPageCount(SecSize); 814 } 815 } 816 817 // Merge GOTs. Try to join as much as possible GOTs but do not exceed 818 // maximum GOT size. At first, try to fill the primary GOT because 819 // the primary GOT can be accessed in the most effective way. If it 820 // is not possible, try to fill the last GOT in the list, and finally 821 // create a new GOT if both attempts failed. 822 for (FileGot &SrcGot : Gots) { 823 InputFile *File = SrcGot.File; 824 if (tryMergeGots(MergedGots.front(), SrcGot, true)) { 825 File->MipsGotIndex = 0; 826 } else { 827 // If this is the first time we failed to merge with the primary GOT, 828 // MergedGots.back() will also be the primary GOT. We must make sure not 829 // to try to merge again with IsPrimary=false, as otherwise, if the 830 // inputs are just right, we could allow the primary GOT to become 1 or 2 831 // words too big due to ignoring the header size. 832 if (MergedGots.size() == 1 || 833 !tryMergeGots(MergedGots.back(), SrcGot, false)) { 834 MergedGots.emplace_back(); 835 std::swap(MergedGots.back(), SrcGot); 836 } 837 File->MipsGotIndex = MergedGots.size() - 1; 838 } 839 } 840 std::swap(Gots, MergedGots); 841 842 // Reduce number of "reloc-only" entries in the primary GOT 843 // by substracting "global" entries exist in the primary GOT. 844 PrimGot = &Gots.front(); 845 PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) { 846 return PrimGot->Global.count(P.first); 847 }); 848 849 // Calculate indexes for each GOT entry. 850 size_t Index = HeaderEntriesNum; 851 for (FileGot &Got : Gots) { 852 Got.StartIndex = &Got == PrimGot ? 0 : Index; 853 for (std::pair<const OutputSection *, FileGot::PageBlock> &P : 854 Got.PagesMap) { 855 // For each output section referenced by GOT page relocations calculate 856 // and save into PagesMap an upper bound of MIPS GOT entries required 857 // to store page addresses of local symbols. We assume the worst case - 858 // each 64kb page of the output section has at least one GOT relocation 859 // against it. And take in account the case when the section intersects 860 // page boundaries. 861 P.second.FirstIndex = Index; 862 Index += P.second.Count; 863 } 864 for (auto &P: Got.Local16) 865 P.second = Index++; 866 for (auto &P: Got.Global) 867 P.second = Index++; 868 for (auto &P: Got.Relocs) 869 P.second = Index++; 870 for (auto &P: Got.Tls) 871 P.second = Index++; 872 for (auto &P: Got.DynTlsSymbols) { 873 P.second = Index; 874 Index += 2; 875 } 876 } 877 878 // Update Symbol::GotIndex field to use this 879 // value later in the `sortMipsSymbols` function. 880 for (auto &P : PrimGot->Global) 881 P.first->GotIndex = P.second; 882 for (auto &P : PrimGot->Relocs) 883 P.first->GotIndex = P.second; 884 885 // Create dynamic relocations. 886 for (FileGot &Got : Gots) { 887 // Create dynamic relocations for TLS entries. 888 for (std::pair<Symbol *, size_t> &P : Got.Tls) { 889 Symbol *S = P.first; 890 uint64_t Offset = P.second * Config->Wordsize; 891 if (S->IsPreemptible) 892 In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S); 893 } 894 for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) { 895 Symbol *S = P.first; 896 uint64_t Offset = P.second * Config->Wordsize; 897 if (S == nullptr) { 898 if (!Config->Pic) 899 continue; 900 In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S); 901 } else { 902 // When building a shared library we still need a dynamic relocation 903 // for the module index. Therefore only checking for 904 // S->IsPreemptible is not sufficient (this happens e.g. for 905 // thread-locals that have been marked as local through a linker script) 906 if (!S->IsPreemptible && !Config->Pic) 907 continue; 908 In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S); 909 // However, we can skip writing the TLS offset reloc for non-preemptible 910 // symbols since it is known even in shared libraries 911 if (!S->IsPreemptible) 912 continue; 913 Offset += Config->Wordsize; 914 In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S); 915 } 916 } 917 918 // Do not create dynamic relocations for non-TLS 919 // entries in the primary GOT. 920 if (&Got == PrimGot) 921 continue; 922 923 // Dynamic relocations for "global" entries. 924 for (const std::pair<Symbol *, size_t> &P : Got.Global) { 925 uint64_t Offset = P.second * Config->Wordsize; 926 In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first); 927 } 928 if (!Config->Pic) 929 continue; 930 // Dynamic relocations for "local" entries in case of PIC. 931 for (const std::pair<const OutputSection *, FileGot::PageBlock> &L : 932 Got.PagesMap) { 933 size_t PageCount = L.second.Count; 934 for (size_t PI = 0; PI < PageCount; ++PI) { 935 uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize; 936 In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first, 937 int64_t(PI * 0x10000)}); 938 } 939 } 940 for (const std::pair<GotEntry, size_t> &P : Got.Local16) { 941 uint64_t Offset = P.second * Config->Wordsize; 942 In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true, 943 P.first.first, P.first.second}); 944 } 945 } 946 } 947 948 bool MipsGotSection::isNeeded() const { 949 // We add the .got section to the result for dynamic MIPS target because 950 // its address and properties are mentioned in the .dynamic section. 951 return !Config->Relocatable; 952 } 953 954 uint64_t MipsGotSection::getGp(const InputFile *F) const { 955 // For files without related GOT or files refer a primary GOT 956 // returns "common" _gp value. For secondary GOTs calculate 957 // individual _gp values. 958 if (!F || !F->MipsGotIndex.hasValue() || *F->MipsGotIndex == 0) 959 return ElfSym::MipsGp->getVA(0); 960 return getVA() + Gots[*F->MipsGotIndex].StartIndex * Config->Wordsize + 961 0x7ff0; 962 } 963 964 void MipsGotSection::writeTo(uint8_t *Buf) { 965 // Set the MSB of the second GOT slot. This is not required by any 966 // MIPS ABI documentation, though. 967 // 968 // There is a comment in glibc saying that "The MSB of got[1] of a 969 // gnu object is set to identify gnu objects," and in GNU gold it 970 // says "the second entry will be used by some runtime loaders". 971 // But how this field is being used is unclear. 972 // 973 // We are not really willing to mimic other linkers behaviors 974 // without understanding why they do that, but because all files 975 // generated by GNU tools have this special GOT value, and because 976 // we've been doing this for years, it is probably a safe bet to 977 // keep doing this for now. We really need to revisit this to see 978 // if we had to do this. 979 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1)); 980 for (const FileGot &G : Gots) { 981 auto Write = [&](size_t I, const Symbol *S, int64_t A) { 982 uint64_t VA = A; 983 if (S) 984 VA = S->getVA(A); 985 writeUint(Buf + I * Config->Wordsize, VA); 986 }; 987 // Write 'page address' entries to the local part of the GOT. 988 for (const std::pair<const OutputSection *, FileGot::PageBlock> &L : 989 G.PagesMap) { 990 size_t PageCount = L.second.Count; 991 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr); 992 for (size_t PI = 0; PI < PageCount; ++PI) 993 Write(L.second.FirstIndex + PI, nullptr, FirstPageAddr + PI * 0x10000); 994 } 995 // Local, global, TLS, reloc-only entries. 996 // If TLS entry has a corresponding dynamic relocations, leave it 997 // initialized by zero. Write down adjusted TLS symbol's values otherwise. 998 // To calculate the adjustments use offsets for thread-local storage. 999 // https://www.linux-mips.org/wiki/NPTL 1000 for (const std::pair<GotEntry, size_t> &P : G.Local16) 1001 Write(P.second, P.first.first, P.first.second); 1002 // Write VA to the primary GOT only. For secondary GOTs that 1003 // will be done by REL32 dynamic relocations. 1004 if (&G == &Gots.front()) 1005 for (const std::pair<const Symbol *, size_t> &P : G.Global) 1006 Write(P.second, P.first, 0); 1007 for (const std::pair<Symbol *, size_t> &P : G.Relocs) 1008 Write(P.second, P.first, 0); 1009 for (const std::pair<Symbol *, size_t> &P : G.Tls) 1010 Write(P.second, P.first, P.first->IsPreemptible ? 0 : -0x7000); 1011 for (const std::pair<Symbol *, size_t> &P : G.DynTlsSymbols) { 1012 if (P.first == nullptr && !Config->Pic) 1013 Write(P.second, nullptr, 1); 1014 else if (P.first && !P.first->IsPreemptible) { 1015 // If we are emitting PIC code with relocations we mustn't write 1016 // anything to the GOT here. When using Elf_Rel relocations the value 1017 // one will be treated as an addend and will cause crashes at runtime 1018 if (!Config->Pic) 1019 Write(P.second, nullptr, 1); 1020 Write(P.second + 1, P.first, -0x8000); 1021 } 1022 } 1023 } 1024 } 1025 1026 // On PowerPC the .plt section is used to hold the table of function addresses 1027 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss 1028 // section. I don't know why we have a BSS style type for the section but it is 1029 // consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI. 1030 GotPltSection::GotPltSection() 1031 : SyntheticSection(SHF_ALLOC | SHF_WRITE, 1032 Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS, 1033 Target->GotPltEntrySize, 1034 Config->EMachine == EM_PPC64 ? ".plt" : ".got.plt") {} 1035 1036 void GotPltSection::addEntry(Symbol &Sym) { 1037 assert(Sym.PltIndex == Entries.size()); 1038 Entries.push_back(&Sym); 1039 } 1040 1041 size_t GotPltSection::getSize() const { 1042 return (Target->GotPltHeaderEntriesNum + Entries.size()) * 1043 Target->GotPltEntrySize; 1044 } 1045 1046 void GotPltSection::writeTo(uint8_t *Buf) { 1047 Target->writeGotPltHeader(Buf); 1048 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize; 1049 for (const Symbol *B : Entries) { 1050 Target->writeGotPlt(Buf, *B); 1051 Buf += Config->Wordsize; 1052 } 1053 } 1054 1055 bool GotPltSection::isNeeded() const { 1056 // We need to emit GOTPLT even if it's empty if there's a relocation relative 1057 // to it. 1058 return !Entries.empty() || HasGotPltOffRel; 1059 } 1060 1061 static StringRef getIgotPltName() { 1062 // On ARM the IgotPltSection is part of the GotSection. 1063 if (Config->EMachine == EM_ARM) 1064 return ".got"; 1065 1066 // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection 1067 // needs to be named the same. 1068 if (Config->EMachine == EM_PPC64) 1069 return ".plt"; 1070 1071 return ".got.plt"; 1072 } 1073 1074 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit 1075 // with the IgotPltSection. 1076 IgotPltSection::IgotPltSection() 1077 : SyntheticSection(SHF_ALLOC | SHF_WRITE, 1078 Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS, 1079 Target->GotPltEntrySize, getIgotPltName()) {} 1080 1081 void IgotPltSection::addEntry(Symbol &Sym) { 1082 assert(Sym.PltIndex == Entries.size()); 1083 Entries.push_back(&Sym); 1084 } 1085 1086 size_t IgotPltSection::getSize() const { 1087 return Entries.size() * Target->GotPltEntrySize; 1088 } 1089 1090 void IgotPltSection::writeTo(uint8_t *Buf) { 1091 for (const Symbol *B : Entries) { 1092 Target->writeIgotPlt(Buf, *B); 1093 Buf += Config->Wordsize; 1094 } 1095 } 1096 1097 StringTableSection::StringTableSection(StringRef Name, bool Dynamic) 1098 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name), 1099 Dynamic(Dynamic) { 1100 // ELF string tables start with a NUL byte. 1101 addString(""); 1102 } 1103 1104 // Adds a string to the string table. If HashIt is true we hash and check for 1105 // duplicates. It is optional because the name of global symbols are already 1106 // uniqued and hashing them again has a big cost for a small value: uniquing 1107 // them with some other string that happens to be the same. 1108 unsigned StringTableSection::addString(StringRef S, bool HashIt) { 1109 if (HashIt) { 1110 auto R = StringMap.insert(std::make_pair(S, this->Size)); 1111 if (!R.second) 1112 return R.first->second; 1113 } 1114 unsigned Ret = this->Size; 1115 this->Size = this->Size + S.size() + 1; 1116 Strings.push_back(S); 1117 return Ret; 1118 } 1119 1120 void StringTableSection::writeTo(uint8_t *Buf) { 1121 for (StringRef S : Strings) { 1122 memcpy(Buf, S.data(), S.size()); 1123 Buf[S.size()] = '\0'; 1124 Buf += S.size() + 1; 1125 } 1126 } 1127 1128 // Returns the number of version definition entries. Because the first entry 1129 // is for the version definition itself, it is the number of versioned symbols 1130 // plus one. Note that we don't support multiple versions yet. 1131 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; } 1132 1133 template <class ELFT> 1134 DynamicSection<ELFT>::DynamicSection() 1135 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize, 1136 ".dynamic") { 1137 this->Entsize = ELFT::Is64Bits ? 16 : 8; 1138 1139 // .dynamic section is not writable on MIPS and on Fuchsia OS 1140 // which passes -z rodynamic. 1141 // See "Special Section" in Chapter 4 in the following document: 1142 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1143 if (Config->EMachine == EM_MIPS || Config->ZRodynamic) 1144 this->Flags = SHF_ALLOC; 1145 } 1146 1147 template <class ELFT> 1148 void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) { 1149 Entries.push_back({Tag, Fn}); 1150 } 1151 1152 template <class ELFT> 1153 void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) { 1154 Entries.push_back({Tag, [=] { return Val; }}); 1155 } 1156 1157 template <class ELFT> 1158 void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) { 1159 Entries.push_back({Tag, [=] { return Sec->getVA(0); }}); 1160 } 1161 1162 template <class ELFT> 1163 void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) { 1164 size_t TagOffset = Entries.size() * Entsize; 1165 Entries.push_back( 1166 {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }}); 1167 } 1168 1169 template <class ELFT> 1170 void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) { 1171 Entries.push_back({Tag, [=] { return Sec->Addr; }}); 1172 } 1173 1174 template <class ELFT> 1175 void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) { 1176 Entries.push_back({Tag, [=] { return Sec->Size; }}); 1177 } 1178 1179 template <class ELFT> 1180 void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) { 1181 Entries.push_back({Tag, [=] { return Sym->getVA(); }}); 1182 } 1183 1184 // A Linker script may assign the RELA relocation sections to the same 1185 // output section. When this occurs we cannot just use the OutputSection 1186 // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to 1187 // overlap with the [DT_RELA, DT_RELA + DT_RELASZ). 1188 static uint64_t addPltRelSz() { 1189 size_t Size = In.RelaPlt->getSize(); 1190 if (In.RelaIplt->getParent() == In.RelaPlt->getParent() && 1191 In.RelaIplt->Name == In.RelaPlt->Name) 1192 Size += In.RelaIplt->getSize(); 1193 return Size; 1194 } 1195 1196 // Add remaining entries to complete .dynamic contents. 1197 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { 1198 for (StringRef S : Config->FilterList) 1199 addInt(DT_FILTER, In.DynStrTab->addString(S)); 1200 for (StringRef S : Config->AuxiliaryList) 1201 addInt(DT_AUXILIARY, In.DynStrTab->addString(S)); 1202 1203 if (!Config->Rpath.empty()) 1204 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, 1205 In.DynStrTab->addString(Config->Rpath)); 1206 1207 for (SharedFile *File : SharedFiles) 1208 if (File->IsNeeded) 1209 addInt(DT_NEEDED, In.DynStrTab->addString(File->SoName)); 1210 if (!Config->SoName.empty()) 1211 addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName)); 1212 1213 // Set DT_FLAGS and DT_FLAGS_1. 1214 uint32_t DtFlags = 0; 1215 uint32_t DtFlags1 = 0; 1216 if (Config->Bsymbolic) 1217 DtFlags |= DF_SYMBOLIC; 1218 if (Config->ZGlobal) 1219 DtFlags1 |= DF_1_GLOBAL; 1220 if (Config->ZInitfirst) 1221 DtFlags1 |= DF_1_INITFIRST; 1222 if (Config->ZInterpose) 1223 DtFlags1 |= DF_1_INTERPOSE; 1224 if (Config->ZNodefaultlib) 1225 DtFlags1 |= DF_1_NODEFLIB; 1226 if (Config->ZNodelete) 1227 DtFlags1 |= DF_1_NODELETE; 1228 if (Config->ZNodlopen) 1229 DtFlags1 |= DF_1_NOOPEN; 1230 if (Config->ZNow) { 1231 DtFlags |= DF_BIND_NOW; 1232 DtFlags1 |= DF_1_NOW; 1233 } 1234 if (Config->ZOrigin) { 1235 DtFlags |= DF_ORIGIN; 1236 DtFlags1 |= DF_1_ORIGIN; 1237 } 1238 if (!Config->ZText) 1239 DtFlags |= DF_TEXTREL; 1240 if (Config->HasStaticTlsModel) 1241 DtFlags |= DF_STATIC_TLS; 1242 1243 if (DtFlags) 1244 addInt(DT_FLAGS, DtFlags); 1245 if (DtFlags1) 1246 addInt(DT_FLAGS_1, DtFlags1); 1247 1248 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We 1249 // need it for each process, so we don't write it for DSOs. The loader writes 1250 // the pointer into this entry. 1251 // 1252 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some 1253 // systems (currently only Fuchsia OS) provide other means to give the 1254 // debugger this information. Such systems may choose make .dynamic read-only. 1255 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG. 1256 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic) 1257 addInt(DT_DEBUG, 0); 1258 1259 if (OutputSection *Sec = In.DynStrTab->getParent()) 1260 this->Link = Sec->SectionIndex; 1261 1262 if (In.RelaDyn->isNeeded()) { 1263 addInSec(In.RelaDyn->DynamicTag, In.RelaDyn); 1264 addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent()); 1265 1266 bool IsRela = Config->IsRela; 1267 addInt(IsRela ? DT_RELAENT : DT_RELENT, 1268 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)); 1269 1270 // MIPS dynamic loader does not support RELCOUNT tag. 1271 // The problem is in the tight relation between dynamic 1272 // relocations and GOT. So do not emit this tag on MIPS. 1273 if (Config->EMachine != EM_MIPS) { 1274 size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount(); 1275 if (Config->ZCombreloc && NumRelativeRels) 1276 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels); 1277 } 1278 } 1279 if (In.RelrDyn && !In.RelrDyn->Relocs.empty()) { 1280 addInSec(Config->UseAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR, 1281 In.RelrDyn); 1282 addSize(Config->UseAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ, 1283 In.RelrDyn->getParent()); 1284 addInt(Config->UseAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT, 1285 sizeof(Elf_Relr)); 1286 } 1287 // .rel[a].plt section usually consists of two parts, containing plt and 1288 // iplt relocations. It is possible to have only iplt relocations in the 1289 // output. In that case RelaPlt is empty and have zero offset, the same offset 1290 // as RelaIplt have. And we still want to emit proper dynamic tags for that 1291 // case, so here we always use RelaPlt as marker for the begining of 1292 // .rel[a].plt section. 1293 if (In.RelaPlt->getParent()->Live) { 1294 addInSec(DT_JMPREL, In.RelaPlt); 1295 Entries.push_back({DT_PLTRELSZ, addPltRelSz}); 1296 switch (Config->EMachine) { 1297 case EM_MIPS: 1298 addInSec(DT_MIPS_PLTGOT, In.GotPlt); 1299 break; 1300 case EM_SPARCV9: 1301 addInSec(DT_PLTGOT, In.Plt); 1302 break; 1303 default: 1304 addInSec(DT_PLTGOT, In.GotPlt); 1305 break; 1306 } 1307 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL); 1308 } 1309 1310 addInSec(DT_SYMTAB, In.DynSymTab); 1311 addInt(DT_SYMENT, sizeof(Elf_Sym)); 1312 addInSec(DT_STRTAB, In.DynStrTab); 1313 addInt(DT_STRSZ, In.DynStrTab->getSize()); 1314 if (!Config->ZText) 1315 addInt(DT_TEXTREL, 0); 1316 if (In.GnuHashTab) 1317 addInSec(DT_GNU_HASH, In.GnuHashTab); 1318 if (In.HashTab) 1319 addInSec(DT_HASH, In.HashTab); 1320 1321 if (Out::PreinitArray) { 1322 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray); 1323 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray); 1324 } 1325 if (Out::InitArray) { 1326 addOutSec(DT_INIT_ARRAY, Out::InitArray); 1327 addSize(DT_INIT_ARRAYSZ, Out::InitArray); 1328 } 1329 if (Out::FiniArray) { 1330 addOutSec(DT_FINI_ARRAY, Out::FiniArray); 1331 addSize(DT_FINI_ARRAYSZ, Out::FiniArray); 1332 } 1333 1334 if (Symbol *B = Symtab->find(Config->Init)) 1335 if (B->isDefined()) 1336 addSym(DT_INIT, B); 1337 if (Symbol *B = Symtab->find(Config->Fini)) 1338 if (B->isDefined()) 1339 addSym(DT_FINI, B); 1340 1341 bool HasVerNeed = SharedFile::VernauxNum != 0; 1342 if (HasVerNeed || In.VerDef) 1343 addInSec(DT_VERSYM, In.VerSym); 1344 if (In.VerDef) { 1345 addInSec(DT_VERDEF, In.VerDef); 1346 addInt(DT_VERDEFNUM, getVerDefNum()); 1347 } 1348 if (HasVerNeed) { 1349 addInSec(DT_VERNEED, In.VerNeed); 1350 unsigned NeedNum = 0; 1351 for (SharedFile *F : SharedFiles) 1352 if (!F->Vernauxs.empty()) 1353 ++NeedNum; 1354 addInt(DT_VERNEEDNUM, NeedNum); 1355 } 1356 1357 if (Config->EMachine == EM_MIPS) { 1358 addInt(DT_MIPS_RLD_VERSION, 1); 1359 addInt(DT_MIPS_FLAGS, RHF_NOTPOT); 1360 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase()); 1361 addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols()); 1362 1363 add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); }); 1364 1365 if (const Symbol *B = In.MipsGot->getFirstGlobalEntry()) 1366 addInt(DT_MIPS_GOTSYM, B->DynsymIndex); 1367 else 1368 addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols()); 1369 addInSec(DT_PLTGOT, In.MipsGot); 1370 if (In.MipsRldMap) { 1371 if (!Config->Pie) 1372 addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap); 1373 // Store the offset to the .rld_map section 1374 // relative to the address of the tag. 1375 addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap); 1376 } 1377 } 1378 1379 // Glink dynamic tag is required by the V2 abi if the plt section isn't empty. 1380 if (Config->EMachine == EM_PPC64 && In.Plt->isNeeded()) { 1381 // The Glink tag points to 32 bytes before the first lazy symbol resolution 1382 // stub, which starts directly after the header. 1383 Entries.push_back({DT_PPC64_GLINK, [=] { 1384 unsigned Offset = Target->PltHeaderSize - 32; 1385 return In.Plt->getVA(0) + Offset; 1386 }}); 1387 } 1388 1389 addInt(DT_NULL, 0); 1390 1391 getParent()->Link = this->Link; 1392 this->Size = Entries.size() * this->Entsize; 1393 } 1394 1395 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) { 1396 auto *P = reinterpret_cast<Elf_Dyn *>(Buf); 1397 1398 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) { 1399 P->d_tag = KV.first; 1400 P->d_un.d_val = KV.second(); 1401 ++P; 1402 } 1403 } 1404 1405 uint64_t DynamicReloc::getOffset() const { 1406 return InputSec->getVA(OffsetInSec); 1407 } 1408 1409 int64_t DynamicReloc::computeAddend() const { 1410 if (UseSymVA) 1411 return Sym->getVA(Addend); 1412 if (!OutputSec) 1413 return Addend; 1414 // See the comment in the DynamicReloc ctor. 1415 return getMipsPageAddr(OutputSec->Addr) + Addend; 1416 } 1417 1418 uint32_t DynamicReloc::getSymIndex() const { 1419 if (Sym && !UseSymVA) 1420 return Sym->DynsymIndex; 1421 return 0; 1422 } 1423 1424 RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type, 1425 int32_t DynamicTag, 1426 int32_t SizeDynamicTag) 1427 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name), 1428 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {} 1429 1430 void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS, 1431 uint64_t OffsetInSec, Symbol *Sym) { 1432 addReloc({DynType, IS, OffsetInSec, false, Sym, 0}); 1433 } 1434 1435 void RelocationBaseSection::addReloc(RelType DynType, 1436 InputSectionBase *InputSec, 1437 uint64_t OffsetInSec, Symbol *Sym, 1438 int64_t Addend, RelExpr Expr, 1439 RelType Type) { 1440 // Write the addends to the relocated address if required. We skip 1441 // it if the written value would be zero. 1442 if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0)) 1443 InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym}); 1444 addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend}); 1445 } 1446 1447 void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) { 1448 if (Reloc.Type == Target->RelativeRel) 1449 ++NumRelativeRelocs; 1450 Relocs.push_back(Reloc); 1451 } 1452 1453 void RelocationBaseSection::finalizeContents() { 1454 // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE 1455 // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that 1456 // case. 1457 if (In.DynSymTab && In.DynSymTab->getParent()) 1458 getParent()->Link = In.DynSymTab->getParent()->SectionIndex; 1459 else 1460 getParent()->Link = 0; 1461 1462 if (In.RelaPlt == this) 1463 getParent()->Info = In.GotPlt->getParent()->SectionIndex; 1464 if (In.RelaIplt == this) 1465 getParent()->Info = In.IgotPlt->getParent()->SectionIndex; 1466 } 1467 1468 RelrBaseSection::RelrBaseSection() 1469 : SyntheticSection(SHF_ALLOC, 1470 Config->UseAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR, 1471 Config->Wordsize, ".relr.dyn") {} 1472 1473 template <class ELFT> 1474 static void encodeDynamicReloc(typename ELFT::Rela *P, 1475 const DynamicReloc &Rel) { 1476 if (Config->IsRela) 1477 P->r_addend = Rel.computeAddend(); 1478 P->r_offset = Rel.getOffset(); 1479 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL); 1480 } 1481 1482 template <class ELFT> 1483 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort) 1484 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL, 1485 Config->IsRela ? DT_RELA : DT_REL, 1486 Config->IsRela ? DT_RELASZ : DT_RELSZ), 1487 Sort(Sort) { 1488 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1489 } 1490 1491 static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) { 1492 bool AIsRel = A.Type == Target->RelativeRel; 1493 bool BIsRel = B.Type == Target->RelativeRel; 1494 if (AIsRel != BIsRel) 1495 return AIsRel; 1496 return A.getSymIndex() < B.getSymIndex(); 1497 } 1498 1499 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { 1500 if (Sort) 1501 llvm::stable_sort(Relocs, compRelocations); 1502 1503 for (const DynamicReloc &Rel : Relocs) { 1504 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel); 1505 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1506 } 1507 } 1508 1509 template <class ELFT> 1510 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection( 1511 StringRef Name) 1512 : RelocationBaseSection( 1513 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL, 1514 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL, 1515 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) { 1516 this->Entsize = 1; 1517 } 1518 1519 template <class ELFT> 1520 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() { 1521 // This function computes the contents of an Android-format packed relocation 1522 // section. 1523 // 1524 // This format compresses relocations by using relocation groups to factor out 1525 // fields that are common between relocations and storing deltas from previous 1526 // relocations in SLEB128 format (which has a short representation for small 1527 // numbers). A good example of a relocation type with common fields is 1528 // R_*_RELATIVE, which is normally used to represent function pointers in 1529 // vtables. In the REL format, each relative relocation has the same r_info 1530 // field, and is only different from other relative relocations in terms of 1531 // the r_offset field. By sorting relocations by offset, grouping them by 1532 // r_info and representing each relocation with only the delta from the 1533 // previous offset, each 8-byte relocation can be compressed to as little as 1 1534 // byte (or less with run-length encoding). This relocation packer was able to 1535 // reduce the size of the relocation section in an Android Chromium DSO from 1536 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size. 1537 // 1538 // A relocation section consists of a header containing the literal bytes 1539 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two 1540 // elements are the total number of relocations in the section and an initial 1541 // r_offset value. The remaining elements define a sequence of relocation 1542 // groups. Each relocation group starts with a header consisting of the 1543 // following elements: 1544 // 1545 // - the number of relocations in the relocation group 1546 // - flags for the relocation group 1547 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta 1548 // for each relocation in the group. 1549 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info 1550 // field for each relocation in the group. 1551 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and 1552 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for 1553 // each relocation in the group. 1554 // 1555 // Following the relocation group header are descriptions of each of the 1556 // relocations in the group. They consist of the following elements: 1557 // 1558 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset 1559 // delta for this relocation. 1560 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info 1561 // field for this relocation. 1562 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and 1563 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for 1564 // this relocation. 1565 1566 size_t OldSize = RelocData.size(); 1567 1568 RelocData = {'A', 'P', 'S', '2'}; 1569 raw_svector_ostream OS(RelocData); 1570 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); }; 1571 1572 // The format header includes the number of relocations and the initial 1573 // offset (we set this to zero because the first relocation group will 1574 // perform the initial adjustment). 1575 Add(Relocs.size()); 1576 Add(0); 1577 1578 std::vector<Elf_Rela> Relatives, NonRelatives; 1579 1580 for (const DynamicReloc &Rel : Relocs) { 1581 Elf_Rela R; 1582 encodeDynamicReloc<ELFT>(&R, Rel); 1583 1584 if (R.getType(Config->IsMips64EL) == Target->RelativeRel) 1585 Relatives.push_back(R); 1586 else 1587 NonRelatives.push_back(R); 1588 } 1589 1590 llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) { 1591 return A.r_offset < B.r_offset; 1592 }); 1593 1594 // Try to find groups of relative relocations which are spaced one word 1595 // apart from one another. These generally correspond to vtable entries. The 1596 // format allows these groups to be encoded using a sort of run-length 1597 // encoding, but each group will cost 7 bytes in addition to the offset from 1598 // the previous group, so it is only profitable to do this for groups of 1599 // size 8 or larger. 1600 std::vector<Elf_Rela> UngroupedRelatives; 1601 std::vector<std::vector<Elf_Rela>> RelativeGroups; 1602 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) { 1603 std::vector<Elf_Rela> Group; 1604 do { 1605 Group.push_back(*I++); 1606 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset); 1607 1608 if (Group.size() < 8) 1609 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(), 1610 Group.end()); 1611 else 1612 RelativeGroups.emplace_back(std::move(Group)); 1613 } 1614 1615 unsigned HasAddendIfRela = 1616 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0; 1617 1618 uint64_t Offset = 0; 1619 uint64_t Addend = 0; 1620 1621 // Emit the run-length encoding for the groups of adjacent relative 1622 // relocations. Each group is represented using two groups in the packed 1623 // format. The first is used to set the current offset to the start of the 1624 // group (and also encodes the first relocation), and the second encodes the 1625 // remaining relocations. 1626 for (std::vector<Elf_Rela> &G : RelativeGroups) { 1627 // The first relocation in the group. 1628 Add(1); 1629 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | 1630 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1631 Add(G[0].r_offset - Offset); 1632 Add(Target->RelativeRel); 1633 if (Config->IsRela) { 1634 Add(G[0].r_addend - Addend); 1635 Addend = G[0].r_addend; 1636 } 1637 1638 // The remaining relocations. 1639 Add(G.size() - 1); 1640 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | 1641 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1642 Add(Config->Wordsize); 1643 Add(Target->RelativeRel); 1644 if (Config->IsRela) { 1645 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) { 1646 Add(I->r_addend - Addend); 1647 Addend = I->r_addend; 1648 } 1649 } 1650 1651 Offset = G.back().r_offset; 1652 } 1653 1654 // Now the ungrouped relatives. 1655 if (!UngroupedRelatives.empty()) { 1656 Add(UngroupedRelatives.size()); 1657 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); 1658 Add(Target->RelativeRel); 1659 for (Elf_Rela &R : UngroupedRelatives) { 1660 Add(R.r_offset - Offset); 1661 Offset = R.r_offset; 1662 if (Config->IsRela) { 1663 Add(R.r_addend - Addend); 1664 Addend = R.r_addend; 1665 } 1666 } 1667 } 1668 1669 // Finally the non-relative relocations. 1670 llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) { 1671 return A.r_offset < B.r_offset; 1672 }); 1673 if (!NonRelatives.empty()) { 1674 Add(NonRelatives.size()); 1675 Add(HasAddendIfRela); 1676 for (Elf_Rela &R : NonRelatives) { 1677 Add(R.r_offset - Offset); 1678 Offset = R.r_offset; 1679 Add(R.r_info); 1680 if (Config->IsRela) { 1681 Add(R.r_addend - Addend); 1682 Addend = R.r_addend; 1683 } 1684 } 1685 } 1686 1687 // Don't allow the section to shrink; otherwise the size of the section can 1688 // oscillate infinitely. 1689 if (RelocData.size() < OldSize) 1690 RelocData.append(OldSize - RelocData.size(), 0); 1691 1692 // Returns whether the section size changed. We need to keep recomputing both 1693 // section layout and the contents of this section until the size converges 1694 // because changing this section's size can affect section layout, which in 1695 // turn can affect the sizes of the LEB-encoded integers stored in this 1696 // section. 1697 return RelocData.size() != OldSize; 1698 } 1699 1700 template <class ELFT> RelrSection<ELFT>::RelrSection() { 1701 this->Entsize = Config->Wordsize; 1702 } 1703 1704 template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() { 1705 // This function computes the contents of an SHT_RELR packed relocation 1706 // section. 1707 // 1708 // Proposal for adding SHT_RELR sections to generic-abi is here: 1709 // https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg 1710 // 1711 // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks 1712 // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ] 1713 // 1714 // i.e. start with an address, followed by any number of bitmaps. The address 1715 // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63 1716 // relocations each, at subsequent offsets following the last address entry. 1717 // 1718 // The bitmap entries must have 1 in the least significant bit. The assumption 1719 // here is that an address cannot have 1 in lsb. Odd addresses are not 1720 // supported. 1721 // 1722 // Excluding the least significant bit in the bitmap, each non-zero bit in 1723 // the bitmap represents a relocation to be applied to a corresponding machine 1724 // word that follows the base address word. The second least significant bit 1725 // represents the machine word immediately following the initial address, and 1726 // each bit that follows represents the next word, in linear order. As such, 1727 // a single bitmap can encode up to 31 relocations in a 32-bit object, and 1728 // 63 relocations in a 64-bit object. 1729 // 1730 // This encoding has a couple of interesting properties: 1731 // 1. Looking at any entry, it is clear whether it's an address or a bitmap: 1732 // even means address, odd means bitmap. 1733 // 2. Just a simple list of addresses is a valid encoding. 1734 1735 size_t OldSize = RelrRelocs.size(); 1736 RelrRelocs.clear(); 1737 1738 // Same as Config->Wordsize but faster because this is a compile-time 1739 // constant. 1740 const size_t Wordsize = sizeof(typename ELFT::uint); 1741 1742 // Number of bits to use for the relocation offsets bitmap. 1743 // Must be either 63 or 31. 1744 const size_t NBits = Wordsize * 8 - 1; 1745 1746 // Get offsets for all relative relocations and sort them. 1747 std::vector<uint64_t> Offsets; 1748 for (const RelativeReloc &Rel : Relocs) 1749 Offsets.push_back(Rel.getOffset()); 1750 llvm::sort(Offsets); 1751 1752 // For each leading relocation, find following ones that can be folded 1753 // as a bitmap and fold them. 1754 for (size_t I = 0, E = Offsets.size(); I < E;) { 1755 // Add a leading relocation. 1756 RelrRelocs.push_back(Elf_Relr(Offsets[I])); 1757 uint64_t Base = Offsets[I] + Wordsize; 1758 ++I; 1759 1760 // Find foldable relocations to construct bitmaps. 1761 while (I < E) { 1762 uint64_t Bitmap = 0; 1763 1764 while (I < E) { 1765 uint64_t Delta = Offsets[I] - Base; 1766 1767 // If it is too far, it cannot be folded. 1768 if (Delta >= NBits * Wordsize) 1769 break; 1770 1771 // If it is not a multiple of wordsize away, it cannot be folded. 1772 if (Delta % Wordsize) 1773 break; 1774 1775 // Fold it. 1776 Bitmap |= 1ULL << (Delta / Wordsize); 1777 ++I; 1778 } 1779 1780 if (!Bitmap) 1781 break; 1782 1783 RelrRelocs.push_back(Elf_Relr((Bitmap << 1) | 1)); 1784 Base += NBits * Wordsize; 1785 } 1786 } 1787 1788 return RelrRelocs.size() != OldSize; 1789 } 1790 1791 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec) 1792 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0, 1793 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, 1794 Config->Wordsize, 1795 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"), 1796 StrTabSec(StrTabSec) {} 1797 1798 // Orders symbols according to their positions in the GOT, 1799 // in compliance with MIPS ABI rules. 1800 // See "Global Offset Table" in Chapter 5 in the following document 1801 // for detailed description: 1802 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1803 static bool sortMipsSymbols(const SymbolTableEntry &L, 1804 const SymbolTableEntry &R) { 1805 // Sort entries related to non-local preemptible symbols by GOT indexes. 1806 // All other entries go to the beginning of a dynsym in arbitrary order. 1807 if (L.Sym->isInGot() && R.Sym->isInGot()) 1808 return L.Sym->GotIndex < R.Sym->GotIndex; 1809 if (!L.Sym->isInGot() && !R.Sym->isInGot()) 1810 return false; 1811 return !L.Sym->isInGot(); 1812 } 1813 1814 void SymbolTableBaseSection::finalizeContents() { 1815 if (OutputSection *Sec = StrTabSec.getParent()) 1816 getParent()->Link = Sec->SectionIndex; 1817 1818 if (this->Type != SHT_DYNSYM) { 1819 sortSymTabSymbols(); 1820 return; 1821 } 1822 1823 // If it is a .dynsym, there should be no local symbols, but we need 1824 // to do a few things for the dynamic linker. 1825 1826 // Section's Info field has the index of the first non-local symbol. 1827 // Because the first symbol entry is a null entry, 1 is the first. 1828 getParent()->Info = 1; 1829 1830 if (In.GnuHashTab) { 1831 // NB: It also sorts Symbols to meet the GNU hash table requirements. 1832 In.GnuHashTab->addSymbols(Symbols); 1833 } else if (Config->EMachine == EM_MIPS) { 1834 llvm::stable_sort(Symbols, sortMipsSymbols); 1835 } 1836 1837 size_t I = 0; 1838 for (const SymbolTableEntry &S : Symbols) 1839 S.Sym->DynsymIndex = ++I; 1840 } 1841 1842 // The ELF spec requires that all local symbols precede global symbols, so we 1843 // sort symbol entries in this function. (For .dynsym, we don't do that because 1844 // symbols for dynamic linking are inherently all globals.) 1845 // 1846 // Aside from above, we put local symbols in groups starting with the STT_FILE 1847 // symbol. That is convenient for purpose of identifying where are local symbols 1848 // coming from. 1849 void SymbolTableBaseSection::sortSymTabSymbols() { 1850 // Move all local symbols before global symbols. 1851 auto E = std::stable_partition( 1852 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) { 1853 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL; 1854 }); 1855 size_t NumLocals = E - Symbols.begin(); 1856 getParent()->Info = NumLocals + 1; 1857 1858 // We want to group the local symbols by file. For that we rebuild the local 1859 // part of the symbols vector. We do not need to care about the STT_FILE 1860 // symbols, they are already naturally placed first in each group. That 1861 // happens because STT_FILE is always the first symbol in the object and hence 1862 // precede all other local symbols we add for a file. 1863 MapVector<InputFile *, std::vector<SymbolTableEntry>> Arr; 1864 for (const SymbolTableEntry &S : llvm::make_range(Symbols.begin(), E)) 1865 Arr[S.Sym->File].push_back(S); 1866 1867 auto I = Symbols.begin(); 1868 for (std::pair<InputFile *, std::vector<SymbolTableEntry>> &P : Arr) 1869 for (SymbolTableEntry &Entry : P.second) 1870 *I++ = Entry; 1871 } 1872 1873 void SymbolTableBaseSection::addSymbol(Symbol *B) { 1874 // Adding a local symbol to a .dynsym is a bug. 1875 assert(this->Type != SHT_DYNSYM || !B->isLocal()); 1876 1877 bool HashIt = B->isLocal(); 1878 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)}); 1879 } 1880 1881 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) { 1882 // Initializes symbol lookup tables lazily. This is used only 1883 // for -r or -emit-relocs. 1884 llvm::call_once(OnceFlag, [&] { 1885 SymbolIndexMap.reserve(Symbols.size()); 1886 size_t I = 0; 1887 for (const SymbolTableEntry &E : Symbols) { 1888 if (E.Sym->Type == STT_SECTION) 1889 SectionIndexMap[E.Sym->getOutputSection()] = ++I; 1890 else 1891 SymbolIndexMap[E.Sym] = ++I; 1892 } 1893 }); 1894 1895 // Section symbols are mapped based on their output sections 1896 // to maintain their semantics. 1897 if (Sym->Type == STT_SECTION) 1898 return SectionIndexMap.lookup(Sym->getOutputSection()); 1899 return SymbolIndexMap.lookup(Sym); 1900 } 1901 1902 template <class ELFT> 1903 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec) 1904 : SymbolTableBaseSection(StrTabSec) { 1905 this->Entsize = sizeof(Elf_Sym); 1906 } 1907 1908 static BssSection *getCommonSec(Symbol *Sym) { 1909 if (!Config->DefineCommon) 1910 if (auto *D = dyn_cast<Defined>(Sym)) 1911 return dyn_cast_or_null<BssSection>(D->Section); 1912 return nullptr; 1913 } 1914 1915 static uint32_t getSymSectionIndex(Symbol *Sym) { 1916 if (getCommonSec(Sym)) 1917 return SHN_COMMON; 1918 if (!isa<Defined>(Sym) || Sym->NeedsPltAddr) 1919 return SHN_UNDEF; 1920 if (const OutputSection *OS = Sym->getOutputSection()) 1921 return OS->SectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX 1922 : OS->SectionIndex; 1923 return SHN_ABS; 1924 } 1925 1926 // Write the internal symbol table contents to the output symbol table. 1927 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { 1928 // The first entry is a null entry as per the ELF spec. 1929 memset(Buf, 0, sizeof(Elf_Sym)); 1930 Buf += sizeof(Elf_Sym); 1931 1932 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1933 1934 for (SymbolTableEntry &Ent : Symbols) { 1935 Symbol *Sym = Ent.Sym; 1936 1937 // Set st_info and st_other. 1938 ESym->st_other = 0; 1939 if (Sym->isLocal()) { 1940 ESym->setBindingAndType(STB_LOCAL, Sym->Type); 1941 } else { 1942 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type); 1943 ESym->setVisibility(Sym->Visibility); 1944 } 1945 1946 // The 3 most significant bits of st_other are used by OpenPOWER ABI. 1947 // See getPPC64GlobalEntryToLocalEntryOffset() for more details. 1948 if (Config->EMachine == EM_PPC64) 1949 ESym->st_other |= Sym->StOther & 0xe0; 1950 1951 ESym->st_name = Ent.StrTabOffset; 1952 ESym->st_shndx = getSymSectionIndex(Ent.Sym); 1953 1954 // Copy symbol size if it is a defined symbol. st_size is not significant 1955 // for undefined symbols, so whether copying it or not is up to us if that's 1956 // the case. We'll leave it as zero because by not setting a value, we can 1957 // get the exact same outputs for two sets of input files that differ only 1958 // in undefined symbol size in DSOs. 1959 if (ESym->st_shndx == SHN_UNDEF) 1960 ESym->st_size = 0; 1961 else 1962 ESym->st_size = Sym->getSize(); 1963 1964 // st_value is usually an address of a symbol, but that has a 1965 // special meaining for uninstantiated common symbols (this can 1966 // occur if -r is given). 1967 if (BssSection *CommonSec = getCommonSec(Ent.Sym)) 1968 ESym->st_value = CommonSec->Alignment; 1969 else 1970 ESym->st_value = Sym->getVA(); 1971 1972 ++ESym; 1973 } 1974 1975 // On MIPS we need to mark symbol which has a PLT entry and requires 1976 // pointer equality by STO_MIPS_PLT flag. That is necessary to help 1977 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs. 1978 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt 1979 if (Config->EMachine == EM_MIPS) { 1980 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1981 1982 for (SymbolTableEntry &Ent : Symbols) { 1983 Symbol *Sym = Ent.Sym; 1984 if (Sym->isInPlt() && Sym->NeedsPltAddr) 1985 ESym->st_other |= STO_MIPS_PLT; 1986 if (isMicroMips()) { 1987 // We already set the less-significant bit for symbols 1988 // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT 1989 // records. That allows us to distinguish such symbols in 1990 // the `MIPS<ELFT>::relocateOne()` routine. Now we should 1991 // clear that bit for non-dynamic symbol table, so tools 1992 // like `objdump` will be able to deal with a correct 1993 // symbol position. 1994 if (Sym->isDefined() && 1995 ((Sym->StOther & STO_MIPS_MICROMIPS) || Sym->NeedsPltAddr)) { 1996 if (!StrTabSec.isDynamic()) 1997 ESym->st_value &= ~1; 1998 ESym->st_other |= STO_MIPS_MICROMIPS; 1999 } 2000 } 2001 if (Config->Relocatable) 2002 if (auto *D = dyn_cast<Defined>(Sym)) 2003 if (isMipsPIC<ELFT>(D)) 2004 ESym->st_other |= STO_MIPS_PIC; 2005 ++ESym; 2006 } 2007 } 2008 } 2009 2010 SymtabShndxSection::SymtabShndxSection() 2011 : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") { 2012 this->Entsize = 4; 2013 } 2014 2015 void SymtabShndxSection::writeTo(uint8_t *Buf) { 2016 // We write an array of 32 bit values, where each value has 1:1 association 2017 // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX, 2018 // we need to write actual index, otherwise, we must write SHN_UNDEF(0). 2019 Buf += 4; // Ignore .symtab[0] entry. 2020 for (const SymbolTableEntry &Entry : In.SymTab->getSymbols()) { 2021 if (getSymSectionIndex(Entry.Sym) == SHN_XINDEX) 2022 write32(Buf, Entry.Sym->getOutputSection()->SectionIndex); 2023 Buf += 4; 2024 } 2025 } 2026 2027 bool SymtabShndxSection::isNeeded() const { 2028 // SHT_SYMTAB can hold symbols with section indices values up to 2029 // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX 2030 // section. Problem is that we reveal the final section indices a bit too 2031 // late, and we do not know them here. For simplicity, we just always create 2032 // a .symtab_shndx section when the amount of output sections is huge. 2033 size_t Size = 0; 2034 for (BaseCommand *Base : Script->SectionCommands) 2035 if (isa<OutputSection>(Base)) 2036 ++Size; 2037 return Size >= SHN_LORESERVE; 2038 } 2039 2040 void SymtabShndxSection::finalizeContents() { 2041 getParent()->Link = In.SymTab->getParent()->SectionIndex; 2042 } 2043 2044 size_t SymtabShndxSection::getSize() const { 2045 return In.SymTab->getNumSymbols() * 4; 2046 } 2047 2048 // .hash and .gnu.hash sections contain on-disk hash tables that map 2049 // symbol names to their dynamic symbol table indices. Their purpose 2050 // is to help the dynamic linker resolve symbols quickly. If ELF files 2051 // don't have them, the dynamic linker has to do linear search on all 2052 // dynamic symbols, which makes programs slower. Therefore, a .hash 2053 // section is added to a DSO by default. A .gnu.hash is added if you 2054 // give the -hash-style=gnu or -hash-style=both option. 2055 // 2056 // The Unix semantics of resolving dynamic symbols is somewhat expensive. 2057 // Each ELF file has a list of DSOs that the ELF file depends on and a 2058 // list of dynamic symbols that need to be resolved from any of the 2059 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n) 2060 // where m is the number of DSOs and n is the number of dynamic 2061 // symbols. For modern large programs, both m and n are large. So 2062 // making each step faster by using hash tables substiantially 2063 // improves time to load programs. 2064 // 2065 // (Note that this is not the only way to design the shared library. 2066 // For instance, the Windows DLL takes a different approach. On 2067 // Windows, each dynamic symbol has a name of DLL from which the symbol 2068 // has to be resolved. That makes the cost of symbol resolution O(n). 2069 // This disables some hacky techniques you can use on Unix such as 2070 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.) 2071 // 2072 // Due to historical reasons, we have two different hash tables, .hash 2073 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new 2074 // and better version of .hash. .hash is just an on-disk hash table, but 2075 // .gnu.hash has a bloom filter in addition to a hash table to skip 2076 // DSOs very quickly. If you are sure that your dynamic linker knows 2077 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a 2078 // safe bet is to specify -hash-style=both for backward compatibilty. 2079 GnuHashTableSection::GnuHashTableSection() 2080 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") { 2081 } 2082 2083 void GnuHashTableSection::finalizeContents() { 2084 if (OutputSection *Sec = In.DynSymTab->getParent()) 2085 getParent()->Link = Sec->SectionIndex; 2086 2087 // Computes bloom filter size in word size. We want to allocate 12 2088 // bits for each symbol. It must be a power of two. 2089 if (Symbols.empty()) { 2090 MaskWords = 1; 2091 } else { 2092 uint64_t NumBits = Symbols.size() * 12; 2093 MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8)); 2094 } 2095 2096 Size = 16; // Header 2097 Size += Config->Wordsize * MaskWords; // Bloom filter 2098 Size += NBuckets * 4; // Hash buckets 2099 Size += Symbols.size() * 4; // Hash values 2100 } 2101 2102 void GnuHashTableSection::writeTo(uint8_t *Buf) { 2103 // The output buffer is not guaranteed to be zero-cleared because we pre- 2104 // fill executable sections with trap instructions. This is a precaution 2105 // for that case, which happens only when -no-rosegment is given. 2106 memset(Buf, 0, Size); 2107 2108 // Write a header. 2109 write32(Buf, NBuckets); 2110 write32(Buf + 4, In.DynSymTab->getNumSymbols() - Symbols.size()); 2111 write32(Buf + 8, MaskWords); 2112 write32(Buf + 12, Shift2); 2113 Buf += 16; 2114 2115 // Write a bloom filter and a hash table. 2116 writeBloomFilter(Buf); 2117 Buf += Config->Wordsize * MaskWords; 2118 writeHashTable(Buf); 2119 } 2120 2121 // This function writes a 2-bit bloom filter. This bloom filter alone 2122 // usually filters out 80% or more of all symbol lookups [1]. 2123 // The dynamic linker uses the hash table only when a symbol is not 2124 // filtered out by a bloom filter. 2125 // 2126 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2), 2127 // p.9, https://www.akkadia.org/drepper/dsohowto.pdf 2128 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) { 2129 unsigned C = Config->Is64 ? 64 : 32; 2130 for (const Entry &Sym : Symbols) { 2131 // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in 2132 // the word using bits [0:5] and [26:31]. 2133 size_t I = (Sym.Hash / C) & (MaskWords - 1); 2134 uint64_t Val = readUint(Buf + I * Config->Wordsize); 2135 Val |= uint64_t(1) << (Sym.Hash % C); 2136 Val |= uint64_t(1) << ((Sym.Hash >> Shift2) % C); 2137 writeUint(Buf + I * Config->Wordsize, Val); 2138 } 2139 } 2140 2141 void GnuHashTableSection::writeHashTable(uint8_t *Buf) { 2142 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf); 2143 uint32_t OldBucket = -1; 2144 uint32_t *Values = Buckets + NBuckets; 2145 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) { 2146 // Write a hash value. It represents a sequence of chains that share the 2147 // same hash modulo value. The last element of each chain is terminated by 2148 // LSB 1. 2149 uint32_t Hash = I->Hash; 2150 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx; 2151 Hash = IsLastInChain ? Hash | 1 : Hash & ~1; 2152 write32(Values++, Hash); 2153 2154 if (I->BucketIdx == OldBucket) 2155 continue; 2156 // Write a hash bucket. Hash buckets contain indices in the following hash 2157 // value table. 2158 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex); 2159 OldBucket = I->BucketIdx; 2160 } 2161 } 2162 2163 static uint32_t hashGnu(StringRef Name) { 2164 uint32_t H = 5381; 2165 for (uint8_t C : Name) 2166 H = (H << 5) + H + C; 2167 return H; 2168 } 2169 2170 // Add symbols to this symbol hash table. Note that this function 2171 // destructively sort a given vector -- which is needed because 2172 // GNU-style hash table places some sorting requirements. 2173 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) { 2174 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce 2175 // its type correctly. 2176 std::vector<SymbolTableEntry>::iterator Mid = 2177 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) { 2178 return !S.Sym->isDefined(); 2179 }); 2180 2181 // We chose load factor 4 for the on-disk hash table. For each hash 2182 // collision, the dynamic linker will compare a uint32_t hash value. 2183 // Since the integer comparison is quite fast, we believe we can 2184 // make the load factor even larger. 4 is just a conservative choice. 2185 // 2186 // Note that we don't want to create a zero-sized hash table because 2187 // Android loader as of 2018 doesn't like a .gnu.hash containing such 2188 // table. If that's the case, we create a hash table with one unused 2189 // dummy slot. 2190 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1); 2191 2192 if (Mid == V.end()) 2193 return; 2194 2195 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) { 2196 Symbol *B = Ent.Sym; 2197 uint32_t Hash = hashGnu(B->getName()); 2198 uint32_t BucketIdx = Hash % NBuckets; 2199 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx}); 2200 } 2201 2202 llvm::stable_sort(Symbols, [](const Entry &L, const Entry &R) { 2203 return L.BucketIdx < R.BucketIdx; 2204 }); 2205 2206 V.erase(Mid, V.end()); 2207 for (const Entry &Ent : Symbols) 2208 V.push_back({Ent.Sym, Ent.StrTabOffset}); 2209 } 2210 2211 HashTableSection::HashTableSection() 2212 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") { 2213 this->Entsize = 4; 2214 } 2215 2216 void HashTableSection::finalizeContents() { 2217 if (OutputSection *Sec = In.DynSymTab->getParent()) 2218 getParent()->Link = Sec->SectionIndex; 2219 2220 unsigned NumEntries = 2; // nbucket and nchain. 2221 NumEntries += In.DynSymTab->getNumSymbols(); // The chain entries. 2222 2223 // Create as many buckets as there are symbols. 2224 NumEntries += In.DynSymTab->getNumSymbols(); 2225 this->Size = NumEntries * 4; 2226 } 2227 2228 void HashTableSection::writeTo(uint8_t *Buf) { 2229 // See comment in GnuHashTableSection::writeTo. 2230 memset(Buf, 0, Size); 2231 2232 unsigned NumSymbols = In.DynSymTab->getNumSymbols(); 2233 2234 uint32_t *P = reinterpret_cast<uint32_t *>(Buf); 2235 write32(P++, NumSymbols); // nbucket 2236 write32(P++, NumSymbols); // nchain 2237 2238 uint32_t *Buckets = P; 2239 uint32_t *Chains = P + NumSymbols; 2240 2241 for (const SymbolTableEntry &S : In.DynSymTab->getSymbols()) { 2242 Symbol *Sym = S.Sym; 2243 StringRef Name = Sym->getName(); 2244 unsigned I = Sym->DynsymIndex; 2245 uint32_t Hash = hashSysV(Name) % NumSymbols; 2246 Chains[I] = Buckets[Hash]; 2247 write32(Buckets + Hash, I); 2248 } 2249 } 2250 2251 // On PowerPC64 the lazy symbol resolvers go into the `global linkage table` 2252 // in the .glink section, rather then the typical .plt section. 2253 PltSection::PltSection(bool IsIplt) 2254 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, 2255 Config->EMachine == EM_PPC64 ? ".glink" : ".plt"), 2256 HeaderSize(!IsIplt || Config->ZRetpolineplt ? Target->PltHeaderSize : 0), 2257 IsIplt(IsIplt) { 2258 // The PLT needs to be writable on SPARC as the dynamic linker will 2259 // modify the instructions in the PLT entries. 2260 if (Config->EMachine == EM_SPARCV9) 2261 this->Flags |= SHF_WRITE; 2262 } 2263 2264 void PltSection::writeTo(uint8_t *Buf) { 2265 // At beginning of PLT or retpoline IPLT, we have code to call the dynamic 2266 // linker to resolve dynsyms at runtime. Write such code. 2267 if (HeaderSize) 2268 Target->writePltHeader(Buf); 2269 size_t Off = HeaderSize; 2270 2271 RelocationBaseSection *RelSec = IsIplt ? In.RelaIplt : In.RelaPlt; 2272 2273 // The IPlt is immediately after the Plt, account for this in RelOff 2274 size_t PltOff = IsIplt ? In.Plt->getSize() : 0; 2275 2276 for (size_t I = 0, E = Entries.size(); I != E; ++I) { 2277 const Symbol *B = Entries[I]; 2278 unsigned RelOff = RelSec->Entsize * I + PltOff; 2279 uint64_t Got = B->getGotPltVA(); 2280 uint64_t Plt = this->getVA() + Off; 2281 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); 2282 Off += Target->PltEntrySize; 2283 } 2284 } 2285 2286 template <class ELFT> void PltSection::addEntry(Symbol &Sym) { 2287 Sym.PltIndex = Entries.size(); 2288 Entries.push_back(&Sym); 2289 } 2290 2291 size_t PltSection::getSize() const { 2292 return HeaderSize + Entries.size() * Target->PltEntrySize; 2293 } 2294 2295 // Some architectures such as additional symbols in the PLT section. For 2296 // example ARM uses mapping symbols to aid disassembly 2297 void PltSection::addSymbols() { 2298 // The PLT may have symbols defined for the Header, the IPLT has no header 2299 if (!IsIplt) 2300 Target->addPltHeaderSymbols(*this); 2301 2302 size_t Off = HeaderSize; 2303 for (size_t I = 0; I < Entries.size(); ++I) { 2304 Target->addPltSymbols(*this, Off); 2305 Off += Target->PltEntrySize; 2306 } 2307 } 2308 2309 // The string hash function for .gdb_index. 2310 static uint32_t computeGdbHash(StringRef S) { 2311 uint32_t H = 0; 2312 for (uint8_t C : S) 2313 H = H * 67 + toLower(C) - 113; 2314 return H; 2315 } 2316 2317 GdbIndexSection::GdbIndexSection() 2318 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {} 2319 2320 // Returns the desired size of an on-disk hash table for a .gdb_index section. 2321 // There's a tradeoff between size and collision rate. We aim 75% utilization. 2322 size_t GdbIndexSection::computeSymtabSize() const { 2323 return std::max<size_t>(NextPowerOf2(Symbols.size() * 4 / 3), 1024); 2324 } 2325 2326 // Compute the output section size. 2327 void GdbIndexSection::initOutputSize() { 2328 Size = sizeof(GdbIndexHeader) + computeSymtabSize() * 8; 2329 2330 for (GdbChunk &Chunk : Chunks) 2331 Size += Chunk.CompilationUnits.size() * 16 + Chunk.AddressAreas.size() * 20; 2332 2333 // Add the constant pool size if exists. 2334 if (!Symbols.empty()) { 2335 GdbSymbol &Sym = Symbols.back(); 2336 Size += Sym.NameOff + Sym.Name.size() + 1; 2337 } 2338 } 2339 2340 static std::vector<InputSection *> getDebugInfoSections() { 2341 std::vector<InputSection *> Ret; 2342 for (InputSectionBase *S : InputSections) 2343 if (InputSection *IS = dyn_cast<InputSection>(S)) 2344 if (IS->Name == ".debug_info") 2345 Ret.push_back(IS); 2346 return Ret; 2347 } 2348 2349 static std::vector<GdbIndexSection::CuEntry> readCuList(DWARFContext &Dwarf) { 2350 std::vector<GdbIndexSection::CuEntry> Ret; 2351 for (std::unique_ptr<DWARFUnit> &Cu : Dwarf.compile_units()) 2352 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4}); 2353 return Ret; 2354 } 2355 2356 static std::vector<GdbIndexSection::AddressEntry> 2357 readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) { 2358 std::vector<GdbIndexSection::AddressEntry> Ret; 2359 2360 uint32_t CuIdx = 0; 2361 for (std::unique_ptr<DWARFUnit> &Cu : Dwarf.compile_units()) { 2362 Expected<DWARFAddressRangesVector> Ranges = Cu->collectAddressRanges(); 2363 if (!Ranges) { 2364 error(toString(Sec) + ": " + toString(Ranges.takeError())); 2365 return {}; 2366 } 2367 2368 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections(); 2369 for (DWARFAddressRange &R : *Ranges) { 2370 InputSectionBase *S = Sections[R.SectionIndex]; 2371 if (!S || S == &InputSection::Discarded || !S->Live) 2372 continue; 2373 // Range list with zero size has no effect. 2374 if (R.LowPC == R.HighPC) 2375 continue; 2376 auto *IS = cast<InputSection>(S); 2377 uint64_t Offset = IS->getOffsetInFile(); 2378 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx}); 2379 } 2380 ++CuIdx; 2381 } 2382 2383 return Ret; 2384 } 2385 2386 template <class ELFT> 2387 static std::vector<GdbIndexSection::NameAttrEntry> 2388 readPubNamesAndTypes(const LLDDwarfObj<ELFT> &Obj, 2389 const std::vector<GdbIndexSection::CuEntry> &CUs) { 2390 const DWARFSection &PubNames = Obj.getGnuPubNamesSection(); 2391 const DWARFSection &PubTypes = Obj.getGnuPubTypesSection(); 2392 2393 std::vector<GdbIndexSection::NameAttrEntry> Ret; 2394 for (const DWARFSection *Pub : {&PubNames, &PubTypes}) { 2395 DWARFDebugPubTable Table(Obj, *Pub, Config->IsLE, true); 2396 for (const DWARFDebugPubTable::Set &Set : Table.getData()) { 2397 // The value written into the constant pool is Kind << 24 | CuIndex. As we 2398 // don't know how many compilation units precede this object to compute 2399 // CuIndex, we compute (Kind << 24 | CuIndexInThisObject) instead, and add 2400 // the number of preceding compilation units later. 2401 uint32_t I = 2402 lower_bound(CUs, Set.Offset, 2403 [](GdbIndexSection::CuEntry CU, uint32_t Offset) { 2404 return CU.CuOffset < Offset; 2405 }) - 2406 CUs.begin(); 2407 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) 2408 Ret.push_back({{Ent.Name, computeGdbHash(Ent.Name)}, 2409 (Ent.Descriptor.toBits() << 24) | I}); 2410 } 2411 } 2412 return Ret; 2413 } 2414 2415 // Create a list of symbols from a given list of symbol names and types 2416 // by uniquifying them by name. 2417 static std::vector<GdbIndexSection::GdbSymbol> 2418 createSymbols(ArrayRef<std::vector<GdbIndexSection::NameAttrEntry>> NameAttrs, 2419 const std::vector<GdbIndexSection::GdbChunk> &Chunks) { 2420 using GdbSymbol = GdbIndexSection::GdbSymbol; 2421 using NameAttrEntry = GdbIndexSection::NameAttrEntry; 2422 2423 // For each chunk, compute the number of compilation units preceding it. 2424 uint32_t CuIdx = 0; 2425 std::vector<uint32_t> CuIdxs(Chunks.size()); 2426 for (uint32_t I = 0, E = Chunks.size(); I != E; ++I) { 2427 CuIdxs[I] = CuIdx; 2428 CuIdx += Chunks[I].CompilationUnits.size(); 2429 } 2430 2431 // The number of symbols we will handle in this function is of the order 2432 // of millions for very large executables, so we use multi-threading to 2433 // speed it up. 2434 size_t NumShards = 32; 2435 size_t Concurrency = 1; 2436 if (ThreadsEnabled) 2437 Concurrency = 2438 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards); 2439 2440 // A sharded map to uniquify symbols by name. 2441 std::vector<DenseMap<CachedHashStringRef, size_t>> Map(NumShards); 2442 size_t Shift = 32 - countTrailingZeros(NumShards); 2443 2444 // Instantiate GdbSymbols while uniqufying them by name. 2445 std::vector<std::vector<GdbSymbol>> Symbols(NumShards); 2446 parallelForEachN(0, Concurrency, [&](size_t ThreadId) { 2447 uint32_t I = 0; 2448 for (ArrayRef<NameAttrEntry> Entries : NameAttrs) { 2449 for (const NameAttrEntry &Ent : Entries) { 2450 size_t ShardId = Ent.Name.hash() >> Shift; 2451 if ((ShardId & (Concurrency - 1)) != ThreadId) 2452 continue; 2453 2454 uint32_t V = Ent.CuIndexAndAttrs + CuIdxs[I]; 2455 size_t &Idx = Map[ShardId][Ent.Name]; 2456 if (Idx) { 2457 Symbols[ShardId][Idx - 1].CuVector.push_back(V); 2458 continue; 2459 } 2460 2461 Idx = Symbols[ShardId].size() + 1; 2462 Symbols[ShardId].push_back({Ent.Name, {V}, 0, 0}); 2463 } 2464 ++I; 2465 } 2466 }); 2467 2468 size_t NumSymbols = 0; 2469 for (ArrayRef<GdbSymbol> V : Symbols) 2470 NumSymbols += V.size(); 2471 2472 // The return type is a flattened vector, so we'll copy each vector 2473 // contents to Ret. 2474 std::vector<GdbSymbol> Ret; 2475 Ret.reserve(NumSymbols); 2476 for (std::vector<GdbSymbol> &Vec : Symbols) 2477 for (GdbSymbol &Sym : Vec) 2478 Ret.push_back(std::move(Sym)); 2479 2480 // CU vectors and symbol names are adjacent in the output file. 2481 // We can compute their offsets in the output file now. 2482 size_t Off = 0; 2483 for (GdbSymbol &Sym : Ret) { 2484 Sym.CuVectorOff = Off; 2485 Off += (Sym.CuVector.size() + 1) * 4; 2486 } 2487 for (GdbSymbol &Sym : Ret) { 2488 Sym.NameOff = Off; 2489 Off += Sym.Name.size() + 1; 2490 } 2491 2492 return Ret; 2493 } 2494 2495 // Returns a newly-created .gdb_index section. 2496 template <class ELFT> GdbIndexSection *GdbIndexSection::create() { 2497 std::vector<InputSection *> Sections = getDebugInfoSections(); 2498 2499 // .debug_gnu_pub{names,types} are useless in executables. 2500 // They are present in input object files solely for creating 2501 // a .gdb_index. So we can remove them from the output. 2502 for (InputSectionBase *S : InputSections) 2503 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes") 2504 S->Live = false; 2505 2506 std::vector<GdbChunk> Chunks(Sections.size()); 2507 std::vector<std::vector<NameAttrEntry>> NameAttrs(Sections.size()); 2508 2509 parallelForEachN(0, Sections.size(), [&](size_t I) { 2510 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>(); 2511 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File)); 2512 2513 Chunks[I].Sec = Sections[I]; 2514 Chunks[I].CompilationUnits = readCuList(Dwarf); 2515 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]); 2516 NameAttrs[I] = readPubNamesAndTypes<ELFT>( 2517 static_cast<const LLDDwarfObj<ELFT> &>(Dwarf.getDWARFObj()), 2518 Chunks[I].CompilationUnits); 2519 }); 2520 2521 auto *Ret = make<GdbIndexSection>(); 2522 Ret->Chunks = std::move(Chunks); 2523 Ret->Symbols = createSymbols(NameAttrs, Ret->Chunks); 2524 Ret->initOutputSize(); 2525 return Ret; 2526 } 2527 2528 void GdbIndexSection::writeTo(uint8_t *Buf) { 2529 // Write the header. 2530 auto *Hdr = reinterpret_cast<GdbIndexHeader *>(Buf); 2531 uint8_t *Start = Buf; 2532 Hdr->Version = 7; 2533 Buf += sizeof(*Hdr); 2534 2535 // Write the CU list. 2536 Hdr->CuListOff = Buf - Start; 2537 for (GdbChunk &Chunk : Chunks) { 2538 for (CuEntry &Cu : Chunk.CompilationUnits) { 2539 write64le(Buf, Chunk.Sec->OutSecOff + Cu.CuOffset); 2540 write64le(Buf + 8, Cu.CuLength); 2541 Buf += 16; 2542 } 2543 } 2544 2545 // Write the address area. 2546 Hdr->CuTypesOff = Buf - Start; 2547 Hdr->AddressAreaOff = Buf - Start; 2548 uint32_t CuOff = 0; 2549 for (GdbChunk &Chunk : Chunks) { 2550 for (AddressEntry &E : Chunk.AddressAreas) { 2551 uint64_t BaseAddr = E.Section->getVA(0); 2552 write64le(Buf, BaseAddr + E.LowAddress); 2553 write64le(Buf + 8, BaseAddr + E.HighAddress); 2554 write32le(Buf + 16, E.CuIndex + CuOff); 2555 Buf += 20; 2556 } 2557 CuOff += Chunk.CompilationUnits.size(); 2558 } 2559 2560 // Write the on-disk open-addressing hash table containing symbols. 2561 Hdr->SymtabOff = Buf - Start; 2562 size_t SymtabSize = computeSymtabSize(); 2563 uint32_t Mask = SymtabSize - 1; 2564 2565 for (GdbSymbol &Sym : Symbols) { 2566 uint32_t H = Sym.Name.hash(); 2567 uint32_t I = H & Mask; 2568 uint32_t Step = ((H * 17) & Mask) | 1; 2569 2570 while (read32le(Buf + I * 8)) 2571 I = (I + Step) & Mask; 2572 2573 write32le(Buf + I * 8, Sym.NameOff); 2574 write32le(Buf + I * 8 + 4, Sym.CuVectorOff); 2575 } 2576 2577 Buf += SymtabSize * 8; 2578 2579 // Write the string pool. 2580 Hdr->ConstantPoolOff = Buf - Start; 2581 parallelForEach(Symbols, [&](GdbSymbol &Sym) { 2582 memcpy(Buf + Sym.NameOff, Sym.Name.data(), Sym.Name.size()); 2583 }); 2584 2585 // Write the CU vectors. 2586 for (GdbSymbol &Sym : Symbols) { 2587 write32le(Buf, Sym.CuVector.size()); 2588 Buf += 4; 2589 for (uint32_t Val : Sym.CuVector) { 2590 write32le(Buf, Val); 2591 Buf += 4; 2592 } 2593 } 2594 } 2595 2596 bool GdbIndexSection::isNeeded() const { return !Chunks.empty(); } 2597 2598 EhFrameHeader::EhFrameHeader() 2599 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {} 2600 2601 void EhFrameHeader::writeTo(uint8_t *Buf) { 2602 // Unlike most sections, the EhFrameHeader section is written while writing 2603 // another section, namely EhFrameSection, which calls the write() function 2604 // below from its writeTo() function. This is necessary because the contents 2605 // of EhFrameHeader depend on the relocated contents of EhFrameSection and we 2606 // don't know which order the sections will be written in. 2607 } 2608 2609 // .eh_frame_hdr contains a binary search table of pointers to FDEs. 2610 // Each entry of the search table consists of two values, 2611 // the starting PC from where FDEs covers, and the FDE's address. 2612 // It is sorted by PC. 2613 void EhFrameHeader::write() { 2614 uint8_t *Buf = Out::BufferStart + getParent()->Offset + OutSecOff; 2615 using FdeData = EhFrameSection::FdeData; 2616 2617 std::vector<FdeData> Fdes = In.EhFrame->getFdeData(); 2618 2619 Buf[0] = 1; 2620 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4; 2621 Buf[2] = DW_EH_PE_udata4; 2622 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4; 2623 write32(Buf + 4, In.EhFrame->getParent()->Addr - this->getVA() - 4); 2624 write32(Buf + 8, Fdes.size()); 2625 Buf += 12; 2626 2627 for (FdeData &Fde : Fdes) { 2628 write32(Buf, Fde.PcRel); 2629 write32(Buf + 4, Fde.FdeVARel); 2630 Buf += 8; 2631 } 2632 } 2633 2634 size_t EhFrameHeader::getSize() const { 2635 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs. 2636 return 12 + In.EhFrame->NumFdes * 8; 2637 } 2638 2639 bool EhFrameHeader::isNeeded() const { return In.EhFrame->isNeeded(); } 2640 2641 VersionDefinitionSection::VersionDefinitionSection() 2642 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t), 2643 ".gnu.version_d") {} 2644 2645 static StringRef getFileDefName() { 2646 if (!Config->SoName.empty()) 2647 return Config->SoName; 2648 return Config->OutputFile; 2649 } 2650 2651 void VersionDefinitionSection::finalizeContents() { 2652 FileDefNameOff = In.DynStrTab->addString(getFileDefName()); 2653 for (VersionDefinition &V : Config->VersionDefinitions) 2654 V.NameOff = In.DynStrTab->addString(V.Name); 2655 2656 if (OutputSection *Sec = In.DynStrTab->getParent()) 2657 getParent()->Link = Sec->SectionIndex; 2658 2659 // sh_info should be set to the number of definitions. This fact is missed in 2660 // documentation, but confirmed by binutils community: 2661 // https://sourceware.org/ml/binutils/2014-11/msg00355.html 2662 getParent()->Info = getVerDefNum(); 2663 } 2664 2665 void VersionDefinitionSection::writeOne(uint8_t *Buf, uint32_t Index, 2666 StringRef Name, size_t NameOff) { 2667 uint16_t Flags = Index == 1 ? VER_FLG_BASE : 0; 2668 2669 // Write a verdef. 2670 write16(Buf, 1); // vd_version 2671 write16(Buf + 2, Flags); // vd_flags 2672 write16(Buf + 4, Index); // vd_ndx 2673 write16(Buf + 6, 1); // vd_cnt 2674 write32(Buf + 8, hashSysV(Name)); // vd_hash 2675 write32(Buf + 12, 20); // vd_aux 2676 write32(Buf + 16, 28); // vd_next 2677 2678 // Write a veraux. 2679 write32(Buf + 20, NameOff); // vda_name 2680 write32(Buf + 24, 0); // vda_next 2681 } 2682 2683 void VersionDefinitionSection::writeTo(uint8_t *Buf) { 2684 writeOne(Buf, 1, getFileDefName(), FileDefNameOff); 2685 2686 for (VersionDefinition &V : Config->VersionDefinitions) { 2687 Buf += EntrySize; 2688 writeOne(Buf, V.Id, V.Name, V.NameOff); 2689 } 2690 2691 // Need to terminate the last version definition. 2692 write32(Buf + 16, 0); // vd_next 2693 } 2694 2695 size_t VersionDefinitionSection::getSize() const { 2696 return EntrySize * getVerDefNum(); 2697 } 2698 2699 // .gnu.version is a table where each entry is 2 byte long. 2700 VersionTableSection::VersionTableSection() 2701 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t), 2702 ".gnu.version") { 2703 this->Entsize = 2; 2704 } 2705 2706 void VersionTableSection::finalizeContents() { 2707 // At the moment of june 2016 GNU docs does not mention that sh_link field 2708 // should be set, but Sun docs do. Also readelf relies on this field. 2709 getParent()->Link = In.DynSymTab->getParent()->SectionIndex; 2710 } 2711 2712 size_t VersionTableSection::getSize() const { 2713 return (In.DynSymTab->getSymbols().size() + 1) * 2; 2714 } 2715 2716 void VersionTableSection::writeTo(uint8_t *Buf) { 2717 Buf += 2; 2718 for (const SymbolTableEntry &S : In.DynSymTab->getSymbols()) { 2719 write16(Buf, S.Sym->VersionId); 2720 Buf += 2; 2721 } 2722 } 2723 2724 bool VersionTableSection::isNeeded() const { 2725 return In.VerDef || In.VerNeed->isNeeded(); 2726 } 2727 2728 void elf::addVerneed(Symbol *SS) { 2729 auto &File = cast<SharedFile>(*SS->File); 2730 if (SS->VerdefIndex == VER_NDX_GLOBAL) { 2731 SS->VersionId = VER_NDX_GLOBAL; 2732 return; 2733 } 2734 2735 if (File.Vernauxs.empty()) 2736 File.Vernauxs.resize(File.Verdefs.size()); 2737 2738 // Select a version identifier for the vernaux data structure, if we haven't 2739 // already allocated one. The verdef identifiers cover the range 2740 // [1..getVerDefNum()]; this causes the vernaux identifiers to start from 2741 // getVerDefNum()+1. 2742 if (File.Vernauxs[SS->VerdefIndex] == 0) 2743 File.Vernauxs[SS->VerdefIndex] = ++SharedFile::VernauxNum + getVerDefNum(); 2744 2745 SS->VersionId = File.Vernauxs[SS->VerdefIndex]; 2746 } 2747 2748 template <class ELFT> 2749 VersionNeedSection<ELFT>::VersionNeedSection() 2750 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t), 2751 ".gnu.version_r") {} 2752 2753 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() { 2754 for (SharedFile *F : SharedFiles) { 2755 if (F->Vernauxs.empty()) 2756 continue; 2757 Verneeds.emplace_back(); 2758 Verneed &VN = Verneeds.back(); 2759 VN.NameStrTab = In.DynStrTab->addString(F->SoName); 2760 for (unsigned I = 0; I != F->Vernauxs.size(); ++I) { 2761 if (F->Vernauxs[I] == 0) 2762 continue; 2763 auto *Verdef = 2764 reinterpret_cast<const typename ELFT::Verdef *>(F->Verdefs[I]); 2765 VN.Vernauxs.push_back( 2766 {Verdef->vd_hash, F->Vernauxs[I], 2767 In.DynStrTab->addString(F->getStringTable().data() + 2768 Verdef->getAux()->vda_name)}); 2769 } 2770 } 2771 2772 if (OutputSection *Sec = In.DynStrTab->getParent()) 2773 getParent()->Link = Sec->SectionIndex; 2774 getParent()->Info = Verneeds.size(); 2775 } 2776 2777 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { 2778 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. 2779 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf); 2780 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Verneeds.size()); 2781 2782 for (auto &VN : Verneeds) { 2783 // Create an Elf_Verneed for this DSO. 2784 Verneed->vn_version = 1; 2785 Verneed->vn_cnt = VN.Vernauxs.size(); 2786 Verneed->vn_file = VN.NameStrTab; 2787 Verneed->vn_aux = 2788 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed); 2789 Verneed->vn_next = sizeof(Elf_Verneed); 2790 ++Verneed; 2791 2792 // Create the Elf_Vernauxs for this Elf_Verneed. 2793 for (auto &VNA : VN.Vernauxs) { 2794 Vernaux->vna_hash = VNA.Hash; 2795 Vernaux->vna_flags = 0; 2796 Vernaux->vna_other = VNA.VerneedIndex; 2797 Vernaux->vna_name = VNA.NameStrTab; 2798 Vernaux->vna_next = sizeof(Elf_Vernaux); 2799 ++Vernaux; 2800 } 2801 2802 Vernaux[-1].vna_next = 0; 2803 } 2804 Verneed[-1].vn_next = 0; 2805 } 2806 2807 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const { 2808 return Verneeds.size() * sizeof(Elf_Verneed) + 2809 SharedFile::VernauxNum * sizeof(Elf_Vernaux); 2810 } 2811 2812 template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const { 2813 return SharedFile::VernauxNum != 0; 2814 } 2815 2816 void MergeSyntheticSection::addSection(MergeInputSection *MS) { 2817 MS->Parent = this; 2818 Sections.push_back(MS); 2819 } 2820 2821 MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type, 2822 uint64_t Flags, uint32_t Alignment) 2823 : MergeSyntheticSection(Name, Type, Flags, Alignment), 2824 Builder(StringTableBuilder::RAW, Alignment) {} 2825 2826 size_t MergeTailSection::getSize() const { return Builder.getSize(); } 2827 2828 void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); } 2829 2830 void MergeTailSection::finalizeContents() { 2831 // Add all string pieces to the string table builder to create section 2832 // contents. 2833 for (MergeInputSection *Sec : Sections) 2834 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2835 if (Sec->Pieces[I].Live) 2836 Builder.add(Sec->getData(I)); 2837 2838 // Fix the string table content. After this, the contents will never change. 2839 Builder.finalize(); 2840 2841 // finalize() fixed tail-optimized strings, so we can now get 2842 // offsets of strings. Get an offset for each string and save it 2843 // to a corresponding StringPiece for easy access. 2844 for (MergeInputSection *Sec : Sections) 2845 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2846 if (Sec->Pieces[I].Live) 2847 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I)); 2848 } 2849 2850 void MergeNoTailSection::writeTo(uint8_t *Buf) { 2851 for (size_t I = 0; I < NumShards; ++I) 2852 Shards[I].write(Buf + ShardOffsets[I]); 2853 } 2854 2855 // This function is very hot (i.e. it can take several seconds to finish) 2856 // because sometimes the number of inputs is in an order of magnitude of 2857 // millions. So, we use multi-threading. 2858 // 2859 // For any strings S and T, we know S is not mergeable with T if S's hash 2860 // value is different from T's. If that's the case, we can safely put S and 2861 // T into different string builders without worrying about merge misses. 2862 // We do it in parallel. 2863 void MergeNoTailSection::finalizeContents() { 2864 // Initializes string table builders. 2865 for (size_t I = 0; I < NumShards; ++I) 2866 Shards.emplace_back(StringTableBuilder::RAW, Alignment); 2867 2868 // Concurrency level. Must be a power of 2 to avoid expensive modulo 2869 // operations in the following tight loop. 2870 size_t Concurrency = 1; 2871 if (ThreadsEnabled) 2872 Concurrency = 2873 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards); 2874 2875 // Add section pieces to the builders. 2876 parallelForEachN(0, Concurrency, [&](size_t ThreadId) { 2877 for (MergeInputSection *Sec : Sections) { 2878 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) { 2879 if (!Sec->Pieces[I].Live) 2880 continue; 2881 size_t ShardId = getShardId(Sec->Pieces[I].Hash); 2882 if ((ShardId & (Concurrency - 1)) == ThreadId) 2883 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I)); 2884 } 2885 } 2886 }); 2887 2888 // Compute an in-section offset for each shard. 2889 size_t Off = 0; 2890 for (size_t I = 0; I < NumShards; ++I) { 2891 Shards[I].finalizeInOrder(); 2892 if (Shards[I].getSize() > 0) 2893 Off = alignTo(Off, Alignment); 2894 ShardOffsets[I] = Off; 2895 Off += Shards[I].getSize(); 2896 } 2897 Size = Off; 2898 2899 // So far, section pieces have offsets from beginning of shards, but 2900 // we want offsets from beginning of the whole section. Fix them. 2901 parallelForEach(Sections, [&](MergeInputSection *Sec) { 2902 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2903 if (Sec->Pieces[I].Live) 2904 Sec->Pieces[I].OutputOff += 2905 ShardOffsets[getShardId(Sec->Pieces[I].Hash)]; 2906 }); 2907 } 2908 2909 static MergeSyntheticSection *createMergeSynthetic(StringRef Name, 2910 uint32_t Type, 2911 uint64_t Flags, 2912 uint32_t Alignment) { 2913 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2; 2914 if (ShouldTailMerge) 2915 return make<MergeTailSection>(Name, Type, Flags, Alignment); 2916 return make<MergeNoTailSection>(Name, Type, Flags, Alignment); 2917 } 2918 2919 template <class ELFT> void elf::splitSections() { 2920 // splitIntoPieces needs to be called on each MergeInputSection 2921 // before calling finalizeContents(). 2922 parallelForEach(InputSections, [](InputSectionBase *Sec) { 2923 if (auto *S = dyn_cast<MergeInputSection>(Sec)) 2924 S->splitIntoPieces(); 2925 else if (auto *Eh = dyn_cast<EhInputSection>(Sec)) 2926 Eh->split<ELFT>(); 2927 }); 2928 } 2929 2930 // This function scans over the inputsections to create mergeable 2931 // synthetic sections. 2932 // 2933 // It removes MergeInputSections from the input section array and adds 2934 // new synthetic sections at the location of the first input section 2935 // that it replaces. It then finalizes each synthetic section in order 2936 // to compute an output offset for each piece of each input section. 2937 void elf::mergeSections() { 2938 std::vector<MergeSyntheticSection *> MergeSections; 2939 for (InputSectionBase *&S : InputSections) { 2940 MergeInputSection *MS = dyn_cast<MergeInputSection>(S); 2941 if (!MS) 2942 continue; 2943 2944 // We do not want to handle sections that are not alive, so just remove 2945 // them instead of trying to merge. 2946 if (!MS->Live) { 2947 S = nullptr; 2948 continue; 2949 } 2950 2951 StringRef OutsecName = getOutputSectionName(MS); 2952 2953 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { 2954 // While we could create a single synthetic section for two different 2955 // values of Entsize, it is better to take Entsize into consideration. 2956 // 2957 // With a single synthetic section no two pieces with different Entsize 2958 // could be equal, so we may as well have two sections. 2959 // 2960 // Using Entsize in here also allows us to propagate it to the synthetic 2961 // section. 2962 return Sec->Name == OutsecName && Sec->Flags == MS->Flags && 2963 Sec->Entsize == MS->Entsize && Sec->Alignment == MS->Alignment; 2964 }); 2965 if (I == MergeSections.end()) { 2966 MergeSyntheticSection *Syn = 2967 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, MS->Alignment); 2968 MergeSections.push_back(Syn); 2969 I = std::prev(MergeSections.end()); 2970 S = Syn; 2971 Syn->Entsize = MS->Entsize; 2972 } else { 2973 S = nullptr; 2974 } 2975 (*I)->addSection(MS); 2976 } 2977 for (auto *MS : MergeSections) 2978 MS->finalizeContents(); 2979 2980 std::vector<InputSectionBase *> &V = InputSections; 2981 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); 2982 } 2983 2984 MipsRldMapSection::MipsRldMapSection() 2985 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize, 2986 ".rld_map") {} 2987 2988 ARMExidxSyntheticSection::ARMExidxSyntheticSection() 2989 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX, 2990 Config->Wordsize, ".ARM.exidx") {} 2991 2992 static InputSection *findExidxSection(InputSection *IS) { 2993 for (InputSection *D : IS->DependentSections) 2994 if (D->Type == SHT_ARM_EXIDX) 2995 return D; 2996 return nullptr; 2997 } 2998 2999 bool ARMExidxSyntheticSection::addSection(InputSection *IS) { 3000 if (IS->Type == SHT_ARM_EXIDX) { 3001 ExidxSections.push_back(IS); 3002 return true; 3003 } 3004 3005 if ((IS->Flags & SHF_ALLOC) && (IS->Flags & SHF_EXECINSTR) && 3006 IS->getSize() > 0) { 3007 ExecutableSections.push_back(IS); 3008 if (Empty && findExidxSection(IS)) 3009 Empty = false; 3010 return false; 3011 } 3012 3013 // FIXME: we do not output a relocation section when --emit-relocs is used 3014 // as we do not have relocation sections for linker generated table entries 3015 // and we would have to erase at a late stage relocations from merged entries. 3016 // Given that exception tables are already position independent and a binary 3017 // analyzer could derive the relocations we choose to erase the relocations. 3018 if (Config->EmitRelocs && IS->Type == SHT_REL) 3019 if (InputSectionBase *EX = IS->getRelocatedSection()) 3020 if (isa<InputSection>(EX) && EX->Type == SHT_ARM_EXIDX) 3021 return true; 3022 3023 return false; 3024 } 3025 3026 // References to .ARM.Extab Sections have bit 31 clear and are not the 3027 // special EXIDX_CANTUNWIND bit-pattern. 3028 static bool isExtabRef(uint32_t Unwind) { 3029 return (Unwind & 0x80000000) == 0 && Unwind != 0x1; 3030 } 3031 3032 // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx 3033 // section Prev, where Cur follows Prev in the table. This can be done if the 3034 // unwinding instructions in Cur are identical to Prev. Linker generated 3035 // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an 3036 // InputSection. 3037 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) { 3038 3039 struct ExidxEntry { 3040 ulittle32_t Fn; 3041 ulittle32_t Unwind; 3042 }; 3043 // Get the last table Entry from the previous .ARM.exidx section. If Prev is 3044 // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry. 3045 ExidxEntry PrevEntry = {ulittle32_t(0), ulittle32_t(1)}; 3046 if (Prev) 3047 PrevEntry = Prev->getDataAs<ExidxEntry>().back(); 3048 if (isExtabRef(PrevEntry.Unwind)) 3049 return false; 3050 3051 // We consider the unwind instructions of an .ARM.exidx table entry 3052 // a duplicate if the previous unwind instructions if: 3053 // - Both are the special EXIDX_CANTUNWIND. 3054 // - Both are the same inline unwind instructions. 3055 // We do not attempt to follow and check links into .ARM.extab tables as 3056 // consecutive identical entries are rare and the effort to check that they 3057 // are identical is high. 3058 3059 // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry. 3060 if (Cur == nullptr) 3061 return PrevEntry.Unwind == 1; 3062 3063 for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>()) 3064 if (isExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind) 3065 return false; 3066 3067 // All table entries in this .ARM.exidx Section can be merged into the 3068 // previous Section. 3069 return true; 3070 } 3071 3072 // The .ARM.exidx table must be sorted in ascending order of the address of the 3073 // functions the table describes. Optionally duplicate adjacent table entries 3074 // can be removed. At the end of the function the ExecutableSections must be 3075 // sorted in ascending order of address, Sentinel is set to the InputSection 3076 // with the highest address and any InputSections that have mergeable 3077 // .ARM.exidx table entries are removed from it. 3078 void ARMExidxSyntheticSection::finalizeContents() { 3079 // Sort the executable sections that may or may not have associated 3080 // .ARM.exidx sections by order of ascending address. This requires the 3081 // relative positions of InputSections to be known. 3082 auto CompareByFilePosition = [](const InputSection *A, 3083 const InputSection *B) { 3084 OutputSection *AOut = A->getParent(); 3085 OutputSection *BOut = B->getParent(); 3086 3087 if (AOut != BOut) 3088 return AOut->SectionIndex < BOut->SectionIndex; 3089 return A->OutSecOff < B->OutSecOff; 3090 }; 3091 llvm::stable_sort(ExecutableSections, CompareByFilePosition); 3092 Sentinel = ExecutableSections.back(); 3093 // Optionally merge adjacent duplicate entries. 3094 if (Config->MergeArmExidx) { 3095 std::vector<InputSection *> SelectedSections; 3096 SelectedSections.reserve(ExecutableSections.size()); 3097 SelectedSections.push_back(ExecutableSections[0]); 3098 size_t Prev = 0; 3099 for (size_t I = 1; I < ExecutableSections.size(); ++I) { 3100 InputSection *EX1 = findExidxSection(ExecutableSections[Prev]); 3101 InputSection *EX2 = findExidxSection(ExecutableSections[I]); 3102 if (!isDuplicateArmExidxSec(EX1, EX2)) { 3103 SelectedSections.push_back(ExecutableSections[I]); 3104 Prev = I; 3105 } 3106 } 3107 ExecutableSections = std::move(SelectedSections); 3108 } 3109 3110 size_t Offset = 0; 3111 Size = 0; 3112 for (InputSection *IS : ExecutableSections) { 3113 if (InputSection *D = findExidxSection(IS)) { 3114 D->OutSecOff = Offset; 3115 D->Parent = getParent(); 3116 Offset += D->getSize(); 3117 } else { 3118 Offset += 8; 3119 } 3120 } 3121 // Size includes Sentinel. 3122 Size = Offset + 8; 3123 } 3124 3125 InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const { 3126 return ExecutableSections.front(); 3127 } 3128 3129 // To write the .ARM.exidx table from the ExecutableSections we have three cases 3130 // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections. 3131 // We write the .ARM.exidx section contents and apply its relocations. 3132 // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We 3133 // must write the contents of an EXIDX_CANTUNWIND directly. We use the 3134 // start of the InputSection as the purpose of the linker generated 3135 // section is to terminate the address range of the previous entry. 3136 // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of 3137 // the table to terminate the address range of the final entry. 3138 void ARMExidxSyntheticSection::writeTo(uint8_t *Buf) { 3139 3140 const uint8_t CantUnwindData[8] = {0, 0, 0, 0, // PREL31 to target 3141 1, 0, 0, 0}; // EXIDX_CANTUNWIND 3142 3143 uint64_t Offset = 0; 3144 for (InputSection *IS : ExecutableSections) { 3145 assert(IS->getParent() != nullptr); 3146 if (InputSection *D = findExidxSection(IS)) { 3147 memcpy(Buf + Offset, D->data().data(), D->data().size()); 3148 D->relocateAlloc(Buf, Buf + D->getSize()); 3149 Offset += D->getSize(); 3150 } else { 3151 // A Linker generated CANTUNWIND section. 3152 memcpy(Buf + Offset, CantUnwindData, sizeof(CantUnwindData)); 3153 uint64_t S = IS->getVA(); 3154 uint64_t P = getVA() + Offset; 3155 Target->relocateOne(Buf + Offset, R_ARM_PREL31, S - P); 3156 Offset += 8; 3157 } 3158 } 3159 // Write Sentinel. 3160 memcpy(Buf + Offset, CantUnwindData, sizeof(CantUnwindData)); 3161 uint64_t S = Sentinel->getVA(Sentinel->getSize()); 3162 uint64_t P = getVA() + Offset; 3163 Target->relocateOne(Buf + Offset, R_ARM_PREL31, S - P); 3164 assert(Size == Offset + 8); 3165 } 3166 3167 bool ARMExidxSyntheticSection::classof(const SectionBase *D) { 3168 return D->kind() == InputSectionBase::Synthetic && D->Type == SHT_ARM_EXIDX; 3169 } 3170 3171 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off) 3172 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 3173 Config->Wordsize, ".text.thunk") { 3174 this->Parent = OS; 3175 this->OutSecOff = Off; 3176 } 3177 3178 void ThunkSection::addThunk(Thunk *T) { 3179 Thunks.push_back(T); 3180 T->addSymbols(*this); 3181 } 3182 3183 void ThunkSection::writeTo(uint8_t *Buf) { 3184 for (Thunk *T : Thunks) 3185 T->writeTo(Buf + T->Offset); 3186 } 3187 3188 InputSection *ThunkSection::getTargetInputSection() const { 3189 if (Thunks.empty()) 3190 return nullptr; 3191 const Thunk *T = Thunks.front(); 3192 return T->getTargetInputSection(); 3193 } 3194 3195 bool ThunkSection::assignOffsets() { 3196 uint64_t Off = 0; 3197 for (Thunk *T : Thunks) { 3198 Off = alignTo(Off, T->Alignment); 3199 T->setOffset(Off); 3200 uint32_t Size = T->size(); 3201 T->getThunkTargetSym()->Size = Size; 3202 Off += Size; 3203 } 3204 bool Changed = Off != Size; 3205 Size = Off; 3206 return Changed; 3207 } 3208 3209 // If linking position-dependent code then the table will store the addresses 3210 // directly in the binary so the section has type SHT_PROGBITS. If linking 3211 // position-independent code the section has type SHT_NOBITS since it will be 3212 // allocated and filled in by the dynamic linker. 3213 PPC64LongBranchTargetSection::PPC64LongBranchTargetSection() 3214 : SyntheticSection(SHF_ALLOC | SHF_WRITE, 3215 Config->Pic ? SHT_NOBITS : SHT_PROGBITS, 8, 3216 ".branch_lt") {} 3217 3218 void PPC64LongBranchTargetSection::addEntry(Symbol &Sym) { 3219 assert(Sym.PPC64BranchltIndex == 0xffff); 3220 Sym.PPC64BranchltIndex = Entries.size(); 3221 Entries.push_back(&Sym); 3222 } 3223 3224 size_t PPC64LongBranchTargetSection::getSize() const { 3225 return Entries.size() * 8; 3226 } 3227 3228 void PPC64LongBranchTargetSection::writeTo(uint8_t *Buf) { 3229 assert(Target->GotPltEntrySize == 8); 3230 // If linking non-pic we have the final addresses of the targets and they get 3231 // written to the table directly. For pic the dynamic linker will allocate 3232 // the section and fill it it. 3233 if (Config->Pic) 3234 return; 3235 3236 for (const Symbol *Sym : Entries) { 3237 assert(Sym->getVA()); 3238 // Need calls to branch to the local entry-point since a long-branch 3239 // must be a local-call. 3240 write64(Buf, 3241 Sym->getVA() + getPPC64GlobalEntryToLocalEntryOffset(Sym->StOther)); 3242 Buf += Target->GotPltEntrySize; 3243 } 3244 } 3245 3246 bool PPC64LongBranchTargetSection::isNeeded() const { 3247 // `removeUnusedSyntheticSections()` is called before thunk allocation which 3248 // is too early to determine if this section will be empty or not. We need 3249 // Finalized to keep the section alive until after thunk creation. Finalized 3250 // only gets set to true once `finalizeSections()` is called after thunk 3251 // creation. Becuase of this, if we don't create any long-branch thunks we end 3252 // up with an empty .branch_lt section in the binary. 3253 return !Finalized || !Entries.empty(); 3254 } 3255 3256 InStruct elf::In; 3257 3258 template GdbIndexSection *GdbIndexSection::create<ELF32LE>(); 3259 template GdbIndexSection *GdbIndexSection::create<ELF32BE>(); 3260 template GdbIndexSection *GdbIndexSection::create<ELF64LE>(); 3261 template GdbIndexSection *GdbIndexSection::create<ELF64BE>(); 3262 3263 template void elf::splitSections<ELF32LE>(); 3264 template void elf::splitSections<ELF32BE>(); 3265 template void elf::splitSections<ELF64LE>(); 3266 template void elf::splitSections<ELF64BE>(); 3267 3268 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *); 3269 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *); 3270 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *); 3271 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *); 3272 3273 template void PltSection::addEntry<ELF32LE>(Symbol &Sym); 3274 template void PltSection::addEntry<ELF32BE>(Symbol &Sym); 3275 template void PltSection::addEntry<ELF64LE>(Symbol &Sym); 3276 template void PltSection::addEntry<ELF64BE>(Symbol &Sym); 3277 3278 template class elf::MipsAbiFlagsSection<ELF32LE>; 3279 template class elf::MipsAbiFlagsSection<ELF32BE>; 3280 template class elf::MipsAbiFlagsSection<ELF64LE>; 3281 template class elf::MipsAbiFlagsSection<ELF64BE>; 3282 3283 template class elf::MipsOptionsSection<ELF32LE>; 3284 template class elf::MipsOptionsSection<ELF32BE>; 3285 template class elf::MipsOptionsSection<ELF64LE>; 3286 template class elf::MipsOptionsSection<ELF64BE>; 3287 3288 template class elf::MipsReginfoSection<ELF32LE>; 3289 template class elf::MipsReginfoSection<ELF32BE>; 3290 template class elf::MipsReginfoSection<ELF64LE>; 3291 template class elf::MipsReginfoSection<ELF64BE>; 3292 3293 template class elf::DynamicSection<ELF32LE>; 3294 template class elf::DynamicSection<ELF32BE>; 3295 template class elf::DynamicSection<ELF64LE>; 3296 template class elf::DynamicSection<ELF64BE>; 3297 3298 template class elf::RelocationSection<ELF32LE>; 3299 template class elf::RelocationSection<ELF32BE>; 3300 template class elf::RelocationSection<ELF64LE>; 3301 template class elf::RelocationSection<ELF64BE>; 3302 3303 template class elf::AndroidPackedRelocationSection<ELF32LE>; 3304 template class elf::AndroidPackedRelocationSection<ELF32BE>; 3305 template class elf::AndroidPackedRelocationSection<ELF64LE>; 3306 template class elf::AndroidPackedRelocationSection<ELF64BE>; 3307 3308 template class elf::RelrSection<ELF32LE>; 3309 template class elf::RelrSection<ELF32BE>; 3310 template class elf::RelrSection<ELF64LE>; 3311 template class elf::RelrSection<ELF64BE>; 3312 3313 template class elf::SymbolTableSection<ELF32LE>; 3314 template class elf::SymbolTableSection<ELF32BE>; 3315 template class elf::SymbolTableSection<ELF64LE>; 3316 template class elf::SymbolTableSection<ELF64BE>; 3317 3318 template class elf::VersionNeedSection<ELF32LE>; 3319 template class elf::VersionNeedSection<ELF32BE>; 3320 template class elf::VersionNeedSection<ELF64LE>; 3321 template class elf::VersionNeedSection<ELF64BE>; 3322