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 // Handle -Map option.
292 writeMapFile<ELFT>(OutputSections);
296 if (auto EC = Buffer->commit())
297 error("failed to write to the output file: " + EC.message());
299 // Flush the output streams and exit immediately. A full shutdown
300 // is a good test that we are keeping track of all allocated memory,
301 // but actually freeing it is a waste of time in a regular linker run.
302 if (Config->ExitEarly)
306 // Initialize Out members.
307 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
308 // Initialize all pointers with NULL. This is needed because
309 // you can call lld::elf::main more than once as a library.
310 memset(&Out::First, 0, sizeof(Out));
312 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
314 InX::DynStrTab = make<StringTableSection>(".dynstr", true);
315 InX::Dynamic = make<DynamicSection<ELFT>>();
316 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
317 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
318 InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
320 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
321 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
322 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
323 Out::ProgramHeaders->updateAlignment(Config->Wordsize);
325 if (needsInterpSection<ELFT>()) {
326 InX::Interp = createInterpSection();
329 InX::Interp = nullptr;
332 if (!Config->Relocatable)
333 Add(createCommentSection<ELFT>());
335 if (Config->Strip != StripPolicy::All) {
336 InX::StrTab = make<StringTableSection>(".strtab", false);
337 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
340 if (Config->BuildId != BuildIdKind::None) {
341 InX::BuildId = make<BuildIdSection>();
345 InX::Common = createCommonSection<ELFT>();
349 InX::Bss = make<BssSection>(".bss");
351 InX::BssRelRo = make<BssSection>(".bss.rel.ro");
354 // Add MIPS-specific sections.
355 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
356 Config->Pic || Config->ExportDynamic;
357 if (Config->EMachine == EM_MIPS) {
358 if (!Config->Shared && HasDynSymTab) {
359 InX::MipsRldMap = make<MipsRldMapSection>();
360 Add(InX::MipsRldMap);
362 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
364 if (auto *Sec = MipsOptionsSection<ELFT>::create())
366 if (auto *Sec = MipsReginfoSection<ELFT>::create())
371 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
374 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
375 Add(In<ELFT>::VerSym);
377 if (!Config->VersionDefinitions.empty()) {
378 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
379 Add(In<ELFT>::VerDef);
382 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
383 Add(In<ELFT>::VerNeed);
385 if (Config->GnuHash) {
386 InX::GnuHashTab = make<GnuHashTableSection>();
387 Add(InX::GnuHashTab);
390 if (Config->SysvHash) {
391 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
392 Add(In<ELFT>::HashTab);
397 Add(In<ELFT>::RelaDyn);
400 // Add .got. MIPS' .got is so different from the other archs,
401 // it has its own class.
402 if (Config->EMachine == EM_MIPS) {
403 InX::MipsGot = make<MipsGotSection>();
406 InX::Got = make<GotSection<ELFT>>();
410 InX::GotPlt = make<GotPltSection>();
412 InX::IgotPlt = make<IgotPltSection>();
415 if (Config->GdbIndex) {
416 InX::GdbIndex = make<GdbIndexSection>();
420 // We always need to add rel[a].plt to output if it has entries.
421 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
422 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
423 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
424 Add(In<ELFT>::RelaPlt);
426 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
427 // that the IRelative relocations are processed last by the dynamic loader
428 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
429 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
431 Add(In<ELFT>::RelaIplt);
433 InX::Plt = make<PltSection>(Target->PltHeaderSize);
435 InX::Iplt = make<PltSection>(0);
438 if (!Config->Relocatable) {
439 if (Config->EhFrameHdr) {
440 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
441 Add(In<ELFT>::EhFrameHdr);
443 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
444 Add(In<ELFT>::EhFrame);
454 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
455 const SymbolBody &B) {
456 if (B.isFile() || B.isSection())
459 // If sym references a section in a discarded group, don't keep it.
460 if (Sec == &InputSection::Discarded)
463 if (Config->Discard == DiscardPolicy::None)
466 // In ELF assembly .L symbols are normally discarded by the assembler.
467 // If the assembler fails to do so, the linker discards them if
468 // * --discard-locals is used.
469 // * The symbol is in a SHF_MERGE section, which is normally the reason for
470 // the assembler keeping the .L symbol.
471 if (!SymName.startswith(".L") && !SymName.empty())
474 if (Config->Discard == DiscardPolicy::Locals)
477 return !Sec || !(Sec->Flags & SHF_MERGE);
480 static bool includeInSymtab(const SymbolBody &B) {
481 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
484 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
485 // Always include absolute symbols.
486 SectionBase *Sec = D->Section;
489 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
491 IS = cast<InputSectionBase>(Sec);
492 // Exclude symbols pointing to garbage-collected sections.
496 if (auto *S = dyn_cast<MergeInputSection>(Sec))
497 if (!S->getSectionPiece(D->Value)->Live)
503 // Local symbols are not in the linker's symbol table. This function scans
504 // each object file's symbol table to copy local symbols to the output.
505 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
508 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
509 for (SymbolBody *B : F->getLocalSymbols()) {
512 ": broken object: getLocalSymbols returns a non-local symbol");
513 auto *DR = dyn_cast<DefinedRegular>(B);
515 // No reason to keep local undefined symbol in symtab.
518 if (!includeInSymtab(*B))
521 SectionBase *Sec = DR->Section;
522 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
524 InX::SymTab->addSymbol(B);
529 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
530 // Create one STT_SECTION symbol for each output section we might
531 // have a relocation with.
532 for (OutputSection *Sec : OutputSections) {
533 if (Sec->Sections.empty())
536 InputSection *IS = Sec->Sections[0];
537 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
538 IS->Type == SHT_RELA)
542 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
543 /*Value=*/0, /*Size=*/0, IS, nullptr);
544 InX::SymTab->addSymbol(Sym);
548 // Today's loaders have a feature to make segments read-only after
549 // processing dynamic relocations to enhance security. PT_GNU_RELRO
550 // is defined for that.
552 // This function returns true if a section needs to be put into a
553 // PT_GNU_RELRO segment.
554 bool elf::isRelroSection(const OutputSection *Sec) {
558 uint64_t Flags = Sec->Flags;
560 // Non-allocatable or non-writable sections don't need RELRO because
561 // they are not writable or not even mapped to memory in the first place.
562 // RELRO is for sections that are essentially read-only but need to
563 // be writable only at process startup to allow dynamic linker to
564 // apply relocations.
565 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
568 // Once initialized, TLS data segments are used as data templates
569 // for a thread-local storage. For each new thread, runtime
570 // allocates memory for a TLS and copy templates there. No thread
571 // are supposed to use templates directly. Thus, it can be in RELRO.
575 // .init_array, .preinit_array and .fini_array contain pointers to
576 // functions that are executed on process startup or exit. These
577 // pointers are set by the static linker, and they are not expected
578 // to change at runtime. But if you are an attacker, you could do
579 // interesting things by manipulating pointers in .fini_array, for
580 // example. So they are put into RELRO.
581 uint32_t Type = Sec->Type;
582 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
583 Type == SHT_PREINIT_ARRAY)
586 // .got contains pointers to external symbols. They are resolved by
587 // the dynamic linker when a module is loaded into memory, and after
588 // that they are not expected to change. So, it can be in RELRO.
589 if (InX::Got && Sec == InX::Got->OutSec)
592 // .got.plt contains pointers to external function symbols. They are
593 // by default resolved lazily, so we usually cannot put it into RELRO.
594 // However, if "-z now" is given, the lazy symbol resolution is
595 // disabled, which enables us to put it into RELRO.
596 if (Sec == InX::GotPlt->OutSec)
599 // .dynamic section contains data for the dynamic linker, and
600 // there's no need to write to it at runtime, so it's better to put
602 if (Sec == InX::Dynamic->OutSec)
605 // .bss.rel.ro is used for copy relocations for read-only symbols.
606 // Since the dynamic linker needs to process copy relocations, the
607 // section cannot be read-only, but once initialized, they shouldn't
609 if (Sec == InX::BssRelRo->OutSec)
612 // Sections with some special names are put into RELRO. This is a
613 // bit unfortunate because section names shouldn't be significant in
614 // ELF in spirit. But in reality many linker features depend on
615 // magic section names.
616 StringRef S = Sec->Name;
617 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
618 S == ".eh_frame" || S == ".openbsd.randomdata";
621 // We compute a rank for each section. The rank indicates where the
622 // section should be placed in the file. Instead of using simple
623 // numbers (0,1,2...), we use a series of flags. One for each decision
624 // point when placing the section.
625 // Using flags has two key properties:
626 // * It is easy to check if a give branch was taken.
627 // * It is easy two see how similar two ranks are (see getRankProximity).
629 RF_NOT_ADDR_SET = 1 << 16,
630 RF_NOT_INTERP = 1 << 15,
631 RF_NOT_ALLOC = 1 << 14,
634 RF_NON_TLS_BSS = 1 << 11,
635 RF_NON_TLS_BSS_RO = 1 << 10,
638 RF_PPC_NOT_TOCBSS = 1 << 7,
640 RF_PPC_TOCL = 1 << 5,
642 RF_PPC_BRANCH_LT = 1 << 3,
643 RF_MIPS_GPREL = 1 << 2,
644 RF_MIPS_NOT_GOT = 1 << 1
647 static unsigned getSectionRank(const OutputSection *Sec) {
650 // We want to put section specified by -T option first, so we
651 // can start assigning VA starting from them later.
652 if (Config->SectionStartMap.count(Sec->Name))
654 Rank |= RF_NOT_ADDR_SET;
656 // Put .interp first because some loaders want to see that section
657 // on the first page of the executable file when loaded into memory.
658 if (Sec->Name == ".interp")
660 Rank |= RF_NOT_INTERP;
662 // Allocatable sections go first to reduce the total PT_LOAD size and
663 // so debug info doesn't change addresses in actual code.
664 if (!(Sec->Flags & SHF_ALLOC))
665 return Rank | RF_NOT_ALLOC;
667 // We want the read only sections first so that they go in the PT_LOAD
668 // covering the program headers at the start of the file.
669 if (Sec->Flags & SHF_WRITE)
672 if (Sec->Flags & SHF_EXECINSTR) {
673 // For a corresponding reason, put non exec sections first (the program
674 // header PT_LOAD is not executable).
675 // We only do that if we are not using linker scripts, since with linker
676 // scripts ro and rx sections are in the same PT_LOAD, so their relative
677 // order is not important. The same applies for -no-rosegment.
678 if ((Rank & RF_WRITE) || !Config->SingleRoRx)
682 // If we got here we know that both A and B are in the same PT_LOAD.
684 bool IsTls = Sec->Flags & SHF_TLS;
685 bool IsNoBits = Sec->Type == SHT_NOBITS;
687 // The first requirement we have is to put (non-TLS) nobits sections last. The
688 // reason is that the only thing the dynamic linker will see about them is a
689 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
690 // PT_LOAD, so that has to correspond to the nobits sections.
691 bool IsNonTlsNoBits = IsNoBits && !IsTls;
693 Rank |= RF_NON_TLS_BSS;
695 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
696 // sections after r/w ones, so that the RelRo sections are contiguous.
697 bool IsRelRo = isRelroSection(Sec);
698 if (IsNonTlsNoBits && !IsRelRo)
699 Rank |= RF_NON_TLS_BSS_RO;
700 if (!IsNonTlsNoBits && IsRelRo)
701 Rank |= RF_NON_TLS_BSS_RO;
703 // The TLS initialization block needs to be a single contiguous block in a R/W
704 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
705 // sections. The TLS NOBITS sections are placed here as they don't take up
706 // virtual address space in the PT_LOAD.
710 // Within the TLS initialization block, the non-nobits sections need to appear
715 // // Some architectures have additional ordering restrictions for sections
716 // // within the same PT_LOAD.
717 if (Config->EMachine == EM_PPC64) {
718 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
719 // that we would like to make sure appear is a specific order to maximize
720 // their coverage by a single signed 16-bit offset from the TOC base
721 // pointer. Conversely, the special .tocbss section should be first among
722 // all SHT_NOBITS sections. This will put it next to the loaded special
723 // PPC64 sections (and, thus, within reach of the TOC base pointer).
724 StringRef Name = Sec->Name;
725 if (Name != ".tocbss")
726 Rank |= RF_PPC_NOT_TOCBSS;
737 if (Name == ".branch_lt")
738 Rank |= RF_PPC_BRANCH_LT;
740 if (Config->EMachine == EM_MIPS) {
741 // All sections with SHF_MIPS_GPREL flag should be grouped together
742 // because data in these sections is addressable with a gp relative address.
743 if (Sec->Flags & SHF_MIPS_GPREL)
744 Rank |= RF_MIPS_GPREL;
746 if (Sec->Name != ".got")
747 Rank |= RF_MIPS_NOT_GOT;
753 static bool compareSectionsNonScript(const OutputSection *A,
754 const OutputSection *B) {
755 if (A->SortRank != B->SortRank)
756 return A->SortRank < B->SortRank;
757 if (!(A->SortRank & RF_NOT_ADDR_SET))
758 return Config->SectionStartMap.lookup(A->Name) <
759 Config->SectionStartMap.lookup(B->Name);
763 // Output section ordering is determined by this function.
764 static bool compareSections(const OutputSection *A, const OutputSection *B) {
765 // For now, put sections mentioned in a linker script
766 // first. Sections not on linker script will have a SectionIndex of
768 int AIndex = A->SectionIndex;
769 int BIndex = B->SectionIndex;
770 if (AIndex != BIndex)
771 return AIndex < BIndex;
773 return compareSectionsNonScript(A, B);
776 // Program header entry
777 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
782 void PhdrEntry::add(OutputSection *Sec) {
786 p_align = std::max(p_align, Sec->Alignment);
787 if (p_type == PT_LOAD)
788 Sec->FirstInPtLoad = First;
791 template <class ELFT>
792 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
793 uint8_t StOther = STV_HIDDEN,
794 uint8_t Binding = STB_WEAK) {
795 // The linker generated symbols are added as STB_WEAK to allow user defined
796 // ones to override them.
797 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
798 /*Size=*/0, Binding, Sec,
802 template <class ELFT>
803 static DefinedRegular *
804 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
805 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
806 SymbolBody *S = Symtab<ELFT>::X->find(Name);
809 if (S->isInCurrentDSO())
811 return cast<DefinedRegular>(
812 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
815 // The beginning and the ending of .rel[a].plt section are marked
816 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
817 // executable. The runtime needs these symbols in order to resolve
818 // all IRELATIVE relocs on startup. For dynamic executables, we don't
819 // need these symbols, since IRELATIVE relocs are resolved through GOT
820 // and PLT. For details, see http://www.airs.com/blog/archives/403.
821 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
824 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
825 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
827 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
828 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
831 // The linker is expected to define some symbols depending on
832 // the linking result. This function defines such symbols.
833 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
834 if (Config->EMachine == EM_MIPS) {
835 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
836 // so that it points to an absolute address which by default is relative
837 // to GOT. Default offset is 0x7ff0.
838 // See "Global Data Symbols" in Chapter 6 in the following document:
839 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
840 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
842 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
843 // start of function and 'gp' pointer into GOT.
844 if (Symtab<ELFT>::X->find("_gp_disp"))
846 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
848 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
849 // pointer. This symbol is used in the code generated by .cpload pseudo-op
850 // in case of using -mno-shared option.
851 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
852 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
853 ElfSym::MipsLocalGp =
854 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
857 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
858 // is magical and is used to produce a R_386_GOTPC relocation.
859 // The R_386_GOTPC relocation value doesn't actually depend on the
860 // symbol value, so it could use an index of STN_UNDEF which, according
861 // to the spec, means the symbol value is 0.
862 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
864 // The situation is even stranger on x86_64 where the assembly doesn't
865 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
866 // an undefined symbol in the .o files.
867 // Given that the symbol is effectively unused, we just create a dummy
868 // hidden one to avoid the undefined symbol error.
869 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
871 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
872 // static linking the linker is required to optimize away any references to
873 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
874 // to avoid the undefined symbol error.
876 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
878 // __ehdr_start is the location of ELF file headers. Note that we define
879 // this symbol unconditionally even when using a linker script, which
880 // differs from the behavior implemented by GNU linker which only define
881 // this symbol if ELF headers are in the memory mapped segment.
882 addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
884 // If linker script do layout we do not need to create any standart symbols.
885 if (Script->Opt.HasSections)
888 auto Add = [](StringRef S) {
889 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
892 ElfSym::Bss = Add("__bss_start");
893 ElfSym::End1 = Add("end");
894 ElfSym::End2 = Add("_end");
895 ElfSym::Etext1 = Add("etext");
896 ElfSym::Etext2 = Add("_etext");
897 ElfSym::Edata1 = Add("edata");
898 ElfSym::Edata2 = Add("_edata");
901 // Sort input sections by section name suffixes for
902 // __attribute__((init_priority(N))).
903 static void sortInitFini(OutputSection *S) {
905 reinterpret_cast<OutputSection *>(S)->sortInitFini();
908 // Sort input sections by the special rule for .ctors and .dtors.
909 static void sortCtorsDtors(OutputSection *S) {
911 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
914 // Sort input sections using the list provided by --symbol-ordering-file.
915 template <class ELFT>
916 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
917 if (Config->SymbolOrderingFile.empty())
920 // Build a map from symbols to their priorities. Symbols that didn't
921 // appear in the symbol ordering file have the lowest priority 0.
922 // All explicitly mentioned symbols have negative (higher) priorities.
923 DenseMap<StringRef, int> SymbolOrder;
924 int Priority = -Config->SymbolOrderingFile.size();
925 for (StringRef S : Config->SymbolOrderingFile)
926 SymbolOrder.insert({S, Priority++});
928 // Build a map from sections to their priorities.
929 DenseMap<SectionBase *, int> SectionOrder;
930 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
931 for (SymbolBody *Body : File->getSymbols()) {
932 auto *D = dyn_cast<DefinedRegular>(Body);
933 if (!D || !D->Section)
935 int &Priority = SectionOrder[D->Section];
936 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
940 // Sort sections by priority.
941 for (OutputSection *Base : OutputSections)
942 if (auto *Sec = dyn_cast<OutputSection>(Base))
943 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
946 template <class ELFT>
947 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
948 for (InputSectionBase *IS : InputSections) {
951 // Scan all relocations. Each relocation goes through a series
952 // of tests to determine if it needs special treatment, such as
953 // creating GOT, PLT, copy relocations, etc.
954 // Note that relocations for non-alloc sections are directly
955 // processed by InputSection::relocateNonAlloc.
956 if (!(IS->Flags & SHF_ALLOC))
958 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
962 if (!Config->Relocatable) {
963 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
968 template <class ELFT> void Writer<ELFT>::createSections() {
969 for (InputSectionBase *IS : InputSections)
971 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
973 sortBySymbolsOrder<ELFT>(OutputSections);
974 sortInitFini(findSection(".init_array"));
975 sortInitFini(findSection(".fini_array"));
976 sortCtorsDtors(findSection(".ctors"));
977 sortCtorsDtors(findSection(".dtors"));
979 for (OutputSection *Sec : OutputSections)
980 Sec->assignOffsets();
983 // We want to find how similar two ranks are.
984 // The more branches in getSectionRank that match, the more similar they are.
985 // Since each branch corresponds to a bit flag, we can just use
986 // countLeadingZeros.
987 static unsigned getRankProximity(OutputSection *A, OutputSection *B) {
988 return countLeadingZeros(A->SortRank ^ B->SortRank);
991 // We want to place orphan sections so that they share as much
992 // characteristics with their neighbors as possible. For example, if
993 // both are rw, or both are tls.
994 template <typename ELFT>
995 static std::vector<OutputSection *>::iterator
996 findOrphanPos(std::vector<OutputSection *>::iterator B,
997 std::vector<OutputSection *>::iterator E) {
998 OutputSection *Sec = *E;
1000 // Find the first element that has as close a rank as possible.
1001 auto I = std::max_element(B, E, [=](OutputSection *A, OutputSection *B) {
1002 return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1007 // Consider all existing sections with the same proximity.
1008 unsigned Proximity = getRankProximity(Sec, *I);
1009 while (I != E && getRankProximity(Sec, *I) == Proximity &&
1010 Sec->SortRank >= (*I)->SortRank)
1015 template <class ELFT> void Writer<ELFT>::sortSections() {
1016 // Don't sort if using -r. It is not necessary and we want to preserve the
1017 // relative order for SHF_LINK_ORDER sections.
1018 if (Config->Relocatable)
1021 if (Script->Opt.HasSections)
1022 Script->adjustSectionsBeforeSorting();
1024 for (OutputSection *Sec : OutputSections)
1025 Sec->SortRank = getSectionRank(Sec);
1027 if (!Script->Opt.HasSections) {
1028 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1029 compareSectionsNonScript);
1033 // The order of the sections in the script is arbitrary and may not agree with
1034 // compareSectionsNonScript. This means that we cannot easily define a
1035 // strict weak ordering. To see why, consider a comparison of a section in the
1036 // script and one not in the script. We have a two simple options:
1037 // * Make them equivalent (a is not less than b, and b is not less than a).
1038 // The problem is then that equivalence has to be transitive and we can
1039 // have sections a, b and c with only b in a script and a less than c
1040 // which breaks this property.
1041 // * Use compareSectionsNonScript. Given that the script order doesn't have
1042 // to match, we can end up with sections a, b, c, d where b and c are in the
1043 // script and c is compareSectionsNonScript less than b. In which case d
1044 // can be equivalent to c, a to b and d < a. As a concrete example:
1045 // .a (rx) # not in script
1046 // .b (rx) # in script
1047 // .c (ro) # in script
1048 // .d (ro) # not in script
1050 // The way we define an order then is:
1051 // * First put script sections at the start and sort the script sections.
1052 // * Move each non-script section to its preferred position. We try
1053 // to put each section in the last position where it it can share
1056 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1059 auto I = OutputSections.begin();
1060 auto E = OutputSections.end();
1062 std::find_if(OutputSections.begin(), E,
1063 [](OutputSection *S) { return S->SectionIndex == INT_MAX; });
1064 while (NonScriptI != E) {
1065 auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1067 // As an optimization, find all sections with the same sort rank
1068 // and insert them with one rotate.
1069 unsigned Rank = (*NonScriptI)->SortRank;
1070 auto End = std::find_if(NonScriptI + 1, E, [=](OutputSection *Sec) {
1071 return Sec->SortRank != Rank;
1073 std::rotate(Pos, NonScriptI, End);
1077 Script->adjustSectionsAfterSorting();
1080 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1081 std::function<void(SyntheticSection *)> Fn) {
1082 for (SyntheticSection *SS : Sections)
1083 if (SS && SS->OutSec && !SS->empty()) {
1085 SS->OutSec->assignOffsets();
1089 // We need to add input synthetic sections early in createSyntheticSections()
1090 // to make them visible from linkescript side. But not all sections are always
1091 // required to be in output. For example we don't need dynamic section content
1092 // sometimes. This function filters out such unused sections from the output.
1093 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1094 // All input synthetic sections that can be empty are placed after
1095 // all regular ones. We iterate over them all and exit at first
1097 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1098 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1101 if (!SS->empty() || !SS->OutSec)
1104 SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1105 SS->OutSec->Sections.end(), SS));
1107 // If there are no other sections in the output section, remove it from the
1109 if (SS->OutSec->Sections.empty())
1110 V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1114 // Create output section objects and add them to OutputSections.
1115 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1116 Out::DebugInfo = findSection(".debug_info");
1117 Out::PreinitArray = findSection(".preinit_array");
1118 Out::InitArray = findSection(".init_array");
1119 Out::FiniArray = findSection(".fini_array");
1121 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1122 // symbols for sections, so that the runtime can get the start and end
1123 // addresses of each section by section name. Add such symbols.
1124 if (!Config->Relocatable) {
1125 addStartEndSymbols();
1126 for (OutputSection *Sec : OutputSections)
1127 addStartStopSymbols(Sec);
1130 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1131 // It should be okay as no one seems to care about the type.
1132 // Even the author of gold doesn't remember why gold behaves that way.
1133 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1135 addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1137 // Define __rel[a]_iplt_{start,end} symbols if needed.
1138 addRelIpltSymbols();
1140 // This responsible for splitting up .eh_frame section into
1141 // pieces. The relocation scan uses those pieces, so this has to be
1143 applySynthetic({In<ELFT>::EhFrame},
1144 [](SyntheticSection *SS) { SS->finalizeContents(); });
1146 // Scan relocations. This must be done after every symbol is declared so that
1147 // we can correctly decide if a dynamic relocation is needed.
1148 forEachRelSec(scanRelocations<ELFT>);
1150 if (InX::Plt && !InX::Plt->empty())
1151 InX::Plt->addSymbols();
1152 if (InX::Iplt && !InX::Iplt->empty())
1153 InX::Iplt->addSymbols();
1155 // Now that we have defined all possible global symbols including linker-
1156 // synthesized ones. Visit all symbols to give the finishing touches.
1157 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1158 SymbolBody *Body = S->body();
1160 if (!includeInSymtab(*Body))
1163 InX::SymTab->addSymbol(Body);
1165 if (InX::DynSymTab && S->includeInDynsym()) {
1166 InX::DynSymTab->addSymbol(Body);
1167 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1168 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1169 In<ELFT>::VerNeed->addSymbol(SS);
1173 // Do not proceed if there was an undefined symbol.
1177 // So far we have added sections from input object files.
1178 // This function adds linker-created Out::* sections.
1179 addPredefinedSections();
1180 removeUnusedSyntheticSections(OutputSections);
1184 // This is a bit of a hack. A value of 0 means undef, so we set it
1185 // to 1 t make __ehdr_start defined. The section number is not
1186 // particularly relevant.
1187 Out::ElfHeader->SectionIndex = 1;
1190 for (OutputSection *Sec : OutputSections) {
1191 Sec->SectionIndex = I++;
1192 Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1195 // Binary and relocatable output does not have PHDRS.
1196 // The headers have to be created before finalize as that can influence the
1197 // image base and the dynamic section on mips includes the image base.
1198 if (!Config->Relocatable && !Config->OFormatBinary) {
1199 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1200 addPtArmExid(Phdrs);
1201 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1204 // Dynamic section must be the last one in this list and dynamic
1205 // symbol table section (DynSymTab) must be the first one.
1206 applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo,
1207 InX::GnuHashTab, In<ELFT>::HashTab, InX::SymTab,
1208 InX::ShStrTab, InX::StrTab, In<ELFT>::VerDef,
1209 InX::DynStrTab, InX::GdbIndex, InX::Got,
1210 InX::MipsGot, InX::IgotPlt, InX::GotPlt,
1211 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1212 InX::Plt, InX::Iplt, In<ELFT>::EhFrameHdr,
1213 In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1214 [](SyntheticSection *SS) { SS->finalizeContents(); });
1216 // Some architectures use small displacements for jump instructions.
1217 // It is linker's responsibility to create thunks containing long
1218 // jump instructions if jump targets are too far. Create thunks.
1219 if (Target->NeedsThunks) {
1220 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1222 // do not require address information. To support range extension Thunks
1223 // we need to assign addresses so that we can tell if jump instructions
1224 // are out of range. This will need to turn into a loop that converges
1225 // when no more Thunks are added
1227 if (TC.createThunks(OutputSections))
1228 applySynthetic({InX::MipsGot},
1229 [](SyntheticSection *SS) { SS->updateAllocSize(); });
1231 // Fill other section headers. The dynamic table is finalized
1232 // at the end because some tags like RELSZ depend on result
1233 // of finalizing other sections.
1234 for (OutputSection *Sec : OutputSections)
1235 Sec->finalize<ELFT>();
1237 // If -compressed-debug-sections is specified, we need to compress
1238 // .debug_* sections. Do it right now because it changes the size of
1240 parallelForEach(OutputSections.begin(), OutputSections.end(),
1241 [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1243 // createThunks may have added local symbols to the static symbol table
1244 applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1245 [](SyntheticSection *SS) { SS->postThunkContents(); });
1248 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1249 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1250 // We have the terminater synthetic section class. Add that at the end.
1251 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1252 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1253 OS->addSection(make<ARMExidxSentinelSection>());
1256 // The linker is expected to define SECNAME_start and SECNAME_end
1257 // symbols for a few sections. This function defines them.
1258 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1259 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1260 // These symbols resolve to the image base if the section does not exist.
1261 // A special value -1 indicates end of the section.
1263 addOptionalRegular<ELFT>(Start, OS, 0);
1264 addOptionalRegular<ELFT>(End, OS, -1);
1267 OS = Out::ElfHeader;
1268 addOptionalRegular<ELFT>(Start, OS, 0);
1269 addOptionalRegular<ELFT>(End, OS, 0);
1273 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1274 Define("__init_array_start", "__init_array_end", Out::InitArray);
1275 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1277 if (OutputSection *Sec = findSection(".ARM.exidx"))
1278 Define("__exidx_start", "__exidx_end", Sec);
1281 // If a section name is valid as a C identifier (which is rare because of
1282 // the leading '.'), linkers are expected to define __start_<secname> and
1283 // __stop_<secname> symbols. They are at beginning and end of the section,
1284 // respectively. This is not requested by the ELF standard, but GNU ld and
1285 // gold provide the feature, and used by many programs.
1286 template <class ELFT>
1287 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1288 StringRef S = Sec->Name;
1289 if (!isValidCIdentifier(S))
1291 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1292 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1295 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1296 for (OutputSection *Sec : OutputSections)
1297 if (Sec->Name == Name)
1302 static bool needsPtLoad(OutputSection *Sec) {
1303 if (!(Sec->Flags & SHF_ALLOC))
1306 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1307 // responsible for allocating space for them, not the PT_LOAD that
1308 // contains the TLS initialization image.
1309 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1314 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1315 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1316 // RW. This means that there is no alignment in the RO to RX transition and we
1317 // cannot create a PT_LOAD there.
1318 static uint64_t computeFlags(uint64_t Flags) {
1320 return PF_R | PF_W | PF_X;
1321 if (Config->SingleRoRx && !(Flags & PF_W))
1322 return Flags | PF_X;
1326 // Decide which program headers to create and which sections to include in each
1328 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1329 std::vector<PhdrEntry> Ret;
1330 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1331 Ret.emplace_back(Type, Flags);
1335 // The first phdr entry is PT_PHDR which describes the program header itself.
1336 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1338 // PT_INTERP must be the second entry if exists.
1339 if (OutputSection *Sec = findSection(".interp"))
1340 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1342 // Add the first PT_LOAD segment for regular output sections.
1343 uint64_t Flags = computeFlags(PF_R);
1344 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1346 // Add the headers. We will remove them if they don't fit.
1347 Load->add(Out::ElfHeader);
1348 Load->add(Out::ProgramHeaders);
1350 for (OutputSection *Sec : OutputSections) {
1351 if (!(Sec->Flags & SHF_ALLOC))
1353 if (!needsPtLoad(Sec))
1356 // Segments are contiguous memory regions that has the same attributes
1357 // (e.g. executable or writable). There is one phdr for each segment.
1358 // Therefore, we need to create a new phdr when the next section has
1359 // different flags or is loaded at a discontiguous address using AT linker
1361 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1362 if (Script->hasLMA(Sec) || Flags != NewFlags) {
1363 Load = AddHdr(PT_LOAD, NewFlags);
1370 // Add a TLS segment if any.
1371 PhdrEntry TlsHdr(PT_TLS, PF_R);
1372 for (OutputSection *Sec : OutputSections)
1373 if (Sec->Flags & SHF_TLS)
1376 Ret.push_back(std::move(TlsHdr));
1378 // Add an entry for .dynamic.
1380 AddHdr(PT_DYNAMIC, InX::Dynamic->OutSec->getPhdrFlags())
1381 ->add(InX::Dynamic->OutSec);
1383 // PT_GNU_RELRO includes all sections that should be marked as
1384 // read-only by dynamic linker after proccessing relocations.
1385 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1386 for (OutputSection *Sec : OutputSections)
1387 if (needsPtLoad(Sec) && isRelroSection(Sec))
1390 Ret.push_back(std::move(RelRo));
1392 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1393 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1394 In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1395 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1396 ->add(In<ELFT>::EhFrameHdr->OutSec);
1398 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1399 // the dynamic linker fill the segment with random data.
1400 if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1401 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1403 // PT_GNU_STACK is a special section to tell the loader to make the
1404 // pages for the stack non-executable. If you really want an executable
1405 // stack, you can pass -z execstack, but that's not recommended for
1406 // security reasons.
1408 if (Config->ZExecstack)
1409 Perm = PF_R | PF_W | PF_X;
1412 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1414 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1415 // is expected to perform W^X violations, such as calling mprotect(2) or
1416 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1418 if (Config->ZWxneeded)
1419 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1421 // Create one PT_NOTE per a group of contiguous .note sections.
1422 PhdrEntry *Note = nullptr;
1423 for (OutputSection *Sec : OutputSections) {
1424 if (Sec->Type == SHT_NOTE) {
1425 if (!Note || Script->hasLMA(Sec))
1426 Note = AddHdr(PT_NOTE, PF_R);
1435 template <class ELFT>
1436 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1437 if (Config->EMachine != EM_ARM)
1439 auto I = std::find_if(
1440 OutputSections.begin(), OutputSections.end(),
1441 [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1442 if (I == OutputSections.end())
1445 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1446 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1448 Phdrs.push_back(ARMExidx);
1451 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1452 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1453 // linker can set the permissions.
1454 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1455 for (const PhdrEntry &P : Phdrs)
1456 if (P.p_type == PT_LOAD && P.First)
1457 P.First->PageAlign = true;
1459 for (const PhdrEntry &P : Phdrs) {
1460 if (P.p_type != PT_GNU_RELRO)
1463 P.First->PageAlign = true;
1464 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1465 // have to align it to a page.
1466 auto End = OutputSections.end();
1467 auto I = std::find(OutputSections.begin(), End, P.Last);
1468 if (I == End || (I + 1) == End)
1470 OutputSection *Sec = *(I + 1);
1471 if (needsPtLoad(Sec))
1472 Sec->PageAlign = true;
1476 // Adjusts the file alignment for a given output section and returns
1477 // its new file offset. The file offset must be the same with its
1478 // virtual address (modulo the page size) so that the loader can load
1479 // executables without any address adjustment.
1480 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1481 OutputSection *First = Sec->FirstInPtLoad;
1482 // If the section is not in a PT_LOAD, we just have to align it.
1484 return alignTo(Off, Sec->Alignment);
1486 // The first section in a PT_LOAD has to have congruent offset and address
1487 // module the page size.
1489 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1491 // If two sections share the same PT_LOAD the file offset is calculated
1492 // using this formula: Off2 = Off1 + (VA2 - VA1).
1493 return First->Offset + Sec->Addr - First->Addr;
1496 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1497 if (Sec->Type == SHT_NOBITS) {
1502 Off = getFileAlignment(Off, Sec);
1504 return Off + Sec->Size;
1507 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1509 for (OutputSection *Sec : OutputSections)
1510 if (Sec->Flags & SHF_ALLOC)
1511 Off = setOffset(Sec, Off);
1512 FileSize = alignTo(Off, Config->Wordsize);
1515 // Assign file offsets to output sections.
1516 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1518 Off = setOffset(Out::ElfHeader, Off);
1519 Off = setOffset(Out::ProgramHeaders, Off);
1521 for (OutputSection *Sec : OutputSections)
1522 Off = setOffset(Sec, Off);
1524 SectionHeaderOff = alignTo(Off, Config->Wordsize);
1525 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1528 // Finalize the program headers. We call this function after we assign
1529 // file offsets and VAs to all sections.
1530 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1531 for (PhdrEntry &P : Phdrs) {
1532 OutputSection *First = P.First;
1533 OutputSection *Last = P.Last;
1535 P.p_filesz = Last->Offset - First->Offset;
1536 if (Last->Type != SHT_NOBITS)
1537 P.p_filesz += Last->Size;
1538 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1539 P.p_offset = First->Offset;
1540 P.p_vaddr = First->Addr;
1542 P.p_paddr = First->getLMA();
1544 if (P.p_type == PT_LOAD)
1545 P.p_align = Config->MaxPageSize;
1546 else if (P.p_type == PT_GNU_RELRO)
1549 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1550 // so round up the size to make sure the offsets are correct.
1551 if (P.p_type == PT_TLS) {
1554 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1559 // The entry point address is chosen in the following ways.
1561 // 1. the '-e' entry command-line option;
1562 // 2. the ENTRY(symbol) command in a linker control script;
1563 // 3. the value of the symbol start, if present;
1564 // 4. the address of the first byte of the .text section, if present;
1565 // 5. the address 0.
1566 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1567 // Case 1, 2 or 3. As a special case, if the symbol is actually
1568 // a number, we'll use that number as an address.
1569 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1572 if (to_integer(Config->Entry, Addr))
1576 if (OutputSection *Sec = findSection(".text")) {
1577 if (Config->WarnMissingEntry)
1578 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1579 utohexstr(Sec->Addr));
1584 if (Config->WarnMissingEntry)
1585 warn("cannot find entry symbol " + Config->Entry +
1586 "; not setting start address");
1590 static uint16_t getELFType() {
1593 if (Config->Relocatable)
1598 // This function is called after we have assigned address and size
1599 // to each section. This function fixes some predefined
1600 // symbol values that depend on section address and size.
1601 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1602 auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1614 // _etext is the first location after the last read-only loadable segment.
1615 // _edata is the first location after the last read-write loadable segment.
1616 // _end is the first location after the uninitialized data region.
1617 PhdrEntry *Last = nullptr;
1618 PhdrEntry *LastRO = nullptr;
1619 PhdrEntry *LastRW = nullptr;
1620 for (PhdrEntry &P : Phdrs) {
1621 if (P.p_type != PT_LOAD)
1624 if (P.p_flags & PF_W)
1630 Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1632 Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1634 Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1637 ElfSym::Bss->Section = findSection(".bss");
1639 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1640 // be equal to the _gp symbol's value.
1641 if (Config->EMachine == EM_MIPS) {
1642 if (!ElfSym::MipsGp->Value) {
1643 // Find GP-relative section with the lowest address
1644 // and use this address to calculate default _gp value.
1646 for (const OutputSection *OS : OutputSections)
1647 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1649 if (Gp != (uint64_t)-1)
1650 ElfSym::MipsGp->Value = Gp + 0x7ff0;
1655 template <class ELFT> void Writer<ELFT>::writeHeader() {
1656 uint8_t *Buf = Buffer->getBufferStart();
1657 memcpy(Buf, "\177ELF", 4);
1659 // Write the ELF header.
1660 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1661 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1662 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1663 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1664 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1665 EHdr->e_type = getELFType();
1666 EHdr->e_machine = Config->EMachine;
1667 EHdr->e_version = EV_CURRENT;
1668 EHdr->e_entry = getEntryAddr();
1669 EHdr->e_shoff = SectionHeaderOff;
1670 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1671 EHdr->e_phnum = Phdrs.size();
1672 EHdr->e_shentsize = sizeof(Elf_Shdr);
1673 EHdr->e_shnum = OutputSections.size() + 1;
1674 EHdr->e_shstrndx = InX::ShStrTab->OutSec->SectionIndex;
1676 if (Config->EMachine == EM_ARM)
1677 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1678 // but we don't have any firm guarantees of conformance. Linux AArch64
1679 // kernels (as of 2016) require an EABI version to be set.
1680 EHdr->e_flags = EF_ARM_EABI_VER5;
1681 else if (Config->EMachine == EM_MIPS)
1682 EHdr->e_flags = getMipsEFlags<ELFT>();
1684 if (!Config->Relocatable) {
1685 EHdr->e_phoff = sizeof(Elf_Ehdr);
1686 EHdr->e_phentsize = sizeof(Elf_Phdr);
1689 // Write the program header table.
1690 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1691 for (PhdrEntry &P : Phdrs) {
1692 HBuf->p_type = P.p_type;
1693 HBuf->p_flags = P.p_flags;
1694 HBuf->p_offset = P.p_offset;
1695 HBuf->p_vaddr = P.p_vaddr;
1696 HBuf->p_paddr = P.p_paddr;
1697 HBuf->p_filesz = P.p_filesz;
1698 HBuf->p_memsz = P.p_memsz;
1699 HBuf->p_align = P.p_align;
1703 // Write the section header table. Note that the first table entry is null.
1704 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1705 for (OutputSection *Sec : OutputSections)
1706 Sec->writeHeaderTo<ELFT>(++SHdrs);
1709 // Open a result file.
1710 template <class ELFT> void Writer<ELFT>::openFile() {
1711 if (!Config->Is64 && FileSize > UINT32_MAX) {
1712 error("output file too large: " + Twine(FileSize) + " bytes");
1716 unlinkAsync(Config->OutputFile);
1717 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1718 FileOutputBuffer::create(Config->OutputFile, FileSize,
1719 FileOutputBuffer::F_executable);
1721 if (auto EC = BufferOrErr.getError())
1722 error("failed to open " + Config->OutputFile + ": " + EC.message());
1724 Buffer = std::move(*BufferOrErr);
1727 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1728 uint8_t *Buf = Buffer->getBufferStart();
1729 for (OutputSection *Sec : OutputSections)
1730 if (Sec->Flags & SHF_ALLOC)
1731 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1734 // Write section contents to a mmap'ed file.
1735 template <class ELFT> void Writer<ELFT>::writeSections() {
1736 uint8_t *Buf = Buffer->getBufferStart();
1738 // PPC64 needs to process relocations in the .opd section
1739 // before processing relocations in code-containing sections.
1740 Out::Opd = findSection(".opd");
1742 Out::OpdBuf = Buf + Out::Opd->Offset;
1743 Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1746 OutputSection *EhFrameHdr =
1747 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1749 // In -r or -emit-relocs mode, write the relocation sections first as in
1750 // ELf_Rel targets we might find out that we need to modify the relocated
1751 // section while doing it.
1752 for (OutputSection *Sec : OutputSections)
1753 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1754 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1756 for (OutputSection *Sec : OutputSections)
1757 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1758 Sec->Type != SHT_RELA)
1759 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1761 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1762 // it should be written after .eh_frame is written.
1763 if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1764 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1767 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1768 if (!InX::BuildId || !InX::BuildId->OutSec)
1771 // Compute a hash of all sections of the output file.
1772 uint8_t *Start = Buffer->getBufferStart();
1773 uint8_t *End = Start + FileSize;
1774 InX::BuildId->writeBuildId({Start, End});
1777 template void elf::writeResult<ELF32LE>();
1778 template void elf::writeResult<ELF32BE>();
1779 template void elf::writeResult<ELF64LE>();
1780 template void elf::writeResult<ELF64BE>();