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