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