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