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