xref: /freebsd/contrib/llvm-project/lld/ELF/Writer.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===- Writer.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Writer.h"
100b57cec5SDimitry Andric #include "AArch64ErrataFix.h"
1185868e8aSDimitry Andric #include "ARMErrataFix.h"
120b57cec5SDimitry Andric #include "CallGraphSort.h"
130b57cec5SDimitry Andric #include "Config.h"
140b57cec5SDimitry Andric #include "LinkerScript.h"
150b57cec5SDimitry Andric #include "MapFile.h"
160b57cec5SDimitry Andric #include "OutputSections.h"
170b57cec5SDimitry Andric #include "Relocations.h"
180b57cec5SDimitry Andric #include "SymbolTable.h"
190b57cec5SDimitry Andric #include "Symbols.h"
200b57cec5SDimitry Andric #include "SyntheticSections.h"
210b57cec5SDimitry Andric #include "Target.h"
220b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
230b57cec5SDimitry Andric #include "lld/Common/Memory.h"
240b57cec5SDimitry Andric #include "lld/Common/Strings.h"
250b57cec5SDimitry Andric #include "lld/Common/Threads.h"
260b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
280b57cec5SDimitry Andric #include "llvm/Support/RandomNumberGenerator.h"
290b57cec5SDimitry Andric #include "llvm/Support/SHA1.h"
300b57cec5SDimitry Andric #include "llvm/Support/xxhash.h"
310b57cec5SDimitry Andric #include <climits>
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric using namespace llvm;
340b57cec5SDimitry Andric using namespace llvm::ELF;
350b57cec5SDimitry Andric using namespace llvm::object;
360b57cec5SDimitry Andric using namespace llvm::support;
370b57cec5SDimitry Andric using namespace llvm::support::endian;
380b57cec5SDimitry Andric 
3985868e8aSDimitry Andric namespace lld {
4085868e8aSDimitry Andric namespace elf {
410b57cec5SDimitry Andric namespace {
420b57cec5SDimitry Andric // The writer writes a SymbolTable result to a file.
430b57cec5SDimitry Andric template <class ELFT> class Writer {
440b57cec5SDimitry Andric public:
450b57cec5SDimitry Andric   Writer() : buffer(errorHandler().outputBuffer) {}
460b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
470b57cec5SDimitry Andric   using Elf_Ehdr = typename ELFT::Ehdr;
480b57cec5SDimitry Andric   using Elf_Phdr = typename ELFT::Phdr;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   void run();
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric private:
530b57cec5SDimitry Andric   void copyLocalSymbols();
540b57cec5SDimitry Andric   void addSectionSymbols();
550b57cec5SDimitry Andric   void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> fn);
560b57cec5SDimitry Andric   void sortSections();
570b57cec5SDimitry Andric   void resolveShfLinkOrder();
580b57cec5SDimitry Andric   void finalizeAddressDependentContent();
590b57cec5SDimitry Andric   void sortInputSections();
600b57cec5SDimitry Andric   void finalizeSections();
610b57cec5SDimitry Andric   void checkExecuteOnly();
620b57cec5SDimitry Andric   void setReservedSymbolSections();
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric   std::vector<PhdrEntry *> createPhdrs(Partition &part);
650b57cec5SDimitry Andric   void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
660b57cec5SDimitry Andric                          unsigned pFlags);
670b57cec5SDimitry Andric   void assignFileOffsets();
680b57cec5SDimitry Andric   void assignFileOffsetsBinary();
690b57cec5SDimitry Andric   void setPhdrs(Partition &part);
700b57cec5SDimitry Andric   void checkSections();
710b57cec5SDimitry Andric   void fixSectionAlignments();
720b57cec5SDimitry Andric   void openFile();
730b57cec5SDimitry Andric   void writeTrapInstr();
740b57cec5SDimitry Andric   void writeHeader();
750b57cec5SDimitry Andric   void writeSections();
760b57cec5SDimitry Andric   void writeSectionsBinary();
770b57cec5SDimitry Andric   void writeBuildId();
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   std::unique_ptr<FileOutputBuffer> &buffer;
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric   void addRelIpltSymbols();
820b57cec5SDimitry Andric   void addStartEndSymbols();
830b57cec5SDimitry Andric   void addStartStopSymbols(OutputSection *sec);
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   uint64_t fileSize;
860b57cec5SDimitry Andric   uint64_t sectionHeaderOff;
870b57cec5SDimitry Andric };
880b57cec5SDimitry Andric } // anonymous namespace
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric static bool isSectionPrefix(StringRef prefix, StringRef name) {
910b57cec5SDimitry Andric   return name.startswith(prefix) || name == prefix.drop_back();
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
9485868e8aSDimitry Andric StringRef getOutputSectionName(const InputSectionBase *s) {
950b57cec5SDimitry Andric   if (config->relocatable)
960b57cec5SDimitry Andric     return s->name;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
990b57cec5SDimitry Andric   // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
1000b57cec5SDimitry Andric   // technically required, but not doing it is odd). This code guarantees that.
1010b57cec5SDimitry Andric   if (auto *isec = dyn_cast<InputSection>(s)) {
1020b57cec5SDimitry Andric     if (InputSectionBase *rel = isec->getRelocatedSection()) {
1030b57cec5SDimitry Andric       OutputSection *out = rel->getOutputSection();
1040b57cec5SDimitry Andric       if (s->type == SHT_RELA)
1050b57cec5SDimitry Andric         return saver.save(".rela" + out->name);
1060b57cec5SDimitry Andric       return saver.save(".rel" + out->name);
1070b57cec5SDimitry Andric     }
1080b57cec5SDimitry Andric   }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // This check is for -z keep-text-section-prefix.  This option separates text
1110b57cec5SDimitry Andric   // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
1120b57cec5SDimitry Andric   // ".text.exit".
1130b57cec5SDimitry Andric   // When enabled, this allows identifying the hot code region (.text.hot) in
1140b57cec5SDimitry Andric   // the final binary which can be selectively mapped to huge pages or mlocked,
1150b57cec5SDimitry Andric   // for instance.
1160b57cec5SDimitry Andric   if (config->zKeepTextSectionPrefix)
1170b57cec5SDimitry Andric     for (StringRef v :
1180b57cec5SDimitry Andric          {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."})
1190b57cec5SDimitry Andric       if (isSectionPrefix(v, s->name))
1200b57cec5SDimitry Andric         return v.drop_back();
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   for (StringRef v :
1230b57cec5SDimitry Andric        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
1240b57cec5SDimitry Andric         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
1250b57cec5SDimitry Andric         ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."})
1260b57cec5SDimitry Andric     if (isSectionPrefix(v, s->name))
1270b57cec5SDimitry Andric       return v.drop_back();
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   // CommonSection is identified as "COMMON" in linker scripts.
1300b57cec5SDimitry Andric   // By default, it should go to .bss section.
1310b57cec5SDimitry Andric   if (s->name == "COMMON")
1320b57cec5SDimitry Andric     return ".bss";
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   return s->name;
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric static bool needsInterpSection() {
138*480093f4SDimitry Andric   return !config->shared && !config->dynamicLinker.empty() &&
1390b57cec5SDimitry Andric          script->needsInterpSection();
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
14285868e8aSDimitry Andric template <class ELFT> void writeResult() { Writer<ELFT>().run(); }
1430b57cec5SDimitry Andric 
14485868e8aSDimitry Andric static void removeEmptyPTLoad(std::vector<PhdrEntry *> &phdrs) {
1450b57cec5SDimitry Andric   llvm::erase_if(phdrs, [&](const PhdrEntry *p) {
1460b57cec5SDimitry Andric     if (p->p_type != PT_LOAD)
1470b57cec5SDimitry Andric       return false;
1480b57cec5SDimitry Andric     if (!p->firstSec)
1490b57cec5SDimitry Andric       return true;
1500b57cec5SDimitry Andric     uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
1510b57cec5SDimitry Andric     return size == 0;
1520b57cec5SDimitry Andric   });
1530b57cec5SDimitry Andric }
1540b57cec5SDimitry Andric 
15585868e8aSDimitry Andric void copySectionsIntoPartitions() {
1560b57cec5SDimitry Andric   std::vector<InputSectionBase *> newSections;
1570b57cec5SDimitry Andric   for (unsigned part = 2; part != partitions.size() + 1; ++part) {
1580b57cec5SDimitry Andric     for (InputSectionBase *s : inputSections) {
1590b57cec5SDimitry Andric       if (!(s->flags & SHF_ALLOC) || !s->isLive())
1600b57cec5SDimitry Andric         continue;
1610b57cec5SDimitry Andric       InputSectionBase *copy;
1620b57cec5SDimitry Andric       if (s->type == SHT_NOTE)
1630b57cec5SDimitry Andric         copy = make<InputSection>(cast<InputSection>(*s));
1640b57cec5SDimitry Andric       else if (auto *es = dyn_cast<EhInputSection>(s))
1650b57cec5SDimitry Andric         copy = make<EhInputSection>(*es);
1660b57cec5SDimitry Andric       else
1670b57cec5SDimitry Andric         continue;
1680b57cec5SDimitry Andric       copy->partition = part;
1690b57cec5SDimitry Andric       newSections.push_back(copy);
1700b57cec5SDimitry Andric     }
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   inputSections.insert(inputSections.end(), newSections.begin(),
1740b57cec5SDimitry Andric                        newSections.end());
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
17785868e8aSDimitry Andric void combineEhSections() {
1780b57cec5SDimitry Andric   for (InputSectionBase *&s : inputSections) {
1790b57cec5SDimitry Andric     // Ignore dead sections and the partition end marker (.part.end),
1800b57cec5SDimitry Andric     // whose partition number is out of bounds.
1810b57cec5SDimitry Andric     if (!s->isLive() || s->partition == 255)
1820b57cec5SDimitry Andric       continue;
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric     Partition &part = s->getPartition();
1850b57cec5SDimitry Andric     if (auto *es = dyn_cast<EhInputSection>(s)) {
18685868e8aSDimitry Andric       part.ehFrame->addSection(es);
1870b57cec5SDimitry Andric       s = nullptr;
1880b57cec5SDimitry Andric     } else if (s->kind() == SectionBase::Regular && part.armExidx &&
1890b57cec5SDimitry Andric                part.armExidx->addSection(cast<InputSection>(s))) {
1900b57cec5SDimitry Andric       s = nullptr;
1910b57cec5SDimitry Andric     }
1920b57cec5SDimitry Andric   }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   std::vector<InputSectionBase *> &v = inputSections;
1950b57cec5SDimitry Andric   v.erase(std::remove(v.begin(), v.end(), nullptr), v.end());
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
1990b57cec5SDimitry Andric                                    uint64_t val, uint8_t stOther = STV_HIDDEN,
2000b57cec5SDimitry Andric                                    uint8_t binding = STB_GLOBAL) {
2010b57cec5SDimitry Andric   Symbol *s = symtab->find(name);
2020b57cec5SDimitry Andric   if (!s || s->isDefined())
2030b57cec5SDimitry Andric     return nullptr;
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   s->resolve(Defined{/*file=*/nullptr, name, binding, stOther, STT_NOTYPE, val,
2060b57cec5SDimitry Andric                      /*size=*/0, sec});
2070b57cec5SDimitry Andric   return cast<Defined>(s);
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric static Defined *addAbsolute(StringRef name) {
2110b57cec5SDimitry Andric   Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
2120b57cec5SDimitry Andric                                           STT_NOTYPE, 0, 0, nullptr});
2130b57cec5SDimitry Andric   return cast<Defined>(sym);
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric // The linker is expected to define some symbols depending on
2170b57cec5SDimitry Andric // the linking result. This function defines such symbols.
21885868e8aSDimitry Andric void addReservedSymbols() {
2190b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
2200b57cec5SDimitry Andric     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
2210b57cec5SDimitry Andric     // so that it points to an absolute address which by default is relative
2220b57cec5SDimitry Andric     // to GOT. Default offset is 0x7ff0.
2230b57cec5SDimitry Andric     // See "Global Data Symbols" in Chapter 6 in the following document:
2240b57cec5SDimitry Andric     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2250b57cec5SDimitry Andric     ElfSym::mipsGp = addAbsolute("_gp");
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
2280b57cec5SDimitry Andric     // start of function and 'gp' pointer into GOT.
2290b57cec5SDimitry Andric     if (symtab->find("_gp_disp"))
2300b57cec5SDimitry Andric       ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
2330b57cec5SDimitry Andric     // pointer. This symbol is used in the code generated by .cpload pseudo-op
2340b57cec5SDimitry Andric     // in case of using -mno-shared option.
2350b57cec5SDimitry Andric     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
2360b57cec5SDimitry Andric     if (symtab->find("__gnu_local_gp"))
2370b57cec5SDimitry Andric       ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
2380b57cec5SDimitry Andric   } else if (config->emachine == EM_PPC) {
2390b57cec5SDimitry Andric     // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
2400b57cec5SDimitry Andric     // support Small Data Area, define it arbitrarily as 0.
2410b57cec5SDimitry Andric     addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
2450b57cec5SDimitry Andric   // combines the typical ELF GOT with the small data sections. It commonly
2460b57cec5SDimitry Andric   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
2470b57cec5SDimitry Andric   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
2480b57cec5SDimitry Andric   // represent the TOC base which is offset by 0x8000 bytes from the start of
2490b57cec5SDimitry Andric   // the .got section.
2500b57cec5SDimitry Andric   // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
2510b57cec5SDimitry Andric   // correctness of some relocations depends on its value.
2520b57cec5SDimitry Andric   StringRef gotSymName =
2530b57cec5SDimitry Andric       (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   if (Symbol *s = symtab->find(gotSymName)) {
2560b57cec5SDimitry Andric     if (s->isDefined()) {
2570b57cec5SDimitry Andric       error(toString(s->file) + " cannot redefine linker defined symbol '" +
2580b57cec5SDimitry Andric             gotSymName + "'");
2590b57cec5SDimitry Andric       return;
2600b57cec5SDimitry Andric     }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     uint64_t gotOff = 0;
2630b57cec5SDimitry Andric     if (config->emachine == EM_PPC64)
2640b57cec5SDimitry Andric       gotOff = 0x8000;
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric     s->resolve(Defined{/*file=*/nullptr, gotSymName, STB_GLOBAL, STV_HIDDEN,
2670b57cec5SDimitry Andric                        STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
2680b57cec5SDimitry Andric     ElfSym::globalOffsetTable = cast<Defined>(s);
2690b57cec5SDimitry Andric   }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   // __ehdr_start is the location of ELF file headers. Note that we define
2720b57cec5SDimitry Andric   // this symbol unconditionally even when using a linker script, which
2730b57cec5SDimitry Andric   // differs from the behavior implemented by GNU linker which only define
2740b57cec5SDimitry Andric   // this symbol if ELF headers are in the memory mapped segment.
2750b57cec5SDimitry Andric   addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   // __executable_start is not documented, but the expectation of at
2780b57cec5SDimitry Andric   // least the Android libc is that it points to the ELF header.
2790b57cec5SDimitry Andric   addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
2820b57cec5SDimitry Andric   // each DSO. The address of the symbol doesn't matter as long as they are
2830b57cec5SDimitry Andric   // different in different DSOs, so we chose the start address of the DSO.
2840b57cec5SDimitry Andric   addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
2850b57cec5SDimitry Andric 
286*480093f4SDimitry Andric   // If linker script do layout we do not need to create any standard symbols.
2870b57cec5SDimitry Andric   if (script->hasSectionsCommand)
2880b57cec5SDimitry Andric     return;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   auto add = [](StringRef s, int64_t pos) {
2910b57cec5SDimitry Andric     return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
2920b57cec5SDimitry Andric   };
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   ElfSym::bss = add("__bss_start", 0);
2950b57cec5SDimitry Andric   ElfSym::end1 = add("end", -1);
2960b57cec5SDimitry Andric   ElfSym::end2 = add("_end", -1);
2970b57cec5SDimitry Andric   ElfSym::etext1 = add("etext", -1);
2980b57cec5SDimitry Andric   ElfSym::etext2 = add("_etext", -1);
2990b57cec5SDimitry Andric   ElfSym::edata1 = add("edata", -1);
3000b57cec5SDimitry Andric   ElfSym::edata2 = add("_edata", -1);
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric static OutputSection *findSection(StringRef name, unsigned partition = 1) {
3040b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands)
3050b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base))
3060b57cec5SDimitry Andric       if (sec->name == name && sec->partition == partition)
3070b57cec5SDimitry Andric         return sec;
3080b57cec5SDimitry Andric   return nullptr;
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric 
31185868e8aSDimitry Andric template <class ELFT> void createSyntheticSections() {
3120b57cec5SDimitry Andric   // Initialize all pointers with NULL. This is needed because
3130b57cec5SDimitry Andric   // you can call lld::elf::main more than once as a library.
3140b57cec5SDimitry Andric   memset(&Out::first, 0, sizeof(Out));
3150b57cec5SDimitry Andric 
31685868e8aSDimitry Andric   // Add the .interp section first because it is not a SyntheticSection.
31785868e8aSDimitry Andric   // The removeUnusedSyntheticSections() function relies on the
31885868e8aSDimitry Andric   // SyntheticSections coming last.
31985868e8aSDimitry Andric   if (needsInterpSection()) {
32085868e8aSDimitry Andric     for (size_t i = 1; i <= partitions.size(); ++i) {
32185868e8aSDimitry Andric       InputSection *sec = createInterpSection();
32285868e8aSDimitry Andric       sec->partition = i;
32385868e8aSDimitry Andric       inputSections.push_back(sec);
32485868e8aSDimitry Andric     }
32585868e8aSDimitry Andric   }
32685868e8aSDimitry Andric 
32785868e8aSDimitry Andric   auto add = [](SyntheticSection *sec) { inputSections.push_back(sec); };
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   in.shStrTab = make<StringTableSection>(".shstrtab", false);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
3320b57cec5SDimitry Andric   Out::programHeaders->alignment = config->wordsize;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   if (config->strip != StripPolicy::All) {
3350b57cec5SDimitry Andric     in.strTab = make<StringTableSection>(".strtab", false);
3360b57cec5SDimitry Andric     in.symTab = make<SymbolTableSection<ELFT>>(*in.strTab);
3370b57cec5SDimitry Andric     in.symTabShndx = make<SymtabShndxSection>();
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   in.bss = make<BssSection>(".bss", 0, 1);
3410b57cec5SDimitry Andric   add(in.bss);
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   // If there is a SECTIONS command and a .data.rel.ro section name use name
3440b57cec5SDimitry Andric   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
3450b57cec5SDimitry Andric   // This makes sure our relro is contiguous.
3460b57cec5SDimitry Andric   bool hasDataRelRo =
3470b57cec5SDimitry Andric       script->hasSectionsCommand && findSection(".data.rel.ro", 0);
3480b57cec5SDimitry Andric   in.bssRelRo =
3490b57cec5SDimitry Andric       make<BssSection>(hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
3500b57cec5SDimitry Andric   add(in.bssRelRo);
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   // Add MIPS-specific sections.
3530b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
3540b57cec5SDimitry Andric     if (!config->shared && config->hasDynSymTab) {
3550b57cec5SDimitry Andric       in.mipsRldMap = make<MipsRldMapSection>();
3560b57cec5SDimitry Andric       add(in.mipsRldMap);
3570b57cec5SDimitry Andric     }
3580b57cec5SDimitry Andric     if (auto *sec = MipsAbiFlagsSection<ELFT>::create())
3590b57cec5SDimitry Andric       add(sec);
3600b57cec5SDimitry Andric     if (auto *sec = MipsOptionsSection<ELFT>::create())
3610b57cec5SDimitry Andric       add(sec);
3620b57cec5SDimitry Andric     if (auto *sec = MipsReginfoSection<ELFT>::create())
3630b57cec5SDimitry Andric       add(sec);
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric 
36685868e8aSDimitry Andric   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
36785868e8aSDimitry Andric 
3680b57cec5SDimitry Andric   for (Partition &part : partitions) {
36985868e8aSDimitry Andric     auto add = [&](SyntheticSection *sec) {
3700b57cec5SDimitry Andric       sec->partition = part.getNumber();
3710b57cec5SDimitry Andric       inputSections.push_back(sec);
3720b57cec5SDimitry Andric     };
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric     if (!part.name.empty()) {
3750b57cec5SDimitry Andric       part.elfHeader = make<PartitionElfHeaderSection<ELFT>>();
3760b57cec5SDimitry Andric       part.elfHeader->name = part.name;
3770b57cec5SDimitry Andric       add(part.elfHeader);
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric       part.programHeaders = make<PartitionProgramHeadersSection<ELFT>>();
3800b57cec5SDimitry Andric       add(part.programHeaders);
3810b57cec5SDimitry Andric     }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     if (config->buildId != BuildIdKind::None) {
3840b57cec5SDimitry Andric       part.buildId = make<BuildIdSection>();
3850b57cec5SDimitry Andric       add(part.buildId);
3860b57cec5SDimitry Andric     }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric     part.dynStrTab = make<StringTableSection>(".dynstr", true);
3890b57cec5SDimitry Andric     part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
3900b57cec5SDimitry Andric     part.dynamic = make<DynamicSection<ELFT>>();
39185868e8aSDimitry Andric     if (config->androidPackDynRelocs)
39285868e8aSDimitry Andric       part.relaDyn = make<AndroidPackedRelocationSection<ELFT>>(relaDynName);
39385868e8aSDimitry Andric     else
39485868e8aSDimitry Andric       part.relaDyn =
39585868e8aSDimitry Andric           make<RelocationSection<ELFT>>(relaDynName, config->zCombreloc);
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     if (config->hasDynSymTab) {
3980b57cec5SDimitry Andric       part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
3990b57cec5SDimitry Andric       add(part.dynSymTab);
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric       part.verSym = make<VersionTableSection>();
4020b57cec5SDimitry Andric       add(part.verSym);
4030b57cec5SDimitry Andric 
40485868e8aSDimitry Andric       if (!namedVersionDefs().empty()) {
4050b57cec5SDimitry Andric         part.verDef = make<VersionDefinitionSection>();
4060b57cec5SDimitry Andric         add(part.verDef);
4070b57cec5SDimitry Andric       }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric       part.verNeed = make<VersionNeedSection<ELFT>>();
4100b57cec5SDimitry Andric       add(part.verNeed);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric       if (config->gnuHash) {
4130b57cec5SDimitry Andric         part.gnuHashTab = make<GnuHashTableSection>();
4140b57cec5SDimitry Andric         add(part.gnuHashTab);
4150b57cec5SDimitry Andric       }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric       if (config->sysvHash) {
4180b57cec5SDimitry Andric         part.hashTab = make<HashTableSection>();
4190b57cec5SDimitry Andric         add(part.hashTab);
4200b57cec5SDimitry Andric       }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric       add(part.dynamic);
4230b57cec5SDimitry Andric       add(part.dynStrTab);
4240b57cec5SDimitry Andric       add(part.relaDyn);
4250b57cec5SDimitry Andric     }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric     if (config->relrPackDynRelocs) {
4280b57cec5SDimitry Andric       part.relrDyn = make<RelrSection<ELFT>>();
4290b57cec5SDimitry Andric       add(part.relrDyn);
4300b57cec5SDimitry Andric     }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric     if (!config->relocatable) {
4330b57cec5SDimitry Andric       if (config->ehFrameHdr) {
4340b57cec5SDimitry Andric         part.ehFrameHdr = make<EhFrameHeader>();
4350b57cec5SDimitry Andric         add(part.ehFrameHdr);
4360b57cec5SDimitry Andric       }
4370b57cec5SDimitry Andric       part.ehFrame = make<EhFrameSection>();
4380b57cec5SDimitry Andric       add(part.ehFrame);
4390b57cec5SDimitry Andric     }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric     if (config->emachine == EM_ARM && !config->relocatable) {
4420b57cec5SDimitry Andric       // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
4430b57cec5SDimitry Andric       // InputSections.
4440b57cec5SDimitry Andric       part.armExidx = make<ARMExidxSyntheticSection>();
4450b57cec5SDimitry Andric       add(part.armExidx);
4460b57cec5SDimitry Andric     }
4470b57cec5SDimitry Andric   }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   if (partitions.size() != 1) {
4500b57cec5SDimitry Andric     // Create the partition end marker. This needs to be in partition number 255
4510b57cec5SDimitry Andric     // so that it is sorted after all other partitions. It also has other
4520b57cec5SDimitry Andric     // special handling (see createPhdrs() and combineEhSections()).
4530b57cec5SDimitry Andric     in.partEnd = make<BssSection>(".part.end", config->maxPageSize, 1);
4540b57cec5SDimitry Andric     in.partEnd->partition = 255;
4550b57cec5SDimitry Andric     add(in.partEnd);
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric     in.partIndex = make<PartitionIndexSection>();
4580b57cec5SDimitry Andric     addOptionalRegular("__part_index_begin", in.partIndex, 0);
4590b57cec5SDimitry Andric     addOptionalRegular("__part_index_end", in.partIndex,
4600b57cec5SDimitry Andric                        in.partIndex->getSize());
4610b57cec5SDimitry Andric     add(in.partIndex);
4620b57cec5SDimitry Andric   }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Add .got. MIPS' .got is so different from the other archs,
4650b57cec5SDimitry Andric   // it has its own class.
4660b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
4670b57cec5SDimitry Andric     in.mipsGot = make<MipsGotSection>();
4680b57cec5SDimitry Andric     add(in.mipsGot);
4690b57cec5SDimitry Andric   } else {
4700b57cec5SDimitry Andric     in.got = make<GotSection>();
4710b57cec5SDimitry Andric     add(in.got);
4720b57cec5SDimitry Andric   }
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   if (config->emachine == EM_PPC) {
4750b57cec5SDimitry Andric     in.ppc32Got2 = make<PPC32Got2Section>();
4760b57cec5SDimitry Andric     add(in.ppc32Got2);
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   if (config->emachine == EM_PPC64) {
4800b57cec5SDimitry Andric     in.ppc64LongBranchTarget = make<PPC64LongBranchTargetSection>();
4810b57cec5SDimitry Andric     add(in.ppc64LongBranchTarget);
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   in.gotPlt = make<GotPltSection>();
4850b57cec5SDimitry Andric   add(in.gotPlt);
4860b57cec5SDimitry Andric   in.igotPlt = make<IgotPltSection>();
4870b57cec5SDimitry Andric   add(in.igotPlt);
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
4900b57cec5SDimitry Andric   // it as a relocation and ensure the referenced section is created.
4910b57cec5SDimitry Andric   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
4920b57cec5SDimitry Andric     if (target->gotBaseSymInGotPlt)
4930b57cec5SDimitry Andric       in.gotPlt->hasGotPltOffRel = true;
4940b57cec5SDimitry Andric     else
4950b57cec5SDimitry Andric       in.got->hasGotOffRel = true;
4960b57cec5SDimitry Andric   }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   if (config->gdbIndex)
4990b57cec5SDimitry Andric     add(GdbIndexSection::create<ELFT>());
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   // We always need to add rel[a].plt to output if it has entries.
5020b57cec5SDimitry Andric   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
5030b57cec5SDimitry Andric   in.relaPlt = make<RelocationSection<ELFT>>(
5040b57cec5SDimitry Andric       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
5050b57cec5SDimitry Andric   add(in.relaPlt);
5060b57cec5SDimitry Andric 
50785868e8aSDimitry Andric   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
50885868e8aSDimitry Andric   // relocations are processed last by the dynamic loader. We cannot place the
50985868e8aSDimitry Andric   // iplt section in .rel.dyn when Android relocation packing is enabled because
51085868e8aSDimitry Andric   // that would cause a section type mismatch. However, because the Android
51185868e8aSDimitry Andric   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
51285868e8aSDimitry Andric   // behaviour by placing the iplt section in .rel.plt.
5130b57cec5SDimitry Andric   in.relaIplt = make<RelocationSection<ELFT>>(
51485868e8aSDimitry Andric       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
5150b57cec5SDimitry Andric       /*sort=*/false);
5160b57cec5SDimitry Andric   add(in.relaIplt);
5170b57cec5SDimitry Andric 
518*480093f4SDimitry Andric   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
519*480093f4SDimitry Andric       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
520*480093f4SDimitry Andric     in.ibtPlt = make<IBTPltSection>();
521*480093f4SDimitry Andric     add(in.ibtPlt);
522*480093f4SDimitry Andric   }
523*480093f4SDimitry Andric 
524*480093f4SDimitry Andric   in.plt = make<PltSection>();
5250b57cec5SDimitry Andric   add(in.plt);
526*480093f4SDimitry Andric   in.iplt = make<IpltSection>();
5270b57cec5SDimitry Andric   add(in.iplt);
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   if (config->andFeatures)
5300b57cec5SDimitry Andric     add(make<GnuPropertySection>());
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   // .note.GNU-stack is always added when we are creating a re-linkable
5330b57cec5SDimitry Andric   // object file. Other linkers are using the presence of this marker
5340b57cec5SDimitry Andric   // section to control the executable-ness of the stack area, but that
5350b57cec5SDimitry Andric   // is irrelevant these days. Stack area should always be non-executable
5360b57cec5SDimitry Andric   // by default. So we emit this section unconditionally.
5370b57cec5SDimitry Andric   if (config->relocatable)
5380b57cec5SDimitry Andric     add(make<GnuStackSection>());
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   if (in.symTab)
5410b57cec5SDimitry Andric     add(in.symTab);
5420b57cec5SDimitry Andric   if (in.symTabShndx)
5430b57cec5SDimitry Andric     add(in.symTabShndx);
5440b57cec5SDimitry Andric   add(in.shStrTab);
5450b57cec5SDimitry Andric   if (in.strTab)
5460b57cec5SDimitry Andric     add(in.strTab);
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric // The main function of the writer.
5500b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::run() {
5510b57cec5SDimitry Andric   if (config->discard != DiscardPolicy::All)
5520b57cec5SDimitry Andric     copyLocalSymbols();
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   if (config->copyRelocs)
5550b57cec5SDimitry Andric     addSectionSymbols();
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   // Now that we have a complete set of output sections. This function
5580b57cec5SDimitry Andric   // completes section contents. For example, we need to add strings
5590b57cec5SDimitry Andric   // to the string table, and add entries to .got and .plt.
5600b57cec5SDimitry Andric   // finalizeSections does that.
5610b57cec5SDimitry Andric   finalizeSections();
5620b57cec5SDimitry Andric   checkExecuteOnly();
5630b57cec5SDimitry Andric   if (errorCount())
5640b57cec5SDimitry Andric     return;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // If -compressed-debug-sections is specified, we need to compress
5670b57cec5SDimitry Andric   // .debug_* sections. Do it right now because it changes the size of
5680b57cec5SDimitry Andric   // output sections.
5690b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
5700b57cec5SDimitry Andric     sec->maybeCompress<ELFT>();
5710b57cec5SDimitry Andric 
57285868e8aSDimitry Andric   if (script->hasSectionsCommand)
5730b57cec5SDimitry Andric     script->allocateHeaders(mainPart->phdrs);
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
5760b57cec5SDimitry Andric   // 0 sized region. This has to be done late since only after assignAddresses
5770b57cec5SDimitry Andric   // we know the size of the sections.
5780b57cec5SDimitry Andric   for (Partition &part : partitions)
5790b57cec5SDimitry Andric     removeEmptyPTLoad(part.phdrs);
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   if (!config->oFormatBinary)
5820b57cec5SDimitry Andric     assignFileOffsets();
5830b57cec5SDimitry Andric   else
5840b57cec5SDimitry Andric     assignFileOffsetsBinary();
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   for (Partition &part : partitions)
5870b57cec5SDimitry Andric     setPhdrs(part);
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   if (config->relocatable)
5900b57cec5SDimitry Andric     for (OutputSection *sec : outputSections)
5910b57cec5SDimitry Andric       sec->addr = 0;
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   if (config->checkSections)
5940b57cec5SDimitry Andric     checkSections();
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // It does not make sense try to open the file if we have error already.
5970b57cec5SDimitry Andric   if (errorCount())
5980b57cec5SDimitry Andric     return;
5990b57cec5SDimitry Andric   // Write the result down to a file.
6000b57cec5SDimitry Andric   openFile();
6010b57cec5SDimitry Andric   if (errorCount())
6020b57cec5SDimitry Andric     return;
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric   if (!config->oFormatBinary) {
60585868e8aSDimitry Andric     if (config->zSeparate != SeparateSegmentKind::None)
6060b57cec5SDimitry Andric       writeTrapInstr();
6070b57cec5SDimitry Andric     writeHeader();
6080b57cec5SDimitry Andric     writeSections();
6090b57cec5SDimitry Andric   } else {
6100b57cec5SDimitry Andric     writeSectionsBinary();
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   // Backfill .note.gnu.build-id section content. This is done at last
6140b57cec5SDimitry Andric   // because the content is usually a hash value of the entire output file.
6150b57cec5SDimitry Andric   writeBuildId();
6160b57cec5SDimitry Andric   if (errorCount())
6170b57cec5SDimitry Andric     return;
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   // Handle -Map and -cref options.
6200b57cec5SDimitry Andric   writeMapFile();
6210b57cec5SDimitry Andric   writeCrossReferenceTable();
6220b57cec5SDimitry Andric   if (errorCount())
6230b57cec5SDimitry Andric     return;
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   if (auto e = buffer->commit())
6260b57cec5SDimitry Andric     error("failed to write to the output file: " + toString(std::move(e)));
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric static bool shouldKeepInSymtab(const Defined &sym) {
6300b57cec5SDimitry Andric   if (sym.isSection())
6310b57cec5SDimitry Andric     return false;
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   if (config->discard == DiscardPolicy::None)
6340b57cec5SDimitry Andric     return true;
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   // If -emit-reloc is given, all symbols including local ones need to be
6370b57cec5SDimitry Andric   // copied because they may be referenced by relocations.
6380b57cec5SDimitry Andric   if (config->emitRelocs)
6390b57cec5SDimitry Andric     return true;
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // In ELF assembly .L symbols are normally discarded by the assembler.
6420b57cec5SDimitry Andric   // If the assembler fails to do so, the linker discards them if
6430b57cec5SDimitry Andric   // * --discard-locals is used.
6440b57cec5SDimitry Andric   // * The symbol is in a SHF_MERGE section, which is normally the reason for
6450b57cec5SDimitry Andric   //   the assembler keeping the .L symbol.
6460b57cec5SDimitry Andric   StringRef name = sym.getName();
6470b57cec5SDimitry Andric   bool isLocal = name.startswith(".L") || name.empty();
6480b57cec5SDimitry Andric   if (!isLocal)
6490b57cec5SDimitry Andric     return true;
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   if (config->discard == DiscardPolicy::Locals)
6520b57cec5SDimitry Andric     return false;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   SectionBase *sec = sym.section;
6550b57cec5SDimitry Andric   return !sec || !(sec->flags & SHF_MERGE);
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric static bool includeInSymtab(const Symbol &b) {
6590b57cec5SDimitry Andric   if (!b.isLocal() && !b.isUsedInRegularObj)
6600b57cec5SDimitry Andric     return false;
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   if (auto *d = dyn_cast<Defined>(&b)) {
6630b57cec5SDimitry Andric     // Always include absolute symbols.
6640b57cec5SDimitry Andric     SectionBase *sec = d->section;
6650b57cec5SDimitry Andric     if (!sec)
6660b57cec5SDimitry Andric       return true;
6670b57cec5SDimitry Andric     sec = sec->repl;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     // Exclude symbols pointing to garbage-collected sections.
6700b57cec5SDimitry Andric     if (isa<InputSectionBase>(sec) && !sec->isLive())
6710b57cec5SDimitry Andric       return false;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric     if (auto *s = dyn_cast<MergeInputSection>(sec))
6740b57cec5SDimitry Andric       if (!s->getSectionPiece(d->value)->live)
6750b57cec5SDimitry Andric         return false;
6760b57cec5SDimitry Andric     return true;
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric   return b.used;
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric // Local symbols are not in the linker's symbol table. This function scans
6820b57cec5SDimitry Andric // each object file's symbol table to copy local symbols to the output.
6830b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
6840b57cec5SDimitry Andric   if (!in.symTab)
6850b57cec5SDimitry Andric     return;
6860b57cec5SDimitry Andric   for (InputFile *file : objectFiles) {
6870b57cec5SDimitry Andric     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
6880b57cec5SDimitry Andric     for (Symbol *b : f->getLocalSymbols()) {
6890b57cec5SDimitry Andric       if (!b->isLocal())
6900b57cec5SDimitry Andric         fatal(toString(f) +
6910b57cec5SDimitry Andric               ": broken object: getLocalSymbols returns a non-local symbol");
6920b57cec5SDimitry Andric       auto *dr = dyn_cast<Defined>(b);
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric       // No reason to keep local undefined symbol in symtab.
6950b57cec5SDimitry Andric       if (!dr)
6960b57cec5SDimitry Andric         continue;
6970b57cec5SDimitry Andric       if (!includeInSymtab(*b))
6980b57cec5SDimitry Andric         continue;
6990b57cec5SDimitry Andric       if (!shouldKeepInSymtab(*dr))
7000b57cec5SDimitry Andric         continue;
7010b57cec5SDimitry Andric       in.symTab->addSymbol(b);
7020b57cec5SDimitry Andric     }
7030b57cec5SDimitry Andric   }
7040b57cec5SDimitry Andric }
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric // Create a section symbol for each output section so that we can represent
7070b57cec5SDimitry Andric // relocations that point to the section. If we know that no relocation is
7080b57cec5SDimitry Andric // referring to a section (that happens if the section is a synthetic one), we
7090b57cec5SDimitry Andric // don't create a section symbol for that section.
7100b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
7110b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands) {
7120b57cec5SDimitry Andric     auto *sec = dyn_cast<OutputSection>(base);
7130b57cec5SDimitry Andric     if (!sec)
7140b57cec5SDimitry Andric       continue;
7150b57cec5SDimitry Andric     auto i = llvm::find_if(sec->sectionCommands, [](BaseCommand *base) {
7160b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(base))
7170b57cec5SDimitry Andric         return !isd->sections.empty();
7180b57cec5SDimitry Andric       return false;
7190b57cec5SDimitry Andric     });
7200b57cec5SDimitry Andric     if (i == sec->sectionCommands.end())
7210b57cec5SDimitry Andric       continue;
72285868e8aSDimitry Andric     InputSectionBase *isec = cast<InputSectionDescription>(*i)->sections[0];
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric     // Relocations are not using REL[A] section symbols.
7250b57cec5SDimitry Andric     if (isec->type == SHT_REL || isec->type == SHT_RELA)
7260b57cec5SDimitry Andric       continue;
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric     // Unlike other synthetic sections, mergeable output sections contain data
7290b57cec5SDimitry Andric     // copied from input sections, and there may be a relocation pointing to its
7300b57cec5SDimitry Andric     // contents if -r or -emit-reloc are given.
7310b57cec5SDimitry Andric     if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
7320b57cec5SDimitry Andric       continue;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     auto *sym =
7350b57cec5SDimitry Andric         make<Defined>(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION,
7360b57cec5SDimitry Andric                       /*value=*/0, /*size=*/0, isec);
7370b57cec5SDimitry Andric     in.symTab->addSymbol(sym);
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric // Today's loaders have a feature to make segments read-only after
7420b57cec5SDimitry Andric // processing dynamic relocations to enhance security. PT_GNU_RELRO
7430b57cec5SDimitry Andric // is defined for that.
7440b57cec5SDimitry Andric //
7450b57cec5SDimitry Andric // This function returns true if a section needs to be put into a
7460b57cec5SDimitry Andric // PT_GNU_RELRO segment.
7470b57cec5SDimitry Andric static bool isRelroSection(const OutputSection *sec) {
7480b57cec5SDimitry Andric   if (!config->zRelro)
7490b57cec5SDimitry Andric     return false;
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   uint64_t flags = sec->flags;
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // Non-allocatable or non-writable sections don't need RELRO because
7540b57cec5SDimitry Andric   // they are not writable or not even mapped to memory in the first place.
7550b57cec5SDimitry Andric   // RELRO is for sections that are essentially read-only but need to
7560b57cec5SDimitry Andric   // be writable only at process startup to allow dynamic linker to
7570b57cec5SDimitry Andric   // apply relocations.
7580b57cec5SDimitry Andric   if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
7590b57cec5SDimitry Andric     return false;
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   // Once initialized, TLS data segments are used as data templates
7620b57cec5SDimitry Andric   // for a thread-local storage. For each new thread, runtime
7630b57cec5SDimitry Andric   // allocates memory for a TLS and copy templates there. No thread
7640b57cec5SDimitry Andric   // are supposed to use templates directly. Thus, it can be in RELRO.
7650b57cec5SDimitry Andric   if (flags & SHF_TLS)
7660b57cec5SDimitry Andric     return true;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   // .init_array, .preinit_array and .fini_array contain pointers to
7690b57cec5SDimitry Andric   // functions that are executed on process startup or exit. These
7700b57cec5SDimitry Andric   // pointers are set by the static linker, and they are not expected
7710b57cec5SDimitry Andric   // to change at runtime. But if you are an attacker, you could do
7720b57cec5SDimitry Andric   // interesting things by manipulating pointers in .fini_array, for
7730b57cec5SDimitry Andric   // example. So they are put into RELRO.
7740b57cec5SDimitry Andric   uint32_t type = sec->type;
7750b57cec5SDimitry Andric   if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
7760b57cec5SDimitry Andric       type == SHT_PREINIT_ARRAY)
7770b57cec5SDimitry Andric     return true;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // .got contains pointers to external symbols. They are resolved by
7800b57cec5SDimitry Andric   // the dynamic linker when a module is loaded into memory, and after
7810b57cec5SDimitry Andric   // that they are not expected to change. So, it can be in RELRO.
7820b57cec5SDimitry Andric   if (in.got && sec == in.got->getParent())
7830b57cec5SDimitry Andric     return true;
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
7860b57cec5SDimitry Andric   // through r2 register, which is reserved for that purpose. Since r2 is used
7870b57cec5SDimitry Andric   // for accessing .got as well, .got and .toc need to be close enough in the
7880b57cec5SDimitry Andric   // virtual address space. Usually, .toc comes just after .got. Since we place
7890b57cec5SDimitry Andric   // .got into RELRO, .toc needs to be placed into RELRO too.
7900b57cec5SDimitry Andric   if (sec->name.equals(".toc"))
7910b57cec5SDimitry Andric     return true;
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   // .got.plt contains pointers to external function symbols. They are
7940b57cec5SDimitry Andric   // by default resolved lazily, so we usually cannot put it into RELRO.
7950b57cec5SDimitry Andric   // However, if "-z now" is given, the lazy symbol resolution is
7960b57cec5SDimitry Andric   // disabled, which enables us to put it into RELRO.
7970b57cec5SDimitry Andric   if (sec == in.gotPlt->getParent())
7980b57cec5SDimitry Andric     return config->zNow;
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   // .dynamic section contains data for the dynamic linker, and
8010b57cec5SDimitry Andric   // there's no need to write to it at runtime, so it's better to put
8020b57cec5SDimitry Andric   // it into RELRO.
8030b57cec5SDimitry Andric   if (sec->name == ".dynamic")
8040b57cec5SDimitry Andric     return true;
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   // Sections with some special names are put into RELRO. This is a
8070b57cec5SDimitry Andric   // bit unfortunate because section names shouldn't be significant in
8080b57cec5SDimitry Andric   // ELF in spirit. But in reality many linker features depend on
8090b57cec5SDimitry Andric   // magic section names.
8100b57cec5SDimitry Andric   StringRef s = sec->name;
8110b57cec5SDimitry Andric   return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
8120b57cec5SDimitry Andric          s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
8130b57cec5SDimitry Andric          s == ".openbsd.randomdata";
8140b57cec5SDimitry Andric }
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric // We compute a rank for each section. The rank indicates where the
8170b57cec5SDimitry Andric // section should be placed in the file.  Instead of using simple
8180b57cec5SDimitry Andric // numbers (0,1,2...), we use a series of flags. One for each decision
8190b57cec5SDimitry Andric // point when placing the section.
8200b57cec5SDimitry Andric // Using flags has two key properties:
8210b57cec5SDimitry Andric // * It is easy to check if a give branch was taken.
8220b57cec5SDimitry Andric // * It is easy two see how similar two ranks are (see getRankProximity).
8230b57cec5SDimitry Andric enum RankFlags {
8240b57cec5SDimitry Andric   RF_NOT_ADDR_SET = 1 << 27,
8250b57cec5SDimitry Andric   RF_NOT_ALLOC = 1 << 26,
8260b57cec5SDimitry Andric   RF_PARTITION = 1 << 18, // Partition number (8 bits)
8270b57cec5SDimitry Andric   RF_NOT_PART_EHDR = 1 << 17,
8280b57cec5SDimitry Andric   RF_NOT_PART_PHDR = 1 << 16,
8290b57cec5SDimitry Andric   RF_NOT_INTERP = 1 << 15,
8300b57cec5SDimitry Andric   RF_NOT_NOTE = 1 << 14,
8310b57cec5SDimitry Andric   RF_WRITE = 1 << 13,
8320b57cec5SDimitry Andric   RF_EXEC_WRITE = 1 << 12,
8330b57cec5SDimitry Andric   RF_EXEC = 1 << 11,
8340b57cec5SDimitry Andric   RF_RODATA = 1 << 10,
8350b57cec5SDimitry Andric   RF_NOT_RELRO = 1 << 9,
8360b57cec5SDimitry Andric   RF_NOT_TLS = 1 << 8,
8370b57cec5SDimitry Andric   RF_BSS = 1 << 7,
8380b57cec5SDimitry Andric   RF_PPC_NOT_TOCBSS = 1 << 6,
8390b57cec5SDimitry Andric   RF_PPC_TOCL = 1 << 5,
8400b57cec5SDimitry Andric   RF_PPC_TOC = 1 << 4,
8410b57cec5SDimitry Andric   RF_PPC_GOT = 1 << 3,
8420b57cec5SDimitry Andric   RF_PPC_BRANCH_LT = 1 << 2,
8430b57cec5SDimitry Andric   RF_MIPS_GPREL = 1 << 1,
8440b57cec5SDimitry Andric   RF_MIPS_NOT_GOT = 1 << 0
8450b57cec5SDimitry Andric };
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric static unsigned getSectionRank(const OutputSection *sec) {
8480b57cec5SDimitry Andric   unsigned rank = sec->partition * RF_PARTITION;
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   // We want to put section specified by -T option first, so we
8510b57cec5SDimitry Andric   // can start assigning VA starting from them later.
8520b57cec5SDimitry Andric   if (config->sectionStartMap.count(sec->name))
8530b57cec5SDimitry Andric     return rank;
8540b57cec5SDimitry Andric   rank |= RF_NOT_ADDR_SET;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   // Allocatable sections go first to reduce the total PT_LOAD size and
8570b57cec5SDimitry Andric   // so debug info doesn't change addresses in actual code.
8580b57cec5SDimitry Andric   if (!(sec->flags & SHF_ALLOC))
8590b57cec5SDimitry Andric     return rank | RF_NOT_ALLOC;
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   if (sec->type == SHT_LLVM_PART_EHDR)
8620b57cec5SDimitry Andric     return rank;
8630b57cec5SDimitry Andric   rank |= RF_NOT_PART_EHDR;
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   if (sec->type == SHT_LLVM_PART_PHDR)
8660b57cec5SDimitry Andric     return rank;
8670b57cec5SDimitry Andric   rank |= RF_NOT_PART_PHDR;
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   // Put .interp first because some loaders want to see that section
8700b57cec5SDimitry Andric   // on the first page of the executable file when loaded into memory.
8710b57cec5SDimitry Andric   if (sec->name == ".interp")
8720b57cec5SDimitry Andric     return rank;
8730b57cec5SDimitry Andric   rank |= RF_NOT_INTERP;
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   // Put .note sections (which make up one PT_NOTE) at the beginning so that
8760b57cec5SDimitry Andric   // they are likely to be included in a core file even if core file size is
8770b57cec5SDimitry Andric   // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
8780b57cec5SDimitry Andric   // included in a core to match core files with executables.
8790b57cec5SDimitry Andric   if (sec->type == SHT_NOTE)
8800b57cec5SDimitry Andric     return rank;
8810b57cec5SDimitry Andric   rank |= RF_NOT_NOTE;
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   // Sort sections based on their access permission in the following
8840b57cec5SDimitry Andric   // order: R, RX, RWX, RW.  This order is based on the following
8850b57cec5SDimitry Andric   // considerations:
8860b57cec5SDimitry Andric   // * Read-only sections come first such that they go in the
8870b57cec5SDimitry Andric   //   PT_LOAD covering the program headers at the start of the file.
8880b57cec5SDimitry Andric   // * Read-only, executable sections come next.
8890b57cec5SDimitry Andric   // * Writable, executable sections follow such that .plt on
8900b57cec5SDimitry Andric   //   architectures where it needs to be writable will be placed
8910b57cec5SDimitry Andric   //   between .text and .data.
8920b57cec5SDimitry Andric   // * Writable sections come last, such that .bss lands at the very
8930b57cec5SDimitry Andric   //   end of the last PT_LOAD.
8940b57cec5SDimitry Andric   bool isExec = sec->flags & SHF_EXECINSTR;
8950b57cec5SDimitry Andric   bool isWrite = sec->flags & SHF_WRITE;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   if (isExec) {
8980b57cec5SDimitry Andric     if (isWrite)
8990b57cec5SDimitry Andric       rank |= RF_EXEC_WRITE;
9000b57cec5SDimitry Andric     else
9010b57cec5SDimitry Andric       rank |= RF_EXEC;
9020b57cec5SDimitry Andric   } else if (isWrite) {
9030b57cec5SDimitry Andric     rank |= RF_WRITE;
9040b57cec5SDimitry Andric   } else if (sec->type == SHT_PROGBITS) {
9050b57cec5SDimitry Andric     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
9060b57cec5SDimitry Andric     // .eh_frame) closer to .text. They likely contain PC or GOT relative
9070b57cec5SDimitry Andric     // relocations and there could be relocation overflow if other huge sections
9080b57cec5SDimitry Andric     // (.dynstr .dynsym) were placed in between.
9090b57cec5SDimitry Andric     rank |= RF_RODATA;
9100b57cec5SDimitry Andric   }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Place RelRo sections first. After considering SHT_NOBITS below, the
9130b57cec5SDimitry Andric   // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
9140b57cec5SDimitry Andric   // where | marks where page alignment happens. An alternative ordering is
9150b57cec5SDimitry Andric   // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
9160b57cec5SDimitry Andric   // waste more bytes due to 2 alignment places.
9170b57cec5SDimitry Andric   if (!isRelroSection(sec))
9180b57cec5SDimitry Andric     rank |= RF_NOT_RELRO;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   // If we got here we know that both A and B are in the same PT_LOAD.
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // The TLS initialization block needs to be a single contiguous block in a R/W
9230b57cec5SDimitry Andric   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
9240b57cec5SDimitry Andric   // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
9250b57cec5SDimitry Andric   // after PROGBITS.
9260b57cec5SDimitry Andric   if (!(sec->flags & SHF_TLS))
9270b57cec5SDimitry Andric     rank |= RF_NOT_TLS;
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   // Within TLS sections, or within other RelRo sections, or within non-RelRo
9300b57cec5SDimitry Andric   // sections, place non-NOBITS sections first.
9310b57cec5SDimitry Andric   if (sec->type == SHT_NOBITS)
9320b57cec5SDimitry Andric     rank |= RF_BSS;
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   // Some architectures have additional ordering restrictions for sections
9350b57cec5SDimitry Andric   // within the same PT_LOAD.
9360b57cec5SDimitry Andric   if (config->emachine == EM_PPC64) {
9370b57cec5SDimitry Andric     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
9380b57cec5SDimitry Andric     // that we would like to make sure appear is a specific order to maximize
9390b57cec5SDimitry Andric     // their coverage by a single signed 16-bit offset from the TOC base
9400b57cec5SDimitry Andric     // pointer. Conversely, the special .tocbss section should be first among
9410b57cec5SDimitry Andric     // all SHT_NOBITS sections. This will put it next to the loaded special
9420b57cec5SDimitry Andric     // PPC64 sections (and, thus, within reach of the TOC base pointer).
9430b57cec5SDimitry Andric     StringRef name = sec->name;
9440b57cec5SDimitry Andric     if (name != ".tocbss")
9450b57cec5SDimitry Andric       rank |= RF_PPC_NOT_TOCBSS;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     if (name == ".toc1")
9480b57cec5SDimitry Andric       rank |= RF_PPC_TOCL;
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric     if (name == ".toc")
9510b57cec5SDimitry Andric       rank |= RF_PPC_TOC;
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric     if (name == ".got")
9540b57cec5SDimitry Andric       rank |= RF_PPC_GOT;
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric     if (name == ".branch_lt")
9570b57cec5SDimitry Andric       rank |= RF_PPC_BRANCH_LT;
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   if (config->emachine == EM_MIPS) {
9610b57cec5SDimitry Andric     // All sections with SHF_MIPS_GPREL flag should be grouped together
9620b57cec5SDimitry Andric     // because data in these sections is addressable with a gp relative address.
9630b57cec5SDimitry Andric     if (sec->flags & SHF_MIPS_GPREL)
9640b57cec5SDimitry Andric       rank |= RF_MIPS_GPREL;
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric     if (sec->name != ".got")
9670b57cec5SDimitry Andric       rank |= RF_MIPS_NOT_GOT;
9680b57cec5SDimitry Andric   }
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   return rank;
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric static bool compareSections(const BaseCommand *aCmd, const BaseCommand *bCmd) {
9740b57cec5SDimitry Andric   const OutputSection *a = cast<OutputSection>(aCmd);
9750b57cec5SDimitry Andric   const OutputSection *b = cast<OutputSection>(bCmd);
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   if (a->sortRank != b->sortRank)
9780b57cec5SDimitry Andric     return a->sortRank < b->sortRank;
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   if (!(a->sortRank & RF_NOT_ADDR_SET))
9810b57cec5SDimitry Andric     return config->sectionStartMap.lookup(a->name) <
9820b57cec5SDimitry Andric            config->sectionStartMap.lookup(b->name);
9830b57cec5SDimitry Andric   return false;
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric void PhdrEntry::add(OutputSection *sec) {
9870b57cec5SDimitry Andric   lastSec = sec;
9880b57cec5SDimitry Andric   if (!firstSec)
9890b57cec5SDimitry Andric     firstSec = sec;
9900b57cec5SDimitry Andric   p_align = std::max(p_align, sec->alignment);
9910b57cec5SDimitry Andric   if (p_type == PT_LOAD)
9920b57cec5SDimitry Andric     sec->ptLoad = this;
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric // The beginning and the ending of .rel[a].plt section are marked
9960b57cec5SDimitry Andric // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
9970b57cec5SDimitry Andric // executable. The runtime needs these symbols in order to resolve
9980b57cec5SDimitry Andric // all IRELATIVE relocs on startup. For dynamic executables, we don't
9990b57cec5SDimitry Andric // need these symbols, since IRELATIVE relocs are resolved through GOT
10000b57cec5SDimitry Andric // and PLT. For details, see http://www.airs.com/blog/archives/403.
10010b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
10020b57cec5SDimitry Andric   if (config->relocatable || needsInterpSection())
10030b57cec5SDimitry Andric     return;
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   // By default, __rela_iplt_{start,end} belong to a dummy section 0
10060b57cec5SDimitry Andric   // because .rela.plt might be empty and thus removed from output.
10070b57cec5SDimitry Andric   // We'll override Out::elfHeader with In.relaIplt later when we are
10080b57cec5SDimitry Andric   // sure that .rela.plt exists in output.
10090b57cec5SDimitry Andric   ElfSym::relaIpltStart = addOptionalRegular(
10100b57cec5SDimitry Andric       config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
10110b57cec5SDimitry Andric       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   ElfSym::relaIpltEnd = addOptionalRegular(
10140b57cec5SDimitry Andric       config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
10150b57cec5SDimitry Andric       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric template <class ELFT>
10190b57cec5SDimitry Andric void Writer<ELFT>::forEachRelSec(
10200b57cec5SDimitry Andric     llvm::function_ref<void(InputSectionBase &)> fn) {
10210b57cec5SDimitry Andric   // Scan all relocations. Each relocation goes through a series
10220b57cec5SDimitry Andric   // of tests to determine if it needs special treatment, such as
10230b57cec5SDimitry Andric   // creating GOT, PLT, copy relocations, etc.
10240b57cec5SDimitry Andric   // Note that relocations for non-alloc sections are directly
10250b57cec5SDimitry Andric   // processed by InputSection::relocateNonAlloc.
10260b57cec5SDimitry Andric   for (InputSectionBase *isec : inputSections)
10270b57cec5SDimitry Andric     if (isec->isLive() && isa<InputSection>(isec) && (isec->flags & SHF_ALLOC))
10280b57cec5SDimitry Andric       fn(*isec);
10290b57cec5SDimitry Andric   for (Partition &part : partitions) {
10300b57cec5SDimitry Andric     for (EhInputSection *es : part.ehFrame->sections)
10310b57cec5SDimitry Andric       fn(*es);
10320b57cec5SDimitry Andric     if (part.armExidx && part.armExidx->isLive())
10330b57cec5SDimitry Andric       for (InputSection *ex : part.armExidx->exidxSections)
10340b57cec5SDimitry Andric         fn(*ex);
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric // This function generates assignments for predefined symbols (e.g. _end or
10390b57cec5SDimitry Andric // _etext) and inserts them into the commands sequence to be processed at the
10400b57cec5SDimitry Andric // appropriate time. This ensures that the value is going to be correct by the
10410b57cec5SDimitry Andric // time any references to these symbols are processed and is equivalent to
10420b57cec5SDimitry Andric // defining these symbols explicitly in the linker script.
10430b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
10440b57cec5SDimitry Andric   if (ElfSym::globalOffsetTable) {
10450b57cec5SDimitry Andric     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
10460b57cec5SDimitry Andric     // to the start of the .got or .got.plt section.
10470b57cec5SDimitry Andric     InputSection *gotSection = in.gotPlt;
10480b57cec5SDimitry Andric     if (!target->gotBaseSymInGotPlt)
10490b57cec5SDimitry Andric       gotSection = in.mipsGot ? cast<InputSection>(in.mipsGot)
10500b57cec5SDimitry Andric                               : cast<InputSection>(in.got);
10510b57cec5SDimitry Andric     ElfSym::globalOffsetTable->section = gotSection;
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric 
105485868e8aSDimitry Andric   // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
10550b57cec5SDimitry Andric   if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
10560b57cec5SDimitry Andric     ElfSym::relaIpltStart->section = in.relaIplt;
10570b57cec5SDimitry Andric     ElfSym::relaIpltEnd->section = in.relaIplt;
10580b57cec5SDimitry Andric     ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   PhdrEntry *last = nullptr;
10620b57cec5SDimitry Andric   PhdrEntry *lastRO = nullptr;
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   for (Partition &part : partitions) {
10650b57cec5SDimitry Andric     for (PhdrEntry *p : part.phdrs) {
10660b57cec5SDimitry Andric       if (p->p_type != PT_LOAD)
10670b57cec5SDimitry Andric         continue;
10680b57cec5SDimitry Andric       last = p;
10690b57cec5SDimitry Andric       if (!(p->p_flags & PF_W))
10700b57cec5SDimitry Andric         lastRO = p;
10710b57cec5SDimitry Andric     }
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   if (lastRO) {
10750b57cec5SDimitry Andric     // _etext is the first location after the last read-only loadable segment.
10760b57cec5SDimitry Andric     if (ElfSym::etext1)
10770b57cec5SDimitry Andric       ElfSym::etext1->section = lastRO->lastSec;
10780b57cec5SDimitry Andric     if (ElfSym::etext2)
10790b57cec5SDimitry Andric       ElfSym::etext2->section = lastRO->lastSec;
10800b57cec5SDimitry Andric   }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric   if (last) {
10830b57cec5SDimitry Andric     // _edata points to the end of the last mapped initialized section.
10840b57cec5SDimitry Andric     OutputSection *edata = nullptr;
10850b57cec5SDimitry Andric     for (OutputSection *os : outputSections) {
10860b57cec5SDimitry Andric       if (os->type != SHT_NOBITS)
10870b57cec5SDimitry Andric         edata = os;
10880b57cec5SDimitry Andric       if (os == last->lastSec)
10890b57cec5SDimitry Andric         break;
10900b57cec5SDimitry Andric     }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric     if (ElfSym::edata1)
10930b57cec5SDimitry Andric       ElfSym::edata1->section = edata;
10940b57cec5SDimitry Andric     if (ElfSym::edata2)
10950b57cec5SDimitry Andric       ElfSym::edata2->section = edata;
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     // _end is the first location after the uninitialized data region.
10980b57cec5SDimitry Andric     if (ElfSym::end1)
10990b57cec5SDimitry Andric       ElfSym::end1->section = last->lastSec;
11000b57cec5SDimitry Andric     if (ElfSym::end2)
11010b57cec5SDimitry Andric       ElfSym::end2->section = last->lastSec;
11020b57cec5SDimitry Andric   }
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric   if (ElfSym::bss)
11050b57cec5SDimitry Andric     ElfSym::bss->section = findSection(".bss");
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
11080b57cec5SDimitry Andric   // be equal to the _gp symbol's value.
11090b57cec5SDimitry Andric   if (ElfSym::mipsGp) {
11100b57cec5SDimitry Andric     // Find GP-relative section with the lowest address
11110b57cec5SDimitry Andric     // and use this address to calculate default _gp value.
11120b57cec5SDimitry Andric     for (OutputSection *os : outputSections) {
11130b57cec5SDimitry Andric       if (os->flags & SHF_MIPS_GPREL) {
11140b57cec5SDimitry Andric         ElfSym::mipsGp->section = os;
11150b57cec5SDimitry Andric         ElfSym::mipsGp->value = 0x7ff0;
11160b57cec5SDimitry Andric         break;
11170b57cec5SDimitry Andric       }
11180b57cec5SDimitry Andric     }
11190b57cec5SDimitry Andric   }
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric // We want to find how similar two ranks are.
11230b57cec5SDimitry Andric // The more branches in getSectionRank that match, the more similar they are.
11240b57cec5SDimitry Andric // Since each branch corresponds to a bit flag, we can just use
11250b57cec5SDimitry Andric // countLeadingZeros.
11260b57cec5SDimitry Andric static int getRankProximityAux(OutputSection *a, OutputSection *b) {
11270b57cec5SDimitry Andric   return countLeadingZeros(a->sortRank ^ b->sortRank);
11280b57cec5SDimitry Andric }
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric static int getRankProximity(OutputSection *a, BaseCommand *b) {
11310b57cec5SDimitry Andric   auto *sec = dyn_cast<OutputSection>(b);
11320b57cec5SDimitry Andric   return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1;
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric // When placing orphan sections, we want to place them after symbol assignments
11360b57cec5SDimitry Andric // so that an orphan after
11370b57cec5SDimitry Andric //   begin_foo = .;
11380b57cec5SDimitry Andric //   foo : { *(foo) }
11390b57cec5SDimitry Andric //   end_foo = .;
11400b57cec5SDimitry Andric // doesn't break the intended meaning of the begin/end symbols.
11410b57cec5SDimitry Andric // We don't want to go over sections since findOrphanPos is the
11420b57cec5SDimitry Andric // one in charge of deciding the order of the sections.
11430b57cec5SDimitry Andric // We don't want to go over changes to '.', since doing so in
11440b57cec5SDimitry Andric //  rx_sec : { *(rx_sec) }
11450b57cec5SDimitry Andric //  . = ALIGN(0x1000);
11460b57cec5SDimitry Andric //  /* The RW PT_LOAD starts here*/
11470b57cec5SDimitry Andric //  rw_sec : { *(rw_sec) }
11480b57cec5SDimitry Andric // would mean that the RW PT_LOAD would become unaligned.
11490b57cec5SDimitry Andric static bool shouldSkip(BaseCommand *cmd) {
11500b57cec5SDimitry Andric   if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
11510b57cec5SDimitry Andric     return assign->name != ".";
11520b57cec5SDimitry Andric   return false;
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric // We want to place orphan sections so that they share as much
11560b57cec5SDimitry Andric // characteristics with their neighbors as possible. For example, if
11570b57cec5SDimitry Andric // both are rw, or both are tls.
11580b57cec5SDimitry Andric static std::vector<BaseCommand *>::iterator
11590b57cec5SDimitry Andric findOrphanPos(std::vector<BaseCommand *>::iterator b,
11600b57cec5SDimitry Andric               std::vector<BaseCommand *>::iterator e) {
11610b57cec5SDimitry Andric   OutputSection *sec = cast<OutputSection>(*e);
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   // Find the first element that has as close a rank as possible.
11640b57cec5SDimitry Andric   auto i = std::max_element(b, e, [=](BaseCommand *a, BaseCommand *b) {
11650b57cec5SDimitry Andric     return getRankProximity(sec, a) < getRankProximity(sec, b);
11660b57cec5SDimitry Andric   });
11670b57cec5SDimitry Andric   if (i == e)
11680b57cec5SDimitry Andric     return e;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // Consider all existing sections with the same proximity.
11710b57cec5SDimitry Andric   int proximity = getRankProximity(sec, *i);
11720b57cec5SDimitry Andric   for (; i != e; ++i) {
11730b57cec5SDimitry Andric     auto *curSec = dyn_cast<OutputSection>(*i);
11740b57cec5SDimitry Andric     if (!curSec || !curSec->hasInputSections)
11750b57cec5SDimitry Andric       continue;
11760b57cec5SDimitry Andric     if (getRankProximity(sec, curSec) != proximity ||
11770b57cec5SDimitry Andric         sec->sortRank < curSec->sortRank)
11780b57cec5SDimitry Andric       break;
11790b57cec5SDimitry Andric   }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   auto isOutputSecWithInputSections = [](BaseCommand *cmd) {
11820b57cec5SDimitry Andric     auto *os = dyn_cast<OutputSection>(cmd);
11830b57cec5SDimitry Andric     return os && os->hasInputSections;
11840b57cec5SDimitry Andric   };
11850b57cec5SDimitry Andric   auto j = std::find_if(llvm::make_reverse_iterator(i),
11860b57cec5SDimitry Andric                         llvm::make_reverse_iterator(b),
11870b57cec5SDimitry Andric                         isOutputSecWithInputSections);
11880b57cec5SDimitry Andric   i = j.base();
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   // As a special case, if the orphan section is the last section, put
11910b57cec5SDimitry Andric   // it at the very end, past any other commands.
11920b57cec5SDimitry Andric   // This matches bfd's behavior and is convenient when the linker script fully
11930b57cec5SDimitry Andric   // specifies the start of the file, but doesn't care about the end (the non
11940b57cec5SDimitry Andric   // alloc sections for example).
11950b57cec5SDimitry Andric   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
11960b57cec5SDimitry Andric   if (nextSec == e)
11970b57cec5SDimitry Andric     return e;
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   while (i != e && shouldSkip(*i))
12000b57cec5SDimitry Andric     ++i;
12010b57cec5SDimitry Andric   return i;
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric // Builds section order for handling --symbol-ordering-file.
12050b57cec5SDimitry Andric static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
12060b57cec5SDimitry Andric   DenseMap<const InputSectionBase *, int> sectionOrder;
12070b57cec5SDimitry Andric   // Use the rarely used option -call-graph-ordering-file to sort sections.
12080b57cec5SDimitry Andric   if (!config->callGraphProfile.empty())
12090b57cec5SDimitry Andric     return computeCallGraphProfileOrder();
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric   if (config->symbolOrderingFile.empty())
12120b57cec5SDimitry Andric     return sectionOrder;
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   struct SymbolOrderEntry {
12150b57cec5SDimitry Andric     int priority;
12160b57cec5SDimitry Andric     bool present;
12170b57cec5SDimitry Andric   };
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric   // Build a map from symbols to their priorities. Symbols that didn't
12200b57cec5SDimitry Andric   // appear in the symbol ordering file have the lowest priority 0.
12210b57cec5SDimitry Andric   // All explicitly mentioned symbols have negative (higher) priorities.
12220b57cec5SDimitry Andric   DenseMap<StringRef, SymbolOrderEntry> symbolOrder;
12230b57cec5SDimitry Andric   int priority = -config->symbolOrderingFile.size();
12240b57cec5SDimitry Andric   for (StringRef s : config->symbolOrderingFile)
12250b57cec5SDimitry Andric     symbolOrder.insert({s, {priority++, false}});
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   // Build a map from sections to their priorities.
12280b57cec5SDimitry Andric   auto addSym = [&](Symbol &sym) {
12290b57cec5SDimitry Andric     auto it = symbolOrder.find(sym.getName());
12300b57cec5SDimitry Andric     if (it == symbolOrder.end())
12310b57cec5SDimitry Andric       return;
12320b57cec5SDimitry Andric     SymbolOrderEntry &ent = it->second;
12330b57cec5SDimitry Andric     ent.present = true;
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric     maybeWarnUnorderableSymbol(&sym);
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric     if (auto *d = dyn_cast<Defined>(&sym)) {
12380b57cec5SDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
12390b57cec5SDimitry Andric         int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)];
12400b57cec5SDimitry Andric         priority = std::min(priority, ent.priority);
12410b57cec5SDimitry Andric       }
12420b57cec5SDimitry Andric     }
12430b57cec5SDimitry Andric   };
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric   // We want both global and local symbols. We get the global ones from the
12460b57cec5SDimitry Andric   // symbol table and iterate the object files for the local ones.
1247*480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols())
12480b57cec5SDimitry Andric     if (!sym->isLazy())
12490b57cec5SDimitry Andric       addSym(*sym);
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   for (InputFile *file : objectFiles)
12520b57cec5SDimitry Andric     for (Symbol *sym : file->getSymbols())
12530b57cec5SDimitry Andric       if (sym->isLocal())
12540b57cec5SDimitry Andric         addSym(*sym);
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric   if (config->warnSymbolOrdering)
12570b57cec5SDimitry Andric     for (auto orderEntry : symbolOrder)
12580b57cec5SDimitry Andric       if (!orderEntry.second.present)
12590b57cec5SDimitry Andric         warn("symbol ordering file: no such symbol: " + orderEntry.first);
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric   return sectionOrder;
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric // Sorts the sections in ISD according to the provided section order.
12650b57cec5SDimitry Andric static void
12660b57cec5SDimitry Andric sortISDBySectionOrder(InputSectionDescription *isd,
12670b57cec5SDimitry Andric                       const DenseMap<const InputSectionBase *, int> &order) {
12680b57cec5SDimitry Andric   std::vector<InputSection *> unorderedSections;
12690b57cec5SDimitry Andric   std::vector<std::pair<InputSection *, int>> orderedSections;
12700b57cec5SDimitry Andric   uint64_t unorderedSize = 0;
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   for (InputSection *isec : isd->sections) {
12730b57cec5SDimitry Andric     auto i = order.find(isec);
12740b57cec5SDimitry Andric     if (i == order.end()) {
12750b57cec5SDimitry Andric       unorderedSections.push_back(isec);
12760b57cec5SDimitry Andric       unorderedSize += isec->getSize();
12770b57cec5SDimitry Andric       continue;
12780b57cec5SDimitry Andric     }
12790b57cec5SDimitry Andric     orderedSections.push_back({isec, i->second});
12800b57cec5SDimitry Andric   }
128185868e8aSDimitry Andric   llvm::sort(orderedSections, llvm::less_second());
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric   // Find an insertion point for the ordered section list in the unordered
12840b57cec5SDimitry Andric   // section list. On targets with limited-range branches, this is the mid-point
12850b57cec5SDimitry Andric   // of the unordered section list. This decreases the likelihood that a range
12860b57cec5SDimitry Andric   // extension thunk will be needed to enter or exit the ordered region. If the
12870b57cec5SDimitry Andric   // ordered section list is a list of hot functions, we can generally expect
12880b57cec5SDimitry Andric   // the ordered functions to be called more often than the unordered functions,
12890b57cec5SDimitry Andric   // making it more likely that any particular call will be within range, and
12900b57cec5SDimitry Andric   // therefore reducing the number of thunks required.
12910b57cec5SDimitry Andric   //
12920b57cec5SDimitry Andric   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
12930b57cec5SDimitry Andric   // If the layout is:
12940b57cec5SDimitry Andric   //
12950b57cec5SDimitry Andric   // 8MB hot
12960b57cec5SDimitry Andric   // 32MB cold
12970b57cec5SDimitry Andric   //
12980b57cec5SDimitry Andric   // only the first 8-16MB of the cold code (depending on which hot function it
12990b57cec5SDimitry Andric   // is actually calling) can call the hot code without a range extension thunk.
13000b57cec5SDimitry Andric   // However, if we use this layout:
13010b57cec5SDimitry Andric   //
13020b57cec5SDimitry Andric   // 16MB cold
13030b57cec5SDimitry Andric   // 8MB hot
13040b57cec5SDimitry Andric   // 16MB cold
13050b57cec5SDimitry Andric   //
13060b57cec5SDimitry Andric   // both the last 8-16MB of the first block of cold code and the first 8-16MB
13070b57cec5SDimitry Andric   // of the second block of cold code can call the hot code without a thunk. So
13080b57cec5SDimitry Andric   // we effectively double the amount of code that could potentially call into
13090b57cec5SDimitry Andric   // the hot code without a thunk.
13100b57cec5SDimitry Andric   size_t insPt = 0;
13110b57cec5SDimitry Andric   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
13120b57cec5SDimitry Andric     uint64_t unorderedPos = 0;
13130b57cec5SDimitry Andric     for (; insPt != unorderedSections.size(); ++insPt) {
13140b57cec5SDimitry Andric       unorderedPos += unorderedSections[insPt]->getSize();
13150b57cec5SDimitry Andric       if (unorderedPos > unorderedSize / 2)
13160b57cec5SDimitry Andric         break;
13170b57cec5SDimitry Andric     }
13180b57cec5SDimitry Andric   }
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric   isd->sections.clear();
13210b57cec5SDimitry Andric   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
13220b57cec5SDimitry Andric     isd->sections.push_back(isec);
13230b57cec5SDimitry Andric   for (std::pair<InputSection *, int> p : orderedSections)
13240b57cec5SDimitry Andric     isd->sections.push_back(p.first);
13250b57cec5SDimitry Andric   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
13260b57cec5SDimitry Andric     isd->sections.push_back(isec);
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric static void sortSection(OutputSection *sec,
13300b57cec5SDimitry Andric                         const DenseMap<const InputSectionBase *, int> &order) {
13310b57cec5SDimitry Andric   StringRef name = sec->name;
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   // Sort input sections by section name suffixes for
13340b57cec5SDimitry Andric   // __attribute__((init_priority(N))).
13350b57cec5SDimitry Andric   if (name == ".init_array" || name == ".fini_array") {
13360b57cec5SDimitry Andric     if (!script->hasSectionsCommand)
13370b57cec5SDimitry Andric       sec->sortInitFini();
13380b57cec5SDimitry Andric     return;
13390b57cec5SDimitry Andric   }
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric   // Sort input sections by the special rule for .ctors and .dtors.
13420b57cec5SDimitry Andric   if (name == ".ctors" || name == ".dtors") {
13430b57cec5SDimitry Andric     if (!script->hasSectionsCommand)
13440b57cec5SDimitry Andric       sec->sortCtorsDtors();
13450b57cec5SDimitry Andric     return;
13460b57cec5SDimitry Andric   }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   // Never sort these.
13490b57cec5SDimitry Andric   if (name == ".init" || name == ".fini")
13500b57cec5SDimitry Andric     return;
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   // .toc is allocated just after .got and is accessed using GOT-relative
13530b57cec5SDimitry Andric   // relocations. Object files compiled with small code model have an
13540b57cec5SDimitry Andric   // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
13550b57cec5SDimitry Andric   // To reduce the risk of relocation overflow, .toc contents are sorted so that
13560b57cec5SDimitry Andric   // sections having smaller relocation offsets are at beginning of .toc
13570b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 && name == ".toc") {
13580b57cec5SDimitry Andric     if (script->hasSectionsCommand)
13590b57cec5SDimitry Andric       return;
13600b57cec5SDimitry Andric     assert(sec->sectionCommands.size() == 1);
13610b57cec5SDimitry Andric     auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]);
13620b57cec5SDimitry Andric     llvm::stable_sort(isd->sections,
13630b57cec5SDimitry Andric                       [](const InputSection *a, const InputSection *b) -> bool {
13640b57cec5SDimitry Andric                         return a->file->ppc64SmallCodeModelTocRelocs &&
13650b57cec5SDimitry Andric                                !b->file->ppc64SmallCodeModelTocRelocs;
13660b57cec5SDimitry Andric                       });
13670b57cec5SDimitry Andric     return;
13680b57cec5SDimitry Andric   }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   // Sort input sections by priority using the list provided
13710b57cec5SDimitry Andric   // by --symbol-ordering-file.
13720b57cec5SDimitry Andric   if (!order.empty())
13730b57cec5SDimitry Andric     for (BaseCommand *b : sec->sectionCommands)
13740b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(b))
13750b57cec5SDimitry Andric         sortISDBySectionOrder(isd, order);
13760b57cec5SDimitry Andric }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric // If no layout was provided by linker script, we want to apply default
13790b57cec5SDimitry Andric // sorting for special input sections. This also handles --symbol-ordering-file.
13800b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::sortInputSections() {
13810b57cec5SDimitry Andric   // Build the order once since it is expensive.
13820b57cec5SDimitry Andric   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
13830b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands)
13840b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base))
13850b57cec5SDimitry Andric       sortSection(sec, order);
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::sortSections() {
13890b57cec5SDimitry Andric   script->adjustSectionsBeforeSorting();
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric   // Don't sort if using -r. It is not necessary and we want to preserve the
13920b57cec5SDimitry Andric   // relative order for SHF_LINK_ORDER sections.
13930b57cec5SDimitry Andric   if (config->relocatable)
13940b57cec5SDimitry Andric     return;
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   sortInputSections();
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands) {
13990b57cec5SDimitry Andric     auto *os = dyn_cast<OutputSection>(base);
14000b57cec5SDimitry Andric     if (!os)
14010b57cec5SDimitry Andric       continue;
14020b57cec5SDimitry Andric     os->sortRank = getSectionRank(os);
14030b57cec5SDimitry Andric 
14040b57cec5SDimitry Andric     // We want to assign rude approximation values to outSecOff fields
14050b57cec5SDimitry Andric     // to know the relative order of the input sections. We use it for
14060b57cec5SDimitry Andric     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
14070b57cec5SDimitry Andric     uint64_t i = 0;
14080b57cec5SDimitry Andric     for (InputSection *sec : getInputSections(os))
14090b57cec5SDimitry Andric       sec->outSecOff = i++;
14100b57cec5SDimitry Andric   }
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric   if (!script->hasSectionsCommand) {
14130b57cec5SDimitry Andric     // We know that all the OutputSections are contiguous in this case.
14140b57cec5SDimitry Andric     auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); };
14150b57cec5SDimitry Andric     std::stable_sort(
14160b57cec5SDimitry Andric         llvm::find_if(script->sectionCommands, isSection),
14170b57cec5SDimitry Andric         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
14180b57cec5SDimitry Andric         compareSections);
14190b57cec5SDimitry Andric     return;
14200b57cec5SDimitry Andric   }
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric   // Orphan sections are sections present in the input files which are
14230b57cec5SDimitry Andric   // not explicitly placed into the output file by the linker script.
14240b57cec5SDimitry Andric   //
14250b57cec5SDimitry Andric   // The sections in the linker script are already in the correct
14260b57cec5SDimitry Andric   // order. We have to figuere out where to insert the orphan
14270b57cec5SDimitry Andric   // sections.
14280b57cec5SDimitry Andric   //
14290b57cec5SDimitry Andric   // The order of the sections in the script is arbitrary and may not agree with
14300b57cec5SDimitry Andric   // compareSections. This means that we cannot easily define a strict weak
14310b57cec5SDimitry Andric   // ordering. To see why, consider a comparison of a section in the script and
14320b57cec5SDimitry Andric   // one not in the script. We have a two simple options:
14330b57cec5SDimitry Andric   // * Make them equivalent (a is not less than b, and b is not less than a).
14340b57cec5SDimitry Andric   //   The problem is then that equivalence has to be transitive and we can
14350b57cec5SDimitry Andric   //   have sections a, b and c with only b in a script and a less than c
14360b57cec5SDimitry Andric   //   which breaks this property.
14370b57cec5SDimitry Andric   // * Use compareSectionsNonScript. Given that the script order doesn't have
14380b57cec5SDimitry Andric   //   to match, we can end up with sections a, b, c, d where b and c are in the
14390b57cec5SDimitry Andric   //   script and c is compareSectionsNonScript less than b. In which case d
14400b57cec5SDimitry Andric   //   can be equivalent to c, a to b and d < a. As a concrete example:
14410b57cec5SDimitry Andric   //   .a (rx) # not in script
14420b57cec5SDimitry Andric   //   .b (rx) # in script
14430b57cec5SDimitry Andric   //   .c (ro) # in script
14440b57cec5SDimitry Andric   //   .d (ro) # not in script
14450b57cec5SDimitry Andric   //
14460b57cec5SDimitry Andric   // The way we define an order then is:
14470b57cec5SDimitry Andric   // *  Sort only the orphan sections. They are in the end right now.
14480b57cec5SDimitry Andric   // *  Move each orphan section to its preferred position. We try
14490b57cec5SDimitry Andric   //    to put each section in the last position where it can share
14500b57cec5SDimitry Andric   //    a PT_LOAD.
14510b57cec5SDimitry Andric   //
14520b57cec5SDimitry Andric   // There is some ambiguity as to where exactly a new entry should be
14530b57cec5SDimitry Andric   // inserted, because Commands contains not only output section
14540b57cec5SDimitry Andric   // commands but also other types of commands such as symbol assignment
14550b57cec5SDimitry Andric   // expressions. There's no correct answer here due to the lack of the
14560b57cec5SDimitry Andric   // formal specification of the linker script. We use heuristics to
14570b57cec5SDimitry Andric   // determine whether a new output command should be added before or
14580b57cec5SDimitry Andric   // after another commands. For the details, look at shouldSkip
14590b57cec5SDimitry Andric   // function.
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   auto i = script->sectionCommands.begin();
14620b57cec5SDimitry Andric   auto e = script->sectionCommands.end();
14630b57cec5SDimitry Andric   auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) {
14640b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base))
14650b57cec5SDimitry Andric       return sec->sectionIndex == UINT32_MAX;
14660b57cec5SDimitry Andric     return false;
14670b57cec5SDimitry Andric   });
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   // Sort the orphan sections.
14700b57cec5SDimitry Andric   std::stable_sort(nonScriptI, e, compareSections);
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   // As a horrible special case, skip the first . assignment if it is before any
14730b57cec5SDimitry Andric   // section. We do this because it is common to set a load address by starting
14740b57cec5SDimitry Andric   // the script with ". = 0xabcd" and the expectation is that every section is
14750b57cec5SDimitry Andric   // after that.
14760b57cec5SDimitry Andric   auto firstSectionOrDotAssignment =
14770b57cec5SDimitry Andric       std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); });
14780b57cec5SDimitry Andric   if (firstSectionOrDotAssignment != e &&
14790b57cec5SDimitry Andric       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
14800b57cec5SDimitry Andric     ++firstSectionOrDotAssignment;
14810b57cec5SDimitry Andric   i = firstSectionOrDotAssignment;
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   while (nonScriptI != e) {
14840b57cec5SDimitry Andric     auto pos = findOrphanPos(i, nonScriptI);
14850b57cec5SDimitry Andric     OutputSection *orphan = cast<OutputSection>(*nonScriptI);
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric     // As an optimization, find all sections with the same sort rank
14880b57cec5SDimitry Andric     // and insert them with one rotate.
14890b57cec5SDimitry Andric     unsigned rank = orphan->sortRank;
14900b57cec5SDimitry Andric     auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) {
14910b57cec5SDimitry Andric       return cast<OutputSection>(cmd)->sortRank != rank;
14920b57cec5SDimitry Andric     });
14930b57cec5SDimitry Andric     std::rotate(pos, nonScriptI, end);
14940b57cec5SDimitry Andric     nonScriptI = end;
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric   script->adjustSectionsAfterSorting();
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric static bool compareByFilePosition(InputSection *a, InputSection *b) {
15010b57cec5SDimitry Andric   InputSection *la = a->getLinkOrderDep();
15020b57cec5SDimitry Andric   InputSection *lb = b->getLinkOrderDep();
15030b57cec5SDimitry Andric   OutputSection *aOut = la->getParent();
15040b57cec5SDimitry Andric   OutputSection *bOut = lb->getParent();
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   if (aOut != bOut)
15070b57cec5SDimitry Andric     return aOut->sectionIndex < bOut->sectionIndex;
15080b57cec5SDimitry Andric   return la->outSecOff < lb->outSecOff;
15090b57cec5SDimitry Andric }
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
15120b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
15130b57cec5SDimitry Andric     if (!(sec->flags & SHF_LINK_ORDER))
15140b57cec5SDimitry Andric       continue;
15150b57cec5SDimitry Andric 
151685868e8aSDimitry Andric     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
151785868e8aSDimitry Andric     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
151885868e8aSDimitry Andric     if (!config->relocatable && config->emachine == EM_ARM &&
151985868e8aSDimitry Andric         sec->type == SHT_ARM_EXIDX)
152085868e8aSDimitry Andric       continue;
152185868e8aSDimitry Andric 
15220b57cec5SDimitry Andric     // Link order may be distributed across several InputSectionDescriptions
15230b57cec5SDimitry Andric     // but sort must consider them all at once.
15240b57cec5SDimitry Andric     std::vector<InputSection **> scriptSections;
15250b57cec5SDimitry Andric     std::vector<InputSection *> sections;
15260b57cec5SDimitry Andric     for (BaseCommand *base : sec->sectionCommands) {
15270b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(base)) {
15280b57cec5SDimitry Andric         for (InputSection *&isec : isd->sections) {
15290b57cec5SDimitry Andric           scriptSections.push_back(&isec);
15300b57cec5SDimitry Andric           sections.push_back(isec);
153185868e8aSDimitry Andric 
153285868e8aSDimitry Andric           InputSection *link = isec->getLinkOrderDep();
153385868e8aSDimitry Andric           if (!link->getParent())
153485868e8aSDimitry Andric             error(toString(isec) + ": sh_link points to discarded section " +
153585868e8aSDimitry Andric                   toString(link));
15360b57cec5SDimitry Andric         }
15370b57cec5SDimitry Andric       }
15380b57cec5SDimitry Andric     }
15390b57cec5SDimitry Andric 
154085868e8aSDimitry Andric     if (errorCount())
15410b57cec5SDimitry Andric       continue;
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric     llvm::stable_sort(sections, compareByFilePosition);
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric     for (int i = 0, n = sections.size(); i < n; ++i)
15460b57cec5SDimitry Andric       *scriptSections[i] = sections[i];
15470b57cec5SDimitry Andric   }
15480b57cec5SDimitry Andric }
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric // We need to generate and finalize the content that depends on the address of
15510b57cec5SDimitry Andric // InputSections. As the generation of the content may also alter InputSection
15520b57cec5SDimitry Andric // addresses we must converge to a fixed point. We do that here. See the comment
15530b57cec5SDimitry Andric // in Writer<ELFT>::finalizeSections().
15540b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
15550b57cec5SDimitry Andric   ThunkCreator tc;
15560b57cec5SDimitry Andric   AArch64Err843419Patcher a64p;
155785868e8aSDimitry Andric   ARMErr657417Patcher a32p;
15580b57cec5SDimitry Andric   script->assignAddresses();
15590b57cec5SDimitry Andric 
156085868e8aSDimitry Andric   int assignPasses = 0;
156185868e8aSDimitry Andric   for (;;) {
156285868e8aSDimitry Andric     bool changed = target->needsThunks && tc.createThunks(outputSections);
156385868e8aSDimitry Andric 
156485868e8aSDimitry Andric     // With Thunk Size much smaller than branch range we expect to
156585868e8aSDimitry Andric     // converge quickly; if we get to 10 something has gone wrong.
156685868e8aSDimitry Andric     if (changed && tc.pass >= 10) {
156785868e8aSDimitry Andric       error("thunk creation not converged");
156885868e8aSDimitry Andric       break;
156985868e8aSDimitry Andric     }
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric     if (config->fixCortexA53Errata843419) {
15720b57cec5SDimitry Andric       if (changed)
15730b57cec5SDimitry Andric         script->assignAddresses();
15740b57cec5SDimitry Andric       changed |= a64p.createFixes();
15750b57cec5SDimitry Andric     }
157685868e8aSDimitry Andric     if (config->fixCortexA8) {
157785868e8aSDimitry Andric       if (changed)
157885868e8aSDimitry Andric         script->assignAddresses();
157985868e8aSDimitry Andric       changed |= a32p.createFixes();
158085868e8aSDimitry Andric     }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric     if (in.mipsGot)
15830b57cec5SDimitry Andric       in.mipsGot->updateAllocSize();
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric     for (Partition &part : partitions) {
15860b57cec5SDimitry Andric       changed |= part.relaDyn->updateAllocSize();
15870b57cec5SDimitry Andric       if (part.relrDyn)
15880b57cec5SDimitry Andric         changed |= part.relrDyn->updateAllocSize();
15890b57cec5SDimitry Andric     }
15900b57cec5SDimitry Andric 
159185868e8aSDimitry Andric     const Defined *changedSym = script->assignAddresses();
159285868e8aSDimitry Andric     if (!changed) {
159385868e8aSDimitry Andric       // Some symbols may be dependent on section addresses. When we break the
159485868e8aSDimitry Andric       // loop, the symbol values are finalized because a previous
159585868e8aSDimitry Andric       // assignAddresses() finalized section addresses.
159685868e8aSDimitry Andric       if (!changedSym)
159785868e8aSDimitry Andric         break;
159885868e8aSDimitry Andric       if (++assignPasses == 5) {
159985868e8aSDimitry Andric         errorOrWarn("assignment to symbol " + toString(*changedSym) +
160085868e8aSDimitry Andric                     " does not converge");
160185868e8aSDimitry Andric         break;
160285868e8aSDimitry Andric       }
160385868e8aSDimitry Andric     }
16040b57cec5SDimitry Andric   }
16050b57cec5SDimitry Andric }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric static void finalizeSynthetic(SyntheticSection *sec) {
16080b57cec5SDimitry Andric   if (sec && sec->isNeeded() && sec->getParent())
16090b57cec5SDimitry Andric     sec->finalizeContents();
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric // In order to allow users to manipulate linker-synthesized sections,
16130b57cec5SDimitry Andric // we had to add synthetic sections to the input section list early,
16140b57cec5SDimitry Andric // even before we make decisions whether they are needed. This allows
16150b57cec5SDimitry Andric // users to write scripts like this: ".mygot : { .got }".
16160b57cec5SDimitry Andric //
16170b57cec5SDimitry Andric // Doing it has an unintended side effects. If it turns out that we
16180b57cec5SDimitry Andric // don't need a .got (for example) at all because there's no
16190b57cec5SDimitry Andric // relocation that needs a .got, we don't want to emit .got.
16200b57cec5SDimitry Andric //
16210b57cec5SDimitry Andric // To deal with the above problem, this function is called after
16220b57cec5SDimitry Andric // scanRelocations is called to remove synthetic sections that turn
16230b57cec5SDimitry Andric // out to be empty.
16240b57cec5SDimitry Andric static void removeUnusedSyntheticSections() {
16250b57cec5SDimitry Andric   // All input synthetic sections that can be empty are placed after
16260b57cec5SDimitry Andric   // all regular ones. We iterate over them all and exit at first
16270b57cec5SDimitry Andric   // non-synthetic.
16280b57cec5SDimitry Andric   for (InputSectionBase *s : llvm::reverse(inputSections)) {
16290b57cec5SDimitry Andric     SyntheticSection *ss = dyn_cast<SyntheticSection>(s);
16300b57cec5SDimitry Andric     if (!ss)
16310b57cec5SDimitry Andric       return;
16320b57cec5SDimitry Andric     OutputSection *os = ss->getParent();
16330b57cec5SDimitry Andric     if (!os || ss->isNeeded())
16340b57cec5SDimitry Andric       continue;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric     // If we reach here, then SS is an unused synthetic section and we want to
16370b57cec5SDimitry Andric     // remove it from corresponding input section description of output section.
16380b57cec5SDimitry Andric     for (BaseCommand *b : os->sectionCommands)
16390b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(b))
16400b57cec5SDimitry Andric         llvm::erase_if(isd->sections,
16410b57cec5SDimitry Andric                        [=](InputSection *isec) { return isec == ss; });
16420b57cec5SDimitry Andric   }
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric // Create output section objects and add them to OutputSections.
16460b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::finalizeSections() {
16470b57cec5SDimitry Andric   Out::preinitArray = findSection(".preinit_array");
16480b57cec5SDimitry Andric   Out::initArray = findSection(".init_array");
16490b57cec5SDimitry Andric   Out::finiArray = findSection(".fini_array");
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
16520b57cec5SDimitry Andric   // symbols for sections, so that the runtime can get the start and end
16530b57cec5SDimitry Andric   // addresses of each section by section name. Add such symbols.
16540b57cec5SDimitry Andric   if (!config->relocatable) {
16550b57cec5SDimitry Andric     addStartEndSymbols();
16560b57cec5SDimitry Andric     for (BaseCommand *base : script->sectionCommands)
16570b57cec5SDimitry Andric       if (auto *sec = dyn_cast<OutputSection>(base))
16580b57cec5SDimitry Andric         addStartStopSymbols(sec);
16590b57cec5SDimitry Andric   }
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
16620b57cec5SDimitry Andric   // It should be okay as no one seems to care about the type.
16630b57cec5SDimitry Andric   // Even the author of gold doesn't remember why gold behaves that way.
16640b57cec5SDimitry Andric   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
16650b57cec5SDimitry Andric   if (mainPart->dynamic->parent)
16660b57cec5SDimitry Andric     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK,
16670b57cec5SDimitry Andric                               STV_HIDDEN, STT_NOTYPE,
16680b57cec5SDimitry Andric                               /*value=*/0, /*size=*/0, mainPart->dynamic});
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric   // Define __rel[a]_iplt_{start,end} symbols if needed.
16710b57cec5SDimitry Andric   addRelIpltSymbols();
16720b57cec5SDimitry Andric 
167385868e8aSDimitry Andric   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
167485868e8aSDimitry Andric   // should only be defined in an executable. If .sdata does not exist, its
167585868e8aSDimitry Andric   // value/section does not matter but it has to be relative, so set its
167685868e8aSDimitry Andric   // st_shndx arbitrarily to 1 (Out::elfHeader).
167785868e8aSDimitry Andric   if (config->emachine == EM_RISCV && !config->shared) {
167885868e8aSDimitry Andric     OutputSection *sec = findSection(".sdata");
16790b57cec5SDimitry Andric     ElfSym::riscvGlobalPointer =
168085868e8aSDimitry Andric         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
168185868e8aSDimitry Andric                            0x800, STV_DEFAULT, STB_GLOBAL);
168285868e8aSDimitry Andric   }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   if (config->emachine == EM_X86_64) {
16850b57cec5SDimitry Andric     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
16860b57cec5SDimitry Andric     // way that:
16870b57cec5SDimitry Andric     //
16880b57cec5SDimitry Andric     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
16890b57cec5SDimitry Andric     // computes 0.
16900b57cec5SDimitry Andric     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
16910b57cec5SDimitry Andric     // the TLS block).
16920b57cec5SDimitry Andric     //
16930b57cec5SDimitry Andric     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
16940b57cec5SDimitry Andric     // an absolute symbol of zero. This is different from GNU linkers which
16950b57cec5SDimitry Andric     // define _TLS_MODULE_BASE_ relative to the first TLS section.
16960b57cec5SDimitry Andric     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
16970b57cec5SDimitry Andric     if (s && s->isUndefined()) {
16980b57cec5SDimitry Andric       s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN,
16990b57cec5SDimitry Andric                          STT_TLS, /*value=*/0, 0,
17000b57cec5SDimitry Andric                          /*section=*/nullptr});
17010b57cec5SDimitry Andric       ElfSym::tlsModuleBase = cast<Defined>(s);
17020b57cec5SDimitry Andric     }
17030b57cec5SDimitry Andric   }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   // This responsible for splitting up .eh_frame section into
17060b57cec5SDimitry Andric   // pieces. The relocation scan uses those pieces, so this has to be
17070b57cec5SDimitry Andric   // earlier.
17080b57cec5SDimitry Andric   for (Partition &part : partitions)
17090b57cec5SDimitry Andric     finalizeSynthetic(part.ehFrame);
17100b57cec5SDimitry Andric 
1711*480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols())
1712*480093f4SDimitry Andric     sym->isPreemptible = computeIsPreemptible(*sym);
171385868e8aSDimitry Andric 
171485868e8aSDimitry Andric   // Change values of linker-script-defined symbols from placeholders (assigned
171585868e8aSDimitry Andric   // by declareSymbols) to actual definitions.
171685868e8aSDimitry Andric   script->processSymbolAssignments();
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   // Scan relocations. This must be done after every symbol is declared so that
171985868e8aSDimitry Andric   // we can correctly decide if a dynamic relocation is needed. This is called
172085868e8aSDimitry Andric   // after processSymbolAssignments() because it needs to know whether a
172185868e8aSDimitry Andric   // linker-script-defined symbol is absolute.
17220b57cec5SDimitry Andric   if (!config->relocatable) {
17230b57cec5SDimitry Andric     forEachRelSec(scanRelocations<ELFT>);
17240b57cec5SDimitry Andric     reportUndefinedSymbols<ELFT>();
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (in.plt && in.plt->isNeeded())
17280b57cec5SDimitry Andric     in.plt->addSymbols();
17290b57cec5SDimitry Andric   if (in.iplt && in.iplt->isNeeded())
17300b57cec5SDimitry Andric     in.iplt->addSymbols();
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   if (!config->allowShlibUndefined) {
17330b57cec5SDimitry Andric     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1734*480093f4SDimitry Andric     // entries are seen. These cases would otherwise lead to runtime errors
17350b57cec5SDimitry Andric     // reported by the dynamic linker.
17360b57cec5SDimitry Andric     //
17370b57cec5SDimitry Andric     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
17380b57cec5SDimitry Andric     // catch more cases. That is too much for us. Our approach resembles the one
17390b57cec5SDimitry Andric     // used in ld.gold, achieves a good balance to be useful but not too smart.
17400b57cec5SDimitry Andric     for (SharedFile *file : sharedFiles)
17410b57cec5SDimitry Andric       file->allNeededIsKnown =
17420b57cec5SDimitry Andric           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
17430b57cec5SDimitry Andric             return symtab->soNames.count(needed);
17440b57cec5SDimitry Andric           });
17450b57cec5SDimitry Andric 
1746*480093f4SDimitry Andric     for (Symbol *sym : symtab->symbols())
17470b57cec5SDimitry Andric       if (sym->isUndefined() && !sym->isWeak())
17480b57cec5SDimitry Andric         if (auto *f = dyn_cast_or_null<SharedFile>(sym->file))
17490b57cec5SDimitry Andric           if (f->allNeededIsKnown)
17500b57cec5SDimitry Andric             error(toString(f) + ": undefined reference to " + toString(*sym));
17510b57cec5SDimitry Andric   }
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   // Now that we have defined all possible global symbols including linker-
17540b57cec5SDimitry Andric   // synthesized ones. Visit all symbols to give the finishing touches.
1755*480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
17560b57cec5SDimitry Andric     if (!includeInSymtab(*sym))
1757*480093f4SDimitry Andric       continue;
17580b57cec5SDimitry Andric     if (in.symTab)
17590b57cec5SDimitry Andric       in.symTab->addSymbol(sym);
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric     if (sym->includeInDynsym()) {
17620b57cec5SDimitry Andric       partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
17630b57cec5SDimitry Andric       if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
17640b57cec5SDimitry Andric         if (file->isNeeded && !sym->isUndefined())
17650b57cec5SDimitry Andric           addVerneed(sym);
17660b57cec5SDimitry Andric     }
1767*480093f4SDimitry Andric   }
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   // We also need to scan the dynamic relocation tables of the other partitions
17700b57cec5SDimitry Andric   // and add any referenced symbols to the partition's dynsym.
17710b57cec5SDimitry Andric   for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
17720b57cec5SDimitry Andric     DenseSet<Symbol *> syms;
17730b57cec5SDimitry Andric     for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
17740b57cec5SDimitry Andric       syms.insert(e.sym);
17750b57cec5SDimitry Andric     for (DynamicReloc &reloc : part.relaDyn->relocs)
17760b57cec5SDimitry Andric       if (reloc.sym && !reloc.useSymVA && syms.insert(reloc.sym).second)
17770b57cec5SDimitry Andric         part.dynSymTab->addSymbol(reloc.sym);
17780b57cec5SDimitry Andric   }
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   // Do not proceed if there was an undefined symbol.
17810b57cec5SDimitry Andric   if (errorCount())
17820b57cec5SDimitry Andric     return;
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   if (in.mipsGot)
17850b57cec5SDimitry Andric     in.mipsGot->build();
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   removeUnusedSyntheticSections();
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   sortSections();
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric   // Now that we have the final list, create a list of all the
17920b57cec5SDimitry Andric   // OutputSections for convenience.
17930b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands)
17940b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base))
17950b57cec5SDimitry Andric       outputSections.push_back(sec);
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   // Prefer command line supplied address over other constraints.
17980b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
17990b57cec5SDimitry Andric     auto i = config->sectionStartMap.find(sec->name);
18000b57cec5SDimitry Andric     if (i != config->sectionStartMap.end())
18010b57cec5SDimitry Andric       sec->addrExpr = [=] { return i->second; };
18020b57cec5SDimitry Andric   }
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   // This is a bit of a hack. A value of 0 means undef, so we set it
18050b57cec5SDimitry Andric   // to 1 to make __ehdr_start defined. The section number is not
18060b57cec5SDimitry Andric   // particularly relevant.
18070b57cec5SDimitry Andric   Out::elfHeader->sectionIndex = 1;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   for (size_t i = 0, e = outputSections.size(); i != e; ++i) {
18100b57cec5SDimitry Andric     OutputSection *sec = outputSections[i];
18110b57cec5SDimitry Andric     sec->sectionIndex = i + 1;
18120b57cec5SDimitry Andric     sec->shName = in.shStrTab->addString(sec->name);
18130b57cec5SDimitry Andric   }
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   // Binary and relocatable output does not have PHDRS.
18160b57cec5SDimitry Andric   // The headers have to be created before finalize as that can influence the
18170b57cec5SDimitry Andric   // image base and the dynamic section on mips includes the image base.
18180b57cec5SDimitry Andric   if (!config->relocatable && !config->oFormatBinary) {
18190b57cec5SDimitry Andric     for (Partition &part : partitions) {
18200b57cec5SDimitry Andric       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
18210b57cec5SDimitry Andric                                               : createPhdrs(part);
18220b57cec5SDimitry Andric       if (config->emachine == EM_ARM) {
18230b57cec5SDimitry Andric         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
18240b57cec5SDimitry Andric         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
18250b57cec5SDimitry Andric       }
18260b57cec5SDimitry Andric       if (config->emachine == EM_MIPS) {
18270b57cec5SDimitry Andric         // Add separate segments for MIPS-specific sections.
18280b57cec5SDimitry Andric         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
18290b57cec5SDimitry Andric         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
18300b57cec5SDimitry Andric         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
18310b57cec5SDimitry Andric       }
18320b57cec5SDimitry Andric     }
18330b57cec5SDimitry Andric     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric     // Find the TLS segment. This happens before the section layout loop so that
18360b57cec5SDimitry Andric     // Android relocation packing can look up TLS symbol addresses. We only need
18370b57cec5SDimitry Andric     // to care about the main partition here because all TLS symbols were moved
18380b57cec5SDimitry Andric     // to the main partition (see MarkLive.cpp).
18390b57cec5SDimitry Andric     for (PhdrEntry *p : mainPart->phdrs)
18400b57cec5SDimitry Andric       if (p->p_type == PT_TLS)
18410b57cec5SDimitry Andric         Out::tlsPhdr = p;
18420b57cec5SDimitry Andric   }
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric   // Some symbols are defined in term of program headers. Now that we
18450b57cec5SDimitry Andric   // have the headers, we can find out which sections they point to.
18460b57cec5SDimitry Andric   setReservedSymbolSections();
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric   finalizeSynthetic(in.bss);
18490b57cec5SDimitry Andric   finalizeSynthetic(in.bssRelRo);
18500b57cec5SDimitry Andric   finalizeSynthetic(in.symTabShndx);
18510b57cec5SDimitry Andric   finalizeSynthetic(in.shStrTab);
18520b57cec5SDimitry Andric   finalizeSynthetic(in.strTab);
18530b57cec5SDimitry Andric   finalizeSynthetic(in.got);
18540b57cec5SDimitry Andric   finalizeSynthetic(in.mipsGot);
18550b57cec5SDimitry Andric   finalizeSynthetic(in.igotPlt);
18560b57cec5SDimitry Andric   finalizeSynthetic(in.gotPlt);
18570b57cec5SDimitry Andric   finalizeSynthetic(in.relaIplt);
18580b57cec5SDimitry Andric   finalizeSynthetic(in.relaPlt);
18590b57cec5SDimitry Andric   finalizeSynthetic(in.plt);
18600b57cec5SDimitry Andric   finalizeSynthetic(in.iplt);
18610b57cec5SDimitry Andric   finalizeSynthetic(in.ppc32Got2);
18620b57cec5SDimitry Andric   finalizeSynthetic(in.partIndex);
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   // Dynamic section must be the last one in this list and dynamic
18650b57cec5SDimitry Andric   // symbol table section (dynSymTab) must be the first one.
18660b57cec5SDimitry Andric   for (Partition &part : partitions) {
18670b57cec5SDimitry Andric     finalizeSynthetic(part.armExidx);
18680b57cec5SDimitry Andric     finalizeSynthetic(part.dynSymTab);
18690b57cec5SDimitry Andric     finalizeSynthetic(part.gnuHashTab);
18700b57cec5SDimitry Andric     finalizeSynthetic(part.hashTab);
18710b57cec5SDimitry Andric     finalizeSynthetic(part.verDef);
18720b57cec5SDimitry Andric     finalizeSynthetic(part.relaDyn);
18730b57cec5SDimitry Andric     finalizeSynthetic(part.relrDyn);
18740b57cec5SDimitry Andric     finalizeSynthetic(part.ehFrameHdr);
18750b57cec5SDimitry Andric     finalizeSynthetic(part.verSym);
18760b57cec5SDimitry Andric     finalizeSynthetic(part.verNeed);
18770b57cec5SDimitry Andric     finalizeSynthetic(part.dynamic);
18780b57cec5SDimitry Andric   }
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   if (!script->hasSectionsCommand && !config->relocatable)
18810b57cec5SDimitry Andric     fixSectionAlignments();
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   // SHFLinkOrder processing must be processed after relative section placements are
18840b57cec5SDimitry Andric   // known but before addresses are allocated.
18850b57cec5SDimitry Andric   resolveShfLinkOrder();
188685868e8aSDimitry Andric   if (errorCount())
188785868e8aSDimitry Andric     return;
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric   // This is used to:
18900b57cec5SDimitry Andric   // 1) Create "thunks":
18910b57cec5SDimitry Andric   //    Jump instructions in many ISAs have small displacements, and therefore
18920b57cec5SDimitry Andric   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
18930b57cec5SDimitry Andric   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
18940b57cec5SDimitry Andric   //    responsibility to create and insert small pieces of code between
18950b57cec5SDimitry Andric   //    sections to extend the ranges if jump targets are out of range. Such
18960b57cec5SDimitry Andric   //    code pieces are called "thunks".
18970b57cec5SDimitry Andric   //
18980b57cec5SDimitry Andric   //    We add thunks at this stage. We couldn't do this before this point
18990b57cec5SDimitry Andric   //    because this is the earliest point where we know sizes of sections and
19000b57cec5SDimitry Andric   //    their layouts (that are needed to determine if jump targets are in
19010b57cec5SDimitry Andric   //    range).
19020b57cec5SDimitry Andric   //
19030b57cec5SDimitry Andric   // 2) Update the sections. We need to generate content that depends on the
19040b57cec5SDimitry Andric   //    address of InputSections. For example, MIPS GOT section content or
19050b57cec5SDimitry Andric   //    android packed relocations sections content.
19060b57cec5SDimitry Andric   //
19070b57cec5SDimitry Andric   // 3) Assign the final values for the linker script symbols. Linker scripts
19080b57cec5SDimitry Andric   //    sometimes using forward symbol declarations. We want to set the correct
19090b57cec5SDimitry Andric   //    values. They also might change after adding the thunks.
19100b57cec5SDimitry Andric   finalizeAddressDependentContent();
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   // finalizeAddressDependentContent may have added local symbols to the static symbol table.
19130b57cec5SDimitry Andric   finalizeSynthetic(in.symTab);
19140b57cec5SDimitry Andric   finalizeSynthetic(in.ppc64LongBranchTarget);
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric   // Fill other section headers. The dynamic table is finalized
19170b57cec5SDimitry Andric   // at the end because some tags like RELSZ depend on result
19180b57cec5SDimitry Andric   // of finalizing other sections.
19190b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
19200b57cec5SDimitry Andric     sec->finalize();
19210b57cec5SDimitry Andric }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric // Ensure data sections are not mixed with executable sections when
19240b57cec5SDimitry Andric // -execute-only is used. -execute-only is a feature to make pages executable
19250b57cec5SDimitry Andric // but not readable, and the feature is currently supported only on AArch64.
19260b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
19270b57cec5SDimitry Andric   if (!config->executeOnly)
19280b57cec5SDimitry Andric     return;
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric   for (OutputSection *os : outputSections)
19310b57cec5SDimitry Andric     if (os->flags & SHF_EXECINSTR)
19320b57cec5SDimitry Andric       for (InputSection *isec : getInputSections(os))
19330b57cec5SDimitry Andric         if (!(isec->flags & SHF_EXECINSTR))
19340b57cec5SDimitry Andric           error("cannot place " + toString(isec) + " into " + toString(os->name) +
19350b57cec5SDimitry Andric                 ": -execute-only does not support intermingling data and code");
19360b57cec5SDimitry Andric }
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric // The linker is expected to define SECNAME_start and SECNAME_end
19390b57cec5SDimitry Andric // symbols for a few sections. This function defines them.
19400b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
19410b57cec5SDimitry Andric   // If a section does not exist, there's ambiguity as to how we
19420b57cec5SDimitry Andric   // define _start and _end symbols for an init/fini section. Since
19430b57cec5SDimitry Andric   // the loader assume that the symbols are always defined, we need to
19440b57cec5SDimitry Andric   // always define them. But what value? The loader iterates over all
19450b57cec5SDimitry Andric   // pointers between _start and _end to run global ctors/dtors, so if
19460b57cec5SDimitry Andric   // the section is empty, their symbol values don't actually matter
19470b57cec5SDimitry Andric   // as long as _start and _end point to the same location.
19480b57cec5SDimitry Andric   //
19490b57cec5SDimitry Andric   // That said, we don't want to set the symbols to 0 (which is
19500b57cec5SDimitry Andric   // probably the simplest value) because that could cause some
19510b57cec5SDimitry Andric   // program to fail to link due to relocation overflow, if their
19520b57cec5SDimitry Andric   // program text is above 2 GiB. We use the address of the .text
19530b57cec5SDimitry Andric   // section instead to prevent that failure.
19540b57cec5SDimitry Andric   //
1955*480093f4SDimitry Andric   // In rare situations, the .text section may not exist. If that's the
19560b57cec5SDimitry Andric   // case, use the image base address as a last resort.
19570b57cec5SDimitry Andric   OutputSection *Default = findSection(".text");
19580b57cec5SDimitry Andric   if (!Default)
19590b57cec5SDimitry Andric     Default = Out::elfHeader;
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
19620b57cec5SDimitry Andric     if (os) {
19630b57cec5SDimitry Andric       addOptionalRegular(start, os, 0);
19640b57cec5SDimitry Andric       addOptionalRegular(end, os, -1);
19650b57cec5SDimitry Andric     } else {
19660b57cec5SDimitry Andric       addOptionalRegular(start, Default, 0);
19670b57cec5SDimitry Andric       addOptionalRegular(end, Default, 0);
19680b57cec5SDimitry Andric     }
19690b57cec5SDimitry Andric   };
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
19720b57cec5SDimitry Andric   define("__init_array_start", "__init_array_end", Out::initArray);
19730b57cec5SDimitry Andric   define("__fini_array_start", "__fini_array_end", Out::finiArray);
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric   if (OutputSection *sec = findSection(".ARM.exidx"))
19760b57cec5SDimitry Andric     define("__exidx_start", "__exidx_end", sec);
19770b57cec5SDimitry Andric }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric // If a section name is valid as a C identifier (which is rare because of
19800b57cec5SDimitry Andric // the leading '.'), linkers are expected to define __start_<secname> and
19810b57cec5SDimitry Andric // __stop_<secname> symbols. They are at beginning and end of the section,
19820b57cec5SDimitry Andric // respectively. This is not requested by the ELF standard, but GNU ld and
19830b57cec5SDimitry Andric // gold provide the feature, and used by many programs.
19840b57cec5SDimitry Andric template <class ELFT>
19850b57cec5SDimitry Andric void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
19860b57cec5SDimitry Andric   StringRef s = sec->name;
19870b57cec5SDimitry Andric   if (!isValidCIdentifier(s))
19880b57cec5SDimitry Andric     return;
19890b57cec5SDimitry Andric   addOptionalRegular(saver.save("__start_" + s), sec, 0, STV_PROTECTED);
19900b57cec5SDimitry Andric   addOptionalRegular(saver.save("__stop_" + s), sec, -1, STV_PROTECTED);
19910b57cec5SDimitry Andric }
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric static bool needsPtLoad(OutputSection *sec) {
19940b57cec5SDimitry Andric   if (!(sec->flags & SHF_ALLOC) || sec->noload)
19950b57cec5SDimitry Andric     return false;
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
19980b57cec5SDimitry Andric   // responsible for allocating space for them, not the PT_LOAD that
19990b57cec5SDimitry Andric   // contains the TLS initialization image.
20000b57cec5SDimitry Andric   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
20010b57cec5SDimitry Andric     return false;
20020b57cec5SDimitry Andric   return true;
20030b57cec5SDimitry Andric }
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric // Linker scripts are responsible for aligning addresses. Unfortunately, most
20060b57cec5SDimitry Andric // linker scripts are designed for creating two PT_LOADs only, one RX and one
20070b57cec5SDimitry Andric // RW. This means that there is no alignment in the RO to RX transition and we
20080b57cec5SDimitry Andric // cannot create a PT_LOAD there.
20090b57cec5SDimitry Andric static uint64_t computeFlags(uint64_t flags) {
20100b57cec5SDimitry Andric   if (config->omagic)
20110b57cec5SDimitry Andric     return PF_R | PF_W | PF_X;
20120b57cec5SDimitry Andric   if (config->executeOnly && (flags & PF_X))
20130b57cec5SDimitry Andric     return flags & ~PF_R;
20140b57cec5SDimitry Andric   if (config->singleRoRx && !(flags & PF_W))
20150b57cec5SDimitry Andric     return flags | PF_X;
20160b57cec5SDimitry Andric   return flags;
20170b57cec5SDimitry Andric }
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric // Decide which program headers to create and which sections to include in each
20200b57cec5SDimitry Andric // one.
20210b57cec5SDimitry Andric template <class ELFT>
20220b57cec5SDimitry Andric std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) {
20230b57cec5SDimitry Andric   std::vector<PhdrEntry *> ret;
20240b57cec5SDimitry Andric   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
20250b57cec5SDimitry Andric     ret.push_back(make<PhdrEntry>(type, flags));
20260b57cec5SDimitry Andric     return ret.back();
20270b57cec5SDimitry Andric   };
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   unsigned partNo = part.getNumber();
20300b57cec5SDimitry Andric   bool isMain = partNo == 1;
20310b57cec5SDimitry Andric 
203285868e8aSDimitry Andric   // Add the first PT_LOAD segment for regular output sections.
203385868e8aSDimitry Andric   uint64_t flags = computeFlags(PF_R);
203485868e8aSDimitry Andric   PhdrEntry *load = nullptr;
203585868e8aSDimitry Andric 
203685868e8aSDimitry Andric   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
203785868e8aSDimitry Andric   // PT_LOAD.
203885868e8aSDimitry Andric   if (!config->nmagic && !config->omagic) {
203985868e8aSDimitry Andric     // The first phdr entry is PT_PHDR which describes the program header
204085868e8aSDimitry Andric     // itself.
20410b57cec5SDimitry Andric     if (isMain)
20420b57cec5SDimitry Andric       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
20430b57cec5SDimitry Andric     else
20440b57cec5SDimitry Andric       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric     // PT_INTERP must be the second entry if exists.
20470b57cec5SDimitry Andric     if (OutputSection *cmd = findSection(".interp", partNo))
20480b57cec5SDimitry Andric       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric     // Add the headers. We will remove them if they don't fit.
20510b57cec5SDimitry Andric     // In the other partitions the headers are ordinary sections, so they don't
20520b57cec5SDimitry Andric     // need to be added here.
20530b57cec5SDimitry Andric     if (isMain) {
20540b57cec5SDimitry Andric       load = addHdr(PT_LOAD, flags);
20550b57cec5SDimitry Andric       load->add(Out::elfHeader);
20560b57cec5SDimitry Andric       load->add(Out::programHeaders);
20570b57cec5SDimitry Andric     }
205885868e8aSDimitry Andric   }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   // PT_GNU_RELRO includes all sections that should be marked as
2061*480093f4SDimitry Andric   // read-only by dynamic linker after processing relocations.
20620b57cec5SDimitry Andric   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
20630b57cec5SDimitry Andric   // an error message if more than one PT_GNU_RELRO PHDR is required.
20640b57cec5SDimitry Andric   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
20650b57cec5SDimitry Andric   bool inRelroPhdr = false;
20660b57cec5SDimitry Andric   OutputSection *relroEnd = nullptr;
20670b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
20680b57cec5SDimitry Andric     if (sec->partition != partNo || !needsPtLoad(sec))
20690b57cec5SDimitry Andric       continue;
20700b57cec5SDimitry Andric     if (isRelroSection(sec)) {
20710b57cec5SDimitry Andric       inRelroPhdr = true;
20720b57cec5SDimitry Andric       if (!relroEnd)
20730b57cec5SDimitry Andric         relRo->add(sec);
20740b57cec5SDimitry Andric       else
20750b57cec5SDimitry Andric         error("section: " + sec->name + " is not contiguous with other relro" +
20760b57cec5SDimitry Andric               " sections");
20770b57cec5SDimitry Andric     } else if (inRelroPhdr) {
20780b57cec5SDimitry Andric       inRelroPhdr = false;
20790b57cec5SDimitry Andric       relroEnd = sec;
20800b57cec5SDimitry Andric     }
20810b57cec5SDimitry Andric   }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
20840b57cec5SDimitry Andric     if (!(sec->flags & SHF_ALLOC))
20850b57cec5SDimitry Andric       break;
20860b57cec5SDimitry Andric     if (!needsPtLoad(sec))
20870b57cec5SDimitry Andric       continue;
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric     // Normally, sections in partitions other than the current partition are
20900b57cec5SDimitry Andric     // ignored. But partition number 255 is a special case: it contains the
20910b57cec5SDimitry Andric     // partition end marker (.part.end). It needs to be added to the main
20920b57cec5SDimitry Andric     // partition so that a segment is created for it in the main partition,
20930b57cec5SDimitry Andric     // which will cause the dynamic loader to reserve space for the other
20940b57cec5SDimitry Andric     // partitions.
20950b57cec5SDimitry Andric     if (sec->partition != partNo) {
20960b57cec5SDimitry Andric       if (isMain && sec->partition == 255)
20970b57cec5SDimitry Andric         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
20980b57cec5SDimitry Andric       continue;
20990b57cec5SDimitry Andric     }
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric     // Segments are contiguous memory regions that has the same attributes
21020b57cec5SDimitry Andric     // (e.g. executable or writable). There is one phdr for each segment.
21030b57cec5SDimitry Andric     // Therefore, we need to create a new phdr when the next section has
21040b57cec5SDimitry Andric     // different flags or is loaded at a discontiguous address or memory
21050b57cec5SDimitry Andric     // region using AT or AT> linker script command, respectively. At the same
21060b57cec5SDimitry Andric     // time, we don't want to create a separate load segment for the headers,
21070b57cec5SDimitry Andric     // even if the first output section has an AT or AT> attribute.
21080b57cec5SDimitry Andric     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
21090b57cec5SDimitry Andric     if (!load ||
21100b57cec5SDimitry Andric         ((sec->lmaExpr ||
21110b57cec5SDimitry Andric           (sec->lmaRegion && (sec->lmaRegion != load->firstSec->lmaRegion))) &&
21120b57cec5SDimitry Andric          load->lastSec != Out::programHeaders) ||
21130b57cec5SDimitry Andric         sec->memRegion != load->firstSec->memRegion || flags != newFlags ||
21140b57cec5SDimitry Andric         sec == relroEnd) {
21150b57cec5SDimitry Andric       load = addHdr(PT_LOAD, newFlags);
21160b57cec5SDimitry Andric       flags = newFlags;
21170b57cec5SDimitry Andric     }
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric     load->add(sec);
21200b57cec5SDimitry Andric   }
21210b57cec5SDimitry Andric 
21220b57cec5SDimitry Andric   // Add a TLS segment if any.
21230b57cec5SDimitry Andric   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
21240b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
21250b57cec5SDimitry Andric     if (sec->partition == partNo && sec->flags & SHF_TLS)
21260b57cec5SDimitry Andric       tlsHdr->add(sec);
21270b57cec5SDimitry Andric   if (tlsHdr->firstSec)
21280b57cec5SDimitry Andric     ret.push_back(tlsHdr);
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   // Add an entry for .dynamic.
21310b57cec5SDimitry Andric   if (OutputSection *sec = part.dynamic->getParent())
21320b57cec5SDimitry Andric     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   if (relRo->firstSec)
21350b57cec5SDimitry Andric     ret.push_back(relRo);
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
21380b57cec5SDimitry Andric   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
21390b57cec5SDimitry Andric       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
21400b57cec5SDimitry Andric     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
21410b57cec5SDimitry Andric         ->add(part.ehFrameHdr->getParent());
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
21440b57cec5SDimitry Andric   // the dynamic linker fill the segment with random data.
21450b57cec5SDimitry Andric   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
21460b57cec5SDimitry Andric     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
21470b57cec5SDimitry Andric 
2148*480093f4SDimitry Andric   if (config->zGnustack != GnuStackKind::None) {
21490b57cec5SDimitry Andric     // PT_GNU_STACK is a special section to tell the loader to make the
21500b57cec5SDimitry Andric     // pages for the stack non-executable. If you really want an executable
21510b57cec5SDimitry Andric     // stack, you can pass -z execstack, but that's not recommended for
21520b57cec5SDimitry Andric     // security reasons.
21530b57cec5SDimitry Andric     unsigned perm = PF_R | PF_W;
2154*480093f4SDimitry Andric     if (config->zGnustack == GnuStackKind::Exec)
21550b57cec5SDimitry Andric       perm |= PF_X;
21560b57cec5SDimitry Andric     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2157*480093f4SDimitry Andric   }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
21600b57cec5SDimitry Andric   // is expected to perform W^X violations, such as calling mprotect(2) or
21610b57cec5SDimitry Andric   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
21620b57cec5SDimitry Andric   // OpenBSD.
21630b57cec5SDimitry Andric   if (config->zWxneeded)
21640b57cec5SDimitry Andric     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
21650b57cec5SDimitry Andric 
2166*480093f4SDimitry Andric   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2167*480093f4SDimitry Andric     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2168*480093f4SDimitry Andric 
21690b57cec5SDimitry Andric   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
21700b57cec5SDimitry Andric   // same alignment.
21710b57cec5SDimitry Andric   PhdrEntry *note = nullptr;
21720b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
21730b57cec5SDimitry Andric     if (sec->partition != partNo)
21740b57cec5SDimitry Andric       continue;
21750b57cec5SDimitry Andric     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
21760b57cec5SDimitry Andric       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
21770b57cec5SDimitry Andric         note = addHdr(PT_NOTE, PF_R);
21780b57cec5SDimitry Andric       note->add(sec);
21790b57cec5SDimitry Andric     } else {
21800b57cec5SDimitry Andric       note = nullptr;
21810b57cec5SDimitry Andric     }
21820b57cec5SDimitry Andric   }
21830b57cec5SDimitry Andric   return ret;
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric template <class ELFT>
21870b57cec5SDimitry Andric void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
21880b57cec5SDimitry Andric                                      unsigned pType, unsigned pFlags) {
21890b57cec5SDimitry Andric   unsigned partNo = part.getNumber();
21900b57cec5SDimitry Andric   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
21910b57cec5SDimitry Andric     return cmd->partition == partNo && cmd->type == shType;
21920b57cec5SDimitry Andric   });
21930b57cec5SDimitry Andric   if (i == outputSections.end())
21940b57cec5SDimitry Andric     return;
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
21970b57cec5SDimitry Andric   entry->add(*i);
21980b57cec5SDimitry Andric   part.phdrs.push_back(entry);
21990b57cec5SDimitry Andric }
22000b57cec5SDimitry Andric 
220185868e8aSDimitry Andric // Place the first section of each PT_LOAD to a different page (of maxPageSize).
220285868e8aSDimitry Andric // This is achieved by assigning an alignment expression to addrExpr of each
220385868e8aSDimitry Andric // such section.
22040b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
220585868e8aSDimitry Andric   const PhdrEntry *prev;
220685868e8aSDimitry Andric   auto pageAlign = [&](const PhdrEntry *p) {
220785868e8aSDimitry Andric     OutputSection *cmd = p->firstSec;
220885868e8aSDimitry Andric     if (cmd && !cmd->addrExpr) {
220985868e8aSDimitry Andric       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
221085868e8aSDimitry Andric       // padding in the file contents.
221185868e8aSDimitry Andric       //
221285868e8aSDimitry Andric       // When -z separate-code is used we must not have any overlap in pages
221385868e8aSDimitry Andric       // between an executable segment and a non-executable segment. We align to
221485868e8aSDimitry Andric       // the next maximum page size boundary on transitions between executable
221585868e8aSDimitry Andric       // and non-executable segments.
221685868e8aSDimitry Andric       //
221785868e8aSDimitry Andric       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
221885868e8aSDimitry Andric       // sections will be extracted to a separate file. Align to the next
221985868e8aSDimitry Andric       // maximum page size boundary so that we can find the ELF header at the
222085868e8aSDimitry Andric       // start. We cannot benefit from overlapping p_offset ranges with the
222185868e8aSDimitry Andric       // previous segment anyway.
222285868e8aSDimitry Andric       if (config->zSeparate == SeparateSegmentKind::Loadable ||
222385868e8aSDimitry Andric           (config->zSeparate == SeparateSegmentKind::Code && prev &&
222485868e8aSDimitry Andric            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
222585868e8aSDimitry Andric           cmd->type == SHT_LLVM_PART_EHDR)
222685868e8aSDimitry Andric         cmd->addrExpr = [] {
22270b57cec5SDimitry Andric           return alignTo(script->getDot(), config->maxPageSize);
22280b57cec5SDimitry Andric         };
222985868e8aSDimitry Andric       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
223085868e8aSDimitry Andric       // it must be the RW. Align to p_align(PT_TLS) to make sure
223185868e8aSDimitry Andric       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
223285868e8aSDimitry Andric       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
223385868e8aSDimitry Andric       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
223485868e8aSDimitry Andric       // be congruent to 0 modulo p_align(PT_TLS).
223585868e8aSDimitry Andric       //
223685868e8aSDimitry Andric       // Technically this is not required, but as of 2019, some dynamic loaders
223785868e8aSDimitry Andric       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
223885868e8aSDimitry Andric       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
223985868e8aSDimitry Andric       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
224085868e8aSDimitry Andric       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
224185868e8aSDimitry Andric       // blocks correctly. We need to keep the workaround for a while.
224285868e8aSDimitry Andric       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
224385868e8aSDimitry Andric         cmd->addrExpr = [] {
224485868e8aSDimitry Andric           return alignTo(script->getDot(), config->maxPageSize) +
224585868e8aSDimitry Andric                  alignTo(script->getDot() % config->maxPageSize,
224685868e8aSDimitry Andric                          Out::tlsPhdr->p_align);
224785868e8aSDimitry Andric         };
224885868e8aSDimitry Andric       else
224985868e8aSDimitry Andric         cmd->addrExpr = [] {
225085868e8aSDimitry Andric           return alignTo(script->getDot(), config->maxPageSize) +
225185868e8aSDimitry Andric                  script->getDot() % config->maxPageSize;
225285868e8aSDimitry Andric         };
225385868e8aSDimitry Andric     }
22540b57cec5SDimitry Andric   };
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric   for (Partition &part : partitions) {
225785868e8aSDimitry Andric     prev = nullptr;
22580b57cec5SDimitry Andric     for (const PhdrEntry *p : part.phdrs)
225985868e8aSDimitry Andric       if (p->p_type == PT_LOAD && p->firstSec) {
226085868e8aSDimitry Andric         pageAlign(p);
226185868e8aSDimitry Andric         prev = p;
226285868e8aSDimitry Andric       }
22630b57cec5SDimitry Andric   }
22640b57cec5SDimitry Andric }
22650b57cec5SDimitry Andric 
22660b57cec5SDimitry Andric // Compute an in-file position for a given section. The file offset must be the
22670b57cec5SDimitry Andric // same with its virtual address modulo the page size, so that the loader can
22680b57cec5SDimitry Andric // load executables without any address adjustment.
22690b57cec5SDimitry Andric static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
22700b57cec5SDimitry Andric   // The first section in a PT_LOAD has to have congruent offset and address
227185868e8aSDimitry Andric   // modulo the maximum page size.
227285868e8aSDimitry Andric   if (os->ptLoad && os->ptLoad->firstSec == os)
227385868e8aSDimitry Andric     return alignTo(off, os->ptLoad->p_align, os->addr);
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric   // File offsets are not significant for .bss sections other than the first one
22760b57cec5SDimitry Andric   // in a PT_LOAD. By convention, we keep section offsets monotonically
22770b57cec5SDimitry Andric   // increasing rather than setting to zero.
22780b57cec5SDimitry Andric    if (os->type == SHT_NOBITS)
22790b57cec5SDimitry Andric      return off;
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   // If the section is not in a PT_LOAD, we just have to align it.
22820b57cec5SDimitry Andric   if (!os->ptLoad)
22830b57cec5SDimitry Andric     return alignTo(off, os->alignment);
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   // If two sections share the same PT_LOAD the file offset is calculated
22860b57cec5SDimitry Andric   // using this formula: Off2 = Off1 + (VA2 - VA1).
22870b57cec5SDimitry Andric   OutputSection *first = os->ptLoad->firstSec;
22880b57cec5SDimitry Andric   return first->offset + os->addr - first->addr;
22890b57cec5SDimitry Andric }
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric // Set an in-file position to a given section and returns the end position of
22920b57cec5SDimitry Andric // the section.
22930b57cec5SDimitry Andric static uint64_t setFileOffset(OutputSection *os, uint64_t off) {
22940b57cec5SDimitry Andric   off = computeFileOffset(os, off);
22950b57cec5SDimitry Andric   os->offset = off;
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   if (os->type == SHT_NOBITS)
22980b57cec5SDimitry Andric     return off;
22990b57cec5SDimitry Andric   return off + os->size;
23000b57cec5SDimitry Andric }
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
23030b57cec5SDimitry Andric   uint64_t off = 0;
23040b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
23050b57cec5SDimitry Andric     if (sec->flags & SHF_ALLOC)
23060b57cec5SDimitry Andric       off = setFileOffset(sec, off);
23070b57cec5SDimitry Andric   fileSize = alignTo(off, config->wordsize);
23080b57cec5SDimitry Andric }
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric static std::string rangeToString(uint64_t addr, uint64_t len) {
23110b57cec5SDimitry Andric   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
23120b57cec5SDimitry Andric }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric // Assign file offsets to output sections.
23150b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
23160b57cec5SDimitry Andric   uint64_t off = 0;
23170b57cec5SDimitry Andric   off = setFileOffset(Out::elfHeader, off);
23180b57cec5SDimitry Andric   off = setFileOffset(Out::programHeaders, off);
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   PhdrEntry *lastRX = nullptr;
23210b57cec5SDimitry Andric   for (Partition &part : partitions)
23220b57cec5SDimitry Andric     for (PhdrEntry *p : part.phdrs)
23230b57cec5SDimitry Andric       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
23240b57cec5SDimitry Andric         lastRX = p;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
23270b57cec5SDimitry Andric     off = setFileOffset(sec, off);
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric     // If this is a last section of the last executable segment and that
23300b57cec5SDimitry Andric     // segment is the last loadable segment, align the offset of the
23310b57cec5SDimitry Andric     // following section to avoid loading non-segments parts of the file.
233285868e8aSDimitry Andric     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
233385868e8aSDimitry Andric         lastRX->lastSec == sec)
23340b57cec5SDimitry Andric       off = alignTo(off, config->commonPageSize);
23350b57cec5SDimitry Andric   }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   sectionHeaderOff = alignTo(off, config->wordsize);
23380b57cec5SDimitry Andric   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
23390b57cec5SDimitry Andric 
23400b57cec5SDimitry Andric   // Our logic assumes that sections have rising VA within the same segment.
23410b57cec5SDimitry Andric   // With use of linker scripts it is possible to violate this rule and get file
23420b57cec5SDimitry Andric   // offset overlaps or overflows. That should never happen with a valid script
23430b57cec5SDimitry Andric   // which does not move the location counter backwards and usually scripts do
23440b57cec5SDimitry Andric   // not do that. Unfortunately, there are apps in the wild, for example, Linux
23450b57cec5SDimitry Andric   // kernel, which control segment distribution explicitly and move the counter
23460b57cec5SDimitry Andric   // backwards, so we have to allow doing that to support linking them. We
23470b57cec5SDimitry Andric   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
23480b57cec5SDimitry Andric   // we want to prevent file size overflows because it would crash the linker.
23490b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
23500b57cec5SDimitry Andric     if (sec->type == SHT_NOBITS)
23510b57cec5SDimitry Andric       continue;
23520b57cec5SDimitry Andric     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
23530b57cec5SDimitry Andric       error("unable to place section " + sec->name + " at file offset " +
23540b57cec5SDimitry Andric             rangeToString(sec->offset, sec->size) +
23550b57cec5SDimitry Andric             "; check your linker script for overflows");
23560b57cec5SDimitry Andric   }
23570b57cec5SDimitry Andric }
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric // Finalize the program headers. We call this function after we assign
23600b57cec5SDimitry Andric // file offsets and VAs to all sections.
23610b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
23620b57cec5SDimitry Andric   for (PhdrEntry *p : part.phdrs) {
23630b57cec5SDimitry Andric     OutputSection *first = p->firstSec;
23640b57cec5SDimitry Andric     OutputSection *last = p->lastSec;
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric     if (first) {
23670b57cec5SDimitry Andric       p->p_filesz = last->offset - first->offset;
23680b57cec5SDimitry Andric       if (last->type != SHT_NOBITS)
23690b57cec5SDimitry Andric         p->p_filesz += last->size;
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric       p->p_memsz = last->addr + last->size - first->addr;
23720b57cec5SDimitry Andric       p->p_offset = first->offset;
23730b57cec5SDimitry Andric       p->p_vaddr = first->addr;
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric       // File offsets in partitions other than the main partition are relative
23760b57cec5SDimitry Andric       // to the offset of the ELF headers. Perform that adjustment now.
23770b57cec5SDimitry Andric       if (part.elfHeader)
23780b57cec5SDimitry Andric         p->p_offset -= part.elfHeader->getParent()->offset;
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric       if (!p->hasLMA)
23810b57cec5SDimitry Andric         p->p_paddr = first->getLMA();
23820b57cec5SDimitry Andric     }
23830b57cec5SDimitry Andric 
238485868e8aSDimitry Andric     if (p->p_type == PT_GNU_RELRO) {
23850b57cec5SDimitry Andric       p->p_align = 1;
238685868e8aSDimitry Andric       // musl/glibc ld.so rounds the size down, so we need to round up
23870b57cec5SDimitry Andric       // to protect the last page. This is a no-op on FreeBSD which always
23880b57cec5SDimitry Andric       // rounds up.
238985868e8aSDimitry Andric       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
239085868e8aSDimitry Andric                    p->p_offset;
23910b57cec5SDimitry Andric     }
23920b57cec5SDimitry Andric   }
23930b57cec5SDimitry Andric }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric // A helper struct for checkSectionOverlap.
23960b57cec5SDimitry Andric namespace {
23970b57cec5SDimitry Andric struct SectionOffset {
23980b57cec5SDimitry Andric   OutputSection *sec;
23990b57cec5SDimitry Andric   uint64_t offset;
24000b57cec5SDimitry Andric };
24010b57cec5SDimitry Andric } // namespace
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric // Check whether sections overlap for a specific address range (file offsets,
2404*480093f4SDimitry Andric // load and virtual addresses).
24050b57cec5SDimitry Andric static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
24060b57cec5SDimitry Andric                          bool isVirtualAddr) {
24070b57cec5SDimitry Andric   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
24080b57cec5SDimitry Andric     return a.offset < b.offset;
24090b57cec5SDimitry Andric   });
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   // Finding overlap is easy given a vector is sorted by start position.
24120b57cec5SDimitry Andric   // If an element starts before the end of the previous element, they overlap.
24130b57cec5SDimitry Andric   for (size_t i = 1, end = sections.size(); i < end; ++i) {
24140b57cec5SDimitry Andric     SectionOffset a = sections[i - 1];
24150b57cec5SDimitry Andric     SectionOffset b = sections[i];
24160b57cec5SDimitry Andric     if (b.offset >= a.offset + a.sec->size)
24170b57cec5SDimitry Andric       continue;
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric     // If both sections are in OVERLAY we allow the overlapping of virtual
24200b57cec5SDimitry Andric     // addresses, because it is what OVERLAY was designed for.
24210b57cec5SDimitry Andric     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
24220b57cec5SDimitry Andric       continue;
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric     errorOrWarn("section " + a.sec->name + " " + name +
24250b57cec5SDimitry Andric                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
24260b57cec5SDimitry Andric                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
24270b57cec5SDimitry Andric                 b.sec->name + " range is " +
24280b57cec5SDimitry Andric                 rangeToString(b.offset, b.sec->size));
24290b57cec5SDimitry Andric   }
24300b57cec5SDimitry Andric }
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric // Check for overlapping sections and address overflows.
24330b57cec5SDimitry Andric //
24340b57cec5SDimitry Andric // In this function we check that none of the output sections have overlapping
24350b57cec5SDimitry Andric // file offsets. For SHF_ALLOC sections we also check that the load address
24360b57cec5SDimitry Andric // ranges and the virtual address ranges don't overlap
24370b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::checkSections() {
24380b57cec5SDimitry Andric   // First, check that section's VAs fit in available address space for target.
24390b57cec5SDimitry Andric   for (OutputSection *os : outputSections)
24400b57cec5SDimitry Andric     if ((os->addr + os->size < os->addr) ||
24410b57cec5SDimitry Andric         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
24420b57cec5SDimitry Andric       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
24430b57cec5SDimitry Andric                   " of size 0x" + utohexstr(os->size) +
24440b57cec5SDimitry Andric                   " exceeds available address space");
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric   // Check for overlapping file offsets. In this case we need to skip any
24470b57cec5SDimitry Andric   // section marked as SHT_NOBITS. These sections don't actually occupy space in
24480b57cec5SDimitry Andric   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
24490b57cec5SDimitry Andric   // binary is specified only add SHF_ALLOC sections are added to the output
24500b57cec5SDimitry Andric   // file so we skip any non-allocated sections in that case.
24510b57cec5SDimitry Andric   std::vector<SectionOffset> fileOffs;
24520b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
24530b57cec5SDimitry Andric     if (sec->size > 0 && sec->type != SHT_NOBITS &&
24540b57cec5SDimitry Andric         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
24550b57cec5SDimitry Andric       fileOffs.push_back({sec, sec->offset});
24560b57cec5SDimitry Andric   checkOverlap("file", fileOffs, false);
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric   // When linking with -r there is no need to check for overlapping virtual/load
24590b57cec5SDimitry Andric   // addresses since those addresses will only be assigned when the final
24600b57cec5SDimitry Andric   // executable/shared object is created.
24610b57cec5SDimitry Andric   if (config->relocatable)
24620b57cec5SDimitry Andric     return;
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric   // Checking for overlapping virtual and load addresses only needs to take
24650b57cec5SDimitry Andric   // into account SHF_ALLOC sections since others will not be loaded.
24660b57cec5SDimitry Andric   // Furthermore, we also need to skip SHF_TLS sections since these will be
24670b57cec5SDimitry Andric   // mapped to other addresses at runtime and can therefore have overlapping
24680b57cec5SDimitry Andric   // ranges in the file.
24690b57cec5SDimitry Andric   std::vector<SectionOffset> vmas;
24700b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
24710b57cec5SDimitry Andric     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
24720b57cec5SDimitry Andric       vmas.push_back({sec, sec->addr});
24730b57cec5SDimitry Andric   checkOverlap("virtual address", vmas, true);
24740b57cec5SDimitry Andric 
24750b57cec5SDimitry Andric   // Finally, check that the load addresses don't overlap. This will usually be
24760b57cec5SDimitry Andric   // the same as the virtual addresses but can be different when using a linker
24770b57cec5SDimitry Andric   // script with AT().
24780b57cec5SDimitry Andric   std::vector<SectionOffset> lmas;
24790b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
24800b57cec5SDimitry Andric     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
24810b57cec5SDimitry Andric       lmas.push_back({sec, sec->getLMA()});
24820b57cec5SDimitry Andric   checkOverlap("load address", lmas, false);
24830b57cec5SDimitry Andric }
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric // The entry point address is chosen in the following ways.
24860b57cec5SDimitry Andric //
24870b57cec5SDimitry Andric // 1. the '-e' entry command-line option;
24880b57cec5SDimitry Andric // 2. the ENTRY(symbol) command in a linker control script;
24890b57cec5SDimitry Andric // 3. the value of the symbol _start, if present;
24900b57cec5SDimitry Andric // 4. the number represented by the entry symbol, if it is a number;
24910b57cec5SDimitry Andric // 5. the address of the first byte of the .text section, if present;
24920b57cec5SDimitry Andric // 6. the address 0.
24930b57cec5SDimitry Andric static uint64_t getEntryAddr() {
24940b57cec5SDimitry Andric   // Case 1, 2 or 3
24950b57cec5SDimitry Andric   if (Symbol *b = symtab->find(config->entry))
24960b57cec5SDimitry Andric     return b->getVA();
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric   // Case 4
24990b57cec5SDimitry Andric   uint64_t addr;
25000b57cec5SDimitry Andric   if (to_integer(config->entry, addr))
25010b57cec5SDimitry Andric     return addr;
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   // Case 5
25040b57cec5SDimitry Andric   if (OutputSection *sec = findSection(".text")) {
25050b57cec5SDimitry Andric     if (config->warnMissingEntry)
25060b57cec5SDimitry Andric       warn("cannot find entry symbol " + config->entry + "; defaulting to 0x" +
25070b57cec5SDimitry Andric            utohexstr(sec->addr));
25080b57cec5SDimitry Andric     return sec->addr;
25090b57cec5SDimitry Andric   }
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   // Case 6
25120b57cec5SDimitry Andric   if (config->warnMissingEntry)
25130b57cec5SDimitry Andric     warn("cannot find entry symbol " + config->entry +
25140b57cec5SDimitry Andric          "; not setting start address");
25150b57cec5SDimitry Andric   return 0;
25160b57cec5SDimitry Andric }
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric static uint16_t getELFType() {
25190b57cec5SDimitry Andric   if (config->isPic)
25200b57cec5SDimitry Andric     return ET_DYN;
25210b57cec5SDimitry Andric   if (config->relocatable)
25220b57cec5SDimitry Andric     return ET_REL;
25230b57cec5SDimitry Andric   return ET_EXEC;
25240b57cec5SDimitry Andric }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::writeHeader() {
25270b57cec5SDimitry Andric   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
25280b57cec5SDimitry Andric   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
25290b57cec5SDimitry Andric 
25300b57cec5SDimitry Andric   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
25310b57cec5SDimitry Andric   eHdr->e_type = getELFType();
25320b57cec5SDimitry Andric   eHdr->e_entry = getEntryAddr();
25330b57cec5SDimitry Andric   eHdr->e_shoff = sectionHeaderOff;
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   // Write the section header table.
25360b57cec5SDimitry Andric   //
25370b57cec5SDimitry Andric   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
25380b57cec5SDimitry Andric   // and e_shstrndx fields. When the value of one of these fields exceeds
25390b57cec5SDimitry Andric   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
25400b57cec5SDimitry Andric   // use fields in the section header at index 0 to store
25410b57cec5SDimitry Andric   // the value. The sentinel values and fields are:
25420b57cec5SDimitry Andric   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
25430b57cec5SDimitry Andric   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
25440b57cec5SDimitry Andric   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
25450b57cec5SDimitry Andric   size_t num = outputSections.size() + 1;
25460b57cec5SDimitry Andric   if (num >= SHN_LORESERVE)
25470b57cec5SDimitry Andric     sHdrs->sh_size = num;
25480b57cec5SDimitry Andric   else
25490b57cec5SDimitry Andric     eHdr->e_shnum = num;
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
25520b57cec5SDimitry Andric   if (strTabIndex >= SHN_LORESERVE) {
25530b57cec5SDimitry Andric     sHdrs->sh_link = strTabIndex;
25540b57cec5SDimitry Andric     eHdr->e_shstrndx = SHN_XINDEX;
25550b57cec5SDimitry Andric   } else {
25560b57cec5SDimitry Andric     eHdr->e_shstrndx = strTabIndex;
25570b57cec5SDimitry Andric   }
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
25600b57cec5SDimitry Andric     sec->writeHeaderTo<ELFT>(++sHdrs);
25610b57cec5SDimitry Andric }
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric // Open a result file.
25640b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::openFile() {
25650b57cec5SDimitry Andric   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
25660b57cec5SDimitry Andric   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
25670b57cec5SDimitry Andric     error("output file too large: " + Twine(fileSize) + " bytes");
25680b57cec5SDimitry Andric     return;
25690b57cec5SDimitry Andric   }
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   unlinkAsync(config->outputFile);
25720b57cec5SDimitry Andric   unsigned flags = 0;
25730b57cec5SDimitry Andric   if (!config->relocatable)
2574*480093f4SDimitry Andric     flags |= FileOutputBuffer::F_executable;
2575*480093f4SDimitry Andric   if (!config->mmapOutputFile)
2576*480093f4SDimitry Andric     flags |= FileOutputBuffer::F_no_mmap;
25770b57cec5SDimitry Andric   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
25780b57cec5SDimitry Andric       FileOutputBuffer::create(config->outputFile, fileSize, flags);
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   if (!bufferOrErr) {
25810b57cec5SDimitry Andric     error("failed to open " + config->outputFile + ": " +
25820b57cec5SDimitry Andric           llvm::toString(bufferOrErr.takeError()));
25830b57cec5SDimitry Andric     return;
25840b57cec5SDimitry Andric   }
25850b57cec5SDimitry Andric   buffer = std::move(*bufferOrErr);
25860b57cec5SDimitry Andric   Out::bufferStart = buffer->getBufferStart();
25870b57cec5SDimitry Andric }
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
25900b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
25910b57cec5SDimitry Andric     if (sec->flags & SHF_ALLOC)
25920b57cec5SDimitry Andric       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
25930b57cec5SDimitry Andric }
25940b57cec5SDimitry Andric 
25950b57cec5SDimitry Andric static void fillTrap(uint8_t *i, uint8_t *end) {
25960b57cec5SDimitry Andric   for (; i + 4 <= end; i += 4)
25970b57cec5SDimitry Andric     memcpy(i, &target->trapInstr, 4);
25980b57cec5SDimitry Andric }
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric // Fill the last page of executable segments with trap instructions
26010b57cec5SDimitry Andric // instead of leaving them as zero. Even though it is not required by any
26020b57cec5SDimitry Andric // standard, it is in general a good thing to do for security reasons.
26030b57cec5SDimitry Andric //
26040b57cec5SDimitry Andric // We'll leave other pages in segments as-is because the rest will be
26050b57cec5SDimitry Andric // overwritten by output sections.
26060b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
26070b57cec5SDimitry Andric   for (Partition &part : partitions) {
26080b57cec5SDimitry Andric     // Fill the last page.
26090b57cec5SDimitry Andric     for (PhdrEntry *p : part.phdrs)
26100b57cec5SDimitry Andric       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
26110b57cec5SDimitry Andric         fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz,
26120b57cec5SDimitry Andric                                               config->commonPageSize),
26130b57cec5SDimitry Andric                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
26140b57cec5SDimitry Andric                                             config->commonPageSize));
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric     // Round up the file size of the last segment to the page boundary iff it is
26170b57cec5SDimitry Andric     // an executable segment to ensure that other tools don't accidentally
26180b57cec5SDimitry Andric     // trim the instruction padding (e.g. when stripping the file).
26190b57cec5SDimitry Andric     PhdrEntry *last = nullptr;
26200b57cec5SDimitry Andric     for (PhdrEntry *p : part.phdrs)
26210b57cec5SDimitry Andric       if (p->p_type == PT_LOAD)
26220b57cec5SDimitry Andric         last = p;
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric     if (last && (last->p_flags & PF_X))
26250b57cec5SDimitry Andric       last->p_memsz = last->p_filesz =
26260b57cec5SDimitry Andric           alignTo(last->p_filesz, config->commonPageSize);
26270b57cec5SDimitry Andric   }
26280b57cec5SDimitry Andric }
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric // Write section contents to a mmap'ed file.
26310b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::writeSections() {
26320b57cec5SDimitry Andric   // In -r or -emit-relocs mode, write the relocation sections first as in
26330b57cec5SDimitry Andric   // ELf_Rel targets we might find out that we need to modify the relocated
26340b57cec5SDimitry Andric   // section while doing it.
26350b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
26360b57cec5SDimitry Andric     if (sec->type == SHT_REL || sec->type == SHT_RELA)
26370b57cec5SDimitry Andric       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
26400b57cec5SDimitry Andric     if (sec->type != SHT_REL && sec->type != SHT_RELA)
26410b57cec5SDimitry Andric       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
26420b57cec5SDimitry Andric }
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric // Split one uint8 array into small pieces of uint8 arrays.
26450b57cec5SDimitry Andric static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> arr,
26460b57cec5SDimitry Andric                                             size_t chunkSize) {
26470b57cec5SDimitry Andric   std::vector<ArrayRef<uint8_t>> ret;
26480b57cec5SDimitry Andric   while (arr.size() > chunkSize) {
26490b57cec5SDimitry Andric     ret.push_back(arr.take_front(chunkSize));
26500b57cec5SDimitry Andric     arr = arr.drop_front(chunkSize);
26510b57cec5SDimitry Andric   }
26520b57cec5SDimitry Andric   if (!arr.empty())
26530b57cec5SDimitry Andric     ret.push_back(arr);
26540b57cec5SDimitry Andric   return ret;
26550b57cec5SDimitry Andric }
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric // Computes a hash value of Data using a given hash function.
26580b57cec5SDimitry Andric // In order to utilize multiple cores, we first split data into 1MB
26590b57cec5SDimitry Andric // chunks, compute a hash for each chunk, and then compute a hash value
26600b57cec5SDimitry Andric // of the hash values.
26610b57cec5SDimitry Andric static void
26620b57cec5SDimitry Andric computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
26630b57cec5SDimitry Andric             llvm::ArrayRef<uint8_t> data,
26640b57cec5SDimitry Andric             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
26650b57cec5SDimitry Andric   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
26660b57cec5SDimitry Andric   std::vector<uint8_t> hashes(chunks.size() * hashBuf.size());
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric   // Compute hash values.
26690b57cec5SDimitry Andric   parallelForEachN(0, chunks.size(), [&](size_t i) {
26700b57cec5SDimitry Andric     hashFn(hashes.data() + i * hashBuf.size(), chunks[i]);
26710b57cec5SDimitry Andric   });
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric   // Write to the final output buffer.
26740b57cec5SDimitry Andric   hashFn(hashBuf.data(), hashes);
26750b57cec5SDimitry Andric }
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric template <class ELFT> void Writer<ELFT>::writeBuildId() {
26780b57cec5SDimitry Andric   if (!mainPart->buildId || !mainPart->buildId->getParent())
26790b57cec5SDimitry Andric     return;
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   if (config->buildId == BuildIdKind::Hexstring) {
26820b57cec5SDimitry Andric     for (Partition &part : partitions)
26830b57cec5SDimitry Andric       part.buildId->writeBuildId(config->buildIdVector);
26840b57cec5SDimitry Andric     return;
26850b57cec5SDimitry Andric   }
26860b57cec5SDimitry Andric 
26870b57cec5SDimitry Andric   // Compute a hash of all sections of the output file.
26880b57cec5SDimitry Andric   size_t hashSize = mainPart->buildId->hashSize;
26890b57cec5SDimitry Andric   std::vector<uint8_t> buildId(hashSize);
26900b57cec5SDimitry Andric   llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)};
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric   switch (config->buildId) {
26930b57cec5SDimitry Andric   case BuildIdKind::Fast:
26940b57cec5SDimitry Andric     computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
26950b57cec5SDimitry Andric       write64le(dest, xxHash64(arr));
26960b57cec5SDimitry Andric     });
26970b57cec5SDimitry Andric     break;
26980b57cec5SDimitry Andric   case BuildIdKind::Md5:
26990b57cec5SDimitry Andric     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
27000b57cec5SDimitry Andric       memcpy(dest, MD5::hash(arr).data(), hashSize);
27010b57cec5SDimitry Andric     });
27020b57cec5SDimitry Andric     break;
27030b57cec5SDimitry Andric   case BuildIdKind::Sha1:
27040b57cec5SDimitry Andric     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
27050b57cec5SDimitry Andric       memcpy(dest, SHA1::hash(arr).data(), hashSize);
27060b57cec5SDimitry Andric     });
27070b57cec5SDimitry Andric     break;
27080b57cec5SDimitry Andric   case BuildIdKind::Uuid:
27090b57cec5SDimitry Andric     if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize))
27100b57cec5SDimitry Andric       error("entropy source failure: " + ec.message());
27110b57cec5SDimitry Andric     break;
27120b57cec5SDimitry Andric   default:
27130b57cec5SDimitry Andric     llvm_unreachable("unknown BuildIdKind");
27140b57cec5SDimitry Andric   }
27150b57cec5SDimitry Andric   for (Partition &part : partitions)
27160b57cec5SDimitry Andric     part.buildId->writeBuildId(buildId);
27170b57cec5SDimitry Andric }
27180b57cec5SDimitry Andric 
271985868e8aSDimitry Andric template void createSyntheticSections<ELF32LE>();
272085868e8aSDimitry Andric template void createSyntheticSections<ELF32BE>();
272185868e8aSDimitry Andric template void createSyntheticSections<ELF64LE>();
272285868e8aSDimitry Andric template void createSyntheticSections<ELF64BE>();
272385868e8aSDimitry Andric 
272485868e8aSDimitry Andric template void writeResult<ELF32LE>();
272585868e8aSDimitry Andric template void writeResult<ELF32BE>();
272685868e8aSDimitry Andric template void writeResult<ELF64LE>();
272785868e8aSDimitry Andric template void writeResult<ELF64BE>();
272885868e8aSDimitry Andric 
272985868e8aSDimitry Andric } // namespace elf
273085868e8aSDimitry Andric } // namespace lld
2731