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