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