xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 98607b67)
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 "OutputSections.h"
13 #include "SymbolTable.h"
14 #include "Target.h"
15 
16 #include "llvm/Support/FileOutputBuffer.h"
17 
18 using namespace llvm;
19 using namespace llvm::ELF;
20 using namespace llvm::object;
21 
22 using namespace lld;
23 using namespace lld::elf2;
24 
25 static const int PageSize = 4096;
26 
27 // On freebsd x86_64 the first page cannot be mmaped.
28 // On linux that is controled by vm.mmap_min_addr. At least on some x86_64
29 // installs that is 65536, so the first 15 pages cannot be used.
30 // Given that, the smallest value that can be used in here is 0x10000.
31 // If using 2MB pages, the smallest page aligned address that works is
32 // 0x200000, but it looks like every OS uses 4k pages for executables.
33 // FIXME: This is architecture and OS dependent.
34 static const int VAStart = 0x10000;
35 
36 namespace {
37 
38 static uint32_t convertSectionFlagsToPHDRFlags(uint64_t Flags) {
39   uint32_t Ret = PF_R;
40   if (Flags & SHF_WRITE)
41     Ret |= PF_W;
42 
43   if (Flags & SHF_EXECINSTR)
44     Ret |= PF_X;
45 
46   return Ret;
47 }
48 
49 template <bool Is64Bits>
50 class ProgramHeader {
51 public:
52   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
53   typedef
54     typename std::conditional<Is64Bits, Elf64_Phdr, Elf32_Phdr>::type HeaderT;
55 
56   ProgramHeader(uintX_t p_type, uintX_t p_flags) {
57     std::memset(&Header, 0, sizeof(HeaderT));
58     Header.p_type = p_type;
59     Header.p_flags = p_flags;
60     Header.p_align = PageSize;
61   }
62 
63   void setValuesFromSection(OutputSectionBase<Is64Bits> &Sec) {
64     Header.p_flags = convertSectionFlagsToPHDRFlags(Sec.getFlags());
65     Header.p_offset = Sec.getFileOff();
66     Header.p_vaddr = Sec.getVA();
67     Header.p_paddr = Header.p_vaddr;
68     Header.p_filesz = Sec.getSize();
69     Header.p_memsz = Header.p_filesz;
70     Header.p_align = Sec.getAlign();
71   }
72 
73   template <endianness E>
74   void writeHeaderTo(typename ELFFile<ELFType<E, Is64Bits>>::Elf_Phdr *PHDR) {
75     PHDR->p_type = Header.p_type;
76     PHDR->p_flags = Header.p_flags;
77     PHDR->p_offset = Header.p_offset;
78     PHDR->p_vaddr = Header.p_vaddr;
79     PHDR->p_paddr = Header.p_paddr;
80     PHDR->p_filesz = Header.p_filesz;
81     PHDR->p_memsz = Header.p_memsz;
82     PHDR->p_align = Header.p_align;
83   }
84 
85   HeaderT Header;
86   bool Closed = false;
87 };
88 
89 // The writer writes a SymbolTable result to a file.
90 template <class ELFT> class Writer {
91 public:
92   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
93   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
94   typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
95   typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
96   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
97   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
98   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
99   Writer(SymbolTable *T)
100       : SymTabSec(*T, StrTabSec, BssSec), DynSymSec(*T, DynStrSec, BssSec),
101         RelaDynSec(DynSymSec, GotSec, T->shouldUseRela()), PltSec(GotSec),
102         HashSec(DynSymSec), DynamicSec(*T, HashSec, RelaDynSec),
103         BssSec(PltSec, GotSec, BssSec, ".bss", SHT_NOBITS,
104                SHF_ALLOC | SHF_WRITE) {}
105   void run();
106 
107 private:
108   void createSections();
109   template <bool isRela>
110   void scanRelocs(const InputSection<ELFT> &C,
111                   iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
112   void scanRelocs(const InputSection<ELFT> &C);
113   void assignAddresses();
114   void openFile(StringRef OutputPath);
115   void writeHeader();
116   void writeSections();
117   bool needsInterpSection() const {
118     return !SymTabSec.getSymTable().getSharedFiles().empty() &&
119            !Config->DynamicLinker.empty();
120   }
121   bool needsDynamicSections() const {
122     return !SymTabSec.getSymTable().getSharedFiles().empty() || Config->Shared;
123   }
124   unsigned getVAStart() const { return Config->Shared ? 0 : VAStart; }
125 
126   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
127 
128   llvm::SpecificBumpPtrAllocator<OutputSection<ELFT>> CAlloc;
129   std::vector<OutputSectionBase<ELFT::Is64Bits> *> OutputSections;
130   unsigned getNumSections() const { return OutputSections.size() + 1; }
131 
132   llvm::BumpPtrAllocator PAlloc;
133   std::vector<ProgramHeader<ELFT::Is64Bits> *> PHDRs;
134   ProgramHeader<ELFT::Is64Bits> FileHeaderPHDR{PT_LOAD, PF_R};
135   ProgramHeader<ELFT::Is64Bits> InterpPHDR{PT_INTERP, 0};
136   ProgramHeader<ELFT::Is64Bits> DynamicPHDR{PT_DYNAMIC, 0};
137 
138   uintX_t FileSize;
139   uintX_t ProgramHeaderOff;
140   uintX_t SectionHeaderOff;
141 
142   StringTableSection<ELFT::Is64Bits> StrTabSec = { /*dynamic=*/false };
143   StringTableSection<ELFT::Is64Bits> DynStrSec = { /*dynamic=*/true };
144 
145   lld::elf2::SymbolTableSection<ELFT> SymTabSec;
146   lld::elf2::SymbolTableSection<ELFT> DynSymSec;
147 
148   RelocationSection<ELFT> RelaDynSec;
149 
150   GotSection<ELFT> GotSec;
151   PltSection<ELFT> PltSec;
152 
153   HashTableSection<ELFT> HashSec;
154 
155   DynamicSection<ELFT> DynamicSec;
156 
157   InterpSection<ELFT::Is64Bits> InterpSec;
158 
159   OutputSection<ELFT> BssSec;
160 };
161 } // anonymous namespace
162 
163 namespace lld {
164 namespace elf2 {
165 
166 template <class ELFT>
167 void writeResult(SymbolTable *Symtab) { Writer<ELFT>(Symtab).run(); }
168 
169 template void writeResult<ELF32LE>(SymbolTable *);
170 template void writeResult<ELF32BE>(SymbolTable *);
171 template void writeResult<ELF64LE>(SymbolTable *);
172 template void writeResult<ELF64BE>(SymbolTable *);
173 
174 } // namespace elf2
175 } // namespace lld
176 
177 // The main function of the writer.
178 template <class ELFT> void Writer<ELFT>::run() {
179   createSections();
180   assignAddresses();
181   openFile(Config->OutputFile);
182   writeHeader();
183   writeSections();
184   error(Buffer->commit());
185 }
186 
187 template <class ELFT>
188 static int compareSym(const typename ELFFile<ELFT>::Elf_Sym *A,
189                       const typename ELFFile<ELFT>::Elf_Sym *B) {
190   uint32_t AN = A->st_name;
191   uint32_t BN = B->st_name;
192   assert(AN != BN);
193   return AN - BN;
194 }
195 
196 namespace {
197 template <bool Is64Bits> struct SectionKey {
198   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
199   StringRef Name;
200   uint32_t sh_type;
201   uintX_t sh_flags;
202 };
203 }
204 namespace llvm {
205 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
206   static SectionKey<Is64Bits> getEmptyKey() {
207     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
208   }
209   static SectionKey<Is64Bits> getTombstoneKey() {
210     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
211                                 0};
212   }
213   static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
214     return hash_combine(Val.Name, Val.sh_type, Val.sh_flags);
215   }
216   static bool isEqual(const SectionKey<Is64Bits> &LHS,
217                       const SectionKey<Is64Bits> &RHS) {
218     return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
219            LHS.sh_type == RHS.sh_type && LHS.sh_flags == RHS.sh_flags;
220   }
221 };
222 }
223 
224 template <class ELFT>
225 static bool cmpAlign(const DefinedCommon<ELFT> *A,
226                      const DefinedCommon<ELFT> *B) {
227   return A->MaxAlignment > B->MaxAlignment;
228 }
229 
230 template <bool Is64Bits>
231 static bool compSec(OutputSectionBase<Is64Bits> *A,
232                     OutputSectionBase<Is64Bits> *B) {
233   // Place SHF_ALLOC sections first.
234   return (A->getFlags() & SHF_ALLOC) && !(B->getFlags() & SHF_ALLOC);
235 }
236 
237 // The reason we have to do this early scan is as follows
238 // * To mmap the output file, we need to know the size
239 // * For that, we need to know how many dynamic relocs we will have.
240 // It might be possible to avoid this by outputting the file with write:
241 // * Write the allocated output sections, computing addresses.
242 // * Apply relocations, recording which ones require a dynamic reloc.
243 // * Write the dynamic relocations.
244 // * Write the rest of the file.
245 template <class ELFT>
246 template <bool isRela>
247 void Writer<ELFT>::scanRelocs(
248     const InputSection<ELFT> &C,
249     iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
250   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
251   const ObjectFile<ELFT> &File = *C.getFile();
252   bool IsMips64EL = File.getObj()->isMips64EL();
253   for (const RelType &RI : Rels) {
254     uint32_t SymIndex = RI.getSymbol(IsMips64EL);
255     SymbolBody *Body = File.getSymbolBody(SymIndex);
256     if (!Body)
257       continue;
258     uint32_t Type = RI.getType(IsMips64EL);
259     if (Target->relocNeedsPlt(Type)) {
260       if (Body->isInPlt())
261         continue;
262       PltSec.addEntry(Body);
263     }
264     if (Target->relocNeedsGot(Type)) {
265       if (Body->isInGot())
266         continue;
267       GotSec.addEntry(Body);
268     }
269     if (!isa<SharedSymbol<ELFT>>(Body))
270       continue;
271     Body->setUsedInDynamicReloc();
272     RelaDynSec.addReloc({C, RI});
273   }
274 }
275 
276 template <class ELFT>
277 void Writer<ELFT>::scanRelocs(const InputSection<ELFT> &C) {
278   const ObjectFile<ELFT> *File = C.getFile();
279   ELFFile<ELFT> *EObj = File->getObj();
280 
281   if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
282     return;
283 
284   for (const Elf_Shdr *RelSec : C.RelocSections) {
285     if (RelSec->sh_type == SHT_RELA)
286       scanRelocs(C, EObj->relas(RelSec));
287     else
288       scanRelocs(C, EObj->rels(RelSec));
289   }
290 }
291 
292 template <class ELFT>
293 static void undefError(const SymbolTable &S, const SymbolBody &Sym) {
294   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
295   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
296 
297   const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym;
298   ELFFileBase *SymFile = nullptr;
299 
300   for (const std::unique_ptr<ObjectFileBase> &F : S.getObjectFiles()) {
301     const auto &File = cast<ObjectFile<ELFT>>(*F);
302     Elf_Sym_Range Syms = File.getObj()->symbols(File.getSymbolTable());
303     if (&SymE > Syms.begin() && &SymE < Syms.end())
304       SymFile = F.get();
305   }
306   if (SymFile)
307     error(Twine("undefined symbol: ") + Sym.getName() + " in " +
308           SymFile->getName());
309   else
310     error(Twine("undefined symbol: ") + Sym.getName());
311 }
312 
313 // Create output section objects and add them to OutputSections.
314 template <class ELFT> void Writer<ELFT>::createSections() {
315   SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSection<ELFT> *> Map;
316 
317   OutputSections.push_back(&BssSec);
318   Map[{BssSec.getName(), BssSec.getType(), BssSec.getFlags()}] = &BssSec;
319 
320   auto getSection = [&](StringRef Name, uint32_t sh_type,
321                         uintX_t sh_flags) -> OutputSection<ELFT> * {
322     SectionKey<ELFT::Is64Bits> Key{Name, sh_type, sh_flags};
323     OutputSection<ELFT> *&Sec = Map[Key];
324     if (!Sec) {
325       Sec = new (CAlloc.Allocate()) OutputSection<ELFT>(
326           PltSec, GotSec, BssSec, Key.Name, Key.sh_type, Key.sh_flags);
327       OutputSections.push_back(Sec);
328     }
329     return Sec;
330   };
331 
332   const SymbolTable &Symtab = SymTabSec.getSymTable();
333   for (const std::unique_ptr<ObjectFileBase> &FileB : Symtab.getObjectFiles()) {
334     auto &File = cast<ObjectFile<ELFT>>(*FileB);
335     if (!Config->DiscardAll) {
336       Elf_Sym_Range Syms = File.getLocalSymbols();
337       for (const Elf_Sym &Sym : Syms) {
338         ErrorOr<StringRef> SymName = Sym.getName(File.getStringTable());
339         if (SymName && !(Config->DiscardLocals && SymName->startswith(".L")))
340           SymTabSec.addSymbol(*SymName, true);
341       }
342     }
343     for (InputSection<ELFT> *C : File.getSections()) {
344       if (!C)
345         continue;
346       const Elf_Shdr *H = C->getSectionHdr();
347       OutputSection<ELFT> *Sec =
348           getSection(C->getSectionName(), H->sh_type, H->sh_flags);
349       Sec->addSection(C);
350       scanRelocs(*C);
351     }
352   }
353 
354   // FIXME: Try to avoid the extra walk over all global symbols.
355   std::vector<DefinedCommon<ELFT> *> CommonSymbols;
356   for (auto &P : Symtab.getSymbols()) {
357     StringRef Name = P.first;
358     SymbolBody *Body = P.second->Body;
359     if (Body->isStrongUndefined())
360       undefError<ELFT>(Symtab, *Body);
361 
362     if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
363       CommonSymbols.push_back(C);
364     if (!includeInSymtab(*Body))
365       continue;
366     SymTabSec.addSymbol(Name);
367 
368     if (needsDynamicSections() && includeInDynamicSymtab(*Body))
369       HashSec.addSymbol(Body);
370   }
371 
372   // Sort the common symbols by alignment as an heuristic to pack them better.
373   std::stable_sort(CommonSymbols.begin(), CommonSymbols.end(), cmpAlign<ELFT>);
374   uintX_t Off = BssSec.getSize();
375   for (DefinedCommon<ELFT> *C : CommonSymbols) {
376     const Elf_Sym &Sym = C->Sym;
377     uintX_t Align = C->MaxAlignment;
378     Off = RoundUpToAlignment(Off, Align);
379     C->OffsetInBSS = Off;
380     Off += Sym.st_size;
381   }
382 
383   BssSec.setSize(Off);
384 
385   OutputSections.push_back(&SymTabSec);
386   OutputSections.push_back(&StrTabSec);
387 
388   if (needsDynamicSections()) {
389     if (needsInterpSection())
390       OutputSections.push_back(&InterpSec);
391     OutputSections.push_back(&DynSymSec);
392     OutputSections.push_back(&HashSec);
393     OutputSections.push_back(&DynamicSec);
394     OutputSections.push_back(&DynStrSec);
395     if (RelaDynSec.hasRelocs())
396       OutputSections.push_back(&RelaDynSec);
397   }
398   if (!GotSec.empty())
399     OutputSections.push_back(&GotSec);
400   if (!PltSec.empty())
401     OutputSections.push_back(&PltSec);
402 
403   std::stable_sort(OutputSections.begin(), OutputSections.end(),
404                    compSec<ELFT::Is64Bits>);
405   for (unsigned I = 0, N = OutputSections.size(); I < N; ++I)
406     OutputSections[I]->setSectionIndex(I + 1);
407 }
408 
409 template <class ELFT>
410 static bool outputSectionHasPHDR(OutputSectionBase<ELFT::Is64Bits> *Sec) {
411   return Sec->getFlags() & SHF_ALLOC;
412 }
413 
414 // Visits all sections to assign incremental, non-overlapping RVAs and
415 // file offsets.
416 template <class ELFT> void Writer<ELFT>::assignAddresses() {
417   assert(!OutputSections.empty() && "No output sections to layout!");
418   uintX_t VA = getVAStart();
419   uintX_t FileOff = 0;
420 
421   FileOff += sizeof(Elf_Ehdr);
422   VA += sizeof(Elf_Ehdr);
423 
424   // Reserve space for PHDRs.
425   ProgramHeaderOff = FileOff;
426   FileOff = RoundUpToAlignment(FileOff, PageSize);
427   VA = RoundUpToAlignment(VA, PageSize);
428 
429   if (needsInterpSection())
430     PHDRs.push_back(&InterpPHDR);
431 
432   ProgramHeader<ELFT::Is64Bits> *LastPHDR = &FileHeaderPHDR;
433   // Create a PHDR for the file header.
434   PHDRs.push_back(&FileHeaderPHDR);
435   FileHeaderPHDR.Header.p_vaddr = getVAStart();
436   FileHeaderPHDR.Header.p_paddr = getVAStart();
437   FileHeaderPHDR.Header.p_align = PageSize;
438 
439   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
440     StrTabSec.add(Sec->getName());
441     Sec->finalize();
442 
443     if (Sec->getSize()) {
444       uintX_t Flags = convertSectionFlagsToPHDRFlags(Sec->getFlags());
445       if (LastPHDR->Header.p_flags != Flags ||
446           !outputSectionHasPHDR<ELFT>(Sec)) {
447         // Flags changed. End current PHDR and potentially create a new one.
448         if (!LastPHDR->Closed) {
449           LastPHDR->Header.p_filesz = FileOff - LastPHDR->Header.p_offset;
450           LastPHDR->Header.p_memsz = VA - LastPHDR->Header.p_vaddr;
451           LastPHDR->Closed = true;
452         }
453 
454         if (outputSectionHasPHDR<ELFT>(Sec)) {
455           LastPHDR = new (PAlloc) ProgramHeader<ELFT::Is64Bits>(PT_LOAD, Flags);
456           PHDRs.push_back(LastPHDR);
457           VA = RoundUpToAlignment(VA, PageSize);
458           FileOff = RoundUpToAlignment(FileOff, PageSize);
459           LastPHDR->Header.p_offset = FileOff;
460           LastPHDR->Header.p_vaddr = VA;
461           LastPHDR->Header.p_paddr = VA;
462         }
463       }
464     }
465 
466     uintX_t Align = Sec->getAlign();
467     uintX_t Size = Sec->getSize();
468     if (Sec->getFlags() & SHF_ALLOC) {
469       VA = RoundUpToAlignment(VA, Align);
470       Sec->setVA(VA);
471       VA += Size;
472     }
473     FileOff = RoundUpToAlignment(FileOff, Align);
474     Sec->setFileOffset(FileOff);
475     if (Sec->getType() != SHT_NOBITS)
476       FileOff += Size;
477   }
478 
479   // Add a PHDR for the dynamic table.
480   if (needsDynamicSections())
481     PHDRs.push_back(&DynamicPHDR);
482 
483   FileOff += OffsetToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4);
484 
485   // Add space for section headers.
486   SectionHeaderOff = FileOff;
487   FileOff += getNumSections() * sizeof(Elf_Shdr);
488   FileSize = FileOff;
489 }
490 
491 template <class ELFT> void Writer<ELFT>::writeHeader() {
492   uint8_t *Buf = Buffer->getBufferStart();
493   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
494   EHdr->e_ident[EI_MAG0] = 0x7F;
495   EHdr->e_ident[EI_MAG1] = 0x45;
496   EHdr->e_ident[EI_MAG2] = 0x4C;
497   EHdr->e_ident[EI_MAG3] = 0x46;
498   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
499   EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little
500                                ? ELFDATA2LSB
501                                : ELFDATA2MSB;
502   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
503   EHdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
504 
505   // FIXME: Generalize the segment construction similar to how we create
506   // output sections.
507   const SymbolTable &Symtab = SymTabSec.getSymTable();
508 
509   EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC;
510   auto &FirstObj = cast<ObjectFile<ELFT>>(*Symtab.getFirstELF());
511   EHdr->e_machine = FirstObj.getEMachine();
512   EHdr->e_version = EV_CURRENT;
513   SymbolBody *Entry = Symtab.getEntrySym();
514   EHdr->e_entry = Entry ? getSymVA(cast<DefinedRegular<ELFT>>(Entry)) : 0;
515   EHdr->e_phoff = ProgramHeaderOff;
516   EHdr->e_shoff = SectionHeaderOff;
517   EHdr->e_ehsize = sizeof(Elf_Ehdr);
518   EHdr->e_phentsize = sizeof(Elf_Phdr);
519   EHdr->e_phnum = PHDRs.size();
520   EHdr->e_shentsize = sizeof(Elf_Shdr);
521   EHdr->e_shnum = getNumSections();
522   EHdr->e_shstrndx = StrTabSec.getSectionIndex();
523 
524   // If nothing was merged into the file header PT_LOAD, set the size correctly.
525   if (FileHeaderPHDR.Header.p_filesz == PageSize)
526     FileHeaderPHDR.Header.p_filesz = FileHeaderPHDR.Header.p_memsz =
527         sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * PHDRs.size();
528 
529   if (needsInterpSection())
530     InterpPHDR.setValuesFromSection(InterpSec);
531   if (needsDynamicSections())
532     DynamicPHDR.setValuesFromSection(DynamicSec);
533 
534   auto PHdrs = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
535   for (ProgramHeader<ELFT::Is64Bits> *PHDR : PHDRs)
536     PHDR->template writeHeaderTo<ELFT::TargetEndianness>(PHdrs++);
537 
538   auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
539   // First entry is null.
540   ++SHdrs;
541   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
542     Sec->setNameOffset(StrTabSec.getFileOff(Sec->getName()));
543     Sec->template writeHeaderTo<ELFT::TargetEndianness>(SHdrs++);
544   }
545 }
546 
547 template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) {
548   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
549       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable);
550   error(BufferOrErr, Twine("failed to open ") + Path);
551   Buffer = std::move(*BufferOrErr);
552 }
553 
554 // Write section contents to a mmap'ed file.
555 template <class ELFT> void Writer<ELFT>::writeSections() {
556   uint8_t *Buf = Buffer->getBufferStart();
557   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections)
558     Sec->writeTo(Buf + Sec->getFileOff());
559 }
560