xref: /openbsd/gnu/llvm/lld/ELF/SyntheticSections.cpp (revision 293d5193)
1ece8a530Spatrick //===- SyntheticSections.cpp ----------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick //
9ece8a530Spatrick // This file contains linker-synthesized sections. Currently,
10ece8a530Spatrick // synthetic sections are created either output sections or input sections,
11ece8a530Spatrick // but we are rewriting code so that all synthetic sections are created as
12ece8a530Spatrick // input sections.
13ece8a530Spatrick //
14ece8a530Spatrick //===----------------------------------------------------------------------===//
15ece8a530Spatrick 
16ece8a530Spatrick #include "SyntheticSections.h"
17ece8a530Spatrick #include "Config.h"
1805edf1c1Srobert #include "DWARF.h"
1905edf1c1Srobert #include "EhFrame.h"
20ece8a530Spatrick #include "InputFiles.h"
21ece8a530Spatrick #include "LinkerScript.h"
22ece8a530Spatrick #include "OutputSections.h"
23ece8a530Spatrick #include "SymbolTable.h"
24ece8a530Spatrick #include "Symbols.h"
25ece8a530Spatrick #include "Target.h"
2605edf1c1Srobert #include "Thunks.h"
27ece8a530Spatrick #include "Writer.h"
2805edf1c1Srobert #include "lld/Common/CommonLinkerContext.h"
29adae0cfdSpatrick #include "lld/Common/DWARF.h"
30ece8a530Spatrick #include "lld/Common/Strings.h"
31ece8a530Spatrick #include "lld/Common/Version.h"
3205edf1c1Srobert #include "llvm/ADT/STLExtras.h"
33ece8a530Spatrick #include "llvm/ADT/SetOperations.h"
34ece8a530Spatrick #include "llvm/ADT/StringExtras.h"
35ece8a530Spatrick #include "llvm/BinaryFormat/Dwarf.h"
3605edf1c1Srobert #include "llvm/BinaryFormat/ELF.h"
37ece8a530Spatrick #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
38ece8a530Spatrick #include "llvm/Support/Endian.h"
39ece8a530Spatrick #include "llvm/Support/LEB128.h"
40adae0cfdSpatrick #include "llvm/Support/Parallel.h"
41adae0cfdSpatrick #include "llvm/Support/TimeProfiler.h"
42ece8a530Spatrick #include <cstdlib>
43ece8a530Spatrick 
44ece8a530Spatrick using namespace llvm;
45ece8a530Spatrick using namespace llvm::dwarf;
46ece8a530Spatrick using namespace llvm::ELF;
47ece8a530Spatrick using namespace llvm::object;
48ece8a530Spatrick using namespace llvm::support;
49adae0cfdSpatrick using namespace lld;
50adae0cfdSpatrick using namespace lld::elf;
51ece8a530Spatrick 
52ece8a530Spatrick using llvm::support::endian::read32le;
53ece8a530Spatrick using llvm::support::endian::write32le;
54ece8a530Spatrick using llvm::support::endian::write64le;
55ece8a530Spatrick 
56ece8a530Spatrick constexpr size_t MergeNoTailSection::numShards;
57ece8a530Spatrick 
readUint(uint8_t * buf)58ece8a530Spatrick static uint64_t readUint(uint8_t *buf) {
59ece8a530Spatrick   return config->is64 ? read64(buf) : read32(buf);
60ece8a530Spatrick }
61ece8a530Spatrick 
writeUint(uint8_t * buf,uint64_t val)62ece8a530Spatrick static void writeUint(uint8_t *buf, uint64_t val) {
63ece8a530Spatrick   if (config->is64)
64ece8a530Spatrick     write64(buf, val);
65ece8a530Spatrick   else
66ece8a530Spatrick     write32(buf, val);
67ece8a530Spatrick }
68ece8a530Spatrick 
69ece8a530Spatrick // Returns an LLD version string.
getVersion()70ece8a530Spatrick static ArrayRef<uint8_t> getVersion() {
71ece8a530Spatrick   // Check LLD_VERSION first for ease of testing.
72ece8a530Spatrick   // You can get consistent output by using the environment variable.
73ece8a530Spatrick   // This is only for testing.
74ece8a530Spatrick   StringRef s = getenv("LLD_VERSION");
75ece8a530Spatrick   if (s.empty())
7605edf1c1Srobert     s = saver().save(Twine("Linker: ") + getLLDVersion());
77ece8a530Spatrick 
78ece8a530Spatrick   // +1 to include the terminating '\0'.
79ece8a530Spatrick   return {(const uint8_t *)s.data(), s.size() + 1};
80ece8a530Spatrick }
81ece8a530Spatrick 
82ece8a530Spatrick // Creates a .comment section containing LLD version info.
83ece8a530Spatrick // With this feature, you can identify LLD-generated binaries easily
84ece8a530Spatrick // by "readelf --string-dump .comment <file>".
85ece8a530Spatrick // The returned object is a mergeable string section.
createCommentSection()86adae0cfdSpatrick MergeInputSection *elf::createCommentSection() {
8705edf1c1Srobert   auto *sec = make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
88ece8a530Spatrick                                       getVersion(), ".comment");
8905edf1c1Srobert   sec->splitIntoPieces();
9005edf1c1Srobert   return sec;
91ece8a530Spatrick }
92ece8a530Spatrick 
93ece8a530Spatrick // .MIPS.abiflags section.
94ece8a530Spatrick template <class ELFT>
MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)95ece8a530Spatrick MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)
96ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
97ece8a530Spatrick       flags(flags) {
98ece8a530Spatrick   this->entsize = sizeof(Elf_Mips_ABIFlags);
99ece8a530Spatrick }
100ece8a530Spatrick 
writeTo(uint8_t * buf)101ece8a530Spatrick template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
102ece8a530Spatrick   memcpy(buf, &flags, sizeof(flags));
103ece8a530Spatrick }
104ece8a530Spatrick 
105ece8a530Spatrick template <class ELFT>
create()10605edf1c1Srobert std::unique_ptr<MipsAbiFlagsSection<ELFT>> MipsAbiFlagsSection<ELFT>::create() {
107ece8a530Spatrick   Elf_Mips_ABIFlags flags = {};
108ece8a530Spatrick   bool create = false;
109ece8a530Spatrick 
11005edf1c1Srobert   for (InputSectionBase *sec : ctx.inputSections) {
111ece8a530Spatrick     if (sec->type != SHT_MIPS_ABIFLAGS)
112ece8a530Spatrick       continue;
113ece8a530Spatrick     sec->markDead();
114ece8a530Spatrick     create = true;
115ece8a530Spatrick 
116ece8a530Spatrick     std::string filename = toString(sec->file);
11705edf1c1Srobert     const size_t size = sec->content().size();
118ece8a530Spatrick     // Older version of BFD (such as the default FreeBSD linker) concatenate
119ece8a530Spatrick     // .MIPS.abiflags instead of merging. To allow for this case (or potential
120ece8a530Spatrick     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
121ece8a530Spatrick     if (size < sizeof(Elf_Mips_ABIFlags)) {
122ece8a530Spatrick       error(filename + ": invalid size of .MIPS.abiflags section: got " +
123ece8a530Spatrick             Twine(size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
124ece8a530Spatrick       return nullptr;
125ece8a530Spatrick     }
12605edf1c1Srobert     auto *s =
12705edf1c1Srobert         reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->content().data());
128ece8a530Spatrick     if (s->version != 0) {
129ece8a530Spatrick       error(filename + ": unexpected .MIPS.abiflags version " +
130ece8a530Spatrick             Twine(s->version));
131ece8a530Spatrick       return nullptr;
132ece8a530Spatrick     }
133ece8a530Spatrick 
134ece8a530Spatrick     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
135ece8a530Spatrick     // select the highest number of ISA/Rev/Ext.
136ece8a530Spatrick     flags.isa_level = std::max(flags.isa_level, s->isa_level);
137ece8a530Spatrick     flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
138ece8a530Spatrick     flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
139ece8a530Spatrick     flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
140ece8a530Spatrick     flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
141ece8a530Spatrick     flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
142ece8a530Spatrick     flags.ases |= s->ases;
143ece8a530Spatrick     flags.flags1 |= s->flags1;
144ece8a530Spatrick     flags.flags2 |= s->flags2;
145adae0cfdSpatrick     flags.fp_abi = elf::getMipsFpAbiFlag(flags.fp_abi, s->fp_abi, filename);
146ece8a530Spatrick   };
147ece8a530Spatrick 
148ece8a530Spatrick   if (create)
14905edf1c1Srobert     return std::make_unique<MipsAbiFlagsSection<ELFT>>(flags);
150ece8a530Spatrick   return nullptr;
151ece8a530Spatrick }
152ece8a530Spatrick 
153ece8a530Spatrick // .MIPS.options section.
154ece8a530Spatrick template <class ELFT>
MipsOptionsSection(Elf_Mips_RegInfo reginfo)155ece8a530Spatrick MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo reginfo)
156ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
157ece8a530Spatrick       reginfo(reginfo) {
158ece8a530Spatrick   this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
159ece8a530Spatrick }
160ece8a530Spatrick 
writeTo(uint8_t * buf)161ece8a530Spatrick template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
162ece8a530Spatrick   auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
163ece8a530Spatrick   options->kind = ODK_REGINFO;
164ece8a530Spatrick   options->size = getSize();
165ece8a530Spatrick 
166ece8a530Spatrick   if (!config->relocatable)
167ece8a530Spatrick     reginfo.ri_gp_value = in.mipsGot->getGp();
168ece8a530Spatrick   memcpy(buf + sizeof(Elf_Mips_Options), &reginfo, sizeof(reginfo));
169ece8a530Spatrick }
170ece8a530Spatrick 
171ece8a530Spatrick template <class ELFT>
create()17205edf1c1Srobert std::unique_ptr<MipsOptionsSection<ELFT>> MipsOptionsSection<ELFT>::create() {
173ece8a530Spatrick   // N64 ABI only.
174ece8a530Spatrick   if (!ELFT::Is64Bits)
175ece8a530Spatrick     return nullptr;
176ece8a530Spatrick 
17705edf1c1Srobert   SmallVector<InputSectionBase *, 0> sections;
17805edf1c1Srobert   for (InputSectionBase *sec : ctx.inputSections)
179ece8a530Spatrick     if (sec->type == SHT_MIPS_OPTIONS)
180ece8a530Spatrick       sections.push_back(sec);
181ece8a530Spatrick 
182ece8a530Spatrick   if (sections.empty())
183ece8a530Spatrick     return nullptr;
184ece8a530Spatrick 
185ece8a530Spatrick   Elf_Mips_RegInfo reginfo = {};
186ece8a530Spatrick   for (InputSectionBase *sec : sections) {
187ece8a530Spatrick     sec->markDead();
188ece8a530Spatrick 
189ece8a530Spatrick     std::string filename = toString(sec->file);
19005edf1c1Srobert     ArrayRef<uint8_t> d = sec->content();
191ece8a530Spatrick 
192ece8a530Spatrick     while (!d.empty()) {
193ece8a530Spatrick       if (d.size() < sizeof(Elf_Mips_Options)) {
194ece8a530Spatrick         error(filename + ": invalid size of .MIPS.options section");
195ece8a530Spatrick         break;
196ece8a530Spatrick       }
197ece8a530Spatrick 
198ece8a530Spatrick       auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
199ece8a530Spatrick       if (opt->kind == ODK_REGINFO) {
200ece8a530Spatrick         reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
201ece8a530Spatrick         sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
202ece8a530Spatrick         break;
203ece8a530Spatrick       }
204ece8a530Spatrick 
205ece8a530Spatrick       if (!opt->size)
206ece8a530Spatrick         fatal(filename + ": zero option descriptor size");
207ece8a530Spatrick       d = d.slice(opt->size);
208ece8a530Spatrick     }
209ece8a530Spatrick   };
210ece8a530Spatrick 
21105edf1c1Srobert   return std::make_unique<MipsOptionsSection<ELFT>>(reginfo);
212ece8a530Spatrick }
213ece8a530Spatrick 
214ece8a530Spatrick // MIPS .reginfo section.
215ece8a530Spatrick template <class ELFT>
MipsReginfoSection(Elf_Mips_RegInfo reginfo)216ece8a530Spatrick MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo reginfo)
217ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
218ece8a530Spatrick       reginfo(reginfo) {
219ece8a530Spatrick   this->entsize = sizeof(Elf_Mips_RegInfo);
220ece8a530Spatrick }
221ece8a530Spatrick 
writeTo(uint8_t * buf)222ece8a530Spatrick template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
223ece8a530Spatrick   if (!config->relocatable)
224ece8a530Spatrick     reginfo.ri_gp_value = in.mipsGot->getGp();
225ece8a530Spatrick   memcpy(buf, &reginfo, sizeof(reginfo));
226ece8a530Spatrick }
227ece8a530Spatrick 
228ece8a530Spatrick template <class ELFT>
create()22905edf1c1Srobert std::unique_ptr<MipsReginfoSection<ELFT>> MipsReginfoSection<ELFT>::create() {
230ece8a530Spatrick   // Section should be alive for O32 and N32 ABIs only.
231ece8a530Spatrick   if (ELFT::Is64Bits)
232ece8a530Spatrick     return nullptr;
233ece8a530Spatrick 
23405edf1c1Srobert   SmallVector<InputSectionBase *, 0> sections;
23505edf1c1Srobert   for (InputSectionBase *sec : ctx.inputSections)
236ece8a530Spatrick     if (sec->type == SHT_MIPS_REGINFO)
237ece8a530Spatrick       sections.push_back(sec);
238ece8a530Spatrick 
239ece8a530Spatrick   if (sections.empty())
240ece8a530Spatrick     return nullptr;
241ece8a530Spatrick 
242ece8a530Spatrick   Elf_Mips_RegInfo reginfo = {};
243ece8a530Spatrick   for (InputSectionBase *sec : sections) {
244ece8a530Spatrick     sec->markDead();
245ece8a530Spatrick 
24605edf1c1Srobert     if (sec->content().size() != sizeof(Elf_Mips_RegInfo)) {
247ece8a530Spatrick       error(toString(sec->file) + ": invalid size of .reginfo section");
248ece8a530Spatrick       return nullptr;
249ece8a530Spatrick     }
250ece8a530Spatrick 
25105edf1c1Srobert     auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->content().data());
252ece8a530Spatrick     reginfo.ri_gprmask |= r->ri_gprmask;
253ece8a530Spatrick     sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
254ece8a530Spatrick   };
255ece8a530Spatrick 
25605edf1c1Srobert   return std::make_unique<MipsReginfoSection<ELFT>>(reginfo);
257ece8a530Spatrick }
258ece8a530Spatrick 
createInterpSection()259adae0cfdSpatrick InputSection *elf::createInterpSection() {
260ece8a530Spatrick   // StringSaver guarantees that the returned string ends with '\0'.
26105edf1c1Srobert   StringRef s = saver().save(config->dynamicLinker);
262ece8a530Spatrick   ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
263ece8a530Spatrick 
264ece8a530Spatrick   return make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, contents,
265ece8a530Spatrick                             ".interp");
266ece8a530Spatrick }
267ece8a530Spatrick 
addSyntheticLocal(StringRef name,uint8_t type,uint64_t value,uint64_t size,InputSectionBase & section)268adae0cfdSpatrick Defined *elf::addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
269ece8a530Spatrick                                 uint64_t size, InputSectionBase &section) {
27005edf1c1Srobert   Defined *s = makeDefined(section.file, name, STB_LOCAL, STV_DEFAULT, type,
271ece8a530Spatrick                            value, size, &section);
272ece8a530Spatrick   if (in.symTab)
273ece8a530Spatrick     in.symTab->addSymbol(s);
274ece8a530Spatrick   return s;
275ece8a530Spatrick }
276ece8a530Spatrick 
getHashSize()277ece8a530Spatrick static size_t getHashSize() {
278ece8a530Spatrick   switch (config->buildId) {
279ece8a530Spatrick   case BuildIdKind::Fast:
280ece8a530Spatrick     return 8;
281ece8a530Spatrick   case BuildIdKind::Md5:
282ece8a530Spatrick   case BuildIdKind::Uuid:
283ece8a530Spatrick     return 16;
284ece8a530Spatrick   case BuildIdKind::Sha1:
285ece8a530Spatrick     return 20;
286ece8a530Spatrick   case BuildIdKind::Hexstring:
287ece8a530Spatrick     return config->buildIdVector.size();
288ece8a530Spatrick   default:
289ece8a530Spatrick     llvm_unreachable("unknown BuildIdKind");
290ece8a530Spatrick   }
291ece8a530Spatrick }
292ece8a530Spatrick 
293ece8a530Spatrick // This class represents a linker-synthesized .note.gnu.property section.
294ece8a530Spatrick //
295ece8a530Spatrick // In x86 and AArch64, object files may contain feature flags indicating the
296ece8a530Spatrick // features that they have used. The flags are stored in a .note.gnu.property
297ece8a530Spatrick // section.
298ece8a530Spatrick //
299ece8a530Spatrick // lld reads the sections from input files and merges them by computing AND of
300ece8a530Spatrick // the flags. The result is written as a new .note.gnu.property section.
301ece8a530Spatrick //
302ece8a530Spatrick // If the flag is zero (which indicates that the intersection of the feature
303ece8a530Spatrick // sets is empty, or some input files didn't have .note.gnu.property sections),
304ece8a530Spatrick // we don't create this section.
GnuPropertySection()305ece8a530Spatrick GnuPropertySection::GnuPropertySection()
306ece8a530Spatrick     : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
307ece8a530Spatrick                        config->wordsize, ".note.gnu.property") {}
308ece8a530Spatrick 
writeTo(uint8_t * buf)309ece8a530Spatrick void GnuPropertySection::writeTo(uint8_t *buf) {
310ece8a530Spatrick   uint32_t featureAndType = config->emachine == EM_AARCH64
311ece8a530Spatrick                                 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
312ece8a530Spatrick                                 : GNU_PROPERTY_X86_FEATURE_1_AND;
313ece8a530Spatrick 
314ece8a530Spatrick   write32(buf, 4);                                   // Name size
315ece8a530Spatrick   write32(buf + 4, config->is64 ? 16 : 12);          // Content size
316ece8a530Spatrick   write32(buf + 8, NT_GNU_PROPERTY_TYPE_0);          // Type
317ece8a530Spatrick   memcpy(buf + 12, "GNU", 4);                        // Name string
318ece8a530Spatrick   write32(buf + 16, featureAndType);                 // Feature type
319ece8a530Spatrick   write32(buf + 20, 4);                              // Feature size
320ece8a530Spatrick   write32(buf + 24, config->andFeatures);            // Feature flags
321ece8a530Spatrick   if (config->is64)
322ece8a530Spatrick     write32(buf + 28, 0); // Padding
323ece8a530Spatrick }
324ece8a530Spatrick 
getSize() const325ece8a530Spatrick size_t GnuPropertySection::getSize() const { return config->is64 ? 32 : 28; }
326ece8a530Spatrick 
BuildIdSection()327ece8a530Spatrick BuildIdSection::BuildIdSection()
328ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
329ece8a530Spatrick       hashSize(getHashSize()) {}
330ece8a530Spatrick 
writeTo(uint8_t * buf)331ece8a530Spatrick void BuildIdSection::writeTo(uint8_t *buf) {
332ece8a530Spatrick   write32(buf, 4);                      // Name size
333ece8a530Spatrick   write32(buf + 4, hashSize);           // Content size
334ece8a530Spatrick   write32(buf + 8, NT_GNU_BUILD_ID);    // Type
335ece8a530Spatrick   memcpy(buf + 12, "GNU", 4);           // Name string
336ece8a530Spatrick   hashBuf = buf + 16;
337ece8a530Spatrick }
338ece8a530Spatrick 
writeBuildId(ArrayRef<uint8_t> buf)339ece8a530Spatrick void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
340ece8a530Spatrick   assert(buf.size() == hashSize);
341ece8a530Spatrick   memcpy(hashBuf, buf.data(), hashSize);
342ece8a530Spatrick }
343ece8a530Spatrick 
BssSection(StringRef name,uint64_t size,uint32_t alignment)344ece8a530Spatrick BssSection::BssSection(StringRef name, uint64_t size, uint32_t alignment)
345ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, alignment, name) {
346ece8a530Spatrick   this->bss = true;
347ece8a530Spatrick   this->size = size;
348ece8a530Spatrick }
349ece8a530Spatrick 
EhFrameSection()350ece8a530Spatrick EhFrameSection::EhFrameSection()
351ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
352ece8a530Spatrick 
353ece8a530Spatrick // Search for an existing CIE record or create a new one.
354ece8a530Spatrick // CIE records from input object files are uniquified by their contents
355ece8a530Spatrick // and where their relocations point to.
356ece8a530Spatrick template <class ELFT, class RelTy>
addCie(EhSectionPiece & cie,ArrayRef<RelTy> rels)357ece8a530Spatrick CieRecord *EhFrameSection::addCie(EhSectionPiece &cie, ArrayRef<RelTy> rels) {
358ece8a530Spatrick   Symbol *personality = nullptr;
359ece8a530Spatrick   unsigned firstRelI = cie.firstRelocation;
360ece8a530Spatrick   if (firstRelI != (unsigned)-1)
361ece8a530Spatrick     personality =
362ece8a530Spatrick         &cie.sec->template getFile<ELFT>()->getRelocTargetSym(rels[firstRelI]);
363ece8a530Spatrick 
364ece8a530Spatrick   // Search for an existing CIE by CIE contents/relocation target pair.
365ece8a530Spatrick   CieRecord *&rec = cieMap[{cie.data(), personality}];
366ece8a530Spatrick 
367ece8a530Spatrick   // If not found, create a new one.
368ece8a530Spatrick   if (!rec) {
369ece8a530Spatrick     rec = make<CieRecord>();
370ece8a530Spatrick     rec->cie = &cie;
371ece8a530Spatrick     cieRecords.push_back(rec);
372ece8a530Spatrick   }
373ece8a530Spatrick   return rec;
374ece8a530Spatrick }
375ece8a530Spatrick 
376a0747c9fSpatrick // There is one FDE per function. Returns a non-null pointer to the function
377a0747c9fSpatrick // symbol if the given FDE points to a live function.
378ece8a530Spatrick template <class ELFT, class RelTy>
isFdeLive(EhSectionPiece & fde,ArrayRef<RelTy> rels)379a0747c9fSpatrick Defined *EhFrameSection::isFdeLive(EhSectionPiece &fde, ArrayRef<RelTy> rels) {
380ece8a530Spatrick   auto *sec = cast<EhInputSection>(fde.sec);
381ece8a530Spatrick   unsigned firstRelI = fde.firstRelocation;
382ece8a530Spatrick 
383ece8a530Spatrick   // An FDE should point to some function because FDEs are to describe
384ece8a530Spatrick   // functions. That's however not always the case due to an issue of
385ece8a530Spatrick   // ld.gold with -r. ld.gold may discard only functions and leave their
386ece8a530Spatrick   // corresponding FDEs, which results in creating bad .eh_frame sections.
387ece8a530Spatrick   // To deal with that, we ignore such FDEs.
388ece8a530Spatrick   if (firstRelI == (unsigned)-1)
389a0747c9fSpatrick     return nullptr;
390ece8a530Spatrick 
391ece8a530Spatrick   const RelTy &rel = rels[firstRelI];
392ece8a530Spatrick   Symbol &b = sec->template getFile<ELFT>()->getRelocTargetSym(rel);
393ece8a530Spatrick 
394ece8a530Spatrick   // FDEs for garbage-collected or merged-by-ICF sections, or sections in
395ece8a530Spatrick   // another partition, are dead.
396ece8a530Spatrick   if (auto *d = dyn_cast<Defined>(&b))
39705edf1c1Srobert     if (!d->folded && d->section && d->section->partition == partition)
398a0747c9fSpatrick       return d;
399a0747c9fSpatrick   return nullptr;
400ece8a530Spatrick }
401ece8a530Spatrick 
402ece8a530Spatrick // .eh_frame is a sequence of CIE or FDE records. In general, there
403ece8a530Spatrick // is one CIE record per input object file which is followed by
404ece8a530Spatrick // a list of FDEs. This function searches an existing CIE or create a new
405ece8a530Spatrick // one and associates FDEs to the CIE.
406ece8a530Spatrick template <class ELFT, class RelTy>
addRecords(EhInputSection * sec,ArrayRef<RelTy> rels)407ece8a530Spatrick void EhFrameSection::addRecords(EhInputSection *sec, ArrayRef<RelTy> rels) {
408ece8a530Spatrick   offsetToCie.clear();
40905edf1c1Srobert   for (EhSectionPiece &cie : sec->cies)
41005edf1c1Srobert     offsetToCie[cie.inputOff] = addCie<ELFT>(cie, rels);
41105edf1c1Srobert   for (EhSectionPiece &fde : sec->fdes) {
41205edf1c1Srobert     uint32_t id = endian::read32<ELFT::TargetEndianness>(fde.data().data() + 4);
41305edf1c1Srobert     CieRecord *rec = offsetToCie[fde.inputOff + 4 - id];
414ece8a530Spatrick     if (!rec)
415ece8a530Spatrick       fatal(toString(sec) + ": invalid CIE reference");
416ece8a530Spatrick 
41705edf1c1Srobert     if (!isFdeLive<ELFT>(fde, rels))
418ece8a530Spatrick       continue;
41905edf1c1Srobert     rec->fdes.push_back(&fde);
420ece8a530Spatrick     numFdes++;
421ece8a530Spatrick   }
422ece8a530Spatrick }
423ece8a530Spatrick 
424ece8a530Spatrick template <class ELFT>
addSectionAux(EhInputSection * sec)425ece8a530Spatrick void EhFrameSection::addSectionAux(EhInputSection *sec) {
426ece8a530Spatrick   if (!sec->isLive())
427ece8a530Spatrick     return;
42805edf1c1Srobert   const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
42905edf1c1Srobert   if (rels.areRelocsRel())
43005edf1c1Srobert     addRecords<ELFT>(sec, rels.rels);
431ece8a530Spatrick   else
43205edf1c1Srobert     addRecords<ELFT>(sec, rels.relas);
433ece8a530Spatrick }
434ece8a530Spatrick 
435a0747c9fSpatrick // Used by ICF<ELFT>::handleLSDA(). This function is very similar to
436a0747c9fSpatrick // EhFrameSection::addRecords().
437a0747c9fSpatrick template <class ELFT, class RelTy>
iterateFDEWithLSDAAux(EhInputSection & sec,ArrayRef<RelTy> rels,DenseSet<size_t> & ciesWithLSDA,llvm::function_ref<void (InputSection &)> fn)438a0747c9fSpatrick void EhFrameSection::iterateFDEWithLSDAAux(
439a0747c9fSpatrick     EhInputSection &sec, ArrayRef<RelTy> rels, DenseSet<size_t> &ciesWithLSDA,
440a0747c9fSpatrick     llvm::function_ref<void(InputSection &)> fn) {
44105edf1c1Srobert   for (EhSectionPiece &cie : sec.cies)
44205edf1c1Srobert     if (hasLSDA(cie))
44305edf1c1Srobert       ciesWithLSDA.insert(cie.inputOff);
44405edf1c1Srobert   for (EhSectionPiece &fde : sec.fdes) {
44505edf1c1Srobert     uint32_t id = endian::read32<ELFT::TargetEndianness>(fde.data().data() + 4);
44605edf1c1Srobert     if (!ciesWithLSDA.contains(fde.inputOff + 4 - id))
447a0747c9fSpatrick       continue;
448a0747c9fSpatrick 
449a0747c9fSpatrick     // The CIE has a LSDA argument. Call fn with d's section.
45005edf1c1Srobert     if (Defined *d = isFdeLive<ELFT>(fde, rels))
451a0747c9fSpatrick       if (auto *s = dyn_cast_or_null<InputSection>(d->section))
452a0747c9fSpatrick         fn(*s);
453a0747c9fSpatrick   }
454a0747c9fSpatrick }
455a0747c9fSpatrick 
456a0747c9fSpatrick template <class ELFT>
iterateFDEWithLSDA(llvm::function_ref<void (InputSection &)> fn)457a0747c9fSpatrick void EhFrameSection::iterateFDEWithLSDA(
458a0747c9fSpatrick     llvm::function_ref<void(InputSection &)> fn) {
459a0747c9fSpatrick   DenseSet<size_t> ciesWithLSDA;
460a0747c9fSpatrick   for (EhInputSection *sec : sections) {
461a0747c9fSpatrick     ciesWithLSDA.clear();
46205edf1c1Srobert     const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
46305edf1c1Srobert     if (rels.areRelocsRel())
46405edf1c1Srobert       iterateFDEWithLSDAAux<ELFT>(*sec, rels.rels, ciesWithLSDA, fn);
465a0747c9fSpatrick     else
46605edf1c1Srobert       iterateFDEWithLSDAAux<ELFT>(*sec, rels.relas, ciesWithLSDA, fn);
467a0747c9fSpatrick   }
468a0747c9fSpatrick }
469a0747c9fSpatrick 
writeCieFde(uint8_t * buf,ArrayRef<uint8_t> d)470ece8a530Spatrick static void writeCieFde(uint8_t *buf, ArrayRef<uint8_t> d) {
471ece8a530Spatrick   memcpy(buf, d.data(), d.size());
472ece8a530Spatrick   // Fix the size field. -4 since size does not include the size field itself.
47305edf1c1Srobert   write32(buf, d.size() - 4);
474ece8a530Spatrick }
475ece8a530Spatrick 
finalizeContents()476ece8a530Spatrick void EhFrameSection::finalizeContents() {
477ece8a530Spatrick   assert(!this->size); // Not finalized.
478ece8a530Spatrick 
479ece8a530Spatrick   switch (config->ekind) {
480ece8a530Spatrick   case ELFNoneKind:
481ece8a530Spatrick     llvm_unreachable("invalid ekind");
482ece8a530Spatrick   case ELF32LEKind:
483ece8a530Spatrick     for (EhInputSection *sec : sections)
484ece8a530Spatrick       addSectionAux<ELF32LE>(sec);
485ece8a530Spatrick     break;
486ece8a530Spatrick   case ELF32BEKind:
487ece8a530Spatrick     for (EhInputSection *sec : sections)
488ece8a530Spatrick       addSectionAux<ELF32BE>(sec);
489ece8a530Spatrick     break;
490ece8a530Spatrick   case ELF64LEKind:
491ece8a530Spatrick     for (EhInputSection *sec : sections)
492ece8a530Spatrick       addSectionAux<ELF64LE>(sec);
493ece8a530Spatrick     break;
494ece8a530Spatrick   case ELF64BEKind:
495ece8a530Spatrick     for (EhInputSection *sec : sections)
496ece8a530Spatrick       addSectionAux<ELF64BE>(sec);
497ece8a530Spatrick     break;
498ece8a530Spatrick   }
499ece8a530Spatrick 
500ece8a530Spatrick   size_t off = 0;
501ece8a530Spatrick   for (CieRecord *rec : cieRecords) {
502ece8a530Spatrick     rec->cie->outputOff = off;
50305edf1c1Srobert     off += rec->cie->size;
504ece8a530Spatrick 
505ece8a530Spatrick     for (EhSectionPiece *fde : rec->fdes) {
506ece8a530Spatrick       fde->outputOff = off;
50705edf1c1Srobert       off += fde->size;
508ece8a530Spatrick     }
509ece8a530Spatrick   }
510ece8a530Spatrick 
511ece8a530Spatrick   // The LSB standard does not allow a .eh_frame section with zero
512ece8a530Spatrick   // Call Frame Information records. glibc unwind-dw2-fde.c
513ece8a530Spatrick   // classify_object_over_fdes expects there is a CIE record length 0 as a
514ece8a530Spatrick   // terminator. Thus we add one unconditionally.
515ece8a530Spatrick   off += 4;
516ece8a530Spatrick 
517ece8a530Spatrick   this->size = off;
518ece8a530Spatrick }
519ece8a530Spatrick 
520ece8a530Spatrick // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
521ece8a530Spatrick // to get an FDE from an address to which FDE is applied. This function
522ece8a530Spatrick // returns a list of such pairs.
getFdeData() const52305edf1c1Srobert SmallVector<EhFrameSection::FdeData, 0> EhFrameSection::getFdeData() const {
524ece8a530Spatrick   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
52505edf1c1Srobert   SmallVector<FdeData, 0> ret;
526ece8a530Spatrick 
527ece8a530Spatrick   uint64_t va = getPartition().ehFrameHdr->getVA();
528ece8a530Spatrick   for (CieRecord *rec : cieRecords) {
529ece8a530Spatrick     uint8_t enc = getFdeEncoding(rec->cie);
530ece8a530Spatrick     for (EhSectionPiece *fde : rec->fdes) {
531ece8a530Spatrick       uint64_t pc = getFdePc(buf, fde->outputOff, enc);
532ece8a530Spatrick       uint64_t fdeVA = getParent()->addr + fde->outputOff;
533ece8a530Spatrick       if (!isInt<32>(pc - va))
534ece8a530Spatrick         fatal(toString(fde->sec) + ": PC offset is too large: 0x" +
535ece8a530Spatrick               Twine::utohexstr(pc - va));
536ece8a530Spatrick       ret.push_back({uint32_t(pc - va), uint32_t(fdeVA - va)});
537ece8a530Spatrick     }
538ece8a530Spatrick   }
539ece8a530Spatrick 
540ece8a530Spatrick   // Sort the FDE list by their PC and uniqueify. Usually there is only
541ece8a530Spatrick   // one FDE for a PC (i.e. function), but if ICF merges two functions
542ece8a530Spatrick   // into one, there can be more than one FDEs pointing to the address.
543ece8a530Spatrick   auto less = [](const FdeData &a, const FdeData &b) {
544ece8a530Spatrick     return a.pcRel < b.pcRel;
545ece8a530Spatrick   };
546ece8a530Spatrick   llvm::stable_sort(ret, less);
547ece8a530Spatrick   auto eq = [](const FdeData &a, const FdeData &b) {
548ece8a530Spatrick     return a.pcRel == b.pcRel;
549ece8a530Spatrick   };
550ece8a530Spatrick   ret.erase(std::unique(ret.begin(), ret.end(), eq), ret.end());
551ece8a530Spatrick 
552ece8a530Spatrick   return ret;
553ece8a530Spatrick }
554ece8a530Spatrick 
readFdeAddr(uint8_t * buf,int size)555ece8a530Spatrick static uint64_t readFdeAddr(uint8_t *buf, int size) {
556ece8a530Spatrick   switch (size) {
557ece8a530Spatrick   case DW_EH_PE_udata2:
558ece8a530Spatrick     return read16(buf);
559ece8a530Spatrick   case DW_EH_PE_sdata2:
560ece8a530Spatrick     return (int16_t)read16(buf);
561ece8a530Spatrick   case DW_EH_PE_udata4:
562ece8a530Spatrick     return read32(buf);
563ece8a530Spatrick   case DW_EH_PE_sdata4:
564ece8a530Spatrick     return (int32_t)read32(buf);
565ece8a530Spatrick   case DW_EH_PE_udata8:
566ece8a530Spatrick   case DW_EH_PE_sdata8:
567ece8a530Spatrick     return read64(buf);
568ece8a530Spatrick   case DW_EH_PE_absptr:
569ece8a530Spatrick     return readUint(buf);
570ece8a530Spatrick   }
571ece8a530Spatrick   fatal("unknown FDE size encoding");
572ece8a530Spatrick }
573ece8a530Spatrick 
574ece8a530Spatrick // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
575ece8a530Spatrick // We need it to create .eh_frame_hdr section.
getFdePc(uint8_t * buf,size_t fdeOff,uint8_t enc) const576ece8a530Spatrick uint64_t EhFrameSection::getFdePc(uint8_t *buf, size_t fdeOff,
577ece8a530Spatrick                                   uint8_t enc) const {
578ece8a530Spatrick   // The starting address to which this FDE applies is
579ece8a530Spatrick   // stored at FDE + 8 byte.
580ece8a530Spatrick   size_t off = fdeOff + 8;
581ece8a530Spatrick   uint64_t addr = readFdeAddr(buf + off, enc & 0xf);
582ece8a530Spatrick   if ((enc & 0x70) == DW_EH_PE_absptr)
583ece8a530Spatrick     return addr;
584ece8a530Spatrick   if ((enc & 0x70) == DW_EH_PE_pcrel)
585ece8a530Spatrick     return addr + getParent()->addr + off;
586ece8a530Spatrick   fatal("unknown FDE size relative encoding");
587ece8a530Spatrick }
588ece8a530Spatrick 
writeTo(uint8_t * buf)589ece8a530Spatrick void EhFrameSection::writeTo(uint8_t *buf) {
590ece8a530Spatrick   // Write CIE and FDE records.
591ece8a530Spatrick   for (CieRecord *rec : cieRecords) {
592ece8a530Spatrick     size_t cieOffset = rec->cie->outputOff;
593ece8a530Spatrick     writeCieFde(buf + cieOffset, rec->cie->data());
594ece8a530Spatrick 
595ece8a530Spatrick     for (EhSectionPiece *fde : rec->fdes) {
596ece8a530Spatrick       size_t off = fde->outputOff;
597ece8a530Spatrick       writeCieFde(buf + off, fde->data());
598ece8a530Spatrick 
599ece8a530Spatrick       // FDE's second word should have the offset to an associated CIE.
600ece8a530Spatrick       // Write it.
601ece8a530Spatrick       write32(buf + off + 4, off + 4 - cieOffset);
602ece8a530Spatrick     }
603ece8a530Spatrick   }
604ece8a530Spatrick 
605ece8a530Spatrick   // Apply relocations. .eh_frame section contents are not contiguous
606ece8a530Spatrick   // in the output buffer, but relocateAlloc() still works because
607ece8a530Spatrick   // getOffset() takes care of discontiguous section pieces.
608ece8a530Spatrick   for (EhInputSection *s : sections)
60905edf1c1Srobert     target->relocateAlloc(*s, buf);
610ece8a530Spatrick 
611ece8a530Spatrick   if (getPartition().ehFrameHdr && getPartition().ehFrameHdr->getParent())
612ece8a530Spatrick     getPartition().ehFrameHdr->write();
613ece8a530Spatrick }
614ece8a530Spatrick 
GotSection()615ece8a530Spatrick GotSection::GotSection()
616a0747c9fSpatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
617a0747c9fSpatrick                        target->gotEntrySize, ".got") {
618a0747c9fSpatrick   numEntries = target->gotHeaderEntriesNum;
619ece8a530Spatrick }
620ece8a530Spatrick 
addConstant(const Relocation & r)62105edf1c1Srobert void GotSection::addConstant(const Relocation &r) { relocations.push_back(r); }
addEntry(Symbol & sym)622ece8a530Spatrick void GotSection::addEntry(Symbol &sym) {
62305edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1);
62405edf1c1Srobert   symAux.back().gotIdx = numEntries++;
62505edf1c1Srobert }
62605edf1c1Srobert 
addTlsDescEntry(Symbol & sym)62705edf1c1Srobert bool GotSection::addTlsDescEntry(Symbol &sym) {
62805edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1);
62905edf1c1Srobert   symAux.back().tlsDescIdx = numEntries;
63005edf1c1Srobert   numEntries += 2;
63105edf1c1Srobert   return true;
632ece8a530Spatrick }
633ece8a530Spatrick 
addDynTlsEntry(Symbol & sym)634ece8a530Spatrick bool GotSection::addDynTlsEntry(Symbol &sym) {
63505edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1);
63605edf1c1Srobert   symAux.back().tlsGdIdx = numEntries;
637ece8a530Spatrick   // Global Dynamic TLS entries take two GOT slots.
638ece8a530Spatrick   numEntries += 2;
639ece8a530Spatrick   return true;
640ece8a530Spatrick }
641ece8a530Spatrick 
642ece8a530Spatrick // Reserves TLS entries for a TLS module ID and a TLS block offset.
643ece8a530Spatrick // In total it takes two GOT slots.
addTlsIndex()644ece8a530Spatrick bool GotSection::addTlsIndex() {
645ece8a530Spatrick   if (tlsIndexOff != uint32_t(-1))
646ece8a530Spatrick     return false;
647ece8a530Spatrick   tlsIndexOff = numEntries * config->wordsize;
648ece8a530Spatrick   numEntries += 2;
649ece8a530Spatrick   return true;
650ece8a530Spatrick }
651ece8a530Spatrick 
getTlsDescOffset(const Symbol & sym) const65205edf1c1Srobert uint32_t GotSection::getTlsDescOffset(const Symbol &sym) const {
65305edf1c1Srobert   return sym.getTlsDescIdx() * config->wordsize;
65405edf1c1Srobert }
65505edf1c1Srobert 
getTlsDescAddr(const Symbol & sym) const65605edf1c1Srobert uint64_t GotSection::getTlsDescAddr(const Symbol &sym) const {
65705edf1c1Srobert   return getVA() + getTlsDescOffset(sym);
65805edf1c1Srobert }
65905edf1c1Srobert 
getGlobalDynAddr(const Symbol & b) const660ece8a530Spatrick uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
66105edf1c1Srobert   return this->getVA() + b.getTlsGdIdx() * config->wordsize;
662ece8a530Spatrick }
663ece8a530Spatrick 
getGlobalDynOffset(const Symbol & b) const664ece8a530Spatrick uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
66505edf1c1Srobert   return b.getTlsGdIdx() * config->wordsize;
666ece8a530Spatrick }
667ece8a530Spatrick 
finalizeContents()668ece8a530Spatrick void GotSection::finalizeContents() {
669a0747c9fSpatrick   if (config->emachine == EM_PPC64 &&
670a0747c9fSpatrick       numEntries <= target->gotHeaderEntriesNum && !ElfSym::globalOffsetTable)
671a0747c9fSpatrick     size = 0;
672a0747c9fSpatrick   else
673ece8a530Spatrick     size = numEntries * config->wordsize;
674ece8a530Spatrick }
675ece8a530Spatrick 
isNeeded() const676ece8a530Spatrick bool GotSection::isNeeded() const {
677a0747c9fSpatrick   // Needed if the GOT symbol is used or the number of entries is more than just
678a0747c9fSpatrick   // the header. A GOT with just the header may not be needed.
679a0747c9fSpatrick   return hasGotOffRel || numEntries > target->gotHeaderEntriesNum;
680ece8a530Spatrick }
681ece8a530Spatrick 
writeTo(uint8_t * buf)682ece8a530Spatrick void GotSection::writeTo(uint8_t *buf) {
68305edf1c1Srobert   // On PPC64 .got may be needed but empty. Skip the write.
68405edf1c1Srobert   if (size == 0)
68505edf1c1Srobert     return;
686ece8a530Spatrick   target->writeGotHeader(buf);
68705edf1c1Srobert   target->relocateAlloc(*this, buf);
688ece8a530Spatrick }
689ece8a530Spatrick 
getMipsPageAddr(uint64_t addr)690ece8a530Spatrick static uint64_t getMipsPageAddr(uint64_t addr) {
691ece8a530Spatrick   return (addr + 0x8000) & ~0xffff;
692ece8a530Spatrick }
693ece8a530Spatrick 
getMipsPageCount(uint64_t size)694ece8a530Spatrick static uint64_t getMipsPageCount(uint64_t size) {
695ece8a530Spatrick   return (size + 0xfffe) / 0xffff + 1;
696ece8a530Spatrick }
697ece8a530Spatrick 
MipsGotSection()698ece8a530Spatrick MipsGotSection::MipsGotSection()
699ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
700ece8a530Spatrick                        ".got") {}
701ece8a530Spatrick 
addEntry(InputFile & file,Symbol & sym,int64_t addend,RelExpr expr)702ece8a530Spatrick void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
703ece8a530Spatrick                               RelExpr expr) {
704ece8a530Spatrick   FileGot &g = getGot(file);
705ece8a530Spatrick   if (expr == R_MIPS_GOT_LOCAL_PAGE) {
706ece8a530Spatrick     if (const OutputSection *os = sym.getOutputSection())
707ece8a530Spatrick       g.pagesMap.insert({os, {}});
708ece8a530Spatrick     else
709ece8a530Spatrick       g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
710ece8a530Spatrick   } else if (sym.isTls())
711ece8a530Spatrick     g.tls.insert({&sym, 0});
712ece8a530Spatrick   else if (sym.isPreemptible && expr == R_ABS)
713ece8a530Spatrick     g.relocs.insert({&sym, 0});
714ece8a530Spatrick   else if (sym.isPreemptible)
715ece8a530Spatrick     g.global.insert({&sym, 0});
716ece8a530Spatrick   else if (expr == R_MIPS_GOT_OFF32)
717ece8a530Spatrick     g.local32.insert({{&sym, addend}, 0});
718ece8a530Spatrick   else
719ece8a530Spatrick     g.local16.insert({{&sym, addend}, 0});
720ece8a530Spatrick }
721ece8a530Spatrick 
addDynTlsEntry(InputFile & file,Symbol & sym)722ece8a530Spatrick void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
723ece8a530Spatrick   getGot(file).dynTlsSymbols.insert({&sym, 0});
724ece8a530Spatrick }
725ece8a530Spatrick 
addTlsIndex(InputFile & file)726ece8a530Spatrick void MipsGotSection::addTlsIndex(InputFile &file) {
727ece8a530Spatrick   getGot(file).dynTlsSymbols.insert({nullptr, 0});
728ece8a530Spatrick }
729ece8a530Spatrick 
getEntriesNum() const730ece8a530Spatrick size_t MipsGotSection::FileGot::getEntriesNum() const {
731ece8a530Spatrick   return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
732ece8a530Spatrick          tls.size() + dynTlsSymbols.size() * 2;
733ece8a530Spatrick }
734ece8a530Spatrick 
getPageEntriesNum() const735ece8a530Spatrick size_t MipsGotSection::FileGot::getPageEntriesNum() const {
736ece8a530Spatrick   size_t num = 0;
737ece8a530Spatrick   for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
738ece8a530Spatrick     num += p.second.count;
739ece8a530Spatrick   return num;
740ece8a530Spatrick }
741ece8a530Spatrick 
getIndexedEntriesNum() const742ece8a530Spatrick size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
743ece8a530Spatrick   size_t count = getPageEntriesNum() + local16.size() + global.size();
744ece8a530Spatrick   // If there are relocation-only entries in the GOT, TLS entries
745ece8a530Spatrick   // are allocated after them. TLS entries should be addressable
746ece8a530Spatrick   // by 16-bit index so count both reloc-only and TLS entries.
747ece8a530Spatrick   if (!tls.empty() || !dynTlsSymbols.empty())
748ece8a530Spatrick     count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
749ece8a530Spatrick   return count;
750ece8a530Spatrick }
751ece8a530Spatrick 
getGot(InputFile & f)752ece8a530Spatrick MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
75305edf1c1Srobert   if (f.mipsGotIndex == uint32_t(-1)) {
754ece8a530Spatrick     gots.emplace_back();
755ece8a530Spatrick     gots.back().file = &f;
756ece8a530Spatrick     f.mipsGotIndex = gots.size() - 1;
757ece8a530Spatrick   }
75805edf1c1Srobert   return gots[f.mipsGotIndex];
759ece8a530Spatrick }
760ece8a530Spatrick 
getPageEntryOffset(const InputFile * f,const Symbol & sym,int64_t addend) const761ece8a530Spatrick uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
762ece8a530Spatrick                                             const Symbol &sym,
763ece8a530Spatrick                                             int64_t addend) const {
76405edf1c1Srobert   const FileGot &g = gots[f->mipsGotIndex];
765ece8a530Spatrick   uint64_t index = 0;
766ece8a530Spatrick   if (const OutputSection *outSec = sym.getOutputSection()) {
767ece8a530Spatrick     uint64_t secAddr = getMipsPageAddr(outSec->addr);
768ece8a530Spatrick     uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
769ece8a530Spatrick     index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
770ece8a530Spatrick   } else {
771ece8a530Spatrick     index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
772ece8a530Spatrick   }
773ece8a530Spatrick   return index * config->wordsize;
774ece8a530Spatrick }
775ece8a530Spatrick 
getSymEntryOffset(const InputFile * f,const Symbol & s,int64_t addend) const776ece8a530Spatrick uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
777ece8a530Spatrick                                            int64_t addend) const {
77805edf1c1Srobert   const FileGot &g = gots[f->mipsGotIndex];
779ece8a530Spatrick   Symbol *sym = const_cast<Symbol *>(&s);
780ece8a530Spatrick   if (sym->isTls())
781ece8a530Spatrick     return g.tls.lookup(sym) * config->wordsize;
782ece8a530Spatrick   if (sym->isPreemptible)
783ece8a530Spatrick     return g.global.lookup(sym) * config->wordsize;
784ece8a530Spatrick   return g.local16.lookup({sym, addend}) * config->wordsize;
785ece8a530Spatrick }
786ece8a530Spatrick 
getTlsIndexOffset(const InputFile * f) const787ece8a530Spatrick uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
78805edf1c1Srobert   const FileGot &g = gots[f->mipsGotIndex];
789ece8a530Spatrick   return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
790ece8a530Spatrick }
791ece8a530Spatrick 
getGlobalDynOffset(const InputFile * f,const Symbol & s) const792ece8a530Spatrick uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
793ece8a530Spatrick                                             const Symbol &s) const {
79405edf1c1Srobert   const FileGot &g = gots[f->mipsGotIndex];
795ece8a530Spatrick   Symbol *sym = const_cast<Symbol *>(&s);
796ece8a530Spatrick   return g.dynTlsSymbols.lookup(sym) * config->wordsize;
797ece8a530Spatrick }
798ece8a530Spatrick 
getFirstGlobalEntry() const799ece8a530Spatrick const Symbol *MipsGotSection::getFirstGlobalEntry() const {
800ece8a530Spatrick   if (gots.empty())
801ece8a530Spatrick     return nullptr;
802ece8a530Spatrick   const FileGot &primGot = gots.front();
803ece8a530Spatrick   if (!primGot.global.empty())
804ece8a530Spatrick     return primGot.global.front().first;
805ece8a530Spatrick   if (!primGot.relocs.empty())
806ece8a530Spatrick     return primGot.relocs.front().first;
807ece8a530Spatrick   return nullptr;
808ece8a530Spatrick }
809ece8a530Spatrick 
getLocalEntriesNum() const810ece8a530Spatrick unsigned MipsGotSection::getLocalEntriesNum() const {
811ece8a530Spatrick   if (gots.empty())
812ece8a530Spatrick     return headerEntriesNum;
813ece8a530Spatrick   return headerEntriesNum + gots.front().getPageEntriesNum() +
814ece8a530Spatrick          gots.front().local16.size();
815ece8a530Spatrick }
816ece8a530Spatrick 
tryMergeGots(FileGot & dst,FileGot & src,bool isPrimary)817ece8a530Spatrick bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
818ece8a530Spatrick   FileGot tmp = dst;
819ece8a530Spatrick   set_union(tmp.pagesMap, src.pagesMap);
820ece8a530Spatrick   set_union(tmp.local16, src.local16);
821ece8a530Spatrick   set_union(tmp.global, src.global);
822ece8a530Spatrick   set_union(tmp.relocs, src.relocs);
823ece8a530Spatrick   set_union(tmp.tls, src.tls);
824ece8a530Spatrick   set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
825ece8a530Spatrick 
826ece8a530Spatrick   size_t count = isPrimary ? headerEntriesNum : 0;
827ece8a530Spatrick   count += tmp.getIndexedEntriesNum();
828ece8a530Spatrick 
829ece8a530Spatrick   if (count * config->wordsize > config->mipsGotSize)
830ece8a530Spatrick     return false;
831ece8a530Spatrick 
832ece8a530Spatrick   std::swap(tmp, dst);
833ece8a530Spatrick   return true;
834ece8a530Spatrick }
835ece8a530Spatrick 
finalizeContents()836ece8a530Spatrick void MipsGotSection::finalizeContents() { updateAllocSize(); }
837ece8a530Spatrick 
updateAllocSize()838ece8a530Spatrick bool MipsGotSection::updateAllocSize() {
839ece8a530Spatrick   size = headerEntriesNum * config->wordsize;
840ece8a530Spatrick   for (const FileGot &g : gots)
841ece8a530Spatrick     size += g.getEntriesNum() * config->wordsize;
842ece8a530Spatrick   return false;
843ece8a530Spatrick }
844ece8a530Spatrick 
build()845ece8a530Spatrick void MipsGotSection::build() {
846ece8a530Spatrick   if (gots.empty())
847ece8a530Spatrick     return;
848ece8a530Spatrick 
849ece8a530Spatrick   std::vector<FileGot> mergedGots(1);
850ece8a530Spatrick 
851ece8a530Spatrick   // For each GOT move non-preemptible symbols from the `Global`
852ece8a530Spatrick   // to `Local16` list. Preemptible symbol might become non-preemptible
853ece8a530Spatrick   // one if, for example, it gets a related copy relocation.
854ece8a530Spatrick   for (FileGot &got : gots) {
855ece8a530Spatrick     for (auto &p: got.global)
856ece8a530Spatrick       if (!p.first->isPreemptible)
857ece8a530Spatrick         got.local16.insert({{p.first, 0}, 0});
858ece8a530Spatrick     got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
859ece8a530Spatrick       return !p.first->isPreemptible;
860ece8a530Spatrick     });
861ece8a530Spatrick   }
862ece8a530Spatrick 
863ece8a530Spatrick   // For each GOT remove "reloc-only" entry if there is "global"
864ece8a530Spatrick   // entry for the same symbol. And add local entries which indexed
865ece8a530Spatrick   // using 32-bit value at the end of 16-bit entries.
866ece8a530Spatrick   for (FileGot &got : gots) {
867ece8a530Spatrick     got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
868ece8a530Spatrick       return got.global.count(p.first);
869ece8a530Spatrick     });
870ece8a530Spatrick     set_union(got.local16, got.local32);
871ece8a530Spatrick     got.local32.clear();
872ece8a530Spatrick   }
873ece8a530Spatrick 
874ece8a530Spatrick   // Evaluate number of "reloc-only" entries in the resulting GOT.
875ece8a530Spatrick   // To do that put all unique "reloc-only" and "global" entries
876ece8a530Spatrick   // from all GOTs to the future primary GOT.
877ece8a530Spatrick   FileGot *primGot = &mergedGots.front();
878ece8a530Spatrick   for (FileGot &got : gots) {
879ece8a530Spatrick     set_union(primGot->relocs, got.global);
880ece8a530Spatrick     set_union(primGot->relocs, got.relocs);
881ece8a530Spatrick     got.relocs.clear();
882ece8a530Spatrick   }
883ece8a530Spatrick 
884ece8a530Spatrick   // Evaluate number of "page" entries in each GOT.
885ece8a530Spatrick   for (FileGot &got : gots) {
886ece8a530Spatrick     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
887ece8a530Spatrick          got.pagesMap) {
888ece8a530Spatrick       const OutputSection *os = p.first;
889ece8a530Spatrick       uint64_t secSize = 0;
89005edf1c1Srobert       for (SectionCommand *cmd : os->commands) {
891ece8a530Spatrick         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
892ece8a530Spatrick           for (InputSection *isec : isd->sections) {
89305edf1c1Srobert             uint64_t off = alignToPowerOf2(secSize, isec->addralign);
894ece8a530Spatrick             secSize = off + isec->getSize();
895ece8a530Spatrick           }
896ece8a530Spatrick       }
897ece8a530Spatrick       p.second.count = getMipsPageCount(secSize);
898ece8a530Spatrick     }
899ece8a530Spatrick   }
900ece8a530Spatrick 
901ece8a530Spatrick   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
902ece8a530Spatrick   // maximum GOT size. At first, try to fill the primary GOT because
903ece8a530Spatrick   // the primary GOT can be accessed in the most effective way. If it
904ece8a530Spatrick   // is not possible, try to fill the last GOT in the list, and finally
905ece8a530Spatrick   // create a new GOT if both attempts failed.
906ece8a530Spatrick   for (FileGot &srcGot : gots) {
907ece8a530Spatrick     InputFile *file = srcGot.file;
908ece8a530Spatrick     if (tryMergeGots(mergedGots.front(), srcGot, true)) {
909ece8a530Spatrick       file->mipsGotIndex = 0;
910ece8a530Spatrick     } else {
911ece8a530Spatrick       // If this is the first time we failed to merge with the primary GOT,
912ece8a530Spatrick       // MergedGots.back() will also be the primary GOT. We must make sure not
913ece8a530Spatrick       // to try to merge again with isPrimary=false, as otherwise, if the
914ece8a530Spatrick       // inputs are just right, we could allow the primary GOT to become 1 or 2
915ece8a530Spatrick       // words bigger due to ignoring the header size.
916ece8a530Spatrick       if (mergedGots.size() == 1 ||
917ece8a530Spatrick           !tryMergeGots(mergedGots.back(), srcGot, false)) {
918ece8a530Spatrick         mergedGots.emplace_back();
919ece8a530Spatrick         std::swap(mergedGots.back(), srcGot);
920ece8a530Spatrick       }
921ece8a530Spatrick       file->mipsGotIndex = mergedGots.size() - 1;
922ece8a530Spatrick     }
923ece8a530Spatrick   }
924ece8a530Spatrick   std::swap(gots, mergedGots);
925ece8a530Spatrick 
926ece8a530Spatrick   // Reduce number of "reloc-only" entries in the primary GOT
927ece8a530Spatrick   // by subtracting "global" entries in the primary GOT.
928ece8a530Spatrick   primGot = &gots.front();
929ece8a530Spatrick   primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
930ece8a530Spatrick     return primGot->global.count(p.first);
931ece8a530Spatrick   });
932ece8a530Spatrick 
933ece8a530Spatrick   // Calculate indexes for each GOT entry.
934ece8a530Spatrick   size_t index = headerEntriesNum;
935ece8a530Spatrick   for (FileGot &got : gots) {
936ece8a530Spatrick     got.startIndex = &got == primGot ? 0 : index;
937ece8a530Spatrick     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
938ece8a530Spatrick          got.pagesMap) {
939ece8a530Spatrick       // For each output section referenced by GOT page relocations calculate
940ece8a530Spatrick       // and save into pagesMap an upper bound of MIPS GOT entries required
941ece8a530Spatrick       // to store page addresses of local symbols. We assume the worst case -
942ece8a530Spatrick       // each 64kb page of the output section has at least one GOT relocation
943ece8a530Spatrick       // against it. And take in account the case when the section intersects
944ece8a530Spatrick       // page boundaries.
945ece8a530Spatrick       p.second.firstIndex = index;
946ece8a530Spatrick       index += p.second.count;
947ece8a530Spatrick     }
948ece8a530Spatrick     for (auto &p: got.local16)
949ece8a530Spatrick       p.second = index++;
950ece8a530Spatrick     for (auto &p: got.global)
951ece8a530Spatrick       p.second = index++;
952ece8a530Spatrick     for (auto &p: got.relocs)
953ece8a530Spatrick       p.second = index++;
954ece8a530Spatrick     for (auto &p: got.tls)
955ece8a530Spatrick       p.second = index++;
956ece8a530Spatrick     for (auto &p: got.dynTlsSymbols) {
957ece8a530Spatrick       p.second = index;
958ece8a530Spatrick       index += 2;
959ece8a530Spatrick     }
960ece8a530Spatrick   }
961ece8a530Spatrick 
96205edf1c1Srobert   // Update SymbolAux::gotIdx field to use this
963ece8a530Spatrick   // value later in the `sortMipsSymbols` function.
96405edf1c1Srobert   for (auto &p : primGot->global) {
96505edf1c1Srobert     if (p.first->auxIdx == 0)
96605edf1c1Srobert       p.first->allocateAux();
96705edf1c1Srobert     symAux.back().gotIdx = p.second;
96805edf1c1Srobert   }
96905edf1c1Srobert   for (auto &p : primGot->relocs) {
97005edf1c1Srobert     if (p.first->auxIdx == 0)
97105edf1c1Srobert       p.first->allocateAux();
97205edf1c1Srobert     symAux.back().gotIdx = p.second;
97305edf1c1Srobert   }
974ece8a530Spatrick 
975ece8a530Spatrick   // Create dynamic relocations.
976ece8a530Spatrick   for (FileGot &got : gots) {
977ece8a530Spatrick     // Create dynamic relocations for TLS entries.
978ece8a530Spatrick     for (std::pair<Symbol *, size_t> &p : got.tls) {
979ece8a530Spatrick       Symbol *s = p.first;
980ece8a530Spatrick       uint64_t offset = p.second * config->wordsize;
981a0747c9fSpatrick       // When building a shared library we still need a dynamic relocation
982a0747c9fSpatrick       // for the TP-relative offset as we don't know how much other data will
983a0747c9fSpatrick       // be allocated before us in the static TLS block.
984a0747c9fSpatrick       if (s->isPreemptible || config->shared)
985a0747c9fSpatrick         mainPart->relaDyn->addReloc({target->tlsGotRel, this, offset,
986a0747c9fSpatrick                                      DynamicReloc::AgainstSymbolWithTargetVA,
987a0747c9fSpatrick                                      *s, 0, R_ABS});
988ece8a530Spatrick     }
989ece8a530Spatrick     for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
990ece8a530Spatrick       Symbol *s = p.first;
991ece8a530Spatrick       uint64_t offset = p.second * config->wordsize;
992ece8a530Spatrick       if (s == nullptr) {
993a0747c9fSpatrick         if (!config->shared)
994ece8a530Spatrick           continue;
995a0747c9fSpatrick         mainPart->relaDyn->addReloc({target->tlsModuleIndexRel, this, offset});
996ece8a530Spatrick       } else {
997ece8a530Spatrick         // When building a shared library we still need a dynamic relocation
998ece8a530Spatrick         // for the module index. Therefore only checking for
999ece8a530Spatrick         // S->isPreemptible is not sufficient (this happens e.g. for
1000ece8a530Spatrick         // thread-locals that have been marked as local through a linker script)
1001a0747c9fSpatrick         if (!s->isPreemptible && !config->shared)
1002ece8a530Spatrick           continue;
100305edf1c1Srobert         mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *this,
1004a0747c9fSpatrick                                           offset, *s);
1005ece8a530Spatrick         // However, we can skip writing the TLS offset reloc for non-preemptible
1006ece8a530Spatrick         // symbols since it is known even in shared libraries
1007ece8a530Spatrick         if (!s->isPreemptible)
1008ece8a530Spatrick           continue;
1009ece8a530Spatrick         offset += config->wordsize;
101005edf1c1Srobert         mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *this, offset,
1011a0747c9fSpatrick                                           *s);
1012ece8a530Spatrick       }
1013ece8a530Spatrick     }
1014ece8a530Spatrick 
1015ece8a530Spatrick     // Do not create dynamic relocations for non-TLS
1016ece8a530Spatrick     // entries in the primary GOT.
1017ece8a530Spatrick     if (&got == primGot)
1018ece8a530Spatrick       continue;
1019ece8a530Spatrick 
1020ece8a530Spatrick     // Dynamic relocations for "global" entries.
1021ece8a530Spatrick     for (const std::pair<Symbol *, size_t> &p : got.global) {
1022ece8a530Spatrick       uint64_t offset = p.second * config->wordsize;
102305edf1c1Srobert       mainPart->relaDyn->addSymbolReloc(target->relativeRel, *this, offset,
1024a0747c9fSpatrick                                         *p.first);
1025ece8a530Spatrick     }
1026ece8a530Spatrick     if (!config->isPic)
1027ece8a530Spatrick       continue;
1028ece8a530Spatrick     // Dynamic relocations for "local" entries in case of PIC.
1029ece8a530Spatrick     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1030ece8a530Spatrick          got.pagesMap) {
1031ece8a530Spatrick       size_t pageCount = l.second.count;
1032ece8a530Spatrick       for (size_t pi = 0; pi < pageCount; ++pi) {
1033ece8a530Spatrick         uint64_t offset = (l.second.firstIndex + pi) * config->wordsize;
1034ece8a530Spatrick         mainPart->relaDyn->addReloc({target->relativeRel, this, offset, l.first,
1035ece8a530Spatrick                                      int64_t(pi * 0x10000)});
1036ece8a530Spatrick       }
1037ece8a530Spatrick     }
1038ece8a530Spatrick     for (const std::pair<GotEntry, size_t> &p : got.local16) {
1039ece8a530Spatrick       uint64_t offset = p.second * config->wordsize;
1040a0747c9fSpatrick       mainPart->relaDyn->addReloc({target->relativeRel, this, offset,
1041a0747c9fSpatrick                                    DynamicReloc::AddendOnlyWithTargetVA,
1042a0747c9fSpatrick                                    *p.first.first, p.first.second, R_ABS});
1043ece8a530Spatrick     }
1044ece8a530Spatrick   }
1045ece8a530Spatrick }
1046ece8a530Spatrick 
isNeeded() const1047ece8a530Spatrick bool MipsGotSection::isNeeded() const {
1048ece8a530Spatrick   // We add the .got section to the result for dynamic MIPS target because
1049ece8a530Spatrick   // its address and properties are mentioned in the .dynamic section.
1050ece8a530Spatrick   return !config->relocatable;
1051ece8a530Spatrick }
1052ece8a530Spatrick 
getGp(const InputFile * f) const1053ece8a530Spatrick uint64_t MipsGotSection::getGp(const InputFile *f) const {
1054ece8a530Spatrick   // For files without related GOT or files refer a primary GOT
1055ece8a530Spatrick   // returns "common" _gp value. For secondary GOTs calculate
1056ece8a530Spatrick   // individual _gp values.
105705edf1c1Srobert   if (!f || f->mipsGotIndex == uint32_t(-1) || f->mipsGotIndex == 0)
1058ece8a530Spatrick     return ElfSym::mipsGp->getVA(0);
105905edf1c1Srobert   return getVA() + gots[f->mipsGotIndex].startIndex * config->wordsize + 0x7ff0;
1060ece8a530Spatrick }
1061ece8a530Spatrick 
writeTo(uint8_t * buf)1062ece8a530Spatrick void MipsGotSection::writeTo(uint8_t *buf) {
1063ece8a530Spatrick   // Set the MSB of the second GOT slot. This is not required by any
1064ece8a530Spatrick   // MIPS ABI documentation, though.
1065ece8a530Spatrick   //
1066ece8a530Spatrick   // There is a comment in glibc saying that "The MSB of got[1] of a
1067ece8a530Spatrick   // gnu object is set to identify gnu objects," and in GNU gold it
1068ece8a530Spatrick   // says "the second entry will be used by some runtime loaders".
1069ece8a530Spatrick   // But how this field is being used is unclear.
1070ece8a530Spatrick   //
1071ece8a530Spatrick   // We are not really willing to mimic other linkers behaviors
1072ece8a530Spatrick   // without understanding why they do that, but because all files
1073ece8a530Spatrick   // generated by GNU tools have this special GOT value, and because
1074ece8a530Spatrick   // we've been doing this for years, it is probably a safe bet to
1075ece8a530Spatrick   // keep doing this for now. We really need to revisit this to see
1076ece8a530Spatrick   // if we had to do this.
1077ece8a530Spatrick   writeUint(buf + config->wordsize, (uint64_t)1 << (config->wordsize * 8 - 1));
1078ece8a530Spatrick   for (const FileGot &g : gots) {
1079ece8a530Spatrick     auto write = [&](size_t i, const Symbol *s, int64_t a) {
1080ece8a530Spatrick       uint64_t va = a;
1081ece8a530Spatrick       if (s)
1082ece8a530Spatrick         va = s->getVA(a);
1083ece8a530Spatrick       writeUint(buf + i * config->wordsize, va);
1084ece8a530Spatrick     };
1085ece8a530Spatrick     // Write 'page address' entries to the local part of the GOT.
1086ece8a530Spatrick     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1087ece8a530Spatrick          g.pagesMap) {
1088ece8a530Spatrick       size_t pageCount = l.second.count;
1089ece8a530Spatrick       uint64_t firstPageAddr = getMipsPageAddr(l.first->addr);
1090ece8a530Spatrick       for (size_t pi = 0; pi < pageCount; ++pi)
1091ece8a530Spatrick         write(l.second.firstIndex + pi, nullptr, firstPageAddr + pi * 0x10000);
1092ece8a530Spatrick     }
1093ece8a530Spatrick     // Local, global, TLS, reloc-only  entries.
1094ece8a530Spatrick     // If TLS entry has a corresponding dynamic relocations, leave it
1095ece8a530Spatrick     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1096ece8a530Spatrick     // To calculate the adjustments use offsets for thread-local storage.
1097a0747c9fSpatrick     // http://web.archive.org/web/20190324223224/https://www.linux-mips.org/wiki/NPTL
1098ece8a530Spatrick     for (const std::pair<GotEntry, size_t> &p : g.local16)
1099ece8a530Spatrick       write(p.second, p.first.first, p.first.second);
1100ece8a530Spatrick     // Write VA to the primary GOT only. For secondary GOTs that
1101ece8a530Spatrick     // will be done by REL32 dynamic relocations.
1102ece8a530Spatrick     if (&g == &gots.front())
1103ece8a530Spatrick       for (const std::pair<Symbol *, size_t> &p : g.global)
1104ece8a530Spatrick         write(p.second, p.first, 0);
1105ece8a530Spatrick     for (const std::pair<Symbol *, size_t> &p : g.relocs)
1106ece8a530Spatrick       write(p.second, p.first, 0);
1107ece8a530Spatrick     for (const std::pair<Symbol *, size_t> &p : g.tls)
1108a0747c9fSpatrick       write(p.second, p.first,
1109a0747c9fSpatrick             p.first->isPreemptible || config->shared ? 0 : -0x7000);
1110ece8a530Spatrick     for (const std::pair<Symbol *, size_t> &p : g.dynTlsSymbols) {
1111a0747c9fSpatrick       if (p.first == nullptr && !config->shared)
1112ece8a530Spatrick         write(p.second, nullptr, 1);
1113ece8a530Spatrick       else if (p.first && !p.first->isPreemptible) {
111405edf1c1Srobert         // If we are emitting a shared library with relocations we mustn't write
1115ece8a530Spatrick         // anything to the GOT here. When using Elf_Rel relocations the value
1116ece8a530Spatrick         // one will be treated as an addend and will cause crashes at runtime
1117a0747c9fSpatrick         if (!config->shared)
1118ece8a530Spatrick           write(p.second, nullptr, 1);
1119ece8a530Spatrick         write(p.second + 1, p.first, -0x8000);
1120ece8a530Spatrick       }
1121ece8a530Spatrick     }
1122ece8a530Spatrick   }
1123ece8a530Spatrick }
1124ece8a530Spatrick 
1125ece8a530Spatrick // On PowerPC the .plt section is used to hold the table of function addresses
1126ece8a530Spatrick // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1127ece8a530Spatrick // section. I don't know why we have a BSS style type for the section but it is
1128ece8a530Spatrick // consistent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
GotPltSection()1129ece8a530Spatrick GotPltSection::GotPltSection()
1130ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
1131ece8a530Spatrick                        ".got.plt") {
1132ece8a530Spatrick   if (config->emachine == EM_PPC) {
1133ece8a530Spatrick     name = ".plt";
1134ece8a530Spatrick   } else if (config->emachine == EM_PPC64) {
1135ece8a530Spatrick     type = SHT_NOBITS;
1136ece8a530Spatrick     name = ".plt";
1137ece8a530Spatrick   }
1138ece8a530Spatrick }
1139ece8a530Spatrick 
addEntry(Symbol & sym)1140ece8a530Spatrick void GotPltSection::addEntry(Symbol &sym) {
114105edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1 &&
114205edf1c1Srobert          symAux.back().pltIdx == entries.size());
1143ece8a530Spatrick   entries.push_back(&sym);
1144ece8a530Spatrick }
1145ece8a530Spatrick 
getSize() const1146ece8a530Spatrick size_t GotPltSection::getSize() const {
1147a0747c9fSpatrick   return (target->gotPltHeaderEntriesNum + entries.size()) *
1148a0747c9fSpatrick          target->gotEntrySize;
1149ece8a530Spatrick }
1150ece8a530Spatrick 
writeTo(uint8_t * buf)1151ece8a530Spatrick void GotPltSection::writeTo(uint8_t *buf) {
1152ece8a530Spatrick   target->writeGotPltHeader(buf);
1153a0747c9fSpatrick   buf += target->gotPltHeaderEntriesNum * target->gotEntrySize;
1154ece8a530Spatrick   for (const Symbol *b : entries) {
1155ece8a530Spatrick     target->writeGotPlt(buf, *b);
1156a0747c9fSpatrick     buf += target->gotEntrySize;
1157ece8a530Spatrick   }
1158ece8a530Spatrick }
1159ece8a530Spatrick 
isNeeded() const1160ece8a530Spatrick bool GotPltSection::isNeeded() const {
1161ece8a530Spatrick   // We need to emit GOTPLT even if it's empty if there's a relocation relative
1162ece8a530Spatrick   // to it.
1163ece8a530Spatrick   return !entries.empty() || hasGotPltOffRel;
1164ece8a530Spatrick }
1165ece8a530Spatrick 
getIgotPltName()1166ece8a530Spatrick static StringRef getIgotPltName() {
1167ece8a530Spatrick   // On ARM the IgotPltSection is part of the GotSection.
1168ece8a530Spatrick   if (config->emachine == EM_ARM)
1169ece8a530Spatrick     return ".got";
1170ece8a530Spatrick 
1171ece8a530Spatrick   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1172ece8a530Spatrick   // needs to be named the same.
1173ece8a530Spatrick   if (config->emachine == EM_PPC64)
1174ece8a530Spatrick     return ".plt";
1175ece8a530Spatrick 
1176ece8a530Spatrick   return ".got.plt";
1177ece8a530Spatrick }
1178ece8a530Spatrick 
1179ece8a530Spatrick // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1180ece8a530Spatrick // with the IgotPltSection.
IgotPltSection()1181ece8a530Spatrick IgotPltSection::IgotPltSection()
1182ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1183ece8a530Spatrick                        config->emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1184a0747c9fSpatrick                        target->gotEntrySize, getIgotPltName()) {}
1185ece8a530Spatrick 
addEntry(Symbol & sym)1186ece8a530Spatrick void IgotPltSection::addEntry(Symbol &sym) {
118705edf1c1Srobert   assert(symAux.back().pltIdx == entries.size());
1188ece8a530Spatrick   entries.push_back(&sym);
1189ece8a530Spatrick }
1190ece8a530Spatrick 
getSize() const1191ece8a530Spatrick size_t IgotPltSection::getSize() const {
1192a0747c9fSpatrick   return entries.size() * target->gotEntrySize;
1193ece8a530Spatrick }
1194ece8a530Spatrick 
writeTo(uint8_t * buf)1195ece8a530Spatrick void IgotPltSection::writeTo(uint8_t *buf) {
1196ece8a530Spatrick   for (const Symbol *b : entries) {
1197ece8a530Spatrick     target->writeIgotPlt(buf, *b);
1198a0747c9fSpatrick     buf += target->gotEntrySize;
1199ece8a530Spatrick   }
1200ece8a530Spatrick }
1201ece8a530Spatrick 
StringTableSection(StringRef name,bool dynamic)1202ece8a530Spatrick StringTableSection::StringTableSection(StringRef name, bool dynamic)
1203ece8a530Spatrick     : SyntheticSection(dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, name),
1204ece8a530Spatrick       dynamic(dynamic) {
1205ece8a530Spatrick   // ELF string tables start with a NUL byte.
120605edf1c1Srobert   strings.push_back("");
120705edf1c1Srobert   stringMap.try_emplace(CachedHashStringRef(""), 0);
120805edf1c1Srobert   size = 1;
1209ece8a530Spatrick }
1210ece8a530Spatrick 
1211ece8a530Spatrick // Adds a string to the string table. If `hashIt` is true we hash and check for
1212ece8a530Spatrick // duplicates. It is optional because the name of global symbols are already
1213ece8a530Spatrick // uniqued and hashing them again has a big cost for a small value: uniquing
1214ece8a530Spatrick // them with some other string that happens to be the same.
addString(StringRef s,bool hashIt)1215ece8a530Spatrick unsigned StringTableSection::addString(StringRef s, bool hashIt) {
1216ece8a530Spatrick   if (hashIt) {
121705edf1c1Srobert     auto r = stringMap.try_emplace(CachedHashStringRef(s), size);
1218ece8a530Spatrick     if (!r.second)
1219ece8a530Spatrick       return r.first->second;
1220ece8a530Spatrick   }
122105edf1c1Srobert   if (s.empty())
122205edf1c1Srobert     return 0;
1223ece8a530Spatrick   unsigned ret = this->size;
1224ece8a530Spatrick   this->size = this->size + s.size() + 1;
1225ece8a530Spatrick   strings.push_back(s);
1226ece8a530Spatrick   return ret;
1227ece8a530Spatrick }
1228ece8a530Spatrick 
writeTo(uint8_t * buf)1229ece8a530Spatrick void StringTableSection::writeTo(uint8_t *buf) {
1230ece8a530Spatrick   for (StringRef s : strings) {
1231ece8a530Spatrick     memcpy(buf, s.data(), s.size());
1232ece8a530Spatrick     buf[s.size()] = '\0';
1233ece8a530Spatrick     buf += s.size() + 1;
1234ece8a530Spatrick   }
1235ece8a530Spatrick }
1236ece8a530Spatrick 
1237ece8a530Spatrick // Returns the number of entries in .gnu.version_d: the number of
1238ece8a530Spatrick // non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
1239ece8a530Spatrick // Note that we don't support vd_cnt > 1 yet.
getVerDefNum()1240ece8a530Spatrick static unsigned getVerDefNum() {
1241ece8a530Spatrick   return namedVersionDefs().size() + 1;
1242ece8a530Spatrick }
1243ece8a530Spatrick 
1244ece8a530Spatrick template <class ELFT>
DynamicSection()1245ece8a530Spatrick DynamicSection<ELFT>::DynamicSection()
1246ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, config->wordsize,
1247ece8a530Spatrick                        ".dynamic") {
1248ece8a530Spatrick   this->entsize = ELFT::Is64Bits ? 16 : 8;
1249ece8a530Spatrick 
1250ece8a530Spatrick   // .dynamic section is not writable on MIPS and on Fuchsia OS
1251ece8a530Spatrick   // which passes -z rodynamic.
1252ece8a530Spatrick   // See "Special Section" in Chapter 4 in the following document:
1253ece8a530Spatrick   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1254ece8a530Spatrick   if (config->emachine == EM_MIPS || config->zRodynamic)
1255ece8a530Spatrick     this->flags = SHF_ALLOC;
1256ece8a530Spatrick }
1257ece8a530Spatrick 
1258ece8a530Spatrick // The output section .rela.dyn may include these synthetic sections:
1259ece8a530Spatrick //
1260ece8a530Spatrick // - part.relaDyn
1261ece8a530Spatrick // - in.relaIplt: this is included if in.relaIplt is named .rela.dyn
1262ece8a530Spatrick // - in.relaPlt: this is included if a linker script places .rela.plt inside
1263ece8a530Spatrick //   .rela.dyn
1264ece8a530Spatrick //
1265ece8a530Spatrick // DT_RELASZ is the total size of the included sections.
addRelaSz(const RelocationBaseSection & relaDyn)126605edf1c1Srobert static uint64_t addRelaSz(const RelocationBaseSection &relaDyn) {
126705edf1c1Srobert   size_t size = relaDyn.getSize();
126805edf1c1Srobert   if (in.relaIplt->getParent() == relaDyn.getParent())
1269ece8a530Spatrick     size += in.relaIplt->getSize();
127005edf1c1Srobert   if (in.relaPlt->getParent() == relaDyn.getParent())
1271ece8a530Spatrick     size += in.relaPlt->getSize();
1272ece8a530Spatrick   return size;
1273ece8a530Spatrick }
1274ece8a530Spatrick 
1275ece8a530Spatrick // A Linker script may assign the RELA relocation sections to the same
1276ece8a530Spatrick // output section. When this occurs we cannot just use the OutputSection
1277ece8a530Spatrick // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1278ece8a530Spatrick // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
addPltRelSz()1279ece8a530Spatrick static uint64_t addPltRelSz() {
1280ece8a530Spatrick   size_t size = in.relaPlt->getSize();
1281ece8a530Spatrick   if (in.relaIplt->getParent() == in.relaPlt->getParent() &&
1282ece8a530Spatrick       in.relaIplt->name == in.relaPlt->name)
1283ece8a530Spatrick     size += in.relaIplt->getSize();
1284ece8a530Spatrick   return size;
1285ece8a530Spatrick }
1286ece8a530Spatrick 
1287ece8a530Spatrick // Add remaining entries to complete .dynamic contents.
128805edf1c1Srobert template <class ELFT>
128905edf1c1Srobert std::vector<std::pair<int32_t, uint64_t>>
computeContents()129005edf1c1Srobert DynamicSection<ELFT>::computeContents() {
1291adae0cfdSpatrick   elf::Partition &part = getPartition();
1292ece8a530Spatrick   bool isMain = part.name.empty();
129305edf1c1Srobert   std::vector<std::pair<int32_t, uint64_t>> entries;
129405edf1c1Srobert 
129505edf1c1Srobert   auto addInt = [&](int32_t tag, uint64_t val) {
129605edf1c1Srobert     entries.emplace_back(tag, val);
129705edf1c1Srobert   };
129805edf1c1Srobert   auto addInSec = [&](int32_t tag, const InputSection &sec) {
129905edf1c1Srobert     entries.emplace_back(tag, sec.getVA());
130005edf1c1Srobert   };
1301ece8a530Spatrick 
1302ece8a530Spatrick   for (StringRef s : config->filterList)
1303ece8a530Spatrick     addInt(DT_FILTER, part.dynStrTab->addString(s));
1304ece8a530Spatrick   for (StringRef s : config->auxiliaryList)
1305ece8a530Spatrick     addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
1306ece8a530Spatrick 
1307ece8a530Spatrick   if (!config->rpath.empty())
1308ece8a530Spatrick     addInt(config->enableNewDtags ? DT_RUNPATH : DT_RPATH,
1309ece8a530Spatrick            part.dynStrTab->addString(config->rpath));
1310ece8a530Spatrick 
131105edf1c1Srobert   for (SharedFile *file : ctx.sharedFiles)
1312ece8a530Spatrick     if (file->isNeeded)
1313ece8a530Spatrick       addInt(DT_NEEDED, part.dynStrTab->addString(file->soName));
1314ece8a530Spatrick 
1315ece8a530Spatrick   if (isMain) {
1316ece8a530Spatrick     if (!config->soName.empty())
1317ece8a530Spatrick       addInt(DT_SONAME, part.dynStrTab->addString(config->soName));
1318ece8a530Spatrick   } else {
1319ece8a530Spatrick     if (!config->soName.empty())
1320ece8a530Spatrick       addInt(DT_NEEDED, part.dynStrTab->addString(config->soName));
1321ece8a530Spatrick     addInt(DT_SONAME, part.dynStrTab->addString(part.name));
1322ece8a530Spatrick   }
1323ece8a530Spatrick 
1324ece8a530Spatrick   // Set DT_FLAGS and DT_FLAGS_1.
1325ece8a530Spatrick   uint32_t dtFlags = 0;
1326ece8a530Spatrick   uint32_t dtFlags1 = 0;
1327a0747c9fSpatrick   if (config->bsymbolic == BsymbolicKind::All)
1328ece8a530Spatrick     dtFlags |= DF_SYMBOLIC;
1329ece8a530Spatrick   if (config->zGlobal)
1330ece8a530Spatrick     dtFlags1 |= DF_1_GLOBAL;
1331ece8a530Spatrick   if (config->zInitfirst)
1332ece8a530Spatrick     dtFlags1 |= DF_1_INITFIRST;
1333ece8a530Spatrick   if (config->zInterpose)
1334ece8a530Spatrick     dtFlags1 |= DF_1_INTERPOSE;
1335ece8a530Spatrick   if (config->zNodefaultlib)
1336ece8a530Spatrick     dtFlags1 |= DF_1_NODEFLIB;
1337ece8a530Spatrick   if (config->zNodelete)
1338ece8a530Spatrick     dtFlags1 |= DF_1_NODELETE;
1339ece8a530Spatrick   if (config->zNodlopen)
1340ece8a530Spatrick     dtFlags1 |= DF_1_NOOPEN;
1341adae0cfdSpatrick   if (config->pie)
1342adae0cfdSpatrick     dtFlags1 |= DF_1_PIE;
1343ece8a530Spatrick   if (config->zNow) {
1344ece8a530Spatrick     dtFlags |= DF_BIND_NOW;
1345ece8a530Spatrick     dtFlags1 |= DF_1_NOW;
1346ece8a530Spatrick   }
1347ece8a530Spatrick   if (config->zOrigin) {
1348ece8a530Spatrick     dtFlags |= DF_ORIGIN;
1349ece8a530Spatrick     dtFlags1 |= DF_1_ORIGIN;
1350ece8a530Spatrick   }
1351ece8a530Spatrick   if (!config->zText)
1352ece8a530Spatrick     dtFlags |= DF_TEXTREL;
135305edf1c1Srobert   if (ctx.hasTlsIe && config->shared)
1354ece8a530Spatrick     dtFlags |= DF_STATIC_TLS;
1355ece8a530Spatrick 
1356ece8a530Spatrick   if (dtFlags)
1357ece8a530Spatrick     addInt(DT_FLAGS, dtFlags);
1358ece8a530Spatrick   if (dtFlags1)
1359ece8a530Spatrick     addInt(DT_FLAGS_1, dtFlags1);
1360ece8a530Spatrick 
1361ece8a530Spatrick   // DT_DEBUG is a pointer to debug information used by debuggers at runtime. We
1362ece8a530Spatrick   // need it for each process, so we don't write it for DSOs. The loader writes
1363ece8a530Spatrick   // the pointer into this entry.
1364ece8a530Spatrick   //
1365ece8a530Spatrick   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1366ece8a530Spatrick   // systems (currently only Fuchsia OS) provide other means to give the
1367ece8a530Spatrick   // debugger this information. Such systems may choose make .dynamic read-only.
1368ece8a530Spatrick   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1369ece8a530Spatrick   if (!config->shared && !config->relocatable && !config->zRodynamic)
1370ece8a530Spatrick     addInt(DT_DEBUG, 0);
1371ece8a530Spatrick 
1372ece8a530Spatrick   if (part.relaDyn->isNeeded() ||
1373ece8a530Spatrick       (in.relaIplt->isNeeded() &&
1374ece8a530Spatrick        part.relaDyn->getParent() == in.relaIplt->getParent())) {
137505edf1c1Srobert     addInSec(part.relaDyn->dynamicTag, *part.relaDyn);
137605edf1c1Srobert     entries.emplace_back(part.relaDyn->sizeDynamicTag,
137705edf1c1Srobert                          addRelaSz(*part.relaDyn));
1378ece8a530Spatrick 
1379ece8a530Spatrick     bool isRela = config->isRela;
1380ece8a530Spatrick     addInt(isRela ? DT_RELAENT : DT_RELENT,
1381ece8a530Spatrick            isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1382ece8a530Spatrick 
1383ece8a530Spatrick     // MIPS dynamic loader does not support RELCOUNT tag.
1384ece8a530Spatrick     // The problem is in the tight relation between dynamic
1385ece8a530Spatrick     // relocations and GOT. So do not emit this tag on MIPS.
1386ece8a530Spatrick     if (config->emachine != EM_MIPS) {
1387ece8a530Spatrick       size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
1388ece8a530Spatrick       if (config->zCombreloc && numRelativeRels)
1389ece8a530Spatrick         addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
1390ece8a530Spatrick     }
1391ece8a530Spatrick   }
139205edf1c1Srobert   if (part.relrDyn && part.relrDyn->getParent() &&
139305edf1c1Srobert       !part.relrDyn->relocs.empty()) {
1394ece8a530Spatrick     addInSec(config->useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
139505edf1c1Srobert              *part.relrDyn);
139605edf1c1Srobert     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
139705edf1c1Srobert            part.relrDyn->getParent()->size);
1398ece8a530Spatrick     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1399ece8a530Spatrick            sizeof(Elf_Relr));
1400ece8a530Spatrick   }
1401ece8a530Spatrick   // .rel[a].plt section usually consists of two parts, containing plt and
1402ece8a530Spatrick   // iplt relocations. It is possible to have only iplt relocations in the
1403ece8a530Spatrick   // output. In that case relaPlt is empty and have zero offset, the same offset
1404ece8a530Spatrick   // as relaIplt has. And we still want to emit proper dynamic tags for that
1405ece8a530Spatrick   // case, so here we always use relaPlt as marker for the beginning of
1406ece8a530Spatrick   // .rel[a].plt section.
1407ece8a530Spatrick   if (isMain && (in.relaPlt->isNeeded() || in.relaIplt->isNeeded())) {
140805edf1c1Srobert     addInSec(DT_JMPREL, *in.relaPlt);
140905edf1c1Srobert     entries.emplace_back(DT_PLTRELSZ, addPltRelSz());
1410ece8a530Spatrick     switch (config->emachine) {
1411ece8a530Spatrick     case EM_MIPS:
141205edf1c1Srobert       addInSec(DT_MIPS_PLTGOT, *in.gotPlt);
1413ece8a530Spatrick       break;
1414ece8a530Spatrick     case EM_SPARCV9:
141505edf1c1Srobert       addInSec(DT_PLTGOT, *in.plt);
1416ece8a530Spatrick       break;
1417a0747c9fSpatrick     case EM_AARCH64:
1418a0747c9fSpatrick       if (llvm::find_if(in.relaPlt->relocs, [](const DynamicReloc &r) {
1419a0747c9fSpatrick            return r.type == target->pltRel &&
1420a0747c9fSpatrick                   r.sym->stOther & STO_AARCH64_VARIANT_PCS;
1421a0747c9fSpatrick           }) != in.relaPlt->relocs.end())
1422a0747c9fSpatrick         addInt(DT_AARCH64_VARIANT_PCS, 0);
142305edf1c1Srobert       addInSec(DT_PLTGOT, *in.gotPlt);
142405edf1c1Srobert       break;
142505edf1c1Srobert     case EM_RISCV:
142605edf1c1Srobert       if (llvm::any_of(in.relaPlt->relocs, [](const DynamicReloc &r) {
142705edf1c1Srobert             return r.type == target->pltRel &&
142805edf1c1Srobert                    (r.sym->stOther & STO_RISCV_VARIANT_CC);
142905edf1c1Srobert           }))
143005edf1c1Srobert         addInt(DT_RISCV_VARIANT_CC, 0);
143105edf1c1Srobert       [[fallthrough]];
1432ece8a530Spatrick     default:
143305edf1c1Srobert       addInSec(DT_PLTGOT, *in.gotPlt);
1434ece8a530Spatrick       break;
1435ece8a530Spatrick     }
1436ece8a530Spatrick     addInt(DT_PLTREL, config->isRela ? DT_RELA : DT_REL);
1437ece8a530Spatrick   }
1438ece8a530Spatrick 
1439ece8a530Spatrick   if (config->emachine == EM_AARCH64) {
1440ece8a530Spatrick     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1441ece8a530Spatrick       addInt(DT_AARCH64_BTI_PLT, 0);
1442adae0cfdSpatrick     if (config->zPacPlt)
1443ece8a530Spatrick       addInt(DT_AARCH64_PAC_PLT, 0);
1444ece8a530Spatrick   }
1445ece8a530Spatrick 
144605edf1c1Srobert   addInSec(DT_SYMTAB, *part.dynSymTab);
1447ece8a530Spatrick   addInt(DT_SYMENT, sizeof(Elf_Sym));
144805edf1c1Srobert   addInSec(DT_STRTAB, *part.dynStrTab);
1449ece8a530Spatrick   addInt(DT_STRSZ, part.dynStrTab->getSize());
1450ece8a530Spatrick   if (!config->zText)
1451ece8a530Spatrick     addInt(DT_TEXTREL, 0);
145205edf1c1Srobert   if (part.gnuHashTab && part.gnuHashTab->getParent())
145305edf1c1Srobert     addInSec(DT_GNU_HASH, *part.gnuHashTab);
145405edf1c1Srobert   if (part.hashTab && part.hashTab->getParent())
145505edf1c1Srobert     addInSec(DT_HASH, *part.hashTab);
1456ece8a530Spatrick 
1457ece8a530Spatrick   if (isMain) {
1458ece8a530Spatrick     if (Out::preinitArray) {
145905edf1c1Srobert       addInt(DT_PREINIT_ARRAY, Out::preinitArray->addr);
146005edf1c1Srobert       addInt(DT_PREINIT_ARRAYSZ, Out::preinitArray->size);
1461ece8a530Spatrick     }
1462ece8a530Spatrick     if (Out::initArray) {
146305edf1c1Srobert       addInt(DT_INIT_ARRAY, Out::initArray->addr);
146405edf1c1Srobert       addInt(DT_INIT_ARRAYSZ, Out::initArray->size);
1465ece8a530Spatrick     }
1466ece8a530Spatrick     if (Out::finiArray) {
146705edf1c1Srobert       addInt(DT_FINI_ARRAY, Out::finiArray->addr);
146805edf1c1Srobert       addInt(DT_FINI_ARRAYSZ, Out::finiArray->size);
1469ece8a530Spatrick     }
1470ece8a530Spatrick 
147105edf1c1Srobert     if (Symbol *b = symtab.find(config->init))
1472ece8a530Spatrick       if (b->isDefined())
147305edf1c1Srobert         addInt(DT_INIT, b->getVA());
147405edf1c1Srobert     if (Symbol *b = symtab.find(config->fini))
1475ece8a530Spatrick       if (b->isDefined())
147605edf1c1Srobert         addInt(DT_FINI, b->getVA());
1477ece8a530Spatrick   }
1478ece8a530Spatrick 
1479ece8a530Spatrick   if (part.verSym && part.verSym->isNeeded())
148005edf1c1Srobert     addInSec(DT_VERSYM, *part.verSym);
1481ece8a530Spatrick   if (part.verDef && part.verDef->isLive()) {
148205edf1c1Srobert     addInSec(DT_VERDEF, *part.verDef);
1483ece8a530Spatrick     addInt(DT_VERDEFNUM, getVerDefNum());
1484ece8a530Spatrick   }
1485ece8a530Spatrick   if (part.verNeed && part.verNeed->isNeeded()) {
148605edf1c1Srobert     addInSec(DT_VERNEED, *part.verNeed);
1487ece8a530Spatrick     unsigned needNum = 0;
148805edf1c1Srobert     for (SharedFile *f : ctx.sharedFiles)
1489ece8a530Spatrick       if (!f->vernauxs.empty())
1490ece8a530Spatrick         ++needNum;
1491ece8a530Spatrick     addInt(DT_VERNEEDNUM, needNum);
1492ece8a530Spatrick   }
1493ece8a530Spatrick 
1494ece8a530Spatrick   if (config->emachine == EM_MIPS) {
1495ece8a530Spatrick     addInt(DT_MIPS_RLD_VERSION, 1);
1496ece8a530Spatrick     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1497ece8a530Spatrick     addInt(DT_MIPS_BASE_ADDRESS, target->getImageBase());
1498ece8a530Spatrick     addInt(DT_MIPS_SYMTABNO, part.dynSymTab->getNumSymbols());
149905edf1c1Srobert     addInt(DT_MIPS_LOCAL_GOTNO, in.mipsGot->getLocalEntriesNum());
1500ece8a530Spatrick 
1501ece8a530Spatrick     if (const Symbol *b = in.mipsGot->getFirstGlobalEntry())
1502ece8a530Spatrick       addInt(DT_MIPS_GOTSYM, b->dynsymIndex);
1503ece8a530Spatrick     else
1504ece8a530Spatrick       addInt(DT_MIPS_GOTSYM, part.dynSymTab->getNumSymbols());
150505edf1c1Srobert     addInSec(DT_PLTGOT, *in.mipsGot);
1506ece8a530Spatrick     if (in.mipsRldMap) {
1507ece8a530Spatrick       if (!config->pie)
150805edf1c1Srobert         addInSec(DT_MIPS_RLD_MAP, *in.mipsRldMap);
1509ece8a530Spatrick       // Store the offset to the .rld_map section
1510ece8a530Spatrick       // relative to the address of the tag.
151105edf1c1Srobert       addInt(DT_MIPS_RLD_MAP_REL,
151205edf1c1Srobert              in.mipsRldMap->getVA() - (getVA() + entries.size() * entsize));
1513ece8a530Spatrick     }
1514ece8a530Spatrick   }
1515ece8a530Spatrick 
1516ece8a530Spatrick   // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
1517ece8a530Spatrick   // glibc assumes the old-style BSS PLT layout which we don't support.
1518ece8a530Spatrick   if (config->emachine == EM_PPC)
151905edf1c1Srobert     addInSec(DT_PPC_GOT, *in.got);
1520ece8a530Spatrick 
1521ece8a530Spatrick   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1522ece8a530Spatrick   if (config->emachine == EM_PPC64 && in.plt->isNeeded()) {
1523ece8a530Spatrick     // The Glink tag points to 32 bytes before the first lazy symbol resolution
1524ece8a530Spatrick     // stub, which starts directly after the header.
152505edf1c1Srobert     addInt(DT_PPC64_GLINK, in.plt->getVA() + target->pltHeaderSize - 32);
1526ece8a530Spatrick   }
1527ece8a530Spatrick 
1528ece8a530Spatrick   addInt(DT_NULL, 0);
152905edf1c1Srobert   return entries;
153005edf1c1Srobert }
1531ece8a530Spatrick 
finalizeContents()153205edf1c1Srobert template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
153305edf1c1Srobert   if (OutputSection *sec = getPartition().dynStrTab->getParent())
153405edf1c1Srobert     getParent()->link = sec->sectionIndex;
153505edf1c1Srobert   this->size = computeContents().size() * this->entsize;
1536ece8a530Spatrick }
1537ece8a530Spatrick 
writeTo(uint8_t * buf)1538ece8a530Spatrick template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *buf) {
1539ece8a530Spatrick   auto *p = reinterpret_cast<Elf_Dyn *>(buf);
1540ece8a530Spatrick 
154105edf1c1Srobert   for (std::pair<int32_t, uint64_t> kv : computeContents()) {
1542ece8a530Spatrick     p->d_tag = kv.first;
154305edf1c1Srobert     p->d_un.d_val = kv.second;
1544ece8a530Spatrick     ++p;
1545ece8a530Spatrick   }
1546ece8a530Spatrick }
1547ece8a530Spatrick 
getOffset() const1548ece8a530Spatrick uint64_t DynamicReloc::getOffset() const {
1549ece8a530Spatrick   return inputSec->getVA(offsetInSec);
1550ece8a530Spatrick }
1551ece8a530Spatrick 
computeAddend() const1552ece8a530Spatrick int64_t DynamicReloc::computeAddend() const {
1553a0747c9fSpatrick   switch (kind) {
1554a0747c9fSpatrick   case AddendOnly:
1555a0747c9fSpatrick     assert(sym == nullptr);
1556ece8a530Spatrick     return addend;
1557a0747c9fSpatrick   case AgainstSymbol:
1558a0747c9fSpatrick     assert(sym != nullptr);
1559a0747c9fSpatrick     return addend;
1560a0747c9fSpatrick   case AddendOnlyWithTargetVA:
1561a0747c9fSpatrick   case AgainstSymbolWithTargetVA:
1562a0747c9fSpatrick     return InputSection::getRelocTargetVA(inputSec->file, type, addend,
1563a0747c9fSpatrick                                           getOffset(), *sym, expr);
1564a0747c9fSpatrick   case MipsMultiGotPage:
1565a0747c9fSpatrick     assert(sym == nullptr);
1566ece8a530Spatrick     return getMipsPageAddr(outputSec->addr) + addend;
1567ece8a530Spatrick   }
1568a0747c9fSpatrick   llvm_unreachable("Unknown DynamicReloc::Kind enum");
1569a0747c9fSpatrick }
1570ece8a530Spatrick 
getSymIndex(SymbolTableBaseSection * symTab) const1571ece8a530Spatrick uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *symTab) const {
157205edf1c1Srobert   if (!needsDynSymIndex())
1573ece8a530Spatrick     return 0;
157405edf1c1Srobert 
157505edf1c1Srobert   size_t index = symTab->getSymbolIndex(sym);
157605edf1c1Srobert   assert((index != 0 || (type != target->gotRel && type != target->pltRel) ||
157705edf1c1Srobert           !mainPart->dynSymTab->getParent()) &&
157805edf1c1Srobert          "GOT or PLT relocation must refer to symbol in dynamic symbol table");
157905edf1c1Srobert   return index;
1580ece8a530Spatrick }
1581ece8a530Spatrick 
RelocationBaseSection(StringRef name,uint32_t type,int32_t dynamicTag,int32_t sizeDynamicTag,bool combreloc,unsigned concurrency)1582ece8a530Spatrick RelocationBaseSection::RelocationBaseSection(StringRef name, uint32_t type,
1583ece8a530Spatrick                                              int32_t dynamicTag,
158405edf1c1Srobert                                              int32_t sizeDynamicTag,
158505edf1c1Srobert                                              bool combreloc,
158605edf1c1Srobert                                              unsigned concurrency)
1587ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, type, config->wordsize, name),
158805edf1c1Srobert       dynamicTag(dynamicTag), sizeDynamicTag(sizeDynamicTag),
158905edf1c1Srobert       relocsVec(concurrency), combreloc(combreloc) {}
1590ece8a530Spatrick 
addSymbolReloc(RelType dynType,InputSectionBase & isec,uint64_t offsetInSec,Symbol & sym,int64_t addend,std::optional<RelType> addendRelType)159105edf1c1Srobert void RelocationBaseSection::addSymbolReloc(
159205edf1c1Srobert     RelType dynType, InputSectionBase &isec, uint64_t offsetInSec, Symbol &sym,
159305edf1c1Srobert     int64_t addend, std::optional<RelType> addendRelType) {
1594a0747c9fSpatrick   addReloc(DynamicReloc::AgainstSymbol, dynType, isec, offsetInSec, sym, addend,
1595a0747c9fSpatrick            R_ADDEND, addendRelType ? *addendRelType : target->noneRel);
1596ece8a530Spatrick }
1597ece8a530Spatrick 
addAddendOnlyRelocIfNonPreemptible(RelType dynType,GotSection & sec,uint64_t offsetInSec,Symbol & sym,RelType addendRelType)1598a0747c9fSpatrick void RelocationBaseSection::addAddendOnlyRelocIfNonPreemptible(
159905edf1c1Srobert     RelType dynType, GotSection &sec, uint64_t offsetInSec, Symbol &sym,
1600a0747c9fSpatrick     RelType addendRelType) {
1601a0747c9fSpatrick   // No need to write an addend to the section for preemptible symbols.
1602a0747c9fSpatrick   if (sym.isPreemptible)
160305edf1c1Srobert     addReloc({dynType, &sec, offsetInSec, DynamicReloc::AgainstSymbol, sym, 0,
1604a0747c9fSpatrick               R_ABS});
1605a0747c9fSpatrick   else
160605edf1c1Srobert     addReloc(DynamicReloc::AddendOnlyWithTargetVA, dynType, sec, offsetInSec,
1607a0747c9fSpatrick              sym, 0, R_ABS, addendRelType);
1608a0747c9fSpatrick }
1609a0747c9fSpatrick 
mergeRels()161005edf1c1Srobert void RelocationBaseSection::mergeRels() {
161105edf1c1Srobert   size_t newSize = relocs.size();
161205edf1c1Srobert   for (const auto &v : relocsVec)
161305edf1c1Srobert     newSize += v.size();
161405edf1c1Srobert   relocs.reserve(newSize);
161505edf1c1Srobert   for (const auto &v : relocsVec)
161605edf1c1Srobert     llvm::append_range(relocs, v);
161705edf1c1Srobert   relocsVec.clear();
1618ece8a530Spatrick }
1619ece8a530Spatrick 
partitionRels()162005edf1c1Srobert void RelocationBaseSection::partitionRels() {
162105edf1c1Srobert   if (!combreloc)
162205edf1c1Srobert     return;
162305edf1c1Srobert   const RelType relativeRel = target->relativeRel;
162405edf1c1Srobert   numRelativeRelocs =
162505edf1c1Srobert       llvm::partition(relocs, [=](auto &r) { return r.type == relativeRel; }) -
162605edf1c1Srobert       relocs.begin();
1627ece8a530Spatrick }
1628ece8a530Spatrick 
finalizeContents()1629ece8a530Spatrick void RelocationBaseSection::finalizeContents() {
163005edf1c1Srobert   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
1631ece8a530Spatrick 
1632ece8a530Spatrick   // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1633ece8a530Spatrick   // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1634ece8a530Spatrick   // case.
1635ece8a530Spatrick   if (symTab && symTab->getParent())
1636ece8a530Spatrick     getParent()->link = symTab->getParent()->sectionIndex;
1637ece8a530Spatrick   else
1638ece8a530Spatrick     getParent()->link = 0;
1639ece8a530Spatrick 
164005edf1c1Srobert   if (in.relaPlt.get() == this && in.gotPlt->getParent()) {
1641a0747c9fSpatrick     getParent()->flags |= ELF::SHF_INFO_LINK;
1642ece8a530Spatrick     getParent()->info = in.gotPlt->getParent()->sectionIndex;
1643a0747c9fSpatrick   }
164405edf1c1Srobert   if (in.relaIplt.get() == this && in.igotPlt->getParent()) {
1645a0747c9fSpatrick     getParent()->flags |= ELF::SHF_INFO_LINK;
1646ece8a530Spatrick     getParent()->info = in.igotPlt->getParent()->sectionIndex;
1647ece8a530Spatrick   }
1648a0747c9fSpatrick }
1649ece8a530Spatrick 
computeRaw(SymbolTableBaseSection * symtab)165005edf1c1Srobert void DynamicReloc::computeRaw(SymbolTableBaseSection *symtab) {
165105edf1c1Srobert   r_offset = getOffset();
165205edf1c1Srobert   r_sym = getSymIndex(symtab);
165305edf1c1Srobert   addend = computeAddend();
165405edf1c1Srobert   kind = AddendOnly; // Catch errors
165505edf1c1Srobert }
1656ece8a530Spatrick 
computeRels()165705edf1c1Srobert void RelocationBaseSection::computeRels() {
165805edf1c1Srobert   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
165905edf1c1Srobert   parallelForEach(relocs,
166005edf1c1Srobert                   [symTab](DynamicReloc &rel) { rel.computeRaw(symTab); });
166105edf1c1Srobert   // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
166205edf1c1Srobert   // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
166305edf1c1Srobert   // is to make results easier to read.
166405edf1c1Srobert   if (combreloc) {
166505edf1c1Srobert     auto nonRelative = relocs.begin() + numRelativeRelocs;
166605edf1c1Srobert     parallelSort(relocs.begin(), nonRelative,
166705edf1c1Srobert                  [&](auto &a, auto &b) { return a.r_offset < b.r_offset; });
166805edf1c1Srobert     // Non-relative relocations are few, so don't bother with parallelSort.
166905edf1c1Srobert     llvm::sort(nonRelative, relocs.end(), [&](auto &a, auto &b) {
167005edf1c1Srobert       return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset);
167105edf1c1Srobert     });
167205edf1c1Srobert   }
1673ece8a530Spatrick }
1674ece8a530Spatrick 
1675ece8a530Spatrick template <class ELFT>
RelocationSection(StringRef name,bool combreloc,unsigned concurrency)167605edf1c1Srobert RelocationSection<ELFT>::RelocationSection(StringRef name, bool combreloc,
167705edf1c1Srobert                                            unsigned concurrency)
1678ece8a530Spatrick     : RelocationBaseSection(name, config->isRela ? SHT_RELA : SHT_REL,
1679ece8a530Spatrick                             config->isRela ? DT_RELA : DT_REL,
168005edf1c1Srobert                             config->isRela ? DT_RELASZ : DT_RELSZ, combreloc,
168105edf1c1Srobert                             concurrency) {
1682ece8a530Spatrick   this->entsize = config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1683ece8a530Spatrick }
1684ece8a530Spatrick 
writeTo(uint8_t * buf)1685ece8a530Spatrick template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *buf) {
168605edf1c1Srobert   computeRels();
1687ece8a530Spatrick   for (const DynamicReloc &rel : relocs) {
168805edf1c1Srobert     auto *p = reinterpret_cast<Elf_Rela *>(buf);
168905edf1c1Srobert     p->r_offset = rel.r_offset;
169005edf1c1Srobert     p->setSymbolAndType(rel.r_sym, rel.type, config->isMips64EL);
169105edf1c1Srobert     if (config->isRela)
169205edf1c1Srobert       p->r_addend = rel.addend;
1693ece8a530Spatrick     buf += config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1694ece8a530Spatrick   }
1695ece8a530Spatrick }
1696ece8a530Spatrick 
RelrBaseSection(unsigned concurrency)169705edf1c1Srobert RelrBaseSection::RelrBaseSection(unsigned concurrency)
169805edf1c1Srobert     : SyntheticSection(SHF_ALLOC,
169905edf1c1Srobert                        config->useAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
170005edf1c1Srobert                        config->wordsize, ".relr.dyn"),
170105edf1c1Srobert       relocsVec(concurrency) {}
170205edf1c1Srobert 
mergeRels()170305edf1c1Srobert void RelrBaseSection::mergeRels() {
170405edf1c1Srobert   size_t newSize = relocs.size();
170505edf1c1Srobert   for (const auto &v : relocsVec)
170605edf1c1Srobert     newSize += v.size();
170705edf1c1Srobert   relocs.reserve(newSize);
170805edf1c1Srobert   for (const auto &v : relocsVec)
170905edf1c1Srobert     llvm::append_range(relocs, v);
171005edf1c1Srobert   relocsVec.clear();
171105edf1c1Srobert }
171205edf1c1Srobert 
1713ece8a530Spatrick template <class ELFT>
AndroidPackedRelocationSection(StringRef name,unsigned concurrency)1714ece8a530Spatrick AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
171505edf1c1Srobert     StringRef name, unsigned concurrency)
1716ece8a530Spatrick     : RelocationBaseSection(
1717ece8a530Spatrick           name, config->isRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1718ece8a530Spatrick           config->isRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
171905edf1c1Srobert           config->isRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ,
172005edf1c1Srobert           /*combreloc=*/false, concurrency) {
1721ece8a530Spatrick   this->entsize = 1;
1722ece8a530Spatrick }
1723ece8a530Spatrick 
1724ece8a530Spatrick template <class ELFT>
updateAllocSize()1725ece8a530Spatrick bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1726ece8a530Spatrick   // This function computes the contents of an Android-format packed relocation
1727ece8a530Spatrick   // section.
1728ece8a530Spatrick   //
1729ece8a530Spatrick   // This format compresses relocations by using relocation groups to factor out
1730ece8a530Spatrick   // fields that are common between relocations and storing deltas from previous
1731ece8a530Spatrick   // relocations in SLEB128 format (which has a short representation for small
1732ece8a530Spatrick   // numbers). A good example of a relocation type with common fields is
1733ece8a530Spatrick   // R_*_RELATIVE, which is normally used to represent function pointers in
1734ece8a530Spatrick   // vtables. In the REL format, each relative relocation has the same r_info
1735ece8a530Spatrick   // field, and is only different from other relative relocations in terms of
1736ece8a530Spatrick   // the r_offset field. By sorting relocations by offset, grouping them by
1737ece8a530Spatrick   // r_info and representing each relocation with only the delta from the
1738ece8a530Spatrick   // previous offset, each 8-byte relocation can be compressed to as little as 1
1739ece8a530Spatrick   // byte (or less with run-length encoding). This relocation packer was able to
1740ece8a530Spatrick   // reduce the size of the relocation section in an Android Chromium DSO from
1741ece8a530Spatrick   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1742ece8a530Spatrick   //
1743ece8a530Spatrick   // A relocation section consists of a header containing the literal bytes
1744ece8a530Spatrick   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1745ece8a530Spatrick   // elements are the total number of relocations in the section and an initial
1746ece8a530Spatrick   // r_offset value. The remaining elements define a sequence of relocation
1747ece8a530Spatrick   // groups. Each relocation group starts with a header consisting of the
1748ece8a530Spatrick   // following elements:
1749ece8a530Spatrick   //
1750ece8a530Spatrick   // - the number of relocations in the relocation group
1751ece8a530Spatrick   // - flags for the relocation group
1752ece8a530Spatrick   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1753ece8a530Spatrick   //   for each relocation in the group.
1754ece8a530Spatrick   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1755ece8a530Spatrick   //   field for each relocation in the group.
1756ece8a530Spatrick   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1757ece8a530Spatrick   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1758ece8a530Spatrick   //   each relocation in the group.
1759ece8a530Spatrick   //
1760ece8a530Spatrick   // Following the relocation group header are descriptions of each of the
1761ece8a530Spatrick   // relocations in the group. They consist of the following elements:
1762ece8a530Spatrick   //
1763ece8a530Spatrick   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1764ece8a530Spatrick   //   delta for this relocation.
1765ece8a530Spatrick   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1766ece8a530Spatrick   //   field for this relocation.
1767ece8a530Spatrick   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1768ece8a530Spatrick   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1769ece8a530Spatrick   //   this relocation.
1770ece8a530Spatrick 
1771ece8a530Spatrick   size_t oldSize = relocData.size();
1772ece8a530Spatrick 
1773ece8a530Spatrick   relocData = {'A', 'P', 'S', '2'};
1774ece8a530Spatrick   raw_svector_ostream os(relocData);
1775ece8a530Spatrick   auto add = [&](int64_t v) { encodeSLEB128(v, os); };
1776ece8a530Spatrick 
1777ece8a530Spatrick   // The format header includes the number of relocations and the initial
1778ece8a530Spatrick   // offset (we set this to zero because the first relocation group will
1779ece8a530Spatrick   // perform the initial adjustment).
1780ece8a530Spatrick   add(relocs.size());
1781ece8a530Spatrick   add(0);
1782ece8a530Spatrick 
1783ece8a530Spatrick   std::vector<Elf_Rela> relatives, nonRelatives;
1784ece8a530Spatrick 
1785ece8a530Spatrick   for (const DynamicReloc &rel : relocs) {
1786ece8a530Spatrick     Elf_Rela r;
178705edf1c1Srobert     r.r_offset = rel.getOffset();
178805edf1c1Srobert     r.setSymbolAndType(rel.getSymIndex(getPartition().dynSymTab.get()),
178905edf1c1Srobert                        rel.type, false);
179005edf1c1Srobert     r.r_addend = config->isRela ? rel.computeAddend() : 0;
1791ece8a530Spatrick 
1792ece8a530Spatrick     if (r.getType(config->isMips64EL) == target->relativeRel)
1793ece8a530Spatrick       relatives.push_back(r);
1794ece8a530Spatrick     else
1795ece8a530Spatrick       nonRelatives.push_back(r);
1796ece8a530Spatrick   }
1797ece8a530Spatrick 
1798ece8a530Spatrick   llvm::sort(relatives, [](const Elf_Rel &a, const Elf_Rel &b) {
1799ece8a530Spatrick     return a.r_offset < b.r_offset;
1800ece8a530Spatrick   });
1801ece8a530Spatrick 
1802ece8a530Spatrick   // Try to find groups of relative relocations which are spaced one word
1803ece8a530Spatrick   // apart from one another. These generally correspond to vtable entries. The
1804ece8a530Spatrick   // format allows these groups to be encoded using a sort of run-length
1805ece8a530Spatrick   // encoding, but each group will cost 7 bytes in addition to the offset from
1806ece8a530Spatrick   // the previous group, so it is only profitable to do this for groups of
1807ece8a530Spatrick   // size 8 or larger.
1808ece8a530Spatrick   std::vector<Elf_Rela> ungroupedRelatives;
1809ece8a530Spatrick   std::vector<std::vector<Elf_Rela>> relativeGroups;
1810ece8a530Spatrick   for (auto i = relatives.begin(), e = relatives.end(); i != e;) {
1811ece8a530Spatrick     std::vector<Elf_Rela> group;
1812ece8a530Spatrick     do {
1813ece8a530Spatrick       group.push_back(*i++);
1814ece8a530Spatrick     } while (i != e && (i - 1)->r_offset + config->wordsize == i->r_offset);
1815ece8a530Spatrick 
1816ece8a530Spatrick     if (group.size() < 8)
1817ece8a530Spatrick       ungroupedRelatives.insert(ungroupedRelatives.end(), group.begin(),
1818ece8a530Spatrick                                 group.end());
1819ece8a530Spatrick     else
1820ece8a530Spatrick       relativeGroups.emplace_back(std::move(group));
1821ece8a530Spatrick   }
1822ece8a530Spatrick 
1823ece8a530Spatrick   // For non-relative relocations, we would like to:
1824ece8a530Spatrick   //   1. Have relocations with the same symbol offset to be consecutive, so
1825ece8a530Spatrick   //      that the runtime linker can speed-up symbol lookup by implementing an
1826ece8a530Spatrick   //      1-entry cache.
1827ece8a530Spatrick   //   2. Group relocations by r_info to reduce the size of the relocation
1828ece8a530Spatrick   //      section.
1829ece8a530Spatrick   // Since the symbol offset is the high bits in r_info, sorting by r_info
1830ece8a530Spatrick   // allows us to do both.
1831ece8a530Spatrick   //
1832ece8a530Spatrick   // For Rela, we also want to sort by r_addend when r_info is the same. This
1833ece8a530Spatrick   // enables us to group by r_addend as well.
183405edf1c1Srobert   llvm::sort(nonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1835ece8a530Spatrick     if (a.r_info != b.r_info)
1836ece8a530Spatrick       return a.r_info < b.r_info;
183705edf1c1Srobert     if (a.r_addend != b.r_addend)
1838ece8a530Spatrick       return a.r_addend < b.r_addend;
183905edf1c1Srobert     return a.r_offset < b.r_offset;
1840ece8a530Spatrick   });
1841ece8a530Spatrick 
1842ece8a530Spatrick   // Group relocations with the same r_info. Note that each group emits a group
1843ece8a530Spatrick   // header and that may make the relocation section larger. It is hard to
1844ece8a530Spatrick   // estimate the size of a group header as the encoded size of that varies
1845ece8a530Spatrick   // based on r_info. However, we can approximate this trade-off by the number
1846ece8a530Spatrick   // of values encoded. Each group header contains 3 values, and each relocation
1847ece8a530Spatrick   // in a group encodes one less value, as compared to when it is not grouped.
1848ece8a530Spatrick   // Therefore, we only group relocations if there are 3 or more of them with
1849ece8a530Spatrick   // the same r_info.
1850ece8a530Spatrick   //
1851ece8a530Spatrick   // For Rela, the addend for most non-relative relocations is zero, and thus we
1852ece8a530Spatrick   // can usually get a smaller relocation section if we group relocations with 0
1853ece8a530Spatrick   // addend as well.
1854ece8a530Spatrick   std::vector<Elf_Rela> ungroupedNonRelatives;
1855ece8a530Spatrick   std::vector<std::vector<Elf_Rela>> nonRelativeGroups;
1856ece8a530Spatrick   for (auto i = nonRelatives.begin(), e = nonRelatives.end(); i != e;) {
1857ece8a530Spatrick     auto j = i + 1;
1858ece8a530Spatrick     while (j != e && i->r_info == j->r_info &&
1859ece8a530Spatrick            (!config->isRela || i->r_addend == j->r_addend))
1860ece8a530Spatrick       ++j;
1861ece8a530Spatrick     if (j - i < 3 || (config->isRela && i->r_addend != 0))
1862ece8a530Spatrick       ungroupedNonRelatives.insert(ungroupedNonRelatives.end(), i, j);
1863ece8a530Spatrick     else
1864ece8a530Spatrick       nonRelativeGroups.emplace_back(i, j);
1865ece8a530Spatrick     i = j;
1866ece8a530Spatrick   }
1867ece8a530Spatrick 
1868ece8a530Spatrick   // Sort ungrouped relocations by offset to minimize the encoded length.
1869ece8a530Spatrick   llvm::sort(ungroupedNonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1870ece8a530Spatrick     return a.r_offset < b.r_offset;
1871ece8a530Spatrick   });
1872ece8a530Spatrick 
1873ece8a530Spatrick   unsigned hasAddendIfRela =
1874ece8a530Spatrick       config->isRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1875ece8a530Spatrick 
1876ece8a530Spatrick   uint64_t offset = 0;
1877ece8a530Spatrick   uint64_t addend = 0;
1878ece8a530Spatrick 
1879ece8a530Spatrick   // Emit the run-length encoding for the groups of adjacent relative
1880ece8a530Spatrick   // relocations. Each group is represented using two groups in the packed
1881ece8a530Spatrick   // format. The first is used to set the current offset to the start of the
1882ece8a530Spatrick   // group (and also encodes the first relocation), and the second encodes the
1883ece8a530Spatrick   // remaining relocations.
1884ece8a530Spatrick   for (std::vector<Elf_Rela> &g : relativeGroups) {
1885ece8a530Spatrick     // The first relocation in the group.
1886ece8a530Spatrick     add(1);
1887ece8a530Spatrick     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1888ece8a530Spatrick         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1889ece8a530Spatrick     add(g[0].r_offset - offset);
1890ece8a530Spatrick     add(target->relativeRel);
1891ece8a530Spatrick     if (config->isRela) {
1892ece8a530Spatrick       add(g[0].r_addend - addend);
1893ece8a530Spatrick       addend = g[0].r_addend;
1894ece8a530Spatrick     }
1895ece8a530Spatrick 
1896ece8a530Spatrick     // The remaining relocations.
1897ece8a530Spatrick     add(g.size() - 1);
1898ece8a530Spatrick     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1899ece8a530Spatrick         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1900ece8a530Spatrick     add(config->wordsize);
1901ece8a530Spatrick     add(target->relativeRel);
1902ece8a530Spatrick     if (config->isRela) {
190305edf1c1Srobert       for (const auto &i : llvm::drop_begin(g)) {
190405edf1c1Srobert         add(i.r_addend - addend);
190505edf1c1Srobert         addend = i.r_addend;
1906ece8a530Spatrick       }
1907ece8a530Spatrick     }
1908ece8a530Spatrick 
1909ece8a530Spatrick     offset = g.back().r_offset;
1910ece8a530Spatrick   }
1911ece8a530Spatrick 
1912ece8a530Spatrick   // Now the ungrouped relatives.
1913ece8a530Spatrick   if (!ungroupedRelatives.empty()) {
1914ece8a530Spatrick     add(ungroupedRelatives.size());
1915ece8a530Spatrick     add(RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1916ece8a530Spatrick     add(target->relativeRel);
1917ece8a530Spatrick     for (Elf_Rela &r : ungroupedRelatives) {
1918ece8a530Spatrick       add(r.r_offset - offset);
1919ece8a530Spatrick       offset = r.r_offset;
1920ece8a530Spatrick       if (config->isRela) {
1921ece8a530Spatrick         add(r.r_addend - addend);
1922ece8a530Spatrick         addend = r.r_addend;
1923ece8a530Spatrick       }
1924ece8a530Spatrick     }
1925ece8a530Spatrick   }
1926ece8a530Spatrick 
1927ece8a530Spatrick   // Grouped non-relatives.
1928ece8a530Spatrick   for (ArrayRef<Elf_Rela> g : nonRelativeGroups) {
1929ece8a530Spatrick     add(g.size());
1930ece8a530Spatrick     add(RELOCATION_GROUPED_BY_INFO_FLAG);
1931ece8a530Spatrick     add(g[0].r_info);
1932ece8a530Spatrick     for (const Elf_Rela &r : g) {
1933ece8a530Spatrick       add(r.r_offset - offset);
1934ece8a530Spatrick       offset = r.r_offset;
1935ece8a530Spatrick     }
1936ece8a530Spatrick     addend = 0;
1937ece8a530Spatrick   }
1938ece8a530Spatrick 
1939ece8a530Spatrick   // Finally the ungrouped non-relative relocations.
1940ece8a530Spatrick   if (!ungroupedNonRelatives.empty()) {
1941ece8a530Spatrick     add(ungroupedNonRelatives.size());
1942ece8a530Spatrick     add(hasAddendIfRela);
1943ece8a530Spatrick     for (Elf_Rela &r : ungroupedNonRelatives) {
1944ece8a530Spatrick       add(r.r_offset - offset);
1945ece8a530Spatrick       offset = r.r_offset;
1946ece8a530Spatrick       add(r.r_info);
1947ece8a530Spatrick       if (config->isRela) {
1948ece8a530Spatrick         add(r.r_addend - addend);
1949ece8a530Spatrick         addend = r.r_addend;
1950ece8a530Spatrick       }
1951ece8a530Spatrick     }
1952ece8a530Spatrick   }
1953ece8a530Spatrick 
1954ece8a530Spatrick   // Don't allow the section to shrink; otherwise the size of the section can
1955ece8a530Spatrick   // oscillate infinitely.
1956ece8a530Spatrick   if (relocData.size() < oldSize)
1957ece8a530Spatrick     relocData.append(oldSize - relocData.size(), 0);
1958ece8a530Spatrick 
1959ece8a530Spatrick   // Returns whether the section size changed. We need to keep recomputing both
1960ece8a530Spatrick   // section layout and the contents of this section until the size converges
1961ece8a530Spatrick   // because changing this section's size can affect section layout, which in
1962ece8a530Spatrick   // turn can affect the sizes of the LEB-encoded integers stored in this
1963ece8a530Spatrick   // section.
1964ece8a530Spatrick   return relocData.size() != oldSize;
1965ece8a530Spatrick }
1966ece8a530Spatrick 
196705edf1c1Srobert template <class ELFT>
RelrSection(unsigned concurrency)196805edf1c1Srobert RelrSection<ELFT>::RelrSection(unsigned concurrency)
196905edf1c1Srobert     : RelrBaseSection(concurrency) {
1970ece8a530Spatrick   this->entsize = config->wordsize;
1971ece8a530Spatrick }
1972ece8a530Spatrick 
updateAllocSize()1973ece8a530Spatrick template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
1974ece8a530Spatrick   // This function computes the contents of an SHT_RELR packed relocation
1975ece8a530Spatrick   // section.
1976ece8a530Spatrick   //
1977ece8a530Spatrick   // Proposal for adding SHT_RELR sections to generic-abi is here:
1978ece8a530Spatrick   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
1979ece8a530Spatrick   //
1980ece8a530Spatrick   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
1981ece8a530Spatrick   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
1982ece8a530Spatrick   //
1983ece8a530Spatrick   // i.e. start with an address, followed by any number of bitmaps. The address
1984ece8a530Spatrick   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
1985ece8a530Spatrick   // relocations each, at subsequent offsets following the last address entry.
1986ece8a530Spatrick   //
1987ece8a530Spatrick   // The bitmap entries must have 1 in the least significant bit. The assumption
1988ece8a530Spatrick   // here is that an address cannot have 1 in lsb. Odd addresses are not
1989ece8a530Spatrick   // supported.
1990ece8a530Spatrick   //
1991ece8a530Spatrick   // Excluding the least significant bit in the bitmap, each non-zero bit in
1992ece8a530Spatrick   // the bitmap represents a relocation to be applied to a corresponding machine
1993ece8a530Spatrick   // word that follows the base address word. The second least significant bit
1994ece8a530Spatrick   // represents the machine word immediately following the initial address, and
1995ece8a530Spatrick   // each bit that follows represents the next word, in linear order. As such,
1996ece8a530Spatrick   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
1997ece8a530Spatrick   // 63 relocations in a 64-bit object.
1998ece8a530Spatrick   //
1999ece8a530Spatrick   // This encoding has a couple of interesting properties:
2000ece8a530Spatrick   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
2001ece8a530Spatrick   //    even means address, odd means bitmap.
2002ece8a530Spatrick   // 2. Just a simple list of addresses is a valid encoding.
2003ece8a530Spatrick 
2004ece8a530Spatrick   size_t oldSize = relrRelocs.size();
2005ece8a530Spatrick   relrRelocs.clear();
2006ece8a530Spatrick 
2007ece8a530Spatrick   // Same as Config->Wordsize but faster because this is a compile-time
2008ece8a530Spatrick   // constant.
2009ece8a530Spatrick   const size_t wordsize = sizeof(typename ELFT::uint);
2010ece8a530Spatrick 
2011ece8a530Spatrick   // Number of bits to use for the relocation offsets bitmap.
2012ece8a530Spatrick   // Must be either 63 or 31.
2013ece8a530Spatrick   const size_t nBits = wordsize * 8 - 1;
2014ece8a530Spatrick 
2015ece8a530Spatrick   // Get offsets for all relative relocations and sort them.
201605edf1c1Srobert   std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]);
201705edf1c1Srobert   for (auto [i, r] : llvm::enumerate(relocs))
201805edf1c1Srobert     offsets[i] = r.getOffset();
201905edf1c1Srobert   llvm::sort(offsets.get(), offsets.get() + relocs.size());
2020ece8a530Spatrick 
2021ece8a530Spatrick   // For each leading relocation, find following ones that can be folded
2022ece8a530Spatrick   // as a bitmap and fold them.
202305edf1c1Srobert   for (size_t i = 0, e = relocs.size(); i != e;) {
2024ece8a530Spatrick     // Add a leading relocation.
2025ece8a530Spatrick     relrRelocs.push_back(Elf_Relr(offsets[i]));
2026ece8a530Spatrick     uint64_t base = offsets[i] + wordsize;
2027ece8a530Spatrick     ++i;
2028ece8a530Spatrick 
2029ece8a530Spatrick     // Find foldable relocations to construct bitmaps.
203005edf1c1Srobert     for (;;) {
2031ece8a530Spatrick       uint64_t bitmap = 0;
203205edf1c1Srobert       for (; i != e; ++i) {
203305edf1c1Srobert         uint64_t d = offsets[i] - base;
203405edf1c1Srobert         if (d >= nBits * wordsize || d % wordsize)
2035ece8a530Spatrick           break;
203605edf1c1Srobert         bitmap |= uint64_t(1) << (d / wordsize);
2037ece8a530Spatrick       }
2038ece8a530Spatrick       if (!bitmap)
2039ece8a530Spatrick         break;
2040ece8a530Spatrick       relrRelocs.push_back(Elf_Relr((bitmap << 1) | 1));
2041ece8a530Spatrick       base += nBits * wordsize;
2042ece8a530Spatrick     }
2043ece8a530Spatrick   }
2044ece8a530Spatrick 
2045ece8a530Spatrick   // Don't allow the section to shrink; otherwise the size of the section can
2046ece8a530Spatrick   // oscillate infinitely. Trailing 1s do not decode to more relocations.
2047ece8a530Spatrick   if (relrRelocs.size() < oldSize) {
2048ece8a530Spatrick     log(".relr.dyn needs " + Twine(oldSize - relrRelocs.size()) +
2049ece8a530Spatrick         " padding word(s)");
2050ece8a530Spatrick     relrRelocs.resize(oldSize, Elf_Relr(1));
2051ece8a530Spatrick   }
2052ece8a530Spatrick 
2053ece8a530Spatrick   return relrRelocs.size() != oldSize;
2054ece8a530Spatrick }
2055ece8a530Spatrick 
SymbolTableBaseSection(StringTableSection & strTabSec)2056ece8a530Spatrick SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &strTabSec)
2057ece8a530Spatrick     : SyntheticSection(strTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
2058ece8a530Spatrick                        strTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
2059ece8a530Spatrick                        config->wordsize,
2060ece8a530Spatrick                        strTabSec.isDynamic() ? ".dynsym" : ".symtab"),
2061ece8a530Spatrick       strTabSec(strTabSec) {}
2062ece8a530Spatrick 
2063ece8a530Spatrick // Orders symbols according to their positions in the GOT,
2064ece8a530Spatrick // in compliance with MIPS ABI rules.
2065ece8a530Spatrick // See "Global Offset Table" in Chapter 5 in the following document
2066ece8a530Spatrick // for detailed description:
2067ece8a530Spatrick // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
sortMipsSymbols(const SymbolTableEntry & l,const SymbolTableEntry & r)2068ece8a530Spatrick static bool sortMipsSymbols(const SymbolTableEntry &l,
2069ece8a530Spatrick                             const SymbolTableEntry &r) {
2070ece8a530Spatrick   // Sort entries related to non-local preemptible symbols by GOT indexes.
2071ece8a530Spatrick   // All other entries go to the beginning of a dynsym in arbitrary order.
2072ece8a530Spatrick   if (l.sym->isInGot() && r.sym->isInGot())
207305edf1c1Srobert     return l.sym->getGotIdx() < r.sym->getGotIdx();
2074ece8a530Spatrick   if (!l.sym->isInGot() && !r.sym->isInGot())
2075ece8a530Spatrick     return false;
2076ece8a530Spatrick   return !l.sym->isInGot();
2077ece8a530Spatrick }
2078ece8a530Spatrick 
finalizeContents()2079ece8a530Spatrick void SymbolTableBaseSection::finalizeContents() {
2080ece8a530Spatrick   if (OutputSection *sec = strTabSec.getParent())
2081ece8a530Spatrick     getParent()->link = sec->sectionIndex;
2082ece8a530Spatrick 
2083ece8a530Spatrick   if (this->type != SHT_DYNSYM) {
2084ece8a530Spatrick     sortSymTabSymbols();
2085ece8a530Spatrick     return;
2086ece8a530Spatrick   }
2087ece8a530Spatrick 
2088ece8a530Spatrick   // If it is a .dynsym, there should be no local symbols, but we need
2089ece8a530Spatrick   // to do a few things for the dynamic linker.
2090ece8a530Spatrick 
2091ece8a530Spatrick   // Section's Info field has the index of the first non-local symbol.
2092ece8a530Spatrick   // Because the first symbol entry is a null entry, 1 is the first.
2093ece8a530Spatrick   getParent()->info = 1;
2094ece8a530Spatrick 
2095ece8a530Spatrick   if (getPartition().gnuHashTab) {
2096ece8a530Spatrick     // NB: It also sorts Symbols to meet the GNU hash table requirements.
2097ece8a530Spatrick     getPartition().gnuHashTab->addSymbols(symbols);
2098ece8a530Spatrick   } else if (config->emachine == EM_MIPS) {
2099ece8a530Spatrick     llvm::stable_sort(symbols, sortMipsSymbols);
2100ece8a530Spatrick   }
2101ece8a530Spatrick 
2102ece8a530Spatrick   // Only the main partition's dynsym indexes are stored in the symbols
2103ece8a530Spatrick   // themselves. All other partitions use a lookup table.
210405edf1c1Srobert   if (this == mainPart->dynSymTab.get()) {
2105ece8a530Spatrick     size_t i = 0;
2106ece8a530Spatrick     for (const SymbolTableEntry &s : symbols)
2107ece8a530Spatrick       s.sym->dynsymIndex = ++i;
2108ece8a530Spatrick   }
2109ece8a530Spatrick }
2110ece8a530Spatrick 
2111ece8a530Spatrick // The ELF spec requires that all local symbols precede global symbols, so we
2112ece8a530Spatrick // sort symbol entries in this function. (For .dynsym, we don't do that because
2113ece8a530Spatrick // symbols for dynamic linking are inherently all globals.)
2114ece8a530Spatrick //
2115ece8a530Spatrick // Aside from above, we put local symbols in groups starting with the STT_FILE
2116ece8a530Spatrick // symbol. That is convenient for purpose of identifying where are local symbols
2117ece8a530Spatrick // coming from.
sortSymTabSymbols()2118ece8a530Spatrick void SymbolTableBaseSection::sortSymTabSymbols() {
2119ece8a530Spatrick   // Move all local symbols before global symbols.
2120ece8a530Spatrick   auto e = std::stable_partition(
212105edf1c1Srobert       symbols.begin(), symbols.end(),
212205edf1c1Srobert       [](const SymbolTableEntry &s) { return s.sym->isLocal(); });
2123ece8a530Spatrick   size_t numLocals = e - symbols.begin();
2124ece8a530Spatrick   getParent()->info = numLocals + 1;
2125ece8a530Spatrick 
2126ece8a530Spatrick   // We want to group the local symbols by file. For that we rebuild the local
2127ece8a530Spatrick   // part of the symbols vector. We do not need to care about the STT_FILE
2128ece8a530Spatrick   // symbols, they are already naturally placed first in each group. That
2129ece8a530Spatrick   // happens because STT_FILE is always the first symbol in the object and hence
2130ece8a530Spatrick   // precede all other local symbols we add for a file.
213105edf1c1Srobert   MapVector<InputFile *, SmallVector<SymbolTableEntry, 0>> arr;
2132ece8a530Spatrick   for (const SymbolTableEntry &s : llvm::make_range(symbols.begin(), e))
2133ece8a530Spatrick     arr[s.sym->file].push_back(s);
2134ece8a530Spatrick 
2135ece8a530Spatrick   auto i = symbols.begin();
213605edf1c1Srobert   for (auto &p : arr)
2137ece8a530Spatrick     for (SymbolTableEntry &entry : p.second)
2138ece8a530Spatrick       *i++ = entry;
2139ece8a530Spatrick }
2140ece8a530Spatrick 
addSymbol(Symbol * b)2141ece8a530Spatrick void SymbolTableBaseSection::addSymbol(Symbol *b) {
2142ece8a530Spatrick   // Adding a local symbol to a .dynsym is a bug.
2143ece8a530Spatrick   assert(this->type != SHT_DYNSYM || !b->isLocal());
214405edf1c1Srobert   symbols.push_back({b, strTabSec.addString(b->getName(), false)});
2145ece8a530Spatrick }
2146ece8a530Spatrick 
getSymbolIndex(Symbol * sym)2147ece8a530Spatrick size_t SymbolTableBaseSection::getSymbolIndex(Symbol *sym) {
214805edf1c1Srobert   if (this == mainPart->dynSymTab.get())
2149ece8a530Spatrick     return sym->dynsymIndex;
2150ece8a530Spatrick 
2151ece8a530Spatrick   // Initializes symbol lookup tables lazily. This is used only for -r,
215205edf1c1Srobert   // --emit-relocs and dynsyms in partitions other than the main one.
2153ece8a530Spatrick   llvm::call_once(onceFlag, [&] {
2154ece8a530Spatrick     symbolIndexMap.reserve(symbols.size());
2155ece8a530Spatrick     size_t i = 0;
2156ece8a530Spatrick     for (const SymbolTableEntry &e : symbols) {
2157ece8a530Spatrick       if (e.sym->type == STT_SECTION)
2158ece8a530Spatrick         sectionIndexMap[e.sym->getOutputSection()] = ++i;
2159ece8a530Spatrick       else
2160ece8a530Spatrick         symbolIndexMap[e.sym] = ++i;
2161ece8a530Spatrick     }
2162ece8a530Spatrick   });
2163ece8a530Spatrick 
2164ece8a530Spatrick   // Section symbols are mapped based on their output sections
2165ece8a530Spatrick   // to maintain their semantics.
2166ece8a530Spatrick   if (sym->type == STT_SECTION)
2167ece8a530Spatrick     return sectionIndexMap.lookup(sym->getOutputSection());
2168ece8a530Spatrick   return symbolIndexMap.lookup(sym);
2169ece8a530Spatrick }
2170ece8a530Spatrick 
2171ece8a530Spatrick template <class ELFT>
SymbolTableSection(StringTableSection & strTabSec)2172ece8a530Spatrick SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &strTabSec)
2173ece8a530Spatrick     : SymbolTableBaseSection(strTabSec) {
2174ece8a530Spatrick   this->entsize = sizeof(Elf_Sym);
2175ece8a530Spatrick }
2176ece8a530Spatrick 
getCommonSec(Symbol * sym)2177ece8a530Spatrick static BssSection *getCommonSec(Symbol *sym) {
217805edf1c1Srobert   if (config->relocatable)
2179ece8a530Spatrick     if (auto *d = dyn_cast<Defined>(sym))
2180ece8a530Spatrick       return dyn_cast_or_null<BssSection>(d->section);
2181ece8a530Spatrick   return nullptr;
2182ece8a530Spatrick }
2183ece8a530Spatrick 
getSymSectionIndex(Symbol * sym)2184ece8a530Spatrick static uint32_t getSymSectionIndex(Symbol *sym) {
218505edf1c1Srobert   assert(!(sym->hasFlag(NEEDS_COPY) && sym->isObject()));
218605edf1c1Srobert   if (!isa<Defined>(sym) || sym->hasFlag(NEEDS_COPY))
2187ece8a530Spatrick     return SHN_UNDEF;
2188ece8a530Spatrick   if (const OutputSection *os = sym->getOutputSection())
2189ece8a530Spatrick     return os->sectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
2190ece8a530Spatrick                                              : os->sectionIndex;
2191ece8a530Spatrick   return SHN_ABS;
2192ece8a530Spatrick }
2193ece8a530Spatrick 
2194ece8a530Spatrick // Write the internal symbol table contents to the output symbol table.
writeTo(uint8_t * buf)2195ece8a530Spatrick template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *buf) {
2196ece8a530Spatrick   // The first entry is a null entry as per the ELF spec.
2197ece8a530Spatrick   buf += sizeof(Elf_Sym);
2198ece8a530Spatrick 
2199ece8a530Spatrick   auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2200ece8a530Spatrick 
2201ece8a530Spatrick   for (SymbolTableEntry &ent : symbols) {
2202ece8a530Spatrick     Symbol *sym = ent.sym;
2203ece8a530Spatrick     bool isDefinedHere = type == SHT_SYMTAB || sym->partition == partition;
2204ece8a530Spatrick 
220505edf1c1Srobert     // Set st_name, st_info and st_other.
2206ece8a530Spatrick     eSym->st_name = ent.strTabOffset;
220705edf1c1Srobert     eSym->setBindingAndType(sym->binding, sym->type);
220805edf1c1Srobert     eSym->st_other = sym->stOther;
2209ece8a530Spatrick 
221005edf1c1Srobert     if (BssSection *commonSec = getCommonSec(sym)) {
221105edf1c1Srobert       // When -r is specified, a COMMON symbol is not allocated. Its st_shndx
221205edf1c1Srobert       // holds SHN_COMMON and st_value holds the alignment.
221305edf1c1Srobert       eSym->st_shndx = SHN_COMMON;
221405edf1c1Srobert       eSym->st_value = commonSec->addralign;
221505edf1c1Srobert       eSym->st_size = cast<Defined>(sym)->size;
221605edf1c1Srobert     } else {
221705edf1c1Srobert       const uint32_t shndx = getSymSectionIndex(sym);
221805edf1c1Srobert       if (isDefinedHere) {
221905edf1c1Srobert         eSym->st_shndx = shndx;
2220ece8a530Spatrick         eSym->st_value = sym->getVA();
222105edf1c1Srobert         // Copy symbol size if it is a defined symbol. st_size is not
222205edf1c1Srobert         // significant for undefined symbols, so whether copying it or not is up
222305edf1c1Srobert         // to us if that's the case. We'll leave it as zero because by not
222405edf1c1Srobert         // setting a value, we can get the exact same outputs for two sets of
222505edf1c1Srobert         // input files that differ only in undefined symbol size in DSOs.
222605edf1c1Srobert         eSym->st_size = shndx != SHN_UNDEF ? cast<Defined>(sym)->size : 0;
222705edf1c1Srobert       } else {
222805edf1c1Srobert         eSym->st_shndx = 0;
2229ece8a530Spatrick         eSym->st_value = 0;
223005edf1c1Srobert         eSym->st_size = 0;
223105edf1c1Srobert       }
223205edf1c1Srobert     }
2233ece8a530Spatrick 
2234ece8a530Spatrick     ++eSym;
2235ece8a530Spatrick   }
2236ece8a530Spatrick 
2237ece8a530Spatrick   // On MIPS we need to mark symbol which has a PLT entry and requires
2238ece8a530Spatrick   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
2239ece8a530Spatrick   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
2240ece8a530Spatrick   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
2241ece8a530Spatrick   if (config->emachine == EM_MIPS) {
2242ece8a530Spatrick     auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2243ece8a530Spatrick 
2244ece8a530Spatrick     for (SymbolTableEntry &ent : symbols) {
2245ece8a530Spatrick       Symbol *sym = ent.sym;
224605edf1c1Srobert       if (sym->isInPlt() && sym->hasFlag(NEEDS_COPY))
2247ece8a530Spatrick         eSym->st_other |= STO_MIPS_PLT;
2248ece8a530Spatrick       if (isMicroMips()) {
2249ece8a530Spatrick         // We already set the less-significant bit for symbols
2250ece8a530Spatrick         // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
2251ece8a530Spatrick         // records. That allows us to distinguish such symbols in
2252adae0cfdSpatrick         // the `MIPS<ELFT>::relocate()` routine. Now we should
2253ece8a530Spatrick         // clear that bit for non-dynamic symbol table, so tools
2254ece8a530Spatrick         // like `objdump` will be able to deal with a correct
2255ece8a530Spatrick         // symbol position.
2256ece8a530Spatrick         if (sym->isDefined() &&
225705edf1c1Srobert             ((sym->stOther & STO_MIPS_MICROMIPS) || sym->hasFlag(NEEDS_COPY))) {
2258ece8a530Spatrick           if (!strTabSec.isDynamic())
2259ece8a530Spatrick             eSym->st_value &= ~1;
2260ece8a530Spatrick           eSym->st_other |= STO_MIPS_MICROMIPS;
2261ece8a530Spatrick         }
2262ece8a530Spatrick       }
2263ece8a530Spatrick       if (config->relocatable)
2264ece8a530Spatrick         if (auto *d = dyn_cast<Defined>(sym))
2265ece8a530Spatrick           if (isMipsPIC<ELFT>(d))
2266ece8a530Spatrick             eSym->st_other |= STO_MIPS_PIC;
2267ece8a530Spatrick       ++eSym;
2268ece8a530Spatrick     }
2269ece8a530Spatrick   }
2270ece8a530Spatrick }
2271ece8a530Spatrick 
SymtabShndxSection()2272ece8a530Spatrick SymtabShndxSection::SymtabShndxSection()
2273ece8a530Spatrick     : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") {
2274ece8a530Spatrick   this->entsize = 4;
2275ece8a530Spatrick }
2276ece8a530Spatrick 
writeTo(uint8_t * buf)2277ece8a530Spatrick void SymtabShndxSection::writeTo(uint8_t *buf) {
2278ece8a530Spatrick   // We write an array of 32 bit values, where each value has 1:1 association
2279ece8a530Spatrick   // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX,
2280ece8a530Spatrick   // we need to write actual index, otherwise, we must write SHN_UNDEF(0).
2281ece8a530Spatrick   buf += 4; // Ignore .symtab[0] entry.
2282ece8a530Spatrick   for (const SymbolTableEntry &entry : in.symTab->getSymbols()) {
228305edf1c1Srobert     if (!getCommonSec(entry.sym) && getSymSectionIndex(entry.sym) == SHN_XINDEX)
2284ece8a530Spatrick       write32(buf, entry.sym->getOutputSection()->sectionIndex);
2285ece8a530Spatrick     buf += 4;
2286ece8a530Spatrick   }
2287ece8a530Spatrick }
2288ece8a530Spatrick 
isNeeded() const2289ece8a530Spatrick bool SymtabShndxSection::isNeeded() const {
2290ece8a530Spatrick   // SHT_SYMTAB can hold symbols with section indices values up to
2291ece8a530Spatrick   // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
2292ece8a530Spatrick   // section. Problem is that we reveal the final section indices a bit too
2293ece8a530Spatrick   // late, and we do not know them here. For simplicity, we just always create
2294ece8a530Spatrick   // a .symtab_shndx section when the amount of output sections is huge.
2295ece8a530Spatrick   size_t size = 0;
229605edf1c1Srobert   for (SectionCommand *cmd : script->sectionCommands)
229705edf1c1Srobert     if (isa<OutputDesc>(cmd))
2298ece8a530Spatrick       ++size;
2299ece8a530Spatrick   return size >= SHN_LORESERVE;
2300ece8a530Spatrick }
2301ece8a530Spatrick 
finalizeContents()2302ece8a530Spatrick void SymtabShndxSection::finalizeContents() {
2303ece8a530Spatrick   getParent()->link = in.symTab->getParent()->sectionIndex;
2304ece8a530Spatrick }
2305ece8a530Spatrick 
getSize() const2306ece8a530Spatrick size_t SymtabShndxSection::getSize() const {
2307ece8a530Spatrick   return in.symTab->getNumSymbols() * 4;
2308ece8a530Spatrick }
2309ece8a530Spatrick 
2310ece8a530Spatrick // .hash and .gnu.hash sections contain on-disk hash tables that map
2311ece8a530Spatrick // symbol names to their dynamic symbol table indices. Their purpose
2312ece8a530Spatrick // is to help the dynamic linker resolve symbols quickly. If ELF files
2313ece8a530Spatrick // don't have them, the dynamic linker has to do linear search on all
2314ece8a530Spatrick // dynamic symbols, which makes programs slower. Therefore, a .hash
231505edf1c1Srobert // section is added to a DSO by default.
2316ece8a530Spatrick //
2317ece8a530Spatrick // The Unix semantics of resolving dynamic symbols is somewhat expensive.
2318ece8a530Spatrick // Each ELF file has a list of DSOs that the ELF file depends on and a
2319ece8a530Spatrick // list of dynamic symbols that need to be resolved from any of the
2320ece8a530Spatrick // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2321ece8a530Spatrick // where m is the number of DSOs and n is the number of dynamic
2322ece8a530Spatrick // symbols. For modern large programs, both m and n are large.  So
2323adae0cfdSpatrick // making each step faster by using hash tables substantially
2324ece8a530Spatrick // improves time to load programs.
2325ece8a530Spatrick //
2326ece8a530Spatrick // (Note that this is not the only way to design the shared library.
2327ece8a530Spatrick // For instance, the Windows DLL takes a different approach. On
2328ece8a530Spatrick // Windows, each dynamic symbol has a name of DLL from which the symbol
2329ece8a530Spatrick // has to be resolved. That makes the cost of symbol resolution O(n).
2330ece8a530Spatrick // This disables some hacky techniques you can use on Unix such as
2331ece8a530Spatrick // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2332ece8a530Spatrick //
2333ece8a530Spatrick // Due to historical reasons, we have two different hash tables, .hash
2334ece8a530Spatrick // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2335ece8a530Spatrick // and better version of .hash. .hash is just an on-disk hash table, but
2336ece8a530Spatrick // .gnu.hash has a bloom filter in addition to a hash table to skip
2337ece8a530Spatrick // DSOs very quickly. If you are sure that your dynamic linker knows
233805edf1c1Srobert // about .gnu.hash, you want to specify --hash-style=gnu. Otherwise, a
233905edf1c1Srobert // safe bet is to specify --hash-style=both for backward compatibility.
GnuHashTableSection()2340ece8a530Spatrick GnuHashTableSection::GnuHashTableSection()
2341ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, config->wordsize, ".gnu.hash") {
2342ece8a530Spatrick }
2343ece8a530Spatrick 
finalizeContents()2344ece8a530Spatrick void GnuHashTableSection::finalizeContents() {
2345ece8a530Spatrick   if (OutputSection *sec = getPartition().dynSymTab->getParent())
2346ece8a530Spatrick     getParent()->link = sec->sectionIndex;
2347ece8a530Spatrick 
2348ece8a530Spatrick   // Computes bloom filter size in word size. We want to allocate 12
2349ece8a530Spatrick   // bits for each symbol. It must be a power of two.
2350ece8a530Spatrick   if (symbols.empty()) {
2351ece8a530Spatrick     maskWords = 1;
2352ece8a530Spatrick   } else {
2353ece8a530Spatrick     uint64_t numBits = symbols.size() * 12;
2354ece8a530Spatrick     maskWords = NextPowerOf2(numBits / (config->wordsize * 8));
2355ece8a530Spatrick   }
2356ece8a530Spatrick 
2357ece8a530Spatrick   size = 16;                            // Header
2358ece8a530Spatrick   size += config->wordsize * maskWords; // Bloom filter
2359ece8a530Spatrick   size += nBuckets * 4;                 // Hash buckets
2360ece8a530Spatrick   size += symbols.size() * 4;           // Hash values
2361ece8a530Spatrick }
2362ece8a530Spatrick 
writeTo(uint8_t * buf)2363ece8a530Spatrick void GnuHashTableSection::writeTo(uint8_t *buf) {
2364ece8a530Spatrick   // Write a header.
2365ece8a530Spatrick   write32(buf, nBuckets);
2366ece8a530Spatrick   write32(buf + 4, getPartition().dynSymTab->getNumSymbols() - symbols.size());
2367ece8a530Spatrick   write32(buf + 8, maskWords);
2368ece8a530Spatrick   write32(buf + 12, Shift2);
2369ece8a530Spatrick   buf += 16;
2370ece8a530Spatrick 
237105edf1c1Srobert   // Write the 2-bit bloom filter.
237205edf1c1Srobert   const unsigned c = config->is64 ? 64 : 32;
2373ece8a530Spatrick   for (const Entry &sym : symbols) {
2374ece8a530Spatrick     // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
2375ece8a530Spatrick     // the word using bits [0:5] and [26:31].
2376ece8a530Spatrick     size_t i = (sym.hash / c) & (maskWords - 1);
2377ece8a530Spatrick     uint64_t val = readUint(buf + i * config->wordsize);
2378ece8a530Spatrick     val |= uint64_t(1) << (sym.hash % c);
2379ece8a530Spatrick     val |= uint64_t(1) << ((sym.hash >> Shift2) % c);
2380ece8a530Spatrick     writeUint(buf + i * config->wordsize, val);
2381ece8a530Spatrick   }
238205edf1c1Srobert   buf += config->wordsize * maskWords;
2383ece8a530Spatrick 
238405edf1c1Srobert   // Write the hash table.
2385ece8a530Spatrick   uint32_t *buckets = reinterpret_cast<uint32_t *>(buf);
2386ece8a530Spatrick   uint32_t oldBucket = -1;
2387ece8a530Spatrick   uint32_t *values = buckets + nBuckets;
2388ece8a530Spatrick   for (auto i = symbols.begin(), e = symbols.end(); i != e; ++i) {
2389ece8a530Spatrick     // Write a hash value. It represents a sequence of chains that share the
2390ece8a530Spatrick     // same hash modulo value. The last element of each chain is terminated by
2391ece8a530Spatrick     // LSB 1.
2392ece8a530Spatrick     uint32_t hash = i->hash;
2393ece8a530Spatrick     bool isLastInChain = (i + 1) == e || i->bucketIdx != (i + 1)->bucketIdx;
2394ece8a530Spatrick     hash = isLastInChain ? hash | 1 : hash & ~1;
2395ece8a530Spatrick     write32(values++, hash);
2396ece8a530Spatrick 
2397ece8a530Spatrick     if (i->bucketIdx == oldBucket)
2398ece8a530Spatrick       continue;
2399ece8a530Spatrick     // Write a hash bucket. Hash buckets contain indices in the following hash
2400ece8a530Spatrick     // value table.
2401ece8a530Spatrick     write32(buckets + i->bucketIdx,
2402ece8a530Spatrick             getPartition().dynSymTab->getSymbolIndex(i->sym));
2403ece8a530Spatrick     oldBucket = i->bucketIdx;
2404ece8a530Spatrick   }
2405ece8a530Spatrick }
2406ece8a530Spatrick 
2407ece8a530Spatrick // Add symbols to this symbol hash table. Note that this function
2408ece8a530Spatrick // destructively sort a given vector -- which is needed because
2409ece8a530Spatrick // GNU-style hash table places some sorting requirements.
addSymbols(SmallVectorImpl<SymbolTableEntry> & v)241005edf1c1Srobert void GnuHashTableSection::addSymbols(SmallVectorImpl<SymbolTableEntry> &v) {
2411ece8a530Spatrick   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2412ece8a530Spatrick   // its type correctly.
241305edf1c1Srobert   auto mid =
2414ece8a530Spatrick       std::stable_partition(v.begin(), v.end(), [&](const SymbolTableEntry &s) {
2415ece8a530Spatrick         return !s.sym->isDefined() || s.sym->partition != partition;
2416ece8a530Spatrick       });
2417ece8a530Spatrick 
2418ece8a530Spatrick   // We chose load factor 4 for the on-disk hash table. For each hash
2419ece8a530Spatrick   // collision, the dynamic linker will compare a uint32_t hash value.
2420ece8a530Spatrick   // Since the integer comparison is quite fast, we believe we can
2421ece8a530Spatrick   // make the load factor even larger. 4 is just a conservative choice.
2422ece8a530Spatrick   //
2423ece8a530Spatrick   // Note that we don't want to create a zero-sized hash table because
2424ece8a530Spatrick   // Android loader as of 2018 doesn't like a .gnu.hash containing such
2425ece8a530Spatrick   // table. If that's the case, we create a hash table with one unused
2426ece8a530Spatrick   // dummy slot.
2427ece8a530Spatrick   nBuckets = std::max<size_t>((v.end() - mid) / 4, 1);
2428ece8a530Spatrick 
2429ece8a530Spatrick   if (mid == v.end())
2430ece8a530Spatrick     return;
2431ece8a530Spatrick 
2432ece8a530Spatrick   for (SymbolTableEntry &ent : llvm::make_range(mid, v.end())) {
2433ece8a530Spatrick     Symbol *b = ent.sym;
2434ece8a530Spatrick     uint32_t hash = hashGnu(b->getName());
2435ece8a530Spatrick     uint32_t bucketIdx = hash % nBuckets;
2436ece8a530Spatrick     symbols.push_back({b, ent.strTabOffset, hash, bucketIdx});
2437ece8a530Spatrick   }
2438ece8a530Spatrick 
243905edf1c1Srobert   llvm::sort(symbols, [](const Entry &l, const Entry &r) {
244005edf1c1Srobert     return std::tie(l.bucketIdx, l.strTabOffset) <
244105edf1c1Srobert            std::tie(r.bucketIdx, r.strTabOffset);
2442ece8a530Spatrick   });
2443ece8a530Spatrick 
2444ece8a530Spatrick   v.erase(mid, v.end());
2445ece8a530Spatrick   for (const Entry &ent : symbols)
2446ece8a530Spatrick     v.push_back({ent.sym, ent.strTabOffset});
2447ece8a530Spatrick }
2448ece8a530Spatrick 
HashTableSection()2449ece8a530Spatrick HashTableSection::HashTableSection()
2450ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2451ece8a530Spatrick   this->entsize = 4;
2452ece8a530Spatrick }
2453ece8a530Spatrick 
finalizeContents()2454ece8a530Spatrick void HashTableSection::finalizeContents() {
245505edf1c1Srobert   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
2456ece8a530Spatrick 
2457ece8a530Spatrick   if (OutputSection *sec = symTab->getParent())
2458ece8a530Spatrick     getParent()->link = sec->sectionIndex;
2459ece8a530Spatrick 
2460ece8a530Spatrick   unsigned numEntries = 2;               // nbucket and nchain.
2461ece8a530Spatrick   numEntries += symTab->getNumSymbols(); // The chain entries.
2462ece8a530Spatrick 
2463ece8a530Spatrick   // Create as many buckets as there are symbols.
2464ece8a530Spatrick   numEntries += symTab->getNumSymbols();
2465ece8a530Spatrick   this->size = numEntries * 4;
2466ece8a530Spatrick }
2467ece8a530Spatrick 
writeTo(uint8_t * buf)2468ece8a530Spatrick void HashTableSection::writeTo(uint8_t *buf) {
246905edf1c1Srobert   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
2470ece8a530Spatrick   unsigned numSymbols = symTab->getNumSymbols();
2471ece8a530Spatrick 
2472ece8a530Spatrick   uint32_t *p = reinterpret_cast<uint32_t *>(buf);
2473ece8a530Spatrick   write32(p++, numSymbols); // nbucket
2474ece8a530Spatrick   write32(p++, numSymbols); // nchain
2475ece8a530Spatrick 
2476ece8a530Spatrick   uint32_t *buckets = p;
2477ece8a530Spatrick   uint32_t *chains = p + numSymbols;
2478ece8a530Spatrick 
2479ece8a530Spatrick   for (const SymbolTableEntry &s : symTab->getSymbols()) {
2480ece8a530Spatrick     Symbol *sym = s.sym;
2481ece8a530Spatrick     StringRef name = sym->getName();
2482ece8a530Spatrick     unsigned i = sym->dynsymIndex;
2483ece8a530Spatrick     uint32_t hash = hashSysV(name) % numSymbols;
2484ece8a530Spatrick     chains[i] = buckets[hash];
2485ece8a530Spatrick     write32(buckets + hash, i);
2486ece8a530Spatrick   }
2487ece8a530Spatrick }
2488ece8a530Spatrick 
PltSection()2489ece8a530Spatrick PltSection::PltSection()
2490ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
2491ece8a530Spatrick       headerSize(target->pltHeaderSize) {
2492ece8a530Spatrick   // On PowerPC, this section contains lazy symbol resolvers.
2493adae0cfdSpatrick   if (config->emachine == EM_PPC64) {
2494ece8a530Spatrick     name = ".glink";
249505edf1c1Srobert     addralign = 4;
2496ece8a530Spatrick   }
2497ece8a530Spatrick 
2498ece8a530Spatrick   // On x86 when IBT is enabled, this section contains the second PLT (lazy
2499ece8a530Spatrick   // symbol resolvers).
2500ece8a530Spatrick   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
2501ece8a530Spatrick       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT))
2502ece8a530Spatrick     name = ".plt.sec";
2503*293d5193Skettenis #ifdef __OpenBSD__
2504*293d5193Skettenis   else if (config->emachine == EM_X86_64)
2505*293d5193Skettenis     name = ".plt.sec";
2506*293d5193Skettenis #endif
2507ece8a530Spatrick 
2508ece8a530Spatrick   // The PLT needs to be writable on SPARC as the dynamic linker will
2509ece8a530Spatrick   // modify the instructions in the PLT entries.
2510ece8a530Spatrick   if (config->emachine == EM_SPARCV9)
2511ece8a530Spatrick     this->flags |= SHF_WRITE;
2512ece8a530Spatrick }
2513ece8a530Spatrick 
writeTo(uint8_t * buf)2514ece8a530Spatrick void PltSection::writeTo(uint8_t *buf) {
2515ece8a530Spatrick   // At beginning of PLT, we have code to call the dynamic
2516ece8a530Spatrick   // linker to resolve dynsyms at runtime. Write such code.
2517ece8a530Spatrick   target->writePltHeader(buf);
2518ece8a530Spatrick   size_t off = headerSize;
2519ece8a530Spatrick 
2520ece8a530Spatrick   for (const Symbol *sym : entries) {
2521ece8a530Spatrick     target->writePlt(buf + off, *sym, getVA() + off);
2522ece8a530Spatrick     off += target->pltEntrySize;
2523ece8a530Spatrick   }
2524ece8a530Spatrick }
2525ece8a530Spatrick 
addEntry(Symbol & sym)2526ece8a530Spatrick void PltSection::addEntry(Symbol &sym) {
252705edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1);
252805edf1c1Srobert   symAux.back().pltIdx = entries.size();
2529ece8a530Spatrick   entries.push_back(&sym);
2530ece8a530Spatrick }
2531ece8a530Spatrick 
getSize() const2532ece8a530Spatrick size_t PltSection::getSize() const {
2533adae0cfdSpatrick   return headerSize + entries.size() * target->pltEntrySize;
2534ece8a530Spatrick }
2535ece8a530Spatrick 
isNeeded() const2536ece8a530Spatrick bool PltSection::isNeeded() const {
2537ece8a530Spatrick   // For -z retpolineplt, .iplt needs the .plt header.
2538ece8a530Spatrick   return !entries.empty() || (config->zRetpolineplt && in.iplt->isNeeded());
2539ece8a530Spatrick }
2540ece8a530Spatrick 
2541ece8a530Spatrick // Used by ARM to add mapping symbols in the PLT section, which aid
2542ece8a530Spatrick // disassembly.
addSymbols()2543ece8a530Spatrick void PltSection::addSymbols() {
2544ece8a530Spatrick   target->addPltHeaderSymbols(*this);
2545ece8a530Spatrick 
2546ece8a530Spatrick   size_t off = headerSize;
2547ece8a530Spatrick   for (size_t i = 0; i < entries.size(); ++i) {
2548ece8a530Spatrick     target->addPltSymbols(*this, off);
2549ece8a530Spatrick     off += target->pltEntrySize;
2550ece8a530Spatrick   }
2551ece8a530Spatrick }
2552ece8a530Spatrick 
IpltSection()2553ece8a530Spatrick IpltSection::IpltSection()
2554ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".iplt") {
2555ece8a530Spatrick   if (config->emachine == EM_PPC || config->emachine == EM_PPC64) {
2556ece8a530Spatrick     name = ".glink";
255705edf1c1Srobert     addralign = 4;
2558ece8a530Spatrick   }
2559ece8a530Spatrick }
2560ece8a530Spatrick 
writeTo(uint8_t * buf)2561ece8a530Spatrick void IpltSection::writeTo(uint8_t *buf) {
2562ece8a530Spatrick   uint32_t off = 0;
2563ece8a530Spatrick   for (const Symbol *sym : entries) {
2564ece8a530Spatrick     target->writeIplt(buf + off, *sym, getVA() + off);
2565ece8a530Spatrick     off += target->ipltEntrySize;
2566ece8a530Spatrick   }
2567ece8a530Spatrick }
2568ece8a530Spatrick 
getSize() const2569ece8a530Spatrick size_t IpltSection::getSize() const {
2570ece8a530Spatrick   return entries.size() * target->ipltEntrySize;
2571ece8a530Spatrick }
2572ece8a530Spatrick 
addEntry(Symbol & sym)2573ece8a530Spatrick void IpltSection::addEntry(Symbol &sym) {
257405edf1c1Srobert   assert(sym.auxIdx == symAux.size() - 1);
257505edf1c1Srobert   symAux.back().pltIdx = entries.size();
2576ece8a530Spatrick   entries.push_back(&sym);
2577ece8a530Spatrick }
2578ece8a530Spatrick 
2579ece8a530Spatrick // ARM uses mapping symbols to aid disassembly.
addSymbols()2580ece8a530Spatrick void IpltSection::addSymbols() {
2581ece8a530Spatrick   size_t off = 0;
2582ece8a530Spatrick   for (size_t i = 0, e = entries.size(); i != e; ++i) {
2583ece8a530Spatrick     target->addPltSymbols(*this, off);
2584ece8a530Spatrick     off += target->pltEntrySize;
2585ece8a530Spatrick   }
2586ece8a530Spatrick }
2587ece8a530Spatrick 
PPC32GlinkSection()2588adae0cfdSpatrick PPC32GlinkSection::PPC32GlinkSection() {
2589adae0cfdSpatrick   name = ".glink";
259005edf1c1Srobert   addralign = 4;
2591adae0cfdSpatrick }
2592adae0cfdSpatrick 
writeTo(uint8_t * buf)2593adae0cfdSpatrick void PPC32GlinkSection::writeTo(uint8_t *buf) {
2594adae0cfdSpatrick   writePPC32GlinkSection(buf, entries.size());
2595adae0cfdSpatrick }
2596adae0cfdSpatrick 
getSize() const2597adae0cfdSpatrick size_t PPC32GlinkSection::getSize() const {
2598adae0cfdSpatrick   return headerSize + entries.size() * target->pltEntrySize + footerSize;
2599adae0cfdSpatrick }
2600adae0cfdSpatrick 
2601ece8a530Spatrick // This is an x86-only extra PLT section and used only when a security
2602ece8a530Spatrick // enhancement feature called CET is enabled. In this comment, I'll explain what
2603ece8a530Spatrick // the feature is and why we have two PLT sections if CET is enabled.
2604ece8a530Spatrick //
2605ece8a530Spatrick // So, what does CET do? CET introduces a new restriction to indirect jump
2606ece8a530Spatrick // instructions. CET works this way. Assume that CET is enabled. Then, if you
2607ece8a530Spatrick // execute an indirect jump instruction, the processor verifies that a special
2608ece8a530Spatrick // "landing pad" instruction (which is actually a repurposed NOP instruction and
2609ece8a530Spatrick // now called "endbr32" or "endbr64") is at the jump target. If the jump target
2610ece8a530Spatrick // does not start with that instruction, the processor raises an exception
2611ece8a530Spatrick // instead of continuing executing code.
2612ece8a530Spatrick //
2613ece8a530Spatrick // If CET is enabled, the compiler emits endbr to all locations where indirect
2614ece8a530Spatrick // jumps may jump to.
2615ece8a530Spatrick //
2616ece8a530Spatrick // This mechanism makes it extremely hard to transfer the control to a middle of
2617ece8a530Spatrick // a function that is not supporsed to be a indirect jump target, preventing
2618ece8a530Spatrick // certain types of attacks such as ROP or JOP.
2619ece8a530Spatrick //
2620ece8a530Spatrick // Note that the processors in the market as of 2019 don't actually support the
2621ece8a530Spatrick // feature. Only the spec is available at the moment.
2622ece8a530Spatrick //
2623ece8a530Spatrick // Now, I'll explain why we have this extra PLT section for CET.
2624ece8a530Spatrick //
2625ece8a530Spatrick // Since you can indirectly jump to a PLT entry, we have to make PLT entries
2626ece8a530Spatrick // start with endbr. The problem is there's no extra space for endbr (which is 4
2627ece8a530Spatrick // bytes long), as the PLT entry is only 16 bytes long and all bytes are already
2628ece8a530Spatrick // used.
2629ece8a530Spatrick //
2630ece8a530Spatrick // In order to deal with the issue, we split a PLT entry into two PLT entries.
2631ece8a530Spatrick // Remember that each PLT entry contains code to jump to an address read from
2632ece8a530Spatrick // .got.plt AND code to resolve a dynamic symbol lazily. With the 2-PLT scheme,
2633ece8a530Spatrick // the former code is written to .plt.sec, and the latter code is written to
2634ece8a530Spatrick // .plt.
2635ece8a530Spatrick //
2636ece8a530Spatrick // Lazy symbol resolution in the 2-PLT scheme works in the usual way, except
2637ece8a530Spatrick // that the regular .plt is now called .plt.sec and .plt is repurposed to
2638ece8a530Spatrick // contain only code for lazy symbol resolution.
2639ece8a530Spatrick //
2640ece8a530Spatrick // In other words, this is how the 2-PLT scheme works. Application code is
2641ece8a530Spatrick // supposed to jump to .plt.sec to call an external function. Each .plt.sec
2642ece8a530Spatrick // entry contains code to read an address from a corresponding .got.plt entry
2643ece8a530Spatrick // and jump to that address. Addresses in .got.plt initially point to .plt, so
2644ece8a530Spatrick // when an application calls an external function for the first time, the
2645ece8a530Spatrick // control is transferred to a function that resolves a symbol name from
2646ece8a530Spatrick // external shared object files. That function then rewrites a .got.plt entry
2647ece8a530Spatrick // with a resolved address, so that the subsequent function calls directly jump
2648ece8a530Spatrick // to a desired location from .plt.sec.
2649ece8a530Spatrick //
2650ece8a530Spatrick // There is an open question as to whether the 2-PLT scheme was desirable or
2651ece8a530Spatrick // not. We could have simply extended the PLT entry size to 32-bytes to
2652ece8a530Spatrick // accommodate endbr, and that scheme would have been much simpler than the
2653ece8a530Spatrick // 2-PLT scheme. One reason to split PLT was, by doing that, we could keep hot
2654ece8a530Spatrick // code (.plt.sec) from cold code (.plt). But as far as I know no one proved
2655ece8a530Spatrick // that the optimization actually makes a difference.
2656ece8a530Spatrick //
2657ece8a530Spatrick // That said, the 2-PLT scheme is a part of the ABI, debuggers and other tools
2658ece8a530Spatrick // depend on it, so we implement the ABI.
IBTPltSection()2659ece8a530Spatrick IBTPltSection::IBTPltSection()
2660ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt") {}
2661ece8a530Spatrick 
writeTo(uint8_t * buf)2662ece8a530Spatrick void IBTPltSection::writeTo(uint8_t *buf) {
2663ece8a530Spatrick   target->writeIBTPlt(buf, in.plt->getNumEntries());
2664ece8a530Spatrick }
2665ece8a530Spatrick 
getSize() const2666ece8a530Spatrick size_t IBTPltSection::getSize() const {
2667ece8a530Spatrick   // 16 is the header size of .plt.
2668ece8a530Spatrick   return 16 + in.plt->getNumEntries() * target->pltEntrySize;
2669ece8a530Spatrick }
2670ece8a530Spatrick 
isNeeded() const2671a3cd701eSkettenis bool IBTPltSection::isNeeded() const { return in.plt->getNumEntries() > 0; }
2672a3cd701eSkettenis 
2673ece8a530Spatrick // The string hash function for .gdb_index.
computeGdbHash(StringRef s)2674ece8a530Spatrick static uint32_t computeGdbHash(StringRef s) {
2675ece8a530Spatrick   uint32_t h = 0;
2676ece8a530Spatrick   for (uint8_t c : s)
2677ece8a530Spatrick     h = h * 67 + toLower(c) - 113;
2678ece8a530Spatrick   return h;
2679ece8a530Spatrick }
2680ece8a530Spatrick 
GdbIndexSection()2681ece8a530Spatrick GdbIndexSection::GdbIndexSection()
2682ece8a530Spatrick     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2683ece8a530Spatrick 
2684ece8a530Spatrick // Returns the desired size of an on-disk hash table for a .gdb_index section.
2685ece8a530Spatrick // There's a tradeoff between size and collision rate. We aim 75% utilization.
computeSymtabSize() const2686ece8a530Spatrick size_t GdbIndexSection::computeSymtabSize() const {
2687ece8a530Spatrick   return std::max<size_t>(NextPowerOf2(symbols.size() * 4 / 3), 1024);
2688ece8a530Spatrick }
2689ece8a530Spatrick 
269005edf1c1Srobert static SmallVector<GdbIndexSection::CuEntry, 0>
readCuList(DWARFContext & dwarf)269105edf1c1Srobert readCuList(DWARFContext &dwarf) {
269205edf1c1Srobert   SmallVector<GdbIndexSection::CuEntry, 0> ret;
2693ece8a530Spatrick   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
2694ece8a530Spatrick     ret.push_back({cu->getOffset(), cu->getLength() + 4});
2695ece8a530Spatrick   return ret;
2696ece8a530Spatrick }
2697ece8a530Spatrick 
269805edf1c1Srobert static SmallVector<GdbIndexSection::AddressEntry, 0>
readAddressAreas(DWARFContext & dwarf,InputSection * sec)2699ece8a530Spatrick readAddressAreas(DWARFContext &dwarf, InputSection *sec) {
270005edf1c1Srobert   SmallVector<GdbIndexSection::AddressEntry, 0> ret;
2701ece8a530Spatrick 
2702ece8a530Spatrick   uint32_t cuIdx = 0;
2703ece8a530Spatrick   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
2704ece8a530Spatrick     if (Error e = cu->tryExtractDIEsIfNeeded(false)) {
2705adae0cfdSpatrick       warn(toString(sec) + ": " + toString(std::move(e)));
2706ece8a530Spatrick       return {};
2707ece8a530Spatrick     }
2708ece8a530Spatrick     Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
2709ece8a530Spatrick     if (!ranges) {
2710adae0cfdSpatrick       warn(toString(sec) + ": " + toString(ranges.takeError()));
2711ece8a530Spatrick       return {};
2712ece8a530Spatrick     }
2713ece8a530Spatrick 
2714ece8a530Spatrick     ArrayRef<InputSectionBase *> sections = sec->file->getSections();
2715ece8a530Spatrick     for (DWARFAddressRange &r : *ranges) {
2716ece8a530Spatrick       if (r.SectionIndex == -1ULL)
2717ece8a530Spatrick         continue;
2718ece8a530Spatrick       // Range list with zero size has no effect.
2719adae0cfdSpatrick       InputSectionBase *s = sections[r.SectionIndex];
2720adae0cfdSpatrick       if (s && s != &InputSection::discarded && s->isLive())
2721adae0cfdSpatrick         if (r.LowPC != r.HighPC)
2722adae0cfdSpatrick           ret.push_back({cast<InputSection>(s), r.LowPC, r.HighPC, cuIdx});
2723ece8a530Spatrick     }
2724ece8a530Spatrick     ++cuIdx;
2725ece8a530Spatrick   }
2726ece8a530Spatrick 
2727ece8a530Spatrick   return ret;
2728ece8a530Spatrick }
2729ece8a530Spatrick 
2730ece8a530Spatrick template <class ELFT>
273105edf1c1Srobert static SmallVector<GdbIndexSection::NameAttrEntry, 0>
readPubNamesAndTypes(const LLDDwarfObj<ELFT> & obj,const SmallVectorImpl<GdbIndexSection::CuEntry> & cus)2732ece8a530Spatrick readPubNamesAndTypes(const LLDDwarfObj<ELFT> &obj,
273305edf1c1Srobert                      const SmallVectorImpl<GdbIndexSection::CuEntry> &cus) {
2734adae0cfdSpatrick   const LLDDWARFSection &pubNames = obj.getGnuPubnamesSection();
2735adae0cfdSpatrick   const LLDDWARFSection &pubTypes = obj.getGnuPubtypesSection();
2736ece8a530Spatrick 
273705edf1c1Srobert   SmallVector<GdbIndexSection::NameAttrEntry, 0> ret;
2738adae0cfdSpatrick   for (const LLDDWARFSection *pub : {&pubNames, &pubTypes}) {
2739adae0cfdSpatrick     DWARFDataExtractor data(obj, *pub, config->isLE, config->wordsize);
2740adae0cfdSpatrick     DWARFDebugPubTable table;
2741adae0cfdSpatrick     table.extract(data, /*GnuStyle=*/true, [&](Error e) {
2742adae0cfdSpatrick       warn(toString(pub->sec) + ": " + toString(std::move(e)));
2743adae0cfdSpatrick     });
2744ece8a530Spatrick     for (const DWARFDebugPubTable::Set &set : table.getData()) {
2745ece8a530Spatrick       // The value written into the constant pool is kind << 24 | cuIndex. As we
2746ece8a530Spatrick       // don't know how many compilation units precede this object to compute
2747ece8a530Spatrick       // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
2748ece8a530Spatrick       // the number of preceding compilation units later.
2749ece8a530Spatrick       uint32_t i = llvm::partition_point(cus,
2750ece8a530Spatrick                                          [&](GdbIndexSection::CuEntry cu) {
2751ece8a530Spatrick                                            return cu.cuOffset < set.Offset;
2752ece8a530Spatrick                                          }) -
2753ece8a530Spatrick                    cus.begin();
2754ece8a530Spatrick       for (const DWARFDebugPubTable::Entry &ent : set.Entries)
2755ece8a530Spatrick         ret.push_back({{ent.Name, computeGdbHash(ent.Name)},
2756ece8a530Spatrick                        (ent.Descriptor.toBits() << 24) | i});
2757ece8a530Spatrick     }
2758ece8a530Spatrick   }
2759ece8a530Spatrick   return ret;
2760ece8a530Spatrick }
2761ece8a530Spatrick 
2762ece8a530Spatrick // Create a list of symbols from a given list of symbol names and types
2763ece8a530Spatrick // by uniquifying them by name.
276405edf1c1Srobert static std::pair<SmallVector<GdbIndexSection::GdbSymbol, 0>, size_t>
createSymbols(ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry,0>> nameAttrs,const SmallVector<GdbIndexSection::GdbChunk,0> & chunks)276505edf1c1Srobert createSymbols(
276605edf1c1Srobert     ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry, 0>> nameAttrs,
276705edf1c1Srobert     const SmallVector<GdbIndexSection::GdbChunk, 0> &chunks) {
2768ece8a530Spatrick   using GdbSymbol = GdbIndexSection::GdbSymbol;
2769ece8a530Spatrick   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
2770ece8a530Spatrick 
2771ece8a530Spatrick   // For each chunk, compute the number of compilation units preceding it.
2772ece8a530Spatrick   uint32_t cuIdx = 0;
277305edf1c1Srobert   std::unique_ptr<uint32_t[]> cuIdxs(new uint32_t[chunks.size()]);
2774ece8a530Spatrick   for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
2775ece8a530Spatrick     cuIdxs[i] = cuIdx;
2776ece8a530Spatrick     cuIdx += chunks[i].compilationUnits.size();
2777ece8a530Spatrick   }
2778ece8a530Spatrick 
2779ece8a530Spatrick   // The number of symbols we will handle in this function is of the order
2780ece8a530Spatrick   // of millions for very large executables, so we use multi-threading to
2781ece8a530Spatrick   // speed it up.
2782adae0cfdSpatrick   constexpr size_t numShards = 32;
278305edf1c1Srobert   const size_t concurrency =
278405edf1c1Srobert       PowerOf2Floor(std::min<size_t>(config->threadCount, numShards));
2785ece8a530Spatrick 
2786ece8a530Spatrick   // A sharded map to uniquify symbols by name.
278705edf1c1Srobert   auto map =
278805edf1c1Srobert       std::make_unique<DenseMap<CachedHashStringRef, size_t>[]>(numShards);
2789ece8a530Spatrick   size_t shift = 32 - countTrailingZeros(numShards);
2790ece8a530Spatrick 
2791ece8a530Spatrick   // Instantiate GdbSymbols while uniqufying them by name.
279205edf1c1Srobert   auto symbols = std::make_unique<SmallVector<GdbSymbol, 0>[]>(numShards);
279305edf1c1Srobert 
279405edf1c1Srobert   parallelFor(0, concurrency, [&](size_t threadId) {
2795ece8a530Spatrick     uint32_t i = 0;
2796ece8a530Spatrick     for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
2797ece8a530Spatrick       for (const NameAttrEntry &ent : entries) {
2798ece8a530Spatrick         size_t shardId = ent.name.hash() >> shift;
2799ece8a530Spatrick         if ((shardId & (concurrency - 1)) != threadId)
2800ece8a530Spatrick           continue;
2801ece8a530Spatrick 
2802ece8a530Spatrick         uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
2803ece8a530Spatrick         size_t &idx = map[shardId][ent.name];
2804ece8a530Spatrick         if (idx) {
2805ece8a530Spatrick           symbols[shardId][idx - 1].cuVector.push_back(v);
2806ece8a530Spatrick           continue;
2807ece8a530Spatrick         }
2808ece8a530Spatrick 
2809ece8a530Spatrick         idx = symbols[shardId].size() + 1;
2810ece8a530Spatrick         symbols[shardId].push_back({ent.name, {v}, 0, 0});
2811ece8a530Spatrick       }
2812ece8a530Spatrick       ++i;
2813ece8a530Spatrick     }
2814ece8a530Spatrick   });
2815ece8a530Spatrick 
2816ece8a530Spatrick   size_t numSymbols = 0;
281705edf1c1Srobert   for (ArrayRef<GdbSymbol> v : ArrayRef(symbols.get(), numShards))
2818ece8a530Spatrick     numSymbols += v.size();
2819ece8a530Spatrick 
2820ece8a530Spatrick   // The return type is a flattened vector, so we'll copy each vector
2821ece8a530Spatrick   // contents to Ret.
282205edf1c1Srobert   SmallVector<GdbSymbol, 0> ret;
2823ece8a530Spatrick   ret.reserve(numSymbols);
282405edf1c1Srobert   for (SmallVector<GdbSymbol, 0> &vec :
282505edf1c1Srobert        MutableArrayRef(symbols.get(), numShards))
2826ece8a530Spatrick     for (GdbSymbol &sym : vec)
2827ece8a530Spatrick       ret.push_back(std::move(sym));
2828ece8a530Spatrick 
2829ece8a530Spatrick   // CU vectors and symbol names are adjacent in the output file.
2830ece8a530Spatrick   // We can compute their offsets in the output file now.
2831ece8a530Spatrick   size_t off = 0;
2832ece8a530Spatrick   for (GdbSymbol &sym : ret) {
2833ece8a530Spatrick     sym.cuVectorOff = off;
2834ece8a530Spatrick     off += (sym.cuVector.size() + 1) * 4;
2835ece8a530Spatrick   }
2836ece8a530Spatrick   for (GdbSymbol &sym : ret) {
2837ece8a530Spatrick     sym.nameOff = off;
2838ece8a530Spatrick     off += sym.name.size() + 1;
2839ece8a530Spatrick   }
284005edf1c1Srobert   // If off overflows, the last symbol's nameOff likely overflows.
284105edf1c1Srobert   if (!isUInt<32>(off))
284205edf1c1Srobert     errorOrWarn("--gdb-index: constant pool size (" + Twine(off) +
284305edf1c1Srobert                 ") exceeds UINT32_MAX");
2844ece8a530Spatrick 
284505edf1c1Srobert   return {ret, off};
2846ece8a530Spatrick }
2847ece8a530Spatrick 
2848ece8a530Spatrick // Returns a newly-created .gdb_index section.
create()2849ece8a530Spatrick template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
285005edf1c1Srobert   llvm::TimeTraceScope timeScope("Create gdb index");
285105edf1c1Srobert 
2852adae0cfdSpatrick   // Collect InputFiles with .debug_info. See the comment in
2853adae0cfdSpatrick   // LLDDwarfObj<ELFT>::LLDDwarfObj. If we do lightweight parsing in the future,
2854adae0cfdSpatrick   // note that isec->data() may uncompress the full content, which should be
2855adae0cfdSpatrick   // parallelized.
2856adae0cfdSpatrick   SetVector<InputFile *> files;
285705edf1c1Srobert   for (InputSectionBase *s : ctx.inputSections) {
2858adae0cfdSpatrick     InputSection *isec = dyn_cast<InputSection>(s);
2859adae0cfdSpatrick     if (!isec)
2860adae0cfdSpatrick       continue;
2861ece8a530Spatrick     // .debug_gnu_pub{names,types} are useless in executables.
2862ece8a530Spatrick     // They are present in input object files solely for creating
2863ece8a530Spatrick     // a .gdb_index. So we can remove them from the output.
2864ece8a530Spatrick     if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
2865ece8a530Spatrick       s->markDead();
2866adae0cfdSpatrick     else if (isec->name == ".debug_info")
2867adae0cfdSpatrick       files.insert(isec->file);
2868adae0cfdSpatrick   }
2869a0747c9fSpatrick   // Drop .rel[a].debug_gnu_pub{names,types} for --emit-relocs.
287005edf1c1Srobert   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
2871a0747c9fSpatrick     if (auto *isec = dyn_cast<InputSection>(s))
2872a0747c9fSpatrick       if (InputSectionBase *rel = isec->getRelocatedSection())
2873a0747c9fSpatrick         return !rel->isLive();
2874a0747c9fSpatrick     return !s->isLive();
2875a0747c9fSpatrick   });
2876ece8a530Spatrick 
287705edf1c1Srobert   SmallVector<GdbChunk, 0> chunks(files.size());
287805edf1c1Srobert   SmallVector<SmallVector<NameAttrEntry, 0>, 0> nameAttrs(files.size());
2879ece8a530Spatrick 
288005edf1c1Srobert   parallelFor(0, files.size(), [&](size_t i) {
2881adae0cfdSpatrick     // To keep memory usage low, we don't want to keep cached DWARFContext, so
2882adae0cfdSpatrick     // avoid getDwarf() here.
2883adae0cfdSpatrick     ObjFile<ELFT> *file = cast<ObjFile<ELFT>>(files[i]);
2884ece8a530Spatrick     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
2885adae0cfdSpatrick     auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
2886ece8a530Spatrick 
2887adae0cfdSpatrick     // If the are multiple compile units .debug_info (very rare ld -r --unique),
2888adae0cfdSpatrick     // this only picks the last one. Other address ranges are lost.
2889adae0cfdSpatrick     chunks[i].sec = dobj.getInfoSection();
2890ece8a530Spatrick     chunks[i].compilationUnits = readCuList(dwarf);
2891adae0cfdSpatrick     chunks[i].addressAreas = readAddressAreas(dwarf, chunks[i].sec);
2892adae0cfdSpatrick     nameAttrs[i] = readPubNamesAndTypes<ELFT>(dobj, chunks[i].compilationUnits);
2893ece8a530Spatrick   });
2894ece8a530Spatrick 
2895ece8a530Spatrick   auto *ret = make<GdbIndexSection>();
2896ece8a530Spatrick   ret->chunks = std::move(chunks);
289705edf1c1Srobert   std::tie(ret->symbols, ret->size) = createSymbols(nameAttrs, ret->chunks);
289805edf1c1Srobert 
289905edf1c1Srobert   // Count the areas other than the constant pool.
290005edf1c1Srobert   ret->size += sizeof(GdbIndexHeader) + ret->computeSymtabSize() * 8;
290105edf1c1Srobert   for (GdbChunk &chunk : ret->chunks)
290205edf1c1Srobert     ret->size +=
290305edf1c1Srobert         chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
290405edf1c1Srobert 
2905ece8a530Spatrick   return ret;
2906ece8a530Spatrick }
2907ece8a530Spatrick 
writeTo(uint8_t * buf)2908ece8a530Spatrick void GdbIndexSection::writeTo(uint8_t *buf) {
2909ece8a530Spatrick   // Write the header.
2910ece8a530Spatrick   auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
2911ece8a530Spatrick   uint8_t *start = buf;
2912ece8a530Spatrick   hdr->version = 7;
2913ece8a530Spatrick   buf += sizeof(*hdr);
2914ece8a530Spatrick 
2915ece8a530Spatrick   // Write the CU list.
2916ece8a530Spatrick   hdr->cuListOff = buf - start;
2917ece8a530Spatrick   for (GdbChunk &chunk : chunks) {
2918ece8a530Spatrick     for (CuEntry &cu : chunk.compilationUnits) {
2919ece8a530Spatrick       write64le(buf, chunk.sec->outSecOff + cu.cuOffset);
2920ece8a530Spatrick       write64le(buf + 8, cu.cuLength);
2921ece8a530Spatrick       buf += 16;
2922ece8a530Spatrick     }
2923ece8a530Spatrick   }
2924ece8a530Spatrick 
2925ece8a530Spatrick   // Write the address area.
2926ece8a530Spatrick   hdr->cuTypesOff = buf - start;
2927ece8a530Spatrick   hdr->addressAreaOff = buf - start;
2928ece8a530Spatrick   uint32_t cuOff = 0;
2929ece8a530Spatrick   for (GdbChunk &chunk : chunks) {
2930ece8a530Spatrick     for (AddressEntry &e : chunk.addressAreas) {
2931a0747c9fSpatrick       // In the case of ICF there may be duplicate address range entries.
2932a0747c9fSpatrick       const uint64_t baseAddr = e.section->repl->getVA(0);
2933ece8a530Spatrick       write64le(buf, baseAddr + e.lowAddress);
2934ece8a530Spatrick       write64le(buf + 8, baseAddr + e.highAddress);
2935ece8a530Spatrick       write32le(buf + 16, e.cuIndex + cuOff);
2936ece8a530Spatrick       buf += 20;
2937ece8a530Spatrick     }
2938ece8a530Spatrick     cuOff += chunk.compilationUnits.size();
2939ece8a530Spatrick   }
2940ece8a530Spatrick 
2941ece8a530Spatrick   // Write the on-disk open-addressing hash table containing symbols.
2942ece8a530Spatrick   hdr->symtabOff = buf - start;
2943ece8a530Spatrick   size_t symtabSize = computeSymtabSize();
2944ece8a530Spatrick   uint32_t mask = symtabSize - 1;
2945ece8a530Spatrick 
2946ece8a530Spatrick   for (GdbSymbol &sym : symbols) {
2947ece8a530Spatrick     uint32_t h = sym.name.hash();
2948ece8a530Spatrick     uint32_t i = h & mask;
2949ece8a530Spatrick     uint32_t step = ((h * 17) & mask) | 1;
2950ece8a530Spatrick 
2951ece8a530Spatrick     while (read32le(buf + i * 8))
2952ece8a530Spatrick       i = (i + step) & mask;
2953ece8a530Spatrick 
2954ece8a530Spatrick     write32le(buf + i * 8, sym.nameOff);
2955ece8a530Spatrick     write32le(buf + i * 8 + 4, sym.cuVectorOff);
2956ece8a530Spatrick   }
2957ece8a530Spatrick 
2958ece8a530Spatrick   buf += symtabSize * 8;
2959ece8a530Spatrick 
2960ece8a530Spatrick   // Write the string pool.
2961ece8a530Spatrick   hdr->constantPoolOff = buf - start;
2962ece8a530Spatrick   parallelForEach(symbols, [&](GdbSymbol &sym) {
2963ece8a530Spatrick     memcpy(buf + sym.nameOff, sym.name.data(), sym.name.size());
2964ece8a530Spatrick   });
2965ece8a530Spatrick 
2966ece8a530Spatrick   // Write the CU vectors.
2967ece8a530Spatrick   for (GdbSymbol &sym : symbols) {
2968ece8a530Spatrick     write32le(buf, sym.cuVector.size());
2969ece8a530Spatrick     buf += 4;
2970ece8a530Spatrick     for (uint32_t val : sym.cuVector) {
2971ece8a530Spatrick       write32le(buf, val);
2972ece8a530Spatrick       buf += 4;
2973ece8a530Spatrick     }
2974ece8a530Spatrick   }
2975ece8a530Spatrick }
2976ece8a530Spatrick 
isNeeded() const2977ece8a530Spatrick bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
2978ece8a530Spatrick 
EhFrameHeader()2979ece8a530Spatrick EhFrameHeader::EhFrameHeader()
2980ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
2981ece8a530Spatrick 
writeTo(uint8_t * buf)2982ece8a530Spatrick void EhFrameHeader::writeTo(uint8_t *buf) {
2983ece8a530Spatrick   // Unlike most sections, the EhFrameHeader section is written while writing
2984ece8a530Spatrick   // another section, namely EhFrameSection, which calls the write() function
2985ece8a530Spatrick   // below from its writeTo() function. This is necessary because the contents
2986ece8a530Spatrick   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
2987ece8a530Spatrick   // don't know which order the sections will be written in.
2988ece8a530Spatrick }
2989ece8a530Spatrick 
2990ece8a530Spatrick // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2991ece8a530Spatrick // Each entry of the search table consists of two values,
2992ece8a530Spatrick // the starting PC from where FDEs covers, and the FDE's address.
2993ece8a530Spatrick // It is sorted by PC.
write()2994ece8a530Spatrick void EhFrameHeader::write() {
2995ece8a530Spatrick   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
2996ece8a530Spatrick   using FdeData = EhFrameSection::FdeData;
299705edf1c1Srobert   SmallVector<FdeData, 0> fdes = getPartition().ehFrame->getFdeData();
2998ece8a530Spatrick 
2999ece8a530Spatrick   buf[0] = 1;
3000ece8a530Spatrick   buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
3001ece8a530Spatrick   buf[2] = DW_EH_PE_udata4;
3002ece8a530Spatrick   buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
3003ece8a530Spatrick   write32(buf + 4,
3004ece8a530Spatrick           getPartition().ehFrame->getParent()->addr - this->getVA() - 4);
3005ece8a530Spatrick   write32(buf + 8, fdes.size());
3006ece8a530Spatrick   buf += 12;
3007ece8a530Spatrick 
3008ece8a530Spatrick   for (FdeData &fde : fdes) {
3009ece8a530Spatrick     write32(buf, fde.pcRel);
3010ece8a530Spatrick     write32(buf + 4, fde.fdeVARel);
3011ece8a530Spatrick     buf += 8;
3012ece8a530Spatrick   }
3013ece8a530Spatrick }
3014ece8a530Spatrick 
getSize() const3015ece8a530Spatrick size_t EhFrameHeader::getSize() const {
3016ece8a530Spatrick   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
3017ece8a530Spatrick   return 12 + getPartition().ehFrame->numFdes * 8;
3018ece8a530Spatrick }
3019ece8a530Spatrick 
isNeeded() const3020ece8a530Spatrick bool EhFrameHeader::isNeeded() const {
3021ece8a530Spatrick   return isLive() && getPartition().ehFrame->isNeeded();
3022ece8a530Spatrick }
3023ece8a530Spatrick 
VersionDefinitionSection()3024ece8a530Spatrick VersionDefinitionSection::VersionDefinitionSection()
3025ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
3026ece8a530Spatrick                        ".gnu.version_d") {}
3027ece8a530Spatrick 
getFileDefName()3028ece8a530Spatrick StringRef VersionDefinitionSection::getFileDefName() {
3029ece8a530Spatrick   if (!getPartition().name.empty())
3030ece8a530Spatrick     return getPartition().name;
3031ece8a530Spatrick   if (!config->soName.empty())
3032ece8a530Spatrick     return config->soName;
3033ece8a530Spatrick   return config->outputFile;
3034ece8a530Spatrick }
3035ece8a530Spatrick 
finalizeContents()3036ece8a530Spatrick void VersionDefinitionSection::finalizeContents() {
3037ece8a530Spatrick   fileDefNameOff = getPartition().dynStrTab->addString(getFileDefName());
3038ece8a530Spatrick   for (const VersionDefinition &v : namedVersionDefs())
3039ece8a530Spatrick     verDefNameOffs.push_back(getPartition().dynStrTab->addString(v.name));
3040ece8a530Spatrick 
3041ece8a530Spatrick   if (OutputSection *sec = getPartition().dynStrTab->getParent())
3042ece8a530Spatrick     getParent()->link = sec->sectionIndex;
3043ece8a530Spatrick 
3044ece8a530Spatrick   // sh_info should be set to the number of definitions. This fact is missed in
3045ece8a530Spatrick   // documentation, but confirmed by binutils community:
3046ece8a530Spatrick   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
3047ece8a530Spatrick   getParent()->info = getVerDefNum();
3048ece8a530Spatrick }
3049ece8a530Spatrick 
writeOne(uint8_t * buf,uint32_t index,StringRef name,size_t nameOff)3050ece8a530Spatrick void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
3051ece8a530Spatrick                                         StringRef name, size_t nameOff) {
3052ece8a530Spatrick   uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
3053ece8a530Spatrick 
3054ece8a530Spatrick   // Write a verdef.
3055ece8a530Spatrick   write16(buf, 1);                  // vd_version
3056ece8a530Spatrick   write16(buf + 2, flags);          // vd_flags
3057ece8a530Spatrick   write16(buf + 4, index);          // vd_ndx
3058ece8a530Spatrick   write16(buf + 6, 1);              // vd_cnt
3059ece8a530Spatrick   write32(buf + 8, hashSysV(name)); // vd_hash
3060ece8a530Spatrick   write32(buf + 12, 20);            // vd_aux
3061ece8a530Spatrick   write32(buf + 16, 28);            // vd_next
3062ece8a530Spatrick 
3063ece8a530Spatrick   // Write a veraux.
3064ece8a530Spatrick   write32(buf + 20, nameOff); // vda_name
3065ece8a530Spatrick   write32(buf + 24, 0);       // vda_next
3066ece8a530Spatrick }
3067ece8a530Spatrick 
writeTo(uint8_t * buf)3068ece8a530Spatrick void VersionDefinitionSection::writeTo(uint8_t *buf) {
3069ece8a530Spatrick   writeOne(buf, 1, getFileDefName(), fileDefNameOff);
3070ece8a530Spatrick 
3071ece8a530Spatrick   auto nameOffIt = verDefNameOffs.begin();
3072ece8a530Spatrick   for (const VersionDefinition &v : namedVersionDefs()) {
3073ece8a530Spatrick     buf += EntrySize;
3074ece8a530Spatrick     writeOne(buf, v.id, v.name, *nameOffIt++);
3075ece8a530Spatrick   }
3076ece8a530Spatrick 
3077ece8a530Spatrick   // Need to terminate the last version definition.
3078ece8a530Spatrick   write32(buf + 16, 0); // vd_next
3079ece8a530Spatrick }
3080ece8a530Spatrick 
getSize() const3081ece8a530Spatrick size_t VersionDefinitionSection::getSize() const {
3082ece8a530Spatrick   return EntrySize * getVerDefNum();
3083ece8a530Spatrick }
3084ece8a530Spatrick 
3085ece8a530Spatrick // .gnu.version is a table where each entry is 2 byte long.
VersionTableSection()3086ece8a530Spatrick VersionTableSection::VersionTableSection()
3087ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
3088ece8a530Spatrick                        ".gnu.version") {
3089ece8a530Spatrick   this->entsize = 2;
3090ece8a530Spatrick }
3091ece8a530Spatrick 
finalizeContents()3092ece8a530Spatrick void VersionTableSection::finalizeContents() {
3093ece8a530Spatrick   // At the moment of june 2016 GNU docs does not mention that sh_link field
3094ece8a530Spatrick   // should be set, but Sun docs do. Also readelf relies on this field.
3095ece8a530Spatrick   getParent()->link = getPartition().dynSymTab->getParent()->sectionIndex;
3096ece8a530Spatrick }
3097ece8a530Spatrick 
getSize() const3098ece8a530Spatrick size_t VersionTableSection::getSize() const {
3099ece8a530Spatrick   return (getPartition().dynSymTab->getSymbols().size() + 1) * 2;
3100ece8a530Spatrick }
3101ece8a530Spatrick 
writeTo(uint8_t * buf)3102ece8a530Spatrick void VersionTableSection::writeTo(uint8_t *buf) {
3103ece8a530Spatrick   buf += 2;
3104ece8a530Spatrick   for (const SymbolTableEntry &s : getPartition().dynSymTab->getSymbols()) {
310505edf1c1Srobert     // For an unextracted lazy symbol (undefined weak), it must have been
310605edf1c1Srobert     // converted to Undefined and have VER_NDX_GLOBAL version here.
310705edf1c1Srobert     assert(!s.sym->isLazy());
310805edf1c1Srobert     write16(buf, s.sym->versionId);
3109ece8a530Spatrick     buf += 2;
3110ece8a530Spatrick   }
3111ece8a530Spatrick }
3112ece8a530Spatrick 
isNeeded() const3113ece8a530Spatrick bool VersionTableSection::isNeeded() const {
3114ece8a530Spatrick   return isLive() &&
3115ece8a530Spatrick          (getPartition().verDef || getPartition().verNeed->isNeeded());
3116ece8a530Spatrick }
3117ece8a530Spatrick 
addVerneed(Symbol * ss)3118adae0cfdSpatrick void elf::addVerneed(Symbol *ss) {
3119ece8a530Spatrick   auto &file = cast<SharedFile>(*ss->file);
3120ece8a530Spatrick   if (ss->verdefIndex == VER_NDX_GLOBAL) {
3121ece8a530Spatrick     ss->versionId = VER_NDX_GLOBAL;
3122ece8a530Spatrick     return;
3123ece8a530Spatrick   }
3124ece8a530Spatrick 
3125ece8a530Spatrick   if (file.vernauxs.empty())
3126ece8a530Spatrick     file.vernauxs.resize(file.verdefs.size());
3127ece8a530Spatrick 
3128ece8a530Spatrick   // Select a version identifier for the vernaux data structure, if we haven't
3129ece8a530Spatrick   // already allocated one. The verdef identifiers cover the range
3130ece8a530Spatrick   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
3131ece8a530Spatrick   // getVerDefNum()+1.
3132ece8a530Spatrick   if (file.vernauxs[ss->verdefIndex] == 0)
3133ece8a530Spatrick     file.vernauxs[ss->verdefIndex] = ++SharedFile::vernauxNum + getVerDefNum();
3134ece8a530Spatrick 
3135ece8a530Spatrick   ss->versionId = file.vernauxs[ss->verdefIndex];
3136ece8a530Spatrick }
3137ece8a530Spatrick 
3138ece8a530Spatrick template <class ELFT>
VersionNeedSection()3139ece8a530Spatrick VersionNeedSection<ELFT>::VersionNeedSection()
3140ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
3141ece8a530Spatrick                        ".gnu.version_r") {}
3142ece8a530Spatrick 
finalizeContents()3143ece8a530Spatrick template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
314405edf1c1Srobert   for (SharedFile *f : ctx.sharedFiles) {
3145ece8a530Spatrick     if (f->vernauxs.empty())
3146ece8a530Spatrick       continue;
3147ece8a530Spatrick     verneeds.emplace_back();
3148ece8a530Spatrick     Verneed &vn = verneeds.back();
3149ece8a530Spatrick     vn.nameStrTab = getPartition().dynStrTab->addString(f->soName);
315005edf1c1Srobert     bool isLibc = config->relrGlibc && f->soName.startswith("libc.so.");
315105edf1c1Srobert     bool isGlibc2 = false;
3152ece8a530Spatrick     for (unsigned i = 0; i != f->vernauxs.size(); ++i) {
3153ece8a530Spatrick       if (f->vernauxs[i] == 0)
3154ece8a530Spatrick         continue;
3155ece8a530Spatrick       auto *verdef =
3156ece8a530Spatrick           reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
315705edf1c1Srobert       StringRef ver(f->getStringTable().data() + verdef->getAux()->vda_name);
315805edf1c1Srobert       if (isLibc && ver.startswith("GLIBC_2."))
315905edf1c1Srobert         isGlibc2 = true;
316005edf1c1Srobert       vn.vernauxs.push_back({verdef->vd_hash, f->vernauxs[i],
316105edf1c1Srobert                              getPartition().dynStrTab->addString(ver)});
316205edf1c1Srobert     }
316305edf1c1Srobert     if (isGlibc2) {
316405edf1c1Srobert       const char *ver = "GLIBC_ABI_DT_RELR";
316505edf1c1Srobert       vn.vernauxs.push_back({hashSysV(ver),
316605edf1c1Srobert                              ++SharedFile::vernauxNum + getVerDefNum(),
316705edf1c1Srobert                              getPartition().dynStrTab->addString(ver)});
3168ece8a530Spatrick     }
3169ece8a530Spatrick   }
3170ece8a530Spatrick 
3171ece8a530Spatrick   if (OutputSection *sec = getPartition().dynStrTab->getParent())
3172ece8a530Spatrick     getParent()->link = sec->sectionIndex;
3173ece8a530Spatrick   getParent()->info = verneeds.size();
3174ece8a530Spatrick }
3175ece8a530Spatrick 
writeTo(uint8_t * buf)3176ece8a530Spatrick template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
3177ece8a530Spatrick   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
3178ece8a530Spatrick   auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
3179ece8a530Spatrick   auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
3180ece8a530Spatrick 
3181ece8a530Spatrick   for (auto &vn : verneeds) {
3182ece8a530Spatrick     // Create an Elf_Verneed for this DSO.
3183ece8a530Spatrick     verneed->vn_version = 1;
3184ece8a530Spatrick     verneed->vn_cnt = vn.vernauxs.size();
3185ece8a530Spatrick     verneed->vn_file = vn.nameStrTab;
3186ece8a530Spatrick     verneed->vn_aux =
3187ece8a530Spatrick         reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
3188ece8a530Spatrick     verneed->vn_next = sizeof(Elf_Verneed);
3189ece8a530Spatrick     ++verneed;
3190ece8a530Spatrick 
3191ece8a530Spatrick     // Create the Elf_Vernauxs for this Elf_Verneed.
3192ece8a530Spatrick     for (auto &vna : vn.vernauxs) {
3193ece8a530Spatrick       vernaux->vna_hash = vna.hash;
3194ece8a530Spatrick       vernaux->vna_flags = 0;
3195ece8a530Spatrick       vernaux->vna_other = vna.verneedIndex;
3196ece8a530Spatrick       vernaux->vna_name = vna.nameStrTab;
3197ece8a530Spatrick       vernaux->vna_next = sizeof(Elf_Vernaux);
3198ece8a530Spatrick       ++vernaux;
3199ece8a530Spatrick     }
3200ece8a530Spatrick 
3201ece8a530Spatrick     vernaux[-1].vna_next = 0;
3202ece8a530Spatrick   }
3203ece8a530Spatrick   verneed[-1].vn_next = 0;
3204ece8a530Spatrick }
3205ece8a530Spatrick 
getSize() const3206ece8a530Spatrick template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
3207ece8a530Spatrick   return verneeds.size() * sizeof(Elf_Verneed) +
3208ece8a530Spatrick          SharedFile::vernauxNum * sizeof(Elf_Vernaux);
3209ece8a530Spatrick }
3210ece8a530Spatrick 
isNeeded() const3211ece8a530Spatrick template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
3212ece8a530Spatrick   return isLive() && SharedFile::vernauxNum != 0;
3213ece8a530Spatrick }
3214ece8a530Spatrick 
addSection(MergeInputSection * ms)3215ece8a530Spatrick void MergeSyntheticSection::addSection(MergeInputSection *ms) {
3216ece8a530Spatrick   ms->parent = this;
3217ece8a530Spatrick   sections.push_back(ms);
321805edf1c1Srobert   assert(addralign == ms->addralign || !(ms->flags & SHF_STRINGS));
321905edf1c1Srobert   addralign = std::max(addralign, ms->addralign);
3220ece8a530Spatrick }
3221ece8a530Spatrick 
MergeTailSection(StringRef name,uint32_t type,uint64_t flags,uint32_t alignment)3222ece8a530Spatrick MergeTailSection::MergeTailSection(StringRef name, uint32_t type,
3223ece8a530Spatrick                                    uint64_t flags, uint32_t alignment)
3224ece8a530Spatrick     : MergeSyntheticSection(name, type, flags, alignment),
322505edf1c1Srobert       builder(StringTableBuilder::RAW, llvm::Align(alignment)) {}
3226ece8a530Spatrick 
getSize() const3227ece8a530Spatrick size_t MergeTailSection::getSize() const { return builder.getSize(); }
3228ece8a530Spatrick 
writeTo(uint8_t * buf)3229ece8a530Spatrick void MergeTailSection::writeTo(uint8_t *buf) { builder.write(buf); }
3230ece8a530Spatrick 
finalizeContents()3231ece8a530Spatrick void MergeTailSection::finalizeContents() {
3232ece8a530Spatrick   // Add all string pieces to the string table builder to create section
3233ece8a530Spatrick   // contents.
3234ece8a530Spatrick   for (MergeInputSection *sec : sections)
3235ece8a530Spatrick     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3236ece8a530Spatrick       if (sec->pieces[i].live)
3237ece8a530Spatrick         builder.add(sec->getData(i));
3238ece8a530Spatrick 
3239ece8a530Spatrick   // Fix the string table content. After this, the contents will never change.
3240ece8a530Spatrick   builder.finalize();
3241ece8a530Spatrick 
3242ece8a530Spatrick   // finalize() fixed tail-optimized strings, so we can now get
3243ece8a530Spatrick   // offsets of strings. Get an offset for each string and save it
3244ece8a530Spatrick   // to a corresponding SectionPiece for easy access.
3245ece8a530Spatrick   for (MergeInputSection *sec : sections)
3246ece8a530Spatrick     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3247ece8a530Spatrick       if (sec->pieces[i].live)
3248ece8a530Spatrick         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
3249ece8a530Spatrick }
3250ece8a530Spatrick 
writeTo(uint8_t * buf)3251ece8a530Spatrick void MergeNoTailSection::writeTo(uint8_t *buf) {
325205edf1c1Srobert   parallelFor(0, numShards,
325305edf1c1Srobert               [&](size_t i) { shards[i].write(buf + shardOffsets[i]); });
3254ece8a530Spatrick }
3255ece8a530Spatrick 
3256ece8a530Spatrick // This function is very hot (i.e. it can take several seconds to finish)
3257ece8a530Spatrick // because sometimes the number of inputs is in an order of magnitude of
3258ece8a530Spatrick // millions. So, we use multi-threading.
3259ece8a530Spatrick //
3260ece8a530Spatrick // For any strings S and T, we know S is not mergeable with T if S's hash
3261ece8a530Spatrick // value is different from T's. If that's the case, we can safely put S and
3262ece8a530Spatrick // T into different string builders without worrying about merge misses.
3263ece8a530Spatrick // We do it in parallel.
finalizeContents()3264ece8a530Spatrick void MergeNoTailSection::finalizeContents() {
3265ece8a530Spatrick   // Initializes string table builders.
3266ece8a530Spatrick   for (size_t i = 0; i < numShards; ++i)
326705edf1c1Srobert     shards.emplace_back(StringTableBuilder::RAW, llvm::Align(addralign));
3268ece8a530Spatrick 
3269ece8a530Spatrick   // Concurrency level. Must be a power of 2 to avoid expensive modulo
3270ece8a530Spatrick   // operations in the following tight loop.
327105edf1c1Srobert   const size_t concurrency =
327205edf1c1Srobert       PowerOf2Floor(std::min<size_t>(config->threadCount, numShards));
3273ece8a530Spatrick 
3274ece8a530Spatrick   // Add section pieces to the builders.
327505edf1c1Srobert   parallelFor(0, concurrency, [&](size_t threadId) {
3276ece8a530Spatrick     for (MergeInputSection *sec : sections) {
3277ece8a530Spatrick       for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
3278ece8a530Spatrick         if (!sec->pieces[i].live)
3279ece8a530Spatrick           continue;
3280ece8a530Spatrick         size_t shardId = getShardId(sec->pieces[i].hash);
3281ece8a530Spatrick         if ((shardId & (concurrency - 1)) == threadId)
3282ece8a530Spatrick           sec->pieces[i].outputOff = shards[shardId].add(sec->getData(i));
3283ece8a530Spatrick       }
3284ece8a530Spatrick     }
3285ece8a530Spatrick   });
3286ece8a530Spatrick 
3287ece8a530Spatrick   // Compute an in-section offset for each shard.
3288ece8a530Spatrick   size_t off = 0;
3289ece8a530Spatrick   for (size_t i = 0; i < numShards; ++i) {
3290ece8a530Spatrick     shards[i].finalizeInOrder();
3291ece8a530Spatrick     if (shards[i].getSize() > 0)
329205edf1c1Srobert       off = alignToPowerOf2(off, addralign);
3293ece8a530Spatrick     shardOffsets[i] = off;
3294ece8a530Spatrick     off += shards[i].getSize();
3295ece8a530Spatrick   }
3296ece8a530Spatrick   size = off;
3297ece8a530Spatrick 
3298ece8a530Spatrick   // So far, section pieces have offsets from beginning of shards, but
3299ece8a530Spatrick   // we want offsets from beginning of the whole section. Fix them.
3300ece8a530Spatrick   parallelForEach(sections, [&](MergeInputSection *sec) {
3301ece8a530Spatrick     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3302ece8a530Spatrick       if (sec->pieces[i].live)
3303ece8a530Spatrick         sec->pieces[i].outputOff +=
3304ece8a530Spatrick             shardOffsets[getShardId(sec->pieces[i].hash)];
3305ece8a530Spatrick   });
3306ece8a530Spatrick }
3307ece8a530Spatrick 
splitSections()3308adae0cfdSpatrick template <class ELFT> void elf::splitSections() {
3309adae0cfdSpatrick   llvm::TimeTraceScope timeScope("Split sections");
3310ece8a530Spatrick   // splitIntoPieces needs to be called on each MergeInputSection
3311ece8a530Spatrick   // before calling finalizeContents().
331205edf1c1Srobert   parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
331305edf1c1Srobert     for (InputSectionBase *sec : file->getSections()) {
331405edf1c1Srobert       if (!sec)
331505edf1c1Srobert         continue;
3316ece8a530Spatrick       if (auto *s = dyn_cast<MergeInputSection>(sec))
3317ece8a530Spatrick         s->splitIntoPieces();
3318ece8a530Spatrick       else if (auto *eh = dyn_cast<EhInputSection>(sec))
3319ece8a530Spatrick         eh->split<ELFT>();
332005edf1c1Srobert     }
332105edf1c1Srobert   });
332205edf1c1Srobert }
332305edf1c1Srobert 
combineEhSections()332405edf1c1Srobert void elf::combineEhSections() {
332505edf1c1Srobert   llvm::TimeTraceScope timeScope("Combine EH sections");
332605edf1c1Srobert   for (EhInputSection *sec : ctx.ehInputSections) {
332705edf1c1Srobert     EhFrameSection &eh = *sec->getPartition().ehFrame;
332805edf1c1Srobert     sec->parent = &eh;
332905edf1c1Srobert     eh.addralign = std::max(eh.addralign, sec->addralign);
333005edf1c1Srobert     eh.sections.push_back(sec);
333105edf1c1Srobert     llvm::append_range(eh.dependentSections, sec->dependentSections);
333205edf1c1Srobert   }
333305edf1c1Srobert 
333405edf1c1Srobert   if (!mainPart->armExidx)
333505edf1c1Srobert     return;
333605edf1c1Srobert   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
333705edf1c1Srobert     // Ignore dead sections and the partition end marker (.part.end),
333805edf1c1Srobert     // whose partition number is out of bounds.
333905edf1c1Srobert     if (!s->isLive() || s->partition == 255)
334005edf1c1Srobert       return false;
334105edf1c1Srobert     Partition &part = s->getPartition();
334205edf1c1Srobert     return s->kind() == SectionBase::Regular && part.armExidx &&
334305edf1c1Srobert            part.armExidx->addSection(cast<InputSection>(s));
3344ece8a530Spatrick   });
3345ece8a530Spatrick }
3346ece8a530Spatrick 
MipsRldMapSection()3347ece8a530Spatrick MipsRldMapSection::MipsRldMapSection()
3348ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
3349ece8a530Spatrick                        ".rld_map") {}
3350ece8a530Spatrick 
ARMExidxSyntheticSection()3351ece8a530Spatrick ARMExidxSyntheticSection::ARMExidxSyntheticSection()
3352ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
3353ece8a530Spatrick                        config->wordsize, ".ARM.exidx") {}
3354ece8a530Spatrick 
findExidxSection(InputSection * isec)3355ece8a530Spatrick static InputSection *findExidxSection(InputSection *isec) {
3356ece8a530Spatrick   for (InputSection *d : isec->dependentSections)
3357adae0cfdSpatrick     if (d->type == SHT_ARM_EXIDX && d->isLive())
3358ece8a530Spatrick       return d;
3359ece8a530Spatrick   return nullptr;
3360ece8a530Spatrick }
3361ece8a530Spatrick 
isValidExidxSectionDep(InputSection * isec)3362ece8a530Spatrick static bool isValidExidxSectionDep(InputSection *isec) {
3363ece8a530Spatrick   return (isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
3364ece8a530Spatrick          isec->getSize() > 0;
3365ece8a530Spatrick }
3366ece8a530Spatrick 
addSection(InputSection * isec)3367ece8a530Spatrick bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
3368ece8a530Spatrick   if (isec->type == SHT_ARM_EXIDX) {
3369ece8a530Spatrick     if (InputSection *dep = isec->getLinkOrderDep())
3370adae0cfdSpatrick       if (isValidExidxSectionDep(dep)) {
3371ece8a530Spatrick         exidxSections.push_back(isec);
3372adae0cfdSpatrick         // Every exidxSection is 8 bytes, we need an estimate of
3373adae0cfdSpatrick         // size before assignAddresses can be called. Final size
3374adae0cfdSpatrick         // will only be known after finalize is called.
3375adae0cfdSpatrick         size += 8;
3376adae0cfdSpatrick       }
3377ece8a530Spatrick     return true;
3378ece8a530Spatrick   }
3379ece8a530Spatrick 
3380ece8a530Spatrick   if (isValidExidxSectionDep(isec)) {
3381ece8a530Spatrick     executableSections.push_back(isec);
3382ece8a530Spatrick     return false;
3383ece8a530Spatrick   }
3384ece8a530Spatrick 
3385ece8a530Spatrick   // FIXME: we do not output a relocation section when --emit-relocs is used
3386ece8a530Spatrick   // as we do not have relocation sections for linker generated table entries
3387ece8a530Spatrick   // and we would have to erase at a late stage relocations from merged entries.
3388ece8a530Spatrick   // Given that exception tables are already position independent and a binary
3389ece8a530Spatrick   // analyzer could derive the relocations we choose to erase the relocations.
3390ece8a530Spatrick   if (config->emitRelocs && isec->type == SHT_REL)
3391ece8a530Spatrick     if (InputSectionBase *ex = isec->getRelocatedSection())
3392ece8a530Spatrick       if (isa<InputSection>(ex) && ex->type == SHT_ARM_EXIDX)
3393ece8a530Spatrick         return true;
3394ece8a530Spatrick 
3395ece8a530Spatrick   return false;
3396ece8a530Spatrick }
3397ece8a530Spatrick 
3398ece8a530Spatrick // References to .ARM.Extab Sections have bit 31 clear and are not the
3399ece8a530Spatrick // special EXIDX_CANTUNWIND bit-pattern.
isExtabRef(uint32_t unwind)3400ece8a530Spatrick static bool isExtabRef(uint32_t unwind) {
3401ece8a530Spatrick   return (unwind & 0x80000000) == 0 && unwind != 0x1;
3402ece8a530Spatrick }
3403ece8a530Spatrick 
3404ece8a530Spatrick // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
3405ece8a530Spatrick // section Prev, where Cur follows Prev in the table. This can be done if the
3406ece8a530Spatrick // unwinding instructions in Cur are identical to Prev. Linker generated
3407ece8a530Spatrick // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
3408ece8a530Spatrick // InputSection.
isDuplicateArmExidxSec(InputSection * prev,InputSection * cur)3409ece8a530Spatrick static bool isDuplicateArmExidxSec(InputSection *prev, InputSection *cur) {
3410ece8a530Spatrick 
3411ece8a530Spatrick   struct ExidxEntry {
3412ece8a530Spatrick     ulittle32_t fn;
3413ece8a530Spatrick     ulittle32_t unwind;
3414ece8a530Spatrick   };
3415ece8a530Spatrick   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
3416ece8a530Spatrick   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
3417ece8a530Spatrick   ExidxEntry prevEntry = {ulittle32_t(0), ulittle32_t(1)};
3418ece8a530Spatrick   if (prev)
3419ece8a530Spatrick     prevEntry = prev->getDataAs<ExidxEntry>().back();
3420ece8a530Spatrick   if (isExtabRef(prevEntry.unwind))
3421ece8a530Spatrick     return false;
3422ece8a530Spatrick 
3423ece8a530Spatrick   // We consider the unwind instructions of an .ARM.exidx table entry
3424ece8a530Spatrick   // a duplicate if the previous unwind instructions if:
3425ece8a530Spatrick   // - Both are the special EXIDX_CANTUNWIND.
3426ece8a530Spatrick   // - Both are the same inline unwind instructions.
3427ece8a530Spatrick   // We do not attempt to follow and check links into .ARM.extab tables as
3428ece8a530Spatrick   // consecutive identical entries are rare and the effort to check that they
3429ece8a530Spatrick   // are identical is high.
3430ece8a530Spatrick 
3431ece8a530Spatrick   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
3432ece8a530Spatrick   if (cur == nullptr)
3433ece8a530Spatrick     return prevEntry.unwind == 1;
3434ece8a530Spatrick 
3435ece8a530Spatrick   for (const ExidxEntry entry : cur->getDataAs<ExidxEntry>())
3436ece8a530Spatrick     if (isExtabRef(entry.unwind) || entry.unwind != prevEntry.unwind)
3437ece8a530Spatrick       return false;
3438ece8a530Spatrick 
3439ece8a530Spatrick   // All table entries in this .ARM.exidx Section can be merged into the
3440ece8a530Spatrick   // previous Section.
3441ece8a530Spatrick   return true;
3442ece8a530Spatrick }
3443ece8a530Spatrick 
3444ece8a530Spatrick // The .ARM.exidx table must be sorted in ascending order of the address of the
344505edf1c1Srobert // functions the table describes. std::optionally duplicate adjacent table
344605edf1c1Srobert // entries can be removed. At the end of the function the executableSections
344705edf1c1Srobert // must be sorted in ascending order of address, Sentinel is set to the
344805edf1c1Srobert // InputSection with the highest address and any InputSections that have
344905edf1c1Srobert // mergeable .ARM.exidx table entries are removed from it.
finalizeContents()3450ece8a530Spatrick void ARMExidxSyntheticSection::finalizeContents() {
3451ece8a530Spatrick   // The executableSections and exidxSections that we use to derive the final
3452ece8a530Spatrick   // contents of this SyntheticSection are populated before
3453ece8a530Spatrick   // processSectionCommands() and ICF. A /DISCARD/ entry in SECTIONS command or
3454ece8a530Spatrick   // ICF may remove executable InputSections and their dependent .ARM.exidx
3455ece8a530Spatrick   // section that we recorded earlier.
3456ece8a530Spatrick   auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
3457ece8a530Spatrick   llvm::erase_if(exidxSections, isDiscarded);
3458adae0cfdSpatrick   // We need to remove discarded InputSections and InputSections without
3459adae0cfdSpatrick   // .ARM.exidx sections that if we generated the .ARM.exidx it would be out
3460adae0cfdSpatrick   // of range.
3461adae0cfdSpatrick   auto isDiscardedOrOutOfRange = [this](InputSection *isec) {
3462adae0cfdSpatrick     if (!isec->isLive())
3463adae0cfdSpatrick       return true;
3464adae0cfdSpatrick     if (findExidxSection(isec))
3465adae0cfdSpatrick       return false;
3466adae0cfdSpatrick     int64_t off = static_cast<int64_t>(isec->getVA() - getVA());
3467adae0cfdSpatrick     return off != llvm::SignExtend64(off, 31);
3468adae0cfdSpatrick   };
3469adae0cfdSpatrick   llvm::erase_if(executableSections, isDiscardedOrOutOfRange);
3470ece8a530Spatrick 
3471ece8a530Spatrick   // Sort the executable sections that may or may not have associated
3472ece8a530Spatrick   // .ARM.exidx sections by order of ascending address. This requires the
3473adae0cfdSpatrick   // relative positions of InputSections and OutputSections to be known.
3474ece8a530Spatrick   auto compareByFilePosition = [](const InputSection *a,
3475ece8a530Spatrick                                   const InputSection *b) {
3476ece8a530Spatrick     OutputSection *aOut = a->getParent();
3477ece8a530Spatrick     OutputSection *bOut = b->getParent();
3478ece8a530Spatrick 
3479ece8a530Spatrick     if (aOut != bOut)
3480adae0cfdSpatrick       return aOut->addr < bOut->addr;
3481ece8a530Spatrick     return a->outSecOff < b->outSecOff;
3482ece8a530Spatrick   };
3483ece8a530Spatrick   llvm::stable_sort(executableSections, compareByFilePosition);
3484ece8a530Spatrick   sentinel = executableSections.back();
348505edf1c1Srobert   // std::optionally merge adjacent duplicate entries.
3486ece8a530Spatrick   if (config->mergeArmExidx) {
348705edf1c1Srobert     SmallVector<InputSection *, 0> selectedSections;
3488ece8a530Spatrick     selectedSections.reserve(executableSections.size());
3489ece8a530Spatrick     selectedSections.push_back(executableSections[0]);
3490ece8a530Spatrick     size_t prev = 0;
3491ece8a530Spatrick     for (size_t i = 1; i < executableSections.size(); ++i) {
3492ece8a530Spatrick       InputSection *ex1 = findExidxSection(executableSections[prev]);
3493ece8a530Spatrick       InputSection *ex2 = findExidxSection(executableSections[i]);
3494ece8a530Spatrick       if (!isDuplicateArmExidxSec(ex1, ex2)) {
3495ece8a530Spatrick         selectedSections.push_back(executableSections[i]);
3496ece8a530Spatrick         prev = i;
3497ece8a530Spatrick       }
3498ece8a530Spatrick     }
3499ece8a530Spatrick     executableSections = std::move(selectedSections);
3500ece8a530Spatrick   }
3501ece8a530Spatrick 
3502ece8a530Spatrick   size_t offset = 0;
3503ece8a530Spatrick   size = 0;
3504ece8a530Spatrick   for (InputSection *isec : executableSections) {
3505ece8a530Spatrick     if (InputSection *d = findExidxSection(isec)) {
3506ece8a530Spatrick       d->outSecOff = offset;
3507ece8a530Spatrick       d->parent = getParent();
3508ece8a530Spatrick       offset += d->getSize();
3509ece8a530Spatrick     } else {
3510ece8a530Spatrick       offset += 8;
3511ece8a530Spatrick     }
3512ece8a530Spatrick   }
3513ece8a530Spatrick   // Size includes Sentinel.
3514ece8a530Spatrick   size = offset + 8;
3515ece8a530Spatrick }
3516ece8a530Spatrick 
getLinkOrderDep() const3517ece8a530Spatrick InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
3518ece8a530Spatrick   return executableSections.front();
3519ece8a530Spatrick }
3520ece8a530Spatrick 
3521ece8a530Spatrick // To write the .ARM.exidx table from the ExecutableSections we have three cases
3522ece8a530Spatrick // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
3523ece8a530Spatrick //     We write the .ARM.exidx section contents and apply its relocations.
3524ece8a530Spatrick // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
3525ece8a530Spatrick //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
3526ece8a530Spatrick //     start of the InputSection as the purpose of the linker generated
3527ece8a530Spatrick //     section is to terminate the address range of the previous entry.
3528ece8a530Spatrick // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
3529ece8a530Spatrick //     the table to terminate the address range of the final entry.
writeTo(uint8_t * buf)3530ece8a530Spatrick void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
3531ece8a530Spatrick 
3532ece8a530Spatrick   const uint8_t cantUnwindData[8] = {0, 0, 0, 0,  // PREL31 to target
3533ece8a530Spatrick                                      1, 0, 0, 0}; // EXIDX_CANTUNWIND
3534ece8a530Spatrick 
3535ece8a530Spatrick   uint64_t offset = 0;
3536ece8a530Spatrick   for (InputSection *isec : executableSections) {
3537ece8a530Spatrick     assert(isec->getParent() != nullptr);
3538ece8a530Spatrick     if (InputSection *d = findExidxSection(isec)) {
353905edf1c1Srobert       memcpy(buf + offset, d->content().data(), d->content().size());
354005edf1c1Srobert       target->relocateAlloc(*d, buf + d->outSecOff);
3541ece8a530Spatrick       offset += d->getSize();
3542ece8a530Spatrick     } else {
3543ece8a530Spatrick       // A Linker generated CANTUNWIND section.
3544ece8a530Spatrick       memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3545ece8a530Spatrick       uint64_t s = isec->getVA();
3546ece8a530Spatrick       uint64_t p = getVA() + offset;
3547adae0cfdSpatrick       target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3548ece8a530Spatrick       offset += 8;
3549ece8a530Spatrick     }
3550ece8a530Spatrick   }
3551ece8a530Spatrick   // Write Sentinel.
3552ece8a530Spatrick   memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3553ece8a530Spatrick   uint64_t s = sentinel->getVA(sentinel->getSize());
3554ece8a530Spatrick   uint64_t p = getVA() + offset;
3555adae0cfdSpatrick   target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3556ece8a530Spatrick   assert(size == offset + 8);
3557ece8a530Spatrick }
3558ece8a530Spatrick 
isNeeded() const3559ece8a530Spatrick bool ARMExidxSyntheticSection::isNeeded() const {
356005edf1c1Srobert   return llvm::any_of(exidxSections,
356105edf1c1Srobert                       [](InputSection *isec) { return isec->isLive(); });
3562ece8a530Spatrick }
3563ece8a530Spatrick 
ThunkSection(OutputSection * os,uint64_t off)3564ece8a530Spatrick ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
3565a0747c9fSpatrick     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
3566a0747c9fSpatrick                        config->emachine == EM_PPC64 ? 16 : 4, ".text.thunk") {
3567ece8a530Spatrick   this->parent = os;
3568ece8a530Spatrick   this->outSecOff = off;
3569ece8a530Spatrick }
3570ece8a530Spatrick 
getSize() const3571ece8a530Spatrick size_t ThunkSection::getSize() const {
3572ece8a530Spatrick   if (roundUpSizeForErrata)
3573ece8a530Spatrick     return alignTo(size, 4096);
3574ece8a530Spatrick   return size;
3575ece8a530Spatrick }
3576ece8a530Spatrick 
addThunk(Thunk * t)3577ece8a530Spatrick void ThunkSection::addThunk(Thunk *t) {
3578ece8a530Spatrick   thunks.push_back(t);
3579ece8a530Spatrick   t->addSymbols(*this);
3580ece8a530Spatrick }
3581ece8a530Spatrick 
writeTo(uint8_t * buf)3582ece8a530Spatrick void ThunkSection::writeTo(uint8_t *buf) {
3583ece8a530Spatrick   for (Thunk *t : thunks)
3584ece8a530Spatrick     t->writeTo(buf + t->offset);
3585ece8a530Spatrick }
3586ece8a530Spatrick 
getTargetInputSection() const3587ece8a530Spatrick InputSection *ThunkSection::getTargetInputSection() const {
3588ece8a530Spatrick   if (thunks.empty())
3589ece8a530Spatrick     return nullptr;
3590ece8a530Spatrick   const Thunk *t = thunks.front();
3591ece8a530Spatrick   return t->getTargetInputSection();
3592ece8a530Spatrick }
3593ece8a530Spatrick 
assignOffsets()3594ece8a530Spatrick bool ThunkSection::assignOffsets() {
3595ece8a530Spatrick   uint64_t off = 0;
3596ece8a530Spatrick   for (Thunk *t : thunks) {
359705edf1c1Srobert     off = alignToPowerOf2(off, t->alignment);
3598ece8a530Spatrick     t->setOffset(off);
3599ece8a530Spatrick     uint32_t size = t->size();
3600ece8a530Spatrick     t->getThunkTargetSym()->size = size;
3601ece8a530Spatrick     off += size;
3602ece8a530Spatrick   }
3603ece8a530Spatrick   bool changed = off != size;
3604ece8a530Spatrick   size = off;
3605ece8a530Spatrick   return changed;
3606ece8a530Spatrick }
3607ece8a530Spatrick 
PPC32Got2Section()3608ece8a530Spatrick PPC32Got2Section::PPC32Got2Section()
3609ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
3610ece8a530Spatrick 
isNeeded() const3611ece8a530Spatrick bool PPC32Got2Section::isNeeded() const {
3612ece8a530Spatrick   // See the comment below. This is not needed if there is no other
3613ece8a530Spatrick   // InputSection.
361405edf1c1Srobert   for (SectionCommand *cmd : getParent()->commands)
361505edf1c1Srobert     if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
3616ece8a530Spatrick       for (InputSection *isec : isd->sections)
3617ece8a530Spatrick         if (isec != this)
3618ece8a530Spatrick           return true;
3619ece8a530Spatrick   return false;
3620ece8a530Spatrick }
3621ece8a530Spatrick 
finalizeContents()3622ece8a530Spatrick void PPC32Got2Section::finalizeContents() {
3623ece8a530Spatrick   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
3624ece8a530Spatrick   // .got2 . This function computes outSecOff of each .got2 to be used in
3625ece8a530Spatrick   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
3626ece8a530Spatrick   // to collect input sections named ".got2".
362705edf1c1Srobert   for (SectionCommand *cmd : getParent()->commands)
362805edf1c1Srobert     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
3629ece8a530Spatrick       for (InputSection *isec : isd->sections) {
363005edf1c1Srobert         // isec->file may be nullptr for MergeSyntheticSection.
363105edf1c1Srobert         if (isec != this && isec->file)
363205edf1c1Srobert           isec->file->ppc32Got2 = isec;
3633ece8a530Spatrick       }
3634ece8a530Spatrick     }
3635ece8a530Spatrick }
3636ece8a530Spatrick 
3637ece8a530Spatrick // If linking position-dependent code then the table will store the addresses
3638ece8a530Spatrick // directly in the binary so the section has type SHT_PROGBITS. If linking
3639ece8a530Spatrick // position-independent code the section has type SHT_NOBITS since it will be
3640ece8a530Spatrick // allocated and filled in by the dynamic linker.
PPC64LongBranchTargetSection()3641ece8a530Spatrick PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
3642ece8a530Spatrick     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
3643ece8a530Spatrick                        config->isPic ? SHT_NOBITS : SHT_PROGBITS, 8,
3644ece8a530Spatrick                        ".branch_lt") {}
3645ece8a530Spatrick 
getEntryVA(const Symbol * sym,int64_t addend)3646ece8a530Spatrick uint64_t PPC64LongBranchTargetSection::getEntryVA(const Symbol *sym,
3647ece8a530Spatrick                                                   int64_t addend) {
3648ece8a530Spatrick   return getVA() + entry_index.find({sym, addend})->second * 8;
3649ece8a530Spatrick }
3650ece8a530Spatrick 
365105edf1c1Srobert std::optional<uint32_t>
addEntry(const Symbol * sym,int64_t addend)365205edf1c1Srobert PPC64LongBranchTargetSection::addEntry(const Symbol *sym, int64_t addend) {
3653ece8a530Spatrick   auto res =
3654ece8a530Spatrick       entry_index.try_emplace(std::make_pair(sym, addend), entries.size());
3655ece8a530Spatrick   if (!res.second)
365605edf1c1Srobert     return std::nullopt;
3657ece8a530Spatrick   entries.emplace_back(sym, addend);
3658ece8a530Spatrick   return res.first->second;
3659ece8a530Spatrick }
3660ece8a530Spatrick 
getSize() const3661ece8a530Spatrick size_t PPC64LongBranchTargetSection::getSize() const {
3662ece8a530Spatrick   return entries.size() * 8;
3663ece8a530Spatrick }
3664ece8a530Spatrick 
writeTo(uint8_t * buf)3665ece8a530Spatrick void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
3666ece8a530Spatrick   // If linking non-pic we have the final addresses of the targets and they get
3667ece8a530Spatrick   // written to the table directly. For pic the dynamic linker will allocate
366805edf1c1Srobert   // the section and fill it.
3669ece8a530Spatrick   if (config->isPic)
3670ece8a530Spatrick     return;
3671ece8a530Spatrick 
3672ece8a530Spatrick   for (auto entry : entries) {
3673ece8a530Spatrick     const Symbol *sym = entry.first;
3674ece8a530Spatrick     int64_t addend = entry.second;
3675ece8a530Spatrick     assert(sym->getVA());
3676ece8a530Spatrick     // Need calls to branch to the local entry-point since a long-branch
3677ece8a530Spatrick     // must be a local-call.
3678ece8a530Spatrick     write64(buf, sym->getVA(addend) +
3679ece8a530Spatrick                      getPPC64GlobalEntryToLocalEntryOffset(sym->stOther));
3680ece8a530Spatrick     buf += 8;
3681ece8a530Spatrick   }
3682ece8a530Spatrick }
3683ece8a530Spatrick 
isNeeded() const3684ece8a530Spatrick bool PPC64LongBranchTargetSection::isNeeded() const {
3685ece8a530Spatrick   // `removeUnusedSyntheticSections()` is called before thunk allocation which
3686ece8a530Spatrick   // is too early to determine if this section will be empty or not. We need
3687ece8a530Spatrick   // Finalized to keep the section alive until after thunk creation. Finalized
3688ece8a530Spatrick   // only gets set to true once `finalizeSections()` is called after thunk
3689ece8a530Spatrick   // creation. Because of this, if we don't create any long-branch thunks we end
3690ece8a530Spatrick   // up with an empty .branch_lt section in the binary.
3691ece8a530Spatrick   return !finalized || !entries.empty();
3692ece8a530Spatrick }
3693ece8a530Spatrick 
getAbiVersion()3694ece8a530Spatrick static uint8_t getAbiVersion() {
3695ece8a530Spatrick   // MIPS non-PIC executable gets ABI version 1.
3696ece8a530Spatrick   if (config->emachine == EM_MIPS) {
3697ece8a530Spatrick     if (!config->isPic && !config->relocatable &&
3698ece8a530Spatrick         (config->eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
3699ece8a530Spatrick       return 1;
3700ece8a530Spatrick     return 0;
3701ece8a530Spatrick   }
3702ece8a530Spatrick 
370305edf1c1Srobert   if (config->emachine == EM_AMDGPU && !ctx.objectFiles.empty()) {
370405edf1c1Srobert     uint8_t ver = ctx.objectFiles[0]->abiVersion;
370505edf1c1Srobert     for (InputFile *file : ArrayRef(ctx.objectFiles).slice(1))
3706ece8a530Spatrick       if (file->abiVersion != ver)
3707ece8a530Spatrick         error("incompatible ABI version: " + toString(file));
3708ece8a530Spatrick     return ver;
3709ece8a530Spatrick   }
3710ece8a530Spatrick 
3711ece8a530Spatrick   return 0;
3712ece8a530Spatrick }
3713ece8a530Spatrick 
writeEhdr(uint8_t * buf,Partition & part)3714adae0cfdSpatrick template <typename ELFT> void elf::writeEhdr(uint8_t *buf, Partition &part) {
3715ece8a530Spatrick   memcpy(buf, "\177ELF", 4);
3716ece8a530Spatrick 
3717ece8a530Spatrick   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3718ece8a530Spatrick   eHdr->e_ident[EI_CLASS] = config->is64 ? ELFCLASS64 : ELFCLASS32;
3719ece8a530Spatrick   eHdr->e_ident[EI_DATA] = config->isLE ? ELFDATA2LSB : ELFDATA2MSB;
3720ece8a530Spatrick   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
3721ece8a530Spatrick   eHdr->e_ident[EI_OSABI] = config->osabi;
3722ece8a530Spatrick   eHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
3723ece8a530Spatrick   eHdr->e_machine = config->emachine;
3724ece8a530Spatrick   eHdr->e_version = EV_CURRENT;
3725ece8a530Spatrick   eHdr->e_flags = config->eflags;
3726ece8a530Spatrick   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
3727ece8a530Spatrick   eHdr->e_phnum = part.phdrs.size();
3728ece8a530Spatrick   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
3729ece8a530Spatrick 
3730ece8a530Spatrick   if (!config->relocatable) {
3731ece8a530Spatrick     eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
3732ece8a530Spatrick     eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
3733ece8a530Spatrick   }
3734ece8a530Spatrick }
3735ece8a530Spatrick 
writePhdrs(uint8_t * buf,Partition & part)3736adae0cfdSpatrick template <typename ELFT> void elf::writePhdrs(uint8_t *buf, Partition &part) {
3737ece8a530Spatrick   // Write the program header table.
3738ece8a530Spatrick   auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
3739ece8a530Spatrick   for (PhdrEntry *p : part.phdrs) {
3740ece8a530Spatrick     hBuf->p_type = p->p_type;
3741ece8a530Spatrick     hBuf->p_flags = p->p_flags;
3742ece8a530Spatrick     hBuf->p_offset = p->p_offset;
3743ece8a530Spatrick     hBuf->p_vaddr = p->p_vaddr;
3744ece8a530Spatrick     hBuf->p_paddr = p->p_paddr;
3745ece8a530Spatrick     hBuf->p_filesz = p->p_filesz;
3746ece8a530Spatrick     hBuf->p_memsz = p->p_memsz;
3747ece8a530Spatrick     hBuf->p_align = p->p_align;
3748ece8a530Spatrick     ++hBuf;
3749ece8a530Spatrick   }
3750ece8a530Spatrick }
3751ece8a530Spatrick 
3752ece8a530Spatrick template <typename ELFT>
PartitionElfHeaderSection()3753ece8a530Spatrick PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
3754ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
3755ece8a530Spatrick 
3756ece8a530Spatrick template <typename ELFT>
getSize() const3757ece8a530Spatrick size_t PartitionElfHeaderSection<ELFT>::getSize() const {
3758ece8a530Spatrick   return sizeof(typename ELFT::Ehdr);
3759ece8a530Spatrick }
3760ece8a530Spatrick 
3761ece8a530Spatrick template <typename ELFT>
writeTo(uint8_t * buf)3762ece8a530Spatrick void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
3763ece8a530Spatrick   writeEhdr<ELFT>(buf, getPartition());
3764ece8a530Spatrick 
3765ece8a530Spatrick   // Loadable partitions are always ET_DYN.
3766ece8a530Spatrick   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3767ece8a530Spatrick   eHdr->e_type = ET_DYN;
3768ece8a530Spatrick }
3769ece8a530Spatrick 
3770ece8a530Spatrick template <typename ELFT>
PartitionProgramHeadersSection()3771ece8a530Spatrick PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
3772ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
3773ece8a530Spatrick 
3774ece8a530Spatrick template <typename ELFT>
getSize() const3775ece8a530Spatrick size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
3776ece8a530Spatrick   return sizeof(typename ELFT::Phdr) * getPartition().phdrs.size();
3777ece8a530Spatrick }
3778ece8a530Spatrick 
3779ece8a530Spatrick template <typename ELFT>
writeTo(uint8_t * buf)3780ece8a530Spatrick void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
3781ece8a530Spatrick   writePhdrs<ELFT>(buf, getPartition());
3782ece8a530Spatrick }
3783ece8a530Spatrick 
PartitionIndexSection()3784ece8a530Spatrick PartitionIndexSection::PartitionIndexSection()
3785ece8a530Spatrick     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
3786ece8a530Spatrick 
getSize() const3787ece8a530Spatrick size_t PartitionIndexSection::getSize() const {
3788ece8a530Spatrick   return 12 * (partitions.size() - 1);
3789ece8a530Spatrick }
3790ece8a530Spatrick 
finalizeContents()3791ece8a530Spatrick void PartitionIndexSection::finalizeContents() {
3792ece8a530Spatrick   for (size_t i = 1; i != partitions.size(); ++i)
3793ece8a530Spatrick     partitions[i].nameStrTab = mainPart->dynStrTab->addString(partitions[i].name);
3794ece8a530Spatrick }
3795ece8a530Spatrick 
writeTo(uint8_t * buf)3796ece8a530Spatrick void PartitionIndexSection::writeTo(uint8_t *buf) {
3797ece8a530Spatrick   uint64_t va = getVA();
3798ece8a530Spatrick   for (size_t i = 1; i != partitions.size(); ++i) {
3799ece8a530Spatrick     write32(buf, mainPart->dynStrTab->getVA() + partitions[i].nameStrTab - va);
3800ece8a530Spatrick     write32(buf + 4, partitions[i].elfHeader->getVA() - (va + 4));
3801ece8a530Spatrick 
380205edf1c1Srobert     SyntheticSection *next = i == partitions.size() - 1
380305edf1c1Srobert                                  ? in.partEnd.get()
380405edf1c1Srobert                                  : partitions[i + 1].elfHeader.get();
3805ece8a530Spatrick     write32(buf + 8, next->getVA() - partitions[i].elfHeader->getVA());
3806ece8a530Spatrick 
3807ece8a530Spatrick     va += 12;
3808ece8a530Spatrick     buf += 12;
3809ece8a530Spatrick   }
3810ece8a530Spatrick }
3811ece8a530Spatrick 
reset()381205edf1c1Srobert void InStruct::reset() {
381305edf1c1Srobert   attributes.reset();
381405edf1c1Srobert   riscvAttributes.reset();
381505edf1c1Srobert   bss.reset();
381605edf1c1Srobert   bssRelRo.reset();
381705edf1c1Srobert   got.reset();
381805edf1c1Srobert   gotPlt.reset();
381905edf1c1Srobert   igotPlt.reset();
382005edf1c1Srobert   ppc64LongBranchTarget.reset();
382105edf1c1Srobert   mipsAbiFlags.reset();
382205edf1c1Srobert   mipsGot.reset();
382305edf1c1Srobert   mipsOptions.reset();
382405edf1c1Srobert   mipsReginfo.reset();
382505edf1c1Srobert   mipsRldMap.reset();
382605edf1c1Srobert   partEnd.reset();
382705edf1c1Srobert   partIndex.reset();
382805edf1c1Srobert   plt.reset();
382905edf1c1Srobert   iplt.reset();
383005edf1c1Srobert   ppc32Got2.reset();
383105edf1c1Srobert   ibtPlt.reset();
383205edf1c1Srobert   relaPlt.reset();
383305edf1c1Srobert   relaIplt.reset();
383405edf1c1Srobert   shStrTab.reset();
383505edf1c1Srobert   strTab.reset();
383605edf1c1Srobert   symTab.reset();
383705edf1c1Srobert   symTabShndx.reset();
383805edf1c1Srobert }
383905edf1c1Srobert 
384005edf1c1Srobert constexpr char kMemtagAndroidNoteName[] = "Android";
writeTo(uint8_t * buf)384105edf1c1Srobert void MemtagAndroidNote::writeTo(uint8_t *buf) {
384205edf1c1Srobert   static_assert(sizeof(kMemtagAndroidNoteName) == 8,
384305edf1c1Srobert                 "ABI check for Android 11 & 12.");
384405edf1c1Srobert   assert((config->androidMemtagStack || config->androidMemtagHeap) &&
384505edf1c1Srobert          "Should only be synthesizing a note if heap || stack is enabled.");
384605edf1c1Srobert 
384705edf1c1Srobert   write32(buf, sizeof(kMemtagAndroidNoteName));
384805edf1c1Srobert   write32(buf + 4, sizeof(uint32_t));
384905edf1c1Srobert   write32(buf + 8, ELF::NT_ANDROID_TYPE_MEMTAG);
385005edf1c1Srobert   memcpy(buf + 12, kMemtagAndroidNoteName, sizeof(kMemtagAndroidNoteName));
385105edf1c1Srobert   buf += 12 + sizeof(kMemtagAndroidNoteName);
385205edf1c1Srobert 
385305edf1c1Srobert   uint32_t value = 0;
385405edf1c1Srobert   value |= config->androidMemtagMode;
385505edf1c1Srobert   if (config->androidMemtagHeap)
385605edf1c1Srobert     value |= ELF::NT_MEMTAG_HEAP;
385705edf1c1Srobert   // Note, MTE stack is an ABI break. Attempting to run an MTE stack-enabled
385805edf1c1Srobert   // binary on Android 11 or 12 will result in a checkfail in the loader.
385905edf1c1Srobert   if (config->androidMemtagStack)
386005edf1c1Srobert     value |= ELF::NT_MEMTAG_STACK;
386105edf1c1Srobert   write32(buf, value); // note value
386205edf1c1Srobert }
386305edf1c1Srobert 
getSize() const386405edf1c1Srobert size_t MemtagAndroidNote::getSize() const {
386505edf1c1Srobert   return sizeof(llvm::ELF::Elf64_Nhdr) +
386605edf1c1Srobert          /*namesz=*/sizeof(kMemtagAndroidNoteName) +
386705edf1c1Srobert          /*descsz=*/sizeof(uint32_t);
386805edf1c1Srobert }
386905edf1c1Srobert 
writeTo(uint8_t * buf)387005edf1c1Srobert void PackageMetadataNote::writeTo(uint8_t *buf) {
387105edf1c1Srobert   write32(buf, 4);
387205edf1c1Srobert   write32(buf + 4, config->packageMetadata.size() + 1);
387305edf1c1Srobert   write32(buf + 8, FDO_PACKAGING_METADATA);
387405edf1c1Srobert   memcpy(buf + 12, "FDO", 4);
387505edf1c1Srobert   memcpy(buf + 16, config->packageMetadata.data(),
387605edf1c1Srobert          config->packageMetadata.size());
387705edf1c1Srobert }
387805edf1c1Srobert 
getSize() const387905edf1c1Srobert size_t PackageMetadataNote::getSize() const {
388005edf1c1Srobert   return sizeof(llvm::ELF::Elf64_Nhdr) + 4 +
388105edf1c1Srobert          alignTo(config->packageMetadata.size() + 1, 4);
388205edf1c1Srobert }
388305edf1c1Srobert 
3884adae0cfdSpatrick InStruct elf::in;
3885ece8a530Spatrick 
3886adae0cfdSpatrick std::vector<Partition> elf::partitions;
3887adae0cfdSpatrick Partition *elf::mainPart;
3888ece8a530Spatrick 
3889ece8a530Spatrick template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3890ece8a530Spatrick template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3891ece8a530Spatrick template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3892ece8a530Spatrick template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3893ece8a530Spatrick 
3894adae0cfdSpatrick template void elf::splitSections<ELF32LE>();
3895adae0cfdSpatrick template void elf::splitSections<ELF32BE>();
3896adae0cfdSpatrick template void elf::splitSections<ELF64LE>();
3897adae0cfdSpatrick template void elf::splitSections<ELF64BE>();
3898ece8a530Spatrick 
3899adae0cfdSpatrick template class elf::MipsAbiFlagsSection<ELF32LE>;
3900adae0cfdSpatrick template class elf::MipsAbiFlagsSection<ELF32BE>;
3901adae0cfdSpatrick template class elf::MipsAbiFlagsSection<ELF64LE>;
3902adae0cfdSpatrick template class elf::MipsAbiFlagsSection<ELF64BE>;
3903ece8a530Spatrick 
3904adae0cfdSpatrick template class elf::MipsOptionsSection<ELF32LE>;
3905adae0cfdSpatrick template class elf::MipsOptionsSection<ELF32BE>;
3906adae0cfdSpatrick template class elf::MipsOptionsSection<ELF64LE>;
3907adae0cfdSpatrick template class elf::MipsOptionsSection<ELF64BE>;
3908ece8a530Spatrick 
3909a0747c9fSpatrick template void EhFrameSection::iterateFDEWithLSDA<ELF32LE>(
3910a0747c9fSpatrick     function_ref<void(InputSection &)>);
3911a0747c9fSpatrick template void EhFrameSection::iterateFDEWithLSDA<ELF32BE>(
3912a0747c9fSpatrick     function_ref<void(InputSection &)>);
3913a0747c9fSpatrick template void EhFrameSection::iterateFDEWithLSDA<ELF64LE>(
3914a0747c9fSpatrick     function_ref<void(InputSection &)>);
3915a0747c9fSpatrick template void EhFrameSection::iterateFDEWithLSDA<ELF64BE>(
3916a0747c9fSpatrick     function_ref<void(InputSection &)>);
3917a0747c9fSpatrick 
3918adae0cfdSpatrick template class elf::MipsReginfoSection<ELF32LE>;
3919adae0cfdSpatrick template class elf::MipsReginfoSection<ELF32BE>;
3920adae0cfdSpatrick template class elf::MipsReginfoSection<ELF64LE>;
3921adae0cfdSpatrick template class elf::MipsReginfoSection<ELF64BE>;
3922ece8a530Spatrick 
3923adae0cfdSpatrick template class elf::DynamicSection<ELF32LE>;
3924adae0cfdSpatrick template class elf::DynamicSection<ELF32BE>;
3925adae0cfdSpatrick template class elf::DynamicSection<ELF64LE>;
3926adae0cfdSpatrick template class elf::DynamicSection<ELF64BE>;
3927ece8a530Spatrick 
3928adae0cfdSpatrick template class elf::RelocationSection<ELF32LE>;
3929adae0cfdSpatrick template class elf::RelocationSection<ELF32BE>;
3930adae0cfdSpatrick template class elf::RelocationSection<ELF64LE>;
3931adae0cfdSpatrick template class elf::RelocationSection<ELF64BE>;
3932ece8a530Spatrick 
3933adae0cfdSpatrick template class elf::AndroidPackedRelocationSection<ELF32LE>;
3934adae0cfdSpatrick template class elf::AndroidPackedRelocationSection<ELF32BE>;
3935adae0cfdSpatrick template class elf::AndroidPackedRelocationSection<ELF64LE>;
3936adae0cfdSpatrick template class elf::AndroidPackedRelocationSection<ELF64BE>;
3937ece8a530Spatrick 
3938adae0cfdSpatrick template class elf::RelrSection<ELF32LE>;
3939adae0cfdSpatrick template class elf::RelrSection<ELF32BE>;
3940adae0cfdSpatrick template class elf::RelrSection<ELF64LE>;
3941adae0cfdSpatrick template class elf::RelrSection<ELF64BE>;
3942ece8a530Spatrick 
3943adae0cfdSpatrick template class elf::SymbolTableSection<ELF32LE>;
3944adae0cfdSpatrick template class elf::SymbolTableSection<ELF32BE>;
3945adae0cfdSpatrick template class elf::SymbolTableSection<ELF64LE>;
3946adae0cfdSpatrick template class elf::SymbolTableSection<ELF64BE>;
3947ece8a530Spatrick 
3948adae0cfdSpatrick template class elf::VersionNeedSection<ELF32LE>;
3949adae0cfdSpatrick template class elf::VersionNeedSection<ELF32BE>;
3950adae0cfdSpatrick template class elf::VersionNeedSection<ELF64LE>;
3951adae0cfdSpatrick template class elf::VersionNeedSection<ELF64BE>;
3952ece8a530Spatrick 
3953adae0cfdSpatrick template void elf::writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
3954adae0cfdSpatrick template void elf::writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
3955adae0cfdSpatrick template void elf::writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
3956adae0cfdSpatrick template void elf::writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
3957ece8a530Spatrick 
3958adae0cfdSpatrick template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
3959adae0cfdSpatrick template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
3960adae0cfdSpatrick template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
3961adae0cfdSpatrick template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
3962ece8a530Spatrick 
3963adae0cfdSpatrick template class elf::PartitionElfHeaderSection<ELF32LE>;
3964adae0cfdSpatrick template class elf::PartitionElfHeaderSection<ELF32BE>;
3965adae0cfdSpatrick template class elf::PartitionElfHeaderSection<ELF64LE>;
3966adae0cfdSpatrick template class elf::PartitionElfHeaderSection<ELF64BE>;
3967ece8a530Spatrick 
3968adae0cfdSpatrick template class elf::PartitionProgramHeadersSection<ELF32LE>;
3969adae0cfdSpatrick template class elf::PartitionProgramHeadersSection<ELF32BE>;
3970adae0cfdSpatrick template class elf::PartitionProgramHeadersSection<ELF64LE>;
3971adae0cfdSpatrick template class elf::PartitionProgramHeadersSection<ELF64BE>;
3972