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