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