xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 22bdb331)
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 "AArch64ErrataFix.h"
12 #include "CallGraphSort.h"
13 #include "Config.h"
14 #include "Filesystem.h"
15 #include "LinkerScript.h"
16 #include "MapFile.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Strings.h"
25 #include "lld/Common/Threads.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include <climits>
29 
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
35 
36 using namespace lld;
37 using namespace lld::elf;
38 
39 namespace {
40 // The writer writes a SymbolTable result to a file.
41 template <class ELFT> class Writer {
42 public:
43   Writer() : Buffer(errorHandler().OutputBuffer) {}
44   typedef typename ELFT::Shdr Elf_Shdr;
45   typedef typename ELFT::Ehdr Elf_Ehdr;
46   typedef typename ELFT::Phdr Elf_Phdr;
47 
48   void run();
49 
50 private:
51   void copyLocalSymbols();
52   void addSectionSymbols();
53   void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> Fn);
54   void sortSections();
55   void resolveShfLinkOrder();
56   void maybeAddThunks();
57   void sortInputSections();
58   void finalizeSections();
59   void checkExecuteOnly();
60   void setReservedSymbolSections();
61 
62   std::vector<PhdrEntry *> createPhdrs();
63   void removeEmptyPTLoad();
64   void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
65   void assignFileOffsets();
66   void assignFileOffsetsBinary();
67   void setPhdrs();
68   void checkSections();
69   void fixSectionAlignments();
70   void openFile();
71   void writeTrapInstr();
72   void writeHeader();
73   void writeSections();
74   void writeSectionsBinary();
75   void writeBuildId();
76 
77   std::unique_ptr<FileOutputBuffer> &Buffer;
78 
79   void addRelIpltSymbols();
80   void addStartEndSymbols();
81   void addStartStopSymbols(OutputSection *Sec);
82 
83   std::vector<PhdrEntry *> Phdrs;
84 
85   uint64_t FileSize;
86   uint64_t SectionHeaderOff;
87 };
88 } // anonymous namespace
89 
90 static bool isSectionPrefix(StringRef Prefix, StringRef Name) {
91   return Name.startswith(Prefix) || Name == Prefix.drop_back();
92 }
93 
94 StringRef elf::getOutputSectionName(const InputSectionBase *S) {
95   if (Config->Relocatable)
96     return S->Name;
97 
98   // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
99   // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
100   // technically required, but not doing it is odd). This code guarantees that.
101   if (auto *IS = dyn_cast<InputSection>(S)) {
102     if (InputSectionBase *Rel = IS->getRelocatedSection()) {
103       OutputSection *Out = Rel->getOutputSection();
104       if (S->Type == SHT_RELA)
105         return Saver.save(".rela" + Out->Name);
106       return Saver.save(".rel" + Out->Name);
107     }
108   }
109 
110   // This check is for -z keep-text-section-prefix.  This option separates text
111   // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
112   // ".text.exit".
113   // When enabled, this allows identifying the hot code region (.text.hot) in
114   // the final binary which can be selectively mapped to huge pages or mlocked,
115   // for instance.
116   if (Config->ZKeepTextSectionPrefix)
117     for (StringRef V :
118          {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."})
119       if (isSectionPrefix(V, S->Name))
120         return V.drop_back();
121 
122   for (StringRef V :
123        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
124         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
125         ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."})
126     if (isSectionPrefix(V, S->Name))
127       return V.drop_back();
128 
129   // CommonSection is identified as "COMMON" in linker scripts.
130   // By default, it should go to .bss section.
131   if (S->Name == "COMMON")
132     return ".bss";
133 
134   return S->Name;
135 }
136 
137 static bool needsInterpSection() {
138   return !SharedFiles.empty() && !Config->DynamicLinker.empty() &&
139          Script->needsInterpSection();
140 }
141 
142 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
143 
144 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
145   llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
146     if (P->p_type != PT_LOAD)
147       return false;
148     if (!P->FirstSec)
149       return true;
150     uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
151     return Size == 0;
152   });
153 }
154 
155 template <class ELFT> static void combineEhFrameSections() {
156   for (InputSectionBase *&S : InputSections) {
157     EhInputSection *ES = dyn_cast<EhInputSection>(S);
158     if (!ES || !ES->Live)
159       continue;
160 
161     In.EhFrame->addSection<ELFT>(ES);
162     S = nullptr;
163   }
164 
165   std::vector<InputSectionBase *> &V = InputSections;
166   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
167 }
168 
169 static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec,
170                                    uint64_t Val, uint8_t StOther = STV_HIDDEN,
171                                    uint8_t Binding = STB_GLOBAL) {
172   Symbol *S = Symtab->find(Name);
173   if (!S || S->isDefined())
174     return nullptr;
175   Symbol *Sym = Symtab->addDefined(Name, StOther, STT_NOTYPE, Val,
176                                    /*Size=*/0, Binding, Sec,
177                                    /*File=*/nullptr);
178   return cast<Defined>(Sym);
179 }
180 
181 static Defined *addAbsolute(StringRef Name) {
182   return cast<Defined>(Symtab->addDefined(Name, STV_HIDDEN, STT_NOTYPE, 0, 0,
183                                           STB_GLOBAL, nullptr, nullptr));
184 }
185 
186 // The linker is expected to define some symbols depending on
187 // the linking result. This function defines such symbols.
188 void elf::addReservedSymbols() {
189   if (Config->EMachine == EM_MIPS) {
190     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
191     // so that it points to an absolute address which by default is relative
192     // to GOT. Default offset is 0x7ff0.
193     // See "Global Data Symbols" in Chapter 6 in the following document:
194     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
195     ElfSym::MipsGp = addAbsolute("_gp");
196 
197     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
198     // start of function and 'gp' pointer into GOT.
199     if (Symtab->find("_gp_disp"))
200       ElfSym::MipsGpDisp = addAbsolute("_gp_disp");
201 
202     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
203     // pointer. This symbol is used in the code generated by .cpload pseudo-op
204     // in case of using -mno-shared option.
205     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
206     if (Symtab->find("__gnu_local_gp"))
207       ElfSym::MipsLocalGp = addAbsolute("__gnu_local_gp");
208   }
209 
210   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
211   // combines the typical ELF GOT with the small data sections. It commonly
212   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
213   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
214   // represent the TOC base which is offset by 0x8000 bytes from the start of
215   // the .got section.
216   ElfSym::GlobalOffsetTable = addOptionalRegular(
217       (Config->EMachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_",
218       Out::ElfHeader, Target->GotBaseSymOff);
219 
220   // __ehdr_start is the location of ELF file headers. Note that we define
221   // this symbol unconditionally even when using a linker script, which
222   // differs from the behavior implemented by GNU linker which only define
223   // this symbol if ELF headers are in the memory mapped segment.
224   addOptionalRegular("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
225 
226   // __executable_start is not documented, but the expectation of at
227   // least the Android libc is that it points to the ELF header.
228   addOptionalRegular("__executable_start", Out::ElfHeader, 0, STV_HIDDEN);
229 
230   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
231   // each DSO. The address of the symbol doesn't matter as long as they are
232   // different in different DSOs, so we chose the start address of the DSO.
233   addOptionalRegular("__dso_handle", Out::ElfHeader, 0, STV_HIDDEN);
234 
235   // If linker script do layout we do not need to create any standart symbols.
236   if (Script->HasSectionsCommand)
237     return;
238 
239   auto Add = [](StringRef S, int64_t Pos) {
240     return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT);
241   };
242 
243   ElfSym::Bss = Add("__bss_start", 0);
244   ElfSym::End1 = Add("end", -1);
245   ElfSym::End2 = Add("_end", -1);
246   ElfSym::Etext1 = Add("etext", -1);
247   ElfSym::Etext2 = Add("_etext", -1);
248   ElfSym::Edata1 = Add("edata", -1);
249   ElfSym::Edata2 = Add("_edata", -1);
250 }
251 
252 static OutputSection *findSection(StringRef Name) {
253   for (BaseCommand *Base : Script->SectionCommands)
254     if (auto *Sec = dyn_cast<OutputSection>(Base))
255       if (Sec->Name == Name)
256         return Sec;
257   return nullptr;
258 }
259 
260 // Initialize Out members.
261 template <class ELFT> static void createSyntheticSections() {
262   // Initialize all pointers with NULL. This is needed because
263   // you can call lld::elf::main more than once as a library.
264   memset(&Out::First, 0, sizeof(Out));
265 
266   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
267 
268   In.DynStrTab = make<StringTableSection>(".dynstr", true);
269   In.Dynamic = make<DynamicSection<ELFT>>();
270   if (Config->AndroidPackDynRelocs) {
271     In.RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
272         Config->IsRela ? ".rela.dyn" : ".rel.dyn");
273   } else {
274     In.RelaDyn = make<RelocationSection<ELFT>>(
275         Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
276   }
277   In.ShStrTab = make<StringTableSection>(".shstrtab", false);
278 
279   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
280   Out::ProgramHeaders->Alignment = Config->Wordsize;
281 
282   if (needsInterpSection()) {
283     In.Interp = createInterpSection();
284     Add(In.Interp);
285   }
286 
287   if (Config->Strip != StripPolicy::All) {
288     In.StrTab = make<StringTableSection>(".strtab", false);
289     In.SymTab = make<SymbolTableSection<ELFT>>(*In.StrTab);
290     In.SymTabShndx = make<SymtabShndxSection>();
291   }
292 
293   if (Config->BuildId != BuildIdKind::None) {
294     In.BuildId = make<BuildIdSection>();
295     Add(In.BuildId);
296   }
297 
298   In.Bss = make<BssSection>(".bss", 0, 1);
299   Add(In.Bss);
300 
301   // If there is a SECTIONS command and a .data.rel.ro section name use name
302   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
303   // This makes sure our relro is contiguous.
304   bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro");
305   In.BssRelRo =
306       make<BssSection>(HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
307   Add(In.BssRelRo);
308 
309   // Add MIPS-specific sections.
310   if (Config->EMachine == EM_MIPS) {
311     if (!Config->Shared && Config->HasDynSymTab) {
312       In.MipsRldMap = make<MipsRldMapSection>();
313       Add(In.MipsRldMap);
314     }
315     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
316       Add(Sec);
317     if (auto *Sec = MipsOptionsSection<ELFT>::create())
318       Add(Sec);
319     if (auto *Sec = MipsReginfoSection<ELFT>::create())
320       Add(Sec);
321   }
322 
323   if (Config->HasDynSymTab) {
324     In.DynSymTab = make<SymbolTableSection<ELFT>>(*In.DynStrTab);
325     Add(In.DynSymTab);
326 
327     InX<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
328     Add(InX<ELFT>::VerSym);
329 
330     if (!Config->VersionDefinitions.empty()) {
331       In.VerDef = make<VersionDefinitionSection>();
332       Add(In.VerDef);
333     }
334 
335     InX<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
336     Add(InX<ELFT>::VerNeed);
337 
338     if (Config->GnuHash) {
339       In.GnuHashTab = make<GnuHashTableSection>();
340       Add(In.GnuHashTab);
341     }
342 
343     if (Config->SysvHash) {
344       In.HashTab = make<HashTableSection>();
345       Add(In.HashTab);
346     }
347 
348     Add(In.Dynamic);
349     Add(In.DynStrTab);
350     Add(In.RelaDyn);
351   }
352 
353   if (Config->RelrPackDynRelocs) {
354     In.RelrDyn = make<RelrSection<ELFT>>();
355     Add(In.RelrDyn);
356   }
357 
358   // Add .got. MIPS' .got is so different from the other archs,
359   // it has its own class.
360   if (Config->EMachine == EM_MIPS) {
361     In.MipsGot = make<MipsGotSection>();
362     Add(In.MipsGot);
363   } else {
364     In.Got = make<GotSection>();
365     Add(In.Got);
366   }
367 
368   if (Config->EMachine == EM_PPC64) {
369     In.PPC64LongBranchTarget = make<PPC64LongBranchTargetSection>();
370     Add(In.PPC64LongBranchTarget);
371   }
372 
373   In.GotPlt = make<GotPltSection>();
374   Add(In.GotPlt);
375   In.IgotPlt = make<IgotPltSection>();
376   Add(In.IgotPlt);
377 
378   if (Config->GdbIndex) {
379     In.GdbIndex = GdbIndexSection::create<ELFT>();
380     Add(In.GdbIndex);
381   }
382 
383   // We always need to add rel[a].plt to output if it has entries.
384   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
385   In.RelaPlt = make<RelocationSection<ELFT>>(
386       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
387   Add(In.RelaPlt);
388 
389   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
390   // that the IRelative relocations are processed last by the dynamic loader.
391   // We cannot place the iplt section in .rel.dyn when Android relocation
392   // packing is enabled because that would cause a section type mismatch.
393   // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
394   // we can get the desired behaviour by placing the iplt section in .rel.plt.
395   In.RelaIplt = make<RelocationSection<ELFT>>(
396       (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs)
397           ? ".rel.dyn"
398           : In.RelaPlt->Name,
399       false /*Sort*/);
400   Add(In.RelaIplt);
401 
402   In.Plt = make<PltSection>(false);
403   Add(In.Plt);
404   In.Iplt = make<PltSection>(true);
405   Add(In.Iplt);
406 
407   // .note.GNU-stack is always added when we are creating a re-linkable
408   // object file. Other linkers are using the presence of this marker
409   // section to control the executable-ness of the stack area, but that
410   // is irrelevant these days. Stack area should always be non-executable
411   // by default. So we emit this section unconditionally.
412   if (Config->Relocatable)
413     Add(make<GnuStackSection>());
414 
415   if (!Config->Relocatable) {
416     if (Config->EhFrameHdr) {
417       In.EhFrameHdr = make<EhFrameHeader>();
418       Add(In.EhFrameHdr);
419     }
420     In.EhFrame = make<EhFrameSection>();
421     Add(In.EhFrame);
422   }
423 
424   if (In.SymTab)
425     Add(In.SymTab);
426   if (In.SymTabShndx)
427     Add(In.SymTabShndx);
428   Add(In.ShStrTab);
429   if (In.StrTab)
430     Add(In.StrTab);
431 
432   if (Config->EMachine == EM_ARM && !Config->Relocatable)
433     // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
434     // to find the exact address range of the last entry.
435     Add(make<ARMExidxSentinelSection>());
436 }
437 
438 // The main function of the writer.
439 template <class ELFT> void Writer<ELFT>::run() {
440   // Create linker-synthesized sections such as .got or .plt.
441   // Such sections are of type input section.
442   createSyntheticSections<ELFT>();
443 
444   if (!Config->Relocatable)
445     combineEhFrameSections<ELFT>();
446 
447   // We want to process linker script commands. When SECTIONS command
448   // is given we let it create sections.
449   Script->processSectionCommands();
450 
451   // Linker scripts controls how input sections are assigned to output sections.
452   // Input sections that were not handled by scripts are called "orphans", and
453   // they are assigned to output sections by the default rule. Process that.
454   Script->addOrphanSections();
455 
456   if (Config->Discard != DiscardPolicy::All)
457     copyLocalSymbols();
458 
459   if (Config->CopyRelocs)
460     addSectionSymbols();
461 
462   // Now that we have a complete set of output sections. This function
463   // completes section contents. For example, we need to add strings
464   // to the string table, and add entries to .got and .plt.
465   // finalizeSections does that.
466   finalizeSections();
467   checkExecuteOnly();
468   if (errorCount())
469     return;
470 
471   Script->assignAddresses();
472 
473   // If -compressed-debug-sections is specified, we need to compress
474   // .debug_* sections. Do it right now because it changes the size of
475   // output sections.
476   for (OutputSection *Sec : OutputSections)
477     Sec->maybeCompress<ELFT>();
478 
479   Script->allocateHeaders(Phdrs);
480 
481   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
482   // 0 sized region. This has to be done late since only after assignAddresses
483   // we know the size of the sections.
484   removeEmptyPTLoad();
485 
486   if (!Config->OFormatBinary)
487     assignFileOffsets();
488   else
489     assignFileOffsetsBinary();
490 
491   setPhdrs();
492 
493   if (Config->Relocatable)
494     for (OutputSection *Sec : OutputSections)
495       Sec->Addr = 0;
496 
497   if (Config->CheckSections)
498     checkSections();
499 
500   // It does not make sense try to open the file if we have error already.
501   if (errorCount())
502     return;
503   // Write the result down to a file.
504   openFile();
505   if (errorCount())
506     return;
507 
508   if (!Config->OFormatBinary) {
509     writeTrapInstr();
510     writeHeader();
511     writeSections();
512   } else {
513     writeSectionsBinary();
514   }
515 
516   // Backfill .note.gnu.build-id section content. This is done at last
517   // because the content is usually a hash value of the entire output file.
518   writeBuildId();
519   if (errorCount())
520     return;
521 
522   // Handle -Map and -cref options.
523   writeMapFile();
524   writeCrossReferenceTable();
525   if (errorCount())
526     return;
527 
528   if (auto E = Buffer->commit())
529     error("failed to write to the output file: " + toString(std::move(E)));
530 }
531 
532 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
533                                const Symbol &B) {
534   if (B.isSection())
535     return false;
536 
537   if (Config->Discard == DiscardPolicy::None)
538     return true;
539 
540   // In ELF assembly .L symbols are normally discarded by the assembler.
541   // If the assembler fails to do so, the linker discards them if
542   // * --discard-locals is used.
543   // * The symbol is in a SHF_MERGE section, which is normally the reason for
544   //   the assembler keeping the .L symbol.
545   if (!SymName.startswith(".L") && !SymName.empty())
546     return true;
547 
548   if (Config->Discard == DiscardPolicy::Locals)
549     return false;
550 
551   return !Sec || !(Sec->Flags & SHF_MERGE);
552 }
553 
554 static bool includeInSymtab(const Symbol &B) {
555   if (!B.isLocal() && !B.IsUsedInRegularObj)
556     return false;
557 
558   if (auto *D = dyn_cast<Defined>(&B)) {
559     // Always include absolute symbols.
560     SectionBase *Sec = D->Section;
561     if (!Sec)
562       return true;
563     Sec = Sec->Repl;
564 
565     // Exclude symbols pointing to garbage-collected sections.
566     if (isa<InputSectionBase>(Sec) && !Sec->Live)
567       return false;
568 
569     if (auto *S = dyn_cast<MergeInputSection>(Sec))
570       if (!S->getSectionPiece(D->Value)->Live)
571         return false;
572     return true;
573   }
574   return B.Used;
575 }
576 
577 // Local symbols are not in the linker's symbol table. This function scans
578 // each object file's symbol table to copy local symbols to the output.
579 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
580   if (!In.SymTab)
581     return;
582   for (InputFile *File : ObjectFiles) {
583     ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
584     for (Symbol *B : F->getLocalSymbols()) {
585       if (!B->isLocal())
586         fatal(toString(F) +
587               ": broken object: getLocalSymbols returns a non-local symbol");
588       auto *DR = dyn_cast<Defined>(B);
589 
590       // No reason to keep local undefined symbol in symtab.
591       if (!DR)
592         continue;
593       if (!includeInSymtab(*B))
594         continue;
595 
596       SectionBase *Sec = DR->Section;
597       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
598         continue;
599       In.SymTab->addSymbol(B);
600     }
601   }
602 }
603 
604 // Create a section symbol for each output section so that we can represent
605 // relocations that point to the section. If we know that no relocation is
606 // referring to a section (that happens if the section is a synthetic one), we
607 // don't create a section symbol for that section.
608 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
609   for (BaseCommand *Base : Script->SectionCommands) {
610     auto *Sec = dyn_cast<OutputSection>(Base);
611     if (!Sec)
612       continue;
613     auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
614       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
615         return !ISD->Sections.empty();
616       return false;
617     });
618     if (I == Sec->SectionCommands.end())
619       continue;
620     InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
621 
622     // Relocations are not using REL[A] section symbols.
623     if (IS->Type == SHT_REL || IS->Type == SHT_RELA)
624       continue;
625 
626     // Unlike other synthetic sections, mergeable output sections contain data
627     // copied from input sections, and there may be a relocation pointing to its
628     // contents if -r or -emit-reloc are given.
629     if (isa<SyntheticSection>(IS) && !(IS->Flags & SHF_MERGE))
630       continue;
631 
632     auto *Sym =
633         make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
634                       /*Value=*/0, /*Size=*/0, IS);
635     In.SymTab->addSymbol(Sym);
636   }
637 }
638 
639 // Today's loaders have a feature to make segments read-only after
640 // processing dynamic relocations to enhance security. PT_GNU_RELRO
641 // is defined for that.
642 //
643 // This function returns true if a section needs to be put into a
644 // PT_GNU_RELRO segment.
645 static bool isRelroSection(const OutputSection *Sec) {
646   if (!Config->ZRelro)
647     return false;
648 
649   uint64_t Flags = Sec->Flags;
650 
651   // Non-allocatable or non-writable sections don't need RELRO because
652   // they are not writable or not even mapped to memory in the first place.
653   // RELRO is for sections that are essentially read-only but need to
654   // be writable only at process startup to allow dynamic linker to
655   // apply relocations.
656   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
657     return false;
658 
659   // Once initialized, TLS data segments are used as data templates
660   // for a thread-local storage. For each new thread, runtime
661   // allocates memory for a TLS and copy templates there. No thread
662   // are supposed to use templates directly. Thus, it can be in RELRO.
663   if (Flags & SHF_TLS)
664     return true;
665 
666   // .init_array, .preinit_array and .fini_array contain pointers to
667   // functions that are executed on process startup or exit. These
668   // pointers are set by the static linker, and they are not expected
669   // to change at runtime. But if you are an attacker, you could do
670   // interesting things by manipulating pointers in .fini_array, for
671   // example. So they are put into RELRO.
672   uint32_t Type = Sec->Type;
673   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
674       Type == SHT_PREINIT_ARRAY)
675     return true;
676 
677   // .got contains pointers to external symbols. They are resolved by
678   // the dynamic linker when a module is loaded into memory, and after
679   // that they are not expected to change. So, it can be in RELRO.
680   if (In.Got && Sec == In.Got->getParent())
681     return true;
682 
683   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
684   // through r2 register, which is reserved for that purpose. Since r2 is used
685   // for accessing .got as well, .got and .toc need to be close enough in the
686   // virtual address space. Usually, .toc comes just after .got. Since we place
687   // .got into RELRO, .toc needs to be placed into RELRO too.
688   if (Sec->Name.equals(".toc"))
689     return true;
690 
691   // .got.plt contains pointers to external function symbols. They are
692   // by default resolved lazily, so we usually cannot put it into RELRO.
693   // However, if "-z now" is given, the lazy symbol resolution is
694   // disabled, which enables us to put it into RELRO.
695   if (Sec == In.GotPlt->getParent())
696     return Config->ZNow;
697 
698   // .dynamic section contains data for the dynamic linker, and
699   // there's no need to write to it at runtime, so it's better to put
700   // it into RELRO.
701   if (Sec == In.Dynamic->getParent())
702     return true;
703 
704   // Sections with some special names are put into RELRO. This is a
705   // bit unfortunate because section names shouldn't be significant in
706   // ELF in spirit. But in reality many linker features depend on
707   // magic section names.
708   StringRef S = Sec->Name;
709   return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" ||
710          S == ".dtors" || S == ".jcr" || S == ".eh_frame" ||
711          S == ".openbsd.randomdata";
712 }
713 
714 // We compute a rank for each section. The rank indicates where the
715 // section should be placed in the file.  Instead of using simple
716 // numbers (0,1,2...), we use a series of flags. One for each decision
717 // point when placing the section.
718 // Using flags has two key properties:
719 // * It is easy to check if a give branch was taken.
720 // * It is easy two see how similar two ranks are (see getRankProximity).
721 enum RankFlags {
722   RF_NOT_ADDR_SET = 1 << 18,
723   RF_NOT_INTERP = 1 << 17,
724   RF_NOT_ALLOC = 1 << 16,
725   RF_WRITE = 1 << 15,
726   RF_EXEC_WRITE = 1 << 14,
727   RF_EXEC = 1 << 13,
728   RF_RODATA = 1 << 12,
729   RF_NON_TLS_BSS = 1 << 11,
730   RF_NON_TLS_BSS_RO = 1 << 10,
731   RF_NOT_TLS = 1 << 9,
732   RF_BSS = 1 << 8,
733   RF_NOTE = 1 << 7,
734   RF_PPC_NOT_TOCBSS = 1 << 6,
735   RF_PPC_TOCL = 1 << 5,
736   RF_PPC_TOC = 1 << 4,
737   RF_PPC_GOT = 1 << 3,
738   RF_PPC_BRANCH_LT = 1 << 2,
739   RF_MIPS_GPREL = 1 << 1,
740   RF_MIPS_NOT_GOT = 1 << 0
741 };
742 
743 static unsigned getSectionRank(const OutputSection *Sec) {
744   unsigned Rank = 0;
745 
746   // We want to put section specified by -T option first, so we
747   // can start assigning VA starting from them later.
748   if (Config->SectionStartMap.count(Sec->Name))
749     return Rank;
750   Rank |= RF_NOT_ADDR_SET;
751 
752   // Put .interp first because some loaders want to see that section
753   // on the first page of the executable file when loaded into memory.
754   if (Sec->Name == ".interp")
755     return Rank;
756   Rank |= RF_NOT_INTERP;
757 
758   // Allocatable sections go first to reduce the total PT_LOAD size and
759   // so debug info doesn't change addresses in actual code.
760   if (!(Sec->Flags & SHF_ALLOC))
761     return Rank | RF_NOT_ALLOC;
762 
763   // Sort sections based on their access permission in the following
764   // order: R, RX, RWX, RW.  This order is based on the following
765   // considerations:
766   // * Read-only sections come first such that they go in the
767   //   PT_LOAD covering the program headers at the start of the file.
768   // * Read-only, executable sections come next.
769   // * Writable, executable sections follow such that .plt on
770   //   architectures where it needs to be writable will be placed
771   //   between .text and .data.
772   // * Writable sections come last, such that .bss lands at the very
773   //   end of the last PT_LOAD.
774   bool IsExec = Sec->Flags & SHF_EXECINSTR;
775   bool IsWrite = Sec->Flags & SHF_WRITE;
776 
777   if (IsExec) {
778     if (IsWrite)
779       Rank |= RF_EXEC_WRITE;
780     else
781       Rank |= RF_EXEC;
782   } else if (IsWrite) {
783     Rank |= RF_WRITE;
784   } else if (Sec->Type == SHT_PROGBITS) {
785     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
786     // .eh_frame) closer to .text. They likely contain PC or GOT relative
787     // relocations and there could be relocation overflow if other huge sections
788     // (.dynstr .dynsym) were placed in between.
789     Rank |= RF_RODATA;
790   }
791 
792   // If we got here we know that both A and B are in the same PT_LOAD.
793 
794   bool IsTls = Sec->Flags & SHF_TLS;
795   bool IsNoBits = Sec->Type == SHT_NOBITS;
796 
797   // The first requirement we have is to put (non-TLS) nobits sections last. The
798   // reason is that the only thing the dynamic linker will see about them is a
799   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
800   // PT_LOAD, so that has to correspond to the nobits sections.
801   bool IsNonTlsNoBits = IsNoBits && !IsTls;
802   if (IsNonTlsNoBits)
803     Rank |= RF_NON_TLS_BSS;
804 
805   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
806   // sections after r/w ones, so that the RelRo sections are contiguous.
807   bool IsRelRo = isRelroSection(Sec);
808   if (IsNonTlsNoBits && !IsRelRo)
809     Rank |= RF_NON_TLS_BSS_RO;
810   if (!IsNonTlsNoBits && IsRelRo)
811     Rank |= RF_NON_TLS_BSS_RO;
812 
813   // The TLS initialization block needs to be a single contiguous block in a R/W
814   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
815   // sections. The TLS NOBITS sections are placed here as they don't take up
816   // virtual address space in the PT_LOAD.
817   if (!IsTls)
818     Rank |= RF_NOT_TLS;
819 
820   // Within the TLS initialization block, the non-nobits sections need to appear
821   // first.
822   if (IsNoBits)
823     Rank |= RF_BSS;
824 
825   // We create a NOTE segment for contiguous .note sections, so make
826   // them contigous if there are more than one .note section with the
827   // same attributes.
828   if (Sec->Type == SHT_NOTE)
829     Rank |= RF_NOTE;
830 
831   // Some architectures have additional ordering restrictions for sections
832   // within the same PT_LOAD.
833   if (Config->EMachine == EM_PPC64) {
834     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
835     // that we would like to make sure appear is a specific order to maximize
836     // their coverage by a single signed 16-bit offset from the TOC base
837     // pointer. Conversely, the special .tocbss section should be first among
838     // all SHT_NOBITS sections. This will put it next to the loaded special
839     // PPC64 sections (and, thus, within reach of the TOC base pointer).
840     StringRef Name = Sec->Name;
841     if (Name != ".tocbss")
842       Rank |= RF_PPC_NOT_TOCBSS;
843 
844     if (Name == ".toc1")
845       Rank |= RF_PPC_TOCL;
846 
847     if (Name == ".toc")
848       Rank |= RF_PPC_TOC;
849 
850     if (Name == ".got")
851       Rank |= RF_PPC_GOT;
852 
853     if (Name == ".branch_lt")
854       Rank |= RF_PPC_BRANCH_LT;
855   }
856 
857   if (Config->EMachine == EM_MIPS) {
858     // All sections with SHF_MIPS_GPREL flag should be grouped together
859     // because data in these sections is addressable with a gp relative address.
860     if (Sec->Flags & SHF_MIPS_GPREL)
861       Rank |= RF_MIPS_GPREL;
862 
863     if (Sec->Name != ".got")
864       Rank |= RF_MIPS_NOT_GOT;
865   }
866 
867   return Rank;
868 }
869 
870 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
871   const OutputSection *A = cast<OutputSection>(ACmd);
872   const OutputSection *B = cast<OutputSection>(BCmd);
873 
874   if (A->SortRank != B->SortRank)
875     return A->SortRank < B->SortRank;
876 
877   if (!(A->SortRank & RF_NOT_ADDR_SET))
878     return Config->SectionStartMap.lookup(A->Name) <
879            Config->SectionStartMap.lookup(B->Name);
880   return false;
881 }
882 
883 void PhdrEntry::add(OutputSection *Sec) {
884   LastSec = Sec;
885   if (!FirstSec)
886     FirstSec = Sec;
887   p_align = std::max(p_align, Sec->Alignment);
888   if (p_type == PT_LOAD)
889     Sec->PtLoad = this;
890 }
891 
892 // The beginning and the ending of .rel[a].plt section are marked
893 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
894 // executable. The runtime needs these symbols in order to resolve
895 // all IRELATIVE relocs on startup. For dynamic executables, we don't
896 // need these symbols, since IRELATIVE relocs are resolved through GOT
897 // and PLT. For details, see http://www.airs.com/blog/archives/403.
898 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
899   if (Config->Relocatable || needsInterpSection())
900     return;
901   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
902   addOptionalRegular(S, In.RelaIplt, 0, STV_HIDDEN, STB_WEAK);
903 
904   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
905   ElfSym::RelaIpltEnd =
906       addOptionalRegular(S, In.RelaIplt, 0, STV_HIDDEN, STB_WEAK);
907 }
908 
909 template <class ELFT>
910 void Writer<ELFT>::forEachRelSec(
911     llvm::function_ref<void(InputSectionBase &)> Fn) {
912   // Scan all relocations. Each relocation goes through a series
913   // of tests to determine if it needs special treatment, such as
914   // creating GOT, PLT, copy relocations, etc.
915   // Note that relocations for non-alloc sections are directly
916   // processed by InputSection::relocateNonAlloc.
917   for (InputSectionBase *IS : InputSections)
918     if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
919       Fn(*IS);
920   for (EhInputSection *ES : In.EhFrame->Sections)
921     Fn(*ES);
922 }
923 
924 // This function generates assignments for predefined symbols (e.g. _end or
925 // _etext) and inserts them into the commands sequence to be processed at the
926 // appropriate time. This ensures that the value is going to be correct by the
927 // time any references to these symbols are processed and is equivalent to
928 // defining these symbols explicitly in the linker script.
929 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
930   if (ElfSym::GlobalOffsetTable) {
931     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
932     // to the start of the .got or .got.plt section.
933     InputSection *GotSection = In.GotPlt;
934     if (!Target->GotBaseSymInGotPlt)
935       GotSection = In.MipsGot ? cast<InputSection>(In.MipsGot)
936                               : cast<InputSection>(In.Got);
937     ElfSym::GlobalOffsetTable->Section = GotSection;
938   }
939 
940   if (ElfSym::RelaIpltEnd)
941     ElfSym::RelaIpltEnd->Value = In.RelaIplt->getSize();
942 
943   PhdrEntry *Last = nullptr;
944   PhdrEntry *LastRO = nullptr;
945 
946   for (PhdrEntry *P : Phdrs) {
947     if (P->p_type != PT_LOAD)
948       continue;
949     Last = P;
950     if (!(P->p_flags & PF_W))
951       LastRO = P;
952   }
953 
954   if (LastRO) {
955     // _etext is the first location after the last read-only loadable segment.
956     if (ElfSym::Etext1)
957       ElfSym::Etext1->Section = LastRO->LastSec;
958     if (ElfSym::Etext2)
959       ElfSym::Etext2->Section = LastRO->LastSec;
960   }
961 
962   if (Last) {
963     // _edata points to the end of the last mapped initialized section.
964     OutputSection *Edata = nullptr;
965     for (OutputSection *OS : OutputSections) {
966       if (OS->Type != SHT_NOBITS)
967         Edata = OS;
968       if (OS == Last->LastSec)
969         break;
970     }
971 
972     if (ElfSym::Edata1)
973       ElfSym::Edata1->Section = Edata;
974     if (ElfSym::Edata2)
975       ElfSym::Edata2->Section = Edata;
976 
977     // _end is the first location after the uninitialized data region.
978     if (ElfSym::End1)
979       ElfSym::End1->Section = Last->LastSec;
980     if (ElfSym::End2)
981       ElfSym::End2->Section = Last->LastSec;
982   }
983 
984   if (ElfSym::Bss)
985     ElfSym::Bss->Section = findSection(".bss");
986 
987   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
988   // be equal to the _gp symbol's value.
989   if (ElfSym::MipsGp) {
990     // Find GP-relative section with the lowest address
991     // and use this address to calculate default _gp value.
992     for (OutputSection *OS : OutputSections) {
993       if (OS->Flags & SHF_MIPS_GPREL) {
994         ElfSym::MipsGp->Section = OS;
995         ElfSym::MipsGp->Value = 0x7ff0;
996         break;
997       }
998     }
999   }
1000 }
1001 
1002 // We want to find how similar two ranks are.
1003 // The more branches in getSectionRank that match, the more similar they are.
1004 // Since each branch corresponds to a bit flag, we can just use
1005 // countLeadingZeros.
1006 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
1007   return countLeadingZeros(A->SortRank ^ B->SortRank);
1008 }
1009 
1010 static int getRankProximity(OutputSection *A, BaseCommand *B) {
1011   if (auto *Sec = dyn_cast<OutputSection>(B))
1012     return getRankProximityAux(A, Sec);
1013   return -1;
1014 }
1015 
1016 // When placing orphan sections, we want to place them after symbol assignments
1017 // so that an orphan after
1018 //   begin_foo = .;
1019 //   foo : { *(foo) }
1020 //   end_foo = .;
1021 // doesn't break the intended meaning of the begin/end symbols.
1022 // We don't want to go over sections since findOrphanPos is the
1023 // one in charge of deciding the order of the sections.
1024 // We don't want to go over changes to '.', since doing so in
1025 //  rx_sec : { *(rx_sec) }
1026 //  . = ALIGN(0x1000);
1027 //  /* The RW PT_LOAD starts here*/
1028 //  rw_sec : { *(rw_sec) }
1029 // would mean that the RW PT_LOAD would become unaligned.
1030 static bool shouldSkip(BaseCommand *Cmd) {
1031   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
1032     return Assign->Name != ".";
1033   return false;
1034 }
1035 
1036 // We want to place orphan sections so that they share as much
1037 // characteristics with their neighbors as possible. For example, if
1038 // both are rw, or both are tls.
1039 template <typename ELFT>
1040 static std::vector<BaseCommand *>::iterator
1041 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1042               std::vector<BaseCommand *>::iterator E) {
1043   OutputSection *Sec = cast<OutputSection>(*E);
1044 
1045   // Find the first element that has as close a rank as possible.
1046   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1047     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1048   });
1049   if (I == E)
1050     return E;
1051 
1052   // Consider all existing sections with the same proximity.
1053   int Proximity = getRankProximity(Sec, *I);
1054   for (; I != E; ++I) {
1055     auto *CurSec = dyn_cast<OutputSection>(*I);
1056     if (!CurSec)
1057       continue;
1058     if (getRankProximity(Sec, CurSec) != Proximity ||
1059         Sec->SortRank < CurSec->SortRank)
1060       break;
1061   }
1062 
1063   auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); };
1064   auto J = std::find_if(llvm::make_reverse_iterator(I),
1065                         llvm::make_reverse_iterator(B), IsOutputSec);
1066   I = J.base();
1067 
1068   // As a special case, if the orphan section is the last section, put
1069   // it at the very end, past any other commands.
1070   // This matches bfd's behavior and is convenient when the linker script fully
1071   // specifies the start of the file, but doesn't care about the end (the non
1072   // alloc sections for example).
1073   auto NextSec = std::find_if(I, E, IsOutputSec);
1074   if (NextSec == E)
1075     return E;
1076 
1077   while (I != E && shouldSkip(*I))
1078     ++I;
1079   return I;
1080 }
1081 
1082 // Builds section order for handling --symbol-ordering-file.
1083 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1084   DenseMap<const InputSectionBase *, int> SectionOrder;
1085   // Use the rarely used option -call-graph-ordering-file to sort sections.
1086   if (!Config->CallGraphProfile.empty())
1087     return computeCallGraphProfileOrder();
1088 
1089   if (Config->SymbolOrderingFile.empty())
1090     return SectionOrder;
1091 
1092   struct SymbolOrderEntry {
1093     int Priority;
1094     bool Present;
1095   };
1096 
1097   // Build a map from symbols to their priorities. Symbols that didn't
1098   // appear in the symbol ordering file have the lowest priority 0.
1099   // All explicitly mentioned symbols have negative (higher) priorities.
1100   DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1101   int Priority = -Config->SymbolOrderingFile.size();
1102   for (StringRef S : Config->SymbolOrderingFile)
1103     SymbolOrder.insert({S, {Priority++, false}});
1104 
1105   // Build a map from sections to their priorities.
1106   auto AddSym = [&](Symbol &Sym) {
1107     auto It = SymbolOrder.find(Sym.getName());
1108     if (It == SymbolOrder.end())
1109       return;
1110     SymbolOrderEntry &Ent = It->second;
1111     Ent.Present = true;
1112 
1113     maybeWarnUnorderableSymbol(&Sym);
1114 
1115     if (auto *D = dyn_cast<Defined>(&Sym)) {
1116       if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1117         int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1118         Priority = std::min(Priority, Ent.Priority);
1119       }
1120     }
1121   };
1122 
1123   // We want both global and local symbols. We get the global ones from the
1124   // symbol table and iterate the object files for the local ones.
1125   for (Symbol *Sym : Symtab->getSymbols())
1126     if (!Sym->isLazy())
1127       AddSym(*Sym);
1128   for (InputFile *File : ObjectFiles)
1129     for (Symbol *Sym : File->getSymbols())
1130       if (Sym->isLocal())
1131         AddSym(*Sym);
1132 
1133   if (Config->WarnSymbolOrdering)
1134     for (auto OrderEntry : SymbolOrder)
1135       if (!OrderEntry.second.Present)
1136         warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1137 
1138   return SectionOrder;
1139 }
1140 
1141 // Sorts the sections in ISD according to the provided section order.
1142 static void
1143 sortISDBySectionOrder(InputSectionDescription *ISD,
1144                       const DenseMap<const InputSectionBase *, int> &Order) {
1145   std::vector<InputSection *> UnorderedSections;
1146   std::vector<std::pair<InputSection *, int>> OrderedSections;
1147   uint64_t UnorderedSize = 0;
1148 
1149   for (InputSection *IS : ISD->Sections) {
1150     auto I = Order.find(IS);
1151     if (I == Order.end()) {
1152       UnorderedSections.push_back(IS);
1153       UnorderedSize += IS->getSize();
1154       continue;
1155     }
1156     OrderedSections.push_back({IS, I->second});
1157   }
1158   llvm::sort(OrderedSections, [&](std::pair<InputSection *, int> A,
1159                                   std::pair<InputSection *, int> B) {
1160     return A.second < B.second;
1161   });
1162 
1163   // Find an insertion point for the ordered section list in the unordered
1164   // section list. On targets with limited-range branches, this is the mid-point
1165   // of the unordered section list. This decreases the likelihood that a range
1166   // extension thunk will be needed to enter or exit the ordered region. If the
1167   // ordered section list is a list of hot functions, we can generally expect
1168   // the ordered functions to be called more often than the unordered functions,
1169   // making it more likely that any particular call will be within range, and
1170   // therefore reducing the number of thunks required.
1171   //
1172   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1173   // If the layout is:
1174   //
1175   // 8MB hot
1176   // 32MB cold
1177   //
1178   // only the first 8-16MB of the cold code (depending on which hot function it
1179   // is actually calling) can call the hot code without a range extension thunk.
1180   // However, if we use this layout:
1181   //
1182   // 16MB cold
1183   // 8MB hot
1184   // 16MB cold
1185   //
1186   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1187   // of the second block of cold code can call the hot code without a thunk. So
1188   // we effectively double the amount of code that could potentially call into
1189   // the hot code without a thunk.
1190   size_t InsPt = 0;
1191   if (Target->getThunkSectionSpacing() && !OrderedSections.empty()) {
1192     uint64_t UnorderedPos = 0;
1193     for (; InsPt != UnorderedSections.size(); ++InsPt) {
1194       UnorderedPos += UnorderedSections[InsPt]->getSize();
1195       if (UnorderedPos > UnorderedSize / 2)
1196         break;
1197     }
1198   }
1199 
1200   ISD->Sections.clear();
1201   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1202     ISD->Sections.push_back(IS);
1203   for (std::pair<InputSection *, int> P : OrderedSections)
1204     ISD->Sections.push_back(P.first);
1205   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1206     ISD->Sections.push_back(IS);
1207 }
1208 
1209 static void sortSection(OutputSection *Sec,
1210                         const DenseMap<const InputSectionBase *, int> &Order) {
1211   StringRef Name = Sec->Name;
1212 
1213   // Sort input sections by section name suffixes for
1214   // __attribute__((init_priority(N))).
1215   if (Name == ".init_array" || Name == ".fini_array") {
1216     if (!Script->HasSectionsCommand)
1217       Sec->sortInitFini();
1218     return;
1219   }
1220 
1221   // Sort input sections by the special rule for .ctors and .dtors.
1222   if (Name == ".ctors" || Name == ".dtors") {
1223     if (!Script->HasSectionsCommand)
1224       Sec->sortCtorsDtors();
1225     return;
1226   }
1227 
1228   // Never sort these.
1229   if (Name == ".init" || Name == ".fini")
1230     return;
1231 
1232   // Sort input sections by priority using the list provided
1233   // by --symbol-ordering-file.
1234   if (!Order.empty())
1235     for (BaseCommand *B : Sec->SectionCommands)
1236       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1237         sortISDBySectionOrder(ISD, Order);
1238 }
1239 
1240 // If no layout was provided by linker script, we want to apply default
1241 // sorting for special input sections. This also handles --symbol-ordering-file.
1242 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1243   // Build the order once since it is expensive.
1244   DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1245   for (BaseCommand *Base : Script->SectionCommands)
1246     if (auto *Sec = dyn_cast<OutputSection>(Base))
1247       sortSection(Sec, Order);
1248 }
1249 
1250 template <class ELFT> void Writer<ELFT>::sortSections() {
1251   Script->adjustSectionsBeforeSorting();
1252 
1253   // Don't sort if using -r. It is not necessary and we want to preserve the
1254   // relative order for SHF_LINK_ORDER sections.
1255   if (Config->Relocatable)
1256     return;
1257 
1258   sortInputSections();
1259 
1260   for (BaseCommand *Base : Script->SectionCommands) {
1261     auto *OS = dyn_cast<OutputSection>(Base);
1262     if (!OS)
1263       continue;
1264     OS->SortRank = getSectionRank(OS);
1265 
1266     // We want to assign rude approximation values to OutSecOff fields
1267     // to know the relative order of the input sections. We use it for
1268     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1269     uint64_t I = 0;
1270     for (InputSection *Sec : getInputSections(OS))
1271       Sec->OutSecOff = I++;
1272   }
1273 
1274   if (!Script->HasSectionsCommand) {
1275     // We know that all the OutputSections are contiguous in this case.
1276     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1277     std::stable_sort(
1278         llvm::find_if(Script->SectionCommands, IsSection),
1279         llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1280         compareSections);
1281     return;
1282   }
1283 
1284   // Orphan sections are sections present in the input files which are
1285   // not explicitly placed into the output file by the linker script.
1286   //
1287   // The sections in the linker script are already in the correct
1288   // order. We have to figuere out where to insert the orphan
1289   // sections.
1290   //
1291   // The order of the sections in the script is arbitrary and may not agree with
1292   // compareSections. This means that we cannot easily define a strict weak
1293   // ordering. To see why, consider a comparison of a section in the script and
1294   // one not in the script. We have a two simple options:
1295   // * Make them equivalent (a is not less than b, and b is not less than a).
1296   //   The problem is then that equivalence has to be transitive and we can
1297   //   have sections a, b and c with only b in a script and a less than c
1298   //   which breaks this property.
1299   // * Use compareSectionsNonScript. Given that the script order doesn't have
1300   //   to match, we can end up with sections a, b, c, d where b and c are in the
1301   //   script and c is compareSectionsNonScript less than b. In which case d
1302   //   can be equivalent to c, a to b and d < a. As a concrete example:
1303   //   .a (rx) # not in script
1304   //   .b (rx) # in script
1305   //   .c (ro) # in script
1306   //   .d (ro) # not in script
1307   //
1308   // The way we define an order then is:
1309   // *  Sort only the orphan sections. They are in the end right now.
1310   // *  Move each orphan section to its preferred position. We try
1311   //    to put each section in the last position where it can share
1312   //    a PT_LOAD.
1313   //
1314   // There is some ambiguity as to where exactly a new entry should be
1315   // inserted, because Commands contains not only output section
1316   // commands but also other types of commands such as symbol assignment
1317   // expressions. There's no correct answer here due to the lack of the
1318   // formal specification of the linker script. We use heuristics to
1319   // determine whether a new output command should be added before or
1320   // after another commands. For the details, look at shouldSkip
1321   // function.
1322 
1323   auto I = Script->SectionCommands.begin();
1324   auto E = Script->SectionCommands.end();
1325   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1326     if (auto *Sec = dyn_cast<OutputSection>(Base))
1327       return Sec->SectionIndex == UINT32_MAX;
1328     return false;
1329   });
1330 
1331   // Sort the orphan sections.
1332   std::stable_sort(NonScriptI, E, compareSections);
1333 
1334   // As a horrible special case, skip the first . assignment if it is before any
1335   // section. We do this because it is common to set a load address by starting
1336   // the script with ". = 0xabcd" and the expectation is that every section is
1337   // after that.
1338   auto FirstSectionOrDotAssignment =
1339       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1340   if (FirstSectionOrDotAssignment != E &&
1341       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1342     ++FirstSectionOrDotAssignment;
1343   I = FirstSectionOrDotAssignment;
1344 
1345   while (NonScriptI != E) {
1346     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1347     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1348 
1349     // As an optimization, find all sections with the same sort rank
1350     // and insert them with one rotate.
1351     unsigned Rank = Orphan->SortRank;
1352     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1353       return cast<OutputSection>(Cmd)->SortRank != Rank;
1354     });
1355     std::rotate(Pos, NonScriptI, End);
1356     NonScriptI = End;
1357   }
1358 
1359   Script->adjustSectionsAfterSorting();
1360 }
1361 
1362 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1363   // Synthetic, i. e. a sentinel section, should go last.
1364   if (A->kind() == InputSectionBase::Synthetic ||
1365       B->kind() == InputSectionBase::Synthetic)
1366     return A->kind() != InputSectionBase::Synthetic;
1367 
1368   InputSection *LA = A->getLinkOrderDep();
1369   InputSection *LB = B->getLinkOrderDep();
1370   OutputSection *AOut = LA->getParent();
1371   OutputSection *BOut = LB->getParent();
1372 
1373   if (AOut != BOut)
1374     return AOut->SectionIndex < BOut->SectionIndex;
1375   return LA->OutSecOff < LB->OutSecOff;
1376 }
1377 
1378 // This function is used by the --merge-exidx-entries to detect duplicate
1379 // .ARM.exidx sections. It is Arm only.
1380 //
1381 // The .ARM.exidx section is of the form:
1382 // | PREL31 offset to function | Unwind instructions for function |
1383 // where the unwind instructions are either a small number of unwind
1384 // instructions inlined into the table entry, the special CANT_UNWIND value of
1385 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1386 // instructions.
1387 //
1388 // We return true if all the unwind instructions in the .ARM.exidx entries of
1389 // Cur can be merged into the last entry of Prev.
1390 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1391 
1392   // References to .ARM.Extab Sections have bit 31 clear and are not the
1393   // special EXIDX_CANTUNWIND bit-pattern.
1394   auto IsExtabRef = [](uint32_t Unwind) {
1395     return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1396   };
1397 
1398   struct ExidxEntry {
1399     ulittle32_t Fn;
1400     ulittle32_t Unwind;
1401   };
1402 
1403   // Get the last table Entry from the previous .ARM.exidx section.
1404   const ExidxEntry &PrevEntry = Prev->getDataAs<ExidxEntry>().back();
1405   if (IsExtabRef(PrevEntry.Unwind))
1406     return false;
1407 
1408   // We consider the unwind instructions of an .ARM.exidx table entry
1409   // a duplicate if the previous unwind instructions if:
1410   // - Both are the special EXIDX_CANTUNWIND.
1411   // - Both are the same inline unwind instructions.
1412   // We do not attempt to follow and check links into .ARM.extab tables as
1413   // consecutive identical entries are rare and the effort to check that they
1414   // are identical is high.
1415 
1416   for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>())
1417     if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1418       return false;
1419 
1420   // All table entries in this .ARM.exidx Section can be merged into the
1421   // previous Section.
1422   return true;
1423 }
1424 
1425 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1426   for (OutputSection *Sec : OutputSections) {
1427     if (!(Sec->Flags & SHF_LINK_ORDER))
1428       continue;
1429 
1430     // Link order may be distributed across several InputSectionDescriptions
1431     // but sort must consider them all at once.
1432     std::vector<InputSection **> ScriptSections;
1433     std::vector<InputSection *> Sections;
1434     for (BaseCommand *Base : Sec->SectionCommands) {
1435       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1436         for (InputSection *&IS : ISD->Sections) {
1437           ScriptSections.push_back(&IS);
1438           Sections.push_back(IS);
1439         }
1440       }
1441     }
1442     std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1443 
1444     if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1445         Sec->Type == SHT_ARM_EXIDX) {
1446 
1447       if (auto *Sentinel = dyn_cast<ARMExidxSentinelSection>(Sections.back())) {
1448         assert(Sections.size() >= 2 &&
1449                "We should create a sentinel section only if there are "
1450                "alive regular exidx sections.");
1451 
1452         // The last executable section is required to fill the sentinel.
1453         // Remember it here so that we don't have to find it again.
1454         Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1455       }
1456 
1457       // The EHABI for the Arm Architecture permits consecutive identical
1458       // table entries to be merged. We use a simple implementation that
1459       // removes a .ARM.exidx Input Section if it can be merged into the
1460       // previous one. This does not require any rewriting of InputSection
1461       // contents but misses opportunities for fine grained deduplication
1462       // where only a subset of the InputSection contents can be merged.
1463       if (Config->MergeArmExidx) {
1464         size_t Prev = 0;
1465         // The last one is a sentinel entry which should not be removed.
1466         for (size_t I = 1; I < Sections.size() - 1; ++I) {
1467           if (isDuplicateArmExidxSec(Sections[Prev], Sections[I]))
1468             Sections[I] = nullptr;
1469           else
1470             Prev = I;
1471         }
1472       }
1473     }
1474 
1475     for (int I = 0, N = Sections.size(); I < N; ++I)
1476       *ScriptSections[I] = Sections[I];
1477 
1478     // Remove the Sections we marked as duplicate earlier.
1479     for (BaseCommand *Base : Sec->SectionCommands)
1480       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1481         llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; });
1482   }
1483 }
1484 
1485 // For most RISC ISAs, we need to generate content that depends on the address
1486 // of InputSections. For example some architectures such as AArch64 use small
1487 // displacements for jump instructions that is the linker's responsibility for
1488 // creating range extension thunks for. As the generation of the content may
1489 // also alter InputSection addresses we must converge to a fixed point.
1490 template <class ELFT> void Writer<ELFT>::maybeAddThunks() {
1491   if (!Target->NeedsThunks && !Config->AndroidPackDynRelocs &&
1492       !Config->RelrPackDynRelocs)
1493     return;
1494 
1495   ThunkCreator TC;
1496   AArch64Err843419Patcher A64P;
1497 
1498   for (;;) {
1499     bool Changed = false;
1500 
1501     Script->assignAddresses();
1502 
1503     if (Target->NeedsThunks)
1504       Changed |= TC.createThunks(OutputSections);
1505 
1506     if (Config->FixCortexA53Errata843419) {
1507       if (Changed)
1508         Script->assignAddresses();
1509       Changed |= A64P.createFixes();
1510     }
1511 
1512     if (In.MipsGot)
1513       In.MipsGot->updateAllocSize();
1514 
1515     Changed |= In.RelaDyn->updateAllocSize();
1516 
1517     if (In.RelrDyn)
1518       Changed |= In.RelrDyn->updateAllocSize();
1519 
1520     if (!Changed)
1521       return;
1522   }
1523 }
1524 
1525 static void finalizeSynthetic(SyntheticSection *Sec) {
1526   if (Sec && !Sec->empty() && Sec->getParent())
1527     Sec->finalizeContents();
1528 }
1529 
1530 // In order to allow users to manipulate linker-synthesized sections,
1531 // we had to add synthetic sections to the input section list early,
1532 // even before we make decisions whether they are needed. This allows
1533 // users to write scripts like this: ".mygot : { .got }".
1534 //
1535 // Doing it has an unintended side effects. If it turns out that we
1536 // don't need a .got (for example) at all because there's no
1537 // relocation that needs a .got, we don't want to emit .got.
1538 //
1539 // To deal with the above problem, this function is called after
1540 // scanRelocations is called to remove synthetic sections that turn
1541 // out to be empty.
1542 static void removeUnusedSyntheticSections() {
1543   // All input synthetic sections that can be empty are placed after
1544   // all regular ones. We iterate over them all and exit at first
1545   // non-synthetic.
1546   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1547     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1548     if (!SS)
1549       return;
1550     OutputSection *OS = SS->getParent();
1551     if (!OS || !SS->empty())
1552       continue;
1553 
1554     // If we reach here, then SS is an unused synthetic section and we want to
1555     // remove it from corresponding input section description of output section.
1556     for (BaseCommand *B : OS->SectionCommands)
1557       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1558         llvm::erase_if(ISD->Sections,
1559                        [=](InputSection *IS) { return IS == SS; });
1560   }
1561 }
1562 
1563 // Returns true if a symbol can be replaced at load-time by a symbol
1564 // with the same name defined in other ELF executable or DSO.
1565 static bool computeIsPreemptible(const Symbol &B) {
1566   assert(!B.isLocal());
1567 
1568   // Only symbols that appear in dynsym can be preempted.
1569   if (!B.includeInDynsym())
1570     return false;
1571 
1572   // Only default visibility symbols can be preempted.
1573   if (B.Visibility != STV_DEFAULT)
1574     return false;
1575 
1576   // At this point copy relocations have not been created yet, so any
1577   // symbol that is not defined locally is preemptible.
1578   if (!B.isDefined())
1579     return true;
1580 
1581   // If we have a dynamic list it specifies which local symbols are preemptible.
1582   if (Config->HasDynamicList)
1583     return false;
1584 
1585   if (!Config->Shared)
1586     return false;
1587 
1588   // -Bsymbolic means that definitions are not preempted.
1589   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1590     return false;
1591   return true;
1592 }
1593 
1594 // Create output section objects and add them to OutputSections.
1595 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1596   Out::PreinitArray = findSection(".preinit_array");
1597   Out::InitArray = findSection(".init_array");
1598   Out::FiniArray = findSection(".fini_array");
1599 
1600   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1601   // symbols for sections, so that the runtime can get the start and end
1602   // addresses of each section by section name. Add such symbols.
1603   if (!Config->Relocatable) {
1604     addStartEndSymbols();
1605     for (BaseCommand *Base : Script->SectionCommands)
1606       if (auto *Sec = dyn_cast<OutputSection>(Base))
1607         addStartStopSymbols(Sec);
1608   }
1609 
1610   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1611   // It should be okay as no one seems to care about the type.
1612   // Even the author of gold doesn't remember why gold behaves that way.
1613   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1614   if (In.DynSymTab)
1615     Symtab->addDefined("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1616                        /*Size=*/0, STB_WEAK, In.Dynamic,
1617                        /*File=*/nullptr);
1618 
1619   // Define __rel[a]_iplt_{start,end} symbols if needed.
1620   addRelIpltSymbols();
1621 
1622   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1623   if (Config->EMachine == EM_RISCV)
1624     if (!dyn_cast_or_null<Defined>(Symtab->find("__global_pointer$")))
1625       addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800);
1626 
1627   // This responsible for splitting up .eh_frame section into
1628   // pieces. The relocation scan uses those pieces, so this has to be
1629   // earlier.
1630   finalizeSynthetic(In.EhFrame);
1631 
1632   for (Symbol *S : Symtab->getSymbols())
1633     if (!S->IsPreemptible)
1634       S->IsPreemptible = computeIsPreemptible(*S);
1635 
1636   // Scan relocations. This must be done after every symbol is declared so that
1637   // we can correctly decide if a dynamic relocation is needed.
1638   if (!Config->Relocatable)
1639     forEachRelSec(scanRelocations<ELFT>);
1640 
1641   if (In.Plt && !In.Plt->empty())
1642     In.Plt->addSymbols();
1643   if (In.Iplt && !In.Iplt->empty())
1644     In.Iplt->addSymbols();
1645 
1646   // Now that we have defined all possible global symbols including linker-
1647   // synthesized ones. Visit all symbols to give the finishing touches.
1648   for (Symbol *Sym : Symtab->getSymbols()) {
1649     if (!includeInSymtab(*Sym))
1650       continue;
1651     if (In.SymTab)
1652       In.SymTab->addSymbol(Sym);
1653 
1654     if (In.DynSymTab && Sym->includeInDynsym()) {
1655       In.DynSymTab->addSymbol(Sym);
1656       if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1657         if (File->IsNeeded && !Sym->isUndefined())
1658           InX<ELFT>::VerNeed->addSymbol(Sym);
1659     }
1660   }
1661 
1662   // Do not proceed if there was an undefined symbol.
1663   if (errorCount())
1664     return;
1665 
1666   if (In.MipsGot)
1667     In.MipsGot->build<ELFT>();
1668 
1669   removeUnusedSyntheticSections();
1670 
1671   sortSections();
1672 
1673   // Now that we have the final list, create a list of all the
1674   // OutputSections for convenience.
1675   for (BaseCommand *Base : Script->SectionCommands)
1676     if (auto *Sec = dyn_cast<OutputSection>(Base))
1677       OutputSections.push_back(Sec);
1678 
1679   // Prefer command line supplied address over other constraints.
1680   for (OutputSection *Sec : OutputSections) {
1681     auto I = Config->SectionStartMap.find(Sec->Name);
1682     if (I != Config->SectionStartMap.end())
1683       Sec->AddrExpr = [=] { return I->second; };
1684   }
1685 
1686   // This is a bit of a hack. A value of 0 means undef, so we set it
1687   // to 1 to make __ehdr_start defined. The section number is not
1688   // particularly relevant.
1689   Out::ElfHeader->SectionIndex = 1;
1690 
1691   for (size_t I = 0, E = OutputSections.size(); I != E; ++I) {
1692     OutputSection *Sec = OutputSections[I];
1693     Sec->SectionIndex = I + 1;
1694     Sec->ShName = In.ShStrTab->addString(Sec->Name);
1695   }
1696 
1697   // Binary and relocatable output does not have PHDRS.
1698   // The headers have to be created before finalize as that can influence the
1699   // image base and the dynamic section on mips includes the image base.
1700   if (!Config->Relocatable && !Config->OFormatBinary) {
1701     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1702     addPtArmExid(Phdrs);
1703     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1704 
1705     // Find the TLS segment. This happens before the section layout loop so that
1706     // Android relocation packing can look up TLS symbol addresses.
1707     for (PhdrEntry *P : Phdrs)
1708       if (P->p_type == PT_TLS)
1709         Out::TlsPhdr = P;
1710   }
1711 
1712   // Some symbols are defined in term of program headers. Now that we
1713   // have the headers, we can find out which sections they point to.
1714   setReservedSymbolSections();
1715 
1716   // Dynamic section must be the last one in this list and dynamic
1717   // symbol table section (DynSymTab) must be the first one.
1718   finalizeSynthetic(In.DynSymTab);
1719   finalizeSynthetic(In.Bss);
1720   finalizeSynthetic(In.BssRelRo);
1721   finalizeSynthetic(In.GnuHashTab);
1722   finalizeSynthetic(In.HashTab);
1723   finalizeSynthetic(In.SymTabShndx);
1724   finalizeSynthetic(In.ShStrTab);
1725   finalizeSynthetic(In.StrTab);
1726   finalizeSynthetic(In.VerDef);
1727   finalizeSynthetic(In.DynStrTab);
1728   finalizeSynthetic(In.Got);
1729   finalizeSynthetic(In.MipsGot);
1730   finalizeSynthetic(In.IgotPlt);
1731   finalizeSynthetic(In.GotPlt);
1732   finalizeSynthetic(In.RelaDyn);
1733   finalizeSynthetic(In.RelrDyn);
1734   finalizeSynthetic(In.RelaIplt);
1735   finalizeSynthetic(In.RelaPlt);
1736   finalizeSynthetic(In.Plt);
1737   finalizeSynthetic(In.Iplt);
1738   finalizeSynthetic(In.EhFrameHdr);
1739   finalizeSynthetic(InX<ELFT>::VerSym);
1740   finalizeSynthetic(InX<ELFT>::VerNeed);
1741   finalizeSynthetic(In.Dynamic);
1742 
1743   if (!Script->HasSectionsCommand && !Config->Relocatable)
1744     fixSectionAlignments();
1745 
1746   // After link order processing .ARM.exidx sections can be deduplicated, which
1747   // needs to be resolved before any other address dependent operation.
1748   resolveShfLinkOrder();
1749 
1750   // Jump instructions in many ISAs have small displacements, and therefore they
1751   // cannot jump to arbitrary addresses in memory. For example, RISC-V JAL
1752   // instruction can target only +-1 MiB from PC. It is a linker's
1753   // responsibility to create and insert small pieces of code between sections
1754   // to extend the ranges if jump targets are out of range. Such code pieces are
1755   // called "thunks".
1756   //
1757   // We add thunks at this stage. We couldn't do this before this point because
1758   // this is the earliest point where we know sizes of sections and their
1759   // layouts (that are needed to determine if jump targets are in range).
1760   maybeAddThunks();
1761 
1762   // maybeAddThunks may have added local symbols to the static symbol table.
1763   finalizeSynthetic(In.SymTab);
1764   finalizeSynthetic(In.PPC64LongBranchTarget);
1765 
1766   // Fill other section headers. The dynamic table is finalized
1767   // at the end because some tags like RELSZ depend on result
1768   // of finalizing other sections.
1769   for (OutputSection *Sec : OutputSections)
1770     Sec->finalize<ELFT>();
1771 }
1772 
1773 // Ensure data sections are not mixed with executable sections when
1774 // -execute-only is used. -execute-only is a feature to make pages executable
1775 // but not readable, and the feature is currently supported only on AArch64.
1776 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1777   if (!Config->ExecuteOnly)
1778     return;
1779 
1780   for (OutputSection *OS : OutputSections)
1781     if (OS->Flags & SHF_EXECINSTR)
1782       for (InputSection *IS : getInputSections(OS))
1783         if (!(IS->Flags & SHF_EXECINSTR))
1784           error("cannot place " + toString(IS) + " into " + toString(OS->Name) +
1785                 ": -execute-only does not support intermingling data and code");
1786 }
1787 
1788 // The linker is expected to define SECNAME_start and SECNAME_end
1789 // symbols for a few sections. This function defines them.
1790 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1791   // If a section does not exist, there's ambiguity as to how we
1792   // define _start and _end symbols for an init/fini section. Since
1793   // the loader assume that the symbols are always defined, we need to
1794   // always define them. But what value? The loader iterates over all
1795   // pointers between _start and _end to run global ctors/dtors, so if
1796   // the section is empty, their symbol values don't actually matter
1797   // as long as _start and _end point to the same location.
1798   //
1799   // That said, we don't want to set the symbols to 0 (which is
1800   // probably the simplest value) because that could cause some
1801   // program to fail to link due to relocation overflow, if their
1802   // program text is above 2 GiB. We use the address of the .text
1803   // section instead to prevent that failure.
1804   //
1805   // In a rare sitaution, .text section may not exist. If that's the
1806   // case, use the image base address as a last resort.
1807   OutputSection *Default = findSection(".text");
1808   if (!Default)
1809     Default = Out::ElfHeader;
1810 
1811   auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1812     if (OS) {
1813       addOptionalRegular(Start, OS, 0);
1814       addOptionalRegular(End, OS, -1);
1815     } else {
1816       addOptionalRegular(Start, Default, 0);
1817       addOptionalRegular(End, Default, 0);
1818     }
1819   };
1820 
1821   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1822   Define("__init_array_start", "__init_array_end", Out::InitArray);
1823   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1824 
1825   if (OutputSection *Sec = findSection(".ARM.exidx"))
1826     Define("__exidx_start", "__exidx_end", Sec);
1827 }
1828 
1829 // If a section name is valid as a C identifier (which is rare because of
1830 // the leading '.'), linkers are expected to define __start_<secname> and
1831 // __stop_<secname> symbols. They are at beginning and end of the section,
1832 // respectively. This is not requested by the ELF standard, but GNU ld and
1833 // gold provide the feature, and used by many programs.
1834 template <class ELFT>
1835 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1836   StringRef S = Sec->Name;
1837   if (!isValidCIdentifier(S))
1838     return;
1839   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1840   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1841 }
1842 
1843 static bool needsPtLoad(OutputSection *Sec) {
1844   if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1845     return false;
1846 
1847   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1848   // responsible for allocating space for them, not the PT_LOAD that
1849   // contains the TLS initialization image.
1850   if ((Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS)
1851     return false;
1852   return true;
1853 }
1854 
1855 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1856 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1857 // RW. This means that there is no alignment in the RO to RX transition and we
1858 // cannot create a PT_LOAD there.
1859 static uint64_t computeFlags(uint64_t Flags) {
1860   if (Config->Omagic)
1861     return PF_R | PF_W | PF_X;
1862   if (Config->ExecuteOnly && (Flags & PF_X))
1863     return Flags & ~PF_R;
1864   if (Config->SingleRoRx && !(Flags & PF_W))
1865     return Flags | PF_X;
1866   return Flags;
1867 }
1868 
1869 // Decide which program headers to create and which sections to include in each
1870 // one.
1871 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1872   std::vector<PhdrEntry *> Ret;
1873   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1874     Ret.push_back(make<PhdrEntry>(Type, Flags));
1875     return Ret.back();
1876   };
1877 
1878   // The first phdr entry is PT_PHDR which describes the program header itself.
1879   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1880 
1881   // PT_INTERP must be the second entry if exists.
1882   if (OutputSection *Cmd = findSection(".interp"))
1883     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1884 
1885   // Add the first PT_LOAD segment for regular output sections.
1886   uint64_t Flags = computeFlags(PF_R);
1887   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1888 
1889   // Add the headers. We will remove them if they don't fit.
1890   Load->add(Out::ElfHeader);
1891   Load->add(Out::ProgramHeaders);
1892 
1893   for (OutputSection *Sec : OutputSections) {
1894     if (!(Sec->Flags & SHF_ALLOC))
1895       break;
1896     if (!needsPtLoad(Sec))
1897       continue;
1898 
1899     // Segments are contiguous memory regions that has the same attributes
1900     // (e.g. executable or writable). There is one phdr for each segment.
1901     // Therefore, we need to create a new phdr when the next section has
1902     // different flags or is loaded at a discontiguous address or memory
1903     // region using AT or AT> linker script command, respectively. At the same
1904     // time, we don't want to create a separate load segment for the headers,
1905     // even if the first output section has an AT or AT> attribute.
1906     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1907     if (((Sec->LMAExpr ||
1908           (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) &&
1909          Load->LastSec != Out::ProgramHeaders) ||
1910         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1911 
1912       Load = AddHdr(PT_LOAD, NewFlags);
1913       Flags = NewFlags;
1914     }
1915 
1916     Load->add(Sec);
1917   }
1918 
1919   // Add a TLS segment if any.
1920   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1921   for (OutputSection *Sec : OutputSections)
1922     if (Sec->Flags & SHF_TLS)
1923       TlsHdr->add(Sec);
1924   if (TlsHdr->FirstSec)
1925     Ret.push_back(TlsHdr);
1926 
1927   // Add an entry for .dynamic.
1928   if (In.DynSymTab)
1929     AddHdr(PT_DYNAMIC, In.Dynamic->getParent()->getPhdrFlags())
1930         ->add(In.Dynamic->getParent());
1931 
1932   // PT_GNU_RELRO includes all sections that should be marked as
1933   // read-only by dynamic linker after proccessing relocations.
1934   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1935   // an error message if more than one PT_GNU_RELRO PHDR is required.
1936   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1937   bool InRelroPhdr = false;
1938   bool IsRelroFinished = false;
1939   for (OutputSection *Sec : OutputSections) {
1940     if (!needsPtLoad(Sec))
1941       continue;
1942     if (isRelroSection(Sec)) {
1943       InRelroPhdr = true;
1944       if (!IsRelroFinished)
1945         RelRo->add(Sec);
1946       else
1947         error("section: " + Sec->Name + " is not contiguous with other relro" +
1948               " sections");
1949     } else if (InRelroPhdr) {
1950       InRelroPhdr = false;
1951       IsRelroFinished = true;
1952     }
1953   }
1954   if (RelRo->FirstSec)
1955     Ret.push_back(RelRo);
1956 
1957   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1958   if (!In.EhFrame->empty() && In.EhFrameHdr && In.EhFrame->getParent() &&
1959       In.EhFrameHdr->getParent())
1960     AddHdr(PT_GNU_EH_FRAME, In.EhFrameHdr->getParent()->getPhdrFlags())
1961         ->add(In.EhFrameHdr->getParent());
1962 
1963   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1964   // the dynamic linker fill the segment with random data.
1965   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1966     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1967 
1968   // PT_GNU_STACK is a special section to tell the loader to make the
1969   // pages for the stack non-executable. If you really want an executable
1970   // stack, you can pass -z execstack, but that's not recommended for
1971   // security reasons.
1972   unsigned Perm = PF_R | PF_W;
1973   if (Config->ZExecstack)
1974     Perm |= PF_X;
1975   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1976 
1977   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1978   // is expected to perform W^X violations, such as calling mprotect(2) or
1979   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1980   // OpenBSD.
1981   if (Config->ZWxneeded)
1982     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1983 
1984   // Create one PT_NOTE per a group of contiguous .note sections.
1985   PhdrEntry *Note = nullptr;
1986   for (OutputSection *Sec : OutputSections) {
1987     if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
1988       if (!Note || Sec->LMAExpr)
1989         Note = AddHdr(PT_NOTE, PF_R);
1990       Note->add(Sec);
1991     } else {
1992       Note = nullptr;
1993     }
1994   }
1995   return Ret;
1996 }
1997 
1998 template <class ELFT>
1999 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
2000   if (Config->EMachine != EM_ARM)
2001     return;
2002   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
2003     return Cmd->Type == SHT_ARM_EXIDX;
2004   });
2005   if (I == OutputSections.end())
2006     return;
2007 
2008   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2009   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
2010   ARMExidx->add(*I);
2011   Phdrs.push_back(ARMExidx);
2012 }
2013 
2014 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2015 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2016 // linker can set the permissions.
2017 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2018   auto PageAlign = [](OutputSection *Cmd) {
2019     if (Cmd && !Cmd->AddrExpr)
2020       Cmd->AddrExpr = [=] {
2021         return alignTo(Script->getDot(), Config->MaxPageSize);
2022       };
2023   };
2024 
2025   for (const PhdrEntry *P : Phdrs)
2026     if (P->p_type == PT_LOAD && P->FirstSec)
2027       PageAlign(P->FirstSec);
2028 
2029   for (const PhdrEntry *P : Phdrs) {
2030     if (P->p_type != PT_GNU_RELRO)
2031       continue;
2032 
2033     if (P->FirstSec)
2034       PageAlign(P->FirstSec);
2035 
2036     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
2037     // have to align it to a page.
2038     auto End = OutputSections.end();
2039     auto I = std::find(OutputSections.begin(), End, P->LastSec);
2040     if (I == End || (I + 1) == End)
2041       continue;
2042 
2043     OutputSection *Cmd = (*(I + 1));
2044     if (needsPtLoad(Cmd))
2045       PageAlign(Cmd);
2046   }
2047 }
2048 
2049 // Compute an in-file position for a given section. The file offset must be the
2050 // same with its virtual address modulo the page size, so that the loader can
2051 // load executables without any address adjustment.
2052 static uint64_t computeFileOffset(OutputSection *OS, uint64_t Off) {
2053   // File offsets are not significant for .bss sections. By convention, we keep
2054   // section offsets monotonically increasing rather than setting to zero.
2055   if (OS->Type == SHT_NOBITS)
2056     return Off;
2057 
2058   // If the section is not in a PT_LOAD, we just have to align it.
2059   if (!OS->PtLoad)
2060     return alignTo(Off, OS->Alignment);
2061 
2062   // The first section in a PT_LOAD has to have congruent offset and address
2063   // module the page size.
2064   OutputSection *First = OS->PtLoad->FirstSec;
2065   if (OS == First) {
2066     uint64_t Alignment = std::max<uint64_t>(OS->Alignment, Config->MaxPageSize);
2067     return alignTo(Off, Alignment, OS->Addr);
2068   }
2069 
2070   // If two sections share the same PT_LOAD the file offset is calculated
2071   // using this formula: Off2 = Off1 + (VA2 - VA1).
2072   return First->Offset + OS->Addr - First->Addr;
2073 }
2074 
2075 // Set an in-file position to a given section and returns the end position of
2076 // the section.
2077 static uint64_t setFileOffset(OutputSection *OS, uint64_t Off) {
2078   Off = computeFileOffset(OS, Off);
2079   OS->Offset = Off;
2080 
2081   if (OS->Type == SHT_NOBITS)
2082     return Off;
2083   return Off + OS->Size;
2084 }
2085 
2086 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2087   uint64_t Off = 0;
2088   for (OutputSection *Sec : OutputSections)
2089     if (Sec->Flags & SHF_ALLOC)
2090       Off = setFileOffset(Sec, Off);
2091   FileSize = alignTo(Off, Config->Wordsize);
2092 }
2093 
2094 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
2095   return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
2096 }
2097 
2098 // Assign file offsets to output sections.
2099 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2100   uint64_t Off = 0;
2101   Off = setFileOffset(Out::ElfHeader, Off);
2102   Off = setFileOffset(Out::ProgramHeaders, Off);
2103 
2104   PhdrEntry *LastRX = nullptr;
2105   for (PhdrEntry *P : Phdrs)
2106     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2107       LastRX = P;
2108 
2109   for (OutputSection *Sec : OutputSections) {
2110     Off = setFileOffset(Sec, Off);
2111     if (Script->HasSectionsCommand)
2112       continue;
2113 
2114     // If this is a last section of the last executable segment and that
2115     // segment is the last loadable segment, align the offset of the
2116     // following section to avoid loading non-segments parts of the file.
2117     if (LastRX && LastRX->LastSec == Sec)
2118       Off = alignTo(Off, Target->PageSize);
2119   }
2120 
2121   SectionHeaderOff = alignTo(Off, Config->Wordsize);
2122   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2123 
2124   // Our logic assumes that sections have rising VA within the same segment.
2125   // With use of linker scripts it is possible to violate this rule and get file
2126   // offset overlaps or overflows. That should never happen with a valid script
2127   // which does not move the location counter backwards and usually scripts do
2128   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2129   // kernel, which control segment distribution explicitly and move the counter
2130   // backwards, so we have to allow doing that to support linking them. We
2131   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2132   // we want to prevent file size overflows because it would crash the linker.
2133   for (OutputSection *Sec : OutputSections) {
2134     if (Sec->Type == SHT_NOBITS)
2135       continue;
2136     if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2137       error("unable to place section " + Sec->Name + " at file offset " +
2138             rangeToString(Sec->Offset, Sec->Size) +
2139             "; check your linker script for overflows");
2140   }
2141 }
2142 
2143 // Finalize the program headers. We call this function after we assign
2144 // file offsets and VAs to all sections.
2145 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2146   for (PhdrEntry *P : Phdrs) {
2147     OutputSection *First = P->FirstSec;
2148     OutputSection *Last = P->LastSec;
2149 
2150     if (First) {
2151       P->p_filesz = Last->Offset - First->Offset;
2152       if (Last->Type != SHT_NOBITS)
2153         P->p_filesz += Last->Size;
2154 
2155       P->p_memsz = Last->Addr + Last->Size - First->Addr;
2156       P->p_offset = First->Offset;
2157       P->p_vaddr = First->Addr;
2158 
2159       if (!P->HasLMA)
2160         P->p_paddr = First->getLMA();
2161     }
2162 
2163     if (P->p_type == PT_LOAD) {
2164       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2165     } else if (P->p_type == PT_GNU_RELRO) {
2166       P->p_align = 1;
2167       // The glibc dynamic loader rounds the size down, so we need to round up
2168       // to protect the last page. This is a no-op on FreeBSD which always
2169       // rounds up.
2170       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2171     }
2172 
2173     // The TLS pointer goes after PT_TLS for variant 2 targets. At least glibc
2174     // will align it, so round up the size to make sure the offsets are
2175     // correct.
2176     if (P->p_type == PT_TLS && P->p_memsz)
2177       P->p_memsz = alignTo(P->p_memsz, P->p_align);
2178   }
2179 }
2180 
2181 // A helper struct for checkSectionOverlap.
2182 namespace {
2183 struct SectionOffset {
2184   OutputSection *Sec;
2185   uint64_t Offset;
2186 };
2187 } // namespace
2188 
2189 // Check whether sections overlap for a specific address range (file offsets,
2190 // load and virtual adresses).
2191 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2192                          bool IsVirtualAddr) {
2193   llvm::sort(Sections, [=](const SectionOffset &A, const SectionOffset &B) {
2194     return A.Offset < B.Offset;
2195   });
2196 
2197   // Finding overlap is easy given a vector is sorted by start position.
2198   // If an element starts before the end of the previous element, they overlap.
2199   for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2200     SectionOffset A = Sections[I - 1];
2201     SectionOffset B = Sections[I];
2202     if (B.Offset >= A.Offset + A.Sec->Size)
2203       continue;
2204 
2205     // If both sections are in OVERLAY we allow the overlapping of virtual
2206     // addresses, because it is what OVERLAY was designed for.
2207     if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2208       continue;
2209 
2210     errorOrWarn("section " + A.Sec->Name + " " + Name +
2211                 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2212                 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2213                 B.Sec->Name + " range is " +
2214                 rangeToString(B.Offset, B.Sec->Size));
2215   }
2216 }
2217 
2218 // Check for overlapping sections and address overflows.
2219 //
2220 // In this function we check that none of the output sections have overlapping
2221 // file offsets. For SHF_ALLOC sections we also check that the load address
2222 // ranges and the virtual address ranges don't overlap
2223 template <class ELFT> void Writer<ELFT>::checkSections() {
2224   // First, check that section's VAs fit in available address space for target.
2225   for (OutputSection *OS : OutputSections)
2226     if ((OS->Addr + OS->Size < OS->Addr) ||
2227         (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2228       errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2229                   " of size 0x" + utohexstr(OS->Size) +
2230                   " exceeds available address space");
2231 
2232   // Check for overlapping file offsets. In this case we need to skip any
2233   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2234   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2235   // binary is specified only add SHF_ALLOC sections are added to the output
2236   // file so we skip any non-allocated sections in that case.
2237   std::vector<SectionOffset> FileOffs;
2238   for (OutputSection *Sec : OutputSections)
2239     if (Sec->Size > 0 && Sec->Type != SHT_NOBITS &&
2240         (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2241       FileOffs.push_back({Sec, Sec->Offset});
2242   checkOverlap("file", FileOffs, false);
2243 
2244   // When linking with -r there is no need to check for overlapping virtual/load
2245   // addresses since those addresses will only be assigned when the final
2246   // executable/shared object is created.
2247   if (Config->Relocatable)
2248     return;
2249 
2250   // Checking for overlapping virtual and load addresses only needs to take
2251   // into account SHF_ALLOC sections since others will not be loaded.
2252   // Furthermore, we also need to skip SHF_TLS sections since these will be
2253   // mapped to other addresses at runtime and can therefore have overlapping
2254   // ranges in the file.
2255   std::vector<SectionOffset> VMAs;
2256   for (OutputSection *Sec : OutputSections)
2257     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2258       VMAs.push_back({Sec, Sec->Addr});
2259   checkOverlap("virtual address", VMAs, true);
2260 
2261   // Finally, check that the load addresses don't overlap. This will usually be
2262   // the same as the virtual addresses but can be different when using a linker
2263   // script with AT().
2264   std::vector<SectionOffset> LMAs;
2265   for (OutputSection *Sec : OutputSections)
2266     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2267       LMAs.push_back({Sec, Sec->getLMA()});
2268   checkOverlap("load address", LMAs, false);
2269 }
2270 
2271 // The entry point address is chosen in the following ways.
2272 //
2273 // 1. the '-e' entry command-line option;
2274 // 2. the ENTRY(symbol) command in a linker control script;
2275 // 3. the value of the symbol _start, if present;
2276 // 4. the number represented by the entry symbol, if it is a number;
2277 // 5. the address of the first byte of the .text section, if present;
2278 // 6. the address 0.
2279 static uint64_t getEntryAddr() {
2280   // Case 1, 2 or 3
2281   if (Symbol *B = Symtab->find(Config->Entry))
2282     return B->getVA();
2283 
2284   // Case 4
2285   uint64_t Addr;
2286   if (to_integer(Config->Entry, Addr))
2287     return Addr;
2288 
2289   // Case 5
2290   if (OutputSection *Sec = findSection(".text")) {
2291     if (Config->WarnMissingEntry)
2292       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2293            utohexstr(Sec->Addr));
2294     return Sec->Addr;
2295   }
2296 
2297   // Case 6
2298   if (Config->WarnMissingEntry)
2299     warn("cannot find entry symbol " + Config->Entry +
2300          "; not setting start address");
2301   return 0;
2302 }
2303 
2304 static uint16_t getELFType() {
2305   if (Config->Pic)
2306     return ET_DYN;
2307   if (Config->Relocatable)
2308     return ET_REL;
2309   return ET_EXEC;
2310 }
2311 
2312 static uint8_t getAbiVersion() {
2313   // MIPS non-PIC executable gets ABI version 1.
2314   if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2315       (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2316     return 1;
2317   return 0;
2318 }
2319 
2320 template <class ELFT> void Writer<ELFT>::writeHeader() {
2321   uint8_t *Buf = Buffer->getBufferStart();
2322 
2323   // For executable segments, the trap instructions are written before writing
2324   // the header. Setting Elf header bytes to zero ensures that any unused bytes
2325   // in header are zero-cleared, instead of having trap instructions.
2326   memset(Buf, 0, sizeof(Elf_Ehdr));
2327   memcpy(Buf, "\177ELF", 4);
2328 
2329   // Write the ELF header.
2330   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2331   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2332   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2333   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2334   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2335   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2336   EHdr->e_type = getELFType();
2337   EHdr->e_machine = Config->EMachine;
2338   EHdr->e_version = EV_CURRENT;
2339   EHdr->e_entry = getEntryAddr();
2340   EHdr->e_shoff = SectionHeaderOff;
2341   EHdr->e_flags = Config->EFlags;
2342   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2343   EHdr->e_phnum = Phdrs.size();
2344   EHdr->e_shentsize = sizeof(Elf_Shdr);
2345 
2346   if (!Config->Relocatable) {
2347     EHdr->e_phoff = sizeof(Elf_Ehdr);
2348     EHdr->e_phentsize = sizeof(Elf_Phdr);
2349   }
2350 
2351   // Write the program header table.
2352   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2353   for (PhdrEntry *P : Phdrs) {
2354     HBuf->p_type = P->p_type;
2355     HBuf->p_flags = P->p_flags;
2356     HBuf->p_offset = P->p_offset;
2357     HBuf->p_vaddr = P->p_vaddr;
2358     HBuf->p_paddr = P->p_paddr;
2359     HBuf->p_filesz = P->p_filesz;
2360     HBuf->p_memsz = P->p_memsz;
2361     HBuf->p_align = P->p_align;
2362     ++HBuf;
2363   }
2364 
2365   // Write the section header table.
2366   //
2367   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2368   // and e_shstrndx fields. When the value of one of these fields exceeds
2369   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2370   // use fields in the section header at index 0 to store
2371   // the value. The sentinel values and fields are:
2372   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2373   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2374   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2375   size_t Num = OutputSections.size() + 1;
2376   if (Num >= SHN_LORESERVE)
2377     SHdrs->sh_size = Num;
2378   else
2379     EHdr->e_shnum = Num;
2380 
2381   uint32_t StrTabIndex = In.ShStrTab->getParent()->SectionIndex;
2382   if (StrTabIndex >= SHN_LORESERVE) {
2383     SHdrs->sh_link = StrTabIndex;
2384     EHdr->e_shstrndx = SHN_XINDEX;
2385   } else {
2386     EHdr->e_shstrndx = StrTabIndex;
2387   }
2388 
2389   for (OutputSection *Sec : OutputSections)
2390     Sec->writeHeaderTo<ELFT>(++SHdrs);
2391 }
2392 
2393 // Open a result file.
2394 template <class ELFT> void Writer<ELFT>::openFile() {
2395   if (!Config->Is64 && FileSize > UINT32_MAX) {
2396     error("output file too large: " + Twine(FileSize) + " bytes");
2397     return;
2398   }
2399 
2400   unlinkAsync(Config->OutputFile);
2401   unsigned Flags = 0;
2402   if (!Config->Relocatable)
2403     Flags = FileOutputBuffer::F_executable;
2404   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2405       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2406 
2407   if (!BufferOrErr)
2408     error("failed to open " + Config->OutputFile + ": " +
2409           llvm::toString(BufferOrErr.takeError()));
2410   else
2411     Buffer = std::move(*BufferOrErr);
2412 }
2413 
2414 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2415   uint8_t *Buf = Buffer->getBufferStart();
2416   for (OutputSection *Sec : OutputSections)
2417     if (Sec->Flags & SHF_ALLOC)
2418       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2419 }
2420 
2421 static void fillTrap(uint8_t *I, uint8_t *End) {
2422   for (; I + 4 <= End; I += 4)
2423     memcpy(I, &Target->TrapInstr, 4);
2424 }
2425 
2426 // Fill the last page of executable segments with trap instructions
2427 // instead of leaving them as zero. Even though it is not required by any
2428 // standard, it is in general a good thing to do for security reasons.
2429 //
2430 // We'll leave other pages in segments as-is because the rest will be
2431 // overwritten by output sections.
2432 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2433   if (Script->HasSectionsCommand)
2434     return;
2435 
2436   // Fill the last page.
2437   uint8_t *Buf = Buffer->getBufferStart();
2438   for (PhdrEntry *P : Phdrs)
2439     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2440       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2441                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2442 
2443   // Round up the file size of the last segment to the page boundary iff it is
2444   // an executable segment to ensure that other tools don't accidentally
2445   // trim the instruction padding (e.g. when stripping the file).
2446   PhdrEntry *Last = nullptr;
2447   for (PhdrEntry *P : Phdrs)
2448     if (P->p_type == PT_LOAD)
2449       Last = P;
2450 
2451   if (Last && (Last->p_flags & PF_X))
2452     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2453 }
2454 
2455 // Write section contents to a mmap'ed file.
2456 template <class ELFT> void Writer<ELFT>::writeSections() {
2457   uint8_t *Buf = Buffer->getBufferStart();
2458 
2459   OutputSection *EhFrameHdr = nullptr;
2460   if (In.EhFrameHdr && !In.EhFrameHdr->empty())
2461     EhFrameHdr = In.EhFrameHdr->getParent();
2462 
2463   // In -r or -emit-relocs mode, write the relocation sections first as in
2464   // ELf_Rel targets we might find out that we need to modify the relocated
2465   // section while doing it.
2466   for (OutputSection *Sec : OutputSections)
2467     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2468       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2469 
2470   for (OutputSection *Sec : OutputSections)
2471     if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2472       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2473 
2474   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2475   // it should be written after .eh_frame is written.
2476   if (EhFrameHdr)
2477     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2478 }
2479 
2480 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2481   if (!In.BuildId || !In.BuildId->getParent())
2482     return;
2483 
2484   // Compute a hash of all sections of the output file.
2485   uint8_t *Start = Buffer->getBufferStart();
2486   uint8_t *End = Start + FileSize;
2487   In.BuildId->writeBuildId({Start, End});
2488 }
2489 
2490 template void elf::writeResult<ELF32LE>();
2491 template void elf::writeResult<ELF32BE>();
2492 template void elf::writeResult<ELF64LE>();
2493 template void elf::writeResult<ELF64BE>();
2494