1 //===- Writer.cpp ---------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "AArch64ErrataFix.h"
11 #include "CallGraphSort.h"
13 #include "LinkerScript.h"
15 #include "OutputSections.h"
16 #include "Relocations.h"
17 #include "SymbolTable.h"
19 #include "SyntheticSections.h"
21 #include "lld/Common/Filesystem.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Strings.h"
24 #include "lld/Common/Threads.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/RandomNumberGenerator.h"
28 #include "llvm/Support/SHA1.h"
29 #include "llvm/Support/xxhash.h"
33 using namespace llvm::ELF;
34 using namespace llvm::object;
35 using namespace llvm::support;
36 using namespace llvm::support::endian;
39 using namespace lld::elf;
42 // The writer writes a SymbolTable result to a file.
43 template <class ELFT> class Writer {
45 Writer() : buffer(errorHandler().outputBuffer) {}
46 using Elf_Shdr = typename ELFT::Shdr;
47 using Elf_Ehdr = typename ELFT::Ehdr;
48 using Elf_Phdr = typename ELFT::Phdr;
53 void copyLocalSymbols();
54 void addSectionSymbols();
55 void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> fn);
57 void resolveShfLinkOrder();
58 void finalizeAddressDependentContent();
59 void sortInputSections();
60 void finalizeSections();
61 void checkExecuteOnly();
62 void setReservedSymbolSections();
64 std::vector<PhdrEntry *> createPhdrs(Partition &part);
65 void removeEmptyPTLoad(std::vector<PhdrEntry *> &phdrEntry);
66 void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
68 void assignFileOffsets();
69 void assignFileOffsetsBinary();
70 void setPhdrs(Partition &part);
72 void fixSectionAlignments();
74 void writeTrapInstr();
77 void writeSectionsBinary();
80 std::unique_ptr<FileOutputBuffer> &buffer;
82 void addRelIpltSymbols();
83 void addStartEndSymbols();
84 void addStartStopSymbols(OutputSection *sec);
87 uint64_t sectionHeaderOff;
89 } // anonymous namespace
91 static bool isSectionPrefix(StringRef prefix, StringRef name) {
92 return name.startswith(prefix) || name == prefix.drop_back();
95 StringRef elf::getOutputSectionName(const InputSectionBase *s) {
96 if (config->relocatable)
99 // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
100 // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
101 // technically required, but not doing it is odd). This code guarantees that.
102 if (auto *isec = dyn_cast<InputSection>(s)) {
103 if (InputSectionBase *rel = isec->getRelocatedSection()) {
104 OutputSection *out = rel->getOutputSection();
105 if (s->type == SHT_RELA)
106 return saver.save(".rela" + out->name);
107 return saver.save(".rel" + out->name);
111 // This check is for -z keep-text-section-prefix. This option separates text
112 // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
114 // When enabled, this allows identifying the hot code region (.text.hot) in
115 // the final binary which can be selectively mapped to huge pages or mlocked,
117 if (config->zKeepTextSectionPrefix)
119 {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."})
120 if (isSectionPrefix(v, s->name))
121 return v.drop_back();
124 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
125 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
126 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."})
127 if (isSectionPrefix(v, s->name))
128 return v.drop_back();
130 // CommonSection is identified as "COMMON" in linker scripts.
131 // By default, it should go to .bss section.
132 if (s->name == "COMMON")
138 static bool needsInterpSection() {
139 return !sharedFiles.empty() && !config->dynamicLinker.empty() &&
140 script->needsInterpSection();
143 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
145 template <class ELFT>
146 void Writer<ELFT>::removeEmptyPTLoad(std::vector<PhdrEntry *> &phdrs) {
147 llvm::erase_if(phdrs, [&](const PhdrEntry *p) {
148 if (p->p_type != PT_LOAD)
152 uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
157 template <class ELFT> static void copySectionsIntoPartitions() {
158 std::vector<InputSectionBase *> newSections;
159 for (unsigned part = 2; part != partitions.size() + 1; ++part) {
160 for (InputSectionBase *s : inputSections) {
161 if (!(s->flags & SHF_ALLOC) || !s->isLive())
163 InputSectionBase *copy;
164 if (s->type == SHT_NOTE)
165 copy = make<InputSection>(cast<InputSection>(*s));
166 else if (auto *es = dyn_cast<EhInputSection>(s))
167 copy = make<EhInputSection>(*es);
170 copy->partition = part;
171 newSections.push_back(copy);
175 inputSections.insert(inputSections.end(), newSections.begin(),
179 template <class ELFT> static void combineEhSections() {
180 for (InputSectionBase *&s : inputSections) {
181 // Ignore dead sections and the partition end marker (.part.end),
182 // whose partition number is out of bounds.
183 if (!s->isLive() || s->partition == 255)
186 Partition &part = s->getPartition();
187 if (auto *es = dyn_cast<EhInputSection>(s)) {
188 part.ehFrame->addSection<ELFT>(es);
190 } else if (s->kind() == SectionBase::Regular && part.armExidx &&
191 part.armExidx->addSection(cast<InputSection>(s))) {
196 std::vector<InputSectionBase *> &v = inputSections;
197 v.erase(std::remove(v.begin(), v.end(), nullptr), v.end());
200 static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
201 uint64_t val, uint8_t stOther = STV_HIDDEN,
202 uint8_t binding = STB_GLOBAL) {
203 Symbol *s = symtab->find(name);
204 if (!s || s->isDefined())
207 s->resolve(Defined{/*file=*/nullptr, name, binding, stOther, STT_NOTYPE, val,
209 return cast<Defined>(s);
212 static Defined *addAbsolute(StringRef name) {
213 Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
214 STT_NOTYPE, 0, 0, nullptr});
215 return cast<Defined>(sym);
218 // The linker is expected to define some symbols depending on
219 // the linking result. This function defines such symbols.
220 void elf::addReservedSymbols() {
221 if (config->emachine == EM_MIPS) {
222 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
223 // so that it points to an absolute address which by default is relative
224 // to GOT. Default offset is 0x7ff0.
225 // See "Global Data Symbols" in Chapter 6 in the following document:
226 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
227 ElfSym::mipsGp = addAbsolute("_gp");
229 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
230 // start of function and 'gp' pointer into GOT.
231 if (symtab->find("_gp_disp"))
232 ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
234 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
235 // pointer. This symbol is used in the code generated by .cpload pseudo-op
236 // in case of using -mno-shared option.
237 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
238 if (symtab->find("__gnu_local_gp"))
239 ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
240 } else if (config->emachine == EM_PPC) {
241 // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
242 // support Small Data Area, define it arbitrarily as 0.
243 addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
246 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
247 // combines the typical ELF GOT with the small data sections. It commonly
248 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
249 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
250 // represent the TOC base which is offset by 0x8000 bytes from the start of
252 // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
253 // correctness of some relocations depends on its value.
254 StringRef gotSymName =
255 (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
257 if (Symbol *s = symtab->find(gotSymName)) {
258 if (s->isDefined()) {
259 error(toString(s->file) + " cannot redefine linker defined symbol '" +
265 if (config->emachine == EM_PPC64)
268 s->resolve(Defined{/*file=*/nullptr, gotSymName, STB_GLOBAL, STV_HIDDEN,
269 STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
270 ElfSym::globalOffsetTable = cast<Defined>(s);
273 // __ehdr_start is the location of ELF file headers. Note that we define
274 // this symbol unconditionally even when using a linker script, which
275 // differs from the behavior implemented by GNU linker which only define
276 // this symbol if ELF headers are in the memory mapped segment.
277 addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
279 // __executable_start is not documented, but the expectation of at
280 // least the Android libc is that it points to the ELF header.
281 addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
283 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
284 // each DSO. The address of the symbol doesn't matter as long as they are
285 // different in different DSOs, so we chose the start address of the DSO.
286 addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
288 // If linker script do layout we do not need to create any standart symbols.
289 if (script->hasSectionsCommand)
292 auto add = [](StringRef s, int64_t pos) {
293 return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
296 ElfSym::bss = add("__bss_start", 0);
297 ElfSym::end1 = add("end", -1);
298 ElfSym::end2 = add("_end", -1);
299 ElfSym::etext1 = add("etext", -1);
300 ElfSym::etext2 = add("_etext", -1);
301 ElfSym::edata1 = add("edata", -1);
302 ElfSym::edata2 = add("_edata", -1);
305 static OutputSection *findSection(StringRef name, unsigned partition = 1) {
306 for (BaseCommand *base : script->sectionCommands)
307 if (auto *sec = dyn_cast<OutputSection>(base))
308 if (sec->name == name && sec->partition == partition)
313 // Initialize Out members.
314 template <class ELFT> static void createSyntheticSections() {
315 // Initialize all pointers with NULL. This is needed because
316 // you can call lld::elf::main more than once as a library.
317 memset(&Out::first, 0, sizeof(Out));
319 auto add = [](InputSectionBase *sec) { inputSections.push_back(sec); };
321 in.shStrTab = make<StringTableSection>(".shstrtab", false);
323 Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
324 Out::programHeaders->alignment = config->wordsize;
326 if (config->strip != StripPolicy::All) {
327 in.strTab = make<StringTableSection>(".strtab", false);
328 in.symTab = make<SymbolTableSection<ELFT>>(*in.strTab);
329 in.symTabShndx = make<SymtabShndxSection>();
332 in.bss = make<BssSection>(".bss", 0, 1);
335 // If there is a SECTIONS command and a .data.rel.ro section name use name
336 // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
337 // This makes sure our relro is contiguous.
339 script->hasSectionsCommand && findSection(".data.rel.ro", 0);
341 make<BssSection>(hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
344 // Add MIPS-specific sections.
345 if (config->emachine == EM_MIPS) {
346 if (!config->shared && config->hasDynSymTab) {
347 in.mipsRldMap = make<MipsRldMapSection>();
350 if (auto *sec = MipsAbiFlagsSection<ELFT>::create())
352 if (auto *sec = MipsOptionsSection<ELFT>::create())
354 if (auto *sec = MipsReginfoSection<ELFT>::create())
358 for (Partition &part : partitions) {
359 auto add = [&](InputSectionBase *sec) {
360 sec->partition = part.getNumber();
361 inputSections.push_back(sec);
364 if (!part.name.empty()) {
365 part.elfHeader = make<PartitionElfHeaderSection<ELFT>>();
366 part.elfHeader->name = part.name;
369 part.programHeaders = make<PartitionProgramHeadersSection<ELFT>>();
370 add(part.programHeaders);
373 if (config->buildId != BuildIdKind::None) {
374 part.buildId = make<BuildIdSection>();
378 part.dynStrTab = make<StringTableSection>(".dynstr", true);
379 part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
380 part.dynamic = make<DynamicSection<ELFT>>();
381 if (config->androidPackDynRelocs) {
382 part.relaDyn = make<AndroidPackedRelocationSection<ELFT>>(
383 config->isRela ? ".rela.dyn" : ".rel.dyn");
385 part.relaDyn = make<RelocationSection<ELFT>>(
386 config->isRela ? ".rela.dyn" : ".rel.dyn", config->zCombreloc);
389 if (needsInterpSection())
390 add(createInterpSection());
392 if (config->hasDynSymTab) {
393 part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
396 part.verSym = make<VersionTableSection>();
399 if (!config->versionDefinitions.empty()) {
400 part.verDef = make<VersionDefinitionSection>();
404 part.verNeed = make<VersionNeedSection<ELFT>>();
407 if (config->gnuHash) {
408 part.gnuHashTab = make<GnuHashTableSection>();
409 add(part.gnuHashTab);
412 if (config->sysvHash) {
413 part.hashTab = make<HashTableSection>();
422 if (config->relrPackDynRelocs) {
423 part.relrDyn = make<RelrSection<ELFT>>();
427 if (!config->relocatable) {
428 if (config->ehFrameHdr) {
429 part.ehFrameHdr = make<EhFrameHeader>();
430 add(part.ehFrameHdr);
432 part.ehFrame = make<EhFrameSection>();
436 if (config->emachine == EM_ARM && !config->relocatable) {
437 // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
439 part.armExidx = make<ARMExidxSyntheticSection>();
444 if (partitions.size() != 1) {
445 // Create the partition end marker. This needs to be in partition number 255
446 // so that it is sorted after all other partitions. It also has other
447 // special handling (see createPhdrs() and combineEhSections()).
448 in.partEnd = make<BssSection>(".part.end", config->maxPageSize, 1);
449 in.partEnd->partition = 255;
452 in.partIndex = make<PartitionIndexSection>();
453 addOptionalRegular("__part_index_begin", in.partIndex, 0);
454 addOptionalRegular("__part_index_end", in.partIndex,
455 in.partIndex->getSize());
459 // Add .got. MIPS' .got is so different from the other archs,
460 // it has its own class.
461 if (config->emachine == EM_MIPS) {
462 in.mipsGot = make<MipsGotSection>();
465 in.got = make<GotSection>();
469 if (config->emachine == EM_PPC) {
470 in.ppc32Got2 = make<PPC32Got2Section>();
474 if (config->emachine == EM_PPC64) {
475 in.ppc64LongBranchTarget = make<PPC64LongBranchTargetSection>();
476 add(in.ppc64LongBranchTarget);
479 if (config->emachine == EM_RISCV) {
480 in.riscvSdata = make<RISCVSdataSection>();
484 in.gotPlt = make<GotPltSection>();
486 in.igotPlt = make<IgotPltSection>();
489 // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
490 // it as a relocation and ensure the referenced section is created.
491 if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
492 if (target->gotBaseSymInGotPlt)
493 in.gotPlt->hasGotPltOffRel = true;
495 in.got->hasGotOffRel = true;
498 if (config->gdbIndex)
499 add(GdbIndexSection::create<ELFT>());
501 // We always need to add rel[a].plt to output if it has entries.
502 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
503 in.relaPlt = make<RelocationSection<ELFT>>(
504 config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
507 // The relaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
508 // that the IRelative relocations are processed last by the dynamic loader.
509 // We cannot place the iplt section in .rel.dyn when Android relocation
510 // packing is enabled because that would cause a section type mismatch.
511 // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
512 // we can get the desired behaviour by placing the iplt section in .rel.plt.
513 in.relaIplt = make<RelocationSection<ELFT>>(
514 (config->emachine == EM_ARM && !config->androidPackDynRelocs)
520 in.plt = make<PltSection>(false);
522 in.iplt = make<PltSection>(true);
525 if (config->andFeatures)
526 add(make<GnuPropertySection>());
528 // .note.GNU-stack is always added when we are creating a re-linkable
529 // object file. Other linkers are using the presence of this marker
530 // section to control the executable-ness of the stack area, but that
531 // is irrelevant these days. Stack area should always be non-executable
532 // by default. So we emit this section unconditionally.
533 if (config->relocatable)
534 add(make<GnuStackSection>());
545 // The main function of the writer.
546 template <class ELFT> void Writer<ELFT>::run() {
547 // Make copies of any input sections that need to be copied into each
549 copySectionsIntoPartitions<ELFT>();
551 // Create linker-synthesized sections such as .got or .plt.
552 // Such sections are of type input section.
553 createSyntheticSections<ELFT>();
555 // Some input sections that are used for exception handling need to be moved
556 // into synthetic sections. Do that now so that they aren't assigned to
557 // output sections in the usual way.
558 if (!config->relocatable)
559 combineEhSections<ELFT>();
561 // We want to process linker script commands. When SECTIONS command
562 // is given we let it create sections.
563 script->processSectionCommands();
565 // Linker scripts controls how input sections are assigned to output sections.
566 // Input sections that were not handled by scripts are called "orphans", and
567 // they are assigned to output sections by the default rule. Process that.
568 script->addOrphanSections();
570 if (config->discard != DiscardPolicy::All)
573 if (config->copyRelocs)
576 // Now that we have a complete set of output sections. This function
577 // completes section contents. For example, we need to add strings
578 // to the string table, and add entries to .got and .plt.
579 // finalizeSections does that.
585 script->assignAddresses();
587 // If -compressed-debug-sections is specified, we need to compress
588 // .debug_* sections. Do it right now because it changes the size of
590 for (OutputSection *sec : outputSections)
591 sec->maybeCompress<ELFT>();
593 script->allocateHeaders(mainPart->phdrs);
595 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
596 // 0 sized region. This has to be done late since only after assignAddresses
597 // we know the size of the sections.
598 for (Partition &part : partitions)
599 removeEmptyPTLoad(part.phdrs);
601 if (!config->oFormatBinary)
604 assignFileOffsetsBinary();
606 for (Partition &part : partitions)
609 if (config->relocatable)
610 for (OutputSection *sec : outputSections)
613 if (config->checkSections)
616 // It does not make sense try to open the file if we have error already.
619 // Write the result down to a file.
624 if (!config->oFormatBinary) {
629 writeSectionsBinary();
632 // Backfill .note.gnu.build-id section content. This is done at last
633 // because the content is usually a hash value of the entire output file.
638 // Handle -Map and -cref options.
640 writeCrossReferenceTable();
644 if (auto e = buffer->commit())
645 error("failed to write to the output file: " + toString(std::move(e)));
648 static bool shouldKeepInSymtab(const Defined &sym) {
652 if (config->discard == DiscardPolicy::None)
655 // If -emit-reloc is given, all symbols including local ones need to be
656 // copied because they may be referenced by relocations.
657 if (config->emitRelocs)
660 // In ELF assembly .L symbols are normally discarded by the assembler.
661 // If the assembler fails to do so, the linker discards them if
662 // * --discard-locals is used.
663 // * The symbol is in a SHF_MERGE section, which is normally the reason for
664 // the assembler keeping the .L symbol.
665 StringRef name = sym.getName();
666 bool isLocal = name.startswith(".L") || name.empty();
670 if (config->discard == DiscardPolicy::Locals)
673 SectionBase *sec = sym.section;
674 return !sec || !(sec->flags & SHF_MERGE);
677 static bool includeInSymtab(const Symbol &b) {
678 if (!b.isLocal() && !b.isUsedInRegularObj)
681 if (auto *d = dyn_cast<Defined>(&b)) {
682 // Always include absolute symbols.
683 SectionBase *sec = d->section;
688 // Exclude symbols pointing to garbage-collected sections.
689 if (isa<InputSectionBase>(sec) && !sec->isLive())
692 if (auto *s = dyn_cast<MergeInputSection>(sec))
693 if (!s->getSectionPiece(d->value)->live)
700 // Local symbols are not in the linker's symbol table. This function scans
701 // each object file's symbol table to copy local symbols to the output.
702 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
705 for (InputFile *file : objectFiles) {
706 ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
707 for (Symbol *b : f->getLocalSymbols()) {
710 ": broken object: getLocalSymbols returns a non-local symbol");
711 auto *dr = dyn_cast<Defined>(b);
713 // No reason to keep local undefined symbol in symtab.
716 if (!includeInSymtab(*b))
718 if (!shouldKeepInSymtab(*dr))
720 in.symTab->addSymbol(b);
725 // Create a section symbol for each output section so that we can represent
726 // relocations that point to the section. If we know that no relocation is
727 // referring to a section (that happens if the section is a synthetic one), we
728 // don't create a section symbol for that section.
729 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
730 for (BaseCommand *base : script->sectionCommands) {
731 auto *sec = dyn_cast<OutputSection>(base);
734 auto i = llvm::find_if(sec->sectionCommands, [](BaseCommand *base) {
735 if (auto *isd = dyn_cast<InputSectionDescription>(base))
736 return !isd->sections.empty();
739 if (i == sec->sectionCommands.end())
741 InputSection *isec = cast<InputSectionDescription>(*i)->sections[0];
743 // Relocations are not using REL[A] section symbols.
744 if (isec->type == SHT_REL || isec->type == SHT_RELA)
747 // Unlike other synthetic sections, mergeable output sections contain data
748 // copied from input sections, and there may be a relocation pointing to its
749 // contents if -r or -emit-reloc are given.
750 if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
754 make<Defined>(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION,
755 /*value=*/0, /*size=*/0, isec);
756 in.symTab->addSymbol(sym);
760 // Today's loaders have a feature to make segments read-only after
761 // processing dynamic relocations to enhance security. PT_GNU_RELRO
762 // is defined for that.
764 // This function returns true if a section needs to be put into a
765 // PT_GNU_RELRO segment.
766 static bool isRelroSection(const OutputSection *sec) {
770 uint64_t flags = sec->flags;
772 // Non-allocatable or non-writable sections don't need RELRO because
773 // they are not writable or not even mapped to memory in the first place.
774 // RELRO is for sections that are essentially read-only but need to
775 // be writable only at process startup to allow dynamic linker to
776 // apply relocations.
777 if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
780 // Once initialized, TLS data segments are used as data templates
781 // for a thread-local storage. For each new thread, runtime
782 // allocates memory for a TLS and copy templates there. No thread
783 // are supposed to use templates directly. Thus, it can be in RELRO.
787 // .init_array, .preinit_array and .fini_array contain pointers to
788 // functions that are executed on process startup or exit. These
789 // pointers are set by the static linker, and they are not expected
790 // to change at runtime. But if you are an attacker, you could do
791 // interesting things by manipulating pointers in .fini_array, for
792 // example. So they are put into RELRO.
793 uint32_t type = sec->type;
794 if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
795 type == SHT_PREINIT_ARRAY)
798 // .got contains pointers to external symbols. They are resolved by
799 // the dynamic linker when a module is loaded into memory, and after
800 // that they are not expected to change. So, it can be in RELRO.
801 if (in.got && sec == in.got->getParent())
804 // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
805 // through r2 register, which is reserved for that purpose. Since r2 is used
806 // for accessing .got as well, .got and .toc need to be close enough in the
807 // virtual address space. Usually, .toc comes just after .got. Since we place
808 // .got into RELRO, .toc needs to be placed into RELRO too.
809 if (sec->name.equals(".toc"))
812 // .got.plt contains pointers to external function symbols. They are
813 // by default resolved lazily, so we usually cannot put it into RELRO.
814 // However, if "-z now" is given, the lazy symbol resolution is
815 // disabled, which enables us to put it into RELRO.
816 if (sec == in.gotPlt->getParent())
819 // .dynamic section contains data for the dynamic linker, and
820 // there's no need to write to it at runtime, so it's better to put
822 if (sec->name == ".dynamic")
825 // Sections with some special names are put into RELRO. This is a
826 // bit unfortunate because section names shouldn't be significant in
827 // ELF in spirit. But in reality many linker features depend on
828 // magic section names.
829 StringRef s = sec->name;
830 return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
831 s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
832 s == ".openbsd.randomdata";
835 // We compute a rank for each section. The rank indicates where the
836 // section should be placed in the file. Instead of using simple
837 // numbers (0,1,2...), we use a series of flags. One for each decision
838 // point when placing the section.
839 // Using flags has two key properties:
840 // * It is easy to check if a give branch was taken.
841 // * It is easy two see how similar two ranks are (see getRankProximity).
843 RF_NOT_ADDR_SET = 1 << 27,
844 RF_NOT_ALLOC = 1 << 26,
845 RF_PARTITION = 1 << 18, // Partition number (8 bits)
846 RF_NOT_PART_EHDR = 1 << 17,
847 RF_NOT_PART_PHDR = 1 << 16,
848 RF_NOT_INTERP = 1 << 15,
849 RF_NOT_NOTE = 1 << 14,
851 RF_EXEC_WRITE = 1 << 12,
854 RF_NOT_RELRO = 1 << 9,
857 RF_PPC_NOT_TOCBSS = 1 << 6,
858 RF_PPC_TOCL = 1 << 5,
861 RF_PPC_BRANCH_LT = 1 << 2,
862 RF_MIPS_GPREL = 1 << 1,
863 RF_MIPS_NOT_GOT = 1 << 0
866 static unsigned getSectionRank(const OutputSection *sec) {
867 unsigned rank = sec->partition * RF_PARTITION;
869 // We want to put section specified by -T option first, so we
870 // can start assigning VA starting from them later.
871 if (config->sectionStartMap.count(sec->name))
873 rank |= RF_NOT_ADDR_SET;
875 // Allocatable sections go first to reduce the total PT_LOAD size and
876 // so debug info doesn't change addresses in actual code.
877 if (!(sec->flags & SHF_ALLOC))
878 return rank | RF_NOT_ALLOC;
880 if (sec->type == SHT_LLVM_PART_EHDR)
882 rank |= RF_NOT_PART_EHDR;
884 if (sec->type == SHT_LLVM_PART_PHDR)
886 rank |= RF_NOT_PART_PHDR;
888 // Put .interp first because some loaders want to see that section
889 // on the first page of the executable file when loaded into memory.
890 if (sec->name == ".interp")
892 rank |= RF_NOT_INTERP;
894 // Put .note sections (which make up one PT_NOTE) at the beginning so that
895 // they are likely to be included in a core file even if core file size is
896 // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
897 // included in a core to match core files with executables.
898 if (sec->type == SHT_NOTE)
902 // Sort sections based on their access permission in the following
903 // order: R, RX, RWX, RW. This order is based on the following
905 // * Read-only sections come first such that they go in the
906 // PT_LOAD covering the program headers at the start of the file.
907 // * Read-only, executable sections come next.
908 // * Writable, executable sections follow such that .plt on
909 // architectures where it needs to be writable will be placed
910 // between .text and .data.
911 // * Writable sections come last, such that .bss lands at the very
912 // end of the last PT_LOAD.
913 bool isExec = sec->flags & SHF_EXECINSTR;
914 bool isWrite = sec->flags & SHF_WRITE;
918 rank |= RF_EXEC_WRITE;
921 } else if (isWrite) {
923 } else if (sec->type == SHT_PROGBITS) {
924 // Make non-executable and non-writable PROGBITS sections (e.g .rodata
925 // .eh_frame) closer to .text. They likely contain PC or GOT relative
926 // relocations and there could be relocation overflow if other huge sections
927 // (.dynstr .dynsym) were placed in between.
931 // Place RelRo sections first. After considering SHT_NOBITS below, the
932 // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
933 // where | marks where page alignment happens. An alternative ordering is
934 // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
935 // waste more bytes due to 2 alignment places.
936 if (!isRelroSection(sec))
937 rank |= RF_NOT_RELRO;
939 // If we got here we know that both A and B are in the same PT_LOAD.
941 // The TLS initialization block needs to be a single contiguous block in a R/W
942 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
943 // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
945 if (!(sec->flags & SHF_TLS))
948 // Within TLS sections, or within other RelRo sections, or within non-RelRo
949 // sections, place non-NOBITS sections first.
950 if (sec->type == SHT_NOBITS)
953 // Some architectures have additional ordering restrictions for sections
954 // within the same PT_LOAD.
955 if (config->emachine == EM_PPC64) {
956 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
957 // that we would like to make sure appear is a specific order to maximize
958 // their coverage by a single signed 16-bit offset from the TOC base
959 // pointer. Conversely, the special .tocbss section should be first among
960 // all SHT_NOBITS sections. This will put it next to the loaded special
961 // PPC64 sections (and, thus, within reach of the TOC base pointer).
962 StringRef name = sec->name;
963 if (name != ".tocbss")
964 rank |= RF_PPC_NOT_TOCBSS;
975 if (name == ".branch_lt")
976 rank |= RF_PPC_BRANCH_LT;
979 if (config->emachine == EM_MIPS) {
980 // All sections with SHF_MIPS_GPREL flag should be grouped together
981 // because data in these sections is addressable with a gp relative address.
982 if (sec->flags & SHF_MIPS_GPREL)
983 rank |= RF_MIPS_GPREL;
985 if (sec->name != ".got")
986 rank |= RF_MIPS_NOT_GOT;
992 static bool compareSections(const BaseCommand *aCmd, const BaseCommand *bCmd) {
993 const OutputSection *a = cast<OutputSection>(aCmd);
994 const OutputSection *b = cast<OutputSection>(bCmd);
996 if (a->sortRank != b->sortRank)
997 return a->sortRank < b->sortRank;
999 if (!(a->sortRank & RF_NOT_ADDR_SET))
1000 return config->sectionStartMap.lookup(a->name) <
1001 config->sectionStartMap.lookup(b->name);
1005 void PhdrEntry::add(OutputSection *sec) {
1009 p_align = std::max(p_align, sec->alignment);
1010 if (p_type == PT_LOAD)
1014 // The beginning and the ending of .rel[a].plt section are marked
1015 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1016 // executable. The runtime needs these symbols in order to resolve
1017 // all IRELATIVE relocs on startup. For dynamic executables, we don't
1018 // need these symbols, since IRELATIVE relocs are resolved through GOT
1019 // and PLT. For details, see http://www.airs.com/blog/archives/403.
1020 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1021 if (config->relocatable || needsInterpSection())
1024 // By default, __rela_iplt_{start,end} belong to a dummy section 0
1025 // because .rela.plt might be empty and thus removed from output.
1026 // We'll override Out::elfHeader with In.relaIplt later when we are
1027 // sure that .rela.plt exists in output.
1028 ElfSym::relaIpltStart = addOptionalRegular(
1029 config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
1030 Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1032 ElfSym::relaIpltEnd = addOptionalRegular(
1033 config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1034 Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1037 template <class ELFT>
1038 void Writer<ELFT>::forEachRelSec(
1039 llvm::function_ref<void(InputSectionBase &)> fn) {
1040 // Scan all relocations. Each relocation goes through a series
1041 // of tests to determine if it needs special treatment, such as
1042 // creating GOT, PLT, copy relocations, etc.
1043 // Note that relocations for non-alloc sections are directly
1044 // processed by InputSection::relocateNonAlloc.
1045 for (InputSectionBase *isec : inputSections)
1046 if (isec->isLive() && isa<InputSection>(isec) && (isec->flags & SHF_ALLOC))
1048 for (Partition &part : partitions) {
1049 for (EhInputSection *es : part.ehFrame->sections)
1051 if (part.armExidx && part.armExidx->isLive())
1052 for (InputSection *ex : part.armExidx->exidxSections)
1057 // This function generates assignments for predefined symbols (e.g. _end or
1058 // _etext) and inserts them into the commands sequence to be processed at the
1059 // appropriate time. This ensures that the value is going to be correct by the
1060 // time any references to these symbols are processed and is equivalent to
1061 // defining these symbols explicitly in the linker script.
1062 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1063 if (ElfSym::globalOffsetTable) {
1064 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1065 // to the start of the .got or .got.plt section.
1066 InputSection *gotSection = in.gotPlt;
1067 if (!target->gotBaseSymInGotPlt)
1068 gotSection = in.mipsGot ? cast<InputSection>(in.mipsGot)
1069 : cast<InputSection>(in.got);
1070 ElfSym::globalOffsetTable->section = gotSection;
1073 // .rela_iplt_{start,end} mark the start and the end of .rela.plt section.
1074 if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
1075 ElfSym::relaIpltStart->section = in.relaIplt;
1076 ElfSym::relaIpltEnd->section = in.relaIplt;
1077 ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1080 PhdrEntry *last = nullptr;
1081 PhdrEntry *lastRO = nullptr;
1083 for (Partition &part : partitions) {
1084 for (PhdrEntry *p : part.phdrs) {
1085 if (p->p_type != PT_LOAD)
1088 if (!(p->p_flags & PF_W))
1094 // _etext is the first location after the last read-only loadable segment.
1096 ElfSym::etext1->section = lastRO->lastSec;
1098 ElfSym::etext2->section = lastRO->lastSec;
1102 // _edata points to the end of the last mapped initialized section.
1103 OutputSection *edata = nullptr;
1104 for (OutputSection *os : outputSections) {
1105 if (os->type != SHT_NOBITS)
1107 if (os == last->lastSec)
1112 ElfSym::edata1->section = edata;
1114 ElfSym::edata2->section = edata;
1116 // _end is the first location after the uninitialized data region.
1118 ElfSym::end1->section = last->lastSec;
1120 ElfSym::end2->section = last->lastSec;
1124 ElfSym::bss->section = findSection(".bss");
1126 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1127 // be equal to the _gp symbol's value.
1128 if (ElfSym::mipsGp) {
1129 // Find GP-relative section with the lowest address
1130 // and use this address to calculate default _gp value.
1131 for (OutputSection *os : outputSections) {
1132 if (os->flags & SHF_MIPS_GPREL) {
1133 ElfSym::mipsGp->section = os;
1134 ElfSym::mipsGp->value = 0x7ff0;
1141 // We want to find how similar two ranks are.
1142 // The more branches in getSectionRank that match, the more similar they are.
1143 // Since each branch corresponds to a bit flag, we can just use
1144 // countLeadingZeros.
1145 static int getRankProximityAux(OutputSection *a, OutputSection *b) {
1146 return countLeadingZeros(a->sortRank ^ b->sortRank);
1149 static int getRankProximity(OutputSection *a, BaseCommand *b) {
1150 auto *sec = dyn_cast<OutputSection>(b);
1151 return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1;
1154 // When placing orphan sections, we want to place them after symbol assignments
1155 // so that an orphan after
1159 // doesn't break the intended meaning of the begin/end symbols.
1160 // We don't want to go over sections since findOrphanPos is the
1161 // one in charge of deciding the order of the sections.
1162 // We don't want to go over changes to '.', since doing so in
1163 // rx_sec : { *(rx_sec) }
1164 // . = ALIGN(0x1000);
1165 // /* The RW PT_LOAD starts here*/
1166 // rw_sec : { *(rw_sec) }
1167 // would mean that the RW PT_LOAD would become unaligned.
1168 static bool shouldSkip(BaseCommand *cmd) {
1169 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1170 return assign->name != ".";
1174 // We want to place orphan sections so that they share as much
1175 // characteristics with their neighbors as possible. For example, if
1176 // both are rw, or both are tls.
1177 static std::vector<BaseCommand *>::iterator
1178 findOrphanPos(std::vector<BaseCommand *>::iterator b,
1179 std::vector<BaseCommand *>::iterator e) {
1180 OutputSection *sec = cast<OutputSection>(*e);
1182 // Find the first element that has as close a rank as possible.
1183 auto i = std::max_element(b, e, [=](BaseCommand *a, BaseCommand *b) {
1184 return getRankProximity(sec, a) < getRankProximity(sec, b);
1189 // Consider all existing sections with the same proximity.
1190 int proximity = getRankProximity(sec, *i);
1191 for (; i != e; ++i) {
1192 auto *curSec = dyn_cast<OutputSection>(*i);
1193 if (!curSec || !curSec->hasInputSections)
1195 if (getRankProximity(sec, curSec) != proximity ||
1196 sec->sortRank < curSec->sortRank)
1200 auto isOutputSecWithInputSections = [](BaseCommand *cmd) {
1201 auto *os = dyn_cast<OutputSection>(cmd);
1202 return os && os->hasInputSections;
1204 auto j = std::find_if(llvm::make_reverse_iterator(i),
1205 llvm::make_reverse_iterator(b),
1206 isOutputSecWithInputSections);
1209 // As a special case, if the orphan section is the last section, put
1210 // it at the very end, past any other commands.
1211 // This matches bfd's behavior and is convenient when the linker script fully
1212 // specifies the start of the file, but doesn't care about the end (the non
1213 // alloc sections for example).
1214 auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1218 while (i != e && shouldSkip(*i))
1223 // Builds section order for handling --symbol-ordering-file.
1224 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1225 DenseMap<const InputSectionBase *, int> sectionOrder;
1226 // Use the rarely used option -call-graph-ordering-file to sort sections.
1227 if (!config->callGraphProfile.empty())
1228 return computeCallGraphProfileOrder();
1230 if (config->symbolOrderingFile.empty())
1231 return sectionOrder;
1233 struct SymbolOrderEntry {
1238 // Build a map from symbols to their priorities. Symbols that didn't
1239 // appear in the symbol ordering file have the lowest priority 0.
1240 // All explicitly mentioned symbols have negative (higher) priorities.
1241 DenseMap<StringRef, SymbolOrderEntry> symbolOrder;
1242 int priority = -config->symbolOrderingFile.size();
1243 for (StringRef s : config->symbolOrderingFile)
1244 symbolOrder.insert({s, {priority++, false}});
1246 // Build a map from sections to their priorities.
1247 auto addSym = [&](Symbol &sym) {
1248 auto it = symbolOrder.find(sym.getName());
1249 if (it == symbolOrder.end())
1251 SymbolOrderEntry &ent = it->second;
1254 maybeWarnUnorderableSymbol(&sym);
1256 if (auto *d = dyn_cast<Defined>(&sym)) {
1257 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1258 int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)];
1259 priority = std::min(priority, ent.priority);
1264 // We want both global and local symbols. We get the global ones from the
1265 // symbol table and iterate the object files for the local ones.
1266 symtab->forEachSymbol([&](Symbol *sym) {
1271 for (InputFile *file : objectFiles)
1272 for (Symbol *sym : file->getSymbols())
1276 if (config->warnSymbolOrdering)
1277 for (auto orderEntry : symbolOrder)
1278 if (!orderEntry.second.present)
1279 warn("symbol ordering file: no such symbol: " + orderEntry.first);
1281 return sectionOrder;
1284 // Sorts the sections in ISD according to the provided section order.
1286 sortISDBySectionOrder(InputSectionDescription *isd,
1287 const DenseMap<const InputSectionBase *, int> &order) {
1288 std::vector<InputSection *> unorderedSections;
1289 std::vector<std::pair<InputSection *, int>> orderedSections;
1290 uint64_t unorderedSize = 0;
1292 for (InputSection *isec : isd->sections) {
1293 auto i = order.find(isec);
1294 if (i == order.end()) {
1295 unorderedSections.push_back(isec);
1296 unorderedSize += isec->getSize();
1299 orderedSections.push_back({isec, i->second});
1301 llvm::sort(orderedSections, [&](std::pair<InputSection *, int> a,
1302 std::pair<InputSection *, int> b) {
1303 return a.second < b.second;
1306 // Find an insertion point for the ordered section list in the unordered
1307 // section list. On targets with limited-range branches, this is the mid-point
1308 // of the unordered section list. This decreases the likelihood that a range
1309 // extension thunk will be needed to enter or exit the ordered region. If the
1310 // ordered section list is a list of hot functions, we can generally expect
1311 // the ordered functions to be called more often than the unordered functions,
1312 // making it more likely that any particular call will be within range, and
1313 // therefore reducing the number of thunks required.
1315 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1316 // If the layout is:
1321 // only the first 8-16MB of the cold code (depending on which hot function it
1322 // is actually calling) can call the hot code without a range extension thunk.
1323 // However, if we use this layout:
1329 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1330 // of the second block of cold code can call the hot code without a thunk. So
1331 // we effectively double the amount of code that could potentially call into
1332 // the hot code without a thunk.
1334 if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1335 uint64_t unorderedPos = 0;
1336 for (; insPt != unorderedSections.size(); ++insPt) {
1337 unorderedPos += unorderedSections[insPt]->getSize();
1338 if (unorderedPos > unorderedSize / 2)
1343 isd->sections.clear();
1344 for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1345 isd->sections.push_back(isec);
1346 for (std::pair<InputSection *, int> p : orderedSections)
1347 isd->sections.push_back(p.first);
1348 for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1349 isd->sections.push_back(isec);
1352 static void sortSection(OutputSection *sec,
1353 const DenseMap<const InputSectionBase *, int> &order) {
1354 StringRef name = sec->name;
1356 // Sort input sections by section name suffixes for
1357 // __attribute__((init_priority(N))).
1358 if (name == ".init_array" || name == ".fini_array") {
1359 if (!script->hasSectionsCommand)
1360 sec->sortInitFini();
1364 // Sort input sections by the special rule for .ctors and .dtors.
1365 if (name == ".ctors" || name == ".dtors") {
1366 if (!script->hasSectionsCommand)
1367 sec->sortCtorsDtors();
1371 // Never sort these.
1372 if (name == ".init" || name == ".fini")
1375 // .toc is allocated just after .got and is accessed using GOT-relative
1376 // relocations. Object files compiled with small code model have an
1377 // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1378 // To reduce the risk of relocation overflow, .toc contents are sorted so that
1379 // sections having smaller relocation offsets are at beginning of .toc
1380 if (config->emachine == EM_PPC64 && name == ".toc") {
1381 if (script->hasSectionsCommand)
1383 assert(sec->sectionCommands.size() == 1);
1384 auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]);
1385 llvm::stable_sort(isd->sections,
1386 [](const InputSection *a, const InputSection *b) -> bool {
1387 return a->file->ppc64SmallCodeModelTocRelocs &&
1388 !b->file->ppc64SmallCodeModelTocRelocs;
1393 // Sort input sections by priority using the list provided
1394 // by --symbol-ordering-file.
1396 for (BaseCommand *b : sec->sectionCommands)
1397 if (auto *isd = dyn_cast<InputSectionDescription>(b))
1398 sortISDBySectionOrder(isd, order);
1401 // If no layout was provided by linker script, we want to apply default
1402 // sorting for special input sections. This also handles --symbol-ordering-file.
1403 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1404 // Build the order once since it is expensive.
1405 DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1406 for (BaseCommand *base : script->sectionCommands)
1407 if (auto *sec = dyn_cast<OutputSection>(base))
1408 sortSection(sec, order);
1411 template <class ELFT> void Writer<ELFT>::sortSections() {
1412 script->adjustSectionsBeforeSorting();
1414 // Don't sort if using -r. It is not necessary and we want to preserve the
1415 // relative order for SHF_LINK_ORDER sections.
1416 if (config->relocatable)
1419 sortInputSections();
1421 for (BaseCommand *base : script->sectionCommands) {
1422 auto *os = dyn_cast<OutputSection>(base);
1425 os->sortRank = getSectionRank(os);
1427 // We want to assign rude approximation values to outSecOff fields
1428 // to know the relative order of the input sections. We use it for
1429 // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1431 for (InputSection *sec : getInputSections(os))
1432 sec->outSecOff = i++;
1435 if (!script->hasSectionsCommand) {
1436 // We know that all the OutputSections are contiguous in this case.
1437 auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); };
1439 llvm::find_if(script->sectionCommands, isSection),
1440 llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1445 // Orphan sections are sections present in the input files which are
1446 // not explicitly placed into the output file by the linker script.
1448 // The sections in the linker script are already in the correct
1449 // order. We have to figuere out where to insert the orphan
1452 // The order of the sections in the script is arbitrary and may not agree with
1453 // compareSections. This means that we cannot easily define a strict weak
1454 // ordering. To see why, consider a comparison of a section in the script and
1455 // one not in the script. We have a two simple options:
1456 // * Make them equivalent (a is not less than b, and b is not less than a).
1457 // The problem is then that equivalence has to be transitive and we can
1458 // have sections a, b and c with only b in a script and a less than c
1459 // which breaks this property.
1460 // * Use compareSectionsNonScript. Given that the script order doesn't have
1461 // to match, we can end up with sections a, b, c, d where b and c are in the
1462 // script and c is compareSectionsNonScript less than b. In which case d
1463 // can be equivalent to c, a to b and d < a. As a concrete example:
1464 // .a (rx) # not in script
1465 // .b (rx) # in script
1466 // .c (ro) # in script
1467 // .d (ro) # not in script
1469 // The way we define an order then is:
1470 // * Sort only the orphan sections. They are in the end right now.
1471 // * Move each orphan section to its preferred position. We try
1472 // to put each section in the last position where it can share
1475 // There is some ambiguity as to where exactly a new entry should be
1476 // inserted, because Commands contains not only output section
1477 // commands but also other types of commands such as symbol assignment
1478 // expressions. There's no correct answer here due to the lack of the
1479 // formal specification of the linker script. We use heuristics to
1480 // determine whether a new output command should be added before or
1481 // after another commands. For the details, look at shouldSkip
1484 auto i = script->sectionCommands.begin();
1485 auto e = script->sectionCommands.end();
1486 auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) {
1487 if (auto *sec = dyn_cast<OutputSection>(base))
1488 return sec->sectionIndex == UINT32_MAX;
1492 // Sort the orphan sections.
1493 std::stable_sort(nonScriptI, e, compareSections);
1495 // As a horrible special case, skip the first . assignment if it is before any
1496 // section. We do this because it is common to set a load address by starting
1497 // the script with ". = 0xabcd" and the expectation is that every section is
1499 auto firstSectionOrDotAssignment =
1500 std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); });
1501 if (firstSectionOrDotAssignment != e &&
1502 isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1503 ++firstSectionOrDotAssignment;
1504 i = firstSectionOrDotAssignment;
1506 while (nonScriptI != e) {
1507 auto pos = findOrphanPos(i, nonScriptI);
1508 OutputSection *orphan = cast<OutputSection>(*nonScriptI);
1510 // As an optimization, find all sections with the same sort rank
1511 // and insert them with one rotate.
1512 unsigned rank = orphan->sortRank;
1513 auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) {
1514 return cast<OutputSection>(cmd)->sortRank != rank;
1516 std::rotate(pos, nonScriptI, end);
1520 script->adjustSectionsAfterSorting();
1523 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1524 InputSection *la = a->getLinkOrderDep();
1525 InputSection *lb = b->getLinkOrderDep();
1526 OutputSection *aOut = la->getParent();
1527 OutputSection *bOut = lb->getParent();
1530 return aOut->sectionIndex < bOut->sectionIndex;
1531 return la->outSecOff < lb->outSecOff;
1534 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1535 for (OutputSection *sec : outputSections) {
1536 if (!(sec->flags & SHF_LINK_ORDER))
1539 // Link order may be distributed across several InputSectionDescriptions
1540 // but sort must consider them all at once.
1541 std::vector<InputSection **> scriptSections;
1542 std::vector<InputSection *> sections;
1543 for (BaseCommand *base : sec->sectionCommands) {
1544 if (auto *isd = dyn_cast<InputSectionDescription>(base)) {
1545 for (InputSection *&isec : isd->sections) {
1546 scriptSections.push_back(&isec);
1547 sections.push_back(isec);
1552 // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1553 // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1554 if (!config->relocatable && config->emachine == EM_ARM &&
1555 sec->type == SHT_ARM_EXIDX)
1558 llvm::stable_sort(sections, compareByFilePosition);
1560 for (int i = 0, n = sections.size(); i < n; ++i)
1561 *scriptSections[i] = sections[i];
1565 // We need to generate and finalize the content that depends on the address of
1566 // InputSections. As the generation of the content may also alter InputSection
1567 // addresses we must converge to a fixed point. We do that here. See the comment
1568 // in Writer<ELFT>::finalizeSections().
1569 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1571 AArch64Err843419Patcher a64p;
1573 // For some targets, like x86, this loop iterates only once.
1575 bool changed = false;
1577 script->assignAddresses();
1579 if (target->needsThunks)
1580 changed |= tc.createThunks(outputSections);
1582 if (config->fixCortexA53Errata843419) {
1584 script->assignAddresses();
1585 changed |= a64p.createFixes();
1589 in.mipsGot->updateAllocSize();
1591 for (Partition &part : partitions) {
1592 changed |= part.relaDyn->updateAllocSize();
1594 changed |= part.relrDyn->updateAllocSize();
1602 static void finalizeSynthetic(SyntheticSection *sec) {
1603 if (sec && sec->isNeeded() && sec->getParent())
1604 sec->finalizeContents();
1607 // In order to allow users to manipulate linker-synthesized sections,
1608 // we had to add synthetic sections to the input section list early,
1609 // even before we make decisions whether they are needed. This allows
1610 // users to write scripts like this: ".mygot : { .got }".
1612 // Doing it has an unintended side effects. If it turns out that we
1613 // don't need a .got (for example) at all because there's no
1614 // relocation that needs a .got, we don't want to emit .got.
1616 // To deal with the above problem, this function is called after
1617 // scanRelocations is called to remove synthetic sections that turn
1619 static void removeUnusedSyntheticSections() {
1620 // All input synthetic sections that can be empty are placed after
1621 // all regular ones. We iterate over them all and exit at first
1623 for (InputSectionBase *s : llvm::reverse(inputSections)) {
1624 SyntheticSection *ss = dyn_cast<SyntheticSection>(s);
1627 OutputSection *os = ss->getParent();
1628 if (!os || ss->isNeeded())
1631 // If we reach here, then SS is an unused synthetic section and we want to
1632 // remove it from corresponding input section description of output section.
1633 for (BaseCommand *b : os->sectionCommands)
1634 if (auto *isd = dyn_cast<InputSectionDescription>(b))
1635 llvm::erase_if(isd->sections,
1636 [=](InputSection *isec) { return isec == ss; });
1640 // Returns true if a symbol can be replaced at load-time by a symbol
1641 // with the same name defined in other ELF executable or DSO.
1642 static bool computeIsPreemptible(const Symbol &b) {
1643 assert(!b.isLocal());
1645 // Only symbols that appear in dynsym can be preempted.
1646 if (!b.includeInDynsym())
1649 // Only default visibility symbols can be preempted.
1650 if (b.visibility != STV_DEFAULT)
1653 // At this point copy relocations have not been created yet, so any
1654 // symbol that is not defined locally is preemptible.
1658 // If we have a dynamic list it specifies which local symbols are preemptible.
1659 if (config->hasDynamicList)
1662 if (!config->shared)
1665 // -Bsymbolic means that definitions are not preempted.
1666 if (config->bsymbolic || (config->bsymbolicFunctions && b.isFunc()))
1671 // Create output section objects and add them to OutputSections.
1672 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1673 Out::preinitArray = findSection(".preinit_array");
1674 Out::initArray = findSection(".init_array");
1675 Out::finiArray = findSection(".fini_array");
1677 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1678 // symbols for sections, so that the runtime can get the start and end
1679 // addresses of each section by section name. Add such symbols.
1680 if (!config->relocatable) {
1681 addStartEndSymbols();
1682 for (BaseCommand *base : script->sectionCommands)
1683 if (auto *sec = dyn_cast<OutputSection>(base))
1684 addStartStopSymbols(sec);
1687 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1688 // It should be okay as no one seems to care about the type.
1689 // Even the author of gold doesn't remember why gold behaves that way.
1690 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1691 if (mainPart->dynamic->parent)
1692 symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK,
1693 STV_HIDDEN, STT_NOTYPE,
1694 /*value=*/0, /*size=*/0, mainPart->dynamic});
1696 // Define __rel[a]_iplt_{start,end} symbols if needed.
1697 addRelIpltSymbols();
1699 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1700 // This symbol should only be defined in an executable.
1701 if (config->emachine == EM_RISCV && !config->shared)
1702 ElfSym::riscvGlobalPointer =
1703 addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800,
1704 STV_DEFAULT, STB_GLOBAL);
1706 if (config->emachine == EM_X86_64) {
1707 // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1710 // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1712 // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1715 // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1716 // an absolute symbol of zero. This is different from GNU linkers which
1717 // define _TLS_MODULE_BASE_ relative to the first TLS section.
1718 Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1719 if (s && s->isUndefined()) {
1720 s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN,
1721 STT_TLS, /*value=*/0, 0,
1722 /*section=*/nullptr});
1723 ElfSym::tlsModuleBase = cast<Defined>(s);
1727 // This responsible for splitting up .eh_frame section into
1728 // pieces. The relocation scan uses those pieces, so this has to be
1730 for (Partition &part : partitions)
1731 finalizeSynthetic(part.ehFrame);
1733 symtab->forEachSymbol([](Symbol *s) {
1734 if (!s->isPreemptible)
1735 s->isPreemptible = computeIsPreemptible(*s);
1738 // Scan relocations. This must be done after every symbol is declared so that
1739 // we can correctly decide if a dynamic relocation is needed.
1740 if (!config->relocatable) {
1741 forEachRelSec(scanRelocations<ELFT>);
1742 reportUndefinedSymbols<ELFT>();
1745 addIRelativeRelocs();
1747 if (in.plt && in.plt->isNeeded())
1748 in.plt->addSymbols();
1749 if (in.iplt && in.iplt->isNeeded())
1750 in.iplt->addSymbols();
1752 if (!config->allowShlibUndefined) {
1753 // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1754 // entires are seen. These cases would otherwise lead to runtime errors
1755 // reported by the dynamic linker.
1757 // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1758 // catch more cases. That is too much for us. Our approach resembles the one
1759 // used in ld.gold, achieves a good balance to be useful but not too smart.
1760 for (SharedFile *file : sharedFiles)
1761 file->allNeededIsKnown =
1762 llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1763 return symtab->soNames.count(needed);
1766 symtab->forEachSymbol([](Symbol *sym) {
1767 if (sym->isUndefined() && !sym->isWeak())
1768 if (auto *f = dyn_cast_or_null<SharedFile>(sym->file))
1769 if (f->allNeededIsKnown)
1770 error(toString(f) + ": undefined reference to " + toString(*sym));
1774 // Now that we have defined all possible global symbols including linker-
1775 // synthesized ones. Visit all symbols to give the finishing touches.
1776 symtab->forEachSymbol([](Symbol *sym) {
1777 if (!includeInSymtab(*sym))
1780 in.symTab->addSymbol(sym);
1782 if (sym->includeInDynsym()) {
1783 partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1784 if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1785 if (file->isNeeded && !sym->isUndefined())
1790 // We also need to scan the dynamic relocation tables of the other partitions
1791 // and add any referenced symbols to the partition's dynsym.
1792 for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1793 DenseSet<Symbol *> syms;
1794 for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1796 for (DynamicReloc &reloc : part.relaDyn->relocs)
1797 if (reloc.sym && !reloc.useSymVA && syms.insert(reloc.sym).second)
1798 part.dynSymTab->addSymbol(reloc.sym);
1801 // Do not proceed if there was an undefined symbol.
1806 in.mipsGot->build();
1808 removeUnusedSyntheticSections();
1812 // Now that we have the final list, create a list of all the
1813 // OutputSections for convenience.
1814 for (BaseCommand *base : script->sectionCommands)
1815 if (auto *sec = dyn_cast<OutputSection>(base))
1816 outputSections.push_back(sec);
1818 // Prefer command line supplied address over other constraints.
1819 for (OutputSection *sec : outputSections) {
1820 auto i = config->sectionStartMap.find(sec->name);
1821 if (i != config->sectionStartMap.end())
1822 sec->addrExpr = [=] { return i->second; };
1825 // This is a bit of a hack. A value of 0 means undef, so we set it
1826 // to 1 to make __ehdr_start defined. The section number is not
1827 // particularly relevant.
1828 Out::elfHeader->sectionIndex = 1;
1830 for (size_t i = 0, e = outputSections.size(); i != e; ++i) {
1831 OutputSection *sec = outputSections[i];
1832 sec->sectionIndex = i + 1;
1833 sec->shName = in.shStrTab->addString(sec->name);
1836 // Binary and relocatable output does not have PHDRS.
1837 // The headers have to be created before finalize as that can influence the
1838 // image base and the dynamic section on mips includes the image base.
1839 if (!config->relocatable && !config->oFormatBinary) {
1840 for (Partition &part : partitions) {
1841 part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
1842 : createPhdrs(part);
1843 if (config->emachine == EM_ARM) {
1844 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1845 addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
1847 if (config->emachine == EM_MIPS) {
1848 // Add separate segments for MIPS-specific sections.
1849 addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
1850 addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
1851 addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
1854 Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
1856 // Find the TLS segment. This happens before the section layout loop so that
1857 // Android relocation packing can look up TLS symbol addresses. We only need
1858 // to care about the main partition here because all TLS symbols were moved
1859 // to the main partition (see MarkLive.cpp).
1860 for (PhdrEntry *p : mainPart->phdrs)
1861 if (p->p_type == PT_TLS)
1865 // Some symbols are defined in term of program headers. Now that we
1866 // have the headers, we can find out which sections they point to.
1867 setReservedSymbolSections();
1869 finalizeSynthetic(in.bss);
1870 finalizeSynthetic(in.bssRelRo);
1871 finalizeSynthetic(in.symTabShndx);
1872 finalizeSynthetic(in.shStrTab);
1873 finalizeSynthetic(in.strTab);
1874 finalizeSynthetic(in.got);
1875 finalizeSynthetic(in.mipsGot);
1876 finalizeSynthetic(in.igotPlt);
1877 finalizeSynthetic(in.gotPlt);
1878 finalizeSynthetic(in.relaIplt);
1879 finalizeSynthetic(in.relaPlt);
1880 finalizeSynthetic(in.plt);
1881 finalizeSynthetic(in.iplt);
1882 finalizeSynthetic(in.ppc32Got2);
1883 finalizeSynthetic(in.riscvSdata);
1884 finalizeSynthetic(in.partIndex);
1886 // Dynamic section must be the last one in this list and dynamic
1887 // symbol table section (dynSymTab) must be the first one.
1888 for (Partition &part : partitions) {
1889 finalizeSynthetic(part.armExidx);
1890 finalizeSynthetic(part.dynSymTab);
1891 finalizeSynthetic(part.gnuHashTab);
1892 finalizeSynthetic(part.hashTab);
1893 finalizeSynthetic(part.verDef);
1894 finalizeSynthetic(part.relaDyn);
1895 finalizeSynthetic(part.relrDyn);
1896 finalizeSynthetic(part.ehFrameHdr);
1897 finalizeSynthetic(part.verSym);
1898 finalizeSynthetic(part.verNeed);
1899 finalizeSynthetic(part.dynamic);
1902 if (!script->hasSectionsCommand && !config->relocatable)
1903 fixSectionAlignments();
1905 // SHFLinkOrder processing must be processed after relative section placements are
1906 // known but before addresses are allocated.
1907 resolveShfLinkOrder();
1910 // 1) Create "thunks":
1911 // Jump instructions in many ISAs have small displacements, and therefore
1912 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
1913 // JAL instruction can target only +-1 MiB from PC. It is a linker's
1914 // responsibility to create and insert small pieces of code between
1915 // sections to extend the ranges if jump targets are out of range. Such
1916 // code pieces are called "thunks".
1918 // We add thunks at this stage. We couldn't do this before this point
1919 // because this is the earliest point where we know sizes of sections and
1920 // their layouts (that are needed to determine if jump targets are in
1923 // 2) Update the sections. We need to generate content that depends on the
1924 // address of InputSections. For example, MIPS GOT section content or
1925 // android packed relocations sections content.
1927 // 3) Assign the final values for the linker script symbols. Linker scripts
1928 // sometimes using forward symbol declarations. We want to set the correct
1929 // values. They also might change after adding the thunks.
1930 finalizeAddressDependentContent();
1932 // finalizeAddressDependentContent may have added local symbols to the static symbol table.
1933 finalizeSynthetic(in.symTab);
1934 finalizeSynthetic(in.ppc64LongBranchTarget);
1936 // Fill other section headers. The dynamic table is finalized
1937 // at the end because some tags like RELSZ depend on result
1938 // of finalizing other sections.
1939 for (OutputSection *sec : outputSections)
1943 // Ensure data sections are not mixed with executable sections when
1944 // -execute-only is used. -execute-only is a feature to make pages executable
1945 // but not readable, and the feature is currently supported only on AArch64.
1946 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1947 if (!config->executeOnly)
1950 for (OutputSection *os : outputSections)
1951 if (os->flags & SHF_EXECINSTR)
1952 for (InputSection *isec : getInputSections(os))
1953 if (!(isec->flags & SHF_EXECINSTR))
1954 error("cannot place " + toString(isec) + " into " + toString(os->name) +
1955 ": -execute-only does not support intermingling data and code");
1958 // The linker is expected to define SECNAME_start and SECNAME_end
1959 // symbols for a few sections. This function defines them.
1960 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1961 // If a section does not exist, there's ambiguity as to how we
1962 // define _start and _end symbols for an init/fini section. Since
1963 // the loader assume that the symbols are always defined, we need to
1964 // always define them. But what value? The loader iterates over all
1965 // pointers between _start and _end to run global ctors/dtors, so if
1966 // the section is empty, their symbol values don't actually matter
1967 // as long as _start and _end point to the same location.
1969 // That said, we don't want to set the symbols to 0 (which is
1970 // probably the simplest value) because that could cause some
1971 // program to fail to link due to relocation overflow, if their
1972 // program text is above 2 GiB. We use the address of the .text
1973 // section instead to prevent that failure.
1975 // In a rare sitaution, .text section may not exist. If that's the
1976 // case, use the image base address as a last resort.
1977 OutputSection *Default = findSection(".text");
1979 Default = Out::elfHeader;
1981 auto define = [=](StringRef start, StringRef end, OutputSection *os) {
1983 addOptionalRegular(start, os, 0);
1984 addOptionalRegular(end, os, -1);
1986 addOptionalRegular(start, Default, 0);
1987 addOptionalRegular(end, Default, 0);
1991 define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
1992 define("__init_array_start", "__init_array_end", Out::initArray);
1993 define("__fini_array_start", "__fini_array_end", Out::finiArray);
1995 if (OutputSection *sec = findSection(".ARM.exidx"))
1996 define("__exidx_start", "__exidx_end", sec);
1999 // If a section name is valid as a C identifier (which is rare because of
2000 // the leading '.'), linkers are expected to define __start_<secname> and
2001 // __stop_<secname> symbols. They are at beginning and end of the section,
2002 // respectively. This is not requested by the ELF standard, but GNU ld and
2003 // gold provide the feature, and used by many programs.
2004 template <class ELFT>
2005 void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2006 StringRef s = sec->name;
2007 if (!isValidCIdentifier(s))
2009 addOptionalRegular(saver.save("__start_" + s), sec, 0, STV_PROTECTED);
2010 addOptionalRegular(saver.save("__stop_" + s), sec, -1, STV_PROTECTED);
2013 static bool needsPtLoad(OutputSection *sec) {
2014 if (!(sec->flags & SHF_ALLOC) || sec->noload)
2017 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2018 // responsible for allocating space for them, not the PT_LOAD that
2019 // contains the TLS initialization image.
2020 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2025 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2026 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2027 // RW. This means that there is no alignment in the RO to RX transition and we
2028 // cannot create a PT_LOAD there.
2029 static uint64_t computeFlags(uint64_t flags) {
2031 return PF_R | PF_W | PF_X;
2032 if (config->executeOnly && (flags & PF_X))
2033 return flags & ~PF_R;
2034 if (config->singleRoRx && !(flags & PF_W))
2035 return flags | PF_X;
2039 // Decide which program headers to create and which sections to include in each
2041 template <class ELFT>
2042 std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) {
2043 std::vector<PhdrEntry *> ret;
2044 auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2045 ret.push_back(make<PhdrEntry>(type, flags));
2049 unsigned partNo = part.getNumber();
2050 bool isMain = partNo == 1;
2052 // The first phdr entry is PT_PHDR which describes the program header itself.
2054 addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2056 addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2058 // PT_INTERP must be the second entry if exists.
2059 if (OutputSection *cmd = findSection(".interp", partNo))
2060 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2062 // Add the first PT_LOAD segment for regular output sections.
2063 uint64_t flags = computeFlags(PF_R);
2064 PhdrEntry *load = nullptr;
2066 // Add the headers. We will remove them if they don't fit.
2067 // In the other partitions the headers are ordinary sections, so they don't
2068 // need to be added here.
2070 load = addHdr(PT_LOAD, flags);
2071 load->add(Out::elfHeader);
2072 load->add(Out::programHeaders);
2075 // PT_GNU_RELRO includes all sections that should be marked as
2076 // read-only by dynamic linker after proccessing relocations.
2077 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2078 // an error message if more than one PT_GNU_RELRO PHDR is required.
2079 PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2080 bool inRelroPhdr = false;
2081 OutputSection *relroEnd = nullptr;
2082 for (OutputSection *sec : outputSections) {
2083 if (sec->partition != partNo || !needsPtLoad(sec))
2085 if (isRelroSection(sec)) {
2090 error("section: " + sec->name + " is not contiguous with other relro" +
2092 } else if (inRelroPhdr) {
2093 inRelroPhdr = false;
2098 for (OutputSection *sec : outputSections) {
2099 if (!(sec->flags & SHF_ALLOC))
2101 if (!needsPtLoad(sec))
2104 // Normally, sections in partitions other than the current partition are
2105 // ignored. But partition number 255 is a special case: it contains the
2106 // partition end marker (.part.end). It needs to be added to the main
2107 // partition so that a segment is created for it in the main partition,
2108 // which will cause the dynamic loader to reserve space for the other
2110 if (sec->partition != partNo) {
2111 if (isMain && sec->partition == 255)
2112 addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2116 // Segments are contiguous memory regions that has the same attributes
2117 // (e.g. executable or writable). There is one phdr for each segment.
2118 // Therefore, we need to create a new phdr when the next section has
2119 // different flags or is loaded at a discontiguous address or memory
2120 // region using AT or AT> linker script command, respectively. At the same
2121 // time, we don't want to create a separate load segment for the headers,
2122 // even if the first output section has an AT or AT> attribute.
2123 uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2126 (sec->lmaRegion && (sec->lmaRegion != load->firstSec->lmaRegion))) &&
2127 load->lastSec != Out::programHeaders) ||
2128 sec->memRegion != load->firstSec->memRegion || flags != newFlags ||
2130 load = addHdr(PT_LOAD, newFlags);
2137 // Add a TLS segment if any.
2138 PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2139 for (OutputSection *sec : outputSections)
2140 if (sec->partition == partNo && sec->flags & SHF_TLS)
2142 if (tlsHdr->firstSec)
2143 ret.push_back(tlsHdr);
2145 // Add an entry for .dynamic.
2146 if (OutputSection *sec = part.dynamic->getParent())
2147 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2149 if (relRo->firstSec)
2150 ret.push_back(relRo);
2152 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2153 if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2154 part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2155 addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2156 ->add(part.ehFrameHdr->getParent());
2158 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2159 // the dynamic linker fill the segment with random data.
2160 if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2161 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2163 // PT_GNU_STACK is a special section to tell the loader to make the
2164 // pages for the stack non-executable. If you really want an executable
2165 // stack, you can pass -z execstack, but that's not recommended for
2166 // security reasons.
2167 unsigned perm = PF_R | PF_W;
2168 if (config->zExecstack)
2170 addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2172 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2173 // is expected to perform W^X violations, such as calling mprotect(2) or
2174 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2176 if (config->zWxneeded)
2177 addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2179 // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2181 PhdrEntry *note = nullptr;
2182 for (OutputSection *sec : outputSections) {
2183 if (sec->partition != partNo)
2185 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2186 if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2187 note = addHdr(PT_NOTE, PF_R);
2196 template <class ELFT>
2197 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2198 unsigned pType, unsigned pFlags) {
2199 unsigned partNo = part.getNumber();
2200 auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2201 return cmd->partition == partNo && cmd->type == shType;
2203 if (i == outputSections.end())
2206 PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2208 part.phdrs.push_back(entry);
2211 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2212 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2213 // linker can set the permissions.
2214 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2215 auto pageAlign = [](OutputSection *cmd) {
2216 if (cmd && !cmd->addrExpr)
2217 cmd->addrExpr = [=] {
2218 return alignTo(script->getDot(), config->maxPageSize);
2222 for (Partition &part : partitions) {
2223 for (const PhdrEntry *p : part.phdrs)
2224 if (p->p_type == PT_LOAD && p->firstSec)
2225 pageAlign(p->firstSec);
2229 // Compute an in-file position for a given section. The file offset must be the
2230 // same with its virtual address modulo the page size, so that the loader can
2231 // load executables without any address adjustment.
2232 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2233 // The first section in a PT_LOAD has to have congruent offset and address
2234 // module the page size.
2235 if (os->ptLoad && os->ptLoad->firstSec == os) {
2236 uint64_t alignment =
2237 std::max<uint64_t>(os->ptLoad->p_align, config->maxPageSize);
2238 return alignTo(off, alignment, os->addr);
2241 // File offsets are not significant for .bss sections other than the first one
2242 // in a PT_LOAD. By convention, we keep section offsets monotonically
2243 // increasing rather than setting to zero.
2244 if (os->type == SHT_NOBITS)
2247 // If the section is not in a PT_LOAD, we just have to align it.
2249 return alignTo(off, os->alignment);
2251 // If two sections share the same PT_LOAD the file offset is calculated
2252 // using this formula: Off2 = Off1 + (VA2 - VA1).
2253 OutputSection *first = os->ptLoad->firstSec;
2254 return first->offset + os->addr - first->addr;
2257 // Set an in-file position to a given section and returns the end position of
2259 static uint64_t setFileOffset(OutputSection *os, uint64_t off) {
2260 off = computeFileOffset(os, off);
2263 if (os->type == SHT_NOBITS)
2265 return off + os->size;
2268 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2270 for (OutputSection *sec : outputSections)
2271 if (sec->flags & SHF_ALLOC)
2272 off = setFileOffset(sec, off);
2273 fileSize = alignTo(off, config->wordsize);
2276 static std::string rangeToString(uint64_t addr, uint64_t len) {
2277 return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2280 // Assign file offsets to output sections.
2281 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2283 off = setFileOffset(Out::elfHeader, off);
2284 off = setFileOffset(Out::programHeaders, off);
2286 PhdrEntry *lastRX = nullptr;
2287 for (Partition &part : partitions)
2288 for (PhdrEntry *p : part.phdrs)
2289 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2292 for (OutputSection *sec : outputSections) {
2293 off = setFileOffset(sec, off);
2294 if (script->hasSectionsCommand)
2297 // If this is a last section of the last executable segment and that
2298 // segment is the last loadable segment, align the offset of the
2299 // following section to avoid loading non-segments parts of the file.
2300 if (lastRX && lastRX->lastSec == sec)
2301 off = alignTo(off, config->commonPageSize);
2304 sectionHeaderOff = alignTo(off, config->wordsize);
2305 fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2307 // Our logic assumes that sections have rising VA within the same segment.
2308 // With use of linker scripts it is possible to violate this rule and get file
2309 // offset overlaps or overflows. That should never happen with a valid script
2310 // which does not move the location counter backwards and usually scripts do
2311 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2312 // kernel, which control segment distribution explicitly and move the counter
2313 // backwards, so we have to allow doing that to support linking them. We
2314 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2315 // we want to prevent file size overflows because it would crash the linker.
2316 for (OutputSection *sec : outputSections) {
2317 if (sec->type == SHT_NOBITS)
2319 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2320 error("unable to place section " + sec->name + " at file offset " +
2321 rangeToString(sec->offset, sec->size) +
2322 "; check your linker script for overflows");
2326 // Finalize the program headers. We call this function after we assign
2327 // file offsets and VAs to all sections.
2328 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2329 for (PhdrEntry *p : part.phdrs) {
2330 OutputSection *first = p->firstSec;
2331 OutputSection *last = p->lastSec;
2334 p->p_filesz = last->offset - first->offset;
2335 if (last->type != SHT_NOBITS)
2336 p->p_filesz += last->size;
2338 p->p_memsz = last->addr + last->size - first->addr;
2339 p->p_offset = first->offset;
2340 p->p_vaddr = first->addr;
2342 // File offsets in partitions other than the main partition are relative
2343 // to the offset of the ELF headers. Perform that adjustment now.
2345 p->p_offset -= part.elfHeader->getParent()->offset;
2348 p->p_paddr = first->getLMA();
2351 if (p->p_type == PT_LOAD) {
2352 p->p_align = std::max<uint64_t>(p->p_align, config->maxPageSize);
2353 } else if (p->p_type == PT_GNU_RELRO) {
2355 // The glibc dynamic loader rounds the size down, so we need to round up
2356 // to protect the last page. This is a no-op on FreeBSD which always
2358 p->p_memsz = alignTo(p->p_memsz, config->commonPageSize);
2363 // A helper struct for checkSectionOverlap.
2365 struct SectionOffset {
2371 // Check whether sections overlap for a specific address range (file offsets,
2372 // load and virtual adresses).
2373 static void checkOverlap(StringRef name, std::vector<SectionOffset> §ions,
2374 bool isVirtualAddr) {
2375 llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2376 return a.offset < b.offset;
2379 // Finding overlap is easy given a vector is sorted by start position.
2380 // If an element starts before the end of the previous element, they overlap.
2381 for (size_t i = 1, end = sections.size(); i < end; ++i) {
2382 SectionOffset a = sections[i - 1];
2383 SectionOffset b = sections[i];
2384 if (b.offset >= a.offset + a.sec->size)
2387 // If both sections are in OVERLAY we allow the overlapping of virtual
2388 // addresses, because it is what OVERLAY was designed for.
2389 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2392 errorOrWarn("section " + a.sec->name + " " + name +
2393 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2394 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2395 b.sec->name + " range is " +
2396 rangeToString(b.offset, b.sec->size));
2400 // Check for overlapping sections and address overflows.
2402 // In this function we check that none of the output sections have overlapping
2403 // file offsets. For SHF_ALLOC sections we also check that the load address
2404 // ranges and the virtual address ranges don't overlap
2405 template <class ELFT> void Writer<ELFT>::checkSections() {
2406 // First, check that section's VAs fit in available address space for target.
2407 for (OutputSection *os : outputSections)
2408 if ((os->addr + os->size < os->addr) ||
2409 (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2410 errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2411 " of size 0x" + utohexstr(os->size) +
2412 " exceeds available address space");
2414 // Check for overlapping file offsets. In this case we need to skip any
2415 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2416 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2417 // binary is specified only add SHF_ALLOC sections are added to the output
2418 // file so we skip any non-allocated sections in that case.
2419 std::vector<SectionOffset> fileOffs;
2420 for (OutputSection *sec : outputSections)
2421 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2422 (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2423 fileOffs.push_back({sec, sec->offset});
2424 checkOverlap("file", fileOffs, false);
2426 // When linking with -r there is no need to check for overlapping virtual/load
2427 // addresses since those addresses will only be assigned when the final
2428 // executable/shared object is created.
2429 if (config->relocatable)
2432 // Checking for overlapping virtual and load addresses only needs to take
2433 // into account SHF_ALLOC sections since others will not be loaded.
2434 // Furthermore, we also need to skip SHF_TLS sections since these will be
2435 // mapped to other addresses at runtime and can therefore have overlapping
2436 // ranges in the file.
2437 std::vector<SectionOffset> vmas;
2438 for (OutputSection *sec : outputSections)
2439 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2440 vmas.push_back({sec, sec->addr});
2441 checkOverlap("virtual address", vmas, true);
2443 // Finally, check that the load addresses don't overlap. This will usually be
2444 // the same as the virtual addresses but can be different when using a linker
2445 // script with AT().
2446 std::vector<SectionOffset> lmas;
2447 for (OutputSection *sec : outputSections)
2448 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2449 lmas.push_back({sec, sec->getLMA()});
2450 checkOverlap("load address", lmas, false);
2453 // The entry point address is chosen in the following ways.
2455 // 1. the '-e' entry command-line option;
2456 // 2. the ENTRY(symbol) command in a linker control script;
2457 // 3. the value of the symbol _start, if present;
2458 // 4. the number represented by the entry symbol, if it is a number;
2459 // 5. the address of the first byte of the .text section, if present;
2460 // 6. the address 0.
2461 static uint64_t getEntryAddr() {
2463 if (Symbol *b = symtab->find(config->entry))
2468 if (to_integer(config->entry, addr))
2472 if (OutputSection *sec = findSection(".text")) {
2473 if (config->warnMissingEntry)
2474 warn("cannot find entry symbol " + config->entry + "; defaulting to 0x" +
2475 utohexstr(sec->addr));
2480 if (config->warnMissingEntry)
2481 warn("cannot find entry symbol " + config->entry +
2482 "; not setting start address");
2486 static uint16_t getELFType() {
2489 if (config->relocatable)
2494 template <class ELFT> void Writer<ELFT>::writeHeader() {
2495 writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2496 writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2498 auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2499 eHdr->e_type = getELFType();
2500 eHdr->e_entry = getEntryAddr();
2501 eHdr->e_shoff = sectionHeaderOff;
2503 // Write the section header table.
2505 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2506 // and e_shstrndx fields. When the value of one of these fields exceeds
2507 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2508 // use fields in the section header at index 0 to store
2509 // the value. The sentinel values and fields are:
2510 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2511 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2512 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2513 size_t num = outputSections.size() + 1;
2514 if (num >= SHN_LORESERVE)
2515 sHdrs->sh_size = num;
2517 eHdr->e_shnum = num;
2519 uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2520 if (strTabIndex >= SHN_LORESERVE) {
2521 sHdrs->sh_link = strTabIndex;
2522 eHdr->e_shstrndx = SHN_XINDEX;
2524 eHdr->e_shstrndx = strTabIndex;
2527 for (OutputSection *sec : outputSections)
2528 sec->writeHeaderTo<ELFT>(++sHdrs);
2531 // Open a result file.
2532 template <class ELFT> void Writer<ELFT>::openFile() {
2533 uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2534 if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2535 error("output file too large: " + Twine(fileSize) + " bytes");
2539 unlinkAsync(config->outputFile);
2541 if (!config->relocatable)
2542 flags = FileOutputBuffer::F_executable;
2543 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2544 FileOutputBuffer::create(config->outputFile, fileSize, flags);
2547 error("failed to open " + config->outputFile + ": " +
2548 llvm::toString(bufferOrErr.takeError()));
2551 buffer = std::move(*bufferOrErr);
2552 Out::bufferStart = buffer->getBufferStart();
2555 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2556 for (OutputSection *sec : outputSections)
2557 if (sec->flags & SHF_ALLOC)
2558 sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2561 static void fillTrap(uint8_t *i, uint8_t *end) {
2562 for (; i + 4 <= end; i += 4)
2563 memcpy(i, &target->trapInstr, 4);
2566 // Fill the last page of executable segments with trap instructions
2567 // instead of leaving them as zero. Even though it is not required by any
2568 // standard, it is in general a good thing to do for security reasons.
2570 // We'll leave other pages in segments as-is because the rest will be
2571 // overwritten by output sections.
2572 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2573 if (script->hasSectionsCommand)
2576 for (Partition &part : partitions) {
2577 // Fill the last page.
2578 for (PhdrEntry *p : part.phdrs)
2579 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2580 fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz,
2581 config->commonPageSize),
2582 Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2583 config->commonPageSize));
2585 // Round up the file size of the last segment to the page boundary iff it is
2586 // an executable segment to ensure that other tools don't accidentally
2587 // trim the instruction padding (e.g. when stripping the file).
2588 PhdrEntry *last = nullptr;
2589 for (PhdrEntry *p : part.phdrs)
2590 if (p->p_type == PT_LOAD)
2593 if (last && (last->p_flags & PF_X))
2594 last->p_memsz = last->p_filesz =
2595 alignTo(last->p_filesz, config->commonPageSize);
2599 // Write section contents to a mmap'ed file.
2600 template <class ELFT> void Writer<ELFT>::writeSections() {
2601 // In -r or -emit-relocs mode, write the relocation sections first as in
2602 // ELf_Rel targets we might find out that we need to modify the relocated
2603 // section while doing it.
2604 for (OutputSection *sec : outputSections)
2605 if (sec->type == SHT_REL || sec->type == SHT_RELA)
2606 sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2608 for (OutputSection *sec : outputSections)
2609 if (sec->type != SHT_REL && sec->type != SHT_RELA)
2610 sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2613 // Split one uint8 array into small pieces of uint8 arrays.
2614 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> arr,
2616 std::vector<ArrayRef<uint8_t>> ret;
2617 while (arr.size() > chunkSize) {
2618 ret.push_back(arr.take_front(chunkSize));
2619 arr = arr.drop_front(chunkSize);
2626 // Computes a hash value of Data using a given hash function.
2627 // In order to utilize multiple cores, we first split data into 1MB
2628 // chunks, compute a hash for each chunk, and then compute a hash value
2629 // of the hash values.
2631 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2632 llvm::ArrayRef<uint8_t> data,
2633 std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2634 std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2635 std::vector<uint8_t> hashes(chunks.size() * hashBuf.size());
2637 // Compute hash values.
2638 parallelForEachN(0, chunks.size(), [&](size_t i) {
2639 hashFn(hashes.data() + i * hashBuf.size(), chunks[i]);
2642 // Write to the final output buffer.
2643 hashFn(hashBuf.data(), hashes);
2646 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2647 if (!mainPart->buildId || !mainPart->buildId->getParent())
2650 if (config->buildId == BuildIdKind::Hexstring) {
2651 for (Partition &part : partitions)
2652 part.buildId->writeBuildId(config->buildIdVector);
2656 // Compute a hash of all sections of the output file.
2657 size_t hashSize = mainPart->buildId->hashSize;
2658 std::vector<uint8_t> buildId(hashSize);
2659 llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)};
2661 switch (config->buildId) {
2662 case BuildIdKind::Fast:
2663 computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2664 write64le(dest, xxHash64(arr));
2667 case BuildIdKind::Md5:
2668 computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2669 memcpy(dest, MD5::hash(arr).data(), hashSize);
2672 case BuildIdKind::Sha1:
2673 computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2674 memcpy(dest, SHA1::hash(arr).data(), hashSize);
2677 case BuildIdKind::Uuid:
2678 if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize))
2679 error("entropy source failure: " + ec.message());
2682 llvm_unreachable("unknown BuildIdKind");
2684 for (Partition &part : partitions)
2685 part.buildId->writeBuildId(buildId);
2688 template void elf::writeResult<ELF32LE>();
2689 template void elf::writeResult<ELF32BE>();
2690 template void elf::writeResult<ELF64LE>();
2691 template void elf::writeResult<ELF64BE>();