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