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"
22 #include "OutputSections.h"
24 #include "SymbolTable.h"
28 #include "lld/Common/ErrorHandler.h"
29 #include "lld/Common/Memory.h"
30 #include "lld/Common/Threads.h"
31 #include "lld/Common/Version.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
34 #include "llvm/Object/Decompressor.h"
35 #include "llvm/Object/ELFObjectFile.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/LEB128.h"
38 #include "llvm/Support/MD5.h"
39 #include "llvm/Support/RandomNumberGenerator.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/xxhash.h"
46 using namespace llvm::dwarf;
47 using namespace llvm::ELF;
48 using namespace llvm::object;
49 using namespace llvm::support;
50 using namespace llvm::support::endian;
53 using namespace lld::elf;
55 constexpr size_t MergeNoTailSection::NumShards;
57 static void write32(void *Buf, uint32_t Val) {
58 endian::write32(Buf, Val, Config->Endianness);
61 uint64_t SyntheticSection::getVA() const {
62 if (OutputSection *Sec = getParent())
63 return Sec->Addr + OutSecOff;
67 // Returns an LLD version string.
68 static ArrayRef<uint8_t> getVersion() {
69 // Check LLD_VERSION first for ease of testing.
70 // You can get consitent output by using the environment variable.
71 // This is only for testing.
72 StringRef S = getenv("LLD_VERSION");
74 S = Saver.save(Twine("Linker: ") + getLLDVersion());
76 // +1 to include the terminating '\0'.
77 return {(const uint8_t *)S.data(), S.size() + 1};
80 // Creates a .comment section containing LLD version info.
81 // With this feature, you can identify LLD-generated binaries easily
82 // by "readelf --string-dump .comment <file>".
83 // The returned object is a mergeable string section.
84 template <class ELFT> MergeInputSection *elf::createCommentSection() {
85 typename ELFT::Shdr Hdr = {};
86 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
87 Hdr.sh_type = SHT_PROGBITS;
92 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
93 Ret->Data = getVersion();
97 // .MIPS.abiflags section.
99 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
100 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
102 this->Entsize = sizeof(Elf_Mips_ABIFlags);
105 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
106 memcpy(Buf, &Flags, sizeof(Flags));
109 template <class ELFT>
110 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
111 Elf_Mips_ABIFlags Flags = {};
114 for (InputSectionBase *Sec : InputSections) {
115 if (Sec->Type != SHT_MIPS_ABIFLAGS)
120 std::string Filename = toString(Sec->File);
121 const size_t Size = Sec->Data.size();
122 // Older version of BFD (such as the default FreeBSD linker) concatenate
123 // .MIPS.abiflags instead of merging. To allow for this case (or potential
124 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
125 if (Size < sizeof(Elf_Mips_ABIFlags)) {
126 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
127 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
130 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
131 if (S->version != 0) {
132 error(Filename + ": unexpected .MIPS.abiflags version " +
137 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
138 // select the highest number of ISA/Rev/Ext.
139 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
140 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
141 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
142 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
143 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
144 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
145 Flags.ases |= S->ases;
146 Flags.flags1 |= S->flags1;
147 Flags.flags2 |= S->flags2;
148 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
152 return make<MipsAbiFlagsSection<ELFT>>(Flags);
156 // .MIPS.options section.
157 template <class ELFT>
158 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
159 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
161 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
164 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
165 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
166 Options->kind = ODK_REGINFO;
167 Options->size = getSize();
169 if (!Config->Relocatable)
170 Reginfo.ri_gp_value = InX::MipsGot->getGp();
171 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
174 template <class ELFT>
175 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
180 std::vector<InputSectionBase *> Sections;
181 for (InputSectionBase *Sec : InputSections)
182 if (Sec->Type == SHT_MIPS_OPTIONS)
183 Sections.push_back(Sec);
185 if (Sections.empty())
188 Elf_Mips_RegInfo Reginfo = {};
189 for (InputSectionBase *Sec : Sections) {
192 std::string Filename = toString(Sec->File);
193 ArrayRef<uint8_t> D = Sec->Data;
196 if (D.size() < sizeof(Elf_Mips_Options)) {
197 error(Filename + ": invalid size of .MIPS.options section");
201 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
202 if (Opt->kind == ODK_REGINFO) {
203 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
204 error(Filename + ": unsupported non-zero ri_gp_value");
205 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
206 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
211 fatal(Filename + ": zero option descriptor size");
212 D = D.slice(Opt->size);
216 return make<MipsOptionsSection<ELFT>>(Reginfo);
219 // MIPS .reginfo section.
220 template <class ELFT>
221 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
222 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
224 this->Entsize = sizeof(Elf_Mips_RegInfo);
227 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
228 if (!Config->Relocatable)
229 Reginfo.ri_gp_value = InX::MipsGot->getGp();
230 memcpy(Buf, &Reginfo, sizeof(Reginfo));
233 template <class ELFT>
234 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
235 // Section should be alive for O32 and N32 ABIs only.
239 std::vector<InputSectionBase *> Sections;
240 for (InputSectionBase *Sec : InputSections)
241 if (Sec->Type == SHT_MIPS_REGINFO)
242 Sections.push_back(Sec);
244 if (Sections.empty())
247 Elf_Mips_RegInfo Reginfo = {};
248 for (InputSectionBase *Sec : Sections) {
251 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
252 error(toString(Sec->File) + ": invalid size of .reginfo section");
255 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
256 if (Config->Relocatable && R->ri_gp_value)
257 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
259 Reginfo.ri_gprmask |= R->ri_gprmask;
260 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
263 return make<MipsReginfoSection<ELFT>>(Reginfo);
266 InputSection *elf::createInterpSection() {
267 // StringSaver guarantees that the returned string ends with '\0'.
268 StringRef S = Saver.save(Config->DynamicLinker);
269 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
272 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
277 Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
278 uint64_t Size, InputSectionBase *Section) {
279 auto *S = make<Defined>(Section->File, Name, STB_LOCAL, STV_DEFAULT, Type,
280 Value, Size, Section);
282 InX::SymTab->addSymbol(S);
286 static size_t getHashSize() {
287 switch (Config->BuildId) {
288 case BuildIdKind::Fast:
290 case BuildIdKind::Md5:
291 case BuildIdKind::Uuid:
293 case BuildIdKind::Sha1:
295 case BuildIdKind::Hexstring:
296 return Config->BuildIdVector.size();
298 llvm_unreachable("unknown BuildIdKind");
302 BuildIdSection::BuildIdSection()
303 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
304 HashSize(getHashSize()) {}
306 void BuildIdSection::writeTo(uint8_t *Buf) {
307 write32(Buf, 4); // Name size
308 write32(Buf + 4, HashSize); // Content size
309 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
310 memcpy(Buf + 12, "GNU", 4); // Name string
314 // Split one uint8 array into small pieces of uint8 arrays.
315 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
317 std::vector<ArrayRef<uint8_t>> Ret;
318 while (Arr.size() > ChunkSize) {
319 Ret.push_back(Arr.take_front(ChunkSize));
320 Arr = Arr.drop_front(ChunkSize);
327 // Computes a hash value of Data using a given hash function.
328 // In order to utilize multiple cores, we first split data into 1MB
329 // chunks, compute a hash for each chunk, and then compute a hash value
330 // of the hash values.
331 void BuildIdSection::computeHash(
332 llvm::ArrayRef<uint8_t> Data,
333 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
334 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
335 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
337 // Compute hash values.
338 parallelForEachN(0, Chunks.size(), [&](size_t I) {
339 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
342 // Write to the final output buffer.
343 HashFn(HashBuf, Hashes);
346 BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
347 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
349 if (OutputSection *Sec = getParent())
350 Sec->Alignment = std::max(Sec->Alignment, Alignment);
354 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
355 switch (Config->BuildId) {
356 case BuildIdKind::Fast:
357 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
358 write64le(Dest, xxHash64(toStringRef(Arr)));
361 case BuildIdKind::Md5:
362 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
363 memcpy(Dest, MD5::hash(Arr).data(), 16);
366 case BuildIdKind::Sha1:
367 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
368 memcpy(Dest, SHA1::hash(Arr).data(), 20);
371 case BuildIdKind::Uuid:
372 if (auto EC = getRandomBytes(HashBuf, HashSize))
373 error("entropy source failure: " + EC.message());
375 case BuildIdKind::Hexstring:
376 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
379 llvm_unreachable("unknown BuildIdKind");
383 EhFrameSection::EhFrameSection()
384 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
386 // Search for an existing CIE record or create a new one.
387 // CIE records from input object files are uniquified by their contents
388 // and where their relocations point to.
389 template <class ELFT, class RelTy>
390 CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
391 auto *Sec = cast<EhInputSection>(Cie.Sec);
392 if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
393 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
395 Symbol *Personality = nullptr;
396 unsigned FirstRelI = Cie.FirstRelocation;
397 if (FirstRelI != (unsigned)-1)
399 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
401 // Search for an existing CIE by CIE contents/relocation target pair.
402 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
404 // If not found, create a new one.
406 Rec = make<CieRecord>();
408 CieRecords.push_back(Rec);
413 // There is one FDE per function. Returns true if a given FDE
414 // points to a live function.
415 template <class ELFT, class RelTy>
416 bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
417 auto *Sec = cast<EhInputSection>(Fde.Sec);
418 unsigned FirstRelI = Fde.FirstRelocation;
420 // An FDE should point to some function because FDEs are to describe
421 // functions. That's however not always the case due to an issue of
422 // ld.gold with -r. ld.gold may discard only functions and leave their
423 // corresponding FDEs, which results in creating bad .eh_frame sections.
424 // To deal with that, we ignore such FDEs.
425 if (FirstRelI == (unsigned)-1)
428 const RelTy &Rel = Rels[FirstRelI];
429 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
431 // FDEs for garbage-collected or merged-by-ICF sections are dead.
432 if (auto *D = dyn_cast<Defined>(&B))
433 if (SectionBase *Sec = D->Section)
438 // .eh_frame is a sequence of CIE or FDE records. In general, there
439 // is one CIE record per input object file which is followed by
440 // a list of FDEs. This function searches an existing CIE or create a new
441 // one and associates FDEs to the CIE.
442 template <class ELFT, class RelTy>
443 void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
444 DenseMap<size_t, CieRecord *> OffsetToCie;
445 for (EhSectionPiece &Piece : Sec->Pieces) {
446 // The empty record is the end marker.
450 size_t Offset = Piece.InputOff;
451 uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
453 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
457 uint32_t CieOffset = Offset + 4 - ID;
458 CieRecord *Rec = OffsetToCie[CieOffset];
460 fatal(toString(Sec) + ": invalid CIE reference");
462 if (!isFdeLive<ELFT>(Piece, Rels))
464 Rec->Fdes.push_back(&Piece);
469 template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
470 auto *Sec = cast<EhInputSection>(C);
473 Alignment = std::max(Alignment, Sec->Alignment);
474 Sections.push_back(Sec);
476 for (auto *DS : Sec->DependentSections)
477 DependentSections.push_back(DS);
479 // .eh_frame is a sequence of CIE or FDE records. This function
480 // splits it into pieces so that we can call
481 // SplitInputSection::getSectionPiece on the section.
483 if (Sec->Pieces.empty())
486 if (Sec->AreRelocsRela)
487 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
489 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
492 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
493 memcpy(Buf, D.data(), D.size());
495 size_t Aligned = alignTo(D.size(), Config->Wordsize);
497 // Zero-clear trailing padding if it exists.
498 memset(Buf + D.size(), 0, Aligned - D.size());
500 // Fix the size field. -4 since size does not include the size field itself.
501 write32(Buf, Aligned - 4);
504 void EhFrameSection::finalizeContents() {
506 return; // Already finalized.
509 for (CieRecord *Rec : CieRecords) {
510 Rec->Cie->OutputOff = Off;
511 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
513 for (EhSectionPiece *Fde : Rec->Fdes) {
514 Fde->OutputOff = Off;
515 Off += alignTo(Fde->Size, Config->Wordsize);
519 // The LSB standard does not allow a .eh_frame section with zero
520 // Call Frame Information records. Therefore add a CIE record length
521 // 0 as a terminator if this .eh_frame section is empty.
528 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
529 // to get an FDE from an address to which FDE is applied. This function
530 // returns a list of such pairs.
531 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
532 uint8_t *Buf = getParent()->Loc + OutSecOff;
533 std::vector<FdeData> Ret;
535 for (CieRecord *Rec : CieRecords) {
536 uint8_t Enc = getFdeEncoding(Rec->Cie);
537 for (EhSectionPiece *Fde : Rec->Fdes) {
538 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
539 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
540 Ret.push_back({Pc, FdeVA});
546 static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
548 case DW_EH_PE_udata2:
549 return read16(Buf, Config->Endianness);
550 case DW_EH_PE_udata4:
551 return read32(Buf, Config->Endianness);
552 case DW_EH_PE_udata8:
553 return read64(Buf, Config->Endianness);
554 case DW_EH_PE_absptr:
555 return readUint(Buf);
557 fatal("unknown FDE size encoding");
560 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
561 // We need it to create .eh_frame_hdr section.
562 uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
564 // The starting address to which this FDE applies is
565 // stored at FDE + 8 byte.
566 size_t Off = FdeOff + 8;
567 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
568 if ((Enc & 0x70) == DW_EH_PE_absptr)
570 if ((Enc & 0x70) == DW_EH_PE_pcrel)
571 return Addr + getParent()->Addr + Off;
572 fatal("unknown FDE size relative encoding");
575 void EhFrameSection::writeTo(uint8_t *Buf) {
576 // Write CIE and FDE records.
577 for (CieRecord *Rec : CieRecords) {
578 size_t CieOffset = Rec->Cie->OutputOff;
579 writeCieFde(Buf + CieOffset, Rec->Cie->data());
581 for (EhSectionPiece *Fde : Rec->Fdes) {
582 size_t Off = Fde->OutputOff;
583 writeCieFde(Buf + Off, Fde->data());
585 // FDE's second word should have the offset to an associated CIE.
587 write32(Buf + Off + 4, Off + 4 - CieOffset);
591 // Apply relocations. .eh_frame section contents are not contiguous
592 // in the output buffer, but relocateAlloc() still works because
593 // getOffset() takes care of discontiguous section pieces.
594 for (EhInputSection *S : Sections)
595 S->relocateAlloc(Buf, nullptr);
598 GotSection::GotSection()
599 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
600 Target->GotEntrySize, ".got") {}
602 void GotSection::addEntry(Symbol &Sym) {
603 Sym.GotIndex = NumEntries;
607 bool GotSection::addDynTlsEntry(Symbol &Sym) {
608 if (Sym.GlobalDynIndex != -1U)
610 Sym.GlobalDynIndex = NumEntries;
611 // Global Dynamic TLS entries take two GOT slots.
616 // Reserves TLS entries for a TLS module ID and a TLS block offset.
617 // In total it takes two GOT slots.
618 bool GotSection::addTlsIndex() {
619 if (TlsIndexOff != uint32_t(-1))
621 TlsIndexOff = NumEntries * Config->Wordsize;
626 uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
627 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
630 uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
631 return B.GlobalDynIndex * Config->Wordsize;
634 void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
636 bool GotSection::empty() const {
637 // We need to emit a GOT even if it's empty if there's a relocation that is
638 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
639 // (i.e. _GLOBAL_OFFSET_TABLE_).
640 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
643 void GotSection::writeTo(uint8_t *Buf) {
644 // Buf points to the start of this section's buffer,
645 // whereas InputSectionBase::relocateAlloc() expects its argument
646 // to point to the start of the output section.
647 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
650 MipsGotSection::MipsGotSection()
651 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
654 void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
655 // For "true" local symbols which can be referenced from the same module
656 // only compiler creates two instructions for address loading:
658 // lw $8, 0($gp) # R_MIPS_GOT16
659 // addi $8, $8, 0 # R_MIPS_LO16
661 // The first instruction loads high 16 bits of the symbol address while
662 // the second adds an offset. That allows to reduce number of required
663 // GOT entries because only one global offset table entry is necessary
664 // for every 64 KBytes of local data. So for local symbols we need to
665 // allocate number of GOT entries to hold all required "page" addresses.
667 // All global symbols (hidden and regular) considered by compiler uniformly.
668 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
669 // to load address of the symbol. So for each such symbol we need to
670 // allocate dedicated GOT entry to store its address.
672 // If a symbol is preemptible we need help of dynamic linker to get its
673 // final address. The corresponding GOT entries are allocated in the
674 // "global" part of GOT. Entries for non preemptible global symbol allocated
675 // in the "local" part of GOT.
677 // See "Global Offset Table" in Chapter 5:
678 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
679 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
680 // At this point we do not know final symbol value so to reduce number
681 // of allocated GOT entries do the following trick. Save all output
682 // sections referenced by GOT relocations. Then later in the `finalize`
683 // method calculate number of "pages" required to cover all saved output
684 // section and allocate appropriate number of GOT entries.
685 PageIndexMap.insert({Sym.getOutputSection(), 0});
689 // GOT entries created for MIPS TLS relocations behave like
690 // almost GOT entries from other ABIs. They go to the end
691 // of the global offset table.
692 Sym.GotIndex = TlsEntries.size();
693 TlsEntries.push_back(&Sym);
696 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
697 if (S.isInGot() && !A)
699 size_t NewIndex = Items.size();
700 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
702 Items.emplace_back(&S, A);
704 S.GotIndex = NewIndex;
706 if (Sym.IsPreemptible) {
707 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
708 AddEntry(Sym, 0, GlobalEntries);
709 Sym.IsInGlobalMipsGot = true;
710 } else if (Expr == R_MIPS_GOT_OFF32) {
711 AddEntry(Sym, Addend, LocalEntries32);
712 Sym.Is32BitMipsGot = true;
714 // Hold local GOT entries accessed via a 16-bit index separately.
715 // That allows to write them in the beginning of the GOT and keep
716 // their indexes as less as possible to escape relocation's overflow.
717 AddEntry(Sym, Addend, LocalEntries);
721 bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
722 if (Sym.GlobalDynIndex != -1U)
724 Sym.GlobalDynIndex = TlsEntries.size();
725 // Global Dynamic TLS entries take two GOT slots.
726 TlsEntries.push_back(nullptr);
727 TlsEntries.push_back(&Sym);
731 // Reserves TLS entries for a TLS module ID and a TLS block offset.
732 // In total it takes two GOT slots.
733 bool MipsGotSection::addTlsIndex() {
734 if (TlsIndexOff != uint32_t(-1))
736 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
737 TlsEntries.push_back(nullptr);
738 TlsEntries.push_back(nullptr);
742 static uint64_t getMipsPageAddr(uint64_t Addr) {
743 return (Addr + 0x8000) & ~0xffff;
746 static uint64_t getMipsPageCount(uint64_t Size) {
747 return (Size + 0xfffe) / 0xffff + 1;
750 uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
751 int64_t Addend) const {
752 const OutputSection *OutSec = B.getOutputSection();
753 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
754 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
755 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
756 assert(Index < PageEntriesNum);
757 return (HeaderEntriesNum + Index) * Config->Wordsize;
760 uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
761 int64_t Addend) const {
762 // Calculate offset of the GOT entries block: TLS, global, local.
763 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
765 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
766 else if (B.IsInGlobalMipsGot)
767 Index += LocalEntries.size() + LocalEntries32.size();
768 else if (B.Is32BitMipsGot)
769 Index += LocalEntries.size();
770 // Calculate offset of the GOT entry in the block.
774 auto It = EntryIndexMap.find({&B, Addend});
775 assert(It != EntryIndexMap.end());
778 return Index * Config->Wordsize;
781 uint64_t MipsGotSection::getTlsOffset() const {
782 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
785 uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
786 return B.GlobalDynIndex * Config->Wordsize;
789 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
790 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
793 unsigned MipsGotSection::getLocalEntriesNum() const {
794 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
795 LocalEntries32.size();
798 void MipsGotSection::finalizeContents() { updateAllocSize(); }
800 bool MipsGotSection::updateAllocSize() {
802 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
803 // For each output section referenced by GOT page relocations calculate
804 // and save into PageIndexMap an upper bound of MIPS GOT entries required
805 // to store page addresses of local symbols. We assume the worst case -
806 // each 64kb page of the output section has at least one GOT relocation
807 // against it. And take in account the case when the section intersects
809 P.second = PageEntriesNum;
810 PageEntriesNum += getMipsPageCount(P.first->Size);
812 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
817 bool MipsGotSection::empty() const {
818 // We add the .got section to the result for dynamic MIPS target because
819 // its address and properties are mentioned in the .dynamic section.
820 return Config->Relocatable;
823 uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
825 void MipsGotSection::writeTo(uint8_t *Buf) {
826 // Set the MSB of the second GOT slot. This is not required by any
827 // MIPS ABI documentation, though.
829 // There is a comment in glibc saying that "The MSB of got[1] of a
830 // gnu object is set to identify gnu objects," and in GNU gold it
831 // says "the second entry will be used by some runtime loaders".
832 // But how this field is being used is unclear.
834 // We are not really willing to mimic other linkers behaviors
835 // without understanding why they do that, but because all files
836 // generated by GNU tools have this special GOT value, and because
837 // we've been doing this for years, it is probably a safe bet to
838 // keep doing this for now. We really need to revisit this to see
839 // if we had to do this.
840 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
841 Buf += HeaderEntriesNum * Config->Wordsize;
842 // Write 'page address' entries to the local part of the GOT.
843 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
844 size_t PageCount = getMipsPageCount(L.first->Size);
845 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
846 for (size_t PI = 0; PI < PageCount; ++PI) {
847 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
848 writeUint(Entry, FirstPageAddr + PI * 0x10000);
851 Buf += PageEntriesNum * Config->Wordsize;
852 auto AddEntry = [&](const GotEntry &SA) {
853 uint8_t *Entry = Buf;
854 Buf += Config->Wordsize;
855 const Symbol *Sym = SA.first;
856 uint64_t VA = Sym->getVA(SA.second);
857 if (Sym->StOther & STO_MIPS_MICROMIPS)
859 writeUint(Entry, VA);
861 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
862 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
863 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
864 // Initialize TLS-related GOT entries. If the entry has a corresponding
865 // dynamic relocations, leave it initialized by zero. Write down adjusted
866 // TLS symbol's values otherwise. To calculate the adjustments use offsets
867 // for thread-local storage.
868 // https://www.linux-mips.org/wiki/NPTL
869 if (TlsIndexOff != -1U && !Config->Pic)
870 writeUint(Buf + TlsIndexOff, 1);
871 for (const Symbol *B : TlsEntries) {
872 if (!B || B->IsPreemptible)
874 uint64_t VA = B->getVA();
875 if (B->GotIndex != -1U) {
876 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
877 writeUint(Entry, VA - 0x7000);
879 if (B->GlobalDynIndex != -1U) {
880 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
882 Entry += Config->Wordsize;
883 writeUint(Entry, VA - 0x8000);
888 GotPltSection::GotPltSection()
889 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
890 Target->GotPltEntrySize, ".got.plt") {}
892 void GotPltSection::addEntry(Symbol &Sym) {
893 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
894 Entries.push_back(&Sym);
897 size_t GotPltSection::getSize() const {
898 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
899 Target->GotPltEntrySize;
902 void GotPltSection::writeTo(uint8_t *Buf) {
903 Target->writeGotPltHeader(Buf);
904 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
905 for (const Symbol *B : Entries) {
906 Target->writeGotPlt(Buf, *B);
907 Buf += Config->Wordsize;
911 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
912 // part of the .got.plt
913 IgotPltSection::IgotPltSection()
914 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
915 Target->GotPltEntrySize,
916 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
918 void IgotPltSection::addEntry(Symbol &Sym) {
920 Sym.GotPltIndex = Entries.size();
921 Entries.push_back(&Sym);
924 size_t IgotPltSection::getSize() const {
925 return Entries.size() * Target->GotPltEntrySize;
928 void IgotPltSection::writeTo(uint8_t *Buf) {
929 for (const Symbol *B : Entries) {
930 Target->writeIgotPlt(Buf, *B);
931 Buf += Config->Wordsize;
935 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
936 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
938 // ELF string tables start with a NUL byte.
942 // Adds a string to the string table. If HashIt is true we hash and check for
943 // duplicates. It is optional because the name of global symbols are already
944 // uniqued and hashing them again has a big cost for a small value: uniquing
945 // them with some other string that happens to be the same.
946 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
948 auto R = StringMap.insert(std::make_pair(S, this->Size));
950 return R.first->second;
952 unsigned Ret = this->Size;
953 this->Size = this->Size + S.size() + 1;
954 Strings.push_back(S);
958 void StringTableSection::writeTo(uint8_t *Buf) {
959 for (StringRef S : Strings) {
960 memcpy(Buf, S.data(), S.size());
961 Buf[S.size()] = '\0';
966 // Returns the number of version definition entries. Because the first entry
967 // is for the version definition itself, it is the number of versioned symbols
968 // plus one. Note that we don't support multiple versions yet.
969 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
971 template <class ELFT>
972 DynamicSection<ELFT>::DynamicSection()
973 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
975 this->Entsize = ELFT::Is64Bits ? 16 : 8;
977 // .dynamic section is not writable on MIPS and on Fuchsia OS
978 // which passes -z rodynamic.
979 // See "Special Section" in Chapter 4 in the following document:
980 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
981 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
982 this->Flags = SHF_ALLOC;
984 // Add strings to .dynstr early so that .dynstr's size will be
986 for (StringRef S : Config->FilterList)
987 addInt(DT_FILTER, InX::DynStrTab->addString(S));
988 for (StringRef S : Config->AuxiliaryList)
989 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
991 if (!Config->Rpath.empty())
992 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
993 InX::DynStrTab->addString(Config->Rpath));
995 for (InputFile *File : SharedFiles) {
996 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
998 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
1000 if (!Config->SoName.empty())
1001 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
1004 template <class ELFT>
1005 void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1006 Entries.push_back({Tag, Fn});
1009 template <class ELFT>
1010 void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1011 Entries.push_back({Tag, [=] { return Val; }});
1014 template <class ELFT>
1015 void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1017 {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1020 template <class ELFT>
1021 void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1022 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1025 template <class ELFT>
1026 void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1027 Entries.push_back({Tag, [=] { return Sec->Size; }});
1030 template <class ELFT>
1031 void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1032 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1035 // Add remaining entries to complete .dynamic contents.
1036 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1038 return; // Already finalized.
1040 // Set DT_FLAGS and DT_FLAGS_1.
1041 uint32_t DtFlags = 0;
1042 uint32_t DtFlags1 = 0;
1043 if (Config->Bsymbolic)
1044 DtFlags |= DF_SYMBOLIC;
1045 if (Config->ZNodelete)
1046 DtFlags1 |= DF_1_NODELETE;
1047 if (Config->ZNodlopen)
1048 DtFlags1 |= DF_1_NOOPEN;
1050 DtFlags |= DF_BIND_NOW;
1051 DtFlags1 |= DF_1_NOW;
1053 if (Config->ZOrigin) {
1054 DtFlags |= DF_ORIGIN;
1055 DtFlags1 |= DF_1_ORIGIN;
1059 addInt(DT_FLAGS, DtFlags);
1061 addInt(DT_FLAGS_1, DtFlags1);
1063 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1064 // need it for each process, so we don't write it for DSOs. The loader writes
1065 // the pointer into this entry.
1067 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1068 // systems (currently only Fuchsia OS) provide other means to give the
1069 // debugger this information. Such systems may choose make .dynamic read-only.
1070 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1071 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
1072 addInt(DT_DEBUG, 0);
1074 this->Link = InX::DynStrTab->getParent()->SectionIndex;
1075 if (InX::RelaDyn->getParent() && !InX::RelaDyn->empty()) {
1076 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1077 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1079 bool IsRela = Config->IsRela;
1080 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1081 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1083 // MIPS dynamic loader does not support RELCOUNT tag.
1084 // The problem is in the tight relation between dynamic
1085 // relocations and GOT. So do not emit this tag on MIPS.
1086 if (Config->EMachine != EM_MIPS) {
1087 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1088 if (Config->ZCombreloc && NumRelativeRels)
1089 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
1092 if (InX::RelaPlt->getParent() && !InX::RelaPlt->empty()) {
1093 addInSec(DT_JMPREL, InX::RelaPlt);
1094 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1095 switch (Config->EMachine) {
1097 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1100 addInSec(DT_PLTGOT, InX::Plt);
1103 addInSec(DT_PLTGOT, InX::GotPlt);
1106 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
1109 addInSec(DT_SYMTAB, InX::DynSymTab);
1110 addInt(DT_SYMENT, sizeof(Elf_Sym));
1111 addInSec(DT_STRTAB, InX::DynStrTab);
1112 addInt(DT_STRSZ, InX::DynStrTab->getSize());
1114 addInt(DT_TEXTREL, 0);
1115 if (InX::GnuHashTab)
1116 addInSec(DT_GNU_HASH, InX::GnuHashTab);
1118 addInSec(DT_HASH, InX::HashTab);
1120 if (Out::PreinitArray) {
1121 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1122 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1124 if (Out::InitArray) {
1125 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1126 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1128 if (Out::FiniArray) {
1129 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1130 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1133 if (Symbol *B = Symtab->find(Config->Init))
1136 if (Symbol *B = Symtab->find(Config->Fini))
1140 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1141 if (HasVerNeed || In<ELFT>::VerDef)
1142 addInSec(DT_VERSYM, In<ELFT>::VerSym);
1143 if (In<ELFT>::VerDef) {
1144 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1145 addInt(DT_VERDEFNUM, getVerDefNum());
1148 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1149 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1152 if (Config->EMachine == EM_MIPS) {
1153 addInt(DT_MIPS_RLD_VERSION, 1);
1154 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1155 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1156 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1158 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1160 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1161 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1163 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1164 addInSec(DT_PLTGOT, InX::MipsGot);
1165 if (InX::MipsRldMap)
1166 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1171 getParent()->Link = this->Link;
1172 this->Size = Entries.size() * this->Entsize;
1175 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1176 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1178 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1179 P->d_tag = KV.first;
1180 P->d_un.d_val = KV.second();
1185 uint64_t DynamicReloc::getOffset() const {
1186 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
1189 int64_t DynamicReloc::getAddend() const {
1191 return Sym->getVA(Addend);
1195 uint32_t DynamicReloc::getSymIndex() const {
1196 if (Sym && !UseSymVA)
1197 return Sym->DynsymIndex;
1201 RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1203 int32_t SizeDynamicTag)
1204 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1205 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
1207 void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
1208 if (Reloc.Type == Target->RelativeRel)
1209 ++NumRelativeRelocs;
1210 Relocs.push_back(Reloc);
1213 void RelocationBaseSection::finalizeContents() {
1214 // If all relocations are R_*_RELATIVE they don't refer to any
1215 // dynamic symbol and we don't need a dynamic symbol table. If that
1216 // is the case, just use 0 as the link.
1217 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
1219 // Set required output section properties.
1220 getParent()->Link = Link;
1223 template <class ELFT>
1224 static void encodeDynamicReloc(typename ELFT::Rela *P,
1225 const DynamicReloc &Rel) {
1227 P->r_addend = Rel.getAddend();
1228 P->r_offset = Rel.getOffset();
1229 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1230 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1231 // entries. These entries are placed after the global and local sections of
1232 // the GOT. At the point when we create these relocations, the size of the
1233 // global and local sections is unknown, so the offset that we store in the
1234 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1235 // the GOT, rather than being relative to the start of the GOT. This line of
1236 // code adds the size of the global and local sections to the virtual
1237 // address computed by getOffset() in order to adjust it into the TLS
1239 P->r_offset += InX::MipsGot->getTlsOffset();
1240 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1243 template <class ELFT>
1244 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1245 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1246 Config->IsRela ? DT_RELA : DT_REL,
1247 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1249 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1252 template <class ELFT, class RelTy>
1253 static bool compRelocations(const RelTy &A, const RelTy &B) {
1254 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1255 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1256 if (AIsRel != BIsRel)
1259 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1262 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1263 uint8_t *BufBegin = Buf;
1264 for (const DynamicReloc &Rel : Relocs) {
1265 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1266 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1271 std::stable_sort((Elf_Rela *)BufBegin,
1272 (Elf_Rela *)BufBegin + Relocs.size(),
1273 compRelocations<ELFT, Elf_Rela>);
1275 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1276 compRelocations<ELFT, Elf_Rel>);
1280 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1281 return this->Entsize * Relocs.size();
1284 template <class ELFT>
1285 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1287 : RelocationBaseSection(
1288 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1289 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1290 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1294 template <class ELFT>
1295 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1296 // This function computes the contents of an Android-format packed relocation
1299 // This format compresses relocations by using relocation groups to factor out
1300 // fields that are common between relocations and storing deltas from previous
1301 // relocations in SLEB128 format (which has a short representation for small
1302 // numbers). A good example of a relocation type with common fields is
1303 // R_*_RELATIVE, which is normally used to represent function pointers in
1304 // vtables. In the REL format, each relative relocation has the same r_info
1305 // field, and is only different from other relative relocations in terms of
1306 // the r_offset field. By sorting relocations by offset, grouping them by
1307 // r_info and representing each relocation with only the delta from the
1308 // previous offset, each 8-byte relocation can be compressed to as little as 1
1309 // byte (or less with run-length encoding). This relocation packer was able to
1310 // reduce the size of the relocation section in an Android Chromium DSO from
1311 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1313 // A relocation section consists of a header containing the literal bytes
1314 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1315 // elements are the total number of relocations in the section and an initial
1316 // r_offset value. The remaining elements define a sequence of relocation
1317 // groups. Each relocation group starts with a header consisting of the
1318 // following elements:
1320 // - the number of relocations in the relocation group
1321 // - flags for the relocation group
1322 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1323 // for each relocation in the group.
1324 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1325 // field for each relocation in the group.
1326 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1327 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1328 // each relocation in the group.
1330 // Following the relocation group header are descriptions of each of the
1331 // relocations in the group. They consist of the following elements:
1333 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1334 // delta for this relocation.
1335 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1336 // field for this relocation.
1337 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1338 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1341 size_t OldSize = RelocData.size();
1343 RelocData = {'A', 'P', 'S', '2'};
1344 raw_svector_ostream OS(RelocData);
1345 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1347 // The format header includes the number of relocations and the initial
1348 // offset (we set this to zero because the first relocation group will
1349 // perform the initial adjustment).
1353 std::vector<Elf_Rela> Relatives, NonRelatives;
1355 for (const DynamicReloc &Rel : Relocs) {
1357 encodeDynamicReloc<ELFT>(&R, Rel);
1359 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1360 Relatives.push_back(R);
1362 NonRelatives.push_back(R);
1365 std::sort(Relatives.begin(), Relatives.end(),
1366 [](const Elf_Rel &A, const Elf_Rel &B) {
1367 return A.r_offset < B.r_offset;
1370 // Try to find groups of relative relocations which are spaced one word
1371 // apart from one another. These generally correspond to vtable entries. The
1372 // format allows these groups to be encoded using a sort of run-length
1373 // encoding, but each group will cost 7 bytes in addition to the offset from
1374 // the previous group, so it is only profitable to do this for groups of
1375 // size 8 or larger.
1376 std::vector<Elf_Rela> UngroupedRelatives;
1377 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1378 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1379 std::vector<Elf_Rela> Group;
1381 Group.push_back(*I++);
1382 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1384 if (Group.size() < 8)
1385 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1388 RelativeGroups.emplace_back(std::move(Group));
1391 unsigned HasAddendIfRela =
1392 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1394 uint64_t Offset = 0;
1395 uint64_t Addend = 0;
1397 // Emit the run-length encoding for the groups of adjacent relative
1398 // relocations. Each group is represented using two groups in the packed
1399 // format. The first is used to set the current offset to the start of the
1400 // group (and also encodes the first relocation), and the second encodes the
1401 // remaining relocations.
1402 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1403 // The first relocation in the group.
1405 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1406 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1407 Add(G[0].r_offset - Offset);
1408 Add(Target->RelativeRel);
1409 if (Config->IsRela) {
1410 Add(G[0].r_addend - Addend);
1411 Addend = G[0].r_addend;
1414 // The remaining relocations.
1416 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1417 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1418 Add(Config->Wordsize);
1419 Add(Target->RelativeRel);
1420 if (Config->IsRela) {
1421 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1422 Add(I->r_addend - Addend);
1423 Addend = I->r_addend;
1427 Offset = G.back().r_offset;
1430 // Now the ungrouped relatives.
1431 if (!UngroupedRelatives.empty()) {
1432 Add(UngroupedRelatives.size());
1433 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1434 Add(Target->RelativeRel);
1435 for (Elf_Rela &R : UngroupedRelatives) {
1436 Add(R.r_offset - Offset);
1437 Offset = R.r_offset;
1438 if (Config->IsRela) {
1439 Add(R.r_addend - Addend);
1440 Addend = R.r_addend;
1445 // Finally the non-relative relocations.
1446 std::sort(NonRelatives.begin(), NonRelatives.end(),
1447 [](const Elf_Rela &A, const Elf_Rela &B) {
1448 return A.r_offset < B.r_offset;
1450 if (!NonRelatives.empty()) {
1451 Add(NonRelatives.size());
1452 Add(HasAddendIfRela);
1453 for (Elf_Rela &R : NonRelatives) {
1454 Add(R.r_offset - Offset);
1455 Offset = R.r_offset;
1457 if (Config->IsRela) {
1458 Add(R.r_addend - Addend);
1459 Addend = R.r_addend;
1464 // Returns whether the section size changed. We need to keep recomputing both
1465 // section layout and the contents of this section until the size converges
1466 // because changing this section's size can affect section layout, which in
1467 // turn can affect the sizes of the LEB-encoded integers stored in this
1469 return RelocData.size() != OldSize;
1472 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1473 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1474 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1476 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1477 StrTabSec(StrTabSec) {}
1479 // Orders symbols according to their positions in the GOT,
1480 // in compliance with MIPS ABI rules.
1481 // See "Global Offset Table" in Chapter 5 in the following document
1482 // for detailed description:
1483 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1484 static bool sortMipsSymbols(const SymbolTableEntry &L,
1485 const SymbolTableEntry &R) {
1486 // Sort entries related to non-local preemptible symbols by GOT indexes.
1487 // All other entries go to the first part of GOT in arbitrary order.
1488 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1489 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
1490 if (LIsInLocalGot || RIsInLocalGot)
1491 return !RIsInLocalGot;
1492 return L.Sym->GotIndex < R.Sym->GotIndex;
1495 void SymbolTableBaseSection::finalizeContents() {
1496 getParent()->Link = StrTabSec.getParent()->SectionIndex;
1498 // If it is a .dynsym, there should be no local symbols, but we need
1499 // to do a few things for the dynamic linker.
1500 if (this->Type == SHT_DYNSYM) {
1501 // Section's Info field has the index of the first non-local symbol.
1502 // Because the first symbol entry is a null entry, 1 is the first.
1503 getParent()->Info = 1;
1505 if (InX::GnuHashTab) {
1506 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1507 InX::GnuHashTab->addSymbols(Symbols);
1508 } else if (Config->EMachine == EM_MIPS) {
1509 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1513 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
1518 // The ELF spec requires that all local symbols precede global symbols, so we
1519 // sort symbol entries in this function. (For .dynsym, we don't do that because
1520 // symbols for dynamic linking are inherently all globals.)
1521 void SymbolTableBaseSection::postThunkContents() {
1522 if (this->Type == SHT_DYNSYM)
1524 // move all local symbols before global symbols.
1525 auto It = std::stable_partition(
1526 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1527 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
1529 size_t NumLocals = It - Symbols.begin();
1530 getParent()->Info = NumLocals + 1;
1533 void SymbolTableBaseSection::addSymbol(Symbol *B) {
1534 // Adding a local symbol to a .dynsym is a bug.
1535 assert(this->Type != SHT_DYNSYM || !B->isLocal());
1537 bool HashIt = B->isLocal();
1538 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1541 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
1542 // Initializes symbol lookup tables lazily. This is used only
1543 // for -r or -emit-relocs.
1544 llvm::call_once(OnceFlag, [&] {
1545 SymbolIndexMap.reserve(Symbols.size());
1547 for (const SymbolTableEntry &E : Symbols) {
1548 if (E.Sym->Type == STT_SECTION)
1549 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
1551 SymbolIndexMap[E.Sym] = ++I;
1555 // Section symbols are mapped based on their output sections
1556 // to maintain their semantics.
1557 if (Sym->Type == STT_SECTION)
1558 return SectionIndexMap.lookup(Sym->getOutputSection());
1559 return SymbolIndexMap.lookup(Sym);
1562 template <class ELFT>
1563 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1564 : SymbolTableBaseSection(StrTabSec) {
1565 this->Entsize = sizeof(Elf_Sym);
1568 // Write the internal symbol table contents to the output symbol table.
1569 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1570 // The first entry is a null entry as per the ELF spec.
1571 memset(Buf, 0, sizeof(Elf_Sym));
1572 Buf += sizeof(Elf_Sym);
1574 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1576 for (SymbolTableEntry &Ent : Symbols) {
1577 Symbol *Sym = Ent.Sym;
1579 // Set st_info and st_other.
1581 if (Sym->isLocal()) {
1582 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1584 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1585 ESym->setVisibility(Sym->Visibility);
1588 ESym->st_name = Ent.StrTabOffset;
1590 // Set a section index.
1591 BssSection *CommonSec = nullptr;
1592 if (!Config->DefineCommon)
1593 if (auto *D = dyn_cast<Defined>(Sym))
1594 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1596 ESym->st_shndx = SHN_COMMON;
1597 else if (const OutputSection *OutSec = Sym->getOutputSection())
1598 ESym->st_shndx = OutSec->SectionIndex;
1599 else if (isa<Defined>(Sym))
1600 ESym->st_shndx = SHN_ABS;
1602 ESym->st_shndx = SHN_UNDEF;
1604 // Copy symbol size if it is a defined symbol. st_size is not significant
1605 // for undefined symbols, so whether copying it or not is up to us if that's
1606 // the case. We'll leave it as zero because by not setting a value, we can
1607 // get the exact same outputs for two sets of input files that differ only
1608 // in undefined symbol size in DSOs.
1609 if (ESym->st_shndx == SHN_UNDEF)
1612 ESym->st_size = Sym->getSize();
1614 // st_value is usually an address of a symbol, but that has a
1615 // special meaining for uninstantiated common symbols (this can
1616 // occur if -r is given).
1618 ESym->st_value = CommonSec->Alignment;
1620 ESym->st_value = Sym->getVA();
1625 // On MIPS we need to mark symbol which has a PLT entry and requires
1626 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1627 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1628 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1629 if (Config->EMachine == EM_MIPS) {
1630 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1632 for (SymbolTableEntry &Ent : Symbols) {
1633 Symbol *Sym = Ent.Sym;
1634 if (Sym->isInPlt() && Sym->NeedsPltAddr)
1635 ESym->st_other |= STO_MIPS_PLT;
1636 if (isMicroMips()) {
1637 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1638 // defined microMIPS symbols and shared symbols with PLT record.
1639 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1640 (Sym->isShared() && Sym->NeedsPltAddr)) {
1641 if (StrTabSec.isDynamic())
1642 ESym->st_value |= 1;
1643 ESym->st_other |= STO_MIPS_MICROMIPS;
1646 if (Config->Relocatable)
1647 if (auto *D = dyn_cast<Defined>(Sym))
1648 if (isMipsPIC<ELFT>(D))
1649 ESym->st_other |= STO_MIPS_PIC;
1655 // .hash and .gnu.hash sections contain on-disk hash tables that map
1656 // symbol names to their dynamic symbol table indices. Their purpose
1657 // is to help the dynamic linker resolve symbols quickly. If ELF files
1658 // don't have them, the dynamic linker has to do linear search on all
1659 // dynamic symbols, which makes programs slower. Therefore, a .hash
1660 // section is added to a DSO by default. A .gnu.hash is added if you
1661 // give the -hash-style=gnu or -hash-style=both option.
1663 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
1664 // Each ELF file has a list of DSOs that the ELF file depends on and a
1665 // list of dynamic symbols that need to be resolved from any of the
1666 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1667 // where m is the number of DSOs and n is the number of dynamic
1668 // symbols. For modern large programs, both m and n are large. So
1669 // making each step faster by using hash tables substiantially
1670 // improves time to load programs.
1672 // (Note that this is not the only way to design the shared library.
1673 // For instance, the Windows DLL takes a different approach. On
1674 // Windows, each dynamic symbol has a name of DLL from which the symbol
1675 // has to be resolved. That makes the cost of symbol resolution O(n).
1676 // This disables some hacky techniques you can use on Unix such as
1677 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1679 // Due to historical reasons, we have two different hash tables, .hash
1680 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1681 // and better version of .hash. .hash is just an on-disk hash table, but
1682 // .gnu.hash has a bloom filter in addition to a hash table to skip
1683 // DSOs very quickly. If you are sure that your dynamic linker knows
1684 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1685 // safe bet is to specify -hash-style=both for backward compatibilty.
1686 GnuHashTableSection::GnuHashTableSection()
1687 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1690 void GnuHashTableSection::finalizeContents() {
1691 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1693 // Computes bloom filter size in word size. We want to allocate 8
1694 // bits for each symbol. It must be a power of two.
1695 if (Symbols.empty())
1698 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
1700 Size = 16; // Header
1701 Size += Config->Wordsize * MaskWords; // Bloom filter
1702 Size += NBuckets * 4; // Hash buckets
1703 Size += Symbols.size() * 4; // Hash values
1706 void GnuHashTableSection::writeTo(uint8_t *Buf) {
1707 // The output buffer is not guaranteed to be zero-cleared because we pre-
1708 // fill executable sections with trap instructions. This is a precaution
1709 // for that case, which happens only when -no-rosegment is given.
1710 memset(Buf, 0, Size);
1713 write32(Buf, NBuckets);
1714 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1715 write32(Buf + 8, MaskWords);
1716 write32(Buf + 12, getShift2());
1719 // Write a bloom filter and a hash table.
1720 writeBloomFilter(Buf);
1721 Buf += Config->Wordsize * MaskWords;
1722 writeHashTable(Buf);
1725 // This function writes a 2-bit bloom filter. This bloom filter alone
1726 // usually filters out 80% or more of all symbol lookups [1].
1727 // The dynamic linker uses the hash table only when a symbol is not
1728 // filtered out by a bloom filter.
1730 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1731 // p.9, https://www.akkadia.org/drepper/dsohowto.pdf
1732 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
1733 const unsigned C = Config->Wordsize * 8;
1734 for (const Entry &Sym : Symbols) {
1735 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1736 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1737 Val |= uint64_t(1) << (Sym.Hash % C);
1738 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1739 writeUint(Buf + I * Config->Wordsize, Val);
1743 void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
1744 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
1745 uint32_t OldBucket = -1;
1746 uint32_t *Values = Buckets + NBuckets;
1747 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
1748 // Write a hash value. It represents a sequence of chains that share the
1749 // same hash modulo value. The last element of each chain is terminated by
1751 uint32_t Hash = I->Hash;
1752 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
1753 Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
1754 write32(Values++, Hash);
1756 if (I->BucketIdx == OldBucket)
1758 // Write a hash bucket. Hash buckets contain indices in the following hash
1760 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1761 OldBucket = I->BucketIdx;
1765 static uint32_t hashGnu(StringRef Name) {
1767 for (uint8_t C : Name)
1768 H = (H << 5) + H + C;
1772 // Add symbols to this symbol hash table. Note that this function
1773 // destructively sort a given vector -- which is needed because
1774 // GNU-style hash table places some sorting requirements.
1775 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
1776 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1777 // its type correctly.
1778 std::vector<SymbolTableEntry>::iterator Mid =
1779 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1780 // Shared symbols that this executable preempts are special. The dynamic
1781 // linker has to look them up, so they have to be in the hash table.
1782 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
1783 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
1784 return !S.Sym->isDefined();
1789 // We chose load factor 4 for the on-disk hash table. For each hash
1790 // collision, the dynamic linker will compare a uint32_t hash value.
1791 // Since the integer comparison is quite fast, we believe we can make
1792 // the load factor even larger. 4 is just a conservative choice.
1793 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
1795 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1796 Symbol *B = Ent.Sym;
1797 uint32_t Hash = hashGnu(B->getName());
1798 uint32_t BucketIdx = Hash % NBuckets;
1799 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
1803 Symbols.begin(), Symbols.end(),
1804 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
1806 V.erase(Mid, V.end());
1807 for (const Entry &Ent : Symbols)
1808 V.push_back({Ent.Sym, Ent.StrTabOffset});
1811 HashTableSection::HashTableSection()
1812 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1816 void HashTableSection::finalizeContents() {
1817 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1819 unsigned NumEntries = 2; // nbucket and nchain.
1820 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
1822 // Create as many buckets as there are symbols.
1823 NumEntries += InX::DynSymTab->getNumSymbols();
1824 this->Size = NumEntries * 4;
1827 void HashTableSection::writeTo(uint8_t *Buf) {
1828 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
1830 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
1831 write32(P++, NumSymbols); // nbucket
1832 write32(P++, NumSymbols); // nchain
1834 uint32_t *Buckets = P;
1835 uint32_t *Chains = P + NumSymbols;
1837 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
1838 Symbol *Sym = S.Sym;
1839 StringRef Name = Sym->getName();
1840 unsigned I = Sym->DynsymIndex;
1841 uint32_t Hash = hashSysV(Name) % NumSymbols;
1842 Chains[I] = Buckets[Hash];
1843 write32(Buckets + Hash, I);
1847 PltSection::PltSection(size_t S)
1848 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
1850 // The PLT needs to be writable on SPARC as the dynamic linker will
1851 // modify the instructions in the PLT entries.
1852 if (Config->EMachine == EM_SPARCV9)
1853 this->Flags |= SHF_WRITE;
1856 void PltSection::writeTo(uint8_t *Buf) {
1857 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1858 // linker to resolve dynsyms at runtime. Write such code.
1859 if (HeaderSize != 0)
1860 Target->writePltHeader(Buf);
1861 size_t Off = HeaderSize;
1862 // The IPlt is immediately after the Plt, account for this in RelOff
1863 unsigned PltOff = getPltRelocOff();
1865 for (auto &I : Entries) {
1866 const Symbol *B = I.first;
1867 unsigned RelOff = I.second + PltOff;
1868 uint64_t Got = B->getGotPltVA();
1869 uint64_t Plt = this->getVA() + Off;
1870 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1871 Off += Target->PltEntrySize;
1875 template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1876 Sym.PltIndex = Entries.size();
1877 RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1878 if (HeaderSize == 0) {
1879 PltRelocSection = InX::RelaIplt;
1880 Sym.IsInIplt = true;
1883 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1884 Entries.push_back(std::make_pair(&Sym, RelOff));
1887 size_t PltSection::getSize() const {
1888 return HeaderSize + Entries.size() * Target->PltEntrySize;
1891 // Some architectures such as additional symbols in the PLT section. For
1892 // example ARM uses mapping symbols to aid disassembly
1893 void PltSection::addSymbols() {
1894 // The PLT may have symbols defined for the Header, the IPLT has no header
1895 if (HeaderSize != 0)
1896 Target->addPltHeaderSymbols(this);
1897 size_t Off = HeaderSize;
1898 for (size_t I = 0; I < Entries.size(); ++I) {
1899 Target->addPltSymbols(this, Off);
1900 Off += Target->PltEntrySize;
1904 unsigned PltSection::getPltRelocOff() const {
1905 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
1908 // The string hash function for .gdb_index.
1909 static uint32_t computeGdbHash(StringRef S) {
1912 H = H * 67 + tolower(C) - 113;
1916 static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1917 std::vector<GdbIndexChunk::CuEntry> Ret;
1918 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1919 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
1923 static std::vector<GdbIndexChunk::AddressEntry>
1924 readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1925 std::vector<GdbIndexChunk::AddressEntry> Ret;
1928 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
1929 DWARFAddressRangesVector Ranges;
1930 Cu->collectAddressRanges(Ranges);
1932 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
1933 for (DWARFAddressRange &R : Ranges) {
1934 InputSectionBase *S = Sections[R.SectionIndex];
1935 if (!S || S == &InputSection::Discarded || !S->Live)
1937 // Range list with zero size has no effect.
1938 if (R.LowPC == R.HighPC)
1940 auto *IS = cast<InputSection>(S);
1941 uint64_t Offset = IS->getOffsetInFile();
1942 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
1949 static std::vector<GdbIndexChunk::NameTypeEntry>
1950 readPubNamesAndTypes(DWARFContext &Dwarf) {
1951 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1952 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
1954 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1955 for (StringRef Sec : {Sec1, Sec2}) {
1956 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
1957 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1958 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1959 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1960 Ret.push_back({S, Ent.Descriptor.toBits()});
1967 static std::vector<InputSection *> getDebugInfoSections() {
1968 std::vector<InputSection *> Ret;
1969 for (InputSectionBase *S : InputSections)
1970 if (InputSection *IS = dyn_cast<InputSection>(S))
1971 if (IS->Name == ".debug_info")
1976 void GdbIndexSection::fixCuIndex() {
1978 for (GdbIndexChunk &Chunk : Chunks) {
1979 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1981 Idx += Chunk.CompilationUnits.size();
1985 std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
1986 std::vector<std::vector<uint32_t>> Ret;
1990 for (GdbIndexChunk &Chunk : Chunks) {
1991 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
1992 GdbSymbol *&Sym = Symbols[Ent.Name];
1994 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
1995 Off += Ent.Name.size() + 1;
1999 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2000 // duplicate entries, so we want to dedup them.
2001 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2002 uint32_t Val = (Ent.Type << 24) | Idx;
2003 if (Vec.empty() || Vec.back() != Val)
2006 Idx += Chunk.CompilationUnits.size();
2009 StringPoolSize = Off;
2013 template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
2014 // Gather debug info to create a .gdb_index section.
2015 std::vector<InputSection *> Sections = getDebugInfoSections();
2016 std::vector<GdbIndexChunk> Chunks(Sections.size());
2018 parallelForEachN(0, Chunks.size(), [&](size_t I) {
2019 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2020 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2022 Chunks[I].DebugInfoSec = Sections[I];
2023 Chunks[I].CompilationUnits = readCuList(Dwarf);
2024 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2025 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2028 // .debug_gnu_pub{names,types} are useless in executables.
2029 // They are present in input object files solely for creating
2030 // a .gdb_index. So we can remove it from the output.
2031 for (InputSectionBase *S : InputSections)
2032 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2035 // Create a .gdb_index and returns it.
2036 return make<GdbIndexSection>(std::move(Chunks));
2039 static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
2041 for (const GdbIndexChunk &D : Arr)
2042 Ret += D.CompilationUnits.size();
2046 static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
2048 for (const GdbIndexChunk &D : Arr)
2049 Ret += D.AddressAreas.size();
2053 std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
2054 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2058 uint32_t Mask = Size - 1;
2059 std::vector<GdbSymbol *> Ret(Size);
2061 for (auto &KV : Symbols) {
2062 GdbSymbol *Sym = KV.second;
2063 uint32_t I = Sym->NameHash & Mask;
2064 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2067 I = (I + Step) & Mask;
2073 GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
2074 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
2076 CuVectors = createCuVectors();
2077 GdbSymtab = createGdbSymtab();
2079 // Compute offsets early to know the section size.
2080 // Each chunk size needs to be in sync with what we write in writeTo.
2081 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2082 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2083 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
2086 for (ArrayRef<uint32_t> Vec : CuVectors) {
2087 CuVectorOffsets.push_back(Off);
2088 Off += (Vec.size() + 1) * 4;
2090 StringPoolOffset = ConstantPoolOffset + Off;
2093 size_t GdbIndexSection::getSize() const {
2094 return StringPoolOffset + StringPoolSize;
2097 void GdbIndexSection::writeTo(uint8_t *Buf) {
2098 // Write the section header.
2100 write32le(Buf + 4, CuListOffset);
2101 write32le(Buf + 8, CuTypesOffset);
2102 write32le(Buf + 12, CuTypesOffset);
2103 write32le(Buf + 16, SymtabOffset);
2104 write32le(Buf + 20, ConstantPoolOffset);
2107 // Write the CU list.
2108 for (GdbIndexChunk &D : Chunks) {
2109 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
2110 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
2111 write64le(Buf + 8, Cu.CuLength);
2116 // Write the address area.
2117 for (GdbIndexChunk &D : Chunks) {
2118 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
2120 E.Section->getParent()->Addr + E.Section->getOffset(0);
2121 write64le(Buf, BaseAddr + E.LowAddress);
2122 write64le(Buf + 8, BaseAddr + E.HighAddress);
2123 write32le(Buf + 16, E.CuIndex);
2128 // Write the symbol table.
2129 for (GdbSymbol *Sym : GdbSymtab) {
2131 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2132 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
2137 // Write the CU vectors.
2138 for (ArrayRef<uint32_t> Vec : CuVectors) {
2139 write32le(Buf, Vec.size());
2141 for (uint32_t Val : Vec) {
2142 write32le(Buf, Val);
2147 // Write the string pool.
2148 for (auto &KV : Symbols) {
2149 CachedHashStringRef S = KV.first;
2150 GdbSymbol *Sym = KV.second;
2151 size_t Off = Sym->NameOffset;
2152 memcpy(Buf + Off, S.val().data(), S.size());
2153 Buf[Off + S.size()] = '\0';
2157 bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
2159 EhFrameHeader::EhFrameHeader()
2160 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
2162 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2163 // Each entry of the search table consists of two values,
2164 // the starting PC from where FDEs covers, and the FDE's address.
2165 // It is sorted by PC.
2166 void EhFrameHeader::writeTo(uint8_t *Buf) {
2167 typedef EhFrameSection::FdeData FdeData;
2169 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
2171 // Sort the FDE list by their PC and uniqueify. Usually there is only
2172 // one FDE for a PC (i.e. function), but if ICF merges two functions
2173 // into one, there can be more than one FDEs pointing to the address.
2174 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2175 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2176 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2177 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2180 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2181 Buf[2] = DW_EH_PE_udata4;
2182 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2183 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2184 write32(Buf + 8, Fdes.size());
2187 uint64_t VA = this->getVA();
2188 for (FdeData &Fde : Fdes) {
2189 write32(Buf, Fde.Pc - VA);
2190 write32(Buf + 4, Fde.FdeVA - VA);
2195 size_t EhFrameHeader::getSize() const {
2196 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
2197 return 12 + InX::EhFrame->NumFdes * 8;
2200 bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
2202 template <class ELFT>
2203 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
2204 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2205 ".gnu.version_d") {}
2207 static StringRef getFileDefName() {
2208 if (!Config->SoName.empty())
2209 return Config->SoName;
2210 return Config->OutputFile;
2213 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
2214 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
2215 for (VersionDefinition &V : Config->VersionDefinitions)
2216 V.NameOff = InX::DynStrTab->addString(V.Name);
2218 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2220 // sh_info should be set to the number of definitions. This fact is missed in
2221 // documentation, but confirmed by binutils community:
2222 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
2223 getParent()->Info = getVerDefNum();
2226 template <class ELFT>
2227 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2228 StringRef Name, size_t NameOff) {
2229 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2230 Verdef->vd_version = 1;
2232 Verdef->vd_aux = sizeof(Elf_Verdef);
2233 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2234 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2235 Verdef->vd_ndx = Index;
2236 Verdef->vd_hash = hashSysV(Name);
2238 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2239 Verdaux->vda_name = NameOff;
2240 Verdaux->vda_next = 0;
2243 template <class ELFT>
2244 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2245 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2247 for (VersionDefinition &V : Config->VersionDefinitions) {
2248 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2249 writeOne(Buf, V.Id, V.Name, V.NameOff);
2252 // Need to terminate the last version definition.
2253 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2254 Verdef->vd_next = 0;
2257 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2258 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2261 template <class ELFT>
2262 VersionTableSection<ELFT>::VersionTableSection()
2263 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
2265 this->Entsize = sizeof(Elf_Versym);
2268 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
2269 // At the moment of june 2016 GNU docs does not mention that sh_link field
2270 // should be set, but Sun docs do. Also readelf relies on this field.
2271 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
2274 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2275 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
2278 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2279 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2280 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
2281 OutVersym->vs_index = S.Sym->VersionId;
2286 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2287 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2290 template <class ELFT>
2291 VersionNeedSection<ELFT>::VersionNeedSection()
2292 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2294 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2295 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2296 // First identifiers are reserved by verdef section if it exist.
2297 NextIndex = getVerDefNum() + 1;
2300 template <class ELFT>
2301 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2302 SharedFile<ELFT> *File = SS->getFile<ELFT>();
2303 const typename ELFT::Verdef *Ver = File->Verdefs[SS->VerdefIndex];
2305 SS->VersionId = VER_NDX_GLOBAL;
2309 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2310 // to create one by adding it to our needed list and creating a dynstr entry
2312 if (File->VerdefMap.empty())
2313 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
2314 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
2315 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2316 // prepare to create one by allocating a version identifier and creating a
2317 // dynstr entry for the version name.
2318 if (NV.Index == 0) {
2319 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2320 Ver->getAux()->vda_name);
2321 NV.Index = NextIndex++;
2323 SS->VersionId = NV.Index;
2326 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2327 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2328 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2329 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2331 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2332 // Create an Elf_Verneed for this DSO.
2333 Verneed->vn_version = 1;
2334 Verneed->vn_cnt = P.first->VerdefMap.size();
2335 Verneed->vn_file = P.second;
2337 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2338 Verneed->vn_next = sizeof(Elf_Verneed);
2341 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2342 // VerdefMap, which will only contain references to needed version
2343 // definitions. Each Elf_Vernaux is based on the information contained in
2344 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2345 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2346 // data structures within a single input file.
2347 for (auto &NV : P.first->VerdefMap) {
2348 Vernaux->vna_hash = NV.first->vd_hash;
2349 Vernaux->vna_flags = 0;
2350 Vernaux->vna_other = NV.second.Index;
2351 Vernaux->vna_name = NV.second.StrTab;
2352 Vernaux->vna_next = sizeof(Elf_Vernaux);
2356 Vernaux[-1].vna_next = 0;
2358 Verneed[-1].vn_next = 0;
2361 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2362 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2363 getParent()->Info = Needed.size();
2366 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2367 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2368 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2369 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2373 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2374 return getNeedNum() == 0;
2377 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2379 Sections.push_back(MS);
2382 MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2383 uint64_t Flags, uint32_t Alignment)
2384 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2385 Builder(StringTableBuilder::RAW, Alignment) {}
2387 size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2389 void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2391 void MergeTailSection::finalizeContents() {
2392 // Add all string pieces to the string table builder to create section
2394 for (MergeInputSection *Sec : Sections)
2395 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2396 if (Sec->Pieces[I].Live)
2397 Builder.add(Sec->getData(I));
2399 // Fix the string table content. After this, the contents will never change.
2402 // finalize() fixed tail-optimized strings, so we can now get
2403 // offsets of strings. Get an offset for each string and save it
2404 // to a corresponding StringPiece for easy access.
2405 for (MergeInputSection *Sec : Sections)
2406 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2407 if (Sec->Pieces[I].Live)
2408 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2411 void MergeNoTailSection::writeTo(uint8_t *Buf) {
2412 for (size_t I = 0; I < NumShards; ++I)
2413 Shards[I].write(Buf + ShardOffsets[I]);
2416 // This function is very hot (i.e. it can take several seconds to finish)
2417 // because sometimes the number of inputs is in an order of magnitude of
2418 // millions. So, we use multi-threading.
2420 // For any strings S and T, we know S is not mergeable with T if S's hash
2421 // value is different from T's. If that's the case, we can safely put S and
2422 // T into different string builders without worrying about merge misses.
2423 // We do it in parallel.
2424 void MergeNoTailSection::finalizeContents() {
2425 // Initializes string table builders.
2426 for (size_t I = 0; I < NumShards; ++I)
2427 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2429 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2430 // operations in the following tight loop.
2431 size_t Concurrency = 1;
2434 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
2436 // Add section pieces to the builders.
2437 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2438 for (MergeInputSection *Sec : Sections) {
2439 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2440 if (!Sec->Pieces[I].Live)
2442 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
2443 if ((ShardId & (Concurrency - 1)) == ThreadId)
2444 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
2449 // Compute an in-section offset for each shard.
2451 for (size_t I = 0; I < NumShards; ++I) {
2452 Shards[I].finalizeInOrder();
2453 if (Shards[I].getSize() > 0)
2454 Off = alignTo(Off, Alignment);
2455 ShardOffsets[I] = Off;
2456 Off += Shards[I].getSize();
2460 // So far, section pieces have offsets from beginning of shards, but
2461 // we want offsets from beginning of the whole section. Fix them.
2462 parallelForEach(Sections, [&](MergeInputSection *Sec) {
2463 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2464 if (Sec->Pieces[I].Live)
2465 Sec->Pieces[I].OutputOff +=
2466 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
2470 static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2473 uint32_t Alignment) {
2474 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2475 if (ShouldTailMerge)
2476 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2477 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
2480 // Debug sections may be compressed by zlib. Uncompress if exists.
2481 void elf::decompressSections() {
2482 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2484 Sec->maybeUncompress();
2488 // This function scans over the inputsections to create mergeable
2489 // synthetic sections.
2491 // It removes MergeInputSections from the input section array and adds
2492 // new synthetic sections at the location of the first input section
2493 // that it replaces. It then finalizes each synthetic section in order
2494 // to compute an output offset for each piece of each input section.
2495 void elf::mergeSections() {
2496 // splitIntoPieces needs to be called on each MergeInputSection
2497 // before calling finalizeContents(). Do that first.
2498 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2500 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2501 S->splitIntoPieces();
2504 std::vector<MergeSyntheticSection *> MergeSections;
2505 for (InputSectionBase *&S : InputSections) {
2506 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2510 // We do not want to handle sections that are not alive, so just remove
2511 // them instead of trying to merge.
2515 StringRef OutsecName = getOutputSectionName(MS);
2516 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2518 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
2519 // While we could create a single synthetic section for two different
2520 // values of Entsize, it is better to take Entsize into consideration.
2522 // With a single synthetic section no two pieces with different Entsize
2523 // could be equal, so we may as well have two sections.
2525 // Using Entsize in here also allows us to propagate it to the synthetic
2527 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
2528 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
2530 if (I == MergeSections.end()) {
2531 MergeSyntheticSection *Syn =
2532 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
2533 MergeSections.push_back(Syn);
2534 I = std::prev(MergeSections.end());
2536 Syn->Entsize = MS->Entsize;
2540 (*I)->addSection(MS);
2542 for (auto *MS : MergeSections)
2543 MS->finalizeContents();
2545 std::vector<InputSectionBase *> &V = InputSections;
2546 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2549 MipsRldMapSection::MipsRldMapSection()
2550 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2553 ARMExidxSentinelSection::ARMExidxSentinelSection()
2554 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2555 Config->Wordsize, ".ARM.exidx") {}
2557 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
2558 // This section will have been sorted last in the .ARM.exidx table.
2559 // This table entry will have the form:
2560 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
2561 // The sentinel must have the PREL31 value of an address higher than any
2562 // address described by any other table entry.
2563 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
2564 // The Sections are sorted in order of ascending PREL31 address with the
2565 // sentinel last. We need to find the InputSection that precedes the
2567 OutputSection *C = getParent();
2568 InputSection *Highest = nullptr;
2570 for (const BaseCommand *Base : llvm::reverse(C->SectionCommands)) {
2571 if (!isa<InputSectionDescription>(Base))
2573 auto L = cast<InputSectionDescription>(Base);
2574 if (Skip >= L->Sections.size()) {
2575 Skip -= L->Sections.size();
2578 Highest = L->Sections[L->Sections.size() - Skip - 1];
2582 InputSection *LS = Highest->getLinkOrderDep();
2583 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
2584 uint64_t P = getVA();
2585 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2586 write32le(Buf + 4, 1);
2589 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
2590 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
2591 Config->Wordsize, ".text.thunk") {
2593 this->OutSecOff = Off;
2596 void ThunkSection::addThunk(Thunk *T) {
2597 uint64_t Off = alignTo(Size, T->Alignment);
2599 Thunks.push_back(T);
2600 T->addSymbols(*this);
2601 Size = Off + T->size();
2604 void ThunkSection::writeTo(uint8_t *Buf) {
2605 for (const Thunk *T : Thunks)
2606 T->writeTo(Buf + T->Offset, *this);
2609 InputSection *ThunkSection::getTargetInputSection() const {
2612 const Thunk *T = Thunks.front();
2613 return T->getTargetInputSection();
2616 InputSection *InX::ARMAttributes;
2617 BssSection *InX::Bss;
2618 BssSection *InX::BssRelRo;
2619 BuildIdSection *InX::BuildId;
2620 EhFrameHeader *InX::EhFrameHdr;
2621 EhFrameSection *InX::EhFrame;
2622 SyntheticSection *InX::Dynamic;
2623 StringTableSection *InX::DynStrTab;
2624 SymbolTableBaseSection *InX::DynSymTab;
2625 InputSection *InX::Interp;
2626 GdbIndexSection *InX::GdbIndex;
2627 GotSection *InX::Got;
2628 GotPltSection *InX::GotPlt;
2629 GnuHashTableSection *InX::GnuHashTab;
2630 HashTableSection *InX::HashTab;
2631 IgotPltSection *InX::IgotPlt;
2632 MipsGotSection *InX::MipsGot;
2633 MipsRldMapSection *InX::MipsRldMap;
2634 PltSection *InX::Plt;
2635 PltSection *InX::Iplt;
2636 RelocationBaseSection *InX::RelaDyn;
2637 RelocationBaseSection *InX::RelaPlt;
2638 RelocationBaseSection *InX::RelaIplt;
2639 StringTableSection *InX::ShStrTab;
2640 StringTableSection *InX::StrTab;
2641 SymbolTableBaseSection *InX::SymTab;
2643 template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2644 template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2645 template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2646 template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2648 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2649 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2650 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2651 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2653 template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2654 template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2655 template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2656 template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
2658 template MergeInputSection *elf::createCommentSection<ELF32LE>();
2659 template MergeInputSection *elf::createCommentSection<ELF32BE>();
2660 template MergeInputSection *elf::createCommentSection<ELF64LE>();
2661 template MergeInputSection *elf::createCommentSection<ELF64BE>();
2663 template class elf::MipsAbiFlagsSection<ELF32LE>;
2664 template class elf::MipsAbiFlagsSection<ELF32BE>;
2665 template class elf::MipsAbiFlagsSection<ELF64LE>;
2666 template class elf::MipsAbiFlagsSection<ELF64BE>;
2668 template class elf::MipsOptionsSection<ELF32LE>;
2669 template class elf::MipsOptionsSection<ELF32BE>;
2670 template class elf::MipsOptionsSection<ELF64LE>;
2671 template class elf::MipsOptionsSection<ELF64BE>;
2673 template class elf::MipsReginfoSection<ELF32LE>;
2674 template class elf::MipsReginfoSection<ELF32BE>;
2675 template class elf::MipsReginfoSection<ELF64LE>;
2676 template class elf::MipsReginfoSection<ELF64BE>;
2678 template class elf::DynamicSection<ELF32LE>;
2679 template class elf::DynamicSection<ELF32BE>;
2680 template class elf::DynamicSection<ELF64LE>;
2681 template class elf::DynamicSection<ELF64BE>;
2683 template class elf::RelocationSection<ELF32LE>;
2684 template class elf::RelocationSection<ELF32BE>;
2685 template class elf::RelocationSection<ELF64LE>;
2686 template class elf::RelocationSection<ELF64BE>;
2688 template class elf::AndroidPackedRelocationSection<ELF32LE>;
2689 template class elf::AndroidPackedRelocationSection<ELF32BE>;
2690 template class elf::AndroidPackedRelocationSection<ELF64LE>;
2691 template class elf::AndroidPackedRelocationSection<ELF64BE>;
2693 template class elf::SymbolTableSection<ELF32LE>;
2694 template class elf::SymbolTableSection<ELF32BE>;
2695 template class elf::SymbolTableSection<ELF64LE>;
2696 template class elf::SymbolTableSection<ELF64BE>;
2698 template class elf::VersionTableSection<ELF32LE>;
2699 template class elf::VersionTableSection<ELF32BE>;
2700 template class elf::VersionTableSection<ELF64LE>;
2701 template class elf::VersionTableSection<ELF64BE>;
2703 template class elf::VersionNeedSection<ELF32LE>;
2704 template class elf::VersionNeedSection<ELF32BE>;
2705 template class elf::VersionNeedSection<ELF64LE>;
2706 template class elf::VersionNeedSection<ELF64BE>;
2708 template class elf::VersionDefinitionSection<ELF32LE>;
2709 template class elf::VersionDefinitionSection<ELF32BE>;
2710 template class elf::VersionDefinitionSection<ELF64LE>;
2711 template class elf::VersionDefinitionSection<ELF64BE>;