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 "LinkerScript.h"
14 #include "OutputSections.h"
15 #include "Relocations.h"
17 #include "SymbolTable.h"
18 #include "SyntheticSections.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/FileOutputBuffer.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm::ELF;
30 using namespace llvm::object;
31 using namespace llvm::support;
32 using namespace llvm::support::endian;
35 using namespace lld::elf;
38 // The writer writes a SymbolTable result to a file.
39 template <class ELFT> class Writer {
41 typedef typename ELFT::uint uintX_t;
42 typedef typename ELFT::Shdr Elf_Shdr;
43 typedef typename ELFT::Ehdr Elf_Ehdr;
44 typedef typename ELFT::Phdr Elf_Phdr;
45 typedef typename ELFT::Sym Elf_Sym;
46 typedef typename ELFT::SymRange Elf_Sym_Range;
47 typedef typename ELFT::Rela Elf_Rela;
51 void createSyntheticSections();
52 void copyLocalSymbols();
53 void addReservedSymbols();
54 void addInputSec(InputSectionBase<ELFT> *S);
55 void createSections();
56 void forEachRelSec(std::function<void(InputSectionBase<ELFT> &)> Fn);
58 void finalizeSections();
59 void addPredefinedSections();
61 std::vector<PhdrEntry> createPhdrs();
62 void removeEmptyPTLoad();
63 void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
64 void assignAddresses();
65 void assignFileOffsets();
66 void assignFileOffsetsBinary();
69 void fixSectionAlignments();
70 void fixAbsoluteSymbols();
74 void writeSectionsBinary();
77 std::unique_ptr<FileOutputBuffer> Buffer;
79 std::vector<OutputSectionBase *> OutputSections;
80 OutputSectionFactory<ELFT> Factory;
82 void addRelIpltSymbols();
83 void addStartEndSymbols();
84 void addStartStopSymbols(OutputSectionBase *Sec);
85 uintX_t getEntryAddr();
86 OutputSectionBase *findSection(StringRef Name);
88 std::vector<PhdrEntry> Phdrs;
91 uintX_t SectionHeaderOff;
92 bool AllocateHeader = true;
94 } // anonymous namespace
96 StringRef elf::getOutputSectionName(StringRef Name) {
97 if (Config->Relocatable)
101 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
102 ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
103 ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
104 StringRef Prefix = V.drop_back();
105 if (Name.startswith(V) || Name == Prefix)
109 // CommonSection is identified as "COMMON" in linker scripts.
110 // By default, it should go to .bss section.
111 if (Name == "COMMON")
114 // ".zdebug_" is a prefix for ZLIB-compressed sections.
115 // Because we decompressed input sections, we want to remove 'z'.
116 if (Name.startswith(".zdebug_"))
117 return Saver.save(Twine(".") + Name.substr(2));
121 template <class ELFT> void elf::reportDiscarded(InputSectionBase<ELFT> *IS) {
122 if (!Config->PrintGcSections)
124 errs() << "removing unused section from '" << IS->Name << "' in file '"
125 << IS->getFile()->getName() << "'\n";
128 template <class ELFT> static bool needsInterpSection() {
129 return !Symtab<ELFT>::X->getSharedFiles().empty() &&
130 !Config->DynamicLinker.empty() &&
131 !Script<ELFT>::X->ignoreInterpSection();
134 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
136 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
137 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
138 if (P.p_type != PT_LOAD)
142 uintX_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
145 Phdrs.erase(I, Phdrs.end());
148 // The main function of the writer.
149 template <class ELFT> void Writer<ELFT>::run() {
150 // Create linker-synthesized sections such as .got or .plt.
151 // Such sections are of type input section.
152 createSyntheticSections();
154 // We need to create some reserved symbols such as _end. Create them.
155 if (!Config->Relocatable)
156 addReservedSymbols();
158 // Some architectures use small displacements for jump instructions.
159 // It is linker's responsibility to create thunks containing long
160 // jump instructions if jump targets are too far. Create thunks.
161 if (Target->NeedsThunks)
162 forEachRelSec(createThunks<ELFT>);
164 // Create output sections.
165 Script<ELFT>::X->OutputSections = &OutputSections;
166 if (ScriptConfig->HasSections) {
167 // If linker script contains SECTIONS commands, let it create sections.
168 Script<ELFT>::X->processCommands(Factory);
170 // Linker scripts may have left some input sections unassigned.
171 // Assign such sections using the default rule.
172 Script<ELFT>::X->addOrphanSections(Factory);
174 // If linker script does not contain SECTIONS commands, create
175 // output sections by default rules. We still need to give the
176 // linker script a chance to run, because it might contain
177 // non-SECTIONS commands such as ASSERT.
179 Script<ELFT>::X->processCommands(Factory);
182 if (Config->Discard != DiscardPolicy::All)
185 // Now that we have a complete set of output sections. This function
186 // completes section contents. For example, we need to add strings
187 // to the string table, and add entries to .got and .plt.
188 // finalizeSections does that.
193 if (Config->Relocatable) {
196 if (ScriptConfig->HasSections) {
197 Script<ELFT>::X->assignAddresses(Phdrs);
199 fixSectionAlignments();
203 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204 // 0 sized region. This has to be done late since only after assignAddresses
205 // we know the size of the sections.
208 if (!Config->OFormatBinary)
211 assignFileOffsetsBinary();
214 fixAbsoluteSymbols();
217 // Write the result down to a file.
221 if (!Config->OFormatBinary) {
225 writeSectionsBinary();
228 // Backfill .note.gnu.build-id section content. This is done at last
229 // because the content is usually a hash value of the entire output file.
234 if (auto EC = Buffer->commit())
235 error(EC, "failed to write to the output file");
237 // Flush the output streams and exit immediately. A full shutdown
238 // is a good test that we are keeping track of all allocated memory,
239 // but actually freeing it is a waste of time in a regular linker run.
240 if (Config->ExitEarly)
244 // Initialize Out<ELFT> members.
245 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
246 // Initialize all pointers with NULL. This is needed because
247 // you can call lld::elf::main more than once as a library.
248 memset(&Out<ELFT>::First, 0, sizeof(Out<ELFT>));
250 // Create singleton output sections.
252 make<OutputSection<ELFT>>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
253 Out<ELFT>::BssRelRo = make<OutputSection<ELFT>>(".bss.rel.ro", SHT_NOBITS,
254 SHF_ALLOC | SHF_WRITE);
255 In<ELFT>::DynStrTab = make<StringTableSection<ELFT>>(".dynstr", true);
256 In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
257 Out<ELFT>::EhFrame = make<EhOutputSection<ELFT>>();
258 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
259 Config->Rela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
260 In<ELFT>::ShStrTab = make<StringTableSection<ELFT>>(".shstrtab", false);
262 Out<ELFT>::ElfHeader = make<OutputSectionBase>("", 0, SHF_ALLOC);
263 Out<ELFT>::ElfHeader->Size = sizeof(Elf_Ehdr);
264 Out<ELFT>::ProgramHeaders = make<OutputSectionBase>("", 0, SHF_ALLOC);
265 Out<ELFT>::ProgramHeaders->updateAlignment(sizeof(uintX_t));
267 if (needsInterpSection<ELFT>()) {
268 In<ELFT>::Interp = createInterpSection<ELFT>();
269 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Interp);
271 In<ELFT>::Interp = nullptr;
274 if (!Config->Relocatable)
275 Symtab<ELFT>::X->Sections.push_back(createCommentSection<ELFT>());
277 if (Config->Strip != StripPolicy::All) {
278 In<ELFT>::StrTab = make<StringTableSection<ELFT>>(".strtab", false);
279 In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
282 if (Config->BuildId != BuildIdKind::None) {
283 In<ELFT>::BuildId = make<BuildIdSection<ELFT>>();
284 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::BuildId);
287 InputSection<ELFT> *Common = createCommonSection<ELFT>();
288 if (!Common->Data.empty()) {
289 In<ELFT>::Common = Common;
290 Symtab<ELFT>::X->Sections.push_back(Common);
293 // Add MIPS-specific sections.
294 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() || Config->Pic;
295 if (Config->EMachine == EM_MIPS) {
296 if (!Config->Shared && HasDynSymTab) {
297 In<ELFT>::MipsRldMap = make<MipsRldMapSection<ELFT>>();
298 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::MipsRldMap);
300 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
301 Symtab<ELFT>::X->Sections.push_back(Sec);
302 if (auto *Sec = MipsOptionsSection<ELFT>::create())
303 Symtab<ELFT>::X->Sections.push_back(Sec);
304 if (auto *Sec = MipsReginfoSection<ELFT>::create())
305 Symtab<ELFT>::X->Sections.push_back(Sec);
309 In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
310 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::DynSymTab);
312 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
313 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerSym);
315 if (!Config->VersionDefinitions.empty()) {
316 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
317 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerDef);
320 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
321 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerNeed);
323 if (Config->GnuHash) {
324 In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
325 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GnuHashTab);
328 if (Config->SysvHash) {
329 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
330 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::HashTab);
333 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Dynamic);
334 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::DynStrTab);
335 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaDyn);
338 // Add .got. MIPS' .got is so different from the other archs,
339 // it has its own class.
340 if (Config->EMachine == EM_MIPS) {
341 In<ELFT>::MipsGot = make<MipsGotSection<ELFT>>();
342 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::MipsGot);
344 In<ELFT>::Got = make<GotSection<ELFT>>();
345 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Got);
348 In<ELFT>::GotPlt = make<GotPltSection<ELFT>>();
349 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GotPlt);
350 In<ELFT>::IgotPlt = make<IgotPltSection<ELFT>>();
351 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::IgotPlt);
353 if (Config->GdbIndex) {
354 In<ELFT>::GdbIndex = make<GdbIndexSection<ELFT>>();
355 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GdbIndex);
358 // We always need to add rel[a].plt to output if it has entries.
359 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
360 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
361 Config->Rela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
362 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaPlt);
364 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
365 // that the IRelative relocations are processed last by the dynamic loader
366 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
367 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
369 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaIplt);
371 In<ELFT>::Plt = make<PltSection<ELFT>>();
372 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Plt);
373 In<ELFT>::Iplt = make<IpltSection<ELFT>>();
374 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Iplt);
376 if (Config->EhFrameHdr) {
377 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
378 Symtab<ELFT>::X->Sections.push_back(In<ELFT>::EhFrameHdr);
382 template <class ELFT>
383 static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
384 const SymbolBody &B) {
388 // We keep sections in symtab for relocatable output.
390 return Config->Relocatable;
392 // If sym references a section in a discarded group, don't keep it.
393 if (Sec == &InputSection<ELFT>::Discarded)
396 if (Config->Discard == DiscardPolicy::None)
399 // In ELF assembly .L symbols are normally discarded by the assembler.
400 // If the assembler fails to do so, the linker discards them if
401 // * --discard-locals is used.
402 // * The symbol is in a SHF_MERGE section, which is normally the reason for
403 // the assembler keeping the .L symbol.
404 if (!SymName.startswith(".L") && !SymName.empty())
407 if (Config->Discard == DiscardPolicy::Locals)
410 return !Sec || !(Sec->Flags & SHF_MERGE);
413 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
414 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
417 // If --retain-symbols-file is given, we'll keep only symbols listed in that
419 if (Config->Discard == DiscardPolicy::RetainFile &&
420 !Config->RetainSymbolsFile.count(B.getName()))
423 if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
424 // Always include absolute symbols.
427 // Exclude symbols pointing to garbage-collected sections.
428 if (!D->Section->Live)
430 if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
431 if (!S->getSectionPiece(D->Value)->Live)
437 // Local symbols are not in the linker's symbol table. This function scans
438 // each object file's symbol table to copy local symbols to the output.
439 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
440 if (!In<ELFT>::SymTab)
442 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
443 for (SymbolBody *B : F->getLocalSymbols()) {
446 ": broken object: getLocalSymbols returns a non-local symbol");
447 auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
449 // No reason to keep local undefined symbol in symtab.
452 if (!includeInSymtab<ELFT>(*B))
455 InputSectionBase<ELFT> *Sec = DR->Section;
456 if (!shouldKeepInSymtab<ELFT>(Sec, B->getName(), *B))
458 In<ELFT>::SymTab->addLocal(B);
463 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
464 // we would like to make sure appear is a specific order to maximize their
465 // coverage by a single signed 16-bit offset from the TOC base pointer.
466 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
467 // sections. This will put it next to the loaded special PPC64 sections (and,
468 // thus, within reach of the TOC base pointer).
469 static int getPPC64SectionRank(StringRef SectionName) {
470 return StringSwitch<int>(SectionName)
472 .Case(".branch_lt", 2)
479 // All sections with SHF_MIPS_GPREL flag should be grouped together
480 // because data in these sections is addressable with a gp relative address.
481 static int getMipsSectionRank(const OutputSectionBase *S) {
482 if ((S->Flags & SHF_MIPS_GPREL) == 0)
484 if (S->getName() == ".got")
489 template <class ELFT> bool elf::isRelroSection(const OutputSectionBase *Sec) {
492 uint64_t Flags = Sec->Flags;
493 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
497 uint32_t Type = Sec->Type;
498 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
499 Type == SHT_PREINIT_ARRAY)
501 if (Sec == In<ELFT>::GotPlt->OutSec)
503 if (Sec == In<ELFT>::Dynamic->OutSec)
505 if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
507 if (Sec == Out<ELFT>::BssRelRo)
509 StringRef S = Sec->getName();
510 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
511 S == ".eh_frame" || S == ".openbsd.randomdata";
514 template <class ELFT>
515 static bool compareSectionsNonScript(const OutputSectionBase *A,
516 const OutputSectionBase *B) {
517 // Put .interp first because some loaders want to see that section
518 // on the first page of the executable file when loaded into memory.
519 bool AIsInterp = A->getName() == ".interp";
520 bool BIsInterp = B->getName() == ".interp";
521 if (AIsInterp != BIsInterp)
524 // Allocatable sections go first to reduce the total PT_LOAD size and
525 // so debug info doesn't change addresses in actual code.
526 bool AIsAlloc = A->Flags & SHF_ALLOC;
527 bool BIsAlloc = B->Flags & SHF_ALLOC;
528 if (AIsAlloc != BIsAlloc)
531 // We don't have any special requirements for the relative order of two non
532 // allocatable sections.
536 // We want to put section specified by -T option first, so we
537 // can start assigning VA starting from them later.
538 auto AAddrSetI = Config->SectionStartMap.find(A->getName());
539 auto BAddrSetI = Config->SectionStartMap.find(B->getName());
540 bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
541 bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
542 if (AHasAddrSet != BHasAddrSet)
545 return AAddrSetI->second < BAddrSetI->second;
547 // We want the read only sections first so that they go in the PT_LOAD
548 // covering the program headers at the start of the file.
549 bool AIsWritable = A->Flags & SHF_WRITE;
550 bool BIsWritable = B->Flags & SHF_WRITE;
551 if (AIsWritable != BIsWritable)
554 if (!Config->SingleRoRx) {
555 // For a corresponding reason, put non exec sections first (the program
556 // header PT_LOAD is not executable).
557 // We only do that if we are not using linker scripts, since with linker
558 // scripts ro and rx sections are in the same PT_LOAD, so their relative
559 // order is not important. The same applies for -no-rosegment.
560 bool AIsExec = A->Flags & SHF_EXECINSTR;
561 bool BIsExec = B->Flags & SHF_EXECINSTR;
562 if (AIsExec != BIsExec)
566 // If we got here we know that both A and B are in the same PT_LOAD.
568 bool AIsTls = A->Flags & SHF_TLS;
569 bool BIsTls = B->Flags & SHF_TLS;
570 bool AIsNoBits = A->Type == SHT_NOBITS;
571 bool BIsNoBits = B->Type == SHT_NOBITS;
573 // The first requirement we have is to put (non-TLS) nobits sections last. The
574 // reason is that the only thing the dynamic linker will see about them is a
575 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
576 // PT_LOAD, so that has to correspond to the nobits sections.
577 bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
578 bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
579 if (AIsNonTlsNoBits != BIsNonTlsNoBits)
580 return BIsNonTlsNoBits;
582 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
583 // sections after r/w ones, so that the RelRo sections are contiguous.
584 bool AIsRelRo = isRelroSection<ELFT>(A);
585 bool BIsRelRo = isRelroSection<ELFT>(B);
586 if (AIsRelRo != BIsRelRo)
587 return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
589 // The TLS initialization block needs to be a single contiguous block in a R/W
590 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
591 // sections. The TLS NOBITS sections are placed here as they don't take up
592 // virtual address space in the PT_LOAD.
593 if (AIsTls != BIsTls)
596 // Within the TLS initialization block, the non-nobits sections need to appear
598 if (AIsNoBits != BIsNoBits)
601 // Some architectures have additional ordering restrictions for sections
602 // within the same PT_LOAD.
603 if (Config->EMachine == EM_PPC64)
604 return getPPC64SectionRank(A->getName()) <
605 getPPC64SectionRank(B->getName());
606 if (Config->EMachine == EM_MIPS)
607 return getMipsSectionRank(A) < getMipsSectionRank(B);
612 // Output section ordering is determined by this function.
613 template <class ELFT>
614 static bool compareSections(const OutputSectionBase *A,
615 const OutputSectionBase *B) {
616 // For now, put sections mentioned in a linker script first.
617 int AIndex = Script<ELFT>::X->getSectionIndex(A->getName());
618 int BIndex = Script<ELFT>::X->getSectionIndex(B->getName());
619 bool AInScript = AIndex != INT_MAX;
620 bool BInScript = BIndex != INT_MAX;
621 if (AInScript != BInScript)
623 // If both are in the script, use that order.
625 return AIndex < BIndex;
627 return compareSectionsNonScript<ELFT>(A, B);
630 // Program header entry
631 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
636 void PhdrEntry::add(OutputSectionBase *Sec) {
640 p_align = std::max(p_align, Sec->Addralign);
641 if (p_type == PT_LOAD)
642 Sec->FirstInPtLoad = First;
645 template <class ELFT>
646 static void addOptionalSynthetic(StringRef Name, OutputSectionBase *Sec,
647 typename ELFT::uint Val,
648 uint8_t StOther = STV_HIDDEN) {
649 if (SymbolBody *S = Symtab<ELFT>::X->find(Name))
650 if (!S->isInCurrentDSO())
651 Symtab<ELFT>::X->addSynthetic(Name, Sec, Val, StOther);
654 template <class ELFT>
655 static Symbol *addRegular(StringRef Name, InputSectionBase<ELFT> *Sec,
656 typename ELFT::uint Value) {
657 // The linker generated symbols are added as STB_WEAK to allow user defined
658 // ones to override them.
659 return Symtab<ELFT>::X->addRegular(Name, STV_HIDDEN, STT_NOTYPE, Value,
660 /*Size=*/0, STB_WEAK, Sec,
664 template <class ELFT>
665 static Symbol *addOptionalRegular(StringRef Name, InputSectionBase<ELFT> *IS,
666 typename ELFT::uint Value) {
667 SymbolBody *S = Symtab<ELFT>::X->find(Name);
670 if (S->isInCurrentDSO())
672 return addRegular(Name, IS, Value);
675 // The beginning and the ending of .rel[a].plt section are marked
676 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
677 // executable. The runtime needs these symbols in order to resolve
678 // all IRELATIVE relocs on startup. For dynamic executables, we don't
679 // need these symbols, since IRELATIVE relocs are resolved through GOT
680 // and PLT. For details, see http://www.airs.com/blog/archives/403.
681 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
682 if (In<ELFT>::DynSymTab)
684 StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
685 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0);
687 S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
688 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1);
691 // The linker is expected to define some symbols depending on
692 // the linking result. This function defines such symbols.
693 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
694 if (Config->EMachine == EM_MIPS) {
695 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
696 // so that it points to an absolute address which by default is relative
697 // to GOT. Default offset is 0x7ff0.
698 // See "Global Data Symbols" in Chapter 6 in the following document:
699 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
700 ElfSym<ELFT>::MipsGp =
701 Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
703 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
704 // start of function and 'gp' pointer into GOT. To simplify relocation
705 // calculation we assign _gp value to it and calculate corresponding
706 // relocations as relative to this value.
707 if (Symtab<ELFT>::X->find("_gp_disp"))
708 ElfSym<ELFT>::MipsGpDisp =
709 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
711 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
712 // pointer. This symbol is used in the code generated by .cpload pseudo-op
713 // in case of using -mno-shared option.
714 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
715 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
716 ElfSym<ELFT>::MipsLocalGp =
717 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
720 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
721 // is magical and is used to produce a R_386_GOTPC relocation.
722 // The R_386_GOTPC relocation value doesn't actually depend on the
723 // symbol value, so it could use an index of STN_UNDEF which, according
724 // to the spec, means the symbol value is 0.
725 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
727 // The situation is even stranger on x86_64 where the assembly doesn't
728 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
729 // an undefined symbol in the .o files.
730 // Given that the symbol is effectively unused, we just create a dummy
731 // hidden one to avoid the undefined symbol error.
732 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
734 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
735 // static linking the linker is required to optimize away any references to
736 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
737 // to avoid the undefined symbol error. As usual special cases are ARM and
738 // MIPS - the libc for these targets defines __tls_get_addr itself because
739 // there are no TLS optimizations for these targets.
740 if (!In<ELFT>::DynSymTab &&
741 (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
742 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
744 // If linker script do layout we do not need to create any standart symbols.
745 if (ScriptConfig->HasSections)
748 ElfSym<ELFT>::EhdrStart = Symtab<ELFT>::X->addIgnored("__ehdr_start");
750 auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
751 DefinedRegular<ELFT> *&Sym2) {
752 Sym1 = Symtab<ELFT>::X->addIgnored(S, STV_DEFAULT);
754 // The name without the underscore is not a reserved name,
755 // so it is defined only when there is a reference against it.
756 assert(S.startswith("_"));
758 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
759 if (B->isUndefined())
760 Sym2 = Symtab<ELFT>::X->addAbsolute(S, STV_DEFAULT);
763 Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
764 Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
765 Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
768 // Sort input sections by section name suffixes for
769 // __attribute__((init_priority(N))).
770 template <class ELFT> static void sortInitFini(OutputSectionBase *S) {
772 reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
775 // Sort input sections by the special rule for .ctors and .dtors.
776 template <class ELFT> static void sortCtorsDtors(OutputSectionBase *S) {
778 reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
781 // Sort input sections using the list provided by --symbol-ordering-file.
782 template <class ELFT>
783 static void sortBySymbolsOrder(ArrayRef<OutputSectionBase *> OutputSections) {
784 if (Config->SymbolOrderingFile.empty())
787 // Build a map from symbols to their priorities. Symbols that didn't
788 // appear in the symbol ordering file have the lowest priority 0.
789 // All explicitly mentioned symbols have negative (higher) priorities.
790 DenseMap<StringRef, int> SymbolOrder;
791 int Priority = -Config->SymbolOrderingFile.size();
792 for (StringRef S : Config->SymbolOrderingFile)
793 SymbolOrder.insert({S, Priority++});
795 // Build a map from sections to their priorities.
796 DenseMap<InputSectionBase<ELFT> *, int> SectionOrder;
797 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
798 for (SymbolBody *Body : File->getSymbols()) {
799 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
800 if (!D || !D->Section)
802 int &Priority = SectionOrder[D->Section];
803 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
807 // Sort sections by priority.
808 for (OutputSectionBase *Base : OutputSections)
809 if (auto *Sec = dyn_cast<OutputSection<ELFT>>(Base))
810 Sec->sort([&](InputSection<ELFT> *S) { return SectionOrder.lookup(S); });
813 template <class ELFT>
814 void Writer<ELFT>::forEachRelSec(
815 std::function<void(InputSectionBase<ELFT> &)> Fn) {
816 for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections) {
819 // Scan all relocations. Each relocation goes through a series
820 // of tests to determine if it needs special treatment, such as
821 // creating GOT, PLT, copy relocations, etc.
822 // Note that relocations for non-alloc sections are directly
823 // processed by InputSection::relocateNonAlloc.
824 if (!(IS->Flags & SHF_ALLOC))
826 if (isa<InputSection<ELFT>>(IS) || isa<EhInputSection<ELFT>>(IS))
831 template <class ELFT>
832 void Writer<ELFT>::addInputSec(InputSectionBase<ELFT> *IS) {
840 OutputSectionBase *Sec;
842 StringRef OutsecName = getOutputSectionName(IS->Name);
843 std::tie(Sec, IsNew) = Factory.create(IS, OutsecName);
845 OutputSections.push_back(Sec);
849 template <class ELFT> void Writer<ELFT>::createSections() {
850 for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections)
853 sortBySymbolsOrder<ELFT>(OutputSections);
854 sortInitFini<ELFT>(findSection(".init_array"));
855 sortInitFini<ELFT>(findSection(".fini_array"));
856 sortCtorsDtors<ELFT>(findSection(".ctors"));
857 sortCtorsDtors<ELFT>(findSection(".dtors"));
859 for (OutputSectionBase *Sec : OutputSections)
860 Sec->assignOffsets();
863 template <class ELFT>
864 static bool canSharePtLoad(const OutputSectionBase &S1,
865 const OutputSectionBase &S2) {
866 if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
869 bool S1IsWrite = S1.Flags & SHF_WRITE;
870 bool S2IsWrite = S2.Flags & SHF_WRITE;
871 if (S1IsWrite != S2IsWrite)
875 return true; // RO and RX share a PT_LOAD with linker scripts.
876 return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
879 template <class ELFT> void Writer<ELFT>::sortSections() {
880 // Don't sort if using -r. It is not necessary and we want to preserve the
881 // relative order for SHF_LINK_ORDER sections.
882 if (Config->Relocatable)
884 if (!ScriptConfig->HasSections) {
885 std::stable_sort(OutputSections.begin(), OutputSections.end(),
886 compareSectionsNonScript<ELFT>);
889 Script<ELFT>::X->adjustSectionsBeforeSorting();
891 // The order of the sections in the script is arbitrary and may not agree with
892 // compareSectionsNonScript. This means that we cannot easily define a
893 // strict weak ordering. To see why, consider a comparison of a section in the
894 // script and one not in the script. We have a two simple options:
895 // * Make them equivalent (a is not less than b, and b is not less than a).
896 // The problem is then that equivalence has to be transitive and we can
897 // have sections a, b and c with only b in a script and a less than c
898 // which breaks this property.
899 // * Use compareSectionsNonScript. Given that the script order doesn't have
900 // to match, we can end up with sections a, b, c, d where b and c are in the
901 // script and c is compareSectionsNonScript less than b. In which case d
902 // can be equivalent to c, a to b and d < a. As a concrete example:
903 // .a (rx) # not in script
904 // .b (rx) # in script
905 // .c (ro) # in script
906 // .d (ro) # not in script
908 // The way we define an order then is:
909 // * First put script sections at the start and sort the script and
910 // non-script sections independently.
911 // * Move each non-script section to its preferred position. We try
912 // to put each section in the last position where it it can share
915 std::stable_sort(OutputSections.begin(), OutputSections.end(),
916 compareSections<ELFT>);
918 auto I = OutputSections.begin();
919 auto E = OutputSections.end();
921 std::find_if(OutputSections.begin(), E, [](OutputSectionBase *S) {
922 return Script<ELFT>::X->getSectionIndex(S->getName()) == INT_MAX;
924 while (NonScriptI != E) {
925 auto BestPos = std::max_element(
926 I, NonScriptI, [&](OutputSectionBase *&A, OutputSectionBase *&B) {
927 bool ACanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *A);
928 bool BCanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *B);
929 if (ACanSharePtLoad != BCanSharePtLoad)
930 return BCanSharePtLoad;
932 bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
933 bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
935 return BCmp; // FIXME: missing test
937 size_t PosA = &A - &OutputSections[0];
938 size_t PosB = &B - &OutputSections[0];
939 return ACmp ? PosA > PosB : PosA < PosB;
942 // max_element only returns NonScriptI if the range is empty. If the range
943 // is not empty we should consider moving the the element forward one
945 if (BestPos != NonScriptI &&
946 !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
948 std::rotate(BestPos, NonScriptI, NonScriptI + 1);
952 Script<ELFT>::X->adjustSectionsAfterSorting();
955 template <class ELFT>
957 finalizeSynthetic(const std::vector<SyntheticSection<ELFT> *> &Sections) {
958 for (SyntheticSection<ELFT> *SS : Sections)
959 if (SS && SS->OutSec && !SS->empty()) {
961 SS->OutSec->Size = 0;
962 SS->OutSec->assignOffsets();
966 // We need to add input synthetic sections early in createSyntheticSections()
967 // to make them visible from linkescript side. But not all sections are always
968 // required to be in output. For example we don't need dynamic section content
969 // sometimes. This function filters out such unused sections from output.
970 template <class ELFT>
971 static void removeUnusedSyntheticSections(std::vector<OutputSectionBase *> &V) {
972 // Input synthetic sections are placed after all regular ones. We iterate over
973 // them all and exit at first non-synthetic.
974 for (InputSectionBase<ELFT> *S : llvm::reverse(Symtab<ELFT>::X->Sections)) {
975 SyntheticSection<ELFT> *SS = dyn_cast<SyntheticSection<ELFT>>(S);
978 if (!SS->empty() || !SS->OutSec)
981 OutputSection<ELFT> *OutSec = cast<OutputSection<ELFT>>(SS->OutSec);
982 OutSec->Sections.erase(
983 std::find(OutSec->Sections.begin(), OutSec->Sections.end(), SS));
984 // If there is no other sections in output section, remove it from output.
985 if (OutSec->Sections.empty())
986 V.erase(std::find(V.begin(), V.end(), OutSec));
990 // Create output section objects and add them to OutputSections.
991 template <class ELFT> void Writer<ELFT>::finalizeSections() {
992 Out<ELFT>::DebugInfo = findSection(".debug_info");
993 Out<ELFT>::PreinitArray = findSection(".preinit_array");
994 Out<ELFT>::InitArray = findSection(".init_array");
995 Out<ELFT>::FiniArray = findSection(".fini_array");
997 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
998 // symbols for sections, so that the runtime can get the start and end
999 // addresses of each section by section name. Add such symbols.
1000 if (!Config->Relocatable) {
1001 addStartEndSymbols();
1002 for (OutputSectionBase *Sec : OutputSections)
1003 addStartStopSymbols(Sec);
1006 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1007 // It should be okay as no one seems to care about the type.
1008 // Even the author of gold doesn't remember why gold behaves that way.
1009 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1010 if (In<ELFT>::DynSymTab)
1011 addRegular("_DYNAMIC", In<ELFT>::Dynamic, 0);
1013 // Define __rel[a]_iplt_{start,end} symbols if needed.
1014 addRelIpltSymbols();
1016 if (!Out<ELFT>::EhFrame->empty()) {
1017 OutputSections.push_back(Out<ELFT>::EhFrame);
1018 Out<ELFT>::EhFrame->finalize();
1021 // Scan relocations. This must be done after every symbol is declared so that
1022 // we can correctly decide if a dynamic relocation is needed.
1023 forEachRelSec(scanRelocations<ELFT>);
1025 // Now that we have defined all possible symbols including linker-
1026 // synthesized ones. Visit all symbols to give the finishing touches.
1027 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1028 SymbolBody *Body = S->body();
1030 if (!includeInSymtab<ELFT>(*Body))
1032 if (In<ELFT>::SymTab)
1033 In<ELFT>::SymTab->addGlobal(Body);
1035 if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1036 In<ELFT>::DynSymTab->addGlobal(Body);
1037 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1038 if (SS->file()->isNeeded())
1039 In<ELFT>::VerNeed->addSymbol(SS);
1043 // Do not proceed if there was an undefined symbol.
1047 // So far we have added sections from input object files.
1048 // This function adds linker-created Out<ELFT>::* sections.
1049 addPredefinedSections();
1050 removeUnusedSyntheticSections<ELFT>(OutputSections);
1055 for (OutputSectionBase *Sec : OutputSections) {
1056 Sec->SectionIndex = I++;
1057 Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->getName());
1060 // Binary and relocatable output does not have PHDRS.
1061 // The headers have to be created before finalize as that can influence the
1062 // image base and the dynamic section on mips includes the image base.
1063 if (!Config->Relocatable && !Config->OFormatBinary) {
1064 Phdrs = Script<ELFT>::X->hasPhdrsCommands() ? Script<ELFT>::X->createPhdrs()
1066 addPtArmExid(Phdrs);
1070 // Fill other section headers. The dynamic table is finalized
1071 // at the end because some tags like RELSZ depend on result
1072 // of finalizing other sections.
1073 for (OutputSectionBase *Sec : OutputSections)
1076 // Dynamic section must be the last one in this list and dynamic
1077 // symbol table section (DynSymTab) must be the first one.
1078 finalizeSynthetic<ELFT>(
1079 {In<ELFT>::DynSymTab, In<ELFT>::GnuHashTab, In<ELFT>::HashTab,
1080 In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab,
1081 In<ELFT>::VerDef, In<ELFT>::DynStrTab, In<ELFT>::GdbIndex,
1082 In<ELFT>::Got, In<ELFT>::MipsGot, In<ELFT>::IgotPlt,
1083 In<ELFT>::GotPlt, In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1084 In<ELFT>::RelaPlt, In<ELFT>::Plt, In<ELFT>::Iplt,
1085 In<ELFT>::Plt, In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,
1086 In<ELFT>::VerNeed, In<ELFT>::Dynamic});
1089 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1090 if (Out<ELFT>::Bss->Size > 0)
1091 OutputSections.push_back(Out<ELFT>::Bss);
1092 if (Out<ELFT>::BssRelRo->Size > 0)
1093 OutputSections.push_back(Out<ELFT>::BssRelRo);
1095 auto OS = dyn_cast_or_null<OutputSection<ELFT>>(findSection(".ARM.exidx"));
1096 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1097 OS->addSection(make<ARMExidxSentinelSection<ELFT>>());
1099 addInputSec(In<ELFT>::SymTab);
1100 addInputSec(In<ELFT>::ShStrTab);
1101 addInputSec(In<ELFT>::StrTab);
1104 // The linker is expected to define SECNAME_start and SECNAME_end
1105 // symbols for a few sections. This function defines them.
1106 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1107 auto Define = [&](StringRef Start, StringRef End, OutputSectionBase *OS) {
1108 // These symbols resolve to the image base if the section does not exist.
1109 // A special value -1 indicates end of the section.
1110 addOptionalSynthetic<ELFT>(Start, OS, 0);
1111 addOptionalSynthetic<ELFT>(End, OS, OS ? -1 : 0);
1114 Define("__preinit_array_start", "__preinit_array_end",
1115 Out<ELFT>::PreinitArray);
1116 Define("__init_array_start", "__init_array_end", Out<ELFT>::InitArray);
1117 Define("__fini_array_start", "__fini_array_end", Out<ELFT>::FiniArray);
1119 if (OutputSectionBase *Sec = findSection(".ARM.exidx"))
1120 Define("__exidx_start", "__exidx_end", Sec);
1123 // If a section name is valid as a C identifier (which is rare because of
1124 // the leading '.'), linkers are expected to define __start_<secname> and
1125 // __stop_<secname> symbols. They are at beginning and end of the section,
1126 // respectively. This is not requested by the ELF standard, but GNU ld and
1127 // gold provide the feature, and used by many programs.
1128 template <class ELFT>
1129 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase *Sec) {
1130 StringRef S = Sec->getName();
1131 if (!isValidCIdentifier(S))
1133 addOptionalSynthetic<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1134 addOptionalSynthetic<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1137 template <class ELFT>
1138 OutputSectionBase *Writer<ELFT>::findSection(StringRef Name) {
1139 for (OutputSectionBase *Sec : OutputSections)
1140 if (Sec->getName() == Name)
1145 template <class ELFT> static bool needsPtLoad(OutputSectionBase *Sec) {
1146 if (!(Sec->Flags & SHF_ALLOC))
1149 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1150 // responsible for allocating space for them, not the PT_LOAD that
1151 // contains the TLS initialization image.
1152 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1157 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1158 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1159 // RW. This means that there is no alignment in the RO to RX transition and we
1160 // cannot create a PT_LOAD there.
1161 template <class ELFT>
1162 static typename ELFT::uint computeFlags(typename ELFT::uint F) {
1164 return PF_R | PF_W | PF_X;
1165 if (Config->SingleRoRx && !(F & PF_W))
1170 // Decide which program headers to create and which sections to include in each
1172 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1173 std::vector<PhdrEntry> Ret;
1174 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1175 Ret.emplace_back(Type, Flags);
1179 // The first phdr entry is PT_PHDR which describes the program header itself.
1180 PhdrEntry &Hdr = *AddHdr(PT_PHDR, PF_R);
1181 Hdr.add(Out<ELFT>::ProgramHeaders);
1183 // PT_INTERP must be the second entry if exists.
1184 if (OutputSectionBase *Sec = findSection(".interp")) {
1185 PhdrEntry &Hdr = *AddHdr(PT_INTERP, Sec->getPhdrFlags());
1189 // Add the first PT_LOAD segment for regular output sections.
1190 uintX_t Flags = computeFlags<ELFT>(PF_R);
1191 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1193 PhdrEntry TlsHdr(PT_TLS, PF_R);
1194 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1195 PhdrEntry Note(PT_NOTE, PF_R);
1196 for (OutputSectionBase *Sec : OutputSections) {
1197 if (!(Sec->Flags & SHF_ALLOC))
1200 // If we meet TLS section then we create TLS header
1201 // and put all TLS sections inside for further use when
1202 // assign addresses.
1203 if (Sec->Flags & SHF_TLS)
1206 if (!needsPtLoad<ELFT>(Sec))
1209 // Segments are contiguous memory regions that has the same attributes
1210 // (e.g. executable or writable). There is one phdr for each segment.
1211 // Therefore, we need to create a new phdr when the next section has
1212 // different flags or is loaded at a discontiguous address using AT linker
1214 uintX_t NewFlags = computeFlags<ELFT>(Sec->getPhdrFlags());
1215 if (Script<ELFT>::X->hasLMA(Sec->getName()) || Flags != NewFlags) {
1216 Load = AddHdr(PT_LOAD, NewFlags);
1222 if (isRelroSection<ELFT>(Sec))
1224 if (Sec->Type == SHT_NOTE)
1228 // Add the TLS segment unless it's empty.
1230 Ret.push_back(std::move(TlsHdr));
1232 // Add an entry for .dynamic.
1233 if (In<ELFT>::DynSymTab) {
1235 *AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags());
1236 H.add(In<ELFT>::Dynamic->OutSec);
1239 // PT_GNU_RELRO includes all sections that should be marked as
1240 // read-only by dynamic linker after proccessing relocations.
1242 Ret.push_back(std::move(RelRo));
1244 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1245 if (!Out<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr) {
1247 *AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags());
1248 Hdr.add(In<ELFT>::EhFrameHdr->OutSec);
1251 // PT_OPENBSD_RANDOMIZE specifies the location and size of a part of the
1252 // memory image of the program that must be filled with random data before any
1253 // code in the object is executed.
1254 if (OutputSectionBase *Sec = findSection(".openbsd.randomdata")) {
1255 PhdrEntry &Hdr = *AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags());
1259 // PT_GNU_STACK is a special section to tell the loader to make the
1260 // pages for the stack non-executable.
1261 if (!Config->ZExecstack) {
1262 PhdrEntry &Hdr = *AddHdr(PT_GNU_STACK, PF_R | PF_W);
1263 if (Config->ZStackSize != uint64_t(-1))
1264 Hdr.p_memsz = Config->ZStackSize;
1267 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1268 // is expected to perform W^X violations, such as calling mprotect(2) or
1269 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1271 if (Config->ZWxneeded)
1272 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1275 Ret.push_back(std::move(Note));
1279 template <class ELFT>
1280 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1281 if (Config->EMachine != EM_ARM)
1283 auto I = std::find_if(
1284 OutputSections.begin(), OutputSections.end(),
1285 [](OutputSectionBase *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1286 if (I == OutputSections.end())
1289 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1290 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1292 Phdrs.push_back(ARMExidx);
1295 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1296 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1297 // linker can set the permissions.
1298 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1299 for (const PhdrEntry &P : Phdrs)
1300 if (P.p_type == PT_LOAD && P.First)
1301 P.First->PageAlign = true;
1303 for (const PhdrEntry &P : Phdrs) {
1304 if (P.p_type != PT_GNU_RELRO)
1307 P.First->PageAlign = true;
1308 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1309 // have to align it to a page.
1310 auto End = OutputSections.end();
1311 auto I = std::find(OutputSections.begin(), End, P.Last);
1312 if (I == End || (I + 1) == End)
1314 OutputSectionBase *Sec = *(I + 1);
1315 if (needsPtLoad<ELFT>(Sec))
1316 Sec->PageAlign = true;
1320 template <class ELFT>
1321 void elf::allocateHeaders(MutableArrayRef<PhdrEntry> Phdrs,
1322 ArrayRef<OutputSectionBase *> OutputSections) {
1324 std::find_if(Phdrs.begin(), Phdrs.end(),
1325 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1326 if (FirstPTLoad == Phdrs.end())
1328 if (FirstPTLoad->First)
1329 for (OutputSectionBase *Sec : OutputSections)
1330 if (Sec->FirstInPtLoad == FirstPTLoad->First)
1331 Sec->FirstInPtLoad = Out<ELFT>::ElfHeader;
1332 FirstPTLoad->First = Out<ELFT>::ElfHeader;
1333 if (!FirstPTLoad->Last)
1334 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
1337 // We should set file offsets and VAs for elf header and program headers
1338 // sections. These are special, we do not include them into output sections
1339 // list, but have them to simplify the code.
1340 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1341 Out<ELFT>::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1342 // If the script has SECTIONS, assignAddresses will compute the values.
1343 if (ScriptConfig->HasSections)
1346 uintX_t HeaderSize = getHeaderSize<ELFT>();
1347 // When -T<section> option is specified, lower the base to make room for those
1349 if (!Config->SectionStartMap.empty()) {
1351 for (const auto &P : Config->SectionStartMap)
1352 Min = std::min(Min, P.second);
1353 if (HeaderSize < Min)
1356 AllocateHeader = false;
1357 if (Min < Config->ImageBase)
1358 Config->ImageBase = alignDown(Min, Config->MaxPageSize);
1362 allocateHeaders<ELFT>(Phdrs, OutputSections);
1364 uintX_t BaseVA = Config->ImageBase;
1365 Out<ELFT>::ElfHeader->Addr = BaseVA;
1366 Out<ELFT>::ProgramHeaders->Addr = BaseVA + Out<ELFT>::ElfHeader->Size;
1369 // Assign VAs (addresses at run-time) to output sections.
1370 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1371 uintX_t VA = Config->ImageBase;
1373 VA += getHeaderSize<ELFT>();
1374 uintX_t ThreadBssOffset = 0;
1375 for (OutputSectionBase *Sec : OutputSections) {
1376 uintX_t Alignment = Sec->Addralign;
1378 Alignment = std::max<uintX_t>(Alignment, Config->MaxPageSize);
1380 auto I = Config->SectionStartMap.find(Sec->getName());
1381 if (I != Config->SectionStartMap.end())
1384 // We only assign VAs to allocated sections.
1385 if (needsPtLoad<ELFT>(Sec)) {
1386 VA = alignTo(VA, Alignment);
1389 } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
1390 uintX_t TVA = VA + ThreadBssOffset;
1391 TVA = alignTo(TVA, Alignment);
1393 ThreadBssOffset = TVA - VA + Sec->Size;
1398 // Adjusts the file alignment for a given output section and returns
1399 // its new file offset. The file offset must be the same with its
1400 // virtual address (modulo the page size) so that the loader can load
1401 // executables without any address adjustment.
1402 template <class ELFT, class uintX_t>
1403 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase *Sec) {
1404 OutputSectionBase *First = Sec->FirstInPtLoad;
1405 // If the section is not in a PT_LOAD, we just have to align it.
1407 return alignTo(Off, Sec->Addralign);
1409 // The first section in a PT_LOAD has to have congruent offset and address
1410 // module the page size.
1412 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1414 // If two sections share the same PT_LOAD the file offset is calculated
1415 // using this formula: Off2 = Off1 + (VA2 - VA1).
1416 return First->Offset + Sec->Addr - First->Addr;
1419 template <class ELFT, class uintX_t>
1420 void setOffset(OutputSectionBase *Sec, uintX_t &Off) {
1421 if (Sec->Type == SHT_NOBITS) {
1426 Off = getFileAlignment<ELFT>(Off, Sec);
1431 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1433 for (OutputSectionBase *Sec : OutputSections)
1434 if (Sec->Flags & SHF_ALLOC)
1435 setOffset<ELFT>(Sec, Off);
1436 FileSize = alignTo(Off, sizeof(uintX_t));
1439 // Assign file offsets to output sections.
1440 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1442 setOffset<ELFT>(Out<ELFT>::ElfHeader, Off);
1443 setOffset<ELFT>(Out<ELFT>::ProgramHeaders, Off);
1445 for (OutputSectionBase *Sec : OutputSections)
1446 setOffset<ELFT>(Sec, Off);
1448 SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1449 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1452 // Finalize the program headers. We call this function after we assign
1453 // file offsets and VAs to all sections.
1454 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1455 for (PhdrEntry &P : Phdrs) {
1456 OutputSectionBase *First = P.First;
1457 OutputSectionBase *Last = P.Last;
1459 P.p_filesz = Last->Offset - First->Offset;
1460 if (Last->Type != SHT_NOBITS)
1461 P.p_filesz += Last->Size;
1462 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1463 P.p_offset = First->Offset;
1464 P.p_vaddr = First->Addr;
1466 P.p_paddr = First->getLMA();
1468 if (P.p_type == PT_LOAD)
1469 P.p_align = Config->MaxPageSize;
1470 else if (P.p_type == PT_GNU_RELRO)
1473 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1474 // so round up the size to make sure the offsets are correct.
1475 if (P.p_type == PT_TLS) {
1476 Out<ELFT>::TlsPhdr = &P;
1478 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1483 // The entry point address is chosen in the following ways.
1485 // 1. the '-e' entry command-line option;
1486 // 2. the ENTRY(symbol) command in a linker control script;
1487 // 3. the value of the symbol start, if present;
1488 // 4. the address of the first byte of the .text section, if present;
1489 // 5. the address 0.
1490 template <class ELFT> typename ELFT::uint Writer<ELFT>::getEntryAddr() {
1491 // Case 1, 2 or 3. As a special case, if the symbol is actually
1492 // a number, we'll use that number as an address.
1493 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1494 return B->getVA<ELFT>();
1496 if (!Config->Entry.getAsInteger(0, Addr))
1500 if (OutputSectionBase *Sec = findSection(".text")) {
1501 if (Config->WarnMissingEntry)
1502 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1503 utohexstr(Sec->Addr));
1508 if (Config->WarnMissingEntry)
1509 warn("cannot find entry symbol " + Config->Entry +
1510 "; not setting start address");
1514 template <class ELFT> static uint8_t getELFEncoding() {
1515 if (ELFT::TargetEndianness == llvm::support::little)
1520 static uint16_t getELFType() {
1523 if (Config->Relocatable)
1528 // This function is called after we have assigned address and size
1529 // to each section. This function fixes some predefined absolute
1530 // symbol values that depend on section address and size.
1531 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1532 // __ehdr_start is the location of program headers.
1533 if (ElfSym<ELFT>::EhdrStart)
1534 ElfSym<ELFT>::EhdrStart->Value = Out<ELFT>::ProgramHeaders->Addr;
1536 auto Set = [](DefinedRegular<ELFT> *S1, DefinedRegular<ELFT> *S2, uintX_t V) {
1543 // _etext is the first location after the last read-only loadable segment.
1544 // _edata is the first location after the last read-write loadable segment.
1545 // _end is the first location after the uninitialized data region.
1546 for (PhdrEntry &P : Phdrs) {
1547 if (P.p_type != PT_LOAD)
1549 Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, P.p_vaddr + P.p_memsz);
1551 uintX_t Val = P.p_vaddr + P.p_filesz;
1552 if (P.p_flags & PF_W)
1553 Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
1555 Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
1558 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1559 // be equal to the _gp symbol's value.
1560 if (Config->EMachine == EM_MIPS) {
1561 if (!ElfSym<ELFT>::MipsGp->Value) {
1562 // Find GP-relative section with the lowest address
1563 // and use this address to calculate default _gp value.
1565 for (const OutputSectionBase * OS : OutputSections)
1566 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1568 if (Gp != (uintX_t)-1)
1569 ElfSym<ELFT>::MipsGp->Value = Gp + 0x7ff0;
1571 if (ElfSym<ELFT>::MipsGpDisp)
1572 ElfSym<ELFT>::MipsGpDisp->Value = ElfSym<ELFT>::MipsGp->Value;
1573 if (ElfSym<ELFT>::MipsLocalGp)
1574 ElfSym<ELFT>::MipsLocalGp->Value = ElfSym<ELFT>::MipsGp->Value;
1578 template <class ELFT> void Writer<ELFT>::writeHeader() {
1579 uint8_t *Buf = Buffer->getBufferStart();
1580 memcpy(Buf, "\177ELF", 4);
1582 // Write the ELF header.
1583 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1584 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1585 EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1586 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1587 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1588 EHdr->e_type = getELFType();
1589 EHdr->e_machine = Config->EMachine;
1590 EHdr->e_version = EV_CURRENT;
1591 EHdr->e_entry = getEntryAddr();
1592 EHdr->e_shoff = SectionHeaderOff;
1593 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1594 EHdr->e_phnum = Phdrs.size();
1595 EHdr->e_shentsize = sizeof(Elf_Shdr);
1596 EHdr->e_shnum = OutputSections.size() + 1;
1597 EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1599 if (Config->EMachine == EM_ARM)
1600 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1601 // but we don't have any firm guarantees of conformance. Linux AArch64
1602 // kernels (as of 2016) require an EABI version to be set.
1603 EHdr->e_flags = EF_ARM_EABI_VER5;
1604 else if (Config->EMachine == EM_MIPS)
1605 EHdr->e_flags = getMipsEFlags<ELFT>();
1607 if (!Config->Relocatable) {
1608 EHdr->e_phoff = sizeof(Elf_Ehdr);
1609 EHdr->e_phentsize = sizeof(Elf_Phdr);
1612 // Write the program header table.
1613 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1614 for (PhdrEntry &P : Phdrs) {
1615 HBuf->p_type = P.p_type;
1616 HBuf->p_flags = P.p_flags;
1617 HBuf->p_offset = P.p_offset;
1618 HBuf->p_vaddr = P.p_vaddr;
1619 HBuf->p_paddr = P.p_paddr;
1620 HBuf->p_filesz = P.p_filesz;
1621 HBuf->p_memsz = P.p_memsz;
1622 HBuf->p_align = P.p_align;
1626 // Write the section header table. Note that the first table entry is null.
1627 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1628 for (OutputSectionBase *Sec : OutputSections)
1629 Sec->writeHeaderTo<ELFT>(++SHdrs);
1632 // Removes a given file asynchronously. This is a performance hack,
1633 // so remove this when operating systems are improved.
1635 // On Linux (and probably on other Unix-like systems), unlink(2) is a
1636 // noticeably slow system call. As of 2016, unlink takes 250
1637 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
1639 // To create a new result file, we first remove existing file. So, if
1640 // you repeatedly link a 1 GB program in a regular compile-link-debug
1641 // cycle, every cycle wastes 250 milliseconds only to remove a file.
1642 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
1645 // This function spawns a background thread to call unlink.
1646 // The calling thread returns almost immediately.
1647 static void unlinkAsync(StringRef Path) {
1648 if (!Config->Threads || !sys::fs::exists(Config->OutputFile))
1651 // First, rename Path to avoid race condition. We cannot remove
1652 // Path from a different thread because we are now going to create
1653 // Path as a new file. If we do that in a different thread, the new
1654 // thread can remove the new file.
1655 SmallString<128> TempPath;
1656 if (sys::fs::createUniqueFile(Path + "tmp%%%%%%%%", TempPath))
1658 if (sys::fs::rename(Path, TempPath)) {
1659 sys::fs::remove(TempPath);
1663 // Remove TempPath in background.
1664 std::thread([=] { ::remove(TempPath.str().str().c_str()); }).detach();
1667 // Open a result file.
1668 template <class ELFT> void Writer<ELFT>::openFile() {
1669 unlinkAsync(Config->OutputFile);
1670 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1671 FileOutputBuffer::create(Config->OutputFile, FileSize,
1672 FileOutputBuffer::F_executable);
1674 if (auto EC = BufferOrErr.getError())
1675 error(EC, "failed to open " + Config->OutputFile);
1677 Buffer = std::move(*BufferOrErr);
1680 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1681 uint8_t *Buf = Buffer->getBufferStart();
1682 for (OutputSectionBase *Sec : OutputSections)
1683 if (Sec->Flags & SHF_ALLOC)
1684 Sec->writeTo(Buf + Sec->Offset);
1687 // Write section contents to a mmap'ed file.
1688 template <class ELFT> void Writer<ELFT>::writeSections() {
1689 uint8_t *Buf = Buffer->getBufferStart();
1691 // PPC64 needs to process relocations in the .opd section
1692 // before processing relocations in code-containing sections.
1693 Out<ELFT>::Opd = findSection(".opd");
1694 if (Out<ELFT>::Opd) {
1695 Out<ELFT>::OpdBuf = Buf + Out<ELFT>::Opd->Offset;
1696 Out<ELFT>::Opd->writeTo(Buf + Out<ELFT>::Opd->Offset);
1699 OutputSectionBase *EhFrameHdr =
1700 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1701 for (OutputSectionBase *Sec : OutputSections)
1702 if (Sec != Out<ELFT>::Opd && Sec != EhFrameHdr)
1703 Sec->writeTo(Buf + Sec->Offset);
1705 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1706 // it should be written after .eh_frame is written.
1707 if (!Out<ELFT>::EhFrame->empty() && EhFrameHdr)
1708 EhFrameHdr->writeTo(Buf + EhFrameHdr->Offset);
1711 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1712 if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1715 // Compute a hash of all sections of the output file.
1716 uint8_t *Start = Buffer->getBufferStart();
1717 uint8_t *End = Start + FileSize;
1718 In<ELFT>::BuildId->writeBuildId({Start, End});
1721 template void elf::writeResult<ELF32LE>();
1722 template void elf::writeResult<ELF32BE>();
1723 template void elf::writeResult<ELF64LE>();
1724 template void elf::writeResult<ELF64BE>();
1726 template void elf::allocateHeaders<ELF32LE>(MutableArrayRef<PhdrEntry>,
1727 ArrayRef<OutputSectionBase *>);
1728 template void elf::allocateHeaders<ELF32BE>(MutableArrayRef<PhdrEntry>,
1729 ArrayRef<OutputSectionBase *>);
1730 template void elf::allocateHeaders<ELF64LE>(MutableArrayRef<PhdrEntry>,
1731 ArrayRef<OutputSectionBase *>);
1732 template void elf::allocateHeaders<ELF64BE>(MutableArrayRef<PhdrEntry>,
1733 ArrayRef<OutputSectionBase *>);
1735 template bool elf::isRelroSection<ELF32LE>(const OutputSectionBase *);
1736 template bool elf::isRelroSection<ELF32BE>(const OutputSectionBase *);
1737 template bool elf::isRelroSection<ELF64LE>(const OutputSectionBase *);
1738 template bool elf::isRelroSection<ELF64BE>(const OutputSectionBase *);
1740 template void elf::reportDiscarded<ELF32LE>(InputSectionBase<ELF32LE> *);
1741 template void elf::reportDiscarded<ELF32BE>(InputSectionBase<ELF32BE> *);
1742 template void elf::reportDiscarded<ELF64LE>(InputSectionBase<ELF64LE> *);
1743 template void elf::reportDiscarded<ELF64BE>(InputSectionBase<ELF64BE> *);