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