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