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(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("." + 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(AllocateHeader);
257 Script->synchronize();
258 Script->assignAddresses(Phdrs);
260 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
261 // 0 sized region. This has to be done late since only after assignAddresses
262 // we know the size of the sections.
265 if (!Config->OFormatBinary)
268 assignFileOffsetsBinary();
271 fixPredefinedSymbols();
274 // It does not make sense try to open the file if we have error already.
277 // Write the result down to a file.
281 if (!Config->OFormatBinary) {
285 writeSectionsBinary();
288 // Backfill .note.gnu.build-id section content. This is done at last
289 // because the content is usually a hash value of the entire output file.
294 // Handle -Map option.
295 writeMapFile<ELFT>(OutputSections);
299 if (auto EC = Buffer->commit())
300 error("failed to write to the output file: " + EC.message());
302 // Flush the output streams and exit immediately. A full shutdown
303 // is a good test that we are keeping track of all allocated memory,
304 // but actually freeing it is a waste of time in a regular linker run.
305 if (Config->ExitEarly)
309 // Initialize Out members.
310 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
311 // Initialize all pointers with NULL. This is needed because
312 // you can call lld::elf::main more than once as a library.
313 memset(&Out::First, 0, sizeof(Out));
315 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
317 In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true);
318 In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
319 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
320 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
321 In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false);
323 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
324 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
325 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
326 Out::ProgramHeaders->updateAlignment(Config->Wordsize);
328 if (needsInterpSection<ELFT>()) {
329 In<ELFT>::Interp = createInterpSection();
330 Add(In<ELFT>::Interp);
332 In<ELFT>::Interp = nullptr;
335 if (!Config->Relocatable)
336 Add(createCommentSection<ELFT>());
338 if (Config->Strip != StripPolicy::All) {
339 In<ELFT>::StrTab = make<StringTableSection>(".strtab", false);
340 In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
343 if (Config->BuildId != BuildIdKind::None) {
344 In<ELFT>::BuildId = make<BuildIdSection>();
345 Add(In<ELFT>::BuildId);
348 In<ELFT>::Common = createCommonSection<ELFT>();
349 if (In<ELFT>::Common)
352 In<ELFT>::Bss = make<BssSection>(".bss");
354 In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro");
355 Add(In<ELFT>::BssRelRo);
357 // Add MIPS-specific sections.
358 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
359 Config->Pic || Config->ExportDynamic;
360 if (Config->EMachine == EM_MIPS) {
361 if (!Config->Shared && HasDynSymTab) {
362 In<ELFT>::MipsRldMap = make<MipsRldMapSection>();
363 Add(In<ELFT>::MipsRldMap);
365 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
367 if (auto *Sec = MipsOptionsSection<ELFT>::create())
369 if (auto *Sec = MipsReginfoSection<ELFT>::create())
374 In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
375 Add(In<ELFT>::DynSymTab);
377 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
378 Add(In<ELFT>::VerSym);
380 if (!Config->VersionDefinitions.empty()) {
381 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
382 Add(In<ELFT>::VerDef);
385 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
386 Add(In<ELFT>::VerNeed);
388 if (Config->GnuHash) {
389 In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
390 Add(In<ELFT>::GnuHashTab);
393 if (Config->SysvHash) {
394 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
395 Add(In<ELFT>::HashTab);
398 Add(In<ELFT>::Dynamic);
399 Add(In<ELFT>::DynStrTab);
400 Add(In<ELFT>::RelaDyn);
403 // Add .got. MIPS' .got is so different from the other archs,
404 // it has its own class.
405 if (Config->EMachine == EM_MIPS) {
406 In<ELFT>::MipsGot = make<MipsGotSection>();
407 Add(In<ELFT>::MipsGot);
409 In<ELFT>::Got = make<GotSection<ELFT>>();
413 In<ELFT>::GotPlt = make<GotPltSection>();
414 Add(In<ELFT>::GotPlt);
415 In<ELFT>::IgotPlt = make<IgotPltSection>();
416 Add(In<ELFT>::IgotPlt);
418 if (Config->GdbIndex) {
419 In<ELFT>::GdbIndex = make<GdbIndexSection>();
420 Add(In<ELFT>::GdbIndex);
423 // We always need to add rel[a].plt to output if it has entries.
424 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
425 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
426 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
427 Add(In<ELFT>::RelaPlt);
429 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
430 // that the IRelative relocations are processed last by the dynamic loader
431 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
432 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
434 Add(In<ELFT>::RelaIplt);
436 In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize);
438 In<ELFT>::Iplt = make<PltSection>(0);
441 if (!Config->Relocatable) {
442 if (Config->EhFrameHdr) {
443 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
444 Add(In<ELFT>::EhFrameHdr);
446 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
447 Add(In<ELFT>::EhFrame);
450 if (In<ELFT>::SymTab)
451 Add(In<ELFT>::SymTab);
452 Add(In<ELFT>::ShStrTab);
453 if (In<ELFT>::StrTab)
454 Add(In<ELFT>::StrTab);
457 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
458 const SymbolBody &B) {
459 if (B.isFile() || B.isSection())
462 // If sym references a section in a discarded group, don't keep it.
463 if (Sec == &InputSection::Discarded)
466 if (Config->Discard == DiscardPolicy::None)
469 // In ELF assembly .L symbols are normally discarded by the assembler.
470 // If the assembler fails to do so, the linker discards them if
471 // * --discard-locals is used.
472 // * The symbol is in a SHF_MERGE section, which is normally the reason for
473 // the assembler keeping the .L symbol.
474 if (!SymName.startswith(".L") && !SymName.empty())
477 if (Config->Discard == DiscardPolicy::Locals)
480 return !Sec || !(Sec->Flags & SHF_MERGE);
483 static bool includeInSymtab(const SymbolBody &B) {
484 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
487 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
488 // Always include absolute symbols.
489 SectionBase *Sec = D->Section;
492 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
494 IS = cast<InputSectionBase>(Sec);
495 // Exclude symbols pointing to garbage-collected sections.
499 if (auto *S = dyn_cast<MergeInputSection>(Sec))
500 if (!S->getSectionPiece(D->Value)->Live)
506 // Local symbols are not in the linker's symbol table. This function scans
507 // each object file's symbol table to copy local symbols to the output.
508 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
509 if (!In<ELFT>::SymTab)
511 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
512 for (SymbolBody *B : F->getLocalSymbols()) {
515 ": broken object: getLocalSymbols returns a non-local symbol");
516 auto *DR = dyn_cast<DefinedRegular>(B);
518 // No reason to keep local undefined symbol in symtab.
521 if (!includeInSymtab(*B))
524 SectionBase *Sec = DR->Section;
525 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
527 In<ELFT>::SymTab->addSymbol(B);
532 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
533 // Create one STT_SECTION symbol for each output section we might
534 // have a relocation with.
535 for (OutputSection *Sec : OutputSections) {
536 if (Sec->Sections.empty())
539 InputSection *IS = Sec->Sections[0];
540 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
541 IS->Type == SHT_RELA)
545 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
546 /*Value=*/0, /*Size=*/0, IS, nullptr);
547 In<ELFT>::SymTab->addSymbol(Sym);
551 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
552 // we would like to make sure appear is a specific order to maximize their
553 // coverage by a single signed 16-bit offset from the TOC base pointer.
554 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
555 // sections. This will put it next to the loaded special PPC64 sections (and,
556 // thus, within reach of the TOC base pointer).
557 static int getPPC64SectionRank(StringRef SectionName) {
558 return StringSwitch<int>(SectionName)
560 .Case(".branch_lt", 2)
567 // All sections with SHF_MIPS_GPREL flag should be grouped together
568 // because data in these sections is addressable with a gp relative address.
569 static int getMipsSectionRank(const OutputSection *S) {
570 if ((S->Flags & SHF_MIPS_GPREL) == 0)
572 if (S->Name == ".got")
577 // Today's loaders have a feature to make segments read-only after
578 // processing dynamic relocations to enhance security. PT_GNU_RELRO
579 // is defined for that.
581 // This function returns true if a section needs to be put into a
582 // PT_GNU_RELRO segment.
583 template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) {
587 uint64_t Flags = Sec->Flags;
589 // Non-allocatable or non-writable sections don't need RELRO because
590 // they are not writable or not even mapped to memory in the first place.
591 // RELRO is for sections that are essentially read-only but need to
592 // be writable only at process startup to allow dynamic linker to
593 // apply relocations.
594 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
597 // Once initialized, TLS data segments are used as data templates
598 // for a thread-local storage. For each new thread, runtime
599 // allocates memory for a TLS and copy templates there. No thread
600 // are supposed to use templates directly. Thus, it can be in RELRO.
604 // .init_array, .preinit_array and .fini_array contain pointers to
605 // functions that are executed on process startup or exit. These
606 // pointers are set by the static linker, and they are not expected
607 // to change at runtime. But if you are an attacker, you could do
608 // interesting things by manipulating pointers in .fini_array, for
609 // example. So they are put into RELRO.
610 uint32_t Type = Sec->Type;
611 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
612 Type == SHT_PREINIT_ARRAY)
615 // .got contains pointers to external symbols. They are resolved by
616 // the dynamic linker when a module is loaded into memory, and after
617 // that they are not expected to change. So, it can be in RELRO.
618 if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
621 // .got.plt contains pointers to external function symbols. They are
622 // by default resolved lazily, so we usually cannot put it into RELRO.
623 // However, if "-z now" is given, the lazy symbol resolution is
624 // disabled, which enables us to put it into RELRO.
625 if (Sec == In<ELFT>::GotPlt->OutSec)
628 // .dynamic section contains data for the dynamic linker, and
629 // there's no need to write to it at runtime, so it's better to put
631 if (Sec == In<ELFT>::Dynamic->OutSec)
634 // .bss.rel.ro is used for copy relocations for read-only symbols.
635 // Since the dynamic linker needs to process copy relocations, the
636 // section cannot be read-only, but once initialized, they shouldn't
638 if (Sec == In<ELFT>::BssRelRo->OutSec)
641 // Sections with some special names are put into RELRO. This is a
642 // bit unfortunate because section names shouldn't be significant in
643 // ELF in spirit. But in reality many linker features depend on
644 // magic section names.
645 StringRef S = Sec->Name;
646 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
647 S == ".eh_frame" || S == ".openbsd.randomdata";
650 template <class ELFT>
651 static bool compareSectionsNonScript(const OutputSection *A,
652 const OutputSection *B) {
653 // Put .interp first because some loaders want to see that section
654 // on the first page of the executable file when loaded into memory.
655 bool AIsInterp = A->Name == ".interp";
656 bool BIsInterp = B->Name == ".interp";
657 if (AIsInterp != BIsInterp)
660 // Allocatable sections go first to reduce the total PT_LOAD size and
661 // so debug info doesn't change addresses in actual code.
662 bool AIsAlloc = A->Flags & SHF_ALLOC;
663 bool BIsAlloc = B->Flags & SHF_ALLOC;
664 if (AIsAlloc != BIsAlloc)
667 // We don't have any special requirements for the relative order of two non
668 // allocatable sections.
672 // We want to put section specified by -T option first, so we
673 // can start assigning VA starting from them later.
674 auto AAddrSetI = Config->SectionStartMap.find(A->Name);
675 auto BAddrSetI = Config->SectionStartMap.find(B->Name);
676 bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
677 bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
678 if (AHasAddrSet != BHasAddrSet)
681 return AAddrSetI->second < BAddrSetI->second;
683 // We want the read only sections first so that they go in the PT_LOAD
684 // covering the program headers at the start of the file.
685 bool AIsWritable = A->Flags & SHF_WRITE;
686 bool BIsWritable = B->Flags & SHF_WRITE;
687 if (AIsWritable != BIsWritable)
690 if (!Config->SingleRoRx) {
691 // For a corresponding reason, put non exec sections first (the program
692 // header PT_LOAD is not executable).
693 // We only do that if we are not using linker scripts, since with linker
694 // scripts ro and rx sections are in the same PT_LOAD, so their relative
695 // order is not important. The same applies for -no-rosegment.
696 bool AIsExec = A->Flags & SHF_EXECINSTR;
697 bool BIsExec = B->Flags & SHF_EXECINSTR;
698 if (AIsExec != BIsExec)
702 // If we got here we know that both A and B are in the same PT_LOAD.
704 bool AIsTls = A->Flags & SHF_TLS;
705 bool BIsTls = B->Flags & SHF_TLS;
706 bool AIsNoBits = A->Type == SHT_NOBITS;
707 bool BIsNoBits = B->Type == SHT_NOBITS;
709 // The first requirement we have is to put (non-TLS) nobits sections last. The
710 // reason is that the only thing the dynamic linker will see about them is a
711 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
712 // PT_LOAD, so that has to correspond to the nobits sections.
713 bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
714 bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
715 if (AIsNonTlsNoBits != BIsNonTlsNoBits)
716 return BIsNonTlsNoBits;
718 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
719 // sections after r/w ones, so that the RelRo sections are contiguous.
720 bool AIsRelRo = isRelroSection<ELFT>(A);
721 bool BIsRelRo = isRelroSection<ELFT>(B);
722 if (AIsRelRo != BIsRelRo)
723 return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
725 // The TLS initialization block needs to be a single contiguous block in a R/W
726 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
727 // sections. The TLS NOBITS sections are placed here as they don't take up
728 // virtual address space in the PT_LOAD.
729 if (AIsTls != BIsTls)
732 // Within the TLS initialization block, the non-nobits sections need to appear
734 if (AIsNoBits != BIsNoBits)
737 // Some architectures have additional ordering restrictions for sections
738 // within the same PT_LOAD.
739 if (Config->EMachine == EM_PPC64)
740 return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name);
741 if (Config->EMachine == EM_MIPS)
742 return getMipsSectionRank(A) < getMipsSectionRank(B);
747 // Output section ordering is determined by this function.
748 template <class ELFT>
749 static bool compareSections(const OutputSection *A, const OutputSection *B) {
750 // For now, put sections mentioned in a linker script first.
751 int AIndex = Script->getSectionIndex(A->Name);
752 int BIndex = Script->getSectionIndex(B->Name);
753 bool AInScript = AIndex != INT_MAX;
754 bool BInScript = BIndex != INT_MAX;
755 if (AInScript != BInScript)
757 // If both are in the script, use that order.
759 return AIndex < BIndex;
761 return compareSectionsNonScript<ELFT>(A, B);
764 // Program header entry
765 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
770 void PhdrEntry::add(OutputSection *Sec) {
774 p_align = std::max(p_align, Sec->Alignment);
775 if (p_type == PT_LOAD)
776 Sec->FirstInPtLoad = First;
779 template <class ELFT>
780 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
781 uint8_t StOther = STV_HIDDEN,
782 uint8_t Binding = STB_WEAK) {
783 // The linker generated symbols are added as STB_WEAK to allow user defined
784 // ones to override them.
785 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
786 /*Size=*/0, Binding, Sec,
790 template <class ELFT>
791 static DefinedRegular *
792 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
793 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
794 SymbolBody *S = Symtab<ELFT>::X->find(Name);
797 if (S->isInCurrentDSO())
799 return cast<DefinedRegular>(
800 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
803 // The beginning and the ending of .rel[a].plt section are marked
804 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
805 // executable. The runtime needs these symbols in order to resolve
806 // all IRELATIVE relocs on startup. For dynamic executables, we don't
807 // need these symbols, since IRELATIVE relocs are resolved through GOT
808 // and PLT. For details, see http://www.airs.com/blog/archives/403.
809 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
810 if (In<ELFT>::DynSymTab)
812 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
813 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
815 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
816 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
819 // The linker is expected to define some symbols depending on
820 // the linking result. This function defines such symbols.
821 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
822 if (Config->EMachine == EM_MIPS) {
823 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
824 // so that it points to an absolute address which by default is relative
825 // to GOT. Default offset is 0x7ff0.
826 // See "Global Data Symbols" in Chapter 6 in the following document:
827 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
828 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
830 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
831 // start of function and 'gp' pointer into GOT.
832 if (Symtab<ELFT>::X->find("_gp_disp"))
834 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
836 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
837 // pointer. This symbol is used in the code generated by .cpload pseudo-op
838 // in case of using -mno-shared option.
839 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
840 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
841 ElfSym::MipsLocalGp =
842 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
845 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
846 // is magical and is used to produce a R_386_GOTPC relocation.
847 // The R_386_GOTPC relocation value doesn't actually depend on the
848 // symbol value, so it could use an index of STN_UNDEF which, according
849 // to the spec, means the symbol value is 0.
850 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
852 // The situation is even stranger on x86_64 where the assembly doesn't
853 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
854 // an undefined symbol in the .o files.
855 // Given that the symbol is effectively unused, we just create a dummy
856 // hidden one to avoid the undefined symbol error.
857 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
859 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
860 // static linking the linker is required to optimize away any references to
861 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
862 // to avoid the undefined symbol error.
863 if (!In<ELFT>::DynSymTab)
864 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
866 // If linker script do layout we do not need to create any standart symbols.
867 if (Script->Opt.HasSections)
870 // __ehdr_start is the location of ELF file headers.
871 addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
873 auto Add = [](StringRef S) {
874 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
877 ElfSym::Bss = Add("__bss_start");
878 ElfSym::End1 = Add("end");
879 ElfSym::End2 = Add("_end");
880 ElfSym::Etext1 = Add("etext");
881 ElfSym::Etext2 = Add("_etext");
882 ElfSym::Edata1 = Add("edata");
883 ElfSym::Edata2 = Add("_edata");
886 // Sort input sections by section name suffixes for
887 // __attribute__((init_priority(N))).
888 static void sortInitFini(OutputSection *S) {
890 reinterpret_cast<OutputSection *>(S)->sortInitFini();
893 // Sort input sections by the special rule for .ctors and .dtors.
894 static void sortCtorsDtors(OutputSection *S) {
896 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
899 // Sort input sections using the list provided by --symbol-ordering-file.
900 template <class ELFT>
901 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
902 if (Config->SymbolOrderingFile.empty())
905 // Build a map from symbols to their priorities. Symbols that didn't
906 // appear in the symbol ordering file have the lowest priority 0.
907 // All explicitly mentioned symbols have negative (higher) priorities.
908 DenseMap<StringRef, int> SymbolOrder;
909 int Priority = -Config->SymbolOrderingFile.size();
910 for (StringRef S : Config->SymbolOrderingFile)
911 SymbolOrder.insert({S, Priority++});
913 // Build a map from sections to their priorities.
914 DenseMap<SectionBase *, int> SectionOrder;
915 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
916 for (SymbolBody *Body : File->getSymbols()) {
917 auto *D = dyn_cast<DefinedRegular>(Body);
918 if (!D || !D->Section)
920 int &Priority = SectionOrder[D->Section];
921 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
925 // Sort sections by priority.
926 for (OutputSection *Base : OutputSections)
927 if (auto *Sec = dyn_cast<OutputSection>(Base))
928 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
931 template <class ELFT>
932 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
933 for (InputSectionBase *IS : InputSections) {
936 // Scan all relocations. Each relocation goes through a series
937 // of tests to determine if it needs special treatment, such as
938 // creating GOT, PLT, copy relocations, etc.
939 // Note that relocations for non-alloc sections are directly
940 // processed by InputSection::relocateNonAlloc.
941 if (!(IS->Flags & SHF_ALLOC))
943 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
947 if (!Config->Relocatable) {
948 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
953 template <class ELFT> void Writer<ELFT>::createSections() {
954 for (InputSectionBase *IS : InputSections)
956 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
958 sortBySymbolsOrder<ELFT>(OutputSections);
959 sortInitFini(findSection(".init_array"));
960 sortInitFini(findSection(".fini_array"));
961 sortCtorsDtors(findSection(".ctors"));
962 sortCtorsDtors(findSection(".dtors"));
964 for (OutputSection *Sec : OutputSections)
965 Sec->assignOffsets();
968 static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) {
969 if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
972 bool S1IsWrite = S1.Flags & SHF_WRITE;
973 bool S2IsWrite = S2.Flags & SHF_WRITE;
974 if (S1IsWrite != S2IsWrite)
978 return true; // RO and RX share a PT_LOAD with linker scripts.
979 return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
982 template <class ELFT> void Writer<ELFT>::sortSections() {
983 // Don't sort if using -r. It is not necessary and we want to preserve the
984 // relative order for SHF_LINK_ORDER sections.
985 if (Config->Relocatable)
987 if (!Script->Opt.HasSections) {
988 std::stable_sort(OutputSections.begin(), OutputSections.end(),
989 compareSectionsNonScript<ELFT>);
992 Script->adjustSectionsBeforeSorting();
994 // The order of the sections in the script is arbitrary and may not agree with
995 // compareSectionsNonScript. This means that we cannot easily define a
996 // strict weak ordering. To see why, consider a comparison of a section in the
997 // script and one not in the script. We have a two simple options:
998 // * Make them equivalent (a is not less than b, and b is not less than a).
999 // The problem is then that equivalence has to be transitive and we can
1000 // have sections a, b and c with only b in a script and a less than c
1001 // which breaks this property.
1002 // * Use compareSectionsNonScript. Given that the script order doesn't have
1003 // to match, we can end up with sections a, b, c, d where b and c are in the
1004 // script and c is compareSectionsNonScript less than b. In which case d
1005 // can be equivalent to c, a to b and d < a. As a concrete example:
1006 // .a (rx) # not in script
1007 // .b (rx) # in script
1008 // .c (ro) # in script
1009 // .d (ro) # not in script
1011 // The way we define an order then is:
1012 // * First put script sections at the start and sort the script and
1013 // non-script sections independently.
1014 // * Move each non-script section to its preferred position. We try
1015 // to put each section in the last position where it it can share
1018 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1019 compareSections<ELFT>);
1021 auto I = OutputSections.begin();
1022 auto E = OutputSections.end();
1024 std::find_if(OutputSections.begin(), E, [](OutputSection *S) {
1025 return Script->getSectionIndex(S->Name) == INT_MAX;
1027 while (NonScriptI != E) {
1028 auto BestPos = std::max_element(
1029 I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) {
1030 bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A);
1031 bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B);
1032 if (ACanSharePtLoad != BCanSharePtLoad)
1033 return BCanSharePtLoad;
1035 bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1036 bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1038 return BCmp; // FIXME: missing test
1040 size_t PosA = &A - &OutputSections[0];
1041 size_t PosB = &B - &OutputSections[0];
1042 return ACmp ? PosA > PosB : PosA < PosB;
1045 // max_element only returns NonScriptI if the range is empty. If the range
1046 // is not empty we should consider moving the the element forward one
1048 if (BestPos != NonScriptI &&
1049 !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1051 std::rotate(BestPos, NonScriptI, NonScriptI + 1);
1055 Script->adjustSectionsAfterSorting();
1058 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1059 std::function<void(SyntheticSection *)> Fn) {
1060 for (SyntheticSection *SS : Sections)
1061 if (SS && SS->OutSec && !SS->empty()) {
1063 SS->OutSec->assignOffsets();
1067 // We need to add input synthetic sections early in createSyntheticSections()
1068 // to make them visible from linkescript side. But not all sections are always
1069 // required to be in output. For example we don't need dynamic section content
1070 // sometimes. This function filters out such unused sections from the output.
1071 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1072 // All input synthetic sections that can be empty are placed after
1073 // all regular ones. We iterate over them all and exit at first
1075 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1076 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1079 if (!SS->empty() || !SS->OutSec)
1082 SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1083 SS->OutSec->Sections.end(), SS));
1085 // If there are no other sections in the output section, remove it from the
1087 if (SS->OutSec->Sections.empty())
1088 V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1092 // Create output section objects and add them to OutputSections.
1093 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1094 Out::DebugInfo = findSection(".debug_info");
1095 Out::PreinitArray = findSection(".preinit_array");
1096 Out::InitArray = findSection(".init_array");
1097 Out::FiniArray = findSection(".fini_array");
1099 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1100 // symbols for sections, so that the runtime can get the start and end
1101 // addresses of each section by section name. Add such symbols.
1102 if (!Config->Relocatable) {
1103 addStartEndSymbols();
1104 for (OutputSection *Sec : OutputSections)
1105 addStartStopSymbols(Sec);
1108 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1109 // It should be okay as no one seems to care about the type.
1110 // Even the author of gold doesn't remember why gold behaves that way.
1111 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1112 if (In<ELFT>::DynSymTab)
1113 addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0);
1115 // Define __rel[a]_iplt_{start,end} symbols if needed.
1116 addRelIpltSymbols();
1118 // This responsible for splitting up .eh_frame section into
1119 // pieces. The relocation scan uses those pieces, so this has to be
1121 applySynthetic({In<ELFT>::EhFrame},
1122 [](SyntheticSection *SS) { SS->finalizeContents(); });
1124 // Scan relocations. This must be done after every symbol is declared so that
1125 // we can correctly decide if a dynamic relocation is needed.
1126 forEachRelSec(scanRelocations<ELFT>);
1128 if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1129 In<ELFT>::Plt->addSymbols();
1130 if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1131 In<ELFT>::Iplt->addSymbols();
1133 // Now that we have defined all possible global symbols including linker-
1134 // synthesized ones. Visit all symbols to give the finishing touches.
1135 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1136 SymbolBody *Body = S->body();
1138 if (!includeInSymtab(*Body))
1140 if (In<ELFT>::SymTab)
1141 In<ELFT>::SymTab->addSymbol(Body);
1143 if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1144 In<ELFT>::DynSymTab->addSymbol(Body);
1145 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1146 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1147 In<ELFT>::VerNeed->addSymbol(SS);
1151 // Do not proceed if there was an undefined symbol.
1155 // So far we have added sections from input object files.
1156 // This function adds linker-created Out::* sections.
1157 addPredefinedSections();
1158 removeUnusedSyntheticSections(OutputSections);
1162 // This is a bit of a hack. A value of 0 means undef, so we set it
1163 // to 1 t make __ehdr_start defined. The section number is not
1164 // particularly relevant.
1165 Out::ElfHeader->SectionIndex = 1;
1168 for (OutputSection *Sec : OutputSections) {
1169 Sec->SectionIndex = I++;
1170 Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name);
1173 // Binary and relocatable output does not have PHDRS.
1174 // The headers have to be created before finalize as that can influence the
1175 // image base and the dynamic section on mips includes the image base.
1176 if (!Config->Relocatable && !Config->OFormatBinary) {
1177 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1178 addPtArmExid(Phdrs);
1182 // Dynamic section must be the last one in this list and dynamic
1183 // symbol table section (DynSymTab) must be the first one.
1184 applySynthetic({In<ELFT>::DynSymTab, In<ELFT>::Bss, In<ELFT>::BssRelRo,
1185 In<ELFT>::GnuHashTab, In<ELFT>::HashTab, In<ELFT>::SymTab,
1186 In<ELFT>::ShStrTab, In<ELFT>::StrTab, In<ELFT>::VerDef,
1187 In<ELFT>::DynStrTab, In<ELFT>::GdbIndex, In<ELFT>::Got,
1188 In<ELFT>::MipsGot, In<ELFT>::IgotPlt, In<ELFT>::GotPlt,
1189 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1190 In<ELFT>::Plt, In<ELFT>::Iplt, In<ELFT>::Plt,
1191 In<ELFT>::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed,
1193 [](SyntheticSection *SS) { SS->finalizeContents(); });
1195 // Some architectures use small displacements for jump instructions.
1196 // It is linker's responsibility to create thunks containing long
1197 // jump instructions if jump targets are too far. Create thunks.
1198 if (Target->NeedsThunks) {
1199 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1201 // do not require address information. To support range extension Thunks
1202 // we need to assign addresses so that we can tell if jump instructions
1203 // are out of range. This will need to turn into a loop that converges
1204 // when no more Thunks are added
1205 ThunkCreator<ELFT> TC;
1206 if (TC.createThunks(OutputSections))
1207 applySynthetic({In<ELFT>::MipsGot},
1208 [](SyntheticSection *SS) { SS->updateAllocSize(); });
1210 // Fill other section headers. The dynamic table is finalized
1211 // at the end because some tags like RELSZ depend on result
1212 // of finalizing other sections.
1213 for (OutputSection *Sec : OutputSections)
1214 Sec->finalize<ELFT>();
1216 // If -compressed-debug-sections is specified, we need to compress
1217 // .debug_* sections. Do it right now because it changes the size of
1219 parallelForEach(OutputSections.begin(), OutputSections.end(),
1220 [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1222 // createThunks may have added local symbols to the static symbol table
1223 applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab},
1224 [](SyntheticSection *SS) { SS->postThunkContents(); });
1227 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1228 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1229 // We have the terminater synthetic section class. Add that at the end.
1230 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1231 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1232 OS->addSection(make<ARMExidxSentinelSection>());
1235 // The linker is expected to define SECNAME_start and SECNAME_end
1236 // symbols for a few sections. This function defines them.
1237 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1238 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1239 // These symbols resolve to the image base if the section does not exist.
1240 // A special value -1 indicates end of the section.
1242 addOptionalRegular<ELFT>(Start, OS, 0);
1243 addOptionalRegular<ELFT>(End, OS, -1);
1246 OS = Out::ElfHeader;
1247 addOptionalRegular<ELFT>(Start, OS, 0);
1248 addOptionalRegular<ELFT>(End, OS, 0);
1252 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1253 Define("__init_array_start", "__init_array_end", Out::InitArray);
1254 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1256 if (OutputSection *Sec = findSection(".ARM.exidx"))
1257 Define("__exidx_start", "__exidx_end", Sec);
1260 // If a section name is valid as a C identifier (which is rare because of
1261 // the leading '.'), linkers are expected to define __start_<secname> and
1262 // __stop_<secname> symbols. They are at beginning and end of the section,
1263 // respectively. This is not requested by the ELF standard, but GNU ld and
1264 // gold provide the feature, and used by many programs.
1265 template <class ELFT>
1266 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1267 StringRef S = Sec->Name;
1268 if (!isValidCIdentifier(S))
1270 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1271 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1274 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1275 for (OutputSection *Sec : OutputSections)
1276 if (Sec->Name == Name)
1281 static bool needsPtLoad(OutputSection *Sec) {
1282 if (!(Sec->Flags & SHF_ALLOC))
1285 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1286 // responsible for allocating space for them, not the PT_LOAD that
1287 // contains the TLS initialization image.
1288 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1293 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1294 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1295 // RW. This means that there is no alignment in the RO to RX transition and we
1296 // cannot create a PT_LOAD there.
1297 static uint64_t computeFlags(uint64_t Flags) {
1299 return PF_R | PF_W | PF_X;
1300 if (Config->SingleRoRx && !(Flags & PF_W))
1301 return Flags | PF_X;
1305 // Decide which program headers to create and which sections to include in each
1307 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1308 std::vector<PhdrEntry> Ret;
1309 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1310 Ret.emplace_back(Type, Flags);
1314 // The first phdr entry is PT_PHDR which describes the program header itself.
1315 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1317 // PT_INTERP must be the second entry if exists.
1318 if (OutputSection *Sec = findSection(".interp"))
1319 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1321 // Add the first PT_LOAD segment for regular output sections.
1322 uint64_t Flags = computeFlags(PF_R);
1323 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1324 for (OutputSection *Sec : OutputSections) {
1325 if (!(Sec->Flags & SHF_ALLOC))
1327 if (!needsPtLoad(Sec))
1330 // Segments are contiguous memory regions that has the same attributes
1331 // (e.g. executable or writable). There is one phdr for each segment.
1332 // Therefore, we need to create a new phdr when the next section has
1333 // different flags or is loaded at a discontiguous address using AT linker
1335 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1336 if (Script->hasLMA(Sec->Name) || Flags != NewFlags) {
1337 Load = AddHdr(PT_LOAD, NewFlags);
1344 // Add a TLS segment if any.
1345 PhdrEntry TlsHdr(PT_TLS, PF_R);
1346 for (OutputSection *Sec : OutputSections)
1347 if (Sec->Flags & SHF_TLS)
1350 Ret.push_back(std::move(TlsHdr));
1352 // Add an entry for .dynamic.
1353 if (In<ELFT>::DynSymTab)
1354 AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1355 ->add(In<ELFT>::Dynamic->OutSec);
1357 // PT_GNU_RELRO includes all sections that should be marked as
1358 // read-only by dynamic linker after proccessing relocations.
1359 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1360 for (OutputSection *Sec : OutputSections)
1361 if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec))
1364 Ret.push_back(std::move(RelRo));
1366 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1367 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1368 In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1369 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1370 ->add(In<ELFT>::EhFrameHdr->OutSec);
1372 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1373 // the dynamic linker fill the segment with random data.
1374 if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1375 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1377 // PT_GNU_STACK is a special section to tell the loader to make the
1378 // pages for the stack non-executable. If you really want an executable
1379 // stack, you can pass -z execstack, but that's not recommended for
1380 // security reasons.
1382 if (Config->ZExecstack)
1383 Perm = PF_R | PF_W | PF_X;
1386 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1388 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1389 // is expected to perform W^X violations, such as calling mprotect(2) or
1390 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1392 if (Config->ZWxneeded)
1393 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1395 // Create one PT_NOTE per a group of contiguous .note sections.
1396 PhdrEntry *Note = nullptr;
1397 for (OutputSection *Sec : OutputSections) {
1398 if (Sec->Type == SHT_NOTE) {
1399 if (!Note || Script->hasLMA(Sec->Name))
1400 Note = AddHdr(PT_NOTE, PF_R);
1409 template <class ELFT>
1410 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1411 if (Config->EMachine != EM_ARM)
1413 auto I = std::find_if(
1414 OutputSections.begin(), OutputSections.end(),
1415 [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1416 if (I == OutputSections.end())
1419 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1420 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1422 Phdrs.push_back(ARMExidx);
1425 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1426 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1427 // linker can set the permissions.
1428 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1429 for (const PhdrEntry &P : Phdrs)
1430 if (P.p_type == PT_LOAD && P.First)
1431 P.First->PageAlign = true;
1433 for (const PhdrEntry &P : Phdrs) {
1434 if (P.p_type != PT_GNU_RELRO)
1437 P.First->PageAlign = true;
1438 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1439 // have to align it to a page.
1440 auto End = OutputSections.end();
1441 auto I = std::find(OutputSections.begin(), End, P.Last);
1442 if (I == End || (I + 1) == End)
1444 OutputSection *Sec = *(I + 1);
1445 if (needsPtLoad(Sec))
1446 Sec->PageAlign = true;
1450 bool elf::allocateHeaders(std::vector<PhdrEntry> &Phdrs,
1451 ArrayRef<OutputSection *> OutputSections,
1454 std::find_if(Phdrs.begin(), Phdrs.end(),
1455 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1456 if (FirstPTLoad == Phdrs.end())
1459 uint64_t HeaderSize = getHeaderSize();
1460 if (HeaderSize > Min) {
1462 std::find_if(Phdrs.begin(), Phdrs.end(),
1463 [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
1464 if (PhdrI != Phdrs.end())
1468 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1470 if (!Script->Opt.HasSections)
1471 Config->ImageBase = Min = std::min(Min, Config->ImageBase);
1473 Out::ElfHeader->Addr = Min;
1474 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
1476 if (Script->hasPhdrsCommands())
1479 if (FirstPTLoad->First)
1480 for (OutputSection *Sec : OutputSections)
1481 if (Sec->FirstInPtLoad == FirstPTLoad->First)
1482 Sec->FirstInPtLoad = Out::ElfHeader;
1483 FirstPTLoad->First = Out::ElfHeader;
1484 if (!FirstPTLoad->Last)
1485 FirstPTLoad->Last = Out::ProgramHeaders;
1489 // We should set file offsets and VAs for elf header and program headers
1490 // sections. These are special, we do not include them into output sections
1491 // list, but have them to simplify the code.
1492 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1493 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1494 // If the script has SECTIONS, assignAddresses will compute the values.
1495 if (Script->Opt.HasSections)
1498 // When -T<section> option is specified, lower the base to make room for those
1501 if (!Config->SectionStartMap.empty())
1502 for (const auto &P : Config->SectionStartMap)
1503 Min = std::min(Min, P.second);
1505 AllocateHeader = allocateHeaders(Phdrs, OutputSections, Min);
1508 // Adjusts the file alignment for a given output section and returns
1509 // its new file offset. The file offset must be the same with its
1510 // virtual address (modulo the page size) so that the loader can load
1511 // executables without any address adjustment.
1512 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1513 OutputSection *First = Sec->FirstInPtLoad;
1514 // If the section is not in a PT_LOAD, we just have to align it.
1516 return alignTo(Off, Sec->Alignment);
1518 // The first section in a PT_LOAD has to have congruent offset and address
1519 // module the page size.
1521 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1523 // If two sections share the same PT_LOAD the file offset is calculated
1524 // using this formula: Off2 = Off1 + (VA2 - VA1).
1525 return First->Offset + Sec->Addr - First->Addr;
1528 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1529 if (Sec->Type == SHT_NOBITS) {
1534 Off = getFileAlignment(Off, Sec);
1536 return Off + Sec->Size;
1539 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1541 for (OutputSection *Sec : OutputSections)
1542 if (Sec->Flags & SHF_ALLOC)
1543 Off = setOffset(Sec, Off);
1544 FileSize = alignTo(Off, Config->Wordsize);
1547 // Assign file offsets to output sections.
1548 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1550 Off = setOffset(Out::ElfHeader, Off);
1551 Off = setOffset(Out::ProgramHeaders, Off);
1553 for (OutputSection *Sec : OutputSections)
1554 Off = setOffset(Sec, Off);
1556 SectionHeaderOff = alignTo(Off, Config->Wordsize);
1557 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1560 // Finalize the program headers. We call this function after we assign
1561 // file offsets and VAs to all sections.
1562 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1563 for (PhdrEntry &P : Phdrs) {
1564 OutputSection *First = P.First;
1565 OutputSection *Last = P.Last;
1567 P.p_filesz = Last->Offset - First->Offset;
1568 if (Last->Type != SHT_NOBITS)
1569 P.p_filesz += Last->Size;
1570 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1571 P.p_offset = First->Offset;
1572 P.p_vaddr = First->Addr;
1574 P.p_paddr = First->getLMA();
1576 if (P.p_type == PT_LOAD)
1577 P.p_align = Config->MaxPageSize;
1578 else if (P.p_type == PT_GNU_RELRO)
1581 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1582 // so round up the size to make sure the offsets are correct.
1583 if (P.p_type == PT_TLS) {
1586 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1591 // The entry point address is chosen in the following ways.
1593 // 1. the '-e' entry command-line option;
1594 // 2. the ENTRY(symbol) command in a linker control script;
1595 // 3. the value of the symbol start, if present;
1596 // 4. the address of the first byte of the .text section, if present;
1597 // 5. the address 0.
1598 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1599 // Case 1, 2 or 3. As a special case, if the symbol is actually
1600 // a number, we'll use that number as an address.
1601 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1604 if (!Config->Entry.getAsInteger(0, Addr))
1608 if (OutputSection *Sec = findSection(".text")) {
1609 if (Config->WarnMissingEntry)
1610 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1611 utohexstr(Sec->Addr));
1616 if (Config->WarnMissingEntry)
1617 warn("cannot find entry symbol " + Config->Entry +
1618 "; not setting start address");
1622 static uint16_t getELFType() {
1625 if (Config->Relocatable)
1630 // This function is called after we have assigned address and size
1631 // to each section. This function fixes some predefined
1632 // symbol values that depend on section address and size.
1633 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1634 auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1646 // _etext is the first location after the last read-only loadable segment.
1647 // _edata is the first location after the last read-write loadable segment.
1648 // _end is the first location after the uninitialized data region.
1649 PhdrEntry *Last = nullptr;
1650 PhdrEntry *LastRO = nullptr;
1651 PhdrEntry *LastRW = nullptr;
1652 for (PhdrEntry &P : Phdrs) {
1653 if (P.p_type != PT_LOAD)
1656 if (P.p_flags & PF_W)
1662 Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1664 Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1666 Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1669 ElfSym::Bss->Section = findSection(".bss");
1671 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1672 // be equal to the _gp symbol's value.
1673 if (Config->EMachine == EM_MIPS) {
1674 if (!ElfSym::MipsGp->Value) {
1675 // Find GP-relative section with the lowest address
1676 // and use this address to calculate default _gp value.
1678 for (const OutputSection *OS : OutputSections)
1679 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1681 if (Gp != (uint64_t)-1)
1682 ElfSym::MipsGp->Value = Gp + 0x7ff0;
1687 template <class ELFT> void Writer<ELFT>::writeHeader() {
1688 uint8_t *Buf = Buffer->getBufferStart();
1689 memcpy(Buf, "\177ELF", 4);
1691 // Write the ELF header.
1692 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1693 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1694 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1695 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1696 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1697 EHdr->e_type = getELFType();
1698 EHdr->e_machine = Config->EMachine;
1699 EHdr->e_version = EV_CURRENT;
1700 EHdr->e_entry = getEntryAddr();
1701 EHdr->e_shoff = SectionHeaderOff;
1702 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1703 EHdr->e_phnum = Phdrs.size();
1704 EHdr->e_shentsize = sizeof(Elf_Shdr);
1705 EHdr->e_shnum = OutputSections.size() + 1;
1706 EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1708 if (Config->EMachine == EM_ARM)
1709 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1710 // but we don't have any firm guarantees of conformance. Linux AArch64
1711 // kernels (as of 2016) require an EABI version to be set.
1712 EHdr->e_flags = EF_ARM_EABI_VER5;
1713 else if (Config->EMachine == EM_MIPS)
1714 EHdr->e_flags = getMipsEFlags<ELFT>();
1716 if (!Config->Relocatable) {
1717 EHdr->e_phoff = sizeof(Elf_Ehdr);
1718 EHdr->e_phentsize = sizeof(Elf_Phdr);
1721 // Write the program header table.
1722 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1723 for (PhdrEntry &P : Phdrs) {
1724 HBuf->p_type = P.p_type;
1725 HBuf->p_flags = P.p_flags;
1726 HBuf->p_offset = P.p_offset;
1727 HBuf->p_vaddr = P.p_vaddr;
1728 HBuf->p_paddr = P.p_paddr;
1729 HBuf->p_filesz = P.p_filesz;
1730 HBuf->p_memsz = P.p_memsz;
1731 HBuf->p_align = P.p_align;
1735 // Write the section header table. Note that the first table entry is null.
1736 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1737 for (OutputSection *Sec : OutputSections)
1738 Sec->writeHeaderTo<ELFT>(++SHdrs);
1741 // Open a result file.
1742 template <class ELFT> void Writer<ELFT>::openFile() {
1743 if (!Config->Is64 && FileSize > UINT32_MAX) {
1744 error("output file too large: " + Twine(FileSize) + " bytes");
1748 unlinkAsync(Config->OutputFile);
1749 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1750 FileOutputBuffer::create(Config->OutputFile, FileSize,
1751 FileOutputBuffer::F_executable);
1753 if (auto EC = BufferOrErr.getError())
1754 error("failed to open " + Config->OutputFile + ": " + EC.message());
1756 Buffer = std::move(*BufferOrErr);
1759 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1760 uint8_t *Buf = Buffer->getBufferStart();
1761 for (OutputSection *Sec : OutputSections)
1762 if (Sec->Flags & SHF_ALLOC)
1763 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1766 // Write section contents to a mmap'ed file.
1767 template <class ELFT> void Writer<ELFT>::writeSections() {
1768 uint8_t *Buf = Buffer->getBufferStart();
1770 // PPC64 needs to process relocations in the .opd section
1771 // before processing relocations in code-containing sections.
1772 Out::Opd = findSection(".opd");
1774 Out::OpdBuf = Buf + Out::Opd->Offset;
1775 Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1778 OutputSection *EhFrameHdr =
1779 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1781 // In -r or -emit-relocs mode, write the relocation sections first as in
1782 // ELf_Rel targets we might find out that we need to modify the relocated
1783 // section while doing it.
1784 for (OutputSection *Sec : OutputSections)
1785 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1786 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1788 for (OutputSection *Sec : OutputSections)
1789 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1790 Sec->Type != SHT_RELA)
1791 Sec->writeTo<ELFT>(Buf + Sec->Offset);
1793 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1794 // it should be written after .eh_frame is written.
1795 if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1796 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1799 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1800 if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1803 // Compute a hash of all sections of the output file.
1804 uint8_t *Start = Buffer->getBufferStart();
1805 uint8_t *End = Start + FileSize;
1806 In<ELFT>::BuildId->writeBuildId({Start, End});
1809 template void elf::writeResult<ELF32LE>();
1810 template void elf::writeResult<ELF32BE>();
1811 template void elf::writeResult<ELF64LE>();
1812 template void elf::writeResult<ELF64BE>();
1814 template bool elf::isRelroSection<ELF32LE>(const OutputSection *);
1815 template bool elf::isRelroSection<ELF32BE>(const OutputSection *);
1816 template bool elf::isRelroSection<ELF64LE>(const OutputSection *);
1817 template bool elf::isRelroSection<ELF64BE>(const OutputSection *);