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