1 //===- SyntheticSections.cpp ----------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains linker-synthesized sections. Currently,
11 // synthetic sections are created either output sections or input sections,
12 // but we are rewriting code so that all synthetic sections are created as
15 //===----------------------------------------------------------------------===//
17 #include "SyntheticSections.h"
20 #include "InputFiles.h"
21 #include "LinkerScript.h"
23 #include "OutputSections.h"
25 #include "SymbolTable.h"
29 #include "lld/Config/Version.h"
30 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
31 #include "llvm/Object/ELFObjectFile.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/MD5.h"
35 #include "llvm/Support/RandomNumberGenerator.h"
36 #include "llvm/Support/SHA1.h"
37 #include "llvm/Support/xxhash.h"
41 using namespace llvm::dwarf;
42 using namespace llvm::ELF;
43 using namespace llvm::object;
44 using namespace llvm::support;
45 using namespace llvm::support::endian;
48 using namespace lld::elf;
50 uint64_t SyntheticSection::getVA() const {
52 return this->OutSec->Addr + this->OutSecOff;
56 template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
57 std::vector<DefinedCommon *> V;
58 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
59 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
64 // Find all common symbols and allocate space for them.
65 template <class ELFT> InputSection *elf::createCommonSection() {
66 if (!Config->DefineCommon)
69 // Sort the common symbols by alignment as an heuristic to pack them better.
70 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
74 std::stable_sort(Syms.begin(), Syms.end(),
75 [](const DefinedCommon *A, const DefinedCommon *B) {
76 return A->Alignment > B->Alignment;
79 BssSection *Sec = make<BssSection>("COMMON");
80 for (DefinedCommon *Sym : Syms)
81 Sym->Offset = Sec->reserveSpace(Sym->Size, Sym->Alignment);
85 // Returns an LLD version string.
86 static ArrayRef<uint8_t> getVersion() {
87 // Check LLD_VERSION first for ease of testing.
88 // You can get consitent output by using the environment variable.
89 // This is only for testing.
90 StringRef S = getenv("LLD_VERSION");
92 S = Saver.save(Twine("Linker: ") + getLLDVersion());
94 // +1 to include the terminating '\0'.
95 return {(const uint8_t *)S.data(), S.size() + 1};
98 // Creates a .comment section containing LLD version info.
99 // With this feature, you can identify LLD-generated binaries easily
100 // by "objdump -s -j .comment <file>".
101 // The returned object is a mergeable string section.
102 template <class ELFT> MergeInputSection *elf::createCommentSection() {
103 typename ELFT::Shdr Hdr = {};
104 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
105 Hdr.sh_type = SHT_PROGBITS;
107 Hdr.sh_addralign = 1;
110 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
111 Ret->Data = getVersion();
112 Ret->splitIntoPieces();
116 // .MIPS.abiflags section.
117 template <class ELFT>
118 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
119 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
121 this->Entsize = sizeof(Elf_Mips_ABIFlags);
124 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
125 memcpy(Buf, &Flags, sizeof(Flags));
128 template <class ELFT>
129 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
130 Elf_Mips_ABIFlags Flags = {};
133 for (InputSectionBase *Sec : InputSections) {
134 if (Sec->Type != SHT_MIPS_ABIFLAGS)
139 std::string Filename = toString(Sec->getFile<ELFT>());
140 const size_t Size = Sec->Data.size();
141 // Older version of BFD (such as the default FreeBSD linker) concatenate
142 // .MIPS.abiflags instead of merging. To allow for this case (or potential
143 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
144 if (Size < sizeof(Elf_Mips_ABIFlags)) {
145 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
146 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
149 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
150 if (S->version != 0) {
151 error(Filename + ": unexpected .MIPS.abiflags version " +
156 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
157 // select the highest number of ISA/Rev/Ext.
158 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
159 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
160 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
161 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
162 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
163 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
164 Flags.ases |= S->ases;
165 Flags.flags1 |= S->flags1;
166 Flags.flags2 |= S->flags2;
167 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
171 return make<MipsAbiFlagsSection<ELFT>>(Flags);
175 // .MIPS.options section.
176 template <class ELFT>
177 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
178 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
180 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
183 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
184 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
185 Options->kind = ODK_REGINFO;
186 Options->size = getSize();
188 if (!Config->Relocatable)
189 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
190 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
193 template <class ELFT>
194 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
199 Elf_Mips_RegInfo Reginfo = {};
202 for (InputSectionBase *Sec : InputSections) {
203 if (Sec->Type != SHT_MIPS_OPTIONS)
208 std::string Filename = toString(Sec->getFile<ELFT>());
209 ArrayRef<uint8_t> D = Sec->Data;
212 if (D.size() < sizeof(Elf_Mips_Options)) {
213 error(Filename + ": invalid size of .MIPS.options section");
217 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
218 if (Opt->kind == ODK_REGINFO) {
219 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
220 error(Filename + ": unsupported non-zero ri_gp_value");
221 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
222 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
227 fatal(Filename + ": zero option descriptor size");
228 D = D.slice(Opt->size);
233 return make<MipsOptionsSection<ELFT>>(Reginfo);
237 // MIPS .reginfo section.
238 template <class ELFT>
239 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
240 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
242 this->Entsize = sizeof(Elf_Mips_RegInfo);
245 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
246 if (!Config->Relocatable)
247 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
248 memcpy(Buf, &Reginfo, sizeof(Reginfo));
251 template <class ELFT>
252 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
253 // Section should be alive for O32 and N32 ABIs only.
257 Elf_Mips_RegInfo Reginfo = {};
260 for (InputSectionBase *Sec : InputSections) {
261 if (Sec->Type != SHT_MIPS_REGINFO)
266 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
267 error(toString(Sec->getFile<ELFT>()) +
268 ": invalid size of .reginfo section");
271 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
272 if (Config->Relocatable && R->ri_gp_value)
273 error(toString(Sec->getFile<ELFT>()) +
274 ": unsupported non-zero ri_gp_value");
276 Reginfo.ri_gprmask |= R->ri_gprmask;
277 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
281 return make<MipsReginfoSection<ELFT>>(Reginfo);
285 InputSection *elf::createInterpSection() {
286 // StringSaver guarantees that the returned string ends with '\0'.
287 StringRef S = Saver.save(Config->DynamicLinker);
288 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
291 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
296 template <class ELFT>
297 SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
298 uint64_t Size, InputSectionBase *Section) {
299 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
300 Value, Size, Section, nullptr);
301 if (In<ELFT>::SymTab)
302 In<ELFT>::SymTab->addSymbol(S);
306 static size_t getHashSize() {
307 switch (Config->BuildId) {
308 case BuildIdKind::Fast:
310 case BuildIdKind::Md5:
311 case BuildIdKind::Uuid:
313 case BuildIdKind::Sha1:
315 case BuildIdKind::Hexstring:
316 return Config->BuildIdVector.size();
318 llvm_unreachable("unknown BuildIdKind");
322 BuildIdSection::BuildIdSection()
323 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
324 HashSize(getHashSize()) {}
326 void BuildIdSection::writeTo(uint8_t *Buf) {
327 endianness E = Config->Endianness;
328 write32(Buf, 4, E); // Name size
329 write32(Buf + 4, HashSize, E); // Content size
330 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
331 memcpy(Buf + 12, "GNU", 4); // Name string
335 // Split one uint8 array into small pieces of uint8 arrays.
336 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
338 std::vector<ArrayRef<uint8_t>> Ret;
339 while (Arr.size() > ChunkSize) {
340 Ret.push_back(Arr.take_front(ChunkSize));
341 Arr = Arr.drop_front(ChunkSize);
348 // Computes a hash value of Data using a given hash function.
349 // In order to utilize multiple cores, we first split data into 1MB
350 // chunks, compute a hash for each chunk, and then compute a hash value
351 // of the hash values.
352 void BuildIdSection::computeHash(
353 llvm::ArrayRef<uint8_t> Data,
354 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
355 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
356 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
358 // Compute hash values.
359 parallelFor(0, Chunks.size(), [&](size_t I) {
360 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
363 // Write to the final output buffer.
364 HashFn(HashBuf, Hashes);
367 BssSection::BssSection(StringRef Name)
368 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
370 size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) {
372 OutSec->updateAlignment(Alignment);
373 this->Size = alignTo(this->Size, Alignment) + Size;
374 this->Alignment = std::max(this->Alignment, Alignment);
375 return this->Size - Size;
378 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
379 switch (Config->BuildId) {
380 case BuildIdKind::Fast:
381 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
382 write64le(Dest, xxHash64(toStringRef(Arr)));
385 case BuildIdKind::Md5:
386 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
387 memcpy(Dest, MD5::hash(Arr).data(), 16);
390 case BuildIdKind::Sha1:
391 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
392 memcpy(Dest, SHA1::hash(Arr).data(), 20);
395 case BuildIdKind::Uuid:
396 if (getRandomBytes(HashBuf, HashSize))
397 error("entropy source failure");
399 case BuildIdKind::Hexstring:
400 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
403 llvm_unreachable("unknown BuildIdKind");
407 template <class ELFT>
408 EhFrameSection<ELFT>::EhFrameSection()
409 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
411 // Search for an existing CIE record or create a new one.
412 // CIE records from input object files are uniquified by their contents
413 // and where their relocations point to.
414 template <class ELFT>
415 template <class RelTy>
416 CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
417 ArrayRef<RelTy> Rels) {
418 auto *Sec = cast<EhInputSection>(Piece.ID);
419 const endianness E = ELFT::TargetEndianness;
420 if (read32<E>(Piece.data().data() + 4) != 0)
421 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
423 SymbolBody *Personality = nullptr;
424 unsigned FirstRelI = Piece.FirstRelocation;
425 if (FirstRelI != (unsigned)-1)
427 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
429 // Search for an existing CIE by CIE contents/relocation target pair.
430 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
432 // If not found, create a new one.
433 if (Cie->Piece == nullptr) {
440 // There is one FDE per function. Returns true if a given FDE
441 // points to a live function.
442 template <class ELFT>
443 template <class RelTy>
444 bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
445 ArrayRef<RelTy> Rels) {
446 auto *Sec = cast<EhInputSection>(Piece.ID);
447 unsigned FirstRelI = Piece.FirstRelocation;
448 if (FirstRelI == (unsigned)-1)
450 const RelTy &Rel = Rels[FirstRelI];
451 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
452 auto *D = dyn_cast<DefinedRegular>(&B);
453 if (!D || !D->Section)
456 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
457 return Target && Target->Live;
460 // .eh_frame is a sequence of CIE or FDE records. In general, there
461 // is one CIE record per input object file which is followed by
462 // a list of FDEs. This function searches an existing CIE or create a new
463 // one and associates FDEs to the CIE.
464 template <class ELFT>
465 template <class RelTy>
466 void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
467 ArrayRef<RelTy> Rels) {
468 const endianness E = ELFT::TargetEndianness;
470 DenseMap<size_t, CieRecord *> OffsetToCie;
471 for (EhSectionPiece &Piece : Sec->Pieces) {
472 // The empty record is the end marker.
473 if (Piece.size() == 4)
476 size_t Offset = Piece.InputOff;
477 uint32_t ID = read32<E>(Piece.data().data() + 4);
479 OffsetToCie[Offset] = addCie(Piece, Rels);
483 uint32_t CieOffset = Offset + 4 - ID;
484 CieRecord *Cie = OffsetToCie[CieOffset];
486 fatal(toString(Sec) + ": invalid CIE reference");
488 if (!isFdeLive(Piece, Rels))
490 Cie->FdePieces.push_back(&Piece);
495 template <class ELFT>
496 void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
497 auto *Sec = cast<EhInputSection>(C);
499 updateAlignment(Sec->Alignment);
500 Sections.push_back(Sec);
501 for (auto *DS : Sec->DependentSections)
502 DependentSections.push_back(DS);
504 // .eh_frame is a sequence of CIE or FDE records. This function
505 // splits it into pieces so that we can call
506 // SplitInputSection::getSectionPiece on the section.
508 if (Sec->Pieces.empty())
511 if (Sec->NumRelocations) {
512 if (Sec->AreRelocsRela)
513 addSectionAux(Sec, Sec->template relas<ELFT>());
515 addSectionAux(Sec, Sec->template rels<ELFT>());
518 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
521 template <class ELFT>
522 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
523 memcpy(Buf, D.data(), D.size());
525 // Fix the size field. -4 since size does not include the size field itself.
526 const endianness E = ELFT::TargetEndianness;
527 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
530 template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
532 return; // Already finalized.
535 for (CieRecord *Cie : Cies) {
536 Cie->Piece->OutputOff = Off;
537 Off += alignTo(Cie->Piece->size(), Config->Wordsize);
539 for (EhSectionPiece *Fde : Cie->FdePieces) {
540 Fde->OutputOff = Off;
541 Off += alignTo(Fde->size(), Config->Wordsize);
547 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
548 const endianness E = ELFT::TargetEndianness;
550 case DW_EH_PE_udata2:
551 return read16<E>(Buf);
552 case DW_EH_PE_udata4:
553 return read32<E>(Buf);
554 case DW_EH_PE_udata8:
555 return read64<E>(Buf);
556 case DW_EH_PE_absptr:
558 return read64<E>(Buf);
559 return read32<E>(Buf);
561 fatal("unknown FDE size encoding");
564 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
565 // We need it to create .eh_frame_hdr section.
566 template <class ELFT>
567 uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
569 // The starting address to which this FDE applies is
570 // stored at FDE + 8 byte.
571 size_t Off = FdeOff + 8;
572 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
573 if ((Enc & 0x70) == DW_EH_PE_absptr)
575 if ((Enc & 0x70) == DW_EH_PE_pcrel)
576 return Addr + this->OutSec->Addr + Off;
577 fatal("unknown FDE size relative encoding");
580 template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
581 const endianness E = ELFT::TargetEndianness;
582 for (CieRecord *Cie : Cies) {
583 size_t CieOffset = Cie->Piece->OutputOff;
584 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
586 for (EhSectionPiece *Fde : Cie->FdePieces) {
587 size_t Off = Fde->OutputOff;
588 writeCieFde<ELFT>(Buf + Off, Fde->data());
590 // FDE's second word should have the offset to an associated CIE.
592 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
596 for (EhInputSection *S : Sections)
597 S->template relocate<ELFT>(Buf, nullptr);
599 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
600 // to get a FDE from an address to which FDE is applied. So here
601 // we obtain two addresses and pass them to EhFrameHdr object.
602 if (In<ELFT>::EhFrameHdr) {
603 for (CieRecord *Cie : Cies) {
604 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
605 for (SectionPiece *Fde : Cie->FdePieces) {
606 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
607 uint64_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
608 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
614 template <class ELFT>
615 GotSection<ELFT>::GotSection()
616 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
617 Target->GotEntrySize, ".got") {}
619 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
620 Sym.GotIndex = NumEntries;
624 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
625 if (Sym.GlobalDynIndex != -1U)
627 Sym.GlobalDynIndex = NumEntries;
628 // Global Dynamic TLS entries take two GOT slots.
633 // Reserves TLS entries for a TLS module ID and a TLS block offset.
634 // In total it takes two GOT slots.
635 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
636 if (TlsIndexOff != uint32_t(-1))
638 TlsIndexOff = NumEntries * Config->Wordsize;
643 template <class ELFT>
644 uint64_t GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
645 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
648 template <class ELFT>
649 uint64_t GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
650 return B.GlobalDynIndex * Config->Wordsize;
653 template <class ELFT> void GotSection<ELFT>::finalizeContents() {
654 Size = NumEntries * Config->Wordsize;
657 template <class ELFT> bool GotSection<ELFT>::empty() const {
658 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
659 // we need to emit a GOT even if it's empty.
660 return NumEntries == 0 && !HasGotOffRel;
663 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
664 this->template relocate<ELFT>(Buf, Buf + Size);
667 MipsGotSection::MipsGotSection()
668 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
671 void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
672 // For "true" local symbols which can be referenced from the same module
673 // only compiler creates two instructions for address loading:
675 // lw $8, 0($gp) # R_MIPS_GOT16
676 // addi $8, $8, 0 # R_MIPS_LO16
678 // The first instruction loads high 16 bits of the symbol address while
679 // the second adds an offset. That allows to reduce number of required
680 // GOT entries because only one global offset table entry is necessary
681 // for every 64 KBytes of local data. So for local symbols we need to
682 // allocate number of GOT entries to hold all required "page" addresses.
684 // All global symbols (hidden and regular) considered by compiler uniformly.
685 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
686 // to load address of the symbol. So for each such symbol we need to
687 // allocate dedicated GOT entry to store its address.
689 // If a symbol is preemptible we need help of dynamic linker to get its
690 // final address. The corresponding GOT entries are allocated in the
691 // "global" part of GOT. Entries for non preemptible global symbol allocated
692 // in the "local" part of GOT.
694 // See "Global Offset Table" in Chapter 5:
695 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
696 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
697 // At this point we do not know final symbol value so to reduce number
698 // of allocated GOT entries do the following trick. Save all output
699 // sections referenced by GOT relocations. Then later in the `finalize`
700 // method calculate number of "pages" required to cover all saved output
701 // section and allocate appropriate number of GOT entries.
702 auto *DefSym = cast<DefinedRegular>(&Sym);
703 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
707 // GOT entries created for MIPS TLS relocations behave like
708 // almost GOT entries from other ABIs. They go to the end
709 // of the global offset table.
710 Sym.GotIndex = TlsEntries.size();
711 TlsEntries.push_back(&Sym);
714 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
715 if (S.isInGot() && !A)
717 size_t NewIndex = Items.size();
718 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
720 Items.emplace_back(&S, A);
722 S.GotIndex = NewIndex;
724 if (Sym.isPreemptible()) {
725 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
726 AddEntry(Sym, 0, GlobalEntries);
727 Sym.IsInGlobalMipsGot = true;
728 } else if (Expr == R_MIPS_GOT_OFF32) {
729 AddEntry(Sym, Addend, LocalEntries32);
730 Sym.Is32BitMipsGot = true;
732 // Hold local GOT entries accessed via a 16-bit index separately.
733 // That allows to write them in the beginning of the GOT and keep
734 // their indexes as less as possible to escape relocation's overflow.
735 AddEntry(Sym, Addend, LocalEntries);
739 bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
740 if (Sym.GlobalDynIndex != -1U)
742 Sym.GlobalDynIndex = TlsEntries.size();
743 // Global Dynamic TLS entries take two GOT slots.
744 TlsEntries.push_back(nullptr);
745 TlsEntries.push_back(&Sym);
749 // Reserves TLS entries for a TLS module ID and a TLS block offset.
750 // In total it takes two GOT slots.
751 bool MipsGotSection::addTlsIndex() {
752 if (TlsIndexOff != uint32_t(-1))
754 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
755 TlsEntries.push_back(nullptr);
756 TlsEntries.push_back(nullptr);
760 static uint64_t getMipsPageAddr(uint64_t Addr) {
761 return (Addr + 0x8000) & ~0xffff;
764 static uint64_t getMipsPageCount(uint64_t Size) {
765 return (Size + 0xfffe) / 0xffff + 1;
768 uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
769 int64_t Addend) const {
770 const OutputSection *OutSec =
771 cast<DefinedRegular>(&B)->Section->getOutputSection();
772 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
773 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
774 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
775 assert(Index < PageEntriesNum);
776 return (HeaderEntriesNum + Index) * Config->Wordsize;
779 uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
780 int64_t Addend) const {
781 // Calculate offset of the GOT entries block: TLS, global, local.
782 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
784 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
785 else if (B.IsInGlobalMipsGot)
786 Index += LocalEntries.size() + LocalEntries32.size();
787 else if (B.Is32BitMipsGot)
788 Index += LocalEntries.size();
789 // Calculate offset of the GOT entry in the block.
793 auto It = EntryIndexMap.find({&B, Addend});
794 assert(It != EntryIndexMap.end());
797 return Index * Config->Wordsize;
800 uint64_t MipsGotSection::getTlsOffset() const {
801 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
804 uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
805 return B.GlobalDynIndex * Config->Wordsize;
808 const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
809 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
812 unsigned MipsGotSection::getLocalEntriesNum() const {
813 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
814 LocalEntries32.size();
817 void MipsGotSection::finalizeContents() {
821 void MipsGotSection::updateAllocSize() {
823 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
824 // For each output section referenced by GOT page relocations calculate
825 // and save into PageIndexMap an upper bound of MIPS GOT entries required
826 // to store page addresses of local symbols. We assume the worst case -
827 // each 64kb page of the output section has at least one GOT relocation
828 // against it. And take in account the case when the section intersects
830 P.second = PageEntriesNum;
831 PageEntriesNum += getMipsPageCount(P.first->Size);
833 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
837 bool MipsGotSection::empty() const {
838 // We add the .got section to the result for dynamic MIPS target because
839 // its address and properties are mentioned in the .dynamic section.
840 return Config->Relocatable;
843 uint64_t MipsGotSection::getGp() const {
844 return ElfSym::MipsGp->getVA(0);
847 static uint64_t readUint(uint8_t *Buf) {
849 return read64(Buf, Config->Endianness);
850 return read32(Buf, Config->Endianness);
853 static void writeUint(uint8_t *Buf, uint64_t Val) {
855 write64(Buf, Val, Config->Endianness);
857 write32(Buf, Val, Config->Endianness);
860 void MipsGotSection::writeTo(uint8_t *Buf) {
861 // Set the MSB of the second GOT slot. This is not required by any
862 // MIPS ABI documentation, though.
864 // There is a comment in glibc saying that "The MSB of got[1] of a
865 // gnu object is set to identify gnu objects," and in GNU gold it
866 // says "the second entry will be used by some runtime loaders".
867 // But how this field is being used is unclear.
869 // We are not really willing to mimic other linkers behaviors
870 // without understanding why they do that, but because all files
871 // generated by GNU tools have this special GOT value, and because
872 // we've been doing this for years, it is probably a safe bet to
873 // keep doing this for now. We really need to revisit this to see
874 // if we had to do this.
875 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
876 Buf += HeaderEntriesNum * Config->Wordsize;
877 // Write 'page address' entries to the local part of the GOT.
878 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
879 size_t PageCount = getMipsPageCount(L.first->Size);
880 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
881 for (size_t PI = 0; PI < PageCount; ++PI) {
882 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
883 writeUint(Entry, FirstPageAddr + PI * 0x10000);
886 Buf += PageEntriesNum * Config->Wordsize;
887 auto AddEntry = [&](const GotEntry &SA) {
888 uint8_t *Entry = Buf;
889 Buf += Config->Wordsize;
890 const SymbolBody *Body = SA.first;
891 uint64_t VA = Body->getVA(SA.second);
892 writeUint(Entry, VA);
894 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
895 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
896 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
897 // Initialize TLS-related GOT entries. If the entry has a corresponding
898 // dynamic relocations, leave it initialized by zero. Write down adjusted
899 // TLS symbol's values otherwise. To calculate the adjustments use offsets
900 // for thread-local storage.
901 // https://www.linux-mips.org/wiki/NPTL
902 if (TlsIndexOff != -1U && !Config->Pic)
903 writeUint(Buf + TlsIndexOff, 1);
904 for (const SymbolBody *B : TlsEntries) {
905 if (!B || B->isPreemptible())
907 uint64_t VA = B->getVA();
908 if (B->GotIndex != -1U) {
909 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
910 writeUint(Entry, VA - 0x7000);
912 if (B->GlobalDynIndex != -1U) {
913 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
915 Entry += Config->Wordsize;
916 writeUint(Entry, VA - 0x8000);
921 GotPltSection::GotPltSection()
922 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
923 Target->GotPltEntrySize, ".got.plt") {}
925 void GotPltSection::addEntry(SymbolBody &Sym) {
926 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
927 Entries.push_back(&Sym);
930 size_t GotPltSection::getSize() const {
931 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
932 Target->GotPltEntrySize;
935 void GotPltSection::writeTo(uint8_t *Buf) {
936 Target->writeGotPltHeader(Buf);
937 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
938 for (const SymbolBody *B : Entries) {
939 Target->writeGotPlt(Buf, *B);
940 Buf += Config->Wordsize;
944 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
945 // part of the .got.plt
946 IgotPltSection::IgotPltSection()
947 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
948 Target->GotPltEntrySize,
949 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
951 void IgotPltSection::addEntry(SymbolBody &Sym) {
953 Sym.GotPltIndex = Entries.size();
954 Entries.push_back(&Sym);
957 size_t IgotPltSection::getSize() const {
958 return Entries.size() * Target->GotPltEntrySize;
961 void IgotPltSection::writeTo(uint8_t *Buf) {
962 for (const SymbolBody *B : Entries) {
963 Target->writeIgotPlt(Buf, *B);
964 Buf += Config->Wordsize;
968 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
969 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
971 // ELF string tables start with a NUL byte.
975 // Adds a string to the string table. If HashIt is true we hash and check for
976 // duplicates. It is optional because the name of global symbols are already
977 // uniqued and hashing them again has a big cost for a small value: uniquing
978 // them with some other string that happens to be the same.
979 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
981 auto R = StringMap.insert(std::make_pair(S, this->Size));
983 return R.first->second;
985 unsigned Ret = this->Size;
986 this->Size = this->Size + S.size() + 1;
987 Strings.push_back(S);
991 void StringTableSection::writeTo(uint8_t *Buf) {
992 for (StringRef S : Strings) {
993 memcpy(Buf, S.data(), S.size());
998 // Returns the number of version definition entries. Because the first entry
999 // is for the version definition itself, it is the number of versioned symbols
1000 // plus one. Note that we don't support multiple versions yet.
1001 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1003 template <class ELFT>
1004 DynamicSection<ELFT>::DynamicSection()
1005 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1007 this->Entsize = ELFT::Is64Bits ? 16 : 8;
1009 // .dynamic section is not writable on MIPS.
1010 // See "Special Section" in Chapter 4 in the following document:
1011 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1012 if (Config->EMachine == EM_MIPS)
1013 this->Flags = SHF_ALLOC;
1018 // There are some dynamic entries that don't depend on other sections.
1019 // Such entries can be set early.
1020 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1021 // Add strings to .dynstr early so that .dynstr's size will be
1023 for (StringRef S : Config->AuxiliaryList)
1024 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
1025 if (!Config->RPath.empty())
1026 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1027 In<ELFT>::DynStrTab->addString(Config->RPath)});
1028 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1030 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->SoName)});
1031 if (!Config->SoName.empty())
1032 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
1034 // Set DT_FLAGS and DT_FLAGS_1.
1035 uint32_t DtFlags = 0;
1036 uint32_t DtFlags1 = 0;
1037 if (Config->Bsymbolic)
1038 DtFlags |= DF_SYMBOLIC;
1039 if (Config->ZNodelete)
1040 DtFlags1 |= DF_1_NODELETE;
1041 if (Config->ZNodlopen)
1042 DtFlags1 |= DF_1_NOOPEN;
1044 DtFlags |= DF_BIND_NOW;
1045 DtFlags1 |= DF_1_NOW;
1047 if (Config->ZOrigin) {
1048 DtFlags |= DF_ORIGIN;
1049 DtFlags1 |= DF_1_ORIGIN;
1053 add({DT_FLAGS, DtFlags});
1055 add({DT_FLAGS_1, DtFlags1});
1057 if (!Config->Shared && !Config->Relocatable)
1058 add({DT_DEBUG, (uint64_t)0});
1061 // Add remaining entries to complete .dynamic contents.
1062 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1064 return; // Already finalized.
1066 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1067 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
1068 bool IsRela = Config->IsRela;
1069 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
1070 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
1071 add({IsRela ? DT_RELAENT : DT_RELENT,
1072 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1074 // MIPS dynamic loader does not support RELCOUNT tag.
1075 // The problem is in the tight relation between dynamic
1076 // relocations and GOT. So do not emit this tag on MIPS.
1077 if (Config->EMachine != EM_MIPS) {
1078 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
1079 if (Config->ZCombreloc && NumRelativeRels)
1080 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
1083 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
1084 add({DT_JMPREL, In<ELFT>::RelaPlt});
1085 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
1086 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
1088 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
1091 add({DT_SYMTAB, In<ELFT>::DynSymTab});
1092 add({DT_SYMENT, sizeof(Elf_Sym)});
1093 add({DT_STRTAB, In<ELFT>::DynStrTab});
1094 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
1096 add({DT_TEXTREL, (uint64_t)0});
1097 if (In<ELFT>::GnuHashTab)
1098 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
1099 if (In<ELFT>::HashTab)
1100 add({DT_HASH, In<ELFT>::HashTab});
1102 if (Out::PreinitArray) {
1103 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1104 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
1106 if (Out::InitArray) {
1107 add({DT_INIT_ARRAY, Out::InitArray});
1108 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
1110 if (Out::FiniArray) {
1111 add({DT_FINI_ARRAY, Out::FiniArray});
1112 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
1115 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
1117 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
1120 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1121 if (HasVerNeed || In<ELFT>::VerDef)
1122 add({DT_VERSYM, In<ELFT>::VerSym});
1123 if (In<ELFT>::VerDef) {
1124 add({DT_VERDEF, In<ELFT>::VerDef});
1125 add({DT_VERDEFNUM, getVerDefNum()});
1128 add({DT_VERNEED, In<ELFT>::VerNeed});
1129 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
1132 if (Config->EMachine == EM_MIPS) {
1133 add({DT_MIPS_RLD_VERSION, 1});
1134 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1135 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
1136 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
1137 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1138 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
1139 add({DT_MIPS_GOTSYM, B->DynsymIndex});
1141 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
1142 add({DT_PLTGOT, In<ELFT>::MipsGot});
1143 if (In<ELFT>::MipsRldMap)
1144 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
1147 this->OutSec->Link = this->Link;
1150 this->Size = (Entries.size() + 1) * this->Entsize;
1153 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1154 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1156 for (const Entry &E : Entries) {
1159 case Entry::SecAddr:
1160 P->d_un.d_ptr = E.OutSec->Addr;
1162 case Entry::InSecAddr:
1163 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1165 case Entry::SecSize:
1166 P->d_un.d_val = E.OutSec->Size;
1168 case Entry::SymAddr:
1169 P->d_un.d_ptr = E.Sym->getVA();
1171 case Entry::PlainInt:
1172 P->d_un.d_val = E.Val;
1179 uint64_t DynamicReloc::getOffset() const {
1180 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
1183 int64_t DynamicReloc::getAddend() const {
1185 return Sym->getVA(Addend);
1189 uint32_t DynamicReloc::getSymIndex() const {
1190 if (Sym && !UseSymVA)
1191 return Sym->DynsymIndex;
1195 template <class ELFT>
1196 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1197 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
1198 Config->Wordsize, Name),
1200 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1203 template <class ELFT>
1204 void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
1205 if (Reloc.Type == Target->RelativeRel)
1206 ++NumRelativeRelocs;
1207 Relocs.push_back(Reloc);
1210 template <class ELFT, class RelTy>
1211 static bool compRelocations(const RelTy &A, const RelTy &B) {
1212 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1213 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1214 if (AIsRel != BIsRel)
1217 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1220 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1221 uint8_t *BufBegin = Buf;
1222 for (const DynamicReloc &Rel : Relocs) {
1223 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
1224 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1227 P->r_addend = Rel.getAddend();
1228 P->r_offset = Rel.getOffset();
1229 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
1230 // Dynamic relocation against MIPS GOT section make deal TLS entries
1231 // allocated in the end of the GOT. We need to adjust the offset to take
1232 // in account 'local' and 'global' GOT entries.
1233 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
1234 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1239 std::stable_sort((Elf_Rela *)BufBegin,
1240 (Elf_Rela *)BufBegin + Relocs.size(),
1241 compRelocations<ELFT, Elf_Rela>);
1243 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1244 compRelocations<ELFT, Elf_Rel>);
1248 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1249 return this->Entsize * Relocs.size();
1252 template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
1253 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1254 : In<ELFT>::SymTab->OutSec->SectionIndex;
1256 // Set required output section properties.
1257 this->OutSec->Link = this->Link;
1260 template <class ELFT>
1261 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1262 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1263 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1265 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1266 StrTabSec(StrTabSec) {
1267 this->Entsize = sizeof(Elf_Sym);
1270 // Orders symbols according to their positions in the GOT,
1271 // in compliance with MIPS ABI rules.
1272 // See "Global Offset Table" in Chapter 5 in the following document
1273 // for detailed description:
1274 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1275 static bool sortMipsSymbols(const SymbolTableEntry &L,
1276 const SymbolTableEntry &R) {
1277 // Sort entries related to non-local preemptible symbols by GOT indexes.
1278 // All other entries go to the first part of GOT in arbitrary order.
1279 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1280 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
1281 if (LIsInLocalGot || RIsInLocalGot)
1282 return !RIsInLocalGot;
1283 return L.Symbol->GotIndex < R.Symbol->GotIndex;
1286 // Finalize a symbol table. The ELF spec requires that all local
1287 // symbols precede global symbols, so we sort symbol entries in this
1288 // function. (For .dynsym, we don't do that because symbols for
1289 // dynamic linking are inherently all globals.)
1290 template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
1291 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
1293 // If it is a .dynsym, there should be no local symbols, but we need
1294 // to do a few things for the dynamic linker.
1295 if (this->Type == SHT_DYNSYM) {
1296 // Section's Info field has the index of the first non-local symbol.
1297 // Because the first symbol entry is a null entry, 1 is the first.
1298 this->OutSec->Info = 1;
1300 if (In<ELFT>::GnuHashTab) {
1301 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1302 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1303 } else if (Config->EMachine == EM_MIPS) {
1304 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1308 for (const SymbolTableEntry &S : Symbols)
1309 S.Symbol->DynsymIndex = ++I;
1314 template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1315 if (this->Type == SHT_DYNSYM)
1317 // move all local symbols before global symbols.
1318 auto It = std::stable_partition(
1319 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1320 return S.Symbol->isLocal() ||
1321 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1323 size_t NumLocals = It - Symbols.begin();
1324 this->OutSec->Info = NumLocals + 1;
1327 template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1328 // Adding a local symbol to a .dynsym is a bug.
1329 assert(this->Type != SHT_DYNSYM || !B->isLocal());
1331 bool HashIt = B->isLocal();
1332 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1335 template <class ELFT>
1336 size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
1337 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1338 if (E.Symbol == Body)
1340 // This is used for -r, so we have to handle multiple section
1341 // symbols being combined.
1342 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
1343 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1344 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
1347 if (I == Symbols.end())
1349 return I - Symbols.begin() + 1;
1352 // Write the internal symbol table contents to the output symbol table.
1353 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1354 // The first entry is a null entry as per the ELF spec.
1355 Buf += sizeof(Elf_Sym);
1357 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1359 for (SymbolTableEntry &Ent : Symbols) {
1360 SymbolBody *Body = Ent.Symbol;
1362 // Set st_info and st_other.
1363 if (Body->isLocal()) {
1364 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1366 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1367 ESym->setVisibility(Body->symbol()->Visibility);
1370 ESym->st_name = Ent.StrTabOffset;
1371 ESym->st_size = Body->getSize<ELFT>();
1373 // Set a section index.
1374 if (const OutputSection *OutSec = Body->getOutputSection())
1375 ESym->st_shndx = OutSec->SectionIndex;
1376 else if (isa<DefinedRegular>(Body))
1377 ESym->st_shndx = SHN_ABS;
1378 else if (isa<DefinedCommon>(Body))
1379 ESym->st_shndx = SHN_COMMON;
1381 // st_value is usually an address of a symbol, but that has a
1382 // special meaining for uninstantiated common symbols (this can
1383 // occur if -r is given).
1384 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
1385 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
1387 ESym->st_value = Body->getVA();
1392 // On MIPS we need to mark symbol which has a PLT entry and requires
1393 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1394 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1395 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1396 if (Config->EMachine == EM_MIPS) {
1397 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1399 for (SymbolTableEntry &Ent : Symbols) {
1400 SymbolBody *Body = Ent.Symbol;
1401 if (Body->isInPlt() && Body->NeedsPltAddr)
1402 ESym->st_other |= STO_MIPS_PLT;
1404 if (Config->Relocatable)
1405 if (auto *D = dyn_cast<DefinedRegular>(Body))
1406 if (D->isMipsPIC<ELFT>())
1407 ESym->st_other |= STO_MIPS_PIC;
1413 // .hash and .gnu.hash sections contain on-disk hash tables that map
1414 // symbol names to their dynamic symbol table indices. Their purpose
1415 // is to help the dynamic linker resolve symbols quickly. If ELF files
1416 // don't have them, the dynamic linker has to do linear search on all
1417 // dynamic symbols, which makes programs slower. Therefore, a .hash
1418 // section is added to a DSO by default. A .gnu.hash is added if you
1419 // give the -hash-style=gnu or -hash-style=both option.
1421 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
1422 // Each ELF file has a list of DSOs that the ELF file depends on and a
1423 // list of dynamic symbols that need to be resolved from any of the
1424 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1425 // where m is the number of DSOs and n is the number of dynamic
1426 // symbols. For modern large programs, both m and n are large. So
1427 // making each step faster by using hash tables substiantially
1428 // improves time to load programs.
1430 // (Note that this is not the only way to design the shared library.
1431 // For instance, the Windows DLL takes a different approach. On
1432 // Windows, each dynamic symbol has a name of DLL from which the symbol
1433 // has to be resolved. That makes the cost of symbol resolution O(n).
1434 // This disables some hacky techniques you can use on Unix such as
1435 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1437 // Due to historical reasons, we have two different hash tables, .hash
1438 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1439 // and better version of .hash. .hash is just an on-disk hash table, but
1440 // .gnu.hash has a bloom filter in addition to a hash table to skip
1441 // DSOs very quickly. If you are sure that your dynamic linker knows
1442 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1443 // safe bet is to specify -hash-style=both for backward compatibilty.
1444 template <class ELFT>
1445 GnuHashTableSection<ELFT>::GnuHashTableSection()
1446 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1449 template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
1450 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1452 // Computes bloom filter size in word size. We want to allocate 8
1453 // bits for each symbol. It must be a power of two.
1454 if (Symbols.empty())
1457 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
1459 Size = 16; // Header
1460 Size += Config->Wordsize * MaskWords; // Bloom filter
1461 Size += NBuckets * 4; // Hash buckets
1462 Size += Symbols.size() * 4; // Hash values
1465 template <class ELFT>
1466 void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1468 write32(Buf, NBuckets, Config->Endianness);
1469 write32(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size(),
1470 Config->Endianness);
1471 write32(Buf + 8, MaskWords, Config->Endianness);
1472 write32(Buf + 12, getShift2(), Config->Endianness);
1475 // Write a bloom filter and a hash table.
1476 writeBloomFilter(Buf);
1477 Buf += Config->Wordsize * MaskWords;
1478 writeHashTable(Buf);
1481 // This function writes a 2-bit bloom filter. This bloom filter alone
1482 // usually filters out 80% or more of all symbol lookups [1].
1483 // The dynamic linker uses the hash table only when a symbol is not
1484 // filtered out by a bloom filter.
1486 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1487 // p.9, https://www.akkadia.org/drepper/dsohowto.pdf
1488 template <class ELFT>
1489 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
1490 const unsigned C = Config->Wordsize * 8;
1491 for (const Entry &Sym : Symbols) {
1492 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1493 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1494 Val |= uint64_t(1) << (Sym.Hash % C);
1495 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1496 writeUint(Buf + I * Config->Wordsize, Val);
1500 template <class ELFT>
1501 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
1502 // Group symbols by hash value.
1503 std::vector<std::vector<Entry>> Syms(NBuckets);
1504 for (const Entry &Ent : Symbols)
1505 Syms[Ent.Hash % NBuckets].push_back(Ent);
1507 // Write hash buckets. Hash buckets contain indices in the following
1508 // hash value table.
1509 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
1510 for (size_t I = 0; I < NBuckets; ++I)
1511 if (!Syms[I].empty())
1512 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
1514 // Write a hash value table. It represents a sequence of chains that
1515 // share the same hash modulo value. The last element of each chain
1516 // is terminated by LSB 1.
1517 uint32_t *Values = Buckets + NBuckets;
1519 for (std::vector<Entry> &Vec : Syms) {
1522 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1523 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1524 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
1528 static uint32_t hashGnu(StringRef Name) {
1530 for (uint8_t C : Name)
1531 H = (H << 5) + H + C;
1535 // Returns a number of hash buckets to accomodate given number of elements.
1536 // We want to choose a moderate number that is not too small (which
1537 // causes too many hash collisions) and not too large (which wastes
1540 // We return a prime number because it (is believed to) achieve good
1541 // hash distribution.
1542 static size_t getBucketSize(size_t NumSymbols) {
1543 // List of largest prime numbers that are not greater than 2^n + 1.
1544 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1545 251, 127, 61, 31, 13, 7, 3, 1})
1546 if (N <= NumSymbols)
1551 // Add symbols to this symbol hash table. Note that this function
1552 // destructively sort a given vector -- which is needed because
1553 // GNU-style hash table places some sorting requirements.
1554 template <class ELFT>
1555 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
1556 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1557 // its type correctly.
1558 std::vector<SymbolTableEntry>::iterator Mid =
1559 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1560 return S.Symbol->isUndefined();
1565 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1566 SymbolBody *B = Ent.Symbol;
1567 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
1570 NBuckets = getBucketSize(Symbols.size());
1571 std::stable_sort(Symbols.begin(), Symbols.end(),
1572 [&](const Entry &L, const Entry &R) {
1573 return L.Hash % NBuckets < R.Hash % NBuckets;
1576 V.erase(Mid, V.end());
1577 for (const Entry &Ent : Symbols)
1578 V.push_back({Ent.Body, Ent.StrTabOffset});
1581 template <class ELFT>
1582 HashTableSection<ELFT>::HashTableSection()
1583 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1587 template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
1588 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1590 unsigned NumEntries = 2; // nbucket and nchain.
1591 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1593 // Create as many buckets as there are symbols.
1594 // FIXME: This is simplistic. We can try to optimize it, but implementing
1595 // support for SHT_GNU_HASH is probably even more profitable.
1596 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
1597 this->Size = NumEntries * 4;
1600 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1601 // A 32-bit integer type in the target endianness.
1602 typedef typename ELFT::Word Elf_Word;
1604 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
1606 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1607 *P++ = NumSymbols; // nbucket
1608 *P++ = NumSymbols; // nchain
1610 Elf_Word *Buckets = P;
1611 Elf_Word *Chains = P + NumSymbols;
1613 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1614 SymbolBody *Body = S.Symbol;
1615 StringRef Name = Body->getName();
1616 unsigned I = Body->DynsymIndex;
1617 uint32_t Hash = hashSysV(Name) % NumSymbols;
1618 Chains[I] = Buckets[Hash];
1623 PltSection::PltSection(size_t S)
1624 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
1627 void PltSection::writeTo(uint8_t *Buf) {
1628 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1629 // linker to resolve dynsyms at runtime. Write such code.
1630 if (HeaderSize != 0)
1631 Target->writePltHeader(Buf);
1632 size_t Off = HeaderSize;
1633 // The IPlt is immediately after the Plt, account for this in RelOff
1634 unsigned PltOff = getPltRelocOff();
1636 for (auto &I : Entries) {
1637 const SymbolBody *B = I.first;
1638 unsigned RelOff = I.second + PltOff;
1639 uint64_t Got = B->getGotPltVA();
1640 uint64_t Plt = this->getVA() + Off;
1641 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1642 Off += Target->PltEntrySize;
1646 template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
1647 Sym.PltIndex = Entries.size();
1648 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1649 if (HeaderSize == 0) {
1650 PltRelocSection = In<ELFT>::RelaIplt;
1651 Sym.IsInIplt = true;
1653 unsigned RelOff = PltRelocSection->getRelocOffset();
1654 Entries.push_back(std::make_pair(&Sym, RelOff));
1657 size_t PltSection::getSize() const {
1658 return HeaderSize + Entries.size() * Target->PltEntrySize;
1661 // Some architectures such as additional symbols in the PLT section. For
1662 // example ARM uses mapping symbols to aid disassembly
1663 void PltSection::addSymbols() {
1664 // The PLT may have symbols defined for the Header, the IPLT has no header
1665 if (HeaderSize != 0)
1666 Target->addPltHeaderSymbols(this);
1667 size_t Off = HeaderSize;
1668 for (size_t I = 0; I < Entries.size(); ++I) {
1669 Target->addPltSymbols(this, Off);
1670 Off += Target->PltEntrySize;
1674 unsigned PltSection::getPltRelocOff() const {
1675 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
1678 GdbIndexSection::GdbIndexSection()
1679 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
1680 StringPool(llvm::StringTableBuilder::ELF) {}
1682 // Iterative hash function for symbol's name is described in .gdb_index format
1683 // specification. Note that we use one for version 5 to 7 here, it is different
1685 static uint32_t hash(StringRef Str) {
1687 for (uint8_t C : Str)
1688 R = R * 67 + tolower(C) - 113;
1692 static std::vector<std::pair<uint64_t, uint64_t>>
1693 readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1694 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1695 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1696 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1700 static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1702 for (InputSectionBase *S : Arr)
1703 if (S && S != &InputSection::Discarded)
1704 if (Offset >= S->getOffsetInFile() &&
1705 Offset < S->getOffsetInFile() + S->getSize())
1710 static std::vector<AddressEntry>
1711 readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1712 std::vector<AddressEntry> Ret;
1714 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1715 DWARFAddressRangesVector Ranges;
1716 CU->collectAddressRanges(Ranges);
1718 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
1719 for (std::pair<uint64_t, uint64_t> &R : Ranges)
1720 if (InputSectionBase *S = findSection(Sections, R.first))
1721 Ret.push_back({S, R.first - S->getOffsetInFile(),
1722 R.second - S->getOffsetInFile(), CurrentCU});
1728 static std::vector<std::pair<StringRef, uint8_t>>
1729 readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1730 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1731 Dwarf.getGnuPubTypesSection()};
1733 std::vector<std::pair<StringRef, uint8_t>> Ret;
1734 for (StringRef D : Data) {
1735 DWARFDebugPubTable PubTable(D, IsLE, true);
1736 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1737 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1738 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1743 class ObjInfoTy : public llvm::LoadedObjectInfo {
1744 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1745 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1746 if (S.getFlags() & ELF::SHF_ALLOC)
1747 return S.getOffset();
1751 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1754 void GdbIndexSection::readDwarf(InputSection *Sec) {
1755 Expected<std::unique_ptr<object::ObjectFile>> Obj =
1756 object::ObjectFile::createObjectFile(Sec->File->MB);
1758 error(toString(Sec->File) + ": error creating DWARF context");
1763 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
1765 size_t CuId = CompilationUnits.size();
1766 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1767 CompilationUnits.push_back(P);
1769 for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
1770 AddressArea.push_back(Ent);
1772 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
1773 readPubNamesAndTypes(Dwarf, Config->IsLE);
1775 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1776 uint32_t Hash = hash(Pair.first);
1777 size_t Offset = StringPool.add(Pair.first);
1781 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1783 Sym->CuVectorIndex = CuVectors.size();
1784 CuVectors.push_back({{CuId, Pair.second}});
1788 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
1792 void GdbIndexSection::finalizeContents() {
1797 for (InputSectionBase *S : InputSections)
1798 if (InputSection *IS = dyn_cast<InputSection>(S))
1799 if (IS->OutSec && IS->Name == ".debug_info")
1802 SymbolTable.finalizeContents();
1804 // GdbIndex header consist from version fields
1805 // and 5 more fields with different kinds of offsets.
1806 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1807 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
1809 ConstantPoolOffset =
1810 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1812 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1813 CuVectorsOffset.push_back(CuVectorsSize);
1814 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1816 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1818 StringPool.finalizeInOrder();
1821 size_t GdbIndexSection::getSize() const {
1822 const_cast<GdbIndexSection *>(this)->finalizeContents();
1823 return StringPoolOffset + StringPool.getSize();
1826 void GdbIndexSection::writeTo(uint8_t *Buf) {
1827 write32le(Buf, 7); // Write version.
1828 write32le(Buf + 4, CuListOffset); // CU list offset.
1829 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1830 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1831 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1832 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
1835 // Write the CU list.
1836 for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
1837 write64le(Buf, CU.first);
1838 write64le(Buf + 8, CU.second);
1842 // Write the address area.
1843 for (AddressEntry &E : AddressArea) {
1844 uint64_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
1845 write64le(Buf, BaseAddr + E.LowAddress);
1846 write64le(Buf + 8, BaseAddr + E.HighAddress);
1847 write32le(Buf + 16, E.CuIndex);
1851 // Write the symbol table.
1852 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1853 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1856 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1857 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1858 write32le(Buf, NameOffset);
1859 write32le(Buf + 4, CuVectorOffset);
1864 // Write the CU vectors into the constant pool.
1865 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1866 write32le(Buf, CuVec.size());
1868 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1869 uint32_t Index = P.first;
1870 uint8_t Flags = P.second;
1871 Index |= Flags << 24;
1872 write32le(Buf, Index);
1877 StringPool.write(Buf);
1880 bool GdbIndexSection::empty() const {
1881 return !Out::DebugInfo;
1884 template <class ELFT>
1885 EhFrameHeader<ELFT>::EhFrameHeader()
1886 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1888 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1889 // Each entry of the search table consists of two values,
1890 // the starting PC from where FDEs covers, and the FDE's address.
1891 // It is sorted by PC.
1892 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1893 const endianness E = ELFT::TargetEndianness;
1895 // Sort the FDE list by their PC and uniqueify. Usually there is only
1896 // one FDE for a PC (i.e. function), but if ICF merges two functions
1897 // into one, there can be more than one FDEs pointing to the address.
1898 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1899 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1900 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1901 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1904 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1905 Buf[2] = DW_EH_PE_udata4;
1906 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1907 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
1908 write32<E>(Buf + 8, Fdes.size());
1911 uint64_t VA = this->getVA();
1912 for (FdeData &Fde : Fdes) {
1913 write32<E>(Buf, Fde.Pc - VA);
1914 write32<E>(Buf + 4, Fde.FdeVA - VA);
1919 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1920 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1921 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
1924 template <class ELFT>
1925 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1926 Fdes.push_back({Pc, FdeVA});
1929 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1930 return In<ELFT>::EhFrame->empty();
1933 template <class ELFT>
1934 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1935 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1936 ".gnu.version_d") {}
1938 static StringRef getFileDefName() {
1939 if (!Config->SoName.empty())
1940 return Config->SoName;
1941 return Config->OutputFile;
1944 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
1945 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1946 for (VersionDefinition &V : Config->VersionDefinitions)
1947 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1949 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1951 // sh_info should be set to the number of definitions. This fact is missed in
1952 // documentation, but confirmed by binutils community:
1953 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1954 this->OutSec->Info = getVerDefNum();
1957 template <class ELFT>
1958 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1959 StringRef Name, size_t NameOff) {
1960 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1961 Verdef->vd_version = 1;
1963 Verdef->vd_aux = sizeof(Elf_Verdef);
1964 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1965 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1966 Verdef->vd_ndx = Index;
1967 Verdef->vd_hash = hashSysV(Name);
1969 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1970 Verdaux->vda_name = NameOff;
1971 Verdaux->vda_next = 0;
1974 template <class ELFT>
1975 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1976 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1978 for (VersionDefinition &V : Config->VersionDefinitions) {
1979 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1980 writeOne(Buf, V.Id, V.Name, V.NameOff);
1983 // Need to terminate the last version definition.
1984 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1985 Verdef->vd_next = 0;
1988 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1989 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1992 template <class ELFT>
1993 VersionTableSection<ELFT>::VersionTableSection()
1994 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1996 this->Entsize = sizeof(Elf_Versym);
1999 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
2000 // At the moment of june 2016 GNU docs does not mention that sh_link field
2001 // should be set, but Sun docs do. Also readelf relies on this field.
2002 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
2005 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2006 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2009 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2010 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2011 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2012 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2017 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2018 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2021 template <class ELFT>
2022 VersionNeedSection<ELFT>::VersionNeedSection()
2023 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2025 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2026 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2027 // First identifiers are reserved by verdef section if it exist.
2028 NextIndex = getVerDefNum() + 1;
2031 template <class ELFT>
2032 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2033 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2035 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2039 auto *File = cast<SharedFile<ELFT>>(SS->File);
2041 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2042 // to create one by adding it to our needed list and creating a dynstr entry
2044 if (File->VerdefMap.empty())
2045 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->SoName)});
2046 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
2047 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2048 // prepare to create one by allocating a version identifier and creating a
2049 // dynstr entry for the version name.
2050 if (NV.Index == 0) {
2051 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2052 Ver->getAux()->vda_name);
2053 NV.Index = NextIndex++;
2055 SS->symbol()->VersionId = NV.Index;
2058 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2059 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2060 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2061 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2063 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2064 // Create an Elf_Verneed for this DSO.
2065 Verneed->vn_version = 1;
2066 Verneed->vn_cnt = P.first->VerdefMap.size();
2067 Verneed->vn_file = P.second;
2069 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2070 Verneed->vn_next = sizeof(Elf_Verneed);
2073 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2074 // VerdefMap, which will only contain references to needed version
2075 // definitions. Each Elf_Vernaux is based on the information contained in
2076 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2077 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2078 // data structures within a single input file.
2079 for (auto &NV : P.first->VerdefMap) {
2080 Vernaux->vna_hash = NV.first->vd_hash;
2081 Vernaux->vna_flags = 0;
2082 Vernaux->vna_other = NV.second.Index;
2083 Vernaux->vna_name = NV.second.StrTab;
2084 Vernaux->vna_next = sizeof(Elf_Vernaux);
2088 Vernaux[-1].vna_next = 0;
2090 Verneed[-1].vn_next = 0;
2093 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2094 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2095 this->OutSec->Info = Needed.size();
2098 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2099 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2100 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2101 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2105 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2106 return getNeedNum() == 0;
2109 MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
2110 uint64_t Flags, uint32_t Alignment)
2111 : SyntheticSection(Flags, Type, Alignment, Name),
2112 Builder(StringTableBuilder::RAW, Alignment) {}
2114 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2116 MS->MergeSec = this;
2117 Sections.push_back(MS);
2120 void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2122 bool MergeSyntheticSection::shouldTailMerge() const {
2123 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2126 void MergeSyntheticSection::finalizeTailMerge() {
2127 // Add all string pieces to the string table builder to create section
2129 for (MergeInputSection *Sec : Sections)
2130 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2131 if (Sec->Pieces[I].Live)
2132 Builder.add(Sec->getData(I));
2134 // Fix the string table content. After this, the contents will never change.
2137 // finalize() fixed tail-optimized strings, so we can now get
2138 // offsets of strings. Get an offset for each string and save it
2139 // to a corresponding StringPiece for easy access.
2140 for (MergeInputSection *Sec : Sections)
2141 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2142 if (Sec->Pieces[I].Live)
2143 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2146 void MergeSyntheticSection::finalizeNoTailMerge() {
2147 // Add all string pieces to the string table builder to create section
2148 // contents. Because we are not tail-optimizing, offsets of strings are
2149 // fixed when they are added to the builder (string table builder contains
2150 // a hash table from strings to offsets).
2151 for (MergeInputSection *Sec : Sections)
2152 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2153 if (Sec->Pieces[I].Live)
2154 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2156 Builder.finalizeInOrder();
2159 void MergeSyntheticSection::finalizeContents() {
2163 if (shouldTailMerge())
2164 finalizeTailMerge();
2166 finalizeNoTailMerge();
2169 size_t MergeSyntheticSection::getSize() const {
2170 // We should finalize string builder to know the size.
2171 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
2172 return Builder.getSize();
2175 MipsRldMapSection::MipsRldMapSection()
2176 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2179 void MipsRldMapSection::writeTo(uint8_t *Buf) {
2180 // Apply filler from linker script.
2181 Optional<uint32_t> Fill = Script->getFiller(this->Name);
2182 if (!Fill || *Fill == 0)
2185 uint64_t Filler = *Fill;
2186 Filler = (Filler << 32) | Filler;
2187 memcpy(Buf, &Filler, getSize());
2190 ARMExidxSentinelSection::ARMExidxSentinelSection()
2191 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2192 Config->Wordsize, ".ARM.exidx") {}
2194 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
2195 // This section will have been sorted last in the .ARM.exidx table.
2196 // This table entry will have the form:
2197 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
2198 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
2199 // Get the InputSection before us, we are by definition last
2200 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
2201 InputSection *LE = *(++RI);
2202 InputSection *LC = cast<InputSection>(LE->getLinkOrderDep());
2203 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
2204 uint64_t P = this->getVA();
2205 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2206 write32le(Buf + 4, 0x1);
2209 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
2210 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
2211 Config->Wordsize, ".text.thunk") {
2213 this->OutSecOff = Off;
2216 void ThunkSection::addThunk(Thunk *T) {
2217 uint64_t Off = alignTo(Size, T->alignment);
2219 Thunks.push_back(T);
2220 T->addSymbols(*this);
2221 Size = Off + T->size();
2224 void ThunkSection::writeTo(uint8_t *Buf) {
2225 for (const Thunk *T : Thunks)
2226 T->writeTo(Buf + T->Offset, *this);
2229 InputSection *ThunkSection::getTargetInputSection() const {
2230 const Thunk *T = Thunks.front();
2231 return T->getTargetInputSection();
2234 InputSection *InX::ARMAttributes;
2235 BssSection *InX::Bss;
2236 BssSection *InX::BssRelRo;
2237 BuildIdSection *InX::BuildId;
2238 InputSection *InX::Common;
2239 StringTableSection *InX::DynStrTab;
2240 InputSection *InX::Interp;
2241 GdbIndexSection *InX::GdbIndex;
2242 GotPltSection *InX::GotPlt;
2243 IgotPltSection *InX::IgotPlt;
2244 MipsGotSection *InX::MipsGot;
2245 MipsRldMapSection *InX::MipsRldMap;
2246 PltSection *InX::Plt;
2247 PltSection *InX::Iplt;
2248 StringTableSection *InX::ShStrTab;
2249 StringTableSection *InX::StrTab;
2251 template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2252 template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2253 template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2254 template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2256 template InputSection *elf::createCommonSection<ELF32LE>();
2257 template InputSection *elf::createCommonSection<ELF32BE>();
2258 template InputSection *elf::createCommonSection<ELF64LE>();
2259 template InputSection *elf::createCommonSection<ELF64BE>();
2261 template MergeInputSection *elf::createCommentSection<ELF32LE>();
2262 template MergeInputSection *elf::createCommentSection<ELF32BE>();
2263 template MergeInputSection *elf::createCommentSection<ELF64LE>();
2264 template MergeInputSection *elf::createCommentSection<ELF64BE>();
2266 template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t,
2268 InputSectionBase *);
2269 template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t,
2271 InputSectionBase *);
2272 template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
2274 InputSectionBase *);
2275 template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
2277 InputSectionBase *);
2279 template class elf::MipsAbiFlagsSection<ELF32LE>;
2280 template class elf::MipsAbiFlagsSection<ELF32BE>;
2281 template class elf::MipsAbiFlagsSection<ELF64LE>;
2282 template class elf::MipsAbiFlagsSection<ELF64BE>;
2284 template class elf::MipsOptionsSection<ELF32LE>;
2285 template class elf::MipsOptionsSection<ELF32BE>;
2286 template class elf::MipsOptionsSection<ELF64LE>;
2287 template class elf::MipsOptionsSection<ELF64BE>;
2289 template class elf::MipsReginfoSection<ELF32LE>;
2290 template class elf::MipsReginfoSection<ELF32BE>;
2291 template class elf::MipsReginfoSection<ELF64LE>;
2292 template class elf::MipsReginfoSection<ELF64BE>;
2294 template class elf::GotSection<ELF32LE>;
2295 template class elf::GotSection<ELF32BE>;
2296 template class elf::GotSection<ELF64LE>;
2297 template class elf::GotSection<ELF64BE>;
2299 template class elf::DynamicSection<ELF32LE>;
2300 template class elf::DynamicSection<ELF32BE>;
2301 template class elf::DynamicSection<ELF64LE>;
2302 template class elf::DynamicSection<ELF64BE>;
2304 template class elf::RelocationSection<ELF32LE>;
2305 template class elf::RelocationSection<ELF32BE>;
2306 template class elf::RelocationSection<ELF64LE>;
2307 template class elf::RelocationSection<ELF64BE>;
2309 template class elf::SymbolTableSection<ELF32LE>;
2310 template class elf::SymbolTableSection<ELF32BE>;
2311 template class elf::SymbolTableSection<ELF64LE>;
2312 template class elf::SymbolTableSection<ELF64BE>;
2314 template class elf::GnuHashTableSection<ELF32LE>;
2315 template class elf::GnuHashTableSection<ELF32BE>;
2316 template class elf::GnuHashTableSection<ELF64LE>;
2317 template class elf::GnuHashTableSection<ELF64BE>;
2319 template class elf::HashTableSection<ELF32LE>;
2320 template class elf::HashTableSection<ELF32BE>;
2321 template class elf::HashTableSection<ELF64LE>;
2322 template class elf::HashTableSection<ELF64BE>;
2324 template class elf::EhFrameHeader<ELF32LE>;
2325 template class elf::EhFrameHeader<ELF32BE>;
2326 template class elf::EhFrameHeader<ELF64LE>;
2327 template class elf::EhFrameHeader<ELF64BE>;
2329 template class elf::VersionTableSection<ELF32LE>;
2330 template class elf::VersionTableSection<ELF32BE>;
2331 template class elf::VersionTableSection<ELF64LE>;
2332 template class elf::VersionTableSection<ELF64BE>;
2334 template class elf::VersionNeedSection<ELF32LE>;
2335 template class elf::VersionNeedSection<ELF32BE>;
2336 template class elf::VersionNeedSection<ELF64LE>;
2337 template class elf::VersionNeedSection<ELF64BE>;
2339 template class elf::VersionDefinitionSection<ELF32LE>;
2340 template class elf::VersionDefinitionSection<ELF32BE>;
2341 template class elf::VersionDefinitionSection<ELF64LE>;
2342 template class elf::VersionDefinitionSection<ELF64BE>;
2344 template class elf::EhFrameSection<ELF32LE>;
2345 template class elf::EhFrameSection<ELF32BE>;
2346 template class elf::EhFrameSection<ELF64LE>;
2347 template class elf::EhFrameSection<ELF64BE>;