1 //===- OutputSections.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 "OutputSections.h"
11 #include "Config.h"
12 #include "EhFrame.h"
13 #include "LinkerScript.h"
14 #include "GdbIndex.h"
15 #include "Strings.h"
16 #include "SymbolTable.h"
17 #include "Target.h"
18 #include "lld/Core/Parallel.h"
19 #include "llvm/Support/Dwarf.h"
20 #include "llvm/Support/MD5.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/RandomNumberGenerator.h"
23 #include "llvm/Support/SHA1.h"
24 #include "llvm/Support/xxhash.h"
25 
26 using namespace llvm;
27 using namespace llvm::dwarf;
28 using namespace llvm::object;
29 using namespace llvm::support::endian;
30 using namespace llvm::ELF;
31 
32 using namespace lld;
33 using namespace lld::elf;
34 
35 template <class ELFT>
36 OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
37                                            uintX_t Flags)
38     : Name(Name) {
39   memset(&Header, 0, sizeof(Elf_Shdr));
40   Header.sh_type = Type;
41   Header.sh_flags = Flags;
42   Header.sh_addralign = 1;
43 }
44 
45 template <class ELFT> uint32_t OutputSectionBase<ELFT>::getPhdrFlags() const {
46   uintX_t Flags = getFlags();
47   uint32_t Ret = PF_R;
48   if (Flags & SHF_WRITE)
49     Ret |= PF_W;
50   if (Flags & SHF_EXECINSTR)
51     Ret |= PF_X;
52   return Ret;
53 }
54 
55 template <class ELFT>
56 void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
57   *Shdr = Header;
58 }
59 
60 template <class ELFT>
61 GdbIndexSection<ELFT>::GdbIndexSection()
62     : OutputSectionBase<ELFT>(".gdb_index", SHT_PROGBITS, 0) {}
63 
64 template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
65   std::vector<InputSection<ELFT> *> &IS =
66       static_cast<OutputSection<ELFT> *>(Out<ELFT>::DebugInfo)->Sections;
67 
68   for (InputSection<ELFT> *I : IS)
69     readDwarf(I);
70 }
71 
72 template <class ELFT>
73 void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
74   std::vector<std::pair<uintX_t, uintX_t>> CuList = readCuList(I);
75   CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
76 }
77 
78 template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
79   parseDebugSections();
80 
81   // GdbIndex header consist from version fields
82   // and 5 more fields with different kinds of offsets.
83   CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
84   this->Header.sh_size = CuTypesOffset;
85 }
86 
87 template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
88   write32le(Buf, 7);                  // Write Version
89   write32le(Buf + 4, CuListOffset);   // CU list offset
90   write32le(Buf + 8, CuTypesOffset);  // Types CU list offset
91   write32le(Buf + 12, CuTypesOffset); // Address area offset
92   write32le(Buf + 16, CuTypesOffset); // Symbol table offset
93   write32le(Buf + 20, CuTypesOffset); // Constant pool offset
94   Buf += 24;
95 
96   // Write the CU list.
97   for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
98     write64le(Buf, CU.first);
99     write64le(Buf + 8, CU.second);
100     Buf += 16;
101   }
102 }
103 
104 template <class ELFT>
105 GotPltSection<ELFT>::GotPltSection()
106     : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
107   this->Header.sh_addralign = Target->GotPltEntrySize;
108 }
109 
110 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
111   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
112   Entries.push_back(&Sym);
113 }
114 
115 template <class ELFT> bool GotPltSection<ELFT>::empty() const {
116   return Entries.empty();
117 }
118 
119 template <class ELFT> void GotPltSection<ELFT>::finalize() {
120   this->Header.sh_size = (Target->GotPltHeaderEntriesNum + Entries.size()) *
121                          Target->GotPltEntrySize;
122 }
123 
124 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
125   Target->writeGotPltHeader(Buf);
126   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
127   for (const SymbolBody *B : Entries) {
128     Target->writeGotPlt(Buf, *B);
129     Buf += sizeof(uintX_t);
130   }
131 }
132 
133 template <class ELFT>
134 GotSection<ELFT>::GotSection()
135     : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
136   if (Config->EMachine == EM_MIPS)
137     this->Header.sh_flags |= SHF_MIPS_GPREL;
138   this->Header.sh_addralign = Target->GotEntrySize;
139 }
140 
141 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
142   Sym.GotIndex = Entries.size();
143   Entries.push_back(&Sym);
144 }
145 
146 template <class ELFT>
147 void GotSection<ELFT>::addMipsEntry(SymbolBody &Sym, uintX_t Addend,
148                                     RelExpr Expr) {
149   // For "true" local symbols which can be referenced from the same module
150   // only compiler creates two instructions for address loading:
151   //
152   // lw   $8, 0($gp) # R_MIPS_GOT16
153   // addi $8, $8, 0  # R_MIPS_LO16
154   //
155   // The first instruction loads high 16 bits of the symbol address while
156   // the second adds an offset. That allows to reduce number of required
157   // GOT entries because only one global offset table entry is necessary
158   // for every 64 KBytes of local data. So for local symbols we need to
159   // allocate number of GOT entries to hold all required "page" addresses.
160   //
161   // All global symbols (hidden and regular) considered by compiler uniformly.
162   // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
163   // to load address of the symbol. So for each such symbol we need to
164   // allocate dedicated GOT entry to store its address.
165   //
166   // If a symbol is preemptible we need help of dynamic linker to get its
167   // final address. The corresponding GOT entries are allocated in the
168   // "global" part of GOT. Entries for non preemptible global symbol allocated
169   // in the "local" part of GOT.
170   //
171   // See "Global Offset Table" in Chapter 5:
172   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
173   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
174     // At this point we do not know final symbol value so to reduce number
175     // of allocated GOT entries do the following trick. Save all output
176     // sections referenced by GOT relocations. Then later in the `finalize`
177     // method calculate number of "pages" required to cover all saved output
178     // section and allocate appropriate number of GOT entries.
179     auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
180     MipsOutSections.insert(OutSec);
181     return;
182   }
183   if (Sym.isTls()) {
184     // GOT entries created for MIPS TLS relocations behave like
185     // almost GOT entries from other ABIs. They go to the end
186     // of the global offset table.
187     Sym.GotIndex = Entries.size();
188     Entries.push_back(&Sym);
189     return;
190   }
191   auto AddEntry = [&](SymbolBody &S, uintX_t A, MipsGotEntries &Items) {
192     if (S.isInGot() && !A)
193       return;
194     size_t NewIndex = Items.size();
195     if (!MipsGotMap.insert({{&S, A}, NewIndex}).second)
196       return;
197     Items.emplace_back(&S, A);
198     if (!A)
199       S.GotIndex = NewIndex;
200   };
201   if (Sym.isPreemptible()) {
202     // Ignore addends for preemptible symbols. They got single GOT entry anyway.
203     AddEntry(Sym, 0, MipsGlobal);
204     Sym.IsInGlobalMipsGot = true;
205   } else if (Expr == R_MIPS_GOT_OFF32) {
206     AddEntry(Sym, Addend, MipsLocal32);
207     Sym.Is32BitMipsGot = true;
208   } else {
209     // Hold local GOT entries accessed via a 16-bit index separately.
210     // That allows to write them in the beginning of the GOT and keep
211     // their indexes as less as possible to escape relocation's overflow.
212     AddEntry(Sym, Addend, MipsLocal);
213   }
214 }
215 
216 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
217   if (Sym.GlobalDynIndex != -1U)
218     return false;
219   Sym.GlobalDynIndex = Entries.size();
220   // Global Dynamic TLS entries take two GOT slots.
221   Entries.push_back(nullptr);
222   Entries.push_back(&Sym);
223   return true;
224 }
225 
226 // Reserves TLS entries for a TLS module ID and a TLS block offset.
227 // In total it takes two GOT slots.
228 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
229   if (TlsIndexOff != uint32_t(-1))
230     return false;
231   TlsIndexOff = Entries.size() * sizeof(uintX_t);
232   Entries.push_back(nullptr);
233   Entries.push_back(nullptr);
234   return true;
235 }
236 
237 template <class ELFT>
238 typename GotSection<ELFT>::uintX_t
239 GotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) {
240   // Initialize the entry by the %hi(EntryValue) expression
241   // but without right-shifting.
242   EntryValue = (EntryValue + 0x8000) & ~0xffff;
243   // Take into account MIPS GOT header.
244   // See comment in the GotSection::writeTo.
245   size_t NewIndex = MipsLocalGotPos.size() + 2;
246   auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
247   assert(!P.second || MipsLocalGotPos.size() <= MipsPageEntries);
248   return (uintX_t)P.first->second * sizeof(uintX_t) - MipsGPOffset;
249 }
250 
251 template <class ELFT>
252 typename GotSection<ELFT>::uintX_t
253 GotSection<ELFT>::getMipsGotOffset(const SymbolBody &B, uintX_t Addend) const {
254   // Calculate offset of the GOT entries block: TLS, global, local.
255   uintX_t GotBlockOff;
256   if (B.isTls())
257     GotBlockOff = getMipsTlsOffset();
258   else if (B.IsInGlobalMipsGot)
259     GotBlockOff = getMipsLocalEntriesNum() * sizeof(uintX_t);
260   else if (B.Is32BitMipsGot)
261     GotBlockOff = (MipsPageEntries + MipsLocal.size()) * sizeof(uintX_t);
262   else
263     GotBlockOff = MipsPageEntries * sizeof(uintX_t);
264   // Calculate index of the GOT entry in the block.
265   uintX_t GotIndex;
266   if (B.isInGot())
267     GotIndex = B.GotIndex;
268   else {
269     auto It = MipsGotMap.find({&B, Addend});
270     assert(It != MipsGotMap.end());
271     GotIndex = It->second;
272   }
273   return GotBlockOff + GotIndex * sizeof(uintX_t) - MipsGPOffset;
274 }
275 
276 template <class ELFT>
277 typename GotSection<ELFT>::uintX_t GotSection<ELFT>::getMipsTlsOffset() const {
278   return (getMipsLocalEntriesNum() + MipsGlobal.size()) * sizeof(uintX_t);
279 }
280 
281 template <class ELFT>
282 typename GotSection<ELFT>::uintX_t
283 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
284   return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
285 }
286 
287 template <class ELFT>
288 typename GotSection<ELFT>::uintX_t
289 GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
290   return B.GlobalDynIndex * sizeof(uintX_t);
291 }
292 
293 template <class ELFT>
294 const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
295   return MipsGlobal.empty() ? nullptr : MipsGlobal.front().first;
296 }
297 
298 template <class ELFT>
299 unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
300   return MipsPageEntries + MipsLocal.size() + MipsLocal32.size();
301 }
302 
303 template <class ELFT> void GotSection<ELFT>::finalize() {
304   size_t EntriesNum = Entries.size();
305   if (Config->EMachine == EM_MIPS) {
306     // Take into account MIPS GOT header.
307     // See comment in the GotSection::writeTo.
308     MipsPageEntries += 2;
309     for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
310       // Calculate an upper bound of MIPS GOT entries required to store page
311       // addresses of local symbols. We assume the worst case - each 64kb
312       // page of the output section has at least one GOT relocation against it.
313       // Add 0x8000 to the section's size because the page address stored
314       // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
315       MipsPageEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
316     }
317     EntriesNum += getMipsLocalEntriesNum() + MipsGlobal.size();
318   }
319   this->Header.sh_size = EntriesNum * sizeof(uintX_t);
320 }
321 
322 template <class ELFT>
323 static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
324   typedef typename ELFT::uint uintX_t;
325   write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
326 }
327 
328 template <class ELFT> void GotSection<ELFT>::writeMipsGot(uint8_t *Buf) {
329   // Set the MSB of the second GOT slot. This is not required by any
330   // MIPS ABI documentation, though.
331   //
332   // There is a comment in glibc saying that "The MSB of got[1] of a
333   // gnu object is set to identify gnu objects," and in GNU gold it
334   // says "the second entry will be used by some runtime loaders".
335   // But how this field is being used is unclear.
336   //
337   // We are not really willing to mimic other linkers behaviors
338   // without understanding why they do that, but because all files
339   // generated by GNU tools have this special GOT value, and because
340   // we've been doing this for years, it is probably a safe bet to
341   // keep doing this for now. We really need to revisit this to see
342   // if we had to do this.
343   auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
344   P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
345   // Write 'page address' entries to the local part of the GOT.
346   for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
347     uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
348     writeUint<ELFT>(Entry, L.first);
349   }
350   Buf += MipsPageEntries * sizeof(uintX_t);
351   auto AddEntry = [&](const MipsGotEntry &SA) {
352     uint8_t *Entry = Buf;
353     Buf += sizeof(uintX_t);
354     const SymbolBody *Body = SA.first;
355     uintX_t VA = Body->template getVA<ELFT>(SA.second);
356     writeUint<ELFT>(Entry, VA);
357   };
358   std::for_each(std::begin(MipsLocal), std::end(MipsLocal), AddEntry);
359   std::for_each(std::begin(MipsLocal32), std::end(MipsLocal32), AddEntry);
360   std::for_each(std::begin(MipsGlobal), std::end(MipsGlobal), AddEntry);
361   // Initialize TLS-related GOT entries. If the entry has a corresponding
362   // dynamic relocations, leave it initialized by zero. Write down adjusted
363   // TLS symbol's values otherwise. To calculate the adjustments use offsets
364   // for thread-local storage.
365   // https://www.linux-mips.org/wiki/NPTL
366   if (TlsIndexOff != -1U && !Config->Pic)
367     writeUint<ELFT>(Buf + TlsIndexOff, 1);
368   for (const SymbolBody *B : Entries) {
369     if (!B || B->isPreemptible())
370       continue;
371     uintX_t VA = B->getVA<ELFT>();
372     if (B->GotIndex != -1U) {
373       uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
374       writeUint<ELFT>(Entry, VA - 0x7000);
375     }
376     if (B->GlobalDynIndex != -1U) {
377       uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
378       writeUint<ELFT>(Entry, 1);
379       Entry += sizeof(uintX_t);
380       writeUint<ELFT>(Entry, VA - 0x8000);
381     }
382   }
383 }
384 
385 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
386   if (Config->EMachine == EM_MIPS) {
387     writeMipsGot(Buf);
388     return;
389   }
390   for (const SymbolBody *B : Entries) {
391     uint8_t *Entry = Buf;
392     Buf += sizeof(uintX_t);
393     if (!B)
394       continue;
395     if (B->isPreemptible())
396       continue; // The dynamic linker will take care of it.
397     uintX_t VA = B->getVA<ELFT>();
398     writeUint<ELFT>(Entry, VA);
399   }
400 }
401 
402 template <class ELFT>
403 PltSection<ELFT>::PltSection()
404     : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
405   this->Header.sh_addralign = 16;
406 }
407 
408 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
409   // At beginning of PLT, we have code to call the dynamic linker
410   // to resolve dynsyms at runtime. Write such code.
411   Target->writePltHeader(Buf);
412   size_t Off = Target->PltHeaderSize;
413 
414   for (auto &I : Entries) {
415     const SymbolBody *B = I.first;
416     unsigned RelOff = I.second;
417     uint64_t Got = B->getGotPltVA<ELFT>();
418     uint64_t Plt = this->getVA() + Off;
419     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
420     Off += Target->PltEntrySize;
421   }
422 }
423 
424 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
425   Sym.PltIndex = Entries.size();
426   unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset();
427   Entries.push_back(std::make_pair(&Sym, RelOff));
428 }
429 
430 template <class ELFT> void PltSection<ELFT>::finalize() {
431   this->Header.sh_size =
432       Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
433 }
434 
435 template <class ELFT>
436 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
437     : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
438                               SHF_ALLOC),
439       Sort(Sort) {
440   this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
441   this->Header.sh_addralign = sizeof(uintX_t);
442 }
443 
444 template <class ELFT>
445 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
446   if (Reloc.Type == Target->RelativeRel)
447     ++NumRelativeRelocs;
448   Relocs.push_back(Reloc);
449 }
450 
451 template <class ELFT, class RelTy>
452 static bool compRelocations(const RelTy &A, const RelTy &B) {
453   bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
454   bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
455   if (AIsRel != BIsRel)
456     return AIsRel;
457 
458   return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
459 }
460 
461 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
462   uint8_t *BufBegin = Buf;
463   for (const DynamicReloc<ELFT> &Rel : Relocs) {
464     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
465     Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
466 
467     if (Config->Rela)
468       P->r_addend = Rel.getAddend();
469     P->r_offset = Rel.getOffset();
470     if (Config->EMachine == EM_MIPS && Rel.getOutputSec() == Out<ELFT>::Got)
471       // Dynamic relocation against MIPS GOT section make deal TLS entries
472       // allocated in the end of the GOT. We need to adjust the offset to take
473       // in account 'local' and 'global' GOT entries.
474       P->r_offset += Out<ELFT>::Got->getMipsTlsOffset();
475     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
476   }
477 
478   if (Sort) {
479     if (Config->Rela)
480       std::stable_sort((Elf_Rela *)BufBegin,
481                        (Elf_Rela *)BufBegin + Relocs.size(),
482                        compRelocations<ELFT, Elf_Rela>);
483     else
484       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
485                        compRelocations<ELFT, Elf_Rel>);
486   }
487 }
488 
489 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
490   return this->Header.sh_entsize * Relocs.size();
491 }
492 
493 template <class ELFT> void RelocationSection<ELFT>::finalize() {
494   this->Header.sh_link = Out<ELFT>::DynSymTab
495                              ? Out<ELFT>::DynSymTab->SectionIndex
496                              : Out<ELFT>::SymTab->SectionIndex;
497   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
498 }
499 
500 template <class ELFT>
501 InterpSection<ELFT>::InterpSection()
502     : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
503   this->Header.sh_size = Config->DynamicLinker.size() + 1;
504 }
505 
506 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
507   StringRef S = Config->DynamicLinker;
508   memcpy(Buf, S.data(), S.size());
509 }
510 
511 template <class ELFT>
512 HashTableSection<ELFT>::HashTableSection()
513     : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
514   this->Header.sh_entsize = sizeof(Elf_Word);
515   this->Header.sh_addralign = sizeof(Elf_Word);
516 }
517 
518 static uint32_t hashSysv(StringRef Name) {
519   uint32_t H = 0;
520   for (char C : Name) {
521     H = (H << 4) + C;
522     uint32_t G = H & 0xf0000000;
523     if (G)
524       H ^= G >> 24;
525     H &= ~G;
526   }
527   return H;
528 }
529 
530 template <class ELFT> void HashTableSection<ELFT>::finalize() {
531   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
532 
533   unsigned NumEntries = 2;                             // nbucket and nchain.
534   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
535 
536   // Create as many buckets as there are symbols.
537   // FIXME: This is simplistic. We can try to optimize it, but implementing
538   // support for SHT_GNU_HASH is probably even more profitable.
539   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
540   this->Header.sh_size = NumEntries * sizeof(Elf_Word);
541 }
542 
543 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
544   unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
545   auto *P = reinterpret_cast<Elf_Word *>(Buf);
546   *P++ = NumSymbols; // nbucket
547   *P++ = NumSymbols; // nchain
548 
549   Elf_Word *Buckets = P;
550   Elf_Word *Chains = P + NumSymbols;
551 
552   for (const SymbolTableEntry &S : Out<ELFT>::DynSymTab->getSymbols()) {
553     SymbolBody *Body = S.Symbol;
554     StringRef Name = Body->getName();
555     unsigned I = Body->DynsymIndex;
556     uint32_t Hash = hashSysv(Name) % NumSymbols;
557     Chains[I] = Buckets[Hash];
558     Buckets[Hash] = I;
559   }
560 }
561 
562 static uint32_t hashGnu(StringRef Name) {
563   uint32_t H = 5381;
564   for (uint8_t C : Name)
565     H = (H << 5) + H + C;
566   return H;
567 }
568 
569 template <class ELFT>
570 GnuHashTableSection<ELFT>::GnuHashTableSection()
571     : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
572   this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
573   this->Header.sh_addralign = sizeof(uintX_t);
574 }
575 
576 template <class ELFT>
577 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
578   if (!NumHashed)
579     return 0;
580 
581   // These values are prime numbers which are not greater than 2^(N-1) + 1.
582   // In result, for any particular NumHashed we return a prime number
583   // which is not greater than NumHashed.
584   static const unsigned Primes[] = {
585       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
586       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
587 
588   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
589                                    array_lengthof(Primes) - 1)];
590 }
591 
592 // Bloom filter estimation: at least 8 bits for each hashed symbol.
593 // GNU Hash table requirement: it should be a power of 2,
594 //   the minimum value is 1, even for an empty table.
595 // Expected results for a 32-bit target:
596 //   calcMaskWords(0..4)   = 1
597 //   calcMaskWords(5..8)   = 2
598 //   calcMaskWords(9..16)  = 4
599 // For a 64-bit target:
600 //   calcMaskWords(0..8)   = 1
601 //   calcMaskWords(9..16)  = 2
602 //   calcMaskWords(17..32) = 4
603 template <class ELFT>
604 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
605   if (!NumHashed)
606     return 1;
607   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
608 }
609 
610 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
611   unsigned NumHashed = Symbols.size();
612   NBuckets = calcNBuckets(NumHashed);
613   MaskWords = calcMaskWords(NumHashed);
614   // Second hash shift estimation: just predefined values.
615   Shift2 = ELFT::Is64Bits ? 6 : 5;
616 
617   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
618   this->Header.sh_size = sizeof(Elf_Word) * 4            // Header
619                          + sizeof(Elf_Off) * MaskWords   // Bloom Filter
620                          + sizeof(Elf_Word) * NBuckets   // Hash Buckets
621                          + sizeof(Elf_Word) * NumHashed; // Hash Values
622 }
623 
624 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
625   writeHeader(Buf);
626   if (Symbols.empty())
627     return;
628   writeBloomFilter(Buf);
629   writeHashTable(Buf);
630 }
631 
632 template <class ELFT>
633 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
634   auto *P = reinterpret_cast<Elf_Word *>(Buf);
635   *P++ = NBuckets;
636   *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
637   *P++ = MaskWords;
638   *P++ = Shift2;
639   Buf = reinterpret_cast<uint8_t *>(P);
640 }
641 
642 template <class ELFT>
643 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
644   unsigned C = sizeof(Elf_Off) * 8;
645 
646   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
647   for (const SymbolData &Sym : Symbols) {
648     size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
649     uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
650                 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
651     Masks[Pos] |= V;
652   }
653   Buf += sizeof(Elf_Off) * MaskWords;
654 }
655 
656 template <class ELFT>
657 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
658   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
659   Elf_Word *Values = Buckets + NBuckets;
660 
661   int PrevBucket = -1;
662   int I = 0;
663   for (const SymbolData &Sym : Symbols) {
664     int Bucket = Sym.Hash % NBuckets;
665     assert(PrevBucket <= Bucket);
666     if (Bucket != PrevBucket) {
667       Buckets[Bucket] = Sym.Body->DynsymIndex;
668       PrevBucket = Bucket;
669       if (I > 0)
670         Values[I - 1] |= 1;
671     }
672     Values[I] = Sym.Hash & ~1;
673     ++I;
674   }
675   if (I > 0)
676     Values[I - 1] |= 1;
677 }
678 
679 // Add symbols to this symbol hash table. Note that this function
680 // destructively sort a given vector -- which is needed because
681 // GNU-style hash table places some sorting requirements.
682 template <class ELFT>
683 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
684   // Ideally this will just be 'auto' but GCC 6.1 is not able
685   // to deduce it correctly.
686   std::vector<SymbolTableEntry>::iterator Mid =
687       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
688         return S.Symbol->isUndefined();
689       });
690   if (Mid == V.end())
691     return;
692   for (auto I = Mid, E = V.end(); I != E; ++I) {
693     SymbolBody *B = I->Symbol;
694     size_t StrOff = I->StrTabOffset;
695     Symbols.push_back({B, StrOff, hashGnu(B->getName())});
696   }
697 
698   unsigned NBuckets = calcNBuckets(Symbols.size());
699   std::stable_sort(Symbols.begin(), Symbols.end(),
700                    [&](const SymbolData &L, const SymbolData &R) {
701                      return L.Hash % NBuckets < R.Hash % NBuckets;
702                    });
703 
704   V.erase(Mid, V.end());
705   for (const SymbolData &Sym : Symbols)
706     V.push_back({Sym.Body, Sym.STName});
707 }
708 
709 // Returns the number of version definition entries. Because the first entry
710 // is for the version definition itself, it is the number of versioned symbols
711 // plus one. Note that we don't support multiple versions yet.
712 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
713 
714 template <class ELFT>
715 DynamicSection<ELFT>::DynamicSection()
716     : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE) {
717   Elf_Shdr &Header = this->Header;
718   Header.sh_addralign = sizeof(uintX_t);
719   Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
720 
721   // .dynamic section is not writable on MIPS.
722   // See "Special Section" in Chapter 4 in the following document:
723   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
724   if (Config->EMachine == EM_MIPS)
725     Header.sh_flags = SHF_ALLOC;
726 }
727 
728 template <class ELFT> void DynamicSection<ELFT>::finalize() {
729   if (this->Header.sh_size)
730     return; // Already finalized.
731 
732   Elf_Shdr &Header = this->Header;
733   Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
734 
735   auto Add = [=](Entry E) { Entries.push_back(E); };
736 
737   // Add strings. We know that these are the last strings to be added to
738   // DynStrTab and doing this here allows this function to set DT_STRSZ.
739   for (StringRef S : Config->AuxiliaryList)
740     Add({DT_AUXILIARY, Out<ELFT>::DynStrTab->addString(S)});
741   if (!Config->RPath.empty())
742     Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
743          Out<ELFT>::DynStrTab->addString(Config->RPath)});
744   for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
745     if (F->isNeeded())
746       Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
747   if (!Config->SoName.empty())
748     Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
749 
750   Out<ELFT>::DynStrTab->finalize();
751 
752   if (Out<ELFT>::RelaDyn->hasRelocs()) {
753     bool IsRela = Config->Rela;
754     Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
755     Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
756     Add({IsRela ? DT_RELAENT : DT_RELENT,
757          uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
758 
759     // MIPS dynamic loader does not support RELCOUNT tag.
760     // The problem is in the tight relation between dynamic
761     // relocations and GOT. So do not emit this tag on MIPS.
762     if (Config->EMachine != EM_MIPS) {
763       size_t NumRelativeRels = Out<ELFT>::RelaDyn->getRelativeRelocCount();
764       if (Config->ZCombreloc && NumRelativeRels)
765         Add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
766     }
767   }
768   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
769     Add({DT_JMPREL, Out<ELFT>::RelaPlt});
770     Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
771     Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
772          Out<ELFT>::GotPlt});
773     Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
774   }
775 
776   Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
777   Add({DT_SYMENT, sizeof(Elf_Sym)});
778   Add({DT_STRTAB, Out<ELFT>::DynStrTab});
779   Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
780   if (Out<ELFT>::GnuHashTab)
781     Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
782   if (Out<ELFT>::HashTab)
783     Add({DT_HASH, Out<ELFT>::HashTab});
784 
785   if (Out<ELFT>::PreinitArray) {
786     Add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
787     Add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
788   }
789   if (Out<ELFT>::InitArray) {
790     Add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
791     Add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
792   }
793   if (Out<ELFT>::FiniArray) {
794     Add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
795     Add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
796   }
797 
798   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
799     Add({DT_INIT, B});
800   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
801     Add({DT_FINI, B});
802 
803   uint32_t DtFlags = 0;
804   uint32_t DtFlags1 = 0;
805   if (Config->Bsymbolic)
806     DtFlags |= DF_SYMBOLIC;
807   if (Config->ZNodelete)
808     DtFlags1 |= DF_1_NODELETE;
809   if (Config->ZNow) {
810     DtFlags |= DF_BIND_NOW;
811     DtFlags1 |= DF_1_NOW;
812   }
813   if (Config->ZOrigin) {
814     DtFlags |= DF_ORIGIN;
815     DtFlags1 |= DF_1_ORIGIN;
816   }
817 
818   if (DtFlags)
819     Add({DT_FLAGS, DtFlags});
820   if (DtFlags1)
821     Add({DT_FLAGS_1, DtFlags1});
822 
823   if (!Config->Entry.empty())
824     Add({DT_DEBUG, (uint64_t)0});
825 
826   bool HasVerNeed = Out<ELFT>::VerNeed->getNeedNum() != 0;
827   if (HasVerNeed || Out<ELFT>::VerDef)
828     Add({DT_VERSYM, Out<ELFT>::VerSym});
829   if (Out<ELFT>::VerDef) {
830     Add({DT_VERDEF, Out<ELFT>::VerDef});
831     Add({DT_VERDEFNUM, getVerDefNum()});
832   }
833   if (HasVerNeed) {
834     Add({DT_VERNEED, Out<ELFT>::VerNeed});
835     Add({DT_VERNEEDNUM, Out<ELFT>::VerNeed->getNeedNum()});
836   }
837 
838   if (Config->EMachine == EM_MIPS) {
839     Add({DT_MIPS_RLD_VERSION, 1});
840     Add({DT_MIPS_FLAGS, RHF_NOTPOT});
841     Add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
842     Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
843     Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
844     if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
845       Add({DT_MIPS_GOTSYM, B->DynsymIndex});
846     else
847       Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
848     Add({DT_PLTGOT, Out<ELFT>::Got});
849     if (Out<ELFT>::MipsRldMap)
850       Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
851   }
852 
853   // +1 for DT_NULL
854   Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
855 }
856 
857 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
858   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
859 
860   for (const Entry &E : Entries) {
861     P->d_tag = E.Tag;
862     switch (E.Kind) {
863     case Entry::SecAddr:
864       P->d_un.d_ptr = E.OutSec->getVA();
865       break;
866     case Entry::SecSize:
867       P->d_un.d_val = E.OutSec->getSize();
868       break;
869     case Entry::SymAddr:
870       P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
871       break;
872     case Entry::PlainInt:
873       P->d_un.d_val = E.Val;
874       break;
875     }
876     ++P;
877   }
878 }
879 
880 template <class ELFT>
881 EhFrameHeader<ELFT>::EhFrameHeader()
882     : OutputSectionBase<ELFT>(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
883 
884 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
885 // Each entry of the search table consists of two values,
886 // the starting PC from where FDEs covers, and the FDE's address.
887 // It is sorted by PC.
888 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
889   const endianness E = ELFT::TargetEndianness;
890 
891   // Sort the FDE list by their PC and uniqueify. Usually there is only
892   // one FDE for a PC (i.e. function), but if ICF merges two functions
893   // into one, there can be more than one FDEs pointing to the address.
894   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
895   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
896   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
897   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
898 
899   Buf[0] = 1;
900   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
901   Buf[2] = DW_EH_PE_udata4;
902   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
903   write32<E>(Buf + 4, Out<ELFT>::EhFrame->getVA() - this->getVA() - 4);
904   write32<E>(Buf + 8, Fdes.size());
905   Buf += 12;
906 
907   uintX_t VA = this->getVA();
908   for (FdeData &Fde : Fdes) {
909     write32<E>(Buf, Fde.Pc - VA);
910     write32<E>(Buf + 4, Fde.FdeVA - VA);
911     Buf += 8;
912   }
913 }
914 
915 template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
916   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
917   this->Header.sh_size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
918 }
919 
920 template <class ELFT>
921 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
922   Fdes.push_back({Pc, FdeVA});
923 }
924 
925 template <class ELFT>
926 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
927     : OutputSectionBase<ELFT>(Name, Type, Flags) {
928   if (Type == SHT_RELA)
929     this->Header.sh_entsize = sizeof(Elf_Rela);
930   else if (Type == SHT_REL)
931     this->Header.sh_entsize = sizeof(Elf_Rel);
932 }
933 
934 template <class ELFT> void OutputSection<ELFT>::finalize() {
935   uint32_t Type = this->Header.sh_type;
936   if (this->Header.sh_flags & SHF_LINK_ORDER) {
937     if (!Config->Relocatable) {
938       // SHF_LINK_ORDER only has meaning in relocatable objects
939       this->Header.sh_flags &= ~SHF_LINK_ORDER;
940     }
941     else if (!this->Sections.empty()) {
942       // When doing a relocatable link we must preserve the link order
943       // dependency of sections with the SHF_LINK_ORDER flag. The dependency
944       // is indicated by the sh_link field. We need to translate the
945       // InputSection sh_link to the OutputSection sh_link, all InputSections
946       // in the OutputSection have the same dependency.
947       if (auto *D = this->Sections.front()->getLinkOrderDep())
948         this->Header.sh_link = D->OutSec->SectionIndex;
949     }
950   }
951   if (Type != SHT_RELA && Type != SHT_REL)
952     return;
953   this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
954   // sh_info for SHT_REL[A] sections should contain the section header index of
955   // the section to which the relocation applies.
956   InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
957   this->Header.sh_info = S->OutSec->SectionIndex;
958 }
959 
960 template <class ELFT>
961 void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
962   assert(C->Live);
963   auto *S = cast<InputSection<ELFT>>(C);
964   Sections.push_back(S);
965   S->OutSec = this;
966   this->updateAlignment(S->Alignment);
967   // Keep sh_entsize value of the input section to be able to perform merging
968   // later during a final linking using the generated relocatable object.
969   if (Config->Relocatable && (S->getSectionHdr()->sh_flags & SHF_MERGE))
970     this->Header.sh_entsize = S->getSectionHdr()->sh_entsize;
971 }
972 
973 // This function is called after we sort input sections
974 // and scan relocations to setup sections' offsets.
975 template <class ELFT> void OutputSection<ELFT>::assignOffsets() {
976   uintX_t Off = this->Header.sh_size;
977   for (InputSection<ELFT> *S : Sections) {
978     Off = alignTo(Off, S->Alignment);
979     S->OutSecOff = Off;
980     Off += S->getSize();
981   }
982   this->Header.sh_size = Off;
983 }
984 
985 // Sorts input sections by section name suffixes, so that .foo.N comes
986 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
987 // We want to keep the original order if the priorities are the same
988 // because the compiler keeps the original initialization order in a
989 // translation unit and we need to respect that.
990 // For more detail, read the section of the GCC's manual about init_priority.
991 template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
992   // Sort sections by priority.
993   typedef std::pair<int, InputSection<ELFT> *> Pair;
994   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
995 
996   std::vector<Pair> V;
997   for (InputSection<ELFT> *S : Sections)
998     V.push_back({getPriority(S->Name), S});
999   std::stable_sort(V.begin(), V.end(), Comp);
1000   Sections.clear();
1001   for (Pair &P : V)
1002     Sections.push_back(P.second);
1003 }
1004 
1005 // Returns true if S matches /Filename.?\.o$/.
1006 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
1007   if (!S.endswith(".o"))
1008     return false;
1009   S = S.drop_back(2);
1010   if (S.endswith(Filename))
1011     return true;
1012   return !S.empty() && S.drop_back().endswith(Filename);
1013 }
1014 
1015 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
1016 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
1017 
1018 // .ctors and .dtors are sorted by this priority from highest to lowest.
1019 //
1020 //  1. The section was contained in crtbegin (crtbegin contains
1021 //     some sentinel value in its .ctors and .dtors so that the runtime
1022 //     can find the beginning of the sections.)
1023 //
1024 //  2. The section has an optional priority value in the form of ".ctors.N"
1025 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
1026 //     they are compared as string rather than number.
1027 //
1028 //  3. The section is just ".ctors" or ".dtors".
1029 //
1030 //  4. The section was contained in crtend, which contains an end marker.
1031 //
1032 // In an ideal world, we don't need this function because .init_array and
1033 // .ctors are duplicate features (and .init_array is newer.) However, there
1034 // are too many real-world use cases of .ctors, so we had no choice to
1035 // support that with this rather ad-hoc semantics.
1036 template <class ELFT>
1037 static bool compCtors(const InputSection<ELFT> *A,
1038                       const InputSection<ELFT> *B) {
1039   bool BeginA = isCrtbegin(A->getFile()->getName());
1040   bool BeginB = isCrtbegin(B->getFile()->getName());
1041   if (BeginA != BeginB)
1042     return BeginA;
1043   bool EndA = isCrtend(A->getFile()->getName());
1044   bool EndB = isCrtend(B->getFile()->getName());
1045   if (EndA != EndB)
1046     return EndB;
1047   StringRef X = A->Name;
1048   StringRef Y = B->Name;
1049   assert(X.startswith(".ctors") || X.startswith(".dtors"));
1050   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
1051   X = X.substr(6);
1052   Y = Y.substr(6);
1053   if (X.empty() && Y.empty())
1054     return false;
1055   return X < Y;
1056 }
1057 
1058 // Sorts input sections by the special rules for .ctors and .dtors.
1059 // Unfortunately, the rules are different from the one for .{init,fini}_array.
1060 // Read the comment above.
1061 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
1062   std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
1063 }
1064 
1065 static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
1066   size_t I = 0;
1067   for (; I + A.size() < Size; I += A.size())
1068     memcpy(Buf + I, A.data(), A.size());
1069   memcpy(Buf + I, A.data(), Size - I);
1070 }
1071 
1072 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
1073   ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
1074   if (!Filler.empty())
1075     fill(Buf, this->getSize(), Filler);
1076   if (Config->Threads) {
1077     parallel_for_each(Sections.begin(), Sections.end(),
1078                       [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
1079   } else {
1080     for (InputSection<ELFT> *C : Sections)
1081       C->writeTo(Buf);
1082   }
1083   // Linker scripts may have BYTE()-family commands with which you
1084   // can write arbitrary bytes to the output. Process them if any.
1085   Script<ELFT>::X->writeDataBytes(this->Name, Buf);
1086 }
1087 
1088 template <class ELFT>
1089 EhOutputSection<ELFT>::EhOutputSection()
1090     : OutputSectionBase<ELFT>(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
1091 
1092 // Search for an existing CIE record or create a new one.
1093 // CIE records from input object files are uniquified by their contents
1094 // and where their relocations point to.
1095 template <class ELFT>
1096 template <class RelTy>
1097 CieRecord *EhOutputSection<ELFT>::addCie(EhSectionPiece &Piece,
1098                                          EhInputSection<ELFT> *Sec,
1099                                          ArrayRef<RelTy> Rels) {
1100   const endianness E = ELFT::TargetEndianness;
1101   if (read32<E>(Piece.data().data() + 4) != 0)
1102     fatal("CIE expected at beginning of .eh_frame: " + Sec->Name);
1103 
1104   SymbolBody *Personality = nullptr;
1105   unsigned FirstRelI = Piece.FirstRelocation;
1106   if (FirstRelI != (unsigned)-1)
1107     Personality = &Sec->getFile()->getRelocTargetSym(Rels[FirstRelI]);
1108 
1109   // Search for an existing CIE by CIE contents/relocation target pair.
1110   CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
1111 
1112   // If not found, create a new one.
1113   if (Cie->Piece == nullptr) {
1114     Cie->Piece = &Piece;
1115     Cies.push_back(Cie);
1116   }
1117   return Cie;
1118 }
1119 
1120 // There is one FDE per function. Returns true if a given FDE
1121 // points to a live function.
1122 template <class ELFT>
1123 template <class RelTy>
1124 bool EhOutputSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
1125                                       EhInputSection<ELFT> *Sec,
1126                                       ArrayRef<RelTy> Rels) {
1127   unsigned FirstRelI = Piece.FirstRelocation;
1128   if (FirstRelI == (unsigned)-1)
1129     fatal("FDE doesn't reference another section");
1130   const RelTy &Rel = Rels[FirstRelI];
1131   SymbolBody &B = Sec->getFile()->getRelocTargetSym(Rel);
1132   auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
1133   if (!D || !D->Section)
1134     return false;
1135   InputSectionBase<ELFT> *Target = D->Section->Repl;
1136   return Target && Target->Live;
1137 }
1138 
1139 // .eh_frame is a sequence of CIE or FDE records. In general, there
1140 // is one CIE record per input object file which is followed by
1141 // a list of FDEs. This function searches an existing CIE or create a new
1142 // one and associates FDEs to the CIE.
1143 template <class ELFT>
1144 template <class RelTy>
1145 void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
1146                                           ArrayRef<RelTy> Rels) {
1147   const endianness E = ELFT::TargetEndianness;
1148 
1149   DenseMap<size_t, CieRecord *> OffsetToCie;
1150   for (EhSectionPiece &Piece : Sec->Pieces) {
1151     // The empty record is the end marker.
1152     if (Piece.size() == 4)
1153       return;
1154 
1155     size_t Offset = Piece.InputOff;
1156     uint32_t ID = read32<E>(Piece.data().data() + 4);
1157     if (ID == 0) {
1158       OffsetToCie[Offset] = addCie(Piece, Sec, Rels);
1159       continue;
1160     }
1161 
1162     uint32_t CieOffset = Offset + 4 - ID;
1163     CieRecord *Cie = OffsetToCie[CieOffset];
1164     if (!Cie)
1165       fatal("invalid CIE reference");
1166 
1167     if (!isFdeLive(Piece, Sec, Rels))
1168       continue;
1169     Cie->FdePieces.push_back(&Piece);
1170     NumFdes++;
1171   }
1172 }
1173 
1174 template <class ELFT>
1175 void EhOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1176   auto *Sec = cast<EhInputSection<ELFT>>(C);
1177   Sec->OutSec = this;
1178   this->updateAlignment(Sec->Alignment);
1179   Sections.push_back(Sec);
1180 
1181   // .eh_frame is a sequence of CIE or FDE records. This function
1182   // splits it into pieces so that we can call
1183   // SplitInputSection::getSectionPiece on the section.
1184   Sec->split();
1185   if (Sec->Pieces.empty())
1186     return;
1187 
1188   if (const Elf_Shdr *RelSec = Sec->RelocSection) {
1189     ELFFile<ELFT> &Obj = Sec->getFile()->getObj();
1190     if (RelSec->sh_type == SHT_RELA)
1191       addSectionAux(Sec, Obj.relas(RelSec));
1192     else
1193       addSectionAux(Sec, Obj.rels(RelSec));
1194     return;
1195   }
1196   addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
1197 }
1198 
1199 template <class ELFT>
1200 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1201   memcpy(Buf, D.data(), D.size());
1202 
1203   // Fix the size field. -4 since size does not include the size field itself.
1204   const endianness E = ELFT::TargetEndianness;
1205   write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
1206 }
1207 
1208 template <class ELFT> void EhOutputSection<ELFT>::finalize() {
1209   if (this->Header.sh_size)
1210     return; // Already finalized.
1211 
1212   size_t Off = 0;
1213   for (CieRecord *Cie : Cies) {
1214     Cie->Piece->OutputOff = Off;
1215     Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
1216 
1217     for (EhSectionPiece *Fde : Cie->FdePieces) {
1218       Fde->OutputOff = Off;
1219       Off += alignTo(Fde->size(), sizeof(uintX_t));
1220     }
1221   }
1222   this->Header.sh_size = Off;
1223 }
1224 
1225 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1226   const endianness E = ELFT::TargetEndianness;
1227   switch (Size) {
1228   case DW_EH_PE_udata2:
1229     return read16<E>(Buf);
1230   case DW_EH_PE_udata4:
1231     return read32<E>(Buf);
1232   case DW_EH_PE_udata8:
1233     return read64<E>(Buf);
1234   case DW_EH_PE_absptr:
1235     if (ELFT::Is64Bits)
1236       return read64<E>(Buf);
1237     return read32<E>(Buf);
1238   }
1239   fatal("unknown FDE size encoding");
1240 }
1241 
1242 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1243 // We need it to create .eh_frame_hdr section.
1244 template <class ELFT>
1245 typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
1246                                                     uint8_t Enc) {
1247   // The starting address to which this FDE applies is
1248   // stored at FDE + 8 byte.
1249   size_t Off = FdeOff + 8;
1250   uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1251   if ((Enc & 0x70) == DW_EH_PE_absptr)
1252     return Addr;
1253   if ((Enc & 0x70) == DW_EH_PE_pcrel)
1254     return Addr + this->getVA() + Off;
1255   fatal("unknown FDE size relative encoding");
1256 }
1257 
1258 template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1259   const endianness E = ELFT::TargetEndianness;
1260   for (CieRecord *Cie : Cies) {
1261     size_t CieOffset = Cie->Piece->OutputOff;
1262     writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
1263 
1264     for (EhSectionPiece *Fde : Cie->FdePieces) {
1265       size_t Off = Fde->OutputOff;
1266       writeCieFde<ELFT>(Buf + Off, Fde->data());
1267 
1268       // FDE's second word should have the offset to an associated CIE.
1269       // Write it.
1270       write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
1271     }
1272   }
1273 
1274   for (EhInputSection<ELFT> *S : Sections)
1275     S->relocate(Buf, nullptr);
1276 
1277   // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
1278   // to get a FDE from an address to which FDE is applied. So here
1279   // we obtain two addresses and pass them to EhFrameHdr object.
1280   if (Out<ELFT>::EhFrameHdr) {
1281     for (CieRecord *Cie : Cies) {
1282       uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->data());
1283       for (SectionPiece *Fde : Cie->FdePieces) {
1284         uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
1285         uintX_t FdeVA = this->getVA() + Fde->OutputOff;
1286         Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1287       }
1288     }
1289   }
1290 }
1291 
1292 template <class ELFT>
1293 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
1294                                              uintX_t Flags, uintX_t Alignment)
1295     : OutputSectionBase<ELFT>(Name, Type, Flags),
1296       Builder(StringTableBuilder::RAW, Alignment) {}
1297 
1298 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1299   Builder.write(Buf);
1300 }
1301 
1302 template <class ELFT>
1303 void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1304   auto *Sec = cast<MergeInputSection<ELFT>>(C);
1305   Sec->OutSec = this;
1306   this->updateAlignment(Sec->Alignment);
1307   this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize;
1308   Sections.push_back(Sec);
1309 
1310   auto HashI = Sec->Hashes.begin();
1311   for (auto I = Sec->Pieces.begin(), E = Sec->Pieces.end(); I != E; ++I) {
1312     SectionPiece &Piece = *I;
1313     uint32_t Hash = *HashI;
1314     ++HashI;
1315     if (!Piece.Live)
1316       continue;
1317     StringRef Data = toStringRef(Sec->getData(I));
1318     CachedHashStringRef V(Data, Hash);
1319     uintX_t OutputOffset = Builder.add(V);
1320     if (!shouldTailMerge())
1321       Piece.OutputOff = OutputOffset;
1322   }
1323 }
1324 
1325 template <class ELFT>
1326 unsigned MergeOutputSection<ELFT>::getOffset(CachedHashStringRef Val) {
1327   return Builder.getOffset(Val);
1328 }
1329 
1330 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1331   return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1332 }
1333 
1334 template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1335   if (shouldTailMerge())
1336     Builder.finalize();
1337   else
1338     Builder.finalizeInOrder();
1339   this->Header.sh_size = Builder.getSize();
1340 }
1341 
1342 template <class ELFT> void MergeOutputSection<ELFT>::finalizePieces() {
1343   for (MergeInputSection<ELFT> *Sec : Sections)
1344     Sec->finalizePieces();
1345 }
1346 
1347 template <class ELFT>
1348 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
1349     : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1350                               Dynamic ? (uintX_t)SHF_ALLOC : 0),
1351       Dynamic(Dynamic) {}
1352 
1353 // Adds a string to the string table. If HashIt is true we hash and check for
1354 // duplicates. It is optional because the name of global symbols are already
1355 // uniqued and hashing them again has a big cost for a small value: uniquing
1356 // them with some other string that happens to be the same.
1357 template <class ELFT>
1358 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1359   if (HashIt) {
1360     auto R = StringMap.insert(std::make_pair(S, Size));
1361     if (!R.second)
1362       return R.first->second;
1363   }
1364   unsigned Ret = Size;
1365   Size += S.size() + 1;
1366   Strings.push_back(S);
1367   return Ret;
1368 }
1369 
1370 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
1371   // ELF string tables start with NUL byte, so advance the pointer by one.
1372   ++Buf;
1373   for (StringRef S : Strings) {
1374     memcpy(Buf, S.data(), S.size());
1375     Buf += S.size() + 1;
1376   }
1377 }
1378 
1379 template <class ELFT>
1380 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
1381   if (OutputSec)
1382     return OutputSec->getVA() + OffsetInSec;
1383   return InputSec->OutSec->getVA() + InputSec->getOffset(OffsetInSec);
1384 }
1385 
1386 template <class ELFT>
1387 typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
1388   if (UseSymVA)
1389     return Sym->getVA<ELFT>(Addend);
1390   return Addend;
1391 }
1392 
1393 template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
1394   if (Sym && !UseSymVA)
1395     return Sym->DynsymIndex;
1396   return 0;
1397 }
1398 
1399 template <class ELFT>
1400 SymbolTableSection<ELFT>::SymbolTableSection(
1401     StringTableSection<ELFT> &StrTabSec)
1402     : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1403                               StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1404                               StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
1405       StrTabSec(StrTabSec) {
1406   this->Header.sh_entsize = sizeof(Elf_Sym);
1407   this->Header.sh_addralign = sizeof(uintX_t);
1408 }
1409 
1410 // Orders symbols according to their positions in the GOT,
1411 // in compliance with MIPS ABI rules.
1412 // See "Global Offset Table" in Chapter 5 in the following document
1413 // for detailed description:
1414 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1415 static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
1416   // Sort entries related to non-local preemptible symbols by GOT indexes.
1417   // All other entries go to the first part of GOT in arbitrary order.
1418   bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1419   bool RIsInLocalGot = !R->IsInGlobalMipsGot;
1420   if (LIsInLocalGot || RIsInLocalGot)
1421     return !RIsInLocalGot;
1422   return L->GotIndex < R->GotIndex;
1423 }
1424 
1425 static uint8_t getSymbolBinding(SymbolBody *Body) {
1426   Symbol *S = Body->symbol();
1427   if (Config->Relocatable)
1428     return S->Binding;
1429   uint8_t Visibility = S->Visibility;
1430   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1431     return STB_LOCAL;
1432   if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
1433     return STB_GLOBAL;
1434   return S->Binding;
1435 }
1436 
1437 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1438   if (this->Header.sh_size)
1439     return; // Already finalized.
1440 
1441   this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
1442   this->Header.sh_link = StrTabSec.SectionIndex;
1443   this->Header.sh_info = NumLocals + 1;
1444 
1445   if (Config->Relocatable) {
1446     size_t I = NumLocals;
1447     for (const SymbolTableEntry &S : Symbols)
1448       S.Symbol->DynsymIndex = ++I;
1449     return;
1450   }
1451 
1452   if (!StrTabSec.isDynamic()) {
1453     std::stable_sort(Symbols.begin(), Symbols.end(),
1454                      [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1455                        return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1456                               getSymbolBinding(R.Symbol) != STB_LOCAL;
1457                      });
1458     return;
1459   }
1460   if (Out<ELFT>::GnuHashTab)
1461     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1462     Out<ELFT>::GnuHashTab->addSymbols(Symbols);
1463   else if (Config->EMachine == EM_MIPS)
1464     std::stable_sort(Symbols.begin(), Symbols.end(),
1465                      [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1466                        return sortMipsSymbols(L.Symbol, R.Symbol);
1467                      });
1468   size_t I = 0;
1469   for (const SymbolTableEntry &S : Symbols)
1470     S.Symbol->DynsymIndex = ++I;
1471 }
1472 
1473 template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1474   Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1475 }
1476 
1477 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1478   Buf += sizeof(Elf_Sym);
1479 
1480   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1481   // .dynsym only contains global symbols.
1482   if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1483     writeLocalSymbols(Buf);
1484 
1485   writeGlobalSymbols(Buf);
1486 }
1487 
1488 template <class ELFT>
1489 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1490   // Iterate over all input object files to copy their local symbols
1491   // to the output symbol table pointed by Buf.
1492   for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
1493     for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1494          File->KeptLocalSyms) {
1495       const DefinedRegular<ELFT> &Body = *P.first;
1496       InputSectionBase<ELFT> *Section = Body.Section;
1497       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1498 
1499       if (!Section) {
1500         ESym->st_shndx = SHN_ABS;
1501         ESym->st_value = Body.Value;
1502       } else {
1503         const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1504         ESym->st_shndx = OutSec->SectionIndex;
1505         ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
1506       }
1507       ESym->st_name = P.second;
1508       ESym->st_size = Body.template getSize<ELFT>();
1509       ESym->setBindingAndType(STB_LOCAL, Body.Type);
1510       Buf += sizeof(*ESym);
1511     }
1512   }
1513 }
1514 
1515 template <class ELFT>
1516 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1517   // Write the internal symbol table contents to the output symbol table
1518   // pointed by Buf.
1519   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1520   for (const SymbolTableEntry &S : Symbols) {
1521     SymbolBody *Body = S.Symbol;
1522     size_t StrOff = S.StrTabOffset;
1523 
1524     uint8_t Type = Body->Type;
1525     uintX_t Size = Body->getSize<ELFT>();
1526 
1527     ESym->setBindingAndType(getSymbolBinding(Body), Type);
1528     ESym->st_size = Size;
1529     ESym->st_name = StrOff;
1530     ESym->setVisibility(Body->symbol()->Visibility);
1531     ESym->st_value = Body->getVA<ELFT>();
1532 
1533     if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
1534       ESym->st_shndx = OutSec->SectionIndex;
1535     else if (isa<DefinedRegular<ELFT>>(Body))
1536       ESym->st_shndx = SHN_ABS;
1537 
1538     if (Config->EMachine == EM_MIPS) {
1539       // On MIPS we need to mark symbol which has a PLT entry and requires
1540       // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1541       // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1542       // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1543       if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1544         ESym->st_other |= STO_MIPS_PLT;
1545       if (Config->Relocatable) {
1546         auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1547         if (D && D->isMipsPIC())
1548           ESym->st_other |= STO_MIPS_PIC;
1549       }
1550     }
1551     ++ESym;
1552   }
1553 }
1554 
1555 template <class ELFT>
1556 const OutputSectionBase<ELFT> *
1557 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1558   switch (Sym->kind()) {
1559   case SymbolBody::DefinedSyntheticKind:
1560     return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1561   case SymbolBody::DefinedRegularKind: {
1562     auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1563     if (D.Section)
1564       return D.Section->OutSec;
1565     break;
1566   }
1567   case SymbolBody::DefinedCommonKind:
1568     return CommonInputSection<ELFT>::X->OutSec;
1569   case SymbolBody::SharedKind:
1570     if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1571       return Out<ELFT>::Bss;
1572     break;
1573   case SymbolBody::UndefinedKind:
1574   case SymbolBody::LazyArchiveKind:
1575   case SymbolBody::LazyObjectKind:
1576     break;
1577   }
1578   return nullptr;
1579 }
1580 
1581 template <class ELFT>
1582 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1583     : OutputSectionBase<ELFT>(".gnu.version_d", SHT_GNU_verdef, SHF_ALLOC) {
1584   this->Header.sh_addralign = sizeof(uint32_t);
1585 }
1586 
1587 static StringRef getFileDefName() {
1588   if (!Config->SoName.empty())
1589     return Config->SoName;
1590   return Config->OutputFile;
1591 }
1592 
1593 template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1594   FileDefNameOff = Out<ELFT>::DynStrTab->addString(getFileDefName());
1595   for (VersionDefinition &V : Config->VersionDefinitions)
1596     V.NameOff = Out<ELFT>::DynStrTab->addString(V.Name);
1597 
1598   this->Header.sh_size =
1599       (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1600   this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1601 
1602   // sh_info should be set to the number of definitions. This fact is missed in
1603   // documentation, but confirmed by binutils community:
1604   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1605   this->Header.sh_info = getVerDefNum();
1606 }
1607 
1608 template <class ELFT>
1609 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1610                                               StringRef Name, size_t NameOff) {
1611   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1612   Verdef->vd_version = 1;
1613   Verdef->vd_cnt = 1;
1614   Verdef->vd_aux = sizeof(Elf_Verdef);
1615   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1616   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1617   Verdef->vd_ndx = Index;
1618   Verdef->vd_hash = hashSysv(Name);
1619 
1620   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1621   Verdaux->vda_name = NameOff;
1622   Verdaux->vda_next = 0;
1623 }
1624 
1625 template <class ELFT>
1626 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1627   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1628 
1629   for (VersionDefinition &V : Config->VersionDefinitions) {
1630     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1631     writeOne(Buf, V.Id, V.Name, V.NameOff);
1632   }
1633 
1634   // Need to terminate the last version definition.
1635   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1636   Verdef->vd_next = 0;
1637 }
1638 
1639 template <class ELFT>
1640 VersionTableSection<ELFT>::VersionTableSection()
1641     : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
1642   this->Header.sh_addralign = sizeof(uint16_t);
1643 }
1644 
1645 template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1646   this->Header.sh_size =
1647       sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
1648   this->Header.sh_entsize = sizeof(Elf_Versym);
1649   // At the moment of june 2016 GNU docs does not mention that sh_link field
1650   // should be set, but Sun docs do. Also readelf relies on this field.
1651   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
1652 }
1653 
1654 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1655   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1656   for (const SymbolTableEntry &S : Out<ELFT>::DynSymTab->getSymbols()) {
1657     OutVersym->vs_index = S.Symbol->symbol()->VersionId;
1658     ++OutVersym;
1659   }
1660 }
1661 
1662 template <class ELFT>
1663 VersionNeedSection<ELFT>::VersionNeedSection()
1664     : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
1665   this->Header.sh_addralign = sizeof(uint32_t);
1666 
1667   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1668   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1669   // First identifiers are reserved by verdef section if it exist.
1670   NextIndex = getVerDefNum() + 1;
1671 }
1672 
1673 template <class ELFT>
1674 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1675   if (!SS->Verdef) {
1676     SS->symbol()->VersionId = VER_NDX_GLOBAL;
1677     return;
1678   }
1679   SharedFile<ELFT> *F = SS->file();
1680   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1681   // to create one by adding it to our needed list and creating a dynstr entry
1682   // for the soname.
1683   if (F->VerdefMap.empty())
1684     Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1685   typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1686   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1687   // prepare to create one by allocating a version identifier and creating a
1688   // dynstr entry for the version name.
1689   if (NV.Index == 0) {
1690     NV.StrTab = Out<ELFT>::DynStrTab->addString(
1691         SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1692     NV.Index = NextIndex++;
1693   }
1694   SS->symbol()->VersionId = NV.Index;
1695 }
1696 
1697 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1698   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1699   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1700   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1701 
1702   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1703     // Create an Elf_Verneed for this DSO.
1704     Verneed->vn_version = 1;
1705     Verneed->vn_cnt = P.first->VerdefMap.size();
1706     Verneed->vn_file = P.second;
1707     Verneed->vn_aux =
1708         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1709     Verneed->vn_next = sizeof(Elf_Verneed);
1710     ++Verneed;
1711 
1712     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1713     // VerdefMap, which will only contain references to needed version
1714     // definitions. Each Elf_Vernaux is based on the information contained in
1715     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1716     // pointers, but is deterministic because the pointers refer to Elf_Verdef
1717     // data structures within a single input file.
1718     for (auto &NV : P.first->VerdefMap) {
1719       Vernaux->vna_hash = NV.first->vd_hash;
1720       Vernaux->vna_flags = 0;
1721       Vernaux->vna_other = NV.second.Index;
1722       Vernaux->vna_name = NV.second.StrTab;
1723       Vernaux->vna_next = sizeof(Elf_Vernaux);
1724       ++Vernaux;
1725     }
1726 
1727     Vernaux[-1].vna_next = 0;
1728   }
1729   Verneed[-1].vn_next = 0;
1730 }
1731 
1732 template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1733   this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1734   this->Header.sh_info = Needed.size();
1735   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1736   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1737     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1738   this->Header.sh_size = Size;
1739 }
1740 
1741 template <class ELFT>
1742 BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1743     : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1744       HashSize(HashSize) {
1745   // 16 bytes for the note section header.
1746   this->Header.sh_size = 16 + HashSize;
1747 }
1748 
1749 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1750   const endianness E = ELFT::TargetEndianness;
1751   write32<E>(Buf, 4);                   // Name size
1752   write32<E>(Buf + 4, HashSize);        // Content size
1753   write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1754   memcpy(Buf + 12, "GNU", 4);           // Name string
1755   HashBuf = Buf + 16;
1756 }
1757 
1758 template <class ELFT>
1759 void BuildIdFastHash<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
1760   const endianness E = ELFT::TargetEndianness;
1761 
1762   // 64-bit xxhash
1763   uint64_t Hash = xxHash64(toStringRef(Buf));
1764   write64<E>(this->HashBuf, Hash);
1765 }
1766 
1767 template <class ELFT>
1768 void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
1769   MD5 Hash;
1770   Hash.update(Buf);
1771   MD5::MD5Result Res;
1772   Hash.final(Res);
1773   memcpy(this->HashBuf, Res, 16);
1774 }
1775 
1776 template <class ELFT>
1777 void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
1778   SHA1 Hash;
1779   Hash.update(Buf);
1780   memcpy(this->HashBuf, Hash.final().data(), 20);
1781 }
1782 
1783 template <class ELFT>
1784 void BuildIdUuid<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
1785   if (getRandomBytes(this->HashBuf, 16))
1786     error("entropy source failure");
1787 }
1788 
1789 template <class ELFT>
1790 BuildIdHexstring<ELFT>::BuildIdHexstring()
1791     : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
1792 
1793 template <class ELFT>
1794 void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
1795   memcpy(this->HashBuf, Config->BuildIdVector.data(),
1796          Config->BuildIdVector.size());
1797 }
1798 
1799 template <class ELFT>
1800 MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1801     : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1802   this->Header.sh_addralign = 4;
1803   this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1804   this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1805 }
1806 
1807 template <class ELFT>
1808 void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1809   auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1810   if (Config->Relocatable)
1811     R->ri_gp_value = 0;
1812   else
1813     R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1814   R->ri_gprmask = GprMask;
1815 }
1816 
1817 template <class ELFT>
1818 void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1819   // Copy input object file's .reginfo gprmask to output.
1820   auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
1821   GprMask |= S->Reginfo->ri_gprmask;
1822   S->OutSec = this;
1823 }
1824 
1825 template <class ELFT>
1826 MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection()
1827     : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS,
1828                               SHF_ALLOC | SHF_MIPS_NOSTRIP) {
1829   this->Header.sh_addralign = 8;
1830   this->Header.sh_entsize = 1;
1831   this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1832 }
1833 
1834 template <class ELFT>
1835 void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1836   auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf);
1837   Opt->kind = ODK_REGINFO;
1838   Opt->size = this->Header.sh_size;
1839   Opt->section = 0;
1840   Opt->info = 0;
1841   auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt));
1842   if (Config->Relocatable)
1843     Reg->ri_gp_value = 0;
1844   else
1845     Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1846   Reg->ri_gprmask = GprMask;
1847 }
1848 
1849 template <class ELFT>
1850 void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1851   auto *S = cast<MipsOptionsInputSection<ELFT>>(C);
1852   if (S->Reginfo)
1853     GprMask |= S->Reginfo->ri_gprmask;
1854   S->OutSec = this;
1855 }
1856 
1857 template <class ELFT>
1858 MipsAbiFlagsOutputSection<ELFT>::MipsAbiFlagsOutputSection()
1859     : OutputSectionBase<ELFT>(".MIPS.abiflags", SHT_MIPS_ABIFLAGS, SHF_ALLOC) {
1860   this->Header.sh_addralign = 8;
1861   this->Header.sh_entsize = sizeof(Elf_Mips_ABIFlags);
1862   this->Header.sh_size = sizeof(Elf_Mips_ABIFlags);
1863   memset(&Flags, 0, sizeof(Flags));
1864 }
1865 
1866 template <class ELFT>
1867 void MipsAbiFlagsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1868   memcpy(Buf, &Flags, sizeof(Flags));
1869 }
1870 
1871 template <class ELFT>
1872 void MipsAbiFlagsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1873   // Check compatibility and merge fields from input .MIPS.abiflags
1874   // to the output one.
1875   auto *S = cast<MipsAbiFlagsInputSection<ELFT>>(C);
1876   S->OutSec = this;
1877   if (S->Flags->version != 0) {
1878     error(getFilename(S->getFile()) + ": unexpected .MIPS.abiflags version " +
1879           Twine(S->Flags->version));
1880     return;
1881   }
1882   // LLD checks ISA compatibility in getMipsEFlags(). Here we just
1883   // select the highest number of ISA/Rev/Ext.
1884   Flags.isa_level = std::max(Flags.isa_level, S->Flags->isa_level);
1885   Flags.isa_rev = std::max(Flags.isa_rev, S->Flags->isa_rev);
1886   Flags.isa_ext = std::max(Flags.isa_ext, S->Flags->isa_ext);
1887   Flags.gpr_size = std::max(Flags.gpr_size, S->Flags->gpr_size);
1888   Flags.cpr1_size = std::max(Flags.cpr1_size, S->Flags->cpr1_size);
1889   Flags.cpr2_size = std::max(Flags.cpr2_size, S->Flags->cpr2_size);
1890   Flags.ases |= S->Flags->ases;
1891   Flags.flags1 |= S->Flags->flags1;
1892   Flags.flags2 |= S->Flags->flags2;
1893   Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->Flags->fp_abi,
1894                                        getFilename(S->getFile()));
1895 }
1896 
1897 template <class ELFT>
1898 static typename ELFT::uint getOutFlags(InputSectionBase<ELFT> *S) {
1899   return S->getSectionHdr()->sh_flags & ~SHF_GROUP & ~SHF_COMPRESSED;
1900 }
1901 
1902 template <class ELFT>
1903 static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
1904                                             StringRef OutsecName) {
1905   const typename ELFT::Shdr *H = C->getSectionHdr();
1906   typedef typename ELFT::uint uintX_t;
1907   uintX_t Flags = getOutFlags(C);
1908 
1909   // For SHF_MERGE we create different output sections for each alignment.
1910   // This makes each output section simple and keeps a single level mapping from
1911   // input to output.
1912   // In case of relocatable object generation we do not try to perform merging
1913   // and treat SHF_MERGE sections as regular ones, but also create different
1914   // output sections for them to allow merging at final linking stage.
1915   uintX_t Alignment = 0;
1916   if (isa<MergeInputSection<ELFT>>(C) ||
1917       (Config->Relocatable && (H->sh_flags & SHF_MERGE)))
1918     Alignment = std::max(H->sh_addralign, H->sh_entsize);
1919 
1920   uint32_t Type = H->sh_type;
1921   return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
1922 }
1923 
1924 template <class ELFT>
1925 std::pair<OutputSectionBase<ELFT> *, bool>
1926 OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
1927                                    StringRef OutsecName) {
1928   SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
1929   return create(Key, C);
1930 }
1931 
1932 template <class ELFT>
1933 std::pair<OutputSectionBase<ELFT> *, bool>
1934 OutputSectionFactory<ELFT>::create(const SectionKey<ELFT::Is64Bits> &Key,
1935                                    InputSectionBase<ELFT> *C) {
1936   uintX_t Flags = getOutFlags(C);
1937   OutputSectionBase<ELFT> *&Sec = Map[Key];
1938   if (Sec) {
1939     Sec->updateFlags(Flags);
1940     return {Sec, false};
1941   }
1942 
1943   uint32_t Type = C->getSectionHdr()->sh_type;
1944   switch (C->kind()) {
1945   case InputSectionBase<ELFT>::Regular:
1946     Sec = new OutputSection<ELFT>(Key.Name, Type, Flags);
1947     break;
1948   case InputSectionBase<ELFT>::EHFrame:
1949     return {Out<ELFT>::EhFrame, false};
1950   case InputSectionBase<ELFT>::Merge:
1951     Sec = new MergeOutputSection<ELFT>(Key.Name, Type, Flags, Key.Alignment);
1952     break;
1953   case InputSectionBase<ELFT>::MipsReginfo:
1954     Sec = new MipsReginfoOutputSection<ELFT>();
1955     break;
1956   case InputSectionBase<ELFT>::MipsOptions:
1957     Sec = new MipsOptionsOutputSection<ELFT>();
1958     break;
1959   case InputSectionBase<ELFT>::MipsAbiFlags:
1960     Sec = new MipsAbiFlagsOutputSection<ELFT>();
1961     break;
1962   }
1963   Out<ELFT>::Pool.emplace_back(Sec);
1964   return {Sec, true};
1965 }
1966 
1967 template <bool Is64Bits>
1968 typename lld::elf::SectionKey<Is64Bits>
1969 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getEmptyKey() {
1970   return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 0};
1971 }
1972 
1973 template <bool Is64Bits>
1974 typename lld::elf::SectionKey<Is64Bits>
1975 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getTombstoneKey() {
1976   return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0,
1977                               0};
1978 }
1979 
1980 template <bool Is64Bits>
1981 unsigned
1982 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getHashValue(const Key &Val) {
1983   return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
1984 }
1985 
1986 template <bool Is64Bits>
1987 bool DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::isEqual(const Key &LHS,
1988                                                            const Key &RHS) {
1989   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
1990          LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
1991          LHS.Alignment == RHS.Alignment;
1992 }
1993 
1994 namespace llvm {
1995 template struct DenseMapInfo<SectionKey<true>>;
1996 template struct DenseMapInfo<SectionKey<false>>;
1997 }
1998 
1999 namespace lld {
2000 namespace elf {
2001 template class OutputSectionBase<ELF32LE>;
2002 template class OutputSectionBase<ELF32BE>;
2003 template class OutputSectionBase<ELF64LE>;
2004 template class OutputSectionBase<ELF64BE>;
2005 
2006 template class EhFrameHeader<ELF32LE>;
2007 template class EhFrameHeader<ELF32BE>;
2008 template class EhFrameHeader<ELF64LE>;
2009 template class EhFrameHeader<ELF64BE>;
2010 
2011 template class GotPltSection<ELF32LE>;
2012 template class GotPltSection<ELF32BE>;
2013 template class GotPltSection<ELF64LE>;
2014 template class GotPltSection<ELF64BE>;
2015 
2016 template class GotSection<ELF32LE>;
2017 template class GotSection<ELF32BE>;
2018 template class GotSection<ELF64LE>;
2019 template class GotSection<ELF64BE>;
2020 
2021 template class PltSection<ELF32LE>;
2022 template class PltSection<ELF32BE>;
2023 template class PltSection<ELF64LE>;
2024 template class PltSection<ELF64BE>;
2025 
2026 template class RelocationSection<ELF32LE>;
2027 template class RelocationSection<ELF32BE>;
2028 template class RelocationSection<ELF64LE>;
2029 template class RelocationSection<ELF64BE>;
2030 
2031 template class InterpSection<ELF32LE>;
2032 template class InterpSection<ELF32BE>;
2033 template class InterpSection<ELF64LE>;
2034 template class InterpSection<ELF64BE>;
2035 
2036 template class GnuHashTableSection<ELF32LE>;
2037 template class GnuHashTableSection<ELF32BE>;
2038 template class GnuHashTableSection<ELF64LE>;
2039 template class GnuHashTableSection<ELF64BE>;
2040 
2041 template class HashTableSection<ELF32LE>;
2042 template class HashTableSection<ELF32BE>;
2043 template class HashTableSection<ELF64LE>;
2044 template class HashTableSection<ELF64BE>;
2045 
2046 template class DynamicSection<ELF32LE>;
2047 template class DynamicSection<ELF32BE>;
2048 template class DynamicSection<ELF64LE>;
2049 template class DynamicSection<ELF64BE>;
2050 
2051 template class OutputSection<ELF32LE>;
2052 template class OutputSection<ELF32BE>;
2053 template class OutputSection<ELF64LE>;
2054 template class OutputSection<ELF64BE>;
2055 
2056 template class EhOutputSection<ELF32LE>;
2057 template class EhOutputSection<ELF32BE>;
2058 template class EhOutputSection<ELF64LE>;
2059 template class EhOutputSection<ELF64BE>;
2060 
2061 template class MipsReginfoOutputSection<ELF32LE>;
2062 template class MipsReginfoOutputSection<ELF32BE>;
2063 template class MipsReginfoOutputSection<ELF64LE>;
2064 template class MipsReginfoOutputSection<ELF64BE>;
2065 
2066 template class MipsOptionsOutputSection<ELF32LE>;
2067 template class MipsOptionsOutputSection<ELF32BE>;
2068 template class MipsOptionsOutputSection<ELF64LE>;
2069 template class MipsOptionsOutputSection<ELF64BE>;
2070 
2071 template class MipsAbiFlagsOutputSection<ELF32LE>;
2072 template class MipsAbiFlagsOutputSection<ELF32BE>;
2073 template class MipsAbiFlagsOutputSection<ELF64LE>;
2074 template class MipsAbiFlagsOutputSection<ELF64BE>;
2075 
2076 template class MergeOutputSection<ELF32LE>;
2077 template class MergeOutputSection<ELF32BE>;
2078 template class MergeOutputSection<ELF64LE>;
2079 template class MergeOutputSection<ELF64BE>;
2080 
2081 template class StringTableSection<ELF32LE>;
2082 template class StringTableSection<ELF32BE>;
2083 template class StringTableSection<ELF64LE>;
2084 template class StringTableSection<ELF64BE>;
2085 
2086 template class SymbolTableSection<ELF32LE>;
2087 template class SymbolTableSection<ELF32BE>;
2088 template class SymbolTableSection<ELF64LE>;
2089 template class SymbolTableSection<ELF64BE>;
2090 
2091 template class VersionTableSection<ELF32LE>;
2092 template class VersionTableSection<ELF32BE>;
2093 template class VersionTableSection<ELF64LE>;
2094 template class VersionTableSection<ELF64BE>;
2095 
2096 template class VersionNeedSection<ELF32LE>;
2097 template class VersionNeedSection<ELF32BE>;
2098 template class VersionNeedSection<ELF64LE>;
2099 template class VersionNeedSection<ELF64BE>;
2100 
2101 template class VersionDefinitionSection<ELF32LE>;
2102 template class VersionDefinitionSection<ELF32BE>;
2103 template class VersionDefinitionSection<ELF64LE>;
2104 template class VersionDefinitionSection<ELF64BE>;
2105 
2106 template class BuildIdSection<ELF32LE>;
2107 template class BuildIdSection<ELF32BE>;
2108 template class BuildIdSection<ELF64LE>;
2109 template class BuildIdSection<ELF64BE>;
2110 
2111 template class BuildIdFastHash<ELF32LE>;
2112 template class BuildIdFastHash<ELF32BE>;
2113 template class BuildIdFastHash<ELF64LE>;
2114 template class BuildIdFastHash<ELF64BE>;
2115 
2116 template class BuildIdMd5<ELF32LE>;
2117 template class BuildIdMd5<ELF32BE>;
2118 template class BuildIdMd5<ELF64LE>;
2119 template class BuildIdMd5<ELF64BE>;
2120 
2121 template class BuildIdSha1<ELF32LE>;
2122 template class BuildIdSha1<ELF32BE>;
2123 template class BuildIdSha1<ELF64LE>;
2124 template class BuildIdSha1<ELF64BE>;
2125 
2126 template class BuildIdUuid<ELF32LE>;
2127 template class BuildIdUuid<ELF32BE>;
2128 template class BuildIdUuid<ELF64LE>;
2129 template class BuildIdUuid<ELF64BE>;
2130 
2131 template class BuildIdHexstring<ELF32LE>;
2132 template class BuildIdHexstring<ELF32BE>;
2133 template class BuildIdHexstring<ELF64LE>;
2134 template class BuildIdHexstring<ELF64BE>;
2135 
2136 template class GdbIndexSection<ELF32LE>;
2137 template class GdbIndexSection<ELF32BE>;
2138 template class GdbIndexSection<ELF64LE>;
2139 template class GdbIndexSection<ELF64BE>;
2140 
2141 template class OutputSectionFactory<ELF32LE>;
2142 template class OutputSectionFactory<ELF32BE>;
2143 template class OutputSectionFactory<ELF64LE>;
2144 template class OutputSectionFactory<ELF64BE>;
2145 }
2146 }
2147