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