xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 9284931e)
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 "Strings.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/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 << 16,
672   RF_NOT_INTERP = 1 << 15,
673   RF_NOT_ALLOC = 1 << 14,
674   RF_WRITE = 1 << 13,
675   RF_EXEC_WRITE = 1 << 12,
676   RF_EXEC = 1 << 11,
677   RF_NON_TLS_BSS = 1 << 10,
678   RF_NON_TLS_BSS_RO = 1 << 9,
679   RF_NOT_TLS = 1 << 8,
680   RF_BSS = 1 << 7,
681   RF_PPC_NOT_TOCBSS = 1 << 6,
682   RF_PPC_OPD = 1 << 5,
683   RF_PPC_TOCL = 1 << 4,
684   RF_PPC_TOC = 1 << 3,
685   RF_PPC_BRANCH_LT = 1 << 2,
686   RF_MIPS_GPREL = 1 << 1,
687   RF_MIPS_NOT_GOT = 1 << 0
688 };
689 
690 static unsigned getSectionRank(const OutputSection *Sec) {
691   unsigned Rank = 0;
692 
693   // We want to put section specified by -T option first, so we
694   // can start assigning VA starting from them later.
695   if (Config->SectionStartMap.count(Sec->Name))
696     return Rank;
697   Rank |= RF_NOT_ADDR_SET;
698 
699   // Put .interp first because some loaders want to see that section
700   // on the first page of the executable file when loaded into memory.
701   if (Sec->Name == ".interp")
702     return Rank;
703   Rank |= RF_NOT_INTERP;
704 
705   // Allocatable sections go first to reduce the total PT_LOAD size and
706   // so debug info doesn't change addresses in actual code.
707   if (!(Sec->Flags & SHF_ALLOC))
708     return Rank | RF_NOT_ALLOC;
709 
710   // Sort sections based on their access permission in the following
711   // order: R, RX, RWX, RW.  This order is based on the following
712   // considerations:
713   // * Read-only sections come first such that they go in the
714   //   PT_LOAD covering the program headers at the start of the file.
715   // * Read-only, executable sections come next, unless the
716   //   -no-rosegment option is used.
717   // * Writable, executable sections follow such that .plt on
718   //   architectures where it needs to be writable will be placed
719   //   between .text and .data.
720   // * Writable sections come last, such that .bss lands at the very
721   //   end of the last PT_LOAD.
722   bool IsExec = Sec->Flags & SHF_EXECINSTR;
723   bool IsWrite = Sec->Flags & SHF_WRITE;
724 
725   if (IsExec) {
726     if (IsWrite)
727       Rank |= RF_EXEC_WRITE;
728     else if (!Config->SingleRoRx)
729       Rank |= RF_EXEC;
730   } else {
731     if (IsWrite)
732       Rank |= RF_WRITE;
733   }
734 
735   // If we got here we know that both A and B are in the same PT_LOAD.
736 
737   bool IsTls = Sec->Flags & SHF_TLS;
738   bool IsNoBits = Sec->Type == SHT_NOBITS;
739 
740   // The first requirement we have is to put (non-TLS) nobits sections last. The
741   // reason is that the only thing the dynamic linker will see about them is a
742   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
743   // PT_LOAD, so that has to correspond to the nobits sections.
744   bool IsNonTlsNoBits = IsNoBits && !IsTls;
745   if (IsNonTlsNoBits)
746     Rank |= RF_NON_TLS_BSS;
747 
748   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
749   // sections after r/w ones, so that the RelRo sections are contiguous.
750   bool IsRelRo = isRelroSection(Sec);
751   if (IsNonTlsNoBits && !IsRelRo)
752     Rank |= RF_NON_TLS_BSS_RO;
753   if (!IsNonTlsNoBits && IsRelRo)
754     Rank |= RF_NON_TLS_BSS_RO;
755 
756   // The TLS initialization block needs to be a single contiguous block in a R/W
757   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
758   // sections. The TLS NOBITS sections are placed here as they don't take up
759   // virtual address space in the PT_LOAD.
760   if (!IsTls)
761     Rank |= RF_NOT_TLS;
762 
763   // Within the TLS initialization block, the non-nobits sections need to appear
764   // first.
765   if (IsNoBits)
766     Rank |= RF_BSS;
767 
768   // Some architectures have additional ordering restrictions for sections
769   // within the same PT_LOAD.
770   if (Config->EMachine == EM_PPC64) {
771     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
772     // that we would like to make sure appear is a specific order to maximize
773     // their coverage by a single signed 16-bit offset from the TOC base
774     // pointer. Conversely, the special .tocbss section should be first among
775     // all SHT_NOBITS sections. This will put it next to the loaded special
776     // PPC64 sections (and, thus, within reach of the TOC base pointer).
777     StringRef Name = Sec->Name;
778     if (Name != ".tocbss")
779       Rank |= RF_PPC_NOT_TOCBSS;
780 
781     if (Name == ".opd")
782       Rank |= RF_PPC_OPD;
783 
784     if (Name == ".toc1")
785       Rank |= RF_PPC_TOCL;
786 
787     if (Name == ".toc")
788       Rank |= RF_PPC_TOC;
789 
790     if (Name == ".branch_lt")
791       Rank |= RF_PPC_BRANCH_LT;
792   }
793   if (Config->EMachine == EM_MIPS) {
794     // All sections with SHF_MIPS_GPREL flag should be grouped together
795     // because data in these sections is addressable with a gp relative address.
796     if (Sec->Flags & SHF_MIPS_GPREL)
797       Rank |= RF_MIPS_GPREL;
798 
799     if (Sec->Name != ".got")
800       Rank |= RF_MIPS_NOT_GOT;
801   }
802 
803   return Rank;
804 }
805 
806 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
807   const OutputSection *A = cast<OutputSection>(ACmd);
808   const OutputSection *B = cast<OutputSection>(BCmd);
809   if (A->SortRank != B->SortRank)
810     return A->SortRank < B->SortRank;
811   if (!(A->SortRank & RF_NOT_ADDR_SET))
812     return Config->SectionStartMap.lookup(A->Name) <
813            Config->SectionStartMap.lookup(B->Name);
814   return false;
815 }
816 
817 void PhdrEntry::add(OutputSection *Sec) {
818   LastSec = Sec;
819   if (!FirstSec)
820     FirstSec = Sec;
821   p_align = std::max(p_align, Sec->Alignment);
822   if (p_type == PT_LOAD)
823     Sec->PtLoad = this;
824   if (Sec->LMAExpr)
825     ASectionHasLMA = true;
826 }
827 
828 // The beginning and the ending of .rel[a].plt section are marked
829 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
830 // executable. The runtime needs these symbols in order to resolve
831 // all IRELATIVE relocs on startup. For dynamic executables, we don't
832 // need these symbols, since IRELATIVE relocs are resolved through GOT
833 // and PLT. For details, see http://www.airs.com/blog/archives/403.
834 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
835   if (needsInterpSection())
836     return;
837   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
838   addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
839 
840   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
841   addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
842 }
843 
844 template <class ELFT>
845 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
846   // Scan all relocations. Each relocation goes through a series
847   // of tests to determine if it needs special treatment, such as
848   // creating GOT, PLT, copy relocations, etc.
849   // Note that relocations for non-alloc sections are directly
850   // processed by InputSection::relocateNonAlloc.
851   for (InputSectionBase *IS : InputSections)
852     if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
853       Fn(*IS);
854   for (EhInputSection *ES : InX::EhFrame->Sections)
855     Fn(*ES);
856 }
857 
858 // This function generates assignments for predefined symbols (e.g. _end or
859 // _etext) and inserts them into the commands sequence to be processed at the
860 // appropriate time. This ensures that the value is going to be correct by the
861 // time any references to these symbols are processed and is equivalent to
862 // defining these symbols explicitly in the linker script.
863 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
864   if (ElfSym::GlobalOffsetTable) {
865     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
866     // be at some offset from the base of the .got section, usually 0 or the end
867     // of the .got
868     InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
869                                             : cast<InputSection>(InX::Got);
870     ElfSym::GlobalOffsetTable->Section = GotSection;
871   }
872 
873   PhdrEntry *Last = nullptr;
874   PhdrEntry *LastRO = nullptr;
875 
876   for (PhdrEntry *P : Phdrs) {
877     if (P->p_type != PT_LOAD)
878       continue;
879     Last = P;
880     if (!(P->p_flags & PF_W))
881       LastRO = P;
882   }
883 
884   if (LastRO) {
885     // _etext is the first location after the last read-only loadable segment.
886     if (ElfSym::Etext1)
887       ElfSym::Etext1->Section = LastRO->LastSec;
888     if (ElfSym::Etext2)
889       ElfSym::Etext2->Section = LastRO->LastSec;
890   }
891 
892   if (Last) {
893     // _edata points to the end of the last mapped initialized section.
894     OutputSection *Edata = nullptr;
895     for (OutputSection *OS : OutputSections) {
896       if (OS->Type != SHT_NOBITS)
897         Edata = OS;
898       if (OS == Last->LastSec)
899         break;
900     }
901 
902     if (ElfSym::Edata1)
903       ElfSym::Edata1->Section = Edata;
904     if (ElfSym::Edata2)
905       ElfSym::Edata2->Section = Edata;
906 
907     // _end is the first location after the uninitialized data region.
908     if (ElfSym::End1)
909       ElfSym::End1->Section = Last->LastSec;
910     if (ElfSym::End2)
911       ElfSym::End2->Section = Last->LastSec;
912   }
913 
914   if (ElfSym::Bss)
915     ElfSym::Bss->Section = findSection(".bss");
916 
917   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
918   // be equal to the _gp symbol's value.
919   if (ElfSym::MipsGp) {
920     // Find GP-relative section with the lowest address
921     // and use this address to calculate default _gp value.
922     for (OutputSection *OS : OutputSections) {
923       if (OS->Flags & SHF_MIPS_GPREL) {
924         ElfSym::MipsGp->Section = OS;
925         ElfSym::MipsGp->Value = 0x7ff0;
926         break;
927       }
928     }
929   }
930 }
931 
932 // We want to find how similar two ranks are.
933 // The more branches in getSectionRank that match, the more similar they are.
934 // Since each branch corresponds to a bit flag, we can just use
935 // countLeadingZeros.
936 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
937   return countLeadingZeros(A->SortRank ^ B->SortRank);
938 }
939 
940 static int getRankProximity(OutputSection *A, BaseCommand *B) {
941   if (auto *Sec = dyn_cast<OutputSection>(B))
942     if (Sec->Live)
943       return getRankProximityAux(A, Sec);
944   return -1;
945 }
946 
947 // When placing orphan sections, we want to place them after symbol assignments
948 // so that an orphan after
949 //   begin_foo = .;
950 //   foo : { *(foo) }
951 //   end_foo = .;
952 // doesn't break the intended meaning of the begin/end symbols.
953 // We don't want to go over sections since findOrphanPos is the
954 // one in charge of deciding the order of the sections.
955 // We don't want to go over changes to '.', since doing so in
956 //  rx_sec : { *(rx_sec) }
957 //  . = ALIGN(0x1000);
958 //  /* The RW PT_LOAD starts here*/
959 //  rw_sec : { *(rw_sec) }
960 // would mean that the RW PT_LOAD would become unaligned.
961 static bool shouldSkip(BaseCommand *Cmd) {
962   if (isa<OutputSection>(Cmd))
963     return false;
964   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
965     return Assign->Name != ".";
966   return true;
967 }
968 
969 // We want to place orphan sections so that they share as much
970 // characteristics with their neighbors as possible. For example, if
971 // both are rw, or both are tls.
972 template <typename ELFT>
973 static std::vector<BaseCommand *>::iterator
974 findOrphanPos(std::vector<BaseCommand *>::iterator B,
975               std::vector<BaseCommand *>::iterator E) {
976   OutputSection *Sec = cast<OutputSection>(*E);
977 
978   // Find the first element that has as close a rank as possible.
979   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
980     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
981   });
982   if (I == E)
983     return E;
984 
985   // Consider all existing sections with the same proximity.
986   int Proximity = getRankProximity(Sec, *I);
987   for (; I != E; ++I) {
988     auto *CurSec = dyn_cast<OutputSection>(*I);
989     if (!CurSec || !CurSec->Live)
990       continue;
991     if (getRankProximity(Sec, CurSec) != Proximity ||
992         Sec->SortRank < CurSec->SortRank)
993       break;
994   }
995 
996   auto IsLiveSection = [](BaseCommand *Cmd) {
997     auto *OS = dyn_cast<OutputSection>(Cmd);
998     return OS && OS->Live;
999   };
1000 
1001   auto J = std::find_if(llvm::make_reverse_iterator(I),
1002                         llvm::make_reverse_iterator(B), IsLiveSection);
1003   I = J.base();
1004 
1005   // As a special case, if the orphan section is the last section, put
1006   // it at the very end, past any other commands.
1007   // This matches bfd's behavior and is convenient when the linker script fully
1008   // specifies the start of the file, but doesn't care about the end (the non
1009   // alloc sections for example).
1010   auto NextSec = std::find_if(I, E, IsLiveSection);
1011   if (NextSec == E)
1012     return E;
1013 
1014   while (I != E && shouldSkip(*I))
1015     ++I;
1016   return I;
1017 }
1018 
1019 // Builds section order for handling --symbol-ordering-file.
1020 static DenseMap<SectionBase *, int> buildSectionOrder() {
1021   DenseMap<SectionBase *, int> SectionOrder;
1022   if (Config->SymbolOrderingFile.empty())
1023     return SectionOrder;
1024 
1025   // Build a map from symbols to their priorities. Symbols that didn't
1026   // appear in the symbol ordering file have the lowest priority 0.
1027   // All explicitly mentioned symbols have negative (higher) priorities.
1028   DenseMap<StringRef, int> SymbolOrder;
1029   int Priority = -Config->SymbolOrderingFile.size();
1030   for (StringRef S : Config->SymbolOrderingFile)
1031     SymbolOrder.insert({S, Priority++});
1032 
1033   // Build a map from sections to their priorities.
1034   for (InputFile *File : ObjectFiles) {
1035     for (Symbol *Sym : File->getSymbols()) {
1036       auto *D = dyn_cast<Defined>(Sym);
1037       if (!D || !D->Section)
1038         continue;
1039       int &Priority = SectionOrder[D->Section];
1040       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
1041     }
1042   }
1043   return SectionOrder;
1044 }
1045 
1046 static void sortSection(OutputSection *Sec,
1047                         const DenseMap<SectionBase *, int> &Order) {
1048   if (!Sec->Live)
1049     return;
1050   StringRef Name = Sec->Name;
1051 
1052   // Sort input sections by section name suffixes for
1053   // __attribute__((init_priority(N))).
1054   if (Name == ".init_array" || Name == ".fini_array") {
1055     if (!Script->HasSectionsCommand)
1056       Sec->sortInitFini();
1057     return;
1058   }
1059 
1060   // Sort input sections by the special rule for .ctors and .dtors.
1061   if (Name == ".ctors" || Name == ".dtors") {
1062     if (!Script->HasSectionsCommand)
1063       Sec->sortCtorsDtors();
1064     return;
1065   }
1066 
1067   // Never sort these.
1068   if (Name == ".init" || Name == ".fini")
1069     return;
1070 
1071   // Sort input sections by priority using the list provided
1072   // by --symbol-ordering-file.
1073   if (!Order.empty())
1074     Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
1075 }
1076 
1077 // If no layout was provided by linker script, we want to apply default
1078 // sorting for special input sections. This also handles --symbol-ordering-file.
1079 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1080   // Build the order once since it is expensive.
1081   DenseMap<SectionBase *, int> Order = buildSectionOrder();
1082   for (BaseCommand *Base : Script->SectionCommands)
1083     if (auto *Sec = dyn_cast<OutputSection>(Base))
1084       sortSection(Sec, Order);
1085 }
1086 
1087 template <class ELFT> void Writer<ELFT>::sortSections() {
1088   Script->adjustSectionsBeforeSorting();
1089 
1090   // Don't sort if using -r. It is not necessary and we want to preserve the
1091   // relative order for SHF_LINK_ORDER sections.
1092   if (Config->Relocatable)
1093     return;
1094 
1095   for (BaseCommand *Base : Script->SectionCommands)
1096     if (auto *Sec = dyn_cast<OutputSection>(Base))
1097       Sec->SortRank = getSectionRank(Sec);
1098 
1099   sortInputSections();
1100 
1101   if (!Script->HasSectionsCommand) {
1102     // We know that all the OutputSections are contiguous in this case.
1103     auto E = Script->SectionCommands.end();
1104     auto I = Script->SectionCommands.begin();
1105     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1106     I = std::find_if(I, E, IsSection);
1107     E = std::find_if(llvm::make_reverse_iterator(E),
1108                      llvm::make_reverse_iterator(I), IsSection)
1109             .base();
1110     std::stable_sort(I, E, compareSections);
1111     return;
1112   }
1113 
1114   // Orphan sections are sections present in the input files which are
1115   // not explicitly placed into the output file by the linker script.
1116   //
1117   // The sections in the linker script are already in the correct
1118   // order. We have to figuere out where to insert the orphan
1119   // sections.
1120   //
1121   // The order of the sections in the script is arbitrary and may not agree with
1122   // compareSections. This means that we cannot easily define a strict weak
1123   // ordering. To see why, consider a comparison of a section in the script and
1124   // one not in the script. We have a two simple options:
1125   // * Make them equivalent (a is not less than b, and b is not less than a).
1126   //   The problem is then that equivalence has to be transitive and we can
1127   //   have sections a, b and c with only b in a script and a less than c
1128   //   which breaks this property.
1129   // * Use compareSectionsNonScript. Given that the script order doesn't have
1130   //   to match, we can end up with sections a, b, c, d where b and c are in the
1131   //   script and c is compareSectionsNonScript less than b. In which case d
1132   //   can be equivalent to c, a to b and d < a. As a concrete example:
1133   //   .a (rx) # not in script
1134   //   .b (rx) # in script
1135   //   .c (ro) # in script
1136   //   .d (ro) # not in script
1137   //
1138   // The way we define an order then is:
1139   // *  Sort only the orphan sections. They are in the end right now.
1140   // *  Move each orphan section to its preferred position. We try
1141   //    to put each section in the last position where it it can share
1142   //    a PT_LOAD.
1143   //
1144   // There is some ambiguity as to where exactly a new entry should be
1145   // inserted, because Commands contains not only output section
1146   // commands but also other types of commands such as symbol assignment
1147   // expressions. There's no correct answer here due to the lack of the
1148   // formal specification of the linker script. We use heuristics to
1149   // determine whether a new output command should be added before or
1150   // after another commands. For the details, look at shouldSkip
1151   // function.
1152 
1153   auto I = Script->SectionCommands.begin();
1154   auto E = Script->SectionCommands.end();
1155   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1156     if (auto *Sec = dyn_cast<OutputSection>(Base))
1157       return Sec->Live && Sec->SectionIndex == INT_MAX;
1158     return false;
1159   });
1160 
1161   // Sort the orphan sections.
1162   std::stable_sort(NonScriptI, E, compareSections);
1163 
1164   // As a horrible special case, skip the first . assignment if it is before any
1165   // section. We do this because it is common to set a load address by starting
1166   // the script with ". = 0xabcd" and the expectation is that every section is
1167   // after that.
1168   auto FirstSectionOrDotAssignment =
1169       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1170   if (FirstSectionOrDotAssignment != E &&
1171       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1172     ++FirstSectionOrDotAssignment;
1173   I = FirstSectionOrDotAssignment;
1174 
1175   while (NonScriptI != E) {
1176     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1177     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1178 
1179     // As an optimization, find all sections with the same sort rank
1180     // and insert them with one rotate.
1181     unsigned Rank = Orphan->SortRank;
1182     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1183       return cast<OutputSection>(Cmd)->SortRank != Rank;
1184     });
1185     std::rotate(Pos, NonScriptI, End);
1186     NonScriptI = End;
1187   }
1188 
1189   Script->adjustSectionsAfterSorting();
1190 }
1191 
1192 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1193   // Synthetic, i. e. a sentinel section, should go last.
1194   if (A->kind() == InputSectionBase::Synthetic ||
1195       B->kind() == InputSectionBase::Synthetic)
1196     return A->kind() != InputSectionBase::Synthetic;
1197   InputSection *LA = A->getLinkOrderDep();
1198   InputSection *LB = B->getLinkOrderDep();
1199   OutputSection *AOut = LA->getParent();
1200   OutputSection *BOut = LB->getParent();
1201   if (AOut != BOut)
1202     return AOut->SectionIndex < BOut->SectionIndex;
1203   return LA->OutSecOff < LB->OutSecOff;
1204 }
1205 
1206 // This function is used by the --merge-exidx-entries to detect duplicate
1207 // .ARM.exidx sections. It is Arm only.
1208 //
1209 // The .ARM.exidx section is of the form:
1210 // | PREL31 offset to function | Unwind instructions for function |
1211 // where the unwind instructions are either a small number of unwind
1212 // instructions inlined into the table entry, the special CANT_UNWIND value of
1213 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1214 // instructions.
1215 //
1216 // We return true if all the unwind instructions in the .ARM.exidx entries of
1217 // Cur can be merged into the last entry of Prev.
1218 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1219 
1220   // References to .ARM.Extab Sections have bit 31 clear and are not the
1221   // special EXIDX_CANTUNWIND bit-pattern.
1222   auto IsExtabRef = [](uint32_t Unwind) {
1223     return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1224   };
1225 
1226   struct ExidxEntry {
1227     ulittle32_t Fn;
1228     ulittle32_t Unwind;
1229   };
1230 
1231   // Get the last table Entry from the previous .ARM.exidx section.
1232   const ExidxEntry &PrevEntry = *reinterpret_cast<const ExidxEntry *>(
1233       Prev->Data.data() + Prev->getSize() - sizeof(ExidxEntry));
1234   if (IsExtabRef(PrevEntry.Unwind))
1235     return false;
1236 
1237   // We consider the unwind instructions of an .ARM.exidx table entry
1238   // a duplicate if the previous unwind instructions if:
1239   // - Both are the special EXIDX_CANTUNWIND.
1240   // - Both are the same inline unwind instructions.
1241   // We do not attempt to follow and check links into .ARM.extab tables as
1242   // consecutive identical entries are rare and the effort to check that they
1243   // are identical is high.
1244 
1245   if (isa<SyntheticSection>(Cur))
1246     // Exidx sentinel section has implicit EXIDX_CANTUNWIND;
1247     return PrevEntry.Unwind == 0x1;
1248 
1249   ArrayRef<const ExidxEntry> Entries(
1250       reinterpret_cast<const ExidxEntry *>(Cur->Data.data()),
1251       Cur->getSize() / sizeof(ExidxEntry));
1252   for (const ExidxEntry &Entry : Entries)
1253     if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1254       return false;
1255   // All table entries in this .ARM.exidx Section can be merged into the
1256   // previous Section.
1257   return true;
1258 }
1259 
1260 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1261   for (OutputSection *Sec : OutputSections) {
1262     if (!(Sec->Flags & SHF_LINK_ORDER))
1263       continue;
1264 
1265     // Link order may be distributed across several InputSectionDescriptions
1266     // but sort must consider them all at once.
1267     std::vector<InputSection **> ScriptSections;
1268     std::vector<InputSection *> Sections;
1269     for (BaseCommand *Base : Sec->SectionCommands) {
1270       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1271         for (InputSection *&IS : ISD->Sections) {
1272           ScriptSections.push_back(&IS);
1273           Sections.push_back(IS);
1274         }
1275       }
1276     }
1277     std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1278 
1279     if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1280         Sec->Type == SHT_ARM_EXIDX) {
1281 
1282       if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1283         assert(Sections.size() >= 2 &&
1284                "We should create a sentinel section only if there are "
1285                "alive regular exidx sections.");
1286         // The last executable section is required to fill the sentinel.
1287         // Remember it here so that we don't have to find it again.
1288         auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1289         Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1290       }
1291 
1292       if (Config->MergeArmExidx) {
1293         // The EHABI for the Arm Architecture permits consecutive identical
1294         // table entries to be merged. We use a simple implementation that
1295         // removes a .ARM.exidx Input Section if it can be merged into the
1296         // previous one. This does not require any rewriting of InputSection
1297         // contents but misses opportunities for fine grained deduplication
1298         // where only a subset of the InputSection contents can be merged.
1299         int Cur = 1;
1300         int Prev = 0;
1301         // The last one is a sentinel entry which should not be removed.
1302         int N = Sections.size() - 1;
1303         while (Cur < N) {
1304           if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1305             Sections[Cur] = nullptr;
1306           else
1307             Prev = Cur;
1308           ++Cur;
1309         }
1310       }
1311     }
1312 
1313     for (int I = 0, N = Sections.size(); I < N; ++I)
1314       *ScriptSections[I] = Sections[I];
1315 
1316     // Remove the Sections we marked as duplicate earlier.
1317     for (BaseCommand *Base : Sec->SectionCommands)
1318       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1319         ISD->Sections.erase(
1320             std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1321             ISD->Sections.end());
1322   }
1323 }
1324 
1325 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1326                            std::function<void(SyntheticSection *)> Fn) {
1327   for (SyntheticSection *SS : Sections)
1328     if (SS && SS->getParent() && !SS->empty())
1329       Fn(SS);
1330 }
1331 
1332 // In order to allow users to manipulate linker-synthesized sections,
1333 // we had to add synthetic sections to the input section list early,
1334 // even before we make decisions whether they are needed. This allows
1335 // users to write scripts like this: ".mygot : { .got }".
1336 //
1337 // Doing it has an unintended side effects. If it turns out that we
1338 // don't need a .got (for example) at all because there's no
1339 // relocation that needs a .got, we don't want to emit .got.
1340 //
1341 // To deal with the above problem, this function is called after
1342 // scanRelocations is called to remove synthetic sections that turn
1343 // out to be empty.
1344 static void removeUnusedSyntheticSections() {
1345   // All input synthetic sections that can be empty are placed after
1346   // all regular ones. We iterate over them all and exit at first
1347   // non-synthetic.
1348   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1349     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1350     if (!SS)
1351       return;
1352     OutputSection *OS = SS->getParent();
1353     if (!OS || !SS->empty())
1354       continue;
1355 
1356     // If we reach here, then SS is an unused synthetic section and we want to
1357     // remove it from corresponding input section description of output section.
1358     for (BaseCommand *B : OS->SectionCommands)
1359       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1360         llvm::erase_if(ISD->Sections,
1361                        [=](InputSection *IS) { return IS == SS; });
1362 
1363     // If there are no other alive sections or commands left in the output
1364     // section description, we remove it from the output.
1365     bool IsEmpty = llvm::all_of(OS->SectionCommands, [](BaseCommand *B) {
1366       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1367         return ISD->Sections.empty();
1368       return false;
1369     });
1370     if (IsEmpty)
1371       OS->Live = false;
1372   }
1373 }
1374 
1375 // Returns true if a symbol can be replaced at load-time by a symbol
1376 // with the same name defined in other ELF executable or DSO.
1377 static bool computeIsPreemptible(const Symbol &B) {
1378   assert(!B.isLocal());
1379   // Only symbols that appear in dynsym can be preempted.
1380   if (!B.includeInDynsym())
1381     return false;
1382 
1383   // Only default visibility symbols can be preempted.
1384   if (B.Visibility != STV_DEFAULT)
1385     return false;
1386 
1387   // At this point copy relocations have not been created yet, so any
1388   // symbol that is not defined locally is preemptible.
1389   if (!B.isDefined())
1390     return true;
1391 
1392   // If we have a dynamic list it specifies which local symbols are preemptible.
1393   if (Config->HasDynamicList)
1394     return false;
1395 
1396   if (!Config->Shared)
1397     return false;
1398 
1399   // -Bsymbolic means that definitions are not preempted.
1400   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1401     return false;
1402   return true;
1403 }
1404 
1405 // Create output section objects and add them to OutputSections.
1406 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1407   Out::DebugInfo = findSection(".debug_info");
1408   Out::PreinitArray = findSection(".preinit_array");
1409   Out::InitArray = findSection(".init_array");
1410   Out::FiniArray = findSection(".fini_array");
1411 
1412   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1413   // symbols for sections, so that the runtime can get the start and end
1414   // addresses of each section by section name. Add such symbols.
1415   if (!Config->Relocatable) {
1416     addStartEndSymbols();
1417     for (BaseCommand *Base : Script->SectionCommands)
1418       if (auto *Sec = dyn_cast<OutputSection>(Base))
1419         addStartStopSymbols(Sec);
1420   }
1421 
1422   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1423   // It should be okay as no one seems to care about the type.
1424   // Even the author of gold doesn't remember why gold behaves that way.
1425   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1426   if (InX::DynSymTab)
1427     Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1428                        /*Size=*/0, STB_WEAK, InX::Dynamic,
1429                        /*File=*/nullptr);
1430 
1431   // Define __rel[a]_iplt_{start,end} symbols if needed.
1432   addRelIpltSymbols();
1433 
1434   // This responsible for splitting up .eh_frame section into
1435   // pieces. The relocation scan uses those pieces, so this has to be
1436   // earlier.
1437   applySynthetic({InX::EhFrame},
1438                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1439 
1440   for (Symbol *S : Symtab->getSymbols())
1441     S->IsPreemptible |= computeIsPreemptible(*S);
1442 
1443   // Scan relocations. This must be done after every symbol is declared so that
1444   // we can correctly decide if a dynamic relocation is needed.
1445   if (!Config->Relocatable)
1446     forEachRelSec(scanRelocations<ELFT>);
1447 
1448   if (InX::Plt && !InX::Plt->empty())
1449     InX::Plt->addSymbols();
1450   if (InX::Iplt && !InX::Iplt->empty())
1451     InX::Iplt->addSymbols();
1452 
1453   // Now that we have defined all possible global symbols including linker-
1454   // synthesized ones. Visit all symbols to give the finishing touches.
1455   for (Symbol *Sym : Symtab->getSymbols()) {
1456     if (!includeInSymtab(*Sym))
1457       continue;
1458     if (InX::SymTab)
1459       InX::SymTab->addSymbol(Sym);
1460 
1461     if (InX::DynSymTab && Sym->includeInDynsym()) {
1462       InX::DynSymTab->addSymbol(Sym);
1463       if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1464         if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1465           In<ELFT>::VerNeed->addSymbol(SS);
1466     }
1467   }
1468 
1469   // Do not proceed if there was an undefined symbol.
1470   if (errorCount())
1471     return;
1472 
1473   removeUnusedSyntheticSections();
1474 
1475   sortSections();
1476   Script->removeEmptyCommands();
1477 
1478   // Now that we have the final list, create a list of all the
1479   // OutputSections for convenience.
1480   for (BaseCommand *Base : Script->SectionCommands)
1481     if (auto *Sec = dyn_cast<OutputSection>(Base))
1482       OutputSections.push_back(Sec);
1483 
1484   // Prefer command line supplied address over other constraints.
1485   for (OutputSection *Sec : OutputSections) {
1486     auto I = Config->SectionStartMap.find(Sec->Name);
1487     if (I != Config->SectionStartMap.end())
1488       Sec->AddrExpr = [=] { return I->second; };
1489   }
1490 
1491   // This is a bit of a hack. A value of 0 means undef, so we set it
1492   // to 1 t make __ehdr_start defined. The section number is not
1493   // particularly relevant.
1494   Out::ElfHeader->SectionIndex = 1;
1495 
1496   unsigned I = 1;
1497   for (OutputSection *Sec : OutputSections) {
1498     Sec->SectionIndex = I++;
1499     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1500   }
1501 
1502   // Binary and relocatable output does not have PHDRS.
1503   // The headers have to be created before finalize as that can influence the
1504   // image base and the dynamic section on mips includes the image base.
1505   if (!Config->Relocatable && !Config->OFormatBinary) {
1506     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1507     addPtArmExid(Phdrs);
1508     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1509   }
1510 
1511   // Some symbols are defined in term of program headers. Now that we
1512   // have the headers, we can find out which sections they point to.
1513   setReservedSymbolSections();
1514 
1515   // Dynamic section must be the last one in this list and dynamic
1516   // symbol table section (DynSymTab) must be the first one.
1517   applySynthetic(
1518       {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1519        InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1520        In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1521        InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1522        InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1523        In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1524       [](SyntheticSection *SS) { SS->finalizeContents(); });
1525 
1526   if (!Script->HasSectionsCommand && !Config->Relocatable)
1527     fixSectionAlignments();
1528 
1529   // After link order processing .ARM.exidx sections can be deduplicated, which
1530   // needs to be resolved before any other address dependent operation.
1531   resolveShfLinkOrder();
1532 
1533   // Some architectures need to generate content that depends on the address
1534   // of InputSections. For example some architectures use small displacements
1535   // for jump instructions that is is the linker's responsibility for creating
1536   // range extension thunks for. As the generation of the content may also
1537   // alter InputSection addresses we must converge to a fixed point.
1538   if (Target->NeedsThunks || Config->AndroidPackDynRelocs) {
1539     ThunkCreator TC;
1540     AArch64Err843419Patcher A64P;
1541     bool Changed;
1542     do {
1543       Script->assignAddresses();
1544       Changed = false;
1545       if (Target->NeedsThunks)
1546         Changed |= TC.createThunks(OutputSections);
1547       if (Config->FixCortexA53Errata843419) {
1548         if (Changed)
1549           Script->assignAddresses();
1550         Changed |= A64P.createFixes();
1551       }
1552       if (InX::MipsGot)
1553         InX::MipsGot->updateAllocSize();
1554       Changed |= InX::RelaDyn->updateAllocSize();
1555     } while (Changed);
1556   }
1557 
1558   // Fill other section headers. The dynamic table is finalized
1559   // at the end because some tags like RELSZ depend on result
1560   // of finalizing other sections.
1561   for (OutputSection *Sec : OutputSections)
1562     Sec->finalize<ELFT>();
1563 
1564   // createThunks may have added local symbols to the static symbol table
1565   applySynthetic({InX::SymTab},
1566                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1567 }
1568 
1569 // The linker is expected to define SECNAME_start and SECNAME_end
1570 // symbols for a few sections. This function defines them.
1571 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1572   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1573     // These symbols resolve to the image base if the section does not exist.
1574     // A special value -1 indicates end of the section.
1575     if (OS) {
1576       addOptionalRegular(Start, OS, 0);
1577       addOptionalRegular(End, OS, -1);
1578     } else {
1579       if (Config->Pic)
1580         OS = Out::ElfHeader;
1581       addOptionalRegular(Start, OS, 0);
1582       addOptionalRegular(End, OS, 0);
1583     }
1584   };
1585 
1586   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1587   Define("__init_array_start", "__init_array_end", Out::InitArray);
1588   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1589 
1590   if (OutputSection *Sec = findSection(".ARM.exidx"))
1591     Define("__exidx_start", "__exidx_end", Sec);
1592 }
1593 
1594 // If a section name is valid as a C identifier (which is rare because of
1595 // the leading '.'), linkers are expected to define __start_<secname> and
1596 // __stop_<secname> symbols. They are at beginning and end of the section,
1597 // respectively. This is not requested by the ELF standard, but GNU ld and
1598 // gold provide the feature, and used by many programs.
1599 template <class ELFT>
1600 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1601   StringRef S = Sec->Name;
1602   if (!isValidCIdentifier(S))
1603     return;
1604   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1605   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1606 }
1607 
1608 static bool needsPtLoad(OutputSection *Sec) {
1609   if (!(Sec->Flags & SHF_ALLOC))
1610     return false;
1611 
1612   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1613   // responsible for allocating space for them, not the PT_LOAD that
1614   // contains the TLS initialization image.
1615   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1616     return false;
1617   return true;
1618 }
1619 
1620 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1621 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1622 // RW. This means that there is no alignment in the RO to RX transition and we
1623 // cannot create a PT_LOAD there.
1624 static uint64_t computeFlags(uint64_t Flags) {
1625   if (Config->Omagic)
1626     return PF_R | PF_W | PF_X;
1627   if (Config->SingleRoRx && !(Flags & PF_W))
1628     return Flags | PF_X;
1629   return Flags;
1630 }
1631 
1632 // Decide which program headers to create and which sections to include in each
1633 // one.
1634 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1635   std::vector<PhdrEntry *> Ret;
1636   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1637     Ret.push_back(make<PhdrEntry>(Type, Flags));
1638     return Ret.back();
1639   };
1640 
1641   // The first phdr entry is PT_PHDR which describes the program header itself.
1642   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1643 
1644   // PT_INTERP must be the second entry if exists.
1645   if (OutputSection *Cmd = findSection(".interp"))
1646     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1647 
1648   // Add the first PT_LOAD segment for regular output sections.
1649   uint64_t Flags = computeFlags(PF_R);
1650   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1651 
1652   // Add the headers. We will remove them if they don't fit.
1653   Load->add(Out::ElfHeader);
1654   Load->add(Out::ProgramHeaders);
1655 
1656   for (OutputSection *Sec : OutputSections) {
1657     if (!(Sec->Flags & SHF_ALLOC))
1658       break;
1659     if (!needsPtLoad(Sec))
1660       continue;
1661 
1662     // Segments are contiguous memory regions that has the same attributes
1663     // (e.g. executable or writable). There is one phdr for each segment.
1664     // Therefore, we need to create a new phdr when the next section has
1665     // different flags or is loaded at a discontiguous address using AT linker
1666     // script command.
1667     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1668     if ((Sec->LMAExpr && Load->ASectionHasLMA) ||
1669         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1670 
1671       Load = AddHdr(PT_LOAD, NewFlags);
1672       Flags = NewFlags;
1673     }
1674 
1675     Load->add(Sec);
1676   }
1677 
1678   // Add a TLS segment if any.
1679   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1680   for (OutputSection *Sec : OutputSections)
1681     if (Sec->Flags & SHF_TLS)
1682       TlsHdr->add(Sec);
1683   if (TlsHdr->FirstSec)
1684     Ret.push_back(TlsHdr);
1685 
1686   // Add an entry for .dynamic.
1687   if (InX::DynSymTab)
1688     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1689         ->add(InX::Dynamic->getParent());
1690 
1691   // PT_GNU_RELRO includes all sections that should be marked as
1692   // read-only by dynamic linker after proccessing relocations.
1693   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1694   // an error message if more than one PT_GNU_RELRO PHDR is required.
1695   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1696   bool InRelroPhdr = false;
1697   bool IsRelroFinished = false;
1698   for (OutputSection *Sec : OutputSections) {
1699     if (!needsPtLoad(Sec))
1700       continue;
1701     if (isRelroSection(Sec)) {
1702       InRelroPhdr = true;
1703       if (!IsRelroFinished)
1704         RelRo->add(Sec);
1705       else
1706         error("section: " + Sec->Name + " is not contiguous with other relro" +
1707               " sections");
1708     } else if (InRelroPhdr) {
1709       InRelroPhdr = false;
1710       IsRelroFinished = true;
1711     }
1712   }
1713   if (RelRo->FirstSec)
1714     Ret.push_back(RelRo);
1715 
1716   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1717   if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() &&
1718       InX::EhFrameHdr->getParent())
1719     AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags())
1720         ->add(InX::EhFrameHdr->getParent());
1721 
1722   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1723   // the dynamic linker fill the segment with random data.
1724   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1725     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1726 
1727   // PT_GNU_STACK is a special section to tell the loader to make the
1728   // pages for the stack non-executable. If you really want an executable
1729   // stack, you can pass -z execstack, but that's not recommended for
1730   // security reasons.
1731   unsigned Perm;
1732   if (Config->ZExecstack)
1733     Perm = PF_R | PF_W | PF_X;
1734   else
1735     Perm = PF_R | PF_W;
1736   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1737 
1738   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1739   // is expected to perform W^X violations, such as calling mprotect(2) or
1740   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1741   // OpenBSD.
1742   if (Config->ZWxneeded)
1743     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1744 
1745   // Create one PT_NOTE per a group of contiguous .note sections.
1746   PhdrEntry *Note = nullptr;
1747   for (OutputSection *Sec : OutputSections) {
1748     if (Sec->Type == SHT_NOTE) {
1749       if (!Note || Sec->LMAExpr)
1750         Note = AddHdr(PT_NOTE, PF_R);
1751       Note->add(Sec);
1752     } else {
1753       Note = nullptr;
1754     }
1755   }
1756   return Ret;
1757 }
1758 
1759 template <class ELFT>
1760 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
1761   if (Config->EMachine != EM_ARM)
1762     return;
1763   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
1764     return Cmd->Type == SHT_ARM_EXIDX;
1765   });
1766   if (I == OutputSections.end())
1767     return;
1768 
1769   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1770   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
1771   ARMExidx->add(*I);
1772   Phdrs.push_back(ARMExidx);
1773 }
1774 
1775 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1776 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1777 // linker can set the permissions.
1778 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1779   auto PageAlign = [](OutputSection *Cmd) {
1780     if (Cmd && !Cmd->AddrExpr)
1781       Cmd->AddrExpr = [=] {
1782         return alignTo(Script->getDot(), Config->MaxPageSize);
1783       };
1784   };
1785 
1786   for (const PhdrEntry *P : Phdrs)
1787     if (P->p_type == PT_LOAD && P->FirstSec)
1788       PageAlign(P->FirstSec);
1789 
1790   for (const PhdrEntry *P : Phdrs) {
1791     if (P->p_type != PT_GNU_RELRO)
1792       continue;
1793     if (P->FirstSec)
1794       PageAlign(P->FirstSec);
1795     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1796     // have to align it to a page.
1797     auto End = OutputSections.end();
1798     auto I = std::find(OutputSections.begin(), End, P->LastSec);
1799     if (I == End || (I + 1) == End)
1800       continue;
1801     OutputSection *Cmd = (*(I + 1));
1802     if (needsPtLoad(Cmd))
1803       PageAlign(Cmd);
1804   }
1805 }
1806 
1807 // Adjusts the file alignment for a given output section and returns
1808 // its new file offset. The file offset must be the same with its
1809 // virtual address (modulo the page size) so that the loader can load
1810 // executables without any address adjustment.
1811 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) {
1812   OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr;
1813   // The first section in a PT_LOAD has to have congruent offset and address
1814   // module the page size.
1815   if (Cmd == First)
1816     return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize),
1817                    Cmd->Addr);
1818 
1819   // For SHT_NOBITS we don't want the alignment of the section to impact the
1820   // offset of the sections that follow. Since nothing seems to care about the
1821   // sh_offset of the SHT_NOBITS section itself, just ignore it.
1822   if (Cmd->Type == SHT_NOBITS)
1823     return Off;
1824 
1825   // If the section is not in a PT_LOAD, we just have to align it.
1826   if (!Cmd->PtLoad)
1827     return alignTo(Off, Cmd->Alignment);
1828 
1829   // If two sections share the same PT_LOAD the file offset is calculated
1830   // using this formula: Off2 = Off1 + (VA2 - VA1).
1831   return First->Offset + Cmd->Addr - First->Addr;
1832 }
1833 
1834 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) {
1835   Off = getFileAlignment(Off, Cmd);
1836   Cmd->Offset = Off;
1837 
1838   // For SHT_NOBITS we should not count the size.
1839   if (Cmd->Type == SHT_NOBITS)
1840     return Off;
1841 
1842   return Off + Cmd->Size;
1843 }
1844 
1845 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1846   uint64_t Off = 0;
1847   for (OutputSection *Sec : OutputSections)
1848     if (Sec->Flags & SHF_ALLOC)
1849       Off = setOffset(Sec, Off);
1850   FileSize = alignTo(Off, Config->Wordsize);
1851 }
1852 
1853 // Assign file offsets to output sections.
1854 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1855   uint64_t Off = 0;
1856   Off = setOffset(Out::ElfHeader, Off);
1857   Off = setOffset(Out::ProgramHeaders, Off);
1858 
1859   PhdrEntry *LastRX = nullptr;
1860   for (PhdrEntry *P : Phdrs)
1861     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
1862       LastRX = P;
1863 
1864   for (OutputSection *Sec : OutputSections) {
1865     Off = setOffset(Sec, Off);
1866     if (Script->HasSectionsCommand)
1867       continue;
1868     // If this is a last section of the last executable segment and that
1869     // segment is the last loadable segment, align the offset of the
1870     // following section to avoid loading non-segments parts of the file.
1871     if (LastRX && LastRX->LastSec == Sec)
1872       Off = alignTo(Off, Target->PageSize);
1873   }
1874 
1875   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1876   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1877 }
1878 
1879 // Finalize the program headers. We call this function after we assign
1880 // file offsets and VAs to all sections.
1881 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1882   for (PhdrEntry *P : Phdrs) {
1883     OutputSection *First = P->FirstSec;
1884     OutputSection *Last = P->LastSec;
1885     if (First) {
1886       P->p_filesz = Last->Offset - First->Offset;
1887       if (Last->Type != SHT_NOBITS)
1888         P->p_filesz += Last->Size;
1889       P->p_memsz = Last->Addr + Last->Size - First->Addr;
1890       P->p_offset = First->Offset;
1891       P->p_vaddr = First->Addr;
1892       if (!P->HasLMA)
1893         P->p_paddr = First->getLMA();
1894     }
1895     if (P->p_type == PT_LOAD)
1896       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
1897     else if (P->p_type == PT_GNU_RELRO) {
1898       P->p_align = 1;
1899       // The glibc dynamic loader rounds the size down, so we need to round up
1900       // to protect the last page. This is a no-op on FreeBSD which always
1901       // rounds up.
1902       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
1903     }
1904 
1905     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1906     // so round up the size to make sure the offsets are correct.
1907     if (P->p_type == PT_TLS) {
1908       Out::TlsPhdr = P;
1909       if (P->p_memsz)
1910         P->p_memsz = alignTo(P->p_memsz, P->p_align);
1911     }
1912   }
1913 }
1914 
1915 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
1916   if (Len == 0)
1917     return "<emtpy range at 0x" + utohexstr(Addr) + ">";
1918   return "[0x" + utohexstr(Addr) + " -> 0x" +
1919          utohexstr(Addr + Len - 1) + "]";
1920 }
1921 
1922 // Check whether sections overlap for a specific address range (file offsets,
1923 // load and virtual adresses).
1924 //
1925 // This is a helper function called by Writer::checkNoOverlappingSections().
1926 template <typename Getter, typename Predicate>
1927 static void checkForSectionOverlap(ArrayRef<OutputSection *> AllSections,
1928                                    StringRef Kind, Getter GetStart,
1929                                    Predicate ShouldSkip) {
1930   std::vector<OutputSection *> Sections;
1931   // By removing all zero-size sections we can simplify the check for overlap to
1932   // just checking whether the section range contains the other section's start
1933   // address. Additionally, it also slightly speeds up the checking since we
1934   // don't bother checking for overlap with sections that can never overlap.
1935   for (OutputSection *Sec : AllSections)
1936     if (Sec->Size > 0 && !ShouldSkip(Sec))
1937       Sections.push_back(Sec);
1938 
1939   // Instead of comparing every OutputSection with every other output section
1940   // we sort the sections by address (file offset or load/virtual address). This
1941   // way we find all overlapping sections but only need one comparision with the
1942   // next section in the common non-overlapping case. The only time we end up
1943   // doing more than one iteration of the following nested loop is if there are
1944   // overlapping sections.
1945   std::sort(Sections.begin(), Sections.end(),
1946             [=](const OutputSection *A, const OutputSection *B) {
1947               return GetStart(A) < GetStart(B);
1948             });
1949   for (size_t i = 0; i < Sections.size(); ++i) {
1950     OutputSection *Sec = Sections[i];
1951     uint64_t Start = GetStart(Sec);
1952     for (auto *Other : ArrayRef<OutputSection *>(Sections).slice(i + 1)) {
1953       // Since the sections are storted by start address we only need to check
1954       // whether the other sections starts before the end of Sec. If this is
1955       // not the case we can break out of this loop since all following sections
1956       // will also start after the end of Sec.
1957       if (Start + Sec->Size <= GetStart(Other))
1958         break;
1959       errorOrWarn("section " + Sec->Name + " " + Kind +
1960                   " range overlaps with " + Other->Name + "\n>>> " + Sec->Name +
1961                   " range is " + rangeToString(Start, Sec->Size) + "\n>>> " +
1962                   Other->Name + " range is " +
1963                   rangeToString(GetStart(Other), Other->Size));
1964     }
1965   }
1966 }
1967 
1968 // Check for overlapping sections
1969 //
1970 // In this function we check that none of the output sections have overlapping
1971 // file offsets. For SHF_ALLOC sections we also check that the load address
1972 // ranges and the virtual address ranges don't overlap
1973 template <class ELFT> void Writer<ELFT>::checkNoOverlappingSections() {
1974   // First check for overlapping file offsets. In this case we need to skip
1975   // Any section marked as SHT_NOBITS. These sections don't actually occupy
1976   // space in the file so Sec->Offset + Sec->Size can overlap with others.
1977   // If --oformat binary is specified only add SHF_ALLOC sections are added to
1978   // the output file so we skip any non-allocated sections in that case.
1979   checkForSectionOverlap(
1980       OutputSections, "file", [](const OutputSection *Sec) { return Sec->Offset; },
1981       [](const OutputSection *Sec) {
1982         return Sec->Type == SHT_NOBITS ||
1983                (Config->OFormatBinary && (Sec->Flags & SHF_ALLOC) == 0);
1984       });
1985 
1986   // When linking with -r there is no need to check for overlapping virtual/load
1987   // addresses since those addresses will only be assigned when the final
1988   // executable/shared object is created.
1989   if (Config->Relocatable)
1990     return;
1991 
1992   // Checking for overlapping virtual and load addresses only needs to take
1993   // into account SHF_ALLOC sections since since others will not be loaded.
1994   // Furthermore, we also need to skip SHF_TLS sections since these will be
1995   // mapped to other addresses at runtime and can therefore have overlapping
1996   // ranges in the file.
1997   auto SkipNonAllocSections = [](const OutputSection *Sec) {
1998     return (Sec->Flags & SHF_ALLOC) == 0 || (Sec->Flags & SHF_TLS);
1999   };
2000   checkForSectionOverlap(OutputSections, "virtual address",
2001                          [](const OutputSection *Sec) { return Sec->Addr; },
2002                          SkipNonAllocSections);
2003 
2004   // Finally, check that the load addresses don't overlap. This will usually be
2005   // the same as the virtual addresses but can be different when using a linker
2006   // script with AT().
2007   checkForSectionOverlap(OutputSections, "load address",
2008                          [](const OutputSection *Sec) { return Sec->getLMA(); },
2009                          SkipNonAllocSections);
2010 }
2011 
2012 // The entry point address is chosen in the following ways.
2013 //
2014 // 1. the '-e' entry command-line option;
2015 // 2. the ENTRY(symbol) command in a linker control script;
2016 // 3. the value of the symbol _start, if present;
2017 // 4. the number represented by the entry symbol, if it is a number;
2018 // 5. the address of the first byte of the .text section, if present;
2019 // 6. the address 0.
2020 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
2021   // Case 1, 2 or 3
2022   if (Symbol *B = Symtab->find(Config->Entry))
2023     return B->getVA();
2024 
2025   // Case 4
2026   uint64_t Addr;
2027   if (to_integer(Config->Entry, Addr))
2028     return Addr;
2029 
2030   // Case 5
2031   if (OutputSection *Sec = findSection(".text")) {
2032     if (Config->WarnMissingEntry)
2033       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2034            utohexstr(Sec->Addr));
2035     return Sec->Addr;
2036   }
2037 
2038   // Case 6
2039   if (Config->WarnMissingEntry)
2040     warn("cannot find entry symbol " + Config->Entry +
2041          "; not setting start address");
2042   return 0;
2043 }
2044 
2045 static uint16_t getELFType() {
2046   if (Config->Pic)
2047     return ET_DYN;
2048   if (Config->Relocatable)
2049     return ET_REL;
2050   return ET_EXEC;
2051 }
2052 
2053 template <class ELFT> void Writer<ELFT>::writeHeader() {
2054   uint8_t *Buf = Buffer->getBufferStart();
2055   memcpy(Buf, "\177ELF", 4);
2056 
2057   // Write the ELF header.
2058   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2059   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2060   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2061   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2062   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2063   EHdr->e_type = getELFType();
2064   EHdr->e_machine = Config->EMachine;
2065   EHdr->e_version = EV_CURRENT;
2066   EHdr->e_entry = getEntryAddr();
2067   EHdr->e_shoff = SectionHeaderOff;
2068   EHdr->e_flags = Config->EFlags;
2069   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2070   EHdr->e_phnum = Phdrs.size();
2071   EHdr->e_shentsize = sizeof(Elf_Shdr);
2072   EHdr->e_shnum = OutputSections.size() + 1;
2073   EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
2074 
2075   if (!Config->Relocatable) {
2076     EHdr->e_phoff = sizeof(Elf_Ehdr);
2077     EHdr->e_phentsize = sizeof(Elf_Phdr);
2078   }
2079 
2080   // Write the program header table.
2081   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2082   for (PhdrEntry *P : Phdrs) {
2083     HBuf->p_type = P->p_type;
2084     HBuf->p_flags = P->p_flags;
2085     HBuf->p_offset = P->p_offset;
2086     HBuf->p_vaddr = P->p_vaddr;
2087     HBuf->p_paddr = P->p_paddr;
2088     HBuf->p_filesz = P->p_filesz;
2089     HBuf->p_memsz = P->p_memsz;
2090     HBuf->p_align = P->p_align;
2091     ++HBuf;
2092   }
2093 
2094   // Write the section header table. Note that the first table entry is null.
2095   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2096   for (OutputSection *Sec : OutputSections)
2097     Sec->writeHeaderTo<ELFT>(++SHdrs);
2098 }
2099 
2100 // Open a result file.
2101 template <class ELFT> void Writer<ELFT>::openFile() {
2102   if (!Config->Is64 && FileSize > UINT32_MAX) {
2103     error("output file too large: " + Twine(FileSize) + " bytes");
2104     return;
2105   }
2106 
2107   unlinkAsync(Config->OutputFile);
2108   unsigned Flags = 0;
2109   if (!Config->Relocatable)
2110     Flags = FileOutputBuffer::F_executable;
2111   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2112       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2113 
2114   if (!BufferOrErr)
2115     error("failed to open " + Config->OutputFile + ": " +
2116           llvm::toString(BufferOrErr.takeError()));
2117   else
2118     Buffer = std::move(*BufferOrErr);
2119 }
2120 
2121 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2122   uint8_t *Buf = Buffer->getBufferStart();
2123   for (OutputSection *Sec : OutputSections)
2124     if (Sec->Flags & SHF_ALLOC)
2125       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2126 }
2127 
2128 static void fillTrap(uint8_t *I, uint8_t *End) {
2129   for (; I + 4 <= End; I += 4)
2130     memcpy(I, &Target->TrapInstr, 4);
2131 }
2132 
2133 // Fill the last page of executable segments with trap instructions
2134 // instead of leaving them as zero. Even though it is not required by any
2135 // standard, it is in general a good thing to do for security reasons.
2136 //
2137 // We'll leave other pages in segments as-is because the rest will be
2138 // overwritten by output sections.
2139 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2140   if (Script->HasSectionsCommand)
2141     return;
2142 
2143   // Fill the last page.
2144   uint8_t *Buf = Buffer->getBufferStart();
2145   for (PhdrEntry *P : Phdrs)
2146     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2147       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2148                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2149 
2150   // Round up the file size of the last segment to the page boundary iff it is
2151   // an executable segment to ensure that other tools don't accidentally
2152   // trim the instruction padding (e.g. when stripping the file).
2153   PhdrEntry *Last = nullptr;
2154   for (PhdrEntry *P : Phdrs)
2155     if (P->p_type == PT_LOAD)
2156       Last = P;
2157 
2158   if (Last && (Last->p_flags & PF_X))
2159     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2160 }
2161 
2162 // Write section contents to a mmap'ed file.
2163 template <class ELFT> void Writer<ELFT>::writeSections() {
2164   uint8_t *Buf = Buffer->getBufferStart();
2165 
2166   // PPC64 needs to process relocations in the .opd section
2167   // before processing relocations in code-containing sections.
2168   if (auto *OpdCmd = findSection(".opd")) {
2169     Out::Opd = OpdCmd;
2170     Out::OpdBuf = Buf + Out::Opd->Offset;
2171     OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
2172   }
2173 
2174   OutputSection *EhFrameHdr = nullptr;
2175   if (InX::EhFrameHdr && !InX::EhFrameHdr->empty())
2176     EhFrameHdr = InX::EhFrameHdr->getParent();
2177 
2178   // In -r or -emit-relocs mode, write the relocation sections first as in
2179   // ELf_Rel targets we might find out that we need to modify the relocated
2180   // section while doing it.
2181   for (OutputSection *Sec : OutputSections)
2182     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2183       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2184 
2185   for (OutputSection *Sec : OutputSections)
2186     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
2187         Sec->Type != SHT_RELA)
2188       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2189 
2190   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2191   // it should be written after .eh_frame is written.
2192   if (EhFrameHdr)
2193     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2194 }
2195 
2196 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2197   if (!InX::BuildId || !InX::BuildId->getParent())
2198     return;
2199 
2200   // Compute a hash of all sections of the output file.
2201   uint8_t *Start = Buffer->getBufferStart();
2202   uint8_t *End = Start + FileSize;
2203   InX::BuildId->writeBuildId({Start, End});
2204 }
2205 
2206 template void elf::writeResult<ELF32LE>();
2207 template void elf::writeResult<ELF32BE>();
2208 template void elf::writeResult<ELF64LE>();
2209 template void elf::writeResult<ELF64BE>();
2210