1ece8a530Spatrick //===- Writer.cpp ---------------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick
9ece8a530Spatrick #include "Writer.h"
10ece8a530Spatrick #include "AArch64ErrataFix.h"
11ece8a530Spatrick #include "ARMErrataFix.h"
12ece8a530Spatrick #include "CallGraphSort.h"
13ece8a530Spatrick #include "Config.h"
1405edf1c1Srobert #include "InputFiles.h"
15ece8a530Spatrick #include "LinkerScript.h"
16ece8a530Spatrick #include "MapFile.h"
17ece8a530Spatrick #include "OutputSections.h"
18ece8a530Spatrick #include "Relocations.h"
19ece8a530Spatrick #include "SymbolTable.h"
20ece8a530Spatrick #include "Symbols.h"
21ece8a530Spatrick #include "SyntheticSections.h"
22ece8a530Spatrick #include "Target.h"
23a0747c9fSpatrick #include "lld/Common/Arrays.h"
2405edf1c1Srobert #include "lld/Common/CommonLinkerContext.h"
25ece8a530Spatrick #include "lld/Common/Filesystem.h"
26ece8a530Spatrick #include "lld/Common/Strings.h"
27ece8a530Spatrick #include "llvm/ADT/StringMap.h"
2805edf1c1Srobert #include "llvm/Support/BLAKE3.h"
29bb684c34Spatrick #include "llvm/Support/Parallel.h"
30ece8a530Spatrick #include "llvm/Support/RandomNumberGenerator.h"
31bb684c34Spatrick #include "llvm/Support/TimeProfiler.h"
32ece8a530Spatrick #include "llvm/Support/xxhash.h"
33ece8a530Spatrick #include <climits>
34ece8a530Spatrick
35bb684c34Spatrick #define DEBUG_TYPE "lld"
36bb684c34Spatrick
37ece8a530Spatrick using namespace llvm;
38ece8a530Spatrick using namespace llvm::ELF;
39ece8a530Spatrick using namespace llvm::object;
40ece8a530Spatrick using namespace llvm::support;
41ece8a530Spatrick using namespace llvm::support::endian;
42bb684c34Spatrick using namespace lld;
43bb684c34Spatrick using namespace lld::elf;
44ece8a530Spatrick
45ece8a530Spatrick namespace {
46ece8a530Spatrick // The writer writes a SymbolTable result to a file.
47ece8a530Spatrick template <class ELFT> class Writer {
48ece8a530Spatrick public:
49a0747c9fSpatrick LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
50a0747c9fSpatrick
Writer()51ece8a530Spatrick Writer() : buffer(errorHandler().outputBuffer) {}
52ece8a530Spatrick
53ece8a530Spatrick void run();
54ece8a530Spatrick
55ece8a530Spatrick private:
56ece8a530Spatrick void copyLocalSymbols();
57ece8a530Spatrick void addSectionSymbols();
58ece8a530Spatrick void sortSections();
59ece8a530Spatrick void resolveShfLinkOrder();
60ece8a530Spatrick void finalizeAddressDependentContent();
61bb684c34Spatrick void optimizeBasicBlockJumps();
62ece8a530Spatrick void sortInputSections();
63ece8a530Spatrick void finalizeSections();
64ece8a530Spatrick void checkExecuteOnly();
65ece8a530Spatrick void setReservedSymbolSections();
66ece8a530Spatrick
6705edf1c1Srobert SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);
68ece8a530Spatrick void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
69ece8a530Spatrick unsigned pFlags);
70ece8a530Spatrick void assignFileOffsets();
71ece8a530Spatrick void assignFileOffsetsBinary();
72ece8a530Spatrick void setPhdrs(Partition &part);
73ece8a530Spatrick void checkSections();
74ece8a530Spatrick void fixSectionAlignments();
75ece8a530Spatrick void openFile();
76ece8a530Spatrick void writeTrapInstr();
77ece8a530Spatrick void writeHeader();
78ece8a530Spatrick void writeSections();
79ece8a530Spatrick void writeSectionsBinary();
80ece8a530Spatrick void writeBuildId();
81ece8a530Spatrick
82ece8a530Spatrick std::unique_ptr<FileOutputBuffer> &buffer;
83ece8a530Spatrick
84ece8a530Spatrick void addRelIpltSymbols();
85ece8a530Spatrick void addStartEndSymbols();
8605edf1c1Srobert void addStartStopSymbols(OutputSection &osec);
87ece8a530Spatrick
88ece8a530Spatrick uint64_t fileSize;
89ece8a530Spatrick uint64_t sectionHeaderOff;
90ece8a530Spatrick };
91ece8a530Spatrick } // anonymous namespace
92ece8a530Spatrick
needsInterpSection()93ece8a530Spatrick static bool needsInterpSection() {
94ece8a530Spatrick return !config->relocatable && !config->shared &&
95ece8a530Spatrick !config->dynamicLinker.empty() && script->needsInterpSection();
96ece8a530Spatrick }
97ece8a530Spatrick
writeResult()98bb684c34Spatrick template <class ELFT> void elf::writeResult() {
99bb684c34Spatrick Writer<ELFT>().run();
100ece8a530Spatrick }
101ece8a530Spatrick
removeEmptyPTLoad(SmallVector<PhdrEntry *,0> & phdrs)10205edf1c1Srobert static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {
103bb684c34Spatrick auto it = std::stable_partition(
104bb684c34Spatrick phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
105bb684c34Spatrick if (p->p_type != PT_LOAD)
106bb684c34Spatrick return true;
107bb684c34Spatrick if (!p->firstSec)
108bb684c34Spatrick return false;
109bb684c34Spatrick uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
110bb684c34Spatrick return size != 0;
111bb684c34Spatrick });
112bb684c34Spatrick
113bb684c34Spatrick // Clear OutputSection::ptLoad for sections contained in removed
114bb684c34Spatrick // segments.
115bb684c34Spatrick DenseSet<PhdrEntry *> removed(it, phdrs.end());
116bb684c34Spatrick for (OutputSection *sec : outputSections)
117bb684c34Spatrick if (removed.count(sec->ptLoad))
118bb684c34Spatrick sec->ptLoad = nullptr;
119bb684c34Spatrick phdrs.erase(it, phdrs.end());
120bb684c34Spatrick }
121bb684c34Spatrick
copySectionsIntoPartitions()122bb684c34Spatrick void elf::copySectionsIntoPartitions() {
12305edf1c1Srobert SmallVector<InputSectionBase *, 0> newSections;
12405edf1c1Srobert const size_t ehSize = ctx.ehInputSections.size();
125ece8a530Spatrick for (unsigned part = 2; part != partitions.size() + 1; ++part) {
12605edf1c1Srobert for (InputSectionBase *s : ctx.inputSections) {
12705edf1c1Srobert if (!(s->flags & SHF_ALLOC) || !s->isLive() || s->type != SHT_NOTE)
128ece8a530Spatrick continue;
12905edf1c1Srobert auto *copy = make<InputSection>(cast<InputSection>(*s));
130ece8a530Spatrick copy->partition = part;
131ece8a530Spatrick newSections.push_back(copy);
132ece8a530Spatrick }
13305edf1c1Srobert for (size_t i = 0; i != ehSize; ++i) {
13405edf1c1Srobert assert(ctx.ehInputSections[i]->isLive());
13505edf1c1Srobert auto *copy = make<EhInputSection>(*ctx.ehInputSections[i]);
13605edf1c1Srobert copy->partition = part;
13705edf1c1Srobert ctx.ehInputSections.push_back(copy);
13805edf1c1Srobert }
139ece8a530Spatrick }
140ece8a530Spatrick
14105edf1c1Srobert ctx.inputSections.insert(ctx.inputSections.end(), newSections.begin(),
142ece8a530Spatrick newSections.end());
143ece8a530Spatrick }
144ece8a530Spatrick
addOptionalRegular(StringRef name,SectionBase * sec,uint64_t val,uint8_t stOther=STV_HIDDEN)145ece8a530Spatrick static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
14605edf1c1Srobert uint64_t val, uint8_t stOther = STV_HIDDEN) {
14705edf1c1Srobert Symbol *s = symtab.find(name);
14805edf1c1Srobert if (!s || s->isDefined() || s->isCommon())
149ece8a530Spatrick return nullptr;
150ece8a530Spatrick
15105edf1c1Srobert s->resolve(Defined{nullptr, StringRef(), STB_GLOBAL, stOther, STT_NOTYPE, val,
152ece8a530Spatrick /*size=*/0, sec});
15305edf1c1Srobert s->isUsedInRegularObj = true;
154ece8a530Spatrick return cast<Defined>(s);
155ece8a530Spatrick }
156ece8a530Spatrick
addAbsolute(StringRef name)157ece8a530Spatrick static Defined *addAbsolute(StringRef name) {
15805edf1c1Srobert Symbol *sym = symtab.addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
159ece8a530Spatrick STT_NOTYPE, 0, 0, nullptr});
16005edf1c1Srobert sym->isUsedInRegularObj = true;
161ece8a530Spatrick return cast<Defined>(sym);
162ece8a530Spatrick }
163ece8a530Spatrick
164ece8a530Spatrick // The linker is expected to define some symbols depending on
165ece8a530Spatrick // the linking result. This function defines such symbols.
addReservedSymbols()166bb684c34Spatrick void elf::addReservedSymbols() {
167ece8a530Spatrick if (config->emachine == EM_MIPS) {
168ece8a530Spatrick // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
169ece8a530Spatrick // so that it points to an absolute address which by default is relative
170ece8a530Spatrick // to GOT. Default offset is 0x7ff0.
171ece8a530Spatrick // See "Global Data Symbols" in Chapter 6 in the following document:
172ece8a530Spatrick // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
173ece8a530Spatrick ElfSym::mipsGp = addAbsolute("_gp");
174ece8a530Spatrick
175ece8a530Spatrick // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
176ece8a530Spatrick // start of function and 'gp' pointer into GOT.
17705edf1c1Srobert if (symtab.find("_gp_disp"))
178ece8a530Spatrick ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
179ece8a530Spatrick
180ece8a530Spatrick // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
181ece8a530Spatrick // pointer. This symbol is used in the code generated by .cpload pseudo-op
182ece8a530Spatrick // in case of using -mno-shared option.
183ece8a530Spatrick // https://sourceware.org/ml/binutils/2004-12/msg00094.html
18405edf1c1Srobert if (symtab.find("__gnu_local_gp"))
185ece8a530Spatrick ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
186ece8a530Spatrick } else if (config->emachine == EM_PPC) {
187ece8a530Spatrick // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
188ece8a530Spatrick // support Small Data Area, define it arbitrarily as 0.
189ece8a530Spatrick addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
190bb684c34Spatrick } else if (config->emachine == EM_PPC64) {
191bb684c34Spatrick addPPC64SaveRestore();
192ece8a530Spatrick }
193ece8a530Spatrick
194ece8a530Spatrick // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
195ece8a530Spatrick // combines the typical ELF GOT with the small data sections. It commonly
196ece8a530Spatrick // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
197ece8a530Spatrick // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
198ece8a530Spatrick // represent the TOC base which is offset by 0x8000 bytes from the start of
199ece8a530Spatrick // the .got section.
200ece8a530Spatrick // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
201ece8a530Spatrick // correctness of some relocations depends on its value.
202ece8a530Spatrick StringRef gotSymName =
203ece8a530Spatrick (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
204ece8a530Spatrick
20505edf1c1Srobert if (Symbol *s = symtab.find(gotSymName)) {
206ece8a530Spatrick if (s->isDefined()) {
207ece8a530Spatrick error(toString(s->file) + " cannot redefine linker defined symbol '" +
208ece8a530Spatrick gotSymName + "'");
209ece8a530Spatrick return;
210ece8a530Spatrick }
211ece8a530Spatrick
212ece8a530Spatrick uint64_t gotOff = 0;
213ece8a530Spatrick if (config->emachine == EM_PPC64)
214ece8a530Spatrick gotOff = 0x8000;
215ece8a530Spatrick
21605edf1c1Srobert s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
217ece8a530Spatrick STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
218ece8a530Spatrick ElfSym::globalOffsetTable = cast<Defined>(s);
219ece8a530Spatrick }
220ece8a530Spatrick
221ece8a530Spatrick // __ehdr_start is the location of ELF file headers. Note that we define
222ece8a530Spatrick // this symbol unconditionally even when using a linker script, which
223ece8a530Spatrick // differs from the behavior implemented by GNU linker which only define
224ece8a530Spatrick // this symbol if ELF headers are in the memory mapped segment.
225ece8a530Spatrick addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
226ece8a530Spatrick
227ece8a530Spatrick // __executable_start is not documented, but the expectation of at
228ece8a530Spatrick // least the Android libc is that it points to the ELF header.
229ece8a530Spatrick addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
230ece8a530Spatrick
231ece8a530Spatrick // __dso_handle symbol is passed to cxa_finalize as a marker to identify
232ece8a530Spatrick // each DSO. The address of the symbol doesn't matter as long as they are
233ece8a530Spatrick // different in different DSOs, so we chose the start address of the DSO.
234ece8a530Spatrick addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
235ece8a530Spatrick
236ece8a530Spatrick // If linker script do layout we do not need to create any standard symbols.
237ece8a530Spatrick if (script->hasSectionsCommand)
238ece8a530Spatrick return;
239ece8a530Spatrick
240ece8a530Spatrick auto add = [](StringRef s, int64_t pos) {
241ece8a530Spatrick return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
242ece8a530Spatrick };
243ece8a530Spatrick
244ece8a530Spatrick ElfSym::bss = add("__bss_start", 0);
245adae0cfdSpatrick ElfSym::data = add("__data_start", 0);
246ece8a530Spatrick ElfSym::end1 = add("end", -1);
247ece8a530Spatrick ElfSym::end2 = add("_end", -1);
248ece8a530Spatrick ElfSym::etext1 = add("etext", -1);
249ece8a530Spatrick ElfSym::etext2 = add("_etext", -1);
250ece8a530Spatrick ElfSym::edata1 = add("edata", -1);
251ece8a530Spatrick ElfSym::edata2 = add("_edata", -1);
252ece8a530Spatrick }
253ece8a530Spatrick
findSection(StringRef name,unsigned partition=1)254ece8a530Spatrick static OutputSection *findSection(StringRef name, unsigned partition = 1) {
25505edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
25605edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd))
25705edf1c1Srobert if (osd->osec.name == name && osd->osec.partition == partition)
25805edf1c1Srobert return &osd->osec;
259ece8a530Spatrick return nullptr;
260ece8a530Spatrick }
261ece8a530Spatrick
createSyntheticSections()262bb684c34Spatrick template <class ELFT> void elf::createSyntheticSections() {
263ece8a530Spatrick // Initialize all pointers with NULL. This is needed because
264ece8a530Spatrick // you can call lld::elf::main more than once as a library.
26505edf1c1Srobert Out::tlsPhdr = nullptr;
26605edf1c1Srobert Out::preinitArray = nullptr;
26705edf1c1Srobert Out::initArray = nullptr;
26805edf1c1Srobert Out::finiArray = nullptr;
269ece8a530Spatrick
270ece8a530Spatrick // Add the .interp section first because it is not a SyntheticSection.
271ece8a530Spatrick // The removeUnusedSyntheticSections() function relies on the
272ece8a530Spatrick // SyntheticSections coming last.
273ece8a530Spatrick if (needsInterpSection()) {
274ece8a530Spatrick for (size_t i = 1; i <= partitions.size(); ++i) {
275ece8a530Spatrick InputSection *sec = createInterpSection();
276ece8a530Spatrick sec->partition = i;
27705edf1c1Srobert ctx.inputSections.push_back(sec);
278ece8a530Spatrick }
279ece8a530Spatrick }
280ece8a530Spatrick
28105edf1c1Srobert auto add = [](SyntheticSection &sec) { ctx.inputSections.push_back(&sec); };
282ece8a530Spatrick
28305edf1c1Srobert in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
284ece8a530Spatrick
285ece8a530Spatrick Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
28605edf1c1Srobert Out::programHeaders->addralign = config->wordsize;
287ece8a530Spatrick
288ece8a530Spatrick if (config->strip != StripPolicy::All) {
28905edf1c1Srobert in.strTab = std::make_unique<StringTableSection>(".strtab", false);
29005edf1c1Srobert in.symTab = std::make_unique<SymbolTableSection<ELFT>>(*in.strTab);
29105edf1c1Srobert in.symTabShndx = std::make_unique<SymtabShndxSection>();
292ece8a530Spatrick }
293ece8a530Spatrick
29405edf1c1Srobert in.bss = std::make_unique<BssSection>(".bss", 0, 1);
29505edf1c1Srobert add(*in.bss);
296ece8a530Spatrick
297ece8a530Spatrick // If there is a SECTIONS command and a .data.rel.ro section name use name
298ece8a530Spatrick // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
299ece8a530Spatrick // This makes sure our relro is contiguous.
30005edf1c1Srobert bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro");
30105edf1c1Srobert in.bssRelRo = std::make_unique<BssSection>(
30205edf1c1Srobert hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
30305edf1c1Srobert add(*in.bssRelRo);
304ece8a530Spatrick
305ece8a530Spatrick // Add MIPS-specific sections.
306ece8a530Spatrick if (config->emachine == EM_MIPS) {
307ece8a530Spatrick if (!config->shared && config->hasDynSymTab) {
30805edf1c1Srobert in.mipsRldMap = std::make_unique<MipsRldMapSection>();
30905edf1c1Srobert add(*in.mipsRldMap);
310ece8a530Spatrick }
31105edf1c1Srobert if ((in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create()))
31205edf1c1Srobert add(*in.mipsAbiFlags);
31305edf1c1Srobert if ((in.mipsOptions = MipsOptionsSection<ELFT>::create()))
31405edf1c1Srobert add(*in.mipsOptions);
31505edf1c1Srobert if ((in.mipsReginfo = MipsReginfoSection<ELFT>::create()))
31605edf1c1Srobert add(*in.mipsReginfo);
317ece8a530Spatrick }
318ece8a530Spatrick
319ece8a530Spatrick StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
320ece8a530Spatrick
32105edf1c1Srobert const unsigned threadCount = config->threadCount;
322ece8a530Spatrick for (Partition &part : partitions) {
32305edf1c1Srobert auto add = [&](SyntheticSection &sec) {
32405edf1c1Srobert sec.partition = part.getNumber();
32505edf1c1Srobert ctx.inputSections.push_back(&sec);
326ece8a530Spatrick };
327ece8a530Spatrick
328ece8a530Spatrick if (!part.name.empty()) {
32905edf1c1Srobert part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
330ece8a530Spatrick part.elfHeader->name = part.name;
33105edf1c1Srobert add(*part.elfHeader);
332ece8a530Spatrick
33305edf1c1Srobert part.programHeaders =
33405edf1c1Srobert std::make_unique<PartitionProgramHeadersSection<ELFT>>();
33505edf1c1Srobert add(*part.programHeaders);
336ece8a530Spatrick }
337ece8a530Spatrick
338ece8a530Spatrick if (config->buildId != BuildIdKind::None) {
33905edf1c1Srobert part.buildId = std::make_unique<BuildIdSection>();
34005edf1c1Srobert add(*part.buildId);
341ece8a530Spatrick }
342ece8a530Spatrick
34305edf1c1Srobert part.dynStrTab = std::make_unique<StringTableSection>(".dynstr", true);
34405edf1c1Srobert part.dynSymTab =
34505edf1c1Srobert std::make_unique<SymbolTableSection<ELFT>>(*part.dynStrTab);
34605edf1c1Srobert part.dynamic = std::make_unique<DynamicSection<ELFT>>();
34705edf1c1Srobert
34805edf1c1Srobert if (config->emachine == EM_AARCH64 &&
34905edf1c1Srobert config->androidMemtagMode != ELF::NT_MEMTAG_LEVEL_NONE) {
35005edf1c1Srobert part.memtagAndroidNote = std::make_unique<MemtagAndroidNote>();
35105edf1c1Srobert add(*part.memtagAndroidNote);
35205edf1c1Srobert }
35305edf1c1Srobert
354ece8a530Spatrick if (config->androidPackDynRelocs)
35505edf1c1Srobert part.relaDyn = std::make_unique<AndroidPackedRelocationSection<ELFT>>(
35605edf1c1Srobert relaDynName, threadCount);
357ece8a530Spatrick else
35805edf1c1Srobert part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
35905edf1c1Srobert relaDynName, config->zCombreloc, threadCount);
360ece8a530Spatrick
361ece8a530Spatrick if (config->hasDynSymTab) {
36205edf1c1Srobert add(*part.dynSymTab);
363ece8a530Spatrick
36405edf1c1Srobert part.verSym = std::make_unique<VersionTableSection>();
36505edf1c1Srobert add(*part.verSym);
366ece8a530Spatrick
367ece8a530Spatrick if (!namedVersionDefs().empty()) {
36805edf1c1Srobert part.verDef = std::make_unique<VersionDefinitionSection>();
36905edf1c1Srobert add(*part.verDef);
370ece8a530Spatrick }
371ece8a530Spatrick
37205edf1c1Srobert part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
37305edf1c1Srobert add(*part.verNeed);
374ece8a530Spatrick
375ece8a530Spatrick if (config->gnuHash) {
37605edf1c1Srobert part.gnuHashTab = std::make_unique<GnuHashTableSection>();
37705edf1c1Srobert add(*part.gnuHashTab);
378ece8a530Spatrick }
379ece8a530Spatrick
380ece8a530Spatrick if (config->sysvHash) {
38105edf1c1Srobert part.hashTab = std::make_unique<HashTableSection>();
38205edf1c1Srobert add(*part.hashTab);
383ece8a530Spatrick }
384ece8a530Spatrick
38505edf1c1Srobert add(*part.dynamic);
38605edf1c1Srobert add(*part.dynStrTab);
38705edf1c1Srobert add(*part.relaDyn);
388ece8a530Spatrick }
389ece8a530Spatrick
390ece8a530Spatrick if (config->relrPackDynRelocs) {
39105edf1c1Srobert part.relrDyn = std::make_unique<RelrSection<ELFT>>(threadCount);
39205edf1c1Srobert add(*part.relrDyn);
393ece8a530Spatrick }
394ece8a530Spatrick
395ece8a530Spatrick if (!config->relocatable) {
396ece8a530Spatrick if (config->ehFrameHdr) {
39705edf1c1Srobert part.ehFrameHdr = std::make_unique<EhFrameHeader>();
39805edf1c1Srobert add(*part.ehFrameHdr);
399ece8a530Spatrick }
40005edf1c1Srobert part.ehFrame = std::make_unique<EhFrameSection>();
40105edf1c1Srobert add(*part.ehFrame);
40205edf1c1Srobert
40305edf1c1Srobert if (config->emachine == EM_ARM) {
40405edf1c1Srobert // This section replaces all the individual .ARM.exidx InputSections.
40505edf1c1Srobert part.armExidx = std::make_unique<ARMExidxSyntheticSection>();
40605edf1c1Srobert add(*part.armExidx);
40705edf1c1Srobert }
408ece8a530Spatrick }
409ece8a530Spatrick
41005edf1c1Srobert if (!config->packageMetadata.empty()) {
41105edf1c1Srobert part.packageMetadataNote = std::make_unique<PackageMetadataNote>();
41205edf1c1Srobert add(*part.packageMetadataNote);
413ece8a530Spatrick }
414ece8a530Spatrick }
415ece8a530Spatrick
416ece8a530Spatrick if (partitions.size() != 1) {
417ece8a530Spatrick // Create the partition end marker. This needs to be in partition number 255
418ece8a530Spatrick // so that it is sorted after all other partitions. It also has other
419ece8a530Spatrick // special handling (see createPhdrs() and combineEhSections()).
42005edf1c1Srobert in.partEnd =
42105edf1c1Srobert std::make_unique<BssSection>(".part.end", config->maxPageSize, 1);
422ece8a530Spatrick in.partEnd->partition = 255;
42305edf1c1Srobert add(*in.partEnd);
424ece8a530Spatrick
42505edf1c1Srobert in.partIndex = std::make_unique<PartitionIndexSection>();
42605edf1c1Srobert addOptionalRegular("__part_index_begin", in.partIndex.get(), 0);
42705edf1c1Srobert addOptionalRegular("__part_index_end", in.partIndex.get(),
428ece8a530Spatrick in.partIndex->getSize());
42905edf1c1Srobert add(*in.partIndex);
430ece8a530Spatrick }
431ece8a530Spatrick
432ece8a530Spatrick // Add .got. MIPS' .got is so different from the other archs,
433ece8a530Spatrick // it has its own class.
434ece8a530Spatrick if (config->emachine == EM_MIPS) {
43505edf1c1Srobert in.mipsGot = std::make_unique<MipsGotSection>();
43605edf1c1Srobert add(*in.mipsGot);
437ece8a530Spatrick } else {
43805edf1c1Srobert in.got = std::make_unique<GotSection>();
43905edf1c1Srobert add(*in.got);
440ece8a530Spatrick }
441ece8a530Spatrick
442ece8a530Spatrick if (config->emachine == EM_PPC) {
44305edf1c1Srobert in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
44405edf1c1Srobert add(*in.ppc32Got2);
445ece8a530Spatrick }
446ece8a530Spatrick
447ece8a530Spatrick if (config->emachine == EM_PPC64) {
44805edf1c1Srobert in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
44905edf1c1Srobert add(*in.ppc64LongBranchTarget);
450ece8a530Spatrick }
451ece8a530Spatrick
45205edf1c1Srobert in.gotPlt = std::make_unique<GotPltSection>();
45305edf1c1Srobert add(*in.gotPlt);
45405edf1c1Srobert in.igotPlt = std::make_unique<IgotPltSection>();
45505edf1c1Srobert add(*in.igotPlt);
456ece8a530Spatrick
457ece8a530Spatrick // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
458ece8a530Spatrick // it as a relocation and ensure the referenced section is created.
459ece8a530Spatrick if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
460ece8a530Spatrick if (target->gotBaseSymInGotPlt)
461ece8a530Spatrick in.gotPlt->hasGotPltOffRel = true;
462ece8a530Spatrick else
463ece8a530Spatrick in.got->hasGotOffRel = true;
464ece8a530Spatrick }
465ece8a530Spatrick
466ece8a530Spatrick if (config->gdbIndex)
46705edf1c1Srobert add(*GdbIndexSection::create<ELFT>());
468ece8a530Spatrick
469ece8a530Spatrick // We always need to add rel[a].plt to output if it has entries.
470ece8a530Spatrick // Even for static linking it can contain R_[*]_IRELATIVE relocations.
47105edf1c1Srobert in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
47205edf1c1Srobert config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false,
47305edf1c1Srobert /*threadCount=*/1);
47405edf1c1Srobert add(*in.relaPlt);
475ece8a530Spatrick
476ece8a530Spatrick // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
477ece8a530Spatrick // relocations are processed last by the dynamic loader. We cannot place the
478ece8a530Spatrick // iplt section in .rel.dyn when Android relocation packing is enabled because
479ece8a530Spatrick // that would cause a section type mismatch. However, because the Android
480ece8a530Spatrick // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
481ece8a530Spatrick // behaviour by placing the iplt section in .rel.plt.
48205edf1c1Srobert in.relaIplt = std::make_unique<RelocationSection<ELFT>>(
483ece8a530Spatrick config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
48405edf1c1Srobert /*sort=*/false, /*threadCount=*/1);
48505edf1c1Srobert add(*in.relaIplt);
486ece8a530Spatrick
487ece8a530Spatrick if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
488ece8a530Spatrick (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
48905edf1c1Srobert in.ibtPlt = std::make_unique<IBTPltSection>();
49005edf1c1Srobert add(*in.ibtPlt);
491ece8a530Spatrick }
492*293d5193Skettenis #ifdef __OpenBSD__
493*293d5193Skettenis else if (config->emachine == EM_X86_64) {
494*293d5193Skettenis in.ibtPlt = std::make_unique<IBTPltSection>();
495*293d5193Skettenis add(*in.ibtPlt);
496*293d5193Skettenis }
497*293d5193Skettenis #endif
498ece8a530Spatrick
49905edf1c1Srobert if (config->emachine == EM_PPC)
50005edf1c1Srobert in.plt = std::make_unique<PPC32GlinkSection>();
50105edf1c1Srobert else
50205edf1c1Srobert in.plt = std::make_unique<PltSection>();
50305edf1c1Srobert add(*in.plt);
50405edf1c1Srobert in.iplt = std::make_unique<IpltSection>();
50505edf1c1Srobert add(*in.iplt);
506ece8a530Spatrick
507ece8a530Spatrick if (config->andFeatures)
50805edf1c1Srobert add(*make<GnuPropertySection>());
509ece8a530Spatrick
510ece8a530Spatrick // .note.GNU-stack is always added when we are creating a re-linkable
511ece8a530Spatrick // object file. Other linkers are using the presence of this marker
512ece8a530Spatrick // section to control the executable-ness of the stack area, but that
513ece8a530Spatrick // is irrelevant these days. Stack area should always be non-executable
514ece8a530Spatrick // by default. So we emit this section unconditionally.
515ece8a530Spatrick if (config->relocatable)
51605edf1c1Srobert add(*make<GnuStackSection>());
517ece8a530Spatrick
518ece8a530Spatrick if (in.symTab)
51905edf1c1Srobert add(*in.symTab);
520ece8a530Spatrick if (in.symTabShndx)
52105edf1c1Srobert add(*in.symTabShndx);
52205edf1c1Srobert add(*in.shStrTab);
523ece8a530Spatrick if (in.strTab)
52405edf1c1Srobert add(*in.strTab);
525ece8a530Spatrick }
526ece8a530Spatrick
527ece8a530Spatrick // The main function of the writer.
run()528ece8a530Spatrick template <class ELFT> void Writer<ELFT>::run() {
529ece8a530Spatrick copyLocalSymbols();
530ece8a530Spatrick
531ece8a530Spatrick if (config->copyRelocs)
532ece8a530Spatrick addSectionSymbols();
533ece8a530Spatrick
534ece8a530Spatrick // Now that we have a complete set of output sections. This function
535ece8a530Spatrick // completes section contents. For example, we need to add strings
536ece8a530Spatrick // to the string table, and add entries to .got and .plt.
537ece8a530Spatrick // finalizeSections does that.
538ece8a530Spatrick finalizeSections();
539ece8a530Spatrick checkExecuteOnly();
540ece8a530Spatrick
54105edf1c1Srobert // If --compressed-debug-sections is specified, compress .debug_* sections.
54205edf1c1Srobert // Do it right now because it changes the size of output sections.
543ece8a530Spatrick for (OutputSection *sec : outputSections)
544ece8a530Spatrick sec->maybeCompress<ELFT>();
545ece8a530Spatrick
546ece8a530Spatrick if (script->hasSectionsCommand)
547ece8a530Spatrick script->allocateHeaders(mainPart->phdrs);
548ece8a530Spatrick
549ece8a530Spatrick // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
550ece8a530Spatrick // 0 sized region. This has to be done late since only after assignAddresses
551ece8a530Spatrick // we know the size of the sections.
552ece8a530Spatrick for (Partition &part : partitions)
553ece8a530Spatrick removeEmptyPTLoad(part.phdrs);
554ece8a530Spatrick
555ece8a530Spatrick if (!config->oFormatBinary)
556ece8a530Spatrick assignFileOffsets();
557ece8a530Spatrick else
558ece8a530Spatrick assignFileOffsetsBinary();
559ece8a530Spatrick
560ece8a530Spatrick for (Partition &part : partitions)
561ece8a530Spatrick setPhdrs(part);
562ece8a530Spatrick
56305edf1c1Srobert // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
56405edf1c1Srobert // because the files may be useful in case checkSections() or openFile()
56505edf1c1Srobert // fails, for example, due to an erroneous file size.
56605edf1c1Srobert writeMapAndCref();
567bb684c34Spatrick
568ece8a530Spatrick if (config->checkSections)
569ece8a530Spatrick checkSections();
570ece8a530Spatrick
571ece8a530Spatrick // It does not make sense try to open the file if we have error already.
572ece8a530Spatrick if (errorCount())
573ece8a530Spatrick return;
574a0747c9fSpatrick
575a0747c9fSpatrick {
576a0747c9fSpatrick llvm::TimeTraceScope timeScope("Write output file");
577ece8a530Spatrick // Write the result down to a file.
578ece8a530Spatrick openFile();
579ece8a530Spatrick if (errorCount())
580ece8a530Spatrick return;
581ece8a530Spatrick
582ece8a530Spatrick if (!config->oFormatBinary) {
583ece8a530Spatrick if (config->zSeparate != SeparateSegmentKind::None)
584ece8a530Spatrick writeTrapInstr();
585ece8a530Spatrick writeHeader();
586ece8a530Spatrick writeSections();
587ece8a530Spatrick } else {
588ece8a530Spatrick writeSectionsBinary();
589ece8a530Spatrick }
590ece8a530Spatrick
591ece8a530Spatrick // Backfill .note.gnu.build-id section content. This is done at last
592ece8a530Spatrick // because the content is usually a hash value of the entire output file.
593ece8a530Spatrick writeBuildId();
594ece8a530Spatrick if (errorCount())
595ece8a530Spatrick return;
596ece8a530Spatrick
597ece8a530Spatrick if (auto e = buffer->commit())
59805edf1c1Srobert fatal("failed to write output '" + buffer->getPath() +
59905edf1c1Srobert "': " + toString(std::move(e)));
600ece8a530Spatrick }
601a0747c9fSpatrick }
602ece8a530Spatrick
603bb684c34Spatrick template <class ELFT, class RelTy>
markUsedLocalSymbolsImpl(ObjFile<ELFT> * file,llvm::ArrayRef<RelTy> rels)604bb684c34Spatrick static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
605bb684c34Spatrick llvm::ArrayRef<RelTy> rels) {
606bb684c34Spatrick for (const RelTy &rel : rels) {
607bb684c34Spatrick Symbol &sym = file->getRelocTargetSym(rel);
608bb684c34Spatrick if (sym.isLocal())
609bb684c34Spatrick sym.used = true;
610bb684c34Spatrick }
611bb684c34Spatrick }
612bb684c34Spatrick
613bb684c34Spatrick // The function ensures that the "used" field of local symbols reflects the fact
614bb684c34Spatrick // that the symbol is used in a relocation from a live section.
markUsedLocalSymbols()615bb684c34Spatrick template <class ELFT> static void markUsedLocalSymbols() {
616bb684c34Spatrick // With --gc-sections, the field is already filled.
617bb684c34Spatrick // See MarkLive<ELFT>::resolveReloc().
618bb684c34Spatrick if (config->gcSections)
619bb684c34Spatrick return;
62005edf1c1Srobert for (ELFFileBase *file : ctx.objectFiles) {
621bb684c34Spatrick ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
622bb684c34Spatrick for (InputSectionBase *s : f->getSections()) {
623bb684c34Spatrick InputSection *isec = dyn_cast_or_null<InputSection>(s);
624bb684c34Spatrick if (!isec)
625bb684c34Spatrick continue;
626bb684c34Spatrick if (isec->type == SHT_REL)
627bb684c34Spatrick markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
628bb684c34Spatrick else if (isec->type == SHT_RELA)
629bb684c34Spatrick markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
630bb684c34Spatrick }
631bb684c34Spatrick }
632bb684c34Spatrick }
633bb684c34Spatrick
shouldKeepInSymtab(const Defined & sym)634ece8a530Spatrick static bool shouldKeepInSymtab(const Defined &sym) {
635ece8a530Spatrick if (sym.isSection())
636ece8a530Spatrick return false;
637ece8a530Spatrick
638bb684c34Spatrick // If --emit-reloc or -r is given, preserve symbols referenced by relocations
639bb684c34Spatrick // from live sections.
64005edf1c1Srobert if (sym.used && config->copyRelocs)
641ece8a530Spatrick return true;
642ece8a530Spatrick
643bb684c34Spatrick // Exclude local symbols pointing to .ARM.exidx sections.
644bb684c34Spatrick // They are probably mapping symbols "$d", which are optional for these
645bb684c34Spatrick // sections. After merging the .ARM.exidx sections, some of these symbols
646bb684c34Spatrick // may become dangling. The easiest way to avoid the issue is not to add
647bb684c34Spatrick // them to the symbol table from the beginning.
648bb684c34Spatrick if (config->emachine == EM_ARM && sym.section &&
649bb684c34Spatrick sym.section->type == SHT_ARM_EXIDX)
650bb684c34Spatrick return false;
651bb684c34Spatrick
652bb684c34Spatrick if (config->discard == DiscardPolicy::None)
653ece8a530Spatrick return true;
654bb684c34Spatrick if (config->discard == DiscardPolicy::All)
655bb684c34Spatrick return false;
656ece8a530Spatrick
657ece8a530Spatrick // In ELF assembly .L symbols are normally discarded by the assembler.
658ece8a530Spatrick // If the assembler fails to do so, the linker discards them if
659ece8a530Spatrick // * --discard-locals is used.
660ece8a530Spatrick // * The symbol is in a SHF_MERGE section, which is normally the reason for
661ece8a530Spatrick // the assembler keeping the .L symbol.
66205edf1c1Srobert if ((sym.getName().startswith(".L") || sym.getName().empty()) &&
66305edf1c1Srobert (config->discard == DiscardPolicy::Locals ||
66405edf1c1Srobert (sym.section && (sym.section->flags & SHF_MERGE))))
665ece8a530Spatrick return false;
66605edf1c1Srobert return true;
667ece8a530Spatrick }
668ece8a530Spatrick
includeInSymtab(const Symbol & b)669ece8a530Spatrick static bool includeInSymtab(const Symbol &b) {
670ece8a530Spatrick if (auto *d = dyn_cast<Defined>(&b)) {
671ece8a530Spatrick // Always include absolute symbols.
672ece8a530Spatrick SectionBase *sec = d->section;
673ece8a530Spatrick if (!sec)
674ece8a530Spatrick return true;
675ece8a530Spatrick
676ece8a530Spatrick if (auto *s = dyn_cast<MergeInputSection>(sec))
67705edf1c1Srobert return s->getSectionPiece(d->value).live;
67805edf1c1Srobert return sec->isLive();
679ece8a530Spatrick }
68005edf1c1Srobert return b.used || !config->gcSections;
681ece8a530Spatrick }
682ece8a530Spatrick
683ece8a530Spatrick // Local symbols are not in the linker's symbol table. This function scans
684ece8a530Spatrick // each object file's symbol table to copy local symbols to the output.
copyLocalSymbols()685ece8a530Spatrick template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
686ece8a530Spatrick if (!in.symTab)
687ece8a530Spatrick return;
688a0747c9fSpatrick llvm::TimeTraceScope timeScope("Add local symbols");
689bb684c34Spatrick if (config->copyRelocs && config->discard != DiscardPolicy::None)
690bb684c34Spatrick markUsedLocalSymbols<ELFT>();
69105edf1c1Srobert for (ELFFileBase *file : ctx.objectFiles) {
69205edf1c1Srobert for (Symbol *b : file->getLocalSymbols()) {
693bb684c34Spatrick assert(b->isLocal() && "should have been caught in initializeSymbols()");
694ece8a530Spatrick auto *dr = dyn_cast<Defined>(b);
695ece8a530Spatrick
696ece8a530Spatrick // No reason to keep local undefined symbol in symtab.
697ece8a530Spatrick if (!dr)
698ece8a530Spatrick continue;
69905edf1c1Srobert if (includeInSymtab(*b) && shouldKeepInSymtab(*dr))
700ece8a530Spatrick in.symTab->addSymbol(b);
701ece8a530Spatrick }
702ece8a530Spatrick }
703ece8a530Spatrick }
704ece8a530Spatrick
705ece8a530Spatrick // Create a section symbol for each output section so that we can represent
706ece8a530Spatrick // relocations that point to the section. If we know that no relocation is
707ece8a530Spatrick // referring to a section (that happens if the section is a synthetic one), we
708ece8a530Spatrick // don't create a section symbol for that section.
addSectionSymbols()709ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
71005edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands) {
71105edf1c1Srobert auto *osd = dyn_cast<OutputDesc>(cmd);
71205edf1c1Srobert if (!osd)
713ece8a530Spatrick continue;
71405edf1c1Srobert OutputSection &osec = osd->osec;
71505edf1c1Srobert InputSectionBase *isec = nullptr;
71605edf1c1Srobert // Iterate over all input sections and add a STT_SECTION symbol if any input
71705edf1c1Srobert // section may be a relocation target.
71805edf1c1Srobert for (SectionCommand *cmd : osec.commands) {
71905edf1c1Srobert auto *isd = dyn_cast<InputSectionDescription>(cmd);
72005edf1c1Srobert if (!isd)
721ece8a530Spatrick continue;
72205edf1c1Srobert for (InputSectionBase *s : isd->sections) {
723ece8a530Spatrick // Relocations are not using REL[A] section symbols.
72405edf1c1Srobert if (s->type == SHT_REL || s->type == SHT_RELA)
725ece8a530Spatrick continue;
726ece8a530Spatrick
72705edf1c1Srobert // Unlike other synthetic sections, mergeable output sections contain
72805edf1c1Srobert // data copied from input sections, and there may be a relocation
72905edf1c1Srobert // pointing to its contents if -r or --emit-reloc is given.
73005edf1c1Srobert if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))
73105edf1c1Srobert continue;
73205edf1c1Srobert
73305edf1c1Srobert isec = s;
73405edf1c1Srobert break;
73505edf1c1Srobert }
73605edf1c1Srobert }
73705edf1c1Srobert if (!isec)
738ece8a530Spatrick continue;
739ece8a530Spatrick
740a0747c9fSpatrick // Set the symbol to be relative to the output section so that its st_value
741a0747c9fSpatrick // equals the output section address. Note, there may be a gap between the
742a0747c9fSpatrick // start of the output section and isec.
74305edf1c1Srobert in.symTab->addSymbol(makeDefined(isec->file, "", STB_LOCAL, /*stOther=*/0,
74405edf1c1Srobert STT_SECTION,
74505edf1c1Srobert /*value=*/0, /*size=*/0, &osec));
746ece8a530Spatrick }
747ece8a530Spatrick }
748ece8a530Spatrick
749ece8a530Spatrick // Today's loaders have a feature to make segments read-only after
750ece8a530Spatrick // processing dynamic relocations to enhance security. PT_GNU_RELRO
751ece8a530Spatrick // is defined for that.
752ece8a530Spatrick //
753ece8a530Spatrick // This function returns true if a section needs to be put into a
754ece8a530Spatrick // PT_GNU_RELRO segment.
isRelroSection(const OutputSection * sec)755ece8a530Spatrick static bool isRelroSection(const OutputSection *sec) {
756ece8a530Spatrick if (!config->zRelro)
757ece8a530Spatrick return false;
75805edf1c1Srobert if (sec->relro)
75905edf1c1Srobert return true;
760ece8a530Spatrick
761ece8a530Spatrick uint64_t flags = sec->flags;
762ece8a530Spatrick
763ece8a530Spatrick // Non-allocatable or non-writable sections don't need RELRO because
764ece8a530Spatrick // they are not writable or not even mapped to memory in the first place.
765ece8a530Spatrick // RELRO is for sections that are essentially read-only but need to
766ece8a530Spatrick // be writable only at process startup to allow dynamic linker to
767ece8a530Spatrick // apply relocations.
768ece8a530Spatrick if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
769ece8a530Spatrick return false;
770ece8a530Spatrick
771ece8a530Spatrick // Once initialized, TLS data segments are used as data templates
772ece8a530Spatrick // for a thread-local storage. For each new thread, runtime
773ece8a530Spatrick // allocates memory for a TLS and copy templates there. No thread
774ece8a530Spatrick // are supposed to use templates directly. Thus, it can be in RELRO.
775ece8a530Spatrick if (flags & SHF_TLS)
776ece8a530Spatrick return true;
777ece8a530Spatrick
778ece8a530Spatrick // .init_array, .preinit_array and .fini_array contain pointers to
779ece8a530Spatrick // functions that are executed on process startup or exit. These
780ece8a530Spatrick // pointers are set by the static linker, and they are not expected
781ece8a530Spatrick // to change at runtime. But if you are an attacker, you could do
782ece8a530Spatrick // interesting things by manipulating pointers in .fini_array, for
783ece8a530Spatrick // example. So they are put into RELRO.
784ece8a530Spatrick uint32_t type = sec->type;
785ece8a530Spatrick if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
786ece8a530Spatrick type == SHT_PREINIT_ARRAY)
787ece8a530Spatrick return true;
788ece8a530Spatrick
789ece8a530Spatrick // .got contains pointers to external symbols. They are resolved by
790ece8a530Spatrick // the dynamic linker when a module is loaded into memory, and after
791ece8a530Spatrick // that they are not expected to change. So, it can be in RELRO.
792ece8a530Spatrick if (in.got && sec == in.got->getParent())
793ece8a530Spatrick return true;
794ece8a530Spatrick
795ece8a530Spatrick // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
796ece8a530Spatrick // through r2 register, which is reserved for that purpose. Since r2 is used
797ece8a530Spatrick // for accessing .got as well, .got and .toc need to be close enough in the
798ece8a530Spatrick // virtual address space. Usually, .toc comes just after .got. Since we place
799ece8a530Spatrick // .got into RELRO, .toc needs to be placed into RELRO too.
800ece8a530Spatrick if (sec->name.equals(".toc"))
801ece8a530Spatrick return true;
802ece8a530Spatrick
803ece8a530Spatrick // .got.plt contains pointers to external function symbols. They are
804ece8a530Spatrick // by default resolved lazily, so we usually cannot put it into RELRO.
805ece8a530Spatrick // However, if "-z now" is given, the lazy symbol resolution is
806ece8a530Spatrick // disabled, which enables us to put it into RELRO.
807ece8a530Spatrick if (sec == in.gotPlt->getParent())
808adae0cfdSpatrick #ifndef __OpenBSD__
809ece8a530Spatrick return config->zNow;
810adae0cfdSpatrick #else
811adae0cfdSpatrick return true; /* kbind(2) means we can always put these in RELRO */
812adae0cfdSpatrick #endif
813ece8a530Spatrick
814ece8a530Spatrick // .dynamic section contains data for the dynamic linker, and
815ece8a530Spatrick // there's no need to write to it at runtime, so it's better to put
816ece8a530Spatrick // it into RELRO.
817ece8a530Spatrick if (sec->name == ".dynamic")
818ece8a530Spatrick return true;
819ece8a530Spatrick
820ece8a530Spatrick // Sections with some special names are put into RELRO. This is a
821ece8a530Spatrick // bit unfortunate because section names shouldn't be significant in
822ece8a530Spatrick // ELF in spirit. But in reality many linker features depend on
823ece8a530Spatrick // magic section names.
824ece8a530Spatrick StringRef s = sec->name;
825ece8a530Spatrick return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
826ece8a530Spatrick s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
827bb684c34Spatrick s == ".fini_array" || s == ".init_array" ||
828bb684c34Spatrick s == ".openbsd.randomdata" || s == ".preinit_array";
829ece8a530Spatrick }
830ece8a530Spatrick
831ece8a530Spatrick // We compute a rank for each section. The rank indicates where the
832ece8a530Spatrick // section should be placed in the file. Instead of using simple
833ece8a530Spatrick // numbers (0,1,2...), we use a series of flags. One for each decision
834ece8a530Spatrick // point when placing the section.
835ece8a530Spatrick // Using flags has two key properties:
836ece8a530Spatrick // * It is easy to check if a give branch was taken.
837ece8a530Spatrick // * It is easy two see how similar two ranks are (see getRankProximity).
838ece8a530Spatrick enum RankFlags {
839ece8a530Spatrick RF_NOT_ADDR_SET = 1 << 27,
840ece8a530Spatrick RF_NOT_ALLOC = 1 << 26,
841ece8a530Spatrick RF_PARTITION = 1 << 18, // Partition number (8 bits)
842ece8a530Spatrick RF_NOT_PART_EHDR = 1 << 17,
843ece8a530Spatrick RF_NOT_PART_PHDR = 1 << 16,
844ece8a530Spatrick RF_NOT_INTERP = 1 << 15,
845ece8a530Spatrick RF_NOT_NOTE = 1 << 14,
846ece8a530Spatrick RF_WRITE = 1 << 13,
847ece8a530Spatrick RF_EXEC_WRITE = 1 << 12,
848ece8a530Spatrick RF_EXEC = 1 << 11,
849ece8a530Spatrick RF_RODATA = 1 << 10,
850ece8a530Spatrick RF_NOT_RELRO = 1 << 9,
851ece8a530Spatrick RF_NOT_TLS = 1 << 8,
852ece8a530Spatrick RF_BSS = 1 << 7,
853ece8a530Spatrick RF_PPC_NOT_TOCBSS = 1 << 6,
854ece8a530Spatrick RF_PPC_TOCL = 1 << 5,
855ece8a530Spatrick RF_PPC_TOC = 1 << 4,
856ece8a530Spatrick RF_PPC_GOT = 1 << 3,
857ece8a530Spatrick RF_PPC_BRANCH_LT = 1 << 2,
858ece8a530Spatrick RF_MIPS_GPREL = 1 << 1,
859ece8a530Spatrick RF_MIPS_NOT_GOT = 1 << 0
860ece8a530Spatrick };
861ece8a530Spatrick
getSectionRank(const OutputSection & osec)86205edf1c1Srobert static unsigned getSectionRank(const OutputSection &osec) {
86305edf1c1Srobert unsigned rank = osec.partition * RF_PARTITION;
864ece8a530Spatrick
865ece8a530Spatrick // We want to put section specified by -T option first, so we
866ece8a530Spatrick // can start assigning VA starting from them later.
86705edf1c1Srobert if (config->sectionStartMap.count(osec.name))
868ece8a530Spatrick return rank;
869ece8a530Spatrick rank |= RF_NOT_ADDR_SET;
870ece8a530Spatrick
871ece8a530Spatrick // Allocatable sections go first to reduce the total PT_LOAD size and
872ece8a530Spatrick // so debug info doesn't change addresses in actual code.
87305edf1c1Srobert if (!(osec.flags & SHF_ALLOC))
874ece8a530Spatrick return rank | RF_NOT_ALLOC;
875ece8a530Spatrick
87605edf1c1Srobert if (osec.type == SHT_LLVM_PART_EHDR)
877ece8a530Spatrick return rank;
878ece8a530Spatrick rank |= RF_NOT_PART_EHDR;
879ece8a530Spatrick
88005edf1c1Srobert if (osec.type == SHT_LLVM_PART_PHDR)
881ece8a530Spatrick return rank;
882ece8a530Spatrick rank |= RF_NOT_PART_PHDR;
883ece8a530Spatrick
884ece8a530Spatrick // Put .interp first because some loaders want to see that section
885ece8a530Spatrick // on the first page of the executable file when loaded into memory.
88605edf1c1Srobert if (osec.name == ".interp")
887ece8a530Spatrick return rank;
888ece8a530Spatrick rank |= RF_NOT_INTERP;
889ece8a530Spatrick
890ece8a530Spatrick // Put .note sections (which make up one PT_NOTE) at the beginning so that
891ece8a530Spatrick // they are likely to be included in a core file even if core file size is
892ece8a530Spatrick // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
893ece8a530Spatrick // included in a core to match core files with executables.
89405edf1c1Srobert if (osec.type == SHT_NOTE)
895ece8a530Spatrick return rank;
896ece8a530Spatrick rank |= RF_NOT_NOTE;
897ece8a530Spatrick
898ece8a530Spatrick // Sort sections based on their access permission in the following
899ece8a530Spatrick // order: R, RX, RWX, RW. This order is based on the following
900ece8a530Spatrick // considerations:
901ece8a530Spatrick // * Read-only sections come first such that they go in the
902ece8a530Spatrick // PT_LOAD covering the program headers at the start of the file.
903ece8a530Spatrick // * Read-only, executable sections come next.
904ece8a530Spatrick // * Writable, executable sections follow such that .plt on
905ece8a530Spatrick // architectures where it needs to be writable will be placed
906ece8a530Spatrick // between .text and .data.
907ece8a530Spatrick // * Writable sections come last, such that .bss lands at the very
908ece8a530Spatrick // end of the last PT_LOAD.
90905edf1c1Srobert bool isExec = osec.flags & SHF_EXECINSTR;
91005edf1c1Srobert bool isWrite = osec.flags & SHF_WRITE;
911ece8a530Spatrick
912ece8a530Spatrick if (isExec) {
913ece8a530Spatrick if (isWrite)
914ece8a530Spatrick rank |= RF_EXEC_WRITE;
915ece8a530Spatrick else
916ece8a530Spatrick rank |= RF_EXEC;
917ece8a530Spatrick } else if (isWrite) {
918ece8a530Spatrick rank |= RF_WRITE;
91905edf1c1Srobert } else if (osec.type == SHT_PROGBITS) {
920ece8a530Spatrick // Make non-executable and non-writable PROGBITS sections (e.g .rodata
921ece8a530Spatrick // .eh_frame) closer to .text. They likely contain PC or GOT relative
922ece8a530Spatrick // relocations and there could be relocation overflow if other huge sections
923ece8a530Spatrick // (.dynstr .dynsym) were placed in between.
924ece8a530Spatrick rank |= RF_RODATA;
925ece8a530Spatrick }
926ece8a530Spatrick
927ece8a530Spatrick // Place RelRo sections first. After considering SHT_NOBITS below, the
928ece8a530Spatrick // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
929ece8a530Spatrick // where | marks where page alignment happens. An alternative ordering is
930ece8a530Spatrick // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
931ece8a530Spatrick // waste more bytes due to 2 alignment places.
93205edf1c1Srobert if (!isRelroSection(&osec))
933ece8a530Spatrick rank |= RF_NOT_RELRO;
934ece8a530Spatrick
935ece8a530Spatrick // If we got here we know that both A and B are in the same PT_LOAD.
936ece8a530Spatrick
937ece8a530Spatrick // The TLS initialization block needs to be a single contiguous block in a R/W
938ece8a530Spatrick // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
939ece8a530Spatrick // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
940ece8a530Spatrick // after PROGBITS.
94105edf1c1Srobert if (!(osec.flags & SHF_TLS))
942ece8a530Spatrick rank |= RF_NOT_TLS;
943ece8a530Spatrick
944ece8a530Spatrick // Within TLS sections, or within other RelRo sections, or within non-RelRo
945ece8a530Spatrick // sections, place non-NOBITS sections first.
94605edf1c1Srobert if (osec.type == SHT_NOBITS)
947ece8a530Spatrick rank |= RF_BSS;
948ece8a530Spatrick
949ece8a530Spatrick // Some architectures have additional ordering restrictions for sections
950ece8a530Spatrick // within the same PT_LOAD.
951ece8a530Spatrick if (config->emachine == EM_PPC64) {
952ece8a530Spatrick // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
953ece8a530Spatrick // that we would like to make sure appear is a specific order to maximize
954ece8a530Spatrick // their coverage by a single signed 16-bit offset from the TOC base
955ece8a530Spatrick // pointer. Conversely, the special .tocbss section should be first among
956ece8a530Spatrick // all SHT_NOBITS sections. This will put it next to the loaded special
957ece8a530Spatrick // PPC64 sections (and, thus, within reach of the TOC base pointer).
95805edf1c1Srobert StringRef name = osec.name;
959ece8a530Spatrick if (name != ".tocbss")
960ece8a530Spatrick rank |= RF_PPC_NOT_TOCBSS;
961ece8a530Spatrick
962ece8a530Spatrick if (name == ".toc1")
963ece8a530Spatrick rank |= RF_PPC_TOCL;
964ece8a530Spatrick
965ece8a530Spatrick if (name == ".toc")
966ece8a530Spatrick rank |= RF_PPC_TOC;
967ece8a530Spatrick
968ece8a530Spatrick if (name == ".got")
969ece8a530Spatrick rank |= RF_PPC_GOT;
970ece8a530Spatrick
971ece8a530Spatrick if (name == ".branch_lt")
972ece8a530Spatrick rank |= RF_PPC_BRANCH_LT;
973ece8a530Spatrick }
974ece8a530Spatrick
975ece8a530Spatrick if (config->emachine == EM_MIPS) {
976ece8a530Spatrick // All sections with SHF_MIPS_GPREL flag should be grouped together
977ece8a530Spatrick // because data in these sections is addressable with a gp relative address.
97805edf1c1Srobert if (osec.flags & SHF_MIPS_GPREL)
979ece8a530Spatrick rank |= RF_MIPS_GPREL;
980ece8a530Spatrick
98105edf1c1Srobert if (osec.name != ".got")
982ece8a530Spatrick rank |= RF_MIPS_NOT_GOT;
983ece8a530Spatrick }
984ece8a530Spatrick
985ece8a530Spatrick return rank;
986ece8a530Spatrick }
987ece8a530Spatrick
compareSections(const SectionCommand * aCmd,const SectionCommand * bCmd)98805edf1c1Srobert static bool compareSections(const SectionCommand *aCmd,
98905edf1c1Srobert const SectionCommand *bCmd) {
99005edf1c1Srobert const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
99105edf1c1Srobert const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
992ece8a530Spatrick
993ece8a530Spatrick if (a->sortRank != b->sortRank)
994ece8a530Spatrick return a->sortRank < b->sortRank;
995ece8a530Spatrick
996ece8a530Spatrick if (!(a->sortRank & RF_NOT_ADDR_SET))
997ece8a530Spatrick return config->sectionStartMap.lookup(a->name) <
998ece8a530Spatrick config->sectionStartMap.lookup(b->name);
999ece8a530Spatrick return false;
1000ece8a530Spatrick }
1001ece8a530Spatrick
add(OutputSection * sec)1002ece8a530Spatrick void PhdrEntry::add(OutputSection *sec) {
1003ece8a530Spatrick lastSec = sec;
1004ece8a530Spatrick if (!firstSec)
1005ece8a530Spatrick firstSec = sec;
100605edf1c1Srobert p_align = std::max(p_align, sec->addralign);
1007ece8a530Spatrick if (p_type == PT_LOAD)
1008ece8a530Spatrick sec->ptLoad = this;
1009ece8a530Spatrick }
1010ece8a530Spatrick
1011ece8a530Spatrick // The beginning and the ending of .rel[a].plt section are marked
1012ece8a530Spatrick // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1013ece8a530Spatrick // executable. The runtime needs these symbols in order to resolve
1014ece8a530Spatrick // all IRELATIVE relocs on startup. For dynamic executables, we don't
1015ece8a530Spatrick // need these symbols, since IRELATIVE relocs are resolved through GOT
1016ece8a530Spatrick // and PLT. For details, see http://www.airs.com/blog/archives/403.
addRelIpltSymbols()1017ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
101805edf1c1Srobert if (config->isPic)
1019ece8a530Spatrick return;
1020ece8a530Spatrick
1021ece8a530Spatrick // By default, __rela_iplt_{start,end} belong to a dummy section 0
1022ece8a530Spatrick // because .rela.plt might be empty and thus removed from output.
1023ece8a530Spatrick // We'll override Out::elfHeader with In.relaIplt later when we are
1024ece8a530Spatrick // sure that .rela.plt exists in output.
1025ece8a530Spatrick ElfSym::relaIpltStart = addOptionalRegular(
1026ece8a530Spatrick config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
102705edf1c1Srobert Out::elfHeader, 0, STV_HIDDEN);
1028ece8a530Spatrick
1029ece8a530Spatrick ElfSym::relaIpltEnd = addOptionalRegular(
1030ece8a530Spatrick config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
103105edf1c1Srobert Out::elfHeader, 0, STV_HIDDEN);
1032ece8a530Spatrick }
1033ece8a530Spatrick
1034ece8a530Spatrick // This function generates assignments for predefined symbols (e.g. _end or
1035ece8a530Spatrick // _etext) and inserts them into the commands sequence to be processed at the
1036ece8a530Spatrick // appropriate time. This ensures that the value is going to be correct by the
1037ece8a530Spatrick // time any references to these symbols are processed and is equivalent to
1038ece8a530Spatrick // defining these symbols explicitly in the linker script.
setReservedSymbolSections()1039ece8a530Spatrick template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1040ece8a530Spatrick if (ElfSym::globalOffsetTable) {
1041ece8a530Spatrick // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1042ece8a530Spatrick // to the start of the .got or .got.plt section.
104305edf1c1Srobert InputSection *sec = in.gotPlt.get();
1044ece8a530Spatrick if (!target->gotBaseSymInGotPlt)
104505edf1c1Srobert sec = in.mipsGot ? cast<InputSection>(in.mipsGot.get())
104605edf1c1Srobert : cast<InputSection>(in.got.get());
104705edf1c1Srobert ElfSym::globalOffsetTable->section = sec;
1048ece8a530Spatrick }
1049ece8a530Spatrick
1050ece8a530Spatrick // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
1051ece8a530Spatrick if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
105205edf1c1Srobert ElfSym::relaIpltStart->section = in.relaIplt.get();
105305edf1c1Srobert ElfSym::relaIpltEnd->section = in.relaIplt.get();
1054ece8a530Spatrick ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1055ece8a530Spatrick }
1056ece8a530Spatrick
1057ece8a530Spatrick PhdrEntry *last = nullptr;
1058ece8a530Spatrick PhdrEntry *lastRO = nullptr;
1059ece8a530Spatrick
1060ece8a530Spatrick for (Partition &part : partitions) {
1061ece8a530Spatrick for (PhdrEntry *p : part.phdrs) {
1062ece8a530Spatrick if (p->p_type != PT_LOAD)
1063ece8a530Spatrick continue;
1064ece8a530Spatrick last = p;
1065ece8a530Spatrick if (!(p->p_flags & PF_W))
1066ece8a530Spatrick lastRO = p;
1067ece8a530Spatrick }
1068ece8a530Spatrick }
1069ece8a530Spatrick
1070ece8a530Spatrick if (lastRO) {
1071ece8a530Spatrick // _etext is the first location after the last read-only loadable segment.
1072ece8a530Spatrick if (ElfSym::etext1)
1073ece8a530Spatrick ElfSym::etext1->section = lastRO->lastSec;
1074ece8a530Spatrick if (ElfSym::etext2)
1075ece8a530Spatrick ElfSym::etext2->section = lastRO->lastSec;
1076ece8a530Spatrick }
1077ece8a530Spatrick
1078ece8a530Spatrick if (last) {
1079ece8a530Spatrick // _edata points to the end of the last mapped initialized section.
1080ece8a530Spatrick OutputSection *edata = nullptr;
1081ece8a530Spatrick for (OutputSection *os : outputSections) {
1082ece8a530Spatrick if (os->type != SHT_NOBITS)
1083ece8a530Spatrick edata = os;
1084ece8a530Spatrick if (os == last->lastSec)
1085ece8a530Spatrick break;
1086ece8a530Spatrick }
1087ece8a530Spatrick
1088ece8a530Spatrick if (ElfSym::edata1)
1089ece8a530Spatrick ElfSym::edata1->section = edata;
1090ece8a530Spatrick if (ElfSym::edata2)
1091ece8a530Spatrick ElfSym::edata2->section = edata;
1092ece8a530Spatrick
1093ece8a530Spatrick // _end is the first location after the uninitialized data region.
1094ece8a530Spatrick if (ElfSym::end1)
1095ece8a530Spatrick ElfSym::end1->section = last->lastSec;
1096ece8a530Spatrick if (ElfSym::end2)
1097ece8a530Spatrick ElfSym::end2->section = last->lastSec;
1098ece8a530Spatrick }
1099ece8a530Spatrick
1100ece8a530Spatrick if (ElfSym::bss)
1101ece8a530Spatrick ElfSym::bss->section = findSection(".bss");
1102ece8a530Spatrick
1103adae0cfdSpatrick if (ElfSym::data)
1104adae0cfdSpatrick ElfSym::data->section = findSection(".data");
1105adae0cfdSpatrick
1106ece8a530Spatrick // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1107ece8a530Spatrick // be equal to the _gp symbol's value.
1108ece8a530Spatrick if (ElfSym::mipsGp) {
1109ece8a530Spatrick // Find GP-relative section with the lowest address
1110ece8a530Spatrick // and use this address to calculate default _gp value.
1111ece8a530Spatrick for (OutputSection *os : outputSections) {
1112ece8a530Spatrick if (os->flags & SHF_MIPS_GPREL) {
1113ece8a530Spatrick ElfSym::mipsGp->section = os;
1114ece8a530Spatrick ElfSym::mipsGp->value = 0x7ff0;
1115ece8a530Spatrick break;
1116ece8a530Spatrick }
1117ece8a530Spatrick }
1118ece8a530Spatrick }
1119ece8a530Spatrick }
1120ece8a530Spatrick
1121ece8a530Spatrick // We want to find how similar two ranks are.
1122ece8a530Spatrick // The more branches in getSectionRank that match, the more similar they are.
1123ece8a530Spatrick // Since each branch corresponds to a bit flag, we can just use
1124ece8a530Spatrick // countLeadingZeros.
getRankProximity(OutputSection * a,SectionCommand * b)112505edf1c1Srobert static int getRankProximity(OutputSection *a, SectionCommand *b) {
112605edf1c1Srobert auto *osd = dyn_cast<OutputDesc>(b);
112705edf1c1Srobert return (osd && osd->osec.hasInputSections)
112805edf1c1Srobert ? countLeadingZeros(a->sortRank ^ osd->osec.sortRank)
112905edf1c1Srobert : -1;
1130ece8a530Spatrick }
1131ece8a530Spatrick
1132ece8a530Spatrick // When placing orphan sections, we want to place them after symbol assignments
1133ece8a530Spatrick // so that an orphan after
1134ece8a530Spatrick // begin_foo = .;
1135ece8a530Spatrick // foo : { *(foo) }
1136ece8a530Spatrick // end_foo = .;
1137ece8a530Spatrick // doesn't break the intended meaning of the begin/end symbols.
1138ece8a530Spatrick // We don't want to go over sections since findOrphanPos is the
1139ece8a530Spatrick // one in charge of deciding the order of the sections.
1140ece8a530Spatrick // We don't want to go over changes to '.', since doing so in
1141ece8a530Spatrick // rx_sec : { *(rx_sec) }
1142ece8a530Spatrick // . = ALIGN(0x1000);
1143ece8a530Spatrick // /* The RW PT_LOAD starts here*/
1144ece8a530Spatrick // rw_sec : { *(rw_sec) }
1145ece8a530Spatrick // would mean that the RW PT_LOAD would become unaligned.
shouldSkip(SectionCommand * cmd)114605edf1c1Srobert static bool shouldSkip(SectionCommand *cmd) {
1147ece8a530Spatrick if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1148ece8a530Spatrick return assign->name != ".";
1149ece8a530Spatrick return false;
1150ece8a530Spatrick }
1151ece8a530Spatrick
1152ece8a530Spatrick // We want to place orphan sections so that they share as much
1153ece8a530Spatrick // characteristics with their neighbors as possible. For example, if
1154ece8a530Spatrick // both are rw, or both are tls.
115505edf1c1Srobert static SmallVectorImpl<SectionCommand *>::iterator
findOrphanPos(SmallVectorImpl<SectionCommand * >::iterator b,SmallVectorImpl<SectionCommand * >::iterator e)115605edf1c1Srobert findOrphanPos(SmallVectorImpl<SectionCommand *>::iterator b,
115705edf1c1Srobert SmallVectorImpl<SectionCommand *>::iterator e) {
115805edf1c1Srobert OutputSection *sec = &cast<OutputDesc>(*e)->osec;
1159ece8a530Spatrick
1160ece8a530Spatrick // Find the first element that has as close a rank as possible.
116105edf1c1Srobert auto i = std::max_element(b, e, [=](SectionCommand *a, SectionCommand *b) {
1162ece8a530Spatrick return getRankProximity(sec, a) < getRankProximity(sec, b);
1163ece8a530Spatrick });
1164ece8a530Spatrick if (i == e)
1165ece8a530Spatrick return e;
116605edf1c1Srobert if (!isa<OutputDesc>(*i))
116705edf1c1Srobert return e;
116805edf1c1Srobert auto foundSec = &cast<OutputDesc>(*i)->osec;
1169ece8a530Spatrick
1170ece8a530Spatrick // Consider all existing sections with the same proximity.
1171ece8a530Spatrick int proximity = getRankProximity(sec, *i);
117205edf1c1Srobert unsigned sortRank = sec->sortRank;
117305edf1c1Srobert if (script->hasPhdrsCommands() || !script->memoryRegions.empty())
117405edf1c1Srobert // Prevent the orphan section to be placed before the found section. If
117505edf1c1Srobert // custom program headers are defined, that helps to avoid adding it to a
117605edf1c1Srobert // previous segment and changing flags of that segment, for example, making
117705edf1c1Srobert // a read-only segment writable. If memory regions are defined, an orphan
117805edf1c1Srobert // section should continue the same region as the found section to better
117905edf1c1Srobert // resemble the behavior of GNU ld.
118005edf1c1Srobert sortRank = std::max(sortRank, foundSec->sortRank);
1181ece8a530Spatrick for (; i != e; ++i) {
118205edf1c1Srobert auto *curSecDesc = dyn_cast<OutputDesc>(*i);
118305edf1c1Srobert if (!curSecDesc || !curSecDesc->osec.hasInputSections)
1184ece8a530Spatrick continue;
118505edf1c1Srobert if (getRankProximity(sec, curSecDesc) != proximity ||
118605edf1c1Srobert sortRank < curSecDesc->osec.sortRank)
1187ece8a530Spatrick break;
1188ece8a530Spatrick }
1189ece8a530Spatrick
119005edf1c1Srobert auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
119105edf1c1Srobert auto *osd = dyn_cast<OutputDesc>(cmd);
119205edf1c1Srobert return osd && osd->osec.hasInputSections;
1193ece8a530Spatrick };
119405edf1c1Srobert auto j =
119505edf1c1Srobert std::find_if(std::make_reverse_iterator(i), std::make_reverse_iterator(b),
1196ece8a530Spatrick isOutputSecWithInputSections);
1197ece8a530Spatrick i = j.base();
1198ece8a530Spatrick
1199ece8a530Spatrick // As a special case, if the orphan section is the last section, put
1200ece8a530Spatrick // it at the very end, past any other commands.
1201ece8a530Spatrick // This matches bfd's behavior and is convenient when the linker script fully
1202ece8a530Spatrick // specifies the start of the file, but doesn't care about the end (the non
1203ece8a530Spatrick // alloc sections for example).
1204ece8a530Spatrick auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1205ece8a530Spatrick if (nextSec == e)
1206ece8a530Spatrick return e;
1207ece8a530Spatrick
1208ece8a530Spatrick while (i != e && shouldSkip(*i))
1209ece8a530Spatrick ++i;
1210ece8a530Spatrick return i;
1211ece8a530Spatrick }
1212ece8a530Spatrick
1213bb684c34Spatrick // Adds random priorities to sections not already in the map.
maybeShuffle(DenseMap<const InputSectionBase *,int> & order)1214bb684c34Spatrick static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
1215a0747c9fSpatrick if (config->shuffleSections.empty())
1216bb684c34Spatrick return;
1217bb684c34Spatrick
121805edf1c1Srobert SmallVector<InputSectionBase *, 0> matched, sections = ctx.inputSections;
1219a0747c9fSpatrick matched.reserve(sections.size());
1220a0747c9fSpatrick for (const auto &patAndSeed : config->shuffleSections) {
1221a0747c9fSpatrick matched.clear();
1222a0747c9fSpatrick for (InputSectionBase *sec : sections)
1223a0747c9fSpatrick if (patAndSeed.first.match(sec->name))
1224a0747c9fSpatrick matched.push_back(sec);
1225a0747c9fSpatrick const uint32_t seed = patAndSeed.second;
1226a0747c9fSpatrick if (seed == UINT32_MAX) {
1227a0747c9fSpatrick // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1228a0747c9fSpatrick // section order is stable even if the number of sections changes. This is
1229a0747c9fSpatrick // useful to catch issues like static initialization order fiasco
1230a0747c9fSpatrick // reliably.
1231a0747c9fSpatrick std::reverse(matched.begin(), matched.end());
1232a0747c9fSpatrick } else {
1233a0747c9fSpatrick std::mt19937 g(seed ? seed : std::random_device()());
1234a0747c9fSpatrick llvm::shuffle(matched.begin(), matched.end(), g);
1235a0747c9fSpatrick }
1236a0747c9fSpatrick size_t i = 0;
1237a0747c9fSpatrick for (InputSectionBase *&sec : sections)
1238a0747c9fSpatrick if (patAndSeed.first.match(sec->name))
1239a0747c9fSpatrick sec = matched[i++];
1240a0747c9fSpatrick }
1241a0747c9fSpatrick
1242bb684c34Spatrick // Existing priorities are < 0, so use priorities >= 0 for the missing
1243bb684c34Spatrick // sections.
1244a0747c9fSpatrick int prio = 0;
1245a0747c9fSpatrick for (InputSectionBase *sec : sections) {
1246a0747c9fSpatrick if (order.try_emplace(sec, prio).second)
1247a0747c9fSpatrick ++prio;
1248bb684c34Spatrick }
1249bb684c34Spatrick }
1250bb684c34Spatrick
1251ece8a530Spatrick // Builds section order for handling --symbol-ordering-file.
buildSectionOrder()1252ece8a530Spatrick static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1253ece8a530Spatrick DenseMap<const InputSectionBase *, int> sectionOrder;
125405edf1c1Srobert // Use the rarely used option --call-graph-ordering-file to sort sections.
1255ece8a530Spatrick if (!config->callGraphProfile.empty())
1256ece8a530Spatrick return computeCallGraphProfileOrder();
1257ece8a530Spatrick
1258ece8a530Spatrick if (config->symbolOrderingFile.empty())
1259ece8a530Spatrick return sectionOrder;
1260ece8a530Spatrick
1261ece8a530Spatrick struct SymbolOrderEntry {
1262ece8a530Spatrick int priority;
1263ece8a530Spatrick bool present;
1264ece8a530Spatrick };
1265ece8a530Spatrick
1266ece8a530Spatrick // Build a map from symbols to their priorities. Symbols that didn't
1267ece8a530Spatrick // appear in the symbol ordering file have the lowest priority 0.
1268ece8a530Spatrick // All explicitly mentioned symbols have negative (higher) priorities.
126905edf1c1Srobert DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
1270ece8a530Spatrick int priority = -config->symbolOrderingFile.size();
1271ece8a530Spatrick for (StringRef s : config->symbolOrderingFile)
127205edf1c1Srobert symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
1273ece8a530Spatrick
1274ece8a530Spatrick // Build a map from sections to their priorities.
1275ece8a530Spatrick auto addSym = [&](Symbol &sym) {
127605edf1c1Srobert auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
1277ece8a530Spatrick if (it == symbolOrder.end())
1278ece8a530Spatrick return;
1279ece8a530Spatrick SymbolOrderEntry &ent = it->second;
1280ece8a530Spatrick ent.present = true;
1281ece8a530Spatrick
1282ece8a530Spatrick maybeWarnUnorderableSymbol(&sym);
1283ece8a530Spatrick
1284ece8a530Spatrick if (auto *d = dyn_cast<Defined>(&sym)) {
1285ece8a530Spatrick if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
128605edf1c1Srobert int &priority = sectionOrder[cast<InputSectionBase>(sec)];
1287ece8a530Spatrick priority = std::min(priority, ent.priority);
1288ece8a530Spatrick }
1289ece8a530Spatrick }
1290ece8a530Spatrick };
1291ece8a530Spatrick
1292ece8a530Spatrick // We want both global and local symbols. We get the global ones from the
1293ece8a530Spatrick // symbol table and iterate the object files for the local ones.
129405edf1c1Srobert for (Symbol *sym : symtab.getSymbols())
1295ece8a530Spatrick addSym(*sym);
1296ece8a530Spatrick
129705edf1c1Srobert for (ELFFileBase *file : ctx.objectFiles)
129805edf1c1Srobert for (Symbol *sym : file->getLocalSymbols())
1299ece8a530Spatrick addSym(*sym);
1300ece8a530Spatrick
1301ece8a530Spatrick if (config->warnSymbolOrdering)
1302ece8a530Spatrick for (auto orderEntry : symbolOrder)
1303ece8a530Spatrick if (!orderEntry.second.present)
130405edf1c1Srobert warn("symbol ordering file: no such symbol: " + orderEntry.first.val());
1305ece8a530Spatrick
1306ece8a530Spatrick return sectionOrder;
1307ece8a530Spatrick }
1308ece8a530Spatrick
1309ece8a530Spatrick // Sorts the sections in ISD according to the provided section order.
1310ece8a530Spatrick static void
sortISDBySectionOrder(InputSectionDescription * isd,const DenseMap<const InputSectionBase *,int> & order,bool executableOutputSection)1311ece8a530Spatrick sortISDBySectionOrder(InputSectionDescription *isd,
131205edf1c1Srobert const DenseMap<const InputSectionBase *, int> &order,
131305edf1c1Srobert bool executableOutputSection) {
131405edf1c1Srobert SmallVector<InputSection *, 0> unorderedSections;
131505edf1c1Srobert SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
1316ece8a530Spatrick uint64_t unorderedSize = 0;
131705edf1c1Srobert uint64_t totalSize = 0;
1318ece8a530Spatrick
1319ece8a530Spatrick for (InputSection *isec : isd->sections) {
132005edf1c1Srobert if (executableOutputSection)
132105edf1c1Srobert totalSize += isec->getSize();
1322ece8a530Spatrick auto i = order.find(isec);
1323ece8a530Spatrick if (i == order.end()) {
1324ece8a530Spatrick unorderedSections.push_back(isec);
1325ece8a530Spatrick unorderedSize += isec->getSize();
1326ece8a530Spatrick continue;
1327ece8a530Spatrick }
1328ece8a530Spatrick orderedSections.push_back({isec, i->second});
1329ece8a530Spatrick }
1330ece8a530Spatrick llvm::sort(orderedSections, llvm::less_second());
1331ece8a530Spatrick
1332ece8a530Spatrick // Find an insertion point for the ordered section list in the unordered
1333ece8a530Spatrick // section list. On targets with limited-range branches, this is the mid-point
1334ece8a530Spatrick // of the unordered section list. This decreases the likelihood that a range
1335ece8a530Spatrick // extension thunk will be needed to enter or exit the ordered region. If the
1336ece8a530Spatrick // ordered section list is a list of hot functions, we can generally expect
1337ece8a530Spatrick // the ordered functions to be called more often than the unordered functions,
1338ece8a530Spatrick // making it more likely that any particular call will be within range, and
1339ece8a530Spatrick // therefore reducing the number of thunks required.
1340ece8a530Spatrick //
1341ece8a530Spatrick // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1342ece8a530Spatrick // If the layout is:
1343ece8a530Spatrick //
1344ece8a530Spatrick // 8MB hot
1345ece8a530Spatrick // 32MB cold
1346ece8a530Spatrick //
1347ece8a530Spatrick // only the first 8-16MB of the cold code (depending on which hot function it
1348ece8a530Spatrick // is actually calling) can call the hot code without a range extension thunk.
1349ece8a530Spatrick // However, if we use this layout:
1350ece8a530Spatrick //
1351ece8a530Spatrick // 16MB cold
1352ece8a530Spatrick // 8MB hot
1353ece8a530Spatrick // 16MB cold
1354ece8a530Spatrick //
1355ece8a530Spatrick // both the last 8-16MB of the first block of cold code and the first 8-16MB
1356ece8a530Spatrick // of the second block of cold code can call the hot code without a thunk. So
1357ece8a530Spatrick // we effectively double the amount of code that could potentially call into
1358ece8a530Spatrick // the hot code without a thunk.
135905edf1c1Srobert //
136005edf1c1Srobert // The above is not necessary if total size of input sections in this "isd"
136105edf1c1Srobert // is small. Note that we assume all input sections are executable if the
136205edf1c1Srobert // output section is executable (which is not always true but supposed to
136305edf1c1Srobert // cover most cases).
1364ece8a530Spatrick size_t insPt = 0;
136505edf1c1Srobert if (executableOutputSection && !orderedSections.empty() &&
136605edf1c1Srobert target->getThunkSectionSpacing() &&
136705edf1c1Srobert totalSize >= target->getThunkSectionSpacing()) {
1368ece8a530Spatrick uint64_t unorderedPos = 0;
1369ece8a530Spatrick for (; insPt != unorderedSections.size(); ++insPt) {
1370ece8a530Spatrick unorderedPos += unorderedSections[insPt]->getSize();
1371ece8a530Spatrick if (unorderedPos > unorderedSize / 2)
1372ece8a530Spatrick break;
1373ece8a530Spatrick }
1374ece8a530Spatrick }
1375ece8a530Spatrick
1376ece8a530Spatrick isd->sections.clear();
137705edf1c1Srobert for (InputSection *isec : ArrayRef(unorderedSections).slice(0, insPt))
1378ece8a530Spatrick isd->sections.push_back(isec);
1379ece8a530Spatrick for (std::pair<InputSection *, int> p : orderedSections)
1380ece8a530Spatrick isd->sections.push_back(p.first);
138105edf1c1Srobert for (InputSection *isec : ArrayRef(unorderedSections).slice(insPt))
1382ece8a530Spatrick isd->sections.push_back(isec);
1383ece8a530Spatrick }
1384ece8a530Spatrick
sortSection(OutputSection & osec,const DenseMap<const InputSectionBase *,int> & order)138505edf1c1Srobert static void sortSection(OutputSection &osec,
1386ece8a530Spatrick const DenseMap<const InputSectionBase *, int> &order) {
138705edf1c1Srobert StringRef name = osec.name;
1388ece8a530Spatrick
1389bb684c34Spatrick // Never sort these.
1390bb684c34Spatrick if (name == ".init" || name == ".fini")
1391bb684c34Spatrick return;
1392bb684c34Spatrick
1393a0747c9fSpatrick // IRelative relocations that usually live in the .rel[a].dyn section should
1394a0747c9fSpatrick // be processed last by the dynamic loader. To achieve that we add synthetic
1395a0747c9fSpatrick // sections in the required order from the beginning so that the in.relaIplt
1396a0747c9fSpatrick // section is placed last in an output section. Here we just do not apply
1397a0747c9fSpatrick // sorting for an output section which holds the in.relaIplt section.
139805edf1c1Srobert if (in.relaIplt->getParent() == &osec)
1399a0747c9fSpatrick return;
1400a0747c9fSpatrick
1401bb684c34Spatrick // Sort input sections by priority using the list provided by
1402bb684c34Spatrick // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1403bb684c34Spatrick // digit radix sort. The sections may be sorted stably again by a more
1404bb684c34Spatrick // significant key.
1405bb684c34Spatrick if (!order.empty())
140605edf1c1Srobert for (SectionCommand *b : osec.commands)
1407bb684c34Spatrick if (auto *isd = dyn_cast<InputSectionDescription>(b))
140805edf1c1Srobert sortISDBySectionOrder(isd, order, osec.flags & SHF_EXECINSTR);
1409bb684c34Spatrick
141005edf1c1Srobert if (script->hasSectionsCommand)
141105edf1c1Srobert return;
141205edf1c1Srobert
1413ece8a530Spatrick if (name == ".init_array" || name == ".fini_array") {
141405edf1c1Srobert osec.sortInitFini();
141505edf1c1Srobert } else if (name == ".ctors" || name == ".dtors") {
141605edf1c1Srobert osec.sortCtorsDtors();
141705edf1c1Srobert } else if (config->emachine == EM_PPC64 && name == ".toc") {
1418ece8a530Spatrick // .toc is allocated just after .got and is accessed using GOT-relative
1419ece8a530Spatrick // relocations. Object files compiled with small code model have an
1420ece8a530Spatrick // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
142105edf1c1Srobert // To reduce the risk of relocation overflow, .toc contents are sorted so
142205edf1c1Srobert // that sections having smaller relocation offsets are at beginning of .toc
142305edf1c1Srobert assert(osec.commands.size() == 1);
142405edf1c1Srobert auto *isd = cast<InputSectionDescription>(osec.commands[0]);
1425ece8a530Spatrick llvm::stable_sort(isd->sections,
1426ece8a530Spatrick [](const InputSection *a, const InputSection *b) -> bool {
1427ece8a530Spatrick return a->file->ppc64SmallCodeModelTocRelocs &&
1428ece8a530Spatrick !b->file->ppc64SmallCodeModelTocRelocs;
1429ece8a530Spatrick });
1430ece8a530Spatrick }
1431ece8a530Spatrick }
1432ece8a530Spatrick
1433ece8a530Spatrick // If no layout was provided by linker script, we want to apply default
1434ece8a530Spatrick // sorting for special input sections. This also handles --symbol-ordering-file.
sortInputSections()1435ece8a530Spatrick template <class ELFT> void Writer<ELFT>::sortInputSections() {
1436ece8a530Spatrick // Build the order once since it is expensive.
1437ece8a530Spatrick DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1438bb684c34Spatrick maybeShuffle(order);
143905edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
144005edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd))
144105edf1c1Srobert sortSection(osd->osec, order);
1442ece8a530Spatrick }
1443ece8a530Spatrick
sortSections()1444ece8a530Spatrick template <class ELFT> void Writer<ELFT>::sortSections() {
1445a0747c9fSpatrick llvm::TimeTraceScope timeScope("Sort sections");
1446ece8a530Spatrick
1447ece8a530Spatrick // Don't sort if using -r. It is not necessary and we want to preserve the
1448ece8a530Spatrick // relative order for SHF_LINK_ORDER sections.
144905edf1c1Srobert if (config->relocatable) {
145005edf1c1Srobert script->adjustOutputSections();
1451ece8a530Spatrick return;
145205edf1c1Srobert }
1453ece8a530Spatrick
1454ece8a530Spatrick sortInputSections();
1455ece8a530Spatrick
145605edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
145705edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd))
145805edf1c1Srobert osd->osec.sortRank = getSectionRank(osd->osec);
1459ece8a530Spatrick if (!script->hasSectionsCommand) {
1460ece8a530Spatrick // We know that all the OutputSections are contiguous in this case.
146105edf1c1Srobert auto isSection = [](SectionCommand *cmd) { return isa<OutputDesc>(cmd); };
1462ece8a530Spatrick std::stable_sort(
1463ece8a530Spatrick llvm::find_if(script->sectionCommands, isSection),
1464ece8a530Spatrick llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1465ece8a530Spatrick compareSections);
1466ece8a530Spatrick }
1467ece8a530Spatrick
146805edf1c1Srobert // Process INSERT commands and update output section attributes. From this
146905edf1c1Srobert // point onwards the order of script->sectionCommands is fixed.
1470bb684c34Spatrick script->processInsertCommands();
147105edf1c1Srobert script->adjustOutputSections();
147205edf1c1Srobert
147305edf1c1Srobert if (!script->hasSectionsCommand)
147405edf1c1Srobert return;
1475bb684c34Spatrick
1476ece8a530Spatrick // Orphan sections are sections present in the input files which are
1477ece8a530Spatrick // not explicitly placed into the output file by the linker script.
1478ece8a530Spatrick //
1479ece8a530Spatrick // The sections in the linker script are already in the correct
1480ece8a530Spatrick // order. We have to figuere out where to insert the orphan
1481ece8a530Spatrick // sections.
1482ece8a530Spatrick //
1483ece8a530Spatrick // The order of the sections in the script is arbitrary and may not agree with
1484ece8a530Spatrick // compareSections. This means that we cannot easily define a strict weak
1485ece8a530Spatrick // ordering. To see why, consider a comparison of a section in the script and
1486ece8a530Spatrick // one not in the script. We have a two simple options:
1487ece8a530Spatrick // * Make them equivalent (a is not less than b, and b is not less than a).
1488ece8a530Spatrick // The problem is then that equivalence has to be transitive and we can
1489ece8a530Spatrick // have sections a, b and c with only b in a script and a less than c
1490ece8a530Spatrick // which breaks this property.
1491ece8a530Spatrick // * Use compareSectionsNonScript. Given that the script order doesn't have
1492ece8a530Spatrick // to match, we can end up with sections a, b, c, d where b and c are in the
1493ece8a530Spatrick // script and c is compareSectionsNonScript less than b. In which case d
1494ece8a530Spatrick // can be equivalent to c, a to b and d < a. As a concrete example:
1495ece8a530Spatrick // .a (rx) # not in script
1496ece8a530Spatrick // .b (rx) # in script
1497ece8a530Spatrick // .c (ro) # in script
1498ece8a530Spatrick // .d (ro) # not in script
1499ece8a530Spatrick //
1500ece8a530Spatrick // The way we define an order then is:
1501ece8a530Spatrick // * Sort only the orphan sections. They are in the end right now.
1502ece8a530Spatrick // * Move each orphan section to its preferred position. We try
1503ece8a530Spatrick // to put each section in the last position where it can share
1504ece8a530Spatrick // a PT_LOAD.
1505ece8a530Spatrick //
1506ece8a530Spatrick // There is some ambiguity as to where exactly a new entry should be
1507ece8a530Spatrick // inserted, because Commands contains not only output section
1508ece8a530Spatrick // commands but also other types of commands such as symbol assignment
1509ece8a530Spatrick // expressions. There's no correct answer here due to the lack of the
1510ece8a530Spatrick // formal specification of the linker script. We use heuristics to
1511ece8a530Spatrick // determine whether a new output command should be added before or
1512ece8a530Spatrick // after another commands. For the details, look at shouldSkip
1513ece8a530Spatrick // function.
1514ece8a530Spatrick
1515ece8a530Spatrick auto i = script->sectionCommands.begin();
1516ece8a530Spatrick auto e = script->sectionCommands.end();
151705edf1c1Srobert auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
151805edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd))
151905edf1c1Srobert return osd->osec.sectionIndex == UINT32_MAX;
1520ece8a530Spatrick return false;
1521ece8a530Spatrick });
1522ece8a530Spatrick
1523ece8a530Spatrick // Sort the orphan sections.
1524ece8a530Spatrick std::stable_sort(nonScriptI, e, compareSections);
1525ece8a530Spatrick
1526ece8a530Spatrick // As a horrible special case, skip the first . assignment if it is before any
1527ece8a530Spatrick // section. We do this because it is common to set a load address by starting
1528ece8a530Spatrick // the script with ". = 0xabcd" and the expectation is that every section is
1529ece8a530Spatrick // after that.
1530ece8a530Spatrick auto firstSectionOrDotAssignment =
153105edf1c1Srobert std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
1532ece8a530Spatrick if (firstSectionOrDotAssignment != e &&
1533ece8a530Spatrick isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1534ece8a530Spatrick ++firstSectionOrDotAssignment;
1535ece8a530Spatrick i = firstSectionOrDotAssignment;
1536ece8a530Spatrick
1537ece8a530Spatrick while (nonScriptI != e) {
1538ece8a530Spatrick auto pos = findOrphanPos(i, nonScriptI);
153905edf1c1Srobert OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
1540ece8a530Spatrick
1541ece8a530Spatrick // As an optimization, find all sections with the same sort rank
1542ece8a530Spatrick // and insert them with one rotate.
1543ece8a530Spatrick unsigned rank = orphan->sortRank;
154405edf1c1Srobert auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
154505edf1c1Srobert return cast<OutputDesc>(cmd)->osec.sortRank != rank;
1546ece8a530Spatrick });
1547ece8a530Spatrick std::rotate(pos, nonScriptI, end);
1548ece8a530Spatrick nonScriptI = end;
1549ece8a530Spatrick }
1550ece8a530Spatrick
1551ece8a530Spatrick script->adjustSectionsAfterSorting();
1552ece8a530Spatrick }
1553ece8a530Spatrick
compareByFilePosition(InputSection * a,InputSection * b)1554ece8a530Spatrick static bool compareByFilePosition(InputSection *a, InputSection *b) {
1555a0747c9fSpatrick InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1556a0747c9fSpatrick InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1557a0747c9fSpatrick // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1558a0747c9fSpatrick // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1559a0747c9fSpatrick if (!la || !lb)
1560a0747c9fSpatrick return la && !lb;
1561ece8a530Spatrick OutputSection *aOut = la->getParent();
1562ece8a530Spatrick OutputSection *bOut = lb->getParent();
1563ece8a530Spatrick
1564ece8a530Spatrick if (aOut != bOut)
1565bb684c34Spatrick return aOut->addr < bOut->addr;
1566ece8a530Spatrick return la->outSecOff < lb->outSecOff;
1567ece8a530Spatrick }
1568ece8a530Spatrick
resolveShfLinkOrder()1569ece8a530Spatrick template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1570a0747c9fSpatrick llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1571ece8a530Spatrick for (OutputSection *sec : outputSections) {
1572ece8a530Spatrick if (!(sec->flags & SHF_LINK_ORDER))
1573ece8a530Spatrick continue;
1574ece8a530Spatrick
1575ece8a530Spatrick // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1576ece8a530Spatrick // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1577ece8a530Spatrick if (!config->relocatable && config->emachine == EM_ARM &&
1578ece8a530Spatrick sec->type == SHT_ARM_EXIDX)
1579ece8a530Spatrick continue;
1580ece8a530Spatrick
1581a0747c9fSpatrick // Link order may be distributed across several InputSectionDescriptions.
1582a0747c9fSpatrick // Sorting is performed separately.
158305edf1c1Srobert SmallVector<InputSection **, 0> scriptSections;
158405edf1c1Srobert SmallVector<InputSection *, 0> sections;
158505edf1c1Srobert for (SectionCommand *cmd : sec->commands) {
158605edf1c1Srobert auto *isd = dyn_cast<InputSectionDescription>(cmd);
1587a0747c9fSpatrick if (!isd)
1588a0747c9fSpatrick continue;
1589a0747c9fSpatrick bool hasLinkOrder = false;
1590a0747c9fSpatrick scriptSections.clear();
1591a0747c9fSpatrick sections.clear();
1592ece8a530Spatrick for (InputSection *&isec : isd->sections) {
1593a0747c9fSpatrick if (isec->flags & SHF_LINK_ORDER) {
1594ece8a530Spatrick InputSection *link = isec->getLinkOrderDep();
1595a0747c9fSpatrick if (link && !link->getParent())
1596ece8a530Spatrick error(toString(isec) + ": sh_link points to discarded section " +
1597ece8a530Spatrick toString(link));
1598a0747c9fSpatrick hasLinkOrder = true;
1599ece8a530Spatrick }
1600a0747c9fSpatrick scriptSections.push_back(&isec);
1601a0747c9fSpatrick sections.push_back(isec);
1602ece8a530Spatrick }
1603a0747c9fSpatrick if (hasLinkOrder && errorCount() == 0) {
1604ece8a530Spatrick llvm::stable_sort(sections, compareByFilePosition);
1605a0747c9fSpatrick for (int i = 0, n = sections.size(); i != n; ++i)
1606ece8a530Spatrick *scriptSections[i] = sections[i];
1607ece8a530Spatrick }
1608ece8a530Spatrick }
1609a0747c9fSpatrick }
1610a0747c9fSpatrick }
1611ece8a530Spatrick
finalizeSynthetic(SyntheticSection * sec)1612bb684c34Spatrick static void finalizeSynthetic(SyntheticSection *sec) {
1613a0747c9fSpatrick if (sec && sec->isNeeded() && sec->getParent()) {
1614a0747c9fSpatrick llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1615bb684c34Spatrick sec->finalizeContents();
1616bb684c34Spatrick }
1617a0747c9fSpatrick }
1618bb684c34Spatrick
1619ece8a530Spatrick // We need to generate and finalize the content that depends on the address of
1620ece8a530Spatrick // InputSections. As the generation of the content may also alter InputSection
1621ece8a530Spatrick // addresses we must converge to a fixed point. We do that here. See the comment
1622ece8a530Spatrick // in Writer<ELFT>::finalizeSections().
finalizeAddressDependentContent()1623ece8a530Spatrick template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1624a0747c9fSpatrick llvm::TimeTraceScope timeScope("Finalize address dependent content");
1625ece8a530Spatrick ThunkCreator tc;
1626ece8a530Spatrick AArch64Err843419Patcher a64p;
1627ece8a530Spatrick ARMErr657417Patcher a32p;
1628ece8a530Spatrick script->assignAddresses();
1629bb684c34Spatrick // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1630bb684c34Spatrick // do require the relative addresses of OutputSections because linker scripts
1631bb684c34Spatrick // can assign Virtual Addresses to OutputSections that are not monotonically
1632bb684c34Spatrick // increasing.
1633bb684c34Spatrick for (Partition &part : partitions)
163405edf1c1Srobert finalizeSynthetic(part.armExidx.get());
1635bb684c34Spatrick resolveShfLinkOrder();
1636bb684c34Spatrick
1637bb684c34Spatrick // Converts call x@GDPLT to call __tls_get_addr
1638bb684c34Spatrick if (config->emachine == EM_HEXAGON)
1639bb684c34Spatrick hexagonTLSSymbolUpdate(outputSections);
1640ece8a530Spatrick
164105edf1c1Srobert uint32_t pass = 0, assignPasses = 0;
1642ece8a530Spatrick for (;;) {
164305edf1c1Srobert bool changed = target->needsThunks ? tc.createThunks(pass, outputSections)
164405edf1c1Srobert : target->relaxOnce(pass);
164505edf1c1Srobert ++pass;
1646ece8a530Spatrick
1647ece8a530Spatrick // With Thunk Size much smaller than branch range we expect to
1648a0747c9fSpatrick // converge quickly; if we get to 15 something has gone wrong.
164905edf1c1Srobert if (changed && pass >= 15) {
165005edf1c1Srobert error(target->needsThunks ? "thunk creation not converged"
165105edf1c1Srobert : "relaxation not converged");
1652ece8a530Spatrick break;
1653ece8a530Spatrick }
1654ece8a530Spatrick
1655ece8a530Spatrick if (config->fixCortexA53Errata843419) {
1656ece8a530Spatrick if (changed)
1657ece8a530Spatrick script->assignAddresses();
1658ece8a530Spatrick changed |= a64p.createFixes();
1659ece8a530Spatrick }
1660ece8a530Spatrick if (config->fixCortexA8) {
1661ece8a530Spatrick if (changed)
1662ece8a530Spatrick script->assignAddresses();
1663ece8a530Spatrick changed |= a32p.createFixes();
1664ece8a530Spatrick }
1665ece8a530Spatrick
1666ece8a530Spatrick if (in.mipsGot)
1667ece8a530Spatrick in.mipsGot->updateAllocSize();
1668ece8a530Spatrick
1669ece8a530Spatrick for (Partition &part : partitions) {
1670ece8a530Spatrick changed |= part.relaDyn->updateAllocSize();
1671ece8a530Spatrick if (part.relrDyn)
1672ece8a530Spatrick changed |= part.relrDyn->updateAllocSize();
1673ece8a530Spatrick }
1674ece8a530Spatrick
1675ece8a530Spatrick const Defined *changedSym = script->assignAddresses();
1676ece8a530Spatrick if (!changed) {
1677ece8a530Spatrick // Some symbols may be dependent on section addresses. When we break the
1678ece8a530Spatrick // loop, the symbol values are finalized because a previous
1679ece8a530Spatrick // assignAddresses() finalized section addresses.
1680ece8a530Spatrick if (!changedSym)
1681ece8a530Spatrick break;
1682ece8a530Spatrick if (++assignPasses == 5) {
1683ece8a530Spatrick errorOrWarn("assignment to symbol " + toString(*changedSym) +
1684ece8a530Spatrick " does not converge");
1685ece8a530Spatrick break;
1686ece8a530Spatrick }
1687ece8a530Spatrick }
1688ece8a530Spatrick }
168905edf1c1Srobert if (!config->relocatable && config->emachine == EM_RISCV)
169005edf1c1Srobert riscvFinalizeRelax(pass);
169105edf1c1Srobert
169205edf1c1Srobert if (config->relocatable)
169305edf1c1Srobert for (OutputSection *sec : outputSections)
169405edf1c1Srobert sec->addr = 0;
1695bb684c34Spatrick
1696bb684c34Spatrick // If addrExpr is set, the address may not be a multiple of the alignment.
1697bb684c34Spatrick // Warn because this is error-prone.
169805edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
169905edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
170005edf1c1Srobert OutputSection *osec = &osd->osec;
170105edf1c1Srobert if (osec->addr % osec->addralign != 0)
170205edf1c1Srobert warn("address (0x" + Twine::utohexstr(osec->addr) + ") of section " +
170305edf1c1Srobert osec->name + " is not a multiple of alignment (" +
170405edf1c1Srobert Twine(osec->addralign) + ")");
170505edf1c1Srobert }
1706ece8a530Spatrick }
1707ece8a530Spatrick
1708a0747c9fSpatrick // If Input Sections have been shrunk (basic block sections) then
1709bb684c34Spatrick // update symbol values and sizes associated with these sections. With basic
1710bb684c34Spatrick // block sections, input sections can shrink when the jump instructions at
1711bb684c34Spatrick // the end of the section are relaxed.
fixSymbolsAfterShrinking()1712bb684c34Spatrick static void fixSymbolsAfterShrinking() {
171305edf1c1Srobert for (InputFile *File : ctx.objectFiles) {
1714bb684c34Spatrick parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1715bb684c34Spatrick auto *def = dyn_cast<Defined>(Sym);
1716bb684c34Spatrick if (!def)
1717bb684c34Spatrick return;
1718bb684c34Spatrick
1719bb684c34Spatrick const SectionBase *sec = def->section;
1720bb684c34Spatrick if (!sec)
1721bb684c34Spatrick return;
1722bb684c34Spatrick
172305edf1c1Srobert const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1724bb684c34Spatrick if (!inputSec || !inputSec->bytesDropped)
1725bb684c34Spatrick return;
1726bb684c34Spatrick
172705edf1c1Srobert const size_t OldSize = inputSec->content().size();
1728bb684c34Spatrick const size_t NewSize = OldSize - inputSec->bytesDropped;
1729bb684c34Spatrick
1730bb684c34Spatrick if (def->value > NewSize && def->value <= OldSize) {
1731bb684c34Spatrick LLVM_DEBUG(llvm::dbgs()
1732bb684c34Spatrick << "Moving symbol " << Sym->getName() << " from "
1733bb684c34Spatrick << def->value << " to "
1734bb684c34Spatrick << def->value - inputSec->bytesDropped << " bytes\n");
1735bb684c34Spatrick def->value -= inputSec->bytesDropped;
1736bb684c34Spatrick return;
1737bb684c34Spatrick }
1738bb684c34Spatrick
1739bb684c34Spatrick if (def->value + def->size > NewSize && def->value <= OldSize &&
1740bb684c34Spatrick def->value + def->size <= OldSize) {
1741bb684c34Spatrick LLVM_DEBUG(llvm::dbgs()
1742bb684c34Spatrick << "Shrinking symbol " << Sym->getName() << " from "
1743bb684c34Spatrick << def->size << " to " << def->size - inputSec->bytesDropped
1744bb684c34Spatrick << " bytes\n");
1745bb684c34Spatrick def->size -= inputSec->bytesDropped;
1746bb684c34Spatrick }
1747bb684c34Spatrick });
1748bb684c34Spatrick }
1749bb684c34Spatrick }
1750bb684c34Spatrick
1751bb684c34Spatrick // If basic block sections exist, there are opportunities to delete fall thru
1752bb684c34Spatrick // jumps and shrink jump instructions after basic block reordering. This
1753bb684c34Spatrick // relaxation pass does that. It is only enabled when --optimize-bb-jumps
1754bb684c34Spatrick // option is used.
optimizeBasicBlockJumps()1755bb684c34Spatrick template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1756bb684c34Spatrick assert(config->optimizeBBJumps);
175705edf1c1Srobert SmallVector<InputSection *, 0> storage;
1758bb684c34Spatrick
1759bb684c34Spatrick script->assignAddresses();
1760bb684c34Spatrick // For every output section that has executable input sections, this
1761bb684c34Spatrick // does the following:
1762bb684c34Spatrick // 1. Deletes all direct jump instructions in input sections that
1763bb684c34Spatrick // jump to the following section as it is not required.
1764bb684c34Spatrick // 2. If there are two consecutive jump instructions, it checks
1765bb684c34Spatrick // if they can be flipped and one can be deleted.
176605edf1c1Srobert for (OutputSection *osec : outputSections) {
176705edf1c1Srobert if (!(osec->flags & SHF_EXECINSTR))
1768bb684c34Spatrick continue;
176905edf1c1Srobert ArrayRef<InputSection *> sections = getInputSections(*osec, storage);
177005edf1c1Srobert size_t numDeleted = 0;
1771bb684c34Spatrick // Delete all fall through jump instructions. Also, check if two
1772bb684c34Spatrick // consecutive jump instructions can be flipped so that a fall
1773bb684c34Spatrick // through jmp instruction can be deleted.
177405edf1c1Srobert for (size_t i = 0, e = sections.size(); i != e; ++i) {
1775bb684c34Spatrick InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
177605edf1c1Srobert InputSection &sec = *sections[i];
177705edf1c1Srobert numDeleted += target->deleteFallThruJmpInsn(sec, sec.file, next);
177805edf1c1Srobert }
1779bb684c34Spatrick if (numDeleted > 0) {
1780bb684c34Spatrick script->assignAddresses();
1781bb684c34Spatrick LLVM_DEBUG(llvm::dbgs()
1782bb684c34Spatrick << "Removing " << numDeleted << " fall through jumps\n");
1783bb684c34Spatrick }
1784bb684c34Spatrick }
1785bb684c34Spatrick
1786bb684c34Spatrick fixSymbolsAfterShrinking();
1787bb684c34Spatrick
178805edf1c1Srobert for (OutputSection *osec : outputSections)
178905edf1c1Srobert for (InputSection *is : getInputSections(*osec, storage))
1790bb684c34Spatrick is->trim();
1791bb684c34Spatrick }
1792ece8a530Spatrick
1793ece8a530Spatrick // In order to allow users to manipulate linker-synthesized sections,
1794ece8a530Spatrick // we had to add synthetic sections to the input section list early,
1795ece8a530Spatrick // even before we make decisions whether they are needed. This allows
1796ece8a530Spatrick // users to write scripts like this: ".mygot : { .got }".
1797ece8a530Spatrick //
1798ece8a530Spatrick // Doing it has an unintended side effects. If it turns out that we
1799ece8a530Spatrick // don't need a .got (for example) at all because there's no
1800ece8a530Spatrick // relocation that needs a .got, we don't want to emit .got.
1801ece8a530Spatrick //
1802ece8a530Spatrick // To deal with the above problem, this function is called after
1803ece8a530Spatrick // scanRelocations is called to remove synthetic sections that turn
1804ece8a530Spatrick // out to be empty.
removeUnusedSyntheticSections()1805ece8a530Spatrick static void removeUnusedSyntheticSections() {
1806ece8a530Spatrick // All input synthetic sections that can be empty are placed after
1807a0747c9fSpatrick // all regular ones. Reverse iterate to find the first synthetic section
1808a0747c9fSpatrick // after a non-synthetic one which will be our starting point.
180905edf1c1Srobert auto start =
181005edf1c1Srobert llvm::find_if(llvm::reverse(ctx.inputSections), [](InputSectionBase *s) {
1811a0747c9fSpatrick return !isa<SyntheticSection>(s);
181205edf1c1Srobert }).base();
1813a0747c9fSpatrick
181405edf1c1Srobert // Remove unused synthetic sections from ctx.inputSections;
181505edf1c1Srobert DenseSet<InputSectionBase *> unused;
181605edf1c1Srobert auto end =
181705edf1c1Srobert std::remove_if(start, ctx.inputSections.end(), [&](InputSectionBase *s) {
181805edf1c1Srobert auto *sec = cast<SyntheticSection>(s);
181905edf1c1Srobert if (sec->getParent() && sec->isNeeded())
1820a0747c9fSpatrick return false;
182105edf1c1Srobert unused.insert(sec);
182205edf1c1Srobert return true;
1823a0747c9fSpatrick });
182405edf1c1Srobert ctx.inputSections.erase(end, ctx.inputSections.end());
1825a0747c9fSpatrick
182605edf1c1Srobert // Remove unused synthetic sections from the corresponding input section
182705edf1c1Srobert // description and orphanSections.
182805edf1c1Srobert for (auto *sec : unused)
182905edf1c1Srobert if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
183005edf1c1Srobert for (SectionCommand *cmd : osec->commands)
183105edf1c1Srobert if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
183205edf1c1Srobert llvm::erase_if(isd->sections, [&](InputSection *isec) {
183305edf1c1Srobert return unused.count(isec);
183405edf1c1Srobert });
183505edf1c1Srobert llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {
183605edf1c1Srobert return unused.count(sec);
183705edf1c1Srobert });
1838ece8a530Spatrick }
1839ece8a530Spatrick
1840ece8a530Spatrick // Create output section objects and add them to OutputSections.
finalizeSections()1841ece8a530Spatrick template <class ELFT> void Writer<ELFT>::finalizeSections() {
184205edf1c1Srobert if (!config->relocatable) {
1843ece8a530Spatrick Out::preinitArray = findSection(".preinit_array");
1844ece8a530Spatrick Out::initArray = findSection(".init_array");
1845ece8a530Spatrick Out::finiArray = findSection(".fini_array");
1846ece8a530Spatrick
1847ece8a530Spatrick // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1848ece8a530Spatrick // symbols for sections, so that the runtime can get the start and end
1849ece8a530Spatrick // addresses of each section by section name. Add such symbols.
1850ece8a530Spatrick addStartEndSymbols();
185105edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
185205edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd))
185305edf1c1Srobert addStartStopSymbols(osd->osec);
1854ece8a530Spatrick
1855ece8a530Spatrick // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1856ece8a530Spatrick // It should be okay as no one seems to care about the type.
1857ece8a530Spatrick // Even the author of gold doesn't remember why gold behaves that way.
1858ece8a530Spatrick // https://sourceware.org/ml/binutils/2002-03/msg00360.html
185905edf1c1Srobert if (mainPart->dynamic->parent) {
186005edf1c1Srobert Symbol *s = symtab.addSymbol(Defined{
186105edf1c1Srobert /*file=*/nullptr, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
186205edf1c1Srobert /*value=*/0, /*size=*/0, mainPart->dynamic.get()});
186305edf1c1Srobert s->isUsedInRegularObj = true;
186405edf1c1Srobert }
1865ece8a530Spatrick
1866ece8a530Spatrick // Define __rel[a]_iplt_{start,end} symbols if needed.
1867ece8a530Spatrick addRelIpltSymbols();
1868ece8a530Spatrick
1869ece8a530Spatrick // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1870ece8a530Spatrick // should only be defined in an executable. If .sdata does not exist, its
1871ece8a530Spatrick // value/section does not matter but it has to be relative, so set its
1872ece8a530Spatrick // st_shndx arbitrarily to 1 (Out::elfHeader).
1873ece8a530Spatrick if (config->emachine == EM_RISCV && !config->shared) {
1874ece8a530Spatrick OutputSection *sec = findSection(".sdata");
187505edf1c1Srobert addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader, 0x800,
187605edf1c1Srobert STV_DEFAULT);
1877ece8a530Spatrick }
1878ece8a530Spatrick
187905edf1c1Srobert if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
1880ece8a530Spatrick // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1881ece8a530Spatrick // way that:
1882ece8a530Spatrick //
1883ece8a530Spatrick // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1884ece8a530Spatrick // computes 0.
188505edf1c1Srobert // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address
188605edf1c1Srobert // in the TLS block).
1887ece8a530Spatrick //
188805edf1c1Srobert // 2) is special cased in @tpoff computation. To satisfy 1), we define it
188905edf1c1Srobert // as an absolute symbol of zero. This is different from GNU linkers which
1890ece8a530Spatrick // define _TLS_MODULE_BASE_ relative to the first TLS section.
189105edf1c1Srobert Symbol *s = symtab.find("_TLS_MODULE_BASE_");
1892ece8a530Spatrick if (s && s->isUndefined()) {
189305edf1c1Srobert s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL,
189405edf1c1Srobert STV_HIDDEN, STT_TLS, /*value=*/0, 0,
1895ece8a530Spatrick /*section=*/nullptr});
1896ece8a530Spatrick ElfSym::tlsModuleBase = cast<Defined>(s);
1897ece8a530Spatrick }
1898ece8a530Spatrick }
1899ece8a530Spatrick
1900ece8a530Spatrick // This responsible for splitting up .eh_frame section into
1901ece8a530Spatrick // pieces. The relocation scan uses those pieces, so this has to be
1902ece8a530Spatrick // earlier.
190305edf1c1Srobert {
190405edf1c1Srobert llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1905ece8a530Spatrick for (Partition &part : partitions)
190605edf1c1Srobert finalizeSynthetic(part.ehFrame.get());
1907a0747c9fSpatrick }
1908ece8a530Spatrick
190905edf1c1Srobert if (config->hasDynSymTab) {
191005edf1c1Srobert parallelForEach(symtab.getSymbols(), [](Symbol *sym) {
1911ece8a530Spatrick sym->isPreemptible = computeIsPreemptible(*sym);
191205edf1c1Srobert });
191305edf1c1Srobert }
191405edf1c1Srobert }
1915ece8a530Spatrick
1916ece8a530Spatrick // Change values of linker-script-defined symbols from placeholders (assigned
1917ece8a530Spatrick // by declareSymbols) to actual definitions.
1918ece8a530Spatrick script->processSymbolAssignments();
1919ece8a530Spatrick
192005edf1c1Srobert if (!config->relocatable) {
1921a0747c9fSpatrick llvm::TimeTraceScope timeScope("Scan relocations");
1922a0747c9fSpatrick // Scan relocations. This must be done after every symbol is declared so
1923a0747c9fSpatrick // that we can correctly decide if a dynamic relocation is needed. This is
1924a0747c9fSpatrick // called after processSymbolAssignments() because it needs to know whether
1925a0747c9fSpatrick // a linker-script-defined symbol is absolute.
1926bb684c34Spatrick ppc64noTocRelax.clear();
192705edf1c1Srobert scanRelocations<ELFT>();
192805edf1c1Srobert reportUndefinedSymbols();
192905edf1c1Srobert postScanRelocations();
1930ece8a530Spatrick
1931ece8a530Spatrick if (in.plt && in.plt->isNeeded())
1932ece8a530Spatrick in.plt->addSymbols();
1933ece8a530Spatrick if (in.iplt && in.iplt->isNeeded())
1934ece8a530Spatrick in.iplt->addSymbols();
1935ece8a530Spatrick
1936a0747c9fSpatrick if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1937a0747c9fSpatrick auto diagnose =
1938a0747c9fSpatrick config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
1939a0747c9fSpatrick ? errorOrWarn
1940a0747c9fSpatrick : warn;
1941ece8a530Spatrick // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1942ece8a530Spatrick // entries are seen. These cases would otherwise lead to runtime errors
1943ece8a530Spatrick // reported by the dynamic linker.
1944ece8a530Spatrick //
194505edf1c1Srobert // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker
194605edf1c1Srobert // to catch more cases. That is too much for us. Our approach resembles
194705edf1c1Srobert // the one used in ld.gold, achieves a good balance to be useful but not
194805edf1c1Srobert // too smart.
194905edf1c1Srobert for (SharedFile *file : ctx.sharedFiles) {
1950a0747c9fSpatrick bool allNeededIsKnown =
1951ece8a530Spatrick llvm::all_of(file->dtNeeded, [&](StringRef needed) {
195205edf1c1Srobert return symtab.soNames.count(CachedHashStringRef(needed));
1953ece8a530Spatrick });
1954a0747c9fSpatrick if (!allNeededIsKnown)
1955a0747c9fSpatrick continue;
1956a0747c9fSpatrick for (Symbol *sym : file->requiredSymbols)
1957ece8a530Spatrick if (sym->isUndefined() && !sym->isWeak())
195805edf1c1Srobert diagnose("undefined reference due to --no-allow-shlib-undefined: " +
195905edf1c1Srobert toString(*sym) + "\n>>> referenced by " + toString(file));
196005edf1c1Srobert }
1961ece8a530Spatrick }
1962a0747c9fSpatrick }
1963ece8a530Spatrick
1964a0747c9fSpatrick {
1965a0747c9fSpatrick llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1966ece8a530Spatrick // Now that we have defined all possible global symbols including linker-
1967ece8a530Spatrick // synthesized ones. Visit all symbols to give the finishing touches.
196805edf1c1Srobert for (Symbol *sym : symtab.getSymbols()) {
196905edf1c1Srobert if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
1970ece8a530Spatrick continue;
197105edf1c1Srobert if (!config->relocatable)
197205edf1c1Srobert sym->binding = sym->computeBinding();
1973ece8a530Spatrick if (in.symTab)
1974ece8a530Spatrick in.symTab->addSymbol(sym);
1975ece8a530Spatrick
1976ece8a530Spatrick if (sym->includeInDynsym()) {
1977ece8a530Spatrick partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1978ece8a530Spatrick if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1979ece8a530Spatrick if (file->isNeeded && !sym->isUndefined())
1980ece8a530Spatrick addVerneed(sym);
1981ece8a530Spatrick }
1982ece8a530Spatrick }
1983ece8a530Spatrick
1984a0747c9fSpatrick // We also need to scan the dynamic relocation tables of the other
1985a0747c9fSpatrick // partitions and add any referenced symbols to the partition's dynsym.
1986ece8a530Spatrick for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1987ece8a530Spatrick DenseSet<Symbol *> syms;
1988ece8a530Spatrick for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1989ece8a530Spatrick syms.insert(e.sym);
1990ece8a530Spatrick for (DynamicReloc &reloc : part.relaDyn->relocs)
1991a0747c9fSpatrick if (reloc.sym && reloc.needsDynSymIndex() &&
1992a0747c9fSpatrick syms.insert(reloc.sym).second)
1993ece8a530Spatrick part.dynSymTab->addSymbol(reloc.sym);
1994ece8a530Spatrick }
1995a0747c9fSpatrick }
1996ece8a530Spatrick
1997ece8a530Spatrick if (in.mipsGot)
1998ece8a530Spatrick in.mipsGot->build();
1999ece8a530Spatrick
2000ece8a530Spatrick removeUnusedSyntheticSections();
2001bb684c34Spatrick script->diagnoseOrphanHandling();
2002ece8a530Spatrick
2003ece8a530Spatrick sortSections();
2004ece8a530Spatrick
200505edf1c1Srobert // Create a list of OutputSections, assign sectionIndex, and populate
200605edf1c1Srobert // in.shStrTab.
200705edf1c1Srobert for (SectionCommand *cmd : script->sectionCommands)
200805edf1c1Srobert if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
200905edf1c1Srobert OutputSection *osec = &osd->osec;
201005edf1c1Srobert outputSections.push_back(osec);
201105edf1c1Srobert osec->sectionIndex = outputSections.size();
201205edf1c1Srobert osec->shName = in.shStrTab->addString(osec->name);
201305edf1c1Srobert }
2014ece8a530Spatrick
2015ece8a530Spatrick // Prefer command line supplied address over other constraints.
2016ece8a530Spatrick for (OutputSection *sec : outputSections) {
2017ece8a530Spatrick auto i = config->sectionStartMap.find(sec->name);
2018ece8a530Spatrick if (i != config->sectionStartMap.end())
2019ece8a530Spatrick sec->addrExpr = [=] { return i->second; };
2020ece8a530Spatrick }
2021ece8a530Spatrick
2022bb684c34Spatrick // With the outputSections available check for GDPLT relocations
2023bb684c34Spatrick // and add __tls_get_addr symbol if needed.
2024bb684c34Spatrick if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
202505edf1c1Srobert Symbol *sym = symtab.addSymbol(Undefined{
2026bb684c34Spatrick nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2027bb684c34Spatrick sym->isPreemptible = true;
2028bb684c34Spatrick partitions[0].dynSymTab->addSymbol(sym);
2029bb684c34Spatrick }
2030bb684c34Spatrick
2031ece8a530Spatrick // This is a bit of a hack. A value of 0 means undef, so we set it
2032ece8a530Spatrick // to 1 to make __ehdr_start defined. The section number is not
2033ece8a530Spatrick // particularly relevant.
2034ece8a530Spatrick Out::elfHeader->sectionIndex = 1;
203505edf1c1Srobert Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2036ece8a530Spatrick
2037ece8a530Spatrick // Binary and relocatable output does not have PHDRS.
2038ece8a530Spatrick // The headers have to be created before finalize as that can influence the
2039ece8a530Spatrick // image base and the dynamic section on mips includes the image base.
2040ece8a530Spatrick if (!config->relocatable && !config->oFormatBinary) {
2041ece8a530Spatrick for (Partition &part : partitions) {
2042ece8a530Spatrick part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2043ece8a530Spatrick : createPhdrs(part);
2044ece8a530Spatrick if (config->emachine == EM_ARM) {
2045ece8a530Spatrick // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2046ece8a530Spatrick addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2047ece8a530Spatrick }
2048ece8a530Spatrick if (config->emachine == EM_MIPS) {
2049ece8a530Spatrick // Add separate segments for MIPS-specific sections.
2050ece8a530Spatrick addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2051ece8a530Spatrick addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2052ece8a530Spatrick addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2053ece8a530Spatrick }
2054ece8a530Spatrick }
2055ece8a530Spatrick Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2056ece8a530Spatrick
2057ece8a530Spatrick // Find the TLS segment. This happens before the section layout loop so that
2058ece8a530Spatrick // Android relocation packing can look up TLS symbol addresses. We only need
2059ece8a530Spatrick // to care about the main partition here because all TLS symbols were moved
2060ece8a530Spatrick // to the main partition (see MarkLive.cpp).
2061ece8a530Spatrick for (PhdrEntry *p : mainPart->phdrs)
2062ece8a530Spatrick if (p->p_type == PT_TLS)
2063ece8a530Spatrick Out::tlsPhdr = p;
2064ece8a530Spatrick }
2065ece8a530Spatrick
2066ece8a530Spatrick // Some symbols are defined in term of program headers. Now that we
2067ece8a530Spatrick // have the headers, we can find out which sections they point to.
2068ece8a530Spatrick setReservedSymbolSections();
2069ece8a530Spatrick
2070a0747c9fSpatrick {
2071a0747c9fSpatrick llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2072a0747c9fSpatrick
207305edf1c1Srobert finalizeSynthetic(in.bss.get());
207405edf1c1Srobert finalizeSynthetic(in.bssRelRo.get());
207505edf1c1Srobert finalizeSynthetic(in.symTabShndx.get());
207605edf1c1Srobert finalizeSynthetic(in.shStrTab.get());
207705edf1c1Srobert finalizeSynthetic(in.strTab.get());
207805edf1c1Srobert finalizeSynthetic(in.got.get());
207905edf1c1Srobert finalizeSynthetic(in.mipsGot.get());
208005edf1c1Srobert finalizeSynthetic(in.igotPlt.get());
208105edf1c1Srobert finalizeSynthetic(in.gotPlt.get());
208205edf1c1Srobert finalizeSynthetic(in.relaIplt.get());
208305edf1c1Srobert finalizeSynthetic(in.relaPlt.get());
208405edf1c1Srobert finalizeSynthetic(in.plt.get());
208505edf1c1Srobert finalizeSynthetic(in.iplt.get());
208605edf1c1Srobert finalizeSynthetic(in.ppc32Got2.get());
208705edf1c1Srobert finalizeSynthetic(in.partIndex.get());
2088ece8a530Spatrick
2089ece8a530Spatrick // Dynamic section must be the last one in this list and dynamic
2090ece8a530Spatrick // symbol table section (dynSymTab) must be the first one.
2091ece8a530Spatrick for (Partition &part : partitions) {
209205edf1c1Srobert if (part.relaDyn) {
209305edf1c1Srobert part.relaDyn->mergeRels();
209405edf1c1Srobert // Compute DT_RELACOUNT to be used by part.dynamic.
209505edf1c1Srobert part.relaDyn->partitionRels();
209605edf1c1Srobert finalizeSynthetic(part.relaDyn.get());
209705edf1c1Srobert }
209805edf1c1Srobert if (part.relrDyn) {
209905edf1c1Srobert part.relrDyn->mergeRels();
210005edf1c1Srobert finalizeSynthetic(part.relrDyn.get());
210105edf1c1Srobert }
210205edf1c1Srobert
210305edf1c1Srobert finalizeSynthetic(part.dynSymTab.get());
210405edf1c1Srobert finalizeSynthetic(part.gnuHashTab.get());
210505edf1c1Srobert finalizeSynthetic(part.hashTab.get());
210605edf1c1Srobert finalizeSynthetic(part.verDef.get());
210705edf1c1Srobert finalizeSynthetic(part.ehFrameHdr.get());
210805edf1c1Srobert finalizeSynthetic(part.verSym.get());
210905edf1c1Srobert finalizeSynthetic(part.verNeed.get());
211005edf1c1Srobert finalizeSynthetic(part.dynamic.get());
2111ece8a530Spatrick }
2112a0747c9fSpatrick }
2113ece8a530Spatrick
2114ece8a530Spatrick if (!script->hasSectionsCommand && !config->relocatable)
2115ece8a530Spatrick fixSectionAlignments();
2116ece8a530Spatrick
2117ece8a530Spatrick // This is used to:
2118ece8a530Spatrick // 1) Create "thunks":
2119ece8a530Spatrick // Jump instructions in many ISAs have small displacements, and therefore
2120ece8a530Spatrick // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2121ece8a530Spatrick // JAL instruction can target only +-1 MiB from PC. It is a linker's
2122ece8a530Spatrick // responsibility to create and insert small pieces of code between
2123ece8a530Spatrick // sections to extend the ranges if jump targets are out of range. Such
2124ece8a530Spatrick // code pieces are called "thunks".
2125ece8a530Spatrick //
2126ece8a530Spatrick // We add thunks at this stage. We couldn't do this before this point
2127ece8a530Spatrick // because this is the earliest point where we know sizes of sections and
2128ece8a530Spatrick // their layouts (that are needed to determine if jump targets are in
2129ece8a530Spatrick // range).
2130ece8a530Spatrick //
2131ece8a530Spatrick // 2) Update the sections. We need to generate content that depends on the
2132ece8a530Spatrick // address of InputSections. For example, MIPS GOT section content or
2133ece8a530Spatrick // android packed relocations sections content.
2134ece8a530Spatrick //
2135ece8a530Spatrick // 3) Assign the final values for the linker script symbols. Linker scripts
2136ece8a530Spatrick // sometimes using forward symbol declarations. We want to set the correct
2137ece8a530Spatrick // values. They also might change after adding the thunks.
2138ece8a530Spatrick finalizeAddressDependentContent();
213905edf1c1Srobert
214005edf1c1Srobert // All information needed for OutputSection part of Map file is available.
2141bb684c34Spatrick if (errorCount())
2142bb684c34Spatrick return;
2143ece8a530Spatrick
2144a0747c9fSpatrick {
2145a0747c9fSpatrick llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2146a0747c9fSpatrick // finalizeAddressDependentContent may have added local symbols to the
2147a0747c9fSpatrick // static symbol table.
214805edf1c1Srobert finalizeSynthetic(in.symTab.get());
214905edf1c1Srobert finalizeSynthetic(in.ppc64LongBranchTarget.get());
2150a0747c9fSpatrick }
2151ece8a530Spatrick
2152bb684c34Spatrick // Relaxation to delete inter-basic block jumps created by basic block
2153bb684c34Spatrick // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2154bb684c34Spatrick // can relax jump instructions based on symbol offset.
2155bb684c34Spatrick if (config->optimizeBBJumps)
2156bb684c34Spatrick optimizeBasicBlockJumps();
2157bb684c34Spatrick
2158ece8a530Spatrick // Fill other section headers. The dynamic table is finalized
2159ece8a530Spatrick // at the end because some tags like RELSZ depend on result
2160ece8a530Spatrick // of finalizing other sections.
2161ece8a530Spatrick for (OutputSection *sec : outputSections)
2162ece8a530Spatrick sec->finalize();
2163ece8a530Spatrick }
2164ece8a530Spatrick
2165ece8a530Spatrick // Ensure data sections are not mixed with executable sections when
216605edf1c1Srobert // --execute-only is used. --execute-only make pages executable but not
216705edf1c1Srobert // readable.
checkExecuteOnly()2168ece8a530Spatrick template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2169ece8a530Spatrick if (!config->executeOnly)
2170ece8a530Spatrick return;
2171ece8a530Spatrick
217205edf1c1Srobert SmallVector<InputSection *, 0> storage;
217305edf1c1Srobert for (OutputSection *osec : outputSections)
217405edf1c1Srobert if (osec->flags & SHF_EXECINSTR)
217505edf1c1Srobert for (InputSection *isec : getInputSections(*osec, storage))
2176ece8a530Spatrick if (!(isec->flags & SHF_EXECINSTR))
217705edf1c1Srobert error("cannot place " + toString(isec) + " into " +
217805edf1c1Srobert toString(osec->name) +
217905edf1c1Srobert ": --execute-only does not support intermingling data and code");
2180ece8a530Spatrick }
2181ece8a530Spatrick
2182ece8a530Spatrick // The linker is expected to define SECNAME_start and SECNAME_end
2183ece8a530Spatrick // symbols for a few sections. This function defines them.
addStartEndSymbols()2184ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2185ece8a530Spatrick // If a section does not exist, there's ambiguity as to how we
2186ece8a530Spatrick // define _start and _end symbols for an init/fini section. Since
2187ece8a530Spatrick // the loader assume that the symbols are always defined, we need to
2188ece8a530Spatrick // always define them. But what value? The loader iterates over all
2189ece8a530Spatrick // pointers between _start and _end to run global ctors/dtors, so if
2190ece8a530Spatrick // the section is empty, their symbol values don't actually matter
2191ece8a530Spatrick // as long as _start and _end point to the same location.
2192ece8a530Spatrick //
2193ece8a530Spatrick // That said, we don't want to set the symbols to 0 (which is
2194ece8a530Spatrick // probably the simplest value) because that could cause some
2195ece8a530Spatrick // program to fail to link due to relocation overflow, if their
2196ece8a530Spatrick // program text is above 2 GiB. We use the address of the .text
2197ece8a530Spatrick // section instead to prevent that failure.
2198ece8a530Spatrick //
2199ece8a530Spatrick // In rare situations, the .text section may not exist. If that's the
2200ece8a530Spatrick // case, use the image base address as a last resort.
2201ece8a530Spatrick OutputSection *Default = findSection(".text");
2202ece8a530Spatrick if (!Default)
2203ece8a530Spatrick Default = Out::elfHeader;
2204ece8a530Spatrick
2205ece8a530Spatrick auto define = [=](StringRef start, StringRef end, OutputSection *os) {
220605edf1c1Srobert if (os && !script->isDiscarded(os)) {
2207ece8a530Spatrick addOptionalRegular(start, os, 0);
2208ece8a530Spatrick addOptionalRegular(end, os, -1);
2209ece8a530Spatrick } else {
2210ece8a530Spatrick addOptionalRegular(start, Default, 0);
2211ece8a530Spatrick addOptionalRegular(end, Default, 0);
2212ece8a530Spatrick }
2213ece8a530Spatrick };
2214ece8a530Spatrick
2215ece8a530Spatrick define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2216ece8a530Spatrick define("__init_array_start", "__init_array_end", Out::initArray);
2217ece8a530Spatrick define("__fini_array_start", "__fini_array_end", Out::finiArray);
2218ece8a530Spatrick
2219ece8a530Spatrick if (OutputSection *sec = findSection(".ARM.exidx"))
2220ece8a530Spatrick define("__exidx_start", "__exidx_end", sec);
2221ece8a530Spatrick }
2222ece8a530Spatrick
2223ece8a530Spatrick // If a section name is valid as a C identifier (which is rare because of
2224ece8a530Spatrick // the leading '.'), linkers are expected to define __start_<secname> and
2225ece8a530Spatrick // __stop_<secname> symbols. They are at beginning and end of the section,
2226ece8a530Spatrick // respectively. This is not requested by the ELF standard, but GNU ld and
2227ece8a530Spatrick // gold provide the feature, and used by many programs.
2228ece8a530Spatrick template <class ELFT>
addStartStopSymbols(OutputSection & osec)222905edf1c1Srobert void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
223005edf1c1Srobert StringRef s = osec.name;
2231ece8a530Spatrick if (!isValidCIdentifier(s))
2232ece8a530Spatrick return;
223305edf1c1Srobert addOptionalRegular(saver().save("__start_" + s), &osec, 0,
2234bb684c34Spatrick config->zStartStopVisibility);
223505edf1c1Srobert addOptionalRegular(saver().save("__stop_" + s), &osec, -1,
2236bb684c34Spatrick config->zStartStopVisibility);
2237ece8a530Spatrick }
2238ece8a530Spatrick
needsPtLoad(OutputSection * sec)2239ece8a530Spatrick static bool needsPtLoad(OutputSection *sec) {
2240a0747c9fSpatrick if (!(sec->flags & SHF_ALLOC))
2241ece8a530Spatrick return false;
2242ece8a530Spatrick
2243ece8a530Spatrick // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2244ece8a530Spatrick // responsible for allocating space for them, not the PT_LOAD that
2245ece8a530Spatrick // contains the TLS initialization image.
2246ece8a530Spatrick if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2247ece8a530Spatrick return false;
2248ece8a530Spatrick return true;
2249ece8a530Spatrick }
2250ece8a530Spatrick
2251ece8a530Spatrick // Linker scripts are responsible for aligning addresses. Unfortunately, most
2252ece8a530Spatrick // linker scripts are designed for creating two PT_LOADs only, one RX and one
2253ece8a530Spatrick // RW. This means that there is no alignment in the RO to RX transition and we
2254ece8a530Spatrick // cannot create a PT_LOAD there.
computeFlags(uint64_t flags)2255ece8a530Spatrick static uint64_t computeFlags(uint64_t flags) {
2256ece8a530Spatrick if (config->omagic)
2257ece8a530Spatrick return PF_R | PF_W | PF_X;
2258ece8a530Spatrick if (config->executeOnly && (flags & PF_X))
2259ece8a530Spatrick return flags & ~PF_R;
2260ece8a530Spatrick if (config->singleRoRx && !(flags & PF_W))
2261ece8a530Spatrick return flags | PF_X;
2262ece8a530Spatrick return flags;
2263ece8a530Spatrick }
2264ece8a530Spatrick
2265ece8a530Spatrick // Decide which program headers to create and which sections to include in each
2266ece8a530Spatrick // one.
2267ece8a530Spatrick template <class ELFT>
createPhdrs(Partition & part)226805edf1c1Srobert SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
226905edf1c1Srobert SmallVector<PhdrEntry *, 0> ret;
2270ece8a530Spatrick auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2271ece8a530Spatrick ret.push_back(make<PhdrEntry>(type, flags));
2272ece8a530Spatrick return ret.back();
2273ece8a530Spatrick };
2274ece8a530Spatrick
2275ece8a530Spatrick unsigned partNo = part.getNumber();
2276ece8a530Spatrick bool isMain = partNo == 1;
2277ece8a530Spatrick
2278ece8a530Spatrick // Add the first PT_LOAD segment for regular output sections.
2279ece8a530Spatrick uint64_t flags = computeFlags(PF_R);
2280ece8a530Spatrick PhdrEntry *load = nullptr;
2281ece8a530Spatrick
2282ece8a530Spatrick // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2283ece8a530Spatrick // PT_LOAD.
2284ece8a530Spatrick if (!config->nmagic && !config->omagic) {
2285ece8a530Spatrick // The first phdr entry is PT_PHDR which describes the program header
2286ece8a530Spatrick // itself.
2287ece8a530Spatrick if (isMain)
2288ece8a530Spatrick addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2289ece8a530Spatrick else
2290ece8a530Spatrick addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2291ece8a530Spatrick
2292ece8a530Spatrick // PT_INTERP must be the second entry if exists.
2293ece8a530Spatrick if (OutputSection *cmd = findSection(".interp", partNo))
2294ece8a530Spatrick addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2295ece8a530Spatrick
2296ece8a530Spatrick // Add the headers. We will remove them if they don't fit.
2297ece8a530Spatrick // In the other partitions the headers are ordinary sections, so they don't
2298ece8a530Spatrick // need to be added here.
2299ece8a530Spatrick if (isMain) {
2300ece8a530Spatrick load = addHdr(PT_LOAD, flags);
2301ece8a530Spatrick load->add(Out::elfHeader);
2302ece8a530Spatrick load->add(Out::programHeaders);
2303ece8a530Spatrick }
2304ece8a530Spatrick }
2305ece8a530Spatrick
2306ece8a530Spatrick // PT_GNU_RELRO includes all sections that should be marked as
2307ece8a530Spatrick // read-only by dynamic linker after processing relocations.
2308ece8a530Spatrick // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2309ece8a530Spatrick // an error message if more than one PT_GNU_RELRO PHDR is required.
2310ece8a530Spatrick PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2311ece8a530Spatrick bool inRelroPhdr = false;
2312ece8a530Spatrick OutputSection *relroEnd = nullptr;
2313ece8a530Spatrick for (OutputSection *sec : outputSections) {
2314ece8a530Spatrick if (sec->partition != partNo || !needsPtLoad(sec))
2315ece8a530Spatrick continue;
2316ece8a530Spatrick if (isRelroSection(sec)) {
2317ece8a530Spatrick inRelroPhdr = true;
2318ece8a530Spatrick if (!relroEnd)
2319ece8a530Spatrick relRo->add(sec);
2320ece8a530Spatrick else
2321ece8a530Spatrick error("section: " + sec->name + " is not contiguous with other relro" +
2322ece8a530Spatrick " sections");
2323ece8a530Spatrick } else if (inRelroPhdr) {
2324ece8a530Spatrick inRelroPhdr = false;
2325ece8a530Spatrick relroEnd = sec;
2326ece8a530Spatrick }
2327ece8a530Spatrick }
2328ece8a530Spatrick
2329ece8a530Spatrick for (OutputSection *sec : outputSections) {
2330ece8a530Spatrick if (!needsPtLoad(sec))
2331ece8a530Spatrick continue;
2332ece8a530Spatrick
2333ece8a530Spatrick // Normally, sections in partitions other than the current partition are
2334ece8a530Spatrick // ignored. But partition number 255 is a special case: it contains the
2335ece8a530Spatrick // partition end marker (.part.end). It needs to be added to the main
2336ece8a530Spatrick // partition so that a segment is created for it in the main partition,
2337ece8a530Spatrick // which will cause the dynamic loader to reserve space for the other
2338ece8a530Spatrick // partitions.
2339ece8a530Spatrick if (sec->partition != partNo) {
2340ece8a530Spatrick if (isMain && sec->partition == 255)
2341ece8a530Spatrick addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2342ece8a530Spatrick continue;
2343ece8a530Spatrick }
2344ece8a530Spatrick
2345ece8a530Spatrick // Segments are contiguous memory regions that has the same attributes
2346ece8a530Spatrick // (e.g. executable or writable). There is one phdr for each segment.
2347ece8a530Spatrick // Therefore, we need to create a new phdr when the next section has
2348ece8a530Spatrick // different flags or is loaded at a discontiguous address or memory
2349ece8a530Spatrick // region using AT or AT> linker script command, respectively. At the same
2350ece8a530Spatrick // time, we don't want to create a separate load segment for the headers,
2351ece8a530Spatrick // even if the first output section has an AT or AT> attribute.
2352ece8a530Spatrick uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2353bb684c34Spatrick bool sameLMARegion =
2354bb684c34Spatrick load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2355bb684c34Spatrick if (!(load && newFlags == flags && sec != relroEnd &&
2356bb684c34Spatrick sec->memRegion == load->firstSec->memRegion &&
2357bb684c34Spatrick (sameLMARegion || load->lastSec == Out::programHeaders))) {
2358ece8a530Spatrick load = addHdr(PT_LOAD, newFlags);
2359ece8a530Spatrick flags = newFlags;
2360ece8a530Spatrick }
2361ece8a530Spatrick
2362ece8a530Spatrick load->add(sec);
2363ece8a530Spatrick }
2364ece8a530Spatrick
2365ece8a530Spatrick // Add a TLS segment if any.
2366ece8a530Spatrick PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2367ece8a530Spatrick for (OutputSection *sec : outputSections)
2368ece8a530Spatrick if (sec->partition == partNo && sec->flags & SHF_TLS)
2369ece8a530Spatrick tlsHdr->add(sec);
2370ece8a530Spatrick if (tlsHdr->firstSec)
2371ece8a530Spatrick ret.push_back(tlsHdr);
2372ece8a530Spatrick
2373ece8a530Spatrick // Add an entry for .dynamic.
2374ece8a530Spatrick if (OutputSection *sec = part.dynamic->getParent())
2375ece8a530Spatrick addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2376ece8a530Spatrick
2377ece8a530Spatrick if (relRo->firstSec)
2378ece8a530Spatrick ret.push_back(relRo);
2379ece8a530Spatrick
2380ece8a530Spatrick // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2381ece8a530Spatrick if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2382ece8a530Spatrick part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2383ece8a530Spatrick addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2384ece8a530Spatrick ->add(part.ehFrameHdr->getParent());
2385ece8a530Spatrick
2386bd249b56Sderaadt // PT_OPENBSD_MUTABLE is an OpenBSD-specific feature. That makes
2387bd249b56Sderaadt // the dynamic linker fill the segment with zero data, like bss, but
2388bd249b56Sderaadt // it can be treated differently.
2389bd249b56Sderaadt if (OutputSection *cmd = findSection(".openbsd.mutable", partNo))
2390bd249b56Sderaadt addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
2391bd249b56Sderaadt
2392ece8a530Spatrick // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2393ece8a530Spatrick // the dynamic linker fill the segment with random data.
2394ece8a530Spatrick if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2395ece8a530Spatrick addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2396ece8a530Spatrick
239742a61aceSkettenis // PT_OPENBSD_SYSCALLS is an OpenBSD-specific feature. That makes
239842a61aceSkettenis // the kernel and dynamic linker register system call sites.
239942a61aceSkettenis if (OutputSection *cmd = findSection(".openbsd.syscalls", partNo))
240042a61aceSkettenis addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
240142a61aceSkettenis
2402ece8a530Spatrick if (config->zGnustack != GnuStackKind::None) {
2403ece8a530Spatrick // PT_GNU_STACK is a special section to tell the loader to make the
2404ece8a530Spatrick // pages for the stack non-executable. If you really want an executable
2405ece8a530Spatrick // stack, you can pass -z execstack, but that's not recommended for
2406ece8a530Spatrick // security reasons.
2407ece8a530Spatrick unsigned perm = PF_R | PF_W;
2408ece8a530Spatrick if (config->zGnustack == GnuStackKind::Exec)
2409ece8a530Spatrick perm |= PF_X;
2410ece8a530Spatrick addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2411ece8a530Spatrick }
2412ece8a530Spatrick
2413ece8a530Spatrick // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2414ece8a530Spatrick // is expected to perform W^X violations, such as calling mprotect(2) or
2415ece8a530Spatrick // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2416ece8a530Spatrick // OpenBSD.
2417ece8a530Spatrick if (config->zWxneeded)
2418ece8a530Spatrick addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2419ece8a530Spatrick
24207b407c47Skettenis // PT_OPENBSD_NOBTCFI is an OpenBSD-specific header to mark that the
24217b407c47Skettenis // executable is expected to violate branch-target CFI checks.
24227b407c47Skettenis if (config->zNoBtCfi)
24237b407c47Skettenis addHdr(PT_OPENBSD_NOBTCFI, PF_X);
24247b407c47Skettenis
2425ece8a530Spatrick if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2426ece8a530Spatrick addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2427ece8a530Spatrick
2428ece8a530Spatrick // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2429ece8a530Spatrick // same alignment.
2430ece8a530Spatrick PhdrEntry *note = nullptr;
2431ece8a530Spatrick for (OutputSection *sec : outputSections) {
2432ece8a530Spatrick if (sec->partition != partNo)
2433ece8a530Spatrick continue;
2434ece8a530Spatrick if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
243505edf1c1Srobert if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2436ece8a530Spatrick note = addHdr(PT_NOTE, PF_R);
2437ece8a530Spatrick note->add(sec);
2438ece8a530Spatrick } else {
2439ece8a530Spatrick note = nullptr;
2440ece8a530Spatrick }
2441ece8a530Spatrick }
2442ece8a530Spatrick return ret;
2443ece8a530Spatrick }
2444ece8a530Spatrick
2445ece8a530Spatrick template <class ELFT>
addPhdrForSection(Partition & part,unsigned shType,unsigned pType,unsigned pFlags)2446ece8a530Spatrick void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2447ece8a530Spatrick unsigned pType, unsigned pFlags) {
2448ece8a530Spatrick unsigned partNo = part.getNumber();
2449ece8a530Spatrick auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2450ece8a530Spatrick return cmd->partition == partNo && cmd->type == shType;
2451ece8a530Spatrick });
2452ece8a530Spatrick if (i == outputSections.end())
2453ece8a530Spatrick return;
2454ece8a530Spatrick
2455ece8a530Spatrick PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2456ece8a530Spatrick entry->add(*i);
2457ece8a530Spatrick part.phdrs.push_back(entry);
2458ece8a530Spatrick }
2459ece8a530Spatrick
2460ece8a530Spatrick // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2461ece8a530Spatrick // This is achieved by assigning an alignment expression to addrExpr of each
2462ece8a530Spatrick // such section.
fixSectionAlignments()2463ece8a530Spatrick template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2464ece8a530Spatrick const PhdrEntry *prev;
2465ece8a530Spatrick auto pageAlign = [&](const PhdrEntry *p) {
2466ece8a530Spatrick OutputSection *cmd = p->firstSec;
2467bb684c34Spatrick if (!cmd)
2468bb684c34Spatrick return;
246905edf1c1Srobert cmd->alignExpr = [align = cmd->addralign]() { return align; };
2470bb684c34Spatrick if (!cmd->addrExpr) {
2471ece8a530Spatrick // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2472ece8a530Spatrick // padding in the file contents.
2473ece8a530Spatrick //
2474ece8a530Spatrick // When -z separate-code is used we must not have any overlap in pages
2475ece8a530Spatrick // between an executable segment and a non-executable segment. We align to
2476ece8a530Spatrick // the next maximum page size boundary on transitions between executable
2477ece8a530Spatrick // and non-executable segments.
2478ece8a530Spatrick //
2479ece8a530Spatrick // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2480ece8a530Spatrick // sections will be extracted to a separate file. Align to the next
2481ece8a530Spatrick // maximum page size boundary so that we can find the ELF header at the
2482ece8a530Spatrick // start. We cannot benefit from overlapping p_offset ranges with the
2483ece8a530Spatrick // previous segment anyway.
2484ece8a530Spatrick if (config->zSeparate == SeparateSegmentKind::Loadable ||
2485ece8a530Spatrick (config->zSeparate == SeparateSegmentKind::Code && prev &&
2486ece8a530Spatrick (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2487ece8a530Spatrick cmd->type == SHT_LLVM_PART_EHDR)
2488ece8a530Spatrick cmd->addrExpr = [] {
248905edf1c1Srobert return alignToPowerOf2(script->getDot(), config->maxPageSize);
2490ece8a530Spatrick };
2491ece8a530Spatrick // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2492ece8a530Spatrick // it must be the RW. Align to p_align(PT_TLS) to make sure
2493ece8a530Spatrick // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2494ece8a530Spatrick // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2495ece8a530Spatrick // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2496ece8a530Spatrick // be congruent to 0 modulo p_align(PT_TLS).
2497ece8a530Spatrick //
2498ece8a530Spatrick // Technically this is not required, but as of 2019, some dynamic loaders
2499ece8a530Spatrick // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2500ece8a530Spatrick // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2501ece8a530Spatrick // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2502ece8a530Spatrick // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2503ece8a530Spatrick // blocks correctly. We need to keep the workaround for a while.
2504ece8a530Spatrick else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2505ece8a530Spatrick cmd->addrExpr = [] {
250605edf1c1Srobert return alignToPowerOf2(script->getDot(), config->maxPageSize) +
250705edf1c1Srobert alignToPowerOf2(script->getDot() % config->maxPageSize,
2508ece8a530Spatrick Out::tlsPhdr->p_align);
2509ece8a530Spatrick };
2510ece8a530Spatrick else
2511ece8a530Spatrick cmd->addrExpr = [] {
251205edf1c1Srobert return alignToPowerOf2(script->getDot(), config->maxPageSize) +
2513ece8a530Spatrick script->getDot() % config->maxPageSize;
2514ece8a530Spatrick };
2515ece8a530Spatrick }
2516ece8a530Spatrick };
2517ece8a530Spatrick
2518adae0cfdSpatrick #ifdef __OpenBSD__
2519adae0cfdSpatrick // On i386, produce binaries that are compatible with our W^X implementation
2520adae0cfdSpatrick if (config->emachine == EM_386) {
2521adae0cfdSpatrick auto NXAlign = [](OutputSection *Cmd) {
2522adae0cfdSpatrick if (Cmd && !Cmd->addrExpr)
2523adae0cfdSpatrick Cmd->addrExpr = [=] {
2524adae0cfdSpatrick return alignTo(script->getDot(), 0x20000000);
2525adae0cfdSpatrick };
2526adae0cfdSpatrick };
2527adae0cfdSpatrick
2528adae0cfdSpatrick for (Partition &part : partitions) {
2529adae0cfdSpatrick PhdrEntry *firstRW = nullptr;
2530adae0cfdSpatrick for (PhdrEntry *P : part.phdrs) {
2531adae0cfdSpatrick if (P->p_type == PT_LOAD && (P->p_flags & PF_W)) {
2532adae0cfdSpatrick firstRW = P;
2533adae0cfdSpatrick break;
2534adae0cfdSpatrick }
2535adae0cfdSpatrick }
2536adae0cfdSpatrick
2537adae0cfdSpatrick if (firstRW)
2538adae0cfdSpatrick NXAlign(firstRW->firstSec);
2539adae0cfdSpatrick }
2540adae0cfdSpatrick }
2541adae0cfdSpatrick #endif
2542adae0cfdSpatrick
2543ece8a530Spatrick for (Partition &part : partitions) {
2544ece8a530Spatrick prev = nullptr;
2545ece8a530Spatrick for (const PhdrEntry *p : part.phdrs)
2546ece8a530Spatrick if (p->p_type == PT_LOAD && p->firstSec) {
2547ece8a530Spatrick pageAlign(p);
2548ece8a530Spatrick prev = p;
2549ece8a530Spatrick }
2550ece8a530Spatrick }
2551ece8a530Spatrick }
2552ece8a530Spatrick
2553ece8a530Spatrick // Compute an in-file position for a given section. The file offset must be the
2554ece8a530Spatrick // same with its virtual address modulo the page size, so that the loader can
2555ece8a530Spatrick // load executables without any address adjustment.
computeFileOffset(OutputSection * os,uint64_t off)2556ece8a530Spatrick static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2557ece8a530Spatrick // The first section in a PT_LOAD has to have congruent offset and address
2558ece8a530Spatrick // modulo the maximum page size.
2559ece8a530Spatrick if (os->ptLoad && os->ptLoad->firstSec == os)
2560ece8a530Spatrick return alignTo(off, os->ptLoad->p_align, os->addr);
2561ece8a530Spatrick
2562ece8a530Spatrick // File offsets are not significant for .bss sections other than the first one
256305edf1c1Srobert // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2564ece8a530Spatrick // increasing rather than setting to zero.
256505edf1c1Srobert if (os->type == SHT_NOBITS &&
256605edf1c1Srobert (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2567ece8a530Spatrick return off;
2568ece8a530Spatrick
2569ece8a530Spatrick // If the section is not in a PT_LOAD, we just have to align it.
2570ece8a530Spatrick if (!os->ptLoad)
257105edf1c1Srobert return alignToPowerOf2(off, os->addralign);
2572ece8a530Spatrick
2573ece8a530Spatrick // If two sections share the same PT_LOAD the file offset is calculated
2574ece8a530Spatrick // using this formula: Off2 = Off1 + (VA2 - VA1).
2575ece8a530Spatrick OutputSection *first = os->ptLoad->firstSec;
2576ece8a530Spatrick return first->offset + os->addr - first->addr;
2577ece8a530Spatrick }
2578ece8a530Spatrick
assignFileOffsetsBinary()2579ece8a530Spatrick template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2580a0747c9fSpatrick // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2581a0747c9fSpatrick auto needsOffset = [](OutputSection &sec) {
2582a0747c9fSpatrick return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2583a0747c9fSpatrick };
2584a0747c9fSpatrick uint64_t minAddr = UINT64_MAX;
2585ece8a530Spatrick for (OutputSection *sec : outputSections)
2586a0747c9fSpatrick if (needsOffset(*sec)) {
2587a0747c9fSpatrick sec->offset = sec->getLMA();
2588a0747c9fSpatrick minAddr = std::min(minAddr, sec->offset);
2589a0747c9fSpatrick }
2590a0747c9fSpatrick
2591a0747c9fSpatrick // Sections are laid out at LMA minus minAddr.
2592a0747c9fSpatrick fileSize = 0;
2593a0747c9fSpatrick for (OutputSection *sec : outputSections)
2594a0747c9fSpatrick if (needsOffset(*sec)) {
2595a0747c9fSpatrick sec->offset -= minAddr;
2596a0747c9fSpatrick fileSize = std::max(fileSize, sec->offset + sec->size);
2597a0747c9fSpatrick }
2598ece8a530Spatrick }
2599ece8a530Spatrick
rangeToString(uint64_t addr,uint64_t len)2600ece8a530Spatrick static std::string rangeToString(uint64_t addr, uint64_t len) {
2601ece8a530Spatrick return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2602ece8a530Spatrick }
2603ece8a530Spatrick
2604ece8a530Spatrick // Assign file offsets to output sections.
assignFileOffsets()2605ece8a530Spatrick template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
260605edf1c1Srobert Out::programHeaders->offset = Out::elfHeader->size;
260705edf1c1Srobert uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
2608ece8a530Spatrick
2609ece8a530Spatrick PhdrEntry *lastRX = nullptr;
2610ece8a530Spatrick for (Partition &part : partitions)
2611ece8a530Spatrick for (PhdrEntry *p : part.phdrs)
2612ece8a530Spatrick if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2613ece8a530Spatrick lastRX = p;
2614ece8a530Spatrick
2615a0747c9fSpatrick // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2616a0747c9fSpatrick // will not occupy file offsets contained by a PT_LOAD.
2617ece8a530Spatrick for (OutputSection *sec : outputSections) {
2618a0747c9fSpatrick if (!(sec->flags & SHF_ALLOC))
2619a0747c9fSpatrick continue;
262005edf1c1Srobert off = computeFileOffset(sec, off);
262105edf1c1Srobert sec->offset = off;
262205edf1c1Srobert if (sec->type != SHT_NOBITS)
262305edf1c1Srobert off += sec->size;
2624ece8a530Spatrick
2625ece8a530Spatrick // If this is a last section of the last executable segment and that
2626ece8a530Spatrick // segment is the last loadable segment, align the offset of the
2627ece8a530Spatrick // following section to avoid loading non-segments parts of the file.
2628ece8a530Spatrick if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2629ece8a530Spatrick lastRX->lastSec == sec)
263005edf1c1Srobert off = alignToPowerOf2(off, config->maxPageSize);
2631ece8a530Spatrick }
263205edf1c1Srobert for (OutputSection *osec : outputSections)
263305edf1c1Srobert if (!(osec->flags & SHF_ALLOC)) {
263405edf1c1Srobert osec->offset = alignToPowerOf2(off, osec->addralign);
263505edf1c1Srobert off = osec->offset + osec->size;
263605edf1c1Srobert }
2637ece8a530Spatrick
263805edf1c1Srobert sectionHeaderOff = alignToPowerOf2(off, config->wordsize);
2639ece8a530Spatrick fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2640ece8a530Spatrick
2641ece8a530Spatrick // Our logic assumes that sections have rising VA within the same segment.
2642ece8a530Spatrick // With use of linker scripts it is possible to violate this rule and get file
2643ece8a530Spatrick // offset overlaps or overflows. That should never happen with a valid script
2644ece8a530Spatrick // which does not move the location counter backwards and usually scripts do
2645ece8a530Spatrick // not do that. Unfortunately, there are apps in the wild, for example, Linux
2646ece8a530Spatrick // kernel, which control segment distribution explicitly and move the counter
2647ece8a530Spatrick // backwards, so we have to allow doing that to support linking them. We
2648ece8a530Spatrick // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2649ece8a530Spatrick // we want to prevent file size overflows because it would crash the linker.
2650ece8a530Spatrick for (OutputSection *sec : outputSections) {
2651ece8a530Spatrick if (sec->type == SHT_NOBITS)
2652ece8a530Spatrick continue;
2653ece8a530Spatrick if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2654ece8a530Spatrick error("unable to place section " + sec->name + " at file offset " +
2655ece8a530Spatrick rangeToString(sec->offset, sec->size) +
2656ece8a530Spatrick "; check your linker script for overflows");
2657ece8a530Spatrick }
2658ece8a530Spatrick }
2659ece8a530Spatrick
2660ece8a530Spatrick // Finalize the program headers. We call this function after we assign
2661ece8a530Spatrick // file offsets and VAs to all sections.
setPhdrs(Partition & part)2662ece8a530Spatrick template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2663ece8a530Spatrick for (PhdrEntry *p : part.phdrs) {
2664ece8a530Spatrick OutputSection *first = p->firstSec;
2665ece8a530Spatrick OutputSection *last = p->lastSec;
2666ece8a530Spatrick
2667ece8a530Spatrick if (first) {
2668ece8a530Spatrick p->p_filesz = last->offset - first->offset;
2669ece8a530Spatrick if (last->type != SHT_NOBITS)
2670ece8a530Spatrick p->p_filesz += last->size;
2671ece8a530Spatrick
2672ece8a530Spatrick p->p_memsz = last->addr + last->size - first->addr;
2673ece8a530Spatrick p->p_offset = first->offset;
2674ece8a530Spatrick p->p_vaddr = first->addr;
2675ece8a530Spatrick
2676ece8a530Spatrick // File offsets in partitions other than the main partition are relative
2677ece8a530Spatrick // to the offset of the ELF headers. Perform that adjustment now.
2678ece8a530Spatrick if (part.elfHeader)
2679ece8a530Spatrick p->p_offset -= part.elfHeader->getParent()->offset;
2680ece8a530Spatrick
2681ece8a530Spatrick if (!p->hasLMA)
2682ece8a530Spatrick p->p_paddr = first->getLMA();
2683ece8a530Spatrick }
2684ece8a530Spatrick
2685ece8a530Spatrick if (p->p_type == PT_GNU_RELRO) {
2686ece8a530Spatrick p->p_align = 1;
2687ece8a530Spatrick // musl/glibc ld.so rounds the size down, so we need to round up
2688ece8a530Spatrick // to protect the last page. This is a no-op on FreeBSD which always
2689ece8a530Spatrick // rounds up.
269005edf1c1Srobert p->p_memsz =
269105edf1c1Srobert alignToPowerOf2(p->p_offset + p->p_memsz, config->commonPageSize) -
2692ece8a530Spatrick p->p_offset;
2693ece8a530Spatrick }
2694ece8a530Spatrick }
2695ece8a530Spatrick }
2696ece8a530Spatrick
2697ece8a530Spatrick // A helper struct for checkSectionOverlap.
2698ece8a530Spatrick namespace {
2699ece8a530Spatrick struct SectionOffset {
2700ece8a530Spatrick OutputSection *sec;
2701ece8a530Spatrick uint64_t offset;
2702ece8a530Spatrick };
2703ece8a530Spatrick } // namespace
2704ece8a530Spatrick
2705ece8a530Spatrick // Check whether sections overlap for a specific address range (file offsets,
2706ece8a530Spatrick // load and virtual addresses).
checkOverlap(StringRef name,std::vector<SectionOffset> & sections,bool isVirtualAddr)2707ece8a530Spatrick static void checkOverlap(StringRef name, std::vector<SectionOffset> §ions,
2708ece8a530Spatrick bool isVirtualAddr) {
2709ece8a530Spatrick llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2710ece8a530Spatrick return a.offset < b.offset;
2711ece8a530Spatrick });
2712ece8a530Spatrick
2713ece8a530Spatrick // Finding overlap is easy given a vector is sorted by start position.
2714ece8a530Spatrick // If an element starts before the end of the previous element, they overlap.
2715ece8a530Spatrick for (size_t i = 1, end = sections.size(); i < end; ++i) {
2716ece8a530Spatrick SectionOffset a = sections[i - 1];
2717ece8a530Spatrick SectionOffset b = sections[i];
2718ece8a530Spatrick if (b.offset >= a.offset + a.sec->size)
2719ece8a530Spatrick continue;
2720ece8a530Spatrick
2721ece8a530Spatrick // If both sections are in OVERLAY we allow the overlapping of virtual
2722ece8a530Spatrick // addresses, because it is what OVERLAY was designed for.
2723ece8a530Spatrick if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2724ece8a530Spatrick continue;
2725ece8a530Spatrick
2726ece8a530Spatrick errorOrWarn("section " + a.sec->name + " " + name +
2727ece8a530Spatrick " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2728ece8a530Spatrick " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2729ece8a530Spatrick b.sec->name + " range is " +
2730ece8a530Spatrick rangeToString(b.offset, b.sec->size));
2731ece8a530Spatrick }
2732ece8a530Spatrick }
2733ece8a530Spatrick
2734ece8a530Spatrick // Check for overlapping sections and address overflows.
2735ece8a530Spatrick //
2736ece8a530Spatrick // In this function we check that none of the output sections have overlapping
2737ece8a530Spatrick // file offsets. For SHF_ALLOC sections we also check that the load address
2738ece8a530Spatrick // ranges and the virtual address ranges don't overlap
checkSections()2739ece8a530Spatrick template <class ELFT> void Writer<ELFT>::checkSections() {
2740ece8a530Spatrick // First, check that section's VAs fit in available address space for target.
2741ece8a530Spatrick for (OutputSection *os : outputSections)
2742ece8a530Spatrick if ((os->addr + os->size < os->addr) ||
274305edf1c1Srobert (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2744ece8a530Spatrick errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2745ece8a530Spatrick " of size 0x" + utohexstr(os->size) +
2746ece8a530Spatrick " exceeds available address space");
2747ece8a530Spatrick
2748ece8a530Spatrick // Check for overlapping file offsets. In this case we need to skip any
2749ece8a530Spatrick // section marked as SHT_NOBITS. These sections don't actually occupy space in
2750ece8a530Spatrick // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2751ece8a530Spatrick // binary is specified only add SHF_ALLOC sections are added to the output
2752ece8a530Spatrick // file so we skip any non-allocated sections in that case.
2753ece8a530Spatrick std::vector<SectionOffset> fileOffs;
2754ece8a530Spatrick for (OutputSection *sec : outputSections)
2755ece8a530Spatrick if (sec->size > 0 && sec->type != SHT_NOBITS &&
2756ece8a530Spatrick (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2757ece8a530Spatrick fileOffs.push_back({sec, sec->offset});
2758ece8a530Spatrick checkOverlap("file", fileOffs, false);
2759ece8a530Spatrick
2760ece8a530Spatrick // When linking with -r there is no need to check for overlapping virtual/load
2761ece8a530Spatrick // addresses since those addresses will only be assigned when the final
2762ece8a530Spatrick // executable/shared object is created.
2763ece8a530Spatrick if (config->relocatable)
2764ece8a530Spatrick return;
2765ece8a530Spatrick
2766ece8a530Spatrick // Checking for overlapping virtual and load addresses only needs to take
2767ece8a530Spatrick // into account SHF_ALLOC sections since others will not be loaded.
2768ece8a530Spatrick // Furthermore, we also need to skip SHF_TLS sections since these will be
2769ece8a530Spatrick // mapped to other addresses at runtime and can therefore have overlapping
2770ece8a530Spatrick // ranges in the file.
2771ece8a530Spatrick std::vector<SectionOffset> vmas;
2772ece8a530Spatrick for (OutputSection *sec : outputSections)
2773ece8a530Spatrick if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2774ece8a530Spatrick vmas.push_back({sec, sec->addr});
2775ece8a530Spatrick checkOverlap("virtual address", vmas, true);
2776ece8a530Spatrick
2777ece8a530Spatrick // Finally, check that the load addresses don't overlap. This will usually be
2778ece8a530Spatrick // the same as the virtual addresses but can be different when using a linker
2779ece8a530Spatrick // script with AT().
2780ece8a530Spatrick std::vector<SectionOffset> lmas;
2781ece8a530Spatrick for (OutputSection *sec : outputSections)
2782ece8a530Spatrick if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2783ece8a530Spatrick lmas.push_back({sec, sec->getLMA()});
2784ece8a530Spatrick checkOverlap("load address", lmas, false);
2785ece8a530Spatrick }
2786ece8a530Spatrick
2787ece8a530Spatrick // The entry point address is chosen in the following ways.
2788ece8a530Spatrick //
2789ece8a530Spatrick // 1. the '-e' entry command-line option;
2790ece8a530Spatrick // 2. the ENTRY(symbol) command in a linker control script;
2791ece8a530Spatrick // 3. the value of the symbol _start, if present;
2792ece8a530Spatrick // 4. the number represented by the entry symbol, if it is a number;
279305edf1c1Srobert // 5. the address 0.
getEntryAddr()2794ece8a530Spatrick static uint64_t getEntryAddr() {
2795ece8a530Spatrick // Case 1, 2 or 3
279605edf1c1Srobert if (Symbol *b = symtab.find(config->entry))
2797ece8a530Spatrick return b->getVA();
2798ece8a530Spatrick
2799ece8a530Spatrick // Case 4
2800ece8a530Spatrick uint64_t addr;
2801ece8a530Spatrick if (to_integer(config->entry, addr))
2802ece8a530Spatrick return addr;
2803ece8a530Spatrick
2804ece8a530Spatrick // Case 5
2805ece8a530Spatrick if (config->warnMissingEntry)
2806ece8a530Spatrick warn("cannot find entry symbol " + config->entry +
2807ece8a530Spatrick "; not setting start address");
2808ece8a530Spatrick return 0;
2809ece8a530Spatrick }
2810ece8a530Spatrick
getELFType()2811ece8a530Spatrick static uint16_t getELFType() {
2812ece8a530Spatrick if (config->isPic)
2813ece8a530Spatrick return ET_DYN;
2814ece8a530Spatrick if (config->relocatable)
2815ece8a530Spatrick return ET_REL;
2816ece8a530Spatrick return ET_EXEC;
2817ece8a530Spatrick }
2818ece8a530Spatrick
writeHeader()2819ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeHeader() {
2820ece8a530Spatrick writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2821ece8a530Spatrick writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2822ece8a530Spatrick
2823ece8a530Spatrick auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2824ece8a530Spatrick eHdr->e_type = getELFType();
2825ece8a530Spatrick eHdr->e_entry = getEntryAddr();
2826ece8a530Spatrick eHdr->e_shoff = sectionHeaderOff;
2827ece8a530Spatrick
2828ece8a530Spatrick // Write the section header table.
2829ece8a530Spatrick //
2830ece8a530Spatrick // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2831ece8a530Spatrick // and e_shstrndx fields. When the value of one of these fields exceeds
2832ece8a530Spatrick // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2833ece8a530Spatrick // use fields in the section header at index 0 to store
2834ece8a530Spatrick // the value. The sentinel values and fields are:
2835ece8a530Spatrick // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2836ece8a530Spatrick // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2837ece8a530Spatrick auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2838ece8a530Spatrick size_t num = outputSections.size() + 1;
2839ece8a530Spatrick if (num >= SHN_LORESERVE)
2840ece8a530Spatrick sHdrs->sh_size = num;
2841ece8a530Spatrick else
2842ece8a530Spatrick eHdr->e_shnum = num;
2843ece8a530Spatrick
2844ece8a530Spatrick uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2845ece8a530Spatrick if (strTabIndex >= SHN_LORESERVE) {
2846ece8a530Spatrick sHdrs->sh_link = strTabIndex;
2847ece8a530Spatrick eHdr->e_shstrndx = SHN_XINDEX;
2848ece8a530Spatrick } else {
2849ece8a530Spatrick eHdr->e_shstrndx = strTabIndex;
2850ece8a530Spatrick }
2851ece8a530Spatrick
2852ece8a530Spatrick for (OutputSection *sec : outputSections)
2853ece8a530Spatrick sec->writeHeaderTo<ELFT>(++sHdrs);
2854ece8a530Spatrick }
2855ece8a530Spatrick
2856ece8a530Spatrick // Open a result file.
openFile()2857ece8a530Spatrick template <class ELFT> void Writer<ELFT>::openFile() {
2858ece8a530Spatrick uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2859ece8a530Spatrick if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2860a0747c9fSpatrick std::string msg;
2861a0747c9fSpatrick raw_string_ostream s(msg);
2862a0747c9fSpatrick s << "output file too large: " << Twine(fileSize) << " bytes\n"
2863a0747c9fSpatrick << "section sizes:\n";
2864a0747c9fSpatrick for (OutputSection *os : outputSections)
2865a0747c9fSpatrick s << os->name << ' ' << os->size << "\n";
2866a0747c9fSpatrick error(s.str());
2867ece8a530Spatrick return;
2868ece8a530Spatrick }
2869ece8a530Spatrick
2870ece8a530Spatrick unlinkAsync(config->outputFile);
2871ece8a530Spatrick unsigned flags = 0;
2872ece8a530Spatrick if (!config->relocatable)
2873ece8a530Spatrick flags |= FileOutputBuffer::F_executable;
2874ece8a530Spatrick if (!config->mmapOutputFile)
2875ece8a530Spatrick flags |= FileOutputBuffer::F_no_mmap;
2876ece8a530Spatrick Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2877ece8a530Spatrick FileOutputBuffer::create(config->outputFile, fileSize, flags);
2878ece8a530Spatrick
2879ece8a530Spatrick if (!bufferOrErr) {
2880ece8a530Spatrick error("failed to open " + config->outputFile + ": " +
2881ece8a530Spatrick llvm::toString(bufferOrErr.takeError()));
2882ece8a530Spatrick return;
2883ece8a530Spatrick }
2884ece8a530Spatrick buffer = std::move(*bufferOrErr);
2885ece8a530Spatrick Out::bufferStart = buffer->getBufferStart();
2886ece8a530Spatrick }
2887ece8a530Spatrick
writeSectionsBinary()2888ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
288905edf1c1Srobert parallel::TaskGroup tg;
2890ece8a530Spatrick for (OutputSection *sec : outputSections)
2891ece8a530Spatrick if (sec->flags & SHF_ALLOC)
289205edf1c1Srobert sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
2893ece8a530Spatrick }
2894ece8a530Spatrick
fillTrap(uint8_t * i,uint8_t * end)2895ece8a530Spatrick static void fillTrap(uint8_t *i, uint8_t *end) {
2896ece8a530Spatrick for (; i + 4 <= end; i += 4)
2897ece8a530Spatrick memcpy(i, &target->trapInstr, 4);
2898ece8a530Spatrick }
2899ece8a530Spatrick
2900ece8a530Spatrick // Fill the last page of executable segments with trap instructions
2901ece8a530Spatrick // instead of leaving them as zero. Even though it is not required by any
2902ece8a530Spatrick // standard, it is in general a good thing to do for security reasons.
2903ece8a530Spatrick //
2904ece8a530Spatrick // We'll leave other pages in segments as-is because the rest will be
2905ece8a530Spatrick // overwritten by output sections.
writeTrapInstr()2906ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2907ece8a530Spatrick for (Partition &part : partitions) {
2908ece8a530Spatrick // Fill the last page.
2909ece8a530Spatrick for (PhdrEntry *p : part.phdrs)
2910ece8a530Spatrick if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
291105edf1c1Srobert fillTrap(Out::bufferStart +
291205edf1c1Srobert alignDown(p->firstSec->offset + p->p_filesz, 4),
291305edf1c1Srobert Out::bufferStart +
291405edf1c1Srobert alignToPowerOf2(p->firstSec->offset + p->p_filesz,
291505edf1c1Srobert config->maxPageSize));
2916ece8a530Spatrick
2917ece8a530Spatrick // Round up the file size of the last segment to the page boundary iff it is
2918ece8a530Spatrick // an executable segment to ensure that other tools don't accidentally
2919ece8a530Spatrick // trim the instruction padding (e.g. when stripping the file).
2920ece8a530Spatrick PhdrEntry *last = nullptr;
2921ece8a530Spatrick for (PhdrEntry *p : part.phdrs)
2922ece8a530Spatrick if (p->p_type == PT_LOAD)
2923ece8a530Spatrick last = p;
2924ece8a530Spatrick
2925ece8a530Spatrick if (last && (last->p_flags & PF_X))
2926ece8a530Spatrick last->p_memsz = last->p_filesz =
292705edf1c1Srobert alignToPowerOf2(last->p_filesz, config->maxPageSize);
2928ece8a530Spatrick }
2929ece8a530Spatrick }
2930ece8a530Spatrick
2931ece8a530Spatrick // Write section contents to a mmap'ed file.
writeSections()2932ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeSections() {
293305edf1c1Srobert llvm::TimeTraceScope timeScope("Write sections");
293405edf1c1Srobert
293505edf1c1Srobert {
293605edf1c1Srobert // In -r or --emit-relocs mode, write the relocation sections first as in
2937ece8a530Spatrick // ELf_Rel targets we might find out that we need to modify the relocated
2938ece8a530Spatrick // section while doing it.
293905edf1c1Srobert parallel::TaskGroup tg;
2940ece8a530Spatrick for (OutputSection *sec : outputSections)
2941ece8a530Spatrick if (sec->type == SHT_REL || sec->type == SHT_RELA)
294205edf1c1Srobert sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
294305edf1c1Srobert }
294405edf1c1Srobert {
294505edf1c1Srobert parallel::TaskGroup tg;
2946ece8a530Spatrick for (OutputSection *sec : outputSections)
2947ece8a530Spatrick if (sec->type != SHT_REL && sec->type != SHT_RELA)
294805edf1c1Srobert sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
294905edf1c1Srobert }
2950ece8a530Spatrick
2951a0747c9fSpatrick // Finally, check that all dynamic relocation addends were written correctly.
2952a0747c9fSpatrick if (config->checkDynamicRelocs && config->writeAddends) {
2953a0747c9fSpatrick for (OutputSection *sec : outputSections)
2954a0747c9fSpatrick if (sec->type == SHT_REL || sec->type == SHT_RELA)
2955a0747c9fSpatrick sec->checkDynRelAddends(Out::bufferStart);
2956ece8a530Spatrick }
2957ece8a530Spatrick }
2958ece8a530Spatrick
2959ece8a530Spatrick // Computes a hash value of Data using a given hash function.
2960ece8a530Spatrick // In order to utilize multiple cores, we first split data into 1MB
2961ece8a530Spatrick // chunks, compute a hash for each chunk, and then compute a hash value
2962ece8a530Spatrick // of the hash values.
2963ece8a530Spatrick static void
computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,llvm::ArrayRef<uint8_t> data,std::function<void (uint8_t * dest,ArrayRef<uint8_t> arr)> hashFn)2964ece8a530Spatrick computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2965ece8a530Spatrick llvm::ArrayRef<uint8_t> data,
2966ece8a530Spatrick std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2967ece8a530Spatrick std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
296805edf1c1Srobert const size_t hashesSize = chunks.size() * hashBuf.size();
296905edf1c1Srobert std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2970ece8a530Spatrick
2971ece8a530Spatrick // Compute hash values.
297205edf1c1Srobert parallelFor(0, chunks.size(), [&](size_t i) {
297305edf1c1Srobert hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2974ece8a530Spatrick });
2975ece8a530Spatrick
2976ece8a530Spatrick // Write to the final output buffer.
297705edf1c1Srobert hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
2978ece8a530Spatrick }
2979ece8a530Spatrick
writeBuildId()2980ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeBuildId() {
2981ece8a530Spatrick if (!mainPart->buildId || !mainPart->buildId->getParent())
2982ece8a530Spatrick return;
2983ece8a530Spatrick
2984ece8a530Spatrick if (config->buildId == BuildIdKind::Hexstring) {
2985ece8a530Spatrick for (Partition &part : partitions)
2986ece8a530Spatrick part.buildId->writeBuildId(config->buildIdVector);
2987ece8a530Spatrick return;
2988ece8a530Spatrick }
2989ece8a530Spatrick
2990ece8a530Spatrick // Compute a hash of all sections of the output file.
2991ece8a530Spatrick size_t hashSize = mainPart->buildId->hashSize;
299205edf1c1Srobert std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
299305edf1c1Srobert MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
299405edf1c1Srobert llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
2995ece8a530Spatrick
299605edf1c1Srobert // Fedora introduced build ID as "approximation of true uniqueness across all
299705edf1c1Srobert // binaries that might be used by overlapping sets of people". It does not
299805edf1c1Srobert // need some security goals that some hash algorithms strive to provide, e.g.
299905edf1c1Srobert // (second-)preimage and collision resistance. In practice people use 'md5'
300005edf1c1Srobert // and 'sha1' just for different lengths. Implement them with the more
300105edf1c1Srobert // efficient BLAKE3.
3002ece8a530Spatrick switch (config->buildId) {
3003ece8a530Spatrick case BuildIdKind::Fast:
300405edf1c1Srobert computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
3005ece8a530Spatrick write64le(dest, xxHash64(arr));
3006ece8a530Spatrick });
3007ece8a530Spatrick break;
3008ece8a530Spatrick case BuildIdKind::Md5:
300905edf1c1Srobert computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
301005edf1c1Srobert memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
3011ece8a530Spatrick });
3012ece8a530Spatrick break;
3013ece8a530Spatrick case BuildIdKind::Sha1:
301405edf1c1Srobert computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
301505edf1c1Srobert memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
3016ece8a530Spatrick });
3017ece8a530Spatrick break;
3018ece8a530Spatrick case BuildIdKind::Uuid:
301905edf1c1Srobert if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
3020ece8a530Spatrick error("entropy source failure: " + ec.message());
3021ece8a530Spatrick break;
3022ece8a530Spatrick default:
3023ece8a530Spatrick llvm_unreachable("unknown BuildIdKind");
3024ece8a530Spatrick }
3025ece8a530Spatrick for (Partition &part : partitions)
302605edf1c1Srobert part.buildId->writeBuildId(output);
3027ece8a530Spatrick }
3028ece8a530Spatrick
3029bb684c34Spatrick template void elf::createSyntheticSections<ELF32LE>();
3030bb684c34Spatrick template void elf::createSyntheticSections<ELF32BE>();
3031bb684c34Spatrick template void elf::createSyntheticSections<ELF64LE>();
3032bb684c34Spatrick template void elf::createSyntheticSections<ELF64BE>();
3033ece8a530Spatrick
3034bb684c34Spatrick template void elf::writeResult<ELF32LE>();
3035bb684c34Spatrick template void elf::writeResult<ELF32BE>();
3036bb684c34Spatrick template void elf::writeResult<ELF64LE>();
3037bb684c34Spatrick template void elf::writeResult<ELF64BE>();
3038