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