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