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/Support/Dwarf.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/RandomNumberGenerator.h"
34 #include "llvm/Support/SHA1.h"
35 #include "llvm/Support/xxhash.h"
39 using namespace llvm::dwarf;
40 using namespace llvm::ELF;
41 using namespace llvm::object;
42 using namespace llvm::support;
43 using namespace llvm::support::endian;
46 using namespace lld::elf;
48 template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
49 std::vector<DefinedCommon *> V;
50 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
51 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
56 // Find all common symbols and allocate space for them.
57 template <class ELFT> InputSection<ELFT> *elf::createCommonSection() {
58 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
59 ArrayRef<uint8_t>(), "COMMON");
62 // Sort the common symbols by alignment as an heuristic to pack them better.
63 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
64 std::stable_sort(Syms.begin(), Syms.end(),
65 [](const DefinedCommon *A, const DefinedCommon *B) {
66 return A->Alignment > B->Alignment;
69 // Assign offsets to symbols.
72 for (DefinedCommon *Sym : Syms) {
73 Alignment = std::max<size_t>(Alignment, Sym->Alignment);
74 Size = alignTo(Size, Sym->Alignment);
76 // Compute symbol offset relative to beginning of input section.
80 Ret->Alignment = Alignment;
81 Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
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<ELFT> *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;
109 auto *Ret = make<MergeInputSection<ELFT>>(/*file=*/nullptr, &Hdr, ".comment");
110 Ret->Data = getVersion();
111 Ret->splitIntoPieces();
115 // .MIPS.abiflags section.
116 template <class ELFT>
117 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
118 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
121 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
122 memcpy(Buf, &Flags, sizeof(Flags));
125 template <class ELFT>
126 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
127 Elf_Mips_ABIFlags Flags = {};
130 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
131 if (!Sec->Live || Sec->Type != SHT_MIPS_ABIFLAGS)
136 std::string Filename = toString(Sec->getFile());
137 const size_t Size = Sec->Data.size();
138 // Older version of BFD (such as the default FreeBSD linker) concatenate
139 // .MIPS.abiflags instead of merging. To allow for this case (or potential
140 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
141 if (Size < sizeof(Elf_Mips_ABIFlags)) {
142 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
143 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
146 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
147 if (S->version != 0) {
148 error(Filename + ": unexpected .MIPS.abiflags version " +
153 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
154 // select the highest number of ISA/Rev/Ext.
155 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
156 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
157 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
158 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
159 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
160 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
161 Flags.ases |= S->ases;
162 Flags.flags1 |= S->flags1;
163 Flags.flags2 |= S->flags2;
164 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
168 return make<MipsAbiFlagsSection<ELFT>>(Flags);
172 // .MIPS.options section.
173 template <class ELFT>
174 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
175 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
178 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
179 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
180 Options->kind = ODK_REGINFO;
181 Options->size = getSize();
183 if (!Config->Relocatable)
184 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
185 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
188 template <class ELFT>
189 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
194 Elf_Mips_RegInfo Reginfo = {};
197 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
198 if (!Sec->Live || Sec->Type != SHT_MIPS_OPTIONS)
203 std::string Filename = toString(Sec->getFile());
204 ArrayRef<uint8_t> D = Sec->Data;
207 if (D.size() < sizeof(Elf_Mips_Options)) {
208 error(Filename + ": invalid size of .MIPS.options section");
212 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
213 if (Opt->kind == ODK_REGINFO) {
214 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
215 error(Filename + ": unsupported non-zero ri_gp_value");
216 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
217 Sec->getFile()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
222 fatal(Filename + ": zero option descriptor size");
223 D = D.slice(Opt->size);
228 return make<MipsOptionsSection<ELFT>>(Reginfo);
232 // MIPS .reginfo section.
233 template <class ELFT>
234 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
235 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
238 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
239 if (!Config->Relocatable)
240 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
241 memcpy(Buf, &Reginfo, sizeof(Reginfo));
244 template <class ELFT>
245 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
246 // Section should be alive for O32 and N32 ABIs only.
250 Elf_Mips_RegInfo Reginfo = {};
253 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
254 if (!Sec->Live || Sec->Type != SHT_MIPS_REGINFO)
259 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
260 error(toString(Sec->getFile()) + ": invalid size of .reginfo section");
263 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
264 if (Config->Relocatable && R->ri_gp_value)
265 error(toString(Sec->getFile()) + ": unsupported non-zero ri_gp_value");
267 Reginfo.ri_gprmask |= R->ri_gprmask;
268 Sec->getFile()->MipsGp0 = R->ri_gp_value;
272 return make<MipsReginfoSection<ELFT>>(Reginfo);
276 template <class ELFT> InputSection<ELFT> *elf::createInterpSection() {
277 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 1,
278 ArrayRef<uint8_t>(), ".interp");
281 // StringSaver guarantees that the returned string ends with '\0'.
282 StringRef S = Saver.save(Config->DynamicLinker);
283 Ret->Data = {(const uint8_t *)S.data(), S.size() + 1};
287 static size_t getHashSize() {
288 switch (Config->BuildId) {
289 case BuildIdKind::Fast:
291 case BuildIdKind::Md5:
292 case BuildIdKind::Uuid:
294 case BuildIdKind::Sha1:
296 case BuildIdKind::Hexstring:
297 return Config->BuildIdVector.size();
299 llvm_unreachable("unknown BuildIdKind");
303 template <class ELFT>
304 BuildIdSection<ELFT>::BuildIdSection()
305 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
306 HashSize(getHashSize()) {}
308 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
309 const endianness E = ELFT::TargetEndianness;
310 write32<E>(Buf, 4); // Name size
311 write32<E>(Buf + 4, HashSize); // Content size
312 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
313 memcpy(Buf + 12, "GNU", 4); // Name string
317 // Split one uint8 array into small pieces of uint8 arrays.
318 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
320 std::vector<ArrayRef<uint8_t>> Ret;
321 while (Arr.size() > ChunkSize) {
322 Ret.push_back(Arr.take_front(ChunkSize));
323 Arr = Arr.drop_front(ChunkSize);
330 // Computes a hash value of Data using a given hash function.
331 // In order to utilize multiple cores, we first split data into 1MB
332 // chunks, compute a hash for each chunk, and then compute a hash value
333 // of the hash values.
334 template <class ELFT>
335 void BuildIdSection<ELFT>::computeHash(
336 llvm::ArrayRef<uint8_t> Data,
337 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
338 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
339 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
341 // Compute hash values.
342 forLoop(0, Chunks.size(),
343 [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); });
345 // Write to the final output buffer.
346 HashFn(HashBuf, Hashes);
349 template <class ELFT>
350 void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
351 switch (Config->BuildId) {
352 case BuildIdKind::Fast:
353 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
354 write64le(Dest, xxHash64(toStringRef(Arr)));
357 case BuildIdKind::Md5:
358 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
359 memcpy(Dest, MD5::hash(Arr).data(), 16);
362 case BuildIdKind::Sha1:
363 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
364 memcpy(Dest, SHA1::hash(Arr).data(), 20);
367 case BuildIdKind::Uuid:
368 if (getRandomBytes(HashBuf, HashSize))
369 error("entropy source failure");
371 case BuildIdKind::Hexstring:
372 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
375 llvm_unreachable("unknown BuildIdKind");
379 template <class ELFT>
380 GotSection<ELFT>::GotSection()
381 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
382 Target->GotEntrySize, ".got") {}
384 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
385 Sym.GotIndex = NumEntries;
389 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
390 if (Sym.GlobalDynIndex != -1U)
392 Sym.GlobalDynIndex = NumEntries;
393 // Global Dynamic TLS entries take two GOT slots.
398 // Reserves TLS entries for a TLS module ID and a TLS block offset.
399 // In total it takes two GOT slots.
400 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
401 if (TlsIndexOff != uint32_t(-1))
403 TlsIndexOff = NumEntries * sizeof(uintX_t);
408 template <class ELFT>
409 typename GotSection<ELFT>::uintX_t
410 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
411 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
414 template <class ELFT>
415 typename GotSection<ELFT>::uintX_t
416 GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
417 return B.GlobalDynIndex * sizeof(uintX_t);
420 template <class ELFT> void GotSection<ELFT>::finalize() {
421 Size = NumEntries * sizeof(uintX_t);
424 template <class ELFT> bool GotSection<ELFT>::empty() const {
425 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
426 // we need to emit a GOT even if it's empty.
427 return NumEntries == 0 && !HasGotOffRel;
430 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
431 this->relocate(Buf, Buf + Size);
434 template <class ELFT>
435 MipsGotSection<ELFT>::MipsGotSection()
436 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL,
437 SHT_PROGBITS, Target->GotEntrySize, ".got") {}
439 template <class ELFT>
440 void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, uintX_t Addend,
442 // For "true" local symbols which can be referenced from the same module
443 // only compiler creates two instructions for address loading:
445 // lw $8, 0($gp) # R_MIPS_GOT16
446 // addi $8, $8, 0 # R_MIPS_LO16
448 // The first instruction loads high 16 bits of the symbol address while
449 // the second adds an offset. That allows to reduce number of required
450 // GOT entries because only one global offset table entry is necessary
451 // for every 64 KBytes of local data. So for local symbols we need to
452 // allocate number of GOT entries to hold all required "page" addresses.
454 // All global symbols (hidden and regular) considered by compiler uniformly.
455 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
456 // to load address of the symbol. So for each such symbol we need to
457 // allocate dedicated GOT entry to store its address.
459 // If a symbol is preemptible we need help of dynamic linker to get its
460 // final address. The corresponding GOT entries are allocated in the
461 // "global" part of GOT. Entries for non preemptible global symbol allocated
462 // in the "local" part of GOT.
464 // See "Global Offset Table" in Chapter 5:
465 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
466 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
467 // At this point we do not know final symbol value so to reduce number
468 // of allocated GOT entries do the following trick. Save all output
469 // sections referenced by GOT relocations. Then later in the `finalize`
470 // method calculate number of "pages" required to cover all saved output
471 // section and allocate appropriate number of GOT entries.
472 PageIndexMap.insert({cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec, 0});
476 // GOT entries created for MIPS TLS relocations behave like
477 // almost GOT entries from other ABIs. They go to the end
478 // of the global offset table.
479 Sym.GotIndex = TlsEntries.size();
480 TlsEntries.push_back(&Sym);
483 auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
484 if (S.isInGot() && !A)
486 size_t NewIndex = Items.size();
487 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
489 Items.emplace_back(&S, A);
491 S.GotIndex = NewIndex;
493 if (Sym.isPreemptible()) {
494 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
495 AddEntry(Sym, 0, GlobalEntries);
496 Sym.IsInGlobalMipsGot = true;
497 } else if (Expr == R_MIPS_GOT_OFF32) {
498 AddEntry(Sym, Addend, LocalEntries32);
499 Sym.Is32BitMipsGot = true;
501 // Hold local GOT entries accessed via a 16-bit index separately.
502 // That allows to write them in the beginning of the GOT and keep
503 // their indexes as less as possible to escape relocation's overflow.
504 AddEntry(Sym, Addend, LocalEntries);
508 template <class ELFT>
509 bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
510 if (Sym.GlobalDynIndex != -1U)
512 Sym.GlobalDynIndex = TlsEntries.size();
513 // Global Dynamic TLS entries take two GOT slots.
514 TlsEntries.push_back(nullptr);
515 TlsEntries.push_back(&Sym);
519 // Reserves TLS entries for a TLS module ID and a TLS block offset.
520 // In total it takes two GOT slots.
521 template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
522 if (TlsIndexOff != uint32_t(-1))
524 TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
525 TlsEntries.push_back(nullptr);
526 TlsEntries.push_back(nullptr);
530 static uint64_t getMipsPageAddr(uint64_t Addr) {
531 return (Addr + 0x8000) & ~0xffff;
534 static uint64_t getMipsPageCount(uint64_t Size) {
535 return (Size + 0xfffe) / 0xffff + 1;
538 template <class ELFT>
539 typename MipsGotSection<ELFT>::uintX_t
540 MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
541 uintX_t Addend) const {
542 const OutputSectionBase *OutSec =
543 cast<DefinedRegular<ELFT>>(&B)->Section->OutSec;
544 uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
545 uintX_t SymAddr = getMipsPageAddr(B.getVA<ELFT>(Addend));
546 uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
547 assert(Index < PageEntriesNum);
548 return (HeaderEntriesNum + Index) * sizeof(uintX_t);
551 template <class ELFT>
552 typename MipsGotSection<ELFT>::uintX_t
553 MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
554 uintX_t Addend) const {
555 // Calculate offset of the GOT entries block: TLS, global, local.
556 uintX_t Index = HeaderEntriesNum + PageEntriesNum;
558 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
559 else if (B.IsInGlobalMipsGot)
560 Index += LocalEntries.size() + LocalEntries32.size();
561 else if (B.Is32BitMipsGot)
562 Index += LocalEntries.size();
563 // Calculate offset of the GOT entry in the block.
567 auto It = EntryIndexMap.find({&B, Addend});
568 assert(It != EntryIndexMap.end());
571 return Index * sizeof(uintX_t);
574 template <class ELFT>
575 typename MipsGotSection<ELFT>::uintX_t
576 MipsGotSection<ELFT>::getTlsOffset() const {
577 return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
580 template <class ELFT>
581 typename MipsGotSection<ELFT>::uintX_t
582 MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
583 return B.GlobalDynIndex * sizeof(uintX_t);
586 template <class ELFT>
587 const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
588 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
591 template <class ELFT>
592 unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
593 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
594 LocalEntries32.size();
597 template <class ELFT> void MipsGotSection<ELFT>::finalize() {
599 for (std::pair<const OutputSectionBase *, size_t> &P : PageIndexMap) {
600 // For each output section referenced by GOT page relocations calculate
601 // and save into PageIndexMap an upper bound of MIPS GOT entries required
602 // to store page addresses of local symbols. We assume the worst case -
603 // each 64kb page of the output section has at least one GOT relocation
604 // against it. And take in account the case when the section intersects
606 P.second = PageEntriesNum;
607 PageEntriesNum += getMipsPageCount(P.first->Size);
609 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
613 template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
614 // We add the .got section to the result for dynamic MIPS target because
615 // its address and properties are mentioned in the .dynamic section.
616 return Config->Relocatable;
619 template <class ELFT>
620 typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getGp() const {
621 return ElfSym<ELFT>::MipsGp->template getVA<ELFT>(0);
624 template <class ELFT>
625 static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
626 typedef typename ELFT::uint uintX_t;
627 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
630 template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
631 // Set the MSB of the second GOT slot. This is not required by any
632 // MIPS ABI documentation, though.
634 // There is a comment in glibc saying that "The MSB of got[1] of a
635 // gnu object is set to identify gnu objects," and in GNU gold it
636 // says "the second entry will be used by some runtime loaders".
637 // But how this field is being used is unclear.
639 // We are not really willing to mimic other linkers behaviors
640 // without understanding why they do that, but because all files
641 // generated by GNU tools have this special GOT value, and because
642 // we've been doing this for years, it is probably a safe bet to
643 // keep doing this for now. We really need to revisit this to see
644 // if we had to do this.
645 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
646 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
647 Buf += HeaderEntriesNum * sizeof(uintX_t);
648 // Write 'page address' entries to the local part of the GOT.
649 for (std::pair<const OutputSectionBase *, size_t> &L : PageIndexMap) {
650 size_t PageCount = getMipsPageCount(L.first->Size);
651 uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
652 for (size_t PI = 0; PI < PageCount; ++PI) {
653 uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
654 writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
657 Buf += PageEntriesNum * sizeof(uintX_t);
658 auto AddEntry = [&](const GotEntry &SA) {
659 uint8_t *Entry = Buf;
660 Buf += sizeof(uintX_t);
661 const SymbolBody *Body = SA.first;
662 uintX_t VA = Body->template getVA<ELFT>(SA.second);
663 writeUint<ELFT>(Entry, VA);
665 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
666 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
667 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
668 // Initialize TLS-related GOT entries. If the entry has a corresponding
669 // dynamic relocations, leave it initialized by zero. Write down adjusted
670 // TLS symbol's values otherwise. To calculate the adjustments use offsets
671 // for thread-local storage.
672 // https://www.linux-mips.org/wiki/NPTL
673 if (TlsIndexOff != -1U && !Config->Pic)
674 writeUint<ELFT>(Buf + TlsIndexOff, 1);
675 for (const SymbolBody *B : TlsEntries) {
676 if (!B || B->isPreemptible())
678 uintX_t VA = B->getVA<ELFT>();
679 if (B->GotIndex != -1U) {
680 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
681 writeUint<ELFT>(Entry, VA - 0x7000);
683 if (B->GlobalDynIndex != -1U) {
684 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
685 writeUint<ELFT>(Entry, 1);
686 Entry += sizeof(uintX_t);
687 writeUint<ELFT>(Entry, VA - 0x8000);
692 template <class ELFT>
693 GotPltSection<ELFT>::GotPltSection()
694 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
695 Target->GotPltEntrySize, ".got.plt") {}
697 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
698 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
699 Entries.push_back(&Sym);
702 template <class ELFT> size_t GotPltSection<ELFT>::getSize() const {
703 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
704 Target->GotPltEntrySize;
707 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
708 Target->writeGotPltHeader(Buf);
709 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
710 for (const SymbolBody *B : Entries) {
711 Target->writeGotPlt(Buf, *B);
712 Buf += sizeof(uintX_t);
716 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
717 // part of the .got.plt
718 template <class ELFT>
719 IgotPltSection<ELFT>::IgotPltSection()
720 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
721 Target->GotPltEntrySize,
722 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {
725 template <class ELFT> void IgotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
727 Sym.GotPltIndex = Entries.size();
728 Entries.push_back(&Sym);
731 template <class ELFT> size_t IgotPltSection<ELFT>::getSize() const {
732 return Entries.size() * Target->GotPltEntrySize;
735 template <class ELFT> void IgotPltSection<ELFT>::writeTo(uint8_t *Buf) {
736 for (const SymbolBody *B : Entries) {
737 Target->writeIgotPlt(Buf, *B);
738 Buf += sizeof(uintX_t);
742 template <class ELFT>
743 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
744 : SyntheticSection<ELFT>(Dynamic ? (uintX_t)SHF_ALLOC : 0, SHT_STRTAB, 1,
748 // Adds a string to the string table. If HashIt is true we hash and check for
749 // duplicates. It is optional because the name of global symbols are already
750 // uniqued and hashing them again has a big cost for a small value: uniquing
751 // them with some other string that happens to be the same.
752 template <class ELFT>
753 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
755 auto R = StringMap.insert(std::make_pair(S, this->Size));
757 return R.first->second;
759 unsigned Ret = this->Size;
760 this->Size = this->Size + S.size() + 1;
761 Strings.push_back(S);
765 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
766 // ELF string tables start with NUL byte, so advance the pointer by one.
768 for (StringRef S : Strings) {
769 memcpy(Buf, S.data(), S.size());
774 // Returns the number of version definition entries. Because the first entry
775 // is for the version definition itself, it is the number of versioned symbols
776 // plus one. Note that we don't support multiple versions yet.
777 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
779 template <class ELFT>
780 DynamicSection<ELFT>::DynamicSection()
781 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC,
782 sizeof(uintX_t), ".dynamic") {
783 this->Entsize = ELFT::Is64Bits ? 16 : 8;
784 // .dynamic section is not writable on MIPS.
785 // See "Special Section" in Chapter 4 in the following document:
786 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
787 if (Config->EMachine == EM_MIPS)
788 this->Flags = SHF_ALLOC;
793 // There are some dynamic entries that don't depend on other sections.
794 // Such entries can be set early.
795 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
796 // Add strings to .dynstr early so that .dynstr's size will be
798 for (StringRef S : Config->AuxiliaryList)
799 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
800 if (!Config->RPath.empty())
801 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
802 In<ELFT>::DynStrTab->addString(Config->RPath)});
803 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
805 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
806 if (!Config->SoName.empty())
807 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
809 // Set DT_FLAGS and DT_FLAGS_1.
810 uint32_t DtFlags = 0;
811 uint32_t DtFlags1 = 0;
812 if (Config->Bsymbolic)
813 DtFlags |= DF_SYMBOLIC;
814 if (Config->ZNodelete)
815 DtFlags1 |= DF_1_NODELETE;
817 DtFlags |= DF_BIND_NOW;
818 DtFlags1 |= DF_1_NOW;
820 if (Config->ZOrigin) {
821 DtFlags |= DF_ORIGIN;
822 DtFlags1 |= DF_1_ORIGIN;
826 add({DT_FLAGS, DtFlags});
828 add({DT_FLAGS_1, DtFlags1});
830 if (!Config->Shared && !Config->Relocatable)
831 add({DT_DEBUG, (uint64_t)0});
834 // Add remaining entries to complete .dynamic contents.
835 template <class ELFT> void DynamicSection<ELFT>::finalize() {
837 return; // Already finalized.
839 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
840 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
841 bool IsRela = Config->Rela;
842 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
843 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
844 add({IsRela ? DT_RELAENT : DT_RELENT,
845 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
847 // MIPS dynamic loader does not support RELCOUNT tag.
848 // The problem is in the tight relation between dynamic
849 // relocations and GOT. So do not emit this tag on MIPS.
850 if (Config->EMachine != EM_MIPS) {
851 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
852 if (Config->ZCombreloc && NumRelativeRels)
853 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
856 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
857 add({DT_JMPREL, In<ELFT>::RelaPlt});
858 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
859 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
861 add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
864 add({DT_SYMTAB, In<ELFT>::DynSymTab});
865 add({DT_SYMENT, sizeof(Elf_Sym)});
866 add({DT_STRTAB, In<ELFT>::DynStrTab});
867 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
868 if (In<ELFT>::GnuHashTab)
869 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
870 if (In<ELFT>::HashTab)
871 add({DT_HASH, In<ELFT>::HashTab});
873 if (Out<ELFT>::PreinitArray) {
874 add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
875 add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
877 if (Out<ELFT>::InitArray) {
878 add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
879 add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
881 if (Out<ELFT>::FiniArray) {
882 add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
883 add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
886 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
888 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
891 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
892 if (HasVerNeed || In<ELFT>::VerDef)
893 add({DT_VERSYM, In<ELFT>::VerSym});
894 if (In<ELFT>::VerDef) {
895 add({DT_VERDEF, In<ELFT>::VerDef});
896 add({DT_VERDEFNUM, getVerDefNum()});
899 add({DT_VERNEED, In<ELFT>::VerNeed});
900 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
903 if (Config->EMachine == EM_MIPS) {
904 add({DT_MIPS_RLD_VERSION, 1});
905 add({DT_MIPS_FLAGS, RHF_NOTPOT});
906 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
907 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
908 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
909 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
910 add({DT_MIPS_GOTSYM, B->DynsymIndex});
912 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
913 add({DT_PLTGOT, In<ELFT>::MipsGot});
914 if (In<ELFT>::MipsRldMap)
915 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
918 this->OutSec->Entsize = this->Entsize;
919 this->OutSec->Link = this->Link;
922 this->Size = (Entries.size() + 1) * this->Entsize;
925 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
926 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
928 for (const Entry &E : Entries) {
932 P->d_un.d_ptr = E.OutSec->Addr;
934 case Entry::InSecAddr:
935 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
938 P->d_un.d_val = E.OutSec->Size;
941 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
943 case Entry::PlainInt:
944 P->d_un.d_val = E.Val;
951 template <class ELFT>
952 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
954 return OutputSec->Addr + OffsetInSec;
955 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
958 template <class ELFT>
959 typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
961 return Sym->getVA<ELFT>(Addend);
965 template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
966 if (Sym && !UseSymVA)
967 return Sym->DynsymIndex;
971 template <class ELFT>
972 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
973 : SyntheticSection<ELFT>(SHF_ALLOC, Config->Rela ? SHT_RELA : SHT_REL,
974 sizeof(uintX_t), Name),
976 this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
979 template <class ELFT>
980 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
981 if (Reloc.Type == Target->RelativeRel)
983 Relocs.push_back(Reloc);
986 template <class ELFT, class RelTy>
987 static bool compRelocations(const RelTy &A, const RelTy &B) {
988 bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
989 bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
990 if (AIsRel != BIsRel)
993 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
996 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
997 uint8_t *BufBegin = Buf;
998 for (const DynamicReloc<ELFT> &Rel : Relocs) {
999 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
1000 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1003 P->r_addend = Rel.getAddend();
1004 P->r_offset = Rel.getOffset();
1005 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
1006 // Dynamic relocation against MIPS GOT section make deal TLS entries
1007 // allocated in the end of the GOT. We need to adjust the offset to take
1008 // in account 'local' and 'global' GOT entries.
1009 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
1010 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
1015 std::stable_sort((Elf_Rela *)BufBegin,
1016 (Elf_Rela *)BufBegin + Relocs.size(),
1017 compRelocations<ELFT, Elf_Rela>);
1019 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1020 compRelocations<ELFT, Elf_Rel>);
1024 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1025 return this->Entsize * Relocs.size();
1028 template <class ELFT> void RelocationSection<ELFT>::finalize() {
1029 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1030 : In<ELFT>::SymTab->OutSec->SectionIndex;
1032 // Set required output section properties.
1033 this->OutSec->Link = this->Link;
1034 this->OutSec->Entsize = this->Entsize;
1037 template <class ELFT>
1038 SymbolTableSection<ELFT>::SymbolTableSection(
1039 StringTableSection<ELFT> &StrTabSec)
1040 : SyntheticSection<ELFT>(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1041 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1043 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1044 StrTabSec(StrTabSec) {
1045 this->Entsize = sizeof(Elf_Sym);
1048 // Orders symbols according to their positions in the GOT,
1049 // in compliance with MIPS ABI rules.
1050 // See "Global Offset Table" in Chapter 5 in the following document
1051 // for detailed description:
1052 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1053 static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
1054 // Sort entries related to non-local preemptible symbols by GOT indexes.
1055 // All other entries go to the first part of GOT in arbitrary order.
1056 bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1057 bool RIsInLocalGot = !R->IsInGlobalMipsGot;
1058 if (LIsInLocalGot || RIsInLocalGot)
1059 return !RIsInLocalGot;
1060 return L->GotIndex < R->GotIndex;
1063 static uint8_t getSymbolBinding(SymbolBody *Body) {
1064 Symbol *S = Body->symbol();
1065 if (Config->Relocatable)
1067 uint8_t Visibility = S->Visibility;
1068 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1070 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
1075 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1076 this->OutSec->Link = this->Link = StrTabSec.OutSec->SectionIndex;
1077 this->OutSec->Info = this->Info = NumLocals + 1;
1078 this->OutSec->Entsize = this->Entsize;
1080 if (Config->Relocatable) {
1081 size_t I = NumLocals;
1082 for (const SymbolTableEntry &S : Symbols)
1083 S.Symbol->DynsymIndex = ++I;
1087 if (!StrTabSec.isDynamic()) {
1088 std::stable_sort(Symbols.begin(), Symbols.end(),
1089 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1090 return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1091 getSymbolBinding(R.Symbol) != STB_LOCAL;
1095 if (In<ELFT>::GnuHashTab)
1096 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1097 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1098 else if (Config->EMachine == EM_MIPS)
1099 std::stable_sort(Symbols.begin(), Symbols.end(),
1100 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1101 return sortMipsSymbols(L.Symbol, R.Symbol);
1104 for (const SymbolTableEntry &S : Symbols)
1105 S.Symbol->DynsymIndex = ++I;
1108 template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1109 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1112 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1113 Buf += sizeof(Elf_Sym);
1115 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1116 // .dynsym only contains global symbols.
1117 if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1118 writeLocalSymbols(Buf);
1120 writeGlobalSymbols(Buf);
1123 template <class ELFT>
1124 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1125 // Iterate over all input object files to copy their local symbols
1126 // to the output symbol table pointed by Buf.
1127 for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
1128 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1129 File->KeptLocalSyms) {
1130 const DefinedRegular<ELFT> &Body = *P.first;
1131 InputSectionBase<ELFT> *Section = Body.Section;
1132 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1135 ESym->st_shndx = SHN_ABS;
1136 ESym->st_value = Body.Value;
1138 const OutputSectionBase *OutSec = Section->OutSec;
1139 ESym->st_shndx = OutSec->SectionIndex;
1140 ESym->st_value = OutSec->Addr + Section->getOffset(Body);
1142 ESym->st_name = P.second;
1143 ESym->st_size = Body.template getSize<ELFT>();
1144 ESym->setBindingAndType(STB_LOCAL, Body.Type);
1145 Buf += sizeof(*ESym);
1150 template <class ELFT>
1151 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1152 // Write the internal symbol table contents to the output symbol table
1154 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1155 for (const SymbolTableEntry &S : Symbols) {
1156 SymbolBody *Body = S.Symbol;
1157 size_t StrOff = S.StrTabOffset;
1159 uint8_t Type = Body->Type;
1160 uintX_t Size = Body->getSize<ELFT>();
1162 ESym->setBindingAndType(getSymbolBinding(Body), Type);
1163 ESym->st_size = Size;
1164 ESym->st_name = StrOff;
1165 ESym->setVisibility(Body->symbol()->Visibility);
1166 ESym->st_value = Body->getVA<ELFT>();
1168 if (const OutputSectionBase *OutSec = getOutputSection(Body))
1169 ESym->st_shndx = OutSec->SectionIndex;
1170 else if (isa<DefinedRegular<ELFT>>(Body))
1171 ESym->st_shndx = SHN_ABS;
1173 if (Config->EMachine == EM_MIPS) {
1174 // On MIPS we need to mark symbol which has a PLT entry and requires
1175 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1176 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1177 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1178 if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1179 ESym->st_other |= STO_MIPS_PLT;
1180 if (Config->Relocatable) {
1181 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1182 if (D && D->isMipsPIC())
1183 ESym->st_other |= STO_MIPS_PIC;
1190 template <class ELFT>
1191 const OutputSectionBase *
1192 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1193 switch (Sym->kind()) {
1194 case SymbolBody::DefinedSyntheticKind:
1195 return cast<DefinedSynthetic>(Sym)->Section;
1196 case SymbolBody::DefinedRegularKind: {
1197 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1199 return D.Section->OutSec;
1202 case SymbolBody::DefinedCommonKind:
1203 return In<ELFT>::Common->OutSec;
1204 case SymbolBody::SharedKind:
1205 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1206 return Out<ELFT>::Bss;
1208 case SymbolBody::UndefinedKind:
1209 case SymbolBody::LazyArchiveKind:
1210 case SymbolBody::LazyObjectKind:
1216 template <class ELFT>
1217 GnuHashTableSection<ELFT>::GnuHashTableSection()
1218 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t),
1220 this->Entsize = ELFT::Is64Bits ? 0 : 4;
1223 template <class ELFT>
1224 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
1228 // These values are prime numbers which are not greater than 2^(N-1) + 1.
1229 // In result, for any particular NumHashed we return a prime number
1230 // which is not greater than NumHashed.
1231 static const unsigned Primes[] = {
1232 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
1233 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
1235 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
1236 array_lengthof(Primes) - 1)];
1239 // Bloom filter estimation: at least 8 bits for each hashed symbol.
1240 // GNU Hash table requirement: it should be a power of 2,
1241 // the minimum value is 1, even for an empty table.
1242 // Expected results for a 32-bit target:
1243 // calcMaskWords(0..4) = 1
1244 // calcMaskWords(5..8) = 2
1245 // calcMaskWords(9..16) = 4
1246 // For a 64-bit target:
1247 // calcMaskWords(0..8) = 1
1248 // calcMaskWords(9..16) = 2
1249 // calcMaskWords(17..32) = 4
1250 template <class ELFT>
1251 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
1254 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
1257 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
1258 unsigned NumHashed = Symbols.size();
1259 NBuckets = calcNBuckets(NumHashed);
1260 MaskWords = calcMaskWords(NumHashed);
1261 // Second hash shift estimation: just predefined values.
1262 Shift2 = ELFT::Is64Bits ? 6 : 5;
1264 this->OutSec->Entsize = this->Entsize;
1265 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1266 this->Size = sizeof(Elf_Word) * 4 // Header
1267 + sizeof(Elf_Off) * MaskWords // Bloom Filter
1268 + sizeof(Elf_Word) * NBuckets // Hash Buckets
1269 + sizeof(Elf_Word) * NumHashed; // Hash Values
1272 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1274 if (Symbols.empty())
1276 writeBloomFilter(Buf);
1277 writeHashTable(Buf);
1280 template <class ELFT>
1281 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
1282 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1284 *P++ = In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
1287 Buf = reinterpret_cast<uint8_t *>(P);
1290 template <class ELFT>
1291 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
1292 unsigned C = sizeof(Elf_Off) * 8;
1294 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
1295 for (const SymbolData &Sym : Symbols) {
1296 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
1297 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
1298 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
1301 Buf += sizeof(Elf_Off) * MaskWords;
1304 template <class ELFT>
1305 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
1306 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1307 Elf_Word *Values = Buckets + NBuckets;
1309 int PrevBucket = -1;
1311 for (const SymbolData &Sym : Symbols) {
1312 int Bucket = Sym.Hash % NBuckets;
1313 assert(PrevBucket <= Bucket);
1314 if (Bucket != PrevBucket) {
1315 Buckets[Bucket] = Sym.Body->DynsymIndex;
1316 PrevBucket = Bucket;
1320 Values[I] = Sym.Hash & ~1;
1327 static uint32_t hashGnu(StringRef Name) {
1329 for (uint8_t C : Name)
1330 H = (H << 5) + H + C;
1334 // Add symbols to this symbol hash table. Note that this function
1335 // destructively sort a given vector -- which is needed because
1336 // GNU-style hash table places some sorting requirements.
1337 template <class ELFT>
1338 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
1339 // Ideally this will just be 'auto' but GCC 6.1 is not able
1340 // to deduce it correctly.
1341 std::vector<SymbolTableEntry>::iterator Mid =
1342 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1343 return S.Symbol->isUndefined();
1347 for (auto I = Mid, E = V.end(); I != E; ++I) {
1348 SymbolBody *B = I->Symbol;
1349 size_t StrOff = I->StrTabOffset;
1350 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
1353 unsigned NBuckets = calcNBuckets(Symbols.size());
1354 std::stable_sort(Symbols.begin(), Symbols.end(),
1355 [&](const SymbolData &L, const SymbolData &R) {
1356 return L.Hash % NBuckets < R.Hash % NBuckets;
1359 V.erase(Mid, V.end());
1360 for (const SymbolData &Sym : Symbols)
1361 V.push_back({Sym.Body, Sym.STName});
1364 template <class ELFT>
1365 HashTableSection<ELFT>::HashTableSection()
1366 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_HASH, sizeof(Elf_Word), ".hash") {
1367 this->Entsize = sizeof(Elf_Word);
1370 template <class ELFT> void HashTableSection<ELFT>::finalize() {
1371 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1372 this->OutSec->Entsize = this->Entsize;
1374 unsigned NumEntries = 2; // nbucket and nchain.
1375 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1377 // Create as many buckets as there are symbols.
1378 // FIXME: This is simplistic. We can try to optimize it, but implementing
1379 // support for SHT_GNU_HASH is probably even more profitable.
1380 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
1381 this->Size = NumEntries * sizeof(Elf_Word);
1384 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1385 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
1386 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1387 *P++ = NumSymbols; // nbucket
1388 *P++ = NumSymbols; // nchain
1390 Elf_Word *Buckets = P;
1391 Elf_Word *Chains = P + NumSymbols;
1393 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1394 SymbolBody *Body = S.Symbol;
1395 StringRef Name = Body->getName();
1396 unsigned I = Body->DynsymIndex;
1397 uint32_t Hash = hashSysV(Name) % NumSymbols;
1398 Chains[I] = Buckets[Hash];
1403 template <class ELFT>
1404 PltSection<ELFT>::PltSection()
1405 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1408 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
1409 // At beginning of PLT, we have code to call the dynamic linker
1410 // to resolve dynsyms at runtime. Write such code.
1411 Target->writePltHeader(Buf);
1412 size_t Off = Target->PltHeaderSize;
1414 for (auto &I : Entries) {
1415 const SymbolBody *B = I.first;
1416 unsigned RelOff = I.second;
1417 uint64_t Got = B->getGotPltVA<ELFT>();
1418 uint64_t Plt = this->getVA() + Off;
1419 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1420 Off += Target->PltEntrySize;
1424 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
1425 Sym.PltIndex = Entries.size();
1426 unsigned RelOff = In<ELFT>::RelaPlt->getRelocOffset();
1427 Entries.push_back(std::make_pair(&Sym, RelOff));
1430 template <class ELFT> size_t PltSection<ELFT>::getSize() const {
1431 return Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
1434 template <class ELFT>
1435 IpltSection<ELFT>::IpltSection()
1436 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1439 template <class ELFT> void IpltSection<ELFT>::writeTo(uint8_t *Buf) {
1440 // The IRelative relocations do not support lazy binding so no header is
1443 for (auto &I : Entries) {
1444 const SymbolBody *B = I.first;
1445 unsigned RelOff = I.second + In<ELFT>::Plt->getSize();
1446 uint64_t Got = B->getGotPltVA<ELFT>();
1447 uint64_t Plt = this->getVA() + Off;
1448 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1449 Off += Target->PltEntrySize;
1453 template <class ELFT> void IpltSection<ELFT>::addEntry(SymbolBody &Sym) {
1454 Sym.PltIndex = Entries.size();
1455 Sym.IsInIplt = true;
1456 unsigned RelOff = In<ELFT>::RelaIplt->getRelocOffset();
1457 Entries.push_back(std::make_pair(&Sym, RelOff));
1460 template <class ELFT> size_t IpltSection<ELFT>::getSize() const {
1461 return Entries.size() * Target->PltEntrySize;
1464 template <class ELFT>
1465 GdbIndexSection<ELFT>::GdbIndexSection()
1466 : SyntheticSection<ELFT>(0, SHT_PROGBITS, 1, ".gdb_index"),
1467 StringPool(llvm::StringTableBuilder::ELF) {}
1469 template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
1470 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
1471 if (InputSection<ELFT> *IS = dyn_cast<InputSection<ELFT>>(S))
1472 if (IS->OutSec && IS->Name == ".debug_info")
1476 // Iterative hash function for symbol's name is described in .gdb_index format
1477 // specification. Note that we use one for version 5 to 7 here, it is different
1479 static uint32_t hash(StringRef Str) {
1481 for (uint8_t C : Str)
1482 R = R * 67 + tolower(C) - 113;
1486 template <class ELFT>
1487 void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
1488 GdbIndexBuilder<ELFT> Builder(I);
1492 size_t CuId = CompilationUnits.size();
1493 std::vector<std::pair<uintX_t, uintX_t>> CuList = Builder.readCUList();
1494 CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
1496 std::vector<AddressEntry<ELFT>> AddrArea = Builder.readAddressArea(CuId);
1497 AddressArea.insert(AddressArea.end(), AddrArea.begin(), AddrArea.end());
1499 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
1500 Builder.readPubNamesAndTypes();
1502 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1503 uint32_t Hash = hash(Pair.first);
1504 size_t Offset = StringPool.add(Pair.first);
1508 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1510 Sym->CuVectorIndex = CuVectors.size();
1511 CuVectors.push_back({{CuId, Pair.second}});
1515 std::vector<std::pair<uint32_t, uint8_t>> &CuVec =
1516 CuVectors[Sym->CuVectorIndex];
1517 CuVec.push_back({CuId, Pair.second});
1521 template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
1526 parseDebugSections();
1528 // GdbIndex header consist from version fields
1529 // and 5 more fields with different kinds of offsets.
1530 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1531 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
1533 ConstantPoolOffset =
1534 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1536 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1537 CuVectorsOffset.push_back(CuVectorsSize);
1538 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1540 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1542 StringPool.finalizeInOrder();
1545 template <class ELFT> size_t GdbIndexSection<ELFT>::getSize() const {
1546 const_cast<GdbIndexSection<ELFT> *>(this)->finalize();
1547 return StringPoolOffset + StringPool.getSize();
1550 template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
1551 write32le(Buf, 7); // Write version.
1552 write32le(Buf + 4, CuListOffset); // CU list offset.
1553 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1554 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1555 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1556 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
1559 // Write the CU list.
1560 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1561 write64le(Buf, CU.first);
1562 write64le(Buf + 8, CU.second);
1566 // Write the address area.
1567 for (AddressEntry<ELFT> &E : AddressArea) {
1568 uintX_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
1569 write64le(Buf, BaseAddr + E.LowAddress);
1570 write64le(Buf + 8, BaseAddr + E.HighAddress);
1571 write32le(Buf + 16, E.CuIndex);
1575 // Write the symbol table.
1576 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1577 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1580 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1581 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1582 write32le(Buf, NameOffset);
1583 write32le(Buf + 4, CuVectorOffset);
1588 // Write the CU vectors into the constant pool.
1589 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1590 write32le(Buf, CuVec.size());
1592 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1593 uint32_t Index = P.first;
1594 uint8_t Flags = P.second;
1595 Index |= Flags << 24;
1596 write32le(Buf, Index);
1601 StringPool.write(Buf);
1604 template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
1605 return !Out<ELFT>::DebugInfo;
1608 template <class ELFT>
1609 EhFrameHeader<ELFT>::EhFrameHeader()
1610 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1612 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1613 // Each entry of the search table consists of two values,
1614 // the starting PC from where FDEs covers, and the FDE's address.
1615 // It is sorted by PC.
1616 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1617 const endianness E = ELFT::TargetEndianness;
1619 // Sort the FDE list by their PC and uniqueify. Usually there is only
1620 // one FDE for a PC (i.e. function), but if ICF merges two functions
1621 // into one, there can be more than one FDEs pointing to the address.
1622 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1623 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1624 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1625 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1628 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1629 Buf[2] = DW_EH_PE_udata4;
1630 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1631 write32<E>(Buf + 4, Out<ELFT>::EhFrame->Addr - this->getVA() - 4);
1632 write32<E>(Buf + 8, Fdes.size());
1635 uintX_t VA = this->getVA();
1636 for (FdeData &Fde : Fdes) {
1637 write32<E>(Buf, Fde.Pc - VA);
1638 write32<E>(Buf + 4, Fde.FdeVA - VA);
1643 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1644 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1645 return 12 + Out<ELFT>::EhFrame->NumFdes * 8;
1648 template <class ELFT>
1649 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1650 Fdes.push_back({Pc, FdeVA});
1653 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1654 return Out<ELFT>::EhFrame->empty();
1657 template <class ELFT>
1658 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1659 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1660 ".gnu.version_d") {}
1662 static StringRef getFileDefName() {
1663 if (!Config->SoName.empty())
1664 return Config->SoName;
1665 return Config->OutputFile;
1668 template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1669 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1670 for (VersionDefinition &V : Config->VersionDefinitions)
1671 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1673 this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1675 // sh_info should be set to the number of definitions. This fact is missed in
1676 // documentation, but confirmed by binutils community:
1677 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1678 this->OutSec->Info = this->Info = getVerDefNum();
1681 template <class ELFT>
1682 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1683 StringRef Name, size_t NameOff) {
1684 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1685 Verdef->vd_version = 1;
1687 Verdef->vd_aux = sizeof(Elf_Verdef);
1688 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1689 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1690 Verdef->vd_ndx = Index;
1691 Verdef->vd_hash = hashSysV(Name);
1693 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1694 Verdaux->vda_name = NameOff;
1695 Verdaux->vda_next = 0;
1698 template <class ELFT>
1699 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1700 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1702 for (VersionDefinition &V : Config->VersionDefinitions) {
1703 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1704 writeOne(Buf, V.Id, V.Name, V.NameOff);
1707 // Need to terminate the last version definition.
1708 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1709 Verdef->vd_next = 0;
1712 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1713 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1716 template <class ELFT>
1717 VersionTableSection<ELFT>::VersionTableSection()
1718 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1721 template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1722 this->OutSec->Entsize = this->Entsize = sizeof(Elf_Versym);
1723 // At the moment of june 2016 GNU docs does not mention that sh_link field
1724 // should be set, but Sun docs do. Also readelf relies on this field.
1725 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1728 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
1729 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
1732 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1733 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1734 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1735 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
1740 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
1741 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
1744 template <class ELFT>
1745 VersionNeedSection<ELFT>::VersionNeedSection()
1746 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
1748 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1749 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1750 // First identifiers are reserved by verdef section if it exist.
1751 NextIndex = getVerDefNum() + 1;
1754 template <class ELFT>
1755 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1757 SS->symbol()->VersionId = VER_NDX_GLOBAL;
1760 SharedFile<ELFT> *F = SS->file();
1761 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1762 // to create one by adding it to our needed list and creating a dynstr entry
1764 if (F->VerdefMap.empty())
1765 Needed.push_back({F, In<ELFT>::DynStrTab->addString(F->getSoName())});
1766 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1767 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1768 // prepare to create one by allocating a version identifier and creating a
1769 // dynstr entry for the version name.
1770 if (NV.Index == 0) {
1771 NV.StrTab = In<ELFT>::DynStrTab->addString(
1772 SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1773 NV.Index = NextIndex++;
1775 SS->symbol()->VersionId = NV.Index;
1778 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1779 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1780 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1781 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1783 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1784 // Create an Elf_Verneed for this DSO.
1785 Verneed->vn_version = 1;
1786 Verneed->vn_cnt = P.first->VerdefMap.size();
1787 Verneed->vn_file = P.second;
1789 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1790 Verneed->vn_next = sizeof(Elf_Verneed);
1793 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1794 // VerdefMap, which will only contain references to needed version
1795 // definitions. Each Elf_Vernaux is based on the information contained in
1796 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1797 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1798 // data structures within a single input file.
1799 for (auto &NV : P.first->VerdefMap) {
1800 Vernaux->vna_hash = NV.first->vd_hash;
1801 Vernaux->vna_flags = 0;
1802 Vernaux->vna_other = NV.second.Index;
1803 Vernaux->vna_name = NV.second.StrTab;
1804 Vernaux->vna_next = sizeof(Elf_Vernaux);
1808 Vernaux[-1].vna_next = 0;
1810 Verneed[-1].vn_next = 0;
1813 template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1814 this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1815 this->OutSec->Info = this->Info = Needed.size();
1818 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
1819 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1820 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1821 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1825 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
1826 return getNeedNum() == 0;
1829 template <class ELFT>
1830 MipsRldMapSection<ELFT>::MipsRldMapSection()
1831 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1832 sizeof(typename ELFT::uint), ".rld_map") {}
1834 template <class ELFT> void MipsRldMapSection<ELFT>::writeTo(uint8_t *Buf) {
1835 // Apply filler from linker script.
1836 uint64_t Filler = Script<ELFT>::X->getFiller(this->Name);
1837 Filler = (Filler << 32) | Filler;
1838 memcpy(Buf, &Filler, getSize());
1841 template <class ELFT>
1842 ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
1843 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
1844 sizeof(typename ELFT::uint), ".ARM.exidx") {}
1846 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
1847 // This section will have been sorted last in the .ARM.exidx table.
1848 // This table entry will have the form:
1849 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
1850 template <class ELFT>
1851 void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf) {
1852 // Get the InputSection before us, we are by definition last
1853 auto RI = cast<OutputSection<ELFT>>(this->OutSec)->Sections.rbegin();
1854 InputSection<ELFT> *LE = *(++RI);
1855 InputSection<ELFT> *LC = cast<InputSection<ELFT>>(LE->getLinkOrderDep());
1856 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
1857 uint64_t P = this->getVA();
1858 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
1859 write32le(Buf + 4, 0x1);
1862 template InputSection<ELF32LE> *elf::createCommonSection();
1863 template InputSection<ELF32BE> *elf::createCommonSection();
1864 template InputSection<ELF64LE> *elf::createCommonSection();
1865 template InputSection<ELF64BE> *elf::createCommonSection();
1867 template InputSection<ELF32LE> *elf::createInterpSection();
1868 template InputSection<ELF32BE> *elf::createInterpSection();
1869 template InputSection<ELF64LE> *elf::createInterpSection();
1870 template InputSection<ELF64BE> *elf::createInterpSection();
1872 template MergeInputSection<ELF32LE> *elf::createCommentSection();
1873 template MergeInputSection<ELF32BE> *elf::createCommentSection();
1874 template MergeInputSection<ELF64LE> *elf::createCommentSection();
1875 template MergeInputSection<ELF64BE> *elf::createCommentSection();
1877 template class elf::MipsAbiFlagsSection<ELF32LE>;
1878 template class elf::MipsAbiFlagsSection<ELF32BE>;
1879 template class elf::MipsAbiFlagsSection<ELF64LE>;
1880 template class elf::MipsAbiFlagsSection<ELF64BE>;
1882 template class elf::MipsOptionsSection<ELF32LE>;
1883 template class elf::MipsOptionsSection<ELF32BE>;
1884 template class elf::MipsOptionsSection<ELF64LE>;
1885 template class elf::MipsOptionsSection<ELF64BE>;
1887 template class elf::MipsReginfoSection<ELF32LE>;
1888 template class elf::MipsReginfoSection<ELF32BE>;
1889 template class elf::MipsReginfoSection<ELF64LE>;
1890 template class elf::MipsReginfoSection<ELF64BE>;
1892 template class elf::BuildIdSection<ELF32LE>;
1893 template class elf::BuildIdSection<ELF32BE>;
1894 template class elf::BuildIdSection<ELF64LE>;
1895 template class elf::BuildIdSection<ELF64BE>;
1897 template class elf::GotSection<ELF32LE>;
1898 template class elf::GotSection<ELF32BE>;
1899 template class elf::GotSection<ELF64LE>;
1900 template class elf::GotSection<ELF64BE>;
1902 template class elf::MipsGotSection<ELF32LE>;
1903 template class elf::MipsGotSection<ELF32BE>;
1904 template class elf::MipsGotSection<ELF64LE>;
1905 template class elf::MipsGotSection<ELF64BE>;
1907 template class elf::GotPltSection<ELF32LE>;
1908 template class elf::GotPltSection<ELF32BE>;
1909 template class elf::GotPltSection<ELF64LE>;
1910 template class elf::GotPltSection<ELF64BE>;
1912 template class elf::IgotPltSection<ELF32LE>;
1913 template class elf::IgotPltSection<ELF32BE>;
1914 template class elf::IgotPltSection<ELF64LE>;
1915 template class elf::IgotPltSection<ELF64BE>;
1917 template class elf::StringTableSection<ELF32LE>;
1918 template class elf::StringTableSection<ELF32BE>;
1919 template class elf::StringTableSection<ELF64LE>;
1920 template class elf::StringTableSection<ELF64BE>;
1922 template class elf::DynamicSection<ELF32LE>;
1923 template class elf::DynamicSection<ELF32BE>;
1924 template class elf::DynamicSection<ELF64LE>;
1925 template class elf::DynamicSection<ELF64BE>;
1927 template class elf::RelocationSection<ELF32LE>;
1928 template class elf::RelocationSection<ELF32BE>;
1929 template class elf::RelocationSection<ELF64LE>;
1930 template class elf::RelocationSection<ELF64BE>;
1932 template class elf::SymbolTableSection<ELF32LE>;
1933 template class elf::SymbolTableSection<ELF32BE>;
1934 template class elf::SymbolTableSection<ELF64LE>;
1935 template class elf::SymbolTableSection<ELF64BE>;
1937 template class elf::GnuHashTableSection<ELF32LE>;
1938 template class elf::GnuHashTableSection<ELF32BE>;
1939 template class elf::GnuHashTableSection<ELF64LE>;
1940 template class elf::GnuHashTableSection<ELF64BE>;
1942 template class elf::HashTableSection<ELF32LE>;
1943 template class elf::HashTableSection<ELF32BE>;
1944 template class elf::HashTableSection<ELF64LE>;
1945 template class elf::HashTableSection<ELF64BE>;
1947 template class elf::PltSection<ELF32LE>;
1948 template class elf::PltSection<ELF32BE>;
1949 template class elf::PltSection<ELF64LE>;
1950 template class elf::PltSection<ELF64BE>;
1952 template class elf::IpltSection<ELF32LE>;
1953 template class elf::IpltSection<ELF32BE>;
1954 template class elf::IpltSection<ELF64LE>;
1955 template class elf::IpltSection<ELF64BE>;
1957 template class elf::GdbIndexSection<ELF32LE>;
1958 template class elf::GdbIndexSection<ELF32BE>;
1959 template class elf::GdbIndexSection<ELF64LE>;
1960 template class elf::GdbIndexSection<ELF64BE>;
1962 template class elf::EhFrameHeader<ELF32LE>;
1963 template class elf::EhFrameHeader<ELF32BE>;
1964 template class elf::EhFrameHeader<ELF64LE>;
1965 template class elf::EhFrameHeader<ELF64BE>;
1967 template class elf::VersionTableSection<ELF32LE>;
1968 template class elf::VersionTableSection<ELF32BE>;
1969 template class elf::VersionTableSection<ELF64LE>;
1970 template class elf::VersionTableSection<ELF64BE>;
1972 template class elf::VersionNeedSection<ELF32LE>;
1973 template class elf::VersionNeedSection<ELF32BE>;
1974 template class elf::VersionNeedSection<ELF64LE>;
1975 template class elf::VersionNeedSection<ELF64BE>;
1977 template class elf::VersionDefinitionSection<ELF32LE>;
1978 template class elf::VersionDefinitionSection<ELF32BE>;
1979 template class elf::VersionDefinitionSection<ELF64LE>;
1980 template class elf::VersionDefinitionSection<ELF64BE>;
1982 template class elf::MipsRldMapSection<ELF32LE>;
1983 template class elf::MipsRldMapSection<ELF32BE>;
1984 template class elf::MipsRldMapSection<ELF64LE>;
1985 template class elf::MipsRldMapSection<ELF64BE>;
1987 template class elf::ARMExidxSentinelSection<ELF32LE>;
1988 template class elf::ARMExidxSentinelSection<ELF32BE>;
1989 template class elf::ARMExidxSentinelSection<ELF64LE>;
1990 template class elf::ARMExidxSentinelSection<ELF64BE>;