xref: /openbsd-src/gnu/llvm/lld/ELF/Writer.cpp (revision a0747c9f67a4ae71ccb71e62a28d1ea19e06a63c)
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"
14ece8a530Spatrick #include "LinkerScript.h"
15ece8a530Spatrick #include "MapFile.h"
16ece8a530Spatrick #include "OutputSections.h"
17ece8a530Spatrick #include "Relocations.h"
18ece8a530Spatrick #include "SymbolTable.h"
19ece8a530Spatrick #include "Symbols.h"
20ece8a530Spatrick #include "SyntheticSections.h"
21ece8a530Spatrick #include "Target.h"
22*a0747c9fSpatrick #include "lld/Common/Arrays.h"
23ece8a530Spatrick #include "lld/Common/Filesystem.h"
24ece8a530Spatrick #include "lld/Common/Memory.h"
25ece8a530Spatrick #include "lld/Common/Strings.h"
26ece8a530Spatrick #include "llvm/ADT/StringMap.h"
27ece8a530Spatrick #include "llvm/ADT/StringSwitch.h"
28bb684c34Spatrick #include "llvm/Support/Parallel.h"
29ece8a530Spatrick #include "llvm/Support/RandomNumberGenerator.h"
30ece8a530Spatrick #include "llvm/Support/SHA1.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:
49*a0747c9fSpatrick   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
50*a0747c9fSpatrick 
51ece8a530Spatrick   Writer() : buffer(errorHandler().outputBuffer) {}
52ece8a530Spatrick 
53ece8a530Spatrick   void run();
54ece8a530Spatrick 
55ece8a530Spatrick private:
56ece8a530Spatrick   void copyLocalSymbols();
57ece8a530Spatrick   void addSectionSymbols();
58ece8a530Spatrick   void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> fn);
59ece8a530Spatrick   void sortSections();
60ece8a530Spatrick   void resolveShfLinkOrder();
61ece8a530Spatrick   void finalizeAddressDependentContent();
62bb684c34Spatrick   void optimizeBasicBlockJumps();
63ece8a530Spatrick   void sortInputSections();
64ece8a530Spatrick   void finalizeSections();
65ece8a530Spatrick   void checkExecuteOnly();
66ece8a530Spatrick   void setReservedSymbolSections();
67ece8a530Spatrick 
68ece8a530Spatrick   std::vector<PhdrEntry *> createPhdrs(Partition &part);
69ece8a530Spatrick   void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
70ece8a530Spatrick                          unsigned pFlags);
71ece8a530Spatrick   void assignFileOffsets();
72ece8a530Spatrick   void assignFileOffsetsBinary();
73ece8a530Spatrick   void setPhdrs(Partition &part);
74ece8a530Spatrick   void checkSections();
75ece8a530Spatrick   void fixSectionAlignments();
76ece8a530Spatrick   void openFile();
77ece8a530Spatrick   void writeTrapInstr();
78ece8a530Spatrick   void writeHeader();
79ece8a530Spatrick   void writeSections();
80ece8a530Spatrick   void writeSectionsBinary();
81ece8a530Spatrick   void writeBuildId();
82ece8a530Spatrick 
83ece8a530Spatrick   std::unique_ptr<FileOutputBuffer> &buffer;
84ece8a530Spatrick 
85ece8a530Spatrick   void addRelIpltSymbols();
86ece8a530Spatrick   void addStartEndSymbols();
87ece8a530Spatrick   void addStartStopSymbols(OutputSection *sec);
88ece8a530Spatrick 
89ece8a530Spatrick   uint64_t fileSize;
90ece8a530Spatrick   uint64_t sectionHeaderOff;
91ece8a530Spatrick };
92ece8a530Spatrick } // anonymous namespace
93ece8a530Spatrick 
94ece8a530Spatrick static bool isSectionPrefix(StringRef prefix, StringRef name) {
95ece8a530Spatrick   return name.startswith(prefix) || name == prefix.drop_back();
96ece8a530Spatrick }
97ece8a530Spatrick 
98bb684c34Spatrick StringRef elf::getOutputSectionName(const InputSectionBase *s) {
99ece8a530Spatrick   if (config->relocatable)
100ece8a530Spatrick     return s->name;
101ece8a530Spatrick 
102ece8a530Spatrick   // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
103ece8a530Spatrick   // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
104ece8a530Spatrick   // technically required, but not doing it is odd). This code guarantees that.
105ece8a530Spatrick   if (auto *isec = dyn_cast<InputSection>(s)) {
106ece8a530Spatrick     if (InputSectionBase *rel = isec->getRelocatedSection()) {
107ece8a530Spatrick       OutputSection *out = rel->getOutputSection();
108ece8a530Spatrick       if (s->type == SHT_RELA)
109ece8a530Spatrick         return saver.save(".rela" + out->name);
110ece8a530Spatrick       return saver.save(".rel" + out->name);
111ece8a530Spatrick     }
112ece8a530Spatrick   }
113ece8a530Spatrick 
114bb684c34Spatrick   // A BssSection created for a common symbol is identified as "COMMON" in
115bb684c34Spatrick   // linker scripts. It should go to .bss section.
116bb684c34Spatrick   if (s->name == "COMMON")
117bb684c34Spatrick     return ".bss";
118bb684c34Spatrick 
119bb684c34Spatrick   if (script->hasSectionsCommand)
120bb684c34Spatrick     return s->name;
121bb684c34Spatrick 
122bb684c34Spatrick   // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
123bb684c34Spatrick   // by grouping sections with certain prefixes.
124bb684c34Spatrick 
125bb684c34Spatrick   // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
126bb684c34Spatrick   // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
127bb684c34Spatrick   // We provide an option -z keep-text-section-prefix to group such sections
128bb684c34Spatrick   // into separate output sections. This is more flexible. See also
129bb684c34Spatrick   // sortISDBySectionOrder().
130bb684c34Spatrick   // ".text.unknown" means the hotness of the section is unknown. When
131bb684c34Spatrick   // SampleFDO is used, if a function doesn't have sample, it could be very
132bb684c34Spatrick   // cold or it could be a new function never being sampled. Those functions
133bb684c34Spatrick   // will be kept in the ".text.unknown" section.
134*a0747c9fSpatrick   // ".text.split." holds symbols which are split out from functions in other
135*a0747c9fSpatrick   // input sections. For example, with -fsplit-machine-functions, placing the
136*a0747c9fSpatrick   // cold parts in .text.split instead of .text.unlikely mitigates against poor
137*a0747c9fSpatrick   // profile inaccuracy. Techniques such as hugepage remapping can make
138*a0747c9fSpatrick   // conservative decisions at the section granularity.
139ece8a530Spatrick   if (config->zKeepTextSectionPrefix)
140bb684c34Spatrick     for (StringRef v : {".text.hot.", ".text.unknown.", ".text.unlikely.",
141*a0747c9fSpatrick                         ".text.startup.", ".text.exit.", ".text.split."})
142ece8a530Spatrick       if (isSectionPrefix(v, s->name))
143ece8a530Spatrick         return v.drop_back();
144ece8a530Spatrick 
145ece8a530Spatrick   for (StringRef v :
146ece8a530Spatrick        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
147ece8a530Spatrick         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
148adae0cfdSpatrick         ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab.",
149adae0cfdSpatrick         ".openbsd.randomdata."})
150ece8a530Spatrick     if (isSectionPrefix(v, s->name))
151ece8a530Spatrick       return v.drop_back();
152ece8a530Spatrick 
153ece8a530Spatrick   return s->name;
154ece8a530Spatrick }
155ece8a530Spatrick 
156ece8a530Spatrick static bool needsInterpSection() {
157ece8a530Spatrick   return !config->relocatable && !config->shared &&
158ece8a530Spatrick          !config->dynamicLinker.empty() && script->needsInterpSection();
159ece8a530Spatrick }
160ece8a530Spatrick 
161bb684c34Spatrick template <class ELFT> void elf::writeResult() {
162bb684c34Spatrick   Writer<ELFT>().run();
163ece8a530Spatrick }
164ece8a530Spatrick 
165bb684c34Spatrick static void removeEmptyPTLoad(std::vector<PhdrEntry *> &phdrs) {
166bb684c34Spatrick   auto it = std::stable_partition(
167bb684c34Spatrick       phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
168bb684c34Spatrick         if (p->p_type != PT_LOAD)
169bb684c34Spatrick           return true;
170bb684c34Spatrick         if (!p->firstSec)
171bb684c34Spatrick           return false;
172bb684c34Spatrick         uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
173bb684c34Spatrick         return size != 0;
174bb684c34Spatrick       });
175bb684c34Spatrick 
176bb684c34Spatrick   // Clear OutputSection::ptLoad for sections contained in removed
177bb684c34Spatrick   // segments.
178bb684c34Spatrick   DenseSet<PhdrEntry *> removed(it, phdrs.end());
179bb684c34Spatrick   for (OutputSection *sec : outputSections)
180bb684c34Spatrick     if (removed.count(sec->ptLoad))
181bb684c34Spatrick       sec->ptLoad = nullptr;
182bb684c34Spatrick   phdrs.erase(it, phdrs.end());
183bb684c34Spatrick }
184bb684c34Spatrick 
185bb684c34Spatrick void elf::copySectionsIntoPartitions() {
186ece8a530Spatrick   std::vector<InputSectionBase *> newSections;
187ece8a530Spatrick   for (unsigned part = 2; part != partitions.size() + 1; ++part) {
188ece8a530Spatrick     for (InputSectionBase *s : inputSections) {
189ece8a530Spatrick       if (!(s->flags & SHF_ALLOC) || !s->isLive())
190ece8a530Spatrick         continue;
191ece8a530Spatrick       InputSectionBase *copy;
192ece8a530Spatrick       if (s->type == SHT_NOTE)
193ece8a530Spatrick         copy = make<InputSection>(cast<InputSection>(*s));
194ece8a530Spatrick       else if (auto *es = dyn_cast<EhInputSection>(s))
195ece8a530Spatrick         copy = make<EhInputSection>(*es);
196ece8a530Spatrick       else
197ece8a530Spatrick         continue;
198ece8a530Spatrick       copy->partition = part;
199ece8a530Spatrick       newSections.push_back(copy);
200ece8a530Spatrick     }
201ece8a530Spatrick   }
202ece8a530Spatrick 
203ece8a530Spatrick   inputSections.insert(inputSections.end(), newSections.begin(),
204ece8a530Spatrick                        newSections.end());
205ece8a530Spatrick }
206ece8a530Spatrick 
207bb684c34Spatrick void elf::combineEhSections() {
208*a0747c9fSpatrick   llvm::TimeTraceScope timeScope("Combine EH sections");
209ece8a530Spatrick   for (InputSectionBase *&s : inputSections) {
210ece8a530Spatrick     // Ignore dead sections and the partition end marker (.part.end),
211ece8a530Spatrick     // whose partition number is out of bounds.
212ece8a530Spatrick     if (!s->isLive() || s->partition == 255)
213ece8a530Spatrick       continue;
214ece8a530Spatrick 
215ece8a530Spatrick     Partition &part = s->getPartition();
216ece8a530Spatrick     if (auto *es = dyn_cast<EhInputSection>(s)) {
217ece8a530Spatrick       part.ehFrame->addSection(es);
218ece8a530Spatrick       s = nullptr;
219ece8a530Spatrick     } else if (s->kind() == SectionBase::Regular && part.armExidx &&
220ece8a530Spatrick                part.armExidx->addSection(cast<InputSection>(s))) {
221ece8a530Spatrick       s = nullptr;
222ece8a530Spatrick     }
223ece8a530Spatrick   }
224ece8a530Spatrick 
225ece8a530Spatrick   std::vector<InputSectionBase *> &v = inputSections;
226ece8a530Spatrick   v.erase(std::remove(v.begin(), v.end(), nullptr), v.end());
227ece8a530Spatrick }
228ece8a530Spatrick 
229ece8a530Spatrick static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
230ece8a530Spatrick                                    uint64_t val, uint8_t stOther = STV_HIDDEN,
231ece8a530Spatrick                                    uint8_t binding = STB_GLOBAL) {
232ece8a530Spatrick   Symbol *s = symtab->find(name);
233ece8a530Spatrick   if (!s || s->isDefined())
234ece8a530Spatrick     return nullptr;
235ece8a530Spatrick 
236ece8a530Spatrick   s->resolve(Defined{/*file=*/nullptr, name, binding, stOther, STT_NOTYPE, val,
237ece8a530Spatrick                      /*size=*/0, sec});
238ece8a530Spatrick   return cast<Defined>(s);
239ece8a530Spatrick }
240ece8a530Spatrick 
241ece8a530Spatrick static Defined *addAbsolute(StringRef name) {
242ece8a530Spatrick   Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
243ece8a530Spatrick                                           STT_NOTYPE, 0, 0, nullptr});
244ece8a530Spatrick   return cast<Defined>(sym);
245ece8a530Spatrick }
246ece8a530Spatrick 
247ece8a530Spatrick // The linker is expected to define some symbols depending on
248ece8a530Spatrick // the linking result. This function defines such symbols.
249bb684c34Spatrick void elf::addReservedSymbols() {
250ece8a530Spatrick   if (config->emachine == EM_MIPS) {
251ece8a530Spatrick     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
252ece8a530Spatrick     // so that it points to an absolute address which by default is relative
253ece8a530Spatrick     // to GOT. Default offset is 0x7ff0.
254ece8a530Spatrick     // See "Global Data Symbols" in Chapter 6 in the following document:
255ece8a530Spatrick     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
256ece8a530Spatrick     ElfSym::mipsGp = addAbsolute("_gp");
257ece8a530Spatrick 
258ece8a530Spatrick     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
259ece8a530Spatrick     // start of function and 'gp' pointer into GOT.
260ece8a530Spatrick     if (symtab->find("_gp_disp"))
261ece8a530Spatrick       ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
262ece8a530Spatrick 
263ece8a530Spatrick     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
264ece8a530Spatrick     // pointer. This symbol is used in the code generated by .cpload pseudo-op
265ece8a530Spatrick     // in case of using -mno-shared option.
266ece8a530Spatrick     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
267ece8a530Spatrick     if (symtab->find("__gnu_local_gp"))
268ece8a530Spatrick       ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
269ece8a530Spatrick   } else if (config->emachine == EM_PPC) {
270ece8a530Spatrick     // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
271ece8a530Spatrick     // support Small Data Area, define it arbitrarily as 0.
272ece8a530Spatrick     addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
273bb684c34Spatrick   } else if (config->emachine == EM_PPC64) {
274bb684c34Spatrick     addPPC64SaveRestore();
275ece8a530Spatrick   }
276ece8a530Spatrick 
277ece8a530Spatrick   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
278ece8a530Spatrick   // combines the typical ELF GOT with the small data sections. It commonly
279ece8a530Spatrick   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
280ece8a530Spatrick   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
281ece8a530Spatrick   // represent the TOC base which is offset by 0x8000 bytes from the start of
282ece8a530Spatrick   // the .got section.
283ece8a530Spatrick   // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
284ece8a530Spatrick   // correctness of some relocations depends on its value.
285ece8a530Spatrick   StringRef gotSymName =
286ece8a530Spatrick       (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
287ece8a530Spatrick 
288ece8a530Spatrick   if (Symbol *s = symtab->find(gotSymName)) {
289ece8a530Spatrick     if (s->isDefined()) {
290ece8a530Spatrick       error(toString(s->file) + " cannot redefine linker defined symbol '" +
291ece8a530Spatrick             gotSymName + "'");
292ece8a530Spatrick       return;
293ece8a530Spatrick     }
294ece8a530Spatrick 
295ece8a530Spatrick     uint64_t gotOff = 0;
296ece8a530Spatrick     if (config->emachine == EM_PPC64)
297ece8a530Spatrick       gotOff = 0x8000;
298ece8a530Spatrick 
299ece8a530Spatrick     s->resolve(Defined{/*file=*/nullptr, gotSymName, STB_GLOBAL, STV_HIDDEN,
300ece8a530Spatrick                        STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
301ece8a530Spatrick     ElfSym::globalOffsetTable = cast<Defined>(s);
302ece8a530Spatrick   }
303ece8a530Spatrick 
304ece8a530Spatrick   // __ehdr_start is the location of ELF file headers. Note that we define
305ece8a530Spatrick   // this symbol unconditionally even when using a linker script, which
306ece8a530Spatrick   // differs from the behavior implemented by GNU linker which only define
307ece8a530Spatrick   // this symbol if ELF headers are in the memory mapped segment.
308ece8a530Spatrick   addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
309ece8a530Spatrick 
310ece8a530Spatrick   // __executable_start is not documented, but the expectation of at
311ece8a530Spatrick   // least the Android libc is that it points to the ELF header.
312ece8a530Spatrick   addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
313ece8a530Spatrick 
314ece8a530Spatrick   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
315ece8a530Spatrick   // each DSO. The address of the symbol doesn't matter as long as they are
316ece8a530Spatrick   // different in different DSOs, so we chose the start address of the DSO.
317ece8a530Spatrick   addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
318ece8a530Spatrick 
319ece8a530Spatrick   // If linker script do layout we do not need to create any standard symbols.
320ece8a530Spatrick   if (script->hasSectionsCommand)
321ece8a530Spatrick     return;
322ece8a530Spatrick 
323ece8a530Spatrick   auto add = [](StringRef s, int64_t pos) {
324ece8a530Spatrick     return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
325ece8a530Spatrick   };
326ece8a530Spatrick 
327ece8a530Spatrick   ElfSym::bss = add("__bss_start", 0);
328adae0cfdSpatrick   ElfSym::data = add("__data_start", 0);
329ece8a530Spatrick   ElfSym::end1 = add("end", -1);
330ece8a530Spatrick   ElfSym::end2 = add("_end", -1);
331ece8a530Spatrick   ElfSym::etext1 = add("etext", -1);
332ece8a530Spatrick   ElfSym::etext2 = add("_etext", -1);
333ece8a530Spatrick   ElfSym::edata1 = add("edata", -1);
334ece8a530Spatrick   ElfSym::edata2 = add("_edata", -1);
335ece8a530Spatrick }
336ece8a530Spatrick 
337ece8a530Spatrick static OutputSection *findSection(StringRef name, unsigned partition = 1) {
338ece8a530Spatrick   for (BaseCommand *base : script->sectionCommands)
339ece8a530Spatrick     if (auto *sec = dyn_cast<OutputSection>(base))
340ece8a530Spatrick       if (sec->name == name && sec->partition == partition)
341ece8a530Spatrick         return sec;
342ece8a530Spatrick   return nullptr;
343ece8a530Spatrick }
344ece8a530Spatrick 
345bb684c34Spatrick template <class ELFT> void elf::createSyntheticSections() {
346ece8a530Spatrick   // Initialize all pointers with NULL. This is needed because
347ece8a530Spatrick   // you can call lld::elf::main more than once as a library.
348ece8a530Spatrick   memset(&Out::first, 0, sizeof(Out));
349ece8a530Spatrick 
350ece8a530Spatrick   // Add the .interp section first because it is not a SyntheticSection.
351ece8a530Spatrick   // The removeUnusedSyntheticSections() function relies on the
352ece8a530Spatrick   // SyntheticSections coming last.
353ece8a530Spatrick   if (needsInterpSection()) {
354ece8a530Spatrick     for (size_t i = 1; i <= partitions.size(); ++i) {
355ece8a530Spatrick       InputSection *sec = createInterpSection();
356ece8a530Spatrick       sec->partition = i;
357ece8a530Spatrick       inputSections.push_back(sec);
358ece8a530Spatrick     }
359ece8a530Spatrick   }
360ece8a530Spatrick 
361ece8a530Spatrick   auto add = [](SyntheticSection *sec) { inputSections.push_back(sec); };
362ece8a530Spatrick 
363ece8a530Spatrick   in.shStrTab = make<StringTableSection>(".shstrtab", false);
364ece8a530Spatrick 
365ece8a530Spatrick   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
366ece8a530Spatrick   Out::programHeaders->alignment = config->wordsize;
367ece8a530Spatrick 
368ece8a530Spatrick   if (config->strip != StripPolicy::All) {
369ece8a530Spatrick     in.strTab = make<StringTableSection>(".strtab", false);
370ece8a530Spatrick     in.symTab = make<SymbolTableSection<ELFT>>(*in.strTab);
371ece8a530Spatrick     in.symTabShndx = make<SymtabShndxSection>();
372ece8a530Spatrick   }
373ece8a530Spatrick 
374ece8a530Spatrick   in.bss = make<BssSection>(".bss", 0, 1);
375ece8a530Spatrick   add(in.bss);
376ece8a530Spatrick 
377ece8a530Spatrick   // If there is a SECTIONS command and a .data.rel.ro section name use name
378ece8a530Spatrick   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
379ece8a530Spatrick   // This makes sure our relro is contiguous.
380ece8a530Spatrick   bool hasDataRelRo =
381ece8a530Spatrick       script->hasSectionsCommand && findSection(".data.rel.ro", 0);
382ece8a530Spatrick   in.bssRelRo =
383ece8a530Spatrick       make<BssSection>(hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
384ece8a530Spatrick   add(in.bssRelRo);
385ece8a530Spatrick 
386ece8a530Spatrick   // Add MIPS-specific sections.
387ece8a530Spatrick   if (config->emachine == EM_MIPS) {
388ece8a530Spatrick     if (!config->shared && config->hasDynSymTab) {
389ece8a530Spatrick       in.mipsRldMap = make<MipsRldMapSection>();
390ece8a530Spatrick       add(in.mipsRldMap);
391ece8a530Spatrick     }
392ece8a530Spatrick     if (auto *sec = MipsAbiFlagsSection<ELFT>::create())
393ece8a530Spatrick       add(sec);
394ece8a530Spatrick     if (auto *sec = MipsOptionsSection<ELFT>::create())
395ece8a530Spatrick       add(sec);
396ece8a530Spatrick     if (auto *sec = MipsReginfoSection<ELFT>::create())
397ece8a530Spatrick       add(sec);
398ece8a530Spatrick   }
399ece8a530Spatrick 
400ece8a530Spatrick   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
401ece8a530Spatrick 
402ece8a530Spatrick   for (Partition &part : partitions) {
403ece8a530Spatrick     auto add = [&](SyntheticSection *sec) {
404ece8a530Spatrick       sec->partition = part.getNumber();
405ece8a530Spatrick       inputSections.push_back(sec);
406ece8a530Spatrick     };
407ece8a530Spatrick 
408ece8a530Spatrick     if (!part.name.empty()) {
409ece8a530Spatrick       part.elfHeader = make<PartitionElfHeaderSection<ELFT>>();
410ece8a530Spatrick       part.elfHeader->name = part.name;
411ece8a530Spatrick       add(part.elfHeader);
412ece8a530Spatrick 
413ece8a530Spatrick       part.programHeaders = make<PartitionProgramHeadersSection<ELFT>>();
414ece8a530Spatrick       add(part.programHeaders);
415ece8a530Spatrick     }
416ece8a530Spatrick 
417ece8a530Spatrick     if (config->buildId != BuildIdKind::None) {
418ece8a530Spatrick       part.buildId = make<BuildIdSection>();
419ece8a530Spatrick       add(part.buildId);
420ece8a530Spatrick     }
421ece8a530Spatrick 
422ece8a530Spatrick     part.dynStrTab = make<StringTableSection>(".dynstr", true);
423ece8a530Spatrick     part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
424ece8a530Spatrick     part.dynamic = make<DynamicSection<ELFT>>();
425ece8a530Spatrick     if (config->androidPackDynRelocs)
426ece8a530Spatrick       part.relaDyn = make<AndroidPackedRelocationSection<ELFT>>(relaDynName);
427ece8a530Spatrick     else
428ece8a530Spatrick       part.relaDyn =
429ece8a530Spatrick           make<RelocationSection<ELFT>>(relaDynName, config->zCombreloc);
430ece8a530Spatrick 
431ece8a530Spatrick     if (config->hasDynSymTab) {
432ece8a530Spatrick       part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
433ece8a530Spatrick       add(part.dynSymTab);
434ece8a530Spatrick 
435ece8a530Spatrick       part.verSym = make<VersionTableSection>();
436ece8a530Spatrick       add(part.verSym);
437ece8a530Spatrick 
438ece8a530Spatrick       if (!namedVersionDefs().empty()) {
439ece8a530Spatrick         part.verDef = make<VersionDefinitionSection>();
440ece8a530Spatrick         add(part.verDef);
441ece8a530Spatrick       }
442ece8a530Spatrick 
443ece8a530Spatrick       part.verNeed = make<VersionNeedSection<ELFT>>();
444ece8a530Spatrick       add(part.verNeed);
445ece8a530Spatrick 
446ece8a530Spatrick       if (config->gnuHash) {
447ece8a530Spatrick         part.gnuHashTab = make<GnuHashTableSection>();
448ece8a530Spatrick         add(part.gnuHashTab);
449ece8a530Spatrick       }
450ece8a530Spatrick 
451ece8a530Spatrick       if (config->sysvHash) {
452ece8a530Spatrick         part.hashTab = make<HashTableSection>();
453ece8a530Spatrick         add(part.hashTab);
454ece8a530Spatrick       }
455ece8a530Spatrick 
456ece8a530Spatrick       add(part.dynamic);
457ece8a530Spatrick       add(part.dynStrTab);
458ece8a530Spatrick       add(part.relaDyn);
459ece8a530Spatrick     }
460ece8a530Spatrick 
461ece8a530Spatrick     if (config->relrPackDynRelocs) {
462ece8a530Spatrick       part.relrDyn = make<RelrSection<ELFT>>();
463ece8a530Spatrick       add(part.relrDyn);
464ece8a530Spatrick     }
465ece8a530Spatrick 
466ece8a530Spatrick     if (!config->relocatable) {
467ece8a530Spatrick       if (config->ehFrameHdr) {
468ece8a530Spatrick         part.ehFrameHdr = make<EhFrameHeader>();
469ece8a530Spatrick         add(part.ehFrameHdr);
470ece8a530Spatrick       }
471ece8a530Spatrick       part.ehFrame = make<EhFrameSection>();
472ece8a530Spatrick       add(part.ehFrame);
473ece8a530Spatrick     }
474ece8a530Spatrick 
475ece8a530Spatrick     if (config->emachine == EM_ARM && !config->relocatable) {
476ece8a530Spatrick       // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
477ece8a530Spatrick       // InputSections.
478ece8a530Spatrick       part.armExidx = make<ARMExidxSyntheticSection>();
479ece8a530Spatrick       add(part.armExidx);
480ece8a530Spatrick     }
481ece8a530Spatrick   }
482ece8a530Spatrick 
483ece8a530Spatrick   if (partitions.size() != 1) {
484ece8a530Spatrick     // Create the partition end marker. This needs to be in partition number 255
485ece8a530Spatrick     // so that it is sorted after all other partitions. It also has other
486ece8a530Spatrick     // special handling (see createPhdrs() and combineEhSections()).
487ece8a530Spatrick     in.partEnd = make<BssSection>(".part.end", config->maxPageSize, 1);
488ece8a530Spatrick     in.partEnd->partition = 255;
489ece8a530Spatrick     add(in.partEnd);
490ece8a530Spatrick 
491ece8a530Spatrick     in.partIndex = make<PartitionIndexSection>();
492ece8a530Spatrick     addOptionalRegular("__part_index_begin", in.partIndex, 0);
493ece8a530Spatrick     addOptionalRegular("__part_index_end", in.partIndex,
494ece8a530Spatrick                        in.partIndex->getSize());
495ece8a530Spatrick     add(in.partIndex);
496ece8a530Spatrick   }
497ece8a530Spatrick 
498ece8a530Spatrick   // Add .got. MIPS' .got is so different from the other archs,
499ece8a530Spatrick   // it has its own class.
500ece8a530Spatrick   if (config->emachine == EM_MIPS) {
501ece8a530Spatrick     in.mipsGot = make<MipsGotSection>();
502ece8a530Spatrick     add(in.mipsGot);
503ece8a530Spatrick   } else {
504ece8a530Spatrick     in.got = make<GotSection>();
505ece8a530Spatrick     add(in.got);
506ece8a530Spatrick   }
507ece8a530Spatrick 
508ece8a530Spatrick   if (config->emachine == EM_PPC) {
509ece8a530Spatrick     in.ppc32Got2 = make<PPC32Got2Section>();
510ece8a530Spatrick     add(in.ppc32Got2);
511ece8a530Spatrick   }
512ece8a530Spatrick 
513ece8a530Spatrick   if (config->emachine == EM_PPC64) {
514ece8a530Spatrick     in.ppc64LongBranchTarget = make<PPC64LongBranchTargetSection>();
515ece8a530Spatrick     add(in.ppc64LongBranchTarget);
516ece8a530Spatrick   }
517ece8a530Spatrick 
518ece8a530Spatrick   in.gotPlt = make<GotPltSection>();
519ece8a530Spatrick   add(in.gotPlt);
520ece8a530Spatrick   in.igotPlt = make<IgotPltSection>();
521ece8a530Spatrick   add(in.igotPlt);
522ece8a530Spatrick 
523ece8a530Spatrick   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
524ece8a530Spatrick   // it as a relocation and ensure the referenced section is created.
525ece8a530Spatrick   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
526ece8a530Spatrick     if (target->gotBaseSymInGotPlt)
527ece8a530Spatrick       in.gotPlt->hasGotPltOffRel = true;
528ece8a530Spatrick     else
529ece8a530Spatrick       in.got->hasGotOffRel = true;
530ece8a530Spatrick   }
531ece8a530Spatrick 
532ece8a530Spatrick   if (config->gdbIndex)
533ece8a530Spatrick     add(GdbIndexSection::create<ELFT>());
534ece8a530Spatrick 
535ece8a530Spatrick   // We always need to add rel[a].plt to output if it has entries.
536ece8a530Spatrick   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
537ece8a530Spatrick   in.relaPlt = make<RelocationSection<ELFT>>(
538ece8a530Spatrick       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
539ece8a530Spatrick   add(in.relaPlt);
540ece8a530Spatrick 
541ece8a530Spatrick   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
542ece8a530Spatrick   // relocations are processed last by the dynamic loader. We cannot place the
543ece8a530Spatrick   // iplt section in .rel.dyn when Android relocation packing is enabled because
544ece8a530Spatrick   // that would cause a section type mismatch. However, because the Android
545ece8a530Spatrick   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
546ece8a530Spatrick   // behaviour by placing the iplt section in .rel.plt.
547ece8a530Spatrick   in.relaIplt = make<RelocationSection<ELFT>>(
548ece8a530Spatrick       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
549ece8a530Spatrick       /*sort=*/false);
550ece8a530Spatrick   add(in.relaIplt);
551ece8a530Spatrick 
552ece8a530Spatrick   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
553ece8a530Spatrick       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
554ece8a530Spatrick     in.ibtPlt = make<IBTPltSection>();
555ece8a530Spatrick     add(in.ibtPlt);
556ece8a530Spatrick   }
557ece8a530Spatrick 
558bb684c34Spatrick   in.plt = config->emachine == EM_PPC ? make<PPC32GlinkSection>()
559bb684c34Spatrick                                       : make<PltSection>();
560ece8a530Spatrick   add(in.plt);
561ece8a530Spatrick   in.iplt = make<IpltSection>();
562ece8a530Spatrick   add(in.iplt);
563ece8a530Spatrick 
564ece8a530Spatrick   if (config->andFeatures)
565ece8a530Spatrick     add(make<GnuPropertySection>());
566ece8a530Spatrick 
567ece8a530Spatrick   // .note.GNU-stack is always added when we are creating a re-linkable
568ece8a530Spatrick   // object file. Other linkers are using the presence of this marker
569ece8a530Spatrick   // section to control the executable-ness of the stack area, but that
570ece8a530Spatrick   // is irrelevant these days. Stack area should always be non-executable
571ece8a530Spatrick   // by default. So we emit this section unconditionally.
572ece8a530Spatrick   if (config->relocatable)
573ece8a530Spatrick     add(make<GnuStackSection>());
574ece8a530Spatrick 
575ece8a530Spatrick   if (in.symTab)
576ece8a530Spatrick     add(in.symTab);
577ece8a530Spatrick   if (in.symTabShndx)
578ece8a530Spatrick     add(in.symTabShndx);
579ece8a530Spatrick   add(in.shStrTab);
580ece8a530Spatrick   if (in.strTab)
581ece8a530Spatrick     add(in.strTab);
582ece8a530Spatrick }
583ece8a530Spatrick 
584ece8a530Spatrick // The main function of the writer.
585ece8a530Spatrick template <class ELFT> void Writer<ELFT>::run() {
586ece8a530Spatrick   copyLocalSymbols();
587ece8a530Spatrick 
588ece8a530Spatrick   if (config->copyRelocs)
589ece8a530Spatrick     addSectionSymbols();
590ece8a530Spatrick 
591ece8a530Spatrick   // Now that we have a complete set of output sections. This function
592ece8a530Spatrick   // completes section contents. For example, we need to add strings
593ece8a530Spatrick   // to the string table, and add entries to .got and .plt.
594ece8a530Spatrick   // finalizeSections does that.
595ece8a530Spatrick   finalizeSections();
596ece8a530Spatrick   checkExecuteOnly();
597ece8a530Spatrick   if (errorCount())
598ece8a530Spatrick     return;
599ece8a530Spatrick 
600ece8a530Spatrick   // If -compressed-debug-sections is specified, we need to compress
601ece8a530Spatrick   // .debug_* sections. Do it right now because it changes the size of
602ece8a530Spatrick   // output sections.
603ece8a530Spatrick   for (OutputSection *sec : outputSections)
604ece8a530Spatrick     sec->maybeCompress<ELFT>();
605ece8a530Spatrick 
606ece8a530Spatrick   if (script->hasSectionsCommand)
607ece8a530Spatrick     script->allocateHeaders(mainPart->phdrs);
608ece8a530Spatrick 
609ece8a530Spatrick   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
610ece8a530Spatrick   // 0 sized region. This has to be done late since only after assignAddresses
611ece8a530Spatrick   // we know the size of the sections.
612ece8a530Spatrick   for (Partition &part : partitions)
613ece8a530Spatrick     removeEmptyPTLoad(part.phdrs);
614ece8a530Spatrick 
615ece8a530Spatrick   if (!config->oFormatBinary)
616ece8a530Spatrick     assignFileOffsets();
617ece8a530Spatrick   else
618ece8a530Spatrick     assignFileOffsetsBinary();
619ece8a530Spatrick 
620ece8a530Spatrick   for (Partition &part : partitions)
621ece8a530Spatrick     setPhdrs(part);
622ece8a530Spatrick 
623ece8a530Spatrick   if (config->relocatable)
624ece8a530Spatrick     for (OutputSection *sec : outputSections)
625ece8a530Spatrick       sec->addr = 0;
626ece8a530Spatrick 
627bb684c34Spatrick   // Handle --print-map(-M)/--Map, --cref and --print-archive-stats=. Dump them
628bb684c34Spatrick   // before checkSections() because the files may be useful in case
629bb684c34Spatrick   // checkSections() or openFile() fails, for example, due to an erroneous file
630bb684c34Spatrick   // size.
631bb684c34Spatrick   writeMapFile();
632bb684c34Spatrick   writeCrossReferenceTable();
633bb684c34Spatrick   writeArchiveStats();
634bb684c34Spatrick 
635ece8a530Spatrick   if (config->checkSections)
636ece8a530Spatrick     checkSections();
637ece8a530Spatrick 
638ece8a530Spatrick   // It does not make sense try to open the file if we have error already.
639ece8a530Spatrick   if (errorCount())
640ece8a530Spatrick     return;
641*a0747c9fSpatrick 
642*a0747c9fSpatrick   {
643*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Write output file");
644ece8a530Spatrick     // Write the result down to a file.
645ece8a530Spatrick     openFile();
646ece8a530Spatrick     if (errorCount())
647ece8a530Spatrick       return;
648ece8a530Spatrick 
649ece8a530Spatrick     if (!config->oFormatBinary) {
650ece8a530Spatrick       if (config->zSeparate != SeparateSegmentKind::None)
651ece8a530Spatrick         writeTrapInstr();
652ece8a530Spatrick       writeHeader();
653ece8a530Spatrick       writeSections();
654ece8a530Spatrick     } else {
655ece8a530Spatrick       writeSectionsBinary();
656ece8a530Spatrick     }
657ece8a530Spatrick 
658ece8a530Spatrick     // Backfill .note.gnu.build-id section content. This is done at last
659ece8a530Spatrick     // because the content is usually a hash value of the entire output file.
660ece8a530Spatrick     writeBuildId();
661ece8a530Spatrick     if (errorCount())
662ece8a530Spatrick       return;
663ece8a530Spatrick 
664ece8a530Spatrick     if (auto e = buffer->commit())
665ece8a530Spatrick       error("failed to write to the output file: " + toString(std::move(e)));
666ece8a530Spatrick   }
667*a0747c9fSpatrick }
668ece8a530Spatrick 
669bb684c34Spatrick template <class ELFT, class RelTy>
670bb684c34Spatrick static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
671bb684c34Spatrick                                      llvm::ArrayRef<RelTy> rels) {
672bb684c34Spatrick   for (const RelTy &rel : rels) {
673bb684c34Spatrick     Symbol &sym = file->getRelocTargetSym(rel);
674bb684c34Spatrick     if (sym.isLocal())
675bb684c34Spatrick       sym.used = true;
676bb684c34Spatrick   }
677bb684c34Spatrick }
678bb684c34Spatrick 
679bb684c34Spatrick // The function ensures that the "used" field of local symbols reflects the fact
680bb684c34Spatrick // that the symbol is used in a relocation from a live section.
681bb684c34Spatrick template <class ELFT> static void markUsedLocalSymbols() {
682bb684c34Spatrick   // With --gc-sections, the field is already filled.
683bb684c34Spatrick   // See MarkLive<ELFT>::resolveReloc().
684bb684c34Spatrick   if (config->gcSections)
685bb684c34Spatrick     return;
686bb684c34Spatrick   // Without --gc-sections, the field is initialized with "true".
687bb684c34Spatrick   // Drop the flag first and then rise for symbols referenced in relocations.
688bb684c34Spatrick   for (InputFile *file : objectFiles) {
689bb684c34Spatrick     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
690bb684c34Spatrick     for (Symbol *b : f->getLocalSymbols())
691bb684c34Spatrick       b->used = false;
692bb684c34Spatrick     for (InputSectionBase *s : f->getSections()) {
693bb684c34Spatrick       InputSection *isec = dyn_cast_or_null<InputSection>(s);
694bb684c34Spatrick       if (!isec)
695bb684c34Spatrick         continue;
696bb684c34Spatrick       if (isec->type == SHT_REL)
697bb684c34Spatrick         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
698bb684c34Spatrick       else if (isec->type == SHT_RELA)
699bb684c34Spatrick         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
700bb684c34Spatrick     }
701bb684c34Spatrick   }
702bb684c34Spatrick }
703bb684c34Spatrick 
704ece8a530Spatrick static bool shouldKeepInSymtab(const Defined &sym) {
705ece8a530Spatrick   if (sym.isSection())
706ece8a530Spatrick     return false;
707ece8a530Spatrick 
708bb684c34Spatrick   // If --emit-reloc or -r is given, preserve symbols referenced by relocations
709bb684c34Spatrick   // from live sections.
710bb684c34Spatrick   if (config->copyRelocs && sym.used)
711ece8a530Spatrick     return true;
712ece8a530Spatrick 
713bb684c34Spatrick   // Exclude local symbols pointing to .ARM.exidx sections.
714bb684c34Spatrick   // They are probably mapping symbols "$d", which are optional for these
715bb684c34Spatrick   // sections. After merging the .ARM.exidx sections, some of these symbols
716bb684c34Spatrick   // may become dangling. The easiest way to avoid the issue is not to add
717bb684c34Spatrick   // them to the symbol table from the beginning.
718bb684c34Spatrick   if (config->emachine == EM_ARM && sym.section &&
719bb684c34Spatrick       sym.section->type == SHT_ARM_EXIDX)
720bb684c34Spatrick     return false;
721bb684c34Spatrick 
722bb684c34Spatrick   if (config->discard == DiscardPolicy::None)
723ece8a530Spatrick     return true;
724bb684c34Spatrick   if (config->discard == DiscardPolicy::All)
725bb684c34Spatrick     return false;
726ece8a530Spatrick 
727ece8a530Spatrick   // In ELF assembly .L symbols are normally discarded by the assembler.
728ece8a530Spatrick   // If the assembler fails to do so, the linker discards them if
729ece8a530Spatrick   // * --discard-locals is used.
730ece8a530Spatrick   // * The symbol is in a SHF_MERGE section, which is normally the reason for
731ece8a530Spatrick   //   the assembler keeping the .L symbol.
732ece8a530Spatrick   StringRef name = sym.getName();
733ece8a530Spatrick   bool isLocal = name.startswith(".L") || name.empty();
734ece8a530Spatrick   if (!isLocal)
735ece8a530Spatrick     return true;
736ece8a530Spatrick 
737ece8a530Spatrick   if (config->discard == DiscardPolicy::Locals)
738ece8a530Spatrick     return false;
739ece8a530Spatrick 
740ece8a530Spatrick   SectionBase *sec = sym.section;
741ece8a530Spatrick   return !sec || !(sec->flags & SHF_MERGE);
742ece8a530Spatrick }
743ece8a530Spatrick 
744ece8a530Spatrick static bool includeInSymtab(const Symbol &b) {
745ece8a530Spatrick   if (!b.isLocal() && !b.isUsedInRegularObj)
746ece8a530Spatrick     return false;
747ece8a530Spatrick 
748ece8a530Spatrick   if (auto *d = dyn_cast<Defined>(&b)) {
749ece8a530Spatrick     // Always include absolute symbols.
750ece8a530Spatrick     SectionBase *sec = d->section;
751ece8a530Spatrick     if (!sec)
752ece8a530Spatrick       return true;
753ece8a530Spatrick     sec = sec->repl;
754ece8a530Spatrick 
755ece8a530Spatrick     // Exclude symbols pointing to garbage-collected sections.
756ece8a530Spatrick     if (isa<InputSectionBase>(sec) && !sec->isLive())
757ece8a530Spatrick       return false;
758ece8a530Spatrick 
759ece8a530Spatrick     if (auto *s = dyn_cast<MergeInputSection>(sec))
760ece8a530Spatrick       if (!s->getSectionPiece(d->value)->live)
761ece8a530Spatrick         return false;
762ece8a530Spatrick     return true;
763ece8a530Spatrick   }
764ece8a530Spatrick   return b.used;
765ece8a530Spatrick }
766ece8a530Spatrick 
767ece8a530Spatrick // Local symbols are not in the linker's symbol table. This function scans
768ece8a530Spatrick // each object file's symbol table to copy local symbols to the output.
769ece8a530Spatrick template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
770ece8a530Spatrick   if (!in.symTab)
771ece8a530Spatrick     return;
772*a0747c9fSpatrick   llvm::TimeTraceScope timeScope("Add local symbols");
773bb684c34Spatrick   if (config->copyRelocs && config->discard != DiscardPolicy::None)
774bb684c34Spatrick     markUsedLocalSymbols<ELFT>();
775ece8a530Spatrick   for (InputFile *file : objectFiles) {
776ece8a530Spatrick     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
777ece8a530Spatrick     for (Symbol *b : f->getLocalSymbols()) {
778bb684c34Spatrick       assert(b->isLocal() && "should have been caught in initializeSymbols()");
779ece8a530Spatrick       auto *dr = dyn_cast<Defined>(b);
780ece8a530Spatrick 
781ece8a530Spatrick       // No reason to keep local undefined symbol in symtab.
782ece8a530Spatrick       if (!dr)
783ece8a530Spatrick         continue;
784ece8a530Spatrick       if (!includeInSymtab(*b))
785ece8a530Spatrick         continue;
786ece8a530Spatrick       if (!shouldKeepInSymtab(*dr))
787ece8a530Spatrick         continue;
788ece8a530Spatrick       in.symTab->addSymbol(b);
789ece8a530Spatrick     }
790ece8a530Spatrick   }
791ece8a530Spatrick }
792ece8a530Spatrick 
793ece8a530Spatrick // Create a section symbol for each output section so that we can represent
794ece8a530Spatrick // relocations that point to the section. If we know that no relocation is
795ece8a530Spatrick // referring to a section (that happens if the section is a synthetic one), we
796ece8a530Spatrick // don't create a section symbol for that section.
797ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
798ece8a530Spatrick   for (BaseCommand *base : script->sectionCommands) {
799ece8a530Spatrick     auto *sec = dyn_cast<OutputSection>(base);
800ece8a530Spatrick     if (!sec)
801ece8a530Spatrick       continue;
802ece8a530Spatrick     auto i = llvm::find_if(sec->sectionCommands, [](BaseCommand *base) {
803ece8a530Spatrick       if (auto *isd = dyn_cast<InputSectionDescription>(base))
804ece8a530Spatrick         return !isd->sections.empty();
805ece8a530Spatrick       return false;
806ece8a530Spatrick     });
807ece8a530Spatrick     if (i == sec->sectionCommands.end())
808ece8a530Spatrick       continue;
809ece8a530Spatrick     InputSectionBase *isec = cast<InputSectionDescription>(*i)->sections[0];
810ece8a530Spatrick 
811ece8a530Spatrick     // Relocations are not using REL[A] section symbols.
812ece8a530Spatrick     if (isec->type == SHT_REL || isec->type == SHT_RELA)
813ece8a530Spatrick       continue;
814ece8a530Spatrick 
815ece8a530Spatrick     // Unlike other synthetic sections, mergeable output sections contain data
816ece8a530Spatrick     // copied from input sections, and there may be a relocation pointing to its
817ece8a530Spatrick     // contents if -r or -emit-reloc are given.
818ece8a530Spatrick     if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
819ece8a530Spatrick       continue;
820ece8a530Spatrick 
821*a0747c9fSpatrick     // Set the symbol to be relative to the output section so that its st_value
822*a0747c9fSpatrick     // equals the output section address. Note, there may be a gap between the
823*a0747c9fSpatrick     // start of the output section and isec.
824ece8a530Spatrick     auto *sym =
825ece8a530Spatrick         make<Defined>(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION,
826*a0747c9fSpatrick                       /*value=*/0, /*size=*/0, isec->getOutputSection());
827ece8a530Spatrick     in.symTab->addSymbol(sym);
828ece8a530Spatrick   }
829ece8a530Spatrick }
830ece8a530Spatrick 
831ece8a530Spatrick // Today's loaders have a feature to make segments read-only after
832ece8a530Spatrick // processing dynamic relocations to enhance security. PT_GNU_RELRO
833ece8a530Spatrick // is defined for that.
834ece8a530Spatrick //
835ece8a530Spatrick // This function returns true if a section needs to be put into a
836ece8a530Spatrick // PT_GNU_RELRO segment.
837ece8a530Spatrick static bool isRelroSection(const OutputSection *sec) {
838ece8a530Spatrick   if (!config->zRelro)
839ece8a530Spatrick     return false;
840ece8a530Spatrick 
841ece8a530Spatrick   uint64_t flags = sec->flags;
842ece8a530Spatrick 
843ece8a530Spatrick   // Non-allocatable or non-writable sections don't need RELRO because
844ece8a530Spatrick   // they are not writable or not even mapped to memory in the first place.
845ece8a530Spatrick   // RELRO is for sections that are essentially read-only but need to
846ece8a530Spatrick   // be writable only at process startup to allow dynamic linker to
847ece8a530Spatrick   // apply relocations.
848ece8a530Spatrick   if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
849ece8a530Spatrick     return false;
850ece8a530Spatrick 
851ece8a530Spatrick   // Once initialized, TLS data segments are used as data templates
852ece8a530Spatrick   // for a thread-local storage. For each new thread, runtime
853ece8a530Spatrick   // allocates memory for a TLS and copy templates there. No thread
854ece8a530Spatrick   // are supposed to use templates directly. Thus, it can be in RELRO.
855ece8a530Spatrick   if (flags & SHF_TLS)
856ece8a530Spatrick     return true;
857ece8a530Spatrick 
858ece8a530Spatrick   // .init_array, .preinit_array and .fini_array contain pointers to
859ece8a530Spatrick   // functions that are executed on process startup or exit. These
860ece8a530Spatrick   // pointers are set by the static linker, and they are not expected
861ece8a530Spatrick   // to change at runtime. But if you are an attacker, you could do
862ece8a530Spatrick   // interesting things by manipulating pointers in .fini_array, for
863ece8a530Spatrick   // example. So they are put into RELRO.
864ece8a530Spatrick   uint32_t type = sec->type;
865ece8a530Spatrick   if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
866ece8a530Spatrick       type == SHT_PREINIT_ARRAY)
867ece8a530Spatrick     return true;
868ece8a530Spatrick 
869ece8a530Spatrick   // .got contains pointers to external symbols. They are resolved by
870ece8a530Spatrick   // the dynamic linker when a module is loaded into memory, and after
871ece8a530Spatrick   // that they are not expected to change. So, it can be in RELRO.
872ece8a530Spatrick   if (in.got && sec == in.got->getParent())
873ece8a530Spatrick     return true;
874ece8a530Spatrick 
875ece8a530Spatrick   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
876ece8a530Spatrick   // through r2 register, which is reserved for that purpose. Since r2 is used
877ece8a530Spatrick   // for accessing .got as well, .got and .toc need to be close enough in the
878ece8a530Spatrick   // virtual address space. Usually, .toc comes just after .got. Since we place
879ece8a530Spatrick   // .got into RELRO, .toc needs to be placed into RELRO too.
880ece8a530Spatrick   if (sec->name.equals(".toc"))
881ece8a530Spatrick     return true;
882ece8a530Spatrick 
883ece8a530Spatrick   // .got.plt contains pointers to external function symbols. They are
884ece8a530Spatrick   // by default resolved lazily, so we usually cannot put it into RELRO.
885ece8a530Spatrick   // However, if "-z now" is given, the lazy symbol resolution is
886ece8a530Spatrick   // disabled, which enables us to put it into RELRO.
887ece8a530Spatrick   if (sec == in.gotPlt->getParent())
888adae0cfdSpatrick #ifndef __OpenBSD__
889ece8a530Spatrick     return config->zNow;
890adae0cfdSpatrick #else
891adae0cfdSpatrick     return true;	/* kbind(2) means we can always put these in RELRO */
892adae0cfdSpatrick #endif
893ece8a530Spatrick 
894ece8a530Spatrick   // .dynamic section contains data for the dynamic linker, and
895ece8a530Spatrick   // there's no need to write to it at runtime, so it's better to put
896ece8a530Spatrick   // it into RELRO.
897ece8a530Spatrick   if (sec->name == ".dynamic")
898ece8a530Spatrick     return true;
899ece8a530Spatrick 
900ece8a530Spatrick   // Sections with some special names are put into RELRO. This is a
901ece8a530Spatrick   // bit unfortunate because section names shouldn't be significant in
902ece8a530Spatrick   // ELF in spirit. But in reality many linker features depend on
903ece8a530Spatrick   // magic section names.
904ece8a530Spatrick   StringRef s = sec->name;
905ece8a530Spatrick   return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
906ece8a530Spatrick          s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
907bb684c34Spatrick          s == ".fini_array" || s == ".init_array" ||
908bb684c34Spatrick          s == ".openbsd.randomdata" || s == ".preinit_array";
909ece8a530Spatrick }
910ece8a530Spatrick 
911ece8a530Spatrick // We compute a rank for each section. The rank indicates where the
912ece8a530Spatrick // section should be placed in the file.  Instead of using simple
913ece8a530Spatrick // numbers (0,1,2...), we use a series of flags. One for each decision
914ece8a530Spatrick // point when placing the section.
915ece8a530Spatrick // Using flags has two key properties:
916ece8a530Spatrick // * It is easy to check if a give branch was taken.
917ece8a530Spatrick // * It is easy two see how similar two ranks are (see getRankProximity).
918ece8a530Spatrick enum RankFlags {
919ece8a530Spatrick   RF_NOT_ADDR_SET = 1 << 27,
920ece8a530Spatrick   RF_NOT_ALLOC = 1 << 26,
921ece8a530Spatrick   RF_PARTITION = 1 << 18, // Partition number (8 bits)
922ece8a530Spatrick   RF_NOT_PART_EHDR = 1 << 17,
923ece8a530Spatrick   RF_NOT_PART_PHDR = 1 << 16,
924ece8a530Spatrick   RF_NOT_INTERP = 1 << 15,
925ece8a530Spatrick   RF_NOT_NOTE = 1 << 14,
926ece8a530Spatrick   RF_WRITE = 1 << 13,
927ece8a530Spatrick   RF_EXEC_WRITE = 1 << 12,
928ece8a530Spatrick   RF_EXEC = 1 << 11,
929ece8a530Spatrick   RF_RODATA = 1 << 10,
930ece8a530Spatrick   RF_NOT_RELRO = 1 << 9,
931ece8a530Spatrick   RF_NOT_TLS = 1 << 8,
932ece8a530Spatrick   RF_BSS = 1 << 7,
933ece8a530Spatrick   RF_PPC_NOT_TOCBSS = 1 << 6,
934ece8a530Spatrick   RF_PPC_TOCL = 1 << 5,
935ece8a530Spatrick   RF_PPC_TOC = 1 << 4,
936ece8a530Spatrick   RF_PPC_GOT = 1 << 3,
937ece8a530Spatrick   RF_PPC_BRANCH_LT = 1 << 2,
938ece8a530Spatrick   RF_MIPS_GPREL = 1 << 1,
939ece8a530Spatrick   RF_MIPS_NOT_GOT = 1 << 0
940ece8a530Spatrick };
941ece8a530Spatrick 
942ece8a530Spatrick static unsigned getSectionRank(const OutputSection *sec) {
943ece8a530Spatrick   unsigned rank = sec->partition * RF_PARTITION;
944ece8a530Spatrick 
945ece8a530Spatrick   // We want to put section specified by -T option first, so we
946ece8a530Spatrick   // can start assigning VA starting from them later.
947ece8a530Spatrick   if (config->sectionStartMap.count(sec->name))
948ece8a530Spatrick     return rank;
949ece8a530Spatrick   rank |= RF_NOT_ADDR_SET;
950ece8a530Spatrick 
951ece8a530Spatrick   // Allocatable sections go first to reduce the total PT_LOAD size and
952ece8a530Spatrick   // so debug info doesn't change addresses in actual code.
953ece8a530Spatrick   if (!(sec->flags & SHF_ALLOC))
954ece8a530Spatrick     return rank | RF_NOT_ALLOC;
955ece8a530Spatrick 
956ece8a530Spatrick   if (sec->type == SHT_LLVM_PART_EHDR)
957ece8a530Spatrick     return rank;
958ece8a530Spatrick   rank |= RF_NOT_PART_EHDR;
959ece8a530Spatrick 
960ece8a530Spatrick   if (sec->type == SHT_LLVM_PART_PHDR)
961ece8a530Spatrick     return rank;
962ece8a530Spatrick   rank |= RF_NOT_PART_PHDR;
963ece8a530Spatrick 
964ece8a530Spatrick   // Put .interp first because some loaders want to see that section
965ece8a530Spatrick   // on the first page of the executable file when loaded into memory.
966ece8a530Spatrick   if (sec->name == ".interp")
967ece8a530Spatrick     return rank;
968ece8a530Spatrick   rank |= RF_NOT_INTERP;
969ece8a530Spatrick 
970ece8a530Spatrick   // Put .note sections (which make up one PT_NOTE) at the beginning so that
971ece8a530Spatrick   // they are likely to be included in a core file even if core file size is
972ece8a530Spatrick   // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
973ece8a530Spatrick   // included in a core to match core files with executables.
974ece8a530Spatrick   if (sec->type == SHT_NOTE)
975ece8a530Spatrick     return rank;
976ece8a530Spatrick   rank |= RF_NOT_NOTE;
977ece8a530Spatrick 
978ece8a530Spatrick   // Sort sections based on their access permission in the following
979ece8a530Spatrick   // order: R, RX, RWX, RW.  This order is based on the following
980ece8a530Spatrick   // considerations:
981ece8a530Spatrick   // * Read-only sections come first such that they go in the
982ece8a530Spatrick   //   PT_LOAD covering the program headers at the start of the file.
983ece8a530Spatrick   // * Read-only, executable sections come next.
984ece8a530Spatrick   // * Writable, executable sections follow such that .plt on
985ece8a530Spatrick   //   architectures where it needs to be writable will be placed
986ece8a530Spatrick   //   between .text and .data.
987ece8a530Spatrick   // * Writable sections come last, such that .bss lands at the very
988ece8a530Spatrick   //   end of the last PT_LOAD.
989ece8a530Spatrick   bool isExec = sec->flags & SHF_EXECINSTR;
990ece8a530Spatrick   bool isWrite = sec->flags & SHF_WRITE;
991ece8a530Spatrick 
992ece8a530Spatrick   if (isExec) {
993ece8a530Spatrick     if (isWrite)
994ece8a530Spatrick       rank |= RF_EXEC_WRITE;
995ece8a530Spatrick     else
996ece8a530Spatrick       rank |= RF_EXEC;
997ece8a530Spatrick   } else if (isWrite) {
998ece8a530Spatrick     rank |= RF_WRITE;
999ece8a530Spatrick   } else if (sec->type == SHT_PROGBITS) {
1000ece8a530Spatrick     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
1001ece8a530Spatrick     // .eh_frame) closer to .text. They likely contain PC or GOT relative
1002ece8a530Spatrick     // relocations and there could be relocation overflow if other huge sections
1003ece8a530Spatrick     // (.dynstr .dynsym) were placed in between.
1004ece8a530Spatrick     rank |= RF_RODATA;
1005ece8a530Spatrick   }
1006ece8a530Spatrick 
1007ece8a530Spatrick   // Place RelRo sections first. After considering SHT_NOBITS below, the
1008ece8a530Spatrick   // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
1009ece8a530Spatrick   // where | marks where page alignment happens. An alternative ordering is
1010ece8a530Spatrick   // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
1011ece8a530Spatrick   // waste more bytes due to 2 alignment places.
1012ece8a530Spatrick   if (!isRelroSection(sec))
1013ece8a530Spatrick     rank |= RF_NOT_RELRO;
1014ece8a530Spatrick 
1015ece8a530Spatrick   // If we got here we know that both A and B are in the same PT_LOAD.
1016ece8a530Spatrick 
1017ece8a530Spatrick   // The TLS initialization block needs to be a single contiguous block in a R/W
1018ece8a530Spatrick   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
1019ece8a530Spatrick   // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
1020ece8a530Spatrick   // after PROGBITS.
1021ece8a530Spatrick   if (!(sec->flags & SHF_TLS))
1022ece8a530Spatrick     rank |= RF_NOT_TLS;
1023ece8a530Spatrick 
1024ece8a530Spatrick   // Within TLS sections, or within other RelRo sections, or within non-RelRo
1025ece8a530Spatrick   // sections, place non-NOBITS sections first.
1026ece8a530Spatrick   if (sec->type == SHT_NOBITS)
1027ece8a530Spatrick     rank |= RF_BSS;
1028ece8a530Spatrick 
1029ece8a530Spatrick   // Some architectures have additional ordering restrictions for sections
1030ece8a530Spatrick   // within the same PT_LOAD.
1031ece8a530Spatrick   if (config->emachine == EM_PPC64) {
1032ece8a530Spatrick     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
1033ece8a530Spatrick     // that we would like to make sure appear is a specific order to maximize
1034ece8a530Spatrick     // their coverage by a single signed 16-bit offset from the TOC base
1035ece8a530Spatrick     // pointer. Conversely, the special .tocbss section should be first among
1036ece8a530Spatrick     // all SHT_NOBITS sections. This will put it next to the loaded special
1037ece8a530Spatrick     // PPC64 sections (and, thus, within reach of the TOC base pointer).
1038ece8a530Spatrick     StringRef name = sec->name;
1039ece8a530Spatrick     if (name != ".tocbss")
1040ece8a530Spatrick       rank |= RF_PPC_NOT_TOCBSS;
1041ece8a530Spatrick 
1042ece8a530Spatrick     if (name == ".toc1")
1043ece8a530Spatrick       rank |= RF_PPC_TOCL;
1044ece8a530Spatrick 
1045ece8a530Spatrick     if (name == ".toc")
1046ece8a530Spatrick       rank |= RF_PPC_TOC;
1047ece8a530Spatrick 
1048ece8a530Spatrick     if (name == ".got")
1049ece8a530Spatrick       rank |= RF_PPC_GOT;
1050ece8a530Spatrick 
1051ece8a530Spatrick     if (name == ".branch_lt")
1052ece8a530Spatrick       rank |= RF_PPC_BRANCH_LT;
1053ece8a530Spatrick   }
1054ece8a530Spatrick 
1055ece8a530Spatrick   if (config->emachine == EM_MIPS) {
1056ece8a530Spatrick     // All sections with SHF_MIPS_GPREL flag should be grouped together
1057ece8a530Spatrick     // because data in these sections is addressable with a gp relative address.
1058ece8a530Spatrick     if (sec->flags & SHF_MIPS_GPREL)
1059ece8a530Spatrick       rank |= RF_MIPS_GPREL;
1060ece8a530Spatrick 
1061ece8a530Spatrick     if (sec->name != ".got")
1062ece8a530Spatrick       rank |= RF_MIPS_NOT_GOT;
1063ece8a530Spatrick   }
1064ece8a530Spatrick 
1065ece8a530Spatrick   return rank;
1066ece8a530Spatrick }
1067ece8a530Spatrick 
1068ece8a530Spatrick static bool compareSections(const BaseCommand *aCmd, const BaseCommand *bCmd) {
1069ece8a530Spatrick   const OutputSection *a = cast<OutputSection>(aCmd);
1070ece8a530Spatrick   const OutputSection *b = cast<OutputSection>(bCmd);
1071ece8a530Spatrick 
1072ece8a530Spatrick   if (a->sortRank != b->sortRank)
1073ece8a530Spatrick     return a->sortRank < b->sortRank;
1074ece8a530Spatrick 
1075ece8a530Spatrick   if (!(a->sortRank & RF_NOT_ADDR_SET))
1076ece8a530Spatrick     return config->sectionStartMap.lookup(a->name) <
1077ece8a530Spatrick            config->sectionStartMap.lookup(b->name);
1078ece8a530Spatrick   return false;
1079ece8a530Spatrick }
1080ece8a530Spatrick 
1081ece8a530Spatrick void PhdrEntry::add(OutputSection *sec) {
1082ece8a530Spatrick   lastSec = sec;
1083ece8a530Spatrick   if (!firstSec)
1084ece8a530Spatrick     firstSec = sec;
1085ece8a530Spatrick   p_align = std::max(p_align, sec->alignment);
1086ece8a530Spatrick   if (p_type == PT_LOAD)
1087ece8a530Spatrick     sec->ptLoad = this;
1088ece8a530Spatrick }
1089ece8a530Spatrick 
1090ece8a530Spatrick // The beginning and the ending of .rel[a].plt section are marked
1091ece8a530Spatrick // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1092ece8a530Spatrick // executable. The runtime needs these symbols in order to resolve
1093ece8a530Spatrick // all IRELATIVE relocs on startup. For dynamic executables, we don't
1094ece8a530Spatrick // need these symbols, since IRELATIVE relocs are resolved through GOT
1095ece8a530Spatrick // and PLT. For details, see http://www.airs.com/blog/archives/403.
1096ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1097*a0747c9fSpatrick   if (config->relocatable || config->isPic)
1098ece8a530Spatrick     return;
1099ece8a530Spatrick 
1100ece8a530Spatrick   // By default, __rela_iplt_{start,end} belong to a dummy section 0
1101ece8a530Spatrick   // because .rela.plt might be empty and thus removed from output.
1102ece8a530Spatrick   // We'll override Out::elfHeader with In.relaIplt later when we are
1103ece8a530Spatrick   // sure that .rela.plt exists in output.
1104ece8a530Spatrick   ElfSym::relaIpltStart = addOptionalRegular(
1105ece8a530Spatrick       config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
1106ece8a530Spatrick       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1107ece8a530Spatrick 
1108ece8a530Spatrick   ElfSym::relaIpltEnd = addOptionalRegular(
1109ece8a530Spatrick       config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1110ece8a530Spatrick       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1111ece8a530Spatrick }
1112ece8a530Spatrick 
1113ece8a530Spatrick template <class ELFT>
1114ece8a530Spatrick void Writer<ELFT>::forEachRelSec(
1115ece8a530Spatrick     llvm::function_ref<void(InputSectionBase &)> fn) {
1116ece8a530Spatrick   // Scan all relocations. Each relocation goes through a series
1117ece8a530Spatrick   // of tests to determine if it needs special treatment, such as
1118ece8a530Spatrick   // creating GOT, PLT, copy relocations, etc.
1119ece8a530Spatrick   // Note that relocations for non-alloc sections are directly
1120ece8a530Spatrick   // processed by InputSection::relocateNonAlloc.
1121ece8a530Spatrick   for (InputSectionBase *isec : inputSections)
1122ece8a530Spatrick     if (isec->isLive() && isa<InputSection>(isec) && (isec->flags & SHF_ALLOC))
1123ece8a530Spatrick       fn(*isec);
1124ece8a530Spatrick   for (Partition &part : partitions) {
1125ece8a530Spatrick     for (EhInputSection *es : part.ehFrame->sections)
1126ece8a530Spatrick       fn(*es);
1127ece8a530Spatrick     if (part.armExidx && part.armExidx->isLive())
1128ece8a530Spatrick       for (InputSection *ex : part.armExidx->exidxSections)
1129ece8a530Spatrick         fn(*ex);
1130ece8a530Spatrick   }
1131ece8a530Spatrick }
1132ece8a530Spatrick 
1133ece8a530Spatrick // This function generates assignments for predefined symbols (e.g. _end or
1134ece8a530Spatrick // _etext) and inserts them into the commands sequence to be processed at the
1135ece8a530Spatrick // appropriate time. This ensures that the value is going to be correct by the
1136ece8a530Spatrick // time any references to these symbols are processed and is equivalent to
1137ece8a530Spatrick // defining these symbols explicitly in the linker script.
1138ece8a530Spatrick template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1139ece8a530Spatrick   if (ElfSym::globalOffsetTable) {
1140ece8a530Spatrick     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1141ece8a530Spatrick     // to the start of the .got or .got.plt section.
1142ece8a530Spatrick     InputSection *gotSection = in.gotPlt;
1143ece8a530Spatrick     if (!target->gotBaseSymInGotPlt)
1144ece8a530Spatrick       gotSection = in.mipsGot ? cast<InputSection>(in.mipsGot)
1145ece8a530Spatrick                               : cast<InputSection>(in.got);
1146ece8a530Spatrick     ElfSym::globalOffsetTable->section = gotSection;
1147ece8a530Spatrick   }
1148ece8a530Spatrick 
1149ece8a530Spatrick   // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
1150ece8a530Spatrick   if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
1151ece8a530Spatrick     ElfSym::relaIpltStart->section = in.relaIplt;
1152ece8a530Spatrick     ElfSym::relaIpltEnd->section = in.relaIplt;
1153ece8a530Spatrick     ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1154ece8a530Spatrick   }
1155ece8a530Spatrick 
1156ece8a530Spatrick   PhdrEntry *last = nullptr;
1157ece8a530Spatrick   PhdrEntry *lastRO = nullptr;
1158ece8a530Spatrick 
1159ece8a530Spatrick   for (Partition &part : partitions) {
1160ece8a530Spatrick     for (PhdrEntry *p : part.phdrs) {
1161ece8a530Spatrick       if (p->p_type != PT_LOAD)
1162ece8a530Spatrick         continue;
1163ece8a530Spatrick       last = p;
1164ece8a530Spatrick       if (!(p->p_flags & PF_W))
1165ece8a530Spatrick         lastRO = p;
1166ece8a530Spatrick     }
1167ece8a530Spatrick   }
1168ece8a530Spatrick 
1169ece8a530Spatrick   if (lastRO) {
1170ece8a530Spatrick     // _etext is the first location after the last read-only loadable segment.
1171ece8a530Spatrick     if (ElfSym::etext1)
1172ece8a530Spatrick       ElfSym::etext1->section = lastRO->lastSec;
1173ece8a530Spatrick     if (ElfSym::etext2)
1174ece8a530Spatrick       ElfSym::etext2->section = lastRO->lastSec;
1175ece8a530Spatrick   }
1176ece8a530Spatrick 
1177ece8a530Spatrick   if (last) {
1178ece8a530Spatrick     // _edata points to the end of the last mapped initialized section.
1179ece8a530Spatrick     OutputSection *edata = nullptr;
1180ece8a530Spatrick     for (OutputSection *os : outputSections) {
1181ece8a530Spatrick       if (os->type != SHT_NOBITS)
1182ece8a530Spatrick         edata = os;
1183ece8a530Spatrick       if (os == last->lastSec)
1184ece8a530Spatrick         break;
1185ece8a530Spatrick     }
1186ece8a530Spatrick 
1187ece8a530Spatrick     if (ElfSym::edata1)
1188ece8a530Spatrick       ElfSym::edata1->section = edata;
1189ece8a530Spatrick     if (ElfSym::edata2)
1190ece8a530Spatrick       ElfSym::edata2->section = edata;
1191ece8a530Spatrick 
1192ece8a530Spatrick     // _end is the first location after the uninitialized data region.
1193ece8a530Spatrick     if (ElfSym::end1)
1194ece8a530Spatrick       ElfSym::end1->section = last->lastSec;
1195ece8a530Spatrick     if (ElfSym::end2)
1196ece8a530Spatrick       ElfSym::end2->section = last->lastSec;
1197ece8a530Spatrick   }
1198ece8a530Spatrick 
1199ece8a530Spatrick   if (ElfSym::bss)
1200ece8a530Spatrick     ElfSym::bss->section = findSection(".bss");
1201ece8a530Spatrick 
1202adae0cfdSpatrick   if (ElfSym::data)
1203adae0cfdSpatrick     ElfSym::data->section = findSection(".data");
1204adae0cfdSpatrick 
1205ece8a530Spatrick   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1206ece8a530Spatrick   // be equal to the _gp symbol's value.
1207ece8a530Spatrick   if (ElfSym::mipsGp) {
1208ece8a530Spatrick     // Find GP-relative section with the lowest address
1209ece8a530Spatrick     // and use this address to calculate default _gp value.
1210ece8a530Spatrick     for (OutputSection *os : outputSections) {
1211ece8a530Spatrick       if (os->flags & SHF_MIPS_GPREL) {
1212ece8a530Spatrick         ElfSym::mipsGp->section = os;
1213ece8a530Spatrick         ElfSym::mipsGp->value = 0x7ff0;
1214ece8a530Spatrick         break;
1215ece8a530Spatrick       }
1216ece8a530Spatrick     }
1217ece8a530Spatrick   }
1218ece8a530Spatrick }
1219ece8a530Spatrick 
1220ece8a530Spatrick // We want to find how similar two ranks are.
1221ece8a530Spatrick // The more branches in getSectionRank that match, the more similar they are.
1222ece8a530Spatrick // Since each branch corresponds to a bit flag, we can just use
1223ece8a530Spatrick // countLeadingZeros.
1224ece8a530Spatrick static int getRankProximityAux(OutputSection *a, OutputSection *b) {
1225ece8a530Spatrick   return countLeadingZeros(a->sortRank ^ b->sortRank);
1226ece8a530Spatrick }
1227ece8a530Spatrick 
1228ece8a530Spatrick static int getRankProximity(OutputSection *a, BaseCommand *b) {
1229ece8a530Spatrick   auto *sec = dyn_cast<OutputSection>(b);
1230ece8a530Spatrick   return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1;
1231ece8a530Spatrick }
1232ece8a530Spatrick 
1233ece8a530Spatrick // When placing orphan sections, we want to place them after symbol assignments
1234ece8a530Spatrick // so that an orphan after
1235ece8a530Spatrick //   begin_foo = .;
1236ece8a530Spatrick //   foo : { *(foo) }
1237ece8a530Spatrick //   end_foo = .;
1238ece8a530Spatrick // doesn't break the intended meaning of the begin/end symbols.
1239ece8a530Spatrick // We don't want to go over sections since findOrphanPos is the
1240ece8a530Spatrick // one in charge of deciding the order of the sections.
1241ece8a530Spatrick // We don't want to go over changes to '.', since doing so in
1242ece8a530Spatrick //  rx_sec : { *(rx_sec) }
1243ece8a530Spatrick //  . = ALIGN(0x1000);
1244ece8a530Spatrick //  /* The RW PT_LOAD starts here*/
1245ece8a530Spatrick //  rw_sec : { *(rw_sec) }
1246ece8a530Spatrick // would mean that the RW PT_LOAD would become unaligned.
1247ece8a530Spatrick static bool shouldSkip(BaseCommand *cmd) {
1248ece8a530Spatrick   if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1249ece8a530Spatrick     return assign->name != ".";
1250ece8a530Spatrick   return false;
1251ece8a530Spatrick }
1252ece8a530Spatrick 
1253ece8a530Spatrick // We want to place orphan sections so that they share as much
1254ece8a530Spatrick // characteristics with their neighbors as possible. For example, if
1255ece8a530Spatrick // both are rw, or both are tls.
1256ece8a530Spatrick static std::vector<BaseCommand *>::iterator
1257ece8a530Spatrick findOrphanPos(std::vector<BaseCommand *>::iterator b,
1258ece8a530Spatrick               std::vector<BaseCommand *>::iterator e) {
1259ece8a530Spatrick   OutputSection *sec = cast<OutputSection>(*e);
1260ece8a530Spatrick 
1261ece8a530Spatrick   // Find the first element that has as close a rank as possible.
1262ece8a530Spatrick   auto i = std::max_element(b, e, [=](BaseCommand *a, BaseCommand *b) {
1263ece8a530Spatrick     return getRankProximity(sec, a) < getRankProximity(sec, b);
1264ece8a530Spatrick   });
1265ece8a530Spatrick   if (i == e)
1266ece8a530Spatrick     return e;
1267ece8a530Spatrick 
1268ece8a530Spatrick   // Consider all existing sections with the same proximity.
1269ece8a530Spatrick   int proximity = getRankProximity(sec, *i);
1270ece8a530Spatrick   for (; i != e; ++i) {
1271ece8a530Spatrick     auto *curSec = dyn_cast<OutputSection>(*i);
1272ece8a530Spatrick     if (!curSec || !curSec->hasInputSections)
1273ece8a530Spatrick       continue;
1274ece8a530Spatrick     if (getRankProximity(sec, curSec) != proximity ||
1275ece8a530Spatrick         sec->sortRank < curSec->sortRank)
1276ece8a530Spatrick       break;
1277ece8a530Spatrick   }
1278ece8a530Spatrick 
1279ece8a530Spatrick   auto isOutputSecWithInputSections = [](BaseCommand *cmd) {
1280ece8a530Spatrick     auto *os = dyn_cast<OutputSection>(cmd);
1281ece8a530Spatrick     return os && os->hasInputSections;
1282ece8a530Spatrick   };
1283ece8a530Spatrick   auto j = std::find_if(llvm::make_reverse_iterator(i),
1284ece8a530Spatrick                         llvm::make_reverse_iterator(b),
1285ece8a530Spatrick                         isOutputSecWithInputSections);
1286ece8a530Spatrick   i = j.base();
1287ece8a530Spatrick 
1288ece8a530Spatrick   // As a special case, if the orphan section is the last section, put
1289ece8a530Spatrick   // it at the very end, past any other commands.
1290ece8a530Spatrick   // This matches bfd's behavior and is convenient when the linker script fully
1291ece8a530Spatrick   // specifies the start of the file, but doesn't care about the end (the non
1292ece8a530Spatrick   // alloc sections for example).
1293ece8a530Spatrick   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1294ece8a530Spatrick   if (nextSec == e)
1295ece8a530Spatrick     return e;
1296ece8a530Spatrick 
1297ece8a530Spatrick   while (i != e && shouldSkip(*i))
1298ece8a530Spatrick     ++i;
1299ece8a530Spatrick   return i;
1300ece8a530Spatrick }
1301ece8a530Spatrick 
1302bb684c34Spatrick // Adds random priorities to sections not already in the map.
1303bb684c34Spatrick static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
1304*a0747c9fSpatrick   if (config->shuffleSections.empty())
1305bb684c34Spatrick     return;
1306bb684c34Spatrick 
1307*a0747c9fSpatrick   std::vector<InputSectionBase *> matched, sections = inputSections;
1308*a0747c9fSpatrick   matched.reserve(sections.size());
1309*a0747c9fSpatrick   for (const auto &patAndSeed : config->shuffleSections) {
1310*a0747c9fSpatrick     matched.clear();
1311*a0747c9fSpatrick     for (InputSectionBase *sec : sections)
1312*a0747c9fSpatrick       if (patAndSeed.first.match(sec->name))
1313*a0747c9fSpatrick         matched.push_back(sec);
1314*a0747c9fSpatrick     const uint32_t seed = patAndSeed.second;
1315*a0747c9fSpatrick     if (seed == UINT32_MAX) {
1316*a0747c9fSpatrick       // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1317*a0747c9fSpatrick       // section order is stable even if the number of sections changes. This is
1318*a0747c9fSpatrick       // useful to catch issues like static initialization order fiasco
1319*a0747c9fSpatrick       // reliably.
1320*a0747c9fSpatrick       std::reverse(matched.begin(), matched.end());
1321*a0747c9fSpatrick     } else {
1322*a0747c9fSpatrick       std::mt19937 g(seed ? seed : std::random_device()());
1323*a0747c9fSpatrick       llvm::shuffle(matched.begin(), matched.end(), g);
1324*a0747c9fSpatrick     }
1325*a0747c9fSpatrick     size_t i = 0;
1326*a0747c9fSpatrick     for (InputSectionBase *&sec : sections)
1327*a0747c9fSpatrick       if (patAndSeed.first.match(sec->name))
1328*a0747c9fSpatrick         sec = matched[i++];
1329*a0747c9fSpatrick   }
1330*a0747c9fSpatrick 
1331bb684c34Spatrick   // Existing priorities are < 0, so use priorities >= 0 for the missing
1332bb684c34Spatrick   // sections.
1333*a0747c9fSpatrick   int prio = 0;
1334*a0747c9fSpatrick   for (InputSectionBase *sec : sections) {
1335*a0747c9fSpatrick     if (order.try_emplace(sec, prio).second)
1336*a0747c9fSpatrick       ++prio;
1337bb684c34Spatrick   }
1338bb684c34Spatrick }
1339bb684c34Spatrick 
1340ece8a530Spatrick // Builds section order for handling --symbol-ordering-file.
1341ece8a530Spatrick static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1342ece8a530Spatrick   DenseMap<const InputSectionBase *, int> sectionOrder;
1343ece8a530Spatrick   // Use the rarely used option -call-graph-ordering-file to sort sections.
1344ece8a530Spatrick   if (!config->callGraphProfile.empty())
1345ece8a530Spatrick     return computeCallGraphProfileOrder();
1346ece8a530Spatrick 
1347ece8a530Spatrick   if (config->symbolOrderingFile.empty())
1348ece8a530Spatrick     return sectionOrder;
1349ece8a530Spatrick 
1350ece8a530Spatrick   struct SymbolOrderEntry {
1351ece8a530Spatrick     int priority;
1352ece8a530Spatrick     bool present;
1353ece8a530Spatrick   };
1354ece8a530Spatrick 
1355ece8a530Spatrick   // Build a map from symbols to their priorities. Symbols that didn't
1356ece8a530Spatrick   // appear in the symbol ordering file have the lowest priority 0.
1357ece8a530Spatrick   // All explicitly mentioned symbols have negative (higher) priorities.
1358ece8a530Spatrick   DenseMap<StringRef, SymbolOrderEntry> symbolOrder;
1359ece8a530Spatrick   int priority = -config->symbolOrderingFile.size();
1360ece8a530Spatrick   for (StringRef s : config->symbolOrderingFile)
1361ece8a530Spatrick     symbolOrder.insert({s, {priority++, false}});
1362ece8a530Spatrick 
1363ece8a530Spatrick   // Build a map from sections to their priorities.
1364ece8a530Spatrick   auto addSym = [&](Symbol &sym) {
1365ece8a530Spatrick     auto it = symbolOrder.find(sym.getName());
1366ece8a530Spatrick     if (it == symbolOrder.end())
1367ece8a530Spatrick       return;
1368ece8a530Spatrick     SymbolOrderEntry &ent = it->second;
1369ece8a530Spatrick     ent.present = true;
1370ece8a530Spatrick 
1371ece8a530Spatrick     maybeWarnUnorderableSymbol(&sym);
1372ece8a530Spatrick 
1373ece8a530Spatrick     if (auto *d = dyn_cast<Defined>(&sym)) {
1374ece8a530Spatrick       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1375ece8a530Spatrick         int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)];
1376ece8a530Spatrick         priority = std::min(priority, ent.priority);
1377ece8a530Spatrick       }
1378ece8a530Spatrick     }
1379ece8a530Spatrick   };
1380ece8a530Spatrick 
1381ece8a530Spatrick   // We want both global and local symbols. We get the global ones from the
1382ece8a530Spatrick   // symbol table and iterate the object files for the local ones.
1383ece8a530Spatrick   for (Symbol *sym : symtab->symbols())
1384ece8a530Spatrick     if (!sym->isLazy())
1385ece8a530Spatrick       addSym(*sym);
1386ece8a530Spatrick 
1387ece8a530Spatrick   for (InputFile *file : objectFiles)
1388*a0747c9fSpatrick     for (Symbol *sym : file->getSymbols()) {
1389*a0747c9fSpatrick       if (!sym->isLocal())
1390*a0747c9fSpatrick         break;
1391ece8a530Spatrick       addSym(*sym);
1392*a0747c9fSpatrick     }
1393ece8a530Spatrick 
1394ece8a530Spatrick   if (config->warnSymbolOrdering)
1395ece8a530Spatrick     for (auto orderEntry : symbolOrder)
1396ece8a530Spatrick       if (!orderEntry.second.present)
1397ece8a530Spatrick         warn("symbol ordering file: no such symbol: " + orderEntry.first);
1398ece8a530Spatrick 
1399ece8a530Spatrick   return sectionOrder;
1400ece8a530Spatrick }
1401ece8a530Spatrick 
1402ece8a530Spatrick // Sorts the sections in ISD according to the provided section order.
1403ece8a530Spatrick static void
1404ece8a530Spatrick sortISDBySectionOrder(InputSectionDescription *isd,
1405ece8a530Spatrick                       const DenseMap<const InputSectionBase *, int> &order) {
1406ece8a530Spatrick   std::vector<InputSection *> unorderedSections;
1407ece8a530Spatrick   std::vector<std::pair<InputSection *, int>> orderedSections;
1408ece8a530Spatrick   uint64_t unorderedSize = 0;
1409ece8a530Spatrick 
1410ece8a530Spatrick   for (InputSection *isec : isd->sections) {
1411ece8a530Spatrick     auto i = order.find(isec);
1412ece8a530Spatrick     if (i == order.end()) {
1413ece8a530Spatrick       unorderedSections.push_back(isec);
1414ece8a530Spatrick       unorderedSize += isec->getSize();
1415ece8a530Spatrick       continue;
1416ece8a530Spatrick     }
1417ece8a530Spatrick     orderedSections.push_back({isec, i->second});
1418ece8a530Spatrick   }
1419ece8a530Spatrick   llvm::sort(orderedSections, llvm::less_second());
1420ece8a530Spatrick 
1421ece8a530Spatrick   // Find an insertion point for the ordered section list in the unordered
1422ece8a530Spatrick   // section list. On targets with limited-range branches, this is the mid-point
1423ece8a530Spatrick   // of the unordered section list. This decreases the likelihood that a range
1424ece8a530Spatrick   // extension thunk will be needed to enter or exit the ordered region. If the
1425ece8a530Spatrick   // ordered section list is a list of hot functions, we can generally expect
1426ece8a530Spatrick   // the ordered functions to be called more often than the unordered functions,
1427ece8a530Spatrick   // making it more likely that any particular call will be within range, and
1428ece8a530Spatrick   // therefore reducing the number of thunks required.
1429ece8a530Spatrick   //
1430ece8a530Spatrick   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1431ece8a530Spatrick   // If the layout is:
1432ece8a530Spatrick   //
1433ece8a530Spatrick   // 8MB hot
1434ece8a530Spatrick   // 32MB cold
1435ece8a530Spatrick   //
1436ece8a530Spatrick   // only the first 8-16MB of the cold code (depending on which hot function it
1437ece8a530Spatrick   // is actually calling) can call the hot code without a range extension thunk.
1438ece8a530Spatrick   // However, if we use this layout:
1439ece8a530Spatrick   //
1440ece8a530Spatrick   // 16MB cold
1441ece8a530Spatrick   // 8MB hot
1442ece8a530Spatrick   // 16MB cold
1443ece8a530Spatrick   //
1444ece8a530Spatrick   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1445ece8a530Spatrick   // of the second block of cold code can call the hot code without a thunk. So
1446ece8a530Spatrick   // we effectively double the amount of code that could potentially call into
1447ece8a530Spatrick   // the hot code without a thunk.
1448ece8a530Spatrick   size_t insPt = 0;
1449ece8a530Spatrick   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1450ece8a530Spatrick     uint64_t unorderedPos = 0;
1451ece8a530Spatrick     for (; insPt != unorderedSections.size(); ++insPt) {
1452ece8a530Spatrick       unorderedPos += unorderedSections[insPt]->getSize();
1453ece8a530Spatrick       if (unorderedPos > unorderedSize / 2)
1454ece8a530Spatrick         break;
1455ece8a530Spatrick     }
1456ece8a530Spatrick   }
1457ece8a530Spatrick 
1458ece8a530Spatrick   isd->sections.clear();
1459ece8a530Spatrick   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1460ece8a530Spatrick     isd->sections.push_back(isec);
1461ece8a530Spatrick   for (std::pair<InputSection *, int> p : orderedSections)
1462ece8a530Spatrick     isd->sections.push_back(p.first);
1463ece8a530Spatrick   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1464ece8a530Spatrick     isd->sections.push_back(isec);
1465ece8a530Spatrick }
1466ece8a530Spatrick 
1467ece8a530Spatrick static void sortSection(OutputSection *sec,
1468ece8a530Spatrick                         const DenseMap<const InputSectionBase *, int> &order) {
1469ece8a530Spatrick   StringRef name = sec->name;
1470ece8a530Spatrick 
1471bb684c34Spatrick   // Never sort these.
1472bb684c34Spatrick   if (name == ".init" || name == ".fini")
1473bb684c34Spatrick     return;
1474bb684c34Spatrick 
1475*a0747c9fSpatrick   // IRelative relocations that usually live in the .rel[a].dyn section should
1476*a0747c9fSpatrick   // be processed last by the dynamic loader. To achieve that we add synthetic
1477*a0747c9fSpatrick   // sections in the required order from the beginning so that the in.relaIplt
1478*a0747c9fSpatrick   // section is placed last in an output section. Here we just do not apply
1479*a0747c9fSpatrick   // sorting for an output section which holds the in.relaIplt section.
1480*a0747c9fSpatrick   if (in.relaIplt->getParent() == sec)
1481*a0747c9fSpatrick     return;
1482*a0747c9fSpatrick 
1483bb684c34Spatrick   // Sort input sections by priority using the list provided by
1484bb684c34Spatrick   // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1485bb684c34Spatrick   // digit radix sort. The sections may be sorted stably again by a more
1486bb684c34Spatrick   // significant key.
1487bb684c34Spatrick   if (!order.empty())
1488bb684c34Spatrick     for (BaseCommand *b : sec->sectionCommands)
1489bb684c34Spatrick       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1490bb684c34Spatrick         sortISDBySectionOrder(isd, order);
1491bb684c34Spatrick 
1492ece8a530Spatrick   // Sort input sections by section name suffixes for
1493ece8a530Spatrick   // __attribute__((init_priority(N))).
1494ece8a530Spatrick   if (name == ".init_array" || name == ".fini_array") {
1495ece8a530Spatrick     if (!script->hasSectionsCommand)
1496ece8a530Spatrick       sec->sortInitFini();
1497ece8a530Spatrick     return;
1498ece8a530Spatrick   }
1499ece8a530Spatrick 
1500ece8a530Spatrick   // Sort input sections by the special rule for .ctors and .dtors.
1501ece8a530Spatrick   if (name == ".ctors" || name == ".dtors") {
1502ece8a530Spatrick     if (!script->hasSectionsCommand)
1503ece8a530Spatrick       sec->sortCtorsDtors();
1504ece8a530Spatrick     return;
1505ece8a530Spatrick   }
1506ece8a530Spatrick 
1507ece8a530Spatrick   // .toc is allocated just after .got and is accessed using GOT-relative
1508ece8a530Spatrick   // relocations. Object files compiled with small code model have an
1509ece8a530Spatrick   // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1510ece8a530Spatrick   // To reduce the risk of relocation overflow, .toc contents are sorted so that
1511ece8a530Spatrick   // sections having smaller relocation offsets are at beginning of .toc
1512ece8a530Spatrick   if (config->emachine == EM_PPC64 && name == ".toc") {
1513ece8a530Spatrick     if (script->hasSectionsCommand)
1514ece8a530Spatrick       return;
1515ece8a530Spatrick     assert(sec->sectionCommands.size() == 1);
1516ece8a530Spatrick     auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]);
1517ece8a530Spatrick     llvm::stable_sort(isd->sections,
1518ece8a530Spatrick                       [](const InputSection *a, const InputSection *b) -> bool {
1519ece8a530Spatrick                         return a->file->ppc64SmallCodeModelTocRelocs &&
1520ece8a530Spatrick                                !b->file->ppc64SmallCodeModelTocRelocs;
1521ece8a530Spatrick                       });
1522ece8a530Spatrick     return;
1523ece8a530Spatrick   }
1524ece8a530Spatrick }
1525ece8a530Spatrick 
1526ece8a530Spatrick // If no layout was provided by linker script, we want to apply default
1527ece8a530Spatrick // sorting for special input sections. This also handles --symbol-ordering-file.
1528ece8a530Spatrick template <class ELFT> void Writer<ELFT>::sortInputSections() {
1529ece8a530Spatrick   // Build the order once since it is expensive.
1530ece8a530Spatrick   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1531bb684c34Spatrick   maybeShuffle(order);
1532ece8a530Spatrick   for (BaseCommand *base : script->sectionCommands)
1533ece8a530Spatrick     if (auto *sec = dyn_cast<OutputSection>(base))
1534ece8a530Spatrick       sortSection(sec, order);
1535ece8a530Spatrick }
1536ece8a530Spatrick 
1537ece8a530Spatrick template <class ELFT> void Writer<ELFT>::sortSections() {
1538*a0747c9fSpatrick   llvm::TimeTraceScope timeScope("Sort sections");
1539ece8a530Spatrick   script->adjustSectionsBeforeSorting();
1540ece8a530Spatrick 
1541ece8a530Spatrick   // Don't sort if using -r. It is not necessary and we want to preserve the
1542ece8a530Spatrick   // relative order for SHF_LINK_ORDER sections.
1543ece8a530Spatrick   if (config->relocatable)
1544ece8a530Spatrick     return;
1545ece8a530Spatrick 
1546ece8a530Spatrick   sortInputSections();
1547ece8a530Spatrick 
1548ece8a530Spatrick   for (BaseCommand *base : script->sectionCommands) {
1549ece8a530Spatrick     auto *os = dyn_cast<OutputSection>(base);
1550ece8a530Spatrick     if (!os)
1551ece8a530Spatrick       continue;
1552ece8a530Spatrick     os->sortRank = getSectionRank(os);
1553ece8a530Spatrick 
1554ece8a530Spatrick     // We want to assign rude approximation values to outSecOff fields
1555ece8a530Spatrick     // to know the relative order of the input sections. We use it for
1556ece8a530Spatrick     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1557ece8a530Spatrick     uint64_t i = 0;
1558ece8a530Spatrick     for (InputSection *sec : getInputSections(os))
1559ece8a530Spatrick       sec->outSecOff = i++;
1560ece8a530Spatrick   }
1561ece8a530Spatrick 
1562ece8a530Spatrick   if (!script->hasSectionsCommand) {
1563ece8a530Spatrick     // We know that all the OutputSections are contiguous in this case.
1564ece8a530Spatrick     auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); };
1565ece8a530Spatrick     std::stable_sort(
1566ece8a530Spatrick         llvm::find_if(script->sectionCommands, isSection),
1567ece8a530Spatrick         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1568ece8a530Spatrick         compareSections);
1569bb684c34Spatrick 
1570bb684c34Spatrick     // Process INSERT commands. From this point onwards the order of
1571bb684c34Spatrick     // script->sectionCommands is fixed.
1572bb684c34Spatrick     script->processInsertCommands();
1573ece8a530Spatrick     return;
1574ece8a530Spatrick   }
1575ece8a530Spatrick 
1576bb684c34Spatrick   script->processInsertCommands();
1577bb684c34Spatrick 
1578ece8a530Spatrick   // Orphan sections are sections present in the input files which are
1579ece8a530Spatrick   // not explicitly placed into the output file by the linker script.
1580ece8a530Spatrick   //
1581ece8a530Spatrick   // The sections in the linker script are already in the correct
1582ece8a530Spatrick   // order. We have to figuere out where to insert the orphan
1583ece8a530Spatrick   // sections.
1584ece8a530Spatrick   //
1585ece8a530Spatrick   // The order of the sections in the script is arbitrary and may not agree with
1586ece8a530Spatrick   // compareSections. This means that we cannot easily define a strict weak
1587ece8a530Spatrick   // ordering. To see why, consider a comparison of a section in the script and
1588ece8a530Spatrick   // one not in the script. We have a two simple options:
1589ece8a530Spatrick   // * Make them equivalent (a is not less than b, and b is not less than a).
1590ece8a530Spatrick   //   The problem is then that equivalence has to be transitive and we can
1591ece8a530Spatrick   //   have sections a, b and c with only b in a script and a less than c
1592ece8a530Spatrick   //   which breaks this property.
1593ece8a530Spatrick   // * Use compareSectionsNonScript. Given that the script order doesn't have
1594ece8a530Spatrick   //   to match, we can end up with sections a, b, c, d where b and c are in the
1595ece8a530Spatrick   //   script and c is compareSectionsNonScript less than b. In which case d
1596ece8a530Spatrick   //   can be equivalent to c, a to b and d < a. As a concrete example:
1597ece8a530Spatrick   //   .a (rx) # not in script
1598ece8a530Spatrick   //   .b (rx) # in script
1599ece8a530Spatrick   //   .c (ro) # in script
1600ece8a530Spatrick   //   .d (ro) # not in script
1601ece8a530Spatrick   //
1602ece8a530Spatrick   // The way we define an order then is:
1603ece8a530Spatrick   // *  Sort only the orphan sections. They are in the end right now.
1604ece8a530Spatrick   // *  Move each orphan section to its preferred position. We try
1605ece8a530Spatrick   //    to put each section in the last position where it can share
1606ece8a530Spatrick   //    a PT_LOAD.
1607ece8a530Spatrick   //
1608ece8a530Spatrick   // There is some ambiguity as to where exactly a new entry should be
1609ece8a530Spatrick   // inserted, because Commands contains not only output section
1610ece8a530Spatrick   // commands but also other types of commands such as symbol assignment
1611ece8a530Spatrick   // expressions. There's no correct answer here due to the lack of the
1612ece8a530Spatrick   // formal specification of the linker script. We use heuristics to
1613ece8a530Spatrick   // determine whether a new output command should be added before or
1614ece8a530Spatrick   // after another commands. For the details, look at shouldSkip
1615ece8a530Spatrick   // function.
1616ece8a530Spatrick 
1617ece8a530Spatrick   auto i = script->sectionCommands.begin();
1618ece8a530Spatrick   auto e = script->sectionCommands.end();
1619ece8a530Spatrick   auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) {
1620ece8a530Spatrick     if (auto *sec = dyn_cast<OutputSection>(base))
1621ece8a530Spatrick       return sec->sectionIndex == UINT32_MAX;
1622ece8a530Spatrick     return false;
1623ece8a530Spatrick   });
1624ece8a530Spatrick 
1625ece8a530Spatrick   // Sort the orphan sections.
1626ece8a530Spatrick   std::stable_sort(nonScriptI, e, compareSections);
1627ece8a530Spatrick 
1628ece8a530Spatrick   // As a horrible special case, skip the first . assignment if it is before any
1629ece8a530Spatrick   // section. We do this because it is common to set a load address by starting
1630ece8a530Spatrick   // the script with ". = 0xabcd" and the expectation is that every section is
1631ece8a530Spatrick   // after that.
1632ece8a530Spatrick   auto firstSectionOrDotAssignment =
1633ece8a530Spatrick       std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); });
1634ece8a530Spatrick   if (firstSectionOrDotAssignment != e &&
1635ece8a530Spatrick       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1636ece8a530Spatrick     ++firstSectionOrDotAssignment;
1637ece8a530Spatrick   i = firstSectionOrDotAssignment;
1638ece8a530Spatrick 
1639ece8a530Spatrick   while (nonScriptI != e) {
1640ece8a530Spatrick     auto pos = findOrphanPos(i, nonScriptI);
1641ece8a530Spatrick     OutputSection *orphan = cast<OutputSection>(*nonScriptI);
1642ece8a530Spatrick 
1643ece8a530Spatrick     // As an optimization, find all sections with the same sort rank
1644ece8a530Spatrick     // and insert them with one rotate.
1645ece8a530Spatrick     unsigned rank = orphan->sortRank;
1646ece8a530Spatrick     auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) {
1647ece8a530Spatrick       return cast<OutputSection>(cmd)->sortRank != rank;
1648ece8a530Spatrick     });
1649ece8a530Spatrick     std::rotate(pos, nonScriptI, end);
1650ece8a530Spatrick     nonScriptI = end;
1651ece8a530Spatrick   }
1652ece8a530Spatrick 
1653ece8a530Spatrick   script->adjustSectionsAfterSorting();
1654ece8a530Spatrick }
1655ece8a530Spatrick 
1656ece8a530Spatrick static bool compareByFilePosition(InputSection *a, InputSection *b) {
1657*a0747c9fSpatrick   InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1658*a0747c9fSpatrick   InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1659*a0747c9fSpatrick   // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1660*a0747c9fSpatrick   // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1661*a0747c9fSpatrick   if (!la || !lb)
1662*a0747c9fSpatrick     return la && !lb;
1663ece8a530Spatrick   OutputSection *aOut = la->getParent();
1664ece8a530Spatrick   OutputSection *bOut = lb->getParent();
1665ece8a530Spatrick 
1666ece8a530Spatrick   if (aOut != bOut)
1667bb684c34Spatrick     return aOut->addr < bOut->addr;
1668ece8a530Spatrick   return la->outSecOff < lb->outSecOff;
1669ece8a530Spatrick }
1670ece8a530Spatrick 
1671ece8a530Spatrick template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1672*a0747c9fSpatrick   llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1673ece8a530Spatrick   for (OutputSection *sec : outputSections) {
1674ece8a530Spatrick     if (!(sec->flags & SHF_LINK_ORDER))
1675ece8a530Spatrick       continue;
1676ece8a530Spatrick 
1677ece8a530Spatrick     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1678ece8a530Spatrick     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1679ece8a530Spatrick     if (!config->relocatable && config->emachine == EM_ARM &&
1680ece8a530Spatrick         sec->type == SHT_ARM_EXIDX)
1681ece8a530Spatrick       continue;
1682ece8a530Spatrick 
1683*a0747c9fSpatrick     // Link order may be distributed across several InputSectionDescriptions.
1684*a0747c9fSpatrick     // Sorting is performed separately.
1685ece8a530Spatrick     std::vector<InputSection **> scriptSections;
1686ece8a530Spatrick     std::vector<InputSection *> sections;
1687ece8a530Spatrick     for (BaseCommand *base : sec->sectionCommands) {
1688*a0747c9fSpatrick       auto *isd = dyn_cast<InputSectionDescription>(base);
1689*a0747c9fSpatrick       if (!isd)
1690*a0747c9fSpatrick         continue;
1691*a0747c9fSpatrick       bool hasLinkOrder = false;
1692*a0747c9fSpatrick       scriptSections.clear();
1693*a0747c9fSpatrick       sections.clear();
1694ece8a530Spatrick       for (InputSection *&isec : isd->sections) {
1695*a0747c9fSpatrick         if (isec->flags & SHF_LINK_ORDER) {
1696ece8a530Spatrick           InputSection *link = isec->getLinkOrderDep();
1697*a0747c9fSpatrick           if (link && !link->getParent())
1698ece8a530Spatrick             error(toString(isec) + ": sh_link points to discarded section " +
1699ece8a530Spatrick                   toString(link));
1700*a0747c9fSpatrick           hasLinkOrder = true;
1701ece8a530Spatrick         }
1702*a0747c9fSpatrick         scriptSections.push_back(&isec);
1703*a0747c9fSpatrick         sections.push_back(isec);
1704ece8a530Spatrick       }
1705*a0747c9fSpatrick       if (hasLinkOrder && errorCount() == 0) {
1706ece8a530Spatrick         llvm::stable_sort(sections, compareByFilePosition);
1707*a0747c9fSpatrick         for (int i = 0, n = sections.size(); i != n; ++i)
1708ece8a530Spatrick           *scriptSections[i] = sections[i];
1709ece8a530Spatrick       }
1710ece8a530Spatrick     }
1711*a0747c9fSpatrick   }
1712*a0747c9fSpatrick }
1713ece8a530Spatrick 
1714bb684c34Spatrick static void finalizeSynthetic(SyntheticSection *sec) {
1715*a0747c9fSpatrick   if (sec && sec->isNeeded() && sec->getParent()) {
1716*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1717bb684c34Spatrick     sec->finalizeContents();
1718bb684c34Spatrick   }
1719*a0747c9fSpatrick }
1720bb684c34Spatrick 
1721ece8a530Spatrick // We need to generate and finalize the content that depends on the address of
1722ece8a530Spatrick // InputSections. As the generation of the content may also alter InputSection
1723ece8a530Spatrick // addresses we must converge to a fixed point. We do that here. See the comment
1724ece8a530Spatrick // in Writer<ELFT>::finalizeSections().
1725ece8a530Spatrick template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1726*a0747c9fSpatrick   llvm::TimeTraceScope timeScope("Finalize address dependent content");
1727ece8a530Spatrick   ThunkCreator tc;
1728ece8a530Spatrick   AArch64Err843419Patcher a64p;
1729ece8a530Spatrick   ARMErr657417Patcher a32p;
1730ece8a530Spatrick   script->assignAddresses();
1731bb684c34Spatrick   // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1732bb684c34Spatrick   // do require the relative addresses of OutputSections because linker scripts
1733bb684c34Spatrick   // can assign Virtual Addresses to OutputSections that are not monotonically
1734bb684c34Spatrick   // increasing.
1735bb684c34Spatrick   for (Partition &part : partitions)
1736bb684c34Spatrick     finalizeSynthetic(part.armExidx);
1737bb684c34Spatrick   resolveShfLinkOrder();
1738bb684c34Spatrick 
1739bb684c34Spatrick   // Converts call x@GDPLT to call __tls_get_addr
1740bb684c34Spatrick   if (config->emachine == EM_HEXAGON)
1741bb684c34Spatrick     hexagonTLSSymbolUpdate(outputSections);
1742ece8a530Spatrick 
1743ece8a530Spatrick   int assignPasses = 0;
1744ece8a530Spatrick   for (;;) {
1745ece8a530Spatrick     bool changed = target->needsThunks && tc.createThunks(outputSections);
1746ece8a530Spatrick 
1747ece8a530Spatrick     // With Thunk Size much smaller than branch range we expect to
1748*a0747c9fSpatrick     // converge quickly; if we get to 15 something has gone wrong.
1749*a0747c9fSpatrick     if (changed && tc.pass >= 15) {
1750ece8a530Spatrick       error("thunk creation not converged");
1751ece8a530Spatrick       break;
1752ece8a530Spatrick     }
1753ece8a530Spatrick 
1754ece8a530Spatrick     if (config->fixCortexA53Errata843419) {
1755ece8a530Spatrick       if (changed)
1756ece8a530Spatrick         script->assignAddresses();
1757ece8a530Spatrick       changed |= a64p.createFixes();
1758ece8a530Spatrick     }
1759ece8a530Spatrick     if (config->fixCortexA8) {
1760ece8a530Spatrick       if (changed)
1761ece8a530Spatrick         script->assignAddresses();
1762ece8a530Spatrick       changed |= a32p.createFixes();
1763ece8a530Spatrick     }
1764ece8a530Spatrick 
1765ece8a530Spatrick     if (in.mipsGot)
1766ece8a530Spatrick       in.mipsGot->updateAllocSize();
1767ece8a530Spatrick 
1768ece8a530Spatrick     for (Partition &part : partitions) {
1769ece8a530Spatrick       changed |= part.relaDyn->updateAllocSize();
1770ece8a530Spatrick       if (part.relrDyn)
1771ece8a530Spatrick         changed |= part.relrDyn->updateAllocSize();
1772ece8a530Spatrick     }
1773ece8a530Spatrick 
1774ece8a530Spatrick     const Defined *changedSym = script->assignAddresses();
1775ece8a530Spatrick     if (!changed) {
1776ece8a530Spatrick       // Some symbols may be dependent on section addresses. When we break the
1777ece8a530Spatrick       // loop, the symbol values are finalized because a previous
1778ece8a530Spatrick       // assignAddresses() finalized section addresses.
1779ece8a530Spatrick       if (!changedSym)
1780ece8a530Spatrick         break;
1781ece8a530Spatrick       if (++assignPasses == 5) {
1782ece8a530Spatrick         errorOrWarn("assignment to symbol " + toString(*changedSym) +
1783ece8a530Spatrick                     " does not converge");
1784ece8a530Spatrick         break;
1785ece8a530Spatrick       }
1786ece8a530Spatrick     }
1787ece8a530Spatrick   }
1788bb684c34Spatrick 
1789bb684c34Spatrick   // If addrExpr is set, the address may not be a multiple of the alignment.
1790bb684c34Spatrick   // Warn because this is error-prone.
1791bb684c34Spatrick   for (BaseCommand *cmd : script->sectionCommands)
1792bb684c34Spatrick     if (auto *os = dyn_cast<OutputSection>(cmd))
1793bb684c34Spatrick       if (os->addr % os->alignment != 0)
1794bb684c34Spatrick         warn("address (0x" + Twine::utohexstr(os->addr) + ") of section " +
1795bb684c34Spatrick              os->name + " is not a multiple of alignment (" +
1796bb684c34Spatrick              Twine(os->alignment) + ")");
1797ece8a530Spatrick }
1798ece8a530Spatrick 
1799*a0747c9fSpatrick // If Input Sections have been shrunk (basic block sections) then
1800bb684c34Spatrick // update symbol values and sizes associated with these sections.  With basic
1801bb684c34Spatrick // block sections, input sections can shrink when the jump instructions at
1802bb684c34Spatrick // the end of the section are relaxed.
1803bb684c34Spatrick static void fixSymbolsAfterShrinking() {
1804bb684c34Spatrick   for (InputFile *File : objectFiles) {
1805bb684c34Spatrick     parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1806bb684c34Spatrick       auto *def = dyn_cast<Defined>(Sym);
1807bb684c34Spatrick       if (!def)
1808bb684c34Spatrick         return;
1809bb684c34Spatrick 
1810bb684c34Spatrick       const SectionBase *sec = def->section;
1811bb684c34Spatrick       if (!sec)
1812bb684c34Spatrick         return;
1813bb684c34Spatrick 
1814bb684c34Spatrick       const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec->repl);
1815bb684c34Spatrick       if (!inputSec || !inputSec->bytesDropped)
1816bb684c34Spatrick         return;
1817bb684c34Spatrick 
1818bb684c34Spatrick       const size_t OldSize = inputSec->data().size();
1819bb684c34Spatrick       const size_t NewSize = OldSize - inputSec->bytesDropped;
1820bb684c34Spatrick 
1821bb684c34Spatrick       if (def->value > NewSize && def->value <= OldSize) {
1822bb684c34Spatrick         LLVM_DEBUG(llvm::dbgs()
1823bb684c34Spatrick                    << "Moving symbol " << Sym->getName() << " from "
1824bb684c34Spatrick                    << def->value << " to "
1825bb684c34Spatrick                    << def->value - inputSec->bytesDropped << " bytes\n");
1826bb684c34Spatrick         def->value -= inputSec->bytesDropped;
1827bb684c34Spatrick         return;
1828bb684c34Spatrick       }
1829bb684c34Spatrick 
1830bb684c34Spatrick       if (def->value + def->size > NewSize && def->value <= OldSize &&
1831bb684c34Spatrick           def->value + def->size <= OldSize) {
1832bb684c34Spatrick         LLVM_DEBUG(llvm::dbgs()
1833bb684c34Spatrick                    << "Shrinking symbol " << Sym->getName() << " from "
1834bb684c34Spatrick                    << def->size << " to " << def->size - inputSec->bytesDropped
1835bb684c34Spatrick                    << " bytes\n");
1836bb684c34Spatrick         def->size -= inputSec->bytesDropped;
1837bb684c34Spatrick       }
1838bb684c34Spatrick     });
1839bb684c34Spatrick   }
1840bb684c34Spatrick }
1841bb684c34Spatrick 
1842bb684c34Spatrick // If basic block sections exist, there are opportunities to delete fall thru
1843bb684c34Spatrick // jumps and shrink jump instructions after basic block reordering.  This
1844bb684c34Spatrick // relaxation pass does that.  It is only enabled when --optimize-bb-jumps
1845bb684c34Spatrick // option is used.
1846bb684c34Spatrick template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1847bb684c34Spatrick   assert(config->optimizeBBJumps);
1848bb684c34Spatrick 
1849bb684c34Spatrick   script->assignAddresses();
1850bb684c34Spatrick   // For every output section that has executable input sections, this
1851bb684c34Spatrick   // does the following:
1852bb684c34Spatrick   //   1. Deletes all direct jump instructions in input sections that
1853bb684c34Spatrick   //      jump to the following section as it is not required.
1854bb684c34Spatrick   //   2. If there are two consecutive jump instructions, it checks
1855bb684c34Spatrick   //      if they can be flipped and one can be deleted.
1856bb684c34Spatrick   for (OutputSection *os : outputSections) {
1857bb684c34Spatrick     if (!(os->flags & SHF_EXECINSTR))
1858bb684c34Spatrick       continue;
1859bb684c34Spatrick     std::vector<InputSection *> sections = getInputSections(os);
1860bb684c34Spatrick     std::vector<unsigned> result(sections.size());
1861bb684c34Spatrick     // Delete all fall through jump instructions.  Also, check if two
1862bb684c34Spatrick     // consecutive jump instructions can be flipped so that a fall
1863bb684c34Spatrick     // through jmp instruction can be deleted.
1864bb684c34Spatrick     parallelForEachN(0, sections.size(), [&](size_t i) {
1865bb684c34Spatrick       InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1866bb684c34Spatrick       InputSection &is = *sections[i];
1867bb684c34Spatrick       result[i] =
1868bb684c34Spatrick           target->deleteFallThruJmpInsn(is, is.getFile<ELFT>(), next) ? 1 : 0;
1869bb684c34Spatrick     });
1870bb684c34Spatrick     size_t numDeleted = std::count(result.begin(), result.end(), 1);
1871bb684c34Spatrick     if (numDeleted > 0) {
1872bb684c34Spatrick       script->assignAddresses();
1873bb684c34Spatrick       LLVM_DEBUG(llvm::dbgs()
1874bb684c34Spatrick                  << "Removing " << numDeleted << " fall through jumps\n");
1875bb684c34Spatrick     }
1876bb684c34Spatrick   }
1877bb684c34Spatrick 
1878bb684c34Spatrick   fixSymbolsAfterShrinking();
1879bb684c34Spatrick 
1880bb684c34Spatrick   for (OutputSection *os : outputSections) {
1881bb684c34Spatrick     std::vector<InputSection *> sections = getInputSections(os);
1882bb684c34Spatrick     for (InputSection *is : sections)
1883bb684c34Spatrick       is->trim();
1884bb684c34Spatrick   }
1885ece8a530Spatrick }
1886ece8a530Spatrick 
1887ece8a530Spatrick // In order to allow users to manipulate linker-synthesized sections,
1888ece8a530Spatrick // we had to add synthetic sections to the input section list early,
1889ece8a530Spatrick // even before we make decisions whether they are needed. This allows
1890ece8a530Spatrick // users to write scripts like this: ".mygot : { .got }".
1891ece8a530Spatrick //
1892ece8a530Spatrick // Doing it has an unintended side effects. If it turns out that we
1893ece8a530Spatrick // don't need a .got (for example) at all because there's no
1894ece8a530Spatrick // relocation that needs a .got, we don't want to emit .got.
1895ece8a530Spatrick //
1896ece8a530Spatrick // To deal with the above problem, this function is called after
1897ece8a530Spatrick // scanRelocations is called to remove synthetic sections that turn
1898ece8a530Spatrick // out to be empty.
1899ece8a530Spatrick static void removeUnusedSyntheticSections() {
1900ece8a530Spatrick   // All input synthetic sections that can be empty are placed after
1901*a0747c9fSpatrick   // all regular ones. Reverse iterate to find the first synthetic section
1902*a0747c9fSpatrick   // after a non-synthetic one which will be our starting point.
1903*a0747c9fSpatrick   auto start = std::find_if(inputSections.rbegin(), inputSections.rend(),
1904*a0747c9fSpatrick                             [](InputSectionBase *s) {
1905*a0747c9fSpatrick                               return !isa<SyntheticSection>(s);
1906*a0747c9fSpatrick                             })
1907*a0747c9fSpatrick                    .base();
1908*a0747c9fSpatrick 
1909*a0747c9fSpatrick   DenseSet<InputSectionDescription *> isdSet;
1910*a0747c9fSpatrick   // Mark unused synthetic sections for deletion
1911*a0747c9fSpatrick   auto end = std::stable_partition(
1912*a0747c9fSpatrick       start, inputSections.end(), [&](InputSectionBase *s) {
1913ece8a530Spatrick         SyntheticSection *ss = dyn_cast<SyntheticSection>(s);
1914ece8a530Spatrick         OutputSection *os = ss->getParent();
1915ece8a530Spatrick         if (!os || ss->isNeeded())
1916*a0747c9fSpatrick           return true;
1917ece8a530Spatrick 
1918*a0747c9fSpatrick         // If we reach here, then ss is an unused synthetic section and we want
1919*a0747c9fSpatrick         // to remove it from the corresponding input section description, and
1920bb684c34Spatrick         // orphanSections.
1921ece8a530Spatrick         for (BaseCommand *b : os->sectionCommands)
1922ece8a530Spatrick           if (auto *isd = dyn_cast<InputSectionDescription>(b))
1923*a0747c9fSpatrick             isdSet.insert(isd);
1924*a0747c9fSpatrick 
1925*a0747c9fSpatrick         llvm::erase_if(
1926*a0747c9fSpatrick             script->orphanSections,
1927bb684c34Spatrick             [=](const InputSectionBase *isec) { return isec == ss; });
1928*a0747c9fSpatrick 
1929*a0747c9fSpatrick         return false;
1930*a0747c9fSpatrick       });
1931*a0747c9fSpatrick 
1932*a0747c9fSpatrick   DenseSet<InputSectionBase *> unused(end, inputSections.end());
1933*a0747c9fSpatrick   for (auto *isd : isdSet)
1934*a0747c9fSpatrick     llvm::erase_if(isd->sections,
1935*a0747c9fSpatrick                    [=](InputSection *isec) { return unused.count(isec); });
1936*a0747c9fSpatrick 
1937*a0747c9fSpatrick   // Erase unused synthetic sections.
1938*a0747c9fSpatrick   inputSections.erase(end, inputSections.end());
1939ece8a530Spatrick }
1940ece8a530Spatrick 
1941ece8a530Spatrick // Create output section objects and add them to OutputSections.
1942ece8a530Spatrick template <class ELFT> void Writer<ELFT>::finalizeSections() {
1943ece8a530Spatrick   Out::preinitArray = findSection(".preinit_array");
1944ece8a530Spatrick   Out::initArray = findSection(".init_array");
1945ece8a530Spatrick   Out::finiArray = findSection(".fini_array");
1946ece8a530Spatrick 
1947ece8a530Spatrick   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1948ece8a530Spatrick   // symbols for sections, so that the runtime can get the start and end
1949ece8a530Spatrick   // addresses of each section by section name. Add such symbols.
1950ece8a530Spatrick   if (!config->relocatable) {
1951ece8a530Spatrick     addStartEndSymbols();
1952ece8a530Spatrick     for (BaseCommand *base : script->sectionCommands)
1953ece8a530Spatrick       if (auto *sec = dyn_cast<OutputSection>(base))
1954ece8a530Spatrick         addStartStopSymbols(sec);
1955ece8a530Spatrick   }
1956ece8a530Spatrick 
1957ece8a530Spatrick   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1958ece8a530Spatrick   // It should be okay as no one seems to care about the type.
1959ece8a530Spatrick   // Even the author of gold doesn't remember why gold behaves that way.
1960ece8a530Spatrick   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1961ece8a530Spatrick   if (mainPart->dynamic->parent)
1962ece8a530Spatrick     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK,
1963ece8a530Spatrick                               STV_HIDDEN, STT_NOTYPE,
1964ece8a530Spatrick                               /*value=*/0, /*size=*/0, mainPart->dynamic});
1965ece8a530Spatrick 
1966ece8a530Spatrick   // Define __rel[a]_iplt_{start,end} symbols if needed.
1967ece8a530Spatrick   addRelIpltSymbols();
1968ece8a530Spatrick 
1969ece8a530Spatrick   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1970ece8a530Spatrick   // should only be defined in an executable. If .sdata does not exist, its
1971ece8a530Spatrick   // value/section does not matter but it has to be relative, so set its
1972ece8a530Spatrick   // st_shndx arbitrarily to 1 (Out::elfHeader).
1973ece8a530Spatrick   if (config->emachine == EM_RISCV && !config->shared) {
1974ece8a530Spatrick     OutputSection *sec = findSection(".sdata");
1975ece8a530Spatrick     ElfSym::riscvGlobalPointer =
1976ece8a530Spatrick         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
1977ece8a530Spatrick                            0x800, STV_DEFAULT, STB_GLOBAL);
1978ece8a530Spatrick   }
1979ece8a530Spatrick 
1980ece8a530Spatrick   if (config->emachine == EM_X86_64) {
1981ece8a530Spatrick     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1982ece8a530Spatrick     // way that:
1983ece8a530Spatrick     //
1984ece8a530Spatrick     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1985ece8a530Spatrick     // computes 0.
1986ece8a530Spatrick     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1987ece8a530Spatrick     // the TLS block).
1988ece8a530Spatrick     //
1989ece8a530Spatrick     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1990ece8a530Spatrick     // an absolute symbol of zero. This is different from GNU linkers which
1991ece8a530Spatrick     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1992ece8a530Spatrick     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1993ece8a530Spatrick     if (s && s->isUndefined()) {
1994ece8a530Spatrick       s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN,
1995ece8a530Spatrick                          STT_TLS, /*value=*/0, 0,
1996ece8a530Spatrick                          /*section=*/nullptr});
1997ece8a530Spatrick       ElfSym::tlsModuleBase = cast<Defined>(s);
1998ece8a530Spatrick     }
1999ece8a530Spatrick   }
2000ece8a530Spatrick 
2001*a0747c9fSpatrick   {
2002*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Finalize .eh_frame");
2003ece8a530Spatrick     // This responsible for splitting up .eh_frame section into
2004ece8a530Spatrick     // pieces. The relocation scan uses those pieces, so this has to be
2005ece8a530Spatrick     // earlier.
2006ece8a530Spatrick     for (Partition &part : partitions)
2007ece8a530Spatrick       finalizeSynthetic(part.ehFrame);
2008*a0747c9fSpatrick   }
2009ece8a530Spatrick 
2010ece8a530Spatrick   for (Symbol *sym : symtab->symbols())
2011ece8a530Spatrick     sym->isPreemptible = computeIsPreemptible(*sym);
2012ece8a530Spatrick 
2013ece8a530Spatrick   // Change values of linker-script-defined symbols from placeholders (assigned
2014ece8a530Spatrick   // by declareSymbols) to actual definitions.
2015ece8a530Spatrick   script->processSymbolAssignments();
2016ece8a530Spatrick 
2017*a0747c9fSpatrick   {
2018*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Scan relocations");
2019*a0747c9fSpatrick     // Scan relocations. This must be done after every symbol is declared so
2020*a0747c9fSpatrick     // that we can correctly decide if a dynamic relocation is needed. This is
2021*a0747c9fSpatrick     // called after processSymbolAssignments() because it needs to know whether
2022*a0747c9fSpatrick     // a linker-script-defined symbol is absolute.
2023bb684c34Spatrick     ppc64noTocRelax.clear();
2024ece8a530Spatrick     if (!config->relocatable) {
2025ece8a530Spatrick       forEachRelSec(scanRelocations<ELFT>);
2026ece8a530Spatrick       reportUndefinedSymbols<ELFT>();
2027ece8a530Spatrick     }
2028*a0747c9fSpatrick   }
2029ece8a530Spatrick 
2030ece8a530Spatrick   if (in.plt && in.plt->isNeeded())
2031ece8a530Spatrick     in.plt->addSymbols();
2032ece8a530Spatrick   if (in.iplt && in.iplt->isNeeded())
2033ece8a530Spatrick     in.iplt->addSymbols();
2034ece8a530Spatrick 
2035*a0747c9fSpatrick   if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
2036*a0747c9fSpatrick     auto diagnose =
2037*a0747c9fSpatrick         config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
2038*a0747c9fSpatrick             ? errorOrWarn
2039*a0747c9fSpatrick             : warn;
2040ece8a530Spatrick     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
2041ece8a530Spatrick     // entries are seen. These cases would otherwise lead to runtime errors
2042ece8a530Spatrick     // reported by the dynamic linker.
2043ece8a530Spatrick     //
2044ece8a530Spatrick     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
2045ece8a530Spatrick     // catch more cases. That is too much for us. Our approach resembles the one
2046ece8a530Spatrick     // used in ld.gold, achieves a good balance to be useful but not too smart.
2047*a0747c9fSpatrick     for (SharedFile *file : sharedFiles) {
2048*a0747c9fSpatrick       bool allNeededIsKnown =
2049ece8a530Spatrick           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
2050ece8a530Spatrick             return symtab->soNames.count(needed);
2051ece8a530Spatrick           });
2052*a0747c9fSpatrick       if (!allNeededIsKnown)
2053*a0747c9fSpatrick         continue;
2054*a0747c9fSpatrick       for (Symbol *sym : file->requiredSymbols)
2055ece8a530Spatrick         if (sym->isUndefined() && !sym->isWeak())
2056*a0747c9fSpatrick           diagnose(toString(file) + ": undefined reference to " +
2057bb684c34Spatrick                    toString(*sym) + " [--no-allow-shlib-undefined]");
2058ece8a530Spatrick     }
2059*a0747c9fSpatrick   }
2060ece8a530Spatrick 
2061*a0747c9fSpatrick   {
2062*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Add symbols to symtabs");
2063ece8a530Spatrick     // Now that we have defined all possible global symbols including linker-
2064ece8a530Spatrick     // synthesized ones. Visit all symbols to give the finishing touches.
2065ece8a530Spatrick     for (Symbol *sym : symtab->symbols()) {
2066ece8a530Spatrick       if (!includeInSymtab(*sym))
2067ece8a530Spatrick         continue;
2068ece8a530Spatrick       if (in.symTab)
2069ece8a530Spatrick         in.symTab->addSymbol(sym);
2070ece8a530Spatrick 
2071ece8a530Spatrick       if (sym->includeInDynsym()) {
2072ece8a530Spatrick         partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
2073ece8a530Spatrick         if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
2074ece8a530Spatrick           if (file->isNeeded && !sym->isUndefined())
2075ece8a530Spatrick             addVerneed(sym);
2076ece8a530Spatrick       }
2077ece8a530Spatrick     }
2078ece8a530Spatrick 
2079*a0747c9fSpatrick     // We also need to scan the dynamic relocation tables of the other
2080*a0747c9fSpatrick     // partitions and add any referenced symbols to the partition's dynsym.
2081ece8a530Spatrick     for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
2082ece8a530Spatrick       DenseSet<Symbol *> syms;
2083ece8a530Spatrick       for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
2084ece8a530Spatrick         syms.insert(e.sym);
2085ece8a530Spatrick       for (DynamicReloc &reloc : part.relaDyn->relocs)
2086*a0747c9fSpatrick         if (reloc.sym && reloc.needsDynSymIndex() &&
2087*a0747c9fSpatrick             syms.insert(reloc.sym).second)
2088ece8a530Spatrick           part.dynSymTab->addSymbol(reloc.sym);
2089ece8a530Spatrick     }
2090*a0747c9fSpatrick   }
2091ece8a530Spatrick 
2092ece8a530Spatrick   // Do not proceed if there was an undefined symbol.
2093ece8a530Spatrick   if (errorCount())
2094ece8a530Spatrick     return;
2095ece8a530Spatrick 
2096ece8a530Spatrick   if (in.mipsGot)
2097ece8a530Spatrick     in.mipsGot->build();
2098ece8a530Spatrick 
2099ece8a530Spatrick   removeUnusedSyntheticSections();
2100bb684c34Spatrick   script->diagnoseOrphanHandling();
2101ece8a530Spatrick 
2102ece8a530Spatrick   sortSections();
2103ece8a530Spatrick 
2104ece8a530Spatrick   // Now that we have the final list, create a list of all the
2105ece8a530Spatrick   // OutputSections for convenience.
2106ece8a530Spatrick   for (BaseCommand *base : script->sectionCommands)
2107ece8a530Spatrick     if (auto *sec = dyn_cast<OutputSection>(base))
2108ece8a530Spatrick       outputSections.push_back(sec);
2109ece8a530Spatrick 
2110ece8a530Spatrick   // Prefer command line supplied address over other constraints.
2111ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2112ece8a530Spatrick     auto i = config->sectionStartMap.find(sec->name);
2113ece8a530Spatrick     if (i != config->sectionStartMap.end())
2114ece8a530Spatrick       sec->addrExpr = [=] { return i->second; };
2115ece8a530Spatrick   }
2116ece8a530Spatrick 
2117bb684c34Spatrick   // With the outputSections available check for GDPLT relocations
2118bb684c34Spatrick   // and add __tls_get_addr symbol if needed.
2119bb684c34Spatrick   if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2120bb684c34Spatrick     Symbol *sym = symtab->addSymbol(Undefined{
2121bb684c34Spatrick         nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2122bb684c34Spatrick     sym->isPreemptible = true;
2123bb684c34Spatrick     partitions[0].dynSymTab->addSymbol(sym);
2124bb684c34Spatrick   }
2125bb684c34Spatrick 
2126ece8a530Spatrick   // This is a bit of a hack. A value of 0 means undef, so we set it
2127ece8a530Spatrick   // to 1 to make __ehdr_start defined. The section number is not
2128ece8a530Spatrick   // particularly relevant.
2129ece8a530Spatrick   Out::elfHeader->sectionIndex = 1;
2130ece8a530Spatrick 
2131ece8a530Spatrick   for (size_t i = 0, e = outputSections.size(); i != e; ++i) {
2132ece8a530Spatrick     OutputSection *sec = outputSections[i];
2133ece8a530Spatrick     sec->sectionIndex = i + 1;
2134ece8a530Spatrick     sec->shName = in.shStrTab->addString(sec->name);
2135ece8a530Spatrick   }
2136ece8a530Spatrick 
2137ece8a530Spatrick   // Binary and relocatable output does not have PHDRS.
2138ece8a530Spatrick   // The headers have to be created before finalize as that can influence the
2139ece8a530Spatrick   // image base and the dynamic section on mips includes the image base.
2140ece8a530Spatrick   if (!config->relocatable && !config->oFormatBinary) {
2141ece8a530Spatrick     for (Partition &part : partitions) {
2142ece8a530Spatrick       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2143ece8a530Spatrick                                               : createPhdrs(part);
2144ece8a530Spatrick       if (config->emachine == EM_ARM) {
2145ece8a530Spatrick         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2146ece8a530Spatrick         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2147ece8a530Spatrick       }
2148ece8a530Spatrick       if (config->emachine == EM_MIPS) {
2149ece8a530Spatrick         // Add separate segments for MIPS-specific sections.
2150ece8a530Spatrick         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2151ece8a530Spatrick         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2152ece8a530Spatrick         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2153ece8a530Spatrick       }
2154ece8a530Spatrick     }
2155ece8a530Spatrick     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2156ece8a530Spatrick 
2157ece8a530Spatrick     // Find the TLS segment. This happens before the section layout loop so that
2158ece8a530Spatrick     // Android relocation packing can look up TLS symbol addresses. We only need
2159ece8a530Spatrick     // to care about the main partition here because all TLS symbols were moved
2160ece8a530Spatrick     // to the main partition (see MarkLive.cpp).
2161ece8a530Spatrick     for (PhdrEntry *p : mainPart->phdrs)
2162ece8a530Spatrick       if (p->p_type == PT_TLS)
2163ece8a530Spatrick         Out::tlsPhdr = p;
2164ece8a530Spatrick   }
2165ece8a530Spatrick 
2166ece8a530Spatrick   // Some symbols are defined in term of program headers. Now that we
2167ece8a530Spatrick   // have the headers, we can find out which sections they point to.
2168ece8a530Spatrick   setReservedSymbolSections();
2169ece8a530Spatrick 
2170*a0747c9fSpatrick   {
2171*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2172*a0747c9fSpatrick 
2173ece8a530Spatrick     finalizeSynthetic(in.bss);
2174ece8a530Spatrick     finalizeSynthetic(in.bssRelRo);
2175ece8a530Spatrick     finalizeSynthetic(in.symTabShndx);
2176ece8a530Spatrick     finalizeSynthetic(in.shStrTab);
2177ece8a530Spatrick     finalizeSynthetic(in.strTab);
2178ece8a530Spatrick     finalizeSynthetic(in.got);
2179ece8a530Spatrick     finalizeSynthetic(in.mipsGot);
2180ece8a530Spatrick     finalizeSynthetic(in.igotPlt);
2181ece8a530Spatrick     finalizeSynthetic(in.gotPlt);
2182ece8a530Spatrick     finalizeSynthetic(in.relaIplt);
2183ece8a530Spatrick     finalizeSynthetic(in.relaPlt);
2184ece8a530Spatrick     finalizeSynthetic(in.plt);
2185ece8a530Spatrick     finalizeSynthetic(in.iplt);
2186ece8a530Spatrick     finalizeSynthetic(in.ppc32Got2);
2187ece8a530Spatrick     finalizeSynthetic(in.partIndex);
2188ece8a530Spatrick 
2189ece8a530Spatrick     // Dynamic section must be the last one in this list and dynamic
2190ece8a530Spatrick     // symbol table section (dynSymTab) must be the first one.
2191ece8a530Spatrick     for (Partition &part : partitions) {
2192ece8a530Spatrick       finalizeSynthetic(part.dynSymTab);
2193ece8a530Spatrick       finalizeSynthetic(part.gnuHashTab);
2194ece8a530Spatrick       finalizeSynthetic(part.hashTab);
2195ece8a530Spatrick       finalizeSynthetic(part.verDef);
2196ece8a530Spatrick       finalizeSynthetic(part.relaDyn);
2197ece8a530Spatrick       finalizeSynthetic(part.relrDyn);
2198ece8a530Spatrick       finalizeSynthetic(part.ehFrameHdr);
2199ece8a530Spatrick       finalizeSynthetic(part.verSym);
2200ece8a530Spatrick       finalizeSynthetic(part.verNeed);
2201ece8a530Spatrick       finalizeSynthetic(part.dynamic);
2202ece8a530Spatrick     }
2203*a0747c9fSpatrick   }
2204ece8a530Spatrick 
2205ece8a530Spatrick   if (!script->hasSectionsCommand && !config->relocatable)
2206ece8a530Spatrick     fixSectionAlignments();
2207ece8a530Spatrick 
2208ece8a530Spatrick   // This is used to:
2209ece8a530Spatrick   // 1) Create "thunks":
2210ece8a530Spatrick   //    Jump instructions in many ISAs have small displacements, and therefore
2211ece8a530Spatrick   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
2212ece8a530Spatrick   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
2213ece8a530Spatrick   //    responsibility to create and insert small pieces of code between
2214ece8a530Spatrick   //    sections to extend the ranges if jump targets are out of range. Such
2215ece8a530Spatrick   //    code pieces are called "thunks".
2216ece8a530Spatrick   //
2217ece8a530Spatrick   //    We add thunks at this stage. We couldn't do this before this point
2218ece8a530Spatrick   //    because this is the earliest point where we know sizes of sections and
2219ece8a530Spatrick   //    their layouts (that are needed to determine if jump targets are in
2220ece8a530Spatrick   //    range).
2221ece8a530Spatrick   //
2222ece8a530Spatrick   // 2) Update the sections. We need to generate content that depends on the
2223ece8a530Spatrick   //    address of InputSections. For example, MIPS GOT section content or
2224ece8a530Spatrick   //    android packed relocations sections content.
2225ece8a530Spatrick   //
2226ece8a530Spatrick   // 3) Assign the final values for the linker script symbols. Linker scripts
2227ece8a530Spatrick   //    sometimes using forward symbol declarations. We want to set the correct
2228ece8a530Spatrick   //    values. They also might change after adding the thunks.
2229ece8a530Spatrick   finalizeAddressDependentContent();
2230bb684c34Spatrick   if (errorCount())
2231bb684c34Spatrick     return;
2232ece8a530Spatrick 
2233*a0747c9fSpatrick   {
2234*a0747c9fSpatrick     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2235*a0747c9fSpatrick     // finalizeAddressDependentContent may have added local symbols to the
2236*a0747c9fSpatrick     // static symbol table.
2237ece8a530Spatrick     finalizeSynthetic(in.symTab);
2238ece8a530Spatrick     finalizeSynthetic(in.ppc64LongBranchTarget);
2239*a0747c9fSpatrick   }
2240ece8a530Spatrick 
2241bb684c34Spatrick   // Relaxation to delete inter-basic block jumps created by basic block
2242bb684c34Spatrick   // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2243bb684c34Spatrick   // can relax jump instructions based on symbol offset.
2244bb684c34Spatrick   if (config->optimizeBBJumps)
2245bb684c34Spatrick     optimizeBasicBlockJumps();
2246bb684c34Spatrick 
2247ece8a530Spatrick   // Fill other section headers. The dynamic table is finalized
2248ece8a530Spatrick   // at the end because some tags like RELSZ depend on result
2249ece8a530Spatrick   // of finalizing other sections.
2250ece8a530Spatrick   for (OutputSection *sec : outputSections)
2251ece8a530Spatrick     sec->finalize();
2252ece8a530Spatrick }
2253ece8a530Spatrick 
2254ece8a530Spatrick // Ensure data sections are not mixed with executable sections when
2255ece8a530Spatrick // -execute-only is used. -execute-only is a feature to make pages executable
2256ece8a530Spatrick // but not readable, and the feature is currently supported only on AArch64.
2257ece8a530Spatrick template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2258ece8a530Spatrick   if (!config->executeOnly)
2259ece8a530Spatrick     return;
2260ece8a530Spatrick 
2261ece8a530Spatrick   for (OutputSection *os : outputSections)
2262ece8a530Spatrick     if (os->flags & SHF_EXECINSTR)
2263ece8a530Spatrick       for (InputSection *isec : getInputSections(os))
2264ece8a530Spatrick         if (!(isec->flags & SHF_EXECINSTR))
2265ece8a530Spatrick           error("cannot place " + toString(isec) + " into " + toString(os->name) +
2266ece8a530Spatrick                 ": -execute-only does not support intermingling data and code");
2267ece8a530Spatrick }
2268ece8a530Spatrick 
2269ece8a530Spatrick // The linker is expected to define SECNAME_start and SECNAME_end
2270ece8a530Spatrick // symbols for a few sections. This function defines them.
2271ece8a530Spatrick template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2272ece8a530Spatrick   // If a section does not exist, there's ambiguity as to how we
2273ece8a530Spatrick   // define _start and _end symbols for an init/fini section. Since
2274ece8a530Spatrick   // the loader assume that the symbols are always defined, we need to
2275ece8a530Spatrick   // always define them. But what value? The loader iterates over all
2276ece8a530Spatrick   // pointers between _start and _end to run global ctors/dtors, so if
2277ece8a530Spatrick   // the section is empty, their symbol values don't actually matter
2278ece8a530Spatrick   // as long as _start and _end point to the same location.
2279ece8a530Spatrick   //
2280ece8a530Spatrick   // That said, we don't want to set the symbols to 0 (which is
2281ece8a530Spatrick   // probably the simplest value) because that could cause some
2282ece8a530Spatrick   // program to fail to link due to relocation overflow, if their
2283ece8a530Spatrick   // program text is above 2 GiB. We use the address of the .text
2284ece8a530Spatrick   // section instead to prevent that failure.
2285ece8a530Spatrick   //
2286ece8a530Spatrick   // In rare situations, the .text section may not exist. If that's the
2287ece8a530Spatrick   // case, use the image base address as a last resort.
2288ece8a530Spatrick   OutputSection *Default = findSection(".text");
2289ece8a530Spatrick   if (!Default)
2290ece8a530Spatrick     Default = Out::elfHeader;
2291ece8a530Spatrick 
2292ece8a530Spatrick   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2293ece8a530Spatrick     if (os) {
2294ece8a530Spatrick       addOptionalRegular(start, os, 0);
2295ece8a530Spatrick       addOptionalRegular(end, os, -1);
2296ece8a530Spatrick     } else {
2297ece8a530Spatrick       addOptionalRegular(start, Default, 0);
2298ece8a530Spatrick       addOptionalRegular(end, Default, 0);
2299ece8a530Spatrick     }
2300ece8a530Spatrick   };
2301ece8a530Spatrick 
2302ece8a530Spatrick   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2303ece8a530Spatrick   define("__init_array_start", "__init_array_end", Out::initArray);
2304ece8a530Spatrick   define("__fini_array_start", "__fini_array_end", Out::finiArray);
2305ece8a530Spatrick 
2306ece8a530Spatrick   if (OutputSection *sec = findSection(".ARM.exidx"))
2307ece8a530Spatrick     define("__exidx_start", "__exidx_end", sec);
2308ece8a530Spatrick }
2309ece8a530Spatrick 
2310ece8a530Spatrick // If a section name is valid as a C identifier (which is rare because of
2311ece8a530Spatrick // the leading '.'), linkers are expected to define __start_<secname> and
2312ece8a530Spatrick // __stop_<secname> symbols. They are at beginning and end of the section,
2313ece8a530Spatrick // respectively. This is not requested by the ELF standard, but GNU ld and
2314ece8a530Spatrick // gold provide the feature, and used by many programs.
2315ece8a530Spatrick template <class ELFT>
2316ece8a530Spatrick void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2317ece8a530Spatrick   StringRef s = sec->name;
2318ece8a530Spatrick   if (!isValidCIdentifier(s))
2319ece8a530Spatrick     return;
2320bb684c34Spatrick   addOptionalRegular(saver.save("__start_" + s), sec, 0,
2321bb684c34Spatrick                      config->zStartStopVisibility);
2322bb684c34Spatrick   addOptionalRegular(saver.save("__stop_" + s), sec, -1,
2323bb684c34Spatrick                      config->zStartStopVisibility);
2324ece8a530Spatrick }
2325ece8a530Spatrick 
2326ece8a530Spatrick static bool needsPtLoad(OutputSection *sec) {
2327*a0747c9fSpatrick   if (!(sec->flags & SHF_ALLOC))
2328ece8a530Spatrick     return false;
2329ece8a530Spatrick 
2330ece8a530Spatrick   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2331ece8a530Spatrick   // responsible for allocating space for them, not the PT_LOAD that
2332ece8a530Spatrick   // contains the TLS initialization image.
2333ece8a530Spatrick   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2334ece8a530Spatrick     return false;
2335ece8a530Spatrick   return true;
2336ece8a530Spatrick }
2337ece8a530Spatrick 
2338ece8a530Spatrick // Linker scripts are responsible for aligning addresses. Unfortunately, most
2339ece8a530Spatrick // linker scripts are designed for creating two PT_LOADs only, one RX and one
2340ece8a530Spatrick // RW. This means that there is no alignment in the RO to RX transition and we
2341ece8a530Spatrick // cannot create a PT_LOAD there.
2342ece8a530Spatrick static uint64_t computeFlags(uint64_t flags) {
2343ece8a530Spatrick   if (config->omagic)
2344ece8a530Spatrick     return PF_R | PF_W | PF_X;
2345ece8a530Spatrick   if (config->executeOnly && (flags & PF_X))
2346ece8a530Spatrick     return flags & ~PF_R;
2347ece8a530Spatrick   if (config->singleRoRx && !(flags & PF_W))
2348ece8a530Spatrick     return flags | PF_X;
2349ece8a530Spatrick   return flags;
2350ece8a530Spatrick }
2351ece8a530Spatrick 
2352ece8a530Spatrick // Decide which program headers to create and which sections to include in each
2353ece8a530Spatrick // one.
2354ece8a530Spatrick template <class ELFT>
2355ece8a530Spatrick std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) {
2356ece8a530Spatrick   std::vector<PhdrEntry *> ret;
2357ece8a530Spatrick   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2358ece8a530Spatrick     ret.push_back(make<PhdrEntry>(type, flags));
2359ece8a530Spatrick     return ret.back();
2360ece8a530Spatrick   };
2361ece8a530Spatrick 
2362ece8a530Spatrick   unsigned partNo = part.getNumber();
2363ece8a530Spatrick   bool isMain = partNo == 1;
2364ece8a530Spatrick 
2365ece8a530Spatrick   // Add the first PT_LOAD segment for regular output sections.
2366ece8a530Spatrick   uint64_t flags = computeFlags(PF_R);
2367ece8a530Spatrick   PhdrEntry *load = nullptr;
2368ece8a530Spatrick 
2369ece8a530Spatrick   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2370ece8a530Spatrick   // PT_LOAD.
2371ece8a530Spatrick   if (!config->nmagic && !config->omagic) {
2372ece8a530Spatrick     // The first phdr entry is PT_PHDR which describes the program header
2373ece8a530Spatrick     // itself.
2374ece8a530Spatrick     if (isMain)
2375ece8a530Spatrick       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2376ece8a530Spatrick     else
2377ece8a530Spatrick       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2378ece8a530Spatrick 
2379ece8a530Spatrick     // PT_INTERP must be the second entry if exists.
2380ece8a530Spatrick     if (OutputSection *cmd = findSection(".interp", partNo))
2381ece8a530Spatrick       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2382ece8a530Spatrick 
2383ece8a530Spatrick     // Add the headers. We will remove them if they don't fit.
2384ece8a530Spatrick     // In the other partitions the headers are ordinary sections, so they don't
2385ece8a530Spatrick     // need to be added here.
2386ece8a530Spatrick     if (isMain) {
2387ece8a530Spatrick       load = addHdr(PT_LOAD, flags);
2388ece8a530Spatrick       load->add(Out::elfHeader);
2389ece8a530Spatrick       load->add(Out::programHeaders);
2390ece8a530Spatrick     }
2391ece8a530Spatrick   }
2392ece8a530Spatrick 
2393ece8a530Spatrick   // PT_GNU_RELRO includes all sections that should be marked as
2394ece8a530Spatrick   // read-only by dynamic linker after processing relocations.
2395ece8a530Spatrick   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2396ece8a530Spatrick   // an error message if more than one PT_GNU_RELRO PHDR is required.
2397ece8a530Spatrick   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2398ece8a530Spatrick   bool inRelroPhdr = false;
2399ece8a530Spatrick   OutputSection *relroEnd = nullptr;
2400ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2401ece8a530Spatrick     if (sec->partition != partNo || !needsPtLoad(sec))
2402ece8a530Spatrick       continue;
2403ece8a530Spatrick     if (isRelroSection(sec)) {
2404ece8a530Spatrick       inRelroPhdr = true;
2405ece8a530Spatrick       if (!relroEnd)
2406ece8a530Spatrick         relRo->add(sec);
2407ece8a530Spatrick       else
2408ece8a530Spatrick         error("section: " + sec->name + " is not contiguous with other relro" +
2409ece8a530Spatrick               " sections");
2410ece8a530Spatrick     } else if (inRelroPhdr) {
2411ece8a530Spatrick       inRelroPhdr = false;
2412ece8a530Spatrick       relroEnd = sec;
2413ece8a530Spatrick     }
2414ece8a530Spatrick   }
2415ece8a530Spatrick 
2416ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2417ece8a530Spatrick     if (!needsPtLoad(sec))
2418ece8a530Spatrick       continue;
2419ece8a530Spatrick 
2420ece8a530Spatrick     // Normally, sections in partitions other than the current partition are
2421ece8a530Spatrick     // ignored. But partition number 255 is a special case: it contains the
2422ece8a530Spatrick     // partition end marker (.part.end). It needs to be added to the main
2423ece8a530Spatrick     // partition so that a segment is created for it in the main partition,
2424ece8a530Spatrick     // which will cause the dynamic loader to reserve space for the other
2425ece8a530Spatrick     // partitions.
2426ece8a530Spatrick     if (sec->partition != partNo) {
2427ece8a530Spatrick       if (isMain && sec->partition == 255)
2428ece8a530Spatrick         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2429ece8a530Spatrick       continue;
2430ece8a530Spatrick     }
2431ece8a530Spatrick 
2432ece8a530Spatrick     // Segments are contiguous memory regions that has the same attributes
2433ece8a530Spatrick     // (e.g. executable or writable). There is one phdr for each segment.
2434ece8a530Spatrick     // Therefore, we need to create a new phdr when the next section has
2435ece8a530Spatrick     // different flags or is loaded at a discontiguous address or memory
2436ece8a530Spatrick     // region using AT or AT> linker script command, respectively. At the same
2437ece8a530Spatrick     // time, we don't want to create a separate load segment for the headers,
2438ece8a530Spatrick     // even if the first output section has an AT or AT> attribute.
2439ece8a530Spatrick     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2440bb684c34Spatrick     bool sameLMARegion =
2441bb684c34Spatrick         load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2442bb684c34Spatrick     if (!(load && newFlags == flags && sec != relroEnd &&
2443bb684c34Spatrick           sec->memRegion == load->firstSec->memRegion &&
2444bb684c34Spatrick           (sameLMARegion || load->lastSec == Out::programHeaders))) {
2445ece8a530Spatrick       load = addHdr(PT_LOAD, newFlags);
2446ece8a530Spatrick       flags = newFlags;
2447ece8a530Spatrick     }
2448ece8a530Spatrick 
2449ece8a530Spatrick     load->add(sec);
2450ece8a530Spatrick   }
2451ece8a530Spatrick 
2452ece8a530Spatrick   // Add a TLS segment if any.
2453ece8a530Spatrick   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2454ece8a530Spatrick   for (OutputSection *sec : outputSections)
2455ece8a530Spatrick     if (sec->partition == partNo && sec->flags & SHF_TLS)
2456ece8a530Spatrick       tlsHdr->add(sec);
2457ece8a530Spatrick   if (tlsHdr->firstSec)
2458ece8a530Spatrick     ret.push_back(tlsHdr);
2459ece8a530Spatrick 
2460ece8a530Spatrick   // Add an entry for .dynamic.
2461ece8a530Spatrick   if (OutputSection *sec = part.dynamic->getParent())
2462ece8a530Spatrick     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2463ece8a530Spatrick 
2464ece8a530Spatrick   if (relRo->firstSec)
2465ece8a530Spatrick     ret.push_back(relRo);
2466ece8a530Spatrick 
2467ece8a530Spatrick   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2468ece8a530Spatrick   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2469ece8a530Spatrick       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2470ece8a530Spatrick     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2471ece8a530Spatrick         ->add(part.ehFrameHdr->getParent());
2472ece8a530Spatrick 
2473ece8a530Spatrick   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2474ece8a530Spatrick   // the dynamic linker fill the segment with random data.
2475ece8a530Spatrick   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2476ece8a530Spatrick     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2477ece8a530Spatrick 
2478ece8a530Spatrick   if (config->zGnustack != GnuStackKind::None) {
2479ece8a530Spatrick     // PT_GNU_STACK is a special section to tell the loader to make the
2480ece8a530Spatrick     // pages for the stack non-executable. If you really want an executable
2481ece8a530Spatrick     // stack, you can pass -z execstack, but that's not recommended for
2482ece8a530Spatrick     // security reasons.
2483ece8a530Spatrick     unsigned perm = PF_R | PF_W;
2484ece8a530Spatrick     if (config->zGnustack == GnuStackKind::Exec)
2485ece8a530Spatrick       perm |= PF_X;
2486ece8a530Spatrick     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2487ece8a530Spatrick   }
2488ece8a530Spatrick 
2489ece8a530Spatrick   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2490ece8a530Spatrick   // is expected to perform W^X violations, such as calling mprotect(2) or
2491ece8a530Spatrick   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2492ece8a530Spatrick   // OpenBSD.
2493ece8a530Spatrick   if (config->zWxneeded)
2494ece8a530Spatrick     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2495ece8a530Spatrick 
2496ece8a530Spatrick   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2497ece8a530Spatrick     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2498ece8a530Spatrick 
2499ece8a530Spatrick   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2500ece8a530Spatrick   // same alignment.
2501ece8a530Spatrick   PhdrEntry *note = nullptr;
2502ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2503ece8a530Spatrick     if (sec->partition != partNo)
2504ece8a530Spatrick       continue;
2505ece8a530Spatrick     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2506ece8a530Spatrick       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2507ece8a530Spatrick         note = addHdr(PT_NOTE, PF_R);
2508ece8a530Spatrick       note->add(sec);
2509ece8a530Spatrick     } else {
2510ece8a530Spatrick       note = nullptr;
2511ece8a530Spatrick     }
2512ece8a530Spatrick   }
2513ece8a530Spatrick   return ret;
2514ece8a530Spatrick }
2515ece8a530Spatrick 
2516ece8a530Spatrick template <class ELFT>
2517ece8a530Spatrick void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2518ece8a530Spatrick                                      unsigned pType, unsigned pFlags) {
2519ece8a530Spatrick   unsigned partNo = part.getNumber();
2520ece8a530Spatrick   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2521ece8a530Spatrick     return cmd->partition == partNo && cmd->type == shType;
2522ece8a530Spatrick   });
2523ece8a530Spatrick   if (i == outputSections.end())
2524ece8a530Spatrick     return;
2525ece8a530Spatrick 
2526ece8a530Spatrick   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2527ece8a530Spatrick   entry->add(*i);
2528ece8a530Spatrick   part.phdrs.push_back(entry);
2529ece8a530Spatrick }
2530ece8a530Spatrick 
2531ece8a530Spatrick // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2532ece8a530Spatrick // This is achieved by assigning an alignment expression to addrExpr of each
2533ece8a530Spatrick // such section.
2534ece8a530Spatrick template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2535ece8a530Spatrick   const PhdrEntry *prev;
2536ece8a530Spatrick   auto pageAlign = [&](const PhdrEntry *p) {
2537ece8a530Spatrick     OutputSection *cmd = p->firstSec;
2538bb684c34Spatrick     if (!cmd)
2539bb684c34Spatrick       return;
2540bb684c34Spatrick     cmd->alignExpr = [align = cmd->alignment]() { return align; };
2541bb684c34Spatrick     if (!cmd->addrExpr) {
2542ece8a530Spatrick       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2543ece8a530Spatrick       // padding in the file contents.
2544ece8a530Spatrick       //
2545ece8a530Spatrick       // When -z separate-code is used we must not have any overlap in pages
2546ece8a530Spatrick       // between an executable segment and a non-executable segment. We align to
2547ece8a530Spatrick       // the next maximum page size boundary on transitions between executable
2548ece8a530Spatrick       // and non-executable segments.
2549ece8a530Spatrick       //
2550ece8a530Spatrick       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2551ece8a530Spatrick       // sections will be extracted to a separate file. Align to the next
2552ece8a530Spatrick       // maximum page size boundary so that we can find the ELF header at the
2553ece8a530Spatrick       // start. We cannot benefit from overlapping p_offset ranges with the
2554ece8a530Spatrick       // previous segment anyway.
2555ece8a530Spatrick       if (config->zSeparate == SeparateSegmentKind::Loadable ||
2556ece8a530Spatrick           (config->zSeparate == SeparateSegmentKind::Code && prev &&
2557ece8a530Spatrick            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2558ece8a530Spatrick           cmd->type == SHT_LLVM_PART_EHDR)
2559ece8a530Spatrick         cmd->addrExpr = [] {
2560ece8a530Spatrick           return alignTo(script->getDot(), config->maxPageSize);
2561ece8a530Spatrick         };
2562ece8a530Spatrick       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2563ece8a530Spatrick       // it must be the RW. Align to p_align(PT_TLS) to make sure
2564ece8a530Spatrick       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2565ece8a530Spatrick       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2566ece8a530Spatrick       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2567ece8a530Spatrick       // be congruent to 0 modulo p_align(PT_TLS).
2568ece8a530Spatrick       //
2569ece8a530Spatrick       // Technically this is not required, but as of 2019, some dynamic loaders
2570ece8a530Spatrick       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2571ece8a530Spatrick       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2572ece8a530Spatrick       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2573ece8a530Spatrick       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2574ece8a530Spatrick       // blocks correctly. We need to keep the workaround for a while.
2575ece8a530Spatrick       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2576ece8a530Spatrick         cmd->addrExpr = [] {
2577ece8a530Spatrick           return alignTo(script->getDot(), config->maxPageSize) +
2578ece8a530Spatrick                  alignTo(script->getDot() % config->maxPageSize,
2579ece8a530Spatrick                          Out::tlsPhdr->p_align);
2580ece8a530Spatrick         };
2581ece8a530Spatrick       else
2582ece8a530Spatrick         cmd->addrExpr = [] {
2583ece8a530Spatrick           return alignTo(script->getDot(), config->maxPageSize) +
2584ece8a530Spatrick                  script->getDot() % config->maxPageSize;
2585ece8a530Spatrick         };
2586ece8a530Spatrick     }
2587ece8a530Spatrick   };
2588ece8a530Spatrick 
2589adae0cfdSpatrick #ifdef __OpenBSD__
2590adae0cfdSpatrick   // On i386, produce binaries that are compatible with our W^X implementation
2591adae0cfdSpatrick   if (config->emachine == EM_386) {
2592adae0cfdSpatrick     auto NXAlign = [](OutputSection *Cmd) {
2593adae0cfdSpatrick       if (Cmd && !Cmd->addrExpr)
2594adae0cfdSpatrick         Cmd->addrExpr = [=] {
2595adae0cfdSpatrick           return alignTo(script->getDot(), 0x20000000);
2596adae0cfdSpatrick         };
2597adae0cfdSpatrick     };
2598adae0cfdSpatrick 
2599adae0cfdSpatrick     for (Partition &part : partitions) {
2600adae0cfdSpatrick       PhdrEntry *firstRW = nullptr;
2601adae0cfdSpatrick       for (PhdrEntry *P : part.phdrs) {
2602adae0cfdSpatrick         if (P->p_type == PT_LOAD && (P->p_flags & PF_W)) {
2603adae0cfdSpatrick           firstRW = P;
2604adae0cfdSpatrick           break;
2605adae0cfdSpatrick         }
2606adae0cfdSpatrick       }
2607adae0cfdSpatrick 
2608adae0cfdSpatrick       if (firstRW)
2609adae0cfdSpatrick         NXAlign(firstRW->firstSec);
2610adae0cfdSpatrick     }
2611adae0cfdSpatrick   }
2612adae0cfdSpatrick #endif
2613adae0cfdSpatrick 
2614ece8a530Spatrick   for (Partition &part : partitions) {
2615ece8a530Spatrick     prev = nullptr;
2616ece8a530Spatrick     for (const PhdrEntry *p : part.phdrs)
2617ece8a530Spatrick       if (p->p_type == PT_LOAD && p->firstSec) {
2618ece8a530Spatrick         pageAlign(p);
2619ece8a530Spatrick         prev = p;
2620ece8a530Spatrick       }
2621ece8a530Spatrick   }
2622ece8a530Spatrick }
2623ece8a530Spatrick 
2624ece8a530Spatrick // Compute an in-file position for a given section. The file offset must be the
2625ece8a530Spatrick // same with its virtual address modulo the page size, so that the loader can
2626ece8a530Spatrick // load executables without any address adjustment.
2627ece8a530Spatrick static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2628ece8a530Spatrick   // The first section in a PT_LOAD has to have congruent offset and address
2629ece8a530Spatrick   // modulo the maximum page size.
2630ece8a530Spatrick   if (os->ptLoad && os->ptLoad->firstSec == os)
2631ece8a530Spatrick     return alignTo(off, os->ptLoad->p_align, os->addr);
2632ece8a530Spatrick 
2633ece8a530Spatrick   // File offsets are not significant for .bss sections other than the first one
2634ece8a530Spatrick   // in a PT_LOAD. By convention, we keep section offsets monotonically
2635ece8a530Spatrick   // increasing rather than setting to zero.
2636ece8a530Spatrick    if (os->type == SHT_NOBITS)
2637ece8a530Spatrick      return off;
2638ece8a530Spatrick 
2639ece8a530Spatrick   // If the section is not in a PT_LOAD, we just have to align it.
2640ece8a530Spatrick   if (!os->ptLoad)
2641ece8a530Spatrick     return alignTo(off, os->alignment);
2642ece8a530Spatrick 
2643ece8a530Spatrick   // If two sections share the same PT_LOAD the file offset is calculated
2644ece8a530Spatrick   // using this formula: Off2 = Off1 + (VA2 - VA1).
2645ece8a530Spatrick   OutputSection *first = os->ptLoad->firstSec;
2646ece8a530Spatrick   return first->offset + os->addr - first->addr;
2647ece8a530Spatrick }
2648ece8a530Spatrick 
2649ece8a530Spatrick // Set an in-file position to a given section and returns the end position of
2650ece8a530Spatrick // the section.
2651ece8a530Spatrick static uint64_t setFileOffset(OutputSection *os, uint64_t off) {
2652ece8a530Spatrick   off = computeFileOffset(os, off);
2653ece8a530Spatrick   os->offset = off;
2654ece8a530Spatrick 
2655ece8a530Spatrick   if (os->type == SHT_NOBITS)
2656ece8a530Spatrick     return off;
2657ece8a530Spatrick   return off + os->size;
2658ece8a530Spatrick }
2659ece8a530Spatrick 
2660ece8a530Spatrick template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2661*a0747c9fSpatrick   // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2662*a0747c9fSpatrick   auto needsOffset = [](OutputSection &sec) {
2663*a0747c9fSpatrick     return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2664*a0747c9fSpatrick   };
2665*a0747c9fSpatrick   uint64_t minAddr = UINT64_MAX;
2666ece8a530Spatrick   for (OutputSection *sec : outputSections)
2667*a0747c9fSpatrick     if (needsOffset(*sec)) {
2668*a0747c9fSpatrick       sec->offset = sec->getLMA();
2669*a0747c9fSpatrick       minAddr = std::min(minAddr, sec->offset);
2670*a0747c9fSpatrick     }
2671*a0747c9fSpatrick 
2672*a0747c9fSpatrick   // Sections are laid out at LMA minus minAddr.
2673*a0747c9fSpatrick   fileSize = 0;
2674*a0747c9fSpatrick   for (OutputSection *sec : outputSections)
2675*a0747c9fSpatrick     if (needsOffset(*sec)) {
2676*a0747c9fSpatrick       sec->offset -= minAddr;
2677*a0747c9fSpatrick       fileSize = std::max(fileSize, sec->offset + sec->size);
2678*a0747c9fSpatrick     }
2679ece8a530Spatrick }
2680ece8a530Spatrick 
2681ece8a530Spatrick static std::string rangeToString(uint64_t addr, uint64_t len) {
2682ece8a530Spatrick   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2683ece8a530Spatrick }
2684ece8a530Spatrick 
2685ece8a530Spatrick // Assign file offsets to output sections.
2686ece8a530Spatrick template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2687ece8a530Spatrick   uint64_t off = 0;
2688ece8a530Spatrick   off = setFileOffset(Out::elfHeader, off);
2689ece8a530Spatrick   off = setFileOffset(Out::programHeaders, off);
2690ece8a530Spatrick 
2691ece8a530Spatrick   PhdrEntry *lastRX = nullptr;
2692ece8a530Spatrick   for (Partition &part : partitions)
2693ece8a530Spatrick     for (PhdrEntry *p : part.phdrs)
2694ece8a530Spatrick       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2695ece8a530Spatrick         lastRX = p;
2696ece8a530Spatrick 
2697*a0747c9fSpatrick   // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2698*a0747c9fSpatrick   // will not occupy file offsets contained by a PT_LOAD.
2699ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2700*a0747c9fSpatrick     if (!(sec->flags & SHF_ALLOC))
2701*a0747c9fSpatrick       continue;
2702ece8a530Spatrick     off = setFileOffset(sec, off);
2703ece8a530Spatrick 
2704ece8a530Spatrick     // If this is a last section of the last executable segment and that
2705ece8a530Spatrick     // segment is the last loadable segment, align the offset of the
2706ece8a530Spatrick     // following section to avoid loading non-segments parts of the file.
2707ece8a530Spatrick     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2708ece8a530Spatrick         lastRX->lastSec == sec)
2709ece8a530Spatrick       off = alignTo(off, config->commonPageSize);
2710ece8a530Spatrick   }
2711*a0747c9fSpatrick   for (OutputSection *sec : outputSections)
2712*a0747c9fSpatrick     if (!(sec->flags & SHF_ALLOC))
2713*a0747c9fSpatrick       off = setFileOffset(sec, off);
2714ece8a530Spatrick 
2715ece8a530Spatrick   sectionHeaderOff = alignTo(off, config->wordsize);
2716ece8a530Spatrick   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2717ece8a530Spatrick 
2718ece8a530Spatrick   // Our logic assumes that sections have rising VA within the same segment.
2719ece8a530Spatrick   // With use of linker scripts it is possible to violate this rule and get file
2720ece8a530Spatrick   // offset overlaps or overflows. That should never happen with a valid script
2721ece8a530Spatrick   // which does not move the location counter backwards and usually scripts do
2722ece8a530Spatrick   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2723ece8a530Spatrick   // kernel, which control segment distribution explicitly and move the counter
2724ece8a530Spatrick   // backwards, so we have to allow doing that to support linking them. We
2725ece8a530Spatrick   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2726ece8a530Spatrick   // we want to prevent file size overflows because it would crash the linker.
2727ece8a530Spatrick   for (OutputSection *sec : outputSections) {
2728ece8a530Spatrick     if (sec->type == SHT_NOBITS)
2729ece8a530Spatrick       continue;
2730ece8a530Spatrick     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2731ece8a530Spatrick       error("unable to place section " + sec->name + " at file offset " +
2732ece8a530Spatrick             rangeToString(sec->offset, sec->size) +
2733ece8a530Spatrick             "; check your linker script for overflows");
2734ece8a530Spatrick   }
2735ece8a530Spatrick }
2736ece8a530Spatrick 
2737ece8a530Spatrick // Finalize the program headers. We call this function after we assign
2738ece8a530Spatrick // file offsets and VAs to all sections.
2739ece8a530Spatrick template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2740ece8a530Spatrick   for (PhdrEntry *p : part.phdrs) {
2741ece8a530Spatrick     OutputSection *first = p->firstSec;
2742ece8a530Spatrick     OutputSection *last = p->lastSec;
2743ece8a530Spatrick 
2744ece8a530Spatrick     if (first) {
2745ece8a530Spatrick       p->p_filesz = last->offset - first->offset;
2746ece8a530Spatrick       if (last->type != SHT_NOBITS)
2747ece8a530Spatrick         p->p_filesz += last->size;
2748ece8a530Spatrick 
2749ece8a530Spatrick       p->p_memsz = last->addr + last->size - first->addr;
2750ece8a530Spatrick       p->p_offset = first->offset;
2751ece8a530Spatrick       p->p_vaddr = first->addr;
2752ece8a530Spatrick 
2753ece8a530Spatrick       // File offsets in partitions other than the main partition are relative
2754ece8a530Spatrick       // to the offset of the ELF headers. Perform that adjustment now.
2755ece8a530Spatrick       if (part.elfHeader)
2756ece8a530Spatrick         p->p_offset -= part.elfHeader->getParent()->offset;
2757ece8a530Spatrick 
2758ece8a530Spatrick       if (!p->hasLMA)
2759ece8a530Spatrick         p->p_paddr = first->getLMA();
2760ece8a530Spatrick     }
2761ece8a530Spatrick 
2762ece8a530Spatrick     if (p->p_type == PT_GNU_RELRO) {
2763ece8a530Spatrick       p->p_align = 1;
2764ece8a530Spatrick       // musl/glibc ld.so rounds the size down, so we need to round up
2765ece8a530Spatrick       // to protect the last page. This is a no-op on FreeBSD which always
2766ece8a530Spatrick       // rounds up.
2767ece8a530Spatrick       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
2768ece8a530Spatrick                    p->p_offset;
2769ece8a530Spatrick     }
2770ece8a530Spatrick   }
2771ece8a530Spatrick }
2772ece8a530Spatrick 
2773ece8a530Spatrick // A helper struct for checkSectionOverlap.
2774ece8a530Spatrick namespace {
2775ece8a530Spatrick struct SectionOffset {
2776ece8a530Spatrick   OutputSection *sec;
2777ece8a530Spatrick   uint64_t offset;
2778ece8a530Spatrick };
2779ece8a530Spatrick } // namespace
2780ece8a530Spatrick 
2781ece8a530Spatrick // Check whether sections overlap for a specific address range (file offsets,
2782ece8a530Spatrick // load and virtual addresses).
2783ece8a530Spatrick static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2784ece8a530Spatrick                          bool isVirtualAddr) {
2785ece8a530Spatrick   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2786ece8a530Spatrick     return a.offset < b.offset;
2787ece8a530Spatrick   });
2788ece8a530Spatrick 
2789ece8a530Spatrick   // Finding overlap is easy given a vector is sorted by start position.
2790ece8a530Spatrick   // If an element starts before the end of the previous element, they overlap.
2791ece8a530Spatrick   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2792ece8a530Spatrick     SectionOffset a = sections[i - 1];
2793ece8a530Spatrick     SectionOffset b = sections[i];
2794ece8a530Spatrick     if (b.offset >= a.offset + a.sec->size)
2795ece8a530Spatrick       continue;
2796ece8a530Spatrick 
2797ece8a530Spatrick     // If both sections are in OVERLAY we allow the overlapping of virtual
2798ece8a530Spatrick     // addresses, because it is what OVERLAY was designed for.
2799ece8a530Spatrick     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2800ece8a530Spatrick       continue;
2801ece8a530Spatrick 
2802ece8a530Spatrick     errorOrWarn("section " + a.sec->name + " " + name +
2803ece8a530Spatrick                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2804ece8a530Spatrick                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2805ece8a530Spatrick                 b.sec->name + " range is " +
2806ece8a530Spatrick                 rangeToString(b.offset, b.sec->size));
2807ece8a530Spatrick   }
2808ece8a530Spatrick }
2809ece8a530Spatrick 
2810ece8a530Spatrick // Check for overlapping sections and address overflows.
2811ece8a530Spatrick //
2812ece8a530Spatrick // In this function we check that none of the output sections have overlapping
2813ece8a530Spatrick // file offsets. For SHF_ALLOC sections we also check that the load address
2814ece8a530Spatrick // ranges and the virtual address ranges don't overlap
2815ece8a530Spatrick template <class ELFT> void Writer<ELFT>::checkSections() {
2816ece8a530Spatrick   // First, check that section's VAs fit in available address space for target.
2817ece8a530Spatrick   for (OutputSection *os : outputSections)
2818ece8a530Spatrick     if ((os->addr + os->size < os->addr) ||
2819ece8a530Spatrick         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2820ece8a530Spatrick       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2821ece8a530Spatrick                   " of size 0x" + utohexstr(os->size) +
2822ece8a530Spatrick                   " exceeds available address space");
2823ece8a530Spatrick 
2824ece8a530Spatrick   // Check for overlapping file offsets. In this case we need to skip any
2825ece8a530Spatrick   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2826ece8a530Spatrick   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2827ece8a530Spatrick   // binary is specified only add SHF_ALLOC sections are added to the output
2828ece8a530Spatrick   // file so we skip any non-allocated sections in that case.
2829ece8a530Spatrick   std::vector<SectionOffset> fileOffs;
2830ece8a530Spatrick   for (OutputSection *sec : outputSections)
2831ece8a530Spatrick     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2832ece8a530Spatrick         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2833ece8a530Spatrick       fileOffs.push_back({sec, sec->offset});
2834ece8a530Spatrick   checkOverlap("file", fileOffs, false);
2835ece8a530Spatrick 
2836ece8a530Spatrick   // When linking with -r there is no need to check for overlapping virtual/load
2837ece8a530Spatrick   // addresses since those addresses will only be assigned when the final
2838ece8a530Spatrick   // executable/shared object is created.
2839ece8a530Spatrick   if (config->relocatable)
2840ece8a530Spatrick     return;
2841ece8a530Spatrick 
2842ece8a530Spatrick   // Checking for overlapping virtual and load addresses only needs to take
2843ece8a530Spatrick   // into account SHF_ALLOC sections since others will not be loaded.
2844ece8a530Spatrick   // Furthermore, we also need to skip SHF_TLS sections since these will be
2845ece8a530Spatrick   // mapped to other addresses at runtime and can therefore have overlapping
2846ece8a530Spatrick   // ranges in the file.
2847ece8a530Spatrick   std::vector<SectionOffset> vmas;
2848ece8a530Spatrick   for (OutputSection *sec : outputSections)
2849ece8a530Spatrick     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2850ece8a530Spatrick       vmas.push_back({sec, sec->addr});
2851ece8a530Spatrick   checkOverlap("virtual address", vmas, true);
2852ece8a530Spatrick 
2853ece8a530Spatrick   // Finally, check that the load addresses don't overlap. This will usually be
2854ece8a530Spatrick   // the same as the virtual addresses but can be different when using a linker
2855ece8a530Spatrick   // script with AT().
2856ece8a530Spatrick   std::vector<SectionOffset> lmas;
2857ece8a530Spatrick   for (OutputSection *sec : outputSections)
2858ece8a530Spatrick     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2859ece8a530Spatrick       lmas.push_back({sec, sec->getLMA()});
2860ece8a530Spatrick   checkOverlap("load address", lmas, false);
2861ece8a530Spatrick }
2862ece8a530Spatrick 
2863ece8a530Spatrick // The entry point address is chosen in the following ways.
2864ece8a530Spatrick //
2865ece8a530Spatrick // 1. the '-e' entry command-line option;
2866ece8a530Spatrick // 2. the ENTRY(symbol) command in a linker control script;
2867ece8a530Spatrick // 3. the value of the symbol _start, if present;
2868ece8a530Spatrick // 4. the number represented by the entry symbol, if it is a number;
2869ece8a530Spatrick // 5. the address of the first byte of the .text section, if present;
2870ece8a530Spatrick // 6. the address 0.
2871ece8a530Spatrick static uint64_t getEntryAddr() {
2872ece8a530Spatrick   // Case 1, 2 or 3
2873ece8a530Spatrick   if (Symbol *b = symtab->find(config->entry))
2874ece8a530Spatrick     return b->getVA();
2875ece8a530Spatrick 
2876ece8a530Spatrick   // Case 4
2877ece8a530Spatrick   uint64_t addr;
2878ece8a530Spatrick   if (to_integer(config->entry, addr))
2879ece8a530Spatrick     return addr;
2880ece8a530Spatrick 
2881ece8a530Spatrick   // Case 5
2882ece8a530Spatrick   if (OutputSection *sec = findSection(".text")) {
2883ece8a530Spatrick     if (config->warnMissingEntry)
2884ece8a530Spatrick       warn("cannot find entry symbol " + config->entry + "; defaulting to 0x" +
2885ece8a530Spatrick            utohexstr(sec->addr));
2886ece8a530Spatrick     return sec->addr;
2887ece8a530Spatrick   }
2888ece8a530Spatrick 
2889ece8a530Spatrick   // Case 6
2890ece8a530Spatrick   if (config->warnMissingEntry)
2891ece8a530Spatrick     warn("cannot find entry symbol " + config->entry +
2892ece8a530Spatrick          "; not setting start address");
2893ece8a530Spatrick   return 0;
2894ece8a530Spatrick }
2895ece8a530Spatrick 
2896ece8a530Spatrick static uint16_t getELFType() {
2897ece8a530Spatrick   if (config->isPic)
2898ece8a530Spatrick     return ET_DYN;
2899ece8a530Spatrick   if (config->relocatable)
2900ece8a530Spatrick     return ET_REL;
2901ece8a530Spatrick   return ET_EXEC;
2902ece8a530Spatrick }
2903ece8a530Spatrick 
2904ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeHeader() {
2905ece8a530Spatrick   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2906ece8a530Spatrick   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2907ece8a530Spatrick 
2908ece8a530Spatrick   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2909ece8a530Spatrick   eHdr->e_type = getELFType();
2910ece8a530Spatrick   eHdr->e_entry = getEntryAddr();
2911ece8a530Spatrick   eHdr->e_shoff = sectionHeaderOff;
2912ece8a530Spatrick 
2913ece8a530Spatrick   // Write the section header table.
2914ece8a530Spatrick   //
2915ece8a530Spatrick   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2916ece8a530Spatrick   // and e_shstrndx fields. When the value of one of these fields exceeds
2917ece8a530Spatrick   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2918ece8a530Spatrick   // use fields in the section header at index 0 to store
2919ece8a530Spatrick   // the value. The sentinel values and fields are:
2920ece8a530Spatrick   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2921ece8a530Spatrick   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2922ece8a530Spatrick   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2923ece8a530Spatrick   size_t num = outputSections.size() + 1;
2924ece8a530Spatrick   if (num >= SHN_LORESERVE)
2925ece8a530Spatrick     sHdrs->sh_size = num;
2926ece8a530Spatrick   else
2927ece8a530Spatrick     eHdr->e_shnum = num;
2928ece8a530Spatrick 
2929ece8a530Spatrick   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2930ece8a530Spatrick   if (strTabIndex >= SHN_LORESERVE) {
2931ece8a530Spatrick     sHdrs->sh_link = strTabIndex;
2932ece8a530Spatrick     eHdr->e_shstrndx = SHN_XINDEX;
2933ece8a530Spatrick   } else {
2934ece8a530Spatrick     eHdr->e_shstrndx = strTabIndex;
2935ece8a530Spatrick   }
2936ece8a530Spatrick 
2937ece8a530Spatrick   for (OutputSection *sec : outputSections)
2938ece8a530Spatrick     sec->writeHeaderTo<ELFT>(++sHdrs);
2939ece8a530Spatrick }
2940ece8a530Spatrick 
2941ece8a530Spatrick // Open a result file.
2942ece8a530Spatrick template <class ELFT> void Writer<ELFT>::openFile() {
2943ece8a530Spatrick   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2944ece8a530Spatrick   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2945*a0747c9fSpatrick     std::string msg;
2946*a0747c9fSpatrick     raw_string_ostream s(msg);
2947*a0747c9fSpatrick     s << "output file too large: " << Twine(fileSize) << " bytes\n"
2948*a0747c9fSpatrick       << "section sizes:\n";
2949*a0747c9fSpatrick     for (OutputSection *os : outputSections)
2950*a0747c9fSpatrick       s << os->name << ' ' << os->size << "\n";
2951*a0747c9fSpatrick     error(s.str());
2952ece8a530Spatrick     return;
2953ece8a530Spatrick   }
2954ece8a530Spatrick 
2955ece8a530Spatrick   unlinkAsync(config->outputFile);
2956ece8a530Spatrick   unsigned flags = 0;
2957ece8a530Spatrick   if (!config->relocatable)
2958ece8a530Spatrick     flags |= FileOutputBuffer::F_executable;
2959ece8a530Spatrick   if (!config->mmapOutputFile)
2960ece8a530Spatrick     flags |= FileOutputBuffer::F_no_mmap;
2961ece8a530Spatrick   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2962ece8a530Spatrick       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2963ece8a530Spatrick 
2964ece8a530Spatrick   if (!bufferOrErr) {
2965ece8a530Spatrick     error("failed to open " + config->outputFile + ": " +
2966ece8a530Spatrick           llvm::toString(bufferOrErr.takeError()));
2967ece8a530Spatrick     return;
2968ece8a530Spatrick   }
2969ece8a530Spatrick   buffer = std::move(*bufferOrErr);
2970ece8a530Spatrick   Out::bufferStart = buffer->getBufferStart();
2971ece8a530Spatrick }
2972ece8a530Spatrick 
2973ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2974ece8a530Spatrick   for (OutputSection *sec : outputSections)
2975ece8a530Spatrick     if (sec->flags & SHF_ALLOC)
2976ece8a530Spatrick       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2977ece8a530Spatrick }
2978ece8a530Spatrick 
2979ece8a530Spatrick static void fillTrap(uint8_t *i, uint8_t *end) {
2980ece8a530Spatrick   for (; i + 4 <= end; i += 4)
2981ece8a530Spatrick     memcpy(i, &target->trapInstr, 4);
2982ece8a530Spatrick }
2983ece8a530Spatrick 
2984ece8a530Spatrick // Fill the last page of executable segments with trap instructions
2985ece8a530Spatrick // instead of leaving them as zero. Even though it is not required by any
2986ece8a530Spatrick // standard, it is in general a good thing to do for security reasons.
2987ece8a530Spatrick //
2988ece8a530Spatrick // We'll leave other pages in segments as-is because the rest will be
2989ece8a530Spatrick // overwritten by output sections.
2990ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2991ece8a530Spatrick   for (Partition &part : partitions) {
2992ece8a530Spatrick     // Fill the last page.
2993ece8a530Spatrick     for (PhdrEntry *p : part.phdrs)
2994ece8a530Spatrick       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2995ece8a530Spatrick         fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz,
2996ece8a530Spatrick                                               config->commonPageSize),
2997ece8a530Spatrick                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2998ece8a530Spatrick                                             config->commonPageSize));
2999ece8a530Spatrick 
3000ece8a530Spatrick     // Round up the file size of the last segment to the page boundary iff it is
3001ece8a530Spatrick     // an executable segment to ensure that other tools don't accidentally
3002ece8a530Spatrick     // trim the instruction padding (e.g. when stripping the file).
3003ece8a530Spatrick     PhdrEntry *last = nullptr;
3004ece8a530Spatrick     for (PhdrEntry *p : part.phdrs)
3005ece8a530Spatrick       if (p->p_type == PT_LOAD)
3006ece8a530Spatrick         last = p;
3007ece8a530Spatrick 
3008ece8a530Spatrick     if (last && (last->p_flags & PF_X))
3009ece8a530Spatrick       last->p_memsz = last->p_filesz =
3010ece8a530Spatrick           alignTo(last->p_filesz, config->commonPageSize);
3011ece8a530Spatrick   }
3012ece8a530Spatrick }
3013ece8a530Spatrick 
3014ece8a530Spatrick // Write section contents to a mmap'ed file.
3015ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeSections() {
3016ece8a530Spatrick   // In -r or -emit-relocs mode, write the relocation sections first as in
3017ece8a530Spatrick   // ELf_Rel targets we might find out that we need to modify the relocated
3018ece8a530Spatrick   // section while doing it.
3019ece8a530Spatrick   for (OutputSection *sec : outputSections)
3020ece8a530Spatrick     if (sec->type == SHT_REL || sec->type == SHT_RELA)
3021ece8a530Spatrick       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
3022ece8a530Spatrick 
3023ece8a530Spatrick   for (OutputSection *sec : outputSections)
3024ece8a530Spatrick     if (sec->type != SHT_REL && sec->type != SHT_RELA)
3025ece8a530Spatrick       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
3026ece8a530Spatrick 
3027*a0747c9fSpatrick   // Finally, check that all dynamic relocation addends were written correctly.
3028*a0747c9fSpatrick   if (config->checkDynamicRelocs && config->writeAddends) {
3029*a0747c9fSpatrick     for (OutputSection *sec : outputSections)
3030*a0747c9fSpatrick       if (sec->type == SHT_REL || sec->type == SHT_RELA)
3031*a0747c9fSpatrick         sec->checkDynRelAddends(Out::bufferStart);
3032ece8a530Spatrick   }
3033ece8a530Spatrick }
3034ece8a530Spatrick 
3035ece8a530Spatrick // Computes a hash value of Data using a given hash function.
3036ece8a530Spatrick // In order to utilize multiple cores, we first split data into 1MB
3037ece8a530Spatrick // chunks, compute a hash for each chunk, and then compute a hash value
3038ece8a530Spatrick // of the hash values.
3039ece8a530Spatrick static void
3040ece8a530Spatrick computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
3041ece8a530Spatrick             llvm::ArrayRef<uint8_t> data,
3042ece8a530Spatrick             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
3043ece8a530Spatrick   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
3044ece8a530Spatrick   std::vector<uint8_t> hashes(chunks.size() * hashBuf.size());
3045ece8a530Spatrick 
3046ece8a530Spatrick   // Compute hash values.
3047ece8a530Spatrick   parallelForEachN(0, chunks.size(), [&](size_t i) {
3048ece8a530Spatrick     hashFn(hashes.data() + i * hashBuf.size(), chunks[i]);
3049ece8a530Spatrick   });
3050ece8a530Spatrick 
3051ece8a530Spatrick   // Write to the final output buffer.
3052ece8a530Spatrick   hashFn(hashBuf.data(), hashes);
3053ece8a530Spatrick }
3054ece8a530Spatrick 
3055ece8a530Spatrick template <class ELFT> void Writer<ELFT>::writeBuildId() {
3056ece8a530Spatrick   if (!mainPart->buildId || !mainPart->buildId->getParent())
3057ece8a530Spatrick     return;
3058ece8a530Spatrick 
3059ece8a530Spatrick   if (config->buildId == BuildIdKind::Hexstring) {
3060ece8a530Spatrick     for (Partition &part : partitions)
3061ece8a530Spatrick       part.buildId->writeBuildId(config->buildIdVector);
3062ece8a530Spatrick     return;
3063ece8a530Spatrick   }
3064ece8a530Spatrick 
3065ece8a530Spatrick   // Compute a hash of all sections of the output file.
3066ece8a530Spatrick   size_t hashSize = mainPart->buildId->hashSize;
3067ece8a530Spatrick   std::vector<uint8_t> buildId(hashSize);
3068ece8a530Spatrick   llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)};
3069ece8a530Spatrick 
3070ece8a530Spatrick   switch (config->buildId) {
3071ece8a530Spatrick   case BuildIdKind::Fast:
3072ece8a530Spatrick     computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
3073ece8a530Spatrick       write64le(dest, xxHash64(arr));
3074ece8a530Spatrick     });
3075ece8a530Spatrick     break;
3076ece8a530Spatrick   case BuildIdKind::Md5:
3077ece8a530Spatrick     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3078ece8a530Spatrick       memcpy(dest, MD5::hash(arr).data(), hashSize);
3079ece8a530Spatrick     });
3080ece8a530Spatrick     break;
3081ece8a530Spatrick   case BuildIdKind::Sha1:
3082ece8a530Spatrick     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3083ece8a530Spatrick       memcpy(dest, SHA1::hash(arr).data(), hashSize);
3084ece8a530Spatrick     });
3085ece8a530Spatrick     break;
3086ece8a530Spatrick   case BuildIdKind::Uuid:
3087ece8a530Spatrick     if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize))
3088ece8a530Spatrick       error("entropy source failure: " + ec.message());
3089ece8a530Spatrick     break;
3090ece8a530Spatrick   default:
3091ece8a530Spatrick     llvm_unreachable("unknown BuildIdKind");
3092ece8a530Spatrick   }
3093ece8a530Spatrick   for (Partition &part : partitions)
3094ece8a530Spatrick     part.buildId->writeBuildId(buildId);
3095ece8a530Spatrick }
3096ece8a530Spatrick 
3097bb684c34Spatrick template void elf::createSyntheticSections<ELF32LE>();
3098bb684c34Spatrick template void elf::createSyntheticSections<ELF32BE>();
3099bb684c34Spatrick template void elf::createSyntheticSections<ELF64LE>();
3100bb684c34Spatrick template void elf::createSyntheticSections<ELF64BE>();
3101ece8a530Spatrick 
3102bb684c34Spatrick template void elf::writeResult<ELF32LE>();
3103bb684c34Spatrick template void elf::writeResult<ELF32BE>();
3104bb684c34Spatrick template void elf::writeResult<ELF64LE>();
3105bb684c34Spatrick template void elf::writeResult<ELF64BE>();
3106