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 "LinkerScript.h"
13 #include "SymbolTable.h"
14 #include "Target.h"
15 #include "lld/Core/Parallel.h"
16 #include "llvm/Support/Dwarf.h"
17 #include "llvm/Support/MathExtras.h"
18 #include <map>
19 
20 using namespace llvm;
21 using namespace llvm::dwarf;
22 using namespace llvm::object;
23 using namespace llvm::support::endian;
24 using namespace llvm::ELF;
25 
26 using namespace lld;
27 using namespace lld::elf;
28 
29 static bool isAlpha(char C) {
30   return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
31 }
32 
33 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
34 
35 // Returns true if S is valid as a C language identifier.
36 bool elf::isValidCIdentifier(StringRef S) {
37   return !S.empty() && isAlpha(S[0]) &&
38          std::all_of(S.begin() + 1, S.end(), isAlnum);
39 }
40 
41 template <class ELFT>
42 OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
43                                            uintX_t Flags)
44     : Name(Name) {
45   memset(&Header, 0, sizeof(Elf_Shdr));
46   Header.sh_type = Type;
47   Header.sh_flags = Flags;
48 }
49 
50 template <class ELFT>
51 void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
52   *Shdr = Header;
53 }
54 
55 template <class ELFT>
56 GotPltSection<ELFT>::GotPltSection()
57     : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
58   this->Header.sh_addralign = sizeof(uintX_t);
59 }
60 
61 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
62   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
63   Entries.push_back(&Sym);
64 }
65 
66 template <class ELFT> bool GotPltSection<ELFT>::empty() const {
67   return Entries.empty();
68 }
69 
70 template <class ELFT> void GotPltSection<ELFT>::finalize() {
71   this->Header.sh_size =
72       (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t);
73 }
74 
75 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
76   Target->writeGotPltHeader(Buf);
77   Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t);
78   for (const SymbolBody *B : Entries) {
79     Target->writeGotPlt(Buf, B->getPltVA<ELFT>());
80     Buf += sizeof(uintX_t);
81   }
82 }
83 
84 template <class ELFT>
85 GotSection<ELFT>::GotSection()
86     : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
87   if (Config->EMachine == EM_MIPS)
88     this->Header.sh_flags |= SHF_MIPS_GPREL;
89   this->Header.sh_addralign = sizeof(uintX_t);
90 }
91 
92 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
93   if (Config->EMachine == EM_MIPS) {
94     // For "true" local symbols which can be referenced from the same module
95     // only compiler creates two instructions for address loading:
96     //
97     // lw   $8, 0($gp) # R_MIPS_GOT16
98     // addi $8, $8, 0  # R_MIPS_LO16
99     //
100     // The first instruction loads high 16 bits of the symbol address while
101     // the second adds an offset. That allows to reduce number of required
102     // GOT entries because only one global offset table entry is necessary
103     // for every 64 KBytes of local data. So for local symbols we need to
104     // allocate number of GOT entries to hold all required "page" addresses.
105     //
106     // All global symbols (hidden and regular) considered by compiler uniformly.
107     // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
108     // to load address of the symbol. So for each such symbol we need to
109     // allocate dedicated GOT entry to store its address.
110     //
111     // If a symbol is preemptible we need help of dynamic linker to get its
112     // final address. The corresponding GOT entries are allocated in the
113     // "global" part of GOT. Entries for non preemptible global symbol allocated
114     // in the "local" part of GOT.
115     //
116     // See "Global Offset Table" in Chapter 5:
117     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
118     //
119     // FIXME (simon): Now LLD allocates GOT entries for each
120     // "local symbol+addend" pair. That should be fixed to reduce size
121     // of generated GOT.
122     if (Sym.isPreemptible())
123       Sym.MustBeInDynSym = true;
124     else {
125       ++MipsLocalEntries;
126       return;
127     }
128   }
129   Sym.GotIndex = Entries.size();
130   Entries.push_back(&Sym);
131 }
132 
133 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
134   if (Sym.hasGlobalDynIndex())
135     return false;
136   Sym.GlobalDynIndex = Target->GotHeaderEntriesNum + Entries.size();
137   // Global Dynamic TLS entries take two GOT slots.
138   Entries.push_back(&Sym);
139   Entries.push_back(nullptr);
140   return true;
141 }
142 
143 // Reserves TLS entries for a TLS module ID and a TLS block offset.
144 // In total it takes two GOT slots.
145 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
146   if (TlsIndexOff != uint32_t(-1))
147     return false;
148   TlsIndexOff = Entries.size() * sizeof(uintX_t);
149   Entries.push_back(nullptr);
150   Entries.push_back(nullptr);
151   return true;
152 }
153 
154 template <class ELFT>
155 typename GotSection<ELFT>::uintX_t
156 GotSection<ELFT>::getMipsLocalFullAddr(const SymbolBody &B) {
157   return getMipsLocalEntryAddr(B.getVA<ELFT>());
158 }
159 
160 template <class ELFT>
161 typename GotSection<ELFT>::uintX_t
162 GotSection<ELFT>::getMipsLocalPageAddr(uintX_t EntryValue) {
163   // Initialize the entry by the %hi(EntryValue) expression
164   // but without right-shifting.
165   return getMipsLocalEntryAddr((EntryValue + 0x8000) & ~0xffff);
166 }
167 
168 template <class ELFT>
169 typename GotSection<ELFT>::uintX_t
170 GotSection<ELFT>::getMipsLocalEntryAddr(uintX_t EntryValue) {
171   size_t NewIndex = Target->GotHeaderEntriesNum + MipsLocalGotPos.size();
172   auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
173   assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries);
174   return this->getVA() + P.first->second * sizeof(uintX_t);
175 }
176 
177 template <class ELFT>
178 typename GotSection<ELFT>::uintX_t
179 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
180   return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
181 }
182 
183 template <class ELFT>
184 const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
185   return Entries.empty() ? nullptr : Entries.front();
186 }
187 
188 template <class ELFT>
189 unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
190   return Target->GotHeaderEntriesNum + MipsLocalEntries;
191 }
192 
193 template <class ELFT> void GotSection<ELFT>::finalize() {
194   this->Header.sh_size =
195       (Target->GotHeaderEntriesNum + MipsLocalEntries + Entries.size()) *
196       sizeof(uintX_t);
197 }
198 
199 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
200   Target->writeGotHeader(Buf);
201   for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
202     uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
203     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
204   }
205   Buf += Target->GotHeaderEntriesNum * sizeof(uintX_t);
206   Buf += MipsLocalEntries * sizeof(uintX_t);
207   for (const SymbolBody *B : Entries) {
208     uint8_t *Entry = Buf;
209     Buf += sizeof(uintX_t);
210     if (!B)
211       continue;
212     // MIPS has special rules to fill up GOT entries.
213     // See "Global Offset Table" in Chapter 5 in the following document
214     // for detailed description:
215     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
216     // As the first approach, we can just store addresses for all symbols.
217     if (Config->EMachine != EM_MIPS && B->isPreemptible())
218       continue; // The dynamic linker will take care of it.
219     uintX_t VA = B->getVA<ELFT>();
220     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
221   }
222 }
223 
224 template <class ELFT>
225 PltSection<ELFT>::PltSection()
226     : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
227   this->Header.sh_addralign = 16;
228 }
229 
230 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
231   size_t Off = 0;
232   if (Target->UseLazyBinding) {
233     // At beginning of PLT, we have code to call the dynamic linker
234     // to resolve dynsyms at runtime. Write such code.
235     Target->writePltZero(Buf);
236     Off += Target->PltZeroSize;
237   }
238   for (auto &I : Entries) {
239     const SymbolBody *B = I.first;
240     unsigned RelOff = I.second;
241     uint64_t Got =
242         Target->UseLazyBinding ? B->getGotPltVA<ELFT>() : B->getGotVA<ELFT>();
243     uint64_t Plt = this->getVA() + Off;
244     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
245     Off += Target->PltEntrySize;
246   }
247 }
248 
249 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
250   Sym.PltIndex = Entries.size();
251   unsigned RelOff = Target->UseLazyBinding
252                         ? Out<ELFT>::RelaPlt->getRelocOffset()
253                         : Out<ELFT>::RelaDyn->getRelocOffset();
254   Entries.push_back(std::make_pair(&Sym, RelOff));
255 }
256 
257 template <class ELFT> void PltSection<ELFT>::finalize() {
258   this->Header.sh_size =
259       Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
260 }
261 
262 template <class ELFT>
263 RelocationSection<ELFT>::RelocationSection(StringRef Name)
264     : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
265                               SHF_ALLOC) {
266   this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
267   this->Header.sh_addralign = sizeof(uintX_t);
268 }
269 
270 template <class ELFT>
271 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
272   SymbolBody *Sym = Reloc.Sym;
273   if (!Reloc.UseSymVA && Sym)
274     Sym->MustBeInDynSym = true;
275   Relocs.push_back(Reloc);
276 }
277 
278 template <class ELFT>
279 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
280   switch (OKind) {
281   case Off_GTlsIndex:
282     return Out<ELFT>::Got->getGlobalDynAddr(*Sym);
283   case Off_GTlsOffset:
284     return Out<ELFT>::Got->getGlobalDynAddr(*Sym) + sizeof(uintX_t);
285   case Off_LTlsIndex:
286     return Out<ELFT>::Got->getTlsIndexVA();
287   case Off_Sec:
288     return OffsetSec->getOffset(OffsetInSec) + OffsetSec->OutSec->getVA();
289   case Off_Bss:
290     return cast<SharedSymbol<ELFT>>(Sym)->OffsetInBss + Out<ELFT>::Bss->getVA();
291   case Off_Got:
292     return Sym->getGotVA<ELFT>();
293   case Off_GotPlt:
294     return Sym->getGotPltVA<ELFT>();
295   }
296   llvm_unreachable("invalid offset kind");
297 }
298 
299 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
300   for (const DynamicReloc<ELFT> &Rel : Relocs) {
301     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
302     Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
303     SymbolBody *Sym = Rel.Sym;
304 
305     if (Config->Rela)
306       P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend;
307     P->r_offset = Rel.getOffset();
308     uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
309     P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
310   }
311 }
312 
313 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
314   return this->Header.sh_entsize * Relocs.size();
315 }
316 
317 template <class ELFT> void RelocationSection<ELFT>::finalize() {
318   this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
319                                 : Out<ELFT>::DynSymTab->SectionIndex;
320   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
321 }
322 
323 template <class ELFT>
324 InterpSection<ELFT>::InterpSection()
325     : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
326   this->Header.sh_size = Config->DynamicLinker.size() + 1;
327   this->Header.sh_addralign = 1;
328 }
329 
330 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
331   StringRef S = Config->DynamicLinker;
332   memcpy(Buf, S.data(), S.size());
333 }
334 
335 template <class ELFT>
336 HashTableSection<ELFT>::HashTableSection()
337     : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
338   this->Header.sh_entsize = sizeof(Elf_Word);
339   this->Header.sh_addralign = sizeof(Elf_Word);
340 }
341 
342 static uint32_t hashSysv(StringRef Name) {
343   uint32_t H = 0;
344   for (char C : Name) {
345     H = (H << 4) + C;
346     uint32_t G = H & 0xf0000000;
347     if (G)
348       H ^= G >> 24;
349     H &= ~G;
350   }
351   return H;
352 }
353 
354 template <class ELFT> void HashTableSection<ELFT>::finalize() {
355   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
356 
357   unsigned NumEntries = 2;                             // nbucket and nchain.
358   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
359 
360   // Create as many buckets as there are symbols.
361   // FIXME: This is simplistic. We can try to optimize it, but implementing
362   // support for SHT_GNU_HASH is probably even more profitable.
363   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
364   this->Header.sh_size = NumEntries * sizeof(Elf_Word);
365 }
366 
367 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
368   unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
369   auto *P = reinterpret_cast<Elf_Word *>(Buf);
370   *P++ = NumSymbols; // nbucket
371   *P++ = NumSymbols; // nchain
372 
373   Elf_Word *Buckets = P;
374   Elf_Word *Chains = P + NumSymbols;
375 
376   for (const std::pair<SymbolBody *, unsigned> &P :
377        Out<ELFT>::DynSymTab->getSymbols()) {
378     SymbolBody *Body = P.first;
379     StringRef Name = Body->getName();
380     unsigned I = Body->DynsymIndex;
381     uint32_t Hash = hashSysv(Name) % NumSymbols;
382     Chains[I] = Buckets[Hash];
383     Buckets[Hash] = I;
384   }
385 }
386 
387 static uint32_t hashGnu(StringRef Name) {
388   uint32_t H = 5381;
389   for (uint8_t C : Name)
390     H = (H << 5) + H + C;
391   return H;
392 }
393 
394 template <class ELFT>
395 GnuHashTableSection<ELFT>::GnuHashTableSection()
396     : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
397   this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
398   this->Header.sh_addralign = sizeof(uintX_t);
399 }
400 
401 template <class ELFT>
402 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
403   if (!NumHashed)
404     return 0;
405 
406   // These values are prime numbers which are not greater than 2^(N-1) + 1.
407   // In result, for any particular NumHashed we return a prime number
408   // which is not greater than NumHashed.
409   static const unsigned Primes[] = {
410       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
411       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
412 
413   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
414                                    array_lengthof(Primes) - 1)];
415 }
416 
417 // Bloom filter estimation: at least 8 bits for each hashed symbol.
418 // GNU Hash table requirement: it should be a power of 2,
419 //   the minimum value is 1, even for an empty table.
420 // Expected results for a 32-bit target:
421 //   calcMaskWords(0..4)   = 1
422 //   calcMaskWords(5..8)   = 2
423 //   calcMaskWords(9..16)  = 4
424 // For a 64-bit target:
425 //   calcMaskWords(0..8)   = 1
426 //   calcMaskWords(9..16)  = 2
427 //   calcMaskWords(17..32) = 4
428 template <class ELFT>
429 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
430   if (!NumHashed)
431     return 1;
432   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
433 }
434 
435 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
436   unsigned NumHashed = Symbols.size();
437   NBuckets = calcNBuckets(NumHashed);
438   MaskWords = calcMaskWords(NumHashed);
439   // Second hash shift estimation: just predefined values.
440   Shift2 = ELFT::Is64Bits ? 6 : 5;
441 
442   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
443   this->Header.sh_size = sizeof(Elf_Word) * 4            // Header
444                          + sizeof(Elf_Off) * MaskWords   // Bloom Filter
445                          + sizeof(Elf_Word) * NBuckets   // Hash Buckets
446                          + sizeof(Elf_Word) * NumHashed; // Hash Values
447 }
448 
449 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
450   writeHeader(Buf);
451   if (Symbols.empty())
452     return;
453   writeBloomFilter(Buf);
454   writeHashTable(Buf);
455 }
456 
457 template <class ELFT>
458 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
459   auto *P = reinterpret_cast<Elf_Word *>(Buf);
460   *P++ = NBuckets;
461   *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
462   *P++ = MaskWords;
463   *P++ = Shift2;
464   Buf = reinterpret_cast<uint8_t *>(P);
465 }
466 
467 template <class ELFT>
468 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
469   unsigned C = sizeof(Elf_Off) * 8;
470 
471   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
472   for (const SymbolData &Sym : Symbols) {
473     size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
474     uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
475                 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
476     Masks[Pos] |= V;
477   }
478   Buf += sizeof(Elf_Off) * MaskWords;
479 }
480 
481 template <class ELFT>
482 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
483   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
484   Elf_Word *Values = Buckets + NBuckets;
485 
486   int PrevBucket = -1;
487   int I = 0;
488   for (const SymbolData &Sym : Symbols) {
489     int Bucket = Sym.Hash % NBuckets;
490     assert(PrevBucket <= Bucket);
491     if (Bucket != PrevBucket) {
492       Buckets[Bucket] = Sym.Body->DynsymIndex;
493       PrevBucket = Bucket;
494       if (I > 0)
495         Values[I - 1] |= 1;
496     }
497     Values[I] = Sym.Hash & ~1;
498     ++I;
499   }
500   if (I > 0)
501     Values[I - 1] |= 1;
502 }
503 
504 static bool includeInGnuHashTable(SymbolBody *B) {
505   // Assume that includeInDynsym() is already checked.
506   return !B->isUndefined();
507 }
508 
509 // Add symbols to this symbol hash table. Note that this function
510 // destructively sort a given vector -- which is needed because
511 // GNU-style hash table places some sorting requirements.
512 template <class ELFT>
513 void GnuHashTableSection<ELFT>::addSymbols(
514     std::vector<std::pair<SymbolBody *, size_t>> &V) {
515   auto Mid = std::stable_partition(V.begin(), V.end(),
516                                    [](std::pair<SymbolBody *, size_t> &P) {
517                                      return !includeInGnuHashTable(P.first);
518                                    });
519   if (Mid == V.end())
520     return;
521   for (auto I = Mid, E = V.end(); I != E; ++I) {
522     SymbolBody *B = I->first;
523     size_t StrOff = I->second;
524     Symbols.push_back({B, StrOff, hashGnu(B->getName())});
525   }
526 
527   unsigned NBuckets = calcNBuckets(Symbols.size());
528   std::stable_sort(Symbols.begin(), Symbols.end(),
529                    [&](const SymbolData &L, const SymbolData &R) {
530                      return L.Hash % NBuckets < R.Hash % NBuckets;
531                    });
532 
533   V.erase(Mid, V.end());
534   for (const SymbolData &Sym : Symbols)
535     V.push_back({Sym.Body, Sym.STName});
536 }
537 
538 template <class ELFT>
539 DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
540     : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE),
541       SymTab(SymTab) {
542   Elf_Shdr &Header = this->Header;
543   Header.sh_addralign = sizeof(uintX_t);
544   Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
545 
546   // .dynamic section is not writable on MIPS.
547   // See "Special Section" in Chapter 4 in the following document:
548   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
549   if (Config->EMachine == EM_MIPS)
550     Header.sh_flags = SHF_ALLOC;
551 }
552 
553 template <class ELFT> void DynamicSection<ELFT>::finalize() {
554   if (this->Header.sh_size)
555     return; // Already finalized.
556 
557   Elf_Shdr &Header = this->Header;
558   Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
559 
560   auto Add = [=](Entry E) { Entries.push_back(E); };
561 
562   // Add strings. We know that these are the last strings to be added to
563   // DynStrTab and doing this here allows this function to set DT_STRSZ.
564   if (!Config->RPath.empty())
565     Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
566          Out<ELFT>::DynStrTab->addString(Config->RPath)});
567   for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
568     if (F->isNeeded())
569       Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
570   if (!Config->SoName.empty())
571     Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
572 
573   Out<ELFT>::DynStrTab->finalize();
574 
575   if (Out<ELFT>::RelaDyn->hasRelocs()) {
576     bool IsRela = Config->Rela;
577     Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
578     Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
579     Add({IsRela ? DT_RELAENT : DT_RELENT,
580          uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
581   }
582   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
583     Add({DT_JMPREL, Out<ELFT>::RelaPlt});
584     Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
585     Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
586          Out<ELFT>::GotPlt});
587     Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
588   }
589 
590   Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
591   Add({DT_SYMENT, sizeof(Elf_Sym)});
592   Add({DT_STRTAB, Out<ELFT>::DynStrTab});
593   Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
594   if (Out<ELFT>::GnuHashTab)
595     Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
596   if (Out<ELFT>::HashTab)
597     Add({DT_HASH, Out<ELFT>::HashTab});
598 
599   if (PreInitArraySec) {
600     Add({DT_PREINIT_ARRAY, PreInitArraySec});
601     Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
602   }
603   if (InitArraySec) {
604     Add({DT_INIT_ARRAY, InitArraySec});
605     Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
606   }
607   if (FiniArraySec) {
608     Add({DT_FINI_ARRAY, FiniArraySec});
609     Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
610   }
611 
612   if (SymbolBody *B = SymTab.find(Config->Init))
613     Add({DT_INIT, B});
614   if (SymbolBody *B = SymTab.find(Config->Fini))
615     Add({DT_FINI, B});
616 
617   uint32_t DtFlags = 0;
618   uint32_t DtFlags1 = 0;
619   if (Config->Bsymbolic)
620     DtFlags |= DF_SYMBOLIC;
621   if (Config->ZNodelete)
622     DtFlags1 |= DF_1_NODELETE;
623   if (Config->ZNow) {
624     DtFlags |= DF_BIND_NOW;
625     DtFlags1 |= DF_1_NOW;
626   }
627   if (Config->ZOrigin) {
628     DtFlags |= DF_ORIGIN;
629     DtFlags1 |= DF_1_ORIGIN;
630   }
631 
632   if (DtFlags)
633     Add({DT_FLAGS, DtFlags});
634   if (DtFlags1)
635     Add({DT_FLAGS_1, DtFlags1});
636 
637   if (!Config->Entry.empty())
638     Add({DT_DEBUG, (uint64_t)0});
639 
640   if (Config->EMachine == EM_MIPS) {
641     Add({DT_MIPS_RLD_VERSION, 1});
642     Add({DT_MIPS_FLAGS, RHF_NOTPOT});
643     Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
644     Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
645     Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
646     if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
647       Add({DT_MIPS_GOTSYM, B->DynsymIndex});
648     else
649       Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
650     Add({DT_PLTGOT, Out<ELFT>::Got});
651     if (Out<ELFT>::MipsRldMap)
652       Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
653   }
654 
655   // +1 for DT_NULL
656   Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
657 }
658 
659 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
660   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
661 
662   for (const Entry &E : Entries) {
663     P->d_tag = E.Tag;
664     switch (E.Kind) {
665     case Entry::SecAddr:
666       P->d_un.d_ptr = E.OutSec->getVA();
667       break;
668     case Entry::SymAddr:
669       P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
670       break;
671     case Entry::PlainInt:
672       P->d_un.d_val = E.Val;
673       break;
674     }
675     ++P;
676   }
677 }
678 
679 template <class ELFT>
680 EhFrameHeader<ELFT>::EhFrameHeader()
681     : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS,
682                               SHF_ALLOC) {
683   // It's a 4 bytes of header + pointer to the contents of the .eh_frame section
684   // + the number of FDE pointers in the table.
685   this->Header.sh_size = 12;
686 }
687 
688 // We have to get PC values of FDEs. They depend on relocations
689 // which are target specific, so we run this code after performing
690 // all relocations. We read the values from ouput buffer according to the
691 // encoding given for FDEs. Return value is an offset to the initial PC value
692 // for the FDE.
693 template <class ELFT>
694 typename EhFrameHeader<ELFT>::uintX_t
695 EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) {
696   const endianness E = ELFT::TargetEndianness;
697   uint8_t Size = F.Enc & 0x7;
698   if (Size == DW_EH_PE_absptr)
699     Size = sizeof(uintX_t) == 8 ? DW_EH_PE_udata8 : DW_EH_PE_udata4;
700   uint64_t PC;
701   switch (Size) {
702   case DW_EH_PE_udata2:
703     PC = read16<E>(F.PCRel);
704     break;
705   case DW_EH_PE_udata4:
706     PC = read32<E>(F.PCRel);
707     break;
708   case DW_EH_PE_udata8:
709     PC = read64<E>(F.PCRel);
710     break;
711   default:
712     fatal("unknown FDE size encoding");
713   }
714   switch (F.Enc & 0x70) {
715   case DW_EH_PE_absptr:
716     return PC;
717   case DW_EH_PE_pcrel:
718     return PC + EhVA + F.Off + 8;
719   default:
720     fatal("unknown FDE size relative encoding");
721   }
722 }
723 
724 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
725   const endianness E = ELFT::TargetEndianness;
726 
727   const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4,
728                             DW_EH_PE_udata4,
729                             DW_EH_PE_datarel | DW_EH_PE_sdata4};
730   memcpy(Buf, Header, sizeof(Header));
731 
732   uintX_t EhVA = Sec->getVA();
733   uintX_t VA = this->getVA();
734   uintX_t EhOff = EhVA - VA - 4;
735   write32<E>(Buf + 4, EhOff);
736   write32<E>(Buf + 8, this->FdeList.size());
737   Buf += 12;
738 
739   // InitialPC -> Offset in .eh_frame, sorted by InitialPC.
740   std::map<uintX_t, size_t> PcToOffset;
741   for (const FdeData &F : FdeList)
742     PcToOffset[getFdePc(EhVA, F)] = F.Off;
743 
744   for (auto &I : PcToOffset) {
745     // The first four bytes are an offset to the initial PC value for the FDE.
746     write32<E>(Buf, I.first - VA);
747     // The last four bytes are an offset to the FDE data itself.
748     write32<E>(Buf + 4, EhVA + I.second - VA);
749     Buf += 8;
750   }
751 }
752 
753 template <class ELFT>
754 void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) {
755   assert((!this->Sec || this->Sec == Sec) &&
756          "multiple .eh_frame sections not supported for .eh_frame_hdr");
757   Live = Config->EhFrameHdr;
758   this->Sec = Sec;
759 }
760 
761 template <class ELFT>
762 void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) {
763   if (Live && (Enc & 0xF0) == DW_EH_PE_datarel)
764     fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr");
765   FdeList.push_back(FdeData{Enc, Off, PCRel});
766 }
767 
768 template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() {
769   // Each FDE entry is 8 bytes long:
770   // The first four bytes are an offset to the initial PC value for the FDE. The
771   // last four byte are an offset to the FDE data itself.
772   this->Header.sh_size += 8;
773 }
774 
775 template <class ELFT>
776 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
777     : OutputSectionBase<ELFT>(Name, Type, Flags) {
778   if (Type == SHT_RELA)
779     this->Header.sh_entsize = sizeof(Elf_Rela);
780   else if (Type == SHT_REL)
781     this->Header.sh_entsize = sizeof(Elf_Rel);
782 }
783 
784 template <class ELFT> void OutputSection<ELFT>::finalize() {
785   uint32_t Type = this->Header.sh_type;
786   if (Type != SHT_RELA && Type != SHT_REL)
787     return;
788   this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
789   // sh_info for SHT_REL[A] sections should contain the section header index of
790   // the section to which the relocation applies.
791   InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
792   this->Header.sh_info = S->OutSec->SectionIndex;
793 }
794 
795 template <class ELFT>
796 void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
797   assert(C->Live);
798   auto *S = cast<InputSection<ELFT>>(C);
799   Sections.push_back(S);
800   S->OutSec = this;
801   this->updateAlign(S->Align);
802 
803   uintX_t Off = this->Header.sh_size;
804   Off = alignTo(Off, S->Align);
805   S->OutSecOff = Off;
806   Off += S->getSize();
807   this->Header.sh_size = Off;
808 }
809 
810 // If an input string is in the form of "foo.N" where N is a number,
811 // return N. Otherwise, returns 65536, which is one greater than the
812 // lowest priority.
813 static int getPriority(StringRef S) {
814   size_t Pos = S.rfind('.');
815   if (Pos == StringRef::npos)
816     return 65536;
817   int V;
818   if (S.substr(Pos + 1).getAsInteger(10, V))
819     return 65536;
820   return V;
821 }
822 
823 // This function is called after we sort input sections
824 // to update their offsets.
825 template <class ELFT> void OutputSection<ELFT>::reassignOffsets() {
826   uintX_t Off = 0;
827   for (InputSection<ELFT> *S : Sections) {
828     Off = alignTo(Off, S->Align);
829     S->OutSecOff = Off;
830     Off += S->getSize();
831   }
832   this->Header.sh_size = Off;
833 }
834 
835 // Sorts input sections by section name suffixes, so that .foo.N comes
836 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
837 // We want to keep the original order if the priorities are the same
838 // because the compiler keeps the original initialization order in a
839 // translation unit and we need to respect that.
840 // For more detail, read the section of the GCC's manual about init_priority.
841 template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
842   // Sort sections by priority.
843   typedef std::pair<int, InputSection<ELFT> *> Pair;
844   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
845 
846   std::vector<Pair> V;
847   for (InputSection<ELFT> *S : Sections)
848     V.push_back({getPriority(S->getSectionName()), S});
849   std::stable_sort(V.begin(), V.end(), Comp);
850   Sections.clear();
851   for (Pair &P : V)
852     Sections.push_back(P.second);
853   reassignOffsets();
854 }
855 
856 // Returns true if S matches /Filename.?\.o$/.
857 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
858   if (!S.endswith(".o"))
859     return false;
860   S = S.drop_back(2);
861   if (S.endswith(Filename))
862     return true;
863   return !S.empty() && S.drop_back().endswith(Filename);
864 }
865 
866 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
867 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
868 
869 // .ctors and .dtors are sorted by this priority from highest to lowest.
870 //
871 //  1. The section was contained in crtbegin (crtbegin contains
872 //     some sentinel value in its .ctors and .dtors so that the runtime
873 //     can find the beginning of the sections.)
874 //
875 //  2. The section has an optional priority value in the form of ".ctors.N"
876 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
877 //     they are compared as string rather than number.
878 //
879 //  3. The section is just ".ctors" or ".dtors".
880 //
881 //  4. The section was contained in crtend, which contains an end marker.
882 //
883 // In an ideal world, we don't need this function because .init_array and
884 // .ctors are duplicate features (and .init_array is newer.) However, there
885 // are too many real-world use cases of .ctors, so we had no choice to
886 // support that with this rather ad-hoc semantics.
887 template <class ELFT>
888 static bool compCtors(const InputSection<ELFT> *A,
889                       const InputSection<ELFT> *B) {
890   bool BeginA = isCrtbegin(A->getFile()->getName());
891   bool BeginB = isCrtbegin(B->getFile()->getName());
892   if (BeginA != BeginB)
893     return BeginA;
894   bool EndA = isCrtend(A->getFile()->getName());
895   bool EndB = isCrtend(B->getFile()->getName());
896   if (EndA != EndB)
897     return EndB;
898   StringRef X = A->getSectionName();
899   StringRef Y = B->getSectionName();
900   assert(X.startswith(".ctors") || X.startswith(".dtors"));
901   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
902   X = X.substr(6);
903   Y = Y.substr(6);
904   if (X.empty() && Y.empty())
905     return false;
906   return X < Y;
907 }
908 
909 // Sorts input sections by the special rules for .ctors and .dtors.
910 // Unfortunately, the rules are different from the one for .{init,fini}_array.
911 // Read the comment above.
912 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
913   std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
914   reassignOffsets();
915 }
916 
917 static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
918   size_t I = 0;
919   for (; I + A.size() < Size; I += A.size())
920     memcpy(Buf + I, A.data(), A.size());
921   memcpy(Buf + I, A.data(), Size - I);
922 }
923 
924 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
925   ArrayRef<uint8_t> Filler = Script->getFiller(this->Name);
926   if (!Filler.empty())
927     fill(Buf, this->getSize(), Filler);
928   if (Config->Threads) {
929     parallel_for_each(Sections.begin(), Sections.end(),
930                       [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
931   } else {
932     for (InputSection<ELFT> *C : Sections)
933       C->writeTo(Buf);
934   }
935 }
936 
937 template <class ELFT>
938 EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type,
939                                        uintX_t Flags)
940     : OutputSectionBase<ELFT>(Name, Type, Flags) {
941   Out<ELFT>::EhFrameHdr->assignEhFrame(this);
942 }
943 
944 template <class ELFT>
945 EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index)
946     : S(S), Index(Index) {}
947 
948 template <class ELFT> StringRef EHRegion<ELFT>::data() const {
949   ArrayRef<uint8_t> SecData = S->getSectionData();
950   ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets;
951   size_t Start = Offsets[Index].first;
952   size_t End =
953       Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first;
954   return StringRef((const char *)SecData.data() + Start, End - Start);
955 }
956 
957 template <class ELFT>
958 Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index)
959     : EHRegion<ELFT>(S, Index) {}
960 
961 // Read a byte and advance D by one byte.
962 static uint8_t readByte(ArrayRef<uint8_t> &D) {
963   if (D.empty())
964     fatal("corrupted or unsupported CIE information");
965   uint8_t B = D.front();
966   D = D.slice(1);
967   return B;
968 }
969 
970 static void skipLeb128(ArrayRef<uint8_t> &D) {
971   while (!D.empty()) {
972     uint8_t Val = D.front();
973     D = D.slice(1);
974     if ((Val & 0x80) == 0)
975       return;
976   }
977   fatal("corrupted or unsupported CIE information");
978 }
979 
980 template <class ELFT> static size_t getAugPSize(unsigned Enc) {
981   switch (Enc & 0x0f) {
982   case DW_EH_PE_absptr:
983   case DW_EH_PE_signed:
984     return ELFT::Is64Bits ? 8 : 4;
985   case DW_EH_PE_udata2:
986   case DW_EH_PE_sdata2:
987     return 2;
988   case DW_EH_PE_udata4:
989   case DW_EH_PE_sdata4:
990     return 4;
991   case DW_EH_PE_udata8:
992   case DW_EH_PE_sdata8:
993     return 8;
994   }
995   fatal("unknown FDE encoding");
996 }
997 
998 template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) {
999   uint8_t Enc = readByte(D);
1000   if ((Enc & 0xf0) == DW_EH_PE_aligned)
1001     fatal("DW_EH_PE_aligned encoding is not supported");
1002   size_t Size = getAugPSize<ELFT>(Enc);
1003   if (Size >= D.size())
1004     fatal("corrupted CIE");
1005   D = D.slice(Size);
1006 }
1007 
1008 template <class ELFT>
1009 uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) {
1010   if (D.size() < 8)
1011     fatal("CIE too small");
1012   D = D.slice(8);
1013 
1014   uint8_t Version = readByte(D);
1015   if (Version != 1 && Version != 3)
1016     fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version));
1017 
1018   const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0');
1019   if (AugEnd == D.end())
1020     fatal("corrupted CIE");
1021   StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin());
1022   D = D.slice(Aug.size() + 1);
1023 
1024   // Code alignment factor should always be 1 for .eh_frame.
1025   if (readByte(D) != 1)
1026     fatal("CIE code alignment must be 1");
1027 
1028   // Skip data alignment factor.
1029   skipLeb128(D);
1030 
1031   // Skip the return address register. In CIE version 1 this is a single
1032   // byte. In CIE version 3 this is an unsigned LEB128.
1033   if (Version == 1)
1034     readByte(D);
1035   else
1036     skipLeb128(D);
1037 
1038   // We only care about an 'R' value, but other records may precede an 'R'
1039   // record. Records are not in TLV (type-length-value) format, so we need
1040   // to teach the linker how to skip records for each type.
1041   for (char C : Aug) {
1042     if (C == 'R')
1043       return readByte(D);
1044     if (C == 'z') {
1045       skipLeb128(D);
1046       continue;
1047     }
1048     if (C == 'P') {
1049       skipAugP<ELFT>(D);
1050       continue;
1051     }
1052     if (C == 'L') {
1053       readByte(D);
1054       continue;
1055     }
1056     fatal("unknown .eh_frame augmentation string: " + Aug);
1057   }
1058   return DW_EH_PE_absptr;
1059 }
1060 
1061 template <class ELFT>
1062 static typename ELFT::uint readEntryLength(ArrayRef<uint8_t> D) {
1063   const endianness E = ELFT::TargetEndianness;
1064   if (D.size() < 4)
1065     fatal("CIE/FDE too small");
1066 
1067   // First 4 bytes of CIE/FDE is the size of the record.
1068   // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead.
1069   uint64_t V = read32<E>(D.data());
1070   if (V < UINT32_MAX) {
1071     uint64_t Len = V + 4;
1072     if (Len > D.size())
1073       fatal("CIE/FIE ends past the end of the section");
1074     return Len;
1075   }
1076 
1077   if (D.size() < 12)
1078     fatal("CIE/FDE too small");
1079   V = read64<E>(D.data() + 4);
1080   uint64_t Len = V + 12;
1081   if (Len < V || D.size() < Len)
1082     fatal("CIE/FIE ends past the end of the section");
1083   return Len;
1084 }
1085 
1086 template <class ELFT>
1087 template <class RelTy>
1088 void EHOutputSection<ELFT>::addSectionAux(EHInputSection<ELFT> *S,
1089                                           iterator_range<const RelTy *> Rels) {
1090   const endianness E = ELFT::TargetEndianness;
1091 
1092   S->OutSec = this;
1093   this->updateAlign(S->Align);
1094   Sections.push_back(S);
1095 
1096   ArrayRef<uint8_t> SecData = S->getSectionData();
1097   ArrayRef<uint8_t> D = SecData;
1098   uintX_t Offset = 0;
1099   auto RelI = Rels.begin();
1100   auto RelE = Rels.end();
1101 
1102   DenseMap<unsigned, unsigned> OffsetToIndex;
1103   while (!D.empty()) {
1104     unsigned Index = S->Offsets.size();
1105     S->Offsets.push_back(std::make_pair(Offset, -1));
1106 
1107     uintX_t Length = readEntryLength<ELFT>(D);
1108     // If CIE/FDE data length is zero then Length is 4, this
1109     // shall be considered a terminator and processing shall end.
1110     if (Length == 4)
1111       break;
1112     StringRef Entry((const char *)D.data(), Length);
1113 
1114     while (RelI != RelE && RelI->r_offset < Offset)
1115       ++RelI;
1116     uintX_t NextOffset = Offset + Length;
1117     bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset;
1118 
1119     uint32_t ID = read32<E>(D.data() + 4);
1120     if (ID == 0) {
1121       // CIE
1122       Cie<ELFT> C(S, Index);
1123       if (Config->EhFrameHdr)
1124         C.FdeEncoding = getFdeEncoding(D);
1125 
1126       SymbolBody *Personality = nullptr;
1127       if (HasReloc) {
1128         uint32_t SymIndex = RelI->getSymbol(Config->Mips64EL);
1129         Personality = &S->getFile()->getSymbolBody(SymIndex).repl();
1130       }
1131 
1132       std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality);
1133       auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size()));
1134       if (P.second) {
1135         Cies.push_back(C);
1136         this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
1137       }
1138       OffsetToIndex[Offset] = P.first->second;
1139     } else {
1140       if (!HasReloc)
1141         fatal("FDE doesn't reference another section");
1142       InputSectionBase<ELFT> *Target = S->getRelocTarget(*RelI);
1143       if (Target && Target->Live) {
1144         uint32_t CieOffset = Offset + 4 - ID;
1145         auto I = OffsetToIndex.find(CieOffset);
1146         if (I == OffsetToIndex.end())
1147           fatal("invalid CIE reference");
1148         Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index));
1149         Out<ELFT>::EhFrameHdr->reserveFde();
1150         this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
1151       }
1152     }
1153 
1154     Offset = NextOffset;
1155     D = D.slice(Length);
1156   }
1157 }
1158 
1159 template <class ELFT>
1160 void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1161   auto *S = cast<EHInputSection<ELFT>>(C);
1162   const Elf_Shdr *RelSec = S->RelocSection;
1163   if (!RelSec) {
1164     addSectionAux(S, make_range<const Elf_Rela *>(nullptr, nullptr));
1165     return;
1166   }
1167   ELFFile<ELFT> &Obj = S->getFile()->getObj();
1168   if (RelSec->sh_type == SHT_RELA)
1169     addSectionAux(S, Obj.relas(RelSec));
1170   else
1171     addSectionAux(S, Obj.rels(RelSec));
1172 }
1173 
1174 template <class ELFT>
1175 static typename ELFT::uint writeAlignedCieOrFde(StringRef Data, uint8_t *Buf) {
1176   typedef typename ELFT::uint uintX_t;
1177   const endianness E = ELFT::TargetEndianness;
1178   uint64_t Len = alignTo(Data.size(), sizeof(uintX_t));
1179   write32<E>(Buf, Len - 4);
1180   memcpy(Buf + 4, Data.data() + 4, Data.size() - 4);
1181   return Len;
1182 }
1183 
1184 template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1185   const endianness E = ELFT::TargetEndianness;
1186   size_t Offset = 0;
1187   for (const Cie<ELFT> &C : Cies) {
1188     size_t CieOffset = Offset;
1189 
1190     uintX_t CIELen = writeAlignedCieOrFde<ELFT>(C.data(), Buf + Offset);
1191     C.S->Offsets[C.Index].second = Offset;
1192     Offset += CIELen;
1193 
1194     for (const EHRegion<ELFT> &F : C.Fdes) {
1195       uintX_t Len = writeAlignedCieOrFde<ELFT>(F.data(), Buf + Offset);
1196       write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer
1197       F.S->Offsets[F.Index].second = Offset;
1198       Out<ELFT>::EhFrameHdr->addFde(C.FdeEncoding, Offset, Buf + Offset + 8);
1199       Offset += Len;
1200     }
1201   }
1202 
1203   for (EHInputSection<ELFT> *S : Sections) {
1204     const Elf_Shdr *RelSec = S->RelocSection;
1205     if (!RelSec)
1206       continue;
1207     ELFFile<ELFT> &EObj = S->getFile()->getObj();
1208     if (RelSec->sh_type == SHT_RELA)
1209       S->relocate(Buf, nullptr, EObj.relas(RelSec));
1210     else
1211       S->relocate(Buf, nullptr, EObj.rels(RelSec));
1212   }
1213 }
1214 
1215 template <class ELFT>
1216 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
1217                                              uintX_t Flags, uintX_t Alignment)
1218     : OutputSectionBase<ELFT>(Name, Type, Flags),
1219       Builder(llvm::StringTableBuilder::RAW, Alignment) {}
1220 
1221 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1222   if (shouldTailMerge()) {
1223     StringRef Data = Builder.data();
1224     memcpy(Buf, Data.data(), Data.size());
1225     return;
1226   }
1227   for (const std::pair<StringRef, size_t> &P : Builder.getMap()) {
1228     StringRef Data = P.first;
1229     memcpy(Buf + P.second, Data.data(), Data.size());
1230   }
1231 }
1232 
1233 static size_t findNull(StringRef S, size_t EntSize) {
1234   // Optimize the common case.
1235   if (EntSize == 1)
1236     return S.find(0);
1237 
1238   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1239     const char *B = S.begin() + I;
1240     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1241       return I;
1242   }
1243   return StringRef::npos;
1244 }
1245 
1246 template <class ELFT>
1247 void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1248   auto *S = cast<MergeInputSection<ELFT>>(C);
1249   S->OutSec = this;
1250   this->updateAlign(S->Align);
1251 
1252   ArrayRef<uint8_t> D = S->getSectionData();
1253   StringRef Data((const char *)D.data(), D.size());
1254   uintX_t EntSize = S->getSectionHdr()->sh_entsize;
1255   this->Header.sh_entsize = EntSize;
1256 
1257   // If this is of type string, the contents are null-terminated strings.
1258   if (this->Header.sh_flags & SHF_STRINGS) {
1259     uintX_t Offset = 0;
1260     while (!Data.empty()) {
1261       size_t End = findNull(Data, EntSize);
1262       if (End == StringRef::npos)
1263         fatal("string is not null terminated");
1264       StringRef Entry = Data.substr(0, End + EntSize);
1265       uintX_t OutputOffset = Builder.add(Entry);
1266       if (shouldTailMerge())
1267         OutputOffset = -1;
1268       S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1269       uintX_t Size = End + EntSize;
1270       Data = Data.substr(Size);
1271       Offset += Size;
1272     }
1273     return;
1274   }
1275 
1276   // If this is not of type string, every entry has the same size.
1277   for (unsigned I = 0, N = Data.size(); I != N; I += EntSize) {
1278     StringRef Entry = Data.substr(I, EntSize);
1279     size_t OutputOffset = Builder.add(Entry);
1280     S->Offsets.push_back(std::make_pair(I, OutputOffset));
1281   }
1282 }
1283 
1284 template <class ELFT>
1285 unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1286   return Builder.getOffset(Val);
1287 }
1288 
1289 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1290   return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1291 }
1292 
1293 template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1294   if (shouldTailMerge())
1295     Builder.finalize();
1296   this->Header.sh_size = Builder.getSize();
1297 }
1298 
1299 template <class ELFT>
1300 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
1301     : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1302                               Dynamic ? (uintX_t)SHF_ALLOC : 0),
1303       Dynamic(Dynamic) {
1304   this->Header.sh_addralign = 1;
1305 }
1306 
1307 // Adds a string to the string table. If HashIt is true we hash and check for
1308 // duplicates. It is optional because the name of global symbols are already
1309 // uniqued and hashing them again has a big cost for a small value: uniquing
1310 // them with some other string that happens to be the same.
1311 template <class ELFT>
1312 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1313   if (HashIt) {
1314     auto R = StringMap.insert(std::make_pair(S, Size));
1315     if (!R.second)
1316       return R.first->second;
1317   }
1318   unsigned Ret = Size;
1319   Size += S.size() + 1;
1320   Strings.push_back(S);
1321   return Ret;
1322 }
1323 
1324 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
1325   // ELF string tables start with NUL byte, so advance the pointer by one.
1326   ++Buf;
1327   for (StringRef S : Strings) {
1328     memcpy(Buf, S.data(), S.size());
1329     Buf += S.size() + 1;
1330   }
1331 }
1332 
1333 template <class ELFT>
1334 SymbolTableSection<ELFT>::SymbolTableSection(
1335     SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
1336     : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1337                               StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1338                               StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
1339       StrTabSec(StrTabSec), Table(Table) {
1340   this->Header.sh_entsize = sizeof(Elf_Sym);
1341   this->Header.sh_addralign = sizeof(uintX_t);
1342 }
1343 
1344 // Orders symbols according to their positions in the GOT,
1345 // in compliance with MIPS ABI rules.
1346 // See "Global Offset Table" in Chapter 5 in the following document
1347 // for detailed description:
1348 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1349 static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1350                             const std::pair<SymbolBody *, unsigned> &R) {
1351   if (!L.first->isInGot() || !R.first->isInGot())
1352     return R.first->isInGot();
1353   return L.first->GotIndex < R.first->GotIndex;
1354 }
1355 
1356 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1357   if (this->Header.sh_size)
1358     return; // Already finalized.
1359 
1360   this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
1361   this->Header.sh_link = StrTabSec.SectionIndex;
1362   this->Header.sh_info = NumLocals + 1;
1363 
1364   if (Config->Relocatable) {
1365     size_t I = NumLocals;
1366     for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1367       P.first->DynsymIndex = ++I;
1368     return;
1369   }
1370 
1371   if (!StrTabSec.isDynamic()) {
1372     std::stable_sort(Symbols.begin(), Symbols.end(),
1373                      [](const std::pair<SymbolBody *, unsigned> &L,
1374                         const std::pair<SymbolBody *, unsigned> &R) {
1375                        return getSymbolBinding(L.first) == STB_LOCAL &&
1376                               getSymbolBinding(R.first) != STB_LOCAL;
1377                      });
1378     return;
1379   }
1380   if (Out<ELFT>::GnuHashTab)
1381     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1382     Out<ELFT>::GnuHashTab->addSymbols(Symbols);
1383   else if (Config->EMachine == EM_MIPS)
1384     std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1385   size_t I = 0;
1386   for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1387     P.first->DynsymIndex = ++I;
1388 }
1389 
1390 template <class ELFT>
1391 void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1392   Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1393 }
1394 
1395 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1396   Buf += sizeof(Elf_Sym);
1397 
1398   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1399   // .dynsym only contains global symbols.
1400   if (!Config->DiscardAll && !StrTabSec.isDynamic())
1401     writeLocalSymbols(Buf);
1402 
1403   writeGlobalSymbols(Buf);
1404 }
1405 
1406 template <class ELFT>
1407 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1408   // Iterate over all input object files to copy their local symbols
1409   // to the output symbol table pointed by Buf.
1410   for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
1411     for (const std::pair<const Elf_Sym *, size_t> &P : File->KeptLocalSyms) {
1412       const Elf_Sym *Sym = P.first;
1413 
1414       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1415       uintX_t VA = 0;
1416       if (Sym->st_shndx == SHN_ABS) {
1417         ESym->st_shndx = SHN_ABS;
1418         VA = Sym->st_value;
1419       } else {
1420         InputSectionBase<ELFT> *Section = File->getSection(*Sym);
1421         const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1422         ESym->st_shndx = OutSec->SectionIndex;
1423         VA = Section->getOffset(*Sym);
1424         VA += OutSec->getVA();
1425       }
1426       ESym->st_name = P.second;
1427       ESym->st_size = Sym->st_size;
1428       ESym->setBindingAndType(Sym->getBinding(), Sym->getType());
1429       ESym->st_value = VA;
1430       Buf += sizeof(*ESym);
1431     }
1432   }
1433 }
1434 
1435 template <class ELFT>
1436 static const typename ELFT::Sym *getElfSym(SymbolBody &Body) {
1437   if (auto *EBody = dyn_cast<DefinedElf<ELFT>>(&Body))
1438     return &EBody->Sym;
1439   if (auto *EBody = dyn_cast<UndefinedElf<ELFT>>(&Body))
1440     return &EBody->Sym;
1441   return nullptr;
1442 }
1443 
1444 template <class ELFT>
1445 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1446   // Write the internal symbol table contents to the output symbol table
1447   // pointed by Buf.
1448   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1449   for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
1450     SymbolBody *Body = P.first;
1451     size_t StrOff = P.second;
1452 
1453     uint8_t Type = STT_NOTYPE;
1454     uintX_t Size = 0;
1455     if (const Elf_Sym *InputSym = getElfSym<ELFT>(*Body)) {
1456       Type = InputSym->getType();
1457       Size = InputSym->st_size;
1458     } else if (auto *C = dyn_cast<DefinedCommon>(Body)) {
1459       Type = STT_OBJECT;
1460       Size = C->Size;
1461     }
1462 
1463     ESym->setBindingAndType(getSymbolBinding(Body), Type);
1464     ESym->st_size = Size;
1465     ESym->st_name = StrOff;
1466     ESym->setVisibility(Body->getVisibility());
1467     ESym->st_value = Body->getVA<ELFT>();
1468 
1469     if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
1470       ESym->st_shndx = OutSec->SectionIndex;
1471     else if (isa<DefinedRegular<ELFT>>(Body))
1472       ESym->st_shndx = SHN_ABS;
1473 
1474     // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1475     // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1476     // distinguish such symbols and MIPS lazy-binding stubs.
1477     // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1478     if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1479         Body->NeedsCopyOrPltAddr)
1480       ESym->st_other |= STO_MIPS_PLT;
1481     ++ESym;
1482   }
1483 }
1484 
1485 template <class ELFT>
1486 const OutputSectionBase<ELFT> *
1487 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1488   switch (Sym->kind()) {
1489   case SymbolBody::DefinedSyntheticKind:
1490     return &cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1491   case SymbolBody::DefinedRegularKind: {
1492     auto &D = cast<DefinedRegular<ELFT>>(Sym->repl());
1493     if (D.Section)
1494       return D.Section->OutSec;
1495     break;
1496   }
1497   case SymbolBody::DefinedCommonKind:
1498     return Out<ELFT>::Bss;
1499   case SymbolBody::SharedKind:
1500     if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1501       return Out<ELFT>::Bss;
1502     break;
1503   case SymbolBody::UndefinedElfKind:
1504   case SymbolBody::UndefinedKind:
1505   case SymbolBody::LazyKind:
1506     break;
1507   case SymbolBody::DefinedBitcodeKind:
1508     llvm_unreachable("should have been replaced");
1509   }
1510   return nullptr;
1511 }
1512 
1513 template <class ELFT>
1514 uint8_t SymbolTableSection<ELFT>::getSymbolBinding(SymbolBody *Body) {
1515   uint8_t Visibility = Body->getVisibility();
1516   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1517     return STB_LOCAL;
1518   if (const Elf_Sym *ESym = getElfSym<ELFT>(*Body))
1519     return ESym->getBinding();
1520   if (isa<DefinedSynthetic<ELFT>>(Body))
1521     return STB_LOCAL;
1522   return Body->isWeak() ? STB_WEAK : STB_GLOBAL;
1523 }
1524 
1525 template <class ELFT>
1526 BuildIdSection<ELFT>::BuildIdSection()
1527     : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC) {
1528   // 16 bytes for the note section header and 8 bytes for FNV1 hash.
1529   this->Header.sh_size = 24;
1530 }
1531 
1532 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1533   const endianness E = ELFT::TargetEndianness;
1534   write32<E>(Buf, 4);                   // Name size
1535   write32<E>(Buf + 4, sizeof(Hash));    // Content size
1536   write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1537   memcpy(Buf + 12, "GNU", 4);           // Name string
1538   HashBuf = Buf + 16;
1539 }
1540 
1541 template <class ELFT> void BuildIdSection<ELFT>::update(ArrayRef<uint8_t> Buf) {
1542   // 64-bit FNV1 hash
1543   const uint64_t Prime = 0x100000001b3;
1544   for (uint8_t B : Buf) {
1545     Hash *= Prime;
1546     Hash ^= B;
1547   }
1548 }
1549 
1550 template <class ELFT> void BuildIdSection<ELFT>::writeBuildId() {
1551   const endianness E = ELFT::TargetEndianness;
1552   write64<E>(HashBuf, Hash);
1553 }
1554 
1555 template <class ELFT>
1556 MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1557     : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1558   this->Header.sh_addralign = 4;
1559   this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1560   this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1561 }
1562 
1563 template <class ELFT>
1564 void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1565   auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1566   R->ri_gp_value = getMipsGpAddr<ELFT>();
1567   R->ri_gprmask = GprMask;
1568 }
1569 
1570 template <class ELFT>
1571 void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1572   // Copy input object file's .reginfo gprmask to output.
1573   auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
1574   GprMask |= S->Reginfo->ri_gprmask;
1575 }
1576 
1577 namespace lld {
1578 namespace elf {
1579 template class OutputSectionBase<ELF32LE>;
1580 template class OutputSectionBase<ELF32BE>;
1581 template class OutputSectionBase<ELF64LE>;
1582 template class OutputSectionBase<ELF64BE>;
1583 
1584 template class EhFrameHeader<ELF32LE>;
1585 template class EhFrameHeader<ELF32BE>;
1586 template class EhFrameHeader<ELF64LE>;
1587 template class EhFrameHeader<ELF64BE>;
1588 
1589 template class GotPltSection<ELF32LE>;
1590 template class GotPltSection<ELF32BE>;
1591 template class GotPltSection<ELF64LE>;
1592 template class GotPltSection<ELF64BE>;
1593 
1594 template class GotSection<ELF32LE>;
1595 template class GotSection<ELF32BE>;
1596 template class GotSection<ELF64LE>;
1597 template class GotSection<ELF64BE>;
1598 
1599 template class PltSection<ELF32LE>;
1600 template class PltSection<ELF32BE>;
1601 template class PltSection<ELF64LE>;
1602 template class PltSection<ELF64BE>;
1603 
1604 template class RelocationSection<ELF32LE>;
1605 template class RelocationSection<ELF32BE>;
1606 template class RelocationSection<ELF64LE>;
1607 template class RelocationSection<ELF64BE>;
1608 
1609 template class InterpSection<ELF32LE>;
1610 template class InterpSection<ELF32BE>;
1611 template class InterpSection<ELF64LE>;
1612 template class InterpSection<ELF64BE>;
1613 
1614 template class GnuHashTableSection<ELF32LE>;
1615 template class GnuHashTableSection<ELF32BE>;
1616 template class GnuHashTableSection<ELF64LE>;
1617 template class GnuHashTableSection<ELF64BE>;
1618 
1619 template class HashTableSection<ELF32LE>;
1620 template class HashTableSection<ELF32BE>;
1621 template class HashTableSection<ELF64LE>;
1622 template class HashTableSection<ELF64BE>;
1623 
1624 template class DynamicSection<ELF32LE>;
1625 template class DynamicSection<ELF32BE>;
1626 template class DynamicSection<ELF64LE>;
1627 template class DynamicSection<ELF64BE>;
1628 
1629 template class OutputSection<ELF32LE>;
1630 template class OutputSection<ELF32BE>;
1631 template class OutputSection<ELF64LE>;
1632 template class OutputSection<ELF64BE>;
1633 
1634 template class EHOutputSection<ELF32LE>;
1635 template class EHOutputSection<ELF32BE>;
1636 template class EHOutputSection<ELF64LE>;
1637 template class EHOutputSection<ELF64BE>;
1638 
1639 template class MipsReginfoOutputSection<ELF32LE>;
1640 template class MipsReginfoOutputSection<ELF32BE>;
1641 template class MipsReginfoOutputSection<ELF64LE>;
1642 template class MipsReginfoOutputSection<ELF64BE>;
1643 
1644 template class MergeOutputSection<ELF32LE>;
1645 template class MergeOutputSection<ELF32BE>;
1646 template class MergeOutputSection<ELF64LE>;
1647 template class MergeOutputSection<ELF64BE>;
1648 
1649 template class StringTableSection<ELF32LE>;
1650 template class StringTableSection<ELF32BE>;
1651 template class StringTableSection<ELF64LE>;
1652 template class StringTableSection<ELF64BE>;
1653 
1654 template class SymbolTableSection<ELF32LE>;
1655 template class SymbolTableSection<ELF32BE>;
1656 template class SymbolTableSection<ELF64LE>;
1657 template class SymbolTableSection<ELF64BE>;
1658 
1659 template class BuildIdSection<ELF32LE>;
1660 template class BuildIdSection<ELF32BE>;
1661 template class BuildIdSection<ELF64LE>;
1662 template class BuildIdSection<ELF64BE>;
1663 }
1664 }
1665