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 createSyntheticSections();
50 void copyLocalSymbols();
51 void addSectionSymbols();
52 void addReservedSymbols();
53 void createSections();
54 void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
56 void finalizeSections();
57 void addPredefinedSections();
59 std::vector<PhdrEntry> createPhdrs();
60 void removeEmptyPTLoad();
61 void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
62 void assignFileOffsets();
63 void assignFileOffsetsBinary();
65 void fixSectionAlignments();
66 void fixPredefinedSymbols();
70 void writeSectionsBinary();
73 std::unique_ptr<FileOutputBuffer> Buffer;
75 std::vector<OutputSection *> OutputSections;
76 OutputSectionFactory Factory{OutputSections};
78 void addRelIpltSymbols();
79 void addStartEndSymbols();
80 void addStartStopSymbols(OutputSection *Sec);
81 uint64_t getEntryAddr();
82 OutputSection *findSection(StringRef Name);
84 std::vector<PhdrEntry> Phdrs;
87 uint64_t SectionHeaderOff;
89 } // anonymous namespace
91 StringRef elf::getOutputSectionName(StringRef Name) {
92 if (Config->Relocatable)
95 // If -emit-relocs is given (which is rare), we need to copy
96 // relocation sections to the output. If input section .foo is
97 // output as .bar, we want to rename .rel.foo .rel.bar as well.
98 if (Config->EmitRelocs) {
99 for (StringRef V : {".rel.", ".rela."}) {
100 if (Name.startswith(V)) {
101 StringRef Inner = getOutputSectionName(Name.substr(V.size() - 1));
102 return Saver.save(V.drop_back() + Inner);
108 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
109 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
110 ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
111 StringRef Prefix = V.drop_back();
112 if (Name.startswith(V) || Name == Prefix)
116 // CommonSection is identified as "COMMON" in linker scripts.
117 // By default, it should go to .bss section.
118 if (Name == "COMMON")
121 // ".zdebug_" is a prefix for ZLIB-compressed sections.
122 // Because we decompressed input sections, we want to remove 'z'.
123 if (Name.startswith(".zdebug_"))
124 return Saver.save("." + Name.substr(2));
128 template <class ELFT> static bool needsInterpSection() {
129 return !Symtab<ELFT>::X->getSharedFiles().empty() &&
130 !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
133 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
135 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
136 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
137 if (P.p_type != PT_LOAD)
141 uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
144 Phdrs.erase(I, Phdrs.end());
147 // This function scans over the input sections and creates mergeable
148 // synthetic sections. It removes MergeInputSections from array and
149 // adds new synthetic ones. Each synthetic section is added to the
150 // location of the first input section it replaces.
151 static void combineMergableSections() {
152 std::vector<MergeSyntheticSection *> MergeSections;
153 for (InputSectionBase *&S : InputSections) {
154 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
158 // We do not want to handle sections that are not alive, so just remove
159 // them instead of trying to merge.
163 StringRef OutsecName = getOutputSectionName(MS->Name);
164 uint64_t Flags = MS->Flags & ~(uint64_t)(SHF_GROUP | SHF_COMPRESSED);
165 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
167 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
168 return Sec->Name == OutsecName && Sec->Flags == Flags &&
169 Sec->Alignment == Alignment;
171 if (I == MergeSections.end()) {
172 MergeSyntheticSection *Syn =
173 make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
174 MergeSections.push_back(Syn);
175 I = std::prev(MergeSections.end());
180 (*I)->addSection(MS);
183 std::vector<InputSectionBase *> &V = InputSections;
184 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
187 template <class ELFT> static void combineEhFrameSections() {
188 for (InputSectionBase *&S : InputSections) {
189 EhInputSection *ES = dyn_cast<EhInputSection>(S);
190 if (!ES || !ES->Live)
193 In<ELFT>::EhFrame->addSection(ES);
197 std::vector<InputSectionBase *> &V = InputSections;
198 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
201 // The main function of the writer.
202 template <class ELFT> void Writer<ELFT>::run() {
203 // Create linker-synthesized sections such as .got or .plt.
204 // Such sections are of type input section.
205 createSyntheticSections();
206 combineMergableSections();
208 if (!Config->Relocatable)
209 combineEhFrameSections<ELFT>();
211 // We need to create some reserved symbols such as _end. Create them.
212 if (!Config->Relocatable)
213 addReservedSymbols();
215 // Create output sections.
216 Script->OutputSections = &OutputSections;
217 if (Script->Opt.HasSections) {
218 // If linker script contains SECTIONS commands, let it create sections.
219 Script->processCommands(Factory);
221 // Linker scripts may have left some input sections unassigned.
222 // Assign such sections using the default rule.
223 Script->addOrphanSections(Factory);
225 // If linker script does not contain SECTIONS commands, create
226 // output sections by default rules. We still need to give the
227 // linker script a chance to run, because it might contain
228 // non-SECTIONS commands such as ASSERT.
230 Script->processCommands(Factory);
233 if (Config->Discard != DiscardPolicy::All)
236 if (Config->CopyRelocs)
239 // Now that we have a complete set of output sections. This function
240 // completes section contents. For example, we need to add strings
241 // to the string table, and add entries to .got and .plt.
242 // finalizeSections does that.
247 if (Config->Relocatable) {
250 if (!Script->Opt.HasSections) {
251 fixSectionAlignments();
252 Script->fabricateDefaultCommands();
254 Script->synchronize();
255 Script->assignAddresses(Phdrs);
257 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
258 // 0 sized region. This has to be done late since only after assignAddresses
259 // we know the size of the sections.
262 if (!Config->OFormatBinary)
265 assignFileOffsetsBinary();
268 fixPredefinedSymbols();
271 // It does not make sense try to open the file if we have error already.
274 // Write the result down to a file.
278 if (!Config->OFormatBinary) {
282 writeSectionsBinary();
285 // Backfill .note.gnu.build-id section content. This is done at last
286 // because the content is usually a hash value of the entire output file.
291 // Clear the OutputSections to make sure it is not used anymore. Any
292 // code from this point on should be using the linker script
294 OutputSections.clear();
296 // Handle -Map option.
297 writeMapFile<ELFT>(Script->Opt.Commands);
301 if (auto EC = Buffer->commit())
302 error("failed to write to the output file: " + EC.message());
304 // Flush the output streams and exit immediately. A full shutdown
305 // is a good test that we are keeping track of all allocated memory,
306 // but actually freeing it is a waste of time in a regular linker run.
307 if (Config->ExitEarly)
311 // Initialize Out members.
312 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
313 // Initialize all pointers with NULL. This is needed because
314 // you can call lld::elf::main more than once as a library.
315 memset(&Out::First, 0, sizeof(Out));
317 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
319 InX::DynStrTab = make<StringTableSection>(".dynstr", true);
320 InX::Dynamic = make<DynamicSection<ELFT>>();
321 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
322 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
323 InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
325 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
326 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
327 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
328 Out::ProgramHeaders->updateAlignment(Config->Wordsize);
330 if (needsInterpSection<ELFT>()) {
331 InX::Interp = createInterpSection();
334 InX::Interp = nullptr;
337 if (!Config->Relocatable)
338 Add(createCommentSection<ELFT>());
340 if (Config->Strip != StripPolicy::All) {
341 InX::StrTab = make<StringTableSection>(".strtab", false);
342 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
345 if (Config->BuildId != BuildIdKind::None) {
346 InX::BuildId = make<BuildIdSection>();
350 InX::Common = createCommonSection<ELFT>();
354 InX::Bss = make<BssSection>(".bss");
356 InX::BssRelRo = make<BssSection>(".bss.rel.ro");
359 // Add MIPS-specific sections.
360 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
361 Config->Pic || Config->ExportDynamic;
362 if (Config->EMachine == EM_MIPS) {
363 if (!Config->Shared && HasDynSymTab) {
364 InX::MipsRldMap = make<MipsRldMapSection>();
365 Add(InX::MipsRldMap);
367 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
369 if (auto *Sec = MipsOptionsSection<ELFT>::create())
371 if (auto *Sec = MipsReginfoSection<ELFT>::create())
376 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
379 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
380 Add(In<ELFT>::VerSym);
382 if (!Config->VersionDefinitions.empty()) {
383 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
384 Add(In<ELFT>::VerDef);
387 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
388 Add(In<ELFT>::VerNeed);
390 if (Config->GnuHash) {
391 InX::GnuHashTab = make<GnuHashTableSection>();
392 Add(InX::GnuHashTab);
395 if (Config->SysvHash) {
396 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
397 Add(In<ELFT>::HashTab);
402 Add(In<ELFT>::RelaDyn);
405 // Add .got. MIPS' .got is so different from the other archs,
406 // it has its own class.
407 if (Config->EMachine == EM_MIPS) {
408 InX::MipsGot = make<MipsGotSection>();
411 InX::Got = make<GotSection>();
415 InX::GotPlt = make<GotPltSection>();
417 InX::IgotPlt = make<IgotPltSection>();
420 if (Config->GdbIndex) {
421 InX::GdbIndex = make<GdbIndexSection>();
425 // We always need to add rel[a].plt to output if it has entries.
426 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
427 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
428 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
429 Add(In<ELFT>::RelaPlt);
431 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
432 // that the IRelative relocations are processed last by the dynamic loader
433 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
434 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
436 Add(In<ELFT>::RelaIplt);
438 InX::Plt = make<PltSection>(Target->PltHeaderSize);
440 InX::Iplt = make<PltSection>(0);
443 if (!Config->Relocatable) {
444 if (Config->EhFrameHdr) {
445 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
446 Add(In<ELFT>::EhFrameHdr);
448 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
449 Add(In<ELFT>::EhFrame);
459 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
460 const SymbolBody &B) {
461 if (B.isFile() || B.isSection())
464 // If sym references a section in a discarded group, don't keep it.
465 if (Sec == &InputSection::Discarded)
468 if (Config->Discard == DiscardPolicy::None)
471 // In ELF assembly .L symbols are normally discarded by the assembler.
472 // If the assembler fails to do so, the linker discards them if
473 // * --discard-locals is used.
474 // * The symbol is in a SHF_MERGE section, which is normally the reason for
475 // the assembler keeping the .L symbol.
476 if (!SymName.startswith(".L") && !SymName.empty())
479 if (Config->Discard == DiscardPolicy::Locals)
482 return !Sec || !(Sec->Flags & SHF_MERGE);
485 static bool includeInSymtab(const SymbolBody &B) {
486 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
489 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
490 // Always include absolute symbols.
491 SectionBase *Sec = D->Section;
494 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
496 IS = cast<InputSectionBase>(Sec);
497 // Exclude symbols pointing to garbage-collected sections.
501 if (auto *S = dyn_cast<MergeInputSection>(Sec))
502 if (!S->getSectionPiece(D->Value)->Live)
508 // Local symbols are not in the linker's symbol table. This function scans
509 // each object file's symbol table to copy local symbols to the output.
510 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
513 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
514 for (SymbolBody *B : F->getLocalSymbols()) {
517 ": broken object: getLocalSymbols returns a non-local symbol");
518 auto *DR = dyn_cast<DefinedRegular>(B);
520 // No reason to keep local undefined symbol in symtab.
523 if (!includeInSymtab(*B))
526 SectionBase *Sec = DR->Section;
527 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
529 InX::SymTab->addSymbol(B);
534 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
535 // Create one STT_SECTION symbol for each output section we might
536 // have a relocation with.
537 for (OutputSection *Sec : OutputSections) {
538 if (Sec->Sections.empty())
541 InputSection *IS = Sec->Sections[0];
542 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
543 IS->Type == SHT_RELA)
547 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
548 /*Value=*/0, /*Size=*/0, IS, nullptr);
549 InX::SymTab->addSymbol(Sym);
553 // Today's loaders have a feature to make segments read-only after
554 // processing dynamic relocations to enhance security. PT_GNU_RELRO
555 // is defined for that.
557 // This function returns true if a section needs to be put into a
558 // PT_GNU_RELRO segment.
559 bool elf::isRelroSection(const OutputSection *Sec) {
563 uint64_t Flags = Sec->Flags;
565 // Non-allocatable or non-writable sections don't need RELRO because
566 // they are not writable or not even mapped to memory in the first place.
567 // RELRO is for sections that are essentially read-only but need to
568 // be writable only at process startup to allow dynamic linker to
569 // apply relocations.
570 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
573 // Once initialized, TLS data segments are used as data templates
574 // for a thread-local storage. For each new thread, runtime
575 // allocates memory for a TLS and copy templates there. No thread
576 // are supposed to use templates directly. Thus, it can be in RELRO.
580 // .init_array, .preinit_array and .fini_array contain pointers to
581 // functions that are executed on process startup or exit. These
582 // pointers are set by the static linker, and they are not expected
583 // to change at runtime. But if you are an attacker, you could do
584 // interesting things by manipulating pointers in .fini_array, for
585 // example. So they are put into RELRO.
586 uint32_t Type = Sec->Type;
587 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
588 Type == SHT_PREINIT_ARRAY)
591 // .got contains pointers to external symbols. They are resolved by
592 // the dynamic linker when a module is loaded into memory, and after
593 // that they are not expected to change. So, it can be in RELRO.
594 if (InX::Got && Sec == InX::Got->OutSec)
597 // .got.plt contains pointers to external function symbols. They are
598 // by default resolved lazily, so we usually cannot put it into RELRO.
599 // However, if "-z now" is given, the lazy symbol resolution is
600 // disabled, which enables us to put it into RELRO.
601 if (Sec == InX::GotPlt->OutSec)
604 // .dynamic section contains data for the dynamic linker, and
605 // there's no need to write to it at runtime, so it's better to put
607 if (Sec == InX::Dynamic->OutSec)
610 // .bss.rel.ro is used for copy relocations for read-only symbols.
611 // Since the dynamic linker needs to process copy relocations, the
612 // section cannot be read-only, but once initialized, they shouldn't
614 if (Sec == InX::BssRelRo->OutSec)
617 // Sections with some special names are put into RELRO. This is a
618 // bit unfortunate because section names shouldn't be significant in
619 // ELF in spirit. But in reality many linker features depend on
620 // magic section names.
621 StringRef S = Sec->Name;
622 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
623 S == ".eh_frame" || S == ".openbsd.randomdata";
626 // We compute a rank for each section. The rank indicates where the
627 // section should be placed in the file. Instead of using simple
628 // numbers (0,1,2...), we use a series of flags. One for each decision
629 // point when placing the section.
630 // Using flags has two key properties:
631 // * It is easy to check if a give branch was taken.
632 // * It is easy two see how similar two ranks are (see getRankProximity).
634 RF_NOT_ADDR_SET = 1 << 15,
635 RF_NOT_INTERP = 1 << 14,
636 RF_NOT_ALLOC = 1 << 13,
639 RF_NON_TLS_BSS = 1 << 10,
640 RF_NON_TLS_BSS_RO = 1 << 9,
643 RF_PPC_NOT_TOCBSS = 1 << 6,
645 RF_PPC_TOCL = 1 << 4,
647 RF_PPC_BRANCH_LT = 1 << 2,
648 RF_MIPS_GPREL = 1 << 1,
649 RF_MIPS_NOT_GOT = 1 << 0
652 static unsigned getSectionRank(const OutputSection *Sec) {
655 // We want to put section specified by -T option first, so we
656 // can start assigning VA starting from them later.
657 if (Config->SectionStartMap.count(Sec->Name))
659 Rank |= RF_NOT_ADDR_SET;
661 // Put .interp first because some loaders want to see that section
662 // on the first page of the executable file when loaded into memory.
663 if (Sec->Name == ".interp")
665 Rank |= RF_NOT_INTERP;
667 // Allocatable sections go first to reduce the total PT_LOAD size and
668 // so debug info doesn't change addresses in actual code.
669 if (!(Sec->Flags & SHF_ALLOC))
670 return Rank | RF_NOT_ALLOC;
672 // We want the read only sections first so that they go in the PT_LOAD
673 // covering the program headers at the start of the file.
674 if (Sec->Flags & SHF_WRITE)
677 if (Sec->Flags & SHF_EXECINSTR) {
678 // For a corresponding reason, put non exec sections first (the program
679 // header PT_LOAD is not executable).
680 // We only do that if we are not using linker scripts, since with linker
681 // scripts ro and rx sections are in the same PT_LOAD, so their relative
682 // order is not important. The same applies for -no-rosegment.
683 if ((Rank & RF_WRITE) || !Config->SingleRoRx)
687 // If we got here we know that both A and B are in the same PT_LOAD.
689 bool IsTls = Sec->Flags & SHF_TLS;
690 bool IsNoBits = Sec->Type == SHT_NOBITS;
692 // The first requirement we have is to put (non-TLS) nobits sections last. The
693 // reason is that the only thing the dynamic linker will see about them is a
694 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
695 // PT_LOAD, so that has to correspond to the nobits sections.
696 bool IsNonTlsNoBits = IsNoBits && !IsTls;
698 Rank |= RF_NON_TLS_BSS;
700 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
701 // sections after r/w ones, so that the RelRo sections are contiguous.
702 bool IsRelRo = isRelroSection(Sec);
703 if (IsNonTlsNoBits && !IsRelRo)
704 Rank |= RF_NON_TLS_BSS_RO;
705 if (!IsNonTlsNoBits && IsRelRo)
706 Rank |= RF_NON_TLS_BSS_RO;
708 // The TLS initialization block needs to be a single contiguous block in a R/W
709 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
710 // sections. The TLS NOBITS sections are placed here as they don't take up
711 // virtual address space in the PT_LOAD.
715 // Within the TLS initialization block, the non-nobits sections need to appear
720 // // Some architectures have additional ordering restrictions for sections
721 // // within the same PT_LOAD.
722 if (Config->EMachine == EM_PPC64) {
723 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
724 // that we would like to make sure appear is a specific order to maximize
725 // their coverage by a single signed 16-bit offset from the TOC base
726 // pointer. Conversely, the special .tocbss section should be first among
727 // all SHT_NOBITS sections. This will put it next to the loaded special
728 // PPC64 sections (and, thus, within reach of the TOC base pointer).
729 StringRef Name = Sec->Name;
730 if (Name != ".tocbss")
731 Rank |= RF_PPC_NOT_TOCBSS;
742 if (Name == ".branch_lt")
743 Rank |= RF_PPC_BRANCH_LT;
745 if (Config->EMachine == EM_MIPS) {
746 // All sections with SHF_MIPS_GPREL flag should be grouped together
747 // because data in these sections is addressable with a gp relative address.
748 if (Sec->Flags & SHF_MIPS_GPREL)
749 Rank |= RF_MIPS_GPREL;
751 if (Sec->Name != ".got")
752 Rank |= RF_MIPS_NOT_GOT;
758 static bool compareSectionsNonScript(const OutputSection *A,
759 const OutputSection *B) {
760 if (A->SortRank != B->SortRank)
761 return A->SortRank < B->SortRank;
762 if (!(A->SortRank & RF_NOT_ADDR_SET))
763 return Config->SectionStartMap.lookup(A->Name) <
764 Config->SectionStartMap.lookup(B->Name);
768 // Output section ordering is determined by this function.
769 static bool compareSections(const OutputSection *A, const OutputSection *B) {
770 // For now, put sections mentioned in a linker script
771 // first. Sections not on linker script will have a SectionIndex of
773 int AIndex = A->SectionIndex;
774 int BIndex = B->SectionIndex;
775 if (AIndex != BIndex)
776 return AIndex < BIndex;
778 return compareSectionsNonScript(A, B);
781 // Program header entry
782 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
787 void PhdrEntry::add(OutputSection *Sec) {
791 p_align = std::max(p_align, Sec->Alignment);
792 if (p_type == PT_LOAD)
793 Sec->FirstInPtLoad = First;
796 template <class ELFT>
797 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
798 uint8_t StOther = STV_HIDDEN,
799 uint8_t Binding = STB_WEAK) {
800 // The linker generated symbols are added as STB_WEAK to allow user defined
801 // ones to override them.
802 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
803 /*Size=*/0, Binding, Sec,
807 template <class ELFT>
808 static DefinedRegular *
809 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
810 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
811 SymbolBody *S = Symtab<ELFT>::X->find(Name);
814 if (S->isInCurrentDSO())
816 return cast<DefinedRegular>(
817 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
820 // The beginning and the ending of .rel[a].plt section are marked
821 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
822 // executable. The runtime needs these symbols in order to resolve
823 // all IRELATIVE relocs on startup. For dynamic executables, we don't
824 // need these symbols, since IRELATIVE relocs are resolved through GOT
825 // and PLT. For details, see http://www.airs.com/blog/archives/403.
826 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
829 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
830 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
832 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
833 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
836 // The linker is expected to define some symbols depending on
837 // the linking result. This function defines such symbols.
838 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
839 if (Config->EMachine == EM_MIPS) {
840 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
841 // so that it points to an absolute address which by default is relative
842 // to GOT. Default offset is 0x7ff0.
843 // See "Global Data Symbols" in Chapter 6 in the following document:
844 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
845 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
847 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
848 // start of function and 'gp' pointer into GOT.
849 if (Symtab<ELFT>::X->find("_gp_disp"))
851 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
853 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
854 // pointer. This symbol is used in the code generated by .cpload pseudo-op
855 // in case of using -mno-shared option.
856 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
857 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
858 ElfSym::MipsLocalGp =
859 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
862 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
863 // is magical and is used to produce a R_386_GOTPC relocation.
864 // The R_386_GOTPC relocation value doesn't actually depend on the
865 // symbol value, so it could use an index of STN_UNDEF which, according
866 // to the spec, means the symbol value is 0.
867 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
869 // The situation is even stranger on x86_64 where the assembly doesn't
870 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
871 // an undefined symbol in the .o files.
872 // Given that the symbol is effectively unused, we just create a dummy
873 // hidden one to avoid the undefined symbol error.
874 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
876 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
877 // static linking the linker is required to optimize away any references to
878 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
879 // to avoid the undefined symbol error.
881 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
883 // __ehdr_start is the location of ELF file headers. Note that we define
884 // this symbol unconditionally even when using a linker script, which
885 // differs from the behavior implemented by GNU linker which only define
886 // this symbol if ELF headers are in the memory mapped segment.
887 addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
889 // If linker script do layout we do not need to create any standart symbols.
890 if (Script->Opt.HasSections)
893 auto Add = [](StringRef S) {
894 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
897 ElfSym::Bss = Add("__bss_start");
898 ElfSym::End1 = Add("end");
899 ElfSym::End2 = Add("_end");
900 ElfSym::Etext1 = Add("etext");
901 ElfSym::Etext2 = Add("_etext");
902 ElfSym::Edata1 = Add("edata");
903 ElfSym::Edata2 = Add("_edata");
906 // Sort input sections by section name suffixes for
907 // __attribute__((init_priority(N))).
908 static void sortInitFini(OutputSection *S) {
910 reinterpret_cast<OutputSection *>(S)->sortInitFini();
913 // Sort input sections by the special rule for .ctors and .dtors.
914 static void sortCtorsDtors(OutputSection *S) {
916 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
919 // Sort input sections using the list provided by --symbol-ordering-file.
920 template <class ELFT>
921 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
922 if (Config->SymbolOrderingFile.empty())
925 // Build a map from symbols to their priorities. Symbols that didn't
926 // appear in the symbol ordering file have the lowest priority 0.
927 // All explicitly mentioned symbols have negative (higher) priorities.
928 DenseMap<StringRef, int> SymbolOrder;
929 int Priority = -Config->SymbolOrderingFile.size();
930 for (StringRef S : Config->SymbolOrderingFile)
931 SymbolOrder.insert({S, Priority++});
933 // Build a map from sections to their priorities.
934 DenseMap<SectionBase *, int> SectionOrder;
935 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
936 for (SymbolBody *Body : File->getSymbols()) {
937 auto *D = dyn_cast<DefinedRegular>(Body);
938 if (!D || !D->Section)
940 int &Priority = SectionOrder[D->Section];
941 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
945 // Sort sections by priority.
946 for (OutputSection *Base : OutputSections)
947 if (auto *Sec = dyn_cast<OutputSection>(Base))
948 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
951 template <class ELFT>
952 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
953 for (InputSectionBase *IS : InputSections) {
956 // Scan all relocations. Each relocation goes through a series
957 // of tests to determine if it needs special treatment, such as
958 // creating GOT, PLT, copy relocations, etc.
959 // Note that relocations for non-alloc sections are directly
960 // processed by InputSection::relocateNonAlloc.
961 if (!(IS->Flags & SHF_ALLOC))
963 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
967 if (!Config->Relocatable) {
968 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
973 template <class ELFT> void Writer<ELFT>::createSections() {
974 for (InputSectionBase *IS : InputSections)
976 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
978 sortBySymbolsOrder<ELFT>(OutputSections);
979 sortInitFini(findSection(".init_array"));
980 sortInitFini(findSection(".fini_array"));
981 sortCtorsDtors(findSection(".ctors"));
982 sortCtorsDtors(findSection(".dtors"));
984 for (OutputSection *Sec : OutputSections)
985 Sec->assignOffsets();
988 // We want to find how similar two ranks are.
989 // The more branches in getSectionRank that match, the more similar they are.
990 // Since each branch corresponds to a bit flag, we can just use
991 // countLeadingZeros.
992 static unsigned getRankProximity(OutputSection *A, OutputSection *B) {
993 return countLeadingZeros(A->SortRank ^ B->SortRank);
996 // We want to place orphan sections so that they share as much
997 // characteristics with their neighbors as possible. For example, if
998 // both are rw, or both are tls.
999 template <typename ELFT>
1000 static std::vector<OutputSection *>::iterator
1001 findOrphanPos(std::vector<OutputSection *>::iterator B,
1002 std::vector<OutputSection *>::iterator E) {
1003 OutputSection *Sec = *E;
1005 // Find the first element that has as close a rank as possible.
1006 auto I = std::max_element(B, E, [=](OutputSection *A, OutputSection *B) {
1007 return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1012 // Consider all existing sections with the same proximity.
1013 unsigned Proximity = getRankProximity(Sec, *I);
1014 while (I != E && getRankProximity(Sec, *I) == Proximity &&
1015 Sec->SortRank >= (*I)->SortRank)
1020 template <class ELFT> void Writer<ELFT>::sortSections() {
1021 // Don't sort if using -r. It is not necessary and we want to preserve the
1022 // relative order for SHF_LINK_ORDER sections.
1023 if (Config->Relocatable)
1026 if (Script->Opt.HasSections)
1027 Script->adjustSectionsBeforeSorting();
1029 for (OutputSection *Sec : OutputSections)
1030 Sec->SortRank = getSectionRank(Sec);
1032 if (!Script->Opt.HasSections) {
1033 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1034 compareSectionsNonScript);
1038 // The order of the sections in the script is arbitrary and may not agree with
1039 // compareSectionsNonScript. This means that we cannot easily define a
1040 // strict weak ordering. To see why, consider a comparison of a section in the
1041 // script and one not in the script. We have a two simple options:
1042 // * Make them equivalent (a is not less than b, and b is not less than a).
1043 // The problem is then that equivalence has to be transitive and we can
1044 // have sections a, b and c with only b in a script and a less than c
1045 // which breaks this property.
1046 // * Use compareSectionsNonScript. Given that the script order doesn't have
1047 // to match, we can end up with sections a, b, c, d where b and c are in the
1048 // script and c is compareSectionsNonScript less than b. In which case d
1049 // can be equivalent to c, a to b and d < a. As a concrete example:
1050 // .a (rx) # not in script
1051 // .b (rx) # in script
1052 // .c (ro) # in script
1053 // .d (ro) # not in script
1055 // The way we define an order then is:
1056 // * First put script sections at the start and sort the script sections.
1057 // * Move each non-script section to its preferred position. We try
1058 // to put each section in the last position where it it can share
1061 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1064 auto I = OutputSections.begin();
1065 auto E = OutputSections.end();
1067 std::find_if(OutputSections.begin(), E,
1068 [](OutputSection *S) { return S->SectionIndex == INT_MAX; });
1069 while (NonScriptI != E) {
1070 auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1072 // As an optimization, find all sections with the same sort rank
1073 // and insert them with one rotate.
1074 unsigned Rank = (*NonScriptI)->SortRank;
1075 auto End = std::find_if(NonScriptI + 1, E, [=](OutputSection *Sec) {
1076 return Sec->SortRank != Rank;
1078 std::rotate(Pos, NonScriptI, End);
1082 Script->adjustSectionsAfterSorting();
1085 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1086 std::function<void(SyntheticSection *)> Fn) {
1087 for (SyntheticSection *SS : Sections)
1088 if (SS && SS->OutSec && !SS->empty()) {
1090 SS->OutSec->assignOffsets();
1094 // We need to add input synthetic sections early in createSyntheticSections()
1095 // to make them visible from linkescript side. But not all sections are always
1096 // required to be in output. For example we don't need dynamic section content
1097 // sometimes. This function filters out such unused sections from the output.
1098 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1099 // All input synthetic sections that can be empty are placed after
1100 // all regular ones. We iterate over them all and exit at first
1102 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1103 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1106 if (!SS->empty() || !SS->OutSec)
1109 SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1110 SS->OutSec->Sections.end(), SS));
1112 // If there are no other sections in the output section, remove it from the
1114 if (SS->OutSec->Sections.empty())
1115 V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1119 // Create output section objects and add them to OutputSections.
1120 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1121 Out::DebugInfo = findSection(".debug_info");
1122 Out::PreinitArray = findSection(".preinit_array");
1123 Out::InitArray = findSection(".init_array");
1124 Out::FiniArray = findSection(".fini_array");
1126 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1127 // symbols for sections, so that the runtime can get the start and end
1128 // addresses of each section by section name. Add such symbols.
1129 if (!Config->Relocatable) {
1130 addStartEndSymbols();
1131 for (OutputSection *Sec : OutputSections)
1132 addStartStopSymbols(Sec);
1135 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1136 // It should be okay as no one seems to care about the type.
1137 // Even the author of gold doesn't remember why gold behaves that way.
1138 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1140 addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1142 // Define __rel[a]_iplt_{start,end} symbols if needed.
1143 addRelIpltSymbols();
1145 // This responsible for splitting up .eh_frame section into
1146 // pieces. The relocation scan uses those pieces, so this has to be
1148 applySynthetic({In<ELFT>::EhFrame},
1149 [](SyntheticSection *SS) { SS->finalizeContents(); });
1151 // Scan relocations. This must be done after every symbol is declared so that
1152 // we can correctly decide if a dynamic relocation is needed.
1153 forEachRelSec(scanRelocations<ELFT>);
1155 if (InX::Plt && !InX::Plt->empty())
1156 InX::Plt->addSymbols();
1157 if (InX::Iplt && !InX::Iplt->empty())
1158 InX::Iplt->addSymbols();
1160 // Now that we have defined all possible global symbols including linker-
1161 // synthesized ones. Visit all symbols to give the finishing touches.
1162 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1163 SymbolBody *Body = S->body();
1165 if (!includeInSymtab(*Body))
1168 InX::SymTab->addSymbol(Body);
1170 if (InX::DynSymTab && S->includeInDynsym()) {
1171 InX::DynSymTab->addSymbol(Body);
1172 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1173 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1174 In<ELFT>::VerNeed->addSymbol(SS);
1178 // Do not proceed if there was an undefined symbol.
1182 // So far we have added sections from input object files.
1183 // This function adds linker-created Out::* sections.
1184 addPredefinedSections();
1185 removeUnusedSyntheticSections(OutputSections);
1189 // This is a bit of a hack. A value of 0 means undef, so we set it
1190 // to 1 t make __ehdr_start defined. The section number is not
1191 // particularly relevant.
1192 Out::ElfHeader->SectionIndex = 1;
1195 for (OutputSection *Sec : OutputSections) {
1196 Sec->SectionIndex = I++;
1197 Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1200 // Binary and relocatable output does not have PHDRS.
1201 // The headers have to be created before finalize as that can influence the
1202 // image base and the dynamic section on mips includes the image base.
1203 if (!Config->Relocatable && !Config->OFormatBinary) {
1204 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1205 addPtArmExid(Phdrs);
1206 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1209 // Dynamic section must be the last one in this list and dynamic
1210 // symbol table section (DynSymTab) must be the first one.
1211 applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo,
1212 InX::GnuHashTab, In<ELFT>::HashTab, InX::SymTab,
1213 InX::ShStrTab, InX::StrTab, In<ELFT>::VerDef,
1214 InX::DynStrTab, InX::GdbIndex, InX::Got,
1215 InX::MipsGot, InX::IgotPlt, InX::GotPlt,
1216 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1217 InX::Plt, InX::Iplt, In<ELFT>::EhFrameHdr,
1218 In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1219 [](SyntheticSection *SS) { SS->finalizeContents(); });
1221 // Some architectures use small displacements for jump instructions.
1222 // It is linker's responsibility to create thunks containing long
1223 // jump instructions if jump targets are too far. Create thunks.
1224 if (Target->NeedsThunks) {
1225 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1227 // do not require address information. To support range extension Thunks
1228 // we need to assign addresses so that we can tell if jump instructions
1229 // are out of range. This will need to turn into a loop that converges
1230 // when no more Thunks are added
1232 if (TC.createThunks(OutputSections))
1233 applySynthetic({InX::MipsGot},
1234 [](SyntheticSection *SS) { SS->updateAllocSize(); });
1236 // Fill other section headers. The dynamic table is finalized
1237 // at the end because some tags like RELSZ depend on result
1238 // of finalizing other sections.
1239 for (OutputSection *Sec : OutputSections)
1240 Sec->finalize<ELFT>();
1242 // If -compressed-debug-sections is specified, we need to compress
1243 // .debug_* sections. Do it right now because it changes the size of
1245 parallelForEach(OutputSections.begin(), OutputSections.end(),
1246 [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1248 // createThunks may have added local symbols to the static symbol table
1249 applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1250 [](SyntheticSection *SS) { SS->postThunkContents(); });
1253 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1254 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1255 // We have the terminater synthetic section class. Add that at the end.
1256 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1257 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1258 OS->addSection(make<ARMExidxSentinelSection>());
1261 // The linker is expected to define SECNAME_start and SECNAME_end
1262 // symbols for a few sections. This function defines them.
1263 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1264 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1265 // These symbols resolve to the image base if the section does not exist.
1266 // A special value -1 indicates end of the section.
1268 addOptionalRegular<ELFT>(Start, OS, 0);
1269 addOptionalRegular<ELFT>(End, OS, -1);
1272 OS = Out::ElfHeader;
1273 addOptionalRegular<ELFT>(Start, OS, 0);
1274 addOptionalRegular<ELFT>(End, OS, 0);
1278 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1279 Define("__init_array_start", "__init_array_end", Out::InitArray);
1280 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1282 if (OutputSection *Sec = findSection(".ARM.exidx"))
1283 Define("__exidx_start", "__exidx_end", Sec);
1286 // If a section name is valid as a C identifier (which is rare because of
1287 // the leading '.'), linkers are expected to define __start_<secname> and
1288 // __stop_<secname> symbols. They are at beginning and end of the section,
1289 // respectively. This is not requested by the ELF standard, but GNU ld and
1290 // gold provide the feature, and used by many programs.
1291 template <class ELFT>
1292 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1293 StringRef S = Sec->Name;
1294 if (!isValidCIdentifier(S))
1296 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1297 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1300 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1301 for (OutputSection *Sec : OutputSections)
1302 if (Sec->Name == Name)
1307 static bool needsPtLoad(OutputSection *Sec) {
1308 if (!(Sec->Flags & SHF_ALLOC))
1311 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1312 // responsible for allocating space for them, not the PT_LOAD that
1313 // contains the TLS initialization image.
1314 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1319 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1320 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1321 // RW. This means that there is no alignment in the RO to RX transition and we
1322 // cannot create a PT_LOAD there.
1323 static uint64_t computeFlags(uint64_t Flags) {
1325 return PF_R | PF_W | PF_X;
1326 if (Config->SingleRoRx && !(Flags & PF_W))
1327 return Flags | PF_X;
1331 // Decide which program headers to create and which sections to include in each
1333 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1334 std::vector<PhdrEntry> Ret;
1335 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1336 Ret.emplace_back(Type, Flags);
1340 // The first phdr entry is PT_PHDR which describes the program header itself.
1341 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1343 // PT_INTERP must be the second entry if exists.
1344 if (OutputSection *Sec = findSection(".interp"))
1345 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1347 // Add the first PT_LOAD segment for regular output sections.
1348 uint64_t Flags = computeFlags(PF_R);
1349 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1351 // Add the headers. We will remove them if they don't fit.
1352 Load->add(Out::ElfHeader);
1353 Load->add(Out::ProgramHeaders);
1355 for (OutputSection *Sec : OutputSections) {
1356 if (!(Sec->Flags & SHF_ALLOC))
1358 if (!needsPtLoad(Sec))
1361 // Segments are contiguous memory regions that has the same attributes
1362 // (e.g. executable or writable). There is one phdr for each segment.
1363 // Therefore, we need to create a new phdr when the next section has
1364 // different flags or is loaded at a discontiguous address using AT linker
1366 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1367 if (Script->hasLMA(Sec) || Flags != NewFlags) {
1368 Load = AddHdr(PT_LOAD, NewFlags);
1375 // Add a TLS segment if any.
1376 PhdrEntry TlsHdr(PT_TLS, PF_R);
1377 for (OutputSection *Sec : OutputSections)
1378 if (Sec->Flags & SHF_TLS)
1381 Ret.push_back(std::move(TlsHdr));
1383 // Add an entry for .dynamic.
1385 AddHdr(PT_DYNAMIC, InX::Dynamic->OutSec->getPhdrFlags())
1386 ->add(InX::Dynamic->OutSec);
1388 // PT_GNU_RELRO includes all sections that should be marked as
1389 // read-only by dynamic linker after proccessing relocations.
1390 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1391 for (OutputSection *Sec : OutputSections)
1392 if (needsPtLoad(Sec) && isRelroSection(Sec))
1395 Ret.push_back(std::move(RelRo));
1397 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1398 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1399 In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1400 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1401 ->add(In<ELFT>::EhFrameHdr->OutSec);
1403 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1404 // the dynamic linker fill the segment with random data.
1405 if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1406 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1408 // PT_GNU_STACK is a special section to tell the loader to make the
1409 // pages for the stack non-executable. If you really want an executable
1410 // stack, you can pass -z execstack, but that's not recommended for
1411 // security reasons.
1413 if (Config->ZExecstack)
1414 Perm = PF_R | PF_W | PF_X;
1417 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1419 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1420 // is expected to perform W^X violations, such as calling mprotect(2) or
1421 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1423 if (Config->ZWxneeded)
1424 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1426 // Create one PT_NOTE per a group of contiguous .note sections.
1427 PhdrEntry *Note = nullptr;
1428 for (OutputSection *Sec : OutputSections) {
1429 if (Sec->Type == SHT_NOTE) {
1430 if (!Note || Script->hasLMA(Sec))
1431 Note = AddHdr(PT_NOTE, PF_R);
1440 template <class ELFT>
1441 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1442 if (Config->EMachine != EM_ARM)
1444 auto I = std::find_if(
1445 OutputSections.begin(), OutputSections.end(),
1446 [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1447 if (I == OutputSections.end())
1450 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1451 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1453 Phdrs.push_back(ARMExidx);
1456 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1457 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1458 // linker can set the permissions.
1459 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1460 for (const PhdrEntry &P : Phdrs)
1461 if (P.p_type == PT_LOAD && P.First)
1462 P.First->PageAlign = true;
1464 for (const PhdrEntry &P : Phdrs) {
1465 if (P.p_type != PT_GNU_RELRO)
1468 P.First->PageAlign = true;
1469 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1470 // have to align it to a page.
1471 auto End = OutputSections.end();
1472 auto I = std::find(OutputSections.begin(), End, P.Last);
1473 if (I == End || (I + 1) == End)
1475 OutputSection *Sec = *(I + 1);
1476 if (needsPtLoad(Sec))
1477 Sec->PageAlign = true;
1481 // Adjusts the file alignment for a given output section and returns
1482 // its new file offset. The file offset must be the same with its
1483 // virtual address (modulo the page size) so that the loader can load
1484 // executables without any address adjustment.
1485 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1486 OutputSection *First = Sec->FirstInPtLoad;
1487 // If the section is not in a PT_LOAD, we just have to align it.
1489 return alignTo(Off, Sec->Alignment);
1491 // The first section in a PT_LOAD has to have congruent offset and address
1492 // module the page size.
1494 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1496 // If two sections share the same PT_LOAD the file offset is calculated
1497 // using this formula: Off2 = Off1 + (VA2 - VA1).
1498 return First->Offset + Sec->Addr - First->Addr;
1501 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1502 if (Sec->Type == SHT_NOBITS) {
1507 Off = getFileAlignment(Off, Sec);
1509 return Off + Sec->Size;
1512 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1514 for (OutputSection *Sec : OutputSections)
1515 if (Sec->Flags & SHF_ALLOC)
1516 Off = setOffset(Sec, Off);
1517 FileSize = alignTo(Off, Config->Wordsize);
1520 // Assign file offsets to output sections.
1521 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1523 Off = setOffset(Out::ElfHeader, Off);
1524 Off = setOffset(Out::ProgramHeaders, Off);
1526 for (OutputSection *Sec : OutputSections)
1527 Off = setOffset(Sec, Off);
1529 SectionHeaderOff = alignTo(Off, Config->Wordsize);
1530 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1533 // Finalize the program headers. We call this function after we assign
1534 // file offsets and VAs to all sections.
1535 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1536 for (PhdrEntry &P : Phdrs) {
1537 OutputSection *First = P.First;
1538 OutputSection *Last = P.Last;
1540 P.p_filesz = Last->Offset - First->Offset;
1541 if (Last->Type != SHT_NOBITS)
1542 P.p_filesz += Last->Size;
1543 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1544 P.p_offset = First->Offset;
1545 P.p_vaddr = First->Addr;
1547 P.p_paddr = First->getLMA();
1549 if (P.p_type == PT_LOAD)
1550 P.p_align = Config->MaxPageSize;
1551 else if (P.p_type == PT_GNU_RELRO)
1554 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1555 // so round up the size to make sure the offsets are correct.
1556 if (P.p_type == PT_TLS) {
1559 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1564 // The entry point address is chosen in the following ways.
1566 // 1. the '-e' entry command-line option;
1567 // 2. the ENTRY(symbol) command in a linker control script;
1568 // 3. the value of the symbol start, if present;
1569 // 4. the address of the first byte of the .text section, if present;
1570 // 5. the address 0.
1571 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1572 // Case 1, 2 or 3. As a special case, if the symbol is actually
1573 // a number, we'll use that number as an address.
1574 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1577 if (to_integer(Config->Entry, Addr))
1581 if (OutputSection *Sec = findSection(".text")) {
1582 if (Config->WarnMissingEntry)
1583 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1584 utohexstr(Sec->Addr));
1589 if (Config->WarnMissingEntry)
1590 warn("cannot find entry symbol " + Config->Entry +
1591 "; not setting start address");
1595 static uint16_t getELFType() {
1598 if (Config->Relocatable)
1603 // This function is called after we have assigned address and size
1604 // to each section. This function fixes some predefined
1605 // symbol values that depend on section address and size.
1606 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1607 auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1619 // _etext is the first location after the last read-only loadable segment.
1620 // _edata is the first location after the last read-write loadable segment.
1621 // _end is the first location after the uninitialized data region.
1622 PhdrEntry *Last = nullptr;
1623 PhdrEntry *LastRO = nullptr;
1624 PhdrEntry *LastRW = nullptr;
1625 for (PhdrEntry &P : Phdrs) {
1626 if (P.p_type != PT_LOAD)
1629 if (P.p_flags & PF_W)
1635 Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1637 Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1639 Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1642 ElfSym::Bss->Section = findSection(".bss");
1644 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1645 // be equal to the _gp symbol's value.
1646 if (Config->EMachine == EM_MIPS) {
1647 if (!ElfSym::MipsGp->Value) {
1648 // Find GP-relative section with the lowest address
1649 // and use this address to calculate default _gp value.
1651 for (const OutputSection *OS : OutputSections)
1652 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1654 if (Gp != (uint64_t)-1)
1655 ElfSym::MipsGp->Value = Gp + 0x7ff0;
1660 template <class ELFT> void Writer<ELFT>::writeHeader() {
1661 uint8_t *Buf = Buffer->getBufferStart();
1662 memcpy(Buf, "\177ELF", 4);
1664 // Write the ELF header.
1665 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1666 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1667 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1668 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1669 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1670 EHdr->e_type = getELFType();
1671 EHdr->e_machine = Config->EMachine;
1672 EHdr->e_version = EV_CURRENT;
1673 EHdr->e_entry = getEntryAddr();
1674 EHdr->e_shoff = SectionHeaderOff;
1675 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1676 EHdr->e_phnum = Phdrs.size();
1677 EHdr->e_shentsize = sizeof(Elf_Shdr);
1678 EHdr->e_shnum = OutputSections.size() + 1;
1679 EHdr->e_shstrndx = InX::ShStrTab->OutSec->SectionIndex;
1681 if (Config->EMachine == EM_ARM)
1682 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1683 // but we don't have any firm guarantees of conformance. Linux AArch64
1684 // kernels (as of 2016) require an EABI version to be set.
1685 EHdr->e_flags = EF_ARM_EABI_VER5;
1686 else if (Config->EMachine == EM_MIPS)
1687 EHdr->e_flags = getMipsEFlags<ELFT>();
1689 if (!Config->Relocatable) {
1690 EHdr->e_phoff = sizeof(Elf_Ehdr);
1691 EHdr->e_phentsize = sizeof(Elf_Phdr);
1694 // Write the program header table.
1695 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1696 for (PhdrEntry &P : Phdrs) {
1697 HBuf->p_type = P.p_type;
1698 HBuf->p_flags = P.p_flags;
1699 HBuf->p_offset = P.p_offset;
1700 HBuf->p_vaddr = P.p_vaddr;
1701 HBuf->p_paddr = P.p_paddr;
1702 HBuf->p_filesz = P.p_filesz;
1703 HBuf->p_memsz = P.p_memsz;
1704 HBuf->p_align = P.p_align;
1708 // Write the section header table. Note that the first table entry is null.
1709 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1710 for (OutputSection *Sec : OutputSections)
1711 Sec->writeHeaderTo<ELFT>(++SHdrs);
1714 // Open a result file.
1715 template <class ELFT> void Writer<ELFT>::openFile() {
1716 if (!Config->Is64 && FileSize > UINT32_MAX) {
1717 error("output file too large: " + Twine(FileSize) + " bytes");
1721 unlinkAsync(Config->OutputFile);
1722 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1723 FileOutputBuffer::create(Config->OutputFile, FileSize,
1724 FileOutputBuffer::F_executable);
1726 if (auto EC = BufferOrErr.getError())
1727 error("failed to open " + Config->OutputFile + ": " + EC.message());
1729 Buffer = std::move(*BufferOrErr);
1732 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1733 uint8_t *Buf = Buffer->getBufferStart();
1734 for (OutputSection *Sec : OutputSections)
1735 if (Sec->Flags & SHF_ALLOC)
1736 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1739 // Write section contents to a mmap'ed file.
1740 template <class ELFT> void Writer<ELFT>::writeSections() {
1741 uint8_t *Buf = Buffer->getBufferStart();
1743 // PPC64 needs to process relocations in the .opd section
1744 // before processing relocations in code-containing sections.
1745 Out::Opd = findSection(".opd");
1747 Out::OpdBuf = Buf + Out::Opd->Offset;
1748 Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1751 OutputSection *EhFrameHdr =
1752 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1754 // In -r or -emit-relocs mode, write the relocation sections first as in
1755 // ELf_Rel targets we might find out that we need to modify the relocated
1756 // section while doing it.
1757 for (OutputSection *Sec : OutputSections)
1758 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1759 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1761 for (OutputSection *Sec : OutputSections)
1762 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1763 Sec->Type != SHT_RELA)
1764 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1766 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1767 // it should be written after .eh_frame is written.
1768 if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1769 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1772 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1773 if (!InX::BuildId || !InX::BuildId->OutSec)
1776 // Compute a hash of all sections of the output file.
1777 uint8_t *Start = Buffer->getBufferStart();
1778 uint8_t *End = Start + FileSize;
1779 InX::BuildId->writeBuildId({Start, End});
1782 template void elf::writeResult<ELF32LE>();
1783 template void elf::writeResult<ELF32BE>();
1784 template void elf::writeResult<ELF64LE>();
1785 template void elf::writeResult<ELF64BE>();