1 //===- Writer.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
36 using namespace lld::elf;
39 // The writer writes a SymbolTable result to a file.
40 template <class ELFT> class Writer {
42 typedef typename ELFT::Shdr Elf_Shdr;
43 typedef typename ELFT::Ehdr Elf_Ehdr;
44 typedef typename ELFT::Phdr Elf_Phdr;
49 void clearOutputSections();
50 void createSyntheticSections();
51 void copyLocalSymbols();
52 void addSectionSymbols();
53 void addReservedSymbols();
54 void createSections();
55 void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
57 void finalizeSections();
58 void addPredefinedSections();
60 std::vector<PhdrEntry> createPhdrs();
61 void removeEmptyPTLoad();
62 void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
63 void assignFileOffsets();
64 void assignFileOffsetsBinary();
66 void fixSectionAlignments();
67 void fixPredefinedSymbols();
71 void writeSectionsBinary();
74 std::unique_ptr<FileOutputBuffer> Buffer;
76 OutputSectionFactory Factory{OutputSections};
78 void addRelIpltSymbols();
79 void addStartEndSymbols();
80 void addStartStopSymbols(OutputSection *Sec);
81 uint64_t getEntryAddr();
82 OutputSection *findSection(StringRef Name);
83 OutputSection *findSectionInScript(StringRef Name);
84 OutputSectionCommand *findSectionCommand(StringRef Name);
86 std::vector<PhdrEntry> Phdrs;
89 uint64_t SectionHeaderOff;
91 bool HasGotBaseSym = false;
93 } // anonymous namespace
95 StringRef elf::getOutputSectionName(StringRef Name) {
96 // ".zdebug_" is a prefix for ZLIB-compressed sections.
97 // Because we decompressed input sections, we want to remove 'z'.
98 if (Name.startswith(".zdebug_"))
99 return Saver.save("." + Name.substr(2));
101 if (Config->Relocatable)
105 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
106 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
107 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
108 StringRef Prefix = V.drop_back();
109 if (Name.startswith(V) || Name == Prefix)
113 // CommonSection is identified as "COMMON" in linker scripts.
114 // By default, it should go to .bss section.
115 if (Name == "COMMON")
121 template <class ELFT> static bool needsInterpSection() {
122 return !Symtab<ELFT>::X->getSharedFiles().empty() &&
123 !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
126 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
128 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
129 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
130 if (P.p_type != PT_LOAD)
134 uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
137 Phdrs.erase(I, Phdrs.end());
140 template <class ELFT> static void combineEhFrameSections() {
141 for (InputSectionBase *&S : InputSections) {
142 EhInputSection *ES = dyn_cast<EhInputSection>(S);
143 if (!ES || !ES->Live)
146 In<ELFT>::EhFrame->addSection(ES);
150 std::vector<InputSectionBase *> &V = InputSections;
151 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
154 template <class ELFT> void Writer<ELFT>::clearOutputSections() {
155 if (Script->Opt.HasSections)
156 Script->createOrphanCommands();
158 Script->fabricateDefaultCommands();
159 // Clear the OutputSections to make sure it is not used anymore. Any
160 // code from this point on should be using the linker script
162 for (OutputSection *Sec : OutputSections)
163 Sec->Sections.clear();
164 OutputSections.clear();
167 // The main function of the writer.
168 template <class ELFT> void Writer<ELFT>::run() {
169 // Create linker-synthesized sections such as .got or .plt.
170 // Such sections are of type input section.
171 createSyntheticSections();
173 if (!Config->Relocatable)
174 combineEhFrameSections<ELFT>();
176 // We need to create some reserved symbols such as _end. Create them.
177 if (!Config->Relocatable)
178 addReservedSymbols();
180 // Create output sections.
181 if (Script->Opt.HasSections) {
182 // If linker script contains SECTIONS commands, let it create sections.
183 Script->processCommands(Factory);
185 // Linker scripts may have left some input sections unassigned.
186 // Assign such sections using the default rule.
187 Script->addOrphanSections(Factory);
189 // If linker script does not contain SECTIONS commands, create
190 // output sections by default rules. We still need to give the
191 // linker script a chance to run, because it might contain
192 // non-SECTIONS commands such as ASSERT.
194 Script->processCommands(Factory);
197 if (Config->Discard != DiscardPolicy::All)
200 if (Config->CopyRelocs)
203 // Now that we have a complete set of output sections. This function
204 // completes section contents. For example, we need to add strings
205 // to the string table, and add entries to .got and .plt.
206 // finalizeSections does that.
211 if (!Script->Opt.HasSections && !Config->Relocatable)
212 fixSectionAlignments();
214 // If -compressed-debug-sections is specified, we need to compress
215 // .debug_* sections. Do it right now because it changes the size of
218 OutputSectionCommands.begin(), OutputSectionCommands.end(),
219 [](OutputSectionCommand *Cmd) { Cmd->maybeCompress<ELFT>(); });
221 Script->assignAddresses(Phdrs);
223 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
224 // 0 sized region. This has to be done late since only after assignAddresses
225 // we know the size of the sections.
228 if (!Config->OFormatBinary)
231 assignFileOffsetsBinary();
235 if (Config->Relocatable) {
236 for (OutputSectionCommand *Cmd : OutputSectionCommands)
239 fixPredefinedSymbols();
242 // It does not make sense try to open the file if we have error already.
245 // Write the result down to a file.
250 if (!Config->OFormatBinary) {
254 writeSectionsBinary();
257 // Backfill .note.gnu.build-id section content. This is done at last
258 // because the content is usually a hash value of the entire output file.
264 // Handle -Map option.
265 writeMapFile<ELFT>(OutputSectionCommands);
269 if (auto EC = Buffer->commit())
270 error("failed to write to the output file: " + EC.message());
272 // Flush the output streams and exit immediately. A full shutdown
273 // is a good test that we are keeping track of all allocated memory,
274 // but actually freeing it is a waste of time in a regular linker run.
275 if (Config->ExitEarly)
279 // Initialize Out members.
280 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
281 // Initialize all pointers with NULL. This is needed because
282 // you can call lld::elf::main more than once as a library.
283 memset(&Out::First, 0, sizeof(Out));
285 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
287 InX::DynStrTab = make<StringTableSection>(".dynstr", true);
288 InX::Dynamic = make<DynamicSection<ELFT>>();
289 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
290 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
291 InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
293 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
294 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
295 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
296 Out::ProgramHeaders->updateAlignment(Config->Wordsize);
298 if (needsInterpSection<ELFT>()) {
299 InX::Interp = createInterpSection();
302 InX::Interp = nullptr;
305 if (Config->Strip != StripPolicy::All) {
306 InX::StrTab = make<StringTableSection>(".strtab", false);
307 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
310 if (Config->BuildId != BuildIdKind::None) {
311 InX::BuildId = make<BuildIdSection>();
315 InX::Common = createCommonSection<ELFT>();
319 InX::Bss = make<BssSection>(".bss");
321 InX::BssRelRo = make<BssSection>(".bss.rel.ro");
324 // Add MIPS-specific sections.
325 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
326 Config->Pic || Config->ExportDynamic;
327 if (Config->EMachine == EM_MIPS) {
328 if (!Config->Shared && HasDynSymTab) {
329 InX::MipsRldMap = make<MipsRldMapSection>();
330 Add(InX::MipsRldMap);
332 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
334 if (auto *Sec = MipsOptionsSection<ELFT>::create())
336 if (auto *Sec = MipsReginfoSection<ELFT>::create())
341 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
344 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
345 Add(In<ELFT>::VerSym);
347 if (!Config->VersionDefinitions.empty()) {
348 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
349 Add(In<ELFT>::VerDef);
352 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
353 Add(In<ELFT>::VerNeed);
355 if (Config->GnuHash) {
356 InX::GnuHashTab = make<GnuHashTableSection>();
357 Add(InX::GnuHashTab);
360 if (Config->SysvHash) {
361 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
362 Add(In<ELFT>::HashTab);
367 Add(In<ELFT>::RelaDyn);
370 // Add .got. MIPS' .got is so different from the other archs,
371 // it has its own class.
372 if (Config->EMachine == EM_MIPS) {
373 InX::MipsGot = make<MipsGotSection>();
376 InX::Got = make<GotSection>();
380 InX::GotPlt = make<GotPltSection>();
382 InX::IgotPlt = make<IgotPltSection>();
385 if (Config->GdbIndex) {
386 InX::GdbIndex = make<GdbIndexSection>();
390 // We always need to add rel[a].plt to output if it has entries.
391 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
392 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
393 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
394 Add(In<ELFT>::RelaPlt);
396 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
397 // that the IRelative relocations are processed last by the dynamic loader
398 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
399 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
401 Add(In<ELFT>::RelaIplt);
403 InX::Plt = make<PltSection>(Target->PltHeaderSize);
405 InX::Iplt = make<PltSection>(0);
408 if (!Config->Relocatable) {
409 if (Config->EhFrameHdr) {
410 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
411 Add(In<ELFT>::EhFrameHdr);
413 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
414 Add(In<ELFT>::EhFrame);
424 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
425 const SymbolBody &B) {
426 if (B.isFile() || B.isSection())
429 // If sym references a section in a discarded group, don't keep it.
430 if (Sec == &InputSection::Discarded)
433 if (Config->Discard == DiscardPolicy::None)
436 // In ELF assembly .L symbols are normally discarded by the assembler.
437 // If the assembler fails to do so, the linker discards them if
438 // * --discard-locals is used.
439 // * The symbol is in a SHF_MERGE section, which is normally the reason for
440 // the assembler keeping the .L symbol.
441 if (!SymName.startswith(".L") && !SymName.empty())
444 if (Config->Discard == DiscardPolicy::Locals)
447 return !Sec || !(Sec->Flags & SHF_MERGE);
450 static bool includeInSymtab(const SymbolBody &B) {
451 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
454 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
455 // Always include absolute symbols.
456 SectionBase *Sec = D->Section;
459 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
461 IS = cast<InputSectionBase>(Sec);
462 // Exclude symbols pointing to garbage-collected sections.
466 if (auto *S = dyn_cast<MergeInputSection>(Sec))
467 if (!S->getSectionPiece(D->Value)->Live)
473 // Local symbols are not in the linker's symbol table. This function scans
474 // each object file's symbol table to copy local symbols to the output.
475 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
478 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
479 for (SymbolBody *B : F->getLocalSymbols()) {
482 ": broken object: getLocalSymbols returns a non-local symbol");
483 auto *DR = dyn_cast<DefinedRegular>(B);
485 // No reason to keep local undefined symbol in symtab.
488 if (!includeInSymtab(*B))
491 SectionBase *Sec = DR->Section;
492 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
494 InX::SymTab->addSymbol(B);
499 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
500 // Create one STT_SECTION symbol for each output section we might
501 // have a relocation with.
502 for (OutputSection *Sec : OutputSections) {
503 if (Sec->Sections.empty())
506 InputSection *IS = Sec->Sections[0];
507 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
508 IS->Type == SHT_RELA)
512 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
513 /*Value=*/0, /*Size=*/0, IS, nullptr);
514 InX::SymTab->addSymbol(Sym);
518 // Today's loaders have a feature to make segments read-only after
519 // processing dynamic relocations to enhance security. PT_GNU_RELRO
520 // is defined for that.
522 // This function returns true if a section needs to be put into a
523 // PT_GNU_RELRO segment.
524 bool elf::isRelroSection(const OutputSection *Sec) {
528 uint64_t Flags = Sec->Flags;
530 // Non-allocatable or non-writable sections don't need RELRO because
531 // they are not writable or not even mapped to memory in the first place.
532 // RELRO is for sections that are essentially read-only but need to
533 // be writable only at process startup to allow dynamic linker to
534 // apply relocations.
535 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
538 // Once initialized, TLS data segments are used as data templates
539 // for a thread-local storage. For each new thread, runtime
540 // allocates memory for a TLS and copy templates there. No thread
541 // are supposed to use templates directly. Thus, it can be in RELRO.
545 // .init_array, .preinit_array and .fini_array contain pointers to
546 // functions that are executed on process startup or exit. These
547 // pointers are set by the static linker, and they are not expected
548 // to change at runtime. But if you are an attacker, you could do
549 // interesting things by manipulating pointers in .fini_array, for
550 // example. So they are put into RELRO.
551 uint32_t Type = Sec->Type;
552 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
553 Type == SHT_PREINIT_ARRAY)
556 // .got contains pointers to external symbols. They are resolved by
557 // the dynamic linker when a module is loaded into memory, and after
558 // that they are not expected to change. So, it can be in RELRO.
559 if (InX::Got && Sec == InX::Got->getParent())
562 // .got.plt contains pointers to external function symbols. They are
563 // by default resolved lazily, so we usually cannot put it into RELRO.
564 // However, if "-z now" is given, the lazy symbol resolution is
565 // disabled, which enables us to put it into RELRO.
566 if (Sec == InX::GotPlt->getParent())
569 // .dynamic section contains data for the dynamic linker, and
570 // there's no need to write to it at runtime, so it's better to put
572 if (Sec == InX::Dynamic->getParent())
575 // .bss.rel.ro is used for copy relocations for read-only symbols.
576 // Since the dynamic linker needs to process copy relocations, the
577 // section cannot be read-only, but once initialized, they shouldn't
579 if (Sec == InX::BssRelRo->getParent())
582 // Sections with some special names are put into RELRO. This is a
583 // bit unfortunate because section names shouldn't be significant in
584 // ELF in spirit. But in reality many linker features depend on
585 // magic section names.
586 StringRef S = Sec->Name;
587 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
588 S == ".eh_frame" || S == ".openbsd.randomdata";
591 // We compute a rank for each section. The rank indicates where the
592 // section should be placed in the file. Instead of using simple
593 // numbers (0,1,2...), we use a series of flags. One for each decision
594 // point when placing the section.
595 // Using flags has two key properties:
596 // * It is easy to check if a give branch was taken.
597 // * It is easy two see how similar two ranks are (see getRankProximity).
599 RF_NOT_ADDR_SET = 1 << 16,
600 RF_NOT_INTERP = 1 << 15,
601 RF_NOT_ALLOC = 1 << 14,
603 RF_EXEC_WRITE = 1 << 12,
605 RF_NON_TLS_BSS = 1 << 10,
606 RF_NON_TLS_BSS_RO = 1 << 9,
609 RF_PPC_NOT_TOCBSS = 1 << 6,
611 RF_PPC_TOCL = 1 << 4,
613 RF_PPC_BRANCH_LT = 1 << 2,
614 RF_MIPS_GPREL = 1 << 1,
615 RF_MIPS_NOT_GOT = 1 << 0
618 static unsigned getSectionRank(const OutputSection *Sec) {
621 // We want to put section specified by -T option first, so we
622 // can start assigning VA starting from them later.
623 if (Config->SectionStartMap.count(Sec->Name))
625 Rank |= RF_NOT_ADDR_SET;
627 // Put .interp first because some loaders want to see that section
628 // on the first page of the executable file when loaded into memory.
629 if (Sec->Name == ".interp")
631 Rank |= RF_NOT_INTERP;
633 // Allocatable sections go first to reduce the total PT_LOAD size and
634 // so debug info doesn't change addresses in actual code.
635 if (!(Sec->Flags & SHF_ALLOC))
636 return Rank | RF_NOT_ALLOC;
638 // Sort sections based on their access permission in the following
639 // order: R, RX, RWX, RW. This order is based on the following
641 // * Read-only sections come first such that they go in the
642 // PT_LOAD covering the program headers at the start of the file.
643 // * Read-only, executable sections come next, unless the
644 // -no-rosegment option is used.
645 // * Writable, executable sections follow such that .plt on
646 // architectures where it needs to be writable will be placed
647 // between .text and .data.
648 // * Writable sections come last, such that .bss lands at the very
649 // end of the last PT_LOAD.
650 bool IsExec = Sec->Flags & SHF_EXECINSTR;
651 bool IsWrite = Sec->Flags & SHF_WRITE;
655 Rank |= RF_EXEC_WRITE;
656 else if (!Config->SingleRoRx)
663 // If we got here we know that both A and B are in the same PT_LOAD.
665 bool IsTls = Sec->Flags & SHF_TLS;
666 bool IsNoBits = Sec->Type == SHT_NOBITS;
668 // The first requirement we have is to put (non-TLS) nobits sections last. The
669 // reason is that the only thing the dynamic linker will see about them is a
670 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
671 // PT_LOAD, so that has to correspond to the nobits sections.
672 bool IsNonTlsNoBits = IsNoBits && !IsTls;
674 Rank |= RF_NON_TLS_BSS;
676 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
677 // sections after r/w ones, so that the RelRo sections are contiguous.
678 bool IsRelRo = isRelroSection(Sec);
679 if (IsNonTlsNoBits && !IsRelRo)
680 Rank |= RF_NON_TLS_BSS_RO;
681 if (!IsNonTlsNoBits && IsRelRo)
682 Rank |= RF_NON_TLS_BSS_RO;
684 // The TLS initialization block needs to be a single contiguous block in a R/W
685 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
686 // sections. The TLS NOBITS sections are placed here as they don't take up
687 // virtual address space in the PT_LOAD.
691 // Within the TLS initialization block, the non-nobits sections need to appear
696 // // Some architectures have additional ordering restrictions for sections
697 // // within the same PT_LOAD.
698 if (Config->EMachine == EM_PPC64) {
699 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
700 // that we would like to make sure appear is a specific order to maximize
701 // their coverage by a single signed 16-bit offset from the TOC base
702 // pointer. Conversely, the special .tocbss section should be first among
703 // all SHT_NOBITS sections. This will put it next to the loaded special
704 // PPC64 sections (and, thus, within reach of the TOC base pointer).
705 StringRef Name = Sec->Name;
706 if (Name != ".tocbss")
707 Rank |= RF_PPC_NOT_TOCBSS;
718 if (Name == ".branch_lt")
719 Rank |= RF_PPC_BRANCH_LT;
721 if (Config->EMachine == EM_MIPS) {
722 // All sections with SHF_MIPS_GPREL flag should be grouped together
723 // because data in these sections is addressable with a gp relative address.
724 if (Sec->Flags & SHF_MIPS_GPREL)
725 Rank |= RF_MIPS_GPREL;
727 if (Sec->Name != ".got")
728 Rank |= RF_MIPS_NOT_GOT;
734 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
735 const OutputSection *A = cast<OutputSectionCommand>(ACmd)->Sec;
736 const OutputSection *B = cast<OutputSectionCommand>(BCmd)->Sec;
737 if (A->SortRank != B->SortRank)
738 return A->SortRank < B->SortRank;
739 if (!(A->SortRank & RF_NOT_ADDR_SET))
740 return Config->SectionStartMap.lookup(A->Name) <
741 Config->SectionStartMap.lookup(B->Name);
745 void PhdrEntry::add(OutputSection *Sec) {
749 p_align = std::max(p_align, Sec->Alignment);
750 if (p_type == PT_LOAD)
751 Sec->FirstInPtLoad = First;
754 template <class ELFT>
755 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
756 uint8_t StOther = STV_HIDDEN,
757 uint8_t Binding = STB_WEAK) {
758 // The linker generated symbols are added as STB_WEAK to allow user defined
759 // ones to override them.
760 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
761 /*Size=*/0, Binding, Sec,
765 template <class ELFT>
766 static DefinedRegular *
767 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
768 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
769 SymbolBody *S = Symtab<ELFT>::X->find(Name);
772 if (S->isInCurrentDSO())
774 return cast<DefinedRegular>(
775 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
778 // The beginning and the ending of .rel[a].plt section are marked
779 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
780 // executable. The runtime needs these symbols in order to resolve
781 // all IRELATIVE relocs on startup. For dynamic executables, we don't
782 // need these symbols, since IRELATIVE relocs are resolved through GOT
783 // and PLT. For details, see http://www.airs.com/blog/archives/403.
784 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
787 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
788 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
790 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
791 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
794 // The linker is expected to define some symbols depending on
795 // the linking result. This function defines such symbols.
796 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
797 if (Config->EMachine == EM_MIPS) {
798 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
799 // so that it points to an absolute address which by default is relative
800 // to GOT. Default offset is 0x7ff0.
801 // See "Global Data Symbols" in Chapter 6 in the following document:
802 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
803 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
805 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
806 // start of function and 'gp' pointer into GOT.
807 if (Symtab<ELFT>::X->find("_gp_disp"))
809 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
811 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
812 // pointer. This symbol is used in the code generated by .cpload pseudo-op
813 // in case of using -mno-shared option.
814 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
815 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
816 ElfSym::MipsLocalGp =
817 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
820 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
821 // be at some offset from the base of the .got section, usually 0 or the end
823 InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
824 : cast<InputSection>(InX::Got);
825 ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
826 "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
828 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
829 // static linking the linker is required to optimize away any references to
830 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
831 // to avoid the undefined symbol error.
833 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
835 // __ehdr_start is the location of ELF file headers. Note that we define
836 // this symbol unconditionally even when using a linker script, which
837 // differs from the behavior implemented by GNU linker which only define
838 // this symbol if ELF headers are in the memory mapped segment.
839 // __executable_start is not documented, but the expectation of at
840 // least the android libc is that it points to the elf header too.
841 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
842 // each DSO. The address of the symbol doesn't matter as long as they are
843 // different in different DSOs, so we chose the start address of the DSO.
844 for (const char *Name :
845 {"__ehdr_start", "__executable_start", "__dso_handle"})
846 addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
848 // If linker script do layout we do not need to create any standart symbols.
849 if (Script->Opt.HasSections)
852 auto Add = [](StringRef S) {
853 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
856 ElfSym::Bss = Add("__bss_start");
857 ElfSym::End1 = Add("end");
858 ElfSym::End2 = Add("_end");
859 ElfSym::Etext1 = Add("etext");
860 ElfSym::Etext2 = Add("_etext");
861 ElfSym::Edata1 = Add("edata");
862 ElfSym::Edata2 = Add("_edata");
865 // Sort input sections by section name suffixes for
866 // __attribute__((init_priority(N))).
867 static void sortInitFini(OutputSection *S) {
869 reinterpret_cast<OutputSection *>(S)->sortInitFini();
872 // Sort input sections by the special rule for .ctors and .dtors.
873 static void sortCtorsDtors(OutputSection *S) {
875 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
878 // Sort input sections using the list provided by --symbol-ordering-file.
879 template <class ELFT>
880 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
881 if (Config->SymbolOrderingFile.empty())
884 // Build a map from symbols to their priorities. Symbols that didn't
885 // appear in the symbol ordering file have the lowest priority 0.
886 // All explicitly mentioned symbols have negative (higher) priorities.
887 DenseMap<StringRef, int> SymbolOrder;
888 int Priority = -Config->SymbolOrderingFile.size();
889 for (StringRef S : Config->SymbolOrderingFile)
890 SymbolOrder.insert({S, Priority++});
892 // Build a map from sections to their priorities.
893 DenseMap<SectionBase *, int> SectionOrder;
894 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
895 for (SymbolBody *Body : File->getSymbols()) {
896 auto *D = dyn_cast<DefinedRegular>(Body);
897 if (!D || !D->Section)
899 int &Priority = SectionOrder[D->Section];
900 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
904 // Sort sections by priority.
905 for (OutputSection *Base : OutputSections)
906 if (auto *Sec = dyn_cast<OutputSection>(Base))
907 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
910 template <class ELFT>
911 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
912 for (InputSectionBase *IS : InputSections) {
915 // Scan all relocations. Each relocation goes through a series
916 // of tests to determine if it needs special treatment, such as
917 // creating GOT, PLT, copy relocations, etc.
918 // Note that relocations for non-alloc sections are directly
919 // processed by InputSection::relocateNonAlloc.
920 if (!(IS->Flags & SHF_ALLOC))
922 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
926 if (!Config->Relocatable) {
927 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
932 template <class ELFT> void Writer<ELFT>::createSections() {
933 for (InputSectionBase *IS : InputSections)
935 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
937 sortBySymbolsOrder<ELFT>(OutputSections);
938 sortInitFini(findSection(".init_array"));
939 sortInitFini(findSection(".fini_array"));
940 sortCtorsDtors(findSection(".ctors"));
941 sortCtorsDtors(findSection(".dtors"));
944 // We want to find how similar two ranks are.
945 // The more branches in getSectionRank that match, the more similar they are.
946 // Since each branch corresponds to a bit flag, we can just use
947 // countLeadingZeros.
948 static int getRankProximity(OutputSection *A, OutputSection *B) {
949 return countLeadingZeros(A->SortRank ^ B->SortRank);
952 static int getRankProximity(OutputSection *A, BaseCommand *B) {
953 if (auto *Cmd = dyn_cast<OutputSectionCommand>(B))
955 return getRankProximity(A, Cmd->Sec);
959 // When placing orphan sections, we want to place them after symbol assignments
960 // so that an orphan after
964 // doesn't break the intended meaning of the begin/end symbols.
965 // We don't want to go over sections since findOrphanPos is the
966 // one in charge of deciding the order of the sections.
967 // We don't want to go over changes to '.', since doing so in
968 // rx_sec : { *(rx_sec) }
969 // . = ALIGN(0x1000);
970 // /* The RW PT_LOAD starts here*/
971 // rw_sec : { *(rw_sec) }
972 // would mean that the RW PT_LOAD would become unaligned.
973 static bool shouldSkip(BaseCommand *Cmd) {
974 if (isa<OutputSectionCommand>(Cmd))
976 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
977 return Assign->Name != ".";
981 // We want to place orphan sections so that they share as much
982 // characteristics with their neighbors as possible. For example, if
983 // both are rw, or both are tls.
984 template <typename ELFT>
985 static std::vector<BaseCommand *>::iterator
986 findOrphanPos(std::vector<BaseCommand *>::iterator B,
987 std::vector<BaseCommand *>::iterator E) {
988 OutputSection *Sec = cast<OutputSectionCommand>(*E)->Sec;
990 // Find the first element that has as close a rank as possible.
991 auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
992 return getRankProximity(Sec, A) < getRankProximity(Sec, B);
997 // Consider all existing sections with the same proximity.
998 int Proximity = getRankProximity(Sec, *I);
999 for (; I != E; ++I) {
1000 auto *Cmd = dyn_cast<OutputSectionCommand>(*I);
1001 if (!Cmd || !Cmd->Sec)
1003 if (getRankProximity(Sec, Cmd->Sec) != Proximity ||
1004 Sec->SortRank < Cmd->Sec->SortRank)
1007 auto J = std::find_if(
1008 llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1009 [](BaseCommand *Cmd) { return isa<OutputSectionCommand>(Cmd); });
1011 while (I != E && shouldSkip(*I))
1016 template <class ELFT> void Writer<ELFT>::sortSections() {
1017 if (Script->Opt.HasSections)
1018 Script->adjustSectionsBeforeSorting();
1020 // Don't sort if using -r. It is not necessary and we want to preserve the
1021 // relative order for SHF_LINK_ORDER sections.
1022 if (Config->Relocatable)
1025 for (BaseCommand *Base : Script->Opt.Commands)
1026 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1027 if (OutputSection *Sec = Cmd->Sec)
1028 Sec->SortRank = getSectionRank(Sec);
1030 if (!Script->Opt.HasSections) {
1031 // We know that all the OutputSectionCommands are contiguous in
1033 auto E = Script->Opt.Commands.end();
1034 auto I = Script->Opt.Commands.begin();
1035 auto IsSection = [](BaseCommand *Base) {
1036 return isa<OutputSectionCommand>(Base);
1038 I = std::find_if(I, E, IsSection);
1039 E = std::find_if(llvm::make_reverse_iterator(E),
1040 llvm::make_reverse_iterator(I), IsSection)
1042 std::stable_sort(I, E, compareSections);
1046 // Orphan sections are sections present in the input files which are
1047 // not explicitly placed into the output file by the linker script.
1049 // The sections in the linker script are already in the correct
1050 // order. We have to figuere out where to insert the orphan
1053 // The order of the sections in the script is arbitrary and may not agree with
1054 // compareSections. This means that we cannot easily define a strict weak
1055 // ordering. To see why, consider a comparison of a section in the script and
1056 // one not in the script. We have a two simple options:
1057 // * Make them equivalent (a is not less than b, and b is not less than a).
1058 // The problem is then that equivalence has to be transitive and we can
1059 // have sections a, b and c with only b in a script and a less than c
1060 // which breaks this property.
1061 // * Use compareSectionsNonScript. Given that the script order doesn't have
1062 // to match, we can end up with sections a, b, c, d where b and c are in the
1063 // script and c is compareSectionsNonScript less than b. In which case d
1064 // can be equivalent to c, a to b and d < a. As a concrete example:
1065 // .a (rx) # not in script
1066 // .b (rx) # in script
1067 // .c (ro) # in script
1068 // .d (ro) # not in script
1070 // The way we define an order then is:
1071 // * Sort only the orphan sections. They are in the end right now.
1072 // * Move each orphan section to its preferred position. We try
1073 // to put each section in the last position where it it can share
1076 // There is some ambiguity as to where exactly a new entry should be
1077 // inserted, because Opt.Commands contains not only output section
1078 // commands but also other types of commands such as symbol assignment
1079 // expressions. There's no correct answer here due to the lack of the
1080 // formal specification of the linker script. We use heuristics to
1081 // determine whether a new output command should be added before or
1082 // after another commands. For the details, look at shouldSkip
1085 auto I = Script->Opt.Commands.begin();
1086 auto E = Script->Opt.Commands.end();
1087 auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1088 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1089 return Cmd->Sec && Cmd->Sec->SectionIndex == INT_MAX;
1093 // Sort the orphan sections.
1094 std::stable_sort(NonScriptI, E, compareSections);
1096 // As a horrible special case, skip the first . assignment if it is before any
1097 // section. We do this because it is common to set a load address by starting
1098 // the script with ". = 0xabcd" and the expectation is that every section is
1100 auto FirstSectionOrDotAssignment =
1101 std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1102 if (FirstSectionOrDotAssignment != E &&
1103 isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1104 ++FirstSectionOrDotAssignment;
1105 I = FirstSectionOrDotAssignment;
1107 while (NonScriptI != E) {
1108 auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1109 OutputSection *Orphan = cast<OutputSectionCommand>(*NonScriptI)->Sec;
1111 // As an optimization, find all sections with the same sort rank
1112 // and insert them with one rotate.
1113 unsigned Rank = Orphan->SortRank;
1114 auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1115 return cast<OutputSectionCommand>(Cmd)->Sec->SortRank != Rank;
1117 std::rotate(Pos, NonScriptI, End);
1121 Script->adjustSectionsAfterSorting();
1124 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1125 std::function<void(SyntheticSection *)> Fn) {
1126 for (SyntheticSection *SS : Sections)
1127 if (SS && SS->getParent() && !SS->empty())
1131 // We need to add input synthetic sections early in createSyntheticSections()
1132 // to make them visible from linkescript side. But not all sections are always
1133 // required to be in output. For example we don't need dynamic section content
1134 // sometimes. This function filters out such unused sections from the output.
1135 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1136 // All input synthetic sections that can be empty are placed after
1137 // all regular ones. We iterate over them all and exit at first
1139 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1140 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1143 OutputSection *OS = SS->getParent();
1144 if (!SS->empty() || !OS)
1146 if ((SS == InX::Got || SS == InX::MipsGot) && ElfSym::GlobalOffsetTable)
1148 OS->Sections.erase(std::find(OS->Sections.begin(), OS->Sections.end(), SS));
1150 // If there are no other sections in the output section, remove it from the
1152 if (OS->Sections.empty()) {
1153 V.erase(std::find(V.begin(), V.end(), OS));
1154 // Also remove script commands matching the output section.
1155 auto &Cmds = Script->Opt.Commands;
1156 auto I = std::remove_if(Cmds.begin(), Cmds.end(), [&](BaseCommand *Cmd) {
1157 if (auto *OSCmd = dyn_cast<OutputSectionCommand>(Cmd))
1158 return OSCmd->Sec == OS;
1161 Cmds.erase(I, Cmds.end());
1166 // Create output section objects and add them to OutputSections.
1167 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1168 Out::DebugInfo = findSection(".debug_info");
1169 Out::PreinitArray = findSection(".preinit_array");
1170 Out::InitArray = findSection(".init_array");
1171 Out::FiniArray = findSection(".fini_array");
1173 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1174 // symbols for sections, so that the runtime can get the start and end
1175 // addresses of each section by section name. Add such symbols.
1176 if (!Config->Relocatable) {
1177 addStartEndSymbols();
1178 for (OutputSection *Sec : OutputSections)
1179 addStartStopSymbols(Sec);
1182 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1183 // It should be okay as no one seems to care about the type.
1184 // Even the author of gold doesn't remember why gold behaves that way.
1185 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1187 addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1189 // Define __rel[a]_iplt_{start,end} symbols if needed.
1190 addRelIpltSymbols();
1192 // This responsible for splitting up .eh_frame section into
1193 // pieces. The relocation scan uses those pieces, so this has to be
1195 applySynthetic({In<ELFT>::EhFrame},
1196 [](SyntheticSection *SS) { SS->finalizeContents(); });
1198 // Scan relocations. This must be done after every symbol is declared so that
1199 // we can correctly decide if a dynamic relocation is needed.
1200 forEachRelSec(scanRelocations<ELFT>);
1202 if (InX::Plt && !InX::Plt->empty())
1203 InX::Plt->addSymbols();
1204 if (InX::Iplt && !InX::Iplt->empty())
1205 InX::Iplt->addSymbols();
1207 // Now that we have defined all possible global symbols including linker-
1208 // synthesized ones. Visit all symbols to give the finishing touches.
1209 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1210 SymbolBody *Body = S->body();
1212 if (!includeInSymtab(*Body))
1215 InX::SymTab->addSymbol(Body);
1217 if (InX::DynSymTab && S->includeInDynsym()) {
1218 InX::DynSymTab->addSymbol(Body);
1219 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1220 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1221 In<ELFT>::VerNeed->addSymbol(SS);
1225 // Do not proceed if there was an undefined symbol.
1229 addPredefinedSections();
1230 removeUnusedSyntheticSections(OutputSections);
1232 clearOutputSections();
1235 // Now that we have the final list, create a list of all the
1236 // OutputSectionCommands for convenience.
1237 for (BaseCommand *Base : Script->Opt.Commands)
1238 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1239 OutputSectionCommands.push_back(Cmd);
1241 // Prefer command line supplied address over other constraints.
1242 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1243 auto I = Config->SectionStartMap.find(Cmd->Name);
1244 if (I != Config->SectionStartMap.end())
1245 Cmd->AddrExpr = [=] { return I->second; };
1248 // This is a bit of a hack. A value of 0 means undef, so we set it
1249 // to 1 t make __ehdr_start defined. The section number is not
1250 // particularly relevant.
1251 Out::ElfHeader->SectionIndex = 1;
1254 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1255 OutputSection *Sec = Cmd->Sec;
1256 Sec->SectionIndex = I++;
1257 Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1260 // Binary and relocatable output does not have PHDRS.
1261 // The headers have to be created before finalize as that can influence the
1262 // image base and the dynamic section on mips includes the image base.
1263 if (!Config->Relocatable && !Config->OFormatBinary) {
1264 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1265 addPtArmExid(Phdrs);
1266 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1269 // Compute the size of .rela.dyn and .rela.plt early since we need
1270 // them to populate .dynamic.
1271 for (SyntheticSection *SS : {In<ELFT>::RelaDyn, In<ELFT>::RelaPlt})
1272 if (SS->getParent() && !SS->empty())
1273 SS->getParent()->assignOffsets();
1275 // Dynamic section must be the last one in this list and dynamic
1276 // symbol table section (DynSymTab) must be the first one.
1277 applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo,
1278 InX::GnuHashTab, In<ELFT>::HashTab, InX::SymTab,
1279 InX::ShStrTab, InX::StrTab, In<ELFT>::VerDef,
1280 InX::DynStrTab, InX::GdbIndex, InX::Got,
1281 InX::MipsGot, InX::IgotPlt, InX::GotPlt,
1282 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1283 InX::Plt, InX::Iplt, In<ELFT>::EhFrameHdr,
1284 In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1285 [](SyntheticSection *SS) { SS->finalizeContents(); });
1287 // Some architectures use small displacements for jump instructions.
1288 // It is linker's responsibility to create thunks containing long
1289 // jump instructions if jump targets are too far. Create thunks.
1290 if (Target->NeedsThunks) {
1291 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1293 // do not require address information. To support range extension Thunks
1294 // we need to assign addresses so that we can tell if jump instructions
1295 // are out of range. This will need to turn into a loop that converges
1296 // when no more Thunks are added
1298 if (TC.createThunks(OutputSectionCommands)) {
1299 applySynthetic({InX::MipsGot},
1300 [](SyntheticSection *SS) { SS->updateAllocSize(); });
1301 if (TC.createThunks(OutputSectionCommands))
1302 fatal("All non-range thunks should be created in first call");
1306 // Fill other section headers. The dynamic table is finalized
1307 // at the end because some tags like RELSZ depend on result
1308 // of finalizing other sections.
1309 for (OutputSectionCommand *Cmd : OutputSectionCommands)
1310 Cmd->finalize<ELFT>();
1312 // createThunks may have added local symbols to the static symbol table
1313 applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1314 [](SyntheticSection *SS) { SS->postThunkContents(); });
1317 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1318 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1319 // We have the terminater synthetic section class. Add that at the end.
1320 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1321 if (!OS || OS->Sections.empty() || Config->Relocatable)
1324 auto *Sentinel = make<ARMExidxSentinelSection>();
1325 OS->addSection(Sentinel);
1326 // If there are linker script commands existing at this point then add the
1327 // sentinel to the last of these too.
1328 if (OutputSectionCommand *C = Script->getCmd(OS)) {
1329 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
1330 [](const BaseCommand *Base) {
1331 return isa<InputSectionDescription>(Base);
1333 cast<InputSectionDescription>(*ISD)->Sections.push_back(Sentinel);
1337 // The linker is expected to define SECNAME_start and SECNAME_end
1338 // symbols for a few sections. This function defines them.
1339 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1340 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1341 // These symbols resolve to the image base if the section does not exist.
1342 // A special value -1 indicates end of the section.
1344 addOptionalRegular<ELFT>(Start, OS, 0);
1345 addOptionalRegular<ELFT>(End, OS, -1);
1348 OS = Out::ElfHeader;
1349 addOptionalRegular<ELFT>(Start, OS, 0);
1350 addOptionalRegular<ELFT>(End, OS, 0);
1354 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1355 Define("__init_array_start", "__init_array_end", Out::InitArray);
1356 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1358 if (OutputSection *Sec = findSection(".ARM.exidx"))
1359 Define("__exidx_start", "__exidx_end", Sec);
1362 // If a section name is valid as a C identifier (which is rare because of
1363 // the leading '.'), linkers are expected to define __start_<secname> and
1364 // __stop_<secname> symbols. They are at beginning and end of the section,
1365 // respectively. This is not requested by the ELF standard, but GNU ld and
1366 // gold provide the feature, and used by many programs.
1367 template <class ELFT>
1368 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1369 StringRef S = Sec->Name;
1370 if (!isValidCIdentifier(S))
1372 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1373 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1376 template <class ELFT>
1377 OutputSectionCommand *Writer<ELFT>::findSectionCommand(StringRef Name) {
1378 for (OutputSectionCommand *Cmd : OutputSectionCommands)
1379 if (Cmd->Name == Name)
1384 template <class ELFT> OutputSection *Writer<ELFT>::findSectionInScript(StringRef Name) {
1385 if (OutputSectionCommand *Cmd = findSectionCommand(Name))
1390 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1391 for (OutputSection *Sec : OutputSections)
1392 if (Sec->Name == Name)
1397 static bool needsPtLoad(OutputSection *Sec) {
1398 if (!(Sec->Flags & SHF_ALLOC))
1401 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1402 // responsible for allocating space for them, not the PT_LOAD that
1403 // contains the TLS initialization image.
1404 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1409 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1410 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1411 // RW. This means that there is no alignment in the RO to RX transition and we
1412 // cannot create a PT_LOAD there.
1413 static uint64_t computeFlags(uint64_t Flags) {
1415 return PF_R | PF_W | PF_X;
1416 if (Config->SingleRoRx && !(Flags & PF_W))
1417 return Flags | PF_X;
1421 // Decide which program headers to create and which sections to include in each
1423 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1424 std::vector<PhdrEntry> Ret;
1425 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1426 Ret.emplace_back(Type, Flags);
1430 // The first phdr entry is PT_PHDR which describes the program header itself.
1431 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1433 // PT_INTERP must be the second entry if exists.
1434 if (OutputSection *Sec = findSectionInScript(".interp"))
1435 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1437 // Add the first PT_LOAD segment for regular output sections.
1438 uint64_t Flags = computeFlags(PF_R);
1439 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1441 // Add the headers. We will remove them if they don't fit.
1442 Load->add(Out::ElfHeader);
1443 Load->add(Out::ProgramHeaders);
1445 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1446 OutputSection *Sec = Cmd->Sec;
1447 if (!(Sec->Flags & SHF_ALLOC))
1449 if (!needsPtLoad(Sec))
1452 // Segments are contiguous memory regions that has the same attributes
1453 // (e.g. executable or writable). There is one phdr for each segment.
1454 // Therefore, we need to create a new phdr when the next section has
1455 // different flags or is loaded at a discontiguous address using AT linker
1457 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1458 if (Script->hasLMA(Sec) || Flags != NewFlags) {
1459 Load = AddHdr(PT_LOAD, NewFlags);
1466 // Add a TLS segment if any.
1467 PhdrEntry TlsHdr(PT_TLS, PF_R);
1468 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1469 OutputSection *Sec = Cmd->Sec;
1470 if (Sec->Flags & SHF_TLS)
1474 Ret.push_back(std::move(TlsHdr));
1476 // Add an entry for .dynamic.
1478 AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1479 ->add(InX::Dynamic->getParent());
1481 // PT_GNU_RELRO includes all sections that should be marked as
1482 // read-only by dynamic linker after proccessing relocations.
1483 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1484 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1485 OutputSection *Sec = Cmd->Sec;
1486 if (needsPtLoad(Sec) && isRelroSection(Sec))
1490 Ret.push_back(std::move(RelRo));
1492 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1493 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1494 In<ELFT>::EhFrame->getParent() && In<ELFT>::EhFrameHdr->getParent())
1495 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->getParent()->getPhdrFlags())
1496 ->add(In<ELFT>::EhFrameHdr->getParent());
1498 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1499 // the dynamic linker fill the segment with random data.
1500 if (OutputSection *Sec = findSectionInScript(".openbsd.randomdata"))
1501 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1503 // PT_GNU_STACK is a special section to tell the loader to make the
1504 // pages for the stack non-executable. If you really want an executable
1505 // stack, you can pass -z execstack, but that's not recommended for
1506 // security reasons.
1508 if (Config->ZExecstack)
1509 Perm = PF_R | PF_W | PF_X;
1512 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1514 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1515 // is expected to perform W^X violations, such as calling mprotect(2) or
1516 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1518 if (Config->ZWxneeded)
1519 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1521 // Create one PT_NOTE per a group of contiguous .note sections.
1522 PhdrEntry *Note = nullptr;
1523 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1524 OutputSection *Sec = Cmd->Sec;
1525 if (Sec->Type == SHT_NOTE) {
1526 if (!Note || Script->hasLMA(Sec))
1527 Note = AddHdr(PT_NOTE, PF_R);
1536 template <class ELFT>
1537 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1538 if (Config->EMachine != EM_ARM)
1541 std::find_if(OutputSectionCommands.begin(), OutputSectionCommands.end(),
1542 [](OutputSectionCommand *Cmd) {
1543 return Cmd->Sec->Type == SHT_ARM_EXIDX;
1545 if (I == OutputSectionCommands.end())
1548 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1549 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1550 ARMExidx.add((*I)->Sec);
1551 Phdrs.push_back(ARMExidx);
1554 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1555 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1556 // linker can set the permissions.
1557 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1558 auto PageAlign = [](OutputSection *Sec) {
1559 OutputSectionCommand *Cmd = Script->getCmd(Sec);
1560 if (Cmd && !Cmd->AddrExpr)
1561 Cmd->AddrExpr = [=] {
1562 return alignTo(Script->getDot(), Config->MaxPageSize);
1566 for (const PhdrEntry &P : Phdrs)
1567 if (P.p_type == PT_LOAD && P.First)
1570 for (const PhdrEntry &P : Phdrs) {
1571 if (P.p_type != PT_GNU_RELRO)
1575 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1576 // have to align it to a page.
1577 auto End = OutputSectionCommands.end();
1579 std::find(OutputSectionCommands.begin(), End, Script->getCmd(P.Last));
1580 if (I == End || (I + 1) == End)
1582 OutputSection *Sec = (*(I + 1))->Sec;
1583 if (needsPtLoad(Sec))
1588 // Adjusts the file alignment for a given output section and returns
1589 // its new file offset. The file offset must be the same with its
1590 // virtual address (modulo the page size) so that the loader can load
1591 // executables without any address adjustment.
1592 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1593 OutputSection *First = Sec->FirstInPtLoad;
1594 // If the section is not in a PT_LOAD, we just have to align it.
1596 return alignTo(Off, Sec->Alignment);
1598 // The first section in a PT_LOAD has to have congruent offset and address
1599 // module the page size.
1601 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1603 // If two sections share the same PT_LOAD the file offset is calculated
1604 // using this formula: Off2 = Off1 + (VA2 - VA1).
1605 return First->Offset + Sec->Addr - First->Addr;
1608 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1609 if (Sec->Type == SHT_NOBITS) {
1614 Off = getFileAlignment(Off, Sec);
1616 return Off + Sec->Size;
1619 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1621 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1622 OutputSection *Sec = Cmd->Sec;
1623 if (Sec->Flags & SHF_ALLOC)
1624 Off = setOffset(Sec, Off);
1626 FileSize = alignTo(Off, Config->Wordsize);
1629 // Assign file offsets to output sections.
1630 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1632 Off = setOffset(Out::ElfHeader, Off);
1633 Off = setOffset(Out::ProgramHeaders, Off);
1635 for (OutputSectionCommand *Cmd : OutputSectionCommands)
1636 Off = setOffset(Cmd->Sec, Off);
1638 SectionHeaderOff = alignTo(Off, Config->Wordsize);
1640 SectionHeaderOff + (OutputSectionCommands.size() + 1) * sizeof(Elf_Shdr);
1643 // Finalize the program headers. We call this function after we assign
1644 // file offsets and VAs to all sections.
1645 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1646 for (PhdrEntry &P : Phdrs) {
1647 OutputSection *First = P.First;
1648 OutputSection *Last = P.Last;
1650 P.p_filesz = Last->Offset - First->Offset;
1651 if (Last->Type != SHT_NOBITS)
1652 P.p_filesz += Last->Size;
1653 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1654 P.p_offset = First->Offset;
1655 P.p_vaddr = First->Addr;
1657 P.p_paddr = First->getLMA();
1659 if (P.p_type == PT_LOAD)
1660 P.p_align = Config->MaxPageSize;
1661 else if (P.p_type == PT_GNU_RELRO) {
1663 // The glibc dynamic loader rounds the size down, so we need to round up
1664 // to protect the last page. This is a no-op on FreeBSD which always
1666 P.p_memsz = alignTo(P.p_memsz, Target->PageSize);
1669 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1670 // so round up the size to make sure the offsets are correct.
1671 if (P.p_type == PT_TLS) {
1674 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1679 // The entry point address is chosen in the following ways.
1681 // 1. the '-e' entry command-line option;
1682 // 2. the ENTRY(symbol) command in a linker control script;
1683 // 3. the value of the symbol start, if present;
1684 // 4. the address of the first byte of the .text section, if present;
1685 // 5. the address 0.
1686 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1687 // Case 1, 2 or 3. As a special case, if the symbol is actually
1688 // a number, we'll use that number as an address.
1689 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1692 if (to_integer(Config->Entry, Addr))
1696 if (OutputSection *Sec = findSectionInScript(".text")) {
1697 if (Config->WarnMissingEntry)
1698 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1699 utohexstr(Sec->Addr));
1704 if (Config->WarnMissingEntry)
1705 warn("cannot find entry symbol " + Config->Entry +
1706 "; not setting start address");
1710 static uint16_t getELFType() {
1713 if (Config->Relocatable)
1718 // This function is called after we have assigned address and size
1719 // to each section. This function fixes some predefined
1720 // symbol values that depend on section address and size.
1721 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1722 // _etext is the first location after the last read-only loadable segment.
1723 // _edata is the first location after the last read-write loadable segment.
1724 // _end is the first location after the uninitialized data region.
1725 PhdrEntry *Last = nullptr;
1726 PhdrEntry *LastRO = nullptr;
1727 PhdrEntry *LastRW = nullptr;
1728 for (PhdrEntry &P : Phdrs) {
1729 if (P.p_type != PT_LOAD)
1732 if (P.p_flags & PF_W)
1738 auto Set = [](DefinedRegular *S, OutputSection *Sec, uint64_t Value) {
1746 Set(ElfSym::End1, Last->First, Last->p_memsz);
1747 Set(ElfSym::End2, Last->First, Last->p_memsz);
1750 Set(ElfSym::Etext1, LastRO->First, LastRO->p_filesz);
1751 Set(ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1754 Set(ElfSym::Edata1, LastRW->First, LastRW->p_filesz);
1755 Set(ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1759 ElfSym::Bss->Section = findSectionInScript(".bss");
1761 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1762 // be equal to the _gp symbol's value.
1763 if (Config->EMachine == EM_MIPS && !ElfSym::MipsGp->Value) {
1764 // Find GP-relative section with the lowest address
1765 // and use this address to calculate default _gp value.
1766 for (const OutputSectionCommand *Cmd : OutputSectionCommands) {
1767 OutputSection *OS = Cmd->Sec;
1768 if (OS->Flags & SHF_MIPS_GPREL) {
1769 ElfSym::MipsGp->Value = OS->Addr + 0x7ff0;
1776 template <class ELFT> void Writer<ELFT>::writeHeader() {
1777 uint8_t *Buf = Buffer->getBufferStart();
1778 memcpy(Buf, "\177ELF", 4);
1780 // Write the ELF header.
1781 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1782 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1783 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1784 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1785 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1786 EHdr->e_type = getELFType();
1787 EHdr->e_machine = Config->EMachine;
1788 EHdr->e_version = EV_CURRENT;
1789 EHdr->e_entry = getEntryAddr();
1790 EHdr->e_shoff = SectionHeaderOff;
1791 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1792 EHdr->e_phnum = Phdrs.size();
1793 EHdr->e_shentsize = sizeof(Elf_Shdr);
1794 EHdr->e_shnum = OutputSectionCommands.size() + 1;
1795 EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
1797 if (Config->EMachine == EM_ARM)
1798 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1799 // but we don't have any firm guarantees of conformance. Linux AArch64
1800 // kernels (as of 2016) require an EABI version to be set.
1801 EHdr->e_flags = EF_ARM_EABI_VER5;
1802 else if (Config->EMachine == EM_MIPS)
1803 EHdr->e_flags = getMipsEFlags<ELFT>();
1805 if (!Config->Relocatable) {
1806 EHdr->e_phoff = sizeof(Elf_Ehdr);
1807 EHdr->e_phentsize = sizeof(Elf_Phdr);
1810 // Write the program header table.
1811 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1812 for (PhdrEntry &P : Phdrs) {
1813 HBuf->p_type = P.p_type;
1814 HBuf->p_flags = P.p_flags;
1815 HBuf->p_offset = P.p_offset;
1816 HBuf->p_vaddr = P.p_vaddr;
1817 HBuf->p_paddr = P.p_paddr;
1818 HBuf->p_filesz = P.p_filesz;
1819 HBuf->p_memsz = P.p_memsz;
1820 HBuf->p_align = P.p_align;
1824 // Write the section header table. Note that the first table entry is null.
1825 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1826 for (OutputSectionCommand *Cmd : OutputSectionCommands)
1827 Cmd->Sec->writeHeaderTo<ELFT>(++SHdrs);
1830 // Open a result file.
1831 template <class ELFT> void Writer<ELFT>::openFile() {
1832 if (!Config->Is64 && FileSize > UINT32_MAX) {
1833 error("output file too large: " + Twine(FileSize) + " bytes");
1837 unlinkAsync(Config->OutputFile);
1838 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1839 FileOutputBuffer::create(Config->OutputFile, FileSize,
1840 FileOutputBuffer::F_executable);
1842 if (auto EC = BufferOrErr.getError())
1843 error("failed to open " + Config->OutputFile + ": " + EC.message());
1845 Buffer = std::move(*BufferOrErr);
1848 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1849 uint8_t *Buf = Buffer->getBufferStart();
1850 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1851 OutputSection *Sec = Cmd->Sec;
1852 if (Sec->Flags & SHF_ALLOC)
1853 Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1857 // Write section contents to a mmap'ed file.
1858 template <class ELFT> void Writer<ELFT>::writeSections() {
1859 uint8_t *Buf = Buffer->getBufferStart();
1861 // PPC64 needs to process relocations in the .opd section
1862 // before processing relocations in code-containing sections.
1863 if (auto *OpdCmd = findSectionCommand(".opd")) {
1864 Out::Opd = OpdCmd->Sec;
1865 Out::OpdBuf = Buf + Out::Opd->Offset;
1866 OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1869 OutputSection *EhFrameHdr =
1870 (In<ELFT>::EhFrameHdr && !In<ELFT>::EhFrameHdr->empty())
1871 ? In<ELFT>::EhFrameHdr->getParent()
1874 // In -r or -emit-relocs mode, write the relocation sections first as in
1875 // ELf_Rel targets we might find out that we need to modify the relocated
1876 // section while doing it.
1877 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1878 OutputSection *Sec = Cmd->Sec;
1879 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1880 Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1883 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1884 OutputSection *Sec = Cmd->Sec;
1885 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1886 Sec->Type != SHT_RELA)
1887 Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1890 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1891 // it should be written after .eh_frame is written.
1893 OutputSectionCommand *Cmd = Script->getCmd(EhFrameHdr);
1894 Cmd->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1898 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1899 if (!InX::BuildId || !InX::BuildId->getParent())
1902 // Compute a hash of all sections of the output file.
1903 uint8_t *Start = Buffer->getBufferStart();
1904 uint8_t *End = Start + FileSize;
1905 InX::BuildId->writeBuildId({Start, End});
1908 template void elf::writeResult<ELF32LE>();
1909 template void elf::writeResult<ELF32BE>();
1910 template void elf::writeResult<ELF64LE>();
1911 template void elf::writeResult<ELF64BE>();