xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 346bd6a2)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Writer.h"
11 #include "Config.h"
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
14 #include "MapFile.h"
15 #include "Memory.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "Strings.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "lld/Common/Threads.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include <climits>
27 
28 using namespace llvm;
29 using namespace llvm::ELF;
30 using namespace llvm::object;
31 using namespace llvm::support;
32 using namespace llvm::support::endian;
33 
34 using namespace lld;
35 using namespace lld::elf;
36 
37 namespace {
38 // The writer writes a SymbolTable result to a file.
39 template <class ELFT> class Writer {
40 public:
41   typedef typename ELFT::Shdr Elf_Shdr;
42   typedef typename ELFT::Ehdr Elf_Ehdr;
43   typedef typename ELFT::Phdr Elf_Phdr;
44 
45   void run();
46 
47 private:
48   void createSyntheticSections();
49   void copyLocalSymbols();
50   void addSectionSymbols();
51   void addReservedSymbols();
52   void 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->HasSectionsCommand) {
165     // If linker script contains SECTIONS commands, let it create sections.
166     Script->processSectionCommands(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->processSectionCommands(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->SectionCommands) {
470     auto *Sec = dyn_cast<OutputSection>(Base);
471     if (!Sec)
472       continue;
473     auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
474       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
475         return !ISD->Sections.empty();
476       return false;
477     });
478     if (I == Sec->SectionCommands.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   // __ehdr_start is the location of ELF file headers. Note that we define
803   // this symbol unconditionally even when using a linker script, which
804   // differs from the behavior implemented by GNU linker which only define
805   // this symbol if ELF headers are in the memory mapped segment.
806   // __executable_start is not documented, but the expectation of at
807   // least the android libc is that it points to the elf header too.
808   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
809   // each DSO. The address of the symbol doesn't matter as long as they are
810   // different in different DSOs, so we chose the start address of the DSO.
811   for (const char *Name :
812        {"__ehdr_start", "__executable_start", "__dso_handle"})
813     addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
814 
815   // If linker script do layout we do not need to create any standart symbols.
816   if (Script->HasSectionsCommand)
817     return;
818 
819   auto Add = [](StringRef S, int64_t Pos) {
820     return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
821   };
822 
823   ElfSym::Bss = Add("__bss_start", 0);
824   ElfSym::End1 = Add("end", -1);
825   ElfSym::End2 = Add("_end", -1);
826   ElfSym::Etext1 = Add("etext", -1);
827   ElfSym::Etext2 = Add("_etext", -1);
828   ElfSym::Edata1 = Add("edata", -1);
829   ElfSym::Edata2 = Add("_edata", -1);
830 }
831 
832 // Sort input sections by section name suffixes for
833 // __attribute__((init_priority(N))).
834 static void sortInitFini(OutputSection *Cmd) {
835   if (Cmd)
836     Cmd->sortInitFini();
837 }
838 
839 // Sort input sections by the special rule for .ctors and .dtors.
840 static void sortCtorsDtors(OutputSection *Cmd) {
841   if (Cmd)
842     Cmd->sortCtorsDtors();
843 }
844 
845 // Sort input sections using the list provided by --symbol-ordering-file.
846 static void sortBySymbolsOrder() {
847   if (Config->SymbolOrderingFile.empty())
848     return;
849 
850   // Sort sections by priority.
851   DenseMap<SectionBase *, int> SectionOrder = buildSectionOrder();
852   for (BaseCommand *Base : Script->SectionCommands)
853     if (auto *Sec = dyn_cast<OutputSection>(Base))
854       Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
855 }
856 
857 template <class ELFT>
858 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
859   // Scan all relocations. Each relocation goes through a series
860   // of tests to determine if it needs special treatment, such as
861   // creating GOT, PLT, copy relocations, etc.
862   // Note that relocations for non-alloc sections are directly
863   // processed by InputSection::relocateNonAlloc.
864   for (InputSectionBase *IS : InputSections)
865     if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
866       Fn(*IS);
867   for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
868     Fn(*ES);
869 }
870 
871 template <class ELFT> void Writer<ELFT>::createSections() {
872   std::vector<OutputSection *> Vec;
873   for (InputSectionBase *IS : InputSections)
874     if (IS)
875       if (OutputSection *Sec =
876               Factory.addInputSec(IS, getOutputSectionName(IS->Name)))
877         Vec.push_back(Sec);
878 
879   Script->SectionCommands.insert(Script->SectionCommands.begin(), Vec.begin(),
880                                  Vec.end());
881 
882   Script->fabricateDefaultCommands();
883   sortBySymbolsOrder();
884   sortInitFini(findSection(".init_array"));
885   sortInitFini(findSection(".fini_array"));
886   sortCtorsDtors(findSection(".ctors"));
887   sortCtorsDtors(findSection(".dtors"));
888 }
889 
890 // This function generates assignments for predefined symbols (e.g. _end or
891 // _etext) and inserts them into the commands sequence to be processed at the
892 // appropriate time. This ensures that the value is going to be correct by the
893 // time any references to these symbols are processed and is equivalent to
894 // defining these symbols explicitly in the linker script.
895 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
896   PhdrEntry *Last = nullptr;
897   PhdrEntry *LastRO = nullptr;
898   PhdrEntry *LastRW = nullptr;
899 
900   for (PhdrEntry *P : Phdrs) {
901     if (P->p_type != PT_LOAD)
902       continue;
903     Last = P;
904     if (P->p_flags & PF_W)
905       LastRW = P;
906     else
907       LastRO = P;
908   }
909 
910   // _end is the first location after the uninitialized data region.
911   if (Last) {
912     if (ElfSym::End1)
913       ElfSym::End1->Section = Last->LastSec;
914     if (ElfSym::End2)
915       ElfSym::End2->Section = Last->LastSec;
916   }
917 
918   // _etext is the first location after the last read-only loadable segment.
919   if (LastRO) {
920     if (ElfSym::Etext1)
921       ElfSym::Etext1->Section = LastRO->LastSec;
922     if (ElfSym::Etext2)
923       ElfSym::Etext2->Section = LastRO->LastSec;
924   }
925 
926   // _edata points to the end of the last non SHT_NOBITS section.
927   if (LastRW) {
928     size_t I = 0;
929     for (; I < OutputSections.size(); ++I)
930       if (OutputSections[I] == LastRW->FirstSec)
931         break;
932 
933     for (; I < OutputSections.size(); ++I) {
934       if (OutputSections[I]->Type != SHT_NOBITS)
935         continue;
936       break;
937     }
938     if (ElfSym::Edata1)
939       ElfSym::Edata1->Section = OutputSections[I - 1];
940     if (ElfSym::Edata2)
941       ElfSym::Edata2->Section = OutputSections[I - 1];
942   }
943 
944   if (ElfSym::Bss)
945     ElfSym::Bss->Section = findSection(".bss");
946 
947   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
948   // be equal to the _gp symbol's value.
949   if (ElfSym::MipsGp) {
950     // Find GP-relative section with the lowest address
951     // and use this address to calculate default _gp value.
952     for (OutputSection *OS : OutputSections) {
953       if (OS->Flags & SHF_MIPS_GPREL) {
954         ElfSym::MipsGp->Section = OS;
955         ElfSym::MipsGp->Value = 0x7ff0;
956         break;
957       }
958     }
959   }
960 }
961 
962 // We want to find how similar two ranks are.
963 // The more branches in getSectionRank that match, the more similar they are.
964 // Since each branch corresponds to a bit flag, we can just use
965 // countLeadingZeros.
966 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
967   return countLeadingZeros(A->SortRank ^ B->SortRank);
968 }
969 
970 static int getRankProximity(OutputSection *A, BaseCommand *B) {
971   if (auto *Sec = dyn_cast<OutputSection>(B))
972     if (Sec->Live)
973       return getRankProximityAux(A, Sec);
974   return -1;
975 }
976 
977 // When placing orphan sections, we want to place them after symbol assignments
978 // so that an orphan after
979 //   begin_foo = .;
980 //   foo : { *(foo) }
981 //   end_foo = .;
982 // doesn't break the intended meaning of the begin/end symbols.
983 // We don't want to go over sections since findOrphanPos is the
984 // one in charge of deciding the order of the sections.
985 // We don't want to go over changes to '.', since doing so in
986 //  rx_sec : { *(rx_sec) }
987 //  . = ALIGN(0x1000);
988 //  /* The RW PT_LOAD starts here*/
989 //  rw_sec : { *(rw_sec) }
990 // would mean that the RW PT_LOAD would become unaligned.
991 static bool shouldSkip(BaseCommand *Cmd) {
992   if (isa<OutputSection>(Cmd))
993     return false;
994   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
995     return Assign->Name != ".";
996   return true;
997 }
998 
999 // We want to place orphan sections so that they share as much
1000 // characteristics with their neighbors as possible. For example, if
1001 // both are rw, or both are tls.
1002 template <typename ELFT>
1003 static std::vector<BaseCommand *>::iterator
1004 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1005               std::vector<BaseCommand *>::iterator E) {
1006   OutputSection *Sec = cast<OutputSection>(*E);
1007 
1008   // Find the first element that has as close a rank as possible.
1009   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1010     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1011   });
1012   if (I == E)
1013     return E;
1014 
1015   // Consider all existing sections with the same proximity.
1016   int Proximity = getRankProximity(Sec, *I);
1017   for (; I != E; ++I) {
1018     auto *CurSec = dyn_cast<OutputSection>(*I);
1019     if (!CurSec || !CurSec->Live)
1020       continue;
1021     if (getRankProximity(Sec, CurSec) != Proximity ||
1022         Sec->SortRank < CurSec->SortRank)
1023       break;
1024   }
1025   auto J = std::find_if(llvm::make_reverse_iterator(I),
1026                         llvm::make_reverse_iterator(B), [](BaseCommand *Cmd) {
1027                           auto *OS = dyn_cast<OutputSection>(Cmd);
1028                           return OS && OS->Live;
1029                         });
1030   I = J.base();
1031 
1032   // As a special case, if the orphan section is the last section, put
1033   // it at the very end, past any other commands.
1034   // This matches bfd's behavior and is convenient when the linker script fully
1035   // specifies the start of the file, but doesn't care about the end (the non
1036   // alloc sections for example).
1037   auto NextSec = std::find_if(
1038       I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1039   if (NextSec == E)
1040     return E;
1041 
1042   while (I != E && shouldSkip(*I))
1043     ++I;
1044   return I;
1045 }
1046 
1047 template <class ELFT> void Writer<ELFT>::sortSections() {
1048   Script->adjustSectionsBeforeSorting();
1049 
1050   // Don't sort if using -r. It is not necessary and we want to preserve the
1051   // relative order for SHF_LINK_ORDER sections.
1052   if (Config->Relocatable)
1053     return;
1054 
1055   for (BaseCommand *Base : Script->SectionCommands)
1056     if (auto *Sec = dyn_cast<OutputSection>(Base))
1057       Sec->SortRank = getSectionRank(Sec);
1058 
1059   if (!Script->HasSectionsCommand) {
1060     // We know that all the OutputSections are contiguous in
1061     // this case.
1062     auto E = Script->SectionCommands.end();
1063     auto I = Script->SectionCommands.begin();
1064     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065     I = std::find_if(I, E, IsSection);
1066     E = std::find_if(llvm::make_reverse_iterator(E),
1067                      llvm::make_reverse_iterator(I), IsSection)
1068             .base();
1069     std::stable_sort(I, E, compareSections);
1070     return;
1071   }
1072 
1073   // Orphan sections are sections present in the input files which are
1074   // not explicitly placed into the output file by the linker script.
1075   //
1076   // The sections in the linker script are already in the correct
1077   // order. We have to figuere out where to insert the orphan
1078   // sections.
1079   //
1080   // The order of the sections in the script is arbitrary and may not agree with
1081   // compareSections. This means that we cannot easily define a strict weak
1082   // ordering. To see why, consider a comparison of a section in the script and
1083   // one not in the script. We have a two simple options:
1084   // * Make them equivalent (a is not less than b, and b is not less than a).
1085   //   The problem is then that equivalence has to be transitive and we can
1086   //   have sections a, b and c with only b in a script and a less than c
1087   //   which breaks this property.
1088   // * Use compareSectionsNonScript. Given that the script order doesn't have
1089   //   to match, we can end up with sections a, b, c, d where b and c are in the
1090   //   script and c is compareSectionsNonScript less than b. In which case d
1091   //   can be equivalent to c, a to b and d < a. As a concrete example:
1092   //   .a (rx) # not in script
1093   //   .b (rx) # in script
1094   //   .c (ro) # in script
1095   //   .d (ro) # not in script
1096   //
1097   // The way we define an order then is:
1098   // *  Sort only the orphan sections. They are in the end right now.
1099   // *  Move each orphan section to its preferred position. We try
1100   //    to put each section in the last position where it it can share
1101   //    a PT_LOAD.
1102   //
1103   // There is some ambiguity as to where exactly a new entry should be
1104   // inserted, because Commands contains not only output section
1105   // commands but also other types of commands such as symbol assignment
1106   // expressions. There's no correct answer here due to the lack of the
1107   // formal specification of the linker script. We use heuristics to
1108   // determine whether a new output command should be added before or
1109   // after another commands. For the details, look at shouldSkip
1110   // function.
1111 
1112   auto I = Script->SectionCommands.begin();
1113   auto E = Script->SectionCommands.end();
1114   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115     if (auto *Sec = dyn_cast<OutputSection>(Base))
1116       return Sec->Live && Sec->SectionIndex == INT_MAX;
1117     return false;
1118   });
1119 
1120   // Sort the orphan sections.
1121   std::stable_sort(NonScriptI, E, compareSections);
1122 
1123   // As a horrible special case, skip the first . assignment if it is before any
1124   // section. We do this because it is common to set a load address by starting
1125   // the script with ". = 0xabcd" and the expectation is that every section is
1126   // after that.
1127   auto FirstSectionOrDotAssignment =
1128       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129   if (FirstSectionOrDotAssignment != E &&
1130       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131     ++FirstSectionOrDotAssignment;
1132   I = FirstSectionOrDotAssignment;
1133 
1134   while (NonScriptI != E) {
1135     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137 
1138     // As an optimization, find all sections with the same sort rank
1139     // and insert them with one rotate.
1140     unsigned Rank = Orphan->SortRank;
1141     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142       return cast<OutputSection>(Cmd)->SortRank != Rank;
1143     });
1144     std::rotate(Pos, NonScriptI, End);
1145     NonScriptI = End;
1146   }
1147 
1148   Script->adjustSectionsAfterSorting();
1149 }
1150 
1151 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1152                            std::function<void(SyntheticSection *)> Fn) {
1153   for (SyntheticSection *SS : Sections)
1154     if (SS && SS->getParent() && !SS->empty())
1155       Fn(SS);
1156 }
1157 
1158 // In order to allow users to manipulate linker-synthesized sections,
1159 // we had to add synthetic sections to the input section list early,
1160 // even before we make decisions whether they are needed. This allows
1161 // users to write scripts like this: ".mygot : { .got }".
1162 //
1163 // Doing it has an unintended side effects. If it turns out that we
1164 // don't need a .got (for example) at all because there's no
1165 // relocation that needs a .got, we don't want to emit .got.
1166 //
1167 // To deal with the above problem, this function is called after
1168 // scanRelocations is called to remove synthetic sections that turn
1169 // out to be empty.
1170 static void removeUnusedSyntheticSections() {
1171   // All input synthetic sections that can be empty are placed after
1172   // all regular ones. We iterate over them all and exit at first
1173   // non-synthetic.
1174   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1175     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1176     if (!SS)
1177       return;
1178     OutputSection *OS = SS->getParent();
1179     if (!SS->empty() || !OS)
1180       continue;
1181 
1182     std::vector<BaseCommand *>::iterator Empty = OS->SectionCommands.end();
1183     for (auto I = OS->SectionCommands.begin(), E = OS->SectionCommands.end();
1184          I != E; ++I) {
1185       BaseCommand *B = *I;
1186       if (auto *ISD = dyn_cast<InputSectionDescription>(B)) {
1187         llvm::erase_if(ISD->Sections,
1188                        [=](InputSection *IS) { return IS == SS; });
1189         if (ISD->Sections.empty())
1190           Empty = I;
1191       }
1192     }
1193     if (Empty != OS->SectionCommands.end())
1194       OS->SectionCommands.erase(Empty);
1195 
1196     // If there are no other sections in the output section, remove it from the
1197     // output.
1198     if (OS->SectionCommands.empty())
1199       OS->Live = false;
1200   }
1201 }
1202 
1203 // Returns true if a symbol can be replaced at load-time by a symbol
1204 // with the same name defined in other ELF executable or DSO.
1205 static bool computeIsPreemptible(const SymbolBody &B) {
1206   assert(!B.isLocal());
1207   // Only symbols that appear in dynsym can be preempted.
1208   if (!B.symbol()->includeInDynsym())
1209     return false;
1210 
1211   // Only default visibility symbols can be preempted.
1212   if (B.symbol()->Visibility != STV_DEFAULT)
1213     return false;
1214 
1215   // At this point copy relocations have not been created yet, so any
1216   // symbol that is not defined locally is preemptible.
1217   if (!B.isInCurrentDSO())
1218     return true;
1219 
1220   // If we have a dynamic list it specifies which local symbols are preemptible.
1221   if (Config->HasDynamicList)
1222     return false;
1223 
1224   if (!Config->Shared)
1225     return false;
1226 
1227   // -Bsymbolic means that definitions are not preempted.
1228   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1229     return false;
1230   return true;
1231 }
1232 
1233 // Create output section objects and add them to OutputSections.
1234 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1235   Out::DebugInfo = findSection(".debug_info");
1236   Out::PreinitArray = findSection(".preinit_array");
1237   Out::InitArray = findSection(".init_array");
1238   Out::FiniArray = findSection(".fini_array");
1239 
1240   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1241   // symbols for sections, so that the runtime can get the start and end
1242   // addresses of each section by section name. Add such symbols.
1243   if (!Config->Relocatable) {
1244     addStartEndSymbols();
1245     for (BaseCommand *Base : Script->SectionCommands)
1246       if (auto *Sec = dyn_cast<OutputSection>(Base))
1247         addStartStopSymbols(Sec);
1248   }
1249 
1250   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1251   // It should be okay as no one seems to care about the type.
1252   // Even the author of gold doesn't remember why gold behaves that way.
1253   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1254   if (InX::DynSymTab)
1255     addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1256 
1257   // Define __rel[a]_iplt_{start,end} symbols if needed.
1258   addRelIpltSymbols();
1259 
1260   // This responsible for splitting up .eh_frame section into
1261   // pieces. The relocation scan uses those pieces, so this has to be
1262   // earlier.
1263   applySynthetic({In<ELFT>::EhFrame},
1264                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1265 
1266   for (Symbol *S : Symtab->getSymbols())
1267     S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1268 
1269   // Scan relocations. This must be done after every symbol is declared so that
1270   // we can correctly decide if a dynamic relocation is needed.
1271   if (!Config->Relocatable)
1272     forEachRelSec(scanRelocations<ELFT>);
1273 
1274   if (InX::Plt && !InX::Plt->empty())
1275     InX::Plt->addSymbols();
1276   if (InX::Iplt && !InX::Iplt->empty())
1277     InX::Iplt->addSymbols();
1278 
1279   // Now that we have defined all possible global symbols including linker-
1280   // synthesized ones. Visit all symbols to give the finishing touches.
1281   for (Symbol *S : Symtab->getSymbols()) {
1282     SymbolBody *Body = S->body();
1283 
1284     if (!includeInSymtab(*Body))
1285       continue;
1286     if (InX::SymTab)
1287       InX::SymTab->addSymbol(Body);
1288 
1289     if (InX::DynSymTab && S->includeInDynsym()) {
1290       InX::DynSymTab->addSymbol(Body);
1291       if (auto *SS = dyn_cast<SharedSymbol>(Body))
1292         if (cast<SharedFile<ELFT>>(S->File)->isNeeded())
1293           In<ELFT>::VerNeed->addSymbol(SS);
1294     }
1295   }
1296 
1297   // Do not proceed if there was an undefined symbol.
1298   if (ErrorCount)
1299     return;
1300 
1301   addPredefinedSections();
1302   removeUnusedSyntheticSections();
1303 
1304   sortSections();
1305   Script->removeEmptyCommands();
1306 
1307   // Now that we have the final list, create a list of all the
1308   // OutputSections for convenience.
1309   for (BaseCommand *Base : Script->SectionCommands)
1310     if (auto *Sec = dyn_cast<OutputSection>(Base))
1311       OutputSections.push_back(Sec);
1312 
1313   // Prefer command line supplied address over other constraints.
1314   for (OutputSection *Sec : OutputSections) {
1315     auto I = Config->SectionStartMap.find(Sec->Name);
1316     if (I != Config->SectionStartMap.end())
1317       Sec->AddrExpr = [=] { return I->second; };
1318   }
1319 
1320   // This is a bit of a hack. A value of 0 means undef, so we set it
1321   // to 1 t make __ehdr_start defined. The section number is not
1322   // particularly relevant.
1323   Out::ElfHeader->SectionIndex = 1;
1324 
1325   unsigned I = 1;
1326   for (OutputSection *Sec : OutputSections) {
1327     Sec->SectionIndex = I++;
1328     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1329   }
1330 
1331   // Binary and relocatable output does not have PHDRS.
1332   // The headers have to be created before finalize as that can influence the
1333   // image base and the dynamic section on mips includes the image base.
1334   if (!Config->Relocatable && !Config->OFormatBinary) {
1335     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1336     addPtArmExid(Phdrs);
1337     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1338   }
1339 
1340   // Some symbols are defined in term of program headers. Now that we
1341   // have the headers, we can find out which sections they point to.
1342   setReservedSymbolSections();
1343 
1344   // Dynamic section must be the last one in this list and dynamic
1345   // symbol table section (DynSymTab) must be the first one.
1346   applySynthetic({InX::DynSymTab,    InX::Bss,
1347                   InX::BssRelRo,     InX::GnuHashTab,
1348                   InX::HashTab,      InX::SymTab,
1349                   InX::ShStrTab,     InX::StrTab,
1350                   In<ELFT>::VerDef,  InX::DynStrTab,
1351                   InX::Got,          InX::MipsGot,
1352                   InX::IgotPlt,      InX::GotPlt,
1353                   In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1354                   In<ELFT>::RelaPlt, InX::Plt,
1355                   InX::Iplt,         In<ELFT>::EhFrameHdr,
1356                   In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1357                   InX::Dynamic},
1358                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1359 
1360   if (!Script->HasSectionsCommand && !Config->Relocatable)
1361     fixSectionAlignments();
1362 
1363   // Some architectures use small displacements for jump instructions.
1364   // It is linker's responsibility to create thunks containing long
1365   // jump instructions if jump targets are too far. Create thunks.
1366   if (Target->NeedsThunks) {
1367     // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1368     // these
1369     // do not require address information. To support range extension Thunks
1370     // we need to assign addresses so that we can tell if jump instructions
1371     // are out of range. This will need to turn into a loop that converges
1372     // when no more Thunks are added
1373     ThunkCreator TC;
1374     Script->assignAddresses();
1375     if (TC.createThunks(OutputSections)) {
1376       applySynthetic({InX::MipsGot},
1377                      [](SyntheticSection *SS) { SS->updateAllocSize(); });
1378       if (TC.createThunks(OutputSections))
1379         fatal("All non-range thunks should be created in first call");
1380     }
1381   }
1382 
1383   // Fill other section headers. The dynamic table is finalized
1384   // at the end because some tags like RELSZ depend on result
1385   // of finalizing other sections.
1386   for (OutputSection *Sec : OutputSections)
1387     Sec->finalize<ELFT>();
1388 
1389   // createThunks may have added local symbols to the static symbol table
1390   applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1391                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1392 }
1393 
1394 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1395   // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1396   // We have the terminater synthetic section class. Add that at the end.
1397   OutputSection *Cmd = findSection(".ARM.exidx");
1398   if (!Cmd || !Cmd->Live || Config->Relocatable)
1399     return;
1400 
1401   auto *Sentinel = make<ARMExidxSentinelSection>();
1402   Cmd->addSection(Sentinel);
1403 }
1404 
1405 // The linker is expected to define SECNAME_start and SECNAME_end
1406 // symbols for a few sections. This function defines them.
1407 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1408   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1409     // These symbols resolve to the image base if the section does not exist.
1410     // A special value -1 indicates end of the section.
1411     if (OS) {
1412       addOptionalRegular<ELFT>(Start, OS, 0);
1413       addOptionalRegular<ELFT>(End, OS, -1);
1414     } else {
1415       if (Config->Pic)
1416         OS = Out::ElfHeader;
1417       addOptionalRegular<ELFT>(Start, OS, 0);
1418       addOptionalRegular<ELFT>(End, OS, 0);
1419     }
1420   };
1421 
1422   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1423   Define("__init_array_start", "__init_array_end", Out::InitArray);
1424   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1425 
1426   if (OutputSection *Sec = findSection(".ARM.exidx"))
1427     Define("__exidx_start", "__exidx_end", Sec);
1428 }
1429 
1430 // If a section name is valid as a C identifier (which is rare because of
1431 // the leading '.'), linkers are expected to define __start_<secname> and
1432 // __stop_<secname> symbols. They are at beginning and end of the section,
1433 // respectively. This is not requested by the ELF standard, but GNU ld and
1434 // gold provide the feature, and used by many programs.
1435 template <class ELFT>
1436 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1437   StringRef S = Sec->Name;
1438   if (!isValidCIdentifier(S))
1439     return;
1440   addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1441   addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1442 }
1443 
1444 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1445   for (BaseCommand *Base : Script->SectionCommands)
1446     if (auto *Sec = dyn_cast<OutputSection>(Base))
1447       if (Sec->Name == Name)
1448         return Sec;
1449   return nullptr;
1450 }
1451 
1452 static bool needsPtLoad(OutputSection *Sec) {
1453   if (!(Sec->Flags & SHF_ALLOC))
1454     return false;
1455 
1456   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1457   // responsible for allocating space for them, not the PT_LOAD that
1458   // contains the TLS initialization image.
1459   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1460     return false;
1461   return true;
1462 }
1463 
1464 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1465 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1466 // RW. This means that there is no alignment in the RO to RX transition and we
1467 // cannot create a PT_LOAD there.
1468 static uint64_t computeFlags(uint64_t Flags) {
1469   if (Config->Omagic)
1470     return PF_R | PF_W | PF_X;
1471   if (Config->SingleRoRx && !(Flags & PF_W))
1472     return Flags | PF_X;
1473   return Flags;
1474 }
1475 
1476 // Decide which program headers to create and which sections to include in each
1477 // one.
1478 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1479   std::vector<PhdrEntry *> Ret;
1480   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1481     Ret.push_back(make<PhdrEntry>(Type, Flags));
1482     return Ret.back();
1483   };
1484 
1485   // The first phdr entry is PT_PHDR which describes the program header itself.
1486   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1487 
1488   // PT_INTERP must be the second entry if exists.
1489   if (OutputSection *Cmd = findSection(".interp"))
1490     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1491 
1492   // Add the first PT_LOAD segment for regular output sections.
1493   uint64_t Flags = computeFlags(PF_R);
1494   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1495 
1496   // Add the headers. We will remove them if they don't fit.
1497   Load->add(Out::ElfHeader);
1498   Load->add(Out::ProgramHeaders);
1499 
1500   for (OutputSection *Sec : OutputSections) {
1501     if (!(Sec->Flags & SHF_ALLOC))
1502       break;
1503     if (!needsPtLoad(Sec))
1504       continue;
1505 
1506     // Segments are contiguous memory regions that has the same attributes
1507     // (e.g. executable or writable). There is one phdr for each segment.
1508     // Therefore, we need to create a new phdr when the next section has
1509     // different flags or is loaded at a discontiguous address using AT linker
1510     // script command.
1511     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1512     if (Sec->LMAExpr || Flags != NewFlags) {
1513       Load = AddHdr(PT_LOAD, NewFlags);
1514       Flags = NewFlags;
1515     }
1516 
1517     Load->add(Sec);
1518   }
1519 
1520   // Add a TLS segment if any.
1521   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1522   for (OutputSection *Sec : OutputSections)
1523     if (Sec->Flags & SHF_TLS)
1524       TlsHdr->add(Sec);
1525   if (TlsHdr->FirstSec)
1526     Ret.push_back(TlsHdr);
1527 
1528   // Add an entry for .dynamic.
1529   if (InX::DynSymTab)
1530     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1531         ->add(InX::Dynamic->getParent());
1532 
1533   // PT_GNU_RELRO includes all sections that should be marked as
1534   // read-only by dynamic linker after proccessing relocations.
1535   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1536   for (OutputSection *Sec : OutputSections)
1537     if (needsPtLoad(Sec) && isRelroSection(Sec))
1538       RelRo->add(Sec);
1539   if (RelRo->FirstSec)
1540     Ret.push_back(RelRo);
1541 
1542   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1543   if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1544       In<ELFT>::EhFrame->getParent() && In<ELFT>::EhFrameHdr->getParent())
1545     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->getParent()->getPhdrFlags())
1546         ->add(In<ELFT>::EhFrameHdr->getParent());
1547 
1548   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1549   // the dynamic linker fill the segment with random data.
1550   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1551     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1552 
1553   // PT_GNU_STACK is a special section to tell the loader to make the
1554   // pages for the stack non-executable. If you really want an executable
1555   // stack, you can pass -z execstack, but that's not recommended for
1556   // security reasons.
1557   unsigned Perm;
1558   if (Config->ZExecstack)
1559     Perm = PF_R | PF_W | PF_X;
1560   else
1561     Perm = PF_R | PF_W;
1562   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1563 
1564   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1565   // is expected to perform W^X violations, such as calling mprotect(2) or
1566   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1567   // OpenBSD.
1568   if (Config->ZWxneeded)
1569     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1570 
1571   // Create one PT_NOTE per a group of contiguous .note sections.
1572   PhdrEntry *Note = nullptr;
1573   for (OutputSection *Sec : OutputSections) {
1574     if (Sec->Type == SHT_NOTE) {
1575       if (!Note || Sec->LMAExpr)
1576         Note = AddHdr(PT_NOTE, PF_R);
1577       Note->add(Sec);
1578     } else {
1579       Note = nullptr;
1580     }
1581   }
1582   return Ret;
1583 }
1584 
1585 template <class ELFT>
1586 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
1587   if (Config->EMachine != EM_ARM)
1588     return;
1589   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
1590     return Cmd->Type == SHT_ARM_EXIDX;
1591   });
1592   if (I == OutputSections.end())
1593     return;
1594 
1595   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1596   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
1597   ARMExidx->add(*I);
1598   Phdrs.push_back(ARMExidx);
1599 }
1600 
1601 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1602 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1603 // linker can set the permissions.
1604 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1605   auto PageAlign = [](OutputSection *Cmd) {
1606     if (Cmd && !Cmd->AddrExpr)
1607       Cmd->AddrExpr = [=] {
1608         return alignTo(Script->getDot(), Config->MaxPageSize);
1609       };
1610   };
1611 
1612   for (const PhdrEntry *P : Phdrs)
1613     if (P->p_type == PT_LOAD && P->FirstSec)
1614       PageAlign(P->FirstSec);
1615 
1616   for (const PhdrEntry *P : Phdrs) {
1617     if (P->p_type != PT_GNU_RELRO)
1618       continue;
1619     if (P->FirstSec)
1620       PageAlign(P->FirstSec);
1621     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1622     // have to align it to a page.
1623     auto End = OutputSections.end();
1624     auto I = std::find(OutputSections.begin(), End, P->LastSec);
1625     if (I == End || (I + 1) == End)
1626       continue;
1627     OutputSection *Cmd = (*(I + 1));
1628     if (needsPtLoad(Cmd))
1629       PageAlign(Cmd);
1630   }
1631 }
1632 
1633 // Adjusts the file alignment for a given output section and returns
1634 // its new file offset. The file offset must be the same with its
1635 // virtual address (modulo the page size) so that the loader can load
1636 // executables without any address adjustment.
1637 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) {
1638   // If the section is not in a PT_LOAD, we just have to align it.
1639   if (!Cmd->PtLoad)
1640     return alignTo(Off, Cmd->Alignment);
1641 
1642   OutputSection *First = Cmd->PtLoad->FirstSec;
1643   // The first section in a PT_LOAD has to have congruent offset and address
1644   // module the page size.
1645   if (Cmd == First)
1646     return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize),
1647                    Cmd->Addr);
1648 
1649   // If two sections share the same PT_LOAD the file offset is calculated
1650   // using this formula: Off2 = Off1 + (VA2 - VA1).
1651   return First->Offset + Cmd->Addr - First->Addr;
1652 }
1653 
1654 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) {
1655   if (Cmd->Type == SHT_NOBITS) {
1656     Cmd->Offset = Off;
1657     return Off;
1658   }
1659 
1660   Off = getFileAlignment(Off, Cmd);
1661   Cmd->Offset = Off;
1662   return Off + Cmd->Size;
1663 }
1664 
1665 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1666   uint64_t Off = 0;
1667   for (OutputSection *Sec : OutputSections)
1668     if (Sec->Flags & SHF_ALLOC)
1669       Off = setOffset(Sec, Off);
1670   FileSize = alignTo(Off, Config->Wordsize);
1671 }
1672 
1673 // Assign file offsets to output sections.
1674 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1675   uint64_t Off = 0;
1676   Off = setOffset(Out::ElfHeader, Off);
1677   Off = setOffset(Out::ProgramHeaders, Off);
1678 
1679   PhdrEntry *LastRX = nullptr;
1680   for (PhdrEntry *P : Phdrs)
1681     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
1682       LastRX = P;
1683 
1684   for (OutputSection *Sec : OutputSections) {
1685     Off = setOffset(Sec, Off);
1686     if (Script->HasSectionsCommand)
1687       continue;
1688     // If this is a last section of the last executable segment and that
1689     // segment is the last loadable segment, align the offset of the
1690     // following section to avoid loading non-segments parts of the file.
1691     if (LastRX && LastRX->LastSec == Sec)
1692       Off = alignTo(Off, Target->PageSize);
1693   }
1694 
1695   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1696   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1697 }
1698 
1699 // Finalize the program headers. We call this function after we assign
1700 // file offsets and VAs to all sections.
1701 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1702   for (PhdrEntry *P : Phdrs) {
1703     OutputSection *First = P->FirstSec;
1704     OutputSection *Last = P->LastSec;
1705     if (First) {
1706       P->p_filesz = Last->Offset - First->Offset;
1707       if (Last->Type != SHT_NOBITS)
1708         P->p_filesz += Last->Size;
1709       P->p_memsz = Last->Addr + Last->Size - First->Addr;
1710       P->p_offset = First->Offset;
1711       P->p_vaddr = First->Addr;
1712       if (!P->HasLMA)
1713         P->p_paddr = First->getLMA();
1714     }
1715     if (P->p_type == PT_LOAD)
1716       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
1717     else if (P->p_type == PT_GNU_RELRO) {
1718       P->p_align = 1;
1719       // The glibc dynamic loader rounds the size down, so we need to round up
1720       // to protect the last page. This is a no-op on FreeBSD which always
1721       // rounds up.
1722       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
1723     }
1724 
1725     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1726     // so round up the size to make sure the offsets are correct.
1727     if (P->p_type == PT_TLS) {
1728       Out::TlsPhdr = P;
1729       if (P->p_memsz)
1730         P->p_memsz = alignTo(P->p_memsz, P->p_align);
1731     }
1732   }
1733 }
1734 
1735 // The entry point address is chosen in the following ways.
1736 //
1737 // 1. the '-e' entry command-line option;
1738 // 2. the ENTRY(symbol) command in a linker control script;
1739 // 3. the value of the symbol start, if present;
1740 // 4. the address of the first byte of the .text section, if present;
1741 // 5. the address 0.
1742 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1743   // Case 1, 2 or 3. As a special case, if the symbol is actually
1744   // a number, we'll use that number as an address.
1745   if (SymbolBody *B = Symtab->find(Config->Entry))
1746     return B->getVA();
1747   uint64_t Addr;
1748   if (to_integer(Config->Entry, Addr))
1749     return Addr;
1750 
1751   // Case 4
1752   if (OutputSection *Sec = findSection(".text")) {
1753     if (Config->WarnMissingEntry)
1754       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1755            utohexstr(Sec->Addr));
1756     return Sec->Addr;
1757   }
1758 
1759   // Case 5
1760   if (Config->WarnMissingEntry)
1761     warn("cannot find entry symbol " + Config->Entry +
1762          "; not setting start address");
1763   return 0;
1764 }
1765 
1766 static uint16_t getELFType() {
1767   if (Config->Pic)
1768     return ET_DYN;
1769   if (Config->Relocatable)
1770     return ET_REL;
1771   return ET_EXEC;
1772 }
1773 
1774 template <class ELFT> void Writer<ELFT>::writeHeader() {
1775   uint8_t *Buf = Buffer->getBufferStart();
1776   memcpy(Buf, "\177ELF", 4);
1777 
1778   // Write the ELF header.
1779   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1780   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1781   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1782   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1783   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1784   EHdr->e_type = getELFType();
1785   EHdr->e_machine = Config->EMachine;
1786   EHdr->e_version = EV_CURRENT;
1787   EHdr->e_entry = getEntryAddr();
1788   EHdr->e_shoff = SectionHeaderOff;
1789   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1790   EHdr->e_phnum = Phdrs.size();
1791   EHdr->e_shentsize = sizeof(Elf_Shdr);
1792   EHdr->e_shnum = OutputSections.size() + 1;
1793   EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
1794 
1795   if (Config->EMachine == EM_ARM)
1796     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1797     // but we don't have any firm guarantees of conformance. Linux AArch64
1798     // kernels (as of 2016) require an EABI version to be set.
1799     EHdr->e_flags = EF_ARM_EABI_VER5;
1800   else if (Config->EMachine == EM_MIPS)
1801     EHdr->e_flags = Config->MipsEFlags;
1802 
1803   if (!Config->Relocatable) {
1804     EHdr->e_phoff = sizeof(Elf_Ehdr);
1805     EHdr->e_phentsize = sizeof(Elf_Phdr);
1806   }
1807 
1808   // Write the program header table.
1809   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1810   for (PhdrEntry *P : Phdrs) {
1811     HBuf->p_type = P->p_type;
1812     HBuf->p_flags = P->p_flags;
1813     HBuf->p_offset = P->p_offset;
1814     HBuf->p_vaddr = P->p_vaddr;
1815     HBuf->p_paddr = P->p_paddr;
1816     HBuf->p_filesz = P->p_filesz;
1817     HBuf->p_memsz = P->p_memsz;
1818     HBuf->p_align = P->p_align;
1819     ++HBuf;
1820   }
1821 
1822   // Write the section header table. Note that the first table entry is null.
1823   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1824   for (OutputSection *Sec : OutputSections)
1825     Sec->writeHeaderTo<ELFT>(++SHdrs);
1826 }
1827 
1828 // Open a result file.
1829 template <class ELFT> void Writer<ELFT>::openFile() {
1830   if (!Config->Is64 && FileSize > UINT32_MAX) {
1831     error("output file too large: " + Twine(FileSize) + " bytes");
1832     return;
1833   }
1834 
1835   unlinkAsync(Config->OutputFile);
1836   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1837       FileOutputBuffer::create(Config->OutputFile, FileSize,
1838                                FileOutputBuffer::F_executable);
1839 
1840   if (auto EC = BufferOrErr.getError())
1841     error("failed to open " + Config->OutputFile + ": " + EC.message());
1842   else
1843     Buffer = std::move(*BufferOrErr);
1844 }
1845 
1846 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1847   uint8_t *Buf = Buffer->getBufferStart();
1848   for (OutputSection *Sec : OutputSections)
1849     if (Sec->Flags & SHF_ALLOC)
1850       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1851 }
1852 
1853 static void fillTrap(uint8_t *I, uint8_t *End) {
1854   for (; I + 4 <= End; I += 4)
1855     memcpy(I, &Target->TrapInstr, 4);
1856 }
1857 
1858 // Fill the last page of executable segments with trap instructions
1859 // instead of leaving them as zero. Even though it is not required by any
1860 // standard, it is in general a good thing to do for security reasons.
1861 //
1862 // We'll leave other pages in segments as-is because the rest will be
1863 // overwritten by output sections.
1864 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
1865   if (Script->HasSectionsCommand)
1866     return;
1867 
1868   // Fill the last page.
1869   uint8_t *Buf = Buffer->getBufferStart();
1870   for (PhdrEntry *P : Phdrs)
1871     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
1872       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
1873                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
1874 
1875   // Round up the file size of the last segment to the page boundary iff it is
1876   // an executable segment to ensure that other other tools don't accidentally
1877   // trim the instruction padding (e.g. when stripping the file).
1878   PhdrEntry *LastRX = nullptr;
1879   for (PhdrEntry *P : Phdrs) {
1880     if (P->p_type != PT_LOAD)
1881       continue;
1882     if (P->p_flags & PF_X)
1883       LastRX = P;
1884     else
1885       LastRX = nullptr;
1886   }
1887   if (LastRX)
1888     LastRX->p_memsz = LastRX->p_filesz =
1889         alignTo(LastRX->p_filesz, Target->PageSize);
1890 }
1891 
1892 // Write section contents to a mmap'ed file.
1893 template <class ELFT> void Writer<ELFT>::writeSections() {
1894   uint8_t *Buf = Buffer->getBufferStart();
1895 
1896   // PPC64 needs to process relocations in the .opd section
1897   // before processing relocations in code-containing sections.
1898   if (auto *OpdCmd = findSection(".opd")) {
1899     Out::Opd = OpdCmd;
1900     Out::OpdBuf = Buf + Out::Opd->Offset;
1901     OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1902   }
1903 
1904   OutputSection *EhFrameHdr =
1905       (In<ELFT>::EhFrameHdr && !In<ELFT>::EhFrameHdr->empty())
1906           ? In<ELFT>::EhFrameHdr->getParent()
1907           : nullptr;
1908 
1909   // In -r or -emit-relocs mode, write the relocation sections first as in
1910   // ELf_Rel targets we might find out that we need to modify the relocated
1911   // section while doing it.
1912   for (OutputSection *Sec : OutputSections)
1913     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1914       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1915 
1916   for (OutputSection *Sec : OutputSections)
1917     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1918         Sec->Type != SHT_RELA)
1919       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1920 
1921   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1922   // it should be written after .eh_frame is written.
1923   if (EhFrameHdr)
1924     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1925 }
1926 
1927 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1928   if (!InX::BuildId || !InX::BuildId->getParent())
1929     return;
1930 
1931   // Compute a hash of all sections of the output file.
1932   uint8_t *Start = Buffer->getBufferStart();
1933   uint8_t *End = Start + FileSize;
1934   InX::BuildId->writeBuildId({Start, End});
1935 }
1936 
1937 template void elf::writeResult<ELF32LE>();
1938 template void elf::writeResult<ELF32BE>();
1939 template void elf::writeResult<ELF64LE>();
1940 template void elf::writeResult<ELF64BE>();
1941