xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 07f6efdd)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Writer.h"
11 #include "Config.h"
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
14 #include "MapFile.h"
15 #include "Memory.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "Strings.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "Threads.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <climits>
28 
29 using namespace llvm;
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
34 
35 using namespace lld;
36 using namespace lld::elf;
37 
38 namespace {
39 // The writer writes a SymbolTable result to a file.
40 template <class ELFT> class Writer {
41 public:
42   typedef typename ELFT::Shdr Elf_Shdr;
43   typedef typename ELFT::Ehdr Elf_Ehdr;
44   typedef typename ELFT::Phdr Elf_Phdr;
45 
46   void run();
47 
48 private:
49   void clearOutputSections();
50   void createSyntheticSections();
51   void copyLocalSymbols();
52   void addSectionSymbols();
53   void addReservedSymbols();
54   void createSections();
55   void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
56   void sortSections();
57   void finalizeSections();
58   void addPredefinedSections();
59 
60   std::vector<PhdrEntry> createPhdrs();
61   void removeEmptyPTLoad();
62   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
63   void assignFileOffsets();
64   void assignFileOffsetsBinary();
65   void setPhdrs();
66   void fixSectionAlignments();
67   void fixPredefinedSymbols();
68   void openFile();
69   void writeHeader();
70   void writeSections();
71   void writeSectionsBinary();
72   void writeBuildId();
73 
74   std::unique_ptr<FileOutputBuffer> Buffer;
75 
76   OutputSectionFactory Factory;
77 
78   void addRelIpltSymbols();
79   void addStartEndSymbols();
80   void addStartStopSymbols(OutputSection *Sec);
81   uint64_t getEntryAddr();
82   OutputSection *findSectionInScript(StringRef Name);
83   OutputSectionCommand *findSectionCommand(StringRef Name);
84 
85   std::vector<PhdrEntry> Phdrs;
86 
87   uint64_t FileSize;
88   uint64_t SectionHeaderOff;
89 
90   bool HasGotBaseSym = false;
91 };
92 } // anonymous namespace
93 
94 StringRef elf::getOutputSectionName(StringRef Name) {
95   // ".zdebug_" is a prefix for ZLIB-compressed sections.
96   // Because we decompressed input sections, we want to remove 'z'.
97   if (Name.startswith(".zdebug_"))
98     return Saver.save("." + Name.substr(2));
99 
100   if (Config->Relocatable)
101     return Name;
102 
103   for (StringRef V :
104        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
105         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
106         ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
107     StringRef Prefix = V.drop_back();
108     if (Name.startswith(V) || Name == Prefix)
109       return Prefix;
110   }
111 
112   // CommonSection is identified as "COMMON" in linker scripts.
113   // By default, it should go to .bss section.
114   if (Name == "COMMON")
115     return ".bss";
116 
117   return Name;
118 }
119 
120 template <class ELFT> static bool needsInterpSection() {
121   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
122          !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
123 }
124 
125 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
126 
127 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
128   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
129     if (P.p_type != PT_LOAD)
130       return false;
131     if (!P.First)
132       return true;
133     uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
134     return Size == 0;
135   });
136   Phdrs.erase(I, Phdrs.end());
137 }
138 
139 template <class ELFT> static void combineEhFrameSections() {
140   for (InputSectionBase *&S : InputSections) {
141     EhInputSection *ES = dyn_cast<EhInputSection>(S);
142     if (!ES || !ES->Live)
143       continue;
144 
145     In<ELFT>::EhFrame->addSection(ES);
146     S = nullptr;
147   }
148 
149   std::vector<InputSectionBase *> &V = InputSections;
150   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
151 }
152 
153 template <class ELFT> void Writer<ELFT>::clearOutputSections() {
154   // Clear the OutputSections to make sure it is not used anymore. Any
155   // code from this point on should be using the linker script
156   // commands.
157   for (OutputSection *Sec : OutputSections)
158     Sec->Sections.clear();
159   OutputSections.clear();
160 }
161 
162 // The main function of the writer.
163 template <class ELFT> void Writer<ELFT>::run() {
164   // Create linker-synthesized sections such as .got or .plt.
165   // Such sections are of type input section.
166   createSyntheticSections();
167 
168   if (!Config->Relocatable)
169     combineEhFrameSections<ELFT>();
170 
171   // We need to create some reserved symbols such as _end. Create them.
172   if (!Config->Relocatable)
173     addReservedSymbols();
174 
175   // Create output sections.
176   if (Script->Opt.HasSections) {
177     // If linker script contains SECTIONS commands, let it create sections.
178     Script->processCommands(Factory);
179 
180     // Linker scripts may have left some input sections unassigned.
181     // Assign such sections using the default rule.
182     Script->addOrphanSections(Factory);
183   } else {
184     // If linker script does not contain SECTIONS commands, create
185     // output sections by default rules. We still need to give the
186     // linker script a chance to run, because it might contain
187     // non-SECTIONS commands such as ASSERT.
188     Script->processCommands(Factory);
189     createSections();
190   }
191   clearOutputSections();
192 
193   if (Config->Discard != DiscardPolicy::All)
194     copyLocalSymbols();
195 
196   if (Config->CopyRelocs)
197     addSectionSymbols();
198 
199   // Now that we have a complete set of output sections. This function
200   // completes section contents. For example, we need to add strings
201   // to the string table, and add entries to .got and .plt.
202   // finalizeSections does that.
203   finalizeSections();
204   if (ErrorCount)
205     return;
206 
207   if (!Script->Opt.HasSections && !Config->Relocatable)
208     fixSectionAlignments();
209 
210   // If -compressed-debug-sections is specified, we need to compress
211   // .debug_* sections. Do it right now because it changes the size of
212   // output sections.
213   parallelForEach(
214       OutputSectionCommands.begin(), OutputSectionCommands.end(),
215       [](OutputSectionCommand *Cmd) { Cmd->maybeCompress<ELFT>(); });
216 
217   Script->assignAddresses();
218   Script->allocateHeaders(Phdrs);
219 
220   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
221   // 0 sized region. This has to be done late since only after assignAddresses
222   // we know the size of the sections.
223   removeEmptyPTLoad();
224 
225   if (!Config->OFormatBinary)
226     assignFileOffsets();
227   else
228     assignFileOffsetsBinary();
229 
230   setPhdrs();
231 
232   if (Config->Relocatable) {
233     for (OutputSectionCommand *Cmd : OutputSectionCommands)
234       Cmd->Sec->Addr = 0;
235   } else {
236     fixPredefinedSymbols();
237   }
238 
239   // It does not make sense try to open the file if we have error already.
240   if (ErrorCount)
241     return;
242   // Write the result down to a file.
243   openFile();
244   if (ErrorCount)
245     return;
246 
247   if (!Config->OFormatBinary) {
248     writeHeader();
249     writeSections();
250   } else {
251     writeSectionsBinary();
252   }
253 
254   // Backfill .note.gnu.build-id section content. This is done at last
255   // because the content is usually a hash value of the entire output file.
256   writeBuildId();
257   if (ErrorCount)
258     return;
259 
260 
261   // Handle -Map option.
262   writeMapFile<ELFT>(OutputSectionCommands);
263   if (ErrorCount)
264     return;
265 
266   if (auto EC = Buffer->commit())
267     error("failed to write to the output file: " + EC.message());
268 
269   // Flush the output streams and exit immediately. A full shutdown
270   // is a good test that we are keeping track of all allocated memory,
271   // but actually freeing it is a waste of time in a regular linker run.
272   if (Config->ExitEarly)
273     exitLld(0);
274 }
275 
276 // Initialize Out members.
277 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
278   // Initialize all pointers with NULL. This is needed because
279   // you can call lld::elf::main more than once as a library.
280   memset(&Out::First, 0, sizeof(Out));
281 
282   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
283 
284   InX::DynStrTab = make<StringTableSection>(".dynstr", true);
285   InX::Dynamic = make<DynamicSection<ELFT>>();
286   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
287       Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
288   InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
289 
290   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
291   Out::ElfHeader->Size = sizeof(Elf_Ehdr);
292   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
293   Out::ProgramHeaders->updateAlignment(Config->Wordsize);
294 
295   if (needsInterpSection<ELFT>()) {
296     InX::Interp = createInterpSection();
297     Add(InX::Interp);
298   } else {
299     InX::Interp = nullptr;
300   }
301 
302   if (Config->Strip != StripPolicy::All) {
303     InX::StrTab = make<StringTableSection>(".strtab", false);
304     InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
305   }
306 
307   if (Config->BuildId != BuildIdKind::None) {
308     InX::BuildId = make<BuildIdSection>();
309     Add(InX::BuildId);
310   }
311 
312   InX::Common = createCommonSection<ELFT>();
313   if (InX::Common)
314     Add(InX::Common);
315 
316   InX::Bss = make<BssSection>(".bss");
317   Add(InX::Bss);
318   InX::BssRelRo = make<BssSection>(".bss.rel.ro");
319   Add(InX::BssRelRo);
320 
321   // Add MIPS-specific sections.
322   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
323                       Config->Pic || Config->ExportDynamic;
324   if (Config->EMachine == EM_MIPS) {
325     if (!Config->Shared && HasDynSymTab) {
326       InX::MipsRldMap = make<MipsRldMapSection>();
327       Add(InX::MipsRldMap);
328     }
329     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
330       Add(Sec);
331     if (auto *Sec = MipsOptionsSection<ELFT>::create())
332       Add(Sec);
333     if (auto *Sec = MipsReginfoSection<ELFT>::create())
334       Add(Sec);
335   }
336 
337   if (HasDynSymTab) {
338     InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
339     Add(InX::DynSymTab);
340 
341     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
342     Add(In<ELFT>::VerSym);
343 
344     if (!Config->VersionDefinitions.empty()) {
345       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
346       Add(In<ELFT>::VerDef);
347     }
348 
349     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
350     Add(In<ELFT>::VerNeed);
351 
352     if (Config->GnuHash) {
353       InX::GnuHashTab = make<GnuHashTableSection>();
354       Add(InX::GnuHashTab);
355     }
356 
357     if (Config->SysvHash) {
358       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
359       Add(In<ELFT>::HashTab);
360     }
361 
362     Add(InX::Dynamic);
363     Add(InX::DynStrTab);
364     Add(In<ELFT>::RelaDyn);
365   }
366 
367   // Add .got. MIPS' .got is so different from the other archs,
368   // it has its own class.
369   if (Config->EMachine == EM_MIPS) {
370     InX::MipsGot = make<MipsGotSection>();
371     Add(InX::MipsGot);
372   } else {
373     InX::Got = make<GotSection>();
374     Add(InX::Got);
375   }
376 
377   InX::GotPlt = make<GotPltSection>();
378   Add(InX::GotPlt);
379   InX::IgotPlt = make<IgotPltSection>();
380   Add(InX::IgotPlt);
381 
382   if (Config->GdbIndex) {
383     InX::GdbIndex = make<GdbIndexSection>();
384     Add(InX::GdbIndex);
385   }
386 
387   // We always need to add rel[a].plt to output if it has entries.
388   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
389   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
390       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
391   Add(In<ELFT>::RelaPlt);
392 
393   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
394   // that the IRelative relocations are processed last by the dynamic loader
395   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
396       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
397       false /*Sort*/);
398   Add(In<ELFT>::RelaIplt);
399 
400   InX::Plt = make<PltSection>(Target->PltHeaderSize);
401   Add(InX::Plt);
402   InX::Iplt = make<PltSection>(0);
403   Add(InX::Iplt);
404 
405   if (!Config->Relocatable) {
406     if (Config->EhFrameHdr) {
407       In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
408       Add(In<ELFT>::EhFrameHdr);
409     }
410     In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
411     Add(In<ELFT>::EhFrame);
412   }
413 
414   if (InX::SymTab)
415     Add(InX::SymTab);
416   Add(InX::ShStrTab);
417   if (InX::StrTab)
418     Add(InX::StrTab);
419 }
420 
421 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
422                                const SymbolBody &B) {
423   if (B.isFile() || B.isSection())
424     return false;
425 
426   // If sym references a section in a discarded group, don't keep it.
427   if (Sec == &InputSection::Discarded)
428     return false;
429 
430   if (Config->Discard == DiscardPolicy::None)
431     return true;
432 
433   // In ELF assembly .L symbols are normally discarded by the assembler.
434   // If the assembler fails to do so, the linker discards them if
435   // * --discard-locals is used.
436   // * The symbol is in a SHF_MERGE section, which is normally the reason for
437   //   the assembler keeping the .L symbol.
438   if (!SymName.startswith(".L") && !SymName.empty())
439     return true;
440 
441   if (Config->Discard == DiscardPolicy::Locals)
442     return false;
443 
444   return !Sec || !(Sec->Flags & SHF_MERGE);
445 }
446 
447 static bool includeInSymtab(const SymbolBody &B) {
448   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
449     return false;
450 
451   if (auto *D = dyn_cast<DefinedRegular>(&B)) {
452     // Always include absolute symbols.
453     SectionBase *Sec = D->Section;
454     if (!Sec)
455       return true;
456     if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
457       Sec = IS->Repl;
458       IS = cast<InputSectionBase>(Sec);
459       // Exclude symbols pointing to garbage-collected sections.
460       if (!IS->Live)
461         return false;
462     }
463     if (auto *S = dyn_cast<MergeInputSection>(Sec))
464       if (!S->getSectionPiece(D->Value)->Live)
465         return false;
466   }
467   return true;
468 }
469 
470 // Local symbols are not in the linker's symbol table. This function scans
471 // each object file's symbol table to copy local symbols to the output.
472 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
473   if (!InX::SymTab)
474     return;
475   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
476     for (SymbolBody *B : F->getLocalSymbols()) {
477       if (!B->IsLocal)
478         fatal(toString(F) +
479               ": broken object: getLocalSymbols returns a non-local symbol");
480       auto *DR = dyn_cast<DefinedRegular>(B);
481 
482       // No reason to keep local undefined symbol in symtab.
483       if (!DR)
484         continue;
485       if (!includeInSymtab(*B))
486         continue;
487 
488       SectionBase *Sec = DR->Section;
489       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
490         continue;
491       InX::SymTab->addSymbol(B);
492     }
493   }
494 }
495 
496 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
497   // Create one STT_SECTION symbol for each output section we might
498   // have a relocation with.
499   for (BaseCommand *Base : Script->Opt.Commands) {
500     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
501     if (!Cmd)
502       continue;
503     auto I = llvm::find_if(Cmd->Commands, [](BaseCommand *Base) {
504       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
505         return !ISD->Sections.empty();
506       return false;
507     });
508     if (I == Cmd->Commands.end())
509       continue;
510     InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
511     if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
512         IS->Type == SHT_RELA)
513       continue;
514 
515     auto *Sym =
516         make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
517                              /*Value=*/0, /*Size=*/0, IS, nullptr);
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 bool elf::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<OutputSectionCommand>(ACmd)->Sec;
740   const OutputSection *B = cast<OutputSectionCommand>(BCmd)->Sec;
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   Last = Sec;
751   if (!First)
752     First = Sec;
753   p_align = std::max(p_align, Sec->Alignment);
754   if (p_type == PT_LOAD)
755     Sec->FirstInPtLoad = First;
756 }
757 
758 template <class ELFT>
759 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
760                           uint8_t StOther = STV_HIDDEN,
761                           uint8_t Binding = STB_WEAK) {
762   // The linker generated symbols are added as STB_WEAK to allow user defined
763   // ones to override them.
764   return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
765                                      /*Size=*/0, Binding, Sec,
766                                      /*File=*/nullptr);
767 }
768 
769 template <class ELFT>
770 static DefinedRegular *
771 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
772                    uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
773   SymbolBody *S = Symtab<ELFT>::X->find(Name);
774   if (!S)
775     return nullptr;
776   if (S->isInCurrentDSO())
777     return nullptr;
778   return cast<DefinedRegular>(
779       addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
780 }
781 
782 // The beginning and the ending of .rel[a].plt section are marked
783 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
784 // executable. The runtime needs these symbols in order to resolve
785 // all IRELATIVE relocs on startup. For dynamic executables, we don't
786 // need these symbols, since IRELATIVE relocs are resolved through GOT
787 // and PLT. For details, see http://www.airs.com/blog/archives/403.
788 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
789   if (InX::DynSymTab)
790     return;
791   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
792   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
793 
794   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
795   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
796 }
797 
798 // The linker is expected to define some symbols depending on
799 // the linking result. This function defines such symbols.
800 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
801   if (Config->EMachine == EM_MIPS) {
802     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
803     // so that it points to an absolute address which by default is relative
804     // to GOT. Default offset is 0x7ff0.
805     // See "Global Data Symbols" in Chapter 6 in the following document:
806     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
807     ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
808 
809     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
810     // start of function and 'gp' pointer into GOT.
811     if (Symtab<ELFT>::X->find("_gp_disp"))
812       ElfSym::MipsGpDisp =
813           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
814 
815     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
816     // pointer. This symbol is used in the code generated by .cpload pseudo-op
817     // in case of using -mno-shared option.
818     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
819     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
820       ElfSym::MipsLocalGp =
821           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
822   }
823 
824   // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
825   // be at some offset from the base of the .got section, usually 0 or the end
826   // of the .got
827   InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
828                                           : cast<InputSection>(InX::Got);
829   ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
830       "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
831 
832   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
833   // static linking the linker is required to optimize away any references to
834   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
835   // to avoid the undefined symbol error.
836   if (!InX::DynSymTab)
837     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
838 
839   // __ehdr_start is the location of ELF file headers. Note that we define
840   // this symbol unconditionally even when using a linker script, which
841   // differs from the behavior implemented by GNU linker which only define
842   // this symbol if ELF headers are in the memory mapped segment.
843   // __executable_start is not documented, but the expectation of at
844   // least the android libc is that it points to the elf header too.
845   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
846   // each DSO. The address of the symbol doesn't matter as long as they are
847   // different in different DSOs, so we chose the start address of the DSO.
848   for (const char *Name :
849        {"__ehdr_start", "__executable_start", "__dso_handle"})
850     addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
851 
852   // If linker script do layout we do not need to create any standart symbols.
853   if (Script->Opt.HasSections)
854     return;
855 
856   auto Add = [](StringRef S) {
857     return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
858   };
859 
860   ElfSym::Bss = Add("__bss_start");
861   ElfSym::End1 = Add("end");
862   ElfSym::End2 = Add("_end");
863   ElfSym::Etext1 = Add("etext");
864   ElfSym::Etext2 = Add("_etext");
865   ElfSym::Edata1 = Add("edata");
866   ElfSym::Edata2 = Add("_edata");
867 }
868 
869 // Sort input sections by section name suffixes for
870 // __attribute__((init_priority(N))).
871 static void sortInitFini(OutputSectionCommand *Cmd) {
872   if (Cmd)
873     Cmd->sortInitFini();
874 }
875 
876 // Sort input sections by the special rule for .ctors and .dtors.
877 static void sortCtorsDtors(OutputSectionCommand *Cmd) {
878   if (Cmd)
879     Cmd->sortCtorsDtors();
880 }
881 
882 // Sort input sections using the list provided by --symbol-ordering-file.
883 template <class ELFT> static void sortBySymbolsOrder() {
884   if (Config->SymbolOrderingFile.empty())
885     return;
886 
887   // Build a map from symbols to their priorities. Symbols that didn't
888   // appear in the symbol ordering file have the lowest priority 0.
889   // All explicitly mentioned symbols have negative (higher) priorities.
890   DenseMap<StringRef, int> SymbolOrder;
891   int Priority = -Config->SymbolOrderingFile.size();
892   for (StringRef S : Config->SymbolOrderingFile)
893     SymbolOrder.insert({S, Priority++});
894 
895   // Build a map from sections to their priorities.
896   DenseMap<SectionBase *, int> SectionOrder;
897   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
898     for (SymbolBody *Body : File->getSymbols()) {
899       auto *D = dyn_cast<DefinedRegular>(Body);
900       if (!D || !D->Section)
901         continue;
902       int &Priority = SectionOrder[D->Section];
903       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
904     }
905   }
906 
907   // Sort sections by priority.
908   for (BaseCommand *Base : Script->Opt.Commands)
909     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
910       Cmd->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
911 }
912 
913 template <class ELFT>
914 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
915   for (InputSectionBase *IS : InputSections) {
916     if (!IS->Live)
917       continue;
918     // Scan all relocations. Each relocation goes through a series
919     // of tests to determine if it needs special treatment, such as
920     // creating GOT, PLT, copy relocations, etc.
921     // Note that relocations for non-alloc sections are directly
922     // processed by InputSection::relocateNonAlloc.
923     if (!(IS->Flags & SHF_ALLOC))
924       continue;
925     if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
926       Fn(*IS);
927   }
928 
929   if (!Config->Relocatable) {
930     for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
931       Fn(*ES);
932   }
933 }
934 
935 template <class ELFT> void Writer<ELFT>::createSections() {
936   for (InputSectionBase *IS : InputSections)
937     if (IS)
938       Factory.addInputSec(IS, getOutputSectionName(IS->Name));
939 
940   Script->fabricateDefaultCommands();
941   sortBySymbolsOrder<ELFT>();
942   sortInitFini(findSectionCommand(".init_array"));
943   sortInitFini(findSectionCommand(".fini_array"));
944   sortCtorsDtors(findSectionCommand(".ctors"));
945   sortCtorsDtors(findSectionCommand(".dtors"));
946 }
947 
948 // We want to find how similar two ranks are.
949 // The more branches in getSectionRank that match, the more similar they are.
950 // Since each branch corresponds to a bit flag, we can just use
951 // countLeadingZeros.
952 static int getRankProximity(OutputSection *A, OutputSection *B) {
953   return countLeadingZeros(A->SortRank ^ B->SortRank);
954 }
955 
956 static int getRankProximity(OutputSection *A, BaseCommand *B) {
957   if (auto *Cmd = dyn_cast<OutputSectionCommand>(B))
958     if (Cmd->Sec)
959       return getRankProximity(A, Cmd->Sec);
960   return -1;
961 }
962 
963 // When placing orphan sections, we want to place them after symbol assignments
964 // so that an orphan after
965 //   begin_foo = .;
966 //   foo : { *(foo) }
967 //   end_foo = .;
968 // doesn't break the intended meaning of the begin/end symbols.
969 // We don't want to go over sections since findOrphanPos is the
970 // one in charge of deciding the order of the sections.
971 // We don't want to go over changes to '.', since doing so in
972 //  rx_sec : { *(rx_sec) }
973 //  . = ALIGN(0x1000);
974 //  /* The RW PT_LOAD starts here*/
975 //  rw_sec : { *(rw_sec) }
976 // would mean that the RW PT_LOAD would become unaligned.
977 static bool shouldSkip(BaseCommand *Cmd) {
978   if (isa<OutputSectionCommand>(Cmd))
979     return false;
980   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
981     return Assign->Name != ".";
982   return true;
983 }
984 
985 // We want to place orphan sections so that they share as much
986 // characteristics with their neighbors as possible. For example, if
987 // both are rw, or both are tls.
988 template <typename ELFT>
989 static std::vector<BaseCommand *>::iterator
990 findOrphanPos(std::vector<BaseCommand *>::iterator B,
991               std::vector<BaseCommand *>::iterator E) {
992   OutputSection *Sec = cast<OutputSectionCommand>(*E)->Sec;
993 
994   // Find the first element that has as close a rank as possible.
995   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
996     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
997   });
998   if (I == E)
999     return E;
1000 
1001   // Consider all existing sections with the same proximity.
1002   int Proximity = getRankProximity(Sec, *I);
1003   for (; I != E; ++I) {
1004     auto *Cmd = dyn_cast<OutputSectionCommand>(*I);
1005     if (!Cmd || !Cmd->Sec)
1006       continue;
1007     if (getRankProximity(Sec, Cmd->Sec) != Proximity ||
1008         Sec->SortRank < Cmd->Sec->SortRank)
1009       break;
1010   }
1011   auto J = std::find_if(
1012       llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1013       [](BaseCommand *Cmd) { return isa<OutputSectionCommand>(Cmd); });
1014   I = J.base();
1015   while (I != E && shouldSkip(*I))
1016     ++I;
1017   return I;
1018 }
1019 
1020 template <class ELFT> void Writer<ELFT>::sortSections() {
1021   if (Script->Opt.HasSections)
1022     Script->adjustSectionsBeforeSorting();
1023 
1024   // Don't sort if using -r. It is not necessary and we want to preserve the
1025   // relative order for SHF_LINK_ORDER sections.
1026   if (Config->Relocatable)
1027     return;
1028 
1029   for (BaseCommand *Base : Script->Opt.Commands)
1030     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1031       if (OutputSection *Sec = Cmd->Sec)
1032         Sec->SortRank = getSectionRank(Sec);
1033 
1034   if (!Script->Opt.HasSections) {
1035     // We know that all the OutputSectionCommands are contiguous in
1036     // this case.
1037     auto E = Script->Opt.Commands.end();
1038     auto I = Script->Opt.Commands.begin();
1039     auto IsSection = [](BaseCommand *Base) {
1040       return isa<OutputSectionCommand>(Base);
1041     };
1042     I = std::find_if(I, E, IsSection);
1043     E = std::find_if(llvm::make_reverse_iterator(E),
1044                      llvm::make_reverse_iterator(I), IsSection)
1045             .base();
1046     std::stable_sort(I, E, compareSections);
1047     return;
1048   }
1049 
1050   // Orphan sections are sections present in the input files which are
1051   // not explicitly placed into the output file by the linker script.
1052   //
1053   // The sections in the linker script are already in the correct
1054   // order. We have to figuere out where to insert the orphan
1055   // sections.
1056   //
1057   // The order of the sections in the script is arbitrary and may not agree with
1058   // compareSections. This means that we cannot easily define a strict weak
1059   // ordering. To see why, consider a comparison of a section in the script and
1060   // one not in the script. We have a two simple options:
1061   // * Make them equivalent (a is not less than b, and b is not less than a).
1062   //   The problem is then that equivalence has to be transitive and we can
1063   //   have sections a, b and c with only b in a script and a less than c
1064   //   which breaks this property.
1065   // * Use compareSectionsNonScript. Given that the script order doesn't have
1066   //   to match, we can end up with sections a, b, c, d where b and c are in the
1067   //   script and c is compareSectionsNonScript less than b. In which case d
1068   //   can be equivalent to c, a to b and d < a. As a concrete example:
1069   //   .a (rx) # not in script
1070   //   .b (rx) # in script
1071   //   .c (ro) # in script
1072   //   .d (ro) # not in script
1073   //
1074   // The way we define an order then is:
1075   // *  Sort only the orphan sections. They are in the end right now.
1076   // *  Move each orphan section to its preferred position. We try
1077   //    to put each section in the last position where it it can share
1078   //    a PT_LOAD.
1079   //
1080   // There is some ambiguity as to where exactly a new entry should be
1081   // inserted, because Opt.Commands contains not only output section
1082   // commands but also other types of commands such as symbol assignment
1083   // expressions. There's no correct answer here due to the lack of the
1084   // formal specification of the linker script. We use heuristics to
1085   // determine whether a new output command should be added before or
1086   // after another commands. For the details, look at shouldSkip
1087   // function.
1088 
1089   auto I = Script->Opt.Commands.begin();
1090   auto E = Script->Opt.Commands.end();
1091   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1092     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1093       return Cmd->Sec && Cmd->Sec->SectionIndex == INT_MAX;
1094     return false;
1095   });
1096 
1097   // Sort the orphan sections.
1098   std::stable_sort(NonScriptI, E, compareSections);
1099 
1100   // As a horrible special case, skip the first . assignment if it is before any
1101   // section. We do this because it is common to set a load address by starting
1102   // the script with ". = 0xabcd" and the expectation is that every section is
1103   // after that.
1104   auto FirstSectionOrDotAssignment =
1105       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1106   if (FirstSectionOrDotAssignment != E &&
1107       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1108     ++FirstSectionOrDotAssignment;
1109   I = FirstSectionOrDotAssignment;
1110 
1111   while (NonScriptI != E) {
1112     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1113     OutputSection *Orphan = cast<OutputSectionCommand>(*NonScriptI)->Sec;
1114 
1115     // As an optimization, find all sections with the same sort rank
1116     // and insert them with one rotate.
1117     unsigned Rank = Orphan->SortRank;
1118     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1119       return cast<OutputSectionCommand>(Cmd)->Sec->SortRank != Rank;
1120     });
1121     std::rotate(Pos, NonScriptI, End);
1122     NonScriptI = End;
1123   }
1124 
1125   Script->adjustSectionsAfterSorting();
1126 }
1127 
1128 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1129                            std::function<void(SyntheticSection *)> Fn) {
1130   for (SyntheticSection *SS : Sections)
1131     if (SS && SS->getParent() && !SS->empty())
1132       Fn(SS);
1133 }
1134 
1135 // We need to add input synthetic sections early in createSyntheticSections()
1136 // to make them visible from linkescript side. But not all sections are always
1137 // required to be in output. For example we don't need dynamic section content
1138 // sometimes. This function filters out such unused sections from the output.
1139 static void removeUnusedSyntheticSections() {
1140   // All input synthetic sections that can be empty are placed after
1141   // all regular ones. We iterate over them all and exit at first
1142   // non-synthetic.
1143   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1144     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1145     if (!SS)
1146       return;
1147     OutputSection *OS = SS->getParent();
1148     if (!SS->empty() || !OS)
1149       continue;
1150     if ((SS == InX::Got || SS == InX::MipsGot) && ElfSym::GlobalOffsetTable)
1151       continue;
1152 
1153     OutputSectionCommand *Cmd = Script->getCmd(OS);
1154     std::vector<BaseCommand *>::iterator Empty = Cmd->Commands.end();
1155     for (auto I = Cmd->Commands.begin(), E = Cmd->Commands.end(); I != E; ++I) {
1156       BaseCommand *B = *I;
1157       if (auto *ISD = dyn_cast<InputSectionDescription>(B)) {
1158         auto P = std::find(ISD->Sections.begin(), ISD->Sections.end(), SS);
1159         if (P != ISD->Sections.end())
1160           ISD->Sections.erase(P);
1161         if (ISD->Sections.empty())
1162           Empty = I;
1163       }
1164     }
1165     if (Empty != Cmd->Commands.end())
1166       Cmd->Commands.erase(Empty);
1167 
1168     // If there are no other sections in the output section, remove it from the
1169     // output.
1170     if (Cmd->Commands.empty()) {
1171       // Also remove script commands matching the output section.
1172       auto &Cmds = Script->Opt.Commands;
1173       auto I = std::remove_if(Cmds.begin(), Cmds.end(), [&](BaseCommand *Cmd) {
1174         if (auto *OSCmd = dyn_cast<OutputSectionCommand>(Cmd))
1175           return OSCmd->Sec == OS;
1176         return false;
1177       });
1178       Cmds.erase(I, Cmds.end());
1179     }
1180   }
1181 }
1182 
1183 // Create output section objects and add them to OutputSections.
1184 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1185   Out::DebugInfo = findSectionInScript(".debug_info");
1186   Out::PreinitArray = findSectionInScript(".preinit_array");
1187   Out::InitArray = findSectionInScript(".init_array");
1188   Out::FiniArray = findSectionInScript(".fini_array");
1189 
1190   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1191   // symbols for sections, so that the runtime can get the start and end
1192   // addresses of each section by section name. Add such symbols.
1193   if (!Config->Relocatable) {
1194     addStartEndSymbols();
1195     for (BaseCommand *Base : Script->Opt.Commands)
1196       if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1197         if (Cmd->Sec)
1198           addStartStopSymbols(Cmd->Sec);
1199   }
1200 
1201   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1202   // It should be okay as no one seems to care about the type.
1203   // Even the author of gold doesn't remember why gold behaves that way.
1204   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1205   if (InX::DynSymTab)
1206     addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1207 
1208   // Define __rel[a]_iplt_{start,end} symbols if needed.
1209   addRelIpltSymbols();
1210 
1211   // This responsible for splitting up .eh_frame section into
1212   // pieces. The relocation scan uses those pieces, so this has to be
1213   // earlier.
1214   applySynthetic({In<ELFT>::EhFrame},
1215                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1216 
1217   // Scan relocations. This must be done after every symbol is declared so that
1218   // we can correctly decide if a dynamic relocation is needed.
1219   forEachRelSec(scanRelocations<ELFT>);
1220 
1221   if (InX::Plt && !InX::Plt->empty())
1222     InX::Plt->addSymbols();
1223   if (InX::Iplt && !InX::Iplt->empty())
1224     InX::Iplt->addSymbols();
1225 
1226   // Now that we have defined all possible global symbols including linker-
1227   // synthesized ones. Visit all symbols to give the finishing touches.
1228   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1229     SymbolBody *Body = S->body();
1230 
1231     if (!includeInSymtab(*Body))
1232       continue;
1233     if (InX::SymTab)
1234       InX::SymTab->addSymbol(Body);
1235 
1236     if (InX::DynSymTab && S->includeInDynsym()) {
1237       InX::DynSymTab->addSymbol(Body);
1238       if (auto *SS = dyn_cast<SharedSymbol>(Body))
1239         if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1240           In<ELFT>::VerNeed->addSymbol(SS);
1241     }
1242   }
1243 
1244   // Do not proceed if there was an undefined symbol.
1245   if (ErrorCount)
1246     return;
1247 
1248   addPredefinedSections();
1249   removeUnusedSyntheticSections();
1250 
1251   sortSections();
1252 
1253   // Now that we have the final list, create a list of all the
1254   // OutputSectionCommands for convenience.
1255   for (BaseCommand *Base : Script->Opt.Commands)
1256     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1257       OutputSectionCommands.push_back(Cmd);
1258 
1259   // Prefer command line supplied address over other constraints.
1260   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1261     auto I = Config->SectionStartMap.find(Cmd->Name);
1262     if (I != Config->SectionStartMap.end())
1263       Cmd->AddrExpr = [=] { return I->second; };
1264   }
1265 
1266   // This is a bit of a hack. A value of 0 means undef, so we set it
1267   // to 1 t make __ehdr_start defined. The section number is not
1268   // particularly relevant.
1269   Out::ElfHeader->SectionIndex = 1;
1270 
1271   unsigned I = 1;
1272   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1273     OutputSection *Sec = Cmd->Sec;
1274     Sec->SectionIndex = I++;
1275     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1276   }
1277 
1278   // Binary and relocatable output does not have PHDRS.
1279   // The headers have to be created before finalize as that can influence the
1280   // image base and the dynamic section on mips includes the image base.
1281   if (!Config->Relocatable && !Config->OFormatBinary) {
1282     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1283     addPtArmExid(Phdrs);
1284     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1285   }
1286 
1287   // Dynamic section must be the last one in this list and dynamic
1288   // symbol table section (DynSymTab) must be the first one.
1289   applySynthetic({InX::DynSymTab,    InX::Bss,           InX::BssRelRo,
1290                   InX::GnuHashTab,   In<ELFT>::HashTab,  InX::SymTab,
1291                   InX::ShStrTab,     InX::StrTab,        In<ELFT>::VerDef,
1292                   InX::DynStrTab,    InX::GdbIndex,      InX::Got,
1293                   InX::MipsGot,      InX::IgotPlt,       InX::GotPlt,
1294                   In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1295                   InX::Plt,          InX::Iplt,          In<ELFT>::EhFrameHdr,
1296                   In<ELFT>::VerSym,  In<ELFT>::VerNeed,  InX::Dynamic},
1297                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1298 
1299   // Some architectures use small displacements for jump instructions.
1300   // It is linker's responsibility to create thunks containing long
1301   // jump instructions if jump targets are too far. Create thunks.
1302   if (Target->NeedsThunks) {
1303     // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1304     // these
1305     // do not require address information. To support range extension Thunks
1306     // we need to assign addresses so that we can tell if jump instructions
1307     // are out of range. This will need to turn into a loop that converges
1308     // when no more Thunks are added
1309     ThunkCreator TC;
1310     Script->assignAddresses();
1311     if (TC.createThunks(OutputSectionCommands)) {
1312       applySynthetic({InX::MipsGot},
1313                      [](SyntheticSection *SS) { SS->updateAllocSize(); });
1314       if (TC.createThunks(OutputSectionCommands))
1315         fatal("All non-range thunks should be created in first call");
1316     }
1317   }
1318 
1319   // Fill other section headers. The dynamic table is finalized
1320   // at the end because some tags like RELSZ depend on result
1321   // of finalizing other sections.
1322   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1323     Cmd->finalize<ELFT>();
1324 
1325   // createThunks may have added local symbols to the static symbol table
1326   applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1327                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1328 }
1329 
1330 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1331   // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1332   // We have the terminater synthetic section class. Add that at the end.
1333   OutputSectionCommand *Cmd = findSectionCommand(".ARM.exidx");
1334   if (!Cmd || Cmd->Commands.empty() || Config->Relocatable)
1335     return;
1336 
1337   auto *Sentinel = make<ARMExidxSentinelSection>();
1338   Cmd->Sec->addSection(Sentinel);
1339   // Add the sentinel to the last of these too.
1340   auto ISD = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
1341                           [](const BaseCommand *Base) {
1342                             return isa<InputSectionDescription>(Base);
1343                           });
1344   cast<InputSectionDescription>(*ISD)->Sections.push_back(Sentinel);
1345 }
1346 
1347 // The linker is expected to define SECNAME_start and SECNAME_end
1348 // symbols for a few sections. This function defines them.
1349 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1350   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1351     // These symbols resolve to the image base if the section does not exist.
1352     // A special value -1 indicates end of the section.
1353     if (OS) {
1354       addOptionalRegular<ELFT>(Start, OS, 0);
1355       addOptionalRegular<ELFT>(End, OS, -1);
1356     } else {
1357       if (Config->Pic)
1358         OS = Out::ElfHeader;
1359       addOptionalRegular<ELFT>(Start, OS, 0);
1360       addOptionalRegular<ELFT>(End, OS, 0);
1361     }
1362   };
1363 
1364   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1365   Define("__init_array_start", "__init_array_end", Out::InitArray);
1366   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1367 
1368   if (OutputSection *Sec = findSectionInScript(".ARM.exidx"))
1369     Define("__exidx_start", "__exidx_end", Sec);
1370 }
1371 
1372 // If a section name is valid as a C identifier (which is rare because of
1373 // the leading '.'), linkers are expected to define __start_<secname> and
1374 // __stop_<secname> symbols. They are at beginning and end of the section,
1375 // respectively. This is not requested by the ELF standard, but GNU ld and
1376 // gold provide the feature, and used by many programs.
1377 template <class ELFT>
1378 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1379   StringRef S = Sec->Name;
1380   if (!isValidCIdentifier(S))
1381     return;
1382   addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1383   addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1384 }
1385 
1386 template <class ELFT>
1387 OutputSectionCommand *Writer<ELFT>::findSectionCommand(StringRef Name) {
1388   for (BaseCommand *Base : Script->Opt.Commands)
1389     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1390       if (Cmd->Name == Name)
1391         return Cmd;
1392   return nullptr;
1393 }
1394 
1395 template <class ELFT> OutputSection *Writer<ELFT>::findSectionInScript(StringRef Name) {
1396   if (OutputSectionCommand *Cmd = findSectionCommand(Name))
1397     return Cmd->Sec;
1398   return nullptr;
1399 }
1400 
1401 static bool needsPtLoad(OutputSection *Sec) {
1402   if (!(Sec->Flags & SHF_ALLOC))
1403     return false;
1404 
1405   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1406   // responsible for allocating space for them, not the PT_LOAD that
1407   // contains the TLS initialization image.
1408   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1409     return false;
1410   return true;
1411 }
1412 
1413 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1414 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1415 // RW. This means that there is no alignment in the RO to RX transition and we
1416 // cannot create a PT_LOAD there.
1417 static uint64_t computeFlags(uint64_t Flags) {
1418   if (Config->Omagic)
1419     return PF_R | PF_W | PF_X;
1420   if (Config->SingleRoRx && !(Flags & PF_W))
1421     return Flags | PF_X;
1422   return Flags;
1423 }
1424 
1425 // Decide which program headers to create and which sections to include in each
1426 // one.
1427 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1428   std::vector<PhdrEntry> Ret;
1429   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1430     Ret.emplace_back(Type, Flags);
1431     return &Ret.back();
1432   };
1433 
1434   // The first phdr entry is PT_PHDR which describes the program header itself.
1435   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1436 
1437   // PT_INTERP must be the second entry if exists.
1438   if (OutputSection *Sec = findSectionInScript(".interp"))
1439     AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1440 
1441   // Add the first PT_LOAD segment for regular output sections.
1442   uint64_t Flags = computeFlags(PF_R);
1443   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1444 
1445   // Add the headers. We will remove them if they don't fit.
1446   Load->add(Out::ElfHeader);
1447   Load->add(Out::ProgramHeaders);
1448 
1449   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1450     OutputSection *Sec = Cmd->Sec;
1451     if (!(Sec->Flags & SHF_ALLOC))
1452       break;
1453     if (!needsPtLoad(Sec))
1454       continue;
1455 
1456     // Segments are contiguous memory regions that has the same attributes
1457     // (e.g. executable or writable). There is one phdr for each segment.
1458     // Therefore, we need to create a new phdr when the next section has
1459     // different flags or is loaded at a discontiguous address using AT linker
1460     // script command.
1461     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1462     if (Cmd->LMAExpr || Flags != NewFlags) {
1463       Load = AddHdr(PT_LOAD, NewFlags);
1464       Flags = NewFlags;
1465     }
1466 
1467     Load->add(Sec);
1468   }
1469 
1470   // Add a TLS segment if any.
1471   PhdrEntry TlsHdr(PT_TLS, PF_R);
1472   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1473     OutputSection *Sec = Cmd->Sec;
1474     if (Sec->Flags & SHF_TLS)
1475       TlsHdr.add(Sec);
1476   }
1477   if (TlsHdr.First)
1478     Ret.push_back(std::move(TlsHdr));
1479 
1480   // Add an entry for .dynamic.
1481   if (InX::DynSymTab)
1482     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1483         ->add(InX::Dynamic->getParent());
1484 
1485   // PT_GNU_RELRO includes all sections that should be marked as
1486   // read-only by dynamic linker after proccessing relocations.
1487   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1488   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1489     OutputSection *Sec = Cmd->Sec;
1490     if (needsPtLoad(Sec) && isRelroSection(Sec))
1491       RelRo.add(Sec);
1492   }
1493   if (RelRo.First)
1494     Ret.push_back(std::move(RelRo));
1495 
1496   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1497   if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1498       In<ELFT>::EhFrame->getParent() && In<ELFT>::EhFrameHdr->getParent())
1499     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->getParent()->getPhdrFlags())
1500         ->add(In<ELFT>::EhFrameHdr->getParent());
1501 
1502   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1503   // the dynamic linker fill the segment with random data.
1504   if (OutputSection *Sec = findSectionInScript(".openbsd.randomdata"))
1505     AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1506 
1507   // PT_GNU_STACK is a special section to tell the loader to make the
1508   // pages for the stack non-executable. If you really want an executable
1509   // stack, you can pass -z execstack, but that's not recommended for
1510   // security reasons.
1511   unsigned Perm;
1512   if (Config->ZExecstack)
1513     Perm = PF_R | PF_W | PF_X;
1514   else
1515     Perm = PF_R | PF_W;
1516   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1517 
1518   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1519   // is expected to perform W^X violations, such as calling mprotect(2) or
1520   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1521   // OpenBSD.
1522   if (Config->ZWxneeded)
1523     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1524 
1525   // Create one PT_NOTE per a group of contiguous .note sections.
1526   PhdrEntry *Note = nullptr;
1527   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1528     OutputSection *Sec = Cmd->Sec;
1529     if (Sec->Type == SHT_NOTE) {
1530       if (!Note || Cmd->LMAExpr)
1531         Note = AddHdr(PT_NOTE, PF_R);
1532       Note->add(Sec);
1533     } else {
1534       Note = nullptr;
1535     }
1536   }
1537   return Ret;
1538 }
1539 
1540 template <class ELFT>
1541 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1542   if (Config->EMachine != EM_ARM)
1543     return;
1544   auto I = llvm::find_if(OutputSectionCommands, [](OutputSectionCommand *Cmd) {
1545     return Cmd->Sec->Type == SHT_ARM_EXIDX;
1546   });
1547   if (I == OutputSectionCommands.end())
1548     return;
1549 
1550   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1551   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1552   ARMExidx.add((*I)->Sec);
1553   Phdrs.push_back(ARMExidx);
1554 }
1555 
1556 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1557 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1558 // linker can set the permissions.
1559 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1560   auto PageAlign = [](OutputSection *Sec) {
1561     OutputSectionCommand *Cmd = Script->getCmd(Sec);
1562     if (Cmd && !Cmd->AddrExpr)
1563       Cmd->AddrExpr = [=] {
1564         return alignTo(Script->getDot(), Config->MaxPageSize);
1565       };
1566   };
1567 
1568   for (const PhdrEntry &P : Phdrs)
1569     if (P.p_type == PT_LOAD && P.First)
1570       PageAlign(P.First);
1571 
1572   for (const PhdrEntry &P : Phdrs) {
1573     if (P.p_type != PT_GNU_RELRO)
1574       continue;
1575     if (P.First)
1576       PageAlign(P.First);
1577     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1578     // have to align it to a page.
1579     auto End = OutputSectionCommands.end();
1580     auto I =
1581         std::find(OutputSectionCommands.begin(), End, Script->getCmd(P.Last));
1582     if (I == End || (I + 1) == End)
1583       continue;
1584     OutputSection *Sec = (*(I + 1))->Sec;
1585     if (needsPtLoad(Sec))
1586       PageAlign(Sec);
1587   }
1588 }
1589 
1590 // Adjusts the file alignment for a given output section and returns
1591 // its new file offset. The file offset must be the same with its
1592 // virtual address (modulo the page size) so that the loader can load
1593 // executables without any address adjustment.
1594 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1595   OutputSection *First = Sec->FirstInPtLoad;
1596   // If the section is not in a PT_LOAD, we just have to align it.
1597   if (!First)
1598     return alignTo(Off, Sec->Alignment);
1599 
1600   // The first section in a PT_LOAD has to have congruent offset and address
1601   // module the page size.
1602   if (Sec == First)
1603     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1604 
1605   // If two sections share the same PT_LOAD the file offset is calculated
1606   // using this formula: Off2 = Off1 + (VA2 - VA1).
1607   return First->Offset + Sec->Addr - First->Addr;
1608 }
1609 
1610 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1611   if (Sec->Type == SHT_NOBITS) {
1612     Sec->Offset = Off;
1613     return Off;
1614   }
1615 
1616   Off = getFileAlignment(Off, Sec);
1617   Sec->Offset = Off;
1618   return Off + Sec->Size;
1619 }
1620 
1621 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1622   uint64_t Off = 0;
1623   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1624     OutputSection *Sec = Cmd->Sec;
1625     if (Sec->Flags & SHF_ALLOC)
1626       Off = setOffset(Sec, Off);
1627   }
1628   FileSize = alignTo(Off, Config->Wordsize);
1629 }
1630 
1631 // Assign file offsets to output sections.
1632 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1633   uint64_t Off = 0;
1634   Off = setOffset(Out::ElfHeader, Off);
1635   Off = setOffset(Out::ProgramHeaders, Off);
1636 
1637   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1638     Off = setOffset(Cmd->Sec, Off);
1639 
1640   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1641   FileSize =
1642       SectionHeaderOff + (OutputSectionCommands.size() + 1) * sizeof(Elf_Shdr);
1643 }
1644 
1645 // Finalize the program headers. We call this function after we assign
1646 // file offsets and VAs to all sections.
1647 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1648   for (PhdrEntry &P : Phdrs) {
1649     OutputSection *First = P.First;
1650     OutputSection *Last = P.Last;
1651     if (First) {
1652       P.p_filesz = Last->Offset - First->Offset;
1653       if (Last->Type != SHT_NOBITS)
1654         P.p_filesz += Last->Size;
1655       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1656       P.p_offset = First->Offset;
1657       P.p_vaddr = First->Addr;
1658       if (!P.HasLMA)
1659         P.p_paddr = First->getLMA();
1660     }
1661     if (P.p_type == PT_LOAD)
1662       P.p_align = Config->MaxPageSize;
1663     else if (P.p_type == PT_GNU_RELRO) {
1664       P.p_align = 1;
1665       // The glibc dynamic loader rounds the size down, so we need to round up
1666       // to protect the last page. This is a no-op on FreeBSD which always
1667       // rounds up.
1668       P.p_memsz = alignTo(P.p_memsz, Target->PageSize);
1669     }
1670 
1671     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1672     // so round up the size to make sure the offsets are correct.
1673     if (P.p_type == PT_TLS) {
1674       Out::TlsPhdr = &P;
1675       if (P.p_memsz)
1676         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1677     }
1678   }
1679 }
1680 
1681 // The entry point address is chosen in the following ways.
1682 //
1683 // 1. the '-e' entry command-line option;
1684 // 2. the ENTRY(symbol) command in a linker control script;
1685 // 3. the value of the symbol start, if present;
1686 // 4. the address of the first byte of the .text section, if present;
1687 // 5. the address 0.
1688 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1689   // Case 1, 2 or 3. As a special case, if the symbol is actually
1690   // a number, we'll use that number as an address.
1691   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1692     return B->getVA();
1693   uint64_t Addr;
1694   if (to_integer(Config->Entry, Addr))
1695     return Addr;
1696 
1697   // Case 4
1698   if (OutputSection *Sec = findSectionInScript(".text")) {
1699     if (Config->WarnMissingEntry)
1700       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1701            utohexstr(Sec->Addr));
1702     return Sec->Addr;
1703   }
1704 
1705   // Case 5
1706   if (Config->WarnMissingEntry)
1707     warn("cannot find entry symbol " + Config->Entry +
1708          "; not setting start address");
1709   return 0;
1710 }
1711 
1712 static uint16_t getELFType() {
1713   if (Config->Pic)
1714     return ET_DYN;
1715   if (Config->Relocatable)
1716     return ET_REL;
1717   return ET_EXEC;
1718 }
1719 
1720 // This function is called after we have assigned address and size
1721 // to each section. This function fixes some predefined
1722 // symbol values that depend on section address and size.
1723 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1724   // _etext is the first location after the last read-only loadable segment.
1725   // _edata is the first location after the last read-write loadable segment.
1726   // _end is the first location after the uninitialized data region.
1727   PhdrEntry *Last = nullptr;
1728   PhdrEntry *LastRO = nullptr;
1729   PhdrEntry *LastRW = nullptr;
1730   for (PhdrEntry &P : Phdrs) {
1731     if (P.p_type != PT_LOAD)
1732       continue;
1733     Last = &P;
1734     if (P.p_flags & PF_W)
1735       LastRW = &P;
1736     else
1737       LastRO = &P;
1738   }
1739 
1740   auto Set = [](DefinedRegular *S, OutputSection *Sec, uint64_t Value) {
1741     if (S) {
1742       S->Section = Sec;
1743       S->Value = Value;
1744     }
1745   };
1746 
1747   if (Last) {
1748     Set(ElfSym::End1, Last->First, Last->p_memsz);
1749     Set(ElfSym::End2, Last->First, Last->p_memsz);
1750   }
1751   if (LastRO) {
1752     Set(ElfSym::Etext1, LastRO->First, LastRO->p_filesz);
1753     Set(ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1754   }
1755   if (LastRW) {
1756     Set(ElfSym::Edata1, LastRW->First, LastRW->p_filesz);
1757     Set(ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1758   }
1759 
1760   if (ElfSym::Bss)
1761     ElfSym::Bss->Section = findSectionInScript(".bss");
1762 
1763   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1764   // be equal to the _gp symbol's value.
1765   if (Config->EMachine == EM_MIPS && !ElfSym::MipsGp->Value) {
1766     // Find GP-relative section with the lowest address
1767     // and use this address to calculate default _gp value.
1768     for (const OutputSectionCommand *Cmd : OutputSectionCommands) {
1769       OutputSection *OS = Cmd->Sec;
1770       if (OS->Flags & SHF_MIPS_GPREL) {
1771         ElfSym::MipsGp->Value = OS->Addr + 0x7ff0;
1772         break;
1773       }
1774     }
1775   }
1776 }
1777 
1778 template <class ELFT> void Writer<ELFT>::writeHeader() {
1779   uint8_t *Buf = Buffer->getBufferStart();
1780   memcpy(Buf, "\177ELF", 4);
1781 
1782   // Write the ELF header.
1783   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1784   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1785   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1786   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1787   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1788   EHdr->e_type = getELFType();
1789   EHdr->e_machine = Config->EMachine;
1790   EHdr->e_version = EV_CURRENT;
1791   EHdr->e_entry = getEntryAddr();
1792   EHdr->e_shoff = SectionHeaderOff;
1793   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1794   EHdr->e_phnum = Phdrs.size();
1795   EHdr->e_shentsize = sizeof(Elf_Shdr);
1796   EHdr->e_shnum = OutputSectionCommands.size() + 1;
1797   EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
1798 
1799   if (Config->EMachine == EM_ARM)
1800     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1801     // but we don't have any firm guarantees of conformance. Linux AArch64
1802     // kernels (as of 2016) require an EABI version to be set.
1803     EHdr->e_flags = EF_ARM_EABI_VER5;
1804   else if (Config->EMachine == EM_MIPS)
1805     EHdr->e_flags = getMipsEFlags<ELFT>();
1806 
1807   if (!Config->Relocatable) {
1808     EHdr->e_phoff = sizeof(Elf_Ehdr);
1809     EHdr->e_phentsize = sizeof(Elf_Phdr);
1810   }
1811 
1812   // Write the program header table.
1813   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1814   for (PhdrEntry &P : Phdrs) {
1815     HBuf->p_type = P.p_type;
1816     HBuf->p_flags = P.p_flags;
1817     HBuf->p_offset = P.p_offset;
1818     HBuf->p_vaddr = P.p_vaddr;
1819     HBuf->p_paddr = P.p_paddr;
1820     HBuf->p_filesz = P.p_filesz;
1821     HBuf->p_memsz = P.p_memsz;
1822     HBuf->p_align = P.p_align;
1823     ++HBuf;
1824   }
1825 
1826   // Write the section header table. Note that the first table entry is null.
1827   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1828   for (OutputSectionCommand *Cmd : OutputSectionCommands)
1829     Cmd->Sec->writeHeaderTo<ELFT>(++SHdrs);
1830 }
1831 
1832 // Open a result file.
1833 template <class ELFT> void Writer<ELFT>::openFile() {
1834   if (!Config->Is64 && FileSize > UINT32_MAX) {
1835     error("output file too large: " + Twine(FileSize) + " bytes");
1836     return;
1837   }
1838 
1839   unlinkAsync(Config->OutputFile);
1840   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1841       FileOutputBuffer::create(Config->OutputFile, FileSize,
1842                                FileOutputBuffer::F_executable);
1843 
1844   if (auto EC = BufferOrErr.getError())
1845     error("failed to open " + Config->OutputFile + ": " + EC.message());
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 (OutputSectionCommand *Cmd : OutputSectionCommands) {
1853     OutputSection *Sec = Cmd->Sec;
1854     if (Sec->Flags & SHF_ALLOC)
1855       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1856   }
1857 }
1858 
1859 // Write section contents to a mmap'ed file.
1860 template <class ELFT> void Writer<ELFT>::writeSections() {
1861   uint8_t *Buf = Buffer->getBufferStart();
1862 
1863   // PPC64 needs to process relocations in the .opd section
1864   // before processing relocations in code-containing sections.
1865   if (auto *OpdCmd = findSectionCommand(".opd")) {
1866     Out::Opd = OpdCmd->Sec;
1867     Out::OpdBuf = Buf + Out::Opd->Offset;
1868     OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1869   }
1870 
1871   OutputSection *EhFrameHdr =
1872       (In<ELFT>::EhFrameHdr && !In<ELFT>::EhFrameHdr->empty())
1873           ? In<ELFT>::EhFrameHdr->getParent()
1874           : nullptr;
1875 
1876   // In -r or -emit-relocs mode, write the relocation sections first as in
1877   // ELf_Rel targets we might find out that we need to modify the relocated
1878   // section while doing it.
1879   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1880     OutputSection *Sec = Cmd->Sec;
1881     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1882       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1883   }
1884 
1885   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
1886     OutputSection *Sec = Cmd->Sec;
1887     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1888         Sec->Type != SHT_RELA)
1889       Cmd->writeTo<ELFT>(Buf + Sec->Offset);
1890   }
1891 
1892   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1893   // it should be written after .eh_frame is written.
1894   if (EhFrameHdr) {
1895     OutputSectionCommand *Cmd = Script->getCmd(EhFrameHdr);
1896     Cmd->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1897   }
1898 }
1899 
1900 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1901   if (!InX::BuildId || !InX::BuildId->getParent())
1902     return;
1903 
1904   // Compute a hash of all sections of the output file.
1905   uint8_t *Start = Buffer->getBufferStart();
1906   uint8_t *End = Start + FileSize;
1907   InX::BuildId->writeBuildId({Start, End});
1908 }
1909 
1910 template void elf::writeResult<ELF32LE>();
1911 template void elf::writeResult<ELF32BE>();
1912 template void elf::writeResult<ELF64LE>();
1913 template void elf::writeResult<ELF64BE>();
1914