]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Writer.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305575, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Writer.cpp
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Writer.h"
11 #include "Config.h"
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
14 #include "MapFile.h"
15 #include "Memory.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "Strings.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "Threads.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <climits>
28
29 using namespace llvm;
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
34
35 using namespace lld;
36 using namespace lld::elf;
37
38 namespace {
39 // The writer writes a SymbolTable result to a file.
40 template <class ELFT> class Writer {
41 public:
42   typedef typename ELFT::Shdr Elf_Shdr;
43   typedef typename ELFT::Ehdr Elf_Ehdr;
44   typedef typename ELFT::Phdr Elf_Phdr;
45
46   void run();
47
48 private:
49   void clearOutputSections();
50   void createSyntheticSections();
51   void copyLocalSymbols();
52   void addSectionSymbols();
53   void addReservedSymbols();
54   void createSections();
55   void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
56   void sortSections();
57   void finalizeSections();
58   void addPredefinedSections();
59
60   std::vector<PhdrEntry> createPhdrs();
61   void removeEmptyPTLoad();
62   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
63   void assignFileOffsets();
64   void assignFileOffsetsBinary();
65   void setPhdrs();
66   void fixSectionAlignments();
67   void fixPredefinedSymbols();
68   void openFile();
69   void writeHeader();
70   void writeSections();
71   void writeSectionsBinary();
72   void writeBuildId();
73
74   std::unique_ptr<FileOutputBuffer> Buffer;
75
76   OutputSectionFactory Factory{OutputSections};
77
78   void addRelIpltSymbols();
79   void addStartEndSymbols();
80   void addStartStopSymbols(OutputSection *Sec);
81   uint64_t getEntryAddr();
82   OutputSection *findSection(StringRef Name);
83   OutputSection *findSectionInScript(StringRef Name);
84   OutputSectionCommand *findSectionCommand(StringRef Name);
85
86   std::vector<PhdrEntry> Phdrs;
87
88   uint64_t FileSize;
89   uint64_t SectionHeaderOff;
90 };
91 } // anonymous namespace
92
93 StringRef elf::getOutputSectionName(StringRef Name) {
94   // ".zdebug_" is a prefix for ZLIB-compressed sections.
95   // Because we decompressed input sections, we want to remove 'z'.
96   if (Name.startswith(".zdebug_"))
97     return Saver.save("." + Name.substr(2));
98
99   if (Config->Relocatable)
100     return Name;
101
102   for (StringRef V :
103        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
104         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
105         ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
106     StringRef Prefix = V.drop_back();
107     if (Name.startswith(V) || Name == Prefix)
108       return Prefix;
109   }
110
111   // CommonSection is identified as "COMMON" in linker scripts.
112   // By default, it should go to .bss section.
113   if (Name == "COMMON")
114     return ".bss";
115
116   return Name;
117 }
118
119 template <class ELFT> static bool needsInterpSection() {
120   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
121          !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
122 }
123
124 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
125
126 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
127   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
128     if (P.p_type != PT_LOAD)
129       return false;
130     if (!P.First)
131       return true;
132     uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
133     return Size == 0;
134   });
135   Phdrs.erase(I, Phdrs.end());
136 }
137
138 template <class ELFT> static void combineEhFrameSections() {
139   for (InputSectionBase *&S : InputSections) {
140     EhInputSection *ES = dyn_cast<EhInputSection>(S);
141     if (!ES || !ES->Live)
142       continue;
143
144     In<ELFT>::EhFrame->addSection(ES);
145     S = nullptr;
146   }
147
148   std::vector<InputSectionBase *> &V = InputSections;
149   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
150 }
151
152 template <class ELFT> void Writer<ELFT>::clearOutputSections() {
153   if (Script->Opt.HasSections)
154     Script->createOrphanCommands();
155   else
156     Script->fabricateDefaultCommands();
157   // Clear the OutputSections to make sure it is not used anymore. Any
158   // code from this point on should be using the linker script
159   // commands.
160   for (OutputSection *Sec : OutputSections)
161     Sec->Sections.clear();
162   OutputSections.clear();
163 }
164
165 // The main function of the writer.
166 template <class ELFT> void Writer<ELFT>::run() {
167   // Create linker-synthesized sections such as .got or .plt.
168   // Such sections are of type input section.
169   createSyntheticSections();
170
171   if (!Config->Relocatable)
172     combineEhFrameSections<ELFT>();
173
174   // We need to create some reserved symbols such as _end. Create them.
175   if (!Config->Relocatable)
176     addReservedSymbols();
177
178   // Create output sections.
179   if (Script->Opt.HasSections) {
180     // If linker script contains SECTIONS commands, let it create sections.
181     Script->processCommands(Factory);
182
183     // Linker scripts may have left some input sections unassigned.
184     // Assign such sections using the default rule.
185     Script->addOrphanSections(Factory);
186   } else {
187     // If linker script does not contain SECTIONS commands, create
188     // output sections by default rules. We still need to give the
189     // linker script a chance to run, because it might contain
190     // non-SECTIONS commands such as ASSERT.
191     createSections();
192     Script->processCommands(Factory);
193   }
194
195   if (Config->Discard != DiscardPolicy::All)
196     copyLocalSymbols();
197
198   if (Config->CopyRelocs)
199     addSectionSymbols();
200
201   // Now that we have a complete set of output sections. This function
202   // completes section contents. For example, we need to add strings
203   // to the string table, and add entries to .got and .plt.
204   // finalizeSections does that.
205   finalizeSections();
206   if (ErrorCount)
207     return;
208
209   if (!Script->Opt.HasSections && !Config->Relocatable)
210     fixSectionAlignments();
211
212   // If -compressed-debug-sections is specified, we need to compress
213   // .debug_* sections. Do it right now because it changes the size of
214   // output sections.
215   parallelForEach(
216       OutputSectionCommands.begin(), OutputSectionCommands.end(),
217       [](OutputSectionCommand *Cmd) { Cmd->maybeCompress<ELFT>(); });
218
219   Script->assignAddresses(Phdrs);
220
221   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
222   // 0 sized region. This has to be done late since only after assignAddresses
223   // we know the size of the sections.
224   removeEmptyPTLoad();
225
226   if (!Config->OFormatBinary)
227     assignFileOffsets();
228   else
229     assignFileOffsetsBinary();
230
231   setPhdrs();
232
233   if (Config->Relocatable) {
234     for (OutputSectionCommand *Cmd : OutputSectionCommands)
235       Cmd->Sec->Addr = 0;
236   } else {
237     fixPredefinedSymbols();
238   }
239
240   // It does not make sense try to open the file if we have error already.
241   if (ErrorCount)
242     return;
243   // Write the result down to a file.
244   openFile();
245   if (ErrorCount)
246     return;
247
248   if (!Config->OFormatBinary) {
249     writeHeader();
250     writeSections();
251   } else {
252     writeSectionsBinary();
253   }
254
255   // Backfill .note.gnu.build-id section content. This is done at last
256   // because the content is usually a hash value of the entire output file.
257   writeBuildId();
258   if (ErrorCount)
259     return;
260
261
262   // Handle -Map option.
263   writeMapFile<ELFT>(OutputSectionCommands);
264   if (ErrorCount)
265     return;
266
267   if (auto EC = Buffer->commit())
268     error("failed to write to the output file: " + EC.message());
269
270   // Flush the output streams and exit immediately. A full shutdown
271   // is a good test that we are keeping track of all allocated memory,
272   // but actually freeing it is a waste of time in a regular linker run.
273   if (Config->ExitEarly)
274     exitLld(0);
275 }
276
277 // Initialize Out members.
278 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
279   // Initialize all pointers with NULL. This is needed because
280   // you can call lld::elf::main more than once as a library.
281   memset(&Out::First, 0, sizeof(Out));
282
283   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
284
285   InX::DynStrTab = make<StringTableSection>(".dynstr", true);
286   InX::Dynamic = make<DynamicSection<ELFT>>();
287   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
288       Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
289   InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
290
291   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
292   Out::ElfHeader->Size = sizeof(Elf_Ehdr);
293   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
294   Out::ProgramHeaders->updateAlignment(Config->Wordsize);
295
296   if (needsInterpSection<ELFT>()) {
297     InX::Interp = createInterpSection();
298     Add(InX::Interp);
299   } else {
300     InX::Interp = nullptr;
301   }
302
303   if (Config->Strip != StripPolicy::All) {
304     InX::StrTab = make<StringTableSection>(".strtab", false);
305     InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
306   }
307
308   if (Config->BuildId != BuildIdKind::None) {
309     InX::BuildId = make<BuildIdSection>();
310     Add(InX::BuildId);
311   }
312
313   InX::Common = createCommonSection<ELFT>();
314   if (InX::Common)
315     Add(InX::Common);
316
317   InX::Bss = make<BssSection>(".bss");
318   Add(InX::Bss);
319   InX::BssRelRo = make<BssSection>(".bss.rel.ro");
320   Add(InX::BssRelRo);
321
322   // Add MIPS-specific sections.
323   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
324                       Config->Pic || Config->ExportDynamic;
325   if (Config->EMachine == EM_MIPS) {
326     if (!Config->Shared && HasDynSymTab) {
327       InX::MipsRldMap = make<MipsRldMapSection>();
328       Add(InX::MipsRldMap);
329     }
330     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
331       Add(Sec);
332     if (auto *Sec = MipsOptionsSection<ELFT>::create())
333       Add(Sec);
334     if (auto *Sec = MipsReginfoSection<ELFT>::create())
335       Add(Sec);
336   }
337
338   if (HasDynSymTab) {
339     InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
340     Add(InX::DynSymTab);
341
342     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
343     Add(In<ELFT>::VerSym);
344
345     if (!Config->VersionDefinitions.empty()) {
346       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
347       Add(In<ELFT>::VerDef);
348     }
349
350     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
351     Add(In<ELFT>::VerNeed);
352
353     if (Config->GnuHash) {
354       InX::GnuHashTab = make<GnuHashTableSection>();
355       Add(InX::GnuHashTab);
356     }
357
358     if (Config->SysvHash) {
359       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
360       Add(In<ELFT>::HashTab);
361     }
362
363     Add(InX::Dynamic);
364     Add(InX::DynStrTab);
365     Add(In<ELFT>::RelaDyn);
366   }
367
368   // Add .got. MIPS' .got is so different from the other archs,
369   // it has its own class.
370   if (Config->EMachine == EM_MIPS) {
371     InX::MipsGot = make<MipsGotSection>();
372     Add(InX::MipsGot);
373   } else {
374     InX::Got = make<GotSection>();
375     Add(InX::Got);
376   }
377
378   InX::GotPlt = make<GotPltSection>();
379   Add(InX::GotPlt);
380   InX::IgotPlt = make<IgotPltSection>();
381   Add(InX::IgotPlt);
382
383   if (Config->GdbIndex) {
384     InX::GdbIndex = make<GdbIndexSection>();
385     Add(InX::GdbIndex);
386   }
387
388   // We always need to add rel[a].plt to output if it has entries.
389   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
390   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
391       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
392   Add(In<ELFT>::RelaPlt);
393
394   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
395   // that the IRelative relocations are processed last by the dynamic loader
396   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
397       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
398       false /*Sort*/);
399   Add(In<ELFT>::RelaIplt);
400
401   InX::Plt = make<PltSection>(Target->PltHeaderSize);
402   Add(InX::Plt);
403   InX::Iplt = make<PltSection>(0);
404   Add(InX::Iplt);
405
406   if (!Config->Relocatable) {
407     if (Config->EhFrameHdr) {
408       In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
409       Add(In<ELFT>::EhFrameHdr);
410     }
411     In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
412     Add(In<ELFT>::EhFrame);
413   }
414
415   if (InX::SymTab)
416     Add(InX::SymTab);
417   Add(InX::ShStrTab);
418   if (InX::StrTab)
419     Add(InX::StrTab);
420 }
421
422 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
423                                const SymbolBody &B) {
424   if (B.isFile() || B.isSection())
425     return false;
426
427   // If sym references a section in a discarded group, don't keep it.
428   if (Sec == &InputSection::Discarded)
429     return false;
430
431   if (Config->Discard == DiscardPolicy::None)
432     return true;
433
434   // In ELF assembly .L symbols are normally discarded by the assembler.
435   // If the assembler fails to do so, the linker discards them if
436   // * --discard-locals is used.
437   // * The symbol is in a SHF_MERGE section, which is normally the reason for
438   //   the assembler keeping the .L symbol.
439   if (!SymName.startswith(".L") && !SymName.empty())
440     return true;
441
442   if (Config->Discard == DiscardPolicy::Locals)
443     return false;
444
445   return !Sec || !(Sec->Flags & SHF_MERGE);
446 }
447
448 static bool includeInSymtab(const SymbolBody &B) {
449   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
450     return false;
451
452   if (auto *D = dyn_cast<DefinedRegular>(&B)) {
453     // Always include absolute symbols.
454     SectionBase *Sec = D->Section;
455     if (!Sec)
456       return true;
457     if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
458       Sec = IS->Repl;
459       IS = cast<InputSectionBase>(Sec);
460       // Exclude symbols pointing to garbage-collected sections.
461       if (!IS->Live)
462         return false;
463     }
464     if (auto *S = dyn_cast<MergeInputSection>(Sec))
465       if (!S->getSectionPiece(D->Value)->Live)
466         return false;
467   }
468   return true;
469 }
470
471 // Local symbols are not in the linker's symbol table. This function scans
472 // each object file's symbol table to copy local symbols to the output.
473 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
474   if (!InX::SymTab)
475     return;
476   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
477     for (SymbolBody *B : F->getLocalSymbols()) {
478       if (!B->IsLocal)
479         fatal(toString(F) +
480               ": broken object: getLocalSymbols returns a non-local symbol");
481       auto *DR = dyn_cast<DefinedRegular>(B);
482
483       // No reason to keep local undefined symbol in symtab.
484       if (!DR)
485         continue;
486       if (!includeInSymtab(*B))
487         continue;
488
489       SectionBase *Sec = DR->Section;
490       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
491         continue;
492       InX::SymTab->addSymbol(B);
493     }
494   }
495 }
496
497 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
498   // Create one STT_SECTION symbol for each output section we might
499   // have a relocation with.
500   for (OutputSection *Sec : OutputSections) {
501     if (Sec->Sections.empty())
502       continue;
503
504     InputSection *IS = Sec->Sections[0];
505     if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
506         IS->Type == SHT_RELA)
507       continue;
508
509     auto *Sym =
510         make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
511                              /*Value=*/0, /*Size=*/0, IS, nullptr);
512     InX::SymTab->addSymbol(Sym);
513   }
514 }
515
516 // Today's loaders have a feature to make segments read-only after
517 // processing dynamic relocations to enhance security. PT_GNU_RELRO
518 // is defined for that.
519 //
520 // This function returns true if a section needs to be put into a
521 // PT_GNU_RELRO segment.
522 bool elf::isRelroSection(const OutputSection *Sec) {
523   if (!Config->ZRelro)
524     return false;
525
526   uint64_t Flags = Sec->Flags;
527
528   // Non-allocatable or non-writable sections don't need RELRO because
529   // they are not writable or not even mapped to memory in the first place.
530   // RELRO is for sections that are essentially read-only but need to
531   // be writable only at process startup to allow dynamic linker to
532   // apply relocations.
533   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
534     return false;
535
536   // Once initialized, TLS data segments are used as data templates
537   // for a thread-local storage. For each new thread, runtime
538   // allocates memory for a TLS and copy templates there. No thread
539   // are supposed to use templates directly. Thus, it can be in RELRO.
540   if (Flags & SHF_TLS)
541     return true;
542
543   // .init_array, .preinit_array and .fini_array contain pointers to
544   // functions that are executed on process startup or exit. These
545   // pointers are set by the static linker, and they are not expected
546   // to change at runtime. But if you are an attacker, you could do
547   // interesting things by manipulating pointers in .fini_array, for
548   // example. So they are put into RELRO.
549   uint32_t Type = Sec->Type;
550   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
551       Type == SHT_PREINIT_ARRAY)
552     return true;
553
554   // .got contains pointers to external symbols. They are resolved by
555   // the dynamic linker when a module is loaded into memory, and after
556   // that they are not expected to change. So, it can be in RELRO.
557   if (InX::Got && Sec == InX::Got->getParent())
558     return true;
559
560   // .got.plt contains pointers to external function symbols. They are
561   // by default resolved lazily, so we usually cannot put it into RELRO.
562   // However, if "-z now" is given, the lazy symbol resolution is
563   // disabled, which enables us to put it into RELRO.
564   if (Sec == InX::GotPlt->getParent())
565     return Config->ZNow;
566
567   // .dynamic section contains data for the dynamic linker, and
568   // there's no need to write to it at runtime, so it's better to put
569   // it into RELRO.
570   if (Sec == InX::Dynamic->getParent())
571     return true;
572
573   // .bss.rel.ro is used for copy relocations for read-only symbols.
574   // Since the dynamic linker needs to process copy relocations, the
575   // section cannot be read-only, but once initialized, they shouldn't
576   // change.
577   if (Sec == InX::BssRelRo->getParent())
578     return true;
579
580   // Sections with some special names are put into RELRO. This is a
581   // bit unfortunate because section names shouldn't be significant in
582   // ELF in spirit. But in reality many linker features depend on
583   // magic section names.
584   StringRef S = Sec->Name;
585   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
586          S == ".eh_frame" || S == ".openbsd.randomdata";
587 }
588
589 // We compute a rank for each section. The rank indicates where the
590 // section should be placed in the file.  Instead of using simple
591 // numbers (0,1,2...), we use a series of flags. One for each decision
592 // point when placing the section.
593 // Using flags has two key properties:
594 // * It is easy to check if a give branch was taken.
595 // * It is easy two see how similar two ranks are (see getRankProximity).
596 enum RankFlags {
597   RF_NOT_ADDR_SET = 1 << 16,
598   RF_NOT_INTERP = 1 << 15,
599   RF_NOT_ALLOC = 1 << 14,
600   RF_WRITE = 1 << 13,
601   RF_EXEC_WRITE = 1 << 12,
602   RF_EXEC = 1 << 11,
603   RF_NON_TLS_BSS = 1 << 10,
604   RF_NON_TLS_BSS_RO = 1 << 9,
605   RF_NOT_TLS = 1 << 8,
606   RF_BSS = 1 << 7,
607   RF_PPC_NOT_TOCBSS = 1 << 6,
608   RF_PPC_OPD = 1 << 5,
609   RF_PPC_TOCL = 1 << 4,
610   RF_PPC_TOC = 1 << 3,
611   RF_PPC_BRANCH_LT = 1 << 2,
612   RF_MIPS_GPREL = 1 << 1,
613   RF_MIPS_NOT_GOT = 1 << 0
614 };
615
616 static unsigned getSectionRank(const OutputSection *Sec) {
617   unsigned Rank = 0;
618
619   // We want to put section specified by -T option first, so we
620   // can start assigning VA starting from them later.
621   if (Config->SectionStartMap.count(Sec->Name))
622     return Rank;
623   Rank |= RF_NOT_ADDR_SET;
624
625   // Put .interp first because some loaders want to see that section
626   // on the first page of the executable file when loaded into memory.
627   if (Sec->Name == ".interp")
628     return Rank;
629   Rank |= RF_NOT_INTERP;
630
631   // Allocatable sections go first to reduce the total PT_LOAD size and
632   // so debug info doesn't change addresses in actual code.
633   if (!(Sec->Flags & SHF_ALLOC))
634     return Rank | RF_NOT_ALLOC;
635
636   // Sort sections based on their access permission in the following
637   // order: R, RX, RWX, RW.  This order is based on the following
638   // considerations:
639   // * Read-only sections come first such that they go in the
640   //   PT_LOAD covering the program headers at the start of the file.
641   // * Read-only, executable sections come next, unless the
642   //   -no-rosegment option is used.
643   // * Writable, executable sections follow such that .plt on
644   //   architectures where it needs to be writable will be placed
645   //   between .text and .data.
646   // * Writable sections come last, such that .bss lands at the very
647   //   end of the last PT_LOAD.
648   bool IsExec = Sec->Flags & SHF_EXECINSTR;
649   bool IsWrite = Sec->Flags & SHF_WRITE;
650
651   if (IsExec) {
652     if (IsWrite)
653       Rank |= RF_EXEC_WRITE;
654     else if (!Config->SingleRoRx)
655       Rank |= RF_EXEC;
656   } else {
657     if (IsWrite)
658       Rank |= RF_WRITE;
659   }
660
661   // If we got here we know that both A and B are in the same PT_LOAD.
662
663   bool IsTls = Sec->Flags & SHF_TLS;
664   bool IsNoBits = Sec->Type == SHT_NOBITS;
665
666   // The first requirement we have is to put (non-TLS) nobits sections last. The
667   // reason is that the only thing the dynamic linker will see about them is a
668   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
669   // PT_LOAD, so that has to correspond to the nobits sections.
670   bool IsNonTlsNoBits = IsNoBits && !IsTls;
671   if (IsNonTlsNoBits)
672     Rank |= RF_NON_TLS_BSS;
673
674   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
675   // sections after r/w ones, so that the RelRo sections are contiguous.
676   bool IsRelRo = isRelroSection(Sec);
677   if (IsNonTlsNoBits && !IsRelRo)
678     Rank |= RF_NON_TLS_BSS_RO;
679   if (!IsNonTlsNoBits && IsRelRo)
680     Rank |= RF_NON_TLS_BSS_RO;
681
682   // The TLS initialization block needs to be a single contiguous block in a R/W
683   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
684   // sections. The TLS NOBITS sections are placed here as they don't take up
685   // virtual address space in the PT_LOAD.
686   if (!IsTls)
687     Rank |= RF_NOT_TLS;
688
689   // Within the TLS initialization block, the non-nobits sections need to appear
690   // first.
691   if (IsNoBits)
692     Rank |= RF_BSS;
693
694   // // Some architectures have additional ordering restrictions for sections
695   // // within the same PT_LOAD.
696   if (Config->EMachine == EM_PPC64) {
697     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
698     // that we would like to make sure appear is a specific order to maximize
699     // their coverage by a single signed 16-bit offset from the TOC base
700     // pointer. Conversely, the special .tocbss section should be first among
701     // all SHT_NOBITS sections. This will put it next to the loaded special
702     // PPC64 sections (and, thus, within reach of the TOC base pointer).
703     StringRef Name = Sec->Name;
704     if (Name != ".tocbss")
705       Rank |= RF_PPC_NOT_TOCBSS;
706
707     if (Name == ".opd")
708       Rank |= RF_PPC_OPD;
709
710     if (Name == ".toc1")
711       Rank |= RF_PPC_TOCL;
712
713     if (Name == ".toc")
714       Rank |= RF_PPC_TOC;
715
716     if (Name == ".branch_lt")
717       Rank |= RF_PPC_BRANCH_LT;
718   }
719   if (Config->EMachine == EM_MIPS) {
720     // All sections with SHF_MIPS_GPREL flag should be grouped together
721     // because data in these sections is addressable with a gp relative address.
722     if (Sec->Flags & SHF_MIPS_GPREL)
723       Rank |= RF_MIPS_GPREL;
724
725     if (Sec->Name != ".got")
726       Rank |= RF_MIPS_NOT_GOT;
727   }
728
729   return Rank;
730 }
731
732 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
733   const OutputSection *A = cast<OutputSectionCommand>(ACmd)->Sec;
734   const OutputSection *B = cast<OutputSectionCommand>(BCmd)->Sec;
735   if (A->SortRank != B->SortRank)
736     return A->SortRank < B->SortRank;
737   if (!(A->SortRank & RF_NOT_ADDR_SET))
738     return Config->SectionStartMap.lookup(A->Name) <
739            Config->SectionStartMap.lookup(B->Name);
740   return false;
741 }
742
743 void PhdrEntry::add(OutputSection *Sec) {
744   Last = Sec;
745   if (!First)
746     First = Sec;
747   p_align = std::max(p_align, Sec->Alignment);
748   if (p_type == PT_LOAD)
749     Sec->FirstInPtLoad = First;
750 }
751
752 template <class ELFT>
753 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
754                           uint8_t StOther = STV_HIDDEN,
755                           uint8_t Binding = STB_WEAK) {
756   // The linker generated symbols are added as STB_WEAK to allow user defined
757   // ones to override them.
758   return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
759                                      /*Size=*/0, Binding, Sec,
760                                      /*File=*/nullptr);
761 }
762
763 template <class ELFT>
764 static DefinedRegular *
765 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
766                    uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
767   SymbolBody *S = Symtab<ELFT>::X->find(Name);
768   if (!S)
769     return nullptr;
770   if (S->isInCurrentDSO())
771     return nullptr;
772   return cast<DefinedRegular>(
773       addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
774 }
775
776 // The beginning and the ending of .rel[a].plt section are marked
777 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
778 // executable. The runtime needs these symbols in order to resolve
779 // all IRELATIVE relocs on startup. For dynamic executables, we don't
780 // need these symbols, since IRELATIVE relocs are resolved through GOT
781 // and PLT. For details, see http://www.airs.com/blog/archives/403.
782 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
783   if (InX::DynSymTab)
784     return;
785   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
786   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
787
788   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
789   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
790 }
791
792 // The linker is expected to define some symbols depending on
793 // the linking result. This function defines such symbols.
794 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
795   if (Config->EMachine == EM_MIPS) {
796     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
797     // so that it points to an absolute address which by default is relative
798     // to GOT. Default offset is 0x7ff0.
799     // See "Global Data Symbols" in Chapter 6 in the following document:
800     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
801     ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
802
803     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
804     // start of function and 'gp' pointer into GOT.
805     if (Symtab<ELFT>::X->find("_gp_disp"))
806       ElfSym::MipsGpDisp =
807           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
808
809     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
810     // pointer. This symbol is used in the code generated by .cpload pseudo-op
811     // in case of using -mno-shared option.
812     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
813     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
814       ElfSym::MipsLocalGp =
815           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
816   }
817
818   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
819   // is magical and is used to produce a R_386_GOTPC relocation.
820   // The R_386_GOTPC relocation value doesn't actually depend on the
821   // symbol value, so it could use an index of STN_UNDEF which, according
822   // to the spec, means the symbol value is 0.
823   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
824   // the object file.
825   // The situation is even stranger on x86_64 where the assembly doesn't
826   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
827   // an undefined symbol in the .o files.
828   // Given that the symbol is effectively unused, we just create a dummy
829   // hidden one to avoid the undefined symbol error.
830   Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
831
832   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
833   // static linking the linker is required to optimize away any references to
834   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
835   // to avoid the undefined symbol error.
836   if (!InX::DynSymTab)
837     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
838
839   // __ehdr_start is the location of ELF file headers. Note that we define
840   // this symbol unconditionally even when using a linker script, which
841   // differs from the behavior implemented by GNU linker which only define
842   // this symbol if ELF headers are in the memory mapped segment.
843   // __executable_start is not documented, but the expectation of at
844   // least the android libc is that it points to the elf header too.
845   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
846   // each DSO. The address of the symbol doesn't matter as long as they are
847   // different in different DSOs, so we chose the start address of the DSO.
848   for (const char *Name :
849        {"__ehdr_start", "__executable_start", "__dso_handle"})
850     addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
851
852   // If linker script do layout we do not need to create any standart symbols.
853   if (Script->Opt.HasSections)
854     return;
855
856   auto Add = [](StringRef S) {
857     return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
858   };
859
860   ElfSym::Bss = Add("__bss_start");
861   ElfSym::End1 = Add("end");
862   ElfSym::End2 = Add("_end");
863   ElfSym::Etext1 = Add("etext");
864   ElfSym::Etext2 = Add("_etext");
865   ElfSym::Edata1 = Add("edata");
866   ElfSym::Edata2 = Add("_edata");
867 }
868
869 // Sort input sections by section name suffixes for
870 // __attribute__((init_priority(N))).
871 static void sortInitFini(OutputSection *S) {
872   if (S)
873     reinterpret_cast<OutputSection *>(S)->sortInitFini();
874 }
875
876 // Sort input sections by the special rule for .ctors and .dtors.
877 static void sortCtorsDtors(OutputSection *S) {
878   if (S)
879     reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
880 }
881
882 // Sort input sections using the list provided by --symbol-ordering-file.
883 template <class ELFT>
884 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
885   if (Config->SymbolOrderingFile.empty())
886     return;
887
888   // Build a map from symbols to their priorities. Symbols that didn't
889   // appear in the symbol ordering file have the lowest priority 0.
890   // All explicitly mentioned symbols have negative (higher) priorities.
891   DenseMap<StringRef, int> SymbolOrder;
892   int Priority = -Config->SymbolOrderingFile.size();
893   for (StringRef S : Config->SymbolOrderingFile)
894     SymbolOrder.insert({S, Priority++});
895
896   // Build a map from sections to their priorities.
897   DenseMap<SectionBase *, int> SectionOrder;
898   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
899     for (SymbolBody *Body : File->getSymbols()) {
900       auto *D = dyn_cast<DefinedRegular>(Body);
901       if (!D || !D->Section)
902         continue;
903       int &Priority = SectionOrder[D->Section];
904       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
905     }
906   }
907
908   // Sort sections by priority.
909   for (OutputSection *Base : OutputSections)
910     if (auto *Sec = dyn_cast<OutputSection>(Base))
911       Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
912 }
913
914 template <class ELFT>
915 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
916   for (InputSectionBase *IS : InputSections) {
917     if (!IS->Live)
918       continue;
919     // Scan all relocations. Each relocation goes through a series
920     // of tests to determine if it needs special treatment, such as
921     // creating GOT, PLT, copy relocations, etc.
922     // Note that relocations for non-alloc sections are directly
923     // processed by InputSection::relocateNonAlloc.
924     if (!(IS->Flags & SHF_ALLOC))
925       continue;
926     if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
927       Fn(*IS);
928   }
929
930   if (!Config->Relocatable) {
931     for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
932       Fn(*ES);
933   }
934 }
935
936 template <class ELFT> void Writer<ELFT>::createSections() {
937   for (InputSectionBase *IS : InputSections)
938     if (IS)
939       Factory.addInputSec(IS, getOutputSectionName(IS->Name));
940
941   sortBySymbolsOrder<ELFT>(OutputSections);
942   sortInitFini(findSection(".init_array"));
943   sortInitFini(findSection(".fini_array"));
944   sortCtorsDtors(findSection(".ctors"));
945   sortCtorsDtors(findSection(".dtors"));
946 }
947
948 // We want to find how similar two ranks are.
949 // The more branches in getSectionRank that match, the more similar they are.
950 // Since each branch corresponds to a bit flag, we can just use
951 // countLeadingZeros.
952 static int getRankProximity(OutputSection *A, OutputSection *B) {
953   return countLeadingZeros(A->SortRank ^ B->SortRank);
954 }
955
956 static int getRankProximity(OutputSection *A, BaseCommand *B) {
957   if (auto *Cmd = dyn_cast<OutputSectionCommand>(B))
958     if (Cmd->Sec)
959       return getRankProximity(A, Cmd->Sec);
960   return -1;
961 }
962
963 // When placing orphan sections, we want to place them after symbol assignments
964 // so that an orphan after
965 //   begin_foo = .;
966 //   foo : { *(foo) }
967 //   end_foo = .;
968 // doesn't break the intended meaning of the begin/end symbols.
969 // We don't want to go over sections since findOrphanPos is the
970 // one in charge of deciding the order of the sections.
971 // We don't want to go over changes to '.', since doing so in
972 //  rx_sec : { *(rx_sec) }
973 //  . = ALIGN(0x1000);
974 //  /* The RW PT_LOAD starts here*/
975 //  rw_sec : { *(rw_sec) }
976 // would mean that the RW PT_LOAD would become unaligned.
977 static bool shouldSkip(BaseCommand *Cmd) {
978   if (isa<OutputSectionCommand>(Cmd))
979     return false;
980   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
981     return Assign->Name != ".";
982   return true;
983 }
984
985 // We want to place orphan sections so that they share as much
986 // characteristics with their neighbors as possible. For example, if
987 // both are rw, or both are tls.
988 template <typename ELFT>
989 static std::vector<BaseCommand *>::iterator
990 findOrphanPos(std::vector<BaseCommand *>::iterator B,
991               std::vector<BaseCommand *>::iterator E) {
992   OutputSection *Sec = cast<OutputSectionCommand>(*E)->Sec;
993
994   // Find the first element that has as close a rank as possible.
995   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
996     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
997   });
998   if (I == E)
999     return E;
1000
1001   // Consider all existing sections with the same proximity.
1002   int Proximity = getRankProximity(Sec, *I);
1003   for (; I != E; ++I) {
1004     auto *Cmd = dyn_cast<OutputSectionCommand>(*I);
1005     if (!Cmd || !Cmd->Sec)
1006       continue;
1007     if (getRankProximity(Sec, Cmd->Sec) != Proximity ||
1008         Sec->SortRank < Cmd->Sec->SortRank)
1009       break;
1010   }
1011   auto J = std::find_if(
1012       llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1013       [](BaseCommand *Cmd) { return isa<OutputSectionCommand>(Cmd); });
1014   I = J.base();
1015   while (I != E && shouldSkip(*I))
1016     ++I;
1017   return I;
1018 }
1019
1020 template <class ELFT> void Writer<ELFT>::sortSections() {
1021   // Don't sort if using -r. It is not necessary and we want to preserve the
1022   // relative order for SHF_LINK_ORDER sections.
1023   if (Config->Relocatable)
1024     return;
1025
1026   if (Script->Opt.HasSections)
1027     Script->adjustSectionsBeforeSorting();
1028
1029   for (BaseCommand *Base : Script->Opt.Commands)
1030     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1031       if (OutputSection *Sec = Cmd->Sec)
1032         Sec->SortRank = getSectionRank(Sec);
1033
1034   if (!Script->Opt.HasSections) {
1035     // We know that all the OutputSectionCommands are contiguous in
1036     // this case.
1037     auto E = Script->Opt.Commands.end();
1038     auto I = Script->Opt.Commands.begin();
1039     auto IsSection = [](BaseCommand *Base) {
1040       return isa<OutputSectionCommand>(Base);
1041     };
1042     I = std::find_if(I, E, IsSection);
1043     E = std::find_if(llvm::make_reverse_iterator(E),
1044                      llvm::make_reverse_iterator(I), IsSection)
1045             .base();
1046     std::stable_sort(I, E, compareSections);
1047     return;
1048   }
1049
1050   // Orphan sections are sections present in the input files which are
1051   // not explicitly placed into the output file by the linker script.
1052   //
1053   // The sections in the linker script are already in the correct
1054   // order. We have to figuere out where to insert the orphan
1055   // sections.
1056   //
1057   // The order of the sections in the script is arbitrary and may not agree with
1058   // compareSections. This means that we cannot easily define a strict weak
1059   // ordering. To see why, consider a comparison of a section in the script and
1060   // one not in the script. We have a two simple options:
1061   // * Make them equivalent (a is not less than b, and b is not less than a).
1062   //   The problem is then that equivalence has to be transitive and we can
1063   //   have sections a, b and c with only b in a script and a less than c
1064   //   which breaks this property.
1065   // * Use compareSectionsNonScript. Given that the script order doesn't have
1066   //   to match, we can end up with sections a, b, c, d where b and c are in the
1067   //   script and c is compareSectionsNonScript less than b. In which case d
1068   //   can be equivalent to c, a to b and d < a. As a concrete example:
1069   //   .a (rx) # not in script
1070   //   .b (rx) # in script
1071   //   .c (ro) # in script
1072   //   .d (ro) # not in script
1073   //
1074   // The way we define an order then is:
1075   // *  Sort only the orphan sections. They are in the end right now.
1076   // *  Move each orphan section to its preferred position. We try
1077   //    to put each section in the last position where it it can share
1078   //    a PT_LOAD.
1079   //
1080   // There is some ambiguity as to where exactly a new entry should be
1081   // inserted, because Opt.Commands contains not only output section
1082   // commands but also other types of commands such as symbol assignment
1083   // expressions. There's no correct answer here due to the lack of the
1084   // formal specification of the linker script. We use heuristics to
1085   // determine whether a new output command should be added before or
1086   // after another commands. For the details, look at shouldSkip
1087   // function.
1088
1089   auto I = Script->Opt.Commands.begin();
1090   auto E = Script->Opt.Commands.end();
1091   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1092     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1093       return Cmd->Sec && Cmd->Sec->SectionIndex == INT_MAX;
1094     return false;
1095   });
1096
1097   // Sort the orphan sections.
1098   std::stable_sort(NonScriptI, E, compareSections);
1099
1100   // As a horrible special case, skip the first . assignment if it is before any
1101   // section. We do this because it is common to set a load address by starting
1102   // the script with ". = 0xabcd" and the expectation is that every section is
1103   // after that.
1104   auto FirstSectionOrDotAssignment =
1105       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1106   if (FirstSectionOrDotAssignment != E &&
1107       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1108     ++FirstSectionOrDotAssignment;
1109   I = FirstSectionOrDotAssignment;
1110
1111   while (NonScriptI != E) {
1112     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1113     OutputSection *Orphan = cast<OutputSectionCommand>(*NonScriptI)->Sec;
1114
1115     // As an optimization, find all sections with the same sort rank
1116     // and insert them with one rotate.
1117     unsigned Rank = Orphan->SortRank;
1118     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1119       return cast<OutputSectionCommand>(Cmd)->Sec->SortRank != Rank;
1120     });
1121     std::rotate(Pos, NonScriptI, End);
1122     NonScriptI = End;
1123   }
1124
1125   Script->adjustSectionsAfterSorting();
1126 }
1127
1128 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1129                            std::function<void(SyntheticSection *)> Fn) {
1130   for (SyntheticSection *SS : Sections)
1131     if (SS && SS->getParent() && !SS->empty())
1132       Fn(SS);
1133 }
1134
1135 // We need to add input synthetic sections early in createSyntheticSections()
1136 // to make them visible from linkescript side. But not all sections are always
1137 // required to be in output. For example we don't need dynamic section content
1138 // sometimes. This function filters out such unused sections from the output.
1139 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1140   // All input synthetic sections that can be empty are placed after
1141   // all regular ones. We iterate over them all and exit at first
1142   // non-synthetic.
1143   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1144     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1145     if (!SS)
1146       return;
1147     OutputSection *OS = SS->getParent();
1148     if (!SS->empty() || !OS)
1149       continue;
1150     OS->Sections.erase(std::find(OS->Sections.begin(), OS->Sections.end(), SS));
1151     SS->Live = false;
1152     // If there are no other sections in the output section, remove it from the
1153     // output.
1154     if (OS->Sections.empty())
1155       V.erase(std::find(V.begin(), V.end(), OS));
1156   }
1157 }
1158
1159 // Create output section objects and add them to OutputSections.
1160 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1161   Out::DebugInfo = findSection(".debug_info");
1162   Out::PreinitArray = findSection(".preinit_array");
1163   Out::InitArray = findSection(".init_array");
1164   Out::FiniArray = findSection(".fini_array");
1165
1166   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1167   // symbols for sections, so that the runtime can get the start and end
1168   // addresses of each section by section name. Add such symbols.
1169   if (!Config->Relocatable) {
1170     addStartEndSymbols();
1171     for (OutputSection *Sec : OutputSections)
1172       addStartStopSymbols(Sec);
1173   }
1174
1175   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1176   // It should be okay as no one seems to care about the type.
1177   // Even the author of gold doesn't remember why gold behaves that way.
1178   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1179   if (InX::DynSymTab)
1180     addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1181
1182   // Define __rel[a]_iplt_{start,end} symbols if needed.
1183   addRelIpltSymbols();
1184
1185   // This responsible for splitting up .eh_frame section into
1186   // pieces. The relocation scan uses those pieces, so this has to be
1187   // earlier.
1188   applySynthetic({In<ELFT>::EhFrame},
1189                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1190
1191   // Scan relocations. This must be done after every symbol is declared so that
1192   // we can correctly decide if a dynamic relocation is needed.
1193   forEachRelSec(scanRelocations<ELFT>);
1194
1195   if (InX::Plt && !InX::Plt->empty())
1196     InX::Plt->addSymbols();
1197   if (InX::Iplt && !InX::Iplt->empty())
1198     InX::Iplt->addSymbols();
1199
1200   // Now that we have defined all possible global symbols including linker-
1201   // synthesized ones. Visit all symbols to give the finishing touches.
1202   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1203     SymbolBody *Body = S->body();
1204
1205     if (!includeInSymtab(*Body))
1206       continue;
1207     if (InX::SymTab)
1208       InX::SymTab->addSymbol(Body);
1209
1210     if (InX::DynSymTab && S->includeInDynsym()) {
1211       InX::DynSymTab->addSymbol(Body);
1212       if (auto *SS = dyn_cast<SharedSymbol>(Body))
1213         if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1214           In<ELFT>::VerNeed->addSymbol(SS);
1215     }
1216   }
1217
1218   // Do not proceed if there was an undefined symbol.
1219   if (ErrorCount)
1220     return;
1221
1222   addPredefinedSections();
1223   removeUnusedSyntheticSections(OutputSections);
1224
1225   clearOutputSections();
1226   sortSections();
1227
1228   // Now that we have the final list, create a list of all the
1229   // OutputSectionCommands for convenience.
1230   for (BaseCommand *Base : Script->Opt.Commands)
1231     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1232       OutputSectionCommands.push_back(Cmd);
1233
1234   // This is a bit of a hack. A value of 0 means undef, so we set it
1235   // to 1 t make __ehdr_start defined. The section number is not
1236   // particularly relevant.
1237   Out::ElfHeader->SectionIndex = 1;
1238
1239   unsigned I = 1;
1240   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1241     OutputSection *Sec = Cmd->Sec;
1242     Sec->SectionIndex = I++;
1243     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1244   }
1245
1246   // Binary and relocatable output does not have PHDRS.
1247   // The headers have to be created before finalize as that can influence the
1248   // image base and the dynamic section on mips includes the image base.
1249   if (!Config->Relocatable && !Config->OFormatBinary) {
1250     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1251     addPtArmExid(Phdrs);
1252     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1253   }
1254
1255   // Compute the size of .rela.dyn and .rela.plt early since we need
1256   // them to populate .dynamic.
1257   for (SyntheticSection *SS : {In<ELFT>::RelaDyn, In<ELFT>::RelaPlt})
1258     if (SS->getParent() && !SS->empty())
1259       SS->getParent()->assignOffsets();
1260
1261   // Dynamic section must be the last one in this list and dynamic
1262   // symbol table section (DynSymTab) must be the first one.
1263   applySynthetic({InX::DynSymTab,    InX::Bss,           InX::BssRelRo,
1264                   InX::GnuHashTab,   In<ELFT>::HashTab,  InX::SymTab,
1265                   InX::ShStrTab,     InX::StrTab,        In<ELFT>::VerDef,
1266                   InX::DynStrTab,    InX::GdbIndex,      InX::Got,
1267                   InX::MipsGot,      InX::IgotPlt,       InX::GotPlt,
1268                   In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1269                   InX::Plt,          InX::Iplt,          In<ELFT>::EhFrameHdr,
1270                   In<ELFT>::VerSym,  In<ELFT>::VerNeed,  InX::Dynamic},
1271                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1272
1273   // Some architectures use small displacements for jump instructions.
1274   // It is linker's responsibility to create thunks containing long
1275   // jump instructions if jump targets are too far. Create thunks.
1276   if (Target->NeedsThunks) {
1277     // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1278     // these
1279     // do not require address information. To support range extension Thunks
1280     // we need to assign addresses so that we can tell if jump instructions
1281     // are out of range. This will need to turn into a loop that converges
1282     // when no more Thunks are added
1283     ThunkCreator TC;
1284     if (TC.createThunks(OutputSectionCommands)) {
1285       applySynthetic({InX::MipsGot},
1286                      [](SyntheticSection *SS) { SS->updateAllocSize(); });
1287       if (TC.createThunks(OutputSectionCommands))
1288         fatal("All non-range thunks should be created in first call");
1289     }
1290   }
1291
1292   // Fill other section headers. The dynamic table is finalized
1293   // at the end because some tags like RELSZ depend on result
1294   // of finalizing other sections.
1295   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1296     Cmd->finalize<ELFT>();
1297
1298   // createThunks may have added local symbols to the static symbol table
1299   applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1300                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1301 }
1302
1303 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1304   // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1305   // We have the terminater synthetic section class. Add that at the end.
1306   auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1307   if (!OS || OS->Sections.empty() || Config->Relocatable)
1308     return;
1309
1310   auto *Sentinel = make<ARMExidxSentinelSection>();
1311   OS->addSection(Sentinel);
1312   // If there are linker script commands existing at this point then add the
1313   // sentinel to the last of these too.
1314   if (OutputSectionCommand *C = Script->getCmd(OS)) {
1315     auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
1316                             [](const BaseCommand *Base) {
1317                               return isa<InputSectionDescription>(Base);
1318                             });
1319     cast<InputSectionDescription>(*ISD)->Sections.push_back(Sentinel);
1320   }
1321 }
1322
1323 // The linker is expected to define SECNAME_start and SECNAME_end
1324 // symbols for a few sections. This function defines them.
1325 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1326   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1327     // These symbols resolve to the image base if the section does not exist.
1328     // A special value -1 indicates end of the section.
1329     if (OS) {
1330       addOptionalRegular<ELFT>(Start, OS, 0);
1331       addOptionalRegular<ELFT>(End, OS, -1);
1332     } else {
1333       if (Config->Pic)
1334         OS = Out::ElfHeader;
1335       addOptionalRegular<ELFT>(Start, OS, 0);
1336       addOptionalRegular<ELFT>(End, OS, 0);
1337     }
1338   };
1339
1340   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1341   Define("__init_array_start", "__init_array_end", Out::InitArray);
1342   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1343
1344   if (OutputSection *Sec = findSection(".ARM.exidx"))
1345     Define("__exidx_start", "__exidx_end", Sec);
1346 }
1347
1348 // If a section name is valid as a C identifier (which is rare because of
1349 // the leading '.'), linkers are expected to define __start_<secname> and
1350 // __stop_<secname> symbols. They are at beginning and end of the section,
1351 // respectively. This is not requested by the ELF standard, but GNU ld and
1352 // gold provide the feature, and used by many programs.
1353 template <class ELFT>
1354 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1355   StringRef S = Sec->Name;
1356   if (!isValidCIdentifier(S))
1357     return;
1358   addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1359   addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1360 }
1361
1362 template <class ELFT>
1363 OutputSectionCommand *Writer<ELFT>::findSectionCommand(StringRef Name) {
1364   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1365     if (Cmd->Name == Name)
1366       return Cmd;
1367   return nullptr;
1368 }
1369
1370 template <class ELFT> OutputSection *Writer<ELFT>::findSectionInScript(StringRef Name) {
1371   if (OutputSectionCommand *Cmd = findSectionCommand(Name))
1372     return Cmd->Sec;
1373   return nullptr;
1374 }
1375
1376 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1377   for (OutputSection *Sec : OutputSections)
1378     if (Sec->Name == Name)
1379       return Sec;
1380   return nullptr;
1381 }
1382
1383 static bool needsPtLoad(OutputSection *Sec) {
1384   if (!(Sec->Flags & SHF_ALLOC))
1385     return false;
1386
1387   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1388   // responsible for allocating space for them, not the PT_LOAD that
1389   // contains the TLS initialization image.
1390   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1391     return false;
1392   return true;
1393 }
1394
1395 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1396 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1397 // RW. This means that there is no alignment in the RO to RX transition and we
1398 // cannot create a PT_LOAD there.
1399 static uint64_t computeFlags(uint64_t Flags) {
1400   if (Config->Omagic)
1401     return PF_R | PF_W | PF_X;
1402   if (Config->SingleRoRx && !(Flags & PF_W))
1403     return Flags | PF_X;
1404   return Flags;
1405 }
1406
1407 // Decide which program headers to create and which sections to include in each
1408 // one.
1409 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1410   std::vector<PhdrEntry> Ret;
1411   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1412     Ret.emplace_back(Type, Flags);
1413     return &Ret.back();
1414   };
1415
1416   // The first phdr entry is PT_PHDR which describes the program header itself.
1417   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1418
1419   // PT_INTERP must be the second entry if exists.
1420   if (OutputSection *Sec = findSectionInScript(".interp"))
1421     AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1422
1423   // Add the first PT_LOAD segment for regular output sections.
1424   uint64_t Flags = computeFlags(PF_R);
1425   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1426
1427   // Add the headers. We will remove them if they don't fit.
1428   Load->add(Out::ElfHeader);
1429   Load->add(Out::ProgramHeaders);
1430
1431   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1432     OutputSection *Sec = Cmd->Sec;
1433     if (!(Sec->Flags & SHF_ALLOC))
1434       break;
1435     if (!needsPtLoad(Sec))
1436       continue;
1437
1438     // Segments are contiguous memory regions that has the same attributes
1439     // (e.g. executable or writable). There is one phdr for each segment.
1440     // Therefore, we need to create a new phdr when the next section has
1441     // different flags or is loaded at a discontiguous address using AT linker
1442     // script command.
1443     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1444     if (Script->hasLMA(Sec) || Flags != NewFlags) {
1445       Load = AddHdr(PT_LOAD, NewFlags);
1446       Flags = NewFlags;
1447     }
1448
1449     Load->add(Sec);
1450   }
1451
1452   // Add a TLS segment if any.
1453   PhdrEntry TlsHdr(PT_TLS, PF_R);
1454   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1455     OutputSection *Sec = Cmd->Sec;
1456     if (Sec->Flags & SHF_TLS)
1457       TlsHdr.add(Sec);
1458   }
1459   if (TlsHdr.First)
1460     Ret.push_back(std::move(TlsHdr));
1461
1462   // Add an entry for .dynamic.
1463   if (InX::DynSymTab)
1464     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1465         ->add(InX::Dynamic->getParent());
1466
1467   // PT_GNU_RELRO includes all sections that should be marked as
1468   // read-only by dynamic linker after proccessing relocations.
1469   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1470   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1471     OutputSection *Sec = Cmd->Sec;
1472     if (needsPtLoad(Sec) && isRelroSection(Sec))
1473       RelRo.add(Sec);
1474   }
1475   if (RelRo.First)
1476     Ret.push_back(std::move(RelRo));
1477
1478   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1479   if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1480       In<ELFT>::EhFrame->getParent() && In<ELFT>::EhFrameHdr->getParent())
1481     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->getParent()->getPhdrFlags())
1482         ->add(In<ELFT>::EhFrameHdr->getParent());
1483
1484   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1485   // the dynamic linker fill the segment with random data.
1486   if (OutputSection *Sec = findSectionInScript(".openbsd.randomdata"))
1487     AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1488
1489   // PT_GNU_STACK is a special section to tell the loader to make the
1490   // pages for the stack non-executable. If you really want an executable
1491   // stack, you can pass -z execstack, but that's not recommended for
1492   // security reasons.
1493   unsigned Perm;
1494   if (Config->ZExecstack)
1495     Perm = PF_R | PF_W | PF_X;
1496   else
1497     Perm = PF_R | PF_W;
1498   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1499
1500   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1501   // is expected to perform W^X violations, such as calling mprotect(2) or
1502   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1503   // OpenBSD.
1504   if (Config->ZWxneeded)
1505     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1506
1507   // Create one PT_NOTE per a group of contiguous .note sections.
1508   PhdrEntry *Note = nullptr;
1509   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1510     OutputSection *Sec = Cmd->Sec;
1511     if (Sec->Type == SHT_NOTE) {
1512       if (!Note || Script->hasLMA(Sec))
1513         Note = AddHdr(PT_NOTE, PF_R);
1514       Note->add(Sec);
1515     } else {
1516       Note = nullptr;
1517     }
1518   }
1519   return Ret;
1520 }
1521
1522 template <class ELFT>
1523 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1524   if (Config->EMachine != EM_ARM)
1525     return;
1526   auto I =
1527       std::find_if(OutputSectionCommands.begin(), OutputSectionCommands.end(),
1528                    [](OutputSectionCommand *Cmd) {
1529                      return Cmd->Sec->Type == SHT_ARM_EXIDX;
1530                    });
1531   if (I == OutputSectionCommands.end())
1532     return;
1533
1534   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1535   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1536   ARMExidx.add((*I)->Sec);
1537   Phdrs.push_back(ARMExidx);
1538 }
1539
1540 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1541 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1542 // linker can set the permissions.
1543 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1544   auto PageAlign = [](OutputSection *Sec) {
1545     OutputSectionCommand *Cmd = Script->getCmd(Sec);
1546     if (Cmd && !Cmd->AddrExpr)
1547       Cmd->AddrExpr = [=] {
1548         return alignTo(Script->getDot(), Config->MaxPageSize);
1549       };
1550   };
1551
1552   for (const PhdrEntry &P : Phdrs)
1553     if (P.p_type == PT_LOAD && P.First)
1554       PageAlign(P.First);
1555
1556   for (const PhdrEntry &P : Phdrs) {
1557     if (P.p_type != PT_GNU_RELRO)
1558       continue;
1559     if (P.First)
1560       PageAlign(P.First);
1561     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1562     // have to align it to a page.
1563     auto End = OutputSectionCommands.end();
1564     auto I =
1565         std::find(OutputSectionCommands.begin(), End, Script->getCmd(P.Last));
1566     if (I == End || (I + 1) == End)
1567       continue;
1568     OutputSection *Sec = (*(I + 1))->Sec;
1569     if (needsPtLoad(Sec))
1570       PageAlign(Sec);
1571   }
1572 }
1573
1574 // Adjusts the file alignment for a given output section and returns
1575 // its new file offset. The file offset must be the same with its
1576 // virtual address (modulo the page size) so that the loader can load
1577 // executables without any address adjustment.
1578 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1579   OutputSection *First = Sec->FirstInPtLoad;
1580   // If the section is not in a PT_LOAD, we just have to align it.
1581   if (!First)
1582     return alignTo(Off, Sec->Alignment);
1583
1584   // The first section in a PT_LOAD has to have congruent offset and address
1585   // module the page size.
1586   if (Sec == First)
1587     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1588
1589   // If two sections share the same PT_LOAD the file offset is calculated
1590   // using this formula: Off2 = Off1 + (VA2 - VA1).
1591   return First->Offset + Sec->Addr - First->Addr;
1592 }
1593
1594 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1595   if (Sec->Type == SHT_NOBITS) {
1596     Sec->Offset = Off;
1597     return Off;
1598   }
1599
1600   Off = getFileAlignment(Off, Sec);
1601   Sec->Offset = Off;
1602   return Off + Sec->Size;
1603 }
1604
1605 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1606   uint64_t Off = 0;
1607   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1608     OutputSection *Sec = Cmd->Sec;
1609     if (Sec->Flags & SHF_ALLOC)
1610       Off = setOffset(Sec, Off);
1611   }
1612   FileSize = alignTo(Off, Config->Wordsize);
1613 }
1614
1615 // Assign file offsets to output sections.
1616 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1617   uint64_t Off = 0;
1618   Off = setOffset(Out::ElfHeader, Off);
1619   Off = setOffset(Out::ProgramHeaders, Off);
1620
1621   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1622     Off = setOffset(Cmd->Sec, Off);
1623
1624   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1625   FileSize =
1626       SectionHeaderOff + (OutputSectionCommands.size() + 1) * sizeof(Elf_Shdr);
1627 }
1628
1629 // Finalize the program headers. We call this function after we assign
1630 // file offsets and VAs to all sections.
1631 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1632   for (PhdrEntry &P : Phdrs) {
1633     OutputSection *First = P.First;
1634     OutputSection *Last = P.Last;
1635     if (First) {
1636       P.p_filesz = Last->Offset - First->Offset;
1637       if (Last->Type != SHT_NOBITS)
1638         P.p_filesz += Last->Size;
1639       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1640       P.p_offset = First->Offset;
1641       P.p_vaddr = First->Addr;
1642       if (!P.HasLMA)
1643         P.p_paddr = First->getLMA();
1644     }
1645     if (P.p_type == PT_LOAD)
1646       P.p_align = Config->MaxPageSize;
1647     else if (P.p_type == PT_GNU_RELRO)
1648       P.p_align = 1;
1649
1650     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1651     // so round up the size to make sure the offsets are correct.
1652     if (P.p_type == PT_TLS) {
1653       Out::TlsPhdr = &P;
1654       if (P.p_memsz)
1655         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1656     }
1657   }
1658 }
1659
1660 // The entry point address is chosen in the following ways.
1661 //
1662 // 1. the '-e' entry command-line option;
1663 // 2. the ENTRY(symbol) command in a linker control script;
1664 // 3. the value of the symbol start, if present;
1665 // 4. the address of the first byte of the .text section, if present;
1666 // 5. the address 0.
1667 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1668   // Case 1, 2 or 3. As a special case, if the symbol is actually
1669   // a number, we'll use that number as an address.
1670   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1671     return B->getVA();
1672   uint64_t Addr;
1673   if (to_integer(Config->Entry, Addr))
1674     return Addr;
1675
1676   // Case 4
1677   if (OutputSection *Sec = findSectionInScript(".text")) {
1678     if (Config->WarnMissingEntry)
1679       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1680            utohexstr(Sec->Addr));
1681     return Sec->Addr;
1682   }
1683
1684   // Case 5
1685   if (Config->WarnMissingEntry)
1686     warn("cannot find entry symbol " + Config->Entry +
1687          "; not setting start address");
1688   return 0;
1689 }
1690
1691 static uint16_t getELFType() {
1692   if (Config->Pic)
1693     return ET_DYN;
1694   if (Config->Relocatable)
1695     return ET_REL;
1696   return ET_EXEC;
1697 }
1698
1699 // This function is called after we have assigned address and size
1700 // to each section. This function fixes some predefined
1701 // symbol values that depend on section address and size.
1702 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1703   // _etext is the first location after the last read-only loadable segment.
1704   // _edata is the first location after the last read-write loadable segment.
1705   // _end is the first location after the uninitialized data region.
1706   PhdrEntry *Last = nullptr;
1707   PhdrEntry *LastRO = nullptr;
1708   PhdrEntry *LastRW = nullptr;
1709   for (PhdrEntry &P : Phdrs) {
1710     if (P.p_type != PT_LOAD)
1711       continue;
1712     Last = &P;
1713     if (P.p_flags & PF_W)
1714       LastRW = &P;
1715     else
1716       LastRO = &P;
1717   }
1718
1719   auto Set = [](DefinedRegular *S, OutputSection *Sec, uint64_t Value) {
1720     if (S) {
1721       S->Section = Sec;
1722       S->Value = Value;
1723     }
1724   };
1725
1726   if (Last) {
1727     Set(ElfSym::End1, Last->First, Last->p_memsz);
1728     Set(ElfSym::End2, Last->First, Last->p_memsz);
1729   }
1730   if (LastRO) {
1731     Set(ElfSym::Etext1, LastRO->First, LastRO->p_filesz);
1732     Set(ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1733   }
1734   if (LastRW) {
1735     Set(ElfSym::Edata1, LastRW->First, LastRW->p_filesz);
1736     Set(ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1737   }
1738
1739   if (ElfSym::Bss)
1740     ElfSym::Bss->Section = findSectionInScript(".bss");
1741
1742   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1743   // be equal to the _gp symbol's value.
1744   if (Config->EMachine == EM_MIPS && !ElfSym::MipsGp->Value) {
1745     // Find GP-relative section with the lowest address
1746     // and use this address to calculate default _gp value.
1747     for (const OutputSectionCommand *Cmd : OutputSectionCommands) {
1748       OutputSection *OS = Cmd->Sec;
1749       if (OS->Flags & SHF_MIPS_GPREL) {
1750         ElfSym::MipsGp->Value = OS->Addr + 0x7ff0;
1751         break;
1752       }
1753     }
1754   }
1755 }
1756
1757 template <class ELFT> void Writer<ELFT>::writeHeader() {
1758   uint8_t *Buf = Buffer->getBufferStart();
1759   memcpy(Buf, "\177ELF", 4);
1760
1761   // Write the ELF header.
1762   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1763   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1764   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1765   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1766   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1767   EHdr->e_type = getELFType();
1768   EHdr->e_machine = Config->EMachine;
1769   EHdr->e_version = EV_CURRENT;
1770   EHdr->e_entry = getEntryAddr();
1771   EHdr->e_shoff = SectionHeaderOff;
1772   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1773   EHdr->e_phnum = Phdrs.size();
1774   EHdr->e_shentsize = sizeof(Elf_Shdr);
1775   EHdr->e_shnum = OutputSectionCommands.size() + 1;
1776   EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
1777
1778   if (Config->EMachine == EM_ARM)
1779     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1780     // but we don't have any firm guarantees of conformance. Linux AArch64
1781     // kernels (as of 2016) require an EABI version to be set.
1782     EHdr->e_flags = EF_ARM_EABI_VER5;
1783   else if (Config->EMachine == EM_MIPS)
1784     EHdr->e_flags = getMipsEFlags<ELFT>();
1785
1786   if (!Config->Relocatable) {
1787     EHdr->e_phoff = sizeof(Elf_Ehdr);
1788     EHdr->e_phentsize = sizeof(Elf_Phdr);
1789   }
1790
1791   // Write the program header table.
1792   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1793   for (PhdrEntry &P : Phdrs) {
1794     HBuf->p_type = P.p_type;
1795     HBuf->p_flags = P.p_flags;
1796     HBuf->p_offset = P.p_offset;
1797     HBuf->p_vaddr = P.p_vaddr;
1798     HBuf->p_paddr = P.p_paddr;
1799     HBuf->p_filesz = P.p_filesz;
1800     HBuf->p_memsz = P.p_memsz;
1801     HBuf->p_align = P.p_align;
1802     ++HBuf;
1803   }
1804
1805   // Write the section header table. Note that the first table entry is null.
1806   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1807   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1808     Cmd->Sec->writeHeaderTo<ELFT>(++SHdrs);
1809 }
1810
1811 // Open a result file.
1812 template <class ELFT> void Writer<ELFT>::openFile() {
1813   if (!Config->Is64 && FileSize > UINT32_MAX) {
1814     error("output file too large: " + Twine(FileSize) + " bytes");
1815     return;
1816   }
1817
1818   unlinkAsync(Config->OutputFile);
1819   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1820       FileOutputBuffer::create(Config->OutputFile, FileSize,
1821                                FileOutputBuffer::F_executable);
1822
1823   if (auto EC = BufferOrErr.getError())
1824     error("failed to open " + Config->OutputFile + ": " + EC.message());
1825   else
1826     Buffer = std::move(*BufferOrErr);
1827 }
1828
1829 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1830   uint8_t *Buf = Buffer->getBufferStart();
1831   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1832     OutputSection *Sec = Cmd->Sec;
1833     if (Sec->Flags & SHF_ALLOC)
1834       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1835   }
1836 }
1837
1838 // Write section contents to a mmap'ed file.
1839 template <class ELFT> void Writer<ELFT>::writeSections() {
1840   uint8_t *Buf = Buffer->getBufferStart();
1841
1842   // PPC64 needs to process relocations in the .opd section
1843   // before processing relocations in code-containing sections.
1844   if (auto *OpdCmd = findSectionCommand(".opd")) {
1845     Out::Opd = OpdCmd->Sec;
1846     Out::OpdBuf = Buf + Out::Opd->Offset;
1847     OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1848   }
1849
1850   OutputSection *EhFrameHdr =
1851       (In<ELFT>::EhFrameHdr && !In<ELFT>::EhFrameHdr->empty())
1852           ? In<ELFT>::EhFrameHdr->getParent()
1853           : nullptr;
1854
1855   // In -r or -emit-relocs mode, write the relocation sections first as in
1856   // ELf_Rel targets we might find out that we need to modify the relocated
1857   // section while doing it.
1858   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1859     OutputSection *Sec = Cmd->Sec;
1860     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1861       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1862   }
1863
1864   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1865     OutputSection *Sec = Cmd->Sec;
1866     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1867         Sec->Type != SHT_RELA)
1868       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1869   }
1870
1871   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1872   // it should be written after .eh_frame is written.
1873   if (EhFrameHdr) {
1874     OutputSectionCommand *Cmd = Script->getCmd(EhFrameHdr);
1875     Cmd->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1876   }
1877 }
1878
1879 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1880   if (!InX::BuildId || !InX::BuildId->getParent())
1881     return;
1882
1883   // Compute a hash of all sections of the output file.
1884   uint8_t *Start = Buffer->getBufferStart();
1885   uint8_t *End = Start + FileSize;
1886   InX::BuildId->writeBuildId({Start, End});
1887 }
1888
1889 template void elf::writeResult<ELF32LE>();
1890 template void elf::writeResult<ELF32BE>();
1891 template void elf::writeResult<ELF64LE>();
1892 template void elf::writeResult<ELF64BE>();