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();
66 void fixSectionAlignments();
67 void fixPredefinedSymbols();
71 void writeSectionsBinary();
74 std::unique_ptr<FileOutputBuffer> Buffer;
76 std::vector<OutputSection *> OutputSections;
77 OutputSectionFactory Factory{OutputSections};
79 void addRelIpltSymbols();
80 void addStartEndSymbols();
81 void addStartStopSymbols(OutputSection *Sec);
82 uint64_t getEntryAddr();
83 OutputSection *findSection(StringRef Name);
85 std::vector<PhdrEntry> Phdrs;
88 uint64_t SectionHeaderOff;
89 bool AllocateHeader = true;
91 } // anonymous namespace
93 StringRef elf::getOutputSectionName(StringRef Name) {
94 if (Config->Relocatable)
97 // If -emit-relocs is given (which is rare), we need to copy
98 // relocation sections to the output. If input section .foo is
99 // output as .bar, we want to rename .rel.foo .rel.bar as well.
100 if (Config->EmitRelocs) {
101 for (StringRef V : {".rel.", ".rela."}) {
102 if (Name.startswith(V)) {
103 StringRef Inner = getOutputSectionName(Name.substr(V.size() - 1));
104 return Saver.save(Twine(V.drop_back()) + Inner);
110 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
111 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
112 ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
113 StringRef Prefix = V.drop_back();
114 if (Name.startswith(V) || Name == Prefix)
118 // CommonSection is identified as "COMMON" in linker scripts.
119 // By default, it should go to .bss section.
120 if (Name == "COMMON")
123 // ".zdebug_" is a prefix for ZLIB-compressed sections.
124 // Because we decompressed input sections, we want to remove 'z'.
125 if (Name.startswith(".zdebug_"))
126 return Saver.save(Twine(".") + Name.substr(2));
130 template <class ELFT> static bool needsInterpSection() {
131 return !Symtab<ELFT>::X->getSharedFiles().empty() &&
132 !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
135 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
137 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
138 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
139 if (P.p_type != PT_LOAD)
143 uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
146 Phdrs.erase(I, Phdrs.end());
149 // This function scans over the input sections and creates mergeable
150 // synthetic sections. It removes MergeInputSections from array and
151 // adds new synthetic ones. Each synthetic section is added to the
152 // location of the first input section it replaces.
153 static void combineMergableSections() {
154 std::vector<MergeSyntheticSection *> MergeSections;
155 for (InputSectionBase *&S : InputSections) {
156 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
160 // We do not want to handle sections that are not alive, so just remove
161 // them instead of trying to merge.
165 StringRef OutsecName = getOutputSectionName(MS->Name);
166 uint64_t Flags = MS->Flags & ~(uint64_t)(SHF_GROUP | SHF_COMPRESSED);
167 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
170 llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
171 return Sec->Name == OutsecName && Sec->Flags == Flags &&
172 Sec->Alignment == Alignment;
174 if (I == MergeSections.end()) {
175 MergeSyntheticSection *Syn =
176 make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
177 MergeSections.push_back(Syn);
178 I = std::prev(MergeSections.end());
183 (*I)->addSection(MS);
186 std::vector<InputSectionBase *> &V = InputSections;
187 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
190 template <class ELFT> static void combineEhFrameSections() {
191 for (InputSectionBase *&S : InputSections) {
192 EhInputSection *ES = dyn_cast<EhInputSection>(S);
193 if (!ES || !ES->Live)
196 In<ELFT>::EhFrame->addSection(ES);
200 std::vector<InputSectionBase *> &V = InputSections;
201 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
204 // The main function of the writer.
205 template <class ELFT> void Writer<ELFT>::run() {
206 // Create linker-synthesized sections such as .got or .plt.
207 // Such sections are of type input section.
208 createSyntheticSections();
209 combineMergableSections();
211 if (!Config->Relocatable)
212 combineEhFrameSections<ELFT>();
214 // We need to create some reserved symbols such as _end. Create them.
215 if (!Config->Relocatable)
216 addReservedSymbols();
218 // Create output sections.
219 Script->OutputSections = &OutputSections;
220 if (Script->Opt.HasSections) {
221 // If linker script contains SECTIONS commands, let it create sections.
222 Script->processCommands(Factory);
224 // Linker scripts may have left some input sections unassigned.
225 // Assign such sections using the default rule.
226 Script->addOrphanSections(Factory);
228 // If linker script does not contain SECTIONS commands, create
229 // output sections by default rules. We still need to give the
230 // linker script a chance to run, because it might contain
231 // non-SECTIONS commands such as ASSERT.
233 Script->processCommands(Factory);
236 if (Config->Discard != DiscardPolicy::All)
239 if (Config->CopyRelocs)
242 // Now that we have a complete set of output sections. This function
243 // completes section contents. For example, we need to add strings
244 // to the string table, and add entries to .got and .plt.
245 // finalizeSections does that.
250 if (Config->Relocatable) {
253 if (!Script->Opt.HasSections) {
254 fixSectionAlignments();
255 Script->fabricateDefaultCommands(Config->MaxPageSize);
257 Script->assignAddresses(Phdrs);
259 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
260 // 0 sized region. This has to be done late since only after assignAddresses
261 // we know the size of the sections.
264 if (!Config->OFormatBinary)
267 assignFileOffsetsBinary();
270 fixPredefinedSymbols();
273 // It does not make sense try to open the file if we have error already.
276 // Write the result down to a file.
280 if (!Config->OFormatBinary) {
284 writeSectionsBinary();
287 // Backfill .note.gnu.build-id section content. This is done at last
288 // because the content is usually a hash value of the entire output file.
293 // Handle -Map option.
294 writeMapFile<ELFT>(OutputSections);
298 if (auto EC = Buffer->commit())
299 error("failed to write to the output file: " + EC.message());
301 // Flush the output streams and exit immediately. A full shutdown
302 // is a good test that we are keeping track of all allocated memory,
303 // but actually freeing it is a waste of time in a regular linker run.
304 if (Config->ExitEarly)
308 // Initialize Out members.
309 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
310 // Initialize all pointers with NULL. This is needed because
311 // you can call lld::elf::main more than once as a library.
312 memset(&Out::First, 0, sizeof(Out));
314 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
316 In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true);
317 In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
318 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
319 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
320 In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false);
322 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
323 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
324 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
325 Out::ProgramHeaders->updateAlignment(Config->Wordsize);
327 if (needsInterpSection<ELFT>()) {
328 In<ELFT>::Interp = createInterpSection();
329 Add(In<ELFT>::Interp);
331 In<ELFT>::Interp = nullptr;
334 if (!Config->Relocatable)
335 Add(createCommentSection<ELFT>());
337 if (Config->Strip != StripPolicy::All) {
338 In<ELFT>::StrTab = make<StringTableSection>(".strtab", false);
339 In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
342 if (Config->BuildId != BuildIdKind::None) {
343 In<ELFT>::BuildId = make<BuildIdSection>();
344 Add(In<ELFT>::BuildId);
347 In<ELFT>::Common = createCommonSection<ELFT>();
348 if (In<ELFT>::Common)
351 In<ELFT>::Bss = make<BssSection>(".bss");
353 In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro");
354 Add(In<ELFT>::BssRelRo);
356 // Add MIPS-specific sections.
357 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
358 Config->Pic || Config->ExportDynamic;
359 if (Config->EMachine == EM_MIPS) {
360 if (!Config->Shared && HasDynSymTab) {
361 In<ELFT>::MipsRldMap = make<MipsRldMapSection>();
362 Add(In<ELFT>::MipsRldMap);
364 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
366 if (auto *Sec = MipsOptionsSection<ELFT>::create())
368 if (auto *Sec = MipsReginfoSection<ELFT>::create())
373 In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
374 Add(In<ELFT>::DynSymTab);
376 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
377 Add(In<ELFT>::VerSym);
379 if (!Config->VersionDefinitions.empty()) {
380 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
381 Add(In<ELFT>::VerDef);
384 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
385 Add(In<ELFT>::VerNeed);
387 if (Config->GnuHash) {
388 In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
389 Add(In<ELFT>::GnuHashTab);
392 if (Config->SysvHash) {
393 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
394 Add(In<ELFT>::HashTab);
397 Add(In<ELFT>::Dynamic);
398 Add(In<ELFT>::DynStrTab);
399 Add(In<ELFT>::RelaDyn);
402 // Add .got. MIPS' .got is so different from the other archs,
403 // it has its own class.
404 if (Config->EMachine == EM_MIPS) {
405 In<ELFT>::MipsGot = make<MipsGotSection>();
406 Add(In<ELFT>::MipsGot);
408 In<ELFT>::Got = make<GotSection<ELFT>>();
412 In<ELFT>::GotPlt = make<GotPltSection>();
413 Add(In<ELFT>::GotPlt);
414 In<ELFT>::IgotPlt = make<IgotPltSection>();
415 Add(In<ELFT>::IgotPlt);
417 if (Config->GdbIndex) {
418 In<ELFT>::GdbIndex = make<GdbIndexSection>();
419 Add(In<ELFT>::GdbIndex);
422 // We always need to add rel[a].plt to output if it has entries.
423 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
424 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
425 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
426 Add(In<ELFT>::RelaPlt);
428 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
429 // that the IRelative relocations are processed last by the dynamic loader
430 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
431 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
433 Add(In<ELFT>::RelaIplt);
435 In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize);
437 In<ELFT>::Iplt = make<PltSection>(0);
440 if (!Config->Relocatable) {
441 if (Config->EhFrameHdr) {
442 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
443 Add(In<ELFT>::EhFrameHdr);
445 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
446 Add(In<ELFT>::EhFrame);
449 if (In<ELFT>::SymTab)
450 Add(In<ELFT>::SymTab);
451 Add(In<ELFT>::ShStrTab);
452 if (In<ELFT>::StrTab)
453 Add(In<ELFT>::StrTab);
456 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
457 const SymbolBody &B) {
458 if (B.isFile() || B.isSection())
461 // If sym references a section in a discarded group, don't keep it.
462 if (Sec == &InputSection::Discarded)
465 if (Config->Discard == DiscardPolicy::None)
468 // In ELF assembly .L symbols are normally discarded by the assembler.
469 // If the assembler fails to do so, the linker discards them if
470 // * --discard-locals is used.
471 // * The symbol is in a SHF_MERGE section, which is normally the reason for
472 // the assembler keeping the .L symbol.
473 if (!SymName.startswith(".L") && !SymName.empty())
476 if (Config->Discard == DiscardPolicy::Locals)
479 return !Sec || !(Sec->Flags & SHF_MERGE);
482 static bool includeInSymtab(const SymbolBody &B) {
483 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
486 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
487 // Always include absolute symbols.
488 SectionBase *Sec = D->Section;
491 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
493 IS = cast<InputSectionBase>(Sec);
494 // Exclude symbols pointing to garbage-collected sections.
498 if (auto *S = dyn_cast<MergeInputSection>(Sec))
499 if (!S->getSectionPiece(D->Value)->Live)
505 // Local symbols are not in the linker's symbol table. This function scans
506 // each object file's symbol table to copy local symbols to the output.
507 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
508 if (!In<ELFT>::SymTab)
510 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
511 for (SymbolBody *B : F->getLocalSymbols()) {
514 ": broken object: getLocalSymbols returns a non-local symbol");
515 auto *DR = dyn_cast<DefinedRegular>(B);
517 // No reason to keep local undefined symbol in symtab.
520 if (!includeInSymtab(*B))
523 SectionBase *Sec = DR->Section;
524 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
526 In<ELFT>::SymTab->addSymbol(B);
531 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
532 // Create one STT_SECTION symbol for each output section we might
533 // have a relocation with.
534 for (OutputSection *Sec : OutputSections) {
535 if (Sec->Sections.empty())
538 InputSection *IS = Sec->Sections[0];
539 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
540 IS->Type == SHT_RELA)
544 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
545 /*Value=*/0, /*Size=*/0, IS, nullptr);
546 In<ELFT>::SymTab->addSymbol(Sym);
550 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
551 // we would like to make sure appear is a specific order to maximize their
552 // coverage by a single signed 16-bit offset from the TOC base pointer.
553 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
554 // sections. This will put it next to the loaded special PPC64 sections (and,
555 // thus, within reach of the TOC base pointer).
556 static int getPPC64SectionRank(StringRef SectionName) {
557 return StringSwitch<int>(SectionName)
559 .Case(".branch_lt", 2)
566 // All sections with SHF_MIPS_GPREL flag should be grouped together
567 // because data in these sections is addressable with a gp relative address.
568 static int getMipsSectionRank(const OutputSection *S) {
569 if ((S->Flags & SHF_MIPS_GPREL) == 0)
571 if (S->Name == ".got")
576 // Today's loaders have a feature to make segments read-only after
577 // processing dynamic relocations to enhance security. PT_GNU_RELRO
578 // is defined for that.
580 // This function returns true if a section needs to be put into a
581 // PT_GNU_RELRO segment.
582 template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) {
586 uint64_t Flags = Sec->Flags;
588 // Non-allocatable or non-writable sections don't need RELRO because
589 // they are not writable or not even mapped to memory in the first place.
590 // RELRO is for sections that are essentially read-only but need to
591 // be writable only at process startup to allow dynamic linker to
592 // apply relocations.
593 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
596 // Once initialized, TLS data segments are used as data templates
597 // for a thread-local storage. For each new thread, runtime
598 // allocates memory for a TLS and copy templates there. No thread
599 // are supposed to use templates directly. Thus, it can be in RELRO.
603 // .init_array, .preinit_array and .fini_array contain pointers to
604 // functions that are executed on process startup or exit. These
605 // pointers are set by the static linker, and they are not expected
606 // to change at runtime. But if you are an attacker, you could do
607 // interesting things by manipulating pointers in .fini_array, for
608 // example. So they are put into RELRO.
609 uint32_t Type = Sec->Type;
610 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
611 Type == SHT_PREINIT_ARRAY)
614 // .got contains pointers to external symbols. They are resolved by
615 // the dynamic linker when a module is loaded into memory, and after
616 // that they are not expected to change. So, it can be in RELRO.
617 if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
620 // .got.plt contains pointers to external function symbols. They are
621 // by default resolved lazily, so we usually cannot put it into RELRO.
622 // However, if "-z now" is given, the lazy symbol resolution is
623 // disabled, which enables us to put it into RELRO.
624 if (Sec == In<ELFT>::GotPlt->OutSec)
627 // .dynamic section contains data for the dynamic linker, and
628 // there's no need to write to it at runtime, so it's better to put
630 if (Sec == In<ELFT>::Dynamic->OutSec)
633 // .bss.rel.ro is used for copy relocations for read-only symbols.
634 // Since the dynamic linker needs to process copy relocations, the
635 // section cannot be read-only, but once initialized, they shouldn't
637 if (Sec == In<ELFT>::BssRelRo->OutSec)
640 // Sections with some special names are put into RELRO. This is a
641 // bit unfortunate because section names shouldn't be significant in
642 // ELF in spirit. But in reality many linker features depend on
643 // magic section names.
644 StringRef S = Sec->Name;
645 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
646 S == ".eh_frame" || S == ".openbsd.randomdata";
649 template <class ELFT>
650 static bool compareSectionsNonScript(const OutputSection *A,
651 const OutputSection *B) {
652 // Put .interp first because some loaders want to see that section
653 // on the first page of the executable file when loaded into memory.
654 bool AIsInterp = A->Name == ".interp";
655 bool BIsInterp = B->Name == ".interp";
656 if (AIsInterp != BIsInterp)
659 // Allocatable sections go first to reduce the total PT_LOAD size and
660 // so debug info doesn't change addresses in actual code.
661 bool AIsAlloc = A->Flags & SHF_ALLOC;
662 bool BIsAlloc = B->Flags & SHF_ALLOC;
663 if (AIsAlloc != BIsAlloc)
666 // We don't have any special requirements for the relative order of two non
667 // allocatable sections.
671 // We want to put section specified by -T option first, so we
672 // can start assigning VA starting from them later.
673 auto AAddrSetI = Config->SectionStartMap.find(A->Name);
674 auto BAddrSetI = Config->SectionStartMap.find(B->Name);
675 bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
676 bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
677 if (AHasAddrSet != BHasAddrSet)
680 return AAddrSetI->second < BAddrSetI->second;
682 // We want the read only sections first so that they go in the PT_LOAD
683 // covering the program headers at the start of the file.
684 bool AIsWritable = A->Flags & SHF_WRITE;
685 bool BIsWritable = B->Flags & SHF_WRITE;
686 if (AIsWritable != BIsWritable)
689 if (!Config->SingleRoRx) {
690 // For a corresponding reason, put non exec sections first (the program
691 // header PT_LOAD is not executable).
692 // We only do that if we are not using linker scripts, since with linker
693 // scripts ro and rx sections are in the same PT_LOAD, so their relative
694 // order is not important. The same applies for -no-rosegment.
695 bool AIsExec = A->Flags & SHF_EXECINSTR;
696 bool BIsExec = B->Flags & SHF_EXECINSTR;
697 if (AIsExec != BIsExec)
701 // If we got here we know that both A and B are in the same PT_LOAD.
703 bool AIsTls = A->Flags & SHF_TLS;
704 bool BIsTls = B->Flags & SHF_TLS;
705 bool AIsNoBits = A->Type == SHT_NOBITS;
706 bool BIsNoBits = B->Type == SHT_NOBITS;
708 // The first requirement we have is to put (non-TLS) nobits sections last. The
709 // reason is that the only thing the dynamic linker will see about them is a
710 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
711 // PT_LOAD, so that has to correspond to the nobits sections.
712 bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
713 bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
714 if (AIsNonTlsNoBits != BIsNonTlsNoBits)
715 return BIsNonTlsNoBits;
717 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
718 // sections after r/w ones, so that the RelRo sections are contiguous.
719 bool AIsRelRo = isRelroSection<ELFT>(A);
720 bool BIsRelRo = isRelroSection<ELFT>(B);
721 if (AIsRelRo != BIsRelRo)
722 return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
724 // The TLS initialization block needs to be a single contiguous block in a R/W
725 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
726 // sections. The TLS NOBITS sections are placed here as they don't take up
727 // virtual address space in the PT_LOAD.
728 if (AIsTls != BIsTls)
731 // Within the TLS initialization block, the non-nobits sections need to appear
733 if (AIsNoBits != BIsNoBits)
736 // Some architectures have additional ordering restrictions for sections
737 // within the same PT_LOAD.
738 if (Config->EMachine == EM_PPC64)
739 return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name);
740 if (Config->EMachine == EM_MIPS)
741 return getMipsSectionRank(A) < getMipsSectionRank(B);
746 // Output section ordering is determined by this function.
747 template <class ELFT>
748 static bool compareSections(const OutputSection *A, const OutputSection *B) {
749 // For now, put sections mentioned in a linker script first.
750 int AIndex = Script->getSectionIndex(A->Name);
751 int BIndex = Script->getSectionIndex(B->Name);
752 bool AInScript = AIndex != INT_MAX;
753 bool BInScript = BIndex != INT_MAX;
754 if (AInScript != BInScript)
756 // If both are in the script, use that order.
758 return AIndex < BIndex;
760 return compareSectionsNonScript<ELFT>(A, B);
763 // Program header entry
764 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
769 void PhdrEntry::add(OutputSection *Sec) {
773 p_align = std::max(p_align, Sec->Alignment);
774 if (p_type == PT_LOAD)
775 Sec->FirstInPtLoad = First;
778 template <class ELFT>
779 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
780 uint8_t StOther = STV_HIDDEN,
781 uint8_t Binding = STB_WEAK) {
782 // The linker generated symbols are added as STB_WEAK to allow user defined
783 // ones to override them.
784 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
785 /*Size=*/0, Binding, Sec,
789 template <class ELFT>
790 static DefinedRegular *
791 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
792 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
793 SymbolBody *S = Symtab<ELFT>::X->find(Name);
796 if (S->isInCurrentDSO())
798 return cast<DefinedRegular>(
799 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
802 // The beginning and the ending of .rel[a].plt section are marked
803 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
804 // executable. The runtime needs these symbols in order to resolve
805 // all IRELATIVE relocs on startup. For dynamic executables, we don't
806 // need these symbols, since IRELATIVE relocs are resolved through GOT
807 // and PLT. For details, see http://www.airs.com/blog/archives/403.
808 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
809 if (In<ELFT>::DynSymTab)
811 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
812 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
814 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
815 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
818 // The linker is expected to define some symbols depending on
819 // the linking result. This function defines such symbols.
820 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
821 if (Config->EMachine == EM_MIPS) {
822 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
823 // so that it points to an absolute address which by default is relative
824 // to GOT. Default offset is 0x7ff0.
825 // See "Global Data Symbols" in Chapter 6 in the following document:
826 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
827 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
829 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
830 // start of function and 'gp' pointer into GOT.
831 if (Symtab<ELFT>::X->find("_gp_disp"))
833 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
835 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
836 // pointer. This symbol is used in the code generated by .cpload pseudo-op
837 // in case of using -mno-shared option.
838 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
839 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
840 ElfSym::MipsLocalGp =
841 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
844 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
845 // is magical and is used to produce a R_386_GOTPC relocation.
846 // The R_386_GOTPC relocation value doesn't actually depend on the
847 // symbol value, so it could use an index of STN_UNDEF which, according
848 // to the spec, means the symbol value is 0.
849 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
851 // The situation is even stranger on x86_64 where the assembly doesn't
852 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
853 // an undefined symbol in the .o files.
854 // Given that the symbol is effectively unused, we just create a dummy
855 // hidden one to avoid the undefined symbol error.
856 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
858 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
859 // static linking the linker is required to optimize away any references to
860 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
861 // to avoid the undefined symbol error.
862 if (!In<ELFT>::DynSymTab)
863 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
865 // If linker script do layout we do not need to create any standart symbols.
866 if (Script->Opt.HasSections)
869 // __ehdr_start is the location of ELF file headers.
870 addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
872 auto Add = [](StringRef S) {
873 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
876 ElfSym::Bss = Add("__bss_start");
877 ElfSym::End1 = Add("end");
878 ElfSym::End2 = Add("_end");
879 ElfSym::Etext1 = Add("etext");
880 ElfSym::Etext2 = Add("_etext");
881 ElfSym::Edata1 = Add("edata");
882 ElfSym::Edata2 = Add("_edata");
885 // Sort input sections by section name suffixes for
886 // __attribute__((init_priority(N))).
887 static void sortInitFini(OutputSection *S) {
889 reinterpret_cast<OutputSection *>(S)->sortInitFini();
892 // Sort input sections by the special rule for .ctors and .dtors.
893 static void sortCtorsDtors(OutputSection *S) {
895 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
898 // Sort input sections using the list provided by --symbol-ordering-file.
899 template <class ELFT>
900 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
901 if (Config->SymbolOrderingFile.empty())
904 // Build a map from symbols to their priorities. Symbols that didn't
905 // appear in the symbol ordering file have the lowest priority 0.
906 // All explicitly mentioned symbols have negative (higher) priorities.
907 DenseMap<StringRef, int> SymbolOrder;
908 int Priority = -Config->SymbolOrderingFile.size();
909 for (StringRef S : Config->SymbolOrderingFile)
910 SymbolOrder.insert({S, Priority++});
912 // Build a map from sections to their priorities.
913 DenseMap<SectionBase *, int> SectionOrder;
914 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
915 for (SymbolBody *Body : File->getSymbols()) {
916 auto *D = dyn_cast<DefinedRegular>(Body);
917 if (!D || !D->Section)
919 int &Priority = SectionOrder[D->Section];
920 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
924 // Sort sections by priority.
925 for (OutputSection *Base : OutputSections)
926 if (auto *Sec = dyn_cast<OutputSection>(Base))
927 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
930 template <class ELFT>
931 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
932 for (InputSectionBase *IS : InputSections) {
935 // Scan all relocations. Each relocation goes through a series
936 // of tests to determine if it needs special treatment, such as
937 // creating GOT, PLT, copy relocations, etc.
938 // Note that relocations for non-alloc sections are directly
939 // processed by InputSection::relocateNonAlloc.
940 if (!(IS->Flags & SHF_ALLOC))
942 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
946 if (!Config->Relocatable) {
947 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
952 template <class ELFT> void Writer<ELFT>::createSections() {
953 for (InputSectionBase *IS : InputSections)
955 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
957 sortBySymbolsOrder<ELFT>(OutputSections);
958 sortInitFini(findSection(".init_array"));
959 sortInitFini(findSection(".fini_array"));
960 sortCtorsDtors(findSection(".ctors"));
961 sortCtorsDtors(findSection(".dtors"));
963 for (OutputSection *Sec : OutputSections)
964 Sec->assignOffsets();
967 static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) {
968 if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
971 bool S1IsWrite = S1.Flags & SHF_WRITE;
972 bool S2IsWrite = S2.Flags & SHF_WRITE;
973 if (S1IsWrite != S2IsWrite)
977 return true; // RO and RX share a PT_LOAD with linker scripts.
978 return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
981 template <class ELFT> void Writer<ELFT>::sortSections() {
982 // Don't sort if using -r. It is not necessary and we want to preserve the
983 // relative order for SHF_LINK_ORDER sections.
984 if (Config->Relocatable)
986 if (!Script->Opt.HasSections) {
987 std::stable_sort(OutputSections.begin(), OutputSections.end(),
988 compareSectionsNonScript<ELFT>);
991 Script->adjustSectionsBeforeSorting();
993 // The order of the sections in the script is arbitrary and may not agree with
994 // compareSectionsNonScript. This means that we cannot easily define a
995 // strict weak ordering. To see why, consider a comparison of a section in the
996 // script and one not in the script. We have a two simple options:
997 // * Make them equivalent (a is not less than b, and b is not less than a).
998 // The problem is then that equivalence has to be transitive and we can
999 // have sections a, b and c with only b in a script and a less than c
1000 // which breaks this property.
1001 // * Use compareSectionsNonScript. Given that the script order doesn't have
1002 // to match, we can end up with sections a, b, c, d where b and c are in the
1003 // script and c is compareSectionsNonScript less than b. In which case d
1004 // can be equivalent to c, a to b and d < a. As a concrete example:
1005 // .a (rx) # not in script
1006 // .b (rx) # in script
1007 // .c (ro) # in script
1008 // .d (ro) # not in script
1010 // The way we define an order then is:
1011 // * First put script sections at the start and sort the script and
1012 // non-script sections independently.
1013 // * Move each non-script section to its preferred position. We try
1014 // to put each section in the last position where it it can share
1017 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1018 compareSections<ELFT>);
1020 auto I = OutputSections.begin();
1021 auto E = OutputSections.end();
1023 std::find_if(OutputSections.begin(), E, [](OutputSection *S) {
1024 return Script->getSectionIndex(S->Name) == INT_MAX;
1026 while (NonScriptI != E) {
1027 auto BestPos = std::max_element(
1028 I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) {
1029 bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A);
1030 bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B);
1031 if (ACanSharePtLoad != BCanSharePtLoad)
1032 return BCanSharePtLoad;
1034 bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1035 bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1037 return BCmp; // FIXME: missing test
1039 size_t PosA = &A - &OutputSections[0];
1040 size_t PosB = &B - &OutputSections[0];
1041 return ACmp ? PosA > PosB : PosA < PosB;
1044 // max_element only returns NonScriptI if the range is empty. If the range
1045 // is not empty we should consider moving the the element forward one
1047 if (BestPos != NonScriptI &&
1048 !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1050 std::rotate(BestPos, NonScriptI, NonScriptI + 1);
1054 Script->adjustSectionsAfterSorting();
1057 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1058 std::function<void(SyntheticSection *)> Fn) {
1059 for (SyntheticSection *SS : Sections)
1060 if (SS && SS->OutSec && !SS->empty()) {
1062 SS->OutSec->assignOffsets();
1066 // We need to add input synthetic sections early in createSyntheticSections()
1067 // to make them visible from linkescript side. But not all sections are always
1068 // required to be in output. For example we don't need dynamic section content
1069 // sometimes. This function filters out such unused sections from the output.
1070 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1071 // All input synthetic sections that can be empty are placed after
1072 // all regular ones. We iterate over them all and exit at first
1074 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1075 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1078 if (!SS->empty() || !SS->OutSec)
1081 SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1082 SS->OutSec->Sections.end(), SS));
1083 // If there are no other sections in the output section, remove it from the
1085 if (SS->OutSec->Sections.empty())
1086 V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1090 // Create output section objects and add them to OutputSections.
1091 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1092 Out::DebugInfo = findSection(".debug_info");
1093 Out::PreinitArray = findSection(".preinit_array");
1094 Out::InitArray = findSection(".init_array");
1095 Out::FiniArray = findSection(".fini_array");
1097 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1098 // symbols for sections, so that the runtime can get the start and end
1099 // addresses of each section by section name. Add such symbols.
1100 if (!Config->Relocatable) {
1101 addStartEndSymbols();
1102 for (OutputSection *Sec : OutputSections)
1103 addStartStopSymbols(Sec);
1106 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1107 // It should be okay as no one seems to care about the type.
1108 // Even the author of gold doesn't remember why gold behaves that way.
1109 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1110 if (In<ELFT>::DynSymTab)
1111 addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0);
1113 // Define __rel[a]_iplt_{start,end} symbols if needed.
1114 addRelIpltSymbols();
1116 // This responsible for splitting up .eh_frame section into
1117 // pieces. The relocation scan uses those pieces, so this has to be
1119 applySynthetic({In<ELFT>::EhFrame},
1120 [](SyntheticSection *SS) { SS->finalizeContents(); });
1122 // Scan relocations. This must be done after every symbol is declared so that
1123 // we can correctly decide if a dynamic relocation is needed.
1124 forEachRelSec(scanRelocations<ELFT>);
1126 if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1127 In<ELFT>::Plt->addSymbols();
1128 if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1129 In<ELFT>::Iplt->addSymbols();
1131 // Now that we have defined all possible global symbols including linker-
1132 // synthesized ones. Visit all symbols to give the finishing touches.
1133 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1134 SymbolBody *Body = S->body();
1136 if (!includeInSymtab(*Body))
1138 if (In<ELFT>::SymTab)
1139 In<ELFT>::SymTab->addSymbol(Body);
1141 if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1142 In<ELFT>::DynSymTab->addSymbol(Body);
1143 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1144 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1145 In<ELFT>::VerNeed->addSymbol(SS);
1149 // Do not proceed if there was an undefined symbol.
1153 // So far we have added sections from input object files.
1154 // This function adds linker-created Out::* sections.
1155 addPredefinedSections();
1156 removeUnusedSyntheticSections(OutputSections);
1160 // This is a bit of a hack. A value of 0 means undef, so we set it
1161 // to 1 t make __ehdr_start defined. The section number is not
1162 // particularly relevant.
1163 Out::ElfHeader->SectionIndex = 1;
1166 for (OutputSection *Sec : OutputSections) {
1167 Sec->SectionIndex = I++;
1168 Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name);
1171 // Binary and relocatable output does not have PHDRS.
1172 // The headers have to be created before finalize as that can influence the
1173 // image base and the dynamic section on mips includes the image base.
1174 if (!Config->Relocatable && !Config->OFormatBinary) {
1175 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1176 addPtArmExid(Phdrs);
1180 // Dynamic section must be the last one in this list and dynamic
1181 // symbol table section (DynSymTab) must be the first one.
1182 applySynthetic({In<ELFT>::DynSymTab, In<ELFT>::Bss, In<ELFT>::BssRelRo,
1183 In<ELFT>::GnuHashTab, In<ELFT>::HashTab, In<ELFT>::SymTab,
1184 In<ELFT>::ShStrTab, In<ELFT>::StrTab, In<ELFT>::VerDef,
1185 In<ELFT>::DynStrTab, In<ELFT>::GdbIndex, In<ELFT>::Got,
1186 In<ELFT>::MipsGot, In<ELFT>::IgotPlt, In<ELFT>::GotPlt,
1187 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1188 In<ELFT>::Plt, In<ELFT>::Iplt, In<ELFT>::Plt,
1189 In<ELFT>::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed,
1191 [](SyntheticSection *SS) { SS->finalizeContents(); });
1193 // Some architectures use small displacements for jump instructions.
1194 // It is linker's responsibility to create thunks containing long
1195 // jump instructions if jump targets are too far. Create thunks.
1196 if (Target->NeedsThunks) {
1197 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1199 // do not require address information. To support range extension Thunks
1200 // we need to assign addresses so that we can tell if jump instructions
1201 // are out of range. This will need to turn into a loop that converges
1202 // when no more Thunks are added
1203 ThunkCreator<ELFT> TC;
1204 if (TC.createThunks(OutputSections))
1205 applySynthetic({In<ELFT>::MipsGot},
1206 [](SyntheticSection *SS) { SS->updateAllocSize(); });
1208 // Fill other section headers. The dynamic table is finalized
1209 // at the end because some tags like RELSZ depend on result
1210 // of finalizing other sections.
1211 for (OutputSection *Sec : OutputSections)
1212 Sec->finalize<ELFT>();
1214 // If -compressed-debug-sections is specified, we need to compress
1215 // .debug_* sections. Do it right now because it changes the size of
1217 parallelForEach(OutputSections.begin(), OutputSections.end(),
1218 [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1220 // createThunks may have added local symbols to the static symbol table
1221 applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab},
1222 [](SyntheticSection *SS) { SS->postThunkContents(); });
1225 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1226 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1227 // We have the terminater synthetic section class. Add that at the end.
1228 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1229 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1230 OS->addSection(make<ARMExidxSentinelSection>());
1233 // The linker is expected to define SECNAME_start and SECNAME_end
1234 // symbols for a few sections. This function defines them.
1235 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1236 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1237 // These symbols resolve to the image base if the section does not exist.
1238 // A special value -1 indicates end of the section.
1240 addOptionalRegular<ELFT>(Start, OS, 0);
1241 addOptionalRegular<ELFT>(End, OS, -1);
1244 OS = Out::ElfHeader;
1245 addOptionalRegular<ELFT>(Start, OS, 0);
1246 addOptionalRegular<ELFT>(End, OS, 0);
1250 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1251 Define("__init_array_start", "__init_array_end", Out::InitArray);
1252 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1254 if (OutputSection *Sec = findSection(".ARM.exidx"))
1255 Define("__exidx_start", "__exidx_end", Sec);
1258 // If a section name is valid as a C identifier (which is rare because of
1259 // the leading '.'), linkers are expected to define __start_<secname> and
1260 // __stop_<secname> symbols. They are at beginning and end of the section,
1261 // respectively. This is not requested by the ELF standard, but GNU ld and
1262 // gold provide the feature, and used by many programs.
1263 template <class ELFT>
1264 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1265 StringRef S = Sec->Name;
1266 if (!isValidCIdentifier(S))
1268 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1269 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1272 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1273 for (OutputSection *Sec : OutputSections)
1274 if (Sec->Name == Name)
1279 static bool needsPtLoad(OutputSection *Sec) {
1280 if (!(Sec->Flags & SHF_ALLOC))
1283 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1284 // responsible for allocating space for them, not the PT_LOAD that
1285 // contains the TLS initialization image.
1286 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1291 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1292 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1293 // RW. This means that there is no alignment in the RO to RX transition and we
1294 // cannot create a PT_LOAD there.
1295 static uint64_t computeFlags(uint64_t Flags) {
1297 return PF_R | PF_W | PF_X;
1298 if (Config->SingleRoRx && !(Flags & PF_W))
1299 return Flags | PF_X;
1303 // Decide which program headers to create and which sections to include in each
1305 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1306 std::vector<PhdrEntry> Ret;
1307 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1308 Ret.emplace_back(Type, Flags);
1312 // The first phdr entry is PT_PHDR which describes the program header itself.
1313 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1315 // PT_INTERP must be the second entry if exists.
1316 if (OutputSection *Sec = findSection(".interp"))
1317 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1319 // Add the first PT_LOAD segment for regular output sections.
1320 uint64_t Flags = computeFlags(PF_R);
1321 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1322 for (OutputSection *Sec : OutputSections) {
1323 if (!(Sec->Flags & SHF_ALLOC))
1325 if (!needsPtLoad(Sec))
1328 // Segments are contiguous memory regions that has the same attributes
1329 // (e.g. executable or writable). There is one phdr for each segment.
1330 // Therefore, we need to create a new phdr when the next section has
1331 // different flags or is loaded at a discontiguous address using AT linker
1333 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1334 if (Script->hasLMA(Sec->Name) || Flags != NewFlags) {
1335 Load = AddHdr(PT_LOAD, NewFlags);
1342 // Add a TLS segment if any.
1343 PhdrEntry TlsHdr(PT_TLS, PF_R);
1344 for (OutputSection *Sec : OutputSections)
1345 if (Sec->Flags & SHF_TLS)
1348 Ret.push_back(std::move(TlsHdr));
1350 // Add an entry for .dynamic.
1351 if (In<ELFT>::DynSymTab)
1352 AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1353 ->add(In<ELFT>::Dynamic->OutSec);
1355 // PT_GNU_RELRO includes all sections that should be marked as
1356 // read-only by dynamic linker after proccessing relocations.
1357 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1358 for (OutputSection *Sec : OutputSections)
1359 if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec))
1362 Ret.push_back(std::move(RelRo));
1364 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1365 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1366 In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1367 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1368 ->add(In<ELFT>::EhFrameHdr->OutSec);
1370 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1371 // the dynamic linker fill the segment with random data.
1372 if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1373 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1375 // PT_GNU_STACK is a special section to tell the loader to make the
1376 // pages for the stack non-executable. If you really want an executable
1377 // stack, you can pass -z execstack, but that's not recommended for
1378 // security reasons.
1380 if (Config->ZExecstack)
1381 Perm = PF_R | PF_W | PF_X;
1384 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1386 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1387 // is expected to perform W^X violations, such as calling mprotect(2) or
1388 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1390 if (Config->ZWxneeded)
1391 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1393 // Create one PT_NOTE per a group of contiguous .note sections.
1394 PhdrEntry *Note = nullptr;
1395 for (OutputSection *Sec : OutputSections) {
1396 if (Sec->Type == SHT_NOTE) {
1397 if (!Note || Script->hasLMA(Sec->Name))
1398 Note = AddHdr(PT_NOTE, PF_R);
1407 template <class ELFT>
1408 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1409 if (Config->EMachine != EM_ARM)
1411 auto I = std::find_if(
1412 OutputSections.begin(), OutputSections.end(),
1413 [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1414 if (I == OutputSections.end())
1417 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1418 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1420 Phdrs.push_back(ARMExidx);
1423 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1424 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1425 // linker can set the permissions.
1426 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1427 for (const PhdrEntry &P : Phdrs)
1428 if (P.p_type == PT_LOAD && P.First)
1429 P.First->PageAlign = true;
1431 for (const PhdrEntry &P : Phdrs) {
1432 if (P.p_type != PT_GNU_RELRO)
1435 P.First->PageAlign = true;
1436 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1437 // have to align it to a page.
1438 auto End = OutputSections.end();
1439 auto I = std::find(OutputSections.begin(), End, P.Last);
1440 if (I == End || (I + 1) == End)
1442 OutputSection *Sec = *(I + 1);
1443 if (needsPtLoad(Sec))
1444 Sec->PageAlign = true;
1448 bool elf::allocateHeaders(std::vector<PhdrEntry> &Phdrs,
1449 ArrayRef<OutputSection *> OutputSections,
1452 std::find_if(Phdrs.begin(), Phdrs.end(),
1453 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1454 if (FirstPTLoad == Phdrs.end())
1457 uint64_t HeaderSize = getHeaderSize();
1458 if (HeaderSize > Min) {
1460 std::find_if(Phdrs.begin(), Phdrs.end(),
1461 [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
1462 if (PhdrI != Phdrs.end())
1466 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1468 if (!Script->Opt.HasSections)
1469 Config->ImageBase = Min = std::min(Min, Config->ImageBase);
1471 Out::ElfHeader->Addr = Min;
1472 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
1474 if (Script->hasPhdrsCommands())
1477 if (FirstPTLoad->First)
1478 for (OutputSection *Sec : OutputSections)
1479 if (Sec->FirstInPtLoad == FirstPTLoad->First)
1480 Sec->FirstInPtLoad = Out::ElfHeader;
1481 FirstPTLoad->First = Out::ElfHeader;
1482 if (!FirstPTLoad->Last)
1483 FirstPTLoad->Last = Out::ProgramHeaders;
1487 // We should set file offsets and VAs for elf header and program headers
1488 // sections. These are special, we do not include them into output sections
1489 // list, but have them to simplify the code.
1490 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1491 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1492 // If the script has SECTIONS, assignAddresses will compute the values.
1493 if (Script->Opt.HasSections)
1496 // When -T<section> option is specified, lower the base to make room for those
1499 if (!Config->SectionStartMap.empty())
1500 for (const auto &P : Config->SectionStartMap)
1501 Min = std::min(Min, P.second);
1503 AllocateHeader = allocateHeaders(Phdrs, OutputSections, Min);
1506 // Adjusts the file alignment for a given output section and returns
1507 // its new file offset. The file offset must be the same with its
1508 // virtual address (modulo the page size) so that the loader can load
1509 // executables without any address adjustment.
1510 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1511 OutputSection *First = Sec->FirstInPtLoad;
1512 // If the section is not in a PT_LOAD, we just have to align it.
1514 return alignTo(Off, Sec->Alignment);
1516 // The first section in a PT_LOAD has to have congruent offset and address
1517 // module the page size.
1519 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1521 // If two sections share the same PT_LOAD the file offset is calculated
1522 // using this formula: Off2 = Off1 + (VA2 - VA1).
1523 return First->Offset + Sec->Addr - First->Addr;
1526 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1527 if (Sec->Type == SHT_NOBITS) {
1532 Off = getFileAlignment(Off, Sec);
1534 return Off + Sec->Size;
1537 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1539 for (OutputSection *Sec : OutputSections)
1540 if (Sec->Flags & SHF_ALLOC)
1541 Off = setOffset(Sec, Off);
1542 FileSize = alignTo(Off, Config->Wordsize);
1545 // Assign file offsets to output sections.
1546 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1548 Off = setOffset(Out::ElfHeader, Off);
1549 Off = setOffset(Out::ProgramHeaders, Off);
1551 for (OutputSection *Sec : OutputSections)
1552 Off = setOffset(Sec, Off);
1554 SectionHeaderOff = alignTo(Off, Config->Wordsize);
1555 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1558 // Finalize the program headers. We call this function after we assign
1559 // file offsets and VAs to all sections.
1560 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1561 for (PhdrEntry &P : Phdrs) {
1562 OutputSection *First = P.First;
1563 OutputSection *Last = P.Last;
1565 P.p_filesz = Last->Offset - First->Offset;
1566 if (Last->Type != SHT_NOBITS)
1567 P.p_filesz += Last->Size;
1568 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1569 P.p_offset = First->Offset;
1570 P.p_vaddr = First->Addr;
1572 P.p_paddr = First->getLMA();
1574 if (P.p_type == PT_LOAD)
1575 P.p_align = Config->MaxPageSize;
1576 else if (P.p_type == PT_GNU_RELRO)
1579 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1580 // so round up the size to make sure the offsets are correct.
1581 if (P.p_type == PT_TLS) {
1584 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1589 // The entry point address is chosen in the following ways.
1591 // 1. the '-e' entry command-line option;
1592 // 2. the ENTRY(symbol) command in a linker control script;
1593 // 3. the value of the symbol start, if present;
1594 // 4. the address of the first byte of the .text section, if present;
1595 // 5. the address 0.
1596 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1597 // Case 1, 2 or 3. As a special case, if the symbol is actually
1598 // a number, we'll use that number as an address.
1599 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1602 if (!Config->Entry.getAsInteger(0, Addr))
1606 if (OutputSection *Sec = findSection(".text")) {
1607 if (Config->WarnMissingEntry)
1608 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1609 utohexstr(Sec->Addr));
1614 if (Config->WarnMissingEntry)
1615 warn("cannot find entry symbol " + Config->Entry +
1616 "; not setting start address");
1620 static uint16_t getELFType() {
1623 if (Config->Relocatable)
1628 // This function is called after we have assigned address and size
1629 // to each section. This function fixes some predefined
1630 // symbol values that depend on section address and size.
1631 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1632 auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1644 // _etext is the first location after the last read-only loadable segment.
1645 // _edata is the first location after the last read-write loadable segment.
1646 // _end is the first location after the uninitialized data region.
1647 PhdrEntry *Last = nullptr;
1648 PhdrEntry *LastRO = nullptr;
1649 PhdrEntry *LastRW = nullptr;
1650 for (PhdrEntry &P : Phdrs) {
1651 if (P.p_type != PT_LOAD)
1654 if (P.p_flags & PF_W)
1660 Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1662 Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1664 Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1667 ElfSym::Bss->Section = findSection(".bss");
1669 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1670 // be equal to the _gp symbol's value.
1671 if (Config->EMachine == EM_MIPS) {
1672 if (!ElfSym::MipsGp->Value) {
1673 // Find GP-relative section with the lowest address
1674 // and use this address to calculate default _gp value.
1676 for (const OutputSection *OS : OutputSections)
1677 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1679 if (Gp != (uint64_t)-1)
1680 ElfSym::MipsGp->Value = Gp + 0x7ff0;
1685 template <class ELFT> void Writer<ELFT>::writeHeader() {
1686 uint8_t *Buf = Buffer->getBufferStart();
1687 memcpy(Buf, "\177ELF", 4);
1689 // Write the ELF header.
1690 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1691 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1692 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1693 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1694 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1695 EHdr->e_type = getELFType();
1696 EHdr->e_machine = Config->EMachine;
1697 EHdr->e_version = EV_CURRENT;
1698 EHdr->e_entry = getEntryAddr();
1699 EHdr->e_shoff = SectionHeaderOff;
1700 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1701 EHdr->e_phnum = Phdrs.size();
1702 EHdr->e_shentsize = sizeof(Elf_Shdr);
1703 EHdr->e_shnum = OutputSections.size() + 1;
1704 EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1706 if (Config->EMachine == EM_ARM)
1707 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1708 // but we don't have any firm guarantees of conformance. Linux AArch64
1709 // kernels (as of 2016) require an EABI version to be set.
1710 EHdr->e_flags = EF_ARM_EABI_VER5;
1711 else if (Config->EMachine == EM_MIPS)
1712 EHdr->e_flags = getMipsEFlags<ELFT>();
1714 if (!Config->Relocatable) {
1715 EHdr->e_phoff = sizeof(Elf_Ehdr);
1716 EHdr->e_phentsize = sizeof(Elf_Phdr);
1719 // Write the program header table.
1720 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1721 for (PhdrEntry &P : Phdrs) {
1722 HBuf->p_type = P.p_type;
1723 HBuf->p_flags = P.p_flags;
1724 HBuf->p_offset = P.p_offset;
1725 HBuf->p_vaddr = P.p_vaddr;
1726 HBuf->p_paddr = P.p_paddr;
1727 HBuf->p_filesz = P.p_filesz;
1728 HBuf->p_memsz = P.p_memsz;
1729 HBuf->p_align = P.p_align;
1733 // Write the section header table. Note that the first table entry is null.
1734 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1735 for (OutputSection *Sec : OutputSections)
1736 Sec->writeHeaderTo<ELFT>(++SHdrs);
1739 // Open a result file.
1740 template <class ELFT> void Writer<ELFT>::openFile() {
1741 if (!Config->Is64 && FileSize > UINT32_MAX) {
1742 error("output file too large: " + Twine(FileSize) + " bytes");
1746 unlinkAsync(Config->OutputFile);
1747 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1748 FileOutputBuffer::create(Config->OutputFile, FileSize,
1749 FileOutputBuffer::F_executable);
1751 if (auto EC = BufferOrErr.getError())
1752 error("failed to open " + Config->OutputFile + ": " + EC.message());
1754 Buffer = std::move(*BufferOrErr);
1757 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1758 uint8_t *Buf = Buffer->getBufferStart();
1759 for (OutputSection *Sec : OutputSections)
1760 if (Sec->Flags & SHF_ALLOC)
1761 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1764 // Write section contents to a mmap'ed file.
1765 template <class ELFT> void Writer<ELFT>::writeSections() {
1766 uint8_t *Buf = Buffer->getBufferStart();
1768 // PPC64 needs to process relocations in the .opd section
1769 // before processing relocations in code-containing sections.
1770 Out::Opd = findSection(".opd");
1772 Out::OpdBuf = Buf + Out::Opd->Offset;
1773 Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1776 OutputSection *EhFrameHdr =
1777 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1779 // In -r or -emit-relocs mode, write the relocation sections first as in
1780 // ELf_Rel targets we might find out that we need to modify the relocated
1781 // section while doing it.
1782 for (OutputSection *Sec : OutputSections)
1783 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1784 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1786 for (OutputSection *Sec : OutputSections)
1787 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1788 Sec->Type != SHT_RELA)
1789 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1791 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1792 // it should be written after .eh_frame is written.
1793 if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1794 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1797 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1798 if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1801 // Compute a hash of all sections of the output file.
1802 uint8_t *Start = Buffer->getBufferStart();
1803 uint8_t *End = Start + FileSize;
1804 In<ELFT>::BuildId->writeBuildId({Start, End});
1807 template void elf::writeResult<ELF32LE>();
1808 template void elf::writeResult<ELF32BE>();
1809 template void elf::writeResult<ELF64LE>();
1810 template void elf::writeResult<ELF64BE>();
1812 template bool elf::isRelroSection<ELF32LE>(const OutputSection *);
1813 template bool elf::isRelroSection<ELF32BE>(const OutputSection *);
1814 template bool elf::isRelroSection<ELF64LE>(const OutputSection *);
1815 template bool elf::isRelroSection<ELF64BE>(const OutputSection *);