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