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