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