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->NumLocals;
459 if (Config->Relocatable)
460 B->DynsymIndex = In<ELFT>::SymTab->NumLocals;
461 F->KeptLocalSyms.push_back(std::make_pair(
462 DR, In<ELFT>::SymTab->StrTabSec.addString(B->getName())));
467 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
468 // we would like to make sure appear is a specific order to maximize their
469 // coverage by a single signed 16-bit offset from the TOC base pointer.
470 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
471 // sections. This will put it next to the loaded special PPC64 sections (and,
472 // thus, within reach of the TOC base pointer).
473 static int getPPC64SectionRank(StringRef SectionName) {
474 return StringSwitch<int>(SectionName)
476 .Case(".branch_lt", 2)
483 template <class ELFT> bool elf::isRelroSection(const OutputSectionBase *Sec) {
486 uint64_t Flags = Sec->Flags;
487 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
491 uint32_t Type = Sec->Type;
492 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
493 Type == SHT_PREINIT_ARRAY)
495 if (Sec == In<ELFT>::GotPlt->OutSec)
497 if (Sec == In<ELFT>::Dynamic->OutSec)
499 if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
501 if (In<ELFT>::MipsGot && Sec == In<ELFT>::MipsGot->OutSec)
503 if (Sec == Out<ELFT>::BssRelRo)
505 StringRef S = Sec->getName();
506 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
507 S == ".eh_frame" || S == ".openbsd.randomdata";
510 template <class ELFT>
511 static bool compareSectionsNonScript(const OutputSectionBase *A,
512 const OutputSectionBase *B) {
513 // Put .interp first because some loaders want to see that section
514 // on the first page of the executable file when loaded into memory.
515 bool AIsInterp = A->getName() == ".interp";
516 bool BIsInterp = B->getName() == ".interp";
517 if (AIsInterp != BIsInterp)
520 // Allocatable sections go first to reduce the total PT_LOAD size and
521 // so debug info doesn't change addresses in actual code.
522 bool AIsAlloc = A->Flags & SHF_ALLOC;
523 bool BIsAlloc = B->Flags & SHF_ALLOC;
524 if (AIsAlloc != BIsAlloc)
527 // We don't have any special requirements for the relative order of two non
528 // allocatable sections.
532 // We want to put section specified by -T option first, so we
533 // can start assigning VA starting from them later.
534 auto AAddrSetI = Config->SectionStartMap.find(A->getName());
535 auto BAddrSetI = Config->SectionStartMap.find(B->getName());
536 bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
537 bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
538 if (AHasAddrSet != BHasAddrSet)
541 return AAddrSetI->second < BAddrSetI->second;
543 // We want the read only sections first so that they go in the PT_LOAD
544 // covering the program headers at the start of the file.
545 bool AIsWritable = A->Flags & SHF_WRITE;
546 bool BIsWritable = B->Flags & SHF_WRITE;
547 if (AIsWritable != BIsWritable)
550 if (!Config->SingleRoRx) {
551 // For a corresponding reason, put non exec sections first (the program
552 // header PT_LOAD is not executable).
553 // We only do that if we are not using linker scripts, since with linker
554 // scripts ro and rx sections are in the same PT_LOAD, so their relative
555 // order is not important. The same applies for -no-rosegment.
556 bool AIsExec = A->Flags & SHF_EXECINSTR;
557 bool BIsExec = B->Flags & SHF_EXECINSTR;
558 if (AIsExec != BIsExec)
562 // If we got here we know that both A and B are in the same PT_LOAD.
564 bool AIsTls = A->Flags & SHF_TLS;
565 bool BIsTls = B->Flags & SHF_TLS;
566 bool AIsNoBits = A->Type == SHT_NOBITS;
567 bool BIsNoBits = B->Type == SHT_NOBITS;
569 // The first requirement we have is to put (non-TLS) nobits sections last. The
570 // reason is that the only thing the dynamic linker will see about them is a
571 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
572 // PT_LOAD, so that has to correspond to the nobits sections.
573 bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
574 bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
575 if (AIsNonTlsNoBits != BIsNonTlsNoBits)
576 return BIsNonTlsNoBits;
578 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
579 // sections after r/w ones, so that the RelRo sections are contiguous.
580 bool AIsRelRo = isRelroSection<ELFT>(A);
581 bool BIsRelRo = isRelroSection<ELFT>(B);
582 if (AIsRelRo != BIsRelRo)
583 return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
585 // The TLS initialization block needs to be a single contiguous block in a R/W
586 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
587 // sections. The TLS NOBITS sections are placed here as they don't take up
588 // virtual address space in the PT_LOAD.
589 if (AIsTls != BIsTls)
592 // Within the TLS initialization block, the non-nobits sections need to appear
594 if (AIsNoBits != BIsNoBits)
597 // Some architectures have additional ordering restrictions for sections
598 // within the same PT_LOAD.
599 if (Config->EMachine == EM_PPC64)
600 return getPPC64SectionRank(A->getName()) <
601 getPPC64SectionRank(B->getName());
606 // Output section ordering is determined by this function.
607 template <class ELFT>
608 static bool compareSections(const OutputSectionBase *A,
609 const OutputSectionBase *B) {
610 // For now, put sections mentioned in a linker script first.
611 int AIndex = Script<ELFT>::X->getSectionIndex(A->getName());
612 int BIndex = Script<ELFT>::X->getSectionIndex(B->getName());
613 bool AInScript = AIndex != INT_MAX;
614 bool BInScript = BIndex != INT_MAX;
615 if (AInScript != BInScript)
617 // If both are in the script, use that order.
619 return AIndex < BIndex;
621 return compareSectionsNonScript<ELFT>(A, B);
624 // Program header entry
625 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
630 void PhdrEntry::add(OutputSectionBase *Sec) {
634 p_align = std::max(p_align, Sec->Addralign);
635 if (p_type == PT_LOAD)
636 Sec->FirstInPtLoad = First;
639 template <class ELFT>
640 static void addOptionalSynthetic(StringRef Name, OutputSectionBase *Sec,
641 typename ELFT::uint Val,
642 uint8_t StOther = STV_HIDDEN) {
643 if (SymbolBody *S = Symtab<ELFT>::X->find(Name))
644 if (S->isUndefined() || S->isShared())
645 Symtab<ELFT>::X->addSynthetic(Name, Sec, Val, StOther);
648 template <class ELFT>
649 static Symbol *addRegular(StringRef Name, InputSectionBase<ELFT> *Sec,
650 typename ELFT::uint Value) {
651 // The linker generated symbols are added as STB_WEAK to allow user defined
652 // ones to override them.
653 return Symtab<ELFT>::X->addRegular(Name, STV_HIDDEN, STT_NOTYPE, Value,
654 /*Size=*/0, STB_WEAK, Sec,
658 template <class ELFT>
659 static Symbol *addOptionalRegular(StringRef Name, InputSectionBase<ELFT> *IS,
660 typename ELFT::uint Value) {
661 SymbolBody *S = Symtab<ELFT>::X->find(Name);
664 if (!S->isUndefined() && !S->isShared())
666 return addRegular(Name, IS, Value);
669 // The beginning and the ending of .rel[a].plt section are marked
670 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
671 // executable. The runtime needs these symbols in order to resolve
672 // all IRELATIVE relocs on startup. For dynamic executables, we don't
673 // need these symbols, since IRELATIVE relocs are resolved through GOT
674 // and PLT. For details, see http://www.airs.com/blog/archives/403.
675 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
676 if (In<ELFT>::DynSymTab)
678 StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
679 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0);
681 S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
682 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1);
685 // The linker is expected to define some symbols depending on
686 // the linking result. This function defines such symbols.
687 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
688 if (Config->EMachine == EM_MIPS) {
689 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
690 // so that it points to an absolute address which by default is relative
691 // to GOT. Default offset is 0x7ff0.
692 // See "Global Data Symbols" in Chapter 6 in the following document:
693 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
694 ElfSym<ELFT>::MipsGp =
695 Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
697 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
698 // start of function and 'gp' pointer into GOT. To simplify relocation
699 // calculation we assign _gp value to it and calculate corresponding
700 // relocations as relative to this value.
701 if (Symtab<ELFT>::X->find("_gp_disp"))
702 ElfSym<ELFT>::MipsGpDisp =
703 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
705 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
706 // pointer. This symbol is used in the code generated by .cpload pseudo-op
707 // in case of using -mno-shared option.
708 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
709 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
710 ElfSym<ELFT>::MipsLocalGp =
711 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
714 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
715 // is magical and is used to produce a R_386_GOTPC relocation.
716 // The R_386_GOTPC relocation value doesn't actually depend on the
717 // symbol value, so it could use an index of STN_UNDEF which, according
718 // to the spec, means the symbol value is 0.
719 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
721 // The situation is even stranger on x86_64 where the assembly doesn't
722 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
723 // an undefined symbol in the .o files.
724 // Given that the symbol is effectively unused, we just create a dummy
725 // hidden one to avoid the undefined symbol error.
726 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
728 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
729 // static linking the linker is required to optimize away any references to
730 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
731 // to avoid the undefined symbol error. As usual special cases are ARM and
732 // MIPS - the libc for these targets defines __tls_get_addr itself because
733 // there are no TLS optimizations for these targets.
734 if (!In<ELFT>::DynSymTab &&
735 (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
736 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
738 // If linker script do layout we do not need to create any standart symbols.
739 if (ScriptConfig->HasSections)
742 ElfSym<ELFT>::EhdrStart = Symtab<ELFT>::X->addIgnored("__ehdr_start");
744 auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
745 DefinedRegular<ELFT> *&Sym2) {
746 Sym1 = Symtab<ELFT>::X->addIgnored(S, STV_DEFAULT);
748 // The name without the underscore is not a reserved name,
749 // so it is defined only when there is a reference against it.
750 assert(S.startswith("_"));
752 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
753 if (B->isUndefined())
754 Sym2 = Symtab<ELFT>::X->addAbsolute(S, STV_DEFAULT);
757 Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
758 Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
759 Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
762 // Sort input sections by section name suffixes for
763 // __attribute__((init_priority(N))).
764 template <class ELFT> static void sortInitFini(OutputSectionBase *S) {
766 reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
769 // Sort input sections by the special rule for .ctors and .dtors.
770 template <class ELFT> static void sortCtorsDtors(OutputSectionBase *S) {
772 reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
775 // Sort input sections using the list provided by --symbol-ordering-file.
776 template <class ELFT>
777 static void sortBySymbolsOrder(ArrayRef<OutputSectionBase *> OutputSections) {
778 if (Config->SymbolOrderingFile.empty())
781 // Build a map from symbols to their priorities. Symbols that didn't
782 // appear in the symbol ordering file have the lowest priority 0.
783 // All explicitly mentioned symbols have negative (higher) priorities.
784 DenseMap<StringRef, int> SymbolOrder;
785 int Priority = -Config->SymbolOrderingFile.size();
786 for (StringRef S : Config->SymbolOrderingFile)
787 SymbolOrder.insert({S, Priority++});
789 // Build a map from sections to their priorities.
790 DenseMap<InputSectionBase<ELFT> *, int> SectionOrder;
791 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
792 for (SymbolBody *Body : File->getSymbols()) {
793 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
794 if (!D || !D->Section)
796 int &Priority = SectionOrder[D->Section];
797 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
801 // Sort sections by priority.
802 for (OutputSectionBase *Base : OutputSections)
803 if (auto *Sec = dyn_cast<OutputSection<ELFT>>(Base))
804 Sec->sort([&](InputSection<ELFT> *S) { return SectionOrder.lookup(S); });
807 template <class ELFT>
808 void Writer<ELFT>::forEachRelSec(
809 std::function<void(InputSectionBase<ELFT> &)> Fn) {
810 for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections) {
813 // Scan all relocations. Each relocation goes through a series
814 // of tests to determine if it needs special treatment, such as
815 // creating GOT, PLT, copy relocations, etc.
816 // Note that relocations for non-alloc sections are directly
817 // processed by InputSection::relocateNonAlloc.
818 if (!(IS->Flags & SHF_ALLOC))
820 if (isa<InputSection<ELFT>>(IS) || isa<EhInputSection<ELFT>>(IS))
825 template <class ELFT>
826 void Writer<ELFT>::addInputSec(InputSectionBase<ELFT> *IS) {
834 OutputSectionBase *Sec;
836 StringRef OutsecName = getOutputSectionName(IS->Name);
837 std::tie(Sec, IsNew) = Factory.create(IS, OutsecName);
839 OutputSections.push_back(Sec);
843 template <class ELFT> void Writer<ELFT>::createSections() {
844 for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections)
847 sortBySymbolsOrder<ELFT>(OutputSections);
848 sortInitFini<ELFT>(findSection(".init_array"));
849 sortInitFini<ELFT>(findSection(".fini_array"));
850 sortCtorsDtors<ELFT>(findSection(".ctors"));
851 sortCtorsDtors<ELFT>(findSection(".dtors"));
853 for (OutputSectionBase *Sec : OutputSections)
854 Sec->assignOffsets();
857 template <class ELFT>
858 static bool canSharePtLoad(const OutputSectionBase &S1,
859 const OutputSectionBase &S2) {
860 if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
863 bool S1IsWrite = S1.Flags & SHF_WRITE;
864 bool S2IsWrite = S2.Flags & SHF_WRITE;
865 if (S1IsWrite != S2IsWrite)
869 return true; // RO and RX share a PT_LOAD with linker scripts.
870 return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
873 template <class ELFT> void Writer<ELFT>::sortSections() {
874 // Don't sort if using -r. It is not necessary and we want to preserve the
875 // relative order for SHF_LINK_ORDER sections.
876 if (Config->Relocatable)
878 if (!ScriptConfig->HasSections) {
879 std::stable_sort(OutputSections.begin(), OutputSections.end(),
880 compareSectionsNonScript<ELFT>);
883 Script<ELFT>::X->adjustSectionsBeforeSorting();
885 // The order of the sections in the script is arbitrary and may not agree with
886 // compareSectionsNonScript. This means that we cannot easily define a
887 // strict weak ordering. To see why, consider a comparison of a section in the
888 // script and one not in the script. We have a two simple options:
889 // * Make them equivalent (a is not less than b, and b is not less than a).
890 // The problem is then that equivalence has to be transitive and we can
891 // have sections a, b and c with only b in a script and a less than c
892 // which breaks this property.
893 // * Use compareSectionsNonScript. Given that the script order doesn't have
894 // to match, we can end up with sections a, b, c, d where b and c are in the
895 // script and c is compareSectionsNonScript less than b. In which case d
896 // can be equivalent to c, a to b and d < a. As a concrete example:
897 // .a (rx) # not in script
898 // .b (rx) # in script
899 // .c (ro) # in script
900 // .d (ro) # not in script
902 // The way we define an order then is:
903 // * First put script sections at the start and sort the script and
904 // non-script sections independently.
905 // * Move each non-script section to its preferred position. We try
906 // to put each section in the last position where it it can share
909 std::stable_sort(OutputSections.begin(), OutputSections.end(),
910 compareSections<ELFT>);
912 auto I = OutputSections.begin();
913 auto E = OutputSections.end();
915 std::find_if(OutputSections.begin(), E, [](OutputSectionBase *S) {
916 return Script<ELFT>::X->getSectionIndex(S->getName()) == INT_MAX;
918 while (NonScriptI != E) {
919 auto BestPos = std::max_element(
920 I, NonScriptI, [&](OutputSectionBase *&A, OutputSectionBase *&B) {
921 bool ACanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *A);
922 bool BCanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *B);
923 if (ACanSharePtLoad != BCanSharePtLoad)
924 return BCanSharePtLoad;
926 bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
927 bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
929 return BCmp; // FIXME: missing test
931 size_t PosA = &A - &OutputSections[0];
932 size_t PosB = &B - &OutputSections[0];
933 return ACmp ? PosA > PosB : PosA < PosB;
936 // max_element only returns NonScriptI if the range is empty. If the range
937 // is not empty we should consider moving the the element forward one
939 if (BestPos != NonScriptI &&
940 !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
942 std::rotate(BestPos, NonScriptI, NonScriptI + 1);
946 Script<ELFT>::X->adjustSectionsAfterSorting();
949 template <class ELFT>
951 finalizeSynthetic(const std::vector<SyntheticSection<ELFT> *> &Sections) {
952 for (SyntheticSection<ELFT> *SS : Sections)
953 if (SS && SS->OutSec && !SS->empty()) {
955 SS->OutSec->Size = 0;
956 SS->OutSec->assignOffsets();
960 // We need to add input synthetic sections early in createSyntheticSections()
961 // to make them visible from linkescript side. But not all sections are always
962 // required to be in output. For example we don't need dynamic section content
963 // sometimes. This function filters out such unused sections from output.
964 template <class ELFT>
965 static void removeUnusedSyntheticSections(std::vector<OutputSectionBase *> &V) {
966 // Input synthetic sections are placed after all regular ones. We iterate over
967 // them all and exit at first non-synthetic.
968 for (InputSectionBase<ELFT> *S : llvm::reverse(Symtab<ELFT>::X->Sections)) {
969 SyntheticSection<ELFT> *SS = dyn_cast<SyntheticSection<ELFT>>(S);
972 if (!SS->empty() || !SS->OutSec)
975 OutputSection<ELFT> *OutSec = cast<OutputSection<ELFT>>(SS->OutSec);
976 OutSec->Sections.erase(
977 std::find(OutSec->Sections.begin(), OutSec->Sections.end(), SS));
978 // If there is no other sections in output section, remove it from output.
979 if (OutSec->Sections.empty())
980 V.erase(std::find(V.begin(), V.end(), OutSec));
984 // Create output section objects and add them to OutputSections.
985 template <class ELFT> void Writer<ELFT>::finalizeSections() {
986 Out<ELFT>::DebugInfo = findSection(".debug_info");
987 Out<ELFT>::PreinitArray = findSection(".preinit_array");
988 Out<ELFT>::InitArray = findSection(".init_array");
989 Out<ELFT>::FiniArray = findSection(".fini_array");
991 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
992 // symbols for sections, so that the runtime can get the start and end
993 // addresses of each section by section name. Add such symbols.
994 if (!Config->Relocatable) {
995 addStartEndSymbols();
996 for (OutputSectionBase *Sec : OutputSections)
997 addStartStopSymbols(Sec);
1000 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1001 // It should be okay as no one seems to care about the type.
1002 // Even the author of gold doesn't remember why gold behaves that way.
1003 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1004 if (In<ELFT>::DynSymTab)
1005 addRegular("_DYNAMIC", In<ELFT>::Dynamic, 0);
1007 // Define __rel[a]_iplt_{start,end} symbols if needed.
1008 addRelIpltSymbols();
1010 if (!Out<ELFT>::EhFrame->empty()) {
1011 OutputSections.push_back(Out<ELFT>::EhFrame);
1012 Out<ELFT>::EhFrame->finalize();
1015 // Scan relocations. This must be done after every symbol is declared so that
1016 // we can correctly decide if a dynamic relocation is needed.
1017 forEachRelSec(scanRelocations<ELFT>);
1019 // Now that we have defined all possible symbols including linker-
1020 // synthesized ones. Visit all symbols to give the finishing touches.
1021 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1022 SymbolBody *Body = S->body();
1024 if (!includeInSymtab<ELFT>(*Body))
1026 if (In<ELFT>::SymTab)
1027 In<ELFT>::SymTab->addSymbol(Body);
1029 if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1030 In<ELFT>::DynSymTab->addSymbol(Body);
1031 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1032 if (SS->file()->isNeeded())
1033 In<ELFT>::VerNeed->addSymbol(SS);
1037 // Do not proceed if there was an undefined symbol.
1041 // So far we have added sections from input object files.
1042 // This function adds linker-created Out<ELFT>::* sections.
1043 addPredefinedSections();
1044 removeUnusedSyntheticSections<ELFT>(OutputSections);
1049 for (OutputSectionBase *Sec : OutputSections) {
1050 Sec->SectionIndex = I++;
1051 Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->getName());
1054 // Binary and relocatable output does not have PHDRS.
1055 // The headers have to be created before finalize as that can influence the
1056 // image base and the dynamic section on mips includes the image base.
1057 if (!Config->Relocatable && !Config->OFormatBinary) {
1058 Phdrs = Script<ELFT>::X->hasPhdrsCommands() ? Script<ELFT>::X->createPhdrs()
1060 addPtArmExid(Phdrs);
1064 // Fill other section headers. The dynamic table is finalized
1065 // at the end because some tags like RELSZ depend on result
1066 // of finalizing other sections.
1067 for (OutputSectionBase *Sec : OutputSections)
1070 // Dynamic section must be the last one in this list and dynamic
1071 // symbol table section (DynSymTab) must be the first one.
1072 finalizeSynthetic<ELFT>(
1073 {In<ELFT>::DynSymTab, In<ELFT>::GnuHashTab, In<ELFT>::HashTab,
1074 In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab,
1075 In<ELFT>::VerDef, In<ELFT>::DynStrTab, In<ELFT>::GdbIndex,
1076 In<ELFT>::Got, In<ELFT>::MipsGot, In<ELFT>::IgotPlt,
1077 In<ELFT>::GotPlt, In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1078 In<ELFT>::RelaPlt, In<ELFT>::Plt, In<ELFT>::Iplt,
1079 In<ELFT>::Plt, In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,
1080 In<ELFT>::VerNeed, In<ELFT>::Dynamic});
1083 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1084 if (Out<ELFT>::Bss->Size > 0)
1085 OutputSections.push_back(Out<ELFT>::Bss);
1086 if (Out<ELFT>::BssRelRo->Size > 0)
1087 OutputSections.push_back(Out<ELFT>::BssRelRo);
1089 auto OS = dyn_cast_or_null<OutputSection<ELFT>>(findSection(".ARM.exidx"));
1090 if (OS && !OS->Sections.empty() && !Config->Relocatable)
1091 OS->addSection(make<ARMExidxSentinelSection<ELFT>>());
1093 addInputSec(In<ELFT>::SymTab);
1094 addInputSec(In<ELFT>::ShStrTab);
1095 addInputSec(In<ELFT>::StrTab);
1098 // The linker is expected to define SECNAME_start and SECNAME_end
1099 // symbols for a few sections. This function defines them.
1100 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1101 auto Define = [&](StringRef Start, StringRef End, OutputSectionBase *OS) {
1102 // These symbols resolve to the image base if the section does not exist.
1103 // A special value -1 indicates end of the section.
1104 addOptionalSynthetic<ELFT>(Start, OS, 0);
1105 addOptionalSynthetic<ELFT>(End, OS, OS ? -1 : 0);
1108 Define("__preinit_array_start", "__preinit_array_end",
1109 Out<ELFT>::PreinitArray);
1110 Define("__init_array_start", "__init_array_end", Out<ELFT>::InitArray);
1111 Define("__fini_array_start", "__fini_array_end", Out<ELFT>::FiniArray);
1113 if (OutputSectionBase *Sec = findSection(".ARM.exidx"))
1114 Define("__exidx_start", "__exidx_end", Sec);
1117 // If a section name is valid as a C identifier (which is rare because of
1118 // the leading '.'), linkers are expected to define __start_<secname> and
1119 // __stop_<secname> symbols. They are at beginning and end of the section,
1120 // respectively. This is not requested by the ELF standard, but GNU ld and
1121 // gold provide the feature, and used by many programs.
1122 template <class ELFT>
1123 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase *Sec) {
1124 StringRef S = Sec->getName();
1125 if (!isValidCIdentifier(S))
1127 addOptionalSynthetic<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1128 addOptionalSynthetic<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1131 template <class ELFT>
1132 OutputSectionBase *Writer<ELFT>::findSection(StringRef Name) {
1133 for (OutputSectionBase *Sec : OutputSections)
1134 if (Sec->getName() == Name)
1139 template <class ELFT> static bool needsPtLoad(OutputSectionBase *Sec) {
1140 if (!(Sec->Flags & SHF_ALLOC))
1143 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1144 // responsible for allocating space for them, not the PT_LOAD that
1145 // contains the TLS initialization image.
1146 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1151 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1152 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1153 // RW. This means that there is no alignment in the RO to RX transition and we
1154 // cannot create a PT_LOAD there.
1155 template <class ELFT>
1156 static typename ELFT::uint computeFlags(typename ELFT::uint F) {
1158 return PF_R | PF_W | PF_X;
1159 if (Config->SingleRoRx && !(F & PF_W))
1164 // Decide which program headers to create and which sections to include in each
1166 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1167 std::vector<PhdrEntry> Ret;
1168 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1169 Ret.emplace_back(Type, Flags);
1173 // The first phdr entry is PT_PHDR which describes the program header itself.
1174 PhdrEntry &Hdr = *AddHdr(PT_PHDR, PF_R);
1175 Hdr.add(Out<ELFT>::ProgramHeaders);
1177 // PT_INTERP must be the second entry if exists.
1178 if (OutputSectionBase *Sec = findSection(".interp")) {
1179 PhdrEntry &Hdr = *AddHdr(PT_INTERP, Sec->getPhdrFlags());
1183 // Add the first PT_LOAD segment for regular output sections.
1184 uintX_t Flags = computeFlags<ELFT>(PF_R);
1185 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1187 PhdrEntry TlsHdr(PT_TLS, PF_R);
1188 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1189 PhdrEntry Note(PT_NOTE, PF_R);
1190 for (OutputSectionBase *Sec : OutputSections) {
1191 if (!(Sec->Flags & SHF_ALLOC))
1194 // If we meet TLS section then we create TLS header
1195 // and put all TLS sections inside for further use when
1196 // assign addresses.
1197 if (Sec->Flags & SHF_TLS)
1200 if (!needsPtLoad<ELFT>(Sec))
1203 // Segments are contiguous memory regions that has the same attributes
1204 // (e.g. executable or writable). There is one phdr for each segment.
1205 // Therefore, we need to create a new phdr when the next section has
1206 // different flags or is loaded at a discontiguous address using AT linker
1208 uintX_t NewFlags = computeFlags<ELFT>(Sec->getPhdrFlags());
1209 if (Script<ELFT>::X->hasLMA(Sec->getName()) || Flags != NewFlags) {
1210 Load = AddHdr(PT_LOAD, NewFlags);
1216 if (isRelroSection<ELFT>(Sec))
1218 if (Sec->Type == SHT_NOTE)
1222 // Add the TLS segment unless it's empty.
1224 Ret.push_back(std::move(TlsHdr));
1226 // Add an entry for .dynamic.
1227 if (In<ELFT>::DynSymTab) {
1229 *AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags());
1230 H.add(In<ELFT>::Dynamic->OutSec);
1233 // PT_GNU_RELRO includes all sections that should be marked as
1234 // read-only by dynamic linker after proccessing relocations.
1236 Ret.push_back(std::move(RelRo));
1238 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1239 if (!Out<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr) {
1241 *AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags());
1242 Hdr.add(In<ELFT>::EhFrameHdr->OutSec);
1245 // PT_OPENBSD_RANDOMIZE specifies the location and size of a part of the
1246 // memory image of the program that must be filled with random data before any
1247 // code in the object is executed.
1248 if (OutputSectionBase *Sec = findSection(".openbsd.randomdata")) {
1249 PhdrEntry &Hdr = *AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags());
1253 // PT_GNU_STACK is a special section to tell the loader to make the
1254 // pages for the stack non-executable.
1255 if (!Config->ZExecstack) {
1256 PhdrEntry &Hdr = *AddHdr(PT_GNU_STACK, PF_R | PF_W);
1257 if (Config->ZStackSize != uint64_t(-1))
1258 Hdr.p_memsz = Config->ZStackSize;
1261 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1262 // is expected to perform W^X violations, such as calling mprotect(2) or
1263 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1265 if (Config->ZWxneeded)
1266 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1269 Ret.push_back(std::move(Note));
1273 template <class ELFT>
1274 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1275 if (Config->EMachine != EM_ARM)
1277 auto I = std::find_if(
1278 OutputSections.begin(), OutputSections.end(),
1279 [](OutputSectionBase *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1280 if (I == OutputSections.end())
1283 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1284 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1286 Phdrs.push_back(ARMExidx);
1289 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1290 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1291 // linker can set the permissions.
1292 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1293 for (const PhdrEntry &P : Phdrs)
1294 if (P.p_type == PT_LOAD && P.First)
1295 P.First->PageAlign = true;
1297 for (const PhdrEntry &P : Phdrs) {
1298 if (P.p_type != PT_GNU_RELRO)
1301 P.First->PageAlign = true;
1302 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1303 // have to align it to a page.
1304 auto End = OutputSections.end();
1305 auto I = std::find(OutputSections.begin(), End, P.Last);
1306 if (I == End || (I + 1) == End)
1308 OutputSectionBase *Sec = *(I + 1);
1309 if (needsPtLoad<ELFT>(Sec))
1310 Sec->PageAlign = true;
1314 template <class ELFT>
1315 void elf::allocateHeaders(MutableArrayRef<PhdrEntry> Phdrs,
1316 ArrayRef<OutputSectionBase *> OutputSections) {
1318 std::find_if(Phdrs.begin(), Phdrs.end(),
1319 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1320 if (FirstPTLoad == Phdrs.end())
1322 if (FirstPTLoad->First)
1323 for (OutputSectionBase *Sec : OutputSections)
1324 if (Sec->FirstInPtLoad == FirstPTLoad->First)
1325 Sec->FirstInPtLoad = Out<ELFT>::ElfHeader;
1326 FirstPTLoad->First = Out<ELFT>::ElfHeader;
1327 if (!FirstPTLoad->Last)
1328 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
1331 // We should set file offsets and VAs for elf header and program headers
1332 // sections. These are special, we do not include them into output sections
1333 // list, but have them to simplify the code.
1334 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1335 Out<ELFT>::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1336 // If the script has SECTIONS, assignAddresses will compute the values.
1337 if (ScriptConfig->HasSections)
1340 uintX_t HeaderSize = getHeaderSize<ELFT>();
1341 // When -T<section> option is specified, lower the base to make room for those
1343 if (!Config->SectionStartMap.empty()) {
1345 for (const auto &P : Config->SectionStartMap)
1346 Min = std::min(Min, P.second);
1347 if (HeaderSize < Min)
1350 AllocateHeader = false;
1351 if (Min < Config->ImageBase)
1352 Config->ImageBase = alignDown(Min, Config->MaxPageSize);
1356 allocateHeaders<ELFT>(Phdrs, OutputSections);
1358 uintX_t BaseVA = Config->ImageBase;
1359 Out<ELFT>::ElfHeader->Addr = BaseVA;
1360 Out<ELFT>::ProgramHeaders->Addr = BaseVA + Out<ELFT>::ElfHeader->Size;
1363 // Assign VAs (addresses at run-time) to output sections.
1364 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1365 uintX_t VA = Config->ImageBase;
1367 VA += getHeaderSize<ELFT>();
1368 uintX_t ThreadBssOffset = 0;
1369 for (OutputSectionBase *Sec : OutputSections) {
1370 uintX_t Alignment = Sec->Addralign;
1372 Alignment = std::max<uintX_t>(Alignment, Config->MaxPageSize);
1374 auto I = Config->SectionStartMap.find(Sec->getName());
1375 if (I != Config->SectionStartMap.end())
1378 // We only assign VAs to allocated sections.
1379 if (needsPtLoad<ELFT>(Sec)) {
1380 VA = alignTo(VA, Alignment);
1383 } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
1384 uintX_t TVA = VA + ThreadBssOffset;
1385 TVA = alignTo(TVA, Alignment);
1387 ThreadBssOffset = TVA - VA + Sec->Size;
1392 // Adjusts the file alignment for a given output section and returns
1393 // its new file offset. The file offset must be the same with its
1394 // virtual address (modulo the page size) so that the loader can load
1395 // executables without any address adjustment.
1396 template <class ELFT, class uintX_t>
1397 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase *Sec) {
1398 OutputSectionBase *First = Sec->FirstInPtLoad;
1399 // If the section is not in a PT_LOAD, we just have to align it.
1401 return alignTo(Off, Sec->Addralign);
1403 // The first section in a PT_LOAD has to have congruent offset and address
1404 // module the page size.
1406 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1408 // If two sections share the same PT_LOAD the file offset is calculated
1409 // using this formula: Off2 = Off1 + (VA2 - VA1).
1410 return First->Offset + Sec->Addr - First->Addr;
1413 template <class ELFT, class uintX_t>
1414 void setOffset(OutputSectionBase *Sec, uintX_t &Off) {
1415 if (Sec->Type == SHT_NOBITS) {
1420 Off = getFileAlignment<ELFT>(Off, Sec);
1425 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1427 for (OutputSectionBase *Sec : OutputSections)
1428 if (Sec->Flags & SHF_ALLOC)
1429 setOffset<ELFT>(Sec, Off);
1430 FileSize = alignTo(Off, sizeof(uintX_t));
1433 // Assign file offsets to output sections.
1434 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1436 setOffset<ELFT>(Out<ELFT>::ElfHeader, Off);
1437 setOffset<ELFT>(Out<ELFT>::ProgramHeaders, Off);
1439 for (OutputSectionBase *Sec : OutputSections)
1440 setOffset<ELFT>(Sec, Off);
1442 SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1443 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1446 // Finalize the program headers. We call this function after we assign
1447 // file offsets and VAs to all sections.
1448 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1449 for (PhdrEntry &P : Phdrs) {
1450 OutputSectionBase *First = P.First;
1451 OutputSectionBase *Last = P.Last;
1453 P.p_filesz = Last->Offset - First->Offset;
1454 if (Last->Type != SHT_NOBITS)
1455 P.p_filesz += Last->Size;
1456 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1457 P.p_offset = First->Offset;
1458 P.p_vaddr = First->Addr;
1460 P.p_paddr = First->getLMA();
1462 if (P.p_type == PT_LOAD)
1463 P.p_align = Config->MaxPageSize;
1464 else if (P.p_type == PT_GNU_RELRO) {
1466 // The glibc dynamic loader rounds the size down, so we need to round up
1467 // to protect the last page. This is a no-op on FreeBSD which always
1469 P.p_memsz = alignTo(P.p_memsz, Config->MaxPageSize);
1472 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1473 // so round up the size to make sure the offsets are correct.
1474 if (P.p_type == PT_TLS) {
1475 Out<ELFT>::TlsPhdr = &P;
1477 P.p_memsz = alignTo(P.p_memsz, P.p_align);
1482 // The entry point address is chosen in the following ways.
1484 // 1. the '-e' entry command-line option;
1485 // 2. the ENTRY(symbol) command in a linker control script;
1486 // 3. the value of the symbol start, if present;
1487 // 4. the address of the first byte of the .text section, if present;
1488 // 5. the address 0.
1489 template <class ELFT> typename ELFT::uint Writer<ELFT>::getEntryAddr() {
1490 // Case 1, 2 or 3. As a special case, if the symbol is actually
1491 // a number, we'll use that number as an address.
1492 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1493 return B->getVA<ELFT>();
1495 if (!Config->Entry.getAsInteger(0, Addr))
1499 if (OutputSectionBase *Sec = findSection(".text")) {
1500 if (Config->WarnMissingEntry)
1501 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1502 utohexstr(Sec->Addr));
1507 if (Config->WarnMissingEntry)
1508 warn("cannot find entry symbol " + Config->Entry +
1509 "; not setting start address");
1513 template <class ELFT> static uint8_t getELFEncoding() {
1514 if (ELFT::TargetEndianness == llvm::support::little)
1519 static uint16_t getELFType() {
1522 if (Config->Relocatable)
1527 // This function is called after we have assigned address and size
1528 // to each section. This function fixes some predefined absolute
1529 // symbol values that depend on section address and size.
1530 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1531 // __ehdr_start is the location of program headers.
1532 if (ElfSym<ELFT>::EhdrStart)
1533 ElfSym<ELFT>::EhdrStart->Value = Out<ELFT>::ProgramHeaders->Addr;
1535 auto Set = [](DefinedRegular<ELFT> *S1, DefinedRegular<ELFT> *S2, uintX_t V) {
1542 // _etext is the first location after the last read-only loadable segment.
1543 // _edata is the first location after the last read-write loadable segment.
1544 // _end is the first location after the uninitialized data region.
1545 for (PhdrEntry &P : Phdrs) {
1546 if (P.p_type != PT_LOAD)
1548 Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, P.p_vaddr + P.p_memsz);
1550 uintX_t Val = P.p_vaddr + P.p_filesz;
1551 if (P.p_flags & PF_W)
1552 Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
1554 Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
1557 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1558 // be equal to the _gp symbol's value.
1559 if (Config->EMachine == EM_MIPS) {
1560 if (!ElfSym<ELFT>::MipsGp->Value) {
1561 // Find GP-relative section with the lowest address
1562 // and use this address to calculate default _gp value.
1564 for (const OutputSectionBase * OS : OutputSections)
1565 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1567 if (Gp != (uintX_t)-1)
1568 ElfSym<ELFT>::MipsGp->Value = Gp + 0x7ff0;
1570 if (ElfSym<ELFT>::MipsGpDisp)
1571 ElfSym<ELFT>::MipsGpDisp->Value = ElfSym<ELFT>::MipsGp->Value;
1572 if (ElfSym<ELFT>::MipsLocalGp)
1573 ElfSym<ELFT>::MipsLocalGp->Value = ElfSym<ELFT>::MipsGp->Value;
1577 template <class ELFT> void Writer<ELFT>::writeHeader() {
1578 uint8_t *Buf = Buffer->getBufferStart();
1579 memcpy(Buf, "\177ELF", 4);
1581 // Write the ELF header.
1582 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1583 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1584 EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1585 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1586 EHdr->e_ident[EI_OSABI] = Config->OSABI;
1587 EHdr->e_type = getELFType();
1588 EHdr->e_machine = Config->EMachine;
1589 EHdr->e_version = EV_CURRENT;
1590 EHdr->e_entry = getEntryAddr();
1591 EHdr->e_shoff = SectionHeaderOff;
1592 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1593 EHdr->e_phnum = Phdrs.size();
1594 EHdr->e_shentsize = sizeof(Elf_Shdr);
1595 EHdr->e_shnum = OutputSections.size() + 1;
1596 EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1598 if (Config->EMachine == EM_ARM)
1599 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1600 // but we don't have any firm guarantees of conformance. Linux AArch64
1601 // kernels (as of 2016) require an EABI version to be set.
1602 EHdr->e_flags = EF_ARM_EABI_VER5;
1603 else if (Config->EMachine == EM_MIPS)
1604 EHdr->e_flags = getMipsEFlags<ELFT>();
1606 if (!Config->Relocatable) {
1607 EHdr->e_phoff = sizeof(Elf_Ehdr);
1608 EHdr->e_phentsize = sizeof(Elf_Phdr);
1611 // Write the program header table.
1612 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1613 for (PhdrEntry &P : Phdrs) {
1614 HBuf->p_type = P.p_type;
1615 HBuf->p_flags = P.p_flags;
1616 HBuf->p_offset = P.p_offset;
1617 HBuf->p_vaddr = P.p_vaddr;
1618 HBuf->p_paddr = P.p_paddr;
1619 HBuf->p_filesz = P.p_filesz;
1620 HBuf->p_memsz = P.p_memsz;
1621 HBuf->p_align = P.p_align;
1625 // Write the section header table. Note that the first table entry is null.
1626 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1627 for (OutputSectionBase *Sec : OutputSections)
1628 Sec->writeHeaderTo<ELFT>(++SHdrs);
1631 // Removes a given file asynchronously. This is a performance hack,
1632 // so remove this when operating systems are improved.
1634 // On Linux (and probably on other Unix-like systems), unlink(2) is a
1635 // noticeably slow system call. As of 2016, unlink takes 250
1636 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
1638 // To create a new result file, we first remove existing file. So, if
1639 // you repeatedly link a 1 GB program in a regular compile-link-debug
1640 // cycle, every cycle wastes 250 milliseconds only to remove a file.
1641 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
1644 // This function spawns a background thread to call unlink.
1645 // The calling thread returns almost immediately.
1646 static void unlinkAsync(StringRef Path) {
1647 if (!Config->Threads || !sys::fs::exists(Config->OutputFile))
1650 // First, rename Path to avoid race condition. We cannot remove
1651 // Path from a different thread because we are now going to create
1652 // Path as a new file. If we do that in a different thread, the new
1653 // thread can remove the new file.
1654 SmallString<128> TempPath;
1655 if (sys::fs::createUniqueFile(Path + "tmp%%%%%%%%", TempPath))
1657 if (sys::fs::rename(Path, TempPath)) {
1658 sys::fs::remove(TempPath);
1662 // Remove TempPath in background.
1663 std::thread([=] { ::remove(TempPath.str().str().c_str()); }).detach();
1666 // Open a result file.
1667 template <class ELFT> void Writer<ELFT>::openFile() {
1668 unlinkAsync(Config->OutputFile);
1669 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1670 FileOutputBuffer::create(Config->OutputFile, FileSize,
1671 FileOutputBuffer::F_executable);
1673 if (auto EC = BufferOrErr.getError())
1674 error(EC, "failed to open " + Config->OutputFile);
1676 Buffer = std::move(*BufferOrErr);
1679 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1680 uint8_t *Buf = Buffer->getBufferStart();
1681 for (OutputSectionBase *Sec : OutputSections)
1682 if (Sec->Flags & SHF_ALLOC)
1683 Sec->writeTo(Buf + Sec->Offset);
1686 // Write section contents to a mmap'ed file.
1687 template <class ELFT> void Writer<ELFT>::writeSections() {
1688 uint8_t *Buf = Buffer->getBufferStart();
1690 // PPC64 needs to process relocations in the .opd section
1691 // before processing relocations in code-containing sections.
1692 Out<ELFT>::Opd = findSection(".opd");
1693 if (Out<ELFT>::Opd) {
1694 Out<ELFT>::OpdBuf = Buf + Out<ELFT>::Opd->Offset;
1695 Out<ELFT>::Opd->writeTo(Buf + Out<ELFT>::Opd->Offset);
1698 OutputSectionBase *EhFrameHdr =
1699 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1700 for (OutputSectionBase *Sec : OutputSections)
1701 if (Sec != Out<ELFT>::Opd && Sec != EhFrameHdr)
1702 Sec->writeTo(Buf + Sec->Offset);
1704 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1705 // it should be written after .eh_frame is written.
1706 if (!Out<ELFT>::EhFrame->empty() && EhFrameHdr)
1707 EhFrameHdr->writeTo(Buf + EhFrameHdr->Offset);
1710 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1711 if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1714 // Compute a hash of all sections of the output file.
1715 uint8_t *Start = Buffer->getBufferStart();
1716 uint8_t *End = Start + FileSize;
1717 In<ELFT>::BuildId->writeBuildId({Start, End});
1720 template void elf::writeResult<ELF32LE>();
1721 template void elf::writeResult<ELF32BE>();
1722 template void elf::writeResult<ELF64LE>();
1723 template void elf::writeResult<ELF64BE>();
1725 template void elf::allocateHeaders<ELF32LE>(MutableArrayRef<PhdrEntry>,
1726 ArrayRef<OutputSectionBase *>);
1727 template void elf::allocateHeaders<ELF32BE>(MutableArrayRef<PhdrEntry>,
1728 ArrayRef<OutputSectionBase *>);
1729 template void elf::allocateHeaders<ELF64LE>(MutableArrayRef<PhdrEntry>,
1730 ArrayRef<OutputSectionBase *>);
1731 template void elf::allocateHeaders<ELF64BE>(MutableArrayRef<PhdrEntry>,
1732 ArrayRef<OutputSectionBase *>);
1734 template bool elf::isRelroSection<ELF32LE>(const OutputSectionBase *);
1735 template bool elf::isRelroSection<ELF32BE>(const OutputSectionBase *);
1736 template bool elf::isRelroSection<ELF64LE>(const OutputSectionBase *);
1737 template bool elf::isRelroSection<ELF64BE>(const OutputSectionBase *);
1739 template void elf::reportDiscarded<ELF32LE>(InputSectionBase<ELF32LE> *);
1740 template void elf::reportDiscarded<ELF32BE>(InputSectionBase<ELF32BE> *);
1741 template void elf::reportDiscarded<ELF64LE>(InputSectionBase<ELF64LE> *);
1742 template void elf::reportDiscarded<ELF64BE>(InputSectionBase<ELF64BE> *);