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