]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Writer.cpp
Merge ^/head r313644 through r313895.
[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 "Config.h"
12 #include "LinkerScript.h"
13 #include "Memory.h"
14 #include "OutputSections.h"
15 #include "Relocations.h"
16 #include "Strings.h"
17 #include "SymbolTable.h"
18 #include "SyntheticSections.h"
19 #include "Target.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/FileOutputBuffer.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <climits>
26 #include <thread>
27
28 using namespace llvm;
29 using namespace llvm::ELF;
30 using namespace llvm::object;
31 using namespace llvm::support;
32 using namespace llvm::support::endian;
33
34 using namespace lld;
35 using namespace lld::elf;
36
37 namespace {
38 // The writer writes a SymbolTable result to a file.
39 template <class ELFT> class Writer {
40 public:
41   typedef typename ELFT::uint uintX_t;
42   typedef typename ELFT::Shdr Elf_Shdr;
43   typedef typename ELFT::Ehdr Elf_Ehdr;
44   typedef typename ELFT::Phdr Elf_Phdr;
45   typedef typename ELFT::Sym Elf_Sym;
46   typedef typename ELFT::SymRange Elf_Sym_Range;
47   typedef typename ELFT::Rela Elf_Rela;
48   void run();
49
50 private:
51   void createSyntheticSections();
52   void copyLocalSymbols();
53   void addReservedSymbols();
54   void addInputSec(InputSectionBase<ELFT> *S);
55   void createSections();
56   void forEachRelSec(std::function<void(InputSectionBase<ELFT> &)> Fn);
57   void sortSections();
58   void finalizeSections();
59   void addPredefinedSections();
60
61   std::vector<PhdrEntry> createPhdrs();
62   void removeEmptyPTLoad();
63   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
64   void assignAddresses();
65   void assignFileOffsets();
66   void assignFileOffsetsBinary();
67   void setPhdrs();
68   void fixHeaders();
69   void fixSectionAlignments();
70   void fixAbsoluteSymbols();
71   void openFile();
72   void writeHeader();
73   void writeSections();
74   void writeSectionsBinary();
75   void writeBuildId();
76
77   std::unique_ptr<FileOutputBuffer> Buffer;
78
79   std::vector<OutputSectionBase *> OutputSections;
80   OutputSectionFactory<ELFT> Factory;
81
82   void addRelIpltSymbols();
83   void addStartEndSymbols();
84   void addStartStopSymbols(OutputSectionBase *Sec);
85   uintX_t getEntryAddr();
86   OutputSectionBase *findSection(StringRef Name);
87
88   std::vector<PhdrEntry> Phdrs;
89
90   uintX_t FileSize;
91   uintX_t SectionHeaderOff;
92   bool AllocateHeader = true;
93 };
94 } // anonymous namespace
95
96 StringRef elf::getOutputSectionName(StringRef Name) {
97   if (Config->Relocatable)
98     return Name;
99
100   for (StringRef V :
101        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
102         ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
103         ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
104     StringRef Prefix = V.drop_back();
105     if (Name.startswith(V) || Name == Prefix)
106       return Prefix;
107   }
108
109   // CommonSection is identified as "COMMON" in linker scripts.
110   // By default, it should go to .bss section.
111   if (Name == "COMMON")
112     return ".bss";
113
114   // ".zdebug_" is a prefix for ZLIB-compressed sections.
115   // Because we decompressed input sections, we want to remove 'z'.
116   if (Name.startswith(".zdebug_"))
117     return Saver.save(Twine(".") + Name.substr(2));
118   return Name;
119 }
120
121 template <class ELFT> void elf::reportDiscarded(InputSectionBase<ELFT> *IS) {
122   if (!Config->PrintGcSections)
123     return;
124   errs() << "removing unused section from '" << IS->Name << "' in file '"
125          << IS->getFile()->getName() << "'\n";
126 }
127
128 template <class ELFT> static bool needsInterpSection() {
129   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
130          !Config->DynamicLinker.empty() &&
131          !Script<ELFT>::X->ignoreInterpSection();
132 }
133
134 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
135
136 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
137   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
138     if (P.p_type != PT_LOAD)
139       return false;
140     if (!P.First)
141       return true;
142     uintX_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
143     return Size == 0;
144   });
145   Phdrs.erase(I, Phdrs.end());
146 }
147
148 // The main function of the writer.
149 template <class ELFT> void Writer<ELFT>::run() {
150   // Create linker-synthesized sections such as .got or .plt.
151   // Such sections are of type input section.
152   createSyntheticSections();
153
154   // We need to create some reserved symbols such as _end. Create them.
155   if (!Config->Relocatable)
156     addReservedSymbols();
157
158   // Some architectures use small displacements for jump instructions.
159   // It is linker's responsibility to create thunks containing long
160   // jump instructions if jump targets are too far. Create thunks.
161   if (Target->NeedsThunks)
162     forEachRelSec(createThunks<ELFT>);
163
164   // Create output sections.
165   Script<ELFT>::X->OutputSections = &OutputSections;
166   if (ScriptConfig->HasSections) {
167     // If linker script contains SECTIONS commands, let it create sections.
168     Script<ELFT>::X->processCommands(Factory);
169
170     // Linker scripts may have left some input sections unassigned.
171     // Assign such sections using the default rule.
172     Script<ELFT>::X->addOrphanSections(Factory);
173   } else {
174     // If linker script does not contain SECTIONS commands, create
175     // output sections by default rules. We still need to give the
176     // linker script a chance to run, because it might contain
177     // non-SECTIONS commands such as ASSERT.
178     createSections();
179     Script<ELFT>::X->processCommands(Factory);
180   }
181
182   if (Config->Discard != DiscardPolicy::All)
183     copyLocalSymbols();
184
185   // Now that we have a complete set of output sections. This function
186   // completes section contents. For example, we need to add strings
187   // to the string table, and add entries to .got and .plt.
188   // finalizeSections does that.
189   finalizeSections();
190   if (ErrorCount)
191     return;
192
193   if (Config->Relocatable) {
194     assignFileOffsets();
195   } else {
196     if (ScriptConfig->HasSections) {
197       Script<ELFT>::X->assignAddresses(Phdrs);
198     } else {
199       fixSectionAlignments();
200       assignAddresses();
201     }
202
203     // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204     // 0 sized region. This has to be done late since only after assignAddresses
205     // we know the size of the sections.
206     removeEmptyPTLoad();
207
208     if (!Config->OFormatBinary)
209       assignFileOffsets();
210     else
211       assignFileOffsetsBinary();
212
213     setPhdrs();
214     fixAbsoluteSymbols();
215   }
216
217   // Write the result down to a file.
218   openFile();
219   if (ErrorCount)
220     return;
221   if (!Config->OFormatBinary) {
222     writeHeader();
223     writeSections();
224   } else {
225     writeSectionsBinary();
226   }
227
228   // Backfill .note.gnu.build-id section content. This is done at last
229   // because the content is usually a hash value of the entire output file.
230   writeBuildId();
231   if (ErrorCount)
232     return;
233
234   if (auto EC = Buffer->commit())
235     error(EC, "failed to write to the output file");
236
237   // Flush the output streams and exit immediately. A full shutdown
238   // is a good test that we are keeping track of all allocated memory,
239   // but actually freeing it is a waste of time in a regular linker run.
240   if (Config->ExitEarly)
241     exitLld(0);
242 }
243
244 // Initialize Out<ELFT> members.
245 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
246   // Initialize all pointers with NULL. This is needed because
247   // you can call lld::elf::main more than once as a library.
248   memset(&Out<ELFT>::First, 0, sizeof(Out<ELFT>));
249
250   // Create singleton output sections.
251   Out<ELFT>::Bss =
252       make<OutputSection<ELFT>>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
253   Out<ELFT>::BssRelRo = make<OutputSection<ELFT>>(".bss.rel.ro", SHT_NOBITS,
254                                                   SHF_ALLOC | SHF_WRITE);
255   In<ELFT>::DynStrTab = make<StringTableSection<ELFT>>(".dynstr", true);
256   In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
257   Out<ELFT>::EhFrame = make<EhOutputSection<ELFT>>();
258   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
259       Config->Rela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
260   In<ELFT>::ShStrTab = make<StringTableSection<ELFT>>(".shstrtab", false);
261
262   Out<ELFT>::ElfHeader = make<OutputSectionBase>("", 0, SHF_ALLOC);
263   Out<ELFT>::ElfHeader->Size = sizeof(Elf_Ehdr);
264   Out<ELFT>::ProgramHeaders = make<OutputSectionBase>("", 0, SHF_ALLOC);
265   Out<ELFT>::ProgramHeaders->updateAlignment(sizeof(uintX_t));
266
267   if (needsInterpSection<ELFT>()) {
268     In<ELFT>::Interp = createInterpSection<ELFT>();
269     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Interp);
270   } else {
271     In<ELFT>::Interp = nullptr;
272   }
273
274   if (!Config->Relocatable)
275     Symtab<ELFT>::X->Sections.push_back(createCommentSection<ELFT>());
276
277   if (Config->Strip != StripPolicy::All) {
278     In<ELFT>::StrTab = make<StringTableSection<ELFT>>(".strtab", false);
279     In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
280   }
281
282   if (Config->BuildId != BuildIdKind::None) {
283     In<ELFT>::BuildId = make<BuildIdSection<ELFT>>();
284     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::BuildId);
285   }
286
287   InputSection<ELFT> *Common = createCommonSection<ELFT>();
288   if (!Common->Data.empty()) {
289     In<ELFT>::Common = Common;
290     Symtab<ELFT>::X->Sections.push_back(Common);
291   }
292
293   // Add MIPS-specific sections.
294   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() || Config->Pic;
295   if (Config->EMachine == EM_MIPS) {
296     if (!Config->Shared && HasDynSymTab) {
297       In<ELFT>::MipsRldMap = make<MipsRldMapSection<ELFT>>();
298       Symtab<ELFT>::X->Sections.push_back(In<ELFT>::MipsRldMap);
299     }
300     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
301       Symtab<ELFT>::X->Sections.push_back(Sec);
302     if (auto *Sec = MipsOptionsSection<ELFT>::create())
303       Symtab<ELFT>::X->Sections.push_back(Sec);
304     if (auto *Sec = MipsReginfoSection<ELFT>::create())
305       Symtab<ELFT>::X->Sections.push_back(Sec);
306   }
307
308   if (HasDynSymTab) {
309     In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
310     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::DynSymTab);
311
312     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
313     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerSym);
314
315     if (!Config->VersionDefinitions.empty()) {
316       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
317       Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerDef);
318     }
319
320     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
321     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::VerNeed);
322
323     if (Config->GnuHash) {
324       In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
325       Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GnuHashTab);
326     }
327
328     if (Config->SysvHash) {
329       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
330       Symtab<ELFT>::X->Sections.push_back(In<ELFT>::HashTab);
331     }
332
333     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Dynamic);
334     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::DynStrTab);
335     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaDyn);
336   }
337
338   // Add .got. MIPS' .got is so different from the other archs,
339   // it has its own class.
340   if (Config->EMachine == EM_MIPS) {
341     In<ELFT>::MipsGot = make<MipsGotSection<ELFT>>();
342     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::MipsGot);
343   } else {
344     In<ELFT>::Got = make<GotSection<ELFT>>();
345     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Got);
346   }
347
348   In<ELFT>::GotPlt = make<GotPltSection<ELFT>>();
349   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GotPlt);
350   In<ELFT>::IgotPlt = make<IgotPltSection<ELFT>>();
351   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::IgotPlt);
352
353   if (Config->GdbIndex) {
354     In<ELFT>::GdbIndex = make<GdbIndexSection<ELFT>>();
355     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::GdbIndex);
356   }
357
358   // We always need to add rel[a].plt to output if it has entries.
359   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
360   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
361       Config->Rela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
362   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaPlt);
363
364   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
365   // that the IRelative relocations are processed last by the dynamic loader
366   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
367       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
368       false /*Sort*/);
369   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::RelaIplt);
370
371   In<ELFT>::Plt = make<PltSection<ELFT>>();
372   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Plt);
373   In<ELFT>::Iplt = make<IpltSection<ELFT>>();
374   Symtab<ELFT>::X->Sections.push_back(In<ELFT>::Iplt);
375
376   if (Config->EhFrameHdr) {
377     In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
378     Symtab<ELFT>::X->Sections.push_back(In<ELFT>::EhFrameHdr);
379   }
380 }
381
382 template <class ELFT>
383 static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
384                                const SymbolBody &B) {
385   if (B.isFile())
386     return false;
387
388   // We keep sections in symtab for relocatable output.
389   if (B.isSection())
390     return Config->Relocatable;
391
392   // If sym references a section in a discarded group, don't keep it.
393   if (Sec == &InputSection<ELFT>::Discarded)
394     return false;
395
396   if (Config->Discard == DiscardPolicy::None)
397     return true;
398
399   // In ELF assembly .L symbols are normally discarded by the assembler.
400   // If the assembler fails to do so, the linker discards them if
401   // * --discard-locals is used.
402   // * The symbol is in a SHF_MERGE section, which is normally the reason for
403   //   the assembler keeping the .L symbol.
404   if (!SymName.startswith(".L") && !SymName.empty())
405     return true;
406
407   if (Config->Discard == DiscardPolicy::Locals)
408     return false;
409
410   return !Sec || !(Sec->Flags & SHF_MERGE);
411 }
412
413 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
414   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
415     return false;
416
417   // If --retain-symbols-file is given, we'll keep only symbols listed in that
418   // file.
419   if (Config->Discard == DiscardPolicy::RetainFile &&
420       !Config->RetainSymbolsFile.count(B.getName()))
421     return false;
422
423   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
424     // Always include absolute symbols.
425     if (!D->Section)
426       return true;
427     // Exclude symbols pointing to garbage-collected sections.
428     if (!D->Section->Live)
429       return false;
430     if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
431       if (!S->getSectionPiece(D->Value)->Live)
432         return false;
433   }
434   return true;
435 }
436
437 // Local symbols are not in the linker's symbol table. This function scans
438 // each object file's symbol table to copy local symbols to the output.
439 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
440   if (!In<ELFT>::SymTab)
441     return;
442   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
443     for (SymbolBody *B : F->getLocalSymbols()) {
444       if (!B->IsLocal)
445         fatal(toString(F) +
446               ": broken object: getLocalSymbols returns a non-local symbol");
447       auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
448
449       // No reason to keep local undefined symbol in symtab.
450       if (!DR)
451         continue;
452       if (!includeInSymtab<ELFT>(*B))
453         continue;
454
455       InputSectionBase<ELFT> *Sec = DR->Section;
456       if (!shouldKeepInSymtab<ELFT>(Sec, B->getName(), *B))
457         continue;
458       In<ELFT>::SymTab->addLocal(B);
459     }
460   }
461 }
462
463 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
464 // we would like to make sure appear is a specific order to maximize their
465 // coverage by a single signed 16-bit offset from the TOC base pointer.
466 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
467 // sections. This will put it next to the loaded special PPC64 sections (and,
468 // thus, within reach of the TOC base pointer).
469 static int getPPC64SectionRank(StringRef SectionName) {
470   return StringSwitch<int>(SectionName)
471       .Case(".tocbss", 0)
472       .Case(".branch_lt", 2)
473       .Case(".toc", 3)
474       .Case(".toc1", 4)
475       .Case(".opd", 5)
476       .Default(1);
477 }
478
479 // All sections with SHF_MIPS_GPREL flag should be grouped together
480 // because data in these sections is addressable with a gp relative address.
481 static int getMipsSectionRank(const OutputSectionBase *S) {
482   if ((S->Flags & SHF_MIPS_GPREL) == 0)
483     return 0;
484   if (S->getName() == ".got")
485     return 1;
486   return 2;
487 }
488
489 template <class ELFT> bool elf::isRelroSection(const OutputSectionBase *Sec) {
490   if (!Config->ZRelro)
491     return false;
492   uint64_t Flags = Sec->Flags;
493   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
494     return false;
495   if (Flags & SHF_TLS)
496     return true;
497   uint32_t Type = Sec->Type;
498   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
499       Type == SHT_PREINIT_ARRAY)
500     return true;
501   if (Sec == In<ELFT>::GotPlt->OutSec)
502     return Config->ZNow;
503   if (Sec == In<ELFT>::Dynamic->OutSec)
504     return true;
505   if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
506     return true;
507   if (Sec == Out<ELFT>::BssRelRo)
508     return true;
509   StringRef S = Sec->getName();
510   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
511          S == ".eh_frame" || S == ".openbsd.randomdata";
512 }
513
514 template <class ELFT>
515 static bool compareSectionsNonScript(const OutputSectionBase *A,
516                                      const OutputSectionBase *B) {
517   // Put .interp first because some loaders want to see that section
518   // on the first page of the executable file when loaded into memory.
519   bool AIsInterp = A->getName() == ".interp";
520   bool BIsInterp = B->getName() == ".interp";
521   if (AIsInterp != BIsInterp)
522     return AIsInterp;
523
524   // Allocatable sections go first to reduce the total PT_LOAD size and
525   // so debug info doesn't change addresses in actual code.
526   bool AIsAlloc = A->Flags & SHF_ALLOC;
527   bool BIsAlloc = B->Flags & SHF_ALLOC;
528   if (AIsAlloc != BIsAlloc)
529     return AIsAlloc;
530
531   // We don't have any special requirements for the relative order of two non
532   // allocatable sections.
533   if (!AIsAlloc)
534     return false;
535
536   // We want to put section specified by -T option first, so we
537   // can start assigning VA starting from them later.
538   auto AAddrSetI = Config->SectionStartMap.find(A->getName());
539   auto BAddrSetI = Config->SectionStartMap.find(B->getName());
540   bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
541   bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
542   if (AHasAddrSet != BHasAddrSet)
543     return AHasAddrSet;
544   if (AHasAddrSet)
545     return AAddrSetI->second < BAddrSetI->second;
546
547   // We want the read only sections first so that they go in the PT_LOAD
548   // covering the program headers at the start of the file.
549   bool AIsWritable = A->Flags & SHF_WRITE;
550   bool BIsWritable = B->Flags & SHF_WRITE;
551   if (AIsWritable != BIsWritable)
552     return BIsWritable;
553
554   if (!Config->SingleRoRx) {
555     // For a corresponding reason, put non exec sections first (the program
556     // header PT_LOAD is not executable).
557     // We only do that if we are not using linker scripts, since with linker
558     // scripts ro and rx sections are in the same PT_LOAD, so their relative
559     // order is not important. The same applies for -no-rosegment.
560     bool AIsExec = A->Flags & SHF_EXECINSTR;
561     bool BIsExec = B->Flags & SHF_EXECINSTR;
562     if (AIsExec != BIsExec)
563       return BIsExec;
564   }
565
566   // If we got here we know that both A and B are in the same PT_LOAD.
567
568   bool AIsTls = A->Flags & SHF_TLS;
569   bool BIsTls = B->Flags & SHF_TLS;
570   bool AIsNoBits = A->Type == SHT_NOBITS;
571   bool BIsNoBits = B->Type == SHT_NOBITS;
572
573   // The first requirement we have is to put (non-TLS) nobits sections last. The
574   // reason is that the only thing the dynamic linker will see about them is a
575   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
576   // PT_LOAD, so that has to correspond to the nobits sections.
577   bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
578   bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
579   if (AIsNonTlsNoBits != BIsNonTlsNoBits)
580     return BIsNonTlsNoBits;
581
582   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
583   // sections after r/w ones, so that the RelRo sections are contiguous.
584   bool AIsRelRo = isRelroSection<ELFT>(A);
585   bool BIsRelRo = isRelroSection<ELFT>(B);
586   if (AIsRelRo != BIsRelRo)
587     return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
588
589   // The TLS initialization block needs to be a single contiguous block in a R/W
590   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
591   // sections. The TLS NOBITS sections are placed here as they don't take up
592   // virtual address space in the PT_LOAD.
593   if (AIsTls != BIsTls)
594     return AIsTls;
595
596   // Within the TLS initialization block, the non-nobits sections need to appear
597   // first.
598   if (AIsNoBits != BIsNoBits)
599     return BIsNoBits;
600
601   // Some architectures have additional ordering restrictions for sections
602   // within the same PT_LOAD.
603   if (Config->EMachine == EM_PPC64)
604     return getPPC64SectionRank(A->getName()) <
605            getPPC64SectionRank(B->getName());
606   if (Config->EMachine == EM_MIPS)
607     return getMipsSectionRank(A) < getMipsSectionRank(B);
608
609   return false;
610 }
611
612 // Output section ordering is determined by this function.
613 template <class ELFT>
614 static bool compareSections(const OutputSectionBase *A,
615                             const OutputSectionBase *B) {
616   // For now, put sections mentioned in a linker script first.
617   int AIndex = Script<ELFT>::X->getSectionIndex(A->getName());
618   int BIndex = Script<ELFT>::X->getSectionIndex(B->getName());
619   bool AInScript = AIndex != INT_MAX;
620   bool BInScript = BIndex != INT_MAX;
621   if (AInScript != BInScript)
622     return AInScript;
623   // If both are in the script, use that order.
624   if (AInScript)
625     return AIndex < BIndex;
626
627   return compareSectionsNonScript<ELFT>(A, B);
628 }
629
630 // Program header entry
631 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
632   p_type = Type;
633   p_flags = Flags;
634 }
635
636 void PhdrEntry::add(OutputSectionBase *Sec) {
637   Last = Sec;
638   if (!First)
639     First = Sec;
640   p_align = std::max(p_align, Sec->Addralign);
641   if (p_type == PT_LOAD)
642     Sec->FirstInPtLoad = First;
643 }
644
645 template <class ELFT>
646 static void addOptionalSynthetic(StringRef Name, OutputSectionBase *Sec,
647                                  typename ELFT::uint Val,
648                                  uint8_t StOther = STV_HIDDEN) {
649   if (SymbolBody *S = Symtab<ELFT>::X->find(Name))
650     if (!S->isInCurrentDSO())
651       Symtab<ELFT>::X->addSynthetic(Name, Sec, Val, StOther);
652 }
653
654 template <class ELFT>
655 static Symbol *addRegular(StringRef Name, InputSectionBase<ELFT> *Sec,
656                           typename ELFT::uint Value) {
657   // The linker generated symbols are added as STB_WEAK to allow user defined
658   // ones to override them.
659   return Symtab<ELFT>::X->addRegular(Name, STV_HIDDEN, STT_NOTYPE, Value,
660                                      /*Size=*/0, STB_WEAK, Sec,
661                                      /*File=*/nullptr);
662 }
663
664 template <class ELFT>
665 static Symbol *addOptionalRegular(StringRef Name, InputSectionBase<ELFT> *IS,
666                                   typename ELFT::uint Value) {
667   SymbolBody *S = Symtab<ELFT>::X->find(Name);
668   if (!S)
669     return nullptr;
670   if (S->isInCurrentDSO())
671     return S->symbol();
672   return addRegular(Name, IS, Value);
673 }
674
675 // The beginning and the ending of .rel[a].plt section are marked
676 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
677 // executable. The runtime needs these symbols in order to resolve
678 // all IRELATIVE relocs on startup. For dynamic executables, we don't
679 // need these symbols, since IRELATIVE relocs are resolved through GOT
680 // and PLT. For details, see http://www.airs.com/blog/archives/403.
681 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
682   if (In<ELFT>::DynSymTab)
683     return;
684   StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
685   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0);
686
687   S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
688   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1);
689 }
690
691 // The linker is expected to define some symbols depending on
692 // the linking result. This function defines such symbols.
693 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
694   if (Config->EMachine == EM_MIPS) {
695     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
696     // so that it points to an absolute address which by default is relative
697     // to GOT. Default offset is 0x7ff0.
698     // See "Global Data Symbols" in Chapter 6 in the following document:
699     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
700     ElfSym<ELFT>::MipsGp =
701         Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
702
703     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
704     // start of function and 'gp' pointer into GOT. To simplify relocation
705     // calculation we assign _gp value to it and calculate corresponding
706     // relocations as relative to this value.
707     if (Symtab<ELFT>::X->find("_gp_disp"))
708       ElfSym<ELFT>::MipsGpDisp =
709           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
710
711     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
712     // pointer. This symbol is used in the code generated by .cpload pseudo-op
713     // in case of using -mno-shared option.
714     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
715     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
716       ElfSym<ELFT>::MipsLocalGp =
717           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
718   }
719
720   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
721   // is magical and is used to produce a R_386_GOTPC relocation.
722   // The R_386_GOTPC relocation value doesn't actually depend on the
723   // symbol value, so it could use an index of STN_UNDEF which, according
724   // to the spec, means the symbol value is 0.
725   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
726   // the object file.
727   // The situation is even stranger on x86_64 where the assembly doesn't
728   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
729   // an undefined symbol in the .o files.
730   // Given that the symbol is effectively unused, we just create a dummy
731   // hidden one to avoid the undefined symbol error.
732   Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
733
734   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
735   // static linking the linker is required to optimize away any references to
736   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
737   // to avoid the undefined symbol error. As usual special cases are ARM and
738   // MIPS - the libc for these targets defines __tls_get_addr itself because
739   // there are no TLS optimizations for these targets.
740   if (!In<ELFT>::DynSymTab &&
741       (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
742     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
743
744   // If linker script do layout we do not need to create any standart symbols.
745   if (ScriptConfig->HasSections)
746     return;
747
748   ElfSym<ELFT>::EhdrStart = Symtab<ELFT>::X->addIgnored("__ehdr_start");
749
750   auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
751                        DefinedRegular<ELFT> *&Sym2) {
752     Sym1 = Symtab<ELFT>::X->addIgnored(S, STV_DEFAULT);
753
754     // The name without the underscore is not a reserved name,
755     // so it is defined only when there is a reference against it.
756     assert(S.startswith("_"));
757     S = S.substr(1);
758     if (SymbolBody *B = Symtab<ELFT>::X->find(S))
759       if (B->isUndefined())
760         Sym2 = Symtab<ELFT>::X->addAbsolute(S, STV_DEFAULT);
761   };
762
763   Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
764   Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
765   Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
766 }
767
768 // Sort input sections by section name suffixes for
769 // __attribute__((init_priority(N))).
770 template <class ELFT> static void sortInitFini(OutputSectionBase *S) {
771   if (S)
772     reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
773 }
774
775 // Sort input sections by the special rule for .ctors and .dtors.
776 template <class ELFT> static void sortCtorsDtors(OutputSectionBase *S) {
777   if (S)
778     reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
779 }
780
781 // Sort input sections using the list provided by --symbol-ordering-file.
782 template <class ELFT>
783 static void sortBySymbolsOrder(ArrayRef<OutputSectionBase *> OutputSections) {
784   if (Config->SymbolOrderingFile.empty())
785     return;
786
787   // Build a map from symbols to their priorities. Symbols that didn't
788   // appear in the symbol ordering file have the lowest priority 0.
789   // All explicitly mentioned symbols have negative (higher) priorities.
790   DenseMap<StringRef, int> SymbolOrder;
791   int Priority = -Config->SymbolOrderingFile.size();
792   for (StringRef S : Config->SymbolOrderingFile)
793     SymbolOrder.insert({S, Priority++});
794
795   // Build a map from sections to their priorities.
796   DenseMap<InputSectionBase<ELFT> *, int> SectionOrder;
797   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
798     for (SymbolBody *Body : File->getSymbols()) {
799       auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
800       if (!D || !D->Section)
801         continue;
802       int &Priority = SectionOrder[D->Section];
803       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
804     }
805   }
806
807   // Sort sections by priority.
808   for (OutputSectionBase *Base : OutputSections)
809     if (auto *Sec = dyn_cast<OutputSection<ELFT>>(Base))
810       Sec->sort([&](InputSection<ELFT> *S) { return SectionOrder.lookup(S); });
811 }
812
813 template <class ELFT>
814 void Writer<ELFT>::forEachRelSec(
815     std::function<void(InputSectionBase<ELFT> &)> Fn) {
816   for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections) {
817     if (!IS->Live)
818       continue;
819     // Scan all relocations. Each relocation goes through a series
820     // of tests to determine if it needs special treatment, such as
821     // creating GOT, PLT, copy relocations, etc.
822     // Note that relocations for non-alloc sections are directly
823     // processed by InputSection::relocateNonAlloc.
824     if (!(IS->Flags & SHF_ALLOC))
825       continue;
826     if (isa<InputSection<ELFT>>(IS) || isa<EhInputSection<ELFT>>(IS))
827       Fn(*IS);
828   }
829 }
830
831 template <class ELFT>
832 void Writer<ELFT>::addInputSec(InputSectionBase<ELFT> *IS) {
833   if (!IS)
834     return;
835
836   if (!IS->Live) {
837     reportDiscarded(IS);
838     return;
839   }
840   OutputSectionBase *Sec;
841   bool IsNew;
842   StringRef OutsecName = getOutputSectionName(IS->Name);
843   std::tie(Sec, IsNew) = Factory.create(IS, OutsecName);
844   if (IsNew)
845     OutputSections.push_back(Sec);
846   Sec->addSection(IS);
847 }
848
849 template <class ELFT> void Writer<ELFT>::createSections() {
850   for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections)
851     addInputSec(IS);
852
853   sortBySymbolsOrder<ELFT>(OutputSections);
854   sortInitFini<ELFT>(findSection(".init_array"));
855   sortInitFini<ELFT>(findSection(".fini_array"));
856   sortCtorsDtors<ELFT>(findSection(".ctors"));
857   sortCtorsDtors<ELFT>(findSection(".dtors"));
858
859   for (OutputSectionBase *Sec : OutputSections)
860     Sec->assignOffsets();
861 }
862
863 template <class ELFT>
864 static bool canSharePtLoad(const OutputSectionBase &S1,
865                            const OutputSectionBase &S2) {
866   if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
867     return false;
868
869   bool S1IsWrite = S1.Flags & SHF_WRITE;
870   bool S2IsWrite = S2.Flags & SHF_WRITE;
871   if (S1IsWrite != S2IsWrite)
872     return false;
873
874   if (!S1IsWrite)
875     return true; // RO and RX share a PT_LOAD with linker scripts.
876   return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
877 }
878
879 template <class ELFT> void Writer<ELFT>::sortSections() {
880   // Don't sort if using -r. It is not necessary and we want to preserve the
881   // relative order for SHF_LINK_ORDER sections.
882   if (Config->Relocatable)
883     return;
884   if (!ScriptConfig->HasSections) {
885     std::stable_sort(OutputSections.begin(), OutputSections.end(),
886                      compareSectionsNonScript<ELFT>);
887     return;
888   }
889   Script<ELFT>::X->adjustSectionsBeforeSorting();
890
891   // The order of the sections in the script is arbitrary and may not agree with
892   // compareSectionsNonScript. This means that we cannot easily define a
893   // strict weak ordering. To see why, consider a comparison of a section in the
894   // script and one not in the script. We have a two simple options:
895   // * Make them equivalent (a is not less than b, and b is not less than a).
896   //   The problem is then that equivalence has to be transitive and we can
897   //   have sections a, b and c with only b in a script and a less than c
898   //   which breaks this property.
899   // * Use compareSectionsNonScript. Given that the script order doesn't have
900   //   to match, we can end up with sections a, b, c, d where b and c are in the
901   //   script and c is compareSectionsNonScript less than b. In which case d
902   //   can be equivalent to c, a to b and d < a. As a concrete example:
903   //   .a (rx) # not in script
904   //   .b (rx) # in script
905   //   .c (ro) # in script
906   //   .d (ro) # not in script
907   //
908   // The way we define an order then is:
909   // *  First put script sections at the start and sort the script and
910   //    non-script sections independently.
911   // *  Move each non-script section to its preferred position. We try
912   //    to put each section in the last position where it it can share
913   //    a PT_LOAD.
914
915   std::stable_sort(OutputSections.begin(), OutputSections.end(),
916                    compareSections<ELFT>);
917
918   auto I = OutputSections.begin();
919   auto E = OutputSections.end();
920   auto NonScriptI =
921       std::find_if(OutputSections.begin(), E, [](OutputSectionBase *S) {
922         return Script<ELFT>::X->getSectionIndex(S->getName()) == INT_MAX;
923       });
924   while (NonScriptI != E) {
925     auto BestPos = std::max_element(
926         I, NonScriptI, [&](OutputSectionBase *&A, OutputSectionBase *&B) {
927           bool ACanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *A);
928           bool BCanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *B);
929           if (ACanSharePtLoad != BCanSharePtLoad)
930             return BCanSharePtLoad;
931
932           bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
933           bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
934           if (ACmp != BCmp)
935             return BCmp; // FIXME: missing test
936
937           size_t PosA = &A - &OutputSections[0];
938           size_t PosB = &B - &OutputSections[0];
939           return ACmp ? PosA > PosB : PosA < PosB;
940         });
941
942     // max_element only returns NonScriptI if the range is empty. If the range
943     // is not empty we should consider moving the the element forward one
944     // position.
945     if (BestPos != NonScriptI &&
946         !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
947       ++BestPos;
948     std::rotate(BestPos, NonScriptI, NonScriptI + 1);
949     ++NonScriptI;
950   }
951
952   Script<ELFT>::X->adjustSectionsAfterSorting();
953 }
954
955 template <class ELFT>
956 static void
957 finalizeSynthetic(const std::vector<SyntheticSection<ELFT> *> &Sections) {
958   for (SyntheticSection<ELFT> *SS : Sections)
959     if (SS && SS->OutSec && !SS->empty()) {
960       SS->finalize();
961       SS->OutSec->Size = 0;
962       SS->OutSec->assignOffsets();
963     }
964 }
965
966 // We need to add input synthetic sections early in createSyntheticSections()
967 // to make them visible from linkescript side. But not all sections are always
968 // required to be in output. For example we don't need dynamic section content
969 // sometimes. This function filters out such unused sections from output.
970 template <class ELFT>
971 static void removeUnusedSyntheticSections(std::vector<OutputSectionBase *> &V) {
972   // Input synthetic sections are placed after all regular ones. We iterate over
973   // them all and exit at first non-synthetic.
974   for (InputSectionBase<ELFT> *S : llvm::reverse(Symtab<ELFT>::X->Sections)) {
975     SyntheticSection<ELFT> *SS = dyn_cast<SyntheticSection<ELFT>>(S);
976     if (!SS)
977       return;
978     if (!SS->empty() || !SS->OutSec)
979       continue;
980
981     OutputSection<ELFT> *OutSec = cast<OutputSection<ELFT>>(SS->OutSec);
982     OutSec->Sections.erase(
983         std::find(OutSec->Sections.begin(), OutSec->Sections.end(), SS));
984     // If there is no other sections in output section, remove it from output.
985     if (OutSec->Sections.empty())
986       V.erase(std::find(V.begin(), V.end(), OutSec));
987   }
988 }
989
990 // Create output section objects and add them to OutputSections.
991 template <class ELFT> void Writer<ELFT>::finalizeSections() {
992   Out<ELFT>::DebugInfo = findSection(".debug_info");
993   Out<ELFT>::PreinitArray = findSection(".preinit_array");
994   Out<ELFT>::InitArray = findSection(".init_array");
995   Out<ELFT>::FiniArray = findSection(".fini_array");
996
997   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
998   // symbols for sections, so that the runtime can get the start and end
999   // addresses of each section by section name. Add such symbols.
1000   if (!Config->Relocatable) {
1001     addStartEndSymbols();
1002     for (OutputSectionBase *Sec : OutputSections)
1003       addStartStopSymbols(Sec);
1004   }
1005
1006   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1007   // It should be okay as no one seems to care about the type.
1008   // Even the author of gold doesn't remember why gold behaves that way.
1009   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1010   if (In<ELFT>::DynSymTab)
1011     addRegular("_DYNAMIC", In<ELFT>::Dynamic, 0);
1012
1013   // Define __rel[a]_iplt_{start,end} symbols if needed.
1014   addRelIpltSymbols();
1015
1016   if (!Out<ELFT>::EhFrame->empty()) {
1017     OutputSections.push_back(Out<ELFT>::EhFrame);
1018     Out<ELFT>::EhFrame->finalize();
1019   }
1020
1021   // Scan relocations. This must be done after every symbol is declared so that
1022   // we can correctly decide if a dynamic relocation is needed.
1023   forEachRelSec(scanRelocations<ELFT>);
1024
1025   // Now that we have defined all possible symbols including linker-
1026   // synthesized ones. Visit all symbols to give the finishing touches.
1027   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1028     SymbolBody *Body = S->body();
1029
1030     if (!includeInSymtab<ELFT>(*Body))
1031       continue;
1032     if (In<ELFT>::SymTab)
1033       In<ELFT>::SymTab->addGlobal(Body);
1034
1035     if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1036       In<ELFT>::DynSymTab->addGlobal(Body);
1037       if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1038         if (SS->file()->isNeeded())
1039           In<ELFT>::VerNeed->addSymbol(SS);
1040     }
1041   }
1042
1043   // Do not proceed if there was an undefined symbol.
1044   if (ErrorCount)
1045     return;
1046
1047   // So far we have added sections from input object files.
1048   // This function adds linker-created Out<ELFT>::* sections.
1049   addPredefinedSections();
1050   removeUnusedSyntheticSections<ELFT>(OutputSections);
1051
1052   sortSections();
1053
1054   unsigned I = 1;
1055   for (OutputSectionBase *Sec : OutputSections) {
1056     Sec->SectionIndex = I++;
1057     Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->getName());
1058   }
1059
1060   // Binary and relocatable output does not have PHDRS.
1061   // The headers have to be created before finalize as that can influence the
1062   // image base and the dynamic section on mips includes the image base.
1063   if (!Config->Relocatable && !Config->OFormatBinary) {
1064     Phdrs = Script<ELFT>::X->hasPhdrsCommands() ? Script<ELFT>::X->createPhdrs()
1065                                                 : createPhdrs();
1066     addPtArmExid(Phdrs);
1067     fixHeaders();
1068   }
1069
1070   // Fill other section headers. The dynamic table is finalized
1071   // at the end because some tags like RELSZ depend on result
1072   // of finalizing other sections.
1073   for (OutputSectionBase *Sec : OutputSections)
1074     Sec->finalize();
1075
1076   // Dynamic section must be the last one in this list and dynamic
1077   // symbol table section (DynSymTab) must be the first one.
1078   finalizeSynthetic<ELFT>(
1079       {In<ELFT>::DynSymTab, In<ELFT>::GnuHashTab, In<ELFT>::HashTab,
1080        In<ELFT>::SymTab,    In<ELFT>::ShStrTab,   In<ELFT>::StrTab,
1081        In<ELFT>::VerDef,    In<ELFT>::DynStrTab,  In<ELFT>::GdbIndex,
1082        In<ELFT>::Got,       In<ELFT>::MipsGot,    In<ELFT>::IgotPlt,
1083        In<ELFT>::GotPlt,    In<ELFT>::RelaDyn,    In<ELFT>::RelaIplt,
1084        In<ELFT>::RelaPlt,   In<ELFT>::Plt,        In<ELFT>::Iplt,
1085        In<ELFT>::Plt,       In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,
1086        In<ELFT>::VerNeed,   In<ELFT>::Dynamic});
1087 }
1088
1089 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1090   if (Out<ELFT>::Bss->Size > 0)
1091     OutputSections.push_back(Out<ELFT>::Bss);
1092   if (Out<ELFT>::BssRelRo->Size > 0)
1093     OutputSections.push_back(Out<ELFT>::BssRelRo);
1094
1095   auto OS = dyn_cast_or_null<OutputSection<ELFT>>(findSection(".ARM.exidx"));
1096   if (OS && !OS->Sections.empty() && !Config->Relocatable)
1097     OS->addSection(make<ARMExidxSentinelSection<ELFT>>());
1098
1099   addInputSec(In<ELFT>::SymTab);
1100   addInputSec(In<ELFT>::ShStrTab);
1101   addInputSec(In<ELFT>::StrTab);
1102 }
1103
1104 // The linker is expected to define SECNAME_start and SECNAME_end
1105 // symbols for a few sections. This function defines them.
1106 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1107   auto Define = [&](StringRef Start, StringRef End, OutputSectionBase *OS) {
1108     // These symbols resolve to the image base if the section does not exist.
1109     // A special value -1 indicates end of the section.
1110     addOptionalSynthetic<ELFT>(Start, OS, 0);
1111     addOptionalSynthetic<ELFT>(End, OS, OS ? -1 : 0);
1112   };
1113
1114   Define("__preinit_array_start", "__preinit_array_end",
1115          Out<ELFT>::PreinitArray);
1116   Define("__init_array_start", "__init_array_end", Out<ELFT>::InitArray);
1117   Define("__fini_array_start", "__fini_array_end", Out<ELFT>::FiniArray);
1118
1119   if (OutputSectionBase *Sec = findSection(".ARM.exidx"))
1120     Define("__exidx_start", "__exidx_end", Sec);
1121 }
1122
1123 // If a section name is valid as a C identifier (which is rare because of
1124 // the leading '.'), linkers are expected to define __start_<secname> and
1125 // __stop_<secname> symbols. They are at beginning and end of the section,
1126 // respectively. This is not requested by the ELF standard, but GNU ld and
1127 // gold provide the feature, and used by many programs.
1128 template <class ELFT>
1129 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase *Sec) {
1130   StringRef S = Sec->getName();
1131   if (!isValidCIdentifier(S))
1132     return;
1133   addOptionalSynthetic<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1134   addOptionalSynthetic<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1135 }
1136
1137 template <class ELFT>
1138 OutputSectionBase *Writer<ELFT>::findSection(StringRef Name) {
1139   for (OutputSectionBase *Sec : OutputSections)
1140     if (Sec->getName() == Name)
1141       return Sec;
1142   return nullptr;
1143 }
1144
1145 template <class ELFT> static bool needsPtLoad(OutputSectionBase *Sec) {
1146   if (!(Sec->Flags & SHF_ALLOC))
1147     return false;
1148
1149   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1150   // responsible for allocating space for them, not the PT_LOAD that
1151   // contains the TLS initialization image.
1152   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1153     return false;
1154   return true;
1155 }
1156
1157 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1158 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1159 // RW. This means that there is no alignment in the RO to RX transition and we
1160 // cannot create a PT_LOAD there.
1161 template <class ELFT>
1162 static typename ELFT::uint computeFlags(typename ELFT::uint F) {
1163   if (Config->OMagic)
1164     return PF_R | PF_W | PF_X;
1165   if (Config->SingleRoRx && !(F & PF_W))
1166     return F | PF_X;
1167   return F;
1168 }
1169
1170 // Decide which program headers to create and which sections to include in each
1171 // one.
1172 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1173   std::vector<PhdrEntry> Ret;
1174   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1175     Ret.emplace_back(Type, Flags);
1176     return &Ret.back();
1177   };
1178
1179   // The first phdr entry is PT_PHDR which describes the program header itself.
1180   PhdrEntry &Hdr = *AddHdr(PT_PHDR, PF_R);
1181   Hdr.add(Out<ELFT>::ProgramHeaders);
1182
1183   // PT_INTERP must be the second entry if exists.
1184   if (OutputSectionBase *Sec = findSection(".interp")) {
1185     PhdrEntry &Hdr = *AddHdr(PT_INTERP, Sec->getPhdrFlags());
1186     Hdr.add(Sec);
1187   }
1188
1189   // Add the first PT_LOAD segment for regular output sections.
1190   uintX_t Flags = computeFlags<ELFT>(PF_R);
1191   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1192
1193   PhdrEntry TlsHdr(PT_TLS, PF_R);
1194   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1195   PhdrEntry Note(PT_NOTE, PF_R);
1196   for (OutputSectionBase *Sec : OutputSections) {
1197     if (!(Sec->Flags & SHF_ALLOC))
1198       break;
1199
1200     // If we meet TLS section then we create TLS header
1201     // and put all TLS sections inside for further use when
1202     // assign addresses.
1203     if (Sec->Flags & SHF_TLS)
1204       TlsHdr.add(Sec);
1205
1206     if (!needsPtLoad<ELFT>(Sec))
1207       continue;
1208
1209     // Segments are contiguous memory regions that has the same attributes
1210     // (e.g. executable or writable). There is one phdr for each segment.
1211     // Therefore, we need to create a new phdr when the next section has
1212     // different flags or is loaded at a discontiguous address using AT linker
1213     // script command.
1214     uintX_t NewFlags = computeFlags<ELFT>(Sec->getPhdrFlags());
1215     if (Script<ELFT>::X->hasLMA(Sec->getName()) || Flags != NewFlags) {
1216       Load = AddHdr(PT_LOAD, NewFlags);
1217       Flags = NewFlags;
1218     }
1219
1220     Load->add(Sec);
1221
1222     if (isRelroSection<ELFT>(Sec))
1223       RelRo.add(Sec);
1224     if (Sec->Type == SHT_NOTE)
1225       Note.add(Sec);
1226   }
1227
1228   // Add the TLS segment unless it's empty.
1229   if (TlsHdr.First)
1230     Ret.push_back(std::move(TlsHdr));
1231
1232   // Add an entry for .dynamic.
1233   if (In<ELFT>::DynSymTab) {
1234     PhdrEntry &H =
1235         *AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags());
1236     H.add(In<ELFT>::Dynamic->OutSec);
1237   }
1238
1239   // PT_GNU_RELRO includes all sections that should be marked as
1240   // read-only by dynamic linker after proccessing relocations.
1241   if (RelRo.First)
1242     Ret.push_back(std::move(RelRo));
1243
1244   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1245   if (!Out<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr) {
1246     PhdrEntry &Hdr =
1247         *AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags());
1248     Hdr.add(In<ELFT>::EhFrameHdr->OutSec);
1249   }
1250
1251   // PT_OPENBSD_RANDOMIZE specifies the location and size of a part of the
1252   // memory image of the program that must be filled with random data before any
1253   // code in the object is executed.
1254   if (OutputSectionBase *Sec = findSection(".openbsd.randomdata")) {
1255     PhdrEntry &Hdr = *AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags());
1256     Hdr.add(Sec);
1257   }
1258
1259   // PT_GNU_STACK is a special section to tell the loader to make the
1260   // pages for the stack non-executable.
1261   if (!Config->ZExecstack) {
1262     PhdrEntry &Hdr = *AddHdr(PT_GNU_STACK, PF_R | PF_W);
1263     if (Config->ZStackSize != uint64_t(-1))
1264       Hdr.p_memsz = Config->ZStackSize;
1265   }
1266
1267   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1268   // is expected to perform W^X violations, such as calling mprotect(2) or
1269   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1270   // OpenBSD.
1271   if (Config->ZWxneeded)
1272     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1273
1274   if (Note.First)
1275     Ret.push_back(std::move(Note));
1276   return Ret;
1277 }
1278
1279 template <class ELFT>
1280 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1281   if (Config->EMachine != EM_ARM)
1282     return;
1283   auto I = std::find_if(
1284       OutputSections.begin(), OutputSections.end(),
1285       [](OutputSectionBase *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1286   if (I == OutputSections.end())
1287     return;
1288
1289   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1290   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1291   ARMExidx.add(*I);
1292   Phdrs.push_back(ARMExidx);
1293 }
1294
1295 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1296 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1297 // linker can set the permissions.
1298 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1299   for (const PhdrEntry &P : Phdrs)
1300     if (P.p_type == PT_LOAD && P.First)
1301       P.First->PageAlign = true;
1302
1303   for (const PhdrEntry &P : Phdrs) {
1304     if (P.p_type != PT_GNU_RELRO)
1305       continue;
1306     if (P.First)
1307       P.First->PageAlign = true;
1308     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1309     // have to align it to a page.
1310     auto End = OutputSections.end();
1311     auto I = std::find(OutputSections.begin(), End, P.Last);
1312     if (I == End || (I + 1) == End)
1313       continue;
1314     OutputSectionBase *Sec = *(I + 1);
1315     if (needsPtLoad<ELFT>(Sec))
1316       Sec->PageAlign = true;
1317   }
1318 }
1319
1320 template <class ELFT>
1321 void elf::allocateHeaders(MutableArrayRef<PhdrEntry> Phdrs,
1322                           ArrayRef<OutputSectionBase *> OutputSections) {
1323   auto FirstPTLoad =
1324       std::find_if(Phdrs.begin(), Phdrs.end(),
1325                    [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1326   if (FirstPTLoad == Phdrs.end())
1327     return;
1328   if (FirstPTLoad->First)
1329     for (OutputSectionBase *Sec : OutputSections)
1330       if (Sec->FirstInPtLoad == FirstPTLoad->First)
1331         Sec->FirstInPtLoad = Out<ELFT>::ElfHeader;
1332   FirstPTLoad->First = Out<ELFT>::ElfHeader;
1333   if (!FirstPTLoad->Last)
1334     FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
1335 }
1336
1337 // We should set file offsets and VAs for elf header and program headers
1338 // sections. These are special, we do not include them into output sections
1339 // list, but have them to simplify the code.
1340 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1341   Out<ELFT>::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1342   // If the script has SECTIONS, assignAddresses will compute the values.
1343   if (ScriptConfig->HasSections)
1344     return;
1345
1346   uintX_t HeaderSize = getHeaderSize<ELFT>();
1347   // When -T<section> option is specified, lower the base to make room for those
1348   // sections.
1349   if (!Config->SectionStartMap.empty()) {
1350     uint64_t Min = -1;
1351     for (const auto &P : Config->SectionStartMap)
1352       Min = std::min(Min, P.second);
1353     if (HeaderSize < Min)
1354       Min -= HeaderSize;
1355     else
1356       AllocateHeader = false;
1357     if (Min < Config->ImageBase)
1358       Config->ImageBase = alignDown(Min, Config->MaxPageSize);
1359   }
1360
1361   if (AllocateHeader)
1362     allocateHeaders<ELFT>(Phdrs, OutputSections);
1363
1364   uintX_t BaseVA = Config->ImageBase;
1365   Out<ELFT>::ElfHeader->Addr = BaseVA;
1366   Out<ELFT>::ProgramHeaders->Addr = BaseVA + Out<ELFT>::ElfHeader->Size;
1367 }
1368
1369 // Assign VAs (addresses at run-time) to output sections.
1370 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1371   uintX_t VA = Config->ImageBase;
1372   if (AllocateHeader)
1373     VA += getHeaderSize<ELFT>();
1374   uintX_t ThreadBssOffset = 0;
1375   for (OutputSectionBase *Sec : OutputSections) {
1376     uintX_t Alignment = Sec->Addralign;
1377     if (Sec->PageAlign)
1378       Alignment = std::max<uintX_t>(Alignment, Config->MaxPageSize);
1379
1380     auto I = Config->SectionStartMap.find(Sec->getName());
1381     if (I != Config->SectionStartMap.end())
1382       VA = I->second;
1383
1384     // We only assign VAs to allocated sections.
1385     if (needsPtLoad<ELFT>(Sec)) {
1386       VA = alignTo(VA, Alignment);
1387       Sec->Addr = VA;
1388       VA += Sec->Size;
1389     } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
1390       uintX_t TVA = VA + ThreadBssOffset;
1391       TVA = alignTo(TVA, Alignment);
1392       Sec->Addr = TVA;
1393       ThreadBssOffset = TVA - VA + Sec->Size;
1394     }
1395   }
1396 }
1397
1398 // Adjusts the file alignment for a given output section and returns
1399 // its new file offset. The file offset must be the same with its
1400 // virtual address (modulo the page size) so that the loader can load
1401 // executables without any address adjustment.
1402 template <class ELFT, class uintX_t>
1403 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase *Sec) {
1404   OutputSectionBase *First = Sec->FirstInPtLoad;
1405   // If the section is not in a PT_LOAD, we just have to align it.
1406   if (!First)
1407     return alignTo(Off, Sec->Addralign);
1408
1409   // The first section in a PT_LOAD has to have congruent offset and address
1410   // module the page size.
1411   if (Sec == First)
1412     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1413
1414   // If two sections share the same PT_LOAD the file offset is calculated
1415   // using this formula: Off2 = Off1 + (VA2 - VA1).
1416   return First->Offset + Sec->Addr - First->Addr;
1417 }
1418
1419 template <class ELFT, class uintX_t>
1420 void setOffset(OutputSectionBase *Sec, uintX_t &Off) {
1421   if (Sec->Type == SHT_NOBITS) {
1422     Sec->Offset = Off;
1423     return;
1424   }
1425
1426   Off = getFileAlignment<ELFT>(Off, Sec);
1427   Sec->Offset = Off;
1428   Off += Sec->Size;
1429 }
1430
1431 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1432   uintX_t Off = 0;
1433   for (OutputSectionBase *Sec : OutputSections)
1434     if (Sec->Flags & SHF_ALLOC)
1435       setOffset<ELFT>(Sec, Off);
1436   FileSize = alignTo(Off, sizeof(uintX_t));
1437 }
1438
1439 // Assign file offsets to output sections.
1440 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1441   uintX_t Off = 0;
1442   setOffset<ELFT>(Out<ELFT>::ElfHeader, Off);
1443   setOffset<ELFT>(Out<ELFT>::ProgramHeaders, Off);
1444
1445   for (OutputSectionBase *Sec : OutputSections)
1446     setOffset<ELFT>(Sec, Off);
1447
1448   SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1449   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1450 }
1451
1452 // Finalize the program headers. We call this function after we assign
1453 // file offsets and VAs to all sections.
1454 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1455   for (PhdrEntry &P : Phdrs) {
1456     OutputSectionBase *First = P.First;
1457     OutputSectionBase *Last = P.Last;
1458     if (First) {
1459       P.p_filesz = Last->Offset - First->Offset;
1460       if (Last->Type != SHT_NOBITS)
1461         P.p_filesz += Last->Size;
1462       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1463       P.p_offset = First->Offset;
1464       P.p_vaddr = First->Addr;
1465       if (!P.HasLMA)
1466         P.p_paddr = First->getLMA();
1467     }
1468     if (P.p_type == PT_LOAD)
1469       P.p_align = Config->MaxPageSize;
1470     else if (P.p_type == PT_GNU_RELRO)
1471       P.p_align = 1;
1472
1473     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1474     // so round up the size to make sure the offsets are correct.
1475     if (P.p_type == PT_TLS) {
1476       Out<ELFT>::TlsPhdr = &P;
1477       if (P.p_memsz)
1478         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1479     }
1480   }
1481 }
1482
1483 // The entry point address is chosen in the following ways.
1484 //
1485 // 1. the '-e' entry command-line option;
1486 // 2. the ENTRY(symbol) command in a linker control script;
1487 // 3. the value of the symbol start, if present;
1488 // 4. the address of the first byte of the .text section, if present;
1489 // 5. the address 0.
1490 template <class ELFT> typename ELFT::uint Writer<ELFT>::getEntryAddr() {
1491   // Case 1, 2 or 3. As a special case, if the symbol is actually
1492   // a number, we'll use that number as an address.
1493   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1494     return B->getVA<ELFT>();
1495   uint64_t Addr;
1496   if (!Config->Entry.getAsInteger(0, Addr))
1497     return Addr;
1498
1499   // Case 4
1500   if (OutputSectionBase *Sec = findSection(".text")) {
1501     if (Config->WarnMissingEntry)
1502       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1503            utohexstr(Sec->Addr));
1504     return Sec->Addr;
1505   }
1506
1507   // Case 5
1508   if (Config->WarnMissingEntry)
1509     warn("cannot find entry symbol " + Config->Entry +
1510          "; not setting start address");
1511   return 0;
1512 }
1513
1514 template <class ELFT> static uint8_t getELFEncoding() {
1515   if (ELFT::TargetEndianness == llvm::support::little)
1516     return ELFDATA2LSB;
1517   return ELFDATA2MSB;
1518 }
1519
1520 static uint16_t getELFType() {
1521   if (Config->Pic)
1522     return ET_DYN;
1523   if (Config->Relocatable)
1524     return ET_REL;
1525   return ET_EXEC;
1526 }
1527
1528 // This function is called after we have assigned address and size
1529 // to each section. This function fixes some predefined absolute
1530 // symbol values that depend on section address and size.
1531 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1532   // __ehdr_start is the location of program headers.
1533   if (ElfSym<ELFT>::EhdrStart)
1534     ElfSym<ELFT>::EhdrStart->Value = Out<ELFT>::ProgramHeaders->Addr;
1535
1536   auto Set = [](DefinedRegular<ELFT> *S1, DefinedRegular<ELFT> *S2, uintX_t V) {
1537     if (S1)
1538       S1->Value = V;
1539     if (S2)
1540       S2->Value = V;
1541   };
1542
1543   // _etext is the first location after the last read-only loadable segment.
1544   // _edata is the first location after the last read-write loadable segment.
1545   // _end is the first location after the uninitialized data region.
1546   for (PhdrEntry &P : Phdrs) {
1547     if (P.p_type != PT_LOAD)
1548       continue;
1549     Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, P.p_vaddr + P.p_memsz);
1550
1551     uintX_t Val = P.p_vaddr + P.p_filesz;
1552     if (P.p_flags & PF_W)
1553       Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
1554     else
1555       Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
1556   }
1557
1558   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1559   // be equal to the _gp symbol's value.
1560   if (Config->EMachine == EM_MIPS) {
1561     if (!ElfSym<ELFT>::MipsGp->Value) {
1562       // Find GP-relative section with the lowest address
1563       // and use this address to calculate default _gp value.
1564       uintX_t Gp = -1;
1565       for (const OutputSectionBase * OS : OutputSections)
1566         if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1567           Gp = OS->Addr;
1568       if (Gp != (uintX_t)-1)
1569         ElfSym<ELFT>::MipsGp->Value = Gp + 0x7ff0;
1570     }
1571     if (ElfSym<ELFT>::MipsGpDisp)
1572       ElfSym<ELFT>::MipsGpDisp->Value = ElfSym<ELFT>::MipsGp->Value;
1573     if (ElfSym<ELFT>::MipsLocalGp)
1574       ElfSym<ELFT>::MipsLocalGp->Value = ElfSym<ELFT>::MipsGp->Value;
1575   }
1576 }
1577
1578 template <class ELFT> void Writer<ELFT>::writeHeader() {
1579   uint8_t *Buf = Buffer->getBufferStart();
1580   memcpy(Buf, "\177ELF", 4);
1581
1582   // Write the ELF header.
1583   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1584   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1585   EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1586   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1587   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1588   EHdr->e_type = getELFType();
1589   EHdr->e_machine = Config->EMachine;
1590   EHdr->e_version = EV_CURRENT;
1591   EHdr->e_entry = getEntryAddr();
1592   EHdr->e_shoff = SectionHeaderOff;
1593   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1594   EHdr->e_phnum = Phdrs.size();
1595   EHdr->e_shentsize = sizeof(Elf_Shdr);
1596   EHdr->e_shnum = OutputSections.size() + 1;
1597   EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1598
1599   if (Config->EMachine == EM_ARM)
1600     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1601     // but we don't have any firm guarantees of conformance. Linux AArch64
1602     // kernels (as of 2016) require an EABI version to be set.
1603     EHdr->e_flags = EF_ARM_EABI_VER5;
1604   else if (Config->EMachine == EM_MIPS)
1605     EHdr->e_flags = getMipsEFlags<ELFT>();
1606
1607   if (!Config->Relocatable) {
1608     EHdr->e_phoff = sizeof(Elf_Ehdr);
1609     EHdr->e_phentsize = sizeof(Elf_Phdr);
1610   }
1611
1612   // Write the program header table.
1613   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1614   for (PhdrEntry &P : Phdrs) {
1615     HBuf->p_type = P.p_type;
1616     HBuf->p_flags = P.p_flags;
1617     HBuf->p_offset = P.p_offset;
1618     HBuf->p_vaddr = P.p_vaddr;
1619     HBuf->p_paddr = P.p_paddr;
1620     HBuf->p_filesz = P.p_filesz;
1621     HBuf->p_memsz = P.p_memsz;
1622     HBuf->p_align = P.p_align;
1623     ++HBuf;
1624   }
1625
1626   // Write the section header table. Note that the first table entry is null.
1627   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1628   for (OutputSectionBase *Sec : OutputSections)
1629     Sec->writeHeaderTo<ELFT>(++SHdrs);
1630 }
1631
1632 // Removes a given file asynchronously. This is a performance hack,
1633 // so remove this when operating systems are improved.
1634 //
1635 // On Linux (and probably on other Unix-like systems), unlink(2) is a
1636 // noticeably slow system call. As of 2016, unlink takes 250
1637 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
1638 //
1639 // To create a new result file, we first remove existing file. So, if
1640 // you repeatedly link a 1 GB program in a regular compile-link-debug
1641 // cycle, every cycle wastes 250 milliseconds only to remove a file.
1642 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
1643 // actually counts.
1644 //
1645 // This function spawns a background thread to call unlink.
1646 // The calling thread returns almost immediately.
1647 static void unlinkAsync(StringRef Path) {
1648   if (!Config->Threads || !sys::fs::exists(Config->OutputFile))
1649     return;
1650
1651   // First, rename Path to avoid race condition. We cannot remove
1652   // Path from a different thread because we are now going to create
1653   // Path as a new file. If we do that in a different thread, the new
1654   // thread can remove the new file.
1655   SmallString<128> TempPath;
1656   if (sys::fs::createUniqueFile(Path + "tmp%%%%%%%%", TempPath))
1657     return;
1658   if (sys::fs::rename(Path, TempPath)) {
1659     sys::fs::remove(TempPath);
1660     return;
1661   }
1662
1663   // Remove TempPath in background.
1664   std::thread([=] { ::remove(TempPath.str().str().c_str()); }).detach();
1665 }
1666
1667 // Open a result file.
1668 template <class ELFT> void Writer<ELFT>::openFile() {
1669   unlinkAsync(Config->OutputFile);
1670   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1671       FileOutputBuffer::create(Config->OutputFile, FileSize,
1672                                FileOutputBuffer::F_executable);
1673
1674   if (auto EC = BufferOrErr.getError())
1675     error(EC, "failed to open " + Config->OutputFile);
1676   else
1677     Buffer = std::move(*BufferOrErr);
1678 }
1679
1680 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1681   uint8_t *Buf = Buffer->getBufferStart();
1682   for (OutputSectionBase *Sec : OutputSections)
1683     if (Sec->Flags & SHF_ALLOC)
1684       Sec->writeTo(Buf + Sec->Offset);
1685 }
1686
1687 // Write section contents to a mmap'ed file.
1688 template <class ELFT> void Writer<ELFT>::writeSections() {
1689   uint8_t *Buf = Buffer->getBufferStart();
1690
1691   // PPC64 needs to process relocations in the .opd section
1692   // before processing relocations in code-containing sections.
1693   Out<ELFT>::Opd = findSection(".opd");
1694   if (Out<ELFT>::Opd) {
1695     Out<ELFT>::OpdBuf = Buf + Out<ELFT>::Opd->Offset;
1696     Out<ELFT>::Opd->writeTo(Buf + Out<ELFT>::Opd->Offset);
1697   }
1698
1699   OutputSectionBase *EhFrameHdr =
1700       In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1701   for (OutputSectionBase *Sec : OutputSections)
1702     if (Sec != Out<ELFT>::Opd && Sec != EhFrameHdr)
1703       Sec->writeTo(Buf + Sec->Offset);
1704
1705   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1706   // it should be written after .eh_frame is written.
1707   if (!Out<ELFT>::EhFrame->empty() && EhFrameHdr)
1708     EhFrameHdr->writeTo(Buf + EhFrameHdr->Offset);
1709 }
1710
1711 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1712   if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1713     return;
1714
1715   // Compute a hash of all sections of the output file.
1716   uint8_t *Start = Buffer->getBufferStart();
1717   uint8_t *End = Start + FileSize;
1718   In<ELFT>::BuildId->writeBuildId({Start, End});
1719 }
1720
1721 template void elf::writeResult<ELF32LE>();
1722 template void elf::writeResult<ELF32BE>();
1723 template void elf::writeResult<ELF64LE>();
1724 template void elf::writeResult<ELF64BE>();
1725
1726 template void elf::allocateHeaders<ELF32LE>(MutableArrayRef<PhdrEntry>,
1727                                             ArrayRef<OutputSectionBase *>);
1728 template void elf::allocateHeaders<ELF32BE>(MutableArrayRef<PhdrEntry>,
1729                                             ArrayRef<OutputSectionBase *>);
1730 template void elf::allocateHeaders<ELF64LE>(MutableArrayRef<PhdrEntry>,
1731                                             ArrayRef<OutputSectionBase *>);
1732 template void elf::allocateHeaders<ELF64BE>(MutableArrayRef<PhdrEntry>,
1733                                             ArrayRef<OutputSectionBase *>);
1734
1735 template bool elf::isRelroSection<ELF32LE>(const OutputSectionBase *);
1736 template bool elf::isRelroSection<ELF32BE>(const OutputSectionBase *);
1737 template bool elf::isRelroSection<ELF64LE>(const OutputSectionBase *);
1738 template bool elf::isRelroSection<ELF64BE>(const OutputSectionBase *);
1739
1740 template void elf::reportDiscarded<ELF32LE>(InputSectionBase<ELF32LE> *);
1741 template void elf::reportDiscarded<ELF32BE>(InputSectionBase<ELF32BE> *);
1742 template void elf::reportDiscarded<ELF64LE>(InputSectionBase<ELF64LE> *);
1743 template void elf::reportDiscarded<ELF64BE>(InputSectionBase<ELF64BE> *);