1 //===- Writer.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "AArch64ErrataFix.h"
12 #include "CallGraphSort.h"
14 #include "Filesystem.h"
15 #include "LinkerScript.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
21 #include "SyntheticSections.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Strings.h"
25 #include "lld/Common/Threads.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringSwitch.h"
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
37 using namespace lld::elf;
40 // The writer writes a SymbolTable result to a file.
41 template <class ELFT> class Writer {
43 Writer() : Buffer(errorHandler().OutputBuffer) {}
44 typedef typename ELFT::Shdr Elf_Shdr;
45 typedef typename ELFT::Ehdr Elf_Ehdr;
46 typedef typename ELFT::Phdr Elf_Phdr;
51 void copyLocalSymbols();
52 void addSectionSymbols();
53 void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> Fn);
55 void resolveShfLinkOrder();
56 void sortInputSections();
57 void finalizeSections();
58 void setReservedSymbolSections();
60 std::vector<PhdrEntry *> createPhdrs();
61 void removeEmptyPTLoad();
62 void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
63 void assignFileOffsets();
64 void assignFileOffsetsBinary();
67 void fixSectionAlignments();
69 void writeTrapInstr();
72 void writeSectionsBinary();
75 std::unique_ptr<FileOutputBuffer> &Buffer;
77 void addRelIpltSymbols();
78 void addStartEndSymbols();
79 void addStartStopSymbols(OutputSection *Sec);
80 uint64_t getEntryAddr();
82 std::vector<PhdrEntry *> Phdrs;
85 uint64_t SectionHeaderOff;
87 } // anonymous namespace
89 static bool isSectionPrefix(StringRef Prefix, StringRef Name) {
90 return Name.startswith(Prefix) || Name == Prefix.drop_back();
93 StringRef elf::getOutputSectionName(const InputSectionBase *S) {
94 if (Config->Relocatable)
97 // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
98 // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
99 // technically required, but not doing it is odd). This code guarantees that.
100 if (auto *IS = dyn_cast<InputSection>(S)) {
101 if (InputSectionBase *Rel = IS->getRelocatedSection()) {
102 OutputSection *Out = Rel->getOutputSection();
103 if (S->Type == SHT_RELA)
104 return Saver.save(".rela" + Out->Name);
105 return Saver.save(".rel" + Out->Name);
109 // This check is for -z keep-text-section-prefix. This option separates text
110 // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
112 // When enabled, this allows identifying the hot code region (.text.hot) in
113 // the final binary which can be selectively mapped to huge pages or mlocked,
115 if (Config->ZKeepTextSectionPrefix)
117 {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."}) {
118 if (isSectionPrefix(V, S->Name))
119 return V.drop_back();
123 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
124 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
125 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
126 if (isSectionPrefix(V, S->Name))
127 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> void Writer<ELFT>::removeEmptyPTLoad() {
146 llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
147 if (P->p_type != PT_LOAD)
151 uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
156 template <class ELFT> static void combineEhFrameSections() {
157 for (InputSectionBase *&S : InputSections) {
158 EhInputSection *ES = dyn_cast<EhInputSection>(S);
159 if (!ES || !ES->Live)
162 InX::EhFrame->addSection<ELFT>(ES);
166 std::vector<InputSectionBase *> &V = InputSections;
167 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
170 static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec,
171 uint64_t Val, uint8_t StOther = STV_HIDDEN,
172 uint8_t Binding = STB_GLOBAL) {
173 Symbol *S = Symtab->find(Name);
174 if (!S || S->isDefined())
176 Symbol *Sym = Symtab->addRegular(Name, StOther, STT_NOTYPE, Val,
177 /*Size=*/0, Binding, Sec,
179 return cast<Defined>(Sym);
182 // The linker is expected to define some symbols depending on
183 // the linking result. This function defines such symbols.
184 void elf::addReservedSymbols() {
185 if (Config->EMachine == EM_MIPS) {
186 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
187 // so that it points to an absolute address which by default is relative
188 // to GOT. Default offset is 0x7ff0.
189 // See "Global Data Symbols" in Chapter 6 in the following document:
190 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
191 ElfSym::MipsGp = Symtab->addAbsolute("_gp", STV_HIDDEN, STB_GLOBAL);
193 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
194 // start of function and 'gp' pointer into GOT.
195 if (Symtab->find("_gp_disp"))
197 Symtab->addAbsolute("_gp_disp", STV_HIDDEN, STB_GLOBAL);
199 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
200 // pointer. This symbol is used in the code generated by .cpload pseudo-op
201 // in case of using -mno-shared option.
202 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
203 if (Symtab->find("__gnu_local_gp"))
204 ElfSym::MipsLocalGp =
205 Symtab->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_GLOBAL);
208 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
209 // combines the typical ELF GOT with the small data sections. It commonly
210 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
211 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
212 // represent the TOC base which is offset by 0x8000 bytes from the start of
214 ElfSym::GlobalOffsetTable = addOptionalRegular(
215 (Config->EMachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_",
216 Out::ElfHeader, Target->GotBaseSymOff);
218 // __ehdr_start is the location of ELF file headers. Note that we define
219 // this symbol unconditionally even when using a linker script, which
220 // differs from the behavior implemented by GNU linker which only define
221 // this symbol if ELF headers are in the memory mapped segment.
222 addOptionalRegular("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
224 // __executable_start is not documented, but the expectation of at
225 // least the Android libc is that it points to the ELF header.
226 addOptionalRegular("__executable_start", Out::ElfHeader, 0, STV_HIDDEN);
228 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
229 // each DSO. The address of the symbol doesn't matter as long as they are
230 // different in different DSOs, so we chose the start address of the DSO.
231 addOptionalRegular("__dso_handle", Out::ElfHeader, 0, STV_HIDDEN);
233 // If linker script do layout we do not need to create any standart symbols.
234 if (Script->HasSectionsCommand)
237 auto Add = [](StringRef S, int64_t Pos) {
238 return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT);
241 ElfSym::Bss = Add("__bss_start", 0);
242 ElfSym::End1 = Add("end", -1);
243 ElfSym::End2 = Add("_end", -1);
244 ElfSym::Etext1 = Add("etext", -1);
245 ElfSym::Etext2 = Add("_etext", -1);
246 ElfSym::Edata1 = Add("edata", -1);
247 ElfSym::Edata2 = Add("_edata", -1);
250 static OutputSection *findSection(StringRef Name) {
251 for (BaseCommand *Base : Script->SectionCommands)
252 if (auto *Sec = dyn_cast<OutputSection>(Base))
253 if (Sec->Name == Name)
258 // Initialize Out members.
259 template <class ELFT> static void createSyntheticSections() {
260 // Initialize all pointers with NULL. This is needed because
261 // you can call lld::elf::main more than once as a library.
262 memset(&Out::First, 0, sizeof(Out));
264 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
266 InX::DynStrTab = make<StringTableSection>(".dynstr", true);
267 InX::Dynamic = make<DynamicSection<ELFT>>();
268 if (Config->AndroidPackDynRelocs) {
269 InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
270 Config->IsRela ? ".rela.dyn" : ".rel.dyn");
272 InX::RelaDyn = make<RelocationSection<ELFT>>(
273 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
275 InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
277 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
278 Out::ProgramHeaders->Alignment = Config->Wordsize;
280 if (needsInterpSection()) {
281 InX::Interp = createInterpSection();
284 InX::Interp = nullptr;
287 if (Config->Strip != StripPolicy::All) {
288 InX::StrTab = make<StringTableSection>(".strtab", false);
289 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
292 if (Config->BuildId != BuildIdKind::None) {
293 InX::BuildId = make<BuildIdSection>();
297 InX::Bss = make<BssSection>(".bss", 0, 1);
300 // If there is a SECTIONS command and a .data.rel.ro section name use name
301 // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
302 // This makes sure our relro is contiguous.
303 bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro");
305 make<BssSection>(HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
308 // Add MIPS-specific sections.
309 if (Config->EMachine == EM_MIPS) {
310 if (!Config->Shared && Config->HasDynSymTab) {
311 InX::MipsRldMap = make<MipsRldMapSection>();
312 Add(InX::MipsRldMap);
314 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
316 if (auto *Sec = MipsOptionsSection<ELFT>::create())
318 if (auto *Sec = MipsReginfoSection<ELFT>::create())
322 if (Config->HasDynSymTab) {
323 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
326 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
327 Add(In<ELFT>::VerSym);
329 if (!Config->VersionDefinitions.empty()) {
330 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
331 Add(In<ELFT>::VerDef);
334 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
335 Add(In<ELFT>::VerNeed);
337 if (Config->GnuHash) {
338 InX::GnuHashTab = make<GnuHashTableSection>();
339 Add(InX::GnuHashTab);
342 if (Config->SysvHash) {
343 InX::HashTab = make<HashTableSection>();
352 if (Config->RelrPackDynRelocs) {
353 InX::RelrDyn = make<RelrSection<ELFT>>();
357 // Add .got. MIPS' .got is so different from the other archs,
358 // it has its own class.
359 if (Config->EMachine == EM_MIPS) {
360 InX::MipsGot = make<MipsGotSection>();
363 InX::Got = make<GotSection>();
367 InX::GotPlt = make<GotPltSection>();
369 InX::IgotPlt = make<IgotPltSection>();
372 if (Config->GdbIndex) {
373 InX::GdbIndex = GdbIndexSection::create<ELFT>();
377 // We always need to add rel[a].plt to output if it has entries.
378 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
379 InX::RelaPlt = make<RelocationSection<ELFT>>(
380 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
383 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
384 // that the IRelative relocations are processed last by the dynamic loader.
385 // We cannot place the iplt section in .rel.dyn when Android relocation
386 // packing is enabled because that would cause a section type mismatch.
387 // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
388 // we can get the desired behaviour by placing the iplt section in .rel.plt.
389 InX::RelaIplt = make<RelocationSection<ELFT>>(
390 (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs)
392 : InX::RelaPlt->Name,
396 InX::Plt = make<PltSection>(false);
398 InX::Iplt = make<PltSection>(true);
401 if (!Config->Relocatable) {
402 if (Config->EhFrameHdr) {
403 InX::EhFrameHdr = make<EhFrameHeader>();
404 Add(InX::EhFrameHdr);
406 InX::EhFrame = make<EhFrameSection>();
416 if (Config->EMachine == EM_ARM && !Config->Relocatable)
417 // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
418 // to find the exact address range of the last entry.
419 Add(make<ARMExidxSentinelSection>());
422 // The main function of the writer.
423 template <class ELFT> void Writer<ELFT>::run() {
424 // Create linker-synthesized sections such as .got or .plt.
425 // Such sections are of type input section.
426 createSyntheticSections<ELFT>();
428 if (!Config->Relocatable)
429 combineEhFrameSections<ELFT>();
431 // We want to process linker script commands. When SECTIONS command
432 // is given we let it create sections.
433 Script->processSectionCommands();
435 // Linker scripts controls how input sections are assigned to output sections.
436 // Input sections that were not handled by scripts are called "orphans", and
437 // they are assigned to output sections by the default rule. Process that.
438 Script->addOrphanSections();
440 if (Config->Discard != DiscardPolicy::All)
443 if (Config->CopyRelocs)
446 // Now that we have a complete set of output sections. This function
447 // completes section contents. For example, we need to add strings
448 // to the string table, and add entries to .got and .plt.
449 // finalizeSections does that.
454 Script->assignAddresses();
456 // If -compressed-debug-sections is specified, we need to compress
457 // .debug_* sections. Do it right now because it changes the size of
459 for (OutputSection *Sec : OutputSections)
460 Sec->maybeCompress<ELFT>();
462 Script->allocateHeaders(Phdrs);
464 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
465 // 0 sized region. This has to be done late since only after assignAddresses
466 // we know the size of the sections.
469 if (!Config->OFormatBinary)
472 assignFileOffsetsBinary();
476 if (Config->Relocatable) {
477 for (OutputSection *Sec : OutputSections)
481 if (Config->CheckSections)
484 // It does not make sense try to open the file if we have error already.
487 // Write the result down to a file.
492 if (!Config->OFormatBinary) {
497 writeSectionsBinary();
500 // Backfill .note.gnu.build-id section content. This is done at last
501 // because the content is usually a hash value of the entire output file.
506 // Handle -Map and -cref options.
508 writeCrossReferenceTable();
512 if (auto E = Buffer->commit())
513 error("failed to write to the output file: " + toString(std::move(E)));
516 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
522 if (Config->Discard == DiscardPolicy::None)
525 // In ELF assembly .L symbols are normally discarded by the assembler.
526 // If the assembler fails to do so, the linker discards them if
527 // * --discard-locals is used.
528 // * The symbol is in a SHF_MERGE section, which is normally the reason for
529 // the assembler keeping the .L symbol.
530 if (!SymName.startswith(".L") && !SymName.empty())
533 if (Config->Discard == DiscardPolicy::Locals)
536 return !Sec || !(Sec->Flags & SHF_MERGE);
539 static bool includeInSymtab(const Symbol &B) {
540 if (!B.isLocal() && !B.IsUsedInRegularObj)
543 if (auto *D = dyn_cast<Defined>(&B)) {
544 // Always include absolute symbols.
545 SectionBase *Sec = D->Section;
549 // Exclude symbols pointing to garbage-collected sections.
550 if (isa<InputSectionBase>(Sec) && !Sec->Live)
552 if (auto *S = dyn_cast<MergeInputSection>(Sec))
553 if (!S->getSectionPiece(D->Value)->Live)
560 // Local symbols are not in the linker's symbol table. This function scans
561 // each object file's symbol table to copy local symbols to the output.
562 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
565 for (InputFile *File : ObjectFiles) {
566 ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
567 for (Symbol *B : F->getLocalSymbols()) {
570 ": broken object: getLocalSymbols returns a non-local symbol");
571 auto *DR = dyn_cast<Defined>(B);
573 // No reason to keep local undefined symbol in symtab.
576 if (!includeInSymtab(*B))
579 SectionBase *Sec = DR->Section;
580 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
582 InX::SymTab->addSymbol(B);
587 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
588 // Create a section symbol for each output section so that we can represent
589 // relocations that point to the section. If we know that no relocation is
590 // referring to a section (that happens if the section is a synthetic one), we
591 // don't create a section symbol for that section.
592 for (BaseCommand *Base : Script->SectionCommands) {
593 auto *Sec = dyn_cast<OutputSection>(Base);
596 auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
597 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
598 return !ISD->Sections.empty();
601 if (I == Sec->SectionCommands.end())
603 InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
605 // Relocations are not using REL[A] section symbols.
606 if (IS->Type == SHT_REL || IS->Type == SHT_RELA)
609 // Unlike other synthetic sections, mergeable output sections contain data
610 // copied from input sections, and there may be a relocation pointing to its
611 // contents if -r or -emit-reloc are given.
612 if (isa<SyntheticSection>(IS) && !(IS->Flags & SHF_MERGE))
616 make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
617 /*Value=*/0, /*Size=*/0, IS);
618 InX::SymTab->addSymbol(Sym);
622 // Today's loaders have a feature to make segments read-only after
623 // processing dynamic relocations to enhance security. PT_GNU_RELRO
624 // is defined for that.
626 // This function returns true if a section needs to be put into a
627 // PT_GNU_RELRO segment.
628 static bool isRelroSection(const OutputSection *Sec) {
632 uint64_t Flags = Sec->Flags;
634 // Non-allocatable or non-writable sections don't need RELRO because
635 // they are not writable or not even mapped to memory in the first place.
636 // RELRO is for sections that are essentially read-only but need to
637 // be writable only at process startup to allow dynamic linker to
638 // apply relocations.
639 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
642 // Once initialized, TLS data segments are used as data templates
643 // for a thread-local storage. For each new thread, runtime
644 // allocates memory for a TLS and copy templates there. No thread
645 // are supposed to use templates directly. Thus, it can be in RELRO.
649 // .init_array, .preinit_array and .fini_array contain pointers to
650 // functions that are executed on process startup or exit. These
651 // pointers are set by the static linker, and they are not expected
652 // to change at runtime. But if you are an attacker, you could do
653 // interesting things by manipulating pointers in .fini_array, for
654 // example. So they are put into RELRO.
655 uint32_t Type = Sec->Type;
656 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
657 Type == SHT_PREINIT_ARRAY)
660 // .got contains pointers to external symbols. They are resolved by
661 // the dynamic linker when a module is loaded into memory, and after
662 // that they are not expected to change. So, it can be in RELRO.
663 if (InX::Got && Sec == InX::Got->getParent())
666 if (Sec->Name.equals(".toc"))
669 // .got.plt contains pointers to external function symbols. They are
670 // by default resolved lazily, so we usually cannot put it into RELRO.
671 // However, if "-z now" is given, the lazy symbol resolution is
672 // disabled, which enables us to put it into RELRO.
673 if (Sec == InX::GotPlt->getParent())
676 // .dynamic section contains data for the dynamic linker, and
677 // there's no need to write to it at runtime, so it's better to put
679 if (Sec == InX::Dynamic->getParent())
682 // Sections with some special names are put into RELRO. This is a
683 // bit unfortunate because section names shouldn't be significant in
684 // ELF in spirit. But in reality many linker features depend on
685 // magic section names.
686 StringRef S = Sec->Name;
687 return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" ||
688 S == ".dtors" || S == ".jcr" || S == ".eh_frame" ||
689 S == ".openbsd.randomdata";
692 // We compute a rank for each section. The rank indicates where the
693 // section should be placed in the file. Instead of using simple
694 // numbers (0,1,2...), we use a series of flags. One for each decision
695 // point when placing the section.
696 // Using flags has two key properties:
697 // * It is easy to check if a give branch was taken.
698 // * It is easy two see how similar two ranks are (see getRankProximity).
700 RF_NOT_ADDR_SET = 1 << 18,
701 RF_NOT_INTERP = 1 << 17,
702 RF_NOT_ALLOC = 1 << 16,
704 RF_EXEC_WRITE = 1 << 14,
707 RF_NON_TLS_BSS = 1 << 11,
708 RF_NON_TLS_BSS_RO = 1 << 10,
712 RF_PPC_NOT_TOCBSS = 1 << 6,
713 RF_PPC_TOCL = 1 << 5,
716 RF_PPC_BRANCH_LT = 1 << 2,
717 RF_MIPS_GPREL = 1 << 1,
718 RF_MIPS_NOT_GOT = 1 << 0
721 static unsigned getSectionRank(const OutputSection *Sec) {
724 // We want to put section specified by -T option first, so we
725 // can start assigning VA starting from them later.
726 if (Config->SectionStartMap.count(Sec->Name))
728 Rank |= RF_NOT_ADDR_SET;
730 // Put .interp first because some loaders want to see that section
731 // on the first page of the executable file when loaded into memory.
732 if (Sec->Name == ".interp")
734 Rank |= RF_NOT_INTERP;
736 // Allocatable sections go first to reduce the total PT_LOAD size and
737 // so debug info doesn't change addresses in actual code.
738 if (!(Sec->Flags & SHF_ALLOC))
739 return Rank | RF_NOT_ALLOC;
741 // Sort sections based on their access permission in the following
742 // order: R, RX, RWX, RW. This order is based on the following
744 // * Read-only sections come first such that they go in the
745 // PT_LOAD covering the program headers at the start of the file.
746 // * Read-only, executable sections come next.
747 // * Writable, executable sections follow such that .plt on
748 // architectures where it needs to be writable will be placed
749 // between .text and .data.
750 // * Writable sections come last, such that .bss lands at the very
751 // end of the last PT_LOAD.
752 bool IsExec = Sec->Flags & SHF_EXECINSTR;
753 bool IsWrite = Sec->Flags & SHF_WRITE;
757 Rank |= RF_EXEC_WRITE;
760 } else if (IsWrite) {
762 } else if (Sec->Type == SHT_PROGBITS) {
763 // Make non-executable and non-writable PROGBITS sections (e.g .rodata
764 // .eh_frame) closer to .text. They likely contain PC or GOT relative
765 // relocations and there could be relocation overflow if other huge sections
766 // (.dynstr .dynsym) were placed in between.
770 // If we got here we know that both A and B are in the same PT_LOAD.
772 bool IsTls = Sec->Flags & SHF_TLS;
773 bool IsNoBits = Sec->Type == SHT_NOBITS;
775 // The first requirement we have is to put (non-TLS) nobits sections last. The
776 // reason is that the only thing the dynamic linker will see about them is a
777 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
778 // PT_LOAD, so that has to correspond to the nobits sections.
779 bool IsNonTlsNoBits = IsNoBits && !IsTls;
781 Rank |= RF_NON_TLS_BSS;
783 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
784 // sections after r/w ones, so that the RelRo sections are contiguous.
785 bool IsRelRo = isRelroSection(Sec);
786 if (IsNonTlsNoBits && !IsRelRo)
787 Rank |= RF_NON_TLS_BSS_RO;
788 if (!IsNonTlsNoBits && IsRelRo)
789 Rank |= RF_NON_TLS_BSS_RO;
791 // The TLS initialization block needs to be a single contiguous block in a R/W
792 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
793 // sections. The TLS NOBITS sections are placed here as they don't take up
794 // virtual address space in the PT_LOAD.
798 // Within the TLS initialization block, the non-nobits sections need to appear
803 // We create a NOTE segment for contiguous .note sections, so make
804 // them contigous if there are more than one .note section with the
806 if (Sec->Type == SHT_NOTE)
809 // Some architectures have additional ordering restrictions for sections
810 // within the same PT_LOAD.
811 if (Config->EMachine == EM_PPC64) {
812 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
813 // that we would like to make sure appear is a specific order to maximize
814 // their coverage by a single signed 16-bit offset from the TOC base
815 // pointer. Conversely, the special .tocbss section should be first among
816 // all SHT_NOBITS sections. This will put it next to the loaded special
817 // PPC64 sections (and, thus, within reach of the TOC base pointer).
818 StringRef Name = Sec->Name;
819 if (Name != ".tocbss")
820 Rank |= RF_PPC_NOT_TOCBSS;
831 if (Name == ".branch_lt")
832 Rank |= RF_PPC_BRANCH_LT;
835 if (Config->EMachine == EM_MIPS) {
836 // All sections with SHF_MIPS_GPREL flag should be grouped together
837 // because data in these sections is addressable with a gp relative address.
838 if (Sec->Flags & SHF_MIPS_GPREL)
839 Rank |= RF_MIPS_GPREL;
841 if (Sec->Name != ".got")
842 Rank |= RF_MIPS_NOT_GOT;
848 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
849 const OutputSection *A = cast<OutputSection>(ACmd);
850 const OutputSection *B = cast<OutputSection>(BCmd);
851 if (A->SortRank != B->SortRank)
852 return A->SortRank < B->SortRank;
853 if (!(A->SortRank & RF_NOT_ADDR_SET))
854 return Config->SectionStartMap.lookup(A->Name) <
855 Config->SectionStartMap.lookup(B->Name);
859 void PhdrEntry::add(OutputSection *Sec) {
863 p_align = std::max(p_align, Sec->Alignment);
864 if (p_type == PT_LOAD)
868 // The beginning and the ending of .rel[a].plt section are marked
869 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
870 // executable. The runtime needs these symbols in order to resolve
871 // all IRELATIVE relocs on startup. For dynamic executables, we don't
872 // need these symbols, since IRELATIVE relocs are resolved through GOT
873 // and PLT. For details, see http://www.airs.com/blog/archives/403.
874 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
875 if (needsInterpSection())
877 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
878 addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
880 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
881 ElfSym::RelaIpltEnd =
882 addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
885 template <class ELFT>
886 void Writer<ELFT>::forEachRelSec(
887 llvm::function_ref<void(InputSectionBase &)> Fn) {
888 // Scan all relocations. Each relocation goes through a series
889 // of tests to determine if it needs special treatment, such as
890 // creating GOT, PLT, copy relocations, etc.
891 // Note that relocations for non-alloc sections are directly
892 // processed by InputSection::relocateNonAlloc.
893 for (InputSectionBase *IS : InputSections)
894 if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
896 for (EhInputSection *ES : InX::EhFrame->Sections)
900 // This function generates assignments for predefined symbols (e.g. _end or
901 // _etext) and inserts them into the commands sequence to be processed at the
902 // appropriate time. This ensures that the value is going to be correct by the
903 // time any references to these symbols are processed and is equivalent to
904 // defining these symbols explicitly in the linker script.
905 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
906 if (ElfSym::GlobalOffsetTable) {
907 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
908 // to the start of the .got or .got.plt section.
909 InputSection *GotSection = InX::GotPlt;
910 if (!Target->GotBaseSymInGotPlt)
911 GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
912 : cast<InputSection>(InX::Got);
913 ElfSym::GlobalOffsetTable->Section = GotSection;
916 if (ElfSym::RelaIpltEnd)
917 ElfSym::RelaIpltEnd->Value = InX::RelaIplt->getSize();
919 PhdrEntry *Last = nullptr;
920 PhdrEntry *LastRO = nullptr;
922 for (PhdrEntry *P : Phdrs) {
923 if (P->p_type != PT_LOAD)
926 if (!(P->p_flags & PF_W))
931 // _etext is the first location after the last read-only loadable segment.
933 ElfSym::Etext1->Section = LastRO->LastSec;
935 ElfSym::Etext2->Section = LastRO->LastSec;
939 // _edata points to the end of the last mapped initialized section.
940 OutputSection *Edata = nullptr;
941 for (OutputSection *OS : OutputSections) {
942 if (OS->Type != SHT_NOBITS)
944 if (OS == Last->LastSec)
949 ElfSym::Edata1->Section = Edata;
951 ElfSym::Edata2->Section = Edata;
953 // _end is the first location after the uninitialized data region.
955 ElfSym::End1->Section = Last->LastSec;
957 ElfSym::End2->Section = Last->LastSec;
961 ElfSym::Bss->Section = findSection(".bss");
963 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
964 // be equal to the _gp symbol's value.
965 if (ElfSym::MipsGp) {
966 // Find GP-relative section with the lowest address
967 // and use this address to calculate default _gp value.
968 for (OutputSection *OS : OutputSections) {
969 if (OS->Flags & SHF_MIPS_GPREL) {
970 ElfSym::MipsGp->Section = OS;
971 ElfSym::MipsGp->Value = 0x7ff0;
978 // We want to find how similar two ranks are.
979 // The more branches in getSectionRank that match, the more similar they are.
980 // Since each branch corresponds to a bit flag, we can just use
981 // countLeadingZeros.
982 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
983 return countLeadingZeros(A->SortRank ^ B->SortRank);
986 static int getRankProximity(OutputSection *A, BaseCommand *B) {
987 if (auto *Sec = dyn_cast<OutputSection>(B))
988 return getRankProximityAux(A, Sec);
992 // When placing orphan sections, we want to place them after symbol assignments
993 // so that an orphan after
997 // doesn't break the intended meaning of the begin/end symbols.
998 // We don't want to go over sections since findOrphanPos is the
999 // one in charge of deciding the order of the sections.
1000 // We don't want to go over changes to '.', since doing so in
1001 // rx_sec : { *(rx_sec) }
1002 // . = ALIGN(0x1000);
1003 // /* The RW PT_LOAD starts here*/
1004 // rw_sec : { *(rw_sec) }
1005 // would mean that the RW PT_LOAD would become unaligned.
1006 static bool shouldSkip(BaseCommand *Cmd) {
1007 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
1008 return Assign->Name != ".";
1012 // We want to place orphan sections so that they share as much
1013 // characteristics with their neighbors as possible. For example, if
1014 // both are rw, or both are tls.
1015 template <typename ELFT>
1016 static std::vector<BaseCommand *>::iterator
1017 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1018 std::vector<BaseCommand *>::iterator E) {
1019 OutputSection *Sec = cast<OutputSection>(*E);
1021 // Find the first element that has as close a rank as possible.
1022 auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1023 return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1028 // Consider all existing sections with the same proximity.
1029 int Proximity = getRankProximity(Sec, *I);
1030 for (; I != E; ++I) {
1031 auto *CurSec = dyn_cast<OutputSection>(*I);
1034 if (getRankProximity(Sec, CurSec) != Proximity ||
1035 Sec->SortRank < CurSec->SortRank)
1039 auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); };
1040 auto J = std::find_if(llvm::make_reverse_iterator(I),
1041 llvm::make_reverse_iterator(B), IsOutputSec);
1044 // As a special case, if the orphan section is the last section, put
1045 // it at the very end, past any other commands.
1046 // This matches bfd's behavior and is convenient when the linker script fully
1047 // specifies the start of the file, but doesn't care about the end (the non
1048 // alloc sections for example).
1049 auto NextSec = std::find_if(I, E, IsOutputSec);
1053 while (I != E && shouldSkip(*I))
1058 // Builds section order for handling --symbol-ordering-file.
1059 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1060 DenseMap<const InputSectionBase *, int> SectionOrder;
1061 // Use the rarely used option -call-graph-ordering-file to sort sections.
1062 if (!Config->CallGraphProfile.empty())
1063 return computeCallGraphProfileOrder();
1065 if (Config->SymbolOrderingFile.empty())
1066 return SectionOrder;
1068 struct SymbolOrderEntry {
1073 // Build a map from symbols to their priorities. Symbols that didn't
1074 // appear in the symbol ordering file have the lowest priority 0.
1075 // All explicitly mentioned symbols have negative (higher) priorities.
1076 DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1077 int Priority = -Config->SymbolOrderingFile.size();
1078 for (StringRef S : Config->SymbolOrderingFile)
1079 SymbolOrder.insert({S, {Priority++, false}});
1081 // Build a map from sections to their priorities.
1082 auto AddSym = [&](Symbol &Sym) {
1083 auto It = SymbolOrder.find(Sym.getName());
1084 if (It == SymbolOrder.end())
1086 SymbolOrderEntry &Ent = It->second;
1089 warnUnorderableSymbol(&Sym);
1091 if (auto *D = dyn_cast<Defined>(&Sym)) {
1092 if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1093 int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1094 Priority = std::min(Priority, Ent.Priority);
1098 // We want both global and local symbols. We get the global ones from the
1099 // symbol table and iterate the object files for the local ones.
1100 for (Symbol *Sym : Symtab->getSymbols())
1103 for (InputFile *File : ObjectFiles)
1104 for (Symbol *Sym : File->getSymbols())
1108 if (Config->WarnSymbolOrdering)
1109 for (auto OrderEntry : SymbolOrder)
1110 if (!OrderEntry.second.Present)
1111 warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1113 return SectionOrder;
1116 // Sorts the sections in ISD according to the provided section order.
1118 sortISDBySectionOrder(InputSectionDescription *ISD,
1119 const DenseMap<const InputSectionBase *, int> &Order) {
1120 std::vector<InputSection *> UnorderedSections;
1121 std::vector<std::pair<InputSection *, int>> OrderedSections;
1122 uint64_t UnorderedSize = 0;
1124 for (InputSection *IS : ISD->Sections) {
1125 auto I = Order.find(IS);
1126 if (I == Order.end()) {
1127 UnorderedSections.push_back(IS);
1128 UnorderedSize += IS->getSize();
1131 OrderedSections.push_back({IS, I->second});
1134 OrderedSections.begin(), OrderedSections.end(),
1135 [&](std::pair<InputSection *, int> A, std::pair<InputSection *, int> B) {
1136 return A.second < B.second;
1139 // Find an insertion point for the ordered section list in the unordered
1140 // section list. On targets with limited-range branches, this is the mid-point
1141 // of the unordered section list. This decreases the likelihood that a range
1142 // extension thunk will be needed to enter or exit the ordered region. If the
1143 // ordered section list is a list of hot functions, we can generally expect
1144 // the ordered functions to be called more often than the unordered functions,
1145 // making it more likely that any particular call will be within range, and
1146 // therefore reducing the number of thunks required.
1148 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1149 // If the layout is:
1154 // only the first 8-16MB of the cold code (depending on which hot function it
1155 // is actually calling) can call the hot code without a range extension thunk.
1156 // However, if we use this layout:
1162 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1163 // of the second block of cold code can call the hot code without a thunk. So
1164 // we effectively double the amount of code that could potentially call into
1165 // the hot code without a thunk.
1167 if (Target->ThunkSectionSpacing && !OrderedSections.empty()) {
1168 uint64_t UnorderedPos = 0;
1169 for (; InsPt != UnorderedSections.size(); ++InsPt) {
1170 UnorderedPos += UnorderedSections[InsPt]->getSize();
1171 if (UnorderedPos > UnorderedSize / 2)
1176 ISD->Sections.clear();
1177 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1178 ISD->Sections.push_back(IS);
1179 for (std::pair<InputSection *, int> P : OrderedSections)
1180 ISD->Sections.push_back(P.first);
1181 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1182 ISD->Sections.push_back(IS);
1185 static void sortSection(OutputSection *Sec,
1186 const DenseMap<const InputSectionBase *, int> &Order) {
1187 StringRef Name = Sec->Name;
1189 // Sort input sections by section name suffixes for
1190 // __attribute__((init_priority(N))).
1191 if (Name == ".init_array" || Name == ".fini_array") {
1192 if (!Script->HasSectionsCommand)
1193 Sec->sortInitFini();
1197 // Sort input sections by the special rule for .ctors and .dtors.
1198 if (Name == ".ctors" || Name == ".dtors") {
1199 if (!Script->HasSectionsCommand)
1200 Sec->sortCtorsDtors();
1204 // Never sort these.
1205 if (Name == ".init" || Name == ".fini")
1208 // Sort input sections by priority using the list provided
1209 // by --symbol-ordering-file.
1211 for (BaseCommand *B : Sec->SectionCommands)
1212 if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1213 sortISDBySectionOrder(ISD, Order);
1216 // If no layout was provided by linker script, we want to apply default
1217 // sorting for special input sections. This also handles --symbol-ordering-file.
1218 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1219 // Build the order once since it is expensive.
1220 DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1221 for (BaseCommand *Base : Script->SectionCommands)
1222 if (auto *Sec = dyn_cast<OutputSection>(Base))
1223 sortSection(Sec, Order);
1226 template <class ELFT> void Writer<ELFT>::sortSections() {
1227 Script->adjustSectionsBeforeSorting();
1229 // Don't sort if using -r. It is not necessary and we want to preserve the
1230 // relative order for SHF_LINK_ORDER sections.
1231 if (Config->Relocatable)
1234 sortInputSections();
1236 for (BaseCommand *Base : Script->SectionCommands) {
1237 auto *OS = dyn_cast<OutputSection>(Base);
1240 OS->SortRank = getSectionRank(OS);
1242 // We want to assign rude approximation values to OutSecOff fields
1243 // to know the relative order of the input sections. We use it for
1244 // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1246 for (InputSection *Sec : getInputSections(OS))
1247 Sec->OutSecOff = I++;
1250 if (!Script->HasSectionsCommand) {
1251 // We know that all the OutputSections are contiguous in this case.
1252 auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1254 llvm::find_if(Script->SectionCommands, IsSection),
1255 llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1260 // Orphan sections are sections present in the input files which are
1261 // not explicitly placed into the output file by the linker script.
1263 // The sections in the linker script are already in the correct
1264 // order. We have to figuere out where to insert the orphan
1267 // The order of the sections in the script is arbitrary and may not agree with
1268 // compareSections. This means that we cannot easily define a strict weak
1269 // ordering. To see why, consider a comparison of a section in the script and
1270 // one not in the script. We have a two simple options:
1271 // * Make them equivalent (a is not less than b, and b is not less than a).
1272 // The problem is then that equivalence has to be transitive and we can
1273 // have sections a, b and c with only b in a script and a less than c
1274 // which breaks this property.
1275 // * Use compareSectionsNonScript. Given that the script order doesn't have
1276 // to match, we can end up with sections a, b, c, d where b and c are in the
1277 // script and c is compareSectionsNonScript less than b. In which case d
1278 // can be equivalent to c, a to b and d < a. As a concrete example:
1279 // .a (rx) # not in script
1280 // .b (rx) # in script
1281 // .c (ro) # in script
1282 // .d (ro) # not in script
1284 // The way we define an order then is:
1285 // * Sort only the orphan sections. They are in the end right now.
1286 // * Move each orphan section to its preferred position. We try
1287 // to put each section in the last position where it can share
1290 // There is some ambiguity as to where exactly a new entry should be
1291 // inserted, because Commands contains not only output section
1292 // commands but also other types of commands such as symbol assignment
1293 // expressions. There's no correct answer here due to the lack of the
1294 // formal specification of the linker script. We use heuristics to
1295 // determine whether a new output command should be added before or
1296 // after another commands. For the details, look at shouldSkip
1299 auto I = Script->SectionCommands.begin();
1300 auto E = Script->SectionCommands.end();
1301 auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1302 if (auto *Sec = dyn_cast<OutputSection>(Base))
1303 return Sec->SectionIndex == UINT32_MAX;
1307 // Sort the orphan sections.
1308 std::stable_sort(NonScriptI, E, compareSections);
1310 // As a horrible special case, skip the first . assignment if it is before any
1311 // section. We do this because it is common to set a load address by starting
1312 // the script with ". = 0xabcd" and the expectation is that every section is
1314 auto FirstSectionOrDotAssignment =
1315 std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1316 if (FirstSectionOrDotAssignment != E &&
1317 isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1318 ++FirstSectionOrDotAssignment;
1319 I = FirstSectionOrDotAssignment;
1321 while (NonScriptI != E) {
1322 auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1323 OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1325 // As an optimization, find all sections with the same sort rank
1326 // and insert them with one rotate.
1327 unsigned Rank = Orphan->SortRank;
1328 auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1329 return cast<OutputSection>(Cmd)->SortRank != Rank;
1331 std::rotate(Pos, NonScriptI, End);
1335 Script->adjustSectionsAfterSorting();
1338 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1339 // Synthetic, i. e. a sentinel section, should go last.
1340 if (A->kind() == InputSectionBase::Synthetic ||
1341 B->kind() == InputSectionBase::Synthetic)
1342 return A->kind() != InputSectionBase::Synthetic;
1343 InputSection *LA = A->getLinkOrderDep();
1344 InputSection *LB = B->getLinkOrderDep();
1345 OutputSection *AOut = LA->getParent();
1346 OutputSection *BOut = LB->getParent();
1348 return AOut->SectionIndex < BOut->SectionIndex;
1349 return LA->OutSecOff < LB->OutSecOff;
1352 // This function is used by the --merge-exidx-entries to detect duplicate
1353 // .ARM.exidx sections. It is Arm only.
1355 // The .ARM.exidx section is of the form:
1356 // | PREL31 offset to function | Unwind instructions for function |
1357 // where the unwind instructions are either a small number of unwind
1358 // instructions inlined into the table entry, the special CANT_UNWIND value of
1359 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1362 // We return true if all the unwind instructions in the .ARM.exidx entries of
1363 // Cur can be merged into the last entry of Prev.
1364 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1366 // References to .ARM.Extab Sections have bit 31 clear and are not the
1367 // special EXIDX_CANTUNWIND bit-pattern.
1368 auto IsExtabRef = [](uint32_t Unwind) {
1369 return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1377 // Get the last table Entry from the previous .ARM.exidx section.
1378 const ExidxEntry &PrevEntry = Prev->getDataAs<ExidxEntry>().back();
1379 if (IsExtabRef(PrevEntry.Unwind))
1382 // We consider the unwind instructions of an .ARM.exidx table entry
1383 // a duplicate if the previous unwind instructions if:
1384 // - Both are the special EXIDX_CANTUNWIND.
1385 // - Both are the same inline unwind instructions.
1386 // We do not attempt to follow and check links into .ARM.extab tables as
1387 // consecutive identical entries are rare and the effort to check that they
1388 // are identical is high.
1390 for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>())
1391 if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1393 // All table entries in this .ARM.exidx Section can be merged into the
1394 // previous Section.
1398 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1399 for (OutputSection *Sec : OutputSections) {
1400 if (!(Sec->Flags & SHF_LINK_ORDER))
1403 // Link order may be distributed across several InputSectionDescriptions
1404 // but sort must consider them all at once.
1405 std::vector<InputSection **> ScriptSections;
1406 std::vector<InputSection *> Sections;
1407 for (BaseCommand *Base : Sec->SectionCommands) {
1408 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1409 for (InputSection *&IS : ISD->Sections) {
1410 ScriptSections.push_back(&IS);
1411 Sections.push_back(IS);
1415 std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1417 if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1418 Sec->Type == SHT_ARM_EXIDX) {
1420 if (auto *Sentinel = dyn_cast<ARMExidxSentinelSection>(Sections.back())) {
1421 assert(Sections.size() >= 2 &&
1422 "We should create a sentinel section only if there are "
1423 "alive regular exidx sections.");
1424 // The last executable section is required to fill the sentinel.
1425 // Remember it here so that we don't have to find it again.
1426 Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1429 if (Config->MergeArmExidx) {
1430 // The EHABI for the Arm Architecture permits consecutive identical
1431 // table entries to be merged. We use a simple implementation that
1432 // removes a .ARM.exidx Input Section if it can be merged into the
1433 // previous one. This does not require any rewriting of InputSection
1434 // contents but misses opportunities for fine grained deduplication
1435 // where only a subset of the InputSection contents can be merged.
1437 // The last one is a sentinel entry which should not be removed.
1438 for (size_t I = 1; I < Sections.size() - 1; ++I) {
1439 if (isDuplicateArmExidxSec(Sections[Prev], Sections[I]))
1440 Sections[I] = nullptr;
1447 for (int I = 0, N = Sections.size(); I < N; ++I)
1448 *ScriptSections[I] = Sections[I];
1450 // Remove the Sections we marked as duplicate earlier.
1451 for (BaseCommand *Base : Sec->SectionCommands)
1452 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1453 llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; });
1457 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1458 llvm::function_ref<void(SyntheticSection *)> Fn) {
1459 for (SyntheticSection *SS : Sections)
1460 if (SS && SS->getParent() && !SS->empty())
1464 // In order to allow users to manipulate linker-synthesized sections,
1465 // we had to add synthetic sections to the input section list early,
1466 // even before we make decisions whether they are needed. This allows
1467 // users to write scripts like this: ".mygot : { .got }".
1469 // Doing it has an unintended side effects. If it turns out that we
1470 // don't need a .got (for example) at all because there's no
1471 // relocation that needs a .got, we don't want to emit .got.
1473 // To deal with the above problem, this function is called after
1474 // scanRelocations is called to remove synthetic sections that turn
1476 static void removeUnusedSyntheticSections() {
1477 // All input synthetic sections that can be empty are placed after
1478 // all regular ones. We iterate over them all and exit at first
1480 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1481 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1484 OutputSection *OS = SS->getParent();
1485 if (!OS || !SS->empty())
1488 // If we reach here, then SS is an unused synthetic section and we want to
1489 // remove it from corresponding input section description of output section.
1490 for (BaseCommand *B : OS->SectionCommands)
1491 if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1492 llvm::erase_if(ISD->Sections,
1493 [=](InputSection *IS) { return IS == SS; });
1497 // Returns true if a symbol can be replaced at load-time by a symbol
1498 // with the same name defined in other ELF executable or DSO.
1499 static bool computeIsPreemptible(const Symbol &B) {
1500 assert(!B.isLocal());
1501 // Only symbols that appear in dynsym can be preempted.
1502 if (!B.includeInDynsym())
1505 // Only default visibility symbols can be preempted.
1506 if (B.Visibility != STV_DEFAULT)
1509 // At this point copy relocations have not been created yet, so any
1510 // symbol that is not defined locally is preemptible.
1514 // If we have a dynamic list it specifies which local symbols are preemptible.
1515 if (Config->HasDynamicList)
1518 if (!Config->Shared)
1521 // -Bsymbolic means that definitions are not preempted.
1522 if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1527 // Create output section objects and add them to OutputSections.
1528 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1529 Out::DebugInfo = findSection(".debug_info");
1530 Out::PreinitArray = findSection(".preinit_array");
1531 Out::InitArray = findSection(".init_array");
1532 Out::FiniArray = findSection(".fini_array");
1534 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1535 // symbols for sections, so that the runtime can get the start and end
1536 // addresses of each section by section name. Add such symbols.
1537 if (!Config->Relocatable) {
1538 addStartEndSymbols();
1539 for (BaseCommand *Base : Script->SectionCommands)
1540 if (auto *Sec = dyn_cast<OutputSection>(Base))
1541 addStartStopSymbols(Sec);
1544 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1545 // It should be okay as no one seems to care about the type.
1546 // Even the author of gold doesn't remember why gold behaves that way.
1547 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1549 Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1550 /*Size=*/0, STB_WEAK, InX::Dynamic,
1553 // Define __rel[a]_iplt_{start,end} symbols if needed.
1554 addRelIpltSymbols();
1556 // This responsible for splitting up .eh_frame section into
1557 // pieces. The relocation scan uses those pieces, so this has to be
1559 applySynthetic({InX::EhFrame},
1560 [](SyntheticSection *SS) { SS->finalizeContents(); });
1562 for (Symbol *S : Symtab->getSymbols())
1563 S->IsPreemptible |= computeIsPreemptible(*S);
1565 // Scan relocations. This must be done after every symbol is declared so that
1566 // we can correctly decide if a dynamic relocation is needed.
1567 if (!Config->Relocatable)
1568 forEachRelSec(scanRelocations<ELFT>);
1570 if (InX::Plt && !InX::Plt->empty())
1571 InX::Plt->addSymbols();
1572 if (InX::Iplt && !InX::Iplt->empty())
1573 InX::Iplt->addSymbols();
1575 // Now that we have defined all possible global symbols including linker-
1576 // synthesized ones. Visit all symbols to give the finishing touches.
1577 for (Symbol *Sym : Symtab->getSymbols()) {
1578 if (!includeInSymtab(*Sym))
1581 InX::SymTab->addSymbol(Sym);
1583 if (InX::DynSymTab && Sym->includeInDynsym()) {
1584 InX::DynSymTab->addSymbol(Sym);
1585 if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1586 if (File->IsNeeded && !Sym->isUndefined())
1587 In<ELFT>::VerNeed->addSymbol(Sym);
1591 // Do not proceed if there was an undefined symbol.
1596 InX::MipsGot->build<ELFT>();
1598 removeUnusedSyntheticSections();
1602 // Now that we have the final list, create a list of all the
1603 // OutputSections for convenience.
1604 for (BaseCommand *Base : Script->SectionCommands)
1605 if (auto *Sec = dyn_cast<OutputSection>(Base))
1606 OutputSections.push_back(Sec);
1608 // Prefer command line supplied address over other constraints.
1609 for (OutputSection *Sec : OutputSections) {
1610 auto I = Config->SectionStartMap.find(Sec->Name);
1611 if (I != Config->SectionStartMap.end())
1612 Sec->AddrExpr = [=] { return I->second; };
1615 // This is a bit of a hack. A value of 0 means undef, so we set it
1616 // to 1 to make __ehdr_start defined. The section number is not
1617 // particularly relevant.
1618 Out::ElfHeader->SectionIndex = 1;
1621 for (OutputSection *Sec : OutputSections) {
1622 Sec->SectionIndex = I++;
1623 Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1626 // Binary and relocatable output does not have PHDRS.
1627 // The headers have to be created before finalize as that can influence the
1628 // image base and the dynamic section on mips includes the image base.
1629 if (!Config->Relocatable && !Config->OFormatBinary) {
1630 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1631 addPtArmExid(Phdrs);
1632 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1635 // Some symbols are defined in term of program headers. Now that we
1636 // have the headers, we can find out which sections they point to.
1637 setReservedSymbolSections();
1639 // Dynamic section must be the last one in this list and dynamic
1640 // symbol table section (DynSymTab) must be the first one.
1642 {InX::DynSymTab, InX::Bss, InX::BssRelRo, InX::GnuHashTab,
1643 InX::HashTab, InX::SymTab, InX::ShStrTab, InX::StrTab,
1644 In<ELFT>::VerDef, InX::DynStrTab, InX::Got, InX::MipsGot,
1645 InX::IgotPlt, InX::GotPlt, InX::RelaDyn, InX::RelrDyn,
1646 InX::RelaIplt, InX::RelaPlt, InX::Plt, InX::Iplt,
1647 InX::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1648 [](SyntheticSection *SS) { SS->finalizeContents(); });
1650 if (!Script->HasSectionsCommand && !Config->Relocatable)
1651 fixSectionAlignments();
1653 // After link order processing .ARM.exidx sections can be deduplicated, which
1654 // needs to be resolved before any other address dependent operation.
1655 resolveShfLinkOrder();
1657 // Some architectures need to generate content that depends on the address
1658 // of InputSections. For example some architectures use small displacements
1659 // for jump instructions that is the linker's responsibility for creating
1660 // range extension thunks for. As the generation of the content may also
1661 // alter InputSection addresses we must converge to a fixed point.
1662 if (Target->NeedsThunks || Config->AndroidPackDynRelocs ||
1663 Config->RelrPackDynRelocs) {
1665 AArch64Err843419Patcher A64P;
1668 Script->assignAddresses();
1670 if (Target->NeedsThunks)
1671 Changed |= TC.createThunks(OutputSections);
1672 if (Config->FixCortexA53Errata843419) {
1674 Script->assignAddresses();
1675 Changed |= A64P.createFixes();
1678 InX::MipsGot->updateAllocSize();
1679 Changed |= InX::RelaDyn->updateAllocSize();
1681 Changed |= InX::RelrDyn->updateAllocSize();
1685 // createThunks may have added local symbols to the static symbol table
1686 applySynthetic({InX::SymTab},
1687 [](SyntheticSection *SS) { SS->postThunkContents(); });
1689 // Fill other section headers. The dynamic table is finalized
1690 // at the end because some tags like RELSZ depend on result
1691 // of finalizing other sections.
1692 for (OutputSection *Sec : OutputSections)
1693 Sec->finalize<ELFT>();
1696 // The linker is expected to define SECNAME_start and SECNAME_end
1697 // symbols for a few sections. This function defines them.
1698 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1699 // If a section does not exist, there's ambiguity as to how we
1700 // define _start and _end symbols for an init/fini section. Since
1701 // the loader assume that the symbols are always defined, we need to
1702 // always define them. But what value? The loader iterates over all
1703 // pointers between _start and _end to run global ctors/dtors, so if
1704 // the section is empty, their symbol values don't actually matter
1705 // as long as _start and _end point to the same location.
1707 // That said, we don't want to set the symbols to 0 (which is
1708 // probably the simplest value) because that could cause some
1709 // program to fail to link due to relocation overflow, if their
1710 // program text is above 2 GiB. We use the address of the .text
1711 // section instead to prevent that failure.
1712 OutputSection *Default = findSection(".text");
1714 Default = Out::ElfHeader;
1715 auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1717 addOptionalRegular(Start, OS, 0);
1718 addOptionalRegular(End, OS, -1);
1720 addOptionalRegular(Start, Default, 0);
1721 addOptionalRegular(End, Default, 0);
1725 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1726 Define("__init_array_start", "__init_array_end", Out::InitArray);
1727 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1729 if (OutputSection *Sec = findSection(".ARM.exidx"))
1730 Define("__exidx_start", "__exidx_end", Sec);
1733 // If a section name is valid as a C identifier (which is rare because of
1734 // the leading '.'), linkers are expected to define __start_<secname> and
1735 // __stop_<secname> symbols. They are at beginning and end of the section,
1736 // respectively. This is not requested by the ELF standard, but GNU ld and
1737 // gold provide the feature, and used by many programs.
1738 template <class ELFT>
1739 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1740 StringRef S = Sec->Name;
1741 if (!isValidCIdentifier(S))
1743 addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1744 addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1747 static bool needsPtLoad(OutputSection *Sec) {
1748 if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1751 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1752 // responsible for allocating space for them, not the PT_LOAD that
1753 // contains the TLS initialization image.
1754 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1759 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1760 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1761 // RW. This means that there is no alignment in the RO to RX transition and we
1762 // cannot create a PT_LOAD there.
1763 static uint64_t computeFlags(uint64_t Flags) {
1765 return PF_R | PF_W | PF_X;
1766 if (Config->SingleRoRx && !(Flags & PF_W))
1767 return Flags | PF_X;
1771 // Decide which program headers to create and which sections to include in each
1773 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1774 std::vector<PhdrEntry *> Ret;
1775 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1776 Ret.push_back(make<PhdrEntry>(Type, Flags));
1780 // The first phdr entry is PT_PHDR which describes the program header itself.
1781 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1783 // PT_INTERP must be the second entry if exists.
1784 if (OutputSection *Cmd = findSection(".interp"))
1785 AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1787 // Add the first PT_LOAD segment for regular output sections.
1788 uint64_t Flags = computeFlags(PF_R);
1789 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1791 // Add the headers. We will remove them if they don't fit.
1792 Load->add(Out::ElfHeader);
1793 Load->add(Out::ProgramHeaders);
1795 for (OutputSection *Sec : OutputSections) {
1796 if (!(Sec->Flags & SHF_ALLOC))
1798 if (!needsPtLoad(Sec))
1801 // Segments are contiguous memory regions that has the same attributes
1802 // (e.g. executable or writable). There is one phdr for each segment.
1803 // Therefore, we need to create a new phdr when the next section has
1804 // different flags or is loaded at a discontiguous address using AT linker
1805 // script command. At the same time, we don't want to create a separate
1806 // load segment for the headers, even if the first output section has
1808 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1809 if ((Sec->LMAExpr && Load->LastSec != Out::ProgramHeaders) ||
1810 Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1812 Load = AddHdr(PT_LOAD, NewFlags);
1819 // Add a TLS segment if any.
1820 PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1821 for (OutputSection *Sec : OutputSections)
1822 if (Sec->Flags & SHF_TLS)
1824 if (TlsHdr->FirstSec)
1825 Ret.push_back(TlsHdr);
1827 // Add an entry for .dynamic.
1829 AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1830 ->add(InX::Dynamic->getParent());
1832 // PT_GNU_RELRO includes all sections that should be marked as
1833 // read-only by dynamic linker after proccessing relocations.
1834 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1835 // an error message if more than one PT_GNU_RELRO PHDR is required.
1836 PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1837 bool InRelroPhdr = false;
1838 bool IsRelroFinished = false;
1839 for (OutputSection *Sec : OutputSections) {
1840 if (!needsPtLoad(Sec))
1842 if (isRelroSection(Sec)) {
1844 if (!IsRelroFinished)
1847 error("section: " + Sec->Name + " is not contiguous with other relro" +
1849 } else if (InRelroPhdr) {
1850 InRelroPhdr = false;
1851 IsRelroFinished = true;
1854 if (RelRo->FirstSec)
1855 Ret.push_back(RelRo);
1857 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1858 if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() &&
1859 InX::EhFrameHdr->getParent())
1860 AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags())
1861 ->add(InX::EhFrameHdr->getParent());
1863 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1864 // the dynamic linker fill the segment with random data.
1865 if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1866 AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1868 // PT_GNU_STACK is a special section to tell the loader to make the
1869 // pages for the stack non-executable. If you really want an executable
1870 // stack, you can pass -z execstack, but that's not recommended for
1871 // security reasons.
1872 unsigned Perm = PF_R | PF_W;
1873 if (Config->ZExecstack)
1875 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1877 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1878 // is expected to perform W^X violations, such as calling mprotect(2) or
1879 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1881 if (Config->ZWxneeded)
1882 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1884 // Create one PT_NOTE per a group of contiguous .note sections.
1885 PhdrEntry *Note = nullptr;
1886 for (OutputSection *Sec : OutputSections) {
1887 if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
1888 if (!Note || Sec->LMAExpr)
1889 Note = AddHdr(PT_NOTE, PF_R);
1898 template <class ELFT>
1899 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
1900 if (Config->EMachine != EM_ARM)
1902 auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
1903 return Cmd->Type == SHT_ARM_EXIDX;
1905 if (I == OutputSections.end())
1908 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1909 PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
1911 Phdrs.push_back(ARMExidx);
1914 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1915 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1916 // linker can set the permissions.
1917 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1918 auto PageAlign = [](OutputSection *Cmd) {
1919 if (Cmd && !Cmd->AddrExpr)
1920 Cmd->AddrExpr = [=] {
1921 return alignTo(Script->getDot(), Config->MaxPageSize);
1925 for (const PhdrEntry *P : Phdrs)
1926 if (P->p_type == PT_LOAD && P->FirstSec)
1927 PageAlign(P->FirstSec);
1929 for (const PhdrEntry *P : Phdrs) {
1930 if (P->p_type != PT_GNU_RELRO)
1933 PageAlign(P->FirstSec);
1934 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1935 // have to align it to a page.
1936 auto End = OutputSections.end();
1937 auto I = std::find(OutputSections.begin(), End, P->LastSec);
1938 if (I == End || (I + 1) == End)
1940 OutputSection *Cmd = (*(I + 1));
1941 if (needsPtLoad(Cmd))
1946 // Adjusts the file alignment for a given output section and returns
1947 // its new file offset. The file offset must be the same with its
1948 // virtual address (modulo the page size) so that the loader can load
1949 // executables without any address adjustment.
1950 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) {
1951 OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr;
1952 // The first section in a PT_LOAD has to have congruent offset and address
1953 // module the page size.
1955 return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize),
1958 // For SHT_NOBITS we don't want the alignment of the section to impact the
1959 // offset of the sections that follow. Since nothing seems to care about the
1960 // sh_offset of the SHT_NOBITS section itself, just ignore it.
1961 if (Cmd->Type == SHT_NOBITS)
1964 // If the section is not in a PT_LOAD, we just have to align it.
1966 return alignTo(Off, Cmd->Alignment);
1968 // If two sections share the same PT_LOAD the file offset is calculated
1969 // using this formula: Off2 = Off1 + (VA2 - VA1).
1970 return First->Offset + Cmd->Addr - First->Addr;
1973 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) {
1974 Off = getFileAlignment(Off, Cmd);
1977 // For SHT_NOBITS we should not count the size.
1978 if (Cmd->Type == SHT_NOBITS)
1981 return Off + Cmd->Size;
1984 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1986 for (OutputSection *Sec : OutputSections)
1987 if (Sec->Flags & SHF_ALLOC)
1988 Off = setOffset(Sec, Off);
1989 FileSize = alignTo(Off, Config->Wordsize);
1992 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
1994 return "<empty range at 0x" + utohexstr(Addr) + ">";
1995 return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
1998 // Assign file offsets to output sections.
1999 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2001 Off = setOffset(Out::ElfHeader, Off);
2002 Off = setOffset(Out::ProgramHeaders, Off);
2004 PhdrEntry *LastRX = nullptr;
2005 for (PhdrEntry *P : Phdrs)
2006 if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2009 for (OutputSection *Sec : OutputSections) {
2010 Off = setOffset(Sec, Off);
2011 if (Script->HasSectionsCommand)
2013 // If this is a last section of the last executable segment and that
2014 // segment is the last loadable segment, align the offset of the
2015 // following section to avoid loading non-segments parts of the file.
2016 if (LastRX && LastRX->LastSec == Sec)
2017 Off = alignTo(Off, Target->PageSize);
2020 SectionHeaderOff = alignTo(Off, Config->Wordsize);
2021 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2023 // Our logic assumes that sections have rising VA within the same segment.
2024 // With use of linker scripts it is possible to violate this rule and get file
2025 // offset overlaps or overflows. That should never happen with a valid script
2026 // which does not move the location counter backwards and usually scripts do
2027 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2028 // kernel, which control segment distribution explicitly and move the counter
2029 // backwards, so we have to allow doing that to support linking them. We
2030 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2031 // we want to prevent file size overflows because it would crash the linker.
2032 for (OutputSection *Sec : OutputSections) {
2033 if (Sec->Type == SHT_NOBITS)
2035 if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2036 error("unable to place section " + Sec->Name + " at file offset " +
2037 rangeToString(Sec->Offset, Sec->Offset + Sec->Size) +
2038 "; check your linker script for overflows");
2042 // Finalize the program headers. We call this function after we assign
2043 // file offsets and VAs to all sections.
2044 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2045 for (PhdrEntry *P : Phdrs) {
2046 OutputSection *First = P->FirstSec;
2047 OutputSection *Last = P->LastSec;
2049 P->p_filesz = Last->Offset - First->Offset;
2050 if (Last->Type != SHT_NOBITS)
2051 P->p_filesz += Last->Size;
2052 P->p_memsz = Last->Addr + Last->Size - First->Addr;
2053 P->p_offset = First->Offset;
2054 P->p_vaddr = First->Addr;
2056 P->p_paddr = First->getLMA();
2058 if (P->p_type == PT_LOAD)
2059 P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2060 else if (P->p_type == PT_GNU_RELRO) {
2062 // The glibc dynamic loader rounds the size down, so we need to round up
2063 // to protect the last page. This is a no-op on FreeBSD which always
2065 P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2068 // The TLS pointer goes after PT_TLS. At least glibc will align it,
2069 // so round up the size to make sure the offsets are correct.
2070 if (P->p_type == PT_TLS) {
2073 P->p_memsz = alignTo(P->p_memsz, P->p_align);
2078 // A helper struct for checkSectionOverlap.
2080 struct SectionOffset {
2086 // Check whether sections overlap for a specific address range (file offsets,
2087 // load and virtual adresses).
2088 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2089 bool IsVirtualAddr) {
2090 llvm::sort(Sections.begin(), Sections.end(),
2091 [=](const SectionOffset &A, const SectionOffset &B) {
2092 return A.Offset < B.Offset;
2095 // Finding overlap is easy given a vector is sorted by start position.
2096 // If an element starts before the end of the previous element, they overlap.
2097 for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2098 SectionOffset A = Sections[I - 1];
2099 SectionOffset B = Sections[I];
2100 if (B.Offset >= A.Offset + A.Sec->Size)
2103 // If both sections are in OVERLAY we allow the overlapping of virtual
2104 // addresses, because it is what OVERLAY was designed for.
2105 if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2108 errorOrWarn("section " + A.Sec->Name + " " + Name +
2109 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2110 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2111 B.Sec->Name + " range is " +
2112 rangeToString(B.Offset, B.Sec->Size));
2116 // Check for overlapping sections and address overflows.
2118 // In this function we check that none of the output sections have overlapping
2119 // file offsets. For SHF_ALLOC sections we also check that the load address
2120 // ranges and the virtual address ranges don't overlap
2121 template <class ELFT> void Writer<ELFT>::checkSections() {
2122 // First, check that section's VAs fit in available address space for target.
2123 for (OutputSection *OS : OutputSections)
2124 if ((OS->Addr + OS->Size < OS->Addr) ||
2125 (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2126 errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2127 " of size 0x" + utohexstr(OS->Size) +
2128 " exceeds available address space");
2130 // Check for overlapping file offsets. In this case we need to skip any
2131 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2132 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2133 // binary is specified only add SHF_ALLOC sections are added to the output
2134 // file so we skip any non-allocated sections in that case.
2135 std::vector<SectionOffset> FileOffs;
2136 for (OutputSection *Sec : OutputSections)
2137 if (0 < Sec->Size && Sec->Type != SHT_NOBITS &&
2138 (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2139 FileOffs.push_back({Sec, Sec->Offset});
2140 checkOverlap("file", FileOffs, false);
2142 // When linking with -r there is no need to check for overlapping virtual/load
2143 // addresses since those addresses will only be assigned when the final
2144 // executable/shared object is created.
2145 if (Config->Relocatable)
2148 // Checking for overlapping virtual and load addresses only needs to take
2149 // into account SHF_ALLOC sections since others will not be loaded.
2150 // Furthermore, we also need to skip SHF_TLS sections since these will be
2151 // mapped to other addresses at runtime and can therefore have overlapping
2152 // ranges in the file.
2153 std::vector<SectionOffset> VMAs;
2154 for (OutputSection *Sec : OutputSections)
2155 if (0 < Sec->Size && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2156 VMAs.push_back({Sec, Sec->Addr});
2157 checkOverlap("virtual address", VMAs, true);
2159 // Finally, check that the load addresses don't overlap. This will usually be
2160 // the same as the virtual addresses but can be different when using a linker
2161 // script with AT().
2162 std::vector<SectionOffset> LMAs;
2163 for (OutputSection *Sec : OutputSections)
2164 if (0 < Sec->Size && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2165 LMAs.push_back({Sec, Sec->getLMA()});
2166 checkOverlap("load address", LMAs, false);
2169 // The entry point address is chosen in the following ways.
2171 // 1. the '-e' entry command-line option;
2172 // 2. the ENTRY(symbol) command in a linker control script;
2173 // 3. the value of the symbol _start, if present;
2174 // 4. the number represented by the entry symbol, if it is a number;
2175 // 5. the address of the first byte of the .text section, if present;
2176 // 6. the address 0.
2177 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
2179 if (Symbol *B = Symtab->find(Config->Entry))
2184 if (to_integer(Config->Entry, Addr))
2188 if (OutputSection *Sec = findSection(".text")) {
2189 if (Config->WarnMissingEntry)
2190 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2191 utohexstr(Sec->Addr));
2196 if (Config->WarnMissingEntry)
2197 warn("cannot find entry symbol " + Config->Entry +
2198 "; not setting start address");
2202 static uint16_t getELFType() {
2205 if (Config->Relocatable)
2210 static uint8_t getAbiVersion() {
2211 // MIPS non-PIC executable gets ABI version 1.
2212 if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2213 (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2218 template <class ELFT> void Writer<ELFT>::writeHeader() {
2219 uint8_t *Buf = Buffer->getBufferStart();
2220 // For executable segments, the trap instructions are written before writing
2221 // the header. Setting Elf header bytes to zero ensures that any unused bytes
2222 // in header are zero-cleared, instead of having trap instructions.
2223 memset(Buf, 0, sizeof(Elf_Ehdr));
2224 memcpy(Buf, "\177ELF", 4);
2226 // Write the ELF header.
2227 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2228 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2229 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2230 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2231 EHdr->e_ident[EI_OSABI] = Config->OSABI;
2232 EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2233 EHdr->e_type = getELFType();
2234 EHdr->e_machine = Config->EMachine;
2235 EHdr->e_version = EV_CURRENT;
2236 EHdr->e_entry = getEntryAddr();
2237 EHdr->e_shoff = SectionHeaderOff;
2238 EHdr->e_flags = Config->EFlags;
2239 EHdr->e_ehsize = sizeof(Elf_Ehdr);
2240 EHdr->e_phnum = Phdrs.size();
2241 EHdr->e_shentsize = sizeof(Elf_Shdr);
2243 if (!Config->Relocatable) {
2244 EHdr->e_phoff = sizeof(Elf_Ehdr);
2245 EHdr->e_phentsize = sizeof(Elf_Phdr);
2248 // Write the program header table.
2249 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2250 for (PhdrEntry *P : Phdrs) {
2251 HBuf->p_type = P->p_type;
2252 HBuf->p_flags = P->p_flags;
2253 HBuf->p_offset = P->p_offset;
2254 HBuf->p_vaddr = P->p_vaddr;
2255 HBuf->p_paddr = P->p_paddr;
2256 HBuf->p_filesz = P->p_filesz;
2257 HBuf->p_memsz = P->p_memsz;
2258 HBuf->p_align = P->p_align;
2262 // Write the section header table.
2264 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2265 // and e_shstrndx fields. When the value of one of these fields exceeds
2266 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2267 // use fields in the section header at index 0 to store
2268 // the value. The sentinel values and fields are:
2269 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2270 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2271 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2272 size_t Num = OutputSections.size() + 1;
2273 if (Num >= SHN_LORESERVE)
2274 SHdrs->sh_size = Num;
2276 EHdr->e_shnum = Num;
2278 uint32_t StrTabIndex = InX::ShStrTab->getParent()->SectionIndex;
2279 if (StrTabIndex >= SHN_LORESERVE) {
2280 SHdrs->sh_link = StrTabIndex;
2281 EHdr->e_shstrndx = SHN_XINDEX;
2283 EHdr->e_shstrndx = StrTabIndex;
2286 for (OutputSection *Sec : OutputSections)
2287 Sec->writeHeaderTo<ELFT>(++SHdrs);
2290 // Open a result file.
2291 template <class ELFT> void Writer<ELFT>::openFile() {
2292 if (!Config->Is64 && FileSize > UINT32_MAX) {
2293 error("output file too large: " + Twine(FileSize) + " bytes");
2297 unlinkAsync(Config->OutputFile);
2299 if (!Config->Relocatable)
2300 Flags = FileOutputBuffer::F_executable;
2301 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2302 FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2305 error("failed to open " + Config->OutputFile + ": " +
2306 llvm::toString(BufferOrErr.takeError()));
2308 Buffer = std::move(*BufferOrErr);
2311 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2312 uint8_t *Buf = Buffer->getBufferStart();
2313 for (OutputSection *Sec : OutputSections)
2314 if (Sec->Flags & SHF_ALLOC)
2315 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2318 static void fillTrap(uint8_t *I, uint8_t *End) {
2319 for (; I + 4 <= End; I += 4)
2320 memcpy(I, &Target->TrapInstr, 4);
2323 // Fill the last page of executable segments with trap instructions
2324 // instead of leaving them as zero. Even though it is not required by any
2325 // standard, it is in general a good thing to do for security reasons.
2327 // We'll leave other pages in segments as-is because the rest will be
2328 // overwritten by output sections.
2329 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2330 if (Script->HasSectionsCommand)
2333 // Fill the last page.
2334 uint8_t *Buf = Buffer->getBufferStart();
2335 for (PhdrEntry *P : Phdrs)
2336 if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2337 fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2338 Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2340 // Round up the file size of the last segment to the page boundary iff it is
2341 // an executable segment to ensure that other tools don't accidentally
2342 // trim the instruction padding (e.g. when stripping the file).
2343 PhdrEntry *Last = nullptr;
2344 for (PhdrEntry *P : Phdrs)
2345 if (P->p_type == PT_LOAD)
2348 if (Last && (Last->p_flags & PF_X))
2349 Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2352 // Write section contents to a mmap'ed file.
2353 template <class ELFT> void Writer<ELFT>::writeSections() {
2354 uint8_t *Buf = Buffer->getBufferStart();
2356 OutputSection *EhFrameHdr = nullptr;
2357 if (InX::EhFrameHdr && !InX::EhFrameHdr->empty())
2358 EhFrameHdr = InX::EhFrameHdr->getParent();
2360 // In -r or -emit-relocs mode, write the relocation sections first as in
2361 // ELf_Rel targets we might find out that we need to modify the relocated
2362 // section while doing it.
2363 for (OutputSection *Sec : OutputSections)
2364 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2365 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2367 for (OutputSection *Sec : OutputSections)
2368 if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2369 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2371 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2372 // it should be written after .eh_frame is written.
2374 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2377 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2378 if (!InX::BuildId || !InX::BuildId->getParent())
2381 // Compute a hash of all sections of the output file.
2382 uint8_t *Start = Buffer->getBufferStart();
2383 uint8_t *End = Start + FileSize;
2384 InX::BuildId->writeBuildId({Start, End});
2387 template void elf::writeResult<ELF32LE>();
2388 template void elf::writeResult<ELF32BE>();
2389 template void elf::writeResult<ELF64LE>();
2390 template void elf::writeResult<ELF64BE>();