xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 614c7ef8)
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 "Chunks.h"
12 #include "Config.h"
13 #include "Error.h"
14 #include "Symbols.h"
15 #include "SymbolTable.h"
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/MC/StringTableBuilder.h"
20 #include "llvm/Support/FileOutputBuffer.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace llvm;
24 using namespace llvm::ELF;
25 using namespace llvm::object;
26 
27 using namespace lld;
28 using namespace lld::elf2;
29 
30 static const int PageSize = 4096;
31 
32 // On freebsd x86_64 the first page cannot be mmaped.
33 // On linux that is controled by vm.mmap_min_addr. At least on some x86_64
34 // installs that is 65536, so the first 15 pages cannot be used.
35 // Given that, the smallest value that can be used in here is 0x10000.
36 // If using 2MB pages, the smallest page aligned address that works is
37 // 0x200000, but it looks like every OS uses 4k pages for executables.
38 // FIXME: This is architecture and OS dependent.
39 static const int VAStart = 0x10000;
40 
41 namespace {
42 // OutputSection represents a section in an output file. It's a
43 // container of chunks. OutputSection and Chunk are 1:N relationship.
44 // Chunks cannot belong to more than one OutputSections. The writer
45 // creates multiple OutputSections and assign them unique,
46 // non-overlapping file offsets and VAs.
47 template <bool Is64Bits> class OutputSectionBase {
48 public:
49   typedef
50       typename std::conditional<Is64Bits, Elf64_Dyn, Elf32_Dyn>::type Elf_Dyn;
51   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
52   typedef
53       typename std::conditional<Is64Bits, Elf64_Shdr, Elf32_Shdr>::type HeaderT;
54 
55   OutputSectionBase(StringRef Name, uint32_t sh_type, uintX_t sh_flags)
56       : Name(Name) {
57     memset(&Header, 0, sizeof(HeaderT));
58     Header.sh_type = sh_type;
59     Header.sh_flags = sh_flags;
60   }
61   void setVA(uintX_t VA) { Header.sh_addr = VA; }
62   uintX_t getVA() const { return Header.sh_addr; }
63   void setFileOffset(uintX_t Off) { Header.sh_offset = Off; }
64   template <endianness E>
65   void writeHeaderTo(typename ELFFile<ELFType<E, Is64Bits>>::Elf_Shdr *SHdr);
66   StringRef getName() { return Name; }
67   void setNameOffset(uintX_t Offset) { Header.sh_name = Offset; }
68 
69   unsigned getSectionIndex() const { return SectionIndex; }
70   void setSectionIndex(unsigned I) { SectionIndex = I; }
71 
72   // Returns the size of the section in the output file.
73   uintX_t getSize() { return Header.sh_size; }
74   void setSize(uintX_t Val) { Header.sh_size = Val; }
75   uintX_t getFlags() { return Header.sh_flags; }
76   uintX_t getFileOff() { return Header.sh_offset; }
77   uintX_t getAlign() {
78     // The ELF spec states that a value of 0 means the section has no alignment
79     // constraits.
80     return std::max<uintX_t>(Header.sh_addralign, 1);
81   }
82   uint32_t getType() { return Header.sh_type; }
83 
84   static unsigned getAddrSize() { return Is64Bits ? 8 : 4; }
85 
86   virtual void finalize() {}
87   virtual void writeTo(uint8_t *Buf) = 0;
88 
89 protected:
90   StringRef Name;
91   HeaderT Header;
92   unsigned SectionIndex;
93   ~OutputSectionBase() = default;
94 };
95 template <class ELFT> class SymbolTableSection;
96 
97 template <class ELFT> struct DynamicReloc {
98   typedef typename ELFFile<ELFT>::Elf_Rel Elf_Rel;
99   const InputSection<ELFT> &C;
100   const Elf_Rel &RI;
101 };
102 
103 static bool relocNeedsPLT(uint32_t Type) {
104   switch (Type) {
105   default:
106     return false;
107   case R_X86_64_PLT32:
108     return true;
109   }
110 }
111 
112 static bool relocNeedsGOT(uint32_t Type) {
113   if (relocNeedsPLT(Type))
114     return true;
115   switch (Type) {
116   default:
117     return false;
118   case R_X86_64_GOTPCREL:
119     return true;
120   }
121 }
122 
123 template <class ELFT>
124 class GotSection final : public OutputSectionBase<ELFT::Is64Bits> {
125   typedef OutputSectionBase<ELFT::Is64Bits> Base;
126   typedef typename Base::uintX_t uintX_t;
127 
128 public:
129   GotSection()
130       : OutputSectionBase<ELFT::Is64Bits>(".got", SHT_PROGBITS,
131                                           SHF_ALLOC | SHF_WRITE) {
132     this->Header.sh_addralign = this->getAddrSize();
133   }
134   void finalize() override {
135     this->Header.sh_size = Entries.size() * this->getAddrSize();
136   }
137   void writeTo(uint8_t *Buf) override {}
138   void addEntry(SymbolBody *Sym) {
139     Sym->setGotIndex(Entries.size());
140     Entries.push_back(Sym);
141   }
142   bool empty() const { return Entries.empty(); }
143   uintX_t getEntryAddr(const SymbolBody &B) const {
144     return this->getVA() + B.getGotIndex() * this->getAddrSize();
145   }
146 
147 private:
148   std::vector<const SymbolBody *> Entries;
149 };
150 
151 template <class ELFT>
152 class PltSection final : public OutputSectionBase<ELFT::Is64Bits> {
153   typedef OutputSectionBase<ELFT::Is64Bits> Base;
154   typedef typename Base::uintX_t uintX_t;
155 
156 public:
157   PltSection(const GotSection<ELFT> &GotSec)
158       : OutputSectionBase<ELFT::Is64Bits>(".plt", SHT_PROGBITS,
159                                           SHF_ALLOC | SHF_EXECINSTR),
160         GotSec(GotSec) {
161     this->Header.sh_addralign = 16;
162   }
163   void finalize() override {
164     this->Header.sh_size = Entries.size() * EntrySize;
165   }
166   void writeTo(uint8_t *Buf) override {
167     uintptr_t Start = reinterpret_cast<uintptr_t>(Buf);
168     ArrayRef<uint8_t> Jmp = {0xff, 0x25}; // jmpq *val(%rip)
169     for (const SymbolBody *E : Entries) {
170       uintptr_t InstPos = reinterpret_cast<uintptr_t>(Buf);
171 
172       memcpy(Buf, Jmp.data(), Jmp.size());
173       Buf += Jmp.size();
174 
175       uintptr_t OffsetInPLT = (InstPos + 6) - Start;
176       uintptr_t Delta = GotSec.getEntryAddr(*E) - (this->getVA() + OffsetInPLT);
177       assert(isInt<32>(Delta));
178       support::endian::write32le(Buf, Delta);
179       Buf += 4;
180 
181       *Buf = 0x90; // nop
182       ++Buf;
183       *Buf = 0x90; // nop
184       ++Buf;
185     }
186   }
187   void addEntry(SymbolBody *Sym) {
188     Sym->setPltIndex(Entries.size());
189     Entries.push_back(Sym);
190   }
191   bool empty() const { return Entries.empty(); }
192   uintX_t getEntryAddr(const SymbolBody &B) const {
193     return this->getVA() + B.getPltIndex() * EntrySize;
194   }
195 
196   static const unsigned EntrySize = 8;
197 
198 private:
199   std::vector<const SymbolBody *> Entries;
200   const GotSection<ELFT> &GotSec;
201 };
202 
203 template <class ELFT>
204 class RelocationSection final : public OutputSectionBase<ELFT::Is64Bits> {
205   typedef typename ELFFile<ELFT>::Elf_Rel Elf_Rel;
206   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
207 
208 public:
209   RelocationSection(SymbolTableSection<ELFT> &DynSymSec,
210                     const GotSection<ELFT> &GotSec, bool IsRela)
211       : OutputSectionBase<ELFT::Is64Bits>(IsRela ? ".rela.dyn" : ".rel.dyn",
212                                           IsRela ? SHT_RELA : SHT_REL,
213                                           SHF_ALLOC),
214         DynSymSec(DynSymSec), GotSec(GotSec), IsRela(IsRela) {
215     this->Header.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
216     this->Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
217   }
218 
219   void addReloc(const DynamicReloc<ELFT> &Reloc) { Relocs.push_back(Reloc); }
220   void finalize() override {
221     this->Header.sh_link = DynSymSec.getSectionIndex();
222     this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
223   }
224   void writeTo(uint8_t *Buf) override {
225     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
226     bool IsMips64EL = Relocs[0].C.getFile()->getObj()->isMips64EL();
227     for (const DynamicReloc<ELFT> &Rel : Relocs) {
228       const InputSection<ELFT> &C = Rel.C;
229       const Elf_Rel &RI = Rel.RI;
230       OutputSection<ELFT> *Out = C.getOutputSection();
231       uint32_t SymIndex = RI.getSymbol(IsMips64EL);
232       const SymbolBody *Body = C.getFile()->getSymbolBody(SymIndex);
233       uint32_t Type = RI.getType(IsMips64EL);
234       if (relocNeedsGOT(Type)) {
235         P->r_offset = GotSec.getEntryAddr(*Body);
236         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
237                             R_X86_64_GLOB_DAT, IsMips64EL);
238       } else {
239         P->r_offset = RI.r_offset + C.getOutputSectionOff() + Out->getVA();
240         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(), Type,
241                             IsMips64EL);
242         if (IsRela)
243           P->r_addend = static_cast<const Elf_Rela &>(RI).r_addend;
244       }
245 
246       ++P;
247     }
248   }
249   bool hasRelocs() const { return !Relocs.empty(); }
250   bool isRela() const { return IsRela; }
251 
252 private:
253   std::vector<DynamicReloc<ELFT>> Relocs;
254   SymbolTableSection<ELFT> &DynSymSec;
255   const GotSection<ELFT> &GotSec;
256   const bool IsRela;
257 };
258 }
259 
260 template <class ELFT>
261 class lld::elf2::OutputSection final
262     : public OutputSectionBase<ELFT::Is64Bits> {
263 public:
264   typedef typename OutputSectionBase<ELFT::Is64Bits>::uintX_t uintX_t;
265   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
266   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
267   typedef typename ELFFile<ELFT>::Elf_Rel Elf_Rel;
268   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
269   OutputSection(const PltSection<ELFT> &PltSec, const GotSection<ELFT> &GotSec,
270                 StringRef Name, uint32_t sh_type, uintX_t sh_flags)
271       : OutputSectionBase<ELFT::Is64Bits>(Name, sh_type, sh_flags),
272         PltSec(PltSec), GotSec(GotSec) {}
273 
274   void addChunk(InputSection<ELFT> *C);
275   void writeTo(uint8_t *Buf) override;
276 
277   template <bool isRela>
278   void relocate(uint8_t *Buf,
279                 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels,
280                 const ObjectFile<ELFT> &File, uintX_t BaseAddr);
281 
282   void relocateOne(uint8_t *Buf, const Elf_Rela &Rel, uint32_t Type,
283                    uintX_t BaseAddr, uintX_t SymVA);
284   void relocateOne(uint8_t *Buf, const Elf_Rel &Rel, uint32_t Type,
285                    uintX_t BaseAddr, uintX_t SymVA);
286 
287 private:
288   std::vector<InputSection<ELFT> *> Chunks;
289   const PltSection<ELFT> &PltSec;
290   const GotSection<ELFT> &GotSec;
291 };
292 
293 namespace {
294 template <bool Is64Bits>
295 class InterpSection final : public OutputSectionBase<Is64Bits> {
296 public:
297   InterpSection()
298       : OutputSectionBase<Is64Bits>(".interp", SHT_PROGBITS, SHF_ALLOC) {
299     this->Header.sh_size = Config->DynamicLinker.size() + 1;
300     this->Header.sh_addralign = 1;
301   }
302 
303   void writeTo(uint8_t *Buf) override {
304     memcpy(Buf, Config->DynamicLinker.data(), Config->DynamicLinker.size());
305   }
306 };
307 
308 template <bool Is64Bits>
309 class StringTableSection final : public OutputSectionBase<Is64Bits> {
310 public:
311   typedef typename OutputSectionBase<Is64Bits>::uintX_t uintX_t;
312   StringTableSection(bool Dynamic)
313       : OutputSectionBase<Is64Bits>(Dynamic ? ".dynstr" : ".strtab", SHT_STRTAB,
314                                     Dynamic ? (uintX_t)SHF_ALLOC : 0),
315         Dynamic(Dynamic) {
316     this->Header.sh_addralign = 1;
317   }
318 
319   void add(StringRef S) { StrTabBuilder.add(S); }
320   size_t getFileOff(StringRef S) const { return StrTabBuilder.getOffset(S); }
321   StringRef data() const { return StrTabBuilder.data(); }
322   void writeTo(uint8_t *Buf) override;
323 
324   void finalize() override {
325     StrTabBuilder.finalize(StringTableBuilder::ELF);
326     this->Header.sh_size = StrTabBuilder.data().size();
327   }
328 
329   bool isDynamic() const { return Dynamic; }
330 
331 private:
332   const bool Dynamic;
333   llvm::StringTableBuilder StrTabBuilder;
334 };
335 
336 template <class ELFT> class Writer;
337 
338 template <class ELFT>
339 class SymbolTableSection final : public OutputSectionBase<ELFT::Is64Bits> {
340 public:
341   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
342   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
343   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
344   typedef typename OutputSectionBase<ELFT::Is64Bits>::uintX_t uintX_t;
345   SymbolTableSection(Writer<ELFT> &W, SymbolTable &Table,
346                      StringTableSection<ELFT::Is64Bits> &StrTabSec)
347       : OutputSectionBase<ELFT::Is64Bits>(
348             StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
349             StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
350             StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
351         Table(Table), StrTabSec(StrTabSec), W(W) {
352     typedef OutputSectionBase<ELFT::Is64Bits> Base;
353     typename Base::HeaderT &Header = this->Header;
354 
355     Header.sh_entsize = sizeof(Elf_Sym);
356     Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
357   }
358 
359   void finalize() override {
360     this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
361     this->Header.sh_link = StrTabSec.getSectionIndex();
362     this->Header.sh_info = NumLocals + 1;
363   }
364 
365   void writeTo(uint8_t *Buf) override;
366 
367   const SymbolTable &getSymTable() const { return Table; }
368 
369   void addSymbol(StringRef Name, bool isLocal = false) {
370     StrTabSec.add(Name);
371     ++NumVisible;
372     if (isLocal)
373       ++NumLocals;
374   }
375 
376   StringTableSection<ELFT::Is64Bits> &getStrTabSec() { return StrTabSec; }
377   unsigned getNumSymbols() const { return NumVisible + 1; }
378 
379 private:
380   SymbolTable &Table;
381   StringTableSection<ELFT::Is64Bits> &StrTabSec;
382   unsigned NumVisible = 0;
383   unsigned NumLocals = 0;
384   const Writer<ELFT> &W;
385 };
386 
387 template <class ELFT>
388 class HashTableSection final : public OutputSectionBase<ELFT::Is64Bits> {
389   typedef typename ELFFile<ELFT>::Elf_Word Elf_Word;
390 
391 public:
392   HashTableSection(SymbolTableSection<ELFT> &DynSymSec)
393       : OutputSectionBase<ELFT::Is64Bits>(".hash", SHT_HASH, SHF_ALLOC),
394         DynSymSec(DynSymSec) {
395     this->Header.sh_entsize = sizeof(Elf_Word);
396     this->Header.sh_addralign = sizeof(Elf_Word);
397   }
398 
399   void addSymbol(SymbolBody *S) {
400     StringRef Name = S->getName();
401     DynSymSec.addSymbol(Name);
402     Hashes.push_back(hash(Name));
403     S->setDynamicSymbolTableIndex(Hashes.size());
404   }
405 
406   void finalize() override {
407     this->Header.sh_link = DynSymSec.getSectionIndex();
408 
409     assert(DynSymSec.getNumSymbols() == Hashes.size() + 1);
410     unsigned NumEntries = 2;                 // nbucket and nchain.
411     NumEntries += DynSymSec.getNumSymbols(); // The chain entries.
412 
413     // Create as many buckets as there are symbols.
414     // FIXME: This is simplistic. We can try to optimize it, but implementing
415     // support for SHT_GNU_HASH is probably even more profitable.
416     NumEntries += DynSymSec.getNumSymbols();
417     this->Header.sh_size = NumEntries * sizeof(Elf_Word);
418   }
419 
420   void writeTo(uint8_t *Buf) override {
421     unsigned NumSymbols = DynSymSec.getNumSymbols();
422     auto *P = reinterpret_cast<Elf_Word *>(Buf);
423     *P++ = NumSymbols; // nbucket
424     *P++ = NumSymbols; // nchain
425 
426     Elf_Word *Buckets = P;
427     Elf_Word *Chains = P + NumSymbols;
428 
429     for (unsigned I = 1; I < NumSymbols; ++I) {
430       uint32_t Hash = Hashes[I - 1] % NumSymbols;
431       Chains[I] = Buckets[Hash];
432       Buckets[Hash] = I;
433     }
434   }
435 
436   SymbolTableSection<ELFT> &getDynSymSec() { return DynSymSec; }
437 
438 private:
439   uint32_t hash(StringRef Name) {
440     uint32_t H = 0;
441     for (char C : Name) {
442       H = (H << 4) + C;
443       uint32_t G = H & 0xf0000000;
444       if (G)
445         H ^= G >> 24;
446       H &= ~G;
447     }
448     return H;
449   }
450   SymbolTableSection<ELFT> &DynSymSec;
451   std::vector<uint32_t> Hashes;
452 };
453 
454 template <class ELFT>
455 class DynamicSection final : public OutputSectionBase<ELFT::Is64Bits> {
456   typedef OutputSectionBase<ELFT::Is64Bits> Base;
457   typedef typename Base::HeaderT HeaderT;
458   typedef typename Base::Elf_Dyn Elf_Dyn;
459 
460 public:
461   DynamicSection(SymbolTable &SymTab, HashTableSection<ELFT> &HashSec,
462                  RelocationSection<ELFT> &RelaDynSec)
463       : OutputSectionBase<ELFT::Is64Bits>(".dynamic", SHT_DYNAMIC,
464                                           SHF_ALLOC | SHF_WRITE),
465         HashSec(HashSec), DynSymSec(HashSec.getDynSymSec()),
466         DynStrSec(DynSymSec.getStrTabSec()), RelaDynSec(RelaDynSec),
467         SymTab(SymTab) {
468     typename Base::HeaderT &Header = this->Header;
469     Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
470     Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
471   }
472 
473   void finalize() override {
474     typename Base::HeaderT &Header = this->Header;
475     Header.sh_link = DynStrSec.getSectionIndex();
476 
477     unsigned NumEntries = 0;
478     if (RelaDynSec.hasRelocs()) {
479       ++NumEntries; // DT_RELA / DT_REL
480       ++NumEntries; // DT_RELASZ / DTRELSZ
481     }
482     ++NumEntries; // DT_SYMTAB
483     ++NumEntries; // DT_STRTAB
484     ++NumEntries; // DT_STRSZ
485     ++NumEntries; // DT_HASH
486 
487     StringRef RPath = Config->RPath;
488     if (!RPath.empty()) {
489       ++NumEntries; // DT_RUNPATH
490       DynStrSec.add(RPath);
491     }
492 
493     const std::vector<std::unique_ptr<SharedFileBase>> &SharedFiles =
494         SymTab.getSharedFiles();
495     for (const std::unique_ptr<SharedFileBase> &File : SharedFiles)
496       DynStrSec.add(File->getName());
497     NumEntries += SharedFiles.size();
498 
499     ++NumEntries; // DT_NULL
500 
501     Header.sh_size = NumEntries * Header.sh_entsize;
502   }
503 
504   void writeTo(uint8_t *Buf) override {
505     auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
506 
507     if (RelaDynSec.hasRelocs()) {
508       bool IsRela = RelaDynSec.isRela();
509       P->d_tag = IsRela ? DT_RELA : DT_REL;
510       P->d_un.d_ptr = RelaDynSec.getVA();
511       ++P;
512 
513       P->d_tag = IsRela ? DT_RELASZ : DT_RELSZ;
514       P->d_un.d_val = RelaDynSec.getSize();
515       ++P;
516     }
517 
518     P->d_tag = DT_SYMTAB;
519     P->d_un.d_ptr = DynSymSec.getVA();
520     ++P;
521 
522     P->d_tag = DT_STRTAB;
523     P->d_un.d_ptr = DynStrSec.getVA();
524     ++P;
525 
526     P->d_tag = DT_STRSZ;
527     P->d_un.d_val = DynStrSec.data().size();
528     ++P;
529 
530     P->d_tag = DT_HASH;
531     P->d_un.d_ptr = HashSec.getVA();
532     ++P;
533 
534     StringRef RPath = Config->RPath;
535     if (!RPath.empty()) {
536       P->d_tag = DT_RUNPATH;
537       P->d_un.d_val = DynStrSec.getFileOff(RPath);
538       ++P;
539     }
540 
541     const std::vector<std::unique_ptr<SharedFileBase>> &SharedFiles =
542         SymTab.getSharedFiles();
543     for (const std::unique_ptr<SharedFileBase> &File : SharedFiles) {
544       P->d_tag = DT_NEEDED;
545       P->d_un.d_val = DynStrSec.getFileOff(File->getName());
546       ++P;
547     }
548 
549     P->d_tag = DT_NULL;
550     P->d_un.d_val = 0;
551     ++P;
552   }
553 
554 private:
555   HashTableSection<ELFT> &HashSec;
556   SymbolTableSection<ELFT> &DynSymSec;
557   StringTableSection<ELFT::Is64Bits> &DynStrSec;
558   RelocationSection<ELFT> &RelaDynSec;
559   SymbolTable &SymTab;
560 };
561 
562 static uint32_t convertSectionFlagsToPHDRFlags(uint64_t Flags) {
563   uint32_t Ret = PF_R;
564   if (Flags & SHF_WRITE)
565     Ret |= PF_W;
566 
567   if (Flags & SHF_EXECINSTR)
568     Ret |= PF_X;
569 
570   return Ret;
571 }
572 
573 template <bool Is64Bits>
574 class ProgramHeader {
575 public:
576   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
577   typedef
578     typename std::conditional<Is64Bits, Elf64_Phdr, Elf32_Phdr>::type HeaderT;
579 
580   ProgramHeader(uintX_t p_type, uintX_t p_flags) {
581     std::memset(&Header, 0, sizeof(HeaderT));
582     Header.p_type = p_type;
583     Header.p_flags = p_flags;
584     Header.p_align = PageSize;
585   }
586 
587   void setValuesFromSection(OutputSectionBase<Is64Bits> &Sec) {
588     Header.p_flags = convertSectionFlagsToPHDRFlags(Sec.getFlags());
589     Header.p_offset = Sec.getFileOff();
590     Header.p_vaddr = Sec.getVA();
591     Header.p_paddr = Header.p_vaddr;
592     Header.p_filesz = Sec.getSize();
593     Header.p_memsz = Header.p_filesz;
594     Header.p_align = Sec.getAlign();
595   }
596 
597   template <endianness E>
598   void writeHeaderTo(typename ELFFile<ELFType<E, Is64Bits>>::Elf_Phdr *PHDR) {
599     PHDR->p_type = Header.p_type;
600     PHDR->p_flags = Header.p_flags;
601     PHDR->p_offset = Header.p_offset;
602     PHDR->p_vaddr = Header.p_vaddr;
603     PHDR->p_paddr = Header.p_paddr;
604     PHDR->p_filesz = Header.p_filesz;
605     PHDR->p_memsz = Header.p_memsz;
606     PHDR->p_align = Header.p_align;
607   }
608 
609   HeaderT Header;
610   bool Closed = false;
611 };
612 
613 // The writer writes a SymbolTable result to a file.
614 template <class ELFT> class Writer {
615 public:
616   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
617   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
618   typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
619   typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
620   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
621   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
622   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
623   Writer(SymbolTable *T)
624       : SymTabSec(*this, *T, StrTabSec), DynSymSec(*this, *T, DynStrSec),
625         RelaDynSec(DynSymSec, GotSec, T->shouldUseRela()), PltSec(GotSec),
626         HashSec(DynSymSec), DynamicSec(*T, HashSec, RelaDynSec) {}
627   void run();
628 
629   const OutputSection<ELFT> &getBSS() const {
630     assert(BSSSec);
631     return *BSSSec;
632   }
633 
634 private:
635   void createSections();
636   template <bool isRela>
637   void scanRelocs(const InputSection<ELFT> &C,
638                   iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
639   void scanRelocs(const InputSection<ELFT> &C);
640   void assignAddresses();
641   void openFile(StringRef OutputPath);
642   void writeHeader();
643   void writeSections();
644   bool needsInterpSection() const {
645     return !SymTabSec.getSymTable().getSharedFiles().empty() &&
646            !Config->DynamicLinker.empty();
647   }
648   bool needsDynamicSections() const {
649     return !SymTabSec.getSymTable().getSharedFiles().empty() || Config->Shared;
650   }
651   unsigned getVAStart() const { return Config->Shared ? 0 : VAStart; }
652 
653   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
654 
655   llvm::SpecificBumpPtrAllocator<OutputSection<ELFT>> CAlloc;
656   std::vector<OutputSectionBase<ELFT::Is64Bits> *> OutputSections;
657   unsigned getNumSections() const { return OutputSections.size() + 1; }
658 
659   llvm::BumpPtrAllocator PAlloc;
660   std::vector<ProgramHeader<ELFT::Is64Bits> *> PHDRs;
661   ProgramHeader<ELFT::Is64Bits> FileHeaderPHDR{PT_LOAD, PF_R};
662   ProgramHeader<ELFT::Is64Bits> InterpPHDR{PT_INTERP, 0};
663   ProgramHeader<ELFT::Is64Bits> DynamicPHDR{PT_DYNAMIC, 0};
664 
665   uintX_t FileSize;
666   uintX_t ProgramHeaderOff;
667   uintX_t SectionHeaderOff;
668 
669   StringTableSection<ELFT::Is64Bits> StrTabSec = { /*dynamic=*/false };
670   StringTableSection<ELFT::Is64Bits> DynStrSec = { /*dynamic=*/true };
671 
672   SymbolTableSection<ELFT> SymTabSec;
673   SymbolTableSection<ELFT> DynSymSec;
674 
675   RelocationSection<ELFT> RelaDynSec;
676 
677   GotSection<ELFT> GotSec;
678   PltSection<ELFT> PltSec;
679 
680   HashTableSection<ELFT> HashSec;
681 
682   DynamicSection<ELFT> DynamicSec;
683 
684   InterpSection<ELFT::Is64Bits> InterpSec;
685 
686   OutputSection<ELFT> *BSSSec = nullptr;
687 };
688 } // anonymous namespace
689 
690 namespace lld {
691 namespace elf2 {
692 
693 template <class ELFT>
694 void writeResult(SymbolTable *Symtab) { Writer<ELFT>(Symtab).run(); }
695 
696 template void writeResult<ELF32LE>(SymbolTable *);
697 template void writeResult<ELF32BE>(SymbolTable *);
698 template void writeResult<ELF64LE>(SymbolTable *);
699 template void writeResult<ELF64BE>(SymbolTable *);
700 
701 } // namespace elf2
702 } // namespace lld
703 
704 // The main function of the writer.
705 template <class ELFT> void Writer<ELFT>::run() {
706   createSections();
707   assignAddresses();
708   openFile(Config->OutputFile);
709   writeHeader();
710   writeSections();
711   error(Buffer->commit());
712 }
713 
714 template <class ELFT>
715 void OutputSection<ELFT>::addChunk(InputSection<ELFT> *C) {
716   Chunks.push_back(C);
717   C->setOutputSection(this);
718   uint32_t Align = C->getAlign();
719   if (Align > this->Header.sh_addralign)
720     this->Header.sh_addralign = Align;
721 
722   uintX_t Off = this->Header.sh_size;
723   Off = RoundUpToAlignment(Off, Align);
724   C->setOutputSectionOff(Off);
725   Off += C->getSize();
726   this->Header.sh_size = Off;
727 }
728 
729 template <class ELFT>
730 static typename ELFFile<ELFT>::uintX_t
731 getSymVA(const DefinedRegular<ELFT> *DR) {
732   const InputSection<ELFT> *SC = &DR->Section;
733   OutputSection<ELFT> *OS = SC->getOutputSection();
734   return OS->getVA() + SC->getOutputSectionOff() + DR->Sym.st_value;
735 }
736 
737 template <class ELFT>
738 static typename ELFFile<ELFT>::uintX_t
739 getLocalSymVA(const typename ELFFile<ELFT>::Elf_Sym *Sym,
740               const ObjectFile<ELFT> &File) {
741   uint32_t SecIndex = Sym->st_shndx;
742 
743   if (SecIndex == SHN_XINDEX)
744     SecIndex = File.getObj()->getExtendedSymbolTableIndex(
745         Sym, File.getSymbolTable(), File.getSymbolTableShndx());
746   ArrayRef<InputSection<ELFT> *> Chunks = File.getChunks();
747   InputSection<ELFT> *Section = Chunks[SecIndex];
748   OutputSection<ELFT> *Out = Section->getOutputSection();
749   return Out->getVA() + Section->getOutputSectionOff() + Sym->st_value;
750 }
751 
752 template <class ELFT>
753 void OutputSection<ELFT>::relocateOne(uint8_t *Buf, const Elf_Rel &Rel,
754                                       uint32_t Type, uintX_t BaseAddr,
755                                       uintX_t SymVA) {
756   uintX_t Offset = Rel.r_offset;
757   uint8_t *Location = Buf + Offset;
758   switch (Type) {
759   case R_386_32:
760     support::endian::write32le(Location, SymVA);
761     break;
762   default:
763     llvm::errs() << Twine("unrecognized reloc ") + Twine(Type) << '\n';
764     break;
765   }
766 }
767 
768 template <class ELFT>
769 void OutputSection<ELFT>::relocateOne(uint8_t *Buf, const Elf_Rela &Rel,
770                                       uint32_t Type, uintX_t BaseAddr,
771                                       uintX_t SymVA) {
772   uintX_t Offset = Rel.r_offset;
773   uint8_t *Location = Buf + Offset;
774   switch (Type) {
775   case R_X86_64_PC32:
776     support::endian::write32le(Location,
777                                SymVA + (Rel.r_addend - (BaseAddr + Offset)));
778     break;
779   case R_X86_64_64:
780     support::endian::write64le(Location, SymVA + Rel.r_addend);
781     break;
782   case R_X86_64_32: {
783   case R_X86_64_32S:
784     uint64_t VA = SymVA + Rel.r_addend;
785     if (Type == R_X86_64_32 && !isUInt<32>(VA))
786       error("R_X86_64_32 out of range");
787     else if (!isInt<32>(VA))
788       error("R_X86_64_32S out of range");
789 
790     support::endian::write32le(Location, VA);
791     break;
792   }
793   default:
794     llvm::errs() << Twine("unrecognized reloc ") + Twine(Type) << '\n';
795     break;
796   }
797 }
798 
799 template <class ELFT>
800 template <bool isRela>
801 void OutputSection<ELFT>::relocate(
802     uint8_t *Buf, iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels,
803     const ObjectFile<ELFT> &File, uintX_t BaseAddr) {
804   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
805   bool IsMips64EL = File.getObj()->isMips64EL();
806   for (const RelType &RI : Rels) {
807     uint32_t SymIndex = RI.getSymbol(IsMips64EL);
808     uint32_t Type = RI.getType(IsMips64EL);
809     uintX_t SymVA;
810 
811     // Handle relocations for local symbols -- they never get
812     // resolved so we don't allocate a SymbolBody.
813     const Elf_Shdr *SymTab = File.getSymbolTable();
814     if (SymIndex < SymTab->sh_info) {
815       const Elf_Sym *Sym = File.getObj()->getRelocationSymbol(&RI, SymTab);
816       if (!Sym)
817         continue;
818       SymVA = getLocalSymVA(Sym, File);
819     } else {
820       const SymbolBody *Body = File.getSymbolBody(SymIndex);
821       if (!Body)
822         continue;
823       switch (Body->kind()) {
824       case SymbolBody::DefinedRegularKind:
825         SymVA = getSymVA<ELFT>(cast<DefinedRegular<ELFT>>(Body));
826         break;
827       case SymbolBody::DefinedAbsoluteKind:
828         SymVA = cast<DefinedAbsolute<ELFT>>(Body)->Sym.st_value;
829         break;
830       case SymbolBody::DefinedCommonKind: {
831         auto *DC = cast<DefinedCommon<ELFT>>(Body);
832         SymVA = DC->OutputSec->getVA() + DC->OffsetInBSS;
833         break;
834       }
835       case SymbolBody::SharedKind:
836         if (relocNeedsPLT(Type)) {
837           SymVA = PltSec.getEntryAddr(*Body);
838           Type = R_X86_64_PC32;
839         } else if (relocNeedsGOT(Type)) {
840           SymVA = GotSec.getEntryAddr(*Body);
841           Type = R_X86_64_PC32;
842         } else {
843           continue;
844         }
845         break;
846       case SymbolBody::UndefinedKind:
847         assert(Body->isWeak() && "Undefined symbol reached writer");
848         SymVA = 0;
849         break;
850       case SymbolBody::LazyKind:
851         llvm_unreachable("Lazy symbol reached writer");
852       }
853     }
854 
855     relocateOne(Buf, RI, Type, BaseAddr, SymVA);
856   }
857 }
858 
859 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
860   for (InputSection<ELFT> *C : Chunks) {
861     C->writeTo(Buf);
862     const ObjectFile<ELFT> *File = C->getFile();
863     ELFFile<ELFT> *EObj = File->getObj();
864     uint8_t *Base = Buf + C->getOutputSectionOff();
865     uintX_t BaseAddr = this->getVA() + C->getOutputSectionOff();
866     // Iterate over all relocation sections that apply to this section.
867     for (const Elf_Shdr *RelSec : C->RelocSections) {
868       if (RelSec->sh_type == SHT_RELA)
869         relocate(Base, EObj->relas(RelSec), *File, BaseAddr);
870       else
871         relocate(Base, EObj->rels(RelSec), *File, BaseAddr);
872     }
873   }
874 }
875 
876 template <bool Is64Bits>
877 void StringTableSection<Is64Bits>::writeTo(uint8_t *Buf) {
878   StringRef Data = StrTabBuilder.data();
879   memcpy(Buf, Data.data(), Data.size());
880 }
881 
882 template <class ELFT>
883 static int compareSym(const typename ELFFile<ELFT>::Elf_Sym *A,
884                       const typename ELFFile<ELFT>::Elf_Sym *B) {
885   uint32_t AN = A->st_name;
886   uint32_t BN = B->st_name;
887   assert(AN != BN);
888   return AN - BN;
889 }
890 
891 static bool includeInSymtab(const SymbolBody &B) {
892   if (B.isLazy())
893     return false;
894   if (!B.isUsedInRegularObj())
895     return false;
896   uint8_t V = B.getMostConstrainingVisibility();
897   if (V != STV_DEFAULT && V != STV_PROTECTED)
898     return false;
899   return true;
900 }
901 
902 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
903   const OutputSection<ELFT> *Out = nullptr;
904   const InputSection<ELFT> *Section = nullptr;
905   Buf += sizeof(Elf_Sym);
906 
907   // All symbols with STB_LOCAL binding precede the weak and global symbols.
908   // .dynsym only contains global symbols.
909   if (!Config->DiscardAll && !StrTabSec.isDynamic()) {
910     for (const std::unique_ptr<ObjectFileBase> &FileB :
911          Table.getObjectFiles()) {
912       auto &File = cast<ObjectFile<ELFT>>(*FileB);
913       Elf_Sym_Range Syms = File.getLocalSymbols();
914       for (const Elf_Sym &Sym : Syms) {
915         auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
916         uint32_t SecIndex = Sym.st_shndx;
917         ErrorOr<StringRef> SymName = Sym.getName(File.getStringTable());
918         if (Config->DiscardLocals && SymName->startswith(".L"))
919           continue;
920         ESym->st_name = (SymName) ? StrTabSec.getFileOff(*SymName) : 0;
921         ESym->st_size = Sym.st_size;
922         ESym->setBindingAndType(Sym.getBinding(), Sym.getType());
923         if (SecIndex == SHN_XINDEX)
924           SecIndex = File.getObj()->getExtendedSymbolTableIndex(
925               &Sym, File.getSymbolTable(), File.getSymbolTableShndx());
926         ArrayRef<InputSection<ELFT> *> Chunks = File.getChunks();
927         Section = Chunks[SecIndex];
928         assert(Section != nullptr);
929         Out = Section->getOutputSection();
930         assert(Out != nullptr);
931         ESym->st_shndx = Out->getSectionIndex();
932         ESym->st_value =
933             Out->getVA() + Section->getOutputSectionOff() + Sym.st_value;
934         Buf += sizeof(Elf_Sym);
935       }
936     }
937   }
938 
939   for (auto &P : Table.getSymbols()) {
940     StringRef Name = P.first;
941     Symbol *Sym = P.second;
942     SymbolBody *Body = Sym->Body;
943     if (!includeInSymtab(*Body))
944       continue;
945     const Elf_Sym &InputSym = cast<ELFSymbolBody<ELFT>>(Body)->Sym;
946 
947     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
948     ESym->st_name = StrTabSec.getFileOff(Name);
949 
950     Out = nullptr;
951     Section = nullptr;
952 
953     switch (Body->kind()) {
954     case SymbolBody::DefinedRegularKind:
955       Section = &cast<DefinedRegular<ELFT>>(Body)->Section;
956       break;
957     case SymbolBody::DefinedCommonKind:
958       Out = &W.getBSS();
959       break;
960     case SymbolBody::UndefinedKind:
961     case SymbolBody::DefinedAbsoluteKind:
962     case SymbolBody::SharedKind:
963       break;
964     case SymbolBody::LazyKind:
965       llvm_unreachable("Lazy symbol got to output symbol table!");
966     }
967 
968     ESym->setBindingAndType(InputSym.getBinding(), InputSym.getType());
969     ESym->st_size = InputSym.st_size;
970     ESym->setVisibility(Body->getMostConstrainingVisibility());
971     if (InputSym.isAbsolute()) {
972       ESym->st_shndx = SHN_ABS;
973       ESym->st_value = InputSym.st_value;
974     }
975 
976     if (Section)
977       Out = Section->getOutputSection();
978 
979     if (Out) {
980       ESym->st_shndx = Out->getSectionIndex();
981       uintX_t VA = Out->getVA();
982       if (Section)
983         VA += Section->getOutputSectionOff();
984       if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
985         VA += C->OffsetInBSS;
986       else
987         VA += InputSym.st_value;
988       ESym->st_value = VA;
989     }
990 
991     Buf += sizeof(Elf_Sym);
992   }
993 }
994 
995 template <bool Is64Bits>
996 template <endianness E>
997 void OutputSectionBase<Is64Bits>::writeHeaderTo(
998     typename ELFFile<ELFType<E, Is64Bits>>::Elf_Shdr *SHdr) {
999   SHdr->sh_name = Header.sh_name;
1000   SHdr->sh_type = Header.sh_type;
1001   SHdr->sh_flags = Header.sh_flags;
1002   SHdr->sh_addr = Header.sh_addr;
1003   SHdr->sh_offset = Header.sh_offset;
1004   SHdr->sh_size = Header.sh_size;
1005   SHdr->sh_link = Header.sh_link;
1006   SHdr->sh_info = Header.sh_info;
1007   SHdr->sh_addralign = Header.sh_addralign;
1008   SHdr->sh_entsize = Header.sh_entsize;
1009 }
1010 
1011 namespace {
1012 template <bool Is64Bits> struct SectionKey {
1013   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
1014   StringRef Name;
1015   uint32_t sh_type;
1016   uintX_t sh_flags;
1017 };
1018 }
1019 namespace llvm {
1020 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
1021   static SectionKey<Is64Bits> getEmptyKey() {
1022     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
1023   }
1024   static SectionKey<Is64Bits> getTombstoneKey() {
1025     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
1026                                 0};
1027   }
1028   static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
1029     return hash_combine(Val.Name, Val.sh_type, Val.sh_flags);
1030   }
1031   static bool isEqual(const SectionKey<Is64Bits> &LHS,
1032                       const SectionKey<Is64Bits> &RHS) {
1033     return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
1034            LHS.sh_type == RHS.sh_type && LHS.sh_flags == RHS.sh_flags;
1035   }
1036 };
1037 }
1038 
1039 template <class ELFT>
1040 static bool cmpAlign(const DefinedCommon<ELFT> *A,
1041                      const DefinedCommon<ELFT> *B) {
1042   return A->MaxAlignment > B->MaxAlignment;
1043 }
1044 
1045 template <bool Is64Bits>
1046 static bool compSec(OutputSectionBase<Is64Bits> *A,
1047                     OutputSectionBase<Is64Bits> *B) {
1048   // Place SHF_ALLOC sections first.
1049   return (A->getFlags() & SHF_ALLOC) && !(B->getFlags() & SHF_ALLOC);
1050 }
1051 
1052 // The reason we have to do this early scan is as follows
1053 // * To mmap the output file, we need to know the size
1054 // * For that, we need to know how many dynamic relocs we will have.
1055 // It might be possible to avoid this by outputting the file with write:
1056 // * Write the allocated output sections, computing addresses.
1057 // * Apply relocations, recording which ones require a dynamic reloc.
1058 // * Write the dynamic relocations.
1059 // * Write the rest of the file.
1060 template <class ELFT>
1061 template <bool isRela>
1062 void Writer<ELFT>::scanRelocs(
1063     const InputSection<ELFT> &C,
1064     iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
1065   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
1066   const ObjectFile<ELFT> &File = *C.getFile();
1067   bool IsMips64EL = File.getObj()->isMips64EL();
1068   for (const RelType &RI : Rels) {
1069     uint32_t SymIndex = RI.getSymbol(IsMips64EL);
1070     SymbolBody *Body = File.getSymbolBody(SymIndex);
1071     if (!Body)
1072       continue;
1073     auto *S = dyn_cast<SharedSymbol<ELFT>>(Body);
1074     if (!S)
1075       continue;
1076     uint32_t Type = RI.getType(IsMips64EL);
1077     if (relocNeedsPLT(Type)) {
1078       if (Body->isInPlt())
1079         continue;
1080       PltSec.addEntry(Body);
1081     }
1082     if (relocNeedsGOT(Type)) {
1083       if (Body->isInGot())
1084         continue;
1085       GotSec.addEntry(Body);
1086     }
1087     RelaDynSec.addReloc({C, RI});
1088   }
1089 }
1090 
1091 template <class ELFT>
1092 void Writer<ELFT>::scanRelocs(const InputSection<ELFT> &C) {
1093   const ObjectFile<ELFT> *File = C.getFile();
1094   ELFFile<ELFT> *EObj = File->getObj();
1095 
1096   if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
1097     return;
1098 
1099   for (const Elf_Shdr *RelSec : C.RelocSections) {
1100     if (RelSec->sh_type == SHT_RELA)
1101       scanRelocs(C, EObj->relas(RelSec));
1102     else
1103       scanRelocs(C, EObj->rels(RelSec));
1104   }
1105 }
1106 
1107 // Create output section objects and add them to OutputSections.
1108 template <class ELFT> void Writer<ELFT>::createSections() {
1109   SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSection<ELFT> *> Map;
1110   auto getSection = [&](StringRef Name, uint32_t sh_type,
1111                         uintX_t sh_flags) -> OutputSection<ELFT> * {
1112     SectionKey<ELFT::Is64Bits> Key{Name, sh_type, sh_flags};
1113     OutputSection<ELFT> *&Sec = Map[Key];
1114     if (!Sec) {
1115       Sec = new (CAlloc.Allocate()) OutputSection<ELFT>(
1116           PltSec, GotSec, Key.Name, Key.sh_type, Key.sh_flags);
1117       OutputSections.push_back(Sec);
1118     }
1119     return Sec;
1120   };
1121 
1122   // FIXME: Try to avoid the extra walk over all global symbols.
1123   const SymbolTable &Symtab = SymTabSec.getSymTable();
1124   std::vector<DefinedCommon<ELFT> *> CommonSymbols;
1125   for (auto &P : Symtab.getSymbols()) {
1126     StringRef Name = P.first;
1127     SymbolBody *Body = P.second->Body;
1128     if (Body->isStrongUndefined())
1129       error(Twine("undefined symbol: ") + Name);
1130 
1131     if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
1132       CommonSymbols.push_back(C);
1133     if (!includeInSymtab(*Body))
1134       continue;
1135     SymTabSec.addSymbol(Name);
1136 
1137     // FIXME: This adds way too much to the dynamic symbol table. We only
1138     // need to add the symbols use by dynamic relocations when producing
1139     // an executable (ignoring --export-dynamic).
1140     if (needsDynamicSections())
1141       HashSec.addSymbol(Body);
1142   }
1143 
1144   for (const std::unique_ptr<ObjectFileBase> &FileB : Symtab.getObjectFiles()) {
1145     auto &File = cast<ObjectFile<ELFT>>(*FileB);
1146     if (!Config->DiscardAll) {
1147       Elf_Sym_Range Syms = File.getLocalSymbols();
1148       for (const Elf_Sym &Sym : Syms) {
1149         ErrorOr<StringRef> SymName = Sym.getName(File.getStringTable());
1150         if (SymName && !(Config->DiscardLocals && SymName->startswith(".L")))
1151           SymTabSec.addSymbol(*SymName, true);
1152       }
1153     }
1154     for (InputSection<ELFT> *C : File.getChunks()) {
1155       if (!C)
1156         continue;
1157       const Elf_Shdr *H = C->getSectionHdr();
1158       OutputSection<ELFT> *Sec =
1159           getSection(C->getSectionName(), H->sh_type, H->sh_flags);
1160       Sec->addChunk(C);
1161       scanRelocs(*C);
1162     }
1163   }
1164 
1165   BSSSec = getSection(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1166   // Sort the common symbols by alignment as an heuristic to pack them better.
1167   std::stable_sort(CommonSymbols.begin(), CommonSymbols.end(), cmpAlign<ELFT>);
1168   uintX_t Off = BSSSec->getSize();
1169   for (DefinedCommon<ELFT> *C : CommonSymbols) {
1170     const Elf_Sym &Sym = C->Sym;
1171     uintX_t Align = C->MaxAlignment;
1172     Off = RoundUpToAlignment(Off, Align);
1173     C->OffsetInBSS = Off;
1174     C->OutputSec = BSSSec;
1175     Off += Sym.st_size;
1176   }
1177 
1178   BSSSec->setSize(Off);
1179 
1180   OutputSections.push_back(&SymTabSec);
1181   OutputSections.push_back(&StrTabSec);
1182 
1183   if (needsDynamicSections()) {
1184     if (needsInterpSection())
1185       OutputSections.push_back(&InterpSec);
1186     OutputSections.push_back(&DynSymSec);
1187     OutputSections.push_back(&HashSec);
1188     OutputSections.push_back(&DynamicSec);
1189     OutputSections.push_back(&DynStrSec);
1190     if (RelaDynSec.hasRelocs())
1191       OutputSections.push_back(&RelaDynSec);
1192     if (!GotSec.empty())
1193       OutputSections.push_back(&GotSec);
1194     if (!PltSec.empty())
1195       OutputSections.push_back(&PltSec);
1196   }
1197 
1198   std::stable_sort(OutputSections.begin(), OutputSections.end(),
1199                    compSec<ELFT::Is64Bits>);
1200   for (unsigned I = 0, N = OutputSections.size(); I < N; ++I)
1201     OutputSections[I]->setSectionIndex(I + 1);
1202 }
1203 
1204 template <class ELFT>
1205 static bool outputSectionHasPHDR(OutputSectionBase<ELFT::Is64Bits> *Sec) {
1206   return Sec->getFlags() & SHF_ALLOC;
1207 }
1208 
1209 // Visits all sections to assign incremental, non-overlapping RVAs and
1210 // file offsets.
1211 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1212   assert(!OutputSections.empty() && "No output sections to layout!");
1213   uintX_t VA = getVAStart();
1214   uintX_t FileOff = 0;
1215 
1216   FileOff += sizeof(Elf_Ehdr);
1217   VA += sizeof(Elf_Ehdr);
1218 
1219   // Reserve space for PHDRs.
1220   ProgramHeaderOff = FileOff;
1221   FileOff = RoundUpToAlignment(FileOff, PageSize);
1222   VA = RoundUpToAlignment(VA, PageSize);
1223 
1224   if (needsInterpSection())
1225     PHDRs.push_back(&InterpPHDR);
1226 
1227   ProgramHeader<ELFT::Is64Bits> *LastPHDR = &FileHeaderPHDR;
1228   // Create a PHDR for the file header.
1229   PHDRs.push_back(&FileHeaderPHDR);
1230   FileHeaderPHDR.Header.p_vaddr = getVAStart();
1231   FileHeaderPHDR.Header.p_paddr = getVAStart();
1232   FileHeaderPHDR.Header.p_align = PageSize;
1233 
1234   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
1235     StrTabSec.add(Sec->getName());
1236     Sec->finalize();
1237 
1238     if (Sec->getSize()) {
1239       uintX_t Flags = convertSectionFlagsToPHDRFlags(Sec->getFlags());
1240       if (LastPHDR->Header.p_flags != Flags ||
1241           !outputSectionHasPHDR<ELFT>(Sec)) {
1242         // Flags changed. End current PHDR and potentially create a new one.
1243         if (!LastPHDR->Closed) {
1244           LastPHDR->Header.p_filesz = FileOff - LastPHDR->Header.p_offset;
1245           LastPHDR->Header.p_memsz = VA - LastPHDR->Header.p_vaddr;
1246           LastPHDR->Closed = true;
1247         }
1248 
1249         if (outputSectionHasPHDR<ELFT>(Sec)) {
1250           LastPHDR = new (PAlloc) ProgramHeader<ELFT::Is64Bits>(PT_LOAD, Flags);
1251           PHDRs.push_back(LastPHDR);
1252           VA = RoundUpToAlignment(VA, PageSize);
1253           FileOff = RoundUpToAlignment(FileOff, PageSize);
1254           LastPHDR->Header.p_offset = FileOff;
1255           LastPHDR->Header.p_vaddr = VA;
1256           LastPHDR->Header.p_paddr = VA;
1257         }
1258       }
1259     }
1260 
1261     uintX_t Align = Sec->getAlign();
1262     uintX_t Size = Sec->getSize();
1263     if (Sec->getFlags() & SHF_ALLOC) {
1264       VA = RoundUpToAlignment(VA, Align);
1265       Sec->setVA(VA);
1266       VA += Size;
1267     }
1268     FileOff = RoundUpToAlignment(FileOff, Align);
1269     Sec->setFileOffset(FileOff);
1270     if (Sec->getType() != SHT_NOBITS)
1271       FileOff += Size;
1272   }
1273 
1274   // Add a PHDR for the dynamic table.
1275   if (needsDynamicSections())
1276     PHDRs.push_back(&DynamicPHDR);
1277 
1278   FileOff += OffsetToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4);
1279 
1280   // Add space for section headers.
1281   SectionHeaderOff = FileOff;
1282   FileOff += getNumSections() * sizeof(Elf_Shdr);
1283   FileSize = FileOff;
1284 }
1285 
1286 template <class ELFT> void Writer<ELFT>::writeHeader() {
1287   uint8_t *Buf = Buffer->getBufferStart();
1288   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1289   EHdr->e_ident[EI_MAG0] = 0x7F;
1290   EHdr->e_ident[EI_MAG1] = 0x45;
1291   EHdr->e_ident[EI_MAG2] = 0x4C;
1292   EHdr->e_ident[EI_MAG3] = 0x46;
1293   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1294   EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little
1295                                ? ELFDATA2LSB
1296                                : ELFDATA2MSB;
1297   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1298   EHdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1299 
1300   // FIXME: Generalize the segment construction similar to how we create
1301   // output sections.
1302   const SymbolTable &Symtab = SymTabSec.getSymTable();
1303 
1304   EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC;
1305   auto &FirstObj = cast<ObjectFile<ELFT>>(*Symtab.getFirstELF());
1306   EHdr->e_machine = FirstObj.getEMachine();
1307   EHdr->e_version = EV_CURRENT;
1308   SymbolBody *Entry = Symtab.getEntrySym();
1309   EHdr->e_entry = Entry ? getSymVA(cast<DefinedRegular<ELFT>>(Entry)) : 0;
1310   EHdr->e_phoff = ProgramHeaderOff;
1311   EHdr->e_shoff = SectionHeaderOff;
1312   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1313   EHdr->e_phentsize = sizeof(Elf_Phdr);
1314   EHdr->e_phnum = PHDRs.size();
1315   EHdr->e_shentsize = sizeof(Elf_Shdr);
1316   EHdr->e_shnum = getNumSections();
1317   EHdr->e_shstrndx = StrTabSec.getSectionIndex();
1318 
1319   // If nothing was merged into the file header PT_LOAD, set the size correctly.
1320   if (FileHeaderPHDR.Header.p_filesz == PageSize)
1321     FileHeaderPHDR.Header.p_filesz = FileHeaderPHDR.Header.p_memsz =
1322         sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * PHDRs.size();
1323 
1324   if (needsInterpSection())
1325     InterpPHDR.setValuesFromSection(InterpSec);
1326   if (needsDynamicSections())
1327     DynamicPHDR.setValuesFromSection(DynamicSec);
1328 
1329   auto PHdrs = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1330   for (ProgramHeader<ELFT::Is64Bits> *PHDR : PHDRs)
1331     PHDR->template writeHeaderTo<ELFT::TargetEndianness>(PHdrs++);
1332 
1333   auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1334   // First entry is null.
1335   ++SHdrs;
1336   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
1337     Sec->setNameOffset(StrTabSec.getFileOff(Sec->getName()));
1338     Sec->template writeHeaderTo<ELFT::TargetEndianness>(SHdrs++);
1339   }
1340 }
1341 
1342 template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) {
1343   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1344       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable);
1345   error(BufferOrErr, Twine("failed to open ") + Path);
1346   Buffer = std::move(*BufferOrErr);
1347 }
1348 
1349 // Write section contents to a mmap'ed file.
1350 template <class ELFT> void Writer<ELFT>::writeSections() {
1351   uint8_t *Buf = Buffer->getBufferStart();
1352   for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections)
1353     Sec->writeTo(Buf + Sec->getFileOff());
1354 }
1355