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