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