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