xref: /freebsd/contrib/llvm-project/lld/ELF/SyntheticSections.cpp (revision 52418fc2be8efa5172b90a3a9e617017173612c4)
10b57cec5SDimitry Andric //===- SyntheticSections.cpp ----------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains linker-synthesized sections. Currently,
100b57cec5SDimitry Andric // synthetic sections are created either output sections or input sections,
110b57cec5SDimitry Andric // but we are rewriting code so that all synthetic sections are created as
120b57cec5SDimitry Andric // input sections.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "SyntheticSections.h"
170b57cec5SDimitry Andric #include "Config.h"
1881ad6265SDimitry Andric #include "DWARF.h"
1981ad6265SDimitry Andric #include "EhFrame.h"
200b57cec5SDimitry Andric #include "InputFiles.h"
210b57cec5SDimitry Andric #include "LinkerScript.h"
220b57cec5SDimitry Andric #include "OutputSections.h"
230b57cec5SDimitry Andric #include "SymbolTable.h"
240b57cec5SDimitry Andric #include "Symbols.h"
250b57cec5SDimitry Andric #include "Target.h"
2681ad6265SDimitry Andric #include "Thunks.h"
270b57cec5SDimitry Andric #include "Writer.h"
2804eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
295ffd83dbSDimitry Andric #include "lld/Common/DWARF.h"
300b57cec5SDimitry Andric #include "lld/Common/Strings.h"
310b57cec5SDimitry Andric #include "lld/Common/Version.h"
32fcaf7f86SDimitry Andric #include "llvm/ADT/STLExtras.h"
330fca6ea1SDimitry Andric #include "llvm/ADT/Sequence.h"
340b57cec5SDimitry Andric #include "llvm/ADT/SetOperations.h"
350b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
360b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
3781ad6265SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
380fca6ea1SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
390b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
400fca6ea1SDimitry Andric #include "llvm/Support/DJB.h"
410b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
420b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
435ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
445ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h"
450fca6ea1SDimitry Andric #include <cinttypes>
460b57cec5SDimitry Andric #include <cstdlib>
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric using namespace llvm;
490b57cec5SDimitry Andric using namespace llvm::dwarf;
500b57cec5SDimitry Andric using namespace llvm::ELF;
510b57cec5SDimitry Andric using namespace llvm::object;
520b57cec5SDimitry Andric using namespace llvm::support;
535ffd83dbSDimitry Andric using namespace lld;
545ffd83dbSDimitry Andric using namespace lld::elf;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric using llvm::support::endian::read32le;
570b57cec5SDimitry Andric using llvm::support::endian::write32le;
580b57cec5SDimitry Andric using llvm::support::endian::write64le;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric constexpr size_t MergeNoTailSection::numShards;
610b57cec5SDimitry Andric 
readUint(uint8_t * buf)620b57cec5SDimitry Andric static uint64_t readUint(uint8_t *buf) {
630b57cec5SDimitry Andric   return config->is64 ? read64(buf) : read32(buf);
640b57cec5SDimitry Andric }
650b57cec5SDimitry Andric 
writeUint(uint8_t * buf,uint64_t val)660b57cec5SDimitry Andric static void writeUint(uint8_t *buf, uint64_t val) {
670b57cec5SDimitry Andric   if (config->is64)
680b57cec5SDimitry Andric     write64(buf, val);
690b57cec5SDimitry Andric   else
700b57cec5SDimitry Andric     write32(buf, val);
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric // Returns an LLD version string.
getVersion()740b57cec5SDimitry Andric static ArrayRef<uint8_t> getVersion() {
750b57cec5SDimitry Andric   // Check LLD_VERSION first for ease of testing.
760b57cec5SDimitry Andric   // You can get consistent output by using the environment variable.
770b57cec5SDimitry Andric   // This is only for testing.
780b57cec5SDimitry Andric   StringRef s = getenv("LLD_VERSION");
790b57cec5SDimitry Andric   if (s.empty())
8004eeddc0SDimitry Andric     s = saver().save(Twine("Linker: ") + getLLDVersion());
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   // +1 to include the terminating '\0'.
830b57cec5SDimitry Andric   return {(const uint8_t *)s.data(), s.size() + 1};
840b57cec5SDimitry Andric }
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric // Creates a .comment section containing LLD version info.
870b57cec5SDimitry Andric // With this feature, you can identify LLD-generated binaries easily
880b57cec5SDimitry Andric // by "readelf --string-dump .comment <file>".
890b57cec5SDimitry Andric // The returned object is a mergeable string section.
createCommentSection()905ffd83dbSDimitry Andric MergeInputSection *elf::createCommentSection() {
911fd87a68SDimitry Andric   auto *sec = make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
920b57cec5SDimitry Andric                                       getVersion(), ".comment");
931fd87a68SDimitry Andric   sec->splitIntoPieces();
941fd87a68SDimitry Andric   return sec;
950b57cec5SDimitry Andric }
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric // .MIPS.abiflags section.
980b57cec5SDimitry Andric template <class ELFT>
MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)990b57cec5SDimitry Andric MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)
1000b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
1010b57cec5SDimitry Andric       flags(flags) {
1020b57cec5SDimitry Andric   this->entsize = sizeof(Elf_Mips_ABIFlags);
1030b57cec5SDimitry Andric }
1040b57cec5SDimitry Andric 
writeTo(uint8_t * buf)1050b57cec5SDimitry Andric template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
1060b57cec5SDimitry Andric   memcpy(buf, &flags, sizeof(flags));
1070b57cec5SDimitry Andric }
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric template <class ELFT>
create()1101fd87a68SDimitry Andric std::unique_ptr<MipsAbiFlagsSection<ELFT>> MipsAbiFlagsSection<ELFT>::create() {
1110b57cec5SDimitry Andric   Elf_Mips_ABIFlags flags = {};
1120b57cec5SDimitry Andric   bool create = false;
1130b57cec5SDimitry Andric 
114bdd1243dSDimitry Andric   for (InputSectionBase *sec : ctx.inputSections) {
1150b57cec5SDimitry Andric     if (sec->type != SHT_MIPS_ABIFLAGS)
1160b57cec5SDimitry Andric       continue;
1170b57cec5SDimitry Andric     sec->markDead();
1180b57cec5SDimitry Andric     create = true;
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric     std::string filename = toString(sec->file);
121bdd1243dSDimitry Andric     const size_t size = sec->content().size();
1220b57cec5SDimitry Andric     // Older version of BFD (such as the default FreeBSD linker) concatenate
1230b57cec5SDimitry Andric     // .MIPS.abiflags instead of merging. To allow for this case (or potential
1240b57cec5SDimitry Andric     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
1250b57cec5SDimitry Andric     if (size < sizeof(Elf_Mips_ABIFlags)) {
1260b57cec5SDimitry Andric       error(filename + ": invalid size of .MIPS.abiflags section: got " +
1270b57cec5SDimitry Andric             Twine(size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
1280b57cec5SDimitry Andric       return nullptr;
1290b57cec5SDimitry Andric     }
130bdd1243dSDimitry Andric     auto *s =
131bdd1243dSDimitry Andric         reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->content().data());
1320b57cec5SDimitry Andric     if (s->version != 0) {
1330b57cec5SDimitry Andric       error(filename + ": unexpected .MIPS.abiflags version " +
1340b57cec5SDimitry Andric             Twine(s->version));
1350b57cec5SDimitry Andric       return nullptr;
1360b57cec5SDimitry Andric     }
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
1390b57cec5SDimitry Andric     // select the highest number of ISA/Rev/Ext.
1400b57cec5SDimitry Andric     flags.isa_level = std::max(flags.isa_level, s->isa_level);
1410b57cec5SDimitry Andric     flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
1420b57cec5SDimitry Andric     flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
1430b57cec5SDimitry Andric     flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
1440b57cec5SDimitry Andric     flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
1450b57cec5SDimitry Andric     flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
1460b57cec5SDimitry Andric     flags.ases |= s->ases;
1470b57cec5SDimitry Andric     flags.flags1 |= s->flags1;
1480b57cec5SDimitry Andric     flags.flags2 |= s->flags2;
1495ffd83dbSDimitry Andric     flags.fp_abi = elf::getMipsFpAbiFlag(flags.fp_abi, s->fp_abi, filename);
1500b57cec5SDimitry Andric   };
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   if (create)
1531fd87a68SDimitry Andric     return std::make_unique<MipsAbiFlagsSection<ELFT>>(flags);
1540b57cec5SDimitry Andric   return nullptr;
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric // .MIPS.options section.
1580b57cec5SDimitry Andric template <class ELFT>
MipsOptionsSection(Elf_Mips_RegInfo reginfo)1590b57cec5SDimitry Andric MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo reginfo)
1600b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
1610b57cec5SDimitry Andric       reginfo(reginfo) {
1620b57cec5SDimitry Andric   this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric 
writeTo(uint8_t * buf)1650b57cec5SDimitry Andric template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
1660b57cec5SDimitry Andric   auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
1670b57cec5SDimitry Andric   options->kind = ODK_REGINFO;
1680b57cec5SDimitry Andric   options->size = getSize();
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   if (!config->relocatable)
1710b57cec5SDimitry Andric     reginfo.ri_gp_value = in.mipsGot->getGp();
1720b57cec5SDimitry Andric   memcpy(buf + sizeof(Elf_Mips_Options), &reginfo, sizeof(reginfo));
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric template <class ELFT>
create()1761fd87a68SDimitry Andric std::unique_ptr<MipsOptionsSection<ELFT>> MipsOptionsSection<ELFT>::create() {
1770b57cec5SDimitry Andric   // N64 ABI only.
1780b57cec5SDimitry Andric   if (!ELFT::Is64Bits)
1790b57cec5SDimitry Andric     return nullptr;
1800b57cec5SDimitry Andric 
18104eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> sections;
182bdd1243dSDimitry Andric   for (InputSectionBase *sec : ctx.inputSections)
1830b57cec5SDimitry Andric     if (sec->type == SHT_MIPS_OPTIONS)
1840b57cec5SDimitry Andric       sections.push_back(sec);
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   if (sections.empty())
1870b57cec5SDimitry Andric     return nullptr;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   Elf_Mips_RegInfo reginfo = {};
1900b57cec5SDimitry Andric   for (InputSectionBase *sec : sections) {
1910b57cec5SDimitry Andric     sec->markDead();
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric     std::string filename = toString(sec->file);
194bdd1243dSDimitry Andric     ArrayRef<uint8_t> d = sec->content();
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric     while (!d.empty()) {
1970b57cec5SDimitry Andric       if (d.size() < sizeof(Elf_Mips_Options)) {
1980b57cec5SDimitry Andric         error(filename + ": invalid size of .MIPS.options section");
1990b57cec5SDimitry Andric         break;
2000b57cec5SDimitry Andric       }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric       auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
2030b57cec5SDimitry Andric       if (opt->kind == ODK_REGINFO) {
2040b57cec5SDimitry Andric         reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
2050b57cec5SDimitry Andric         sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
2060b57cec5SDimitry Andric         break;
2070b57cec5SDimitry Andric       }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric       if (!opt->size)
2100b57cec5SDimitry Andric         fatal(filename + ": zero option descriptor size");
2110b57cec5SDimitry Andric       d = d.slice(opt->size);
2120b57cec5SDimitry Andric     }
2130b57cec5SDimitry Andric   };
2140b57cec5SDimitry Andric 
2151fd87a68SDimitry Andric   return std::make_unique<MipsOptionsSection<ELFT>>(reginfo);
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric // MIPS .reginfo section.
2190b57cec5SDimitry Andric template <class ELFT>
MipsReginfoSection(Elf_Mips_RegInfo reginfo)2200b57cec5SDimitry Andric MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo reginfo)
2210b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
2220b57cec5SDimitry Andric       reginfo(reginfo) {
2230b57cec5SDimitry Andric   this->entsize = sizeof(Elf_Mips_RegInfo);
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric 
writeTo(uint8_t * buf)2260b57cec5SDimitry Andric template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
2270b57cec5SDimitry Andric   if (!config->relocatable)
2280b57cec5SDimitry Andric     reginfo.ri_gp_value = in.mipsGot->getGp();
2290b57cec5SDimitry Andric   memcpy(buf, &reginfo, sizeof(reginfo));
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric template <class ELFT>
create()2331fd87a68SDimitry Andric std::unique_ptr<MipsReginfoSection<ELFT>> MipsReginfoSection<ELFT>::create() {
2340b57cec5SDimitry Andric   // Section should be alive for O32 and N32 ABIs only.
2350b57cec5SDimitry Andric   if (ELFT::Is64Bits)
2360b57cec5SDimitry Andric     return nullptr;
2370b57cec5SDimitry Andric 
23804eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> sections;
239bdd1243dSDimitry Andric   for (InputSectionBase *sec : ctx.inputSections)
2400b57cec5SDimitry Andric     if (sec->type == SHT_MIPS_REGINFO)
2410b57cec5SDimitry Andric       sections.push_back(sec);
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   if (sections.empty())
2440b57cec5SDimitry Andric     return nullptr;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   Elf_Mips_RegInfo reginfo = {};
2470b57cec5SDimitry Andric   for (InputSectionBase *sec : sections) {
2480b57cec5SDimitry Andric     sec->markDead();
2490b57cec5SDimitry Andric 
250bdd1243dSDimitry Andric     if (sec->content().size() != sizeof(Elf_Mips_RegInfo)) {
2510b57cec5SDimitry Andric       error(toString(sec->file) + ": invalid size of .reginfo section");
2520b57cec5SDimitry Andric       return nullptr;
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric 
255bdd1243dSDimitry Andric     auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->content().data());
2560b57cec5SDimitry Andric     reginfo.ri_gprmask |= r->ri_gprmask;
2570b57cec5SDimitry Andric     sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
2580b57cec5SDimitry Andric   };
2590b57cec5SDimitry Andric 
2601fd87a68SDimitry Andric   return std::make_unique<MipsReginfoSection<ELFT>>(reginfo);
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
createInterpSection()2635ffd83dbSDimitry Andric InputSection *elf::createInterpSection() {
2640b57cec5SDimitry Andric   // StringSaver guarantees that the returned string ends with '\0'.
26504eeddc0SDimitry Andric   StringRef s = saver().save(config->dynamicLinker);
2660b57cec5SDimitry Andric   ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
2670b57cec5SDimitry Andric 
2687a6dacacSDimitry Andric   return make<InputSection>(ctx.internalFile, SHF_ALLOC, SHT_PROGBITS, 1,
2697a6dacacSDimitry Andric                             contents, ".interp");
2700b57cec5SDimitry Andric }
2710b57cec5SDimitry Andric 
addSyntheticLocal(StringRef name,uint8_t type,uint64_t value,uint64_t size,InputSectionBase & section)2725ffd83dbSDimitry Andric Defined *elf::addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
2730b57cec5SDimitry Andric                                 uint64_t size, InputSectionBase &section) {
2740eae32dcSDimitry Andric   Defined *s = makeDefined(section.file, name, STB_LOCAL, STV_DEFAULT, type,
2750b57cec5SDimitry Andric                            value, size, &section);
2760b57cec5SDimitry Andric   if (in.symTab)
2770b57cec5SDimitry Andric     in.symTab->addSymbol(s);
27806c3fb27SDimitry Andric 
27906c3fb27SDimitry Andric   if (config->emachine == EM_ARM && !config->isLE && config->armBe8 &&
28006c3fb27SDimitry Andric       (section.flags & SHF_EXECINSTR))
28106c3fb27SDimitry Andric     // Adding Linker generated mapping symbols to the arm specific mapping
28206c3fb27SDimitry Andric     // symbols list.
28306c3fb27SDimitry Andric     addArmSyntheticSectionMappingSymbol(s);
28406c3fb27SDimitry Andric 
2850b57cec5SDimitry Andric   return s;
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
getHashSize()2880b57cec5SDimitry Andric static size_t getHashSize() {
2890b57cec5SDimitry Andric   switch (config->buildId) {
2900b57cec5SDimitry Andric   case BuildIdKind::Fast:
2910b57cec5SDimitry Andric     return 8;
2920b57cec5SDimitry Andric   case BuildIdKind::Md5:
2930b57cec5SDimitry Andric   case BuildIdKind::Uuid:
2940b57cec5SDimitry Andric     return 16;
2950b57cec5SDimitry Andric   case BuildIdKind::Sha1:
2960b57cec5SDimitry Andric     return 20;
2970b57cec5SDimitry Andric   case BuildIdKind::Hexstring:
2980b57cec5SDimitry Andric     return config->buildIdVector.size();
2990b57cec5SDimitry Andric   default:
3000b57cec5SDimitry Andric     llvm_unreachable("unknown BuildIdKind");
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric // This class represents a linker-synthesized .note.gnu.property section.
3050b57cec5SDimitry Andric //
3060b57cec5SDimitry Andric // In x86 and AArch64, object files may contain feature flags indicating the
3070b57cec5SDimitry Andric // features that they have used. The flags are stored in a .note.gnu.property
3080b57cec5SDimitry Andric // section.
3090b57cec5SDimitry Andric //
3100b57cec5SDimitry Andric // lld reads the sections from input files and merges them by computing AND of
3110b57cec5SDimitry Andric // the flags. The result is written as a new .note.gnu.property section.
3120b57cec5SDimitry Andric //
3130b57cec5SDimitry Andric // If the flag is zero (which indicates that the intersection of the feature
3140b57cec5SDimitry Andric // sets is empty, or some input files didn't have .note.gnu.property sections),
3150b57cec5SDimitry Andric // we don't create this section.
GnuPropertySection()3160b57cec5SDimitry Andric GnuPropertySection::GnuPropertySection()
317480093f4SDimitry Andric     : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
318480093f4SDimitry Andric                        config->wordsize, ".note.gnu.property") {}
3190b57cec5SDimitry Andric 
writeTo(uint8_t * buf)3200b57cec5SDimitry Andric void GnuPropertySection::writeTo(uint8_t *buf) {
3210fca6ea1SDimitry Andric   write32(buf, 4);                          // Name size
3220fca6ea1SDimitry Andric   write32(buf + 4, getSize() - 16);         // Content size
3230fca6ea1SDimitry Andric   write32(buf + 8, NT_GNU_PROPERTY_TYPE_0); // Type
3240fca6ea1SDimitry Andric   memcpy(buf + 12, "GNU", 4);               // Name string
3250fca6ea1SDimitry Andric 
3260b57cec5SDimitry Andric   uint32_t featureAndType = config->emachine == EM_AARCH64
3270b57cec5SDimitry Andric                                 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
3280b57cec5SDimitry Andric                                 : GNU_PROPERTY_X86_FEATURE_1_AND;
3290b57cec5SDimitry Andric 
3300fca6ea1SDimitry Andric   unsigned offset = 16;
3310fca6ea1SDimitry Andric   if (config->andFeatures != 0) {
3320fca6ea1SDimitry Andric     write32(buf + offset + 0, featureAndType);      // Feature type
3330fca6ea1SDimitry Andric     write32(buf + offset + 4, 4);                   // Feature size
3340fca6ea1SDimitry Andric     write32(buf + offset + 8, config->andFeatures); // Feature flags
3350b57cec5SDimitry Andric     if (config->is64)
3360fca6ea1SDimitry Andric       write32(buf + offset + 12, 0); // Padding
3370fca6ea1SDimitry Andric     offset += 16;
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400fca6ea1SDimitry Andric   if (!ctx.aarch64PauthAbiCoreInfo.empty()) {
3410fca6ea1SDimitry Andric     write32(buf + offset + 0, GNU_PROPERTY_AARCH64_FEATURE_PAUTH);
3420fca6ea1SDimitry Andric     write32(buf + offset + 4, ctx.aarch64PauthAbiCoreInfo.size());
3430fca6ea1SDimitry Andric     memcpy(buf + offset + 8, ctx.aarch64PauthAbiCoreInfo.data(),
3440fca6ea1SDimitry Andric            ctx.aarch64PauthAbiCoreInfo.size());
3450fca6ea1SDimitry Andric   }
3460fca6ea1SDimitry Andric }
3470fca6ea1SDimitry Andric 
getSize() const3480fca6ea1SDimitry Andric size_t GnuPropertySection::getSize() const {
3490fca6ea1SDimitry Andric   uint32_t contentSize = 0;
3500fca6ea1SDimitry Andric   if (config->andFeatures != 0)
3510fca6ea1SDimitry Andric     contentSize += config->is64 ? 16 : 12;
3520fca6ea1SDimitry Andric   if (!ctx.aarch64PauthAbiCoreInfo.empty())
3530fca6ea1SDimitry Andric     contentSize += 4 + 4 + ctx.aarch64PauthAbiCoreInfo.size();
3540fca6ea1SDimitry Andric   assert(contentSize != 0);
3550fca6ea1SDimitry Andric   return contentSize + 16;
3560fca6ea1SDimitry Andric }
3570b57cec5SDimitry Andric 
BuildIdSection()3580b57cec5SDimitry Andric BuildIdSection::BuildIdSection()
3590b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
3600b57cec5SDimitry Andric       hashSize(getHashSize()) {}
3610b57cec5SDimitry Andric 
writeTo(uint8_t * buf)3620b57cec5SDimitry Andric void BuildIdSection::writeTo(uint8_t *buf) {
3630b57cec5SDimitry Andric   write32(buf, 4);                      // Name size
3640b57cec5SDimitry Andric   write32(buf + 4, hashSize);           // Content size
3650b57cec5SDimitry Andric   write32(buf + 8, NT_GNU_BUILD_ID);    // Type
3660b57cec5SDimitry Andric   memcpy(buf + 12, "GNU", 4);           // Name string
3670b57cec5SDimitry Andric   hashBuf = buf + 16;
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric 
writeBuildId(ArrayRef<uint8_t> buf)3700b57cec5SDimitry Andric void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
3710b57cec5SDimitry Andric   assert(buf.size() == hashSize);
3720b57cec5SDimitry Andric   memcpy(hashBuf, buf.data(), hashSize);
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
BssSection(StringRef name,uint64_t size,uint32_t alignment)3750b57cec5SDimitry Andric BssSection::BssSection(StringRef name, uint64_t size, uint32_t alignment)
3760b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, alignment, name) {
3770b57cec5SDimitry Andric   this->bss = true;
3780b57cec5SDimitry Andric   this->size = size;
3790b57cec5SDimitry Andric }
3800b57cec5SDimitry Andric 
EhFrameSection()3810b57cec5SDimitry Andric EhFrameSection::EhFrameSection()
3820b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric // Search for an existing CIE record or create a new one.
3850b57cec5SDimitry Andric // CIE records from input object files are uniquified by their contents
3860b57cec5SDimitry Andric // and where their relocations point to.
3870b57cec5SDimitry Andric template <class ELFT, class RelTy>
addCie(EhSectionPiece & cie,ArrayRef<RelTy> rels)3880b57cec5SDimitry Andric CieRecord *EhFrameSection::addCie(EhSectionPiece &cie, ArrayRef<RelTy> rels) {
3890b57cec5SDimitry Andric   Symbol *personality = nullptr;
3900b57cec5SDimitry Andric   unsigned firstRelI = cie.firstRelocation;
3910b57cec5SDimitry Andric   if (firstRelI != (unsigned)-1)
3920fca6ea1SDimitry Andric     personality = &cie.sec->file->getRelocTargetSym(rels[firstRelI]);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Search for an existing CIE by CIE contents/relocation target pair.
3950b57cec5SDimitry Andric   CieRecord *&rec = cieMap[{cie.data(), personality}];
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   // If not found, create a new one.
3980b57cec5SDimitry Andric   if (!rec) {
3990b57cec5SDimitry Andric     rec = make<CieRecord>();
4000b57cec5SDimitry Andric     rec->cie = &cie;
4010b57cec5SDimitry Andric     cieRecords.push_back(rec);
4020b57cec5SDimitry Andric   }
4030b57cec5SDimitry Andric   return rec;
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
406e8d8bef9SDimitry Andric // There is one FDE per function. Returns a non-null pointer to the function
407e8d8bef9SDimitry Andric // symbol if the given FDE points to a live function.
4080b57cec5SDimitry Andric template <class ELFT, class RelTy>
isFdeLive(EhSectionPiece & fde,ArrayRef<RelTy> rels)409e8d8bef9SDimitry Andric Defined *EhFrameSection::isFdeLive(EhSectionPiece &fde, ArrayRef<RelTy> rels) {
4100b57cec5SDimitry Andric   auto *sec = cast<EhInputSection>(fde.sec);
4110b57cec5SDimitry Andric   unsigned firstRelI = fde.firstRelocation;
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // An FDE should point to some function because FDEs are to describe
4140b57cec5SDimitry Andric   // functions. That's however not always the case due to an issue of
4150b57cec5SDimitry Andric   // ld.gold with -r. ld.gold may discard only functions and leave their
4160b57cec5SDimitry Andric   // corresponding FDEs, which results in creating bad .eh_frame sections.
4170b57cec5SDimitry Andric   // To deal with that, we ignore such FDEs.
4180b57cec5SDimitry Andric   if (firstRelI == (unsigned)-1)
419e8d8bef9SDimitry Andric     return nullptr;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   const RelTy &rel = rels[firstRelI];
4220fca6ea1SDimitry Andric   Symbol &b = sec->file->getRelocTargetSym(rel);
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   // FDEs for garbage-collected or merged-by-ICF sections, or sections in
4250b57cec5SDimitry Andric   // another partition, are dead.
4260b57cec5SDimitry Andric   if (auto *d = dyn_cast<Defined>(&b))
4270eae32dcSDimitry Andric     if (!d->folded && d->section && d->section->partition == partition)
428e8d8bef9SDimitry Andric       return d;
429e8d8bef9SDimitry Andric   return nullptr;
4300b57cec5SDimitry Andric }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric // .eh_frame is a sequence of CIE or FDE records. In general, there
4330b57cec5SDimitry Andric // is one CIE record per input object file which is followed by
4340b57cec5SDimitry Andric // a list of FDEs. This function searches an existing CIE or create a new
4350b57cec5SDimitry Andric // one and associates FDEs to the CIE.
4360b57cec5SDimitry Andric template <class ELFT, class RelTy>
addRecords(EhInputSection * sec,ArrayRef<RelTy> rels)43785868e8aSDimitry Andric void EhFrameSection::addRecords(EhInputSection *sec, ArrayRef<RelTy> rels) {
4380b57cec5SDimitry Andric   offsetToCie.clear();
439bdd1243dSDimitry Andric   for (EhSectionPiece &cie : sec->cies)
440bdd1243dSDimitry Andric     offsetToCie[cie.inputOff] = addCie<ELFT>(cie, rels);
441bdd1243dSDimitry Andric   for (EhSectionPiece &fde : sec->fdes) {
4420fca6ea1SDimitry Andric     uint32_t id = endian::read32<ELFT::Endianness>(fde.data().data() + 4);
443bdd1243dSDimitry Andric     CieRecord *rec = offsetToCie[fde.inputOff + 4 - id];
4440b57cec5SDimitry Andric     if (!rec)
4450b57cec5SDimitry Andric       fatal(toString(sec) + ": invalid CIE reference");
4460b57cec5SDimitry Andric 
447bdd1243dSDimitry Andric     if (!isFdeLive<ELFT>(fde, rels))
4480b57cec5SDimitry Andric       continue;
449bdd1243dSDimitry Andric     rec->fdes.push_back(&fde);
4500b57cec5SDimitry Andric     numFdes++;
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric 
45485868e8aSDimitry Andric template <class ELFT>
addSectionAux(EhInputSection * sec)45585868e8aSDimitry Andric void EhFrameSection::addSectionAux(EhInputSection *sec) {
45685868e8aSDimitry Andric   if (!sec->isLive())
45785868e8aSDimitry Andric     return;
458*52418fc2SDimitry Andric   const RelsOrRelas<ELFT> rels =
459*52418fc2SDimitry Andric       sec->template relsOrRelas<ELFT>(/*supportsCrel=*/false);
460349cc55cSDimitry Andric   if (rels.areRelocsRel())
461349cc55cSDimitry Andric     addRecords<ELFT>(sec, rels.rels);
46285868e8aSDimitry Andric   else
463349cc55cSDimitry Andric     addRecords<ELFT>(sec, rels.relas);
46485868e8aSDimitry Andric }
46585868e8aSDimitry Andric 
466e8d8bef9SDimitry Andric // Used by ICF<ELFT>::handleLSDA(). This function is very similar to
467e8d8bef9SDimitry Andric // EhFrameSection::addRecords().
468e8d8bef9SDimitry Andric template <class ELFT, class RelTy>
iterateFDEWithLSDAAux(EhInputSection & sec,ArrayRef<RelTy> rels,DenseSet<size_t> & ciesWithLSDA,llvm::function_ref<void (InputSection &)> fn)469e8d8bef9SDimitry Andric void EhFrameSection::iterateFDEWithLSDAAux(
470e8d8bef9SDimitry Andric     EhInputSection &sec, ArrayRef<RelTy> rels, DenseSet<size_t> &ciesWithLSDA,
471e8d8bef9SDimitry Andric     llvm::function_ref<void(InputSection &)> fn) {
472bdd1243dSDimitry Andric   for (EhSectionPiece &cie : sec.cies)
473bdd1243dSDimitry Andric     if (hasLSDA(cie))
474bdd1243dSDimitry Andric       ciesWithLSDA.insert(cie.inputOff);
475bdd1243dSDimitry Andric   for (EhSectionPiece &fde : sec.fdes) {
4760fca6ea1SDimitry Andric     uint32_t id = endian::read32<ELFT::Endianness>(fde.data().data() + 4);
477bdd1243dSDimitry Andric     if (!ciesWithLSDA.contains(fde.inputOff + 4 - id))
478e8d8bef9SDimitry Andric       continue;
479e8d8bef9SDimitry Andric 
480e8d8bef9SDimitry Andric     // The CIE has a LSDA argument. Call fn with d's section.
481bdd1243dSDimitry Andric     if (Defined *d = isFdeLive<ELFT>(fde, rels))
482e8d8bef9SDimitry Andric       if (auto *s = dyn_cast_or_null<InputSection>(d->section))
483e8d8bef9SDimitry Andric         fn(*s);
484e8d8bef9SDimitry Andric   }
485e8d8bef9SDimitry Andric }
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric template <class ELFT>
iterateFDEWithLSDA(llvm::function_ref<void (InputSection &)> fn)488e8d8bef9SDimitry Andric void EhFrameSection::iterateFDEWithLSDA(
489e8d8bef9SDimitry Andric     llvm::function_ref<void(InputSection &)> fn) {
490e8d8bef9SDimitry Andric   DenseSet<size_t> ciesWithLSDA;
491e8d8bef9SDimitry Andric   for (EhInputSection *sec : sections) {
492e8d8bef9SDimitry Andric     ciesWithLSDA.clear();
493*52418fc2SDimitry Andric     const RelsOrRelas<ELFT> rels =
494*52418fc2SDimitry Andric         sec->template relsOrRelas<ELFT>(/*supportsCrel=*/false);
495349cc55cSDimitry Andric     if (rels.areRelocsRel())
496349cc55cSDimitry Andric       iterateFDEWithLSDAAux<ELFT>(*sec, rels.rels, ciesWithLSDA, fn);
497e8d8bef9SDimitry Andric     else
498349cc55cSDimitry Andric       iterateFDEWithLSDAAux<ELFT>(*sec, rels.relas, ciesWithLSDA, fn);
499e8d8bef9SDimitry Andric   }
500e8d8bef9SDimitry Andric }
501e8d8bef9SDimitry Andric 
writeCieFde(uint8_t * buf,ArrayRef<uint8_t> d)5020b57cec5SDimitry Andric static void writeCieFde(uint8_t *buf, ArrayRef<uint8_t> d) {
5030b57cec5SDimitry Andric   memcpy(buf, d.data(), d.size());
5040b57cec5SDimitry Andric   // Fix the size field. -4 since size does not include the size field itself.
505bdd1243dSDimitry Andric   write32(buf, d.size() - 4);
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric 
finalizeContents()5080b57cec5SDimitry Andric void EhFrameSection::finalizeContents() {
5090b57cec5SDimitry Andric   assert(!this->size); // Not finalized.
51085868e8aSDimitry Andric 
51185868e8aSDimitry Andric   switch (config->ekind) {
51285868e8aSDimitry Andric   case ELFNoneKind:
51385868e8aSDimitry Andric     llvm_unreachable("invalid ekind");
51485868e8aSDimitry Andric   case ELF32LEKind:
51585868e8aSDimitry Andric     for (EhInputSection *sec : sections)
51685868e8aSDimitry Andric       addSectionAux<ELF32LE>(sec);
51785868e8aSDimitry Andric     break;
51885868e8aSDimitry Andric   case ELF32BEKind:
51985868e8aSDimitry Andric     for (EhInputSection *sec : sections)
52085868e8aSDimitry Andric       addSectionAux<ELF32BE>(sec);
52185868e8aSDimitry Andric     break;
52285868e8aSDimitry Andric   case ELF64LEKind:
52385868e8aSDimitry Andric     for (EhInputSection *sec : sections)
52485868e8aSDimitry Andric       addSectionAux<ELF64LE>(sec);
52585868e8aSDimitry Andric     break;
52685868e8aSDimitry Andric   case ELF64BEKind:
52785868e8aSDimitry Andric     for (EhInputSection *sec : sections)
52885868e8aSDimitry Andric       addSectionAux<ELF64BE>(sec);
52985868e8aSDimitry Andric     break;
53085868e8aSDimitry Andric   }
53185868e8aSDimitry Andric 
5320b57cec5SDimitry Andric   size_t off = 0;
5330b57cec5SDimitry Andric   for (CieRecord *rec : cieRecords) {
5340b57cec5SDimitry Andric     rec->cie->outputOff = off;
535bdd1243dSDimitry Andric     off += rec->cie->size;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric     for (EhSectionPiece *fde : rec->fdes) {
5380b57cec5SDimitry Andric       fde->outputOff = off;
539bdd1243dSDimitry Andric       off += fde->size;
5400b57cec5SDimitry Andric     }
5410b57cec5SDimitry Andric   }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   // The LSB standard does not allow a .eh_frame section with zero
5440b57cec5SDimitry Andric   // Call Frame Information records. glibc unwind-dw2-fde.c
5450b57cec5SDimitry Andric   // classify_object_over_fdes expects there is a CIE record length 0 as a
5460b57cec5SDimitry Andric   // terminator. Thus we add one unconditionally.
5470b57cec5SDimitry Andric   off += 4;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   this->size = off;
5500b57cec5SDimitry Andric }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
5530b57cec5SDimitry Andric // to get an FDE from an address to which FDE is applied. This function
5540b57cec5SDimitry Andric // returns a list of such pairs.
getFdeData() const55504eeddc0SDimitry Andric SmallVector<EhFrameSection::FdeData, 0> EhFrameSection::getFdeData() const {
5560b57cec5SDimitry Andric   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
55704eeddc0SDimitry Andric   SmallVector<FdeData, 0> ret;
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric   uint64_t va = getPartition().ehFrameHdr->getVA();
5600b57cec5SDimitry Andric   for (CieRecord *rec : cieRecords) {
5610b57cec5SDimitry Andric     uint8_t enc = getFdeEncoding(rec->cie);
5620b57cec5SDimitry Andric     for (EhSectionPiece *fde : rec->fdes) {
5630b57cec5SDimitry Andric       uint64_t pc = getFdePc(buf, fde->outputOff, enc);
5640b57cec5SDimitry Andric       uint64_t fdeVA = getParent()->addr + fde->outputOff;
5650fca6ea1SDimitry Andric       if (!isInt<32>(pc - va)) {
5660fca6ea1SDimitry Andric         errorOrWarn(toString(fde->sec) + ": PC offset is too large: 0x" +
5670b57cec5SDimitry Andric                     Twine::utohexstr(pc - va));
5680fca6ea1SDimitry Andric         continue;
5690fca6ea1SDimitry Andric       }
5700b57cec5SDimitry Andric       ret.push_back({uint32_t(pc - va), uint32_t(fdeVA - va)});
5710b57cec5SDimitry Andric     }
5720b57cec5SDimitry Andric   }
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   // Sort the FDE list by their PC and uniqueify. Usually there is only
5750b57cec5SDimitry Andric   // one FDE for a PC (i.e. function), but if ICF merges two functions
5760b57cec5SDimitry Andric   // into one, there can be more than one FDEs pointing to the address.
5770b57cec5SDimitry Andric   auto less = [](const FdeData &a, const FdeData &b) {
5780b57cec5SDimitry Andric     return a.pcRel < b.pcRel;
5790b57cec5SDimitry Andric   };
5800b57cec5SDimitry Andric   llvm::stable_sort(ret, less);
5810b57cec5SDimitry Andric   auto eq = [](const FdeData &a, const FdeData &b) {
5820b57cec5SDimitry Andric     return a.pcRel == b.pcRel;
5830b57cec5SDimitry Andric   };
5840b57cec5SDimitry Andric   ret.erase(std::unique(ret.begin(), ret.end(), eq), ret.end());
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   return ret;
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
readFdeAddr(uint8_t * buf,int size)5890b57cec5SDimitry Andric static uint64_t readFdeAddr(uint8_t *buf, int size) {
5900b57cec5SDimitry Andric   switch (size) {
5910b57cec5SDimitry Andric   case DW_EH_PE_udata2:
5920b57cec5SDimitry Andric     return read16(buf);
5930b57cec5SDimitry Andric   case DW_EH_PE_sdata2:
5940b57cec5SDimitry Andric     return (int16_t)read16(buf);
5950b57cec5SDimitry Andric   case DW_EH_PE_udata4:
5960b57cec5SDimitry Andric     return read32(buf);
5970b57cec5SDimitry Andric   case DW_EH_PE_sdata4:
5980b57cec5SDimitry Andric     return (int32_t)read32(buf);
5990b57cec5SDimitry Andric   case DW_EH_PE_udata8:
6000b57cec5SDimitry Andric   case DW_EH_PE_sdata8:
6010b57cec5SDimitry Andric     return read64(buf);
6020b57cec5SDimitry Andric   case DW_EH_PE_absptr:
6030b57cec5SDimitry Andric     return readUint(buf);
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric   fatal("unknown FDE size encoding");
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
6090b57cec5SDimitry Andric // We need it to create .eh_frame_hdr section.
getFdePc(uint8_t * buf,size_t fdeOff,uint8_t enc) const6100b57cec5SDimitry Andric uint64_t EhFrameSection::getFdePc(uint8_t *buf, size_t fdeOff,
6110b57cec5SDimitry Andric                                   uint8_t enc) const {
6120b57cec5SDimitry Andric   // The starting address to which this FDE applies is
6135f757f3fSDimitry Andric   // stored at FDE + 8 byte. And this offset is within
6145f757f3fSDimitry Andric   // the .eh_frame section.
6150b57cec5SDimitry Andric   size_t off = fdeOff + 8;
6160b57cec5SDimitry Andric   uint64_t addr = readFdeAddr(buf + off, enc & 0xf);
6170b57cec5SDimitry Andric   if ((enc & 0x70) == DW_EH_PE_absptr)
6180fca6ea1SDimitry Andric     return config->is64 ? addr : uint32_t(addr);
6190b57cec5SDimitry Andric   if ((enc & 0x70) == DW_EH_PE_pcrel)
6205f757f3fSDimitry Andric     return addr + getParent()->addr + off + outSecOff;
6210b57cec5SDimitry Andric   fatal("unknown FDE size relative encoding");
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
writeTo(uint8_t * buf)6240b57cec5SDimitry Andric void EhFrameSection::writeTo(uint8_t *buf) {
6250b57cec5SDimitry Andric   // Write CIE and FDE records.
6260b57cec5SDimitry Andric   for (CieRecord *rec : cieRecords) {
6270b57cec5SDimitry Andric     size_t cieOffset = rec->cie->outputOff;
6280b57cec5SDimitry Andric     writeCieFde(buf + cieOffset, rec->cie->data());
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric     for (EhSectionPiece *fde : rec->fdes) {
6310b57cec5SDimitry Andric       size_t off = fde->outputOff;
6320b57cec5SDimitry Andric       writeCieFde(buf + off, fde->data());
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric       // FDE's second word should have the offset to an associated CIE.
6350b57cec5SDimitry Andric       // Write it.
6360b57cec5SDimitry Andric       write32(buf + off + 4, off + 4 - cieOffset);
6370b57cec5SDimitry Andric     }
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Apply relocations. .eh_frame section contents are not contiguous
6410b57cec5SDimitry Andric   // in the output buffer, but relocateAlloc() still works because
6420b57cec5SDimitry Andric   // getOffset() takes care of discontiguous section pieces.
6430b57cec5SDimitry Andric   for (EhInputSection *s : sections)
644bdd1243dSDimitry Andric     target->relocateAlloc(*s, buf);
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   if (getPartition().ehFrameHdr && getPartition().ehFrameHdr->getParent())
6470b57cec5SDimitry Andric     getPartition().ehFrameHdr->write();
6480b57cec5SDimitry Andric }
6490b57cec5SDimitry Andric 
GotSection()6500b57cec5SDimitry Andric GotSection::GotSection()
651fe6060f1SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
652fe6060f1SDimitry Andric                        target->gotEntrySize, ".got") {
653fe6060f1SDimitry Andric   numEntries = target->gotHeaderEntriesNum;
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric 
addConstant(const Relocation & r)656bdd1243dSDimitry Andric void GotSection::addConstant(const Relocation &r) { relocations.push_back(r); }
addEntry(const Symbol & sym)6570fca6ea1SDimitry Andric void GotSection::addEntry(const Symbol &sym) {
65804eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1);
65904eeddc0SDimitry Andric   symAux.back().gotIdx = numEntries++;
66004eeddc0SDimitry Andric }
66104eeddc0SDimitry Andric 
addTlsDescEntry(const Symbol & sym)6620fca6ea1SDimitry Andric bool GotSection::addTlsDescEntry(const Symbol &sym) {
66304eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1);
66404eeddc0SDimitry Andric   symAux.back().tlsDescIdx = numEntries;
66504eeddc0SDimitry Andric   numEntries += 2;
66604eeddc0SDimitry Andric   return true;
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
addDynTlsEntry(const Symbol & sym)6690fca6ea1SDimitry Andric bool GotSection::addDynTlsEntry(const Symbol &sym) {
67004eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1);
67104eeddc0SDimitry Andric   symAux.back().tlsGdIdx = numEntries;
6720b57cec5SDimitry Andric   // Global Dynamic TLS entries take two GOT slots.
6730b57cec5SDimitry Andric   numEntries += 2;
6740b57cec5SDimitry Andric   return true;
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric // Reserves TLS entries for a TLS module ID and a TLS block offset.
6780b57cec5SDimitry Andric // In total it takes two GOT slots.
addTlsIndex()6790b57cec5SDimitry Andric bool GotSection::addTlsIndex() {
6800b57cec5SDimitry Andric   if (tlsIndexOff != uint32_t(-1))
6810b57cec5SDimitry Andric     return false;
6820b57cec5SDimitry Andric   tlsIndexOff = numEntries * config->wordsize;
6830b57cec5SDimitry Andric   numEntries += 2;
6840b57cec5SDimitry Andric   return true;
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric 
getTlsDescOffset(const Symbol & sym) const68704eeddc0SDimitry Andric uint32_t GotSection::getTlsDescOffset(const Symbol &sym) const {
68804eeddc0SDimitry Andric   return sym.getTlsDescIdx() * config->wordsize;
68904eeddc0SDimitry Andric }
69004eeddc0SDimitry Andric 
getTlsDescAddr(const Symbol & sym) const69104eeddc0SDimitry Andric uint64_t GotSection::getTlsDescAddr(const Symbol &sym) const {
69204eeddc0SDimitry Andric   return getVA() + getTlsDescOffset(sym);
69304eeddc0SDimitry Andric }
69404eeddc0SDimitry Andric 
getGlobalDynAddr(const Symbol & b) const6950b57cec5SDimitry Andric uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
69604eeddc0SDimitry Andric   return this->getVA() + b.getTlsGdIdx() * config->wordsize;
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
getGlobalDynOffset(const Symbol & b) const6990b57cec5SDimitry Andric uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
70004eeddc0SDimitry Andric   return b.getTlsGdIdx() * config->wordsize;
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
finalizeContents()7030b57cec5SDimitry Andric void GotSection::finalizeContents() {
704fe6060f1SDimitry Andric   if (config->emachine == EM_PPC64 &&
705fe6060f1SDimitry Andric       numEntries <= target->gotHeaderEntriesNum && !ElfSym::globalOffsetTable)
706fe6060f1SDimitry Andric     size = 0;
707fe6060f1SDimitry Andric   else
7080b57cec5SDimitry Andric     size = numEntries * config->wordsize;
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
isNeeded() const7110b57cec5SDimitry Andric bool GotSection::isNeeded() const {
712fe6060f1SDimitry Andric   // Needed if the GOT symbol is used or the number of entries is more than just
713fe6060f1SDimitry Andric   // the header. A GOT with just the header may not be needed.
714fe6060f1SDimitry Andric   return hasGotOffRel || numEntries > target->gotHeaderEntriesNum;
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric 
writeTo(uint8_t * buf)7170b57cec5SDimitry Andric void GotSection::writeTo(uint8_t *buf) {
71861cfbce3SDimitry Andric   // On PPC64 .got may be needed but empty. Skip the write.
71961cfbce3SDimitry Andric   if (size == 0)
72061cfbce3SDimitry Andric     return;
7210b57cec5SDimitry Andric   target->writeGotHeader(buf);
722bdd1243dSDimitry Andric   target->relocateAlloc(*this, buf);
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric 
getMipsPageAddr(uint64_t addr)7250b57cec5SDimitry Andric static uint64_t getMipsPageAddr(uint64_t addr) {
7260b57cec5SDimitry Andric   return (addr + 0x8000) & ~0xffff;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric 
getMipsPageCount(uint64_t size)7290b57cec5SDimitry Andric static uint64_t getMipsPageCount(uint64_t size) {
7300b57cec5SDimitry Andric   return (size + 0xfffe) / 0xffff + 1;
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric 
MipsGotSection()7330b57cec5SDimitry Andric MipsGotSection::MipsGotSection()
7340b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
7350b57cec5SDimitry Andric                        ".got") {}
7360b57cec5SDimitry Andric 
addEntry(InputFile & file,Symbol & sym,int64_t addend,RelExpr expr)7370b57cec5SDimitry Andric void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
7380b57cec5SDimitry Andric                               RelExpr expr) {
7390b57cec5SDimitry Andric   FileGot &g = getGot(file);
7400b57cec5SDimitry Andric   if (expr == R_MIPS_GOT_LOCAL_PAGE) {
7410b57cec5SDimitry Andric     if (const OutputSection *os = sym.getOutputSection())
7420b57cec5SDimitry Andric       g.pagesMap.insert({os, {}});
7430b57cec5SDimitry Andric     else
7440b57cec5SDimitry Andric       g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
7450b57cec5SDimitry Andric   } else if (sym.isTls())
7460b57cec5SDimitry Andric     g.tls.insert({&sym, 0});
7470b57cec5SDimitry Andric   else if (sym.isPreemptible && expr == R_ABS)
7480b57cec5SDimitry Andric     g.relocs.insert({&sym, 0});
7490b57cec5SDimitry Andric   else if (sym.isPreemptible)
7500b57cec5SDimitry Andric     g.global.insert({&sym, 0});
7510b57cec5SDimitry Andric   else if (expr == R_MIPS_GOT_OFF32)
7520b57cec5SDimitry Andric     g.local32.insert({{&sym, addend}, 0});
7530b57cec5SDimitry Andric   else
7540b57cec5SDimitry Andric     g.local16.insert({{&sym, addend}, 0});
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
addDynTlsEntry(InputFile & file,Symbol & sym)7570b57cec5SDimitry Andric void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
7580b57cec5SDimitry Andric   getGot(file).dynTlsSymbols.insert({&sym, 0});
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric 
addTlsIndex(InputFile & file)7610b57cec5SDimitry Andric void MipsGotSection::addTlsIndex(InputFile &file) {
7620b57cec5SDimitry Andric   getGot(file).dynTlsSymbols.insert({nullptr, 0});
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric 
getEntriesNum() const7650b57cec5SDimitry Andric size_t MipsGotSection::FileGot::getEntriesNum() const {
7660b57cec5SDimitry Andric   return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
7670b57cec5SDimitry Andric          tls.size() + dynTlsSymbols.size() * 2;
7680b57cec5SDimitry Andric }
7690b57cec5SDimitry Andric 
getPageEntriesNum() const7700b57cec5SDimitry Andric size_t MipsGotSection::FileGot::getPageEntriesNum() const {
7710b57cec5SDimitry Andric   size_t num = 0;
7720b57cec5SDimitry Andric   for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
7730b57cec5SDimitry Andric     num += p.second.count;
7740b57cec5SDimitry Andric   return num;
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric 
getIndexedEntriesNum() const7770b57cec5SDimitry Andric size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
7780b57cec5SDimitry Andric   size_t count = getPageEntriesNum() + local16.size() + global.size();
7790b57cec5SDimitry Andric   // If there are relocation-only entries in the GOT, TLS entries
7800b57cec5SDimitry Andric   // are allocated after them. TLS entries should be addressable
7810b57cec5SDimitry Andric   // by 16-bit index so count both reloc-only and TLS entries.
7820b57cec5SDimitry Andric   if (!tls.empty() || !dynTlsSymbols.empty())
7830b57cec5SDimitry Andric     count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
7840b57cec5SDimitry Andric   return count;
7850b57cec5SDimitry Andric }
7860b57cec5SDimitry Andric 
getGot(InputFile & f)7870b57cec5SDimitry Andric MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
7880eae32dcSDimitry Andric   if (f.mipsGotIndex == uint32_t(-1)) {
7890b57cec5SDimitry Andric     gots.emplace_back();
7900b57cec5SDimitry Andric     gots.back().file = &f;
7910b57cec5SDimitry Andric     f.mipsGotIndex = gots.size() - 1;
7920b57cec5SDimitry Andric   }
7930eae32dcSDimitry Andric   return gots[f.mipsGotIndex];
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
getPageEntryOffset(const InputFile * f,const Symbol & sym,int64_t addend) const7960b57cec5SDimitry Andric uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
7970b57cec5SDimitry Andric                                             const Symbol &sym,
7980b57cec5SDimitry Andric                                             int64_t addend) const {
7990eae32dcSDimitry Andric   const FileGot &g = gots[f->mipsGotIndex];
8000b57cec5SDimitry Andric   uint64_t index = 0;
8010b57cec5SDimitry Andric   if (const OutputSection *outSec = sym.getOutputSection()) {
8020b57cec5SDimitry Andric     uint64_t secAddr = getMipsPageAddr(outSec->addr);
8030b57cec5SDimitry Andric     uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
8040b57cec5SDimitry Andric     index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
8050b57cec5SDimitry Andric   } else {
8060b57cec5SDimitry Andric     index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric   return index * config->wordsize;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric 
getSymEntryOffset(const InputFile * f,const Symbol & s,int64_t addend) const8110b57cec5SDimitry Andric uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
8120b57cec5SDimitry Andric                                            int64_t addend) const {
8130eae32dcSDimitry Andric   const FileGot &g = gots[f->mipsGotIndex];
8140b57cec5SDimitry Andric   Symbol *sym = const_cast<Symbol *>(&s);
8150b57cec5SDimitry Andric   if (sym->isTls())
8160b57cec5SDimitry Andric     return g.tls.lookup(sym) * config->wordsize;
8170b57cec5SDimitry Andric   if (sym->isPreemptible)
8180b57cec5SDimitry Andric     return g.global.lookup(sym) * config->wordsize;
8190b57cec5SDimitry Andric   return g.local16.lookup({sym, addend}) * config->wordsize;
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
getTlsIndexOffset(const InputFile * f) const8220b57cec5SDimitry Andric uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
8230eae32dcSDimitry Andric   const FileGot &g = gots[f->mipsGotIndex];
8240b57cec5SDimitry Andric   return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric 
getGlobalDynOffset(const InputFile * f,const Symbol & s) const8270b57cec5SDimitry Andric uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
8280b57cec5SDimitry Andric                                             const Symbol &s) const {
8290eae32dcSDimitry Andric   const FileGot &g = gots[f->mipsGotIndex];
8300b57cec5SDimitry Andric   Symbol *sym = const_cast<Symbol *>(&s);
8310b57cec5SDimitry Andric   return g.dynTlsSymbols.lookup(sym) * config->wordsize;
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
getFirstGlobalEntry() const8340b57cec5SDimitry Andric const Symbol *MipsGotSection::getFirstGlobalEntry() const {
8350b57cec5SDimitry Andric   if (gots.empty())
8360b57cec5SDimitry Andric     return nullptr;
8370b57cec5SDimitry Andric   const FileGot &primGot = gots.front();
8380b57cec5SDimitry Andric   if (!primGot.global.empty())
8390b57cec5SDimitry Andric     return primGot.global.front().first;
8400b57cec5SDimitry Andric   if (!primGot.relocs.empty())
8410b57cec5SDimitry Andric     return primGot.relocs.front().first;
8420b57cec5SDimitry Andric   return nullptr;
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric 
getLocalEntriesNum() const8450b57cec5SDimitry Andric unsigned MipsGotSection::getLocalEntriesNum() const {
8460b57cec5SDimitry Andric   if (gots.empty())
8470b57cec5SDimitry Andric     return headerEntriesNum;
8480b57cec5SDimitry Andric   return headerEntriesNum + gots.front().getPageEntriesNum() +
8490b57cec5SDimitry Andric          gots.front().local16.size();
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
tryMergeGots(FileGot & dst,FileGot & src,bool isPrimary)8520b57cec5SDimitry Andric bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
8530b57cec5SDimitry Andric   FileGot tmp = dst;
8540b57cec5SDimitry Andric   set_union(tmp.pagesMap, src.pagesMap);
8550b57cec5SDimitry Andric   set_union(tmp.local16, src.local16);
8560b57cec5SDimitry Andric   set_union(tmp.global, src.global);
8570b57cec5SDimitry Andric   set_union(tmp.relocs, src.relocs);
8580b57cec5SDimitry Andric   set_union(tmp.tls, src.tls);
8590b57cec5SDimitry Andric   set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   size_t count = isPrimary ? headerEntriesNum : 0;
8620b57cec5SDimitry Andric   count += tmp.getIndexedEntriesNum();
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   if (count * config->wordsize > config->mipsGotSize)
8650b57cec5SDimitry Andric     return false;
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   std::swap(tmp, dst);
8680b57cec5SDimitry Andric   return true;
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
finalizeContents()8710b57cec5SDimitry Andric void MipsGotSection::finalizeContents() { updateAllocSize(); }
8720b57cec5SDimitry Andric 
updateAllocSize()8730b57cec5SDimitry Andric bool MipsGotSection::updateAllocSize() {
8740b57cec5SDimitry Andric   size = headerEntriesNum * config->wordsize;
8750b57cec5SDimitry Andric   for (const FileGot &g : gots)
8760b57cec5SDimitry Andric     size += g.getEntriesNum() * config->wordsize;
8770b57cec5SDimitry Andric   return false;
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
build()8800b57cec5SDimitry Andric void MipsGotSection::build() {
8810b57cec5SDimitry Andric   if (gots.empty())
8820b57cec5SDimitry Andric     return;
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   std::vector<FileGot> mergedGots(1);
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   // For each GOT move non-preemptible symbols from the `Global`
8870b57cec5SDimitry Andric   // to `Local16` list. Preemptible symbol might become non-preemptible
8880b57cec5SDimitry Andric   // one if, for example, it gets a related copy relocation.
8890b57cec5SDimitry Andric   for (FileGot &got : gots) {
8900b57cec5SDimitry Andric     for (auto &p: got.global)
8910b57cec5SDimitry Andric       if (!p.first->isPreemptible)
8920b57cec5SDimitry Andric         got.local16.insert({{p.first, 0}, 0});
8930b57cec5SDimitry Andric     got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
8940b57cec5SDimitry Andric       return !p.first->isPreemptible;
8950b57cec5SDimitry Andric     });
8960b57cec5SDimitry Andric   }
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   // For each GOT remove "reloc-only" entry if there is "global"
8990b57cec5SDimitry Andric   // entry for the same symbol. And add local entries which indexed
9000b57cec5SDimitry Andric   // using 32-bit value at the end of 16-bit entries.
9010b57cec5SDimitry Andric   for (FileGot &got : gots) {
9020b57cec5SDimitry Andric     got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
9030b57cec5SDimitry Andric       return got.global.count(p.first);
9040b57cec5SDimitry Andric     });
9050b57cec5SDimitry Andric     set_union(got.local16, got.local32);
9060b57cec5SDimitry Andric     got.local32.clear();
9070b57cec5SDimitry Andric   }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   // Evaluate number of "reloc-only" entries in the resulting GOT.
9100b57cec5SDimitry Andric   // To do that put all unique "reloc-only" and "global" entries
9110b57cec5SDimitry Andric   // from all GOTs to the future primary GOT.
9120b57cec5SDimitry Andric   FileGot *primGot = &mergedGots.front();
9130b57cec5SDimitry Andric   for (FileGot &got : gots) {
9140b57cec5SDimitry Andric     set_union(primGot->relocs, got.global);
9150b57cec5SDimitry Andric     set_union(primGot->relocs, got.relocs);
9160b57cec5SDimitry Andric     got.relocs.clear();
9170b57cec5SDimitry Andric   }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric   // Evaluate number of "page" entries in each GOT.
9200b57cec5SDimitry Andric   for (FileGot &got : gots) {
9210b57cec5SDimitry Andric     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
9220b57cec5SDimitry Andric          got.pagesMap) {
9230b57cec5SDimitry Andric       const OutputSection *os = p.first;
9240b57cec5SDimitry Andric       uint64_t secSize = 0;
9254824e7fdSDimitry Andric       for (SectionCommand *cmd : os->commands) {
9260b57cec5SDimitry Andric         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
9270b57cec5SDimitry Andric           for (InputSection *isec : isd->sections) {
928bdd1243dSDimitry Andric             uint64_t off = alignToPowerOf2(secSize, isec->addralign);
9290b57cec5SDimitry Andric             secSize = off + isec->getSize();
9300b57cec5SDimitry Andric           }
9310b57cec5SDimitry Andric       }
9320b57cec5SDimitry Andric       p.second.count = getMipsPageCount(secSize);
9330b57cec5SDimitry Andric     }
9340b57cec5SDimitry Andric   }
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
9370b57cec5SDimitry Andric   // maximum GOT size. At first, try to fill the primary GOT because
9380b57cec5SDimitry Andric   // the primary GOT can be accessed in the most effective way. If it
9390b57cec5SDimitry Andric   // is not possible, try to fill the last GOT in the list, and finally
9400b57cec5SDimitry Andric   // create a new GOT if both attempts failed.
9410b57cec5SDimitry Andric   for (FileGot &srcGot : gots) {
9420b57cec5SDimitry Andric     InputFile *file = srcGot.file;
9430b57cec5SDimitry Andric     if (tryMergeGots(mergedGots.front(), srcGot, true)) {
9440b57cec5SDimitry Andric       file->mipsGotIndex = 0;
9450b57cec5SDimitry Andric     } else {
9460b57cec5SDimitry Andric       // If this is the first time we failed to merge with the primary GOT,
9470b57cec5SDimitry Andric       // MergedGots.back() will also be the primary GOT. We must make sure not
9480b57cec5SDimitry Andric       // to try to merge again with isPrimary=false, as otherwise, if the
9490b57cec5SDimitry Andric       // inputs are just right, we could allow the primary GOT to become 1 or 2
9500b57cec5SDimitry Andric       // words bigger due to ignoring the header size.
9510b57cec5SDimitry Andric       if (mergedGots.size() == 1 ||
9520b57cec5SDimitry Andric           !tryMergeGots(mergedGots.back(), srcGot, false)) {
9530b57cec5SDimitry Andric         mergedGots.emplace_back();
9540b57cec5SDimitry Andric         std::swap(mergedGots.back(), srcGot);
9550b57cec5SDimitry Andric       }
9560b57cec5SDimitry Andric       file->mipsGotIndex = mergedGots.size() - 1;
9570b57cec5SDimitry Andric     }
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric   std::swap(gots, mergedGots);
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   // Reduce number of "reloc-only" entries in the primary GOT
962480093f4SDimitry Andric   // by subtracting "global" entries in the primary GOT.
9630b57cec5SDimitry Andric   primGot = &gots.front();
9640b57cec5SDimitry Andric   primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
9650b57cec5SDimitry Andric     return primGot->global.count(p.first);
9660b57cec5SDimitry Andric   });
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   // Calculate indexes for each GOT entry.
9690b57cec5SDimitry Andric   size_t index = headerEntriesNum;
9700b57cec5SDimitry Andric   for (FileGot &got : gots) {
9710b57cec5SDimitry Andric     got.startIndex = &got == primGot ? 0 : index;
9720b57cec5SDimitry Andric     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
9730b57cec5SDimitry Andric          got.pagesMap) {
9740b57cec5SDimitry Andric       // For each output section referenced by GOT page relocations calculate
9750b57cec5SDimitry Andric       // and save into pagesMap an upper bound of MIPS GOT entries required
9760b57cec5SDimitry Andric       // to store page addresses of local symbols. We assume the worst case -
9770b57cec5SDimitry Andric       // each 64kb page of the output section has at least one GOT relocation
9780b57cec5SDimitry Andric       // against it. And take in account the case when the section intersects
9790b57cec5SDimitry Andric       // page boundaries.
9800b57cec5SDimitry Andric       p.second.firstIndex = index;
9810b57cec5SDimitry Andric       index += p.second.count;
9820b57cec5SDimitry Andric     }
9830b57cec5SDimitry Andric     for (auto &p: got.local16)
9840b57cec5SDimitry Andric       p.second = index++;
9850b57cec5SDimitry Andric     for (auto &p: got.global)
9860b57cec5SDimitry Andric       p.second = index++;
9870b57cec5SDimitry Andric     for (auto &p: got.relocs)
9880b57cec5SDimitry Andric       p.second = index++;
9890b57cec5SDimitry Andric     for (auto &p: got.tls)
9900b57cec5SDimitry Andric       p.second = index++;
9910b57cec5SDimitry Andric     for (auto &p: got.dynTlsSymbols) {
9920b57cec5SDimitry Andric       p.second = index;
9930b57cec5SDimitry Andric       index += 2;
9940b57cec5SDimitry Andric     }
9950b57cec5SDimitry Andric   }
9960b57cec5SDimitry Andric 
99704eeddc0SDimitry Andric   // Update SymbolAux::gotIdx field to use this
9980b57cec5SDimitry Andric   // value later in the `sortMipsSymbols` function.
99904eeddc0SDimitry Andric   for (auto &p : primGot->global) {
1000bdd1243dSDimitry Andric     if (p.first->auxIdx == 0)
100104eeddc0SDimitry Andric       p.first->allocateAux();
100204eeddc0SDimitry Andric     symAux.back().gotIdx = p.second;
100304eeddc0SDimitry Andric   }
100404eeddc0SDimitry Andric   for (auto &p : primGot->relocs) {
1005bdd1243dSDimitry Andric     if (p.first->auxIdx == 0)
100604eeddc0SDimitry Andric       p.first->allocateAux();
100704eeddc0SDimitry Andric     symAux.back().gotIdx = p.second;
100804eeddc0SDimitry Andric   }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   // Create dynamic relocations.
10110b57cec5SDimitry Andric   for (FileGot &got : gots) {
10120b57cec5SDimitry Andric     // Create dynamic relocations for TLS entries.
10130b57cec5SDimitry Andric     for (std::pair<Symbol *, size_t> &p : got.tls) {
10140b57cec5SDimitry Andric       Symbol *s = p.first;
10150b57cec5SDimitry Andric       uint64_t offset = p.second * config->wordsize;
1016fe6060f1SDimitry Andric       // When building a shared library we still need a dynamic relocation
1017fe6060f1SDimitry Andric       // for the TP-relative offset as we don't know how much other data will
1018fe6060f1SDimitry Andric       // be allocated before us in the static TLS block.
1019fe6060f1SDimitry Andric       if (s->isPreemptible || config->shared)
1020fe6060f1SDimitry Andric         mainPart->relaDyn->addReloc({target->tlsGotRel, this, offset,
1021fe6060f1SDimitry Andric                                      DynamicReloc::AgainstSymbolWithTargetVA,
1022fe6060f1SDimitry Andric                                      *s, 0, R_ABS});
10230b57cec5SDimitry Andric     }
10240b57cec5SDimitry Andric     for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
10250b57cec5SDimitry Andric       Symbol *s = p.first;
10260b57cec5SDimitry Andric       uint64_t offset = p.second * config->wordsize;
10270b57cec5SDimitry Andric       if (s == nullptr) {
1028fe6060f1SDimitry Andric         if (!config->shared)
10290b57cec5SDimitry Andric           continue;
1030fe6060f1SDimitry Andric         mainPart->relaDyn->addReloc({target->tlsModuleIndexRel, this, offset});
10310b57cec5SDimitry Andric       } else {
10320b57cec5SDimitry Andric         // When building a shared library we still need a dynamic relocation
10330b57cec5SDimitry Andric         // for the module index. Therefore only checking for
10340b57cec5SDimitry Andric         // S->isPreemptible is not sufficient (this happens e.g. for
10350b57cec5SDimitry Andric         // thread-locals that have been marked as local through a linker script)
1036fe6060f1SDimitry Andric         if (!s->isPreemptible && !config->shared)
10370b57cec5SDimitry Andric           continue;
10380eae32dcSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *this,
1039fe6060f1SDimitry Andric                                           offset, *s);
10400b57cec5SDimitry Andric         // However, we can skip writing the TLS offset reloc for non-preemptible
10410b57cec5SDimitry Andric         // symbols since it is known even in shared libraries
10420b57cec5SDimitry Andric         if (!s->isPreemptible)
10430b57cec5SDimitry Andric           continue;
10440b57cec5SDimitry Andric         offset += config->wordsize;
10450eae32dcSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *this, offset,
1046fe6060f1SDimitry Andric                                           *s);
10470b57cec5SDimitry Andric       }
10480b57cec5SDimitry Andric     }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric     // Do not create dynamic relocations for non-TLS
10510b57cec5SDimitry Andric     // entries in the primary GOT.
10520b57cec5SDimitry Andric     if (&got == primGot)
10530b57cec5SDimitry Andric       continue;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric     // Dynamic relocations for "global" entries.
10560b57cec5SDimitry Andric     for (const std::pair<Symbol *, size_t> &p : got.global) {
10570b57cec5SDimitry Andric       uint64_t offset = p.second * config->wordsize;
10580eae32dcSDimitry Andric       mainPart->relaDyn->addSymbolReloc(target->relativeRel, *this, offset,
1059fe6060f1SDimitry Andric                                         *p.first);
10600b57cec5SDimitry Andric     }
10610b57cec5SDimitry Andric     if (!config->isPic)
10620b57cec5SDimitry Andric       continue;
10630b57cec5SDimitry Andric     // Dynamic relocations for "local" entries in case of PIC.
10640b57cec5SDimitry Andric     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
10650b57cec5SDimitry Andric          got.pagesMap) {
10660b57cec5SDimitry Andric       size_t pageCount = l.second.count;
10670b57cec5SDimitry Andric       for (size_t pi = 0; pi < pageCount; ++pi) {
10680b57cec5SDimitry Andric         uint64_t offset = (l.second.firstIndex + pi) * config->wordsize;
10690b57cec5SDimitry Andric         mainPart->relaDyn->addReloc({target->relativeRel, this, offset, l.first,
10700b57cec5SDimitry Andric                                      int64_t(pi * 0x10000)});
10710b57cec5SDimitry Andric       }
10720b57cec5SDimitry Andric     }
10730b57cec5SDimitry Andric     for (const std::pair<GotEntry, size_t> &p : got.local16) {
10740b57cec5SDimitry Andric       uint64_t offset = p.second * config->wordsize;
1075fe6060f1SDimitry Andric       mainPart->relaDyn->addReloc({target->relativeRel, this, offset,
1076fe6060f1SDimitry Andric                                    DynamicReloc::AddendOnlyWithTargetVA,
1077fe6060f1SDimitry Andric                                    *p.first.first, p.first.second, R_ABS});
10780b57cec5SDimitry Andric     }
10790b57cec5SDimitry Andric   }
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
isNeeded() const10820b57cec5SDimitry Andric bool MipsGotSection::isNeeded() const {
10830b57cec5SDimitry Andric   // We add the .got section to the result for dynamic MIPS target because
10840b57cec5SDimitry Andric   // its address and properties are mentioned in the .dynamic section.
10850b57cec5SDimitry Andric   return !config->relocatable;
10860b57cec5SDimitry Andric }
10870b57cec5SDimitry Andric 
getGp(const InputFile * f) const10880b57cec5SDimitry Andric uint64_t MipsGotSection::getGp(const InputFile *f) const {
10890b57cec5SDimitry Andric   // For files without related GOT or files refer a primary GOT
10900b57cec5SDimitry Andric   // returns "common" _gp value. For secondary GOTs calculate
10910b57cec5SDimitry Andric   // individual _gp values.
10920eae32dcSDimitry Andric   if (!f || f->mipsGotIndex == uint32_t(-1) || f->mipsGotIndex == 0)
10930b57cec5SDimitry Andric     return ElfSym::mipsGp->getVA(0);
10940eae32dcSDimitry Andric   return getVA() + gots[f->mipsGotIndex].startIndex * config->wordsize + 0x7ff0;
10950b57cec5SDimitry Andric }
10960b57cec5SDimitry Andric 
writeTo(uint8_t * buf)10970b57cec5SDimitry Andric void MipsGotSection::writeTo(uint8_t *buf) {
10980b57cec5SDimitry Andric   // Set the MSB of the second GOT slot. This is not required by any
10990b57cec5SDimitry Andric   // MIPS ABI documentation, though.
11000b57cec5SDimitry Andric   //
11010b57cec5SDimitry Andric   // There is a comment in glibc saying that "The MSB of got[1] of a
11020b57cec5SDimitry Andric   // gnu object is set to identify gnu objects," and in GNU gold it
11030b57cec5SDimitry Andric   // says "the second entry will be used by some runtime loaders".
11040b57cec5SDimitry Andric   // But how this field is being used is unclear.
11050b57cec5SDimitry Andric   //
11060b57cec5SDimitry Andric   // We are not really willing to mimic other linkers behaviors
11070b57cec5SDimitry Andric   // without understanding why they do that, but because all files
11080b57cec5SDimitry Andric   // generated by GNU tools have this special GOT value, and because
11090b57cec5SDimitry Andric   // we've been doing this for years, it is probably a safe bet to
11100b57cec5SDimitry Andric   // keep doing this for now. We really need to revisit this to see
11110b57cec5SDimitry Andric   // if we had to do this.
11120b57cec5SDimitry Andric   writeUint(buf + config->wordsize, (uint64_t)1 << (config->wordsize * 8 - 1));
11130b57cec5SDimitry Andric   for (const FileGot &g : gots) {
11140b57cec5SDimitry Andric     auto write = [&](size_t i, const Symbol *s, int64_t a) {
11150b57cec5SDimitry Andric       uint64_t va = a;
11160b57cec5SDimitry Andric       if (s)
11170b57cec5SDimitry Andric         va = s->getVA(a);
11180b57cec5SDimitry Andric       writeUint(buf + i * config->wordsize, va);
11190b57cec5SDimitry Andric     };
11200b57cec5SDimitry Andric     // Write 'page address' entries to the local part of the GOT.
11210b57cec5SDimitry Andric     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
11220b57cec5SDimitry Andric          g.pagesMap) {
11230b57cec5SDimitry Andric       size_t pageCount = l.second.count;
11240b57cec5SDimitry Andric       uint64_t firstPageAddr = getMipsPageAddr(l.first->addr);
11250b57cec5SDimitry Andric       for (size_t pi = 0; pi < pageCount; ++pi)
11260b57cec5SDimitry Andric         write(l.second.firstIndex + pi, nullptr, firstPageAddr + pi * 0x10000);
11270b57cec5SDimitry Andric     }
11280b57cec5SDimitry Andric     // Local, global, TLS, reloc-only  entries.
11290b57cec5SDimitry Andric     // If TLS entry has a corresponding dynamic relocations, leave it
11300b57cec5SDimitry Andric     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
11310b57cec5SDimitry Andric     // To calculate the adjustments use offsets for thread-local storage.
1132fe6060f1SDimitry Andric     // http://web.archive.org/web/20190324223224/https://www.linux-mips.org/wiki/NPTL
11330b57cec5SDimitry Andric     for (const std::pair<GotEntry, size_t> &p : g.local16)
11340b57cec5SDimitry Andric       write(p.second, p.first.first, p.first.second);
11350b57cec5SDimitry Andric     // Write VA to the primary GOT only. For secondary GOTs that
11360b57cec5SDimitry Andric     // will be done by REL32 dynamic relocations.
11370b57cec5SDimitry Andric     if (&g == &gots.front())
1138480093f4SDimitry Andric       for (const std::pair<Symbol *, size_t> &p : g.global)
11390b57cec5SDimitry Andric         write(p.second, p.first, 0);
11400b57cec5SDimitry Andric     for (const std::pair<Symbol *, size_t> &p : g.relocs)
11410b57cec5SDimitry Andric       write(p.second, p.first, 0);
11420b57cec5SDimitry Andric     for (const std::pair<Symbol *, size_t> &p : g.tls)
1143fe6060f1SDimitry Andric       write(p.second, p.first,
1144fe6060f1SDimitry Andric             p.first->isPreemptible || config->shared ? 0 : -0x7000);
11450b57cec5SDimitry Andric     for (const std::pair<Symbol *, size_t> &p : g.dynTlsSymbols) {
1146fe6060f1SDimitry Andric       if (p.first == nullptr && !config->shared)
11470b57cec5SDimitry Andric         write(p.second, nullptr, 1);
11480b57cec5SDimitry Andric       else if (p.first && !p.first->isPreemptible) {
1149349cc55cSDimitry Andric         // If we are emitting a shared library with relocations we mustn't write
11500b57cec5SDimitry Andric         // anything to the GOT here. When using Elf_Rel relocations the value
11510b57cec5SDimitry Andric         // one will be treated as an addend and will cause crashes at runtime
1152fe6060f1SDimitry Andric         if (!config->shared)
11530b57cec5SDimitry Andric           write(p.second, nullptr, 1);
11540b57cec5SDimitry Andric         write(p.second + 1, p.first, -0x8000);
11550b57cec5SDimitry Andric       }
11560b57cec5SDimitry Andric     }
11570b57cec5SDimitry Andric   }
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric // On PowerPC the .plt section is used to hold the table of function addresses
11610b57cec5SDimitry Andric // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
11620b57cec5SDimitry Andric // section. I don't know why we have a BSS style type for the section but it is
1163480093f4SDimitry Andric // consistent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
GotPltSection()11640b57cec5SDimitry Andric GotPltSection::GotPltSection()
11650b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
11660b57cec5SDimitry Andric                        ".got.plt") {
11670b57cec5SDimitry Andric   if (config->emachine == EM_PPC) {
11680b57cec5SDimitry Andric     name = ".plt";
11690b57cec5SDimitry Andric   } else if (config->emachine == EM_PPC64) {
11700b57cec5SDimitry Andric     type = SHT_NOBITS;
11710b57cec5SDimitry Andric     name = ".plt";
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric }
11740b57cec5SDimitry Andric 
addEntry(Symbol & sym)11750b57cec5SDimitry Andric void GotPltSection::addEntry(Symbol &sym) {
117604eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1 &&
117704eeddc0SDimitry Andric          symAux.back().pltIdx == entries.size());
11780b57cec5SDimitry Andric   entries.push_back(&sym);
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric 
getSize() const11810b57cec5SDimitry Andric size_t GotPltSection::getSize() const {
1182fe6060f1SDimitry Andric   return (target->gotPltHeaderEntriesNum + entries.size()) *
1183fe6060f1SDimitry Andric          target->gotEntrySize;
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
writeTo(uint8_t * buf)11860b57cec5SDimitry Andric void GotPltSection::writeTo(uint8_t *buf) {
11870b57cec5SDimitry Andric   target->writeGotPltHeader(buf);
1188fe6060f1SDimitry Andric   buf += target->gotPltHeaderEntriesNum * target->gotEntrySize;
11890b57cec5SDimitry Andric   for (const Symbol *b : entries) {
11900b57cec5SDimitry Andric     target->writeGotPlt(buf, *b);
1191fe6060f1SDimitry Andric     buf += target->gotEntrySize;
11920b57cec5SDimitry Andric   }
11930b57cec5SDimitry Andric }
11940b57cec5SDimitry Andric 
isNeeded() const11950b57cec5SDimitry Andric bool GotPltSection::isNeeded() const {
11960b57cec5SDimitry Andric   // We need to emit GOTPLT even if it's empty if there's a relocation relative
11970b57cec5SDimitry Andric   // to it.
11980b57cec5SDimitry Andric   return !entries.empty() || hasGotPltOffRel;
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric 
getIgotPltName()12010b57cec5SDimitry Andric static StringRef getIgotPltName() {
12020b57cec5SDimitry Andric   // On ARM the IgotPltSection is part of the GotSection.
12030b57cec5SDimitry Andric   if (config->emachine == EM_ARM)
12040b57cec5SDimitry Andric     return ".got";
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
12070b57cec5SDimitry Andric   // needs to be named the same.
12080b57cec5SDimitry Andric   if (config->emachine == EM_PPC64)
12090b57cec5SDimitry Andric     return ".plt";
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric   return ".got.plt";
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
12150b57cec5SDimitry Andric // with the IgotPltSection.
IgotPltSection()12160b57cec5SDimitry Andric IgotPltSection::IgotPltSection()
12170b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
12180b57cec5SDimitry Andric                        config->emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1219fe6060f1SDimitry Andric                        target->gotEntrySize, getIgotPltName()) {}
12200b57cec5SDimitry Andric 
addEntry(Symbol & sym)12210b57cec5SDimitry Andric void IgotPltSection::addEntry(Symbol &sym) {
122204eeddc0SDimitry Andric   assert(symAux.back().pltIdx == entries.size());
12230b57cec5SDimitry Andric   entries.push_back(&sym);
12240b57cec5SDimitry Andric }
12250b57cec5SDimitry Andric 
getSize() const12260b57cec5SDimitry Andric size_t IgotPltSection::getSize() const {
1227fe6060f1SDimitry Andric   return entries.size() * target->gotEntrySize;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric 
writeTo(uint8_t * buf)12300b57cec5SDimitry Andric void IgotPltSection::writeTo(uint8_t *buf) {
12310b57cec5SDimitry Andric   for (const Symbol *b : entries) {
12320b57cec5SDimitry Andric     target->writeIgotPlt(buf, *b);
1233fe6060f1SDimitry Andric     buf += target->gotEntrySize;
12340b57cec5SDimitry Andric   }
12350b57cec5SDimitry Andric }
12360b57cec5SDimitry Andric 
StringTableSection(StringRef name,bool dynamic)12370b57cec5SDimitry Andric StringTableSection::StringTableSection(StringRef name, bool dynamic)
12380b57cec5SDimitry Andric     : SyntheticSection(dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, name),
12390b57cec5SDimitry Andric       dynamic(dynamic) {
12400b57cec5SDimitry Andric   // ELF string tables start with a NUL byte.
12411fd87a68SDimitry Andric   strings.push_back("");
1242d781ede6SDimitry Andric   stringMap.try_emplace(CachedHashStringRef(""), 0);
12431fd87a68SDimitry Andric   size = 1;
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric // Adds a string to the string table. If `hashIt` is true we hash and check for
12470b57cec5SDimitry Andric // duplicates. It is optional because the name of global symbols are already
12480b57cec5SDimitry Andric // uniqued and hashing them again has a big cost for a small value: uniquing
12490b57cec5SDimitry Andric // them with some other string that happens to be the same.
addString(StringRef s,bool hashIt)12500b57cec5SDimitry Andric unsigned StringTableSection::addString(StringRef s, bool hashIt) {
12510b57cec5SDimitry Andric   if (hashIt) {
125204eeddc0SDimitry Andric     auto r = stringMap.try_emplace(CachedHashStringRef(s), size);
12530b57cec5SDimitry Andric     if (!r.second)
12540b57cec5SDimitry Andric       return r.first->second;
12550b57cec5SDimitry Andric   }
12561fd87a68SDimitry Andric   if (s.empty())
12571fd87a68SDimitry Andric     return 0;
12580b57cec5SDimitry Andric   unsigned ret = this->size;
12590b57cec5SDimitry Andric   this->size = this->size + s.size() + 1;
12600b57cec5SDimitry Andric   strings.push_back(s);
12610b57cec5SDimitry Andric   return ret;
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric 
writeTo(uint8_t * buf)12640b57cec5SDimitry Andric void StringTableSection::writeTo(uint8_t *buf) {
12650b57cec5SDimitry Andric   for (StringRef s : strings) {
12660b57cec5SDimitry Andric     memcpy(buf, s.data(), s.size());
12670b57cec5SDimitry Andric     buf[s.size()] = '\0';
12680b57cec5SDimitry Andric     buf += s.size() + 1;
12690b57cec5SDimitry Andric   }
12700b57cec5SDimitry Andric }
12710b57cec5SDimitry Andric 
127285868e8aSDimitry Andric // Returns the number of entries in .gnu.version_d: the number of
127385868e8aSDimitry Andric // non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
127485868e8aSDimitry Andric // Note that we don't support vd_cnt > 1 yet.
getVerDefNum()127585868e8aSDimitry Andric static unsigned getVerDefNum() {
127685868e8aSDimitry Andric   return namedVersionDefs().size() + 1;
127785868e8aSDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric template <class ELFT>
DynamicSection()12800b57cec5SDimitry Andric DynamicSection<ELFT>::DynamicSection()
12810b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, config->wordsize,
12820b57cec5SDimitry Andric                        ".dynamic") {
12830b57cec5SDimitry Andric   this->entsize = ELFT::Is64Bits ? 16 : 8;
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric   // .dynamic section is not writable on MIPS and on Fuchsia OS
12860b57cec5SDimitry Andric   // which passes -z rodynamic.
12870b57cec5SDimitry Andric   // See "Special Section" in Chapter 4 in the following document:
12880b57cec5SDimitry Andric   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
12890b57cec5SDimitry Andric   if (config->emachine == EM_MIPS || config->zRodynamic)
12900b57cec5SDimitry Andric     this->flags = SHF_ALLOC;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
129385868e8aSDimitry Andric // The output section .rela.dyn may include these synthetic sections:
129485868e8aSDimitry Andric //
129585868e8aSDimitry Andric // - part.relaDyn
129685868e8aSDimitry Andric // - in.relaPlt: this is included if a linker script places .rela.plt inside
129785868e8aSDimitry Andric //   .rela.dyn
129885868e8aSDimitry Andric //
129985868e8aSDimitry Andric // DT_RELASZ is the total size of the included sections.
addRelaSz(const RelocationBaseSection & relaDyn)130004eeddc0SDimitry Andric static uint64_t addRelaSz(const RelocationBaseSection &relaDyn) {
130104eeddc0SDimitry Andric   size_t size = relaDyn.getSize();
130204eeddc0SDimitry Andric   if (in.relaPlt->getParent() == relaDyn.getParent())
130385868e8aSDimitry Andric     size += in.relaPlt->getSize();
130485868e8aSDimitry Andric   return size;
130585868e8aSDimitry Andric }
130685868e8aSDimitry Andric 
13070b57cec5SDimitry Andric // A Linker script may assign the RELA relocation sections to the same
13080b57cec5SDimitry Andric // output section. When this occurs we cannot just use the OutputSection
13090b57cec5SDimitry Andric // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
13100b57cec5SDimitry Andric // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
addPltRelSz()13110fca6ea1SDimitry Andric static uint64_t addPltRelSz() { return in.relaPlt->getSize(); }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric // Add remaining entries to complete .dynamic contents.
13144824e7fdSDimitry Andric template <class ELFT>
13154824e7fdSDimitry Andric std::vector<std::pair<int32_t, uint64_t>>
computeContents()13164824e7fdSDimitry Andric DynamicSection<ELFT>::computeContents() {
13175ffd83dbSDimitry Andric   elf::Partition &part = getPartition();
13180b57cec5SDimitry Andric   bool isMain = part.name.empty();
13194824e7fdSDimitry Andric   std::vector<std::pair<int32_t, uint64_t>> entries;
13204824e7fdSDimitry Andric 
13214824e7fdSDimitry Andric   auto addInt = [&](int32_t tag, uint64_t val) {
13224824e7fdSDimitry Andric     entries.emplace_back(tag, val);
13234824e7fdSDimitry Andric   };
13240eae32dcSDimitry Andric   auto addInSec = [&](int32_t tag, const InputSection &sec) {
13250eae32dcSDimitry Andric     entries.emplace_back(tag, sec.getVA());
13264824e7fdSDimitry Andric   };
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   for (StringRef s : config->filterList)
13290b57cec5SDimitry Andric     addInt(DT_FILTER, part.dynStrTab->addString(s));
13300b57cec5SDimitry Andric   for (StringRef s : config->auxiliaryList)
13310b57cec5SDimitry Andric     addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   if (!config->rpath.empty())
13340b57cec5SDimitry Andric     addInt(config->enableNewDtags ? DT_RUNPATH : DT_RPATH,
13350b57cec5SDimitry Andric            part.dynStrTab->addString(config->rpath));
13360b57cec5SDimitry Andric 
1337bdd1243dSDimitry Andric   for (SharedFile *file : ctx.sharedFiles)
13380b57cec5SDimitry Andric     if (file->isNeeded)
13390b57cec5SDimitry Andric       addInt(DT_NEEDED, part.dynStrTab->addString(file->soName));
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric   if (isMain) {
13420b57cec5SDimitry Andric     if (!config->soName.empty())
13430b57cec5SDimitry Andric       addInt(DT_SONAME, part.dynStrTab->addString(config->soName));
13440b57cec5SDimitry Andric   } else {
13450b57cec5SDimitry Andric     if (!config->soName.empty())
13460b57cec5SDimitry Andric       addInt(DT_NEEDED, part.dynStrTab->addString(config->soName));
13470b57cec5SDimitry Andric     addInt(DT_SONAME, part.dynStrTab->addString(part.name));
13480b57cec5SDimitry Andric   }
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   // Set DT_FLAGS and DT_FLAGS_1.
13510b57cec5SDimitry Andric   uint32_t dtFlags = 0;
13520b57cec5SDimitry Andric   uint32_t dtFlags1 = 0;
13536e75b2fbSDimitry Andric   if (config->bsymbolic == BsymbolicKind::All)
13540b57cec5SDimitry Andric     dtFlags |= DF_SYMBOLIC;
13550b57cec5SDimitry Andric   if (config->zGlobal)
13560b57cec5SDimitry Andric     dtFlags1 |= DF_1_GLOBAL;
13570b57cec5SDimitry Andric   if (config->zInitfirst)
13580b57cec5SDimitry Andric     dtFlags1 |= DF_1_INITFIRST;
13590b57cec5SDimitry Andric   if (config->zInterpose)
13600b57cec5SDimitry Andric     dtFlags1 |= DF_1_INTERPOSE;
13610b57cec5SDimitry Andric   if (config->zNodefaultlib)
13620b57cec5SDimitry Andric     dtFlags1 |= DF_1_NODEFLIB;
13630b57cec5SDimitry Andric   if (config->zNodelete)
13640b57cec5SDimitry Andric     dtFlags1 |= DF_1_NODELETE;
13650b57cec5SDimitry Andric   if (config->zNodlopen)
13660b57cec5SDimitry Andric     dtFlags1 |= DF_1_NOOPEN;
1367dfd4db93SEd Maste   if (config->pie)
1368dfd4db93SEd Maste     dtFlags1 |= DF_1_PIE;
13690b57cec5SDimitry Andric   if (config->zNow) {
13700b57cec5SDimitry Andric     dtFlags |= DF_BIND_NOW;
13710b57cec5SDimitry Andric     dtFlags1 |= DF_1_NOW;
13720b57cec5SDimitry Andric   }
13730b57cec5SDimitry Andric   if (config->zOrigin) {
13740b57cec5SDimitry Andric     dtFlags |= DF_ORIGIN;
13750b57cec5SDimitry Andric     dtFlags1 |= DF_1_ORIGIN;
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric   if (!config->zText)
13780b57cec5SDimitry Andric     dtFlags |= DF_TEXTREL;
1379bdd1243dSDimitry Andric   if (ctx.hasTlsIe && config->shared)
13800b57cec5SDimitry Andric     dtFlags |= DF_STATIC_TLS;
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   if (dtFlags)
13830b57cec5SDimitry Andric     addInt(DT_FLAGS, dtFlags);
13840b57cec5SDimitry Andric   if (dtFlags1)
13850b57cec5SDimitry Andric     addInt(DT_FLAGS_1, dtFlags1);
13860b57cec5SDimitry Andric 
1387480093f4SDimitry Andric   // DT_DEBUG is a pointer to debug information used by debuggers at runtime. We
13880b57cec5SDimitry Andric   // need it for each process, so we don't write it for DSOs. The loader writes
13890b57cec5SDimitry Andric   // the pointer into this entry.
13900b57cec5SDimitry Andric   //
13910b57cec5SDimitry Andric   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
13920b57cec5SDimitry Andric   // systems (currently only Fuchsia OS) provide other means to give the
13930b57cec5SDimitry Andric   // debugger this information. Such systems may choose make .dynamic read-only.
13940b57cec5SDimitry Andric   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
13950b57cec5SDimitry Andric   if (!config->shared && !config->relocatable && !config->zRodynamic)
13960b57cec5SDimitry Andric     addInt(DT_DEBUG, 0);
13970b57cec5SDimitry Andric 
13980fca6ea1SDimitry Andric   if (part.relaDyn->isNeeded()) {
13990eae32dcSDimitry Andric     addInSec(part.relaDyn->dynamicTag, *part.relaDyn);
140004eeddc0SDimitry Andric     entries.emplace_back(part.relaDyn->sizeDynamicTag,
140104eeddc0SDimitry Andric                          addRelaSz(*part.relaDyn));
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric     bool isRela = config->isRela;
14040b57cec5SDimitry Andric     addInt(isRela ? DT_RELAENT : DT_RELENT,
14050b57cec5SDimitry Andric            isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric     // MIPS dynamic loader does not support RELCOUNT tag.
14080b57cec5SDimitry Andric     // The problem is in the tight relation between dynamic
14090b57cec5SDimitry Andric     // relocations and GOT. So do not emit this tag on MIPS.
14100b57cec5SDimitry Andric     if (config->emachine != EM_MIPS) {
14110b57cec5SDimitry Andric       size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
14120b57cec5SDimitry Andric       if (config->zCombreloc && numRelativeRels)
14130b57cec5SDimitry Andric         addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
14140b57cec5SDimitry Andric     }
14150b57cec5SDimitry Andric   }
141604eeddc0SDimitry Andric   if (part.relrDyn && part.relrDyn->getParent() &&
141704eeddc0SDimitry Andric       !part.relrDyn->relocs.empty()) {
14180b57cec5SDimitry Andric     addInSec(config->useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
14190eae32dcSDimitry Andric              *part.relrDyn);
14204824e7fdSDimitry Andric     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
14214824e7fdSDimitry Andric            part.relrDyn->getParent()->size);
14220b57cec5SDimitry Andric     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
14230b57cec5SDimitry Andric            sizeof(Elf_Relr));
14240b57cec5SDimitry Andric   }
14250fca6ea1SDimitry Andric   if (part.relrAuthDyn && part.relrAuthDyn->getParent() &&
14260fca6ea1SDimitry Andric       !part.relrAuthDyn->relocs.empty()) {
14270fca6ea1SDimitry Andric     addInSec(DT_AARCH64_AUTH_RELR, *part.relrAuthDyn);
14280fca6ea1SDimitry Andric     addInt(DT_AARCH64_AUTH_RELRSZ, part.relrAuthDyn->getParent()->size);
14290fca6ea1SDimitry Andric     addInt(DT_AARCH64_AUTH_RELRENT, sizeof(Elf_Relr));
14300fca6ea1SDimitry Andric   }
14310fca6ea1SDimitry Andric   if (isMain && in.relaPlt->isNeeded()) {
14320eae32dcSDimitry Andric     addInSec(DT_JMPREL, *in.relaPlt);
14334824e7fdSDimitry Andric     entries.emplace_back(DT_PLTRELSZ, addPltRelSz());
14340b57cec5SDimitry Andric     switch (config->emachine) {
14350b57cec5SDimitry Andric     case EM_MIPS:
14360eae32dcSDimitry Andric       addInSec(DT_MIPS_PLTGOT, *in.gotPlt);
14370b57cec5SDimitry Andric       break;
143874626c16SDimitry Andric     case EM_S390:
143974626c16SDimitry Andric       addInSec(DT_PLTGOT, *in.got);
144074626c16SDimitry Andric       break;
14410b57cec5SDimitry Andric     case EM_SPARCV9:
14420eae32dcSDimitry Andric       addInSec(DT_PLTGOT, *in.plt);
14430b57cec5SDimitry Andric       break;
1444e8d8bef9SDimitry Andric     case EM_AARCH64:
1445e8d8bef9SDimitry Andric       if (llvm::find_if(in.relaPlt->relocs, [](const DynamicReloc &r) {
1446e8d8bef9SDimitry Andric            return r.type == target->pltRel &&
1447e8d8bef9SDimitry Andric                   r.sym->stOther & STO_AARCH64_VARIANT_PCS;
1448e8d8bef9SDimitry Andric           }) != in.relaPlt->relocs.end())
1449e8d8bef9SDimitry Andric         addInt(DT_AARCH64_VARIANT_PCS, 0);
1450bdd1243dSDimitry Andric       addInSec(DT_PLTGOT, *in.gotPlt);
1451bdd1243dSDimitry Andric       break;
1452bdd1243dSDimitry Andric     case EM_RISCV:
1453bdd1243dSDimitry Andric       if (llvm::any_of(in.relaPlt->relocs, [](const DynamicReloc &r) {
1454bdd1243dSDimitry Andric             return r.type == target->pltRel &&
1455bdd1243dSDimitry Andric                    (r.sym->stOther & STO_RISCV_VARIANT_CC);
1456bdd1243dSDimitry Andric           }))
1457bdd1243dSDimitry Andric         addInt(DT_RISCV_VARIANT_CC, 0);
1458bdd1243dSDimitry Andric       [[fallthrough]];
14590b57cec5SDimitry Andric     default:
14600eae32dcSDimitry Andric       addInSec(DT_PLTGOT, *in.gotPlt);
14610b57cec5SDimitry Andric       break;
14620b57cec5SDimitry Andric     }
14630b57cec5SDimitry Andric     addInt(DT_PLTREL, config->isRela ? DT_RELA : DT_REL);
14640b57cec5SDimitry Andric   }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   if (config->emachine == EM_AARCH64) {
14670b57cec5SDimitry Andric     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
14680b57cec5SDimitry Andric       addInt(DT_AARCH64_BTI_PLT, 0);
14695ffd83dbSDimitry Andric     if (config->zPacPlt)
14700b57cec5SDimitry Andric       addInt(DT_AARCH64_PAC_PLT, 0);
147106c3fb27SDimitry Andric 
14721db9f3b2SDimitry Andric     if (hasMemtag()) {
147306c3fb27SDimitry Andric       addInt(DT_AARCH64_MEMTAG_MODE, config->androidMemtagMode == NT_MEMTAG_LEVEL_ASYNC);
147406c3fb27SDimitry Andric       addInt(DT_AARCH64_MEMTAG_HEAP, config->androidMemtagHeap);
147506c3fb27SDimitry Andric       addInt(DT_AARCH64_MEMTAG_STACK, config->androidMemtagStack);
14761db9f3b2SDimitry Andric       if (mainPart->memtagGlobalDescriptors->isNeeded()) {
14771db9f3b2SDimitry Andric         addInSec(DT_AARCH64_MEMTAG_GLOBALS, *mainPart->memtagGlobalDescriptors);
14781db9f3b2SDimitry Andric         addInt(DT_AARCH64_MEMTAG_GLOBALSSZ,
14791db9f3b2SDimitry Andric                mainPart->memtagGlobalDescriptors->getSize());
14805f757f3fSDimitry Andric       }
148106c3fb27SDimitry Andric     }
14820b57cec5SDimitry Andric   }
14830b57cec5SDimitry Andric 
14840eae32dcSDimitry Andric   addInSec(DT_SYMTAB, *part.dynSymTab);
14850b57cec5SDimitry Andric   addInt(DT_SYMENT, sizeof(Elf_Sym));
14860eae32dcSDimitry Andric   addInSec(DT_STRTAB, *part.dynStrTab);
14870b57cec5SDimitry Andric   addInt(DT_STRSZ, part.dynStrTab->getSize());
14880b57cec5SDimitry Andric   if (!config->zText)
14890b57cec5SDimitry Andric     addInt(DT_TEXTREL, 0);
149004eeddc0SDimitry Andric   if (part.gnuHashTab && part.gnuHashTab->getParent())
14910eae32dcSDimitry Andric     addInSec(DT_GNU_HASH, *part.gnuHashTab);
149204eeddc0SDimitry Andric   if (part.hashTab && part.hashTab->getParent())
14930eae32dcSDimitry Andric     addInSec(DT_HASH, *part.hashTab);
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   if (isMain) {
14960b57cec5SDimitry Andric     if (Out::preinitArray) {
14974824e7fdSDimitry Andric       addInt(DT_PREINIT_ARRAY, Out::preinitArray->addr);
14984824e7fdSDimitry Andric       addInt(DT_PREINIT_ARRAYSZ, Out::preinitArray->size);
14990b57cec5SDimitry Andric     }
15000b57cec5SDimitry Andric     if (Out::initArray) {
15014824e7fdSDimitry Andric       addInt(DT_INIT_ARRAY, Out::initArray->addr);
15024824e7fdSDimitry Andric       addInt(DT_INIT_ARRAYSZ, Out::initArray->size);
15030b57cec5SDimitry Andric     }
15040b57cec5SDimitry Andric     if (Out::finiArray) {
15054824e7fdSDimitry Andric       addInt(DT_FINI_ARRAY, Out::finiArray->addr);
15064824e7fdSDimitry Andric       addInt(DT_FINI_ARRAYSZ, Out::finiArray->size);
15070b57cec5SDimitry Andric     }
15080b57cec5SDimitry Andric 
1509bdd1243dSDimitry Andric     if (Symbol *b = symtab.find(config->init))
15100b57cec5SDimitry Andric       if (b->isDefined())
15114824e7fdSDimitry Andric         addInt(DT_INIT, b->getVA());
1512bdd1243dSDimitry Andric     if (Symbol *b = symtab.find(config->fini))
15130b57cec5SDimitry Andric       if (b->isDefined())
15144824e7fdSDimitry Andric         addInt(DT_FINI, b->getVA());
15150b57cec5SDimitry Andric   }
15160b57cec5SDimitry Andric 
1517480093f4SDimitry Andric   if (part.verSym && part.verSym->isNeeded())
15180eae32dcSDimitry Andric     addInSec(DT_VERSYM, *part.verSym);
1519480093f4SDimitry Andric   if (part.verDef && part.verDef->isLive()) {
15200eae32dcSDimitry Andric     addInSec(DT_VERDEF, *part.verDef);
15210b57cec5SDimitry Andric     addInt(DT_VERDEFNUM, getVerDefNum());
15220b57cec5SDimitry Andric   }
1523480093f4SDimitry Andric   if (part.verNeed && part.verNeed->isNeeded()) {
15240eae32dcSDimitry Andric     addInSec(DT_VERNEED, *part.verNeed);
15250b57cec5SDimitry Andric     unsigned needNum = 0;
1526bdd1243dSDimitry Andric     for (SharedFile *f : ctx.sharedFiles)
15270b57cec5SDimitry Andric       if (!f->vernauxs.empty())
15280b57cec5SDimitry Andric         ++needNum;
15290b57cec5SDimitry Andric     addInt(DT_VERNEEDNUM, needNum);
15300b57cec5SDimitry Andric   }
15310b57cec5SDimitry Andric 
15320b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
15330b57cec5SDimitry Andric     addInt(DT_MIPS_RLD_VERSION, 1);
15340b57cec5SDimitry Andric     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
15350b57cec5SDimitry Andric     addInt(DT_MIPS_BASE_ADDRESS, target->getImageBase());
15360b57cec5SDimitry Andric     addInt(DT_MIPS_SYMTABNO, part.dynSymTab->getNumSymbols());
15374824e7fdSDimitry Andric     addInt(DT_MIPS_LOCAL_GOTNO, in.mipsGot->getLocalEntriesNum());
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric     if (const Symbol *b = in.mipsGot->getFirstGlobalEntry())
15400b57cec5SDimitry Andric       addInt(DT_MIPS_GOTSYM, b->dynsymIndex);
15410b57cec5SDimitry Andric     else
15420b57cec5SDimitry Andric       addInt(DT_MIPS_GOTSYM, part.dynSymTab->getNumSymbols());
15430eae32dcSDimitry Andric     addInSec(DT_PLTGOT, *in.mipsGot);
15440b57cec5SDimitry Andric     if (in.mipsRldMap) {
15450b57cec5SDimitry Andric       if (!config->pie)
15460eae32dcSDimitry Andric         addInSec(DT_MIPS_RLD_MAP, *in.mipsRldMap);
15470b57cec5SDimitry Andric       // Store the offset to the .rld_map section
15480b57cec5SDimitry Andric       // relative to the address of the tag.
15494824e7fdSDimitry Andric       addInt(DT_MIPS_RLD_MAP_REL,
15504824e7fdSDimitry Andric              in.mipsRldMap->getVA() - (getVA() + entries.size() * entsize));
15510b57cec5SDimitry Andric     }
15520b57cec5SDimitry Andric   }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric   // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
15550b57cec5SDimitry Andric   // glibc assumes the old-style BSS PLT layout which we don't support.
15560b57cec5SDimitry Andric   if (config->emachine == EM_PPC)
15570eae32dcSDimitry Andric     addInSec(DT_PPC_GOT, *in.got);
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
15600b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 && in.plt->isNeeded()) {
15610b57cec5SDimitry Andric     // The Glink tag points to 32 bytes before the first lazy symbol resolution
15620b57cec5SDimitry Andric     // stub, which starts directly after the header.
15634824e7fdSDimitry Andric     addInt(DT_PPC64_GLINK, in.plt->getVA() + target->pltHeaderSize - 32);
15640b57cec5SDimitry Andric   }
15650b57cec5SDimitry Andric 
156606c3fb27SDimitry Andric   if (config->emachine == EM_PPC64)
156706c3fb27SDimitry Andric     addInt(DT_PPC64_OPT, getPPC64TargetInfo()->ppc64DynamicSectionOpt);
156806c3fb27SDimitry Andric 
15690b57cec5SDimitry Andric   addInt(DT_NULL, 0);
15704824e7fdSDimitry Andric   return entries;
15714824e7fdSDimitry Andric }
15720b57cec5SDimitry Andric 
finalizeContents()15734824e7fdSDimitry Andric template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
15744824e7fdSDimitry Andric   if (OutputSection *sec = getPartition().dynStrTab->getParent())
15754824e7fdSDimitry Andric     getParent()->link = sec->sectionIndex;
15764824e7fdSDimitry Andric   this->size = computeContents().size() * this->entsize;
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric 
writeTo(uint8_t * buf)15790b57cec5SDimitry Andric template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *buf) {
15800b57cec5SDimitry Andric   auto *p = reinterpret_cast<Elf_Dyn *>(buf);
15810b57cec5SDimitry Andric 
15824824e7fdSDimitry Andric   for (std::pair<int32_t, uint64_t> kv : computeContents()) {
15830b57cec5SDimitry Andric     p->d_tag = kv.first;
15844824e7fdSDimitry Andric     p->d_un.d_val = kv.second;
15850b57cec5SDimitry Andric     ++p;
15860b57cec5SDimitry Andric   }
15870b57cec5SDimitry Andric }
15880b57cec5SDimitry Andric 
getOffset() const15890b57cec5SDimitry Andric uint64_t DynamicReloc::getOffset() const {
15900b57cec5SDimitry Andric   return inputSec->getVA(offsetInSec);
15910b57cec5SDimitry Andric }
15920b57cec5SDimitry Andric 
computeAddend() const15930b57cec5SDimitry Andric int64_t DynamicReloc::computeAddend() const {
1594fe6060f1SDimitry Andric   switch (kind) {
1595fe6060f1SDimitry Andric   case AddendOnly:
1596fe6060f1SDimitry Andric     assert(sym == nullptr);
15970b57cec5SDimitry Andric     return addend;
1598fe6060f1SDimitry Andric   case AgainstSymbol:
1599fe6060f1SDimitry Andric     assert(sym != nullptr);
1600fe6060f1SDimitry Andric     return addend;
1601fe6060f1SDimitry Andric   case AddendOnlyWithTargetVA:
160206c3fb27SDimitry Andric   case AgainstSymbolWithTargetVA: {
160306c3fb27SDimitry Andric     uint64_t ca = InputSection::getRelocTargetVA(inputSec->file, type, addend,
1604fe6060f1SDimitry Andric                                                  getOffset(), *sym, expr);
160506c3fb27SDimitry Andric     return config->is64 ? ca : SignExtend64<32>(ca);
160606c3fb27SDimitry Andric   }
1607fe6060f1SDimitry Andric   case MipsMultiGotPage:
1608fe6060f1SDimitry Andric     assert(sym == nullptr);
16090b57cec5SDimitry Andric     return getMipsPageAddr(outputSec->addr) + addend;
16100b57cec5SDimitry Andric   }
1611fe6060f1SDimitry Andric   llvm_unreachable("Unknown DynamicReloc::Kind enum");
1612fe6060f1SDimitry Andric }
16130b57cec5SDimitry Andric 
getSymIndex(SymbolTableBaseSection * symTab) const16140b57cec5SDimitry Andric uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *symTab) const {
161581ad6265SDimitry Andric   if (!needsDynSymIndex())
16160b57cec5SDimitry Andric     return 0;
161781ad6265SDimitry Andric 
16180fca6ea1SDimitry Andric   size_t index = symTab->getSymbolIndex(*sym);
161981ad6265SDimitry Andric   assert((index != 0 || (type != target->gotRel && type != target->pltRel) ||
162081ad6265SDimitry Andric           !mainPart->dynSymTab->getParent()) &&
162181ad6265SDimitry Andric          "GOT or PLT relocation must refer to symbol in dynamic symbol table");
162281ad6265SDimitry Andric   return index;
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric 
RelocationBaseSection(StringRef name,uint32_t type,int32_t dynamicTag,int32_t sizeDynamicTag,bool combreloc,unsigned concurrency)16250b57cec5SDimitry Andric RelocationBaseSection::RelocationBaseSection(StringRef name, uint32_t type,
16260b57cec5SDimitry Andric                                              int32_t dynamicTag,
16271fd87a68SDimitry Andric                                              int32_t sizeDynamicTag,
1628bdd1243dSDimitry Andric                                              bool combreloc,
1629bdd1243dSDimitry Andric                                              unsigned concurrency)
16300b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, type, config->wordsize, name),
16311fd87a68SDimitry Andric       dynamicTag(dynamicTag), sizeDynamicTag(sizeDynamicTag),
1632bdd1243dSDimitry Andric       relocsVec(concurrency), combreloc(combreloc) {}
16330b57cec5SDimitry Andric 
addSymbolReloc(RelType dynType,InputSectionBase & isec,uint64_t offsetInSec,Symbol & sym,int64_t addend,std::optional<RelType> addendRelType)1634bdd1243dSDimitry Andric void RelocationBaseSection::addSymbolReloc(
1635bdd1243dSDimitry Andric     RelType dynType, InputSectionBase &isec, uint64_t offsetInSec, Symbol &sym,
1636bdd1243dSDimitry Andric     int64_t addend, std::optional<RelType> addendRelType) {
1637fe6060f1SDimitry Andric   addReloc(DynamicReloc::AgainstSymbol, dynType, isec, offsetInSec, sym, addend,
1638fe6060f1SDimitry Andric            R_ADDEND, addendRelType ? *addendRelType : target->noneRel);
16390b57cec5SDimitry Andric }
16400b57cec5SDimitry Andric 
addAddendOnlyRelocIfNonPreemptible(RelType dynType,GotSection & sec,uint64_t offsetInSec,Symbol & sym,RelType addendRelType)1641fe6060f1SDimitry Andric void RelocationBaseSection::addAddendOnlyRelocIfNonPreemptible(
1642bdd1243dSDimitry Andric     RelType dynType, GotSection &sec, uint64_t offsetInSec, Symbol &sym,
1643fe6060f1SDimitry Andric     RelType addendRelType) {
1644fe6060f1SDimitry Andric   // No need to write an addend to the section for preemptible symbols.
1645fe6060f1SDimitry Andric   if (sym.isPreemptible)
1646bdd1243dSDimitry Andric     addReloc({dynType, &sec, offsetInSec, DynamicReloc::AgainstSymbol, sym, 0,
1647fe6060f1SDimitry Andric               R_ABS});
1648fe6060f1SDimitry Andric   else
1649bdd1243dSDimitry Andric     addReloc(DynamicReloc::AddendOnlyWithTargetVA, dynType, sec, offsetInSec,
1650fe6060f1SDimitry Andric              sym, 0, R_ABS, addendRelType);
1651fe6060f1SDimitry Andric }
1652fe6060f1SDimitry Andric 
mergeRels()1653bdd1243dSDimitry Andric void RelocationBaseSection::mergeRels() {
1654bdd1243dSDimitry Andric   size_t newSize = relocs.size();
1655bdd1243dSDimitry Andric   for (const auto &v : relocsVec)
1656bdd1243dSDimitry Andric     newSize += v.size();
1657bdd1243dSDimitry Andric   relocs.reserve(newSize);
1658bdd1243dSDimitry Andric   for (const auto &v : relocsVec)
1659bdd1243dSDimitry Andric     llvm::append_range(relocs, v);
1660bdd1243dSDimitry Andric   relocsVec.clear();
16610b57cec5SDimitry Andric }
16620b57cec5SDimitry Andric 
partitionRels()16631fd87a68SDimitry Andric void RelocationBaseSection::partitionRels() {
16641fd87a68SDimitry Andric   if (!combreloc)
16651fd87a68SDimitry Andric     return;
16661fd87a68SDimitry Andric   const RelType relativeRel = target->relativeRel;
16671fd87a68SDimitry Andric   numRelativeRelocs =
16680fca6ea1SDimitry Andric       std::stable_partition(relocs.begin(), relocs.end(),
16690fca6ea1SDimitry Andric                             [=](auto &r) { return r.type == relativeRel; }) -
16701fd87a68SDimitry Andric       relocs.begin();
16710b57cec5SDimitry Andric }
16720b57cec5SDimitry Andric 
finalizeContents()16730b57cec5SDimitry Andric void RelocationBaseSection::finalizeContents() {
167404eeddc0SDimitry Andric   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
16770b57cec5SDimitry Andric   // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
16780b57cec5SDimitry Andric   // case.
16790b57cec5SDimitry Andric   if (symTab && symTab->getParent())
16800b57cec5SDimitry Andric     getParent()->link = symTab->getParent()->sectionIndex;
16810b57cec5SDimitry Andric   else
16820b57cec5SDimitry Andric     getParent()->link = 0;
16830b57cec5SDimitry Andric 
168404eeddc0SDimitry Andric   if (in.relaPlt.get() == this && in.gotPlt->getParent()) {
1685e8d8bef9SDimitry Andric     getParent()->flags |= ELF::SHF_INFO_LINK;
16860b57cec5SDimitry Andric     getParent()->info = in.gotPlt->getParent()->sectionIndex;
1687e8d8bef9SDimitry Andric   }
1688e8d8bef9SDimitry Andric }
16890b57cec5SDimitry Andric 
computeRaw(SymbolTableBaseSection * symtab)16900eae32dcSDimitry Andric void DynamicReloc::computeRaw(SymbolTableBaseSection *symtab) {
16910eae32dcSDimitry Andric   r_offset = getOffset();
16920eae32dcSDimitry Andric   r_sym = getSymIndex(symtab);
16930eae32dcSDimitry Andric   addend = computeAddend();
16940eae32dcSDimitry Andric   kind = AddendOnly; // Catch errors
16950b57cec5SDimitry Andric }
16960b57cec5SDimitry Andric 
computeRels()16971fd87a68SDimitry Andric void RelocationBaseSection::computeRels() {
169804eeddc0SDimitry Andric   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
16990eae32dcSDimitry Andric   parallelForEach(relocs,
17000eae32dcSDimitry Andric                   [symTab](DynamicReloc &rel) { rel.computeRaw(symTab); });
17010fca6ea1SDimitry Andric 
17020fca6ea1SDimitry Andric   auto irelative = std::stable_partition(
17030fca6ea1SDimitry Andric       relocs.begin() + numRelativeRelocs, relocs.end(),
17040fca6ea1SDimitry Andric       [t = target->iRelativeRel](auto &r) { return r.type != t; });
17050fca6ea1SDimitry Andric 
17060b57cec5SDimitry Andric   // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
17070b57cec5SDimitry Andric   // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
17080b57cec5SDimitry Andric   // is to make results easier to read.
17091fd87a68SDimitry Andric   if (combreloc) {
17101fd87a68SDimitry Andric     auto nonRelative = relocs.begin() + numRelativeRelocs;
171104eeddc0SDimitry Andric     parallelSort(relocs.begin(), nonRelative,
171204eeddc0SDimitry Andric                  [&](auto &a, auto &b) { return a.r_offset < b.r_offset; });
171304eeddc0SDimitry Andric     // Non-relative relocations are few, so don't bother with parallelSort.
17140fca6ea1SDimitry Andric     llvm::sort(nonRelative, irelative, [&](auto &a, auto &b) {
171504eeddc0SDimitry Andric       return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset);
17160b57cec5SDimitry Andric     });
17170eae32dcSDimitry Andric   }
17181fd87a68SDimitry Andric }
17190b57cec5SDimitry Andric 
17201fd87a68SDimitry Andric template <class ELFT>
RelocationSection(StringRef name,bool combreloc,unsigned concurrency)1721bdd1243dSDimitry Andric RelocationSection<ELFT>::RelocationSection(StringRef name, bool combreloc,
1722bdd1243dSDimitry Andric                                            unsigned concurrency)
17231fd87a68SDimitry Andric     : RelocationBaseSection(name, config->isRela ? SHT_RELA : SHT_REL,
17241fd87a68SDimitry Andric                             config->isRela ? DT_RELA : DT_REL,
1725bdd1243dSDimitry Andric                             config->isRela ? DT_RELASZ : DT_RELSZ, combreloc,
1726bdd1243dSDimitry Andric                             concurrency) {
17271fd87a68SDimitry Andric   this->entsize = config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
17281fd87a68SDimitry Andric }
17291fd87a68SDimitry Andric 
writeTo(uint8_t * buf)17301fd87a68SDimitry Andric template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *buf) {
17311fd87a68SDimitry Andric   computeRels();
17320b57cec5SDimitry Andric   for (const DynamicReloc &rel : relocs) {
17331fd87a68SDimitry Andric     auto *p = reinterpret_cast<Elf_Rela *>(buf);
17341fd87a68SDimitry Andric     p->r_offset = rel.r_offset;
17351fd87a68SDimitry Andric     p->setSymbolAndType(rel.r_sym, rel.type, config->isMips64EL);
17361fd87a68SDimitry Andric     if (config->isRela)
17371fd87a68SDimitry Andric       p->r_addend = rel.addend;
17380b57cec5SDimitry Andric     buf += config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
17390b57cec5SDimitry Andric   }
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric 
RelrBaseSection(unsigned concurrency,bool isAArch64Auth)17420fca6ea1SDimitry Andric RelrBaseSection::RelrBaseSection(unsigned concurrency, bool isAArch64Auth)
17430fca6ea1SDimitry Andric     : SyntheticSection(
17440fca6ea1SDimitry Andric           SHF_ALLOC,
17450fca6ea1SDimitry Andric           isAArch64Auth
17460fca6ea1SDimitry Andric               ? SHT_AARCH64_AUTH_RELR
17470fca6ea1SDimitry Andric               : (config->useAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR),
17480fca6ea1SDimitry Andric           config->wordsize, isAArch64Auth ? ".relr.auth.dyn" : ".relr.dyn"),
1749bdd1243dSDimitry Andric       relocsVec(concurrency) {}
1750bdd1243dSDimitry Andric 
mergeRels()1751bdd1243dSDimitry Andric void RelrBaseSection::mergeRels() {
1752bdd1243dSDimitry Andric   size_t newSize = relocs.size();
1753bdd1243dSDimitry Andric   for (const auto &v : relocsVec)
1754bdd1243dSDimitry Andric     newSize += v.size();
1755bdd1243dSDimitry Andric   relocs.reserve(newSize);
1756bdd1243dSDimitry Andric   for (const auto &v : relocsVec)
1757bdd1243dSDimitry Andric     llvm::append_range(relocs, v);
1758bdd1243dSDimitry Andric   relocsVec.clear();
1759bdd1243dSDimitry Andric }
17601fd87a68SDimitry Andric 
17610b57cec5SDimitry Andric template <class ELFT>
AndroidPackedRelocationSection(StringRef name,unsigned concurrency)17620b57cec5SDimitry Andric AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1763bdd1243dSDimitry Andric     StringRef name, unsigned concurrency)
17640b57cec5SDimitry Andric     : RelocationBaseSection(
17650b57cec5SDimitry Andric           name, config->isRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
17660b57cec5SDimitry Andric           config->isRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
17671fd87a68SDimitry Andric           config->isRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ,
1768bdd1243dSDimitry Andric           /*combreloc=*/false, concurrency) {
17690b57cec5SDimitry Andric   this->entsize = 1;
17700b57cec5SDimitry Andric }
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric template <class ELFT>
updateAllocSize()17730b57cec5SDimitry Andric bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
17740b57cec5SDimitry Andric   // This function computes the contents of an Android-format packed relocation
17750b57cec5SDimitry Andric   // section.
17760b57cec5SDimitry Andric   //
17770b57cec5SDimitry Andric   // This format compresses relocations by using relocation groups to factor out
17780b57cec5SDimitry Andric   // fields that are common between relocations and storing deltas from previous
17790b57cec5SDimitry Andric   // relocations in SLEB128 format (which has a short representation for small
17800b57cec5SDimitry Andric   // numbers). A good example of a relocation type with common fields is
17810b57cec5SDimitry Andric   // R_*_RELATIVE, which is normally used to represent function pointers in
17820b57cec5SDimitry Andric   // vtables. In the REL format, each relative relocation has the same r_info
17830b57cec5SDimitry Andric   // field, and is only different from other relative relocations in terms of
17840b57cec5SDimitry Andric   // the r_offset field. By sorting relocations by offset, grouping them by
17850b57cec5SDimitry Andric   // r_info and representing each relocation with only the delta from the
17860b57cec5SDimitry Andric   // previous offset, each 8-byte relocation can be compressed to as little as 1
17870b57cec5SDimitry Andric   // byte (or less with run-length encoding). This relocation packer was able to
17880b57cec5SDimitry Andric   // reduce the size of the relocation section in an Android Chromium DSO from
17890b57cec5SDimitry Andric   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
17900b57cec5SDimitry Andric   //
17910b57cec5SDimitry Andric   // A relocation section consists of a header containing the literal bytes
17920b57cec5SDimitry Andric   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
17930b57cec5SDimitry Andric   // elements are the total number of relocations in the section and an initial
17940b57cec5SDimitry Andric   // r_offset value. The remaining elements define a sequence of relocation
17950b57cec5SDimitry Andric   // groups. Each relocation group starts with a header consisting of the
17960b57cec5SDimitry Andric   // following elements:
17970b57cec5SDimitry Andric   //
17980b57cec5SDimitry Andric   // - the number of relocations in the relocation group
17990b57cec5SDimitry Andric   // - flags for the relocation group
18000b57cec5SDimitry Andric   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
18010b57cec5SDimitry Andric   //   for each relocation in the group.
18020b57cec5SDimitry Andric   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
18030b57cec5SDimitry Andric   //   field for each relocation in the group.
18040b57cec5SDimitry Andric   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
18050b57cec5SDimitry Andric   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
18060b57cec5SDimitry Andric   //   each relocation in the group.
18070b57cec5SDimitry Andric   //
18080b57cec5SDimitry Andric   // Following the relocation group header are descriptions of each of the
18090b57cec5SDimitry Andric   // relocations in the group. They consist of the following elements:
18100b57cec5SDimitry Andric   //
18110b57cec5SDimitry Andric   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
18120b57cec5SDimitry Andric   //   delta for this relocation.
18130b57cec5SDimitry Andric   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
18140b57cec5SDimitry Andric   //   field for this relocation.
18150b57cec5SDimitry Andric   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
18160b57cec5SDimitry Andric   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
18170b57cec5SDimitry Andric   //   this relocation.
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   size_t oldSize = relocData.size();
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric   relocData = {'A', 'P', 'S', '2'};
18220b57cec5SDimitry Andric   raw_svector_ostream os(relocData);
18230b57cec5SDimitry Andric   auto add = [&](int64_t v) { encodeSLEB128(v, os); };
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   // The format header includes the number of relocations and the initial
18260b57cec5SDimitry Andric   // offset (we set this to zero because the first relocation group will
18270b57cec5SDimitry Andric   // perform the initial adjustment).
18280b57cec5SDimitry Andric   add(relocs.size());
18290b57cec5SDimitry Andric   add(0);
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   std::vector<Elf_Rela> relatives, nonRelatives;
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric   for (const DynamicReloc &rel : relocs) {
18340b57cec5SDimitry Andric     Elf_Rela r;
18350eae32dcSDimitry Andric     r.r_offset = rel.getOffset();
183604eeddc0SDimitry Andric     r.setSymbolAndType(rel.getSymIndex(getPartition().dynSymTab.get()),
183704eeddc0SDimitry Andric                        rel.type, false);
1838bdd1243dSDimitry Andric     r.r_addend = config->isRela ? rel.computeAddend() : 0;
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric     if (r.getType(config->isMips64EL) == target->relativeRel)
18410b57cec5SDimitry Andric       relatives.push_back(r);
18420b57cec5SDimitry Andric     else
18430b57cec5SDimitry Andric       nonRelatives.push_back(r);
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   llvm::sort(relatives, [](const Elf_Rel &a, const Elf_Rel &b) {
18470b57cec5SDimitry Andric     return a.r_offset < b.r_offset;
18480b57cec5SDimitry Andric   });
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric   // Try to find groups of relative relocations which are spaced one word
18510b57cec5SDimitry Andric   // apart from one another. These generally correspond to vtable entries. The
18520b57cec5SDimitry Andric   // format allows these groups to be encoded using a sort of run-length
18530b57cec5SDimitry Andric   // encoding, but each group will cost 7 bytes in addition to the offset from
18540b57cec5SDimitry Andric   // the previous group, so it is only profitable to do this for groups of
18550b57cec5SDimitry Andric   // size 8 or larger.
18560b57cec5SDimitry Andric   std::vector<Elf_Rela> ungroupedRelatives;
18570b57cec5SDimitry Andric   std::vector<std::vector<Elf_Rela>> relativeGroups;
18580b57cec5SDimitry Andric   for (auto i = relatives.begin(), e = relatives.end(); i != e;) {
18590b57cec5SDimitry Andric     std::vector<Elf_Rela> group;
18600b57cec5SDimitry Andric     do {
18610b57cec5SDimitry Andric       group.push_back(*i++);
18620b57cec5SDimitry Andric     } while (i != e && (i - 1)->r_offset + config->wordsize == i->r_offset);
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric     if (group.size() < 8)
18650b57cec5SDimitry Andric       ungroupedRelatives.insert(ungroupedRelatives.end(), group.begin(),
18660b57cec5SDimitry Andric                                 group.end());
18670b57cec5SDimitry Andric     else
18680b57cec5SDimitry Andric       relativeGroups.emplace_back(std::move(group));
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
187185868e8aSDimitry Andric   // For non-relative relocations, we would like to:
187285868e8aSDimitry Andric   //   1. Have relocations with the same symbol offset to be consecutive, so
187385868e8aSDimitry Andric   //      that the runtime linker can speed-up symbol lookup by implementing an
187485868e8aSDimitry Andric   //      1-entry cache.
187585868e8aSDimitry Andric   //   2. Group relocations by r_info to reduce the size of the relocation
187685868e8aSDimitry Andric   //      section.
187785868e8aSDimitry Andric   // Since the symbol offset is the high bits in r_info, sorting by r_info
187885868e8aSDimitry Andric   // allows us to do both.
187985868e8aSDimitry Andric   //
188085868e8aSDimitry Andric   // For Rela, we also want to sort by r_addend when r_info is the same. This
188185868e8aSDimitry Andric   // enables us to group by r_addend as well.
1882bdd1243dSDimitry Andric   llvm::sort(nonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
188385868e8aSDimitry Andric     if (a.r_info != b.r_info)
188485868e8aSDimitry Andric       return a.r_info < b.r_info;
1885bdd1243dSDimitry Andric     if (a.r_addend != b.r_addend)
188685868e8aSDimitry Andric       return a.r_addend < b.r_addend;
1887bdd1243dSDimitry Andric     return a.r_offset < b.r_offset;
188885868e8aSDimitry Andric   });
188985868e8aSDimitry Andric 
189085868e8aSDimitry Andric   // Group relocations with the same r_info. Note that each group emits a group
189185868e8aSDimitry Andric   // header and that may make the relocation section larger. It is hard to
189285868e8aSDimitry Andric   // estimate the size of a group header as the encoded size of that varies
189385868e8aSDimitry Andric   // based on r_info. However, we can approximate this trade-off by the number
189485868e8aSDimitry Andric   // of values encoded. Each group header contains 3 values, and each relocation
189585868e8aSDimitry Andric   // in a group encodes one less value, as compared to when it is not grouped.
189685868e8aSDimitry Andric   // Therefore, we only group relocations if there are 3 or more of them with
189785868e8aSDimitry Andric   // the same r_info.
189885868e8aSDimitry Andric   //
189985868e8aSDimitry Andric   // For Rela, the addend for most non-relative relocations is zero, and thus we
190085868e8aSDimitry Andric   // can usually get a smaller relocation section if we group relocations with 0
190185868e8aSDimitry Andric   // addend as well.
190285868e8aSDimitry Andric   std::vector<Elf_Rela> ungroupedNonRelatives;
190385868e8aSDimitry Andric   std::vector<std::vector<Elf_Rela>> nonRelativeGroups;
190485868e8aSDimitry Andric   for (auto i = nonRelatives.begin(), e = nonRelatives.end(); i != e;) {
190585868e8aSDimitry Andric     auto j = i + 1;
190685868e8aSDimitry Andric     while (j != e && i->r_info == j->r_info &&
190785868e8aSDimitry Andric            (!config->isRela || i->r_addend == j->r_addend))
190885868e8aSDimitry Andric       ++j;
190985868e8aSDimitry Andric     if (j - i < 3 || (config->isRela && i->r_addend != 0))
191085868e8aSDimitry Andric       ungroupedNonRelatives.insert(ungroupedNonRelatives.end(), i, j);
191185868e8aSDimitry Andric     else
191285868e8aSDimitry Andric       nonRelativeGroups.emplace_back(i, j);
191385868e8aSDimitry Andric     i = j;
191485868e8aSDimitry Andric   }
191585868e8aSDimitry Andric 
191685868e8aSDimitry Andric   // Sort ungrouped relocations by offset to minimize the encoded length.
191785868e8aSDimitry Andric   llvm::sort(ungroupedNonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
191885868e8aSDimitry Andric     return a.r_offset < b.r_offset;
191985868e8aSDimitry Andric   });
192085868e8aSDimitry Andric 
19210b57cec5SDimitry Andric   unsigned hasAddendIfRela =
19220b57cec5SDimitry Andric       config->isRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   uint64_t offset = 0;
19250b57cec5SDimitry Andric   uint64_t addend = 0;
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   // Emit the run-length encoding for the groups of adjacent relative
19280b57cec5SDimitry Andric   // relocations. Each group is represented using two groups in the packed
19290b57cec5SDimitry Andric   // format. The first is used to set the current offset to the start of the
19300b57cec5SDimitry Andric   // group (and also encodes the first relocation), and the second encodes the
19310b57cec5SDimitry Andric   // remaining relocations.
19320b57cec5SDimitry Andric   for (std::vector<Elf_Rela> &g : relativeGroups) {
19330b57cec5SDimitry Andric     // The first relocation in the group.
19340b57cec5SDimitry Andric     add(1);
19350b57cec5SDimitry Andric     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
19360b57cec5SDimitry Andric         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
19370b57cec5SDimitry Andric     add(g[0].r_offset - offset);
19380b57cec5SDimitry Andric     add(target->relativeRel);
19390b57cec5SDimitry Andric     if (config->isRela) {
19400b57cec5SDimitry Andric       add(g[0].r_addend - addend);
19410b57cec5SDimitry Andric       addend = g[0].r_addend;
19420b57cec5SDimitry Andric     }
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric     // The remaining relocations.
19450b57cec5SDimitry Andric     add(g.size() - 1);
19460b57cec5SDimitry Andric     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
19470b57cec5SDimitry Andric         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
19480b57cec5SDimitry Andric     add(config->wordsize);
19490b57cec5SDimitry Andric     add(target->relativeRel);
19500b57cec5SDimitry Andric     if (config->isRela) {
1951bdd1243dSDimitry Andric       for (const auto &i : llvm::drop_begin(g)) {
1952bdd1243dSDimitry Andric         add(i.r_addend - addend);
1953bdd1243dSDimitry Andric         addend = i.r_addend;
19540b57cec5SDimitry Andric       }
19550b57cec5SDimitry Andric     }
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     offset = g.back().r_offset;
19580b57cec5SDimitry Andric   }
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   // Now the ungrouped relatives.
19610b57cec5SDimitry Andric   if (!ungroupedRelatives.empty()) {
19620b57cec5SDimitry Andric     add(ungroupedRelatives.size());
19630b57cec5SDimitry Andric     add(RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
19640b57cec5SDimitry Andric     add(target->relativeRel);
19650b57cec5SDimitry Andric     for (Elf_Rela &r : ungroupedRelatives) {
19660b57cec5SDimitry Andric       add(r.r_offset - offset);
19670b57cec5SDimitry Andric       offset = r.r_offset;
19680b57cec5SDimitry Andric       if (config->isRela) {
19690b57cec5SDimitry Andric         add(r.r_addend - addend);
19700b57cec5SDimitry Andric         addend = r.r_addend;
19710b57cec5SDimitry Andric       }
19720b57cec5SDimitry Andric     }
19730b57cec5SDimitry Andric   }
19740b57cec5SDimitry Andric 
197585868e8aSDimitry Andric   // Grouped non-relatives.
197685868e8aSDimitry Andric   for (ArrayRef<Elf_Rela> g : nonRelativeGroups) {
197785868e8aSDimitry Andric     add(g.size());
197885868e8aSDimitry Andric     add(RELOCATION_GROUPED_BY_INFO_FLAG);
197985868e8aSDimitry Andric     add(g[0].r_info);
198085868e8aSDimitry Andric     for (const Elf_Rela &r : g) {
198185868e8aSDimitry Andric       add(r.r_offset - offset);
198285868e8aSDimitry Andric       offset = r.r_offset;
198385868e8aSDimitry Andric     }
198485868e8aSDimitry Andric     addend = 0;
198585868e8aSDimitry Andric   }
198685868e8aSDimitry Andric 
198785868e8aSDimitry Andric   // Finally the ungrouped non-relative relocations.
198885868e8aSDimitry Andric   if (!ungroupedNonRelatives.empty()) {
198985868e8aSDimitry Andric     add(ungroupedNonRelatives.size());
19900b57cec5SDimitry Andric     add(hasAddendIfRela);
199185868e8aSDimitry Andric     for (Elf_Rela &r : ungroupedNonRelatives) {
19920b57cec5SDimitry Andric       add(r.r_offset - offset);
19930b57cec5SDimitry Andric       offset = r.r_offset;
19940b57cec5SDimitry Andric       add(r.r_info);
19950b57cec5SDimitry Andric       if (config->isRela) {
19960b57cec5SDimitry Andric         add(r.r_addend - addend);
19970b57cec5SDimitry Andric         addend = r.r_addend;
19980b57cec5SDimitry Andric       }
19990b57cec5SDimitry Andric     }
20000b57cec5SDimitry Andric   }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   // Don't allow the section to shrink; otherwise the size of the section can
20030b57cec5SDimitry Andric   // oscillate infinitely.
20040b57cec5SDimitry Andric   if (relocData.size() < oldSize)
20050b57cec5SDimitry Andric     relocData.append(oldSize - relocData.size(), 0);
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   // Returns whether the section size changed. We need to keep recomputing both
20080b57cec5SDimitry Andric   // section layout and the contents of this section until the size converges
20090b57cec5SDimitry Andric   // because changing this section's size can affect section layout, which in
20100b57cec5SDimitry Andric   // turn can affect the sizes of the LEB-encoded integers stored in this
20110b57cec5SDimitry Andric   // section.
20120b57cec5SDimitry Andric   return relocData.size() != oldSize;
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
2015bdd1243dSDimitry Andric template <class ELFT>
RelrSection(unsigned concurrency,bool isAArch64Auth)20160fca6ea1SDimitry Andric RelrSection<ELFT>::RelrSection(unsigned concurrency, bool isAArch64Auth)
20170fca6ea1SDimitry Andric     : RelrBaseSection(concurrency, isAArch64Auth) {
20180b57cec5SDimitry Andric   this->entsize = config->wordsize;
20190b57cec5SDimitry Andric }
20200b57cec5SDimitry Andric 
updateAllocSize()20210b57cec5SDimitry Andric template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
20220b57cec5SDimitry Andric   // This function computes the contents of an SHT_RELR packed relocation
20230b57cec5SDimitry Andric   // section.
20240b57cec5SDimitry Andric   //
20250b57cec5SDimitry Andric   // Proposal for adding SHT_RELR sections to generic-abi is here:
20260b57cec5SDimitry Andric   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
20270b57cec5SDimitry Andric   //
20280b57cec5SDimitry Andric   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
20290b57cec5SDimitry Andric   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
20300b57cec5SDimitry Andric   //
20310b57cec5SDimitry Andric   // i.e. start with an address, followed by any number of bitmaps. The address
20320b57cec5SDimitry Andric   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
20330b57cec5SDimitry Andric   // relocations each, at subsequent offsets following the last address entry.
20340b57cec5SDimitry Andric   //
20350b57cec5SDimitry Andric   // The bitmap entries must have 1 in the least significant bit. The assumption
20360b57cec5SDimitry Andric   // here is that an address cannot have 1 in lsb. Odd addresses are not
20370b57cec5SDimitry Andric   // supported.
20380b57cec5SDimitry Andric   //
20390b57cec5SDimitry Andric   // Excluding the least significant bit in the bitmap, each non-zero bit in
20400b57cec5SDimitry Andric   // the bitmap represents a relocation to be applied to a corresponding machine
20410b57cec5SDimitry Andric   // word that follows the base address word. The second least significant bit
20420b57cec5SDimitry Andric   // represents the machine word immediately following the initial address, and
20430b57cec5SDimitry Andric   // each bit that follows represents the next word, in linear order. As such,
20440b57cec5SDimitry Andric   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
20450b57cec5SDimitry Andric   // 63 relocations in a 64-bit object.
20460b57cec5SDimitry Andric   //
20470b57cec5SDimitry Andric   // This encoding has a couple of interesting properties:
20480b57cec5SDimitry Andric   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
20490b57cec5SDimitry Andric   //    even means address, odd means bitmap.
20500b57cec5SDimitry Andric   // 2. Just a simple list of addresses is a valid encoding.
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric   size_t oldSize = relrRelocs.size();
20530b57cec5SDimitry Andric   relrRelocs.clear();
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric   // Same as Config->Wordsize but faster because this is a compile-time
20560b57cec5SDimitry Andric   // constant.
20570b57cec5SDimitry Andric   const size_t wordsize = sizeof(typename ELFT::uint);
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   // Number of bits to use for the relocation offsets bitmap.
20600b57cec5SDimitry Andric   // Must be either 63 or 31.
20610b57cec5SDimitry Andric   const size_t nBits = wordsize * 8 - 1;
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   // Get offsets for all relative relocations and sort them.
206404eeddc0SDimitry Andric   std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]);
2065bdd1243dSDimitry Andric   for (auto [i, r] : llvm::enumerate(relocs))
2066bdd1243dSDimitry Andric     offsets[i] = r.getOffset();
2067fcaf7f86SDimitry Andric   llvm::sort(offsets.get(), offsets.get() + relocs.size());
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric   // For each leading relocation, find following ones that can be folded
20700b57cec5SDimitry Andric   // as a bitmap and fold them.
207104eeddc0SDimitry Andric   for (size_t i = 0, e = relocs.size(); i != e;) {
20720b57cec5SDimitry Andric     // Add a leading relocation.
20730b57cec5SDimitry Andric     relrRelocs.push_back(Elf_Relr(offsets[i]));
20740b57cec5SDimitry Andric     uint64_t base = offsets[i] + wordsize;
20750b57cec5SDimitry Andric     ++i;
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     // Find foldable relocations to construct bitmaps.
207804eeddc0SDimitry Andric     for (;;) {
20790b57cec5SDimitry Andric       uint64_t bitmap = 0;
208004eeddc0SDimitry Andric       for (; i != e; ++i) {
208104eeddc0SDimitry Andric         uint64_t d = offsets[i] - base;
208204eeddc0SDimitry Andric         if (d >= nBits * wordsize || d % wordsize)
20830b57cec5SDimitry Andric           break;
208404eeddc0SDimitry Andric         bitmap |= uint64_t(1) << (d / wordsize);
20850b57cec5SDimitry Andric       }
20860b57cec5SDimitry Andric       if (!bitmap)
20870b57cec5SDimitry Andric         break;
20880b57cec5SDimitry Andric       relrRelocs.push_back(Elf_Relr((bitmap << 1) | 1));
20890b57cec5SDimitry Andric       base += nBits * wordsize;
20900b57cec5SDimitry Andric     }
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric 
209385868e8aSDimitry Andric   // Don't allow the section to shrink; otherwise the size of the section can
209485868e8aSDimitry Andric   // oscillate infinitely. Trailing 1s do not decode to more relocations.
209585868e8aSDimitry Andric   if (relrRelocs.size() < oldSize) {
209685868e8aSDimitry Andric     log(".relr.dyn needs " + Twine(oldSize - relrRelocs.size()) +
209785868e8aSDimitry Andric         " padding word(s)");
209885868e8aSDimitry Andric     relrRelocs.resize(oldSize, Elf_Relr(1));
209985868e8aSDimitry Andric   }
210085868e8aSDimitry Andric 
21010b57cec5SDimitry Andric   return relrRelocs.size() != oldSize;
21020b57cec5SDimitry Andric }
21030b57cec5SDimitry Andric 
SymbolTableBaseSection(StringTableSection & strTabSec)21040b57cec5SDimitry Andric SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &strTabSec)
21050b57cec5SDimitry Andric     : SyntheticSection(strTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
21060b57cec5SDimitry Andric                        strTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
21070b57cec5SDimitry Andric                        config->wordsize,
21080b57cec5SDimitry Andric                        strTabSec.isDynamic() ? ".dynsym" : ".symtab"),
21090b57cec5SDimitry Andric       strTabSec(strTabSec) {}
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric // Orders symbols according to their positions in the GOT,
21120b57cec5SDimitry Andric // in compliance with MIPS ABI rules.
21130b57cec5SDimitry Andric // See "Global Offset Table" in Chapter 5 in the following document
21140b57cec5SDimitry Andric // for detailed description:
21150b57cec5SDimitry Andric // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
sortMipsSymbols(const SymbolTableEntry & l,const SymbolTableEntry & r)21160b57cec5SDimitry Andric static bool sortMipsSymbols(const SymbolTableEntry &l,
21170b57cec5SDimitry Andric                             const SymbolTableEntry &r) {
21180b57cec5SDimitry Andric   // Sort entries related to non-local preemptible symbols by GOT indexes.
21190b57cec5SDimitry Andric   // All other entries go to the beginning of a dynsym in arbitrary order.
21200b57cec5SDimitry Andric   if (l.sym->isInGot() && r.sym->isInGot())
212104eeddc0SDimitry Andric     return l.sym->getGotIdx() < r.sym->getGotIdx();
21220b57cec5SDimitry Andric   if (!l.sym->isInGot() && !r.sym->isInGot())
21230b57cec5SDimitry Andric     return false;
21240b57cec5SDimitry Andric   return !l.sym->isInGot();
21250b57cec5SDimitry Andric }
21260b57cec5SDimitry Andric 
finalizeContents()21270b57cec5SDimitry Andric void SymbolTableBaseSection::finalizeContents() {
21280b57cec5SDimitry Andric   if (OutputSection *sec = strTabSec.getParent())
21290b57cec5SDimitry Andric     getParent()->link = sec->sectionIndex;
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   if (this->type != SHT_DYNSYM) {
21320b57cec5SDimitry Andric     sortSymTabSymbols();
21330b57cec5SDimitry Andric     return;
21340b57cec5SDimitry Andric   }
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   // If it is a .dynsym, there should be no local symbols, but we need
21370b57cec5SDimitry Andric   // to do a few things for the dynamic linker.
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   // Section's Info field has the index of the first non-local symbol.
21400b57cec5SDimitry Andric   // Because the first symbol entry is a null entry, 1 is the first.
21410b57cec5SDimitry Andric   getParent()->info = 1;
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric   if (getPartition().gnuHashTab) {
21440b57cec5SDimitry Andric     // NB: It also sorts Symbols to meet the GNU hash table requirements.
21450b57cec5SDimitry Andric     getPartition().gnuHashTab->addSymbols(symbols);
21460b57cec5SDimitry Andric   } else if (config->emachine == EM_MIPS) {
21470b57cec5SDimitry Andric     llvm::stable_sort(symbols, sortMipsSymbols);
21480b57cec5SDimitry Andric   }
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   // Only the main partition's dynsym indexes are stored in the symbols
21510b57cec5SDimitry Andric   // themselves. All other partitions use a lookup table.
215204eeddc0SDimitry Andric   if (this == mainPart->dynSymTab.get()) {
21530b57cec5SDimitry Andric     size_t i = 0;
21540b57cec5SDimitry Andric     for (const SymbolTableEntry &s : symbols)
21550b57cec5SDimitry Andric       s.sym->dynsymIndex = ++i;
21560b57cec5SDimitry Andric   }
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric // The ELF spec requires that all local symbols precede global symbols, so we
21600b57cec5SDimitry Andric // sort symbol entries in this function. (For .dynsym, we don't do that because
21610b57cec5SDimitry Andric // symbols for dynamic linking are inherently all globals.)
21620b57cec5SDimitry Andric //
21630b57cec5SDimitry Andric // Aside from above, we put local symbols in groups starting with the STT_FILE
21640b57cec5SDimitry Andric // symbol. That is convenient for purpose of identifying where are local symbols
21650b57cec5SDimitry Andric // coming from.
sortSymTabSymbols()21660b57cec5SDimitry Andric void SymbolTableBaseSection::sortSymTabSymbols() {
21670b57cec5SDimitry Andric   // Move all local symbols before global symbols.
21680b57cec5SDimitry Andric   auto e = std::stable_partition(
216904eeddc0SDimitry Andric       symbols.begin(), symbols.end(),
217004eeddc0SDimitry Andric       [](const SymbolTableEntry &s) { return s.sym->isLocal(); });
21710b57cec5SDimitry Andric   size_t numLocals = e - symbols.begin();
21720b57cec5SDimitry Andric   getParent()->info = numLocals + 1;
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric   // We want to group the local symbols by file. For that we rebuild the local
21750b57cec5SDimitry Andric   // part of the symbols vector. We do not need to care about the STT_FILE
21760b57cec5SDimitry Andric   // symbols, they are already naturally placed first in each group. That
21770b57cec5SDimitry Andric   // happens because STT_FILE is always the first symbol in the object and hence
21780b57cec5SDimitry Andric   // precede all other local symbols we add for a file.
217904eeddc0SDimitry Andric   MapVector<InputFile *, SmallVector<SymbolTableEntry, 0>> arr;
21800b57cec5SDimitry Andric   for (const SymbolTableEntry &s : llvm::make_range(symbols.begin(), e))
21810b57cec5SDimitry Andric     arr[s.sym->file].push_back(s);
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   auto i = symbols.begin();
218404eeddc0SDimitry Andric   for (auto &p : arr)
21850b57cec5SDimitry Andric     for (SymbolTableEntry &entry : p.second)
21860b57cec5SDimitry Andric       *i++ = entry;
21870b57cec5SDimitry Andric }
21880b57cec5SDimitry Andric 
addSymbol(Symbol * b)21890b57cec5SDimitry Andric void SymbolTableBaseSection::addSymbol(Symbol *b) {
21900b57cec5SDimitry Andric   // Adding a local symbol to a .dynsym is a bug.
21910b57cec5SDimitry Andric   assert(this->type != SHT_DYNSYM || !b->isLocal());
219281ad6265SDimitry Andric   symbols.push_back({b, strTabSec.addString(b->getName(), false)});
21930b57cec5SDimitry Andric }
21940b57cec5SDimitry Andric 
getSymbolIndex(const Symbol & sym)21950fca6ea1SDimitry Andric size_t SymbolTableBaseSection::getSymbolIndex(const Symbol &sym) {
219604eeddc0SDimitry Andric   if (this == mainPart->dynSymTab.get())
21970fca6ea1SDimitry Andric     return sym.dynsymIndex;
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   // Initializes symbol lookup tables lazily. This is used only for -r,
2200349cc55cSDimitry Andric   // --emit-relocs and dynsyms in partitions other than the main one.
22010b57cec5SDimitry Andric   llvm::call_once(onceFlag, [&] {
22020b57cec5SDimitry Andric     symbolIndexMap.reserve(symbols.size());
22030b57cec5SDimitry Andric     size_t i = 0;
22040b57cec5SDimitry Andric     for (const SymbolTableEntry &e : symbols) {
22050b57cec5SDimitry Andric       if (e.sym->type == STT_SECTION)
22060b57cec5SDimitry Andric         sectionIndexMap[e.sym->getOutputSection()] = ++i;
22070b57cec5SDimitry Andric       else
22080b57cec5SDimitry Andric         symbolIndexMap[e.sym] = ++i;
22090b57cec5SDimitry Andric     }
22100b57cec5SDimitry Andric   });
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric   // Section symbols are mapped based on their output sections
22130b57cec5SDimitry Andric   // to maintain their semantics.
22140fca6ea1SDimitry Andric   if (sym.type == STT_SECTION)
22150fca6ea1SDimitry Andric     return sectionIndexMap.lookup(sym.getOutputSection());
22160fca6ea1SDimitry Andric   return symbolIndexMap.lookup(&sym);
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric template <class ELFT>
SymbolTableSection(StringTableSection & strTabSec)22200b57cec5SDimitry Andric SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &strTabSec)
22210b57cec5SDimitry Andric     : SymbolTableBaseSection(strTabSec) {
22220b57cec5SDimitry Andric   this->entsize = sizeof(Elf_Sym);
22230b57cec5SDimitry Andric }
22240b57cec5SDimitry Andric 
getCommonSec(Symbol * sym)22250b57cec5SDimitry Andric static BssSection *getCommonSec(Symbol *sym) {
222681ad6265SDimitry Andric   if (config->relocatable)
22270b57cec5SDimitry Andric     if (auto *d = dyn_cast<Defined>(sym))
22280b57cec5SDimitry Andric       return dyn_cast_or_null<BssSection>(d->section);
22290b57cec5SDimitry Andric   return nullptr;
22300b57cec5SDimitry Andric }
22310b57cec5SDimitry Andric 
getSymSectionIndex(Symbol * sym)22320b57cec5SDimitry Andric static uint32_t getSymSectionIndex(Symbol *sym) {
2233bdd1243dSDimitry Andric   assert(!(sym->hasFlag(NEEDS_COPY) && sym->isObject()));
2234bdd1243dSDimitry Andric   if (!isa<Defined>(sym) || sym->hasFlag(NEEDS_COPY))
22350b57cec5SDimitry Andric     return SHN_UNDEF;
22360b57cec5SDimitry Andric   if (const OutputSection *os = sym->getOutputSection())
22370b57cec5SDimitry Andric     return os->sectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
22380b57cec5SDimitry Andric                                              : os->sectionIndex;
22390b57cec5SDimitry Andric   return SHN_ABS;
22400b57cec5SDimitry Andric }
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric // Write the internal symbol table contents to the output symbol table.
writeTo(uint8_t * buf)22430b57cec5SDimitry Andric template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *buf) {
22440b57cec5SDimitry Andric   // The first entry is a null entry as per the ELF spec.
22450b57cec5SDimitry Andric   buf += sizeof(Elf_Sym);
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric   auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   for (SymbolTableEntry &ent : symbols) {
22500b57cec5SDimitry Andric     Symbol *sym = ent.sym;
22510b57cec5SDimitry Andric     bool isDefinedHere = type == SHT_SYMTAB || sym->partition == partition;
22520b57cec5SDimitry Andric 
225304eeddc0SDimitry Andric     // Set st_name, st_info and st_other.
225404eeddc0SDimitry Andric     eSym->st_name = ent.strTabOffset;
225504eeddc0SDimitry Andric     eSym->setBindingAndType(sym->binding, sym->type);
2256bdd1243dSDimitry Andric     eSym->st_other = sym->stOther;
22570b57cec5SDimitry Andric 
225804eeddc0SDimitry Andric     if (BssSection *commonSec = getCommonSec(sym)) {
225981ad6265SDimitry Andric       // When -r is specified, a COMMON symbol is not allocated. Its st_shndx
226081ad6265SDimitry Andric       // holds SHN_COMMON and st_value holds the alignment.
226104eeddc0SDimitry Andric       eSym->st_shndx = SHN_COMMON;
2262bdd1243dSDimitry Andric       eSym->st_value = commonSec->addralign;
226304eeddc0SDimitry Andric       eSym->st_size = cast<Defined>(sym)->size;
226404eeddc0SDimitry Andric     } else {
226504eeddc0SDimitry Andric       const uint32_t shndx = getSymSectionIndex(sym);
226604eeddc0SDimitry Andric       if (isDefinedHere) {
226704eeddc0SDimitry Andric         eSym->st_shndx = shndx;
22680b57cec5SDimitry Andric         eSym->st_value = sym->getVA();
226904eeddc0SDimitry Andric         // Copy symbol size if it is a defined symbol. st_size is not
227004eeddc0SDimitry Andric         // significant for undefined symbols, so whether copying it or not is up
227104eeddc0SDimitry Andric         // to us if that's the case. We'll leave it as zero because by not
227204eeddc0SDimitry Andric         // setting a value, we can get the exact same outputs for two sets of
227304eeddc0SDimitry Andric         // input files that differ only in undefined symbol size in DSOs.
227404eeddc0SDimitry Andric         eSym->st_size = shndx != SHN_UNDEF ? cast<Defined>(sym)->size : 0;
227504eeddc0SDimitry Andric       } else {
227604eeddc0SDimitry Andric         eSym->st_shndx = 0;
22770b57cec5SDimitry Andric         eSym->st_value = 0;
227804eeddc0SDimitry Andric         eSym->st_size = 0;
227904eeddc0SDimitry Andric       }
228004eeddc0SDimitry Andric     }
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric     ++eSym;
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   // On MIPS we need to mark symbol which has a PLT entry and requires
22860b57cec5SDimitry Andric   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
22870b57cec5SDimitry Andric   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
22880b57cec5SDimitry Andric   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
22890b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
22900b57cec5SDimitry Andric     auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric     for (SymbolTableEntry &ent : symbols) {
22930b57cec5SDimitry Andric       Symbol *sym = ent.sym;
2294bdd1243dSDimitry Andric       if (sym->isInPlt() && sym->hasFlag(NEEDS_COPY))
22950b57cec5SDimitry Andric         eSym->st_other |= STO_MIPS_PLT;
22960b57cec5SDimitry Andric       if (isMicroMips()) {
22970b57cec5SDimitry Andric         // We already set the less-significant bit for symbols
22980b57cec5SDimitry Andric         // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
22990b57cec5SDimitry Andric         // records. That allows us to distinguish such symbols in
23005ffd83dbSDimitry Andric         // the `MIPS<ELFT>::relocate()` routine. Now we should
23010b57cec5SDimitry Andric         // clear that bit for non-dynamic symbol table, so tools
23020b57cec5SDimitry Andric         // like `objdump` will be able to deal with a correct
23030b57cec5SDimitry Andric         // symbol position.
23040b57cec5SDimitry Andric         if (sym->isDefined() &&
2305bdd1243dSDimitry Andric             ((sym->stOther & STO_MIPS_MICROMIPS) || sym->hasFlag(NEEDS_COPY))) {
23060b57cec5SDimitry Andric           if (!strTabSec.isDynamic())
23070b57cec5SDimitry Andric             eSym->st_value &= ~1;
23080b57cec5SDimitry Andric           eSym->st_other |= STO_MIPS_MICROMIPS;
23090b57cec5SDimitry Andric         }
23100b57cec5SDimitry Andric       }
23110b57cec5SDimitry Andric       if (config->relocatable)
23120b57cec5SDimitry Andric         if (auto *d = dyn_cast<Defined>(sym))
23130b57cec5SDimitry Andric           if (isMipsPIC<ELFT>(d))
23140b57cec5SDimitry Andric             eSym->st_other |= STO_MIPS_PIC;
23150b57cec5SDimitry Andric       ++eSym;
23160b57cec5SDimitry Andric     }
23170b57cec5SDimitry Andric   }
23180b57cec5SDimitry Andric }
23190b57cec5SDimitry Andric 
SymtabShndxSection()23200b57cec5SDimitry Andric SymtabShndxSection::SymtabShndxSection()
23210b57cec5SDimitry Andric     : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") {
23220b57cec5SDimitry Andric   this->entsize = 4;
23230b57cec5SDimitry Andric }
23240b57cec5SDimitry Andric 
writeTo(uint8_t * buf)23250b57cec5SDimitry Andric void SymtabShndxSection::writeTo(uint8_t *buf) {
23260b57cec5SDimitry Andric   // We write an array of 32 bit values, where each value has 1:1 association
23270b57cec5SDimitry Andric   // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX,
23280b57cec5SDimitry Andric   // we need to write actual index, otherwise, we must write SHN_UNDEF(0).
23290b57cec5SDimitry Andric   buf += 4; // Ignore .symtab[0] entry.
23300b57cec5SDimitry Andric   for (const SymbolTableEntry &entry : in.symTab->getSymbols()) {
233104eeddc0SDimitry Andric     if (!getCommonSec(entry.sym) && getSymSectionIndex(entry.sym) == SHN_XINDEX)
23320b57cec5SDimitry Andric       write32(buf, entry.sym->getOutputSection()->sectionIndex);
23330b57cec5SDimitry Andric     buf += 4;
23340b57cec5SDimitry Andric   }
23350b57cec5SDimitry Andric }
23360b57cec5SDimitry Andric 
isNeeded() const23370b57cec5SDimitry Andric bool SymtabShndxSection::isNeeded() const {
23380b57cec5SDimitry Andric   // SHT_SYMTAB can hold symbols with section indices values up to
23390b57cec5SDimitry Andric   // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
23400b57cec5SDimitry Andric   // section. Problem is that we reveal the final section indices a bit too
23410b57cec5SDimitry Andric   // late, and we do not know them here. For simplicity, we just always create
23420b57cec5SDimitry Andric   // a .symtab_shndx section when the amount of output sections is huge.
23430b57cec5SDimitry Andric   size_t size = 0;
23444824e7fdSDimitry Andric   for (SectionCommand *cmd : script->sectionCommands)
234581ad6265SDimitry Andric     if (isa<OutputDesc>(cmd))
23460b57cec5SDimitry Andric       ++size;
23470b57cec5SDimitry Andric   return size >= SHN_LORESERVE;
23480b57cec5SDimitry Andric }
23490b57cec5SDimitry Andric 
finalizeContents()23500b57cec5SDimitry Andric void SymtabShndxSection::finalizeContents() {
23510b57cec5SDimitry Andric   getParent()->link = in.symTab->getParent()->sectionIndex;
23520b57cec5SDimitry Andric }
23530b57cec5SDimitry Andric 
getSize() const23540b57cec5SDimitry Andric size_t SymtabShndxSection::getSize() const {
23550b57cec5SDimitry Andric   return in.symTab->getNumSymbols() * 4;
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric // .hash and .gnu.hash sections contain on-disk hash tables that map
23590b57cec5SDimitry Andric // symbol names to their dynamic symbol table indices. Their purpose
23600b57cec5SDimitry Andric // is to help the dynamic linker resolve symbols quickly. If ELF files
23610b57cec5SDimitry Andric // don't have them, the dynamic linker has to do linear search on all
23620b57cec5SDimitry Andric // dynamic symbols, which makes programs slower. Therefore, a .hash
2363349cc55cSDimitry Andric // section is added to a DSO by default.
23640b57cec5SDimitry Andric //
23650b57cec5SDimitry Andric // The Unix semantics of resolving dynamic symbols is somewhat expensive.
23660b57cec5SDimitry Andric // Each ELF file has a list of DSOs that the ELF file depends on and a
23670b57cec5SDimitry Andric // list of dynamic symbols that need to be resolved from any of the
23680b57cec5SDimitry Andric // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
23690b57cec5SDimitry Andric // where m is the number of DSOs and n is the number of dynamic
23700b57cec5SDimitry Andric // symbols. For modern large programs, both m and n are large.  So
23715ffd83dbSDimitry Andric // making each step faster by using hash tables substantially
23720b57cec5SDimitry Andric // improves time to load programs.
23730b57cec5SDimitry Andric //
23740b57cec5SDimitry Andric // (Note that this is not the only way to design the shared library.
23750b57cec5SDimitry Andric // For instance, the Windows DLL takes a different approach. On
23760b57cec5SDimitry Andric // Windows, each dynamic symbol has a name of DLL from which the symbol
23770b57cec5SDimitry Andric // has to be resolved. That makes the cost of symbol resolution O(n).
23780b57cec5SDimitry Andric // This disables some hacky techniques you can use on Unix such as
23790b57cec5SDimitry Andric // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
23800b57cec5SDimitry Andric //
23810b57cec5SDimitry Andric // Due to historical reasons, we have two different hash tables, .hash
23820b57cec5SDimitry Andric // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
23830b57cec5SDimitry Andric // and better version of .hash. .hash is just an on-disk hash table, but
23840b57cec5SDimitry Andric // .gnu.hash has a bloom filter in addition to a hash table to skip
23850b57cec5SDimitry Andric // DSOs very quickly. If you are sure that your dynamic linker knows
2386349cc55cSDimitry Andric // about .gnu.hash, you want to specify --hash-style=gnu. Otherwise, a
2387349cc55cSDimitry Andric // safe bet is to specify --hash-style=both for backward compatibility.
GnuHashTableSection()23880b57cec5SDimitry Andric GnuHashTableSection::GnuHashTableSection()
23890b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, config->wordsize, ".gnu.hash") {
23900b57cec5SDimitry Andric }
23910b57cec5SDimitry Andric 
finalizeContents()23920b57cec5SDimitry Andric void GnuHashTableSection::finalizeContents() {
23930b57cec5SDimitry Andric   if (OutputSection *sec = getPartition().dynSymTab->getParent())
23940b57cec5SDimitry Andric     getParent()->link = sec->sectionIndex;
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric   // Computes bloom filter size in word size. We want to allocate 12
23970b57cec5SDimitry Andric   // bits for each symbol. It must be a power of two.
23980b57cec5SDimitry Andric   if (symbols.empty()) {
23990b57cec5SDimitry Andric     maskWords = 1;
24000b57cec5SDimitry Andric   } else {
24010b57cec5SDimitry Andric     uint64_t numBits = symbols.size() * 12;
24020b57cec5SDimitry Andric     maskWords = NextPowerOf2(numBits / (config->wordsize * 8));
24030b57cec5SDimitry Andric   }
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   size = 16;                            // Header
24060b57cec5SDimitry Andric   size += config->wordsize * maskWords; // Bloom filter
24070b57cec5SDimitry Andric   size += nBuckets * 4;                 // Hash buckets
24080b57cec5SDimitry Andric   size += symbols.size() * 4;           // Hash values
24090b57cec5SDimitry Andric }
24100b57cec5SDimitry Andric 
writeTo(uint8_t * buf)24110b57cec5SDimitry Andric void GnuHashTableSection::writeTo(uint8_t *buf) {
24120b57cec5SDimitry Andric   // Write a header.
24130b57cec5SDimitry Andric   write32(buf, nBuckets);
24140b57cec5SDimitry Andric   write32(buf + 4, getPartition().dynSymTab->getNumSymbols() - symbols.size());
24150b57cec5SDimitry Andric   write32(buf + 8, maskWords);
24160b57cec5SDimitry Andric   write32(buf + 12, Shift2);
24170b57cec5SDimitry Andric   buf += 16;
24180b57cec5SDimitry Andric 
24194824e7fdSDimitry Andric   // Write the 2-bit bloom filter.
24204824e7fdSDimitry Andric   const unsigned c = config->is64 ? 64 : 32;
24210b57cec5SDimitry Andric   for (const Entry &sym : symbols) {
24220b57cec5SDimitry Andric     // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
24230b57cec5SDimitry Andric     // the word using bits [0:5] and [26:31].
24240b57cec5SDimitry Andric     size_t i = (sym.hash / c) & (maskWords - 1);
24250b57cec5SDimitry Andric     uint64_t val = readUint(buf + i * config->wordsize);
24260b57cec5SDimitry Andric     val |= uint64_t(1) << (sym.hash % c);
24270b57cec5SDimitry Andric     val |= uint64_t(1) << ((sym.hash >> Shift2) % c);
24280b57cec5SDimitry Andric     writeUint(buf + i * config->wordsize, val);
24290b57cec5SDimitry Andric   }
24304824e7fdSDimitry Andric   buf += config->wordsize * maskWords;
24310b57cec5SDimitry Andric 
24324824e7fdSDimitry Andric   // Write the hash table.
24330b57cec5SDimitry Andric   uint32_t *buckets = reinterpret_cast<uint32_t *>(buf);
24340b57cec5SDimitry Andric   uint32_t oldBucket = -1;
24350b57cec5SDimitry Andric   uint32_t *values = buckets + nBuckets;
24360b57cec5SDimitry Andric   for (auto i = symbols.begin(), e = symbols.end(); i != e; ++i) {
24370b57cec5SDimitry Andric     // Write a hash value. It represents a sequence of chains that share the
24380b57cec5SDimitry Andric     // same hash modulo value. The last element of each chain is terminated by
24390b57cec5SDimitry Andric     // LSB 1.
24400b57cec5SDimitry Andric     uint32_t hash = i->hash;
24410b57cec5SDimitry Andric     bool isLastInChain = (i + 1) == e || i->bucketIdx != (i + 1)->bucketIdx;
24420b57cec5SDimitry Andric     hash = isLastInChain ? hash | 1 : hash & ~1;
24430b57cec5SDimitry Andric     write32(values++, hash);
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric     if (i->bucketIdx == oldBucket)
24460b57cec5SDimitry Andric       continue;
24470b57cec5SDimitry Andric     // Write a hash bucket. Hash buckets contain indices in the following hash
24480b57cec5SDimitry Andric     // value table.
24490b57cec5SDimitry Andric     write32(buckets + i->bucketIdx,
24500fca6ea1SDimitry Andric             getPartition().dynSymTab->getSymbolIndex(*i->sym));
24510b57cec5SDimitry Andric     oldBucket = i->bucketIdx;
24520b57cec5SDimitry Andric   }
24530b57cec5SDimitry Andric }
24540b57cec5SDimitry Andric 
24550b57cec5SDimitry Andric // Add symbols to this symbol hash table. Note that this function
24560b57cec5SDimitry Andric // destructively sort a given vector -- which is needed because
24570b57cec5SDimitry Andric // GNU-style hash table places some sorting requirements.
addSymbols(SmallVectorImpl<SymbolTableEntry> & v)24580eae32dcSDimitry Andric void GnuHashTableSection::addSymbols(SmallVectorImpl<SymbolTableEntry> &v) {
24590b57cec5SDimitry Andric   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
24600b57cec5SDimitry Andric   // its type correctly.
24610eae32dcSDimitry Andric   auto mid =
24620b57cec5SDimitry Andric       std::stable_partition(v.begin(), v.end(), [&](const SymbolTableEntry &s) {
24630b57cec5SDimitry Andric         return !s.sym->isDefined() || s.sym->partition != partition;
24640b57cec5SDimitry Andric       });
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   // We chose load factor 4 for the on-disk hash table. For each hash
24670b57cec5SDimitry Andric   // collision, the dynamic linker will compare a uint32_t hash value.
24680b57cec5SDimitry Andric   // Since the integer comparison is quite fast, we believe we can
24690b57cec5SDimitry Andric   // make the load factor even larger. 4 is just a conservative choice.
24700b57cec5SDimitry Andric   //
24710b57cec5SDimitry Andric   // Note that we don't want to create a zero-sized hash table because
24720b57cec5SDimitry Andric   // Android loader as of 2018 doesn't like a .gnu.hash containing such
24730b57cec5SDimitry Andric   // table. If that's the case, we create a hash table with one unused
24740b57cec5SDimitry Andric   // dummy slot.
24750b57cec5SDimitry Andric   nBuckets = std::max<size_t>((v.end() - mid) / 4, 1);
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric   if (mid == v.end())
24780b57cec5SDimitry Andric     return;
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric   for (SymbolTableEntry &ent : llvm::make_range(mid, v.end())) {
24810b57cec5SDimitry Andric     Symbol *b = ent.sym;
24820b57cec5SDimitry Andric     uint32_t hash = hashGnu(b->getName());
24830b57cec5SDimitry Andric     uint32_t bucketIdx = hash % nBuckets;
24840b57cec5SDimitry Andric     symbols.push_back({b, ent.strTabOffset, hash, bucketIdx});
24850b57cec5SDimitry Andric   }
24860b57cec5SDimitry Andric 
248704eeddc0SDimitry Andric   llvm::sort(symbols, [](const Entry &l, const Entry &r) {
248804eeddc0SDimitry Andric     return std::tie(l.bucketIdx, l.strTabOffset) <
248904eeddc0SDimitry Andric            std::tie(r.bucketIdx, r.strTabOffset);
24900b57cec5SDimitry Andric   });
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   v.erase(mid, v.end());
24930b57cec5SDimitry Andric   for (const Entry &ent : symbols)
24940b57cec5SDimitry Andric     v.push_back({ent.sym, ent.strTabOffset});
24950b57cec5SDimitry Andric }
24960b57cec5SDimitry Andric 
HashTableSection()24970b57cec5SDimitry Andric HashTableSection::HashTableSection()
24980b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
24990b57cec5SDimitry Andric   this->entsize = 4;
25000b57cec5SDimitry Andric }
25010b57cec5SDimitry Andric 
finalizeContents()25020b57cec5SDimitry Andric void HashTableSection::finalizeContents() {
250304eeddc0SDimitry Andric   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   if (OutputSection *sec = symTab->getParent())
25060b57cec5SDimitry Andric     getParent()->link = sec->sectionIndex;
25070b57cec5SDimitry Andric 
25080b57cec5SDimitry Andric   unsigned numEntries = 2;               // nbucket and nchain.
25090b57cec5SDimitry Andric   numEntries += symTab->getNumSymbols(); // The chain entries.
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   // Create as many buckets as there are symbols.
25120b57cec5SDimitry Andric   numEntries += symTab->getNumSymbols();
25130b57cec5SDimitry Andric   this->size = numEntries * 4;
25140b57cec5SDimitry Andric }
25150b57cec5SDimitry Andric 
writeTo(uint8_t * buf)25160b57cec5SDimitry Andric void HashTableSection::writeTo(uint8_t *buf) {
251704eeddc0SDimitry Andric   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
25180b57cec5SDimitry Andric   unsigned numSymbols = symTab->getNumSymbols();
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric   uint32_t *p = reinterpret_cast<uint32_t *>(buf);
25210b57cec5SDimitry Andric   write32(p++, numSymbols); // nbucket
25220b57cec5SDimitry Andric   write32(p++, numSymbols); // nchain
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric   uint32_t *buckets = p;
25250b57cec5SDimitry Andric   uint32_t *chains = p + numSymbols;
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric   for (const SymbolTableEntry &s : symTab->getSymbols()) {
25280b57cec5SDimitry Andric     Symbol *sym = s.sym;
25290b57cec5SDimitry Andric     StringRef name = sym->getName();
25300b57cec5SDimitry Andric     unsigned i = sym->dynsymIndex;
25310b57cec5SDimitry Andric     uint32_t hash = hashSysV(name) % numSymbols;
25320b57cec5SDimitry Andric     chains[i] = buckets[hash];
25330b57cec5SDimitry Andric     write32(buckets + hash, i);
25340b57cec5SDimitry Andric   }
25350b57cec5SDimitry Andric }
25360b57cec5SDimitry Andric 
PltSection()2537480093f4SDimitry Andric PltSection::PltSection()
2538480093f4SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
2539480093f4SDimitry Andric       headerSize(target->pltHeaderSize) {
2540480093f4SDimitry Andric   // On PowerPC, this section contains lazy symbol resolvers.
254192c0d181SDimitry Andric   if (config->emachine == EM_PPC64) {
2542480093f4SDimitry Andric     name = ".glink";
2543bdd1243dSDimitry Andric     addralign = 4;
2544480093f4SDimitry Andric   }
2545480093f4SDimitry Andric 
2546480093f4SDimitry Andric   // On x86 when IBT is enabled, this section contains the second PLT (lazy
2547480093f4SDimitry Andric   // symbol resolvers).
2548480093f4SDimitry Andric   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
2549480093f4SDimitry Andric       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT))
2550480093f4SDimitry Andric     name = ".plt.sec";
2551480093f4SDimitry Andric 
25520b57cec5SDimitry Andric   // The PLT needs to be writable on SPARC as the dynamic linker will
25530b57cec5SDimitry Andric   // modify the instructions in the PLT entries.
25540b57cec5SDimitry Andric   if (config->emachine == EM_SPARCV9)
25550b57cec5SDimitry Andric     this->flags |= SHF_WRITE;
25560b57cec5SDimitry Andric }
25570b57cec5SDimitry Andric 
writeTo(uint8_t * buf)25580b57cec5SDimitry Andric void PltSection::writeTo(uint8_t *buf) {
2559480093f4SDimitry Andric   // At beginning of PLT, we have code to call the dynamic
25600b57cec5SDimitry Andric   // linker to resolve dynsyms at runtime. Write such code.
25610b57cec5SDimitry Andric   target->writePltHeader(buf);
25620b57cec5SDimitry Andric   size_t off = headerSize;
25630b57cec5SDimitry Andric 
2564480093f4SDimitry Andric   for (const Symbol *sym : entries) {
2565480093f4SDimitry Andric     target->writePlt(buf + off, *sym, getVA() + off);
25660b57cec5SDimitry Andric     off += target->pltEntrySize;
25670b57cec5SDimitry Andric   }
25680b57cec5SDimitry Andric }
25690b57cec5SDimitry Andric 
addEntry(Symbol & sym)2570480093f4SDimitry Andric void PltSection::addEntry(Symbol &sym) {
257104eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1);
257204eeddc0SDimitry Andric   symAux.back().pltIdx = entries.size();
25730b57cec5SDimitry Andric   entries.push_back(&sym);
25740b57cec5SDimitry Andric }
25750b57cec5SDimitry Andric 
getSize() const25760b57cec5SDimitry Andric size_t PltSection::getSize() const {
257792c0d181SDimitry Andric   return headerSize + entries.size() * target->pltEntrySize;
25780b57cec5SDimitry Andric }
25790b57cec5SDimitry Andric 
isNeeded() const2580480093f4SDimitry Andric bool PltSection::isNeeded() const {
2581480093f4SDimitry Andric   // For -z retpolineplt, .iplt needs the .plt header.
2582480093f4SDimitry Andric   return !entries.empty() || (config->zRetpolineplt && in.iplt->isNeeded());
2583480093f4SDimitry Andric }
2584480093f4SDimitry Andric 
2585480093f4SDimitry Andric // Used by ARM to add mapping symbols in the PLT section, which aid
2586480093f4SDimitry Andric // disassembly.
addSymbols()25870b57cec5SDimitry Andric void PltSection::addSymbols() {
25880b57cec5SDimitry Andric   target->addPltHeaderSymbols(*this);
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   size_t off = headerSize;
25910b57cec5SDimitry Andric   for (size_t i = 0; i < entries.size(); ++i) {
25920b57cec5SDimitry Andric     target->addPltSymbols(*this, off);
25930b57cec5SDimitry Andric     off += target->pltEntrySize;
25940b57cec5SDimitry Andric   }
25950b57cec5SDimitry Andric }
25960b57cec5SDimitry Andric 
IpltSection()2597480093f4SDimitry Andric IpltSection::IpltSection()
2598480093f4SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".iplt") {
2599480093f4SDimitry Andric   if (config->emachine == EM_PPC || config->emachine == EM_PPC64) {
2600480093f4SDimitry Andric     name = ".glink";
2601bdd1243dSDimitry Andric     addralign = 4;
2602480093f4SDimitry Andric   }
2603480093f4SDimitry Andric }
2604480093f4SDimitry Andric 
writeTo(uint8_t * buf)2605480093f4SDimitry Andric void IpltSection::writeTo(uint8_t *buf) {
2606480093f4SDimitry Andric   uint32_t off = 0;
2607480093f4SDimitry Andric   for (const Symbol *sym : entries) {
2608480093f4SDimitry Andric     target->writeIplt(buf + off, *sym, getVA() + off);
2609480093f4SDimitry Andric     off += target->ipltEntrySize;
2610480093f4SDimitry Andric   }
2611480093f4SDimitry Andric }
2612480093f4SDimitry Andric 
getSize() const2613480093f4SDimitry Andric size_t IpltSection::getSize() const {
2614480093f4SDimitry Andric   return entries.size() * target->ipltEntrySize;
2615480093f4SDimitry Andric }
2616480093f4SDimitry Andric 
addEntry(Symbol & sym)2617480093f4SDimitry Andric void IpltSection::addEntry(Symbol &sym) {
261804eeddc0SDimitry Andric   assert(sym.auxIdx == symAux.size() - 1);
261904eeddc0SDimitry Andric   symAux.back().pltIdx = entries.size();
2620480093f4SDimitry Andric   entries.push_back(&sym);
2621480093f4SDimitry Andric }
2622480093f4SDimitry Andric 
2623480093f4SDimitry Andric // ARM uses mapping symbols to aid disassembly.
addSymbols()2624480093f4SDimitry Andric void IpltSection::addSymbols() {
2625480093f4SDimitry Andric   size_t off = 0;
2626480093f4SDimitry Andric   for (size_t i = 0, e = entries.size(); i != e; ++i) {
2627480093f4SDimitry Andric     target->addPltSymbols(*this, off);
2628480093f4SDimitry Andric     off += target->pltEntrySize;
2629480093f4SDimitry Andric   }
2630480093f4SDimitry Andric }
2631480093f4SDimitry Andric 
PPC32GlinkSection()263292c0d181SDimitry Andric PPC32GlinkSection::PPC32GlinkSection() {
263392c0d181SDimitry Andric   name = ".glink";
2634bdd1243dSDimitry Andric   addralign = 4;
263592c0d181SDimitry Andric }
263692c0d181SDimitry Andric 
writeTo(uint8_t * buf)263792c0d181SDimitry Andric void PPC32GlinkSection::writeTo(uint8_t *buf) {
263892c0d181SDimitry Andric   writePPC32GlinkSection(buf, entries.size());
263992c0d181SDimitry Andric }
264092c0d181SDimitry Andric 
getSize() const264192c0d181SDimitry Andric size_t PPC32GlinkSection::getSize() const {
264292c0d181SDimitry Andric   return headerSize + entries.size() * target->pltEntrySize + footerSize;
264392c0d181SDimitry Andric }
264492c0d181SDimitry Andric 
2645480093f4SDimitry Andric // This is an x86-only extra PLT section and used only when a security
2646480093f4SDimitry Andric // enhancement feature called CET is enabled. In this comment, I'll explain what
2647480093f4SDimitry Andric // the feature is and why we have two PLT sections if CET is enabled.
2648480093f4SDimitry Andric //
2649480093f4SDimitry Andric // So, what does CET do? CET introduces a new restriction to indirect jump
2650480093f4SDimitry Andric // instructions. CET works this way. Assume that CET is enabled. Then, if you
2651480093f4SDimitry Andric // execute an indirect jump instruction, the processor verifies that a special
2652480093f4SDimitry Andric // "landing pad" instruction (which is actually a repurposed NOP instruction and
2653480093f4SDimitry Andric // now called "endbr32" or "endbr64") is at the jump target. If the jump target
2654480093f4SDimitry Andric // does not start with that instruction, the processor raises an exception
2655480093f4SDimitry Andric // instead of continuing executing code.
2656480093f4SDimitry Andric //
2657480093f4SDimitry Andric // If CET is enabled, the compiler emits endbr to all locations where indirect
2658480093f4SDimitry Andric // jumps may jump to.
2659480093f4SDimitry Andric //
2660480093f4SDimitry Andric // This mechanism makes it extremely hard to transfer the control to a middle of
2661480093f4SDimitry Andric // a function that is not supporsed to be a indirect jump target, preventing
2662480093f4SDimitry Andric // certain types of attacks such as ROP or JOP.
2663480093f4SDimitry Andric //
2664480093f4SDimitry Andric // Note that the processors in the market as of 2019 don't actually support the
2665480093f4SDimitry Andric // feature. Only the spec is available at the moment.
2666480093f4SDimitry Andric //
2667480093f4SDimitry Andric // Now, I'll explain why we have this extra PLT section for CET.
2668480093f4SDimitry Andric //
2669480093f4SDimitry Andric // Since you can indirectly jump to a PLT entry, we have to make PLT entries
2670480093f4SDimitry Andric // start with endbr. The problem is there's no extra space for endbr (which is 4
2671480093f4SDimitry Andric // bytes long), as the PLT entry is only 16 bytes long and all bytes are already
2672480093f4SDimitry Andric // used.
2673480093f4SDimitry Andric //
2674480093f4SDimitry Andric // In order to deal with the issue, we split a PLT entry into two PLT entries.
2675480093f4SDimitry Andric // Remember that each PLT entry contains code to jump to an address read from
2676480093f4SDimitry Andric // .got.plt AND code to resolve a dynamic symbol lazily. With the 2-PLT scheme,
2677480093f4SDimitry Andric // the former code is written to .plt.sec, and the latter code is written to
2678480093f4SDimitry Andric // .plt.
2679480093f4SDimitry Andric //
2680480093f4SDimitry Andric // Lazy symbol resolution in the 2-PLT scheme works in the usual way, except
2681480093f4SDimitry Andric // that the regular .plt is now called .plt.sec and .plt is repurposed to
2682480093f4SDimitry Andric // contain only code for lazy symbol resolution.
2683480093f4SDimitry Andric //
2684480093f4SDimitry Andric // In other words, this is how the 2-PLT scheme works. Application code is
2685480093f4SDimitry Andric // supposed to jump to .plt.sec to call an external function. Each .plt.sec
2686480093f4SDimitry Andric // entry contains code to read an address from a corresponding .got.plt entry
2687480093f4SDimitry Andric // and jump to that address. Addresses in .got.plt initially point to .plt, so
2688480093f4SDimitry Andric // when an application calls an external function for the first time, the
2689480093f4SDimitry Andric // control is transferred to a function that resolves a symbol name from
2690480093f4SDimitry Andric // external shared object files. That function then rewrites a .got.plt entry
2691480093f4SDimitry Andric // with a resolved address, so that the subsequent function calls directly jump
2692480093f4SDimitry Andric // to a desired location from .plt.sec.
2693480093f4SDimitry Andric //
2694480093f4SDimitry Andric // There is an open question as to whether the 2-PLT scheme was desirable or
2695480093f4SDimitry Andric // not. We could have simply extended the PLT entry size to 32-bytes to
2696480093f4SDimitry Andric // accommodate endbr, and that scheme would have been much simpler than the
2697480093f4SDimitry Andric // 2-PLT scheme. One reason to split PLT was, by doing that, we could keep hot
2698480093f4SDimitry Andric // code (.plt.sec) from cold code (.plt). But as far as I know no one proved
2699480093f4SDimitry Andric // that the optimization actually makes a difference.
2700480093f4SDimitry Andric //
2701480093f4SDimitry Andric // That said, the 2-PLT scheme is a part of the ABI, debuggers and other tools
2702480093f4SDimitry Andric // depend on it, so we implement the ABI.
IBTPltSection()2703480093f4SDimitry Andric IBTPltSection::IBTPltSection()
2704480093f4SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt") {}
2705480093f4SDimitry Andric 
writeTo(uint8_t * buf)2706480093f4SDimitry Andric void IBTPltSection::writeTo(uint8_t *buf) {
2707480093f4SDimitry Andric   target->writeIBTPlt(buf, in.plt->getNumEntries());
2708480093f4SDimitry Andric }
2709480093f4SDimitry Andric 
getSize() const2710480093f4SDimitry Andric size_t IBTPltSection::getSize() const {
2711480093f4SDimitry Andric   // 16 is the header size of .plt.
2712480093f4SDimitry Andric   return 16 + in.plt->getNumEntries() * target->pltEntrySize;
2713480093f4SDimitry Andric }
2714480093f4SDimitry Andric 
isNeeded() const2715d781ede6SDimitry Andric bool IBTPltSection::isNeeded() const { return in.plt->getNumEntries() > 0; }
2716d781ede6SDimitry Andric 
RelroPaddingSection()27175f757f3fSDimitry Andric RelroPaddingSection::RelroPaddingSection()
27185f757f3fSDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1, ".relro_padding") {
27195f757f3fSDimitry Andric }
27205f757f3fSDimitry Andric 
27210b57cec5SDimitry Andric // The string hash function for .gdb_index.
computeGdbHash(StringRef s)27220b57cec5SDimitry Andric static uint32_t computeGdbHash(StringRef s) {
27230b57cec5SDimitry Andric   uint32_t h = 0;
27240b57cec5SDimitry Andric   for (uint8_t c : s)
27250b57cec5SDimitry Andric     h = h * 67 + toLower(c) - 113;
27260b57cec5SDimitry Andric   return h;
27270b57cec5SDimitry Andric }
27280b57cec5SDimitry Andric 
27290fca6ea1SDimitry Andric // 4-byte alignment ensures that values in the hash lookup table and the name
27300fca6ea1SDimitry Andric // table are aligned.
DebugNamesBaseSection()27310fca6ea1SDimitry Andric DebugNamesBaseSection::DebugNamesBaseSection()
27320fca6ea1SDimitry Andric     : SyntheticSection(0, SHT_PROGBITS, 4, ".debug_names") {}
27330fca6ea1SDimitry Andric 
27340fca6ea1SDimitry Andric // Get the size of the .debug_names section header in bytes for DWARF32:
getDebugNamesHeaderSize(uint32_t augmentationStringSize)27350fca6ea1SDimitry Andric static uint32_t getDebugNamesHeaderSize(uint32_t augmentationStringSize) {
27360fca6ea1SDimitry Andric   return /* unit length */ 4 +
27370fca6ea1SDimitry Andric          /* version */ 2 +
27380fca6ea1SDimitry Andric          /* padding */ 2 +
27390fca6ea1SDimitry Andric          /* CU count */ 4 +
27400fca6ea1SDimitry Andric          /* TU count */ 4 +
27410fca6ea1SDimitry Andric          /* Foreign TU count */ 4 +
27420fca6ea1SDimitry Andric          /* Bucket Count */ 4 +
27430fca6ea1SDimitry Andric          /* Name Count */ 4 +
27440fca6ea1SDimitry Andric          /* Abbrev table size */ 4 +
27450fca6ea1SDimitry Andric          /* Augmentation string size */ 4 +
27460fca6ea1SDimitry Andric          /* Augmentation string */ augmentationStringSize;
27470fca6ea1SDimitry Andric }
27480fca6ea1SDimitry Andric 
27490fca6ea1SDimitry Andric static Expected<DebugNamesBaseSection::IndexEntry *>
readEntry(uint64_t & offset,const DWARFDebugNames::NameIndex & ni,uint64_t entriesBase,DWARFDataExtractor & namesExtractor,const LLDDWARFSection & namesSec)27500fca6ea1SDimitry Andric readEntry(uint64_t &offset, const DWARFDebugNames::NameIndex &ni,
27510fca6ea1SDimitry Andric           uint64_t entriesBase, DWARFDataExtractor &namesExtractor,
27520fca6ea1SDimitry Andric           const LLDDWARFSection &namesSec) {
27530fca6ea1SDimitry Andric   auto ie = makeThreadLocal<DebugNamesBaseSection::IndexEntry>();
27540fca6ea1SDimitry Andric   ie->poolOffset = offset;
27550fca6ea1SDimitry Andric   Error err = Error::success();
27560fca6ea1SDimitry Andric   uint64_t ulebVal = namesExtractor.getULEB128(&offset, &err);
27570fca6ea1SDimitry Andric   if (err)
27580fca6ea1SDimitry Andric     return createStringError(inconvertibleErrorCode(),
27590fca6ea1SDimitry Andric                              "invalid abbrev code: %s",
27600fca6ea1SDimitry Andric                              toString(std::move(err)).c_str());
27610fca6ea1SDimitry Andric   if (!isUInt<32>(ulebVal))
27620fca6ea1SDimitry Andric     return createStringError(inconvertibleErrorCode(),
27630fca6ea1SDimitry Andric                              "abbrev code too large for DWARF32: %" PRIu64,
27640fca6ea1SDimitry Andric                              ulebVal);
27650fca6ea1SDimitry Andric   ie->abbrevCode = static_cast<uint32_t>(ulebVal);
27660fca6ea1SDimitry Andric   auto it = ni.getAbbrevs().find_as(ie->abbrevCode);
27670fca6ea1SDimitry Andric   if (it == ni.getAbbrevs().end())
27680fca6ea1SDimitry Andric     return createStringError(inconvertibleErrorCode(),
27690fca6ea1SDimitry Andric                              "abbrev code not found in abbrev table: %" PRIu32,
27700fca6ea1SDimitry Andric                              ie->abbrevCode);
27710fca6ea1SDimitry Andric 
27720fca6ea1SDimitry Andric   DebugNamesBaseSection::AttrValue attr, cuAttr = {0, 0};
27730fca6ea1SDimitry Andric   for (DWARFDebugNames::AttributeEncoding a : it->Attributes) {
27740fca6ea1SDimitry Andric     if (a.Index == dwarf::DW_IDX_parent) {
27750fca6ea1SDimitry Andric       if (a.Form == dwarf::DW_FORM_ref4) {
27760fca6ea1SDimitry Andric         attr.attrValue = namesExtractor.getU32(&offset, &err);
27770fca6ea1SDimitry Andric         attr.attrSize = 4;
27780fca6ea1SDimitry Andric         ie->parentOffset = entriesBase + attr.attrValue;
27790fca6ea1SDimitry Andric       } else if (a.Form != DW_FORM_flag_present)
27800fca6ea1SDimitry Andric         return createStringError(inconvertibleErrorCode(),
27810fca6ea1SDimitry Andric                                  "invalid form for DW_IDX_parent");
27820fca6ea1SDimitry Andric     } else {
27830fca6ea1SDimitry Andric       switch (a.Form) {
27840fca6ea1SDimitry Andric       case DW_FORM_data1:
27850fca6ea1SDimitry Andric       case DW_FORM_ref1: {
27860fca6ea1SDimitry Andric         attr.attrValue = namesExtractor.getU8(&offset, &err);
27870fca6ea1SDimitry Andric         attr.attrSize = 1;
27880fca6ea1SDimitry Andric         break;
27890fca6ea1SDimitry Andric       }
27900fca6ea1SDimitry Andric       case DW_FORM_data2:
27910fca6ea1SDimitry Andric       case DW_FORM_ref2: {
27920fca6ea1SDimitry Andric         attr.attrValue = namesExtractor.getU16(&offset, &err);
27930fca6ea1SDimitry Andric         attr.attrSize = 2;
27940fca6ea1SDimitry Andric         break;
27950fca6ea1SDimitry Andric       }
27960fca6ea1SDimitry Andric       case DW_FORM_data4:
27970fca6ea1SDimitry Andric       case DW_FORM_ref4: {
27980fca6ea1SDimitry Andric         attr.attrValue = namesExtractor.getU32(&offset, &err);
27990fca6ea1SDimitry Andric         attr.attrSize = 4;
28000fca6ea1SDimitry Andric         break;
28010fca6ea1SDimitry Andric       }
28020fca6ea1SDimitry Andric       default:
28030fca6ea1SDimitry Andric         return createStringError(
28040fca6ea1SDimitry Andric             inconvertibleErrorCode(),
28050fca6ea1SDimitry Andric             "unrecognized form encoding %d in abbrev table", a.Form);
28060fca6ea1SDimitry Andric       }
28070fca6ea1SDimitry Andric     }
28080fca6ea1SDimitry Andric     if (err)
28090fca6ea1SDimitry Andric       return createStringError(inconvertibleErrorCode(),
28100fca6ea1SDimitry Andric                                "error while reading attributes: %s",
28110fca6ea1SDimitry Andric                                toString(std::move(err)).c_str());
28120fca6ea1SDimitry Andric     if (a.Index == DW_IDX_compile_unit)
28130fca6ea1SDimitry Andric       cuAttr = attr;
28140fca6ea1SDimitry Andric     else if (a.Form != DW_FORM_flag_present)
28150fca6ea1SDimitry Andric       ie->attrValues.push_back(attr);
28160fca6ea1SDimitry Andric   }
28170fca6ea1SDimitry Andric   // Canonicalize abbrev by placing the CU/TU index at the end.
28180fca6ea1SDimitry Andric   ie->attrValues.push_back(cuAttr);
28190fca6ea1SDimitry Andric   return ie;
28200fca6ea1SDimitry Andric }
28210fca6ea1SDimitry Andric 
parseDebugNames(InputChunk & inputChunk,OutputChunk & chunk,DWARFDataExtractor & namesExtractor,DataExtractor & strExtractor,function_ref<SmallVector<uint32_t,0> (uint32_t numCus,const DWARFDebugNames::Header &,const DWARFDebugNames::DWARFDebugNamesOffsets &)> readOffsets)28220fca6ea1SDimitry Andric void DebugNamesBaseSection::parseDebugNames(
28230fca6ea1SDimitry Andric     InputChunk &inputChunk, OutputChunk &chunk,
28240fca6ea1SDimitry Andric     DWARFDataExtractor &namesExtractor, DataExtractor &strExtractor,
28250fca6ea1SDimitry Andric     function_ref<SmallVector<uint32_t, 0>(
28260fca6ea1SDimitry Andric         uint32_t numCus, const DWARFDebugNames::Header &,
28270fca6ea1SDimitry Andric         const DWARFDebugNames::DWARFDebugNamesOffsets &)>
28280fca6ea1SDimitry Andric         readOffsets) {
28290fca6ea1SDimitry Andric   const LLDDWARFSection &namesSec = inputChunk.section;
28300fca6ea1SDimitry Andric   DenseMap<uint32_t, IndexEntry *> offsetMap;
28310fca6ea1SDimitry Andric   // Number of CUs seen in previous NameIndex sections within current chunk.
28320fca6ea1SDimitry Andric   uint32_t numCus = 0;
28330fca6ea1SDimitry Andric   for (const DWARFDebugNames::NameIndex &ni : *inputChunk.llvmDebugNames) {
28340fca6ea1SDimitry Andric     NameData &nd = inputChunk.nameData.emplace_back();
28350fca6ea1SDimitry Andric     nd.hdr = ni.getHeader();
28360fca6ea1SDimitry Andric     if (nd.hdr.Format != DwarfFormat::DWARF32) {
28370fca6ea1SDimitry Andric       errorOrWarn(toString(namesSec.sec) +
28380fca6ea1SDimitry Andric                   Twine(": found DWARF64, which is currently unsupported"));
28390fca6ea1SDimitry Andric       return;
28400fca6ea1SDimitry Andric     }
28410fca6ea1SDimitry Andric     if (nd.hdr.Version != 5) {
28420fca6ea1SDimitry Andric       errorOrWarn(toString(namesSec.sec) + Twine(": unsupported version: ") +
28430fca6ea1SDimitry Andric                   Twine(nd.hdr.Version));
28440fca6ea1SDimitry Andric       return;
28450fca6ea1SDimitry Andric     }
28460fca6ea1SDimitry Andric     uint32_t dwarfSize = dwarf::getDwarfOffsetByteSize(DwarfFormat::DWARF32);
28470fca6ea1SDimitry Andric     DWARFDebugNames::DWARFDebugNamesOffsets locs = ni.getOffsets();
28480fca6ea1SDimitry Andric     if (locs.EntriesBase > namesExtractor.getData().size()) {
28490fca6ea1SDimitry Andric       errorOrWarn(toString(namesSec.sec) +
28500fca6ea1SDimitry Andric                   Twine(": entry pool start is beyond end of section"));
28510fca6ea1SDimitry Andric       return;
28520fca6ea1SDimitry Andric     }
28530fca6ea1SDimitry Andric 
28540fca6ea1SDimitry Andric     SmallVector<uint32_t, 0> entryOffsets = readOffsets(numCus, nd.hdr, locs);
28550fca6ea1SDimitry Andric 
28560fca6ea1SDimitry Andric     // Read the entry pool.
28570fca6ea1SDimitry Andric     offsetMap.clear();
28580fca6ea1SDimitry Andric     nd.nameEntries.resize(nd.hdr.NameCount);
28590fca6ea1SDimitry Andric     for (auto i : seq(nd.hdr.NameCount)) {
28600fca6ea1SDimitry Andric       NameEntry &ne = nd.nameEntries[i];
28610fca6ea1SDimitry Andric       uint64_t strOffset = locs.StringOffsetsBase + i * dwarfSize;
28620fca6ea1SDimitry Andric       ne.stringOffset = strOffset;
28630fca6ea1SDimitry Andric       uint64_t strp = namesExtractor.getRelocatedValue(dwarfSize, &strOffset);
28640fca6ea1SDimitry Andric       StringRef name = strExtractor.getCStrRef(&strp);
28650fca6ea1SDimitry Andric       ne.name = name.data();
28660fca6ea1SDimitry Andric       ne.hashValue = caseFoldingDjbHash(name);
28670fca6ea1SDimitry Andric 
28680fca6ea1SDimitry Andric       // Read a series of index entries that end with abbreviation code 0.
28690fca6ea1SDimitry Andric       uint64_t offset = locs.EntriesBase + entryOffsets[i];
28700fca6ea1SDimitry Andric       while (offset < namesSec.Data.size() && namesSec.Data[offset] != 0) {
28710fca6ea1SDimitry Andric         // Read & store all entries (for the same string).
28720fca6ea1SDimitry Andric         Expected<IndexEntry *> ieOrErr =
28730fca6ea1SDimitry Andric             readEntry(offset, ni, locs.EntriesBase, namesExtractor, namesSec);
28740fca6ea1SDimitry Andric         if (!ieOrErr) {
28750fca6ea1SDimitry Andric           errorOrWarn(toString(namesSec.sec) + ": " +
28760fca6ea1SDimitry Andric                       toString(ieOrErr.takeError()));
28770fca6ea1SDimitry Andric           return;
28780fca6ea1SDimitry Andric         }
28790fca6ea1SDimitry Andric         ne.indexEntries.push_back(std::move(*ieOrErr));
28800fca6ea1SDimitry Andric       }
28810fca6ea1SDimitry Andric       if (offset >= namesSec.Data.size())
28820fca6ea1SDimitry Andric         errorOrWarn(toString(namesSec.sec) +
28830fca6ea1SDimitry Andric                     Twine(": index entry is out of bounds"));
28840fca6ea1SDimitry Andric 
28850fca6ea1SDimitry Andric       for (IndexEntry &ie : ne.entries())
28860fca6ea1SDimitry Andric         offsetMap[ie.poolOffset] = &ie;
28870fca6ea1SDimitry Andric     }
28880fca6ea1SDimitry Andric 
28890fca6ea1SDimitry Andric     // Assign parent pointers, which will be used to update DW_IDX_parent index
28900fca6ea1SDimitry Andric     // attributes. Note: offsetMap[0] does not exist, so parentOffset == 0 will
28910fca6ea1SDimitry Andric     // get parentEntry == null as well.
28920fca6ea1SDimitry Andric     for (NameEntry &ne : nd.nameEntries)
28930fca6ea1SDimitry Andric       for (IndexEntry &ie : ne.entries())
28940fca6ea1SDimitry Andric         ie.parentEntry = offsetMap.lookup(ie.parentOffset);
28950fca6ea1SDimitry Andric     numCus += nd.hdr.CompUnitCount;
28960fca6ea1SDimitry Andric   }
28970fca6ea1SDimitry Andric }
28980fca6ea1SDimitry Andric 
28990fca6ea1SDimitry Andric // Compute the form for output DW_IDX_compile_unit attributes, similar to
29000fca6ea1SDimitry Andric // DIEInteger::BestForm. The input form (often DW_FORM_data1) may not hold all
29010fca6ea1SDimitry Andric // the merged CU indices.
getMergedCuCountForm(uint32_t compUnitCount)29020fca6ea1SDimitry Andric std::pair<uint8_t, dwarf::Form> static getMergedCuCountForm(
29030fca6ea1SDimitry Andric     uint32_t compUnitCount) {
29040fca6ea1SDimitry Andric   if (compUnitCount > UINT16_MAX)
29050fca6ea1SDimitry Andric     return {4, DW_FORM_data4};
29060fca6ea1SDimitry Andric   if (compUnitCount > UINT8_MAX)
29070fca6ea1SDimitry Andric     return {2, DW_FORM_data2};
29080fca6ea1SDimitry Andric   return {1, DW_FORM_data1};
29090fca6ea1SDimitry Andric }
29100fca6ea1SDimitry Andric 
computeHdrAndAbbrevTable(MutableArrayRef<InputChunk> inputChunks)29110fca6ea1SDimitry Andric void DebugNamesBaseSection::computeHdrAndAbbrevTable(
29120fca6ea1SDimitry Andric     MutableArrayRef<InputChunk> inputChunks) {
29130fca6ea1SDimitry Andric   TimeTraceScope timeScope("Merge .debug_names", "hdr and abbrev table");
29140fca6ea1SDimitry Andric   size_t numCu = 0;
29150fca6ea1SDimitry Andric   hdr.Format = DwarfFormat::DWARF32;
29160fca6ea1SDimitry Andric   hdr.Version = 5;
29170fca6ea1SDimitry Andric   hdr.CompUnitCount = 0;
29180fca6ea1SDimitry Andric   hdr.LocalTypeUnitCount = 0;
29190fca6ea1SDimitry Andric   hdr.ForeignTypeUnitCount = 0;
29200fca6ea1SDimitry Andric   hdr.AugmentationStringSize = 0;
29210fca6ea1SDimitry Andric 
29220fca6ea1SDimitry Andric   // Compute CU and TU counts.
29230fca6ea1SDimitry Andric   for (auto i : seq(numChunks)) {
29240fca6ea1SDimitry Andric     InputChunk &inputChunk = inputChunks[i];
29250fca6ea1SDimitry Andric     inputChunk.baseCuIdx = numCu;
29260fca6ea1SDimitry Andric     numCu += chunks[i].compUnits.size();
29270fca6ea1SDimitry Andric     for (const NameData &nd : inputChunk.nameData) {
29280fca6ea1SDimitry Andric       hdr.CompUnitCount += nd.hdr.CompUnitCount;
29290fca6ea1SDimitry Andric       // TODO: We don't handle type units yet, so LocalTypeUnitCount &
29300fca6ea1SDimitry Andric       // ForeignTypeUnitCount are left as 0.
29310fca6ea1SDimitry Andric       if (nd.hdr.LocalTypeUnitCount || nd.hdr.ForeignTypeUnitCount)
29320fca6ea1SDimitry Andric         warn(toString(inputChunk.section.sec) +
29330fca6ea1SDimitry Andric              Twine(": type units are not implemented"));
29340fca6ea1SDimitry Andric       // If augmentation strings are not identical, use an empty string.
29350fca6ea1SDimitry Andric       if (i == 0) {
29360fca6ea1SDimitry Andric         hdr.AugmentationStringSize = nd.hdr.AugmentationStringSize;
29370fca6ea1SDimitry Andric         hdr.AugmentationString = nd.hdr.AugmentationString;
29380fca6ea1SDimitry Andric       } else if (hdr.AugmentationString != nd.hdr.AugmentationString) {
29390fca6ea1SDimitry Andric         // There are conflicting augmentation strings, so it's best for the
29400fca6ea1SDimitry Andric         // merged index to not use an augmentation string.
29410fca6ea1SDimitry Andric         hdr.AugmentationStringSize = 0;
29420fca6ea1SDimitry Andric         hdr.AugmentationString.clear();
29430fca6ea1SDimitry Andric       }
29440fca6ea1SDimitry Andric     }
29450fca6ea1SDimitry Andric   }
29460fca6ea1SDimitry Andric 
29470fca6ea1SDimitry Andric   // Create the merged abbrev table, uniquifyinng the input abbrev tables and
29480fca6ea1SDimitry Andric   // computing mapping from old (per-cu) abbrev codes to new (merged) abbrev
29490fca6ea1SDimitry Andric   // codes.
29500fca6ea1SDimitry Andric   FoldingSet<Abbrev> abbrevSet;
29510fca6ea1SDimitry Andric   // Determine the form for the DW_IDX_compile_unit attributes in the merged
29520fca6ea1SDimitry Andric   // index. The input form may not be big enough for all CU indices.
29530fca6ea1SDimitry Andric   dwarf::Form cuAttrForm = getMergedCuCountForm(hdr.CompUnitCount).second;
29540fca6ea1SDimitry Andric   for (InputChunk &inputChunk : inputChunks) {
29550fca6ea1SDimitry Andric     for (auto [i, ni] : enumerate(*inputChunk.llvmDebugNames)) {
29560fca6ea1SDimitry Andric       for (const DWARFDebugNames::Abbrev &oldAbbrev : ni.getAbbrevs()) {
29570fca6ea1SDimitry Andric         // Canonicalize abbrev by placing the CU/TU index at the end,
29580fca6ea1SDimitry Andric         // similar to 'parseDebugNames'.
29590fca6ea1SDimitry Andric         Abbrev abbrev;
29600fca6ea1SDimitry Andric         DWARFDebugNames::AttributeEncoding cuAttr(DW_IDX_compile_unit,
29610fca6ea1SDimitry Andric                                                   cuAttrForm);
29620fca6ea1SDimitry Andric         abbrev.code = oldAbbrev.Code;
29630fca6ea1SDimitry Andric         abbrev.tag = oldAbbrev.Tag;
29640fca6ea1SDimitry Andric         for (DWARFDebugNames::AttributeEncoding a : oldAbbrev.Attributes) {
29650fca6ea1SDimitry Andric           if (a.Index == DW_IDX_compile_unit)
29660fca6ea1SDimitry Andric             cuAttr.Index = a.Index;
29670fca6ea1SDimitry Andric           else
29680fca6ea1SDimitry Andric             abbrev.attributes.push_back({a.Index, a.Form});
29690fca6ea1SDimitry Andric         }
29700fca6ea1SDimitry Andric         // Put the CU/TU index at the end of the attributes list.
29710fca6ea1SDimitry Andric         abbrev.attributes.push_back(cuAttr);
29720fca6ea1SDimitry Andric 
29730fca6ea1SDimitry Andric         // Profile the abbrev, get or assign a new code, then record the abbrev
29740fca6ea1SDimitry Andric         // code mapping.
29750fca6ea1SDimitry Andric         FoldingSetNodeID id;
29760fca6ea1SDimitry Andric         abbrev.Profile(id);
29770fca6ea1SDimitry Andric         uint32_t newCode;
29780fca6ea1SDimitry Andric         void *insertPos;
29790fca6ea1SDimitry Andric         if (Abbrev *existing = abbrevSet.FindNodeOrInsertPos(id, insertPos)) {
29800fca6ea1SDimitry Andric           // Found it; we've already seen an identical abbreviation.
29810fca6ea1SDimitry Andric           newCode = existing->code;
29820fca6ea1SDimitry Andric         } else {
29830fca6ea1SDimitry Andric           Abbrev *abbrev2 =
29840fca6ea1SDimitry Andric               new (abbrevAlloc.Allocate()) Abbrev(std::move(abbrev));
29850fca6ea1SDimitry Andric           abbrevSet.InsertNode(abbrev2, insertPos);
29860fca6ea1SDimitry Andric           abbrevTable.push_back(abbrev2);
29870fca6ea1SDimitry Andric           newCode = abbrevTable.size();
29880fca6ea1SDimitry Andric           abbrev2->code = newCode;
29890fca6ea1SDimitry Andric         }
29900fca6ea1SDimitry Andric         inputChunk.nameData[i].abbrevCodeMap[oldAbbrev.Code] = newCode;
29910fca6ea1SDimitry Andric       }
29920fca6ea1SDimitry Andric     }
29930fca6ea1SDimitry Andric   }
29940fca6ea1SDimitry Andric 
29950fca6ea1SDimitry Andric   // Compute the merged abbrev table.
29960fca6ea1SDimitry Andric   raw_svector_ostream os(abbrevTableBuf);
29970fca6ea1SDimitry Andric   for (Abbrev *abbrev : abbrevTable) {
29980fca6ea1SDimitry Andric     encodeULEB128(abbrev->code, os);
29990fca6ea1SDimitry Andric     encodeULEB128(abbrev->tag, os);
30000fca6ea1SDimitry Andric     for (DWARFDebugNames::AttributeEncoding a : abbrev->attributes) {
30010fca6ea1SDimitry Andric       encodeULEB128(a.Index, os);
30020fca6ea1SDimitry Andric       encodeULEB128(a.Form, os);
30030fca6ea1SDimitry Andric     }
30040fca6ea1SDimitry Andric     os.write("\0", 2); // attribute specification end
30050fca6ea1SDimitry Andric   }
30060fca6ea1SDimitry Andric   os.write(0); // abbrev table end
30070fca6ea1SDimitry Andric   hdr.AbbrevTableSize = abbrevTableBuf.size();
30080fca6ea1SDimitry Andric }
30090fca6ea1SDimitry Andric 
Profile(FoldingSetNodeID & id) const30100fca6ea1SDimitry Andric void DebugNamesBaseSection::Abbrev::Profile(FoldingSetNodeID &id) const {
30110fca6ea1SDimitry Andric   id.AddInteger(tag);
30120fca6ea1SDimitry Andric   for (const DWARFDebugNames::AttributeEncoding &attr : attributes) {
30130fca6ea1SDimitry Andric     id.AddInteger(attr.Index);
30140fca6ea1SDimitry Andric     id.AddInteger(attr.Form);
30150fca6ea1SDimitry Andric   }
30160fca6ea1SDimitry Andric }
30170fca6ea1SDimitry Andric 
computeEntryPool(MutableArrayRef<InputChunk> inputChunks)30180fca6ea1SDimitry Andric std::pair<uint32_t, uint32_t> DebugNamesBaseSection::computeEntryPool(
30190fca6ea1SDimitry Andric     MutableArrayRef<InputChunk> inputChunks) {
30200fca6ea1SDimitry Andric   TimeTraceScope timeScope("Merge .debug_names", "entry pool");
30210fca6ea1SDimitry Andric   // Collect and de-duplicate all the names (preserving all the entries).
30220fca6ea1SDimitry Andric   // Speed it up using multithreading, as the number of symbols can be in the
30230fca6ea1SDimitry Andric   // order of millions.
30240fca6ea1SDimitry Andric   const size_t concurrency =
30250fca6ea1SDimitry Andric       bit_floor(std::min<size_t>(config->threadCount, numShards));
30260fca6ea1SDimitry Andric   const size_t shift = 32 - countr_zero(numShards);
30270fca6ea1SDimitry Andric   const uint8_t cuAttrSize = getMergedCuCountForm(hdr.CompUnitCount).first;
30280fca6ea1SDimitry Andric   DenseMap<CachedHashStringRef, size_t> maps[numShards];
30290fca6ea1SDimitry Andric 
30300fca6ea1SDimitry Andric   parallelFor(0, concurrency, [&](size_t threadId) {
30310fca6ea1SDimitry Andric     for (auto i : seq(numChunks)) {
30320fca6ea1SDimitry Andric       InputChunk &inputChunk = inputChunks[i];
30330fca6ea1SDimitry Andric       for (auto j : seq(inputChunk.nameData.size())) {
30340fca6ea1SDimitry Andric         NameData &nd = inputChunk.nameData[j];
30350fca6ea1SDimitry Andric         // Deduplicate the NameEntry records (based on the string/name),
30360fca6ea1SDimitry Andric         // appending all IndexEntries from duplicate NameEntry records to
30370fca6ea1SDimitry Andric         // the single preserved copy.
30380fca6ea1SDimitry Andric         for (NameEntry &ne : nd.nameEntries) {
30390fca6ea1SDimitry Andric           auto shardId = ne.hashValue >> shift;
30400fca6ea1SDimitry Andric           if ((shardId & (concurrency - 1)) != threadId)
30410fca6ea1SDimitry Andric             continue;
30420fca6ea1SDimitry Andric 
30430fca6ea1SDimitry Andric           ne.chunkIdx = i;
30440fca6ea1SDimitry Andric           for (IndexEntry &ie : ne.entries()) {
30450fca6ea1SDimitry Andric             // Update the IndexEntry's abbrev code to match the merged
30460fca6ea1SDimitry Andric             // abbreviations.
30470fca6ea1SDimitry Andric             ie.abbrevCode = nd.abbrevCodeMap[ie.abbrevCode];
30480fca6ea1SDimitry Andric             // Update the DW_IDX_compile_unit attribute (the last one after
30490fca6ea1SDimitry Andric             // canonicalization) to have correct merged offset value and size.
30500fca6ea1SDimitry Andric             auto &back = ie.attrValues.back();
30510fca6ea1SDimitry Andric             back.attrValue += inputChunk.baseCuIdx + j;
30520fca6ea1SDimitry Andric             back.attrSize = cuAttrSize;
30530fca6ea1SDimitry Andric           }
30540fca6ea1SDimitry Andric 
30550fca6ea1SDimitry Andric           auto &nameVec = nameVecs[shardId];
30560fca6ea1SDimitry Andric           auto [it, inserted] = maps[shardId].try_emplace(
30570fca6ea1SDimitry Andric               CachedHashStringRef(ne.name, ne.hashValue), nameVec.size());
30580fca6ea1SDimitry Andric           if (inserted)
30590fca6ea1SDimitry Andric             nameVec.push_back(std::move(ne));
30600fca6ea1SDimitry Andric           else
30610fca6ea1SDimitry Andric             nameVec[it->second].indexEntries.append(std::move(ne.indexEntries));
30620fca6ea1SDimitry Andric         }
30630fca6ea1SDimitry Andric       }
30640fca6ea1SDimitry Andric     }
30650fca6ea1SDimitry Andric   });
30660fca6ea1SDimitry Andric 
30670fca6ea1SDimitry Andric   // Compute entry offsets in parallel. First, compute offsets relative to the
30680fca6ea1SDimitry Andric   // current shard.
30690fca6ea1SDimitry Andric   uint32_t offsets[numShards];
30700fca6ea1SDimitry Andric   parallelFor(0, numShards, [&](size_t shard) {
30710fca6ea1SDimitry Andric     uint32_t offset = 0;
30720fca6ea1SDimitry Andric     for (NameEntry &ne : nameVecs[shard]) {
30730fca6ea1SDimitry Andric       ne.entryOffset = offset;
30740fca6ea1SDimitry Andric       for (IndexEntry &ie : ne.entries()) {
30750fca6ea1SDimitry Andric         ie.poolOffset = offset;
30760fca6ea1SDimitry Andric         offset += getULEB128Size(ie.abbrevCode);
30770fca6ea1SDimitry Andric         for (AttrValue value : ie.attrValues)
30780fca6ea1SDimitry Andric           offset += value.attrSize;
30790fca6ea1SDimitry Andric       }
30800fca6ea1SDimitry Andric       ++offset; // index entry sentinel
30810fca6ea1SDimitry Andric     }
30820fca6ea1SDimitry Andric     offsets[shard] = offset;
30830fca6ea1SDimitry Andric   });
30840fca6ea1SDimitry Andric   // Then add shard offsets.
30850fca6ea1SDimitry Andric   std::partial_sum(offsets, std::end(offsets), offsets);
30860fca6ea1SDimitry Andric   parallelFor(1, numShards, [&](size_t shard) {
30870fca6ea1SDimitry Andric     uint32_t offset = offsets[shard - 1];
30880fca6ea1SDimitry Andric     for (NameEntry &ne : nameVecs[shard]) {
30890fca6ea1SDimitry Andric       ne.entryOffset += offset;
30900fca6ea1SDimitry Andric       for (IndexEntry &ie : ne.entries())
30910fca6ea1SDimitry Andric         ie.poolOffset += offset;
30920fca6ea1SDimitry Andric     }
30930fca6ea1SDimitry Andric   });
30940fca6ea1SDimitry Andric 
30950fca6ea1SDimitry Andric   // Update the DW_IDX_parent entries that refer to real parents (have
30960fca6ea1SDimitry Andric   // DW_FORM_ref4).
30970fca6ea1SDimitry Andric   parallelFor(0, numShards, [&](size_t shard) {
30980fca6ea1SDimitry Andric     for (NameEntry &ne : nameVecs[shard]) {
30990fca6ea1SDimitry Andric       for (IndexEntry &ie : ne.entries()) {
31000fca6ea1SDimitry Andric         if (!ie.parentEntry)
31010fca6ea1SDimitry Andric           continue;
31020fca6ea1SDimitry Andric         // Abbrevs are indexed starting at 1; vector starts at 0. (abbrevCode
31030fca6ea1SDimitry Andric         // corresponds to position in the merged table vector).
31040fca6ea1SDimitry Andric         const Abbrev *abbrev = abbrevTable[ie.abbrevCode - 1];
31050fca6ea1SDimitry Andric         for (const auto &[a, v] : zip_equal(abbrev->attributes, ie.attrValues))
31060fca6ea1SDimitry Andric           if (a.Index == DW_IDX_parent && a.Form == DW_FORM_ref4)
31070fca6ea1SDimitry Andric             v.attrValue = ie.parentEntry->poolOffset;
31080fca6ea1SDimitry Andric       }
31090fca6ea1SDimitry Andric     }
31100fca6ea1SDimitry Andric   });
31110fca6ea1SDimitry Andric 
31120fca6ea1SDimitry Andric   // Return (entry pool size, number of entries).
31130fca6ea1SDimitry Andric   uint32_t num = 0;
31140fca6ea1SDimitry Andric   for (auto &map : maps)
31150fca6ea1SDimitry Andric     num += map.size();
31160fca6ea1SDimitry Andric   return {offsets[numShards - 1], num};
31170fca6ea1SDimitry Andric }
31180fca6ea1SDimitry Andric 
init(function_ref<void (InputFile *,InputChunk &,OutputChunk &)> parseFile)31190fca6ea1SDimitry Andric void DebugNamesBaseSection::init(
31200fca6ea1SDimitry Andric     function_ref<void(InputFile *, InputChunk &, OutputChunk &)> parseFile) {
31210fca6ea1SDimitry Andric   TimeTraceScope timeScope("Merge .debug_names");
31220fca6ea1SDimitry Andric   // Collect and remove input .debug_names sections. Save InputSection pointers
31230fca6ea1SDimitry Andric   // to relocate string offsets in `writeTo`.
31240fca6ea1SDimitry Andric   SetVector<InputFile *> files;
31250fca6ea1SDimitry Andric   for (InputSectionBase *s : ctx.inputSections) {
31260fca6ea1SDimitry Andric     InputSection *isec = dyn_cast<InputSection>(s);
31270fca6ea1SDimitry Andric     if (!isec)
31280fca6ea1SDimitry Andric       continue;
31290fca6ea1SDimitry Andric     if (!(s->flags & SHF_ALLOC) && s->name == ".debug_names") {
31300fca6ea1SDimitry Andric       s->markDead();
31310fca6ea1SDimitry Andric       inputSections.push_back(isec);
31320fca6ea1SDimitry Andric       files.insert(isec->file);
31330fca6ea1SDimitry Andric     }
31340fca6ea1SDimitry Andric   }
31350fca6ea1SDimitry Andric 
31360fca6ea1SDimitry Andric   // Parse input .debug_names sections and extract InputChunk and OutputChunk
31370fca6ea1SDimitry Andric   // data. OutputChunk contains CU information, which will be needed by
31380fca6ea1SDimitry Andric   // `writeTo`.
31390fca6ea1SDimitry Andric   auto inputChunksPtr = std::make_unique<InputChunk[]>(files.size());
31400fca6ea1SDimitry Andric   MutableArrayRef<InputChunk> inputChunks(inputChunksPtr.get(), files.size());
31410fca6ea1SDimitry Andric   numChunks = files.size();
31420fca6ea1SDimitry Andric   chunks = std::make_unique<OutputChunk[]>(files.size());
31430fca6ea1SDimitry Andric   {
31440fca6ea1SDimitry Andric     TimeTraceScope timeScope("Merge .debug_names", "parse");
31450fca6ea1SDimitry Andric     parallelFor(0, files.size(), [&](size_t i) {
31460fca6ea1SDimitry Andric       parseFile(files[i], inputChunks[i], chunks[i]);
31470fca6ea1SDimitry Andric     });
31480fca6ea1SDimitry Andric   }
31490fca6ea1SDimitry Andric 
31500fca6ea1SDimitry Andric   // Compute section header (except unit_length), abbrev table, and entry pool.
31510fca6ea1SDimitry Andric   computeHdrAndAbbrevTable(inputChunks);
31520fca6ea1SDimitry Andric   uint32_t entryPoolSize;
31530fca6ea1SDimitry Andric   std::tie(entryPoolSize, hdr.NameCount) = computeEntryPool(inputChunks);
31540fca6ea1SDimitry Andric   hdr.BucketCount = dwarf::getDebugNamesBucketCount(hdr.NameCount);
31550fca6ea1SDimitry Andric 
31560fca6ea1SDimitry Andric   // Compute the section size. Subtract 4 to get the unit_length for DWARF32.
31570fca6ea1SDimitry Andric   uint32_t hdrSize = getDebugNamesHeaderSize(hdr.AugmentationStringSize);
31580fca6ea1SDimitry Andric   size = findDebugNamesOffsets(hdrSize, hdr).EntriesBase + entryPoolSize;
31590fca6ea1SDimitry Andric   hdr.UnitLength = size - 4;
31600fca6ea1SDimitry Andric }
31610fca6ea1SDimitry Andric 
DebugNamesSection()31620fca6ea1SDimitry Andric template <class ELFT> DebugNamesSection<ELFT>::DebugNamesSection() {
31630fca6ea1SDimitry Andric   init([](InputFile *f, InputChunk &inputChunk, OutputChunk &chunk) {
31640fca6ea1SDimitry Andric     auto *file = cast<ObjFile<ELFT>>(f);
31650fca6ea1SDimitry Andric     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
31660fca6ea1SDimitry Andric     auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
31670fca6ea1SDimitry Andric     chunk.infoSec = dobj.getInfoSection();
31680fca6ea1SDimitry Andric     DWARFDataExtractor namesExtractor(dobj, dobj.getNamesSection(),
31690fca6ea1SDimitry Andric                                       ELFT::Endianness == endianness::little,
31700fca6ea1SDimitry Andric                                       ELFT::Is64Bits ? 8 : 4);
31710fca6ea1SDimitry Andric     // .debug_str is needed to get symbol names from string offsets.
31720fca6ea1SDimitry Andric     DataExtractor strExtractor(dobj.getStrSection(),
31730fca6ea1SDimitry Andric                                ELFT::Endianness == endianness::little,
31740fca6ea1SDimitry Andric                                ELFT::Is64Bits ? 8 : 4);
31750fca6ea1SDimitry Andric     inputChunk.section = dobj.getNamesSection();
31760fca6ea1SDimitry Andric 
31770fca6ea1SDimitry Andric     inputChunk.llvmDebugNames.emplace(namesExtractor, strExtractor);
31780fca6ea1SDimitry Andric     if (Error e = inputChunk.llvmDebugNames->extract()) {
31790fca6ea1SDimitry Andric       errorOrWarn(toString(dobj.getNamesSection().sec) + Twine(": ") +
31800fca6ea1SDimitry Andric                   toString(std::move(e)));
31810fca6ea1SDimitry Andric     }
31820fca6ea1SDimitry Andric     parseDebugNames(
31830fca6ea1SDimitry Andric         inputChunk, chunk, namesExtractor, strExtractor,
31840fca6ea1SDimitry Andric         [&chunk, namesData = dobj.getNamesSection().Data.data()](
31850fca6ea1SDimitry Andric             uint32_t numCus, const DWARFDebugNames::Header &hdr,
31860fca6ea1SDimitry Andric             const DWARFDebugNames::DWARFDebugNamesOffsets &locs) {
31870fca6ea1SDimitry Andric           // Read CU offsets, which are relocated by .debug_info + X
31880fca6ea1SDimitry Andric           // relocations. Record the section offset to be relocated by
31890fca6ea1SDimitry Andric           // `finalizeContents`.
31900fca6ea1SDimitry Andric           chunk.compUnits.resize_for_overwrite(numCus + hdr.CompUnitCount);
31910fca6ea1SDimitry Andric           for (auto i : seq(hdr.CompUnitCount))
31920fca6ea1SDimitry Andric             chunk.compUnits[numCus + i] = locs.CUsBase + i * 4;
31930fca6ea1SDimitry Andric 
31940fca6ea1SDimitry Andric           // Read entry offsets.
31950fca6ea1SDimitry Andric           const char *p = namesData + locs.EntryOffsetsBase;
31960fca6ea1SDimitry Andric           SmallVector<uint32_t, 0> entryOffsets;
31970fca6ea1SDimitry Andric           entryOffsets.resize_for_overwrite(hdr.NameCount);
31980fca6ea1SDimitry Andric           for (uint32_t &offset : entryOffsets)
31990fca6ea1SDimitry Andric             offset = endian::readNext<uint32_t, ELFT::Endianness, unaligned>(p);
32000fca6ea1SDimitry Andric           return entryOffsets;
32010fca6ea1SDimitry Andric         });
32020fca6ea1SDimitry Andric   });
32030fca6ea1SDimitry Andric }
32040fca6ea1SDimitry Andric 
32050fca6ea1SDimitry Andric template <class ELFT>
32060fca6ea1SDimitry Andric template <class RelTy>
getNameRelocs(const InputFile & file,DenseMap<uint32_t,uint32_t> & relocs,Relocs<RelTy> rels)32070fca6ea1SDimitry Andric void DebugNamesSection<ELFT>::getNameRelocs(
3208*52418fc2SDimitry Andric     const InputFile &file, DenseMap<uint32_t, uint32_t> &relocs,
3209*52418fc2SDimitry Andric     Relocs<RelTy> rels) {
32100fca6ea1SDimitry Andric   for (const RelTy &rel : rels) {
3211*52418fc2SDimitry Andric     Symbol &sym = file.getRelocTargetSym(rel);
32120fca6ea1SDimitry Andric     relocs[rel.r_offset] = sym.getVA(getAddend<ELFT>(rel));
32130fca6ea1SDimitry Andric   }
32140fca6ea1SDimitry Andric }
32150fca6ea1SDimitry Andric 
finalizeContents()32160fca6ea1SDimitry Andric template <class ELFT> void DebugNamesSection<ELFT>::finalizeContents() {
32170fca6ea1SDimitry Andric   // Get relocations of .debug_names sections.
32180fca6ea1SDimitry Andric   auto relocs = std::make_unique<DenseMap<uint32_t, uint32_t>[]>(numChunks);
32190fca6ea1SDimitry Andric   parallelFor(0, numChunks, [&](size_t i) {
32200fca6ea1SDimitry Andric     InputSection *sec = inputSections[i];
3221*52418fc2SDimitry Andric     invokeOnRelocs(*sec, getNameRelocs, *sec->file, relocs.get()[i]);
32220fca6ea1SDimitry Andric 
32230fca6ea1SDimitry Andric     // Relocate CU offsets with .debug_info + X relocations.
32240fca6ea1SDimitry Andric     OutputChunk &chunk = chunks.get()[i];
32250fca6ea1SDimitry Andric     for (auto [j, cuOffset] : enumerate(chunk.compUnits))
32260fca6ea1SDimitry Andric       cuOffset = relocs.get()[i].lookup(cuOffset);
32270fca6ea1SDimitry Andric   });
32280fca6ea1SDimitry Andric 
32290fca6ea1SDimitry Andric   // Relocate string offsets in the name table with .debug_str + X relocations.
32300fca6ea1SDimitry Andric   parallelForEach(nameVecs, [&](auto &nameVec) {
32310fca6ea1SDimitry Andric     for (NameEntry &ne : nameVec)
32320fca6ea1SDimitry Andric       ne.stringOffset = relocs.get()[ne.chunkIdx].lookup(ne.stringOffset);
32330fca6ea1SDimitry Andric   });
32340fca6ea1SDimitry Andric }
32350fca6ea1SDimitry Andric 
writeTo(uint8_t * buf)32360fca6ea1SDimitry Andric template <class ELFT> void DebugNamesSection<ELFT>::writeTo(uint8_t *buf) {
32370fca6ea1SDimitry Andric   [[maybe_unused]] const uint8_t *const beginBuf = buf;
32380fca6ea1SDimitry Andric   // Write the header.
32390fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.UnitLength);
32400fca6ea1SDimitry Andric   endian::writeNext<uint16_t, ELFT::Endianness>(buf, hdr.Version);
32410fca6ea1SDimitry Andric   buf += 2; // padding
32420fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.CompUnitCount);
32430fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.LocalTypeUnitCount);
32440fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.ForeignTypeUnitCount);
32450fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.BucketCount);
32460fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.NameCount);
32470fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.AbbrevTableSize);
32480fca6ea1SDimitry Andric   endian::writeNext<uint32_t, ELFT::Endianness>(buf,
32490fca6ea1SDimitry Andric                                                 hdr.AugmentationStringSize);
32500fca6ea1SDimitry Andric   memcpy(buf, hdr.AugmentationString.c_str(), hdr.AugmentationString.size());
32510fca6ea1SDimitry Andric   buf += hdr.AugmentationStringSize;
32520fca6ea1SDimitry Andric 
32530fca6ea1SDimitry Andric   // Write the CU list.
32540fca6ea1SDimitry Andric   for (auto &chunk : getChunks())
32550fca6ea1SDimitry Andric     for (uint32_t cuOffset : chunk.compUnits)
32560fca6ea1SDimitry Andric       endian::writeNext<uint32_t, ELFT::Endianness>(buf, cuOffset);
32570fca6ea1SDimitry Andric 
32580fca6ea1SDimitry Andric   // TODO: Write the local TU list, then the foreign TU list..
32590fca6ea1SDimitry Andric 
32600fca6ea1SDimitry Andric   // Write the hash lookup table.
32610fca6ea1SDimitry Andric   SmallVector<SmallVector<NameEntry *, 0>, 0> buckets(hdr.BucketCount);
32620fca6ea1SDimitry Andric   // Symbols enter into a bucket whose index is the hash modulo bucket_count.
32630fca6ea1SDimitry Andric   for (auto &nameVec : nameVecs)
32640fca6ea1SDimitry Andric     for (NameEntry &ne : nameVec)
32650fca6ea1SDimitry Andric       buckets[ne.hashValue % hdr.BucketCount].push_back(&ne);
32660fca6ea1SDimitry Andric 
32670fca6ea1SDimitry Andric   // Write buckets (accumulated bucket counts).
32680fca6ea1SDimitry Andric   uint32_t bucketIdx = 1;
32690fca6ea1SDimitry Andric   for (const SmallVector<NameEntry *, 0> &bucket : buckets) {
32700fca6ea1SDimitry Andric     if (!bucket.empty())
32710fca6ea1SDimitry Andric       endian::write32<ELFT::Endianness>(buf, bucketIdx);
32720fca6ea1SDimitry Andric     buf += 4;
32730fca6ea1SDimitry Andric     bucketIdx += bucket.size();
32740fca6ea1SDimitry Andric   }
32750fca6ea1SDimitry Andric   // Write the hashes.
32760fca6ea1SDimitry Andric   for (const SmallVector<NameEntry *, 0> &bucket : buckets)
32770fca6ea1SDimitry Andric     for (const NameEntry *e : bucket)
32780fca6ea1SDimitry Andric       endian::writeNext<uint32_t, ELFT::Endianness>(buf, e->hashValue);
32790fca6ea1SDimitry Andric 
32800fca6ea1SDimitry Andric   // Write the name table. The name entries are ordered by bucket_idx and
32810fca6ea1SDimitry Andric   // correspond one-to-one with the hash lookup table.
32820fca6ea1SDimitry Andric   //
32830fca6ea1SDimitry Andric   // First, write the relocated string offsets.
32840fca6ea1SDimitry Andric   for (const SmallVector<NameEntry *, 0> &bucket : buckets)
32850fca6ea1SDimitry Andric     for (const NameEntry *ne : bucket)
32860fca6ea1SDimitry Andric       endian::writeNext<uint32_t, ELFT::Endianness>(buf, ne->stringOffset);
32870fca6ea1SDimitry Andric 
32880fca6ea1SDimitry Andric   // Then write the entry offsets.
32890fca6ea1SDimitry Andric   for (const SmallVector<NameEntry *, 0> &bucket : buckets)
32900fca6ea1SDimitry Andric     for (const NameEntry *ne : bucket)
32910fca6ea1SDimitry Andric       endian::writeNext<uint32_t, ELFT::Endianness>(buf, ne->entryOffset);
32920fca6ea1SDimitry Andric 
32930fca6ea1SDimitry Andric   // Write the abbrev table.
32940fca6ea1SDimitry Andric   buf = llvm::copy(abbrevTableBuf, buf);
32950fca6ea1SDimitry Andric 
32960fca6ea1SDimitry Andric   // Write the entry pool. Unlike the name table, the name entries follow the
32970fca6ea1SDimitry Andric   // nameVecs order computed by `computeEntryPool`.
32980fca6ea1SDimitry Andric   for (auto &nameVec : nameVecs) {
32990fca6ea1SDimitry Andric     for (NameEntry &ne : nameVec) {
33000fca6ea1SDimitry Andric       // Write all the entries for the string.
33010fca6ea1SDimitry Andric       for (const IndexEntry &ie : ne.entries()) {
33020fca6ea1SDimitry Andric         buf += encodeULEB128(ie.abbrevCode, buf);
33030fca6ea1SDimitry Andric         for (AttrValue value : ie.attrValues) {
33040fca6ea1SDimitry Andric           switch (value.attrSize) {
33050fca6ea1SDimitry Andric           case 1:
33060fca6ea1SDimitry Andric             *buf++ = value.attrValue;
33070fca6ea1SDimitry Andric             break;
33080fca6ea1SDimitry Andric           case 2:
33090fca6ea1SDimitry Andric             endian::writeNext<uint16_t, ELFT::Endianness>(buf, value.attrValue);
33100fca6ea1SDimitry Andric             break;
33110fca6ea1SDimitry Andric           case 4:
33120fca6ea1SDimitry Andric             endian::writeNext<uint32_t, ELFT::Endianness>(buf, value.attrValue);
33130fca6ea1SDimitry Andric             break;
33140fca6ea1SDimitry Andric           default:
33150fca6ea1SDimitry Andric             llvm_unreachable("invalid attrSize");
33160fca6ea1SDimitry Andric           }
33170fca6ea1SDimitry Andric         }
33180fca6ea1SDimitry Andric       }
33190fca6ea1SDimitry Andric       ++buf; // index entry sentinel
33200fca6ea1SDimitry Andric     }
33210fca6ea1SDimitry Andric   }
33220fca6ea1SDimitry Andric   assert(uint64_t(buf - beginBuf) == size);
33230fca6ea1SDimitry Andric }
33240fca6ea1SDimitry Andric 
GdbIndexSection()33250b57cec5SDimitry Andric GdbIndexSection::GdbIndexSection()
33260b57cec5SDimitry Andric     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric // Returns the desired size of an on-disk hash table for a .gdb_index section.
33290b57cec5SDimitry Andric // There's a tradeoff between size and collision rate. We aim 75% utilization.
computeSymtabSize() const33300b57cec5SDimitry Andric size_t GdbIndexSection::computeSymtabSize() const {
33310b57cec5SDimitry Andric   return std::max<size_t>(NextPowerOf2(symbols.size() * 4 / 3), 1024);
33320b57cec5SDimitry Andric }
33330b57cec5SDimitry Andric 
33340eae32dcSDimitry Andric static SmallVector<GdbIndexSection::CuEntry, 0>
readCuList(DWARFContext & dwarf)33350eae32dcSDimitry Andric readCuList(DWARFContext &dwarf) {
33360eae32dcSDimitry Andric   SmallVector<GdbIndexSection::CuEntry, 0> ret;
33370b57cec5SDimitry Andric   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
33380b57cec5SDimitry Andric     ret.push_back({cu->getOffset(), cu->getLength() + 4});
33390b57cec5SDimitry Andric   return ret;
33400b57cec5SDimitry Andric }
33410b57cec5SDimitry Andric 
33420eae32dcSDimitry Andric static SmallVector<GdbIndexSection::AddressEntry, 0>
readAddressAreas(DWARFContext & dwarf,InputSection * sec)33430b57cec5SDimitry Andric readAddressAreas(DWARFContext &dwarf, InputSection *sec) {
33440eae32dcSDimitry Andric   SmallVector<GdbIndexSection::AddressEntry, 0> ret;
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric   uint32_t cuIdx = 0;
33470b57cec5SDimitry Andric   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
334885868e8aSDimitry Andric     if (Error e = cu->tryExtractDIEsIfNeeded(false)) {
33495ffd83dbSDimitry Andric       warn(toString(sec) + ": " + toString(std::move(e)));
335085868e8aSDimitry Andric       return {};
335185868e8aSDimitry Andric     }
33520b57cec5SDimitry Andric     Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
33530b57cec5SDimitry Andric     if (!ranges) {
33545ffd83dbSDimitry Andric       warn(toString(sec) + ": " + toString(ranges.takeError()));
33550b57cec5SDimitry Andric       return {};
33560b57cec5SDimitry Andric     }
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric     ArrayRef<InputSectionBase *> sections = sec->file->getSections();
33590b57cec5SDimitry Andric     for (DWARFAddressRange &r : *ranges) {
33600b57cec5SDimitry Andric       if (r.SectionIndex == -1ULL)
33610b57cec5SDimitry Andric         continue;
33620b57cec5SDimitry Andric       // Range list with zero size has no effect.
33635ffd83dbSDimitry Andric       InputSectionBase *s = sections[r.SectionIndex];
33645ffd83dbSDimitry Andric       if (s && s != &InputSection::discarded && s->isLive())
33655ffd83dbSDimitry Andric         if (r.LowPC != r.HighPC)
33665ffd83dbSDimitry Andric           ret.push_back({cast<InputSection>(s), r.LowPC, r.HighPC, cuIdx});
33670b57cec5SDimitry Andric     }
33680b57cec5SDimitry Andric     ++cuIdx;
33690b57cec5SDimitry Andric   }
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric   return ret;
33720b57cec5SDimitry Andric }
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric template <class ELFT>
33751fd87a68SDimitry Andric static SmallVector<GdbIndexSection::NameAttrEntry, 0>
readPubNamesAndTypes(const LLDDwarfObj<ELFT> & obj,const SmallVectorImpl<GdbIndexSection::CuEntry> & cus)33760b57cec5SDimitry Andric readPubNamesAndTypes(const LLDDwarfObj<ELFT> &obj,
33770eae32dcSDimitry Andric                      const SmallVectorImpl<GdbIndexSection::CuEntry> &cus) {
33785ffd83dbSDimitry Andric   const LLDDWARFSection &pubNames = obj.getGnuPubnamesSection();
33795ffd83dbSDimitry Andric   const LLDDWARFSection &pubTypes = obj.getGnuPubtypesSection();
33800b57cec5SDimitry Andric 
33811fd87a68SDimitry Andric   SmallVector<GdbIndexSection::NameAttrEntry, 0> ret;
33825ffd83dbSDimitry Andric   for (const LLDDWARFSection *pub : {&pubNames, &pubTypes}) {
33830fca6ea1SDimitry Andric     DWARFDataExtractor data(obj, *pub, ELFT::Endianness == endianness::little,
33840fca6ea1SDimitry Andric                             ELFT::Is64Bits ? 8 : 4);
33855ffd83dbSDimitry Andric     DWARFDebugPubTable table;
33865ffd83dbSDimitry Andric     table.extract(data, /*GnuStyle=*/true, [&](Error e) {
33875ffd83dbSDimitry Andric       warn(toString(pub->sec) + ": " + toString(std::move(e)));
33885ffd83dbSDimitry Andric     });
33890b57cec5SDimitry Andric     for (const DWARFDebugPubTable::Set &set : table.getData()) {
33900b57cec5SDimitry Andric       // The value written into the constant pool is kind << 24 | cuIndex. As we
33910b57cec5SDimitry Andric       // don't know how many compilation units precede this object to compute
33920b57cec5SDimitry Andric       // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
33930b57cec5SDimitry Andric       // the number of preceding compilation units later.
339485868e8aSDimitry Andric       uint32_t i = llvm::partition_point(cus,
339585868e8aSDimitry Andric                                          [&](GdbIndexSection::CuEntry cu) {
339685868e8aSDimitry Andric                                            return cu.cuOffset < set.Offset;
33970b57cec5SDimitry Andric                                          }) -
339885868e8aSDimitry Andric                    cus.begin();
33990b57cec5SDimitry Andric       for (const DWARFDebugPubTable::Entry &ent : set.Entries)
34000b57cec5SDimitry Andric         ret.push_back({{ent.Name, computeGdbHash(ent.Name)},
34010b57cec5SDimitry Andric                        (ent.Descriptor.toBits() << 24) | i});
34020b57cec5SDimitry Andric     }
34030b57cec5SDimitry Andric   }
34040b57cec5SDimitry Andric   return ret;
34050b57cec5SDimitry Andric }
34060b57cec5SDimitry Andric 
34070b57cec5SDimitry Andric // Create a list of symbols from a given list of symbol names and types
34080b57cec5SDimitry Andric // by uniquifying them by name.
3409bdd1243dSDimitry Andric static std::pair<SmallVector<GdbIndexSection::GdbSymbol, 0>, size_t>
createSymbols(ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry,0>> nameAttrs,const SmallVector<GdbIndexSection::GdbChunk,0> & chunks)3410bdd1243dSDimitry Andric createSymbols(
34111fd87a68SDimitry Andric     ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry, 0>> nameAttrs,
34121fd87a68SDimitry Andric     const SmallVector<GdbIndexSection::GdbChunk, 0> &chunks) {
34130b57cec5SDimitry Andric   using GdbSymbol = GdbIndexSection::GdbSymbol;
34140b57cec5SDimitry Andric   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric   // For each chunk, compute the number of compilation units preceding it.
34170b57cec5SDimitry Andric   uint32_t cuIdx = 0;
341804eeddc0SDimitry Andric   std::unique_ptr<uint32_t[]> cuIdxs(new uint32_t[chunks.size()]);
34190b57cec5SDimitry Andric   for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
34200b57cec5SDimitry Andric     cuIdxs[i] = cuIdx;
34210b57cec5SDimitry Andric     cuIdx += chunks[i].compilationUnits.size();
34220b57cec5SDimitry Andric   }
34230b57cec5SDimitry Andric 
34240fca6ea1SDimitry Andric   // Collect the compilation unitss for each unique name. Speed it up using
34250fca6ea1SDimitry Andric   // multi-threading as the number of symbols can be in the order of millions.
34260fca6ea1SDimitry Andric   // Shard GdbSymbols by hash's high bits.
34275ffd83dbSDimitry Andric   constexpr size_t numShards = 32;
3428bdd1243dSDimitry Andric   const size_t concurrency =
342906c3fb27SDimitry Andric       llvm::bit_floor(std::min<size_t>(config->threadCount, numShards));
34300fca6ea1SDimitry Andric   const size_t shift = 32 - llvm::countr_zero(numShards);
343104eeddc0SDimitry Andric   auto map =
343204eeddc0SDimitry Andric       std::make_unique<DenseMap<CachedHashStringRef, size_t>[]>(numShards);
34331fd87a68SDimitry Andric   auto symbols = std::make_unique<SmallVector<GdbSymbol, 0>[]>(numShards);
343481ad6265SDimitry Andric   parallelFor(0, concurrency, [&](size_t threadId) {
34350b57cec5SDimitry Andric     uint32_t i = 0;
34360b57cec5SDimitry Andric     for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
34370b57cec5SDimitry Andric       for (const NameAttrEntry &ent : entries) {
34380b57cec5SDimitry Andric         size_t shardId = ent.name.hash() >> shift;
34390b57cec5SDimitry Andric         if ((shardId & (concurrency - 1)) != threadId)
34400b57cec5SDimitry Andric           continue;
34410b57cec5SDimitry Andric 
34420b57cec5SDimitry Andric         uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
34430fca6ea1SDimitry Andric         auto [it, inserted] =
34440fca6ea1SDimitry Andric             map[shardId].try_emplace(ent.name, symbols[shardId].size());
34450fca6ea1SDimitry Andric         if (inserted)
34460b57cec5SDimitry Andric           symbols[shardId].push_back({ent.name, {v}, 0, 0});
34470fca6ea1SDimitry Andric         else
34480fca6ea1SDimitry Andric           symbols[shardId][it->second].cuVector.push_back(v);
34490b57cec5SDimitry Andric       }
34500b57cec5SDimitry Andric       ++i;
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric   });
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric   size_t numSymbols = 0;
3455bdd1243dSDimitry Andric   for (ArrayRef<GdbSymbol> v : ArrayRef(symbols.get(), numShards))
34560b57cec5SDimitry Andric     numSymbols += v.size();
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric   // The return type is a flattened vector, so we'll copy each vector
34590b57cec5SDimitry Andric   // contents to Ret.
34601fd87a68SDimitry Andric   SmallVector<GdbSymbol, 0> ret;
34610b57cec5SDimitry Andric   ret.reserve(numSymbols);
34621fd87a68SDimitry Andric   for (SmallVector<GdbSymbol, 0> &vec :
3463bdd1243dSDimitry Andric        MutableArrayRef(symbols.get(), numShards))
34640b57cec5SDimitry Andric     for (GdbSymbol &sym : vec)
34650b57cec5SDimitry Andric       ret.push_back(std::move(sym));
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric   // CU vectors and symbol names are adjacent in the output file.
34680b57cec5SDimitry Andric   // We can compute their offsets in the output file now.
34690b57cec5SDimitry Andric   size_t off = 0;
34700b57cec5SDimitry Andric   for (GdbSymbol &sym : ret) {
34710b57cec5SDimitry Andric     sym.cuVectorOff = off;
34720b57cec5SDimitry Andric     off += (sym.cuVector.size() + 1) * 4;
34730b57cec5SDimitry Andric   }
34740b57cec5SDimitry Andric   for (GdbSymbol &sym : ret) {
34750b57cec5SDimitry Andric     sym.nameOff = off;
34760b57cec5SDimitry Andric     off += sym.name.size() + 1;
34770b57cec5SDimitry Andric   }
3478bdd1243dSDimitry Andric   // If off overflows, the last symbol's nameOff likely overflows.
3479bdd1243dSDimitry Andric   if (!isUInt<32>(off))
3480bdd1243dSDimitry Andric     errorOrWarn("--gdb-index: constant pool size (" + Twine(off) +
3481bdd1243dSDimitry Andric                 ") exceeds UINT32_MAX");
34820b57cec5SDimitry Andric 
3483bdd1243dSDimitry Andric   return {ret, off};
34840b57cec5SDimitry Andric }
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric // Returns a newly-created .gdb_index section.
34870fca6ea1SDimitry Andric template <class ELFT>
create()34880fca6ea1SDimitry Andric std::unique_ptr<GdbIndexSection> GdbIndexSection::create() {
3489bdd1243dSDimitry Andric   llvm::TimeTraceScope timeScope("Create gdb index");
3490bdd1243dSDimitry Andric 
349116d6b3b3SDimitry Andric   // Collect InputFiles with .debug_info. See the comment in
349216d6b3b3SDimitry Andric   // LLDDwarfObj<ELFT>::LLDDwarfObj. If we do lightweight parsing in the future,
349316d6b3b3SDimitry Andric   // note that isec->data() may uncompress the full content, which should be
349416d6b3b3SDimitry Andric   // parallelized.
349516d6b3b3SDimitry Andric   SetVector<InputFile *> files;
3496bdd1243dSDimitry Andric   for (InputSectionBase *s : ctx.inputSections) {
349716d6b3b3SDimitry Andric     InputSection *isec = dyn_cast<InputSection>(s);
349816d6b3b3SDimitry Andric     if (!isec)
349916d6b3b3SDimitry Andric       continue;
35000b57cec5SDimitry Andric     // .debug_gnu_pub{names,types} are useless in executables.
35010b57cec5SDimitry Andric     // They are present in input object files solely for creating
35020b57cec5SDimitry Andric     // a .gdb_index. So we can remove them from the output.
35030b57cec5SDimitry Andric     if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
35040b57cec5SDimitry Andric       s->markDead();
350516d6b3b3SDimitry Andric     else if (isec->name == ".debug_info")
350616d6b3b3SDimitry Andric       files.insert(isec->file);
350716d6b3b3SDimitry Andric   }
3508e8d8bef9SDimitry Andric   // Drop .rel[a].debug_gnu_pub{names,types} for --emit-relocs.
3509bdd1243dSDimitry Andric   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3510e8d8bef9SDimitry Andric     if (auto *isec = dyn_cast<InputSection>(s))
3511e8d8bef9SDimitry Andric       if (InputSectionBase *rel = isec->getRelocatedSection())
3512e8d8bef9SDimitry Andric         return !rel->isLive();
3513e8d8bef9SDimitry Andric     return !s->isLive();
3514e8d8bef9SDimitry Andric   });
35150b57cec5SDimitry Andric 
35161fd87a68SDimitry Andric   SmallVector<GdbChunk, 0> chunks(files.size());
35171fd87a68SDimitry Andric   SmallVector<SmallVector<NameAttrEntry, 0>, 0> nameAttrs(files.size());
35180b57cec5SDimitry Andric 
351981ad6265SDimitry Andric   parallelFor(0, files.size(), [&](size_t i) {
35205ffd83dbSDimitry Andric     // To keep memory usage low, we don't want to keep cached DWARFContext, so
35215ffd83dbSDimitry Andric     // avoid getDwarf() here.
352216d6b3b3SDimitry Andric     ObjFile<ELFT> *file = cast<ObjFile<ELFT>>(files[i]);
352385868e8aSDimitry Andric     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
352416d6b3b3SDimitry Andric     auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
35250b57cec5SDimitry Andric 
352616d6b3b3SDimitry Andric     // If the are multiple compile units .debug_info (very rare ld -r --unique),
352716d6b3b3SDimitry Andric     // this only picks the last one. Other address ranges are lost.
352816d6b3b3SDimitry Andric     chunks[i].sec = dobj.getInfoSection();
35290b57cec5SDimitry Andric     chunks[i].compilationUnits = readCuList(dwarf);
353016d6b3b3SDimitry Andric     chunks[i].addressAreas = readAddressAreas(dwarf, chunks[i].sec);
353116d6b3b3SDimitry Andric     nameAttrs[i] = readPubNamesAndTypes<ELFT>(dobj, chunks[i].compilationUnits);
35320b57cec5SDimitry Andric   });
35330b57cec5SDimitry Andric 
35340fca6ea1SDimitry Andric   auto ret = std::make_unique<GdbIndexSection>();
35350b57cec5SDimitry Andric   ret->chunks = std::move(chunks);
3536bdd1243dSDimitry Andric   std::tie(ret->symbols, ret->size) = createSymbols(nameAttrs, ret->chunks);
3537bdd1243dSDimitry Andric 
3538bdd1243dSDimitry Andric   // Count the areas other than the constant pool.
3539bdd1243dSDimitry Andric   ret->size += sizeof(GdbIndexHeader) + ret->computeSymtabSize() * 8;
3540bdd1243dSDimitry Andric   for (GdbChunk &chunk : ret->chunks)
3541bdd1243dSDimitry Andric     ret->size +=
3542bdd1243dSDimitry Andric         chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
3543bdd1243dSDimitry Andric 
35440b57cec5SDimitry Andric   return ret;
35450b57cec5SDimitry Andric }
35460b57cec5SDimitry Andric 
writeTo(uint8_t * buf)35470b57cec5SDimitry Andric void GdbIndexSection::writeTo(uint8_t *buf) {
35480b57cec5SDimitry Andric   // Write the header.
35490b57cec5SDimitry Andric   auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
35500b57cec5SDimitry Andric   uint8_t *start = buf;
35510b57cec5SDimitry Andric   hdr->version = 7;
35520b57cec5SDimitry Andric   buf += sizeof(*hdr);
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric   // Write the CU list.
35550b57cec5SDimitry Andric   hdr->cuListOff = buf - start;
35560b57cec5SDimitry Andric   for (GdbChunk &chunk : chunks) {
35570b57cec5SDimitry Andric     for (CuEntry &cu : chunk.compilationUnits) {
35580b57cec5SDimitry Andric       write64le(buf, chunk.sec->outSecOff + cu.cuOffset);
35590b57cec5SDimitry Andric       write64le(buf + 8, cu.cuLength);
35600b57cec5SDimitry Andric       buf += 16;
35610b57cec5SDimitry Andric     }
35620b57cec5SDimitry Andric   }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric   // Write the address area.
35650b57cec5SDimitry Andric   hdr->cuTypesOff = buf - start;
35660b57cec5SDimitry Andric   hdr->addressAreaOff = buf - start;
35670b57cec5SDimitry Andric   uint32_t cuOff = 0;
35680b57cec5SDimitry Andric   for (GdbChunk &chunk : chunks) {
35690b57cec5SDimitry Andric     for (AddressEntry &e : chunk.addressAreas) {
3570e8d8bef9SDimitry Andric       // In the case of ICF there may be duplicate address range entries.
3571e8d8bef9SDimitry Andric       const uint64_t baseAddr = e.section->repl->getVA(0);
35720b57cec5SDimitry Andric       write64le(buf, baseAddr + e.lowAddress);
35730b57cec5SDimitry Andric       write64le(buf + 8, baseAddr + e.highAddress);
35740b57cec5SDimitry Andric       write32le(buf + 16, e.cuIndex + cuOff);
35750b57cec5SDimitry Andric       buf += 20;
35760b57cec5SDimitry Andric     }
35770b57cec5SDimitry Andric     cuOff += chunk.compilationUnits.size();
35780b57cec5SDimitry Andric   }
35790b57cec5SDimitry Andric 
35800b57cec5SDimitry Andric   // Write the on-disk open-addressing hash table containing symbols.
35810b57cec5SDimitry Andric   hdr->symtabOff = buf - start;
35820b57cec5SDimitry Andric   size_t symtabSize = computeSymtabSize();
35830b57cec5SDimitry Andric   uint32_t mask = symtabSize - 1;
35840b57cec5SDimitry Andric 
35850b57cec5SDimitry Andric   for (GdbSymbol &sym : symbols) {
35860b57cec5SDimitry Andric     uint32_t h = sym.name.hash();
35870b57cec5SDimitry Andric     uint32_t i = h & mask;
35880b57cec5SDimitry Andric     uint32_t step = ((h * 17) & mask) | 1;
35890b57cec5SDimitry Andric 
35900b57cec5SDimitry Andric     while (read32le(buf + i * 8))
35910b57cec5SDimitry Andric       i = (i + step) & mask;
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric     write32le(buf + i * 8, sym.nameOff);
35940b57cec5SDimitry Andric     write32le(buf + i * 8 + 4, sym.cuVectorOff);
35950b57cec5SDimitry Andric   }
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric   buf += symtabSize * 8;
35980b57cec5SDimitry Andric 
35990b57cec5SDimitry Andric   // Write the string pool.
36000b57cec5SDimitry Andric   hdr->constantPoolOff = buf - start;
36010b57cec5SDimitry Andric   parallelForEach(symbols, [&](GdbSymbol &sym) {
36020b57cec5SDimitry Andric     memcpy(buf + sym.nameOff, sym.name.data(), sym.name.size());
36030b57cec5SDimitry Andric   });
36040b57cec5SDimitry Andric 
36050b57cec5SDimitry Andric   // Write the CU vectors.
36060b57cec5SDimitry Andric   for (GdbSymbol &sym : symbols) {
36070b57cec5SDimitry Andric     write32le(buf, sym.cuVector.size());
36080b57cec5SDimitry Andric     buf += 4;
36090b57cec5SDimitry Andric     for (uint32_t val : sym.cuVector) {
36100b57cec5SDimitry Andric       write32le(buf, val);
36110b57cec5SDimitry Andric       buf += 4;
36120b57cec5SDimitry Andric     }
36130b57cec5SDimitry Andric   }
36140b57cec5SDimitry Andric }
36150b57cec5SDimitry Andric 
isNeeded() const36160b57cec5SDimitry Andric bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
36170b57cec5SDimitry Andric 
EhFrameHeader()36180b57cec5SDimitry Andric EhFrameHeader::EhFrameHeader()
36190b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
36200b57cec5SDimitry Andric 
writeTo(uint8_t * buf)36210b57cec5SDimitry Andric void EhFrameHeader::writeTo(uint8_t *buf) {
36220b57cec5SDimitry Andric   // Unlike most sections, the EhFrameHeader section is written while writing
36230b57cec5SDimitry Andric   // another section, namely EhFrameSection, which calls the write() function
36240b57cec5SDimitry Andric   // below from its writeTo() function. This is necessary because the contents
36250b57cec5SDimitry Andric   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
36260b57cec5SDimitry Andric   // don't know which order the sections will be written in.
36270b57cec5SDimitry Andric }
36280b57cec5SDimitry Andric 
36290b57cec5SDimitry Andric // .eh_frame_hdr contains a binary search table of pointers to FDEs.
36300b57cec5SDimitry Andric // Each entry of the search table consists of two values,
36310b57cec5SDimitry Andric // the starting PC from where FDEs covers, and the FDE's address.
36320b57cec5SDimitry Andric // It is sorted by PC.
write()36330b57cec5SDimitry Andric void EhFrameHeader::write() {
36340b57cec5SDimitry Andric   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
36350b57cec5SDimitry Andric   using FdeData = EhFrameSection::FdeData;
363604eeddc0SDimitry Andric   SmallVector<FdeData, 0> fdes = getPartition().ehFrame->getFdeData();
36370b57cec5SDimitry Andric 
36380b57cec5SDimitry Andric   buf[0] = 1;
36390b57cec5SDimitry Andric   buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
36400b57cec5SDimitry Andric   buf[2] = DW_EH_PE_udata4;
36410b57cec5SDimitry Andric   buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
36420b57cec5SDimitry Andric   write32(buf + 4,
36430b57cec5SDimitry Andric           getPartition().ehFrame->getParent()->addr - this->getVA() - 4);
36440b57cec5SDimitry Andric   write32(buf + 8, fdes.size());
36450b57cec5SDimitry Andric   buf += 12;
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric   for (FdeData &fde : fdes) {
36480b57cec5SDimitry Andric     write32(buf, fde.pcRel);
36490b57cec5SDimitry Andric     write32(buf + 4, fde.fdeVARel);
36500b57cec5SDimitry Andric     buf += 8;
36510b57cec5SDimitry Andric   }
36520b57cec5SDimitry Andric }
36530b57cec5SDimitry Andric 
getSize() const36540b57cec5SDimitry Andric size_t EhFrameHeader::getSize() const {
36550b57cec5SDimitry Andric   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
36560b57cec5SDimitry Andric   return 12 + getPartition().ehFrame->numFdes * 8;
36570b57cec5SDimitry Andric }
36580b57cec5SDimitry Andric 
isNeeded() const36590b57cec5SDimitry Andric bool EhFrameHeader::isNeeded() const {
36600b57cec5SDimitry Andric   return isLive() && getPartition().ehFrame->isNeeded();
36610b57cec5SDimitry Andric }
36620b57cec5SDimitry Andric 
VersionDefinitionSection()36630b57cec5SDimitry Andric VersionDefinitionSection::VersionDefinitionSection()
36640b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
36650b57cec5SDimitry Andric                        ".gnu.version_d") {}
36660b57cec5SDimitry Andric 
getFileDefName()36670b57cec5SDimitry Andric StringRef VersionDefinitionSection::getFileDefName() {
36680b57cec5SDimitry Andric   if (!getPartition().name.empty())
36690b57cec5SDimitry Andric     return getPartition().name;
36700b57cec5SDimitry Andric   if (!config->soName.empty())
36710b57cec5SDimitry Andric     return config->soName;
36720b57cec5SDimitry Andric   return config->outputFile;
36730b57cec5SDimitry Andric }
36740b57cec5SDimitry Andric 
finalizeContents()36750b57cec5SDimitry Andric void VersionDefinitionSection::finalizeContents() {
36760b57cec5SDimitry Andric   fileDefNameOff = getPartition().dynStrTab->addString(getFileDefName());
367785868e8aSDimitry Andric   for (const VersionDefinition &v : namedVersionDefs())
36780b57cec5SDimitry Andric     verDefNameOffs.push_back(getPartition().dynStrTab->addString(v.name));
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric   if (OutputSection *sec = getPartition().dynStrTab->getParent())
36810b57cec5SDimitry Andric     getParent()->link = sec->sectionIndex;
36820b57cec5SDimitry Andric 
36830b57cec5SDimitry Andric   // sh_info should be set to the number of definitions. This fact is missed in
36840b57cec5SDimitry Andric   // documentation, but confirmed by binutils community:
36850b57cec5SDimitry Andric   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
36860b57cec5SDimitry Andric   getParent()->info = getVerDefNum();
36870b57cec5SDimitry Andric }
36880b57cec5SDimitry Andric 
writeOne(uint8_t * buf,uint32_t index,StringRef name,size_t nameOff)36890b57cec5SDimitry Andric void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
36900b57cec5SDimitry Andric                                         StringRef name, size_t nameOff) {
36910b57cec5SDimitry Andric   uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric   // Write a verdef.
36940b57cec5SDimitry Andric   write16(buf, 1);                  // vd_version
36950b57cec5SDimitry Andric   write16(buf + 2, flags);          // vd_flags
36960b57cec5SDimitry Andric   write16(buf + 4, index);          // vd_ndx
36970b57cec5SDimitry Andric   write16(buf + 6, 1);              // vd_cnt
36980b57cec5SDimitry Andric   write32(buf + 8, hashSysV(name)); // vd_hash
36990b57cec5SDimitry Andric   write32(buf + 12, 20);            // vd_aux
37000b57cec5SDimitry Andric   write32(buf + 16, 28);            // vd_next
37010b57cec5SDimitry Andric 
37020b57cec5SDimitry Andric   // Write a veraux.
37030b57cec5SDimitry Andric   write32(buf + 20, nameOff); // vda_name
37040b57cec5SDimitry Andric   write32(buf + 24, 0);       // vda_next
37050b57cec5SDimitry Andric }
37060b57cec5SDimitry Andric 
writeTo(uint8_t * buf)37070b57cec5SDimitry Andric void VersionDefinitionSection::writeTo(uint8_t *buf) {
37080b57cec5SDimitry Andric   writeOne(buf, 1, getFileDefName(), fileDefNameOff);
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric   auto nameOffIt = verDefNameOffs.begin();
371185868e8aSDimitry Andric   for (const VersionDefinition &v : namedVersionDefs()) {
37120b57cec5SDimitry Andric     buf += EntrySize;
37130b57cec5SDimitry Andric     writeOne(buf, v.id, v.name, *nameOffIt++);
37140b57cec5SDimitry Andric   }
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric   // Need to terminate the last version definition.
37170b57cec5SDimitry Andric   write32(buf + 16, 0); // vd_next
37180b57cec5SDimitry Andric }
37190b57cec5SDimitry Andric 
getSize() const37200b57cec5SDimitry Andric size_t VersionDefinitionSection::getSize() const {
37210b57cec5SDimitry Andric   return EntrySize * getVerDefNum();
37220b57cec5SDimitry Andric }
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric // .gnu.version is a table where each entry is 2 byte long.
VersionTableSection()37250b57cec5SDimitry Andric VersionTableSection::VersionTableSection()
37260b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
37270b57cec5SDimitry Andric                        ".gnu.version") {
37280b57cec5SDimitry Andric   this->entsize = 2;
37290b57cec5SDimitry Andric }
37300b57cec5SDimitry Andric 
finalizeContents()37310b57cec5SDimitry Andric void VersionTableSection::finalizeContents() {
37320b57cec5SDimitry Andric   // At the moment of june 2016 GNU docs does not mention that sh_link field
37330b57cec5SDimitry Andric   // should be set, but Sun docs do. Also readelf relies on this field.
37340b57cec5SDimitry Andric   getParent()->link = getPartition().dynSymTab->getParent()->sectionIndex;
37350b57cec5SDimitry Andric }
37360b57cec5SDimitry Andric 
getSize() const37370b57cec5SDimitry Andric size_t VersionTableSection::getSize() const {
37380b57cec5SDimitry Andric   return (getPartition().dynSymTab->getSymbols().size() + 1) * 2;
37390b57cec5SDimitry Andric }
37400b57cec5SDimitry Andric 
writeTo(uint8_t * buf)37410b57cec5SDimitry Andric void VersionTableSection::writeTo(uint8_t *buf) {
37420b57cec5SDimitry Andric   buf += 2;
37430b57cec5SDimitry Andric   for (const SymbolTableEntry &s : getPartition().dynSymTab->getSymbols()) {
37444824e7fdSDimitry Andric     // For an unextracted lazy symbol (undefined weak), it must have been
3745349cc55cSDimitry Andric     // converted to Undefined and have VER_NDX_GLOBAL version here.
3746349cc55cSDimitry Andric     assert(!s.sym->isLazy());
3747349cc55cSDimitry Andric     write16(buf, s.sym->versionId);
37480b57cec5SDimitry Andric     buf += 2;
37490b57cec5SDimitry Andric   }
37500b57cec5SDimitry Andric }
37510b57cec5SDimitry Andric 
isNeeded() const37520b57cec5SDimitry Andric bool VersionTableSection::isNeeded() const {
3753480093f4SDimitry Andric   return isLive() &&
3754480093f4SDimitry Andric          (getPartition().verDef || getPartition().verNeed->isNeeded());
37550b57cec5SDimitry Andric }
37560b57cec5SDimitry Andric 
addVerneed(Symbol * ss)37575ffd83dbSDimitry Andric void elf::addVerneed(Symbol *ss) {
37580b57cec5SDimitry Andric   auto &file = cast<SharedFile>(*ss->file);
37595f757f3fSDimitry Andric   if (ss->versionId == VER_NDX_GLOBAL)
37600b57cec5SDimitry Andric     return;
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   if (file.vernauxs.empty())
37630b57cec5SDimitry Andric     file.vernauxs.resize(file.verdefs.size());
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   // Select a version identifier for the vernaux data structure, if we haven't
37660b57cec5SDimitry Andric   // already allocated one. The verdef identifiers cover the range
37670b57cec5SDimitry Andric   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
37680b57cec5SDimitry Andric   // getVerDefNum()+1.
37695f757f3fSDimitry Andric   if (file.vernauxs[ss->versionId] == 0)
37705f757f3fSDimitry Andric     file.vernauxs[ss->versionId] = ++SharedFile::vernauxNum + getVerDefNum();
37710b57cec5SDimitry Andric 
37725f757f3fSDimitry Andric   ss->versionId = file.vernauxs[ss->versionId];
37730b57cec5SDimitry Andric }
37740b57cec5SDimitry Andric 
37750b57cec5SDimitry Andric template <class ELFT>
VersionNeedSection()37760b57cec5SDimitry Andric VersionNeedSection<ELFT>::VersionNeedSection()
37770b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
37780b57cec5SDimitry Andric                        ".gnu.version_r") {}
37790b57cec5SDimitry Andric 
finalizeContents()37800b57cec5SDimitry Andric template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
3781bdd1243dSDimitry Andric   for (SharedFile *f : ctx.sharedFiles) {
37820b57cec5SDimitry Andric     if (f->vernauxs.empty())
37830b57cec5SDimitry Andric       continue;
37840b57cec5SDimitry Andric     verneeds.emplace_back();
37850b57cec5SDimitry Andric     Verneed &vn = verneeds.back();
37860b57cec5SDimitry Andric     vn.nameStrTab = getPartition().dynStrTab->addString(f->soName);
378706c3fb27SDimitry Andric     bool isLibc = config->relrGlibc && f->soName.starts_with("libc.so.");
378881ad6265SDimitry Andric     bool isGlibc2 = false;
37890b57cec5SDimitry Andric     for (unsigned i = 0; i != f->vernauxs.size(); ++i) {
37900b57cec5SDimitry Andric       if (f->vernauxs[i] == 0)
37910b57cec5SDimitry Andric         continue;
37920b57cec5SDimitry Andric       auto *verdef =
37930b57cec5SDimitry Andric           reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
379481ad6265SDimitry Andric       StringRef ver(f->getStringTable().data() + verdef->getAux()->vda_name);
379506c3fb27SDimitry Andric       if (isLibc && ver.starts_with("GLIBC_2."))
379681ad6265SDimitry Andric         isGlibc2 = true;
379781ad6265SDimitry Andric       vn.vernauxs.push_back({verdef->vd_hash, f->vernauxs[i],
379881ad6265SDimitry Andric                              getPartition().dynStrTab->addString(ver)});
379981ad6265SDimitry Andric     }
380081ad6265SDimitry Andric     if (isGlibc2) {
380181ad6265SDimitry Andric       const char *ver = "GLIBC_ABI_DT_RELR";
380281ad6265SDimitry Andric       vn.vernauxs.push_back({hashSysV(ver),
380381ad6265SDimitry Andric                              ++SharedFile::vernauxNum + getVerDefNum(),
380481ad6265SDimitry Andric                              getPartition().dynStrTab->addString(ver)});
38050b57cec5SDimitry Andric     }
38060b57cec5SDimitry Andric   }
38070b57cec5SDimitry Andric 
38080b57cec5SDimitry Andric   if (OutputSection *sec = getPartition().dynStrTab->getParent())
38090b57cec5SDimitry Andric     getParent()->link = sec->sectionIndex;
38100b57cec5SDimitry Andric   getParent()->info = verneeds.size();
38110b57cec5SDimitry Andric }
38120b57cec5SDimitry Andric 
writeTo(uint8_t * buf)38130b57cec5SDimitry Andric template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
38140b57cec5SDimitry Andric   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
38150b57cec5SDimitry Andric   auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
38160b57cec5SDimitry Andric   auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric   for (auto &vn : verneeds) {
38190b57cec5SDimitry Andric     // Create an Elf_Verneed for this DSO.
38200b57cec5SDimitry Andric     verneed->vn_version = 1;
38210b57cec5SDimitry Andric     verneed->vn_cnt = vn.vernauxs.size();
38220b57cec5SDimitry Andric     verneed->vn_file = vn.nameStrTab;
38230b57cec5SDimitry Andric     verneed->vn_aux =
38240b57cec5SDimitry Andric         reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
38250b57cec5SDimitry Andric     verneed->vn_next = sizeof(Elf_Verneed);
38260b57cec5SDimitry Andric     ++verneed;
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric     // Create the Elf_Vernauxs for this Elf_Verneed.
38290b57cec5SDimitry Andric     for (auto &vna : vn.vernauxs) {
38300b57cec5SDimitry Andric       vernaux->vna_hash = vna.hash;
38310b57cec5SDimitry Andric       vernaux->vna_flags = 0;
38320b57cec5SDimitry Andric       vernaux->vna_other = vna.verneedIndex;
38330b57cec5SDimitry Andric       vernaux->vna_name = vna.nameStrTab;
38340b57cec5SDimitry Andric       vernaux->vna_next = sizeof(Elf_Vernaux);
38350b57cec5SDimitry Andric       ++vernaux;
38360b57cec5SDimitry Andric     }
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric     vernaux[-1].vna_next = 0;
38390b57cec5SDimitry Andric   }
38400b57cec5SDimitry Andric   verneed[-1].vn_next = 0;
38410b57cec5SDimitry Andric }
38420b57cec5SDimitry Andric 
getSize() const38430b57cec5SDimitry Andric template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
38440b57cec5SDimitry Andric   return verneeds.size() * sizeof(Elf_Verneed) +
38450b57cec5SDimitry Andric          SharedFile::vernauxNum * sizeof(Elf_Vernaux);
38460b57cec5SDimitry Andric }
38470b57cec5SDimitry Andric 
isNeeded() const38480b57cec5SDimitry Andric template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
3849480093f4SDimitry Andric   return isLive() && SharedFile::vernauxNum != 0;
38500b57cec5SDimitry Andric }
38510b57cec5SDimitry Andric 
addSection(MergeInputSection * ms)38520b57cec5SDimitry Andric void MergeSyntheticSection::addSection(MergeInputSection *ms) {
38530b57cec5SDimitry Andric   ms->parent = this;
38540b57cec5SDimitry Andric   sections.push_back(ms);
3855bdd1243dSDimitry Andric   assert(addralign == ms->addralign || !(ms->flags & SHF_STRINGS));
3856bdd1243dSDimitry Andric   addralign = std::max(addralign, ms->addralign);
38570b57cec5SDimitry Andric }
38580b57cec5SDimitry Andric 
MergeTailSection(StringRef name,uint32_t type,uint64_t flags,uint32_t alignment)38590b57cec5SDimitry Andric MergeTailSection::MergeTailSection(StringRef name, uint32_t type,
38600b57cec5SDimitry Andric                                    uint64_t flags, uint32_t alignment)
38610b57cec5SDimitry Andric     : MergeSyntheticSection(name, type, flags, alignment),
3862bdd1243dSDimitry Andric       builder(StringTableBuilder::RAW, llvm::Align(alignment)) {}
38630b57cec5SDimitry Andric 
getSize() const38640b57cec5SDimitry Andric size_t MergeTailSection::getSize() const { return builder.getSize(); }
38650b57cec5SDimitry Andric 
writeTo(uint8_t * buf)38660b57cec5SDimitry Andric void MergeTailSection::writeTo(uint8_t *buf) { builder.write(buf); }
38670b57cec5SDimitry Andric 
finalizeContents()38680b57cec5SDimitry Andric void MergeTailSection::finalizeContents() {
38690b57cec5SDimitry Andric   // Add all string pieces to the string table builder to create section
38700b57cec5SDimitry Andric   // contents.
38710b57cec5SDimitry Andric   for (MergeInputSection *sec : sections)
38720b57cec5SDimitry Andric     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
38730b57cec5SDimitry Andric       if (sec->pieces[i].live)
38740b57cec5SDimitry Andric         builder.add(sec->getData(i));
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric   // Fix the string table content. After this, the contents will never change.
38770b57cec5SDimitry Andric   builder.finalize();
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric   // finalize() fixed tail-optimized strings, so we can now get
38800b57cec5SDimitry Andric   // offsets of strings. Get an offset for each string and save it
38810b57cec5SDimitry Andric   // to a corresponding SectionPiece for easy access.
38820b57cec5SDimitry Andric   for (MergeInputSection *sec : sections)
38830b57cec5SDimitry Andric     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
38840b57cec5SDimitry Andric       if (sec->pieces[i].live)
38850b57cec5SDimitry Andric         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
38860b57cec5SDimitry Andric }
38870b57cec5SDimitry Andric 
writeTo(uint8_t * buf)38880b57cec5SDimitry Andric void MergeNoTailSection::writeTo(uint8_t *buf) {
388981ad6265SDimitry Andric   parallelFor(0, numShards,
38900eae32dcSDimitry Andric               [&](size_t i) { shards[i].write(buf + shardOffsets[i]); });
38910b57cec5SDimitry Andric }
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric // This function is very hot (i.e. it can take several seconds to finish)
38940b57cec5SDimitry Andric // because sometimes the number of inputs is in an order of magnitude of
38950b57cec5SDimitry Andric // millions. So, we use multi-threading.
38960b57cec5SDimitry Andric //
38970b57cec5SDimitry Andric // For any strings S and T, we know S is not mergeable with T if S's hash
38980b57cec5SDimitry Andric // value is different from T's. If that's the case, we can safely put S and
38990b57cec5SDimitry Andric // T into different string builders without worrying about merge misses.
39000b57cec5SDimitry Andric // We do it in parallel.
finalizeContents()39010b57cec5SDimitry Andric void MergeNoTailSection::finalizeContents() {
39020b57cec5SDimitry Andric   // Initializes string table builders.
39030b57cec5SDimitry Andric   for (size_t i = 0; i < numShards; ++i)
3904bdd1243dSDimitry Andric     shards.emplace_back(StringTableBuilder::RAW, llvm::Align(addralign));
39050b57cec5SDimitry Andric 
39060b57cec5SDimitry Andric   // Concurrency level. Must be a power of 2 to avoid expensive modulo
39070b57cec5SDimitry Andric   // operations in the following tight loop.
3908bdd1243dSDimitry Andric   const size_t concurrency =
390906c3fb27SDimitry Andric       llvm::bit_floor(std::min<size_t>(config->threadCount, numShards));
39100b57cec5SDimitry Andric 
39110b57cec5SDimitry Andric   // Add section pieces to the builders.
391281ad6265SDimitry Andric   parallelFor(0, concurrency, [&](size_t threadId) {
39130b57cec5SDimitry Andric     for (MergeInputSection *sec : sections) {
39140b57cec5SDimitry Andric       for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
39150b57cec5SDimitry Andric         if (!sec->pieces[i].live)
39160b57cec5SDimitry Andric           continue;
39170b57cec5SDimitry Andric         size_t shardId = getShardId(sec->pieces[i].hash);
39180b57cec5SDimitry Andric         if ((shardId & (concurrency - 1)) == threadId)
39190b57cec5SDimitry Andric           sec->pieces[i].outputOff = shards[shardId].add(sec->getData(i));
39200b57cec5SDimitry Andric       }
39210b57cec5SDimitry Andric     }
39220b57cec5SDimitry Andric   });
39230b57cec5SDimitry Andric 
39240b57cec5SDimitry Andric   // Compute an in-section offset for each shard.
39250b57cec5SDimitry Andric   size_t off = 0;
39260b57cec5SDimitry Andric   for (size_t i = 0; i < numShards; ++i) {
39270b57cec5SDimitry Andric     shards[i].finalizeInOrder();
39280b57cec5SDimitry Andric     if (shards[i].getSize() > 0)
3929bdd1243dSDimitry Andric       off = alignToPowerOf2(off, addralign);
39300b57cec5SDimitry Andric     shardOffsets[i] = off;
39310b57cec5SDimitry Andric     off += shards[i].getSize();
39320b57cec5SDimitry Andric   }
39330b57cec5SDimitry Andric   size = off;
39340b57cec5SDimitry Andric 
39350b57cec5SDimitry Andric   // So far, section pieces have offsets from beginning of shards, but
39360b57cec5SDimitry Andric   // we want offsets from beginning of the whole section. Fix them.
39370b57cec5SDimitry Andric   parallelForEach(sections, [&](MergeInputSection *sec) {
39380b57cec5SDimitry Andric     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
39390b57cec5SDimitry Andric       if (sec->pieces[i].live)
39400b57cec5SDimitry Andric         sec->pieces[i].outputOff +=
39410b57cec5SDimitry Andric             shardOffsets[getShardId(sec->pieces[i].hash)];
39420b57cec5SDimitry Andric   });
39430b57cec5SDimitry Andric }
39440b57cec5SDimitry Andric 
splitSections()39455ffd83dbSDimitry Andric template <class ELFT> void elf::splitSections() {
39465ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("Split sections");
39470b57cec5SDimitry Andric   // splitIntoPieces needs to be called on each MergeInputSection
39480b57cec5SDimitry Andric   // before calling finalizeContents().
3949bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
39501fd87a68SDimitry Andric     for (InputSectionBase *sec : file->getSections()) {
39511fd87a68SDimitry Andric       if (!sec)
39521fd87a68SDimitry Andric         continue;
39530b57cec5SDimitry Andric       if (auto *s = dyn_cast<MergeInputSection>(sec))
39540b57cec5SDimitry Andric         s->splitIntoPieces();
39550b57cec5SDimitry Andric       else if (auto *eh = dyn_cast<EhInputSection>(sec))
39560b57cec5SDimitry Andric         eh->split<ELFT>();
39571fd87a68SDimitry Andric     }
39580b57cec5SDimitry Andric   });
39590b57cec5SDimitry Andric }
39600b57cec5SDimitry Andric 
combineEhSections()3961bdd1243dSDimitry Andric void elf::combineEhSections() {
3962bdd1243dSDimitry Andric   llvm::TimeTraceScope timeScope("Combine EH sections");
3963bdd1243dSDimitry Andric   for (EhInputSection *sec : ctx.ehInputSections) {
3964bdd1243dSDimitry Andric     EhFrameSection &eh = *sec->getPartition().ehFrame;
3965bdd1243dSDimitry Andric     sec->parent = &eh;
3966bdd1243dSDimitry Andric     eh.addralign = std::max(eh.addralign, sec->addralign);
3967bdd1243dSDimitry Andric     eh.sections.push_back(sec);
3968bdd1243dSDimitry Andric     llvm::append_range(eh.dependentSections, sec->dependentSections);
3969bdd1243dSDimitry Andric   }
3970bdd1243dSDimitry Andric 
3971bdd1243dSDimitry Andric   if (!mainPart->armExidx)
3972bdd1243dSDimitry Andric     return;
3973bdd1243dSDimitry Andric   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3974bdd1243dSDimitry Andric     // Ignore dead sections and the partition end marker (.part.end),
3975bdd1243dSDimitry Andric     // whose partition number is out of bounds.
3976bdd1243dSDimitry Andric     if (!s->isLive() || s->partition == 255)
3977bdd1243dSDimitry Andric       return false;
3978bdd1243dSDimitry Andric     Partition &part = s->getPartition();
3979bdd1243dSDimitry Andric     return s->kind() == SectionBase::Regular && part.armExidx &&
3980bdd1243dSDimitry Andric            part.armExidx->addSection(cast<InputSection>(s));
3981bdd1243dSDimitry Andric   });
3982bdd1243dSDimitry Andric }
3983bdd1243dSDimitry Andric 
MipsRldMapSection()39840b57cec5SDimitry Andric MipsRldMapSection::MipsRldMapSection()
39850b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
39860b57cec5SDimitry Andric                        ".rld_map") {}
39870b57cec5SDimitry Andric 
ARMExidxSyntheticSection()39880b57cec5SDimitry Andric ARMExidxSyntheticSection::ARMExidxSyntheticSection()
39890b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
39900b57cec5SDimitry Andric                        config->wordsize, ".ARM.exidx") {}
39910b57cec5SDimitry Andric 
findExidxSection(InputSection * isec)39920b57cec5SDimitry Andric static InputSection *findExidxSection(InputSection *isec) {
39930b57cec5SDimitry Andric   for (InputSection *d : isec->dependentSections)
39945ffd83dbSDimitry Andric     if (d->type == SHT_ARM_EXIDX && d->isLive())
39950b57cec5SDimitry Andric       return d;
39960b57cec5SDimitry Andric   return nullptr;
39970b57cec5SDimitry Andric }
39980b57cec5SDimitry Andric 
isValidExidxSectionDep(InputSection * isec)399985868e8aSDimitry Andric static bool isValidExidxSectionDep(InputSection *isec) {
400085868e8aSDimitry Andric   return (isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
400185868e8aSDimitry Andric          isec->getSize() > 0;
400285868e8aSDimitry Andric }
400385868e8aSDimitry Andric 
addSection(InputSection * isec)40040b57cec5SDimitry Andric bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
40050b57cec5SDimitry Andric   if (isec->type == SHT_ARM_EXIDX) {
400685868e8aSDimitry Andric     if (InputSection *dep = isec->getLinkOrderDep())
40075ffd83dbSDimitry Andric       if (isValidExidxSectionDep(dep)) {
40080b57cec5SDimitry Andric         exidxSections.push_back(isec);
40095ffd83dbSDimitry Andric         // Every exidxSection is 8 bytes, we need an estimate of
40105ffd83dbSDimitry Andric         // size before assignAddresses can be called. Final size
40115ffd83dbSDimitry Andric         // will only be known after finalize is called.
40125ffd83dbSDimitry Andric         size += 8;
40135ffd83dbSDimitry Andric       }
40140b57cec5SDimitry Andric     return true;
40150b57cec5SDimitry Andric   }
40160b57cec5SDimitry Andric 
401785868e8aSDimitry Andric   if (isValidExidxSectionDep(isec)) {
40180b57cec5SDimitry Andric     executableSections.push_back(isec);
40190b57cec5SDimitry Andric     return false;
40200b57cec5SDimitry Andric   }
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric   // FIXME: we do not output a relocation section when --emit-relocs is used
40230b57cec5SDimitry Andric   // as we do not have relocation sections for linker generated table entries
40240b57cec5SDimitry Andric   // and we would have to erase at a late stage relocations from merged entries.
40250b57cec5SDimitry Andric   // Given that exception tables are already position independent and a binary
40260b57cec5SDimitry Andric   // analyzer could derive the relocations we choose to erase the relocations.
40270b57cec5SDimitry Andric   if (config->emitRelocs && isec->type == SHT_REL)
40280b57cec5SDimitry Andric     if (InputSectionBase *ex = isec->getRelocatedSection())
40290b57cec5SDimitry Andric       if (isa<InputSection>(ex) && ex->type == SHT_ARM_EXIDX)
40300b57cec5SDimitry Andric         return true;
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric   return false;
40330b57cec5SDimitry Andric }
40340b57cec5SDimitry Andric 
40350b57cec5SDimitry Andric // References to .ARM.Extab Sections have bit 31 clear and are not the
40360b57cec5SDimitry Andric // special EXIDX_CANTUNWIND bit-pattern.
isExtabRef(uint32_t unwind)40370b57cec5SDimitry Andric static bool isExtabRef(uint32_t unwind) {
40380b57cec5SDimitry Andric   return (unwind & 0x80000000) == 0 && unwind != 0x1;
40390b57cec5SDimitry Andric }
40400b57cec5SDimitry Andric 
40410b57cec5SDimitry Andric // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
40420b57cec5SDimitry Andric // section Prev, where Cur follows Prev in the table. This can be done if the
40430b57cec5SDimitry Andric // unwinding instructions in Cur are identical to Prev. Linker generated
40440b57cec5SDimitry Andric // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
40450b57cec5SDimitry Andric // InputSection.
isDuplicateArmExidxSec(InputSection * prev,InputSection * cur)40460b57cec5SDimitry Andric static bool isDuplicateArmExidxSec(InputSection *prev, InputSection *cur) {
40470b57cec5SDimitry Andric   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
40480b57cec5SDimitry Andric   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
404906c3fb27SDimitry Andric   uint32_t prevUnwind = 1;
40500b57cec5SDimitry Andric   if (prev)
405106c3fb27SDimitry Andric     prevUnwind = read32(prev->content().data() + prev->content().size() - 4);
405206c3fb27SDimitry Andric   if (isExtabRef(prevUnwind))
40530b57cec5SDimitry Andric     return false;
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   // We consider the unwind instructions of an .ARM.exidx table entry
40560b57cec5SDimitry Andric   // a duplicate if the previous unwind instructions if:
40570b57cec5SDimitry Andric   // - Both are the special EXIDX_CANTUNWIND.
40580b57cec5SDimitry Andric   // - Both are the same inline unwind instructions.
40590b57cec5SDimitry Andric   // We do not attempt to follow and check links into .ARM.extab tables as
40600b57cec5SDimitry Andric   // consecutive identical entries are rare and the effort to check that they
40610b57cec5SDimitry Andric   // are identical is high.
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
40640b57cec5SDimitry Andric   if (cur == nullptr)
406506c3fb27SDimitry Andric     return prevUnwind == 1;
40660b57cec5SDimitry Andric 
406706c3fb27SDimitry Andric   for (uint32_t offset = 4; offset < (uint32_t)cur->content().size(); offset +=8) {
406806c3fb27SDimitry Andric     uint32_t curUnwind = read32(cur->content().data() + offset);
406906c3fb27SDimitry Andric     if (isExtabRef(curUnwind) || curUnwind != prevUnwind)
40700b57cec5SDimitry Andric       return false;
407106c3fb27SDimitry Andric   }
40720b57cec5SDimitry Andric   // All table entries in this .ARM.exidx Section can be merged into the
40730b57cec5SDimitry Andric   // previous Section.
40740b57cec5SDimitry Andric   return true;
40750b57cec5SDimitry Andric }
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric // The .ARM.exidx table must be sorted in ascending order of the address of the
4078bdd1243dSDimitry Andric // functions the table describes. std::optionally duplicate adjacent table
4079bdd1243dSDimitry Andric // entries can be removed. At the end of the function the executableSections
4080bdd1243dSDimitry Andric // must be sorted in ascending order of address, Sentinel is set to the
4081bdd1243dSDimitry Andric // InputSection with the highest address and any InputSections that have
4082bdd1243dSDimitry Andric // mergeable .ARM.exidx table entries are removed from it.
finalizeContents()40830b57cec5SDimitry Andric void ARMExidxSyntheticSection::finalizeContents() {
40840fca6ea1SDimitry Andric   // Ensure that any fixed-point iterations after the first see the original set
40850fca6ea1SDimitry Andric   // of sections.
40860fca6ea1SDimitry Andric   if (!originalExecutableSections.empty())
40870fca6ea1SDimitry Andric     executableSections = originalExecutableSections;
40880fca6ea1SDimitry Andric   else if (config->enableNonContiguousRegions)
40890fca6ea1SDimitry Andric     originalExecutableSections = executableSections;
40900fca6ea1SDimitry Andric 
409185868e8aSDimitry Andric   // The executableSections and exidxSections that we use to derive the final
409285868e8aSDimitry Andric   // contents of this SyntheticSection are populated before
409385868e8aSDimitry Andric   // processSectionCommands() and ICF. A /DISCARD/ entry in SECTIONS command or
409485868e8aSDimitry Andric   // ICF may remove executable InputSections and their dependent .ARM.exidx
409585868e8aSDimitry Andric   // section that we recorded earlier.
40960b57cec5SDimitry Andric   auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
40970b57cec5SDimitry Andric   llvm::erase_if(exidxSections, isDiscarded);
40985ffd83dbSDimitry Andric   // We need to remove discarded InputSections and InputSections without
40995ffd83dbSDimitry Andric   // .ARM.exidx sections that if we generated the .ARM.exidx it would be out
41005ffd83dbSDimitry Andric   // of range.
41015ffd83dbSDimitry Andric   auto isDiscardedOrOutOfRange = [this](InputSection *isec) {
41025ffd83dbSDimitry Andric     if (!isec->isLive())
41035ffd83dbSDimitry Andric       return true;
41045ffd83dbSDimitry Andric     if (findExidxSection(isec))
41055ffd83dbSDimitry Andric       return false;
41065ffd83dbSDimitry Andric     int64_t off = static_cast<int64_t>(isec->getVA() - getVA());
41075ffd83dbSDimitry Andric     return off != llvm::SignExtend64(off, 31);
41085ffd83dbSDimitry Andric   };
41095ffd83dbSDimitry Andric   llvm::erase_if(executableSections, isDiscardedOrOutOfRange);
41100b57cec5SDimitry Andric 
41110b57cec5SDimitry Andric   // Sort the executable sections that may or may not have associated
41120b57cec5SDimitry Andric   // .ARM.exidx sections by order of ascending address. This requires the
41135ffd83dbSDimitry Andric   // relative positions of InputSections and OutputSections to be known.
41140b57cec5SDimitry Andric   auto compareByFilePosition = [](const InputSection *a,
41150b57cec5SDimitry Andric                                   const InputSection *b) {
41160b57cec5SDimitry Andric     OutputSection *aOut = a->getParent();
41170b57cec5SDimitry Andric     OutputSection *bOut = b->getParent();
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric     if (aOut != bOut)
41205ffd83dbSDimitry Andric       return aOut->addr < bOut->addr;
41210b57cec5SDimitry Andric     return a->outSecOff < b->outSecOff;
41220b57cec5SDimitry Andric   };
41230b57cec5SDimitry Andric   llvm::stable_sort(executableSections, compareByFilePosition);
41240b57cec5SDimitry Andric   sentinel = executableSections.back();
4125bdd1243dSDimitry Andric   // std::optionally merge adjacent duplicate entries.
41260b57cec5SDimitry Andric   if (config->mergeArmExidx) {
41271fd87a68SDimitry Andric     SmallVector<InputSection *, 0> selectedSections;
41280b57cec5SDimitry Andric     selectedSections.reserve(executableSections.size());
41290b57cec5SDimitry Andric     selectedSections.push_back(executableSections[0]);
41300b57cec5SDimitry Andric     size_t prev = 0;
41310b57cec5SDimitry Andric     for (size_t i = 1; i < executableSections.size(); ++i) {
41320b57cec5SDimitry Andric       InputSection *ex1 = findExidxSection(executableSections[prev]);
41330b57cec5SDimitry Andric       InputSection *ex2 = findExidxSection(executableSections[i]);
41340b57cec5SDimitry Andric       if (!isDuplicateArmExidxSec(ex1, ex2)) {
41350b57cec5SDimitry Andric         selectedSections.push_back(executableSections[i]);
41360b57cec5SDimitry Andric         prev = i;
41370b57cec5SDimitry Andric       }
41380b57cec5SDimitry Andric     }
41390b57cec5SDimitry Andric     executableSections = std::move(selectedSections);
41400b57cec5SDimitry Andric   }
414106c3fb27SDimitry Andric   // offset is within the SyntheticSection.
41420b57cec5SDimitry Andric   size_t offset = 0;
41430b57cec5SDimitry Andric   size = 0;
41440b57cec5SDimitry Andric   for (InputSection *isec : executableSections) {
41450b57cec5SDimitry Andric     if (InputSection *d = findExidxSection(isec)) {
41460b57cec5SDimitry Andric       d->outSecOff = offset;
41470b57cec5SDimitry Andric       d->parent = getParent();
41480b57cec5SDimitry Andric       offset += d->getSize();
41490b57cec5SDimitry Andric     } else {
41500b57cec5SDimitry Andric       offset += 8;
41510b57cec5SDimitry Andric     }
41520b57cec5SDimitry Andric   }
41530b57cec5SDimitry Andric   // Size includes Sentinel.
41540b57cec5SDimitry Andric   size = offset + 8;
41550b57cec5SDimitry Andric }
41560b57cec5SDimitry Andric 
getLinkOrderDep() const41570b57cec5SDimitry Andric InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
41580b57cec5SDimitry Andric   return executableSections.front();
41590b57cec5SDimitry Andric }
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric // To write the .ARM.exidx table from the ExecutableSections we have three cases
41620b57cec5SDimitry Andric // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
41630b57cec5SDimitry Andric //     We write the .ARM.exidx section contents and apply its relocations.
41640b57cec5SDimitry Andric // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
41650b57cec5SDimitry Andric //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
41660b57cec5SDimitry Andric //     start of the InputSection as the purpose of the linker generated
41670b57cec5SDimitry Andric //     section is to terminate the address range of the previous entry.
41680b57cec5SDimitry Andric // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
41690b57cec5SDimitry Andric //     the table to terminate the address range of the final entry.
writeTo(uint8_t * buf)41700b57cec5SDimitry Andric void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
41710b57cec5SDimitry Andric 
417206c3fb27SDimitry Andric   // A linker generated CANTUNWIND entry is made up of two words:
417306c3fb27SDimitry Andric   // 0x0 with R_ARM_PREL31 relocation to target.
417406c3fb27SDimitry Andric   // 0x1 with EXIDX_CANTUNWIND.
41750b57cec5SDimitry Andric   uint64_t offset = 0;
41760b57cec5SDimitry Andric   for (InputSection *isec : executableSections) {
41770b57cec5SDimitry Andric     assert(isec->getParent() != nullptr);
41780b57cec5SDimitry Andric     if (InputSection *d = findExidxSection(isec)) {
417906c3fb27SDimitry Andric       for (int dataOffset = 0; dataOffset != (int)d->content().size();
418006c3fb27SDimitry Andric            dataOffset += 4)
418106c3fb27SDimitry Andric         write32(buf + offset + dataOffset,
418206c3fb27SDimitry Andric                 read32(d->content().data() + dataOffset));
418306c3fb27SDimitry Andric       // Recalculate outSecOff as finalizeAddressDependentContent()
418406c3fb27SDimitry Andric       // may have altered syntheticSection outSecOff.
418506c3fb27SDimitry Andric       d->outSecOff = offset + outSecOff;
418606c3fb27SDimitry Andric       target->relocateAlloc(*d, buf + offset);
41870b57cec5SDimitry Andric       offset += d->getSize();
41880b57cec5SDimitry Andric     } else {
41890b57cec5SDimitry Andric       // A Linker generated CANTUNWIND section.
419006c3fb27SDimitry Andric       write32(buf + offset + 0, 0x0);
419106c3fb27SDimitry Andric       write32(buf + offset + 4, 0x1);
41920b57cec5SDimitry Andric       uint64_t s = isec->getVA();
41930b57cec5SDimitry Andric       uint64_t p = getVA() + offset;
41945ffd83dbSDimitry Andric       target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
41950b57cec5SDimitry Andric       offset += 8;
41960b57cec5SDimitry Andric     }
41970b57cec5SDimitry Andric   }
419806c3fb27SDimitry Andric   // Write Sentinel CANTUNWIND entry.
419906c3fb27SDimitry Andric   write32(buf + offset + 0, 0x0);
420006c3fb27SDimitry Andric   write32(buf + offset + 4, 0x1);
42010b57cec5SDimitry Andric   uint64_t s = sentinel->getVA(sentinel->getSize());
42020b57cec5SDimitry Andric   uint64_t p = getVA() + offset;
42035ffd83dbSDimitry Andric   target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
42040b57cec5SDimitry Andric   assert(size == offset + 8);
42050b57cec5SDimitry Andric }
42060b57cec5SDimitry Andric 
isNeeded() const420785868e8aSDimitry Andric bool ARMExidxSyntheticSection::isNeeded() const {
4208349cc55cSDimitry Andric   return llvm::any_of(exidxSections,
4209349cc55cSDimitry Andric                       [](InputSection *isec) { return isec->isLive(); });
421085868e8aSDimitry Andric }
421185868e8aSDimitry Andric 
ThunkSection(OutputSection * os,uint64_t off)42120b57cec5SDimitry Andric ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
4213e8d8bef9SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
4214e8d8bef9SDimitry Andric                        config->emachine == EM_PPC64 ? 16 : 4, ".text.thunk") {
42150b57cec5SDimitry Andric   this->parent = os;
42160b57cec5SDimitry Andric   this->outSecOff = off;
42170b57cec5SDimitry Andric }
42180b57cec5SDimitry Andric 
getSize() const4219480093f4SDimitry Andric size_t ThunkSection::getSize() const {
422013138422SDimitry Andric   if (roundUpSizeForErrata)
4221480093f4SDimitry Andric     return alignTo(size, 4096);
4222480093f4SDimitry Andric   return size;
4223480093f4SDimitry Andric }
4224480093f4SDimitry Andric 
addThunk(Thunk * t)42250b57cec5SDimitry Andric void ThunkSection::addThunk(Thunk *t) {
42260b57cec5SDimitry Andric   thunks.push_back(t);
42270b57cec5SDimitry Andric   t->addSymbols(*this);
42280b57cec5SDimitry Andric }
42290b57cec5SDimitry Andric 
writeTo(uint8_t * buf)42300b57cec5SDimitry Andric void ThunkSection::writeTo(uint8_t *buf) {
42310b57cec5SDimitry Andric   for (Thunk *t : thunks)
42320b57cec5SDimitry Andric     t->writeTo(buf + t->offset);
42330b57cec5SDimitry Andric }
42340b57cec5SDimitry Andric 
getTargetInputSection() const42350b57cec5SDimitry Andric InputSection *ThunkSection::getTargetInputSection() const {
42360b57cec5SDimitry Andric   if (thunks.empty())
42370b57cec5SDimitry Andric     return nullptr;
42380b57cec5SDimitry Andric   const Thunk *t = thunks.front();
42390b57cec5SDimitry Andric   return t->getTargetInputSection();
42400b57cec5SDimitry Andric }
42410b57cec5SDimitry Andric 
assignOffsets()42420b57cec5SDimitry Andric bool ThunkSection::assignOffsets() {
42430b57cec5SDimitry Andric   uint64_t off = 0;
42440b57cec5SDimitry Andric   for (Thunk *t : thunks) {
4245972a253aSDimitry Andric     off = alignToPowerOf2(off, t->alignment);
42460b57cec5SDimitry Andric     t->setOffset(off);
42470b57cec5SDimitry Andric     uint32_t size = t->size();
42480b57cec5SDimitry Andric     t->getThunkTargetSym()->size = size;
42490b57cec5SDimitry Andric     off += size;
42500b57cec5SDimitry Andric   }
42510b57cec5SDimitry Andric   bool changed = off != size;
42520b57cec5SDimitry Andric   size = off;
42530b57cec5SDimitry Andric   return changed;
42540b57cec5SDimitry Andric }
42550b57cec5SDimitry Andric 
PPC32Got2Section()42560b57cec5SDimitry Andric PPC32Got2Section::PPC32Got2Section()
42570b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
42580b57cec5SDimitry Andric 
isNeeded() const42590b57cec5SDimitry Andric bool PPC32Got2Section::isNeeded() const {
42600b57cec5SDimitry Andric   // See the comment below. This is not needed if there is no other
42610b57cec5SDimitry Andric   // InputSection.
42624824e7fdSDimitry Andric   for (SectionCommand *cmd : getParent()->commands)
42634824e7fdSDimitry Andric     if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
42640b57cec5SDimitry Andric       for (InputSection *isec : isd->sections)
42650b57cec5SDimitry Andric         if (isec != this)
42660b57cec5SDimitry Andric           return true;
42670b57cec5SDimitry Andric   return false;
42680b57cec5SDimitry Andric }
42690b57cec5SDimitry Andric 
finalizeContents()42700b57cec5SDimitry Andric void PPC32Got2Section::finalizeContents() {
42710b57cec5SDimitry Andric   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
42720b57cec5SDimitry Andric   // .got2 . This function computes outSecOff of each .got2 to be used in
42730b57cec5SDimitry Andric   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
42740b57cec5SDimitry Andric   // to collect input sections named ".got2".
42754824e7fdSDimitry Andric   for (SectionCommand *cmd : getParent()->commands)
42764824e7fdSDimitry Andric     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
42770b57cec5SDimitry Andric       for (InputSection *isec : isd->sections) {
42780eae32dcSDimitry Andric         // isec->file may be nullptr for MergeSyntheticSection.
42790eae32dcSDimitry Andric         if (isec != this && isec->file)
42800eae32dcSDimitry Andric           isec->file->ppc32Got2 = isec;
42810b57cec5SDimitry Andric       }
42820b57cec5SDimitry Andric     }
42830b57cec5SDimitry Andric }
42840b57cec5SDimitry Andric 
42850b57cec5SDimitry Andric // If linking position-dependent code then the table will store the addresses
42860b57cec5SDimitry Andric // directly in the binary so the section has type SHT_PROGBITS. If linking
42870b57cec5SDimitry Andric // position-independent code the section has type SHT_NOBITS since it will be
42880b57cec5SDimitry Andric // allocated and filled in by the dynamic linker.
PPC64LongBranchTargetSection()42890b57cec5SDimitry Andric PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
42900b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
42910b57cec5SDimitry Andric                        config->isPic ? SHT_NOBITS : SHT_PROGBITS, 8,
42920b57cec5SDimitry Andric                        ".branch_lt") {}
42930b57cec5SDimitry Andric 
getEntryVA(const Symbol * sym,int64_t addend)4294480093f4SDimitry Andric uint64_t PPC64LongBranchTargetSection::getEntryVA(const Symbol *sym,
4295480093f4SDimitry Andric                                                   int64_t addend) {
4296480093f4SDimitry Andric   return getVA() + entry_index.find({sym, addend})->second * 8;
4297480093f4SDimitry Andric }
4298480093f4SDimitry Andric 
4299bdd1243dSDimitry Andric std::optional<uint32_t>
addEntry(const Symbol * sym,int64_t addend)4300bdd1243dSDimitry Andric PPC64LongBranchTargetSection::addEntry(const Symbol *sym, int64_t addend) {
4301480093f4SDimitry Andric   auto res =
4302480093f4SDimitry Andric       entry_index.try_emplace(std::make_pair(sym, addend), entries.size());
4303480093f4SDimitry Andric   if (!res.second)
4304bdd1243dSDimitry Andric     return std::nullopt;
4305480093f4SDimitry Andric   entries.emplace_back(sym, addend);
4306480093f4SDimitry Andric   return res.first->second;
43070b57cec5SDimitry Andric }
43080b57cec5SDimitry Andric 
getSize() const43090b57cec5SDimitry Andric size_t PPC64LongBranchTargetSection::getSize() const {
43100b57cec5SDimitry Andric   return entries.size() * 8;
43110b57cec5SDimitry Andric }
43120b57cec5SDimitry Andric 
writeTo(uint8_t * buf)43130b57cec5SDimitry Andric void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
43140b57cec5SDimitry Andric   // If linking non-pic we have the final addresses of the targets and they get
43150b57cec5SDimitry Andric   // written to the table directly. For pic the dynamic linker will allocate
4316bdd1243dSDimitry Andric   // the section and fill it.
43170b57cec5SDimitry Andric   if (config->isPic)
43180b57cec5SDimitry Andric     return;
43190b57cec5SDimitry Andric 
4320480093f4SDimitry Andric   for (auto entry : entries) {
4321480093f4SDimitry Andric     const Symbol *sym = entry.first;
4322480093f4SDimitry Andric     int64_t addend = entry.second;
43230b57cec5SDimitry Andric     assert(sym->getVA());
43240b57cec5SDimitry Andric     // Need calls to branch to the local entry-point since a long-branch
43250b57cec5SDimitry Andric     // must be a local-call.
4326480093f4SDimitry Andric     write64(buf, sym->getVA(addend) +
4327480093f4SDimitry Andric                      getPPC64GlobalEntryToLocalEntryOffset(sym->stOther));
43280b57cec5SDimitry Andric     buf += 8;
43290b57cec5SDimitry Andric   }
43300b57cec5SDimitry Andric }
43310b57cec5SDimitry Andric 
isNeeded() const43320b57cec5SDimitry Andric bool PPC64LongBranchTargetSection::isNeeded() const {
43330b57cec5SDimitry Andric   // `removeUnusedSyntheticSections()` is called before thunk allocation which
43340b57cec5SDimitry Andric   // is too early to determine if this section will be empty or not. We need
43350b57cec5SDimitry Andric   // Finalized to keep the section alive until after thunk creation. Finalized
43360b57cec5SDimitry Andric   // only gets set to true once `finalizeSections()` is called after thunk
4337480093f4SDimitry Andric   // creation. Because of this, if we don't create any long-branch thunks we end
43380b57cec5SDimitry Andric   // up with an empty .branch_lt section in the binary.
43390b57cec5SDimitry Andric   return !finalized || !entries.empty();
43400b57cec5SDimitry Andric }
43410b57cec5SDimitry Andric 
getAbiVersion()43420b57cec5SDimitry Andric static uint8_t getAbiVersion() {
43430b57cec5SDimitry Andric   // MIPS non-PIC executable gets ABI version 1.
43440b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
43450b57cec5SDimitry Andric     if (!config->isPic && !config->relocatable &&
43460b57cec5SDimitry Andric         (config->eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
43470b57cec5SDimitry Andric       return 1;
43480b57cec5SDimitry Andric     return 0;
43490b57cec5SDimitry Andric   }
43500b57cec5SDimitry Andric 
4351bdd1243dSDimitry Andric   if (config->emachine == EM_AMDGPU && !ctx.objectFiles.empty()) {
4352bdd1243dSDimitry Andric     uint8_t ver = ctx.objectFiles[0]->abiVersion;
4353bdd1243dSDimitry Andric     for (InputFile *file : ArrayRef(ctx.objectFiles).slice(1))
43540b57cec5SDimitry Andric       if (file->abiVersion != ver)
43550b57cec5SDimitry Andric         error("incompatible ABI version: " + toString(file));
43560b57cec5SDimitry Andric     return ver;
43570b57cec5SDimitry Andric   }
43580b57cec5SDimitry Andric 
43590b57cec5SDimitry Andric   return 0;
43600b57cec5SDimitry Andric }
43610b57cec5SDimitry Andric 
writeEhdr(uint8_t * buf,Partition & part)43625ffd83dbSDimitry Andric template <typename ELFT> void elf::writeEhdr(uint8_t *buf, Partition &part) {
43630b57cec5SDimitry Andric   memcpy(buf, "\177ELF", 4);
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
43660fca6ea1SDimitry Andric   eHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
43670fca6ea1SDimitry Andric   eHdr->e_ident[EI_DATA] =
43680fca6ea1SDimitry Andric       ELFT::Endianness == endianness::little ? ELFDATA2LSB : ELFDATA2MSB;
43690b57cec5SDimitry Andric   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
43700b57cec5SDimitry Andric   eHdr->e_ident[EI_OSABI] = config->osabi;
43710b57cec5SDimitry Andric   eHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
43720b57cec5SDimitry Andric   eHdr->e_machine = config->emachine;
43730b57cec5SDimitry Andric   eHdr->e_version = EV_CURRENT;
43740b57cec5SDimitry Andric   eHdr->e_flags = config->eflags;
43750b57cec5SDimitry Andric   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
43760b57cec5SDimitry Andric   eHdr->e_phnum = part.phdrs.size();
43770b57cec5SDimitry Andric   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
43780b57cec5SDimitry Andric 
43790b57cec5SDimitry Andric   if (!config->relocatable) {
43800b57cec5SDimitry Andric     eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
43810b57cec5SDimitry Andric     eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
43820b57cec5SDimitry Andric   }
43830b57cec5SDimitry Andric }
43840b57cec5SDimitry Andric 
writePhdrs(uint8_t * buf,Partition & part)43855ffd83dbSDimitry Andric template <typename ELFT> void elf::writePhdrs(uint8_t *buf, Partition &part) {
43860b57cec5SDimitry Andric   // Write the program header table.
43870b57cec5SDimitry Andric   auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
43880b57cec5SDimitry Andric   for (PhdrEntry *p : part.phdrs) {
43890b57cec5SDimitry Andric     hBuf->p_type = p->p_type;
43900b57cec5SDimitry Andric     hBuf->p_flags = p->p_flags;
43910b57cec5SDimitry Andric     hBuf->p_offset = p->p_offset;
43920b57cec5SDimitry Andric     hBuf->p_vaddr = p->p_vaddr;
43930b57cec5SDimitry Andric     hBuf->p_paddr = p->p_paddr;
43940b57cec5SDimitry Andric     hBuf->p_filesz = p->p_filesz;
43950b57cec5SDimitry Andric     hBuf->p_memsz = p->p_memsz;
43960b57cec5SDimitry Andric     hBuf->p_align = p->p_align;
43970b57cec5SDimitry Andric     ++hBuf;
43980b57cec5SDimitry Andric   }
43990b57cec5SDimitry Andric }
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric template <typename ELFT>
PartitionElfHeaderSection()44020b57cec5SDimitry Andric PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
44030b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
44040b57cec5SDimitry Andric 
44050b57cec5SDimitry Andric template <typename ELFT>
getSize() const44060b57cec5SDimitry Andric size_t PartitionElfHeaderSection<ELFT>::getSize() const {
44070b57cec5SDimitry Andric   return sizeof(typename ELFT::Ehdr);
44080b57cec5SDimitry Andric }
44090b57cec5SDimitry Andric 
44100b57cec5SDimitry Andric template <typename ELFT>
writeTo(uint8_t * buf)44110b57cec5SDimitry Andric void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
44120b57cec5SDimitry Andric   writeEhdr<ELFT>(buf, getPartition());
44130b57cec5SDimitry Andric 
44140b57cec5SDimitry Andric   // Loadable partitions are always ET_DYN.
44150b57cec5SDimitry Andric   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
44160b57cec5SDimitry Andric   eHdr->e_type = ET_DYN;
44170b57cec5SDimitry Andric }
44180b57cec5SDimitry Andric 
44190b57cec5SDimitry Andric template <typename ELFT>
PartitionProgramHeadersSection()44200b57cec5SDimitry Andric PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
44210b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
44220b57cec5SDimitry Andric 
44230b57cec5SDimitry Andric template <typename ELFT>
getSize() const44240b57cec5SDimitry Andric size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
44250b57cec5SDimitry Andric   return sizeof(typename ELFT::Phdr) * getPartition().phdrs.size();
44260b57cec5SDimitry Andric }
44270b57cec5SDimitry Andric 
44280b57cec5SDimitry Andric template <typename ELFT>
writeTo(uint8_t * buf)44290b57cec5SDimitry Andric void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
44300b57cec5SDimitry Andric   writePhdrs<ELFT>(buf, getPartition());
44310b57cec5SDimitry Andric }
44320b57cec5SDimitry Andric 
PartitionIndexSection()44330b57cec5SDimitry Andric PartitionIndexSection::PartitionIndexSection()
44340b57cec5SDimitry Andric     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
44350b57cec5SDimitry Andric 
getSize() const44360b57cec5SDimitry Andric size_t PartitionIndexSection::getSize() const {
44370b57cec5SDimitry Andric   return 12 * (partitions.size() - 1);
44380b57cec5SDimitry Andric }
44390b57cec5SDimitry Andric 
finalizeContents()44400b57cec5SDimitry Andric void PartitionIndexSection::finalizeContents() {
44410b57cec5SDimitry Andric   for (size_t i = 1; i != partitions.size(); ++i)
44420b57cec5SDimitry Andric     partitions[i].nameStrTab = mainPart->dynStrTab->addString(partitions[i].name);
44430b57cec5SDimitry Andric }
44440b57cec5SDimitry Andric 
writeTo(uint8_t * buf)44450b57cec5SDimitry Andric void PartitionIndexSection::writeTo(uint8_t *buf) {
44460b57cec5SDimitry Andric   uint64_t va = getVA();
44470b57cec5SDimitry Andric   for (size_t i = 1; i != partitions.size(); ++i) {
44480b57cec5SDimitry Andric     write32(buf, mainPart->dynStrTab->getVA() + partitions[i].nameStrTab - va);
44490b57cec5SDimitry Andric     write32(buf + 4, partitions[i].elfHeader->getVA() - (va + 4));
44500b57cec5SDimitry Andric 
445104eeddc0SDimitry Andric     SyntheticSection *next = i == partitions.size() - 1
445204eeddc0SDimitry Andric                                  ? in.partEnd.get()
445304eeddc0SDimitry Andric                                  : partitions[i + 1].elfHeader.get();
44540b57cec5SDimitry Andric     write32(buf + 8, next->getVA() - partitions[i].elfHeader->getVA());
44550b57cec5SDimitry Andric 
44560b57cec5SDimitry Andric     va += 12;
44570b57cec5SDimitry Andric     buf += 12;
44580b57cec5SDimitry Andric   }
44590b57cec5SDimitry Andric }
44600b57cec5SDimitry Andric 
reset()446104eeddc0SDimitry Andric void InStruct::reset() {
446204eeddc0SDimitry Andric   attributes.reset();
4463bdd1243dSDimitry Andric   riscvAttributes.reset();
446404eeddc0SDimitry Andric   bss.reset();
446504eeddc0SDimitry Andric   bssRelRo.reset();
446604eeddc0SDimitry Andric   got.reset();
446704eeddc0SDimitry Andric   gotPlt.reset();
446804eeddc0SDimitry Andric   igotPlt.reset();
44695f757f3fSDimitry Andric   relroPadding.reset();
447006c3fb27SDimitry Andric   armCmseSGSection.reset();
447104eeddc0SDimitry Andric   ppc64LongBranchTarget.reset();
44721fd87a68SDimitry Andric   mipsAbiFlags.reset();
447304eeddc0SDimitry Andric   mipsGot.reset();
44741fd87a68SDimitry Andric   mipsOptions.reset();
44751fd87a68SDimitry Andric   mipsReginfo.reset();
447604eeddc0SDimitry Andric   mipsRldMap.reset();
447704eeddc0SDimitry Andric   partEnd.reset();
447804eeddc0SDimitry Andric   partIndex.reset();
447904eeddc0SDimitry Andric   plt.reset();
448004eeddc0SDimitry Andric   iplt.reset();
448104eeddc0SDimitry Andric   ppc32Got2.reset();
448204eeddc0SDimitry Andric   ibtPlt.reset();
448304eeddc0SDimitry Andric   relaPlt.reset();
44840fca6ea1SDimitry Andric   debugNames.reset();
44850fca6ea1SDimitry Andric   gdbIndex.reset();
448604eeddc0SDimitry Andric   shStrTab.reset();
448704eeddc0SDimitry Andric   strTab.reset();
448804eeddc0SDimitry Andric   symTab.reset();
448904eeddc0SDimitry Andric   symTabShndx.reset();
449004eeddc0SDimitry Andric }
449104eeddc0SDimitry Andric 
needsInterpSection()44920fca6ea1SDimitry Andric static bool needsInterpSection() {
44930fca6ea1SDimitry Andric   return !config->relocatable && !config->shared &&
44940fca6ea1SDimitry Andric          !config->dynamicLinker.empty() && script->needsInterpSection();
44950fca6ea1SDimitry Andric }
44960fca6ea1SDimitry Andric 
hasMemtag()44970fca6ea1SDimitry Andric bool elf::hasMemtag() {
44980fca6ea1SDimitry Andric   return config->emachine == EM_AARCH64 &&
44990fca6ea1SDimitry Andric          config->androidMemtagMode != ELF::NT_MEMTAG_LEVEL_NONE;
45000fca6ea1SDimitry Andric }
45010fca6ea1SDimitry Andric 
45020fca6ea1SDimitry Andric // Fully static executables don't support MTE globals at this point in time, as
45030fca6ea1SDimitry Andric // we currently rely on:
45040fca6ea1SDimitry Andric //   - A dynamic loader to process relocations, and
45050fca6ea1SDimitry Andric //   - Dynamic entries.
45060fca6ea1SDimitry Andric // This restriction could be removed in future by re-using some of the ideas
45070fca6ea1SDimitry Andric // that ifuncs use in fully static executables.
canHaveMemtagGlobals()45080fca6ea1SDimitry Andric bool elf::canHaveMemtagGlobals() {
45090fca6ea1SDimitry Andric   return hasMemtag() &&
45100fca6ea1SDimitry Andric          (config->relocatable || config->shared || needsInterpSection());
45110fca6ea1SDimitry Andric }
45120fca6ea1SDimitry Andric 
451381ad6265SDimitry Andric constexpr char kMemtagAndroidNoteName[] = "Android";
writeTo(uint8_t * buf)451481ad6265SDimitry Andric void MemtagAndroidNote::writeTo(uint8_t *buf) {
451506c3fb27SDimitry Andric   static_assert(
451606c3fb27SDimitry Andric       sizeof(kMemtagAndroidNoteName) == 8,
451706c3fb27SDimitry Andric       "Android 11 & 12 have an ABI that the note name is 8 bytes long. Keep it "
451806c3fb27SDimitry Andric       "that way for backwards compatibility.");
451981ad6265SDimitry Andric 
452081ad6265SDimitry Andric   write32(buf, sizeof(kMemtagAndroidNoteName));
452181ad6265SDimitry Andric   write32(buf + 4, sizeof(uint32_t));
452281ad6265SDimitry Andric   write32(buf + 8, ELF::NT_ANDROID_TYPE_MEMTAG);
452381ad6265SDimitry Andric   memcpy(buf + 12, kMemtagAndroidNoteName, sizeof(kMemtagAndroidNoteName));
452406c3fb27SDimitry Andric   buf += 12 + alignTo(sizeof(kMemtagAndroidNoteName), 4);
452581ad6265SDimitry Andric 
452681ad6265SDimitry Andric   uint32_t value = 0;
452781ad6265SDimitry Andric   value |= config->androidMemtagMode;
452881ad6265SDimitry Andric   if (config->androidMemtagHeap)
452981ad6265SDimitry Andric     value |= ELF::NT_MEMTAG_HEAP;
453081ad6265SDimitry Andric   // Note, MTE stack is an ABI break. Attempting to run an MTE stack-enabled
453181ad6265SDimitry Andric   // binary on Android 11 or 12 will result in a checkfail in the loader.
453281ad6265SDimitry Andric   if (config->androidMemtagStack)
453381ad6265SDimitry Andric     value |= ELF::NT_MEMTAG_STACK;
453481ad6265SDimitry Andric   write32(buf, value); // note value
453581ad6265SDimitry Andric }
453681ad6265SDimitry Andric 
getSize() const453781ad6265SDimitry Andric size_t MemtagAndroidNote::getSize() const {
453881ad6265SDimitry Andric   return sizeof(llvm::ELF::Elf64_Nhdr) +
453906c3fb27SDimitry Andric          /*namesz=*/alignTo(sizeof(kMemtagAndroidNoteName), 4) +
454081ad6265SDimitry Andric          /*descsz=*/sizeof(uint32_t);
454181ad6265SDimitry Andric }
454281ad6265SDimitry Andric 
writeTo(uint8_t * buf)454361cfbce3SDimitry Andric void PackageMetadataNote::writeTo(uint8_t *buf) {
454461cfbce3SDimitry Andric   write32(buf, 4);
454561cfbce3SDimitry Andric   write32(buf + 4, config->packageMetadata.size() + 1);
454661cfbce3SDimitry Andric   write32(buf + 8, FDO_PACKAGING_METADATA);
454761cfbce3SDimitry Andric   memcpy(buf + 12, "FDO", 4);
454861cfbce3SDimitry Andric   memcpy(buf + 16, config->packageMetadata.data(),
454961cfbce3SDimitry Andric          config->packageMetadata.size());
455061cfbce3SDimitry Andric }
455161cfbce3SDimitry Andric 
getSize() const455261cfbce3SDimitry Andric size_t PackageMetadataNote::getSize() const {
455361cfbce3SDimitry Andric   return sizeof(llvm::ELF::Elf64_Nhdr) + 4 +
455461cfbce3SDimitry Andric          alignTo(config->packageMetadata.size() + 1, 4);
455561cfbce3SDimitry Andric }
455661cfbce3SDimitry Andric 
45575f757f3fSDimitry Andric // Helper function, return the size of the ULEB128 for 'v', optionally writing
45585f757f3fSDimitry Andric // it to `*(buf + offset)` if `buf` is non-null.
computeOrWriteULEB128(uint64_t v,uint8_t * buf,size_t offset)45595f757f3fSDimitry Andric static size_t computeOrWriteULEB128(uint64_t v, uint8_t *buf, size_t offset) {
45605f757f3fSDimitry Andric   if (buf)
45615f757f3fSDimitry Andric     return encodeULEB128(v, buf + offset);
45625f757f3fSDimitry Andric   return getULEB128Size(v);
45635f757f3fSDimitry Andric }
45645f757f3fSDimitry Andric 
45655f757f3fSDimitry Andric // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
45665f757f3fSDimitry Andric constexpr uint64_t kMemtagStepSizeBits = 3;
45675f757f3fSDimitry Andric constexpr uint64_t kMemtagGranuleSize = 16;
45681db9f3b2SDimitry Andric static size_t
createMemtagGlobalDescriptors(const SmallVector<const Symbol *,0> & symbols,uint8_t * buf=nullptr)45691db9f3b2SDimitry Andric createMemtagGlobalDescriptors(const SmallVector<const Symbol *, 0> &symbols,
45705f757f3fSDimitry Andric                               uint8_t *buf = nullptr) {
45715f757f3fSDimitry Andric   size_t sectionSize = 0;
45725f757f3fSDimitry Andric   uint64_t lastGlobalEnd = 0;
45735f757f3fSDimitry Andric 
45745f757f3fSDimitry Andric   for (const Symbol *sym : symbols) {
45755f757f3fSDimitry Andric     if (!includeInSymtab(*sym))
45765f757f3fSDimitry Andric       continue;
45775f757f3fSDimitry Andric     const uint64_t addr = sym->getVA();
45785f757f3fSDimitry Andric     const uint64_t size = sym->getSize();
45795f757f3fSDimitry Andric 
45805f757f3fSDimitry Andric     if (addr <= kMemtagGranuleSize && buf != nullptr)
45815f757f3fSDimitry Andric       errorOrWarn("address of the tagged symbol \"" + sym->getName() +
45825f757f3fSDimitry Andric                   "\" falls in the ELF header. This is indicative of a "
45835f757f3fSDimitry Andric                   "compiler/linker bug");
45845f757f3fSDimitry Andric     if (addr % kMemtagGranuleSize != 0)
45855f757f3fSDimitry Andric       errorOrWarn("address of the tagged symbol \"" + sym->getName() +
45865f757f3fSDimitry Andric                   "\" at 0x" + Twine::utohexstr(addr) +
45875f757f3fSDimitry Andric                   "\" is not granule (16-byte) aligned");
45885f757f3fSDimitry Andric     if (size == 0)
45895f757f3fSDimitry Andric       errorOrWarn("size of the tagged symbol \"" + sym->getName() +
45905f757f3fSDimitry Andric                   "\" is not allowed to be zero");
45915f757f3fSDimitry Andric     if (size % kMemtagGranuleSize != 0)
45925f757f3fSDimitry Andric       errorOrWarn("size of the tagged symbol \"" + sym->getName() +
45935f757f3fSDimitry Andric                   "\" (size 0x" + Twine::utohexstr(size) +
45945f757f3fSDimitry Andric                   ") is not granule (16-byte) aligned");
45955f757f3fSDimitry Andric 
45965f757f3fSDimitry Andric     const uint64_t sizeToEncode = size / kMemtagGranuleSize;
45975f757f3fSDimitry Andric     const uint64_t stepToEncode = ((addr - lastGlobalEnd) / kMemtagGranuleSize)
45985f757f3fSDimitry Andric                                   << kMemtagStepSizeBits;
45995f757f3fSDimitry Andric     if (sizeToEncode < (1 << kMemtagStepSizeBits)) {
46005f757f3fSDimitry Andric       sectionSize += computeOrWriteULEB128(stepToEncode | sizeToEncode, buf, sectionSize);
46015f757f3fSDimitry Andric     } else {
46025f757f3fSDimitry Andric       sectionSize += computeOrWriteULEB128(stepToEncode, buf, sectionSize);
46035f757f3fSDimitry Andric       sectionSize += computeOrWriteULEB128(sizeToEncode - 1, buf, sectionSize);
46045f757f3fSDimitry Andric     }
46055f757f3fSDimitry Andric     lastGlobalEnd = addr + size;
46065f757f3fSDimitry Andric   }
46075f757f3fSDimitry Andric 
46085f757f3fSDimitry Andric   return sectionSize;
46095f757f3fSDimitry Andric }
46105f757f3fSDimitry Andric 
updateAllocSize()46111db9f3b2SDimitry Andric bool MemtagGlobalDescriptors::updateAllocSize() {
46125f757f3fSDimitry Andric   size_t oldSize = getSize();
46135f757f3fSDimitry Andric   std::stable_sort(symbols.begin(), symbols.end(),
46145f757f3fSDimitry Andric                    [](const Symbol *s1, const Symbol *s2) {
46155f757f3fSDimitry Andric                      return s1->getVA() < s2->getVA();
46165f757f3fSDimitry Andric                    });
46175f757f3fSDimitry Andric   return oldSize != getSize();
46185f757f3fSDimitry Andric }
46195f757f3fSDimitry Andric 
writeTo(uint8_t * buf)46201db9f3b2SDimitry Andric void MemtagGlobalDescriptors::writeTo(uint8_t *buf) {
46211db9f3b2SDimitry Andric   createMemtagGlobalDescriptors(symbols, buf);
46225f757f3fSDimitry Andric }
46235f757f3fSDimitry Andric 
getSize() const46241db9f3b2SDimitry Andric size_t MemtagGlobalDescriptors::getSize() const {
46251db9f3b2SDimitry Andric   return createMemtagGlobalDescriptors(symbols);
46265f757f3fSDimitry Andric }
46275f757f3fSDimitry Andric 
findSection(StringRef name)46280fca6ea1SDimitry Andric static OutputSection *findSection(StringRef name) {
46290fca6ea1SDimitry Andric   for (SectionCommand *cmd : script->sectionCommands)
46300fca6ea1SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(cmd))
46310fca6ea1SDimitry Andric       if (osd->osec.name == name)
46320fca6ea1SDimitry Andric         return &osd->osec;
46330fca6ea1SDimitry Andric   return nullptr;
46340fca6ea1SDimitry Andric }
46350fca6ea1SDimitry Andric 
addOptionalRegular(StringRef name,SectionBase * sec,uint64_t val,uint8_t stOther=STV_HIDDEN)46360fca6ea1SDimitry Andric static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
46370fca6ea1SDimitry Andric                                    uint64_t val, uint8_t stOther = STV_HIDDEN) {
46380fca6ea1SDimitry Andric   Symbol *s = symtab.find(name);
46390fca6ea1SDimitry Andric   if (!s || s->isDefined() || s->isCommon())
46400fca6ea1SDimitry Andric     return nullptr;
46410fca6ea1SDimitry Andric 
46420fca6ea1SDimitry Andric   s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL, stOther,
46430fca6ea1SDimitry Andric                      STT_NOTYPE, val,
46440fca6ea1SDimitry Andric                      /*size=*/0, sec});
46450fca6ea1SDimitry Andric   s->isUsedInRegularObj = true;
46460fca6ea1SDimitry Andric   return cast<Defined>(s);
46470fca6ea1SDimitry Andric }
46480fca6ea1SDimitry Andric 
createSyntheticSections()46490fca6ea1SDimitry Andric template <class ELFT> void elf::createSyntheticSections() {
46500fca6ea1SDimitry Andric   // Initialize all pointers with NULL. This is needed because
46510fca6ea1SDimitry Andric   // you can call lld::elf::main more than once as a library.
46520fca6ea1SDimitry Andric   Out::tlsPhdr = nullptr;
46530fca6ea1SDimitry Andric   Out::preinitArray = nullptr;
46540fca6ea1SDimitry Andric   Out::initArray = nullptr;
46550fca6ea1SDimitry Andric   Out::finiArray = nullptr;
46560fca6ea1SDimitry Andric 
46570fca6ea1SDimitry Andric   // Add the .interp section first because it is not a SyntheticSection.
46580fca6ea1SDimitry Andric   // The removeUnusedSyntheticSections() function relies on the
46590fca6ea1SDimitry Andric   // SyntheticSections coming last.
46600fca6ea1SDimitry Andric   if (needsInterpSection()) {
46610fca6ea1SDimitry Andric     for (size_t i = 1; i <= partitions.size(); ++i) {
46620fca6ea1SDimitry Andric       InputSection *sec = createInterpSection();
46630fca6ea1SDimitry Andric       sec->partition = i;
46640fca6ea1SDimitry Andric       ctx.inputSections.push_back(sec);
46650fca6ea1SDimitry Andric     }
46660fca6ea1SDimitry Andric   }
46670fca6ea1SDimitry Andric 
46680fca6ea1SDimitry Andric   auto add = [](SyntheticSection &sec) { ctx.inputSections.push_back(&sec); };
46690fca6ea1SDimitry Andric 
46700fca6ea1SDimitry Andric   in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
46710fca6ea1SDimitry Andric 
46720fca6ea1SDimitry Andric   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
46730fca6ea1SDimitry Andric   Out::programHeaders->addralign = config->wordsize;
46740fca6ea1SDimitry Andric 
46750fca6ea1SDimitry Andric   if (config->strip != StripPolicy::All) {
46760fca6ea1SDimitry Andric     in.strTab = std::make_unique<StringTableSection>(".strtab", false);
46770fca6ea1SDimitry Andric     in.symTab = std::make_unique<SymbolTableSection<ELFT>>(*in.strTab);
46780fca6ea1SDimitry Andric     in.symTabShndx = std::make_unique<SymtabShndxSection>();
46790fca6ea1SDimitry Andric   }
46800fca6ea1SDimitry Andric 
46810fca6ea1SDimitry Andric   in.bss = std::make_unique<BssSection>(".bss", 0, 1);
46820fca6ea1SDimitry Andric   add(*in.bss);
46830fca6ea1SDimitry Andric 
46840fca6ea1SDimitry Andric   // If there is a SECTIONS command and a .data.rel.ro section name use name
46850fca6ea1SDimitry Andric   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
46860fca6ea1SDimitry Andric   // This makes sure our relro is contiguous.
46870fca6ea1SDimitry Andric   bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro");
46880fca6ea1SDimitry Andric   in.bssRelRo = std::make_unique<BssSection>(
46890fca6ea1SDimitry Andric       hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
46900fca6ea1SDimitry Andric   add(*in.bssRelRo);
46910fca6ea1SDimitry Andric 
46920fca6ea1SDimitry Andric   // Add MIPS-specific sections.
46930fca6ea1SDimitry Andric   if (config->emachine == EM_MIPS) {
46940fca6ea1SDimitry Andric     if (!config->shared && config->hasDynSymTab) {
46950fca6ea1SDimitry Andric       in.mipsRldMap = std::make_unique<MipsRldMapSection>();
46960fca6ea1SDimitry Andric       add(*in.mipsRldMap);
46970fca6ea1SDimitry Andric     }
46980fca6ea1SDimitry Andric     if ((in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create()))
46990fca6ea1SDimitry Andric       add(*in.mipsAbiFlags);
47000fca6ea1SDimitry Andric     if ((in.mipsOptions = MipsOptionsSection<ELFT>::create()))
47010fca6ea1SDimitry Andric       add(*in.mipsOptions);
47020fca6ea1SDimitry Andric     if ((in.mipsReginfo = MipsReginfoSection<ELFT>::create()))
47030fca6ea1SDimitry Andric       add(*in.mipsReginfo);
47040fca6ea1SDimitry Andric   }
47050fca6ea1SDimitry Andric 
47060fca6ea1SDimitry Andric   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
47070fca6ea1SDimitry Andric 
47080fca6ea1SDimitry Andric   const unsigned threadCount = config->threadCount;
47090fca6ea1SDimitry Andric   for (Partition &part : partitions) {
47100fca6ea1SDimitry Andric     auto add = [&](SyntheticSection &sec) {
47110fca6ea1SDimitry Andric       sec.partition = part.getNumber();
47120fca6ea1SDimitry Andric       ctx.inputSections.push_back(&sec);
47130fca6ea1SDimitry Andric     };
47140fca6ea1SDimitry Andric 
47150fca6ea1SDimitry Andric     if (!part.name.empty()) {
47160fca6ea1SDimitry Andric       part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
47170fca6ea1SDimitry Andric       part.elfHeader->name = part.name;
47180fca6ea1SDimitry Andric       add(*part.elfHeader);
47190fca6ea1SDimitry Andric 
47200fca6ea1SDimitry Andric       part.programHeaders =
47210fca6ea1SDimitry Andric           std::make_unique<PartitionProgramHeadersSection<ELFT>>();
47220fca6ea1SDimitry Andric       add(*part.programHeaders);
47230fca6ea1SDimitry Andric     }
47240fca6ea1SDimitry Andric 
47250fca6ea1SDimitry Andric     if (config->buildId != BuildIdKind::None) {
47260fca6ea1SDimitry Andric       part.buildId = std::make_unique<BuildIdSection>();
47270fca6ea1SDimitry Andric       add(*part.buildId);
47280fca6ea1SDimitry Andric     }
47290fca6ea1SDimitry Andric 
47300fca6ea1SDimitry Andric     // dynSymTab is always present to simplify sym->includeInDynsym() in
47310fca6ea1SDimitry Andric     // finalizeSections.
47320fca6ea1SDimitry Andric     part.dynStrTab = std::make_unique<StringTableSection>(".dynstr", true);
47330fca6ea1SDimitry Andric     part.dynSymTab =
47340fca6ea1SDimitry Andric         std::make_unique<SymbolTableSection<ELFT>>(*part.dynStrTab);
47350fca6ea1SDimitry Andric 
47360fca6ea1SDimitry Andric     if (config->relocatable)
47370fca6ea1SDimitry Andric       continue;
47380fca6ea1SDimitry Andric     part.dynamic = std::make_unique<DynamicSection<ELFT>>();
47390fca6ea1SDimitry Andric 
47400fca6ea1SDimitry Andric     if (hasMemtag()) {
47410fca6ea1SDimitry Andric       part.memtagAndroidNote = std::make_unique<MemtagAndroidNote>();
47420fca6ea1SDimitry Andric       add(*part.memtagAndroidNote);
47430fca6ea1SDimitry Andric       if (canHaveMemtagGlobals()) {
47440fca6ea1SDimitry Andric         part.memtagGlobalDescriptors =
47450fca6ea1SDimitry Andric             std::make_unique<MemtagGlobalDescriptors>();
47460fca6ea1SDimitry Andric         add(*part.memtagGlobalDescriptors);
47470fca6ea1SDimitry Andric       }
47480fca6ea1SDimitry Andric     }
47490fca6ea1SDimitry Andric 
47500fca6ea1SDimitry Andric     if (config->androidPackDynRelocs)
47510fca6ea1SDimitry Andric       part.relaDyn = std::make_unique<AndroidPackedRelocationSection<ELFT>>(
47520fca6ea1SDimitry Andric           relaDynName, threadCount);
47530fca6ea1SDimitry Andric     else
47540fca6ea1SDimitry Andric       part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
47550fca6ea1SDimitry Andric           relaDynName, config->zCombreloc, threadCount);
47560fca6ea1SDimitry Andric 
47570fca6ea1SDimitry Andric     if (config->hasDynSymTab) {
47580fca6ea1SDimitry Andric       add(*part.dynSymTab);
47590fca6ea1SDimitry Andric 
47600fca6ea1SDimitry Andric       part.verSym = std::make_unique<VersionTableSection>();
47610fca6ea1SDimitry Andric       add(*part.verSym);
47620fca6ea1SDimitry Andric 
47630fca6ea1SDimitry Andric       if (!namedVersionDefs().empty()) {
47640fca6ea1SDimitry Andric         part.verDef = std::make_unique<VersionDefinitionSection>();
47650fca6ea1SDimitry Andric         add(*part.verDef);
47660fca6ea1SDimitry Andric       }
47670fca6ea1SDimitry Andric 
47680fca6ea1SDimitry Andric       part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
47690fca6ea1SDimitry Andric       add(*part.verNeed);
47700fca6ea1SDimitry Andric 
47710fca6ea1SDimitry Andric       if (config->gnuHash) {
47720fca6ea1SDimitry Andric         part.gnuHashTab = std::make_unique<GnuHashTableSection>();
47730fca6ea1SDimitry Andric         add(*part.gnuHashTab);
47740fca6ea1SDimitry Andric       }
47750fca6ea1SDimitry Andric 
47760fca6ea1SDimitry Andric       if (config->sysvHash) {
47770fca6ea1SDimitry Andric         part.hashTab = std::make_unique<HashTableSection>();
47780fca6ea1SDimitry Andric         add(*part.hashTab);
47790fca6ea1SDimitry Andric       }
47800fca6ea1SDimitry Andric 
47810fca6ea1SDimitry Andric       add(*part.dynamic);
47820fca6ea1SDimitry Andric       add(*part.dynStrTab);
47830fca6ea1SDimitry Andric     }
47840fca6ea1SDimitry Andric     add(*part.relaDyn);
47850fca6ea1SDimitry Andric 
47860fca6ea1SDimitry Andric     if (config->relrPackDynRelocs) {
47870fca6ea1SDimitry Andric       part.relrDyn = std::make_unique<RelrSection<ELFT>>(threadCount);
47880fca6ea1SDimitry Andric       add(*part.relrDyn);
47890fca6ea1SDimitry Andric       part.relrAuthDyn = std::make_unique<RelrSection<ELFT>>(
47900fca6ea1SDimitry Andric           threadCount, /*isAArch64Auth=*/true);
47910fca6ea1SDimitry Andric       add(*part.relrAuthDyn);
47920fca6ea1SDimitry Andric     }
47930fca6ea1SDimitry Andric 
47940fca6ea1SDimitry Andric     if (config->ehFrameHdr) {
47950fca6ea1SDimitry Andric       part.ehFrameHdr = std::make_unique<EhFrameHeader>();
47960fca6ea1SDimitry Andric       add(*part.ehFrameHdr);
47970fca6ea1SDimitry Andric     }
47980fca6ea1SDimitry Andric     part.ehFrame = std::make_unique<EhFrameSection>();
47990fca6ea1SDimitry Andric     add(*part.ehFrame);
48000fca6ea1SDimitry Andric 
48010fca6ea1SDimitry Andric     if (config->emachine == EM_ARM) {
48020fca6ea1SDimitry Andric       // This section replaces all the individual .ARM.exidx InputSections.
48030fca6ea1SDimitry Andric       part.armExidx = std::make_unique<ARMExidxSyntheticSection>();
48040fca6ea1SDimitry Andric       add(*part.armExidx);
48050fca6ea1SDimitry Andric     }
48060fca6ea1SDimitry Andric 
48070fca6ea1SDimitry Andric     if (!config->packageMetadata.empty()) {
48080fca6ea1SDimitry Andric       part.packageMetadataNote = std::make_unique<PackageMetadataNote>();
48090fca6ea1SDimitry Andric       add(*part.packageMetadataNote);
48100fca6ea1SDimitry Andric     }
48110fca6ea1SDimitry Andric   }
48120fca6ea1SDimitry Andric 
48130fca6ea1SDimitry Andric   if (partitions.size() != 1) {
48140fca6ea1SDimitry Andric     // Create the partition end marker. This needs to be in partition number 255
48150fca6ea1SDimitry Andric     // so that it is sorted after all other partitions. It also has other
48160fca6ea1SDimitry Andric     // special handling (see createPhdrs() and combineEhSections()).
48170fca6ea1SDimitry Andric     in.partEnd =
48180fca6ea1SDimitry Andric         std::make_unique<BssSection>(".part.end", config->maxPageSize, 1);
48190fca6ea1SDimitry Andric     in.partEnd->partition = 255;
48200fca6ea1SDimitry Andric     add(*in.partEnd);
48210fca6ea1SDimitry Andric 
48220fca6ea1SDimitry Andric     in.partIndex = std::make_unique<PartitionIndexSection>();
48230fca6ea1SDimitry Andric     addOptionalRegular("__part_index_begin", in.partIndex.get(), 0);
48240fca6ea1SDimitry Andric     addOptionalRegular("__part_index_end", in.partIndex.get(),
48250fca6ea1SDimitry Andric                        in.partIndex->getSize());
48260fca6ea1SDimitry Andric     add(*in.partIndex);
48270fca6ea1SDimitry Andric   }
48280fca6ea1SDimitry Andric 
48290fca6ea1SDimitry Andric   // Add .got. MIPS' .got is so different from the other archs,
48300fca6ea1SDimitry Andric   // it has its own class.
48310fca6ea1SDimitry Andric   if (config->emachine == EM_MIPS) {
48320fca6ea1SDimitry Andric     in.mipsGot = std::make_unique<MipsGotSection>();
48330fca6ea1SDimitry Andric     add(*in.mipsGot);
48340fca6ea1SDimitry Andric   } else {
48350fca6ea1SDimitry Andric     in.got = std::make_unique<GotSection>();
48360fca6ea1SDimitry Andric     add(*in.got);
48370fca6ea1SDimitry Andric   }
48380fca6ea1SDimitry Andric 
48390fca6ea1SDimitry Andric   if (config->emachine == EM_PPC) {
48400fca6ea1SDimitry Andric     in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
48410fca6ea1SDimitry Andric     add(*in.ppc32Got2);
48420fca6ea1SDimitry Andric   }
48430fca6ea1SDimitry Andric 
48440fca6ea1SDimitry Andric   if (config->emachine == EM_PPC64) {
48450fca6ea1SDimitry Andric     in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
48460fca6ea1SDimitry Andric     add(*in.ppc64LongBranchTarget);
48470fca6ea1SDimitry Andric   }
48480fca6ea1SDimitry Andric 
48490fca6ea1SDimitry Andric   in.gotPlt = std::make_unique<GotPltSection>();
48500fca6ea1SDimitry Andric   add(*in.gotPlt);
48510fca6ea1SDimitry Andric   in.igotPlt = std::make_unique<IgotPltSection>();
48520fca6ea1SDimitry Andric   add(*in.igotPlt);
48530fca6ea1SDimitry Andric   // Add .relro_padding if DATA_SEGMENT_RELRO_END is used; otherwise, add the
48540fca6ea1SDimitry Andric   // section in the absence of PHDRS/SECTIONS commands.
48550fca6ea1SDimitry Andric   if (config->zRelro &&
48560fca6ea1SDimitry Andric       ((script->phdrsCommands.empty() && !script->hasSectionsCommand) ||
48570fca6ea1SDimitry Andric        script->seenRelroEnd)) {
48580fca6ea1SDimitry Andric     in.relroPadding = std::make_unique<RelroPaddingSection>();
48590fca6ea1SDimitry Andric     add(*in.relroPadding);
48600fca6ea1SDimitry Andric   }
48610fca6ea1SDimitry Andric 
48620fca6ea1SDimitry Andric   if (config->emachine == EM_ARM) {
48630fca6ea1SDimitry Andric     in.armCmseSGSection = std::make_unique<ArmCmseSGSection>();
48640fca6ea1SDimitry Andric     add(*in.armCmseSGSection);
48650fca6ea1SDimitry Andric   }
48660fca6ea1SDimitry Andric 
48670fca6ea1SDimitry Andric   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
48680fca6ea1SDimitry Andric   // it as a relocation and ensure the referenced section is created.
48690fca6ea1SDimitry Andric   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
48700fca6ea1SDimitry Andric     if (target->gotBaseSymInGotPlt)
48710fca6ea1SDimitry Andric       in.gotPlt->hasGotPltOffRel = true;
48720fca6ea1SDimitry Andric     else
48730fca6ea1SDimitry Andric       in.got->hasGotOffRel = true;
48740fca6ea1SDimitry Andric   }
48750fca6ea1SDimitry Andric 
48760fca6ea1SDimitry Andric   // We always need to add rel[a].plt to output if it has entries.
48770fca6ea1SDimitry Andric   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
48780fca6ea1SDimitry Andric   in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
48790fca6ea1SDimitry Andric       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false,
48800fca6ea1SDimitry Andric       /*threadCount=*/1);
48810fca6ea1SDimitry Andric   add(*in.relaPlt);
48820fca6ea1SDimitry Andric 
48830fca6ea1SDimitry Andric   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
48840fca6ea1SDimitry Andric       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
48850fca6ea1SDimitry Andric     in.ibtPlt = std::make_unique<IBTPltSection>();
48860fca6ea1SDimitry Andric     add(*in.ibtPlt);
48870fca6ea1SDimitry Andric   }
48880fca6ea1SDimitry Andric 
48890fca6ea1SDimitry Andric   if (config->emachine == EM_PPC)
48900fca6ea1SDimitry Andric     in.plt = std::make_unique<PPC32GlinkSection>();
48910fca6ea1SDimitry Andric   else
48920fca6ea1SDimitry Andric     in.plt = std::make_unique<PltSection>();
48930fca6ea1SDimitry Andric   add(*in.plt);
48940fca6ea1SDimitry Andric   in.iplt = std::make_unique<IpltSection>();
48950fca6ea1SDimitry Andric   add(*in.iplt);
48960fca6ea1SDimitry Andric 
48970fca6ea1SDimitry Andric   if (config->andFeatures || !ctx.aarch64PauthAbiCoreInfo.empty())
48980fca6ea1SDimitry Andric     add(*make<GnuPropertySection>());
48990fca6ea1SDimitry Andric 
49000fca6ea1SDimitry Andric   if (config->debugNames) {
49010fca6ea1SDimitry Andric     in.debugNames = std::make_unique<DebugNamesSection<ELFT>>();
49020fca6ea1SDimitry Andric     add(*in.debugNames);
49030fca6ea1SDimitry Andric   }
49040fca6ea1SDimitry Andric 
49050fca6ea1SDimitry Andric   if (config->gdbIndex) {
49060fca6ea1SDimitry Andric     in.gdbIndex = GdbIndexSection::create<ELFT>();
49070fca6ea1SDimitry Andric     add(*in.gdbIndex);
49080fca6ea1SDimitry Andric   }
49090fca6ea1SDimitry Andric 
49100fca6ea1SDimitry Andric   // .note.GNU-stack is always added when we are creating a re-linkable
49110fca6ea1SDimitry Andric   // object file. Other linkers are using the presence of this marker
49120fca6ea1SDimitry Andric   // section to control the executable-ness of the stack area, but that
49130fca6ea1SDimitry Andric   // is irrelevant these days. Stack area should always be non-executable
49140fca6ea1SDimitry Andric   // by default. So we emit this section unconditionally.
49150fca6ea1SDimitry Andric   if (config->relocatable)
49160fca6ea1SDimitry Andric     add(*make<GnuStackSection>());
49170fca6ea1SDimitry Andric 
49180fca6ea1SDimitry Andric   if (in.symTab)
49190fca6ea1SDimitry Andric     add(*in.symTab);
49200fca6ea1SDimitry Andric   if (in.symTabShndx)
49210fca6ea1SDimitry Andric     add(*in.symTabShndx);
49220fca6ea1SDimitry Andric   add(*in.shStrTab);
49230fca6ea1SDimitry Andric   if (in.strTab)
49240fca6ea1SDimitry Andric     add(*in.strTab);
49250fca6ea1SDimitry Andric }
49260fca6ea1SDimitry Andric 
49275ffd83dbSDimitry Andric InStruct elf::in;
49280b57cec5SDimitry Andric 
49295ffd83dbSDimitry Andric std::vector<Partition> elf::partitions;
49305ffd83dbSDimitry Andric Partition *elf::mainPart;
49310b57cec5SDimitry Andric 
49325ffd83dbSDimitry Andric template void elf::splitSections<ELF32LE>();
49335ffd83dbSDimitry Andric template void elf::splitSections<ELF32BE>();
49345ffd83dbSDimitry Andric template void elf::splitSections<ELF64LE>();
49355ffd83dbSDimitry Andric template void elf::splitSections<ELF64BE>();
49360b57cec5SDimitry Andric 
4937e8d8bef9SDimitry Andric template void EhFrameSection::iterateFDEWithLSDA<ELF32LE>(
4938e8d8bef9SDimitry Andric     function_ref<void(InputSection &)>);
4939e8d8bef9SDimitry Andric template void EhFrameSection::iterateFDEWithLSDA<ELF32BE>(
4940e8d8bef9SDimitry Andric     function_ref<void(InputSection &)>);
4941e8d8bef9SDimitry Andric template void EhFrameSection::iterateFDEWithLSDA<ELF64LE>(
4942e8d8bef9SDimitry Andric     function_ref<void(InputSection &)>);
4943e8d8bef9SDimitry Andric template void EhFrameSection::iterateFDEWithLSDA<ELF64BE>(
4944e8d8bef9SDimitry Andric     function_ref<void(InputSection &)>);
4945e8d8bef9SDimitry Andric 
49465ffd83dbSDimitry Andric template class elf::SymbolTableSection<ELF32LE>;
49475ffd83dbSDimitry Andric template class elf::SymbolTableSection<ELF32BE>;
49485ffd83dbSDimitry Andric template class elf::SymbolTableSection<ELF64LE>;
49495ffd83dbSDimitry Andric template class elf::SymbolTableSection<ELF64BE>;
49500b57cec5SDimitry Andric 
49515ffd83dbSDimitry Andric template void elf::writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
49525ffd83dbSDimitry Andric template void elf::writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
49535ffd83dbSDimitry Andric template void elf::writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
49545ffd83dbSDimitry Andric template void elf::writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
49550b57cec5SDimitry Andric 
49565ffd83dbSDimitry Andric template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
49575ffd83dbSDimitry Andric template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
49585ffd83dbSDimitry Andric template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
49595ffd83dbSDimitry Andric template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
49600b57cec5SDimitry Andric 
49610fca6ea1SDimitry Andric template void elf::createSyntheticSections<ELF32LE>();
49620fca6ea1SDimitry Andric template void elf::createSyntheticSections<ELF32BE>();
49630fca6ea1SDimitry Andric template void elf::createSyntheticSections<ELF64LE>();
49640fca6ea1SDimitry Andric template void elf::createSyntheticSections<ELF64BE>();
4965