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