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