1 //===- SyntheticSections.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 // This file contains linker-synthesized sections. Currently,
11 // synthetic sections are created either output sections or input sections,
12 // but we are rewriting code so that all synthetic sections are created as
13 // input sections.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SyntheticSections.h"
18 #include "Config.h"
19 #include "Error.h"
20 #include "InputFiles.h"
21 #include "LinkerScript.h"
22 #include "Memory.h"
23 #include "OutputSections.h"
24 #include "Strings.h"
25 #include "SymbolTable.h"
26 #include "Target.h"
27 #include "Threads.h"
28 #include "Writer.h"
29 #include "lld/Config/Version.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/RandomNumberGenerator.h"
34 #include "llvm/Support/SHA1.h"
35 #include "llvm/Support/xxhash.h"
36 #include <cstdlib>
37 
38 using namespace llvm;
39 using namespace llvm::dwarf;
40 using namespace llvm::ELF;
41 using namespace llvm::object;
42 using namespace llvm::support;
43 using namespace llvm::support::endian;
44 
45 using namespace lld;
46 using namespace lld::elf;
47 
48 template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
49   std::vector<DefinedCommon *> V;
50   for (Symbol *S : Symtab<ELFT>::X->getSymbols())
51     if (auto *B = dyn_cast<DefinedCommon>(S->body()))
52       V.push_back(B);
53   return V;
54 }
55 
56 // Find all common symbols and allocate space for them.
57 template <class ELFT> InputSection<ELFT> *elf::createCommonSection() {
58   auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
59                                        ArrayRef<uint8_t>(), "COMMON");
60   Ret->Live = true;
61 
62   if (!Config->DefineCommon)
63     return Ret;
64 
65   // Sort the common symbols by alignment as an heuristic to pack them better.
66   std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
67   std::stable_sort(Syms.begin(), Syms.end(),
68                    [](const DefinedCommon *A, const DefinedCommon *B) {
69                      return A->Alignment > B->Alignment;
70                    });
71 
72   // Assign offsets to symbols.
73   size_t Size = 0;
74   size_t Alignment = 1;
75   for (DefinedCommon *Sym : Syms) {
76     Alignment = std::max<size_t>(Alignment, Sym->Alignment);
77     Size = alignTo(Size, Sym->Alignment);
78 
79     // Compute symbol offset relative to beginning of input section.
80     Sym->Offset = Size;
81     Size += Sym->Size;
82   }
83   Ret->Alignment = Alignment;
84   Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
85   return Ret;
86 }
87 
88 // Returns an LLD version string.
89 static ArrayRef<uint8_t> getVersion() {
90   // Check LLD_VERSION first for ease of testing.
91   // You can get consitent output by using the environment variable.
92   // This is only for testing.
93   StringRef S = getenv("LLD_VERSION");
94   if (S.empty())
95     S = Saver.save(Twine("Linker: ") + getLLDVersion());
96 
97   // +1 to include the terminating '\0'.
98   return {(const uint8_t *)S.data(), S.size() + 1};
99 }
100 
101 // Creates a .comment section containing LLD version info.
102 // With this feature, you can identify LLD-generated binaries easily
103 // by "objdump -s -j .comment <file>".
104 // The returned object is a mergeable string section.
105 template <class ELFT> MergeInputSection<ELFT> *elf::createCommentSection() {
106   typename ELFT::Shdr Hdr = {};
107   Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
108   Hdr.sh_type = SHT_PROGBITS;
109   Hdr.sh_entsize = 1;
110   Hdr.sh_addralign = 1;
111 
112   auto *Ret = make<MergeInputSection<ELFT>>(/*file=*/nullptr, &Hdr, ".comment");
113   Ret->Data = getVersion();
114   Ret->splitIntoPieces();
115   return Ret;
116 }
117 
118 // .MIPS.abiflags section.
119 template <class ELFT>
120 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
121     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
122       Flags(Flags) {}
123 
124 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
125   memcpy(Buf, &Flags, sizeof(Flags));
126 }
127 
128 template <class ELFT>
129 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
130   Elf_Mips_ABIFlags Flags = {};
131   bool Create = false;
132 
133   for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
134     if (!Sec->Live || Sec->Type != SHT_MIPS_ABIFLAGS)
135       continue;
136     Sec->Live = false;
137     Create = true;
138 
139     std::string Filename = toString(Sec->getFile());
140     const size_t Size = Sec->Data.size();
141     // Older version of BFD (such as the default FreeBSD linker) concatenate
142     // .MIPS.abiflags instead of merging. To allow for this case (or potential
143     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
144     if (Size < sizeof(Elf_Mips_ABIFlags)) {
145       error(Filename + ": invalid size of .MIPS.abiflags section: got " +
146             Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
147       return nullptr;
148     }
149     auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
150     if (S->version != 0) {
151       error(Filename + ": unexpected .MIPS.abiflags version " +
152             Twine(S->version));
153       return nullptr;
154     }
155 
156     // LLD checks ISA compatibility in getMipsEFlags(). Here we just
157     // select the highest number of ISA/Rev/Ext.
158     Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
159     Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
160     Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
161     Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
162     Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
163     Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
164     Flags.ases |= S->ases;
165     Flags.flags1 |= S->flags1;
166     Flags.flags2 |= S->flags2;
167     Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
168   };
169 
170   if (Create)
171     return make<MipsAbiFlagsSection<ELFT>>(Flags);
172   return nullptr;
173 }
174 
175 // .MIPS.options section.
176 template <class ELFT>
177 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
178     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
179       Reginfo(Reginfo) {}
180 
181 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
182   auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
183   Options->kind = ODK_REGINFO;
184   Options->size = getSize();
185 
186   if (!Config->Relocatable)
187     Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
188   memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
189 }
190 
191 template <class ELFT>
192 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
193   // N64 ABI only.
194   if (!ELFT::Is64Bits)
195     return nullptr;
196 
197   Elf_Mips_RegInfo Reginfo = {};
198   bool Create = false;
199 
200   for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
201     if (!Sec->Live || Sec->Type != SHT_MIPS_OPTIONS)
202       continue;
203     Sec->Live = false;
204     Create = true;
205 
206     std::string Filename = toString(Sec->getFile());
207     ArrayRef<uint8_t> D = Sec->Data;
208 
209     while (!D.empty()) {
210       if (D.size() < sizeof(Elf_Mips_Options)) {
211         error(Filename + ": invalid size of .MIPS.options section");
212         break;
213       }
214 
215       auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
216       if (Opt->kind == ODK_REGINFO) {
217         if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
218           error(Filename + ": unsupported non-zero ri_gp_value");
219         Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
220         Sec->getFile()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
221         break;
222       }
223 
224       if (!Opt->size)
225         fatal(Filename + ": zero option descriptor size");
226       D = D.slice(Opt->size);
227     }
228   };
229 
230   if (Create)
231     return make<MipsOptionsSection<ELFT>>(Reginfo);
232   return nullptr;
233 }
234 
235 // MIPS .reginfo section.
236 template <class ELFT>
237 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
238     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
239       Reginfo(Reginfo) {}
240 
241 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
242   if (!Config->Relocatable)
243     Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
244   memcpy(Buf, &Reginfo, sizeof(Reginfo));
245 }
246 
247 template <class ELFT>
248 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
249   // Section should be alive for O32 and N32 ABIs only.
250   if (ELFT::Is64Bits)
251     return nullptr;
252 
253   Elf_Mips_RegInfo Reginfo = {};
254   bool Create = false;
255 
256   for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
257     if (!Sec->Live || Sec->Type != SHT_MIPS_REGINFO)
258       continue;
259     Sec->Live = false;
260     Create = true;
261 
262     if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
263       error(toString(Sec->getFile()) + ": invalid size of .reginfo section");
264       return nullptr;
265     }
266     auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
267     if (Config->Relocatable && R->ri_gp_value)
268       error(toString(Sec->getFile()) + ": unsupported non-zero ri_gp_value");
269 
270     Reginfo.ri_gprmask |= R->ri_gprmask;
271     Sec->getFile()->MipsGp0 = R->ri_gp_value;
272   };
273 
274   if (Create)
275     return make<MipsReginfoSection<ELFT>>(Reginfo);
276   return nullptr;
277 }
278 
279 template <class ELFT> InputSection<ELFT> *elf::createInterpSection() {
280   auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 1,
281                                        ArrayRef<uint8_t>(), ".interp");
282   Ret->Live = true;
283 
284   // StringSaver guarantees that the returned string ends with '\0'.
285   StringRef S = Saver.save(Config->DynamicLinker);
286   Ret->Data = {(const uint8_t *)S.data(), S.size() + 1};
287   return Ret;
288 }
289 
290 template <class ELFT>
291 SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type,
292                                    typename ELFT::uint Value,
293                                    typename ELFT::uint Size,
294                                    InputSectionBase<ELFT> *Section) {
295   auto *S = make<DefinedRegular<ELFT>>(Name, /*IsLocal*/ true, STV_DEFAULT,
296                                        Type, Value, Size, Section, nullptr);
297   if (In<ELFT>::SymTab)
298     In<ELFT>::SymTab->addLocal(S);
299   return S;
300 }
301 
302 static size_t getHashSize() {
303   switch (Config->BuildId) {
304   case BuildIdKind::Fast:
305     return 8;
306   case BuildIdKind::Md5:
307   case BuildIdKind::Uuid:
308     return 16;
309   case BuildIdKind::Sha1:
310     return 20;
311   case BuildIdKind::Hexstring:
312     return Config->BuildIdVector.size();
313   default:
314     llvm_unreachable("unknown BuildIdKind");
315   }
316 }
317 
318 template <class ELFT>
319 BuildIdSection<ELFT>::BuildIdSection()
320     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
321       HashSize(getHashSize()) {}
322 
323 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
324   const endianness E = ELFT::TargetEndianness;
325   write32<E>(Buf, 4);                   // Name size
326   write32<E>(Buf + 4, HashSize);        // Content size
327   write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
328   memcpy(Buf + 12, "GNU", 4);           // Name string
329   HashBuf = Buf + 16;
330 }
331 
332 // Split one uint8 array into small pieces of uint8 arrays.
333 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
334                                             size_t ChunkSize) {
335   std::vector<ArrayRef<uint8_t>> Ret;
336   while (Arr.size() > ChunkSize) {
337     Ret.push_back(Arr.take_front(ChunkSize));
338     Arr = Arr.drop_front(ChunkSize);
339   }
340   if (!Arr.empty())
341     Ret.push_back(Arr);
342   return Ret;
343 }
344 
345 // Computes a hash value of Data using a given hash function.
346 // In order to utilize multiple cores, we first split data into 1MB
347 // chunks, compute a hash for each chunk, and then compute a hash value
348 // of the hash values.
349 template <class ELFT>
350 void BuildIdSection<ELFT>::computeHash(
351     llvm::ArrayRef<uint8_t> Data,
352     std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
353   std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
354   std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
355 
356   // Compute hash values.
357   forLoop(0, Chunks.size(),
358           [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); });
359 
360   // Write to the final output buffer.
361   HashFn(HashBuf, Hashes);
362 }
363 
364 template <class ELFT>
365 CopyRelSection<ELFT>::CopyRelSection(bool ReadOnly, uintX_t AddrAlign, size_t S)
366     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_NOBITS, AddrAlign,
367                              ReadOnly ? ".bss.rel.ro" : ".bss"),
368       Size(S) {
369   if (!ReadOnly)
370     this->Flags |= SHF_WRITE;
371 }
372 
373 template <class ELFT>
374 void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
375   switch (Config->BuildId) {
376   case BuildIdKind::Fast:
377     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
378       write64le(Dest, xxHash64(toStringRef(Arr)));
379     });
380     break;
381   case BuildIdKind::Md5:
382     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
383       memcpy(Dest, MD5::hash(Arr).data(), 16);
384     });
385     break;
386   case BuildIdKind::Sha1:
387     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
388       memcpy(Dest, SHA1::hash(Arr).data(), 20);
389     });
390     break;
391   case BuildIdKind::Uuid:
392     if (getRandomBytes(HashBuf, HashSize))
393       error("entropy source failure");
394     break;
395   case BuildIdKind::Hexstring:
396     memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
397     break;
398   default:
399     llvm_unreachable("unknown BuildIdKind");
400   }
401 }
402 
403 template <class ELFT>
404 GotSection<ELFT>::GotSection()
405     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
406                              Target->GotEntrySize, ".got") {}
407 
408 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
409   Sym.GotIndex = NumEntries;
410   ++NumEntries;
411 }
412 
413 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
414   if (Sym.GlobalDynIndex != -1U)
415     return false;
416   Sym.GlobalDynIndex = NumEntries;
417   // Global Dynamic TLS entries take two GOT slots.
418   NumEntries += 2;
419   return true;
420 }
421 
422 // Reserves TLS entries for a TLS module ID and a TLS block offset.
423 // In total it takes two GOT slots.
424 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
425   if (TlsIndexOff != uint32_t(-1))
426     return false;
427   TlsIndexOff = NumEntries * sizeof(uintX_t);
428   NumEntries += 2;
429   return true;
430 }
431 
432 template <class ELFT>
433 typename GotSection<ELFT>::uintX_t
434 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
435   return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
436 }
437 
438 template <class ELFT>
439 typename GotSection<ELFT>::uintX_t
440 GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
441   return B.GlobalDynIndex * sizeof(uintX_t);
442 }
443 
444 template <class ELFT> void GotSection<ELFT>::finalize() {
445   Size = NumEntries * sizeof(uintX_t);
446 }
447 
448 template <class ELFT> bool GotSection<ELFT>::empty() const {
449   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
450   // we need to emit a GOT even if it's empty.
451   return NumEntries == 0 && !HasGotOffRel;
452 }
453 
454 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
455   this->relocate(Buf, Buf + Size);
456 }
457 
458 template <class ELFT>
459 MipsGotSection<ELFT>::MipsGotSection()
460     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL,
461                              SHT_PROGBITS, 16, ".got") {}
462 
463 template <class ELFT>
464 void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, uintX_t Addend,
465                                     RelExpr Expr) {
466   // For "true" local symbols which can be referenced from the same module
467   // only compiler creates two instructions for address loading:
468   //
469   // lw   $8, 0($gp) # R_MIPS_GOT16
470   // addi $8, $8, 0  # R_MIPS_LO16
471   //
472   // The first instruction loads high 16 bits of the symbol address while
473   // the second adds an offset. That allows to reduce number of required
474   // GOT entries because only one global offset table entry is necessary
475   // for every 64 KBytes of local data. So for local symbols we need to
476   // allocate number of GOT entries to hold all required "page" addresses.
477   //
478   // All global symbols (hidden and regular) considered by compiler uniformly.
479   // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
480   // to load address of the symbol. So for each such symbol we need to
481   // allocate dedicated GOT entry to store its address.
482   //
483   // If a symbol is preemptible we need help of dynamic linker to get its
484   // final address. The corresponding GOT entries are allocated in the
485   // "global" part of GOT. Entries for non preemptible global symbol allocated
486   // in the "local" part of GOT.
487   //
488   // See "Global Offset Table" in Chapter 5:
489   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
490   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
491     // At this point we do not know final symbol value so to reduce number
492     // of allocated GOT entries do the following trick. Save all output
493     // sections referenced by GOT relocations. Then later in the `finalize`
494     // method calculate number of "pages" required to cover all saved output
495     // section and allocate appropriate number of GOT entries.
496     auto *DefSym = cast<DefinedRegular<ELFT>>(&Sym);
497     PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
498     return;
499   }
500   if (Sym.isTls()) {
501     // GOT entries created for MIPS TLS relocations behave like
502     // almost GOT entries from other ABIs. They go to the end
503     // of the global offset table.
504     Sym.GotIndex = TlsEntries.size();
505     TlsEntries.push_back(&Sym);
506     return;
507   }
508   auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
509     if (S.isInGot() && !A)
510       return;
511     size_t NewIndex = Items.size();
512     if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
513       return;
514     Items.emplace_back(&S, A);
515     if (!A)
516       S.GotIndex = NewIndex;
517   };
518   if (Sym.isPreemptible()) {
519     // Ignore addends for preemptible symbols. They got single GOT entry anyway.
520     AddEntry(Sym, 0, GlobalEntries);
521     Sym.IsInGlobalMipsGot = true;
522   } else if (Expr == R_MIPS_GOT_OFF32) {
523     AddEntry(Sym, Addend, LocalEntries32);
524     Sym.Is32BitMipsGot = true;
525   } else {
526     // Hold local GOT entries accessed via a 16-bit index separately.
527     // That allows to write them in the beginning of the GOT and keep
528     // their indexes as less as possible to escape relocation's overflow.
529     AddEntry(Sym, Addend, LocalEntries);
530   }
531 }
532 
533 template <class ELFT>
534 bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
535   if (Sym.GlobalDynIndex != -1U)
536     return false;
537   Sym.GlobalDynIndex = TlsEntries.size();
538   // Global Dynamic TLS entries take two GOT slots.
539   TlsEntries.push_back(nullptr);
540   TlsEntries.push_back(&Sym);
541   return true;
542 }
543 
544 // Reserves TLS entries for a TLS module ID and a TLS block offset.
545 // In total it takes two GOT slots.
546 template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
547   if (TlsIndexOff != uint32_t(-1))
548     return false;
549   TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
550   TlsEntries.push_back(nullptr);
551   TlsEntries.push_back(nullptr);
552   return true;
553 }
554 
555 static uint64_t getMipsPageAddr(uint64_t Addr) {
556   return (Addr + 0x8000) & ~0xffff;
557 }
558 
559 static uint64_t getMipsPageCount(uint64_t Size) {
560   return (Size + 0xfffe) / 0xffff + 1;
561 }
562 
563 template <class ELFT>
564 typename MipsGotSection<ELFT>::uintX_t
565 MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
566                                          uintX_t Addend) const {
567   const OutputSectionBase *OutSec =
568       cast<DefinedRegular<ELFT>>(&B)->Section->getOutputSection();
569   uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
570   uintX_t SymAddr = getMipsPageAddr(B.getVA<ELFT>(Addend));
571   uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
572   assert(Index < PageEntriesNum);
573   return (HeaderEntriesNum + Index) * sizeof(uintX_t);
574 }
575 
576 template <class ELFT>
577 typename MipsGotSection<ELFT>::uintX_t
578 MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
579                                          uintX_t Addend) const {
580   // Calculate offset of the GOT entries block: TLS, global, local.
581   uintX_t Index = HeaderEntriesNum + PageEntriesNum;
582   if (B.isTls())
583     Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
584   else if (B.IsInGlobalMipsGot)
585     Index += LocalEntries.size() + LocalEntries32.size();
586   else if (B.Is32BitMipsGot)
587     Index += LocalEntries.size();
588   // Calculate offset of the GOT entry in the block.
589   if (B.isInGot())
590     Index += B.GotIndex;
591   else {
592     auto It = EntryIndexMap.find({&B, Addend});
593     assert(It != EntryIndexMap.end());
594     Index += It->second;
595   }
596   return Index * sizeof(uintX_t);
597 }
598 
599 template <class ELFT>
600 typename MipsGotSection<ELFT>::uintX_t
601 MipsGotSection<ELFT>::getTlsOffset() const {
602   return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
603 }
604 
605 template <class ELFT>
606 typename MipsGotSection<ELFT>::uintX_t
607 MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
608   return B.GlobalDynIndex * sizeof(uintX_t);
609 }
610 
611 template <class ELFT>
612 const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
613   return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
614 }
615 
616 template <class ELFT>
617 unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
618   return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
619          LocalEntries32.size();
620 }
621 
622 template <class ELFT> void MipsGotSection<ELFT>::finalize() {
623   PageEntriesNum = 0;
624   for (std::pair<const OutputSectionBase *, size_t> &P : PageIndexMap) {
625     // For each output section referenced by GOT page relocations calculate
626     // and save into PageIndexMap an upper bound of MIPS GOT entries required
627     // to store page addresses of local symbols. We assume the worst case -
628     // each 64kb page of the output section has at least one GOT relocation
629     // against it. And take in account the case when the section intersects
630     // page boundaries.
631     P.second = PageEntriesNum;
632     PageEntriesNum += getMipsPageCount(P.first->Size);
633   }
634   Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
635          sizeof(uintX_t);
636 }
637 
638 template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
639   // We add the .got section to the result for dynamic MIPS target because
640   // its address and properties are mentioned in the .dynamic section.
641   return Config->Relocatable;
642 }
643 
644 template <class ELFT>
645 typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getGp() const {
646   return ElfSym<ELFT>::MipsGp->template getVA<ELFT>(0);
647 }
648 
649 template <class ELFT>
650 static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
651   typedef typename ELFT::uint uintX_t;
652   write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
653 }
654 
655 template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
656   // Set the MSB of the second GOT slot. This is not required by any
657   // MIPS ABI documentation, though.
658   //
659   // There is a comment in glibc saying that "The MSB of got[1] of a
660   // gnu object is set to identify gnu objects," and in GNU gold it
661   // says "the second entry will be used by some runtime loaders".
662   // But how this field is being used is unclear.
663   //
664   // We are not really willing to mimic other linkers behaviors
665   // without understanding why they do that, but because all files
666   // generated by GNU tools have this special GOT value, and because
667   // we've been doing this for years, it is probably a safe bet to
668   // keep doing this for now. We really need to revisit this to see
669   // if we had to do this.
670   auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
671   P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
672   Buf += HeaderEntriesNum * sizeof(uintX_t);
673   // Write 'page address' entries to the local part of the GOT.
674   for (std::pair<const OutputSectionBase *, size_t> &L : PageIndexMap) {
675     size_t PageCount = getMipsPageCount(L.first->Size);
676     uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
677     for (size_t PI = 0; PI < PageCount; ++PI) {
678       uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
679       writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
680     }
681   }
682   Buf += PageEntriesNum * sizeof(uintX_t);
683   auto AddEntry = [&](const GotEntry &SA) {
684     uint8_t *Entry = Buf;
685     Buf += sizeof(uintX_t);
686     const SymbolBody *Body = SA.first;
687     uintX_t VA = Body->template getVA<ELFT>(SA.second);
688     writeUint<ELFT>(Entry, VA);
689   };
690   std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
691   std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
692   std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
693   // Initialize TLS-related GOT entries. If the entry has a corresponding
694   // dynamic relocations, leave it initialized by zero. Write down adjusted
695   // TLS symbol's values otherwise. To calculate the adjustments use offsets
696   // for thread-local storage.
697   // https://www.linux-mips.org/wiki/NPTL
698   if (TlsIndexOff != -1U && !Config->pic())
699     writeUint<ELFT>(Buf + TlsIndexOff, 1);
700   for (const SymbolBody *B : TlsEntries) {
701     if (!B || B->isPreemptible())
702       continue;
703     uintX_t VA = B->getVA<ELFT>();
704     if (B->GotIndex != -1U) {
705       uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
706       writeUint<ELFT>(Entry, VA - 0x7000);
707     }
708     if (B->GlobalDynIndex != -1U) {
709       uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
710       writeUint<ELFT>(Entry, 1);
711       Entry += sizeof(uintX_t);
712       writeUint<ELFT>(Entry, VA - 0x8000);
713     }
714   }
715 }
716 
717 template <class ELFT>
718 GotPltSection<ELFT>::GotPltSection()
719     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
720                              Target->GotPltEntrySize, ".got.plt") {}
721 
722 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
723   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
724   Entries.push_back(&Sym);
725 }
726 
727 template <class ELFT> size_t GotPltSection<ELFT>::getSize() const {
728   return (Target->GotPltHeaderEntriesNum + Entries.size()) *
729          Target->GotPltEntrySize;
730 }
731 
732 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
733   Target->writeGotPltHeader(Buf);
734   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
735   for (const SymbolBody *B : Entries) {
736     Target->writeGotPlt(Buf, *B);
737     Buf += sizeof(uintX_t);
738   }
739 }
740 
741 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
742 // part of the .got.plt
743 template <class ELFT>
744 IgotPltSection<ELFT>::IgotPltSection()
745     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
746                              Target->GotPltEntrySize,
747                              Config->EMachine == EM_ARM ? ".got" : ".got.plt") {
748 }
749 
750 template <class ELFT> void IgotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
751   Sym.IsInIgot = true;
752   Sym.GotPltIndex = Entries.size();
753   Entries.push_back(&Sym);
754 }
755 
756 template <class ELFT> size_t IgotPltSection<ELFT>::getSize() const {
757   return Entries.size() * Target->GotPltEntrySize;
758 }
759 
760 template <class ELFT> void IgotPltSection<ELFT>::writeTo(uint8_t *Buf) {
761   for (const SymbolBody *B : Entries) {
762     Target->writeIgotPlt(Buf, *B);
763     Buf += sizeof(uintX_t);
764   }
765 }
766 
767 template <class ELFT>
768 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
769     : SyntheticSection<ELFT>(Dynamic ? (uintX_t)SHF_ALLOC : 0, SHT_STRTAB, 1,
770                              Name),
771       Dynamic(Dynamic) {
772   // ELF string tables start with a NUL byte.
773   addString("");
774 }
775 
776 // Adds a string to the string table. If HashIt is true we hash and check for
777 // duplicates. It is optional because the name of global symbols are already
778 // uniqued and hashing them again has a big cost for a small value: uniquing
779 // them with some other string that happens to be the same.
780 template <class ELFT>
781 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
782   if (HashIt) {
783     auto R = StringMap.insert(std::make_pair(S, this->Size));
784     if (!R.second)
785       return R.first->second;
786   }
787   unsigned Ret = this->Size;
788   this->Size = this->Size + S.size() + 1;
789   Strings.push_back(S);
790   return Ret;
791 }
792 
793 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
794   for (StringRef S : Strings) {
795     memcpy(Buf, S.data(), S.size());
796     Buf += S.size() + 1;
797   }
798 }
799 
800 // Returns the number of version definition entries. Because the first entry
801 // is for the version definition itself, it is the number of versioned symbols
802 // plus one. Note that we don't support multiple versions yet.
803 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
804 
805 template <class ELFT>
806 DynamicSection<ELFT>::DynamicSection()
807     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC,
808                              sizeof(uintX_t), ".dynamic") {
809   this->Entsize = ELFT::Is64Bits ? 16 : 8;
810   // .dynamic section is not writable on MIPS.
811   // See "Special Section" in Chapter 4 in the following document:
812   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
813   if (Config->EMachine == EM_MIPS)
814     this->Flags = SHF_ALLOC;
815 
816   addEntries();
817 }
818 
819 // There are some dynamic entries that don't depend on other sections.
820 // Such entries can be set early.
821 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
822   // Add strings to .dynstr early so that .dynstr's size will be
823   // fixed early.
824   for (StringRef S : Config->AuxiliaryList)
825     add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
826   if (!Config->RPath.empty())
827     add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
828          In<ELFT>::DynStrTab->addString(Config->RPath)});
829   for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
830     if (F->isNeeded())
831       add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
832   if (!Config->SoName.empty())
833     add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
834 
835   // Set DT_FLAGS and DT_FLAGS_1.
836   uint32_t DtFlags = 0;
837   uint32_t DtFlags1 = 0;
838   if (Config->Bsymbolic)
839     DtFlags |= DF_SYMBOLIC;
840   if (Config->ZNodelete)
841     DtFlags1 |= DF_1_NODELETE;
842   if (Config->ZNow) {
843     DtFlags |= DF_BIND_NOW;
844     DtFlags1 |= DF_1_NOW;
845   }
846   if (Config->ZOrigin) {
847     DtFlags |= DF_ORIGIN;
848     DtFlags1 |= DF_1_ORIGIN;
849   }
850 
851   if (DtFlags)
852     add({DT_FLAGS, DtFlags});
853   if (DtFlags1)
854     add({DT_FLAGS_1, DtFlags1});
855 
856   if (!Config->Shared && !Config->Relocatable)
857     add({DT_DEBUG, (uint64_t)0});
858 }
859 
860 // Add remaining entries to complete .dynamic contents.
861 template <class ELFT> void DynamicSection<ELFT>::finalize() {
862   if (this->Size)
863     return; // Already finalized.
864 
865   this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
866   if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
867     bool IsRela = Config->Rela;
868     add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
869     add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
870     add({IsRela ? DT_RELAENT : DT_RELENT,
871          uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
872 
873     // MIPS dynamic loader does not support RELCOUNT tag.
874     // The problem is in the tight relation between dynamic
875     // relocations and GOT. So do not emit this tag on MIPS.
876     if (Config->EMachine != EM_MIPS) {
877       size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
878       if (Config->ZCombreloc && NumRelativeRels)
879         add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
880     }
881   }
882   if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
883     add({DT_JMPREL, In<ELFT>::RelaPlt});
884     add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
885     add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
886          In<ELFT>::GotPlt});
887     add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
888   }
889 
890   add({DT_SYMTAB, In<ELFT>::DynSymTab});
891   add({DT_SYMENT, sizeof(Elf_Sym)});
892   add({DT_STRTAB, In<ELFT>::DynStrTab});
893   add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
894   if (In<ELFT>::GnuHashTab)
895     add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
896   if (In<ELFT>::HashTab)
897     add({DT_HASH, In<ELFT>::HashTab});
898 
899   if (Out<ELFT>::PreinitArray) {
900     add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
901     add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
902   }
903   if (Out<ELFT>::InitArray) {
904     add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
905     add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
906   }
907   if (Out<ELFT>::FiniArray) {
908     add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
909     add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
910   }
911 
912   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
913     add({DT_INIT, B});
914   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
915     add({DT_FINI, B});
916 
917   bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
918   if (HasVerNeed || In<ELFT>::VerDef)
919     add({DT_VERSYM, In<ELFT>::VerSym});
920   if (In<ELFT>::VerDef) {
921     add({DT_VERDEF, In<ELFT>::VerDef});
922     add({DT_VERDEFNUM, getVerDefNum()});
923   }
924   if (HasVerNeed) {
925     add({DT_VERNEED, In<ELFT>::VerNeed});
926     add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
927   }
928 
929   if (Config->EMachine == EM_MIPS) {
930     add({DT_MIPS_RLD_VERSION, 1});
931     add({DT_MIPS_FLAGS, RHF_NOTPOT});
932     add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
933     add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
934     add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
935     if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
936       add({DT_MIPS_GOTSYM, B->DynsymIndex});
937     else
938       add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
939     add({DT_PLTGOT, In<ELFT>::MipsGot});
940     if (In<ELFT>::MipsRldMap)
941       add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
942   }
943 
944   this->OutSec->Entsize = this->Entsize;
945   this->OutSec->Link = this->Link;
946 
947   // +1 for DT_NULL
948   this->Size = (Entries.size() + 1) * this->Entsize;
949 }
950 
951 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
952   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
953 
954   for (const Entry &E : Entries) {
955     P->d_tag = E.Tag;
956     switch (E.Kind) {
957     case Entry::SecAddr:
958       P->d_un.d_ptr = E.OutSec->Addr;
959       break;
960     case Entry::InSecAddr:
961       P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
962       break;
963     case Entry::SecSize:
964       P->d_un.d_val = E.OutSec->Size;
965       break;
966     case Entry::SymAddr:
967       P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
968       break;
969     case Entry::PlainInt:
970       P->d_un.d_val = E.Val;
971       break;
972     }
973     ++P;
974   }
975 }
976 
977 template <class ELFT>
978 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
979   return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
980 }
981 
982 template <class ELFT>
983 typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
984   if (UseSymVA)
985     return Sym->getVA<ELFT>(Addend);
986   return Addend;
987 }
988 
989 template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
990   if (Sym && !UseSymVA)
991     return Sym->DynsymIndex;
992   return 0;
993 }
994 
995 template <class ELFT>
996 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
997     : SyntheticSection<ELFT>(SHF_ALLOC, Config->Rela ? SHT_RELA : SHT_REL,
998                              sizeof(uintX_t), Name),
999       Sort(Sort) {
1000   this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1001 }
1002 
1003 template <class ELFT>
1004 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
1005   if (Reloc.Type == Target->RelativeRel)
1006     ++NumRelativeRelocs;
1007   Relocs.push_back(Reloc);
1008 }
1009 
1010 template <class ELFT, class RelTy>
1011 static bool compRelocations(const RelTy &A, const RelTy &B) {
1012   bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
1013   bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
1014   if (AIsRel != BIsRel)
1015     return AIsRel;
1016 
1017   return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
1018 }
1019 
1020 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1021   uint8_t *BufBegin = Buf;
1022   for (const DynamicReloc<ELFT> &Rel : Relocs) {
1023     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
1024     Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1025 
1026     if (Config->Rela)
1027       P->r_addend = Rel.getAddend();
1028     P->r_offset = Rel.getOffset();
1029     if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
1030       // Dynamic relocation against MIPS GOT section make deal TLS entries
1031       // allocated in the end of the GOT. We need to adjust the offset to take
1032       // in account 'local' and 'global' GOT entries.
1033       P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
1034     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
1035   }
1036 
1037   if (Sort) {
1038     if (Config->Rela)
1039       std::stable_sort((Elf_Rela *)BufBegin,
1040                        (Elf_Rela *)BufBegin + Relocs.size(),
1041                        compRelocations<ELFT, Elf_Rela>);
1042     else
1043       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1044                        compRelocations<ELFT, Elf_Rel>);
1045   }
1046 }
1047 
1048 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1049   return this->Entsize * Relocs.size();
1050 }
1051 
1052 template <class ELFT> void RelocationSection<ELFT>::finalize() {
1053   this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1054                                    : In<ELFT>::SymTab->OutSec->SectionIndex;
1055 
1056   // Set required output section properties.
1057   this->OutSec->Link = this->Link;
1058   this->OutSec->Entsize = this->Entsize;
1059 }
1060 
1061 template <class ELFT>
1062 SymbolTableSection<ELFT>::SymbolTableSection(
1063     StringTableSection<ELFT> &StrTabSec)
1064     : SyntheticSection<ELFT>(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1065                              StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1066                              sizeof(uintX_t),
1067                              StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1068       StrTabSec(StrTabSec) {
1069   this->Entsize = sizeof(Elf_Sym);
1070 }
1071 
1072 // Orders symbols according to their positions in the GOT,
1073 // in compliance with MIPS ABI rules.
1074 // See "Global Offset Table" in Chapter 5 in the following document
1075 // for detailed description:
1076 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1077 static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
1078   // Sort entries related to non-local preemptible symbols by GOT indexes.
1079   // All other entries go to the first part of GOT in arbitrary order.
1080   bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1081   bool RIsInLocalGot = !R->IsInGlobalMipsGot;
1082   if (LIsInLocalGot || RIsInLocalGot)
1083     return !RIsInLocalGot;
1084   return L->GotIndex < R->GotIndex;
1085 }
1086 
1087 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1088   this->OutSec->Link = this->Link = StrTabSec.OutSec->SectionIndex;
1089   this->OutSec->Info = this->Info = NumLocals + 1;
1090   this->OutSec->Entsize = this->Entsize;
1091 
1092   if (Config->Relocatable)
1093     return;
1094 
1095   if (!StrTabSec.isDynamic()) {
1096     auto GlobBegin = Symbols.begin() + NumLocals;
1097     auto It = std::stable_partition(
1098         GlobBegin, Symbols.end(), [](const SymbolTableEntry &S) {
1099           return S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1100         });
1101     // update sh_info with number of Global symbols output with computed
1102     // binding of STB_LOCAL
1103     this->OutSec->Info = this->Info = 1 + (It - Symbols.begin());
1104     return;
1105   }
1106 
1107   if (In<ELFT>::GnuHashTab)
1108     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1109     In<ELFT>::GnuHashTab->addSymbols(Symbols);
1110   else if (Config->EMachine == EM_MIPS)
1111     std::stable_sort(Symbols.begin(), Symbols.end(),
1112                      [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1113                        return sortMipsSymbols(L.Symbol, R.Symbol);
1114                      });
1115   size_t I = 0;
1116   for (const SymbolTableEntry &S : Symbols)
1117     S.Symbol->DynsymIndex = ++I;
1118 }
1119 
1120 template <class ELFT> void SymbolTableSection<ELFT>::addGlobal(SymbolBody *B) {
1121   Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1122 }
1123 
1124 template <class ELFT> void SymbolTableSection<ELFT>::addLocal(SymbolBody *B) {
1125   assert(!StrTabSec.isDynamic());
1126   ++NumLocals;
1127   Symbols.push_back({B, StrTabSec.addString(B->getName())});
1128 }
1129 
1130 template <class ELFT>
1131 size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
1132   auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1133     if (E.Symbol == Body)
1134       return true;
1135     // This is used for -r, so we have to handle multiple section
1136     // symbols being combined.
1137     if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
1138       return cast<DefinedRegular<ELFT>>(Body)->Section->OutSec ==
1139              cast<DefinedRegular<ELFT>>(E.Symbol)->Section->OutSec;
1140     return false;
1141   });
1142   if (I == Symbols.end())
1143     return 0;
1144   return I - Symbols.begin() + 1;
1145 }
1146 
1147 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1148   Buf += sizeof(Elf_Sym);
1149 
1150   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1151   // .dynsym only contains global symbols.
1152   if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1153     writeLocalSymbols(Buf);
1154 
1155   writeGlobalSymbols(Buf);
1156 }
1157 
1158 template <class ELFT>
1159 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1160   // Iterate over all input object files to copy their local symbols
1161   // to the output symbol table pointed by Buf.
1162 
1163   for (auto I = Symbols.begin(); I != Symbols.begin() + NumLocals; ++I) {
1164     const DefinedRegular<ELFT> &Body = *cast<DefinedRegular<ELFT>>(I->Symbol);
1165     InputSectionBase<ELFT> *Section = Body.Section;
1166     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1167 
1168     if (!Section) {
1169       ESym->st_shndx = SHN_ABS;
1170       ESym->st_value = Body.Value;
1171     } else {
1172       const OutputSectionBase *OutSec = Section->getOutputSection();
1173       ESym->st_shndx = OutSec->SectionIndex;
1174       ESym->st_value = OutSec->Addr + Section->getOffset(Body);
1175     }
1176     ESym->st_name = I->StrTabOffset;
1177     ESym->st_size = Body.template getSize<ELFT>();
1178     ESym->setBindingAndType(STB_LOCAL, Body.Type);
1179     Buf += sizeof(*ESym);
1180   }
1181 }
1182 
1183 template <class ELFT>
1184 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1185   // Write the internal symbol table contents to the output symbol table
1186   // pointed by Buf.
1187   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1188 
1189   for (auto I = Symbols.begin() + NumLocals; I != Symbols.end(); ++I) {
1190     const SymbolTableEntry &S = *I;
1191     SymbolBody *Body = S.Symbol;
1192     size_t StrOff = S.StrTabOffset;
1193 
1194     uint8_t Type = Body->Type;
1195     uintX_t Size = Body->getSize<ELFT>();
1196 
1197     ESym->setBindingAndType(Body->symbol()->computeBinding(), Type);
1198     ESym->st_size = Size;
1199     ESym->st_name = StrOff;
1200     ESym->setVisibility(Body->symbol()->Visibility);
1201     ESym->st_value = Body->getVA<ELFT>();
1202 
1203     if (const OutputSectionBase *OutSec = getOutputSection(Body)) {
1204       ESym->st_shndx = OutSec->SectionIndex;
1205     } else if (isa<DefinedRegular<ELFT>>(Body)) {
1206       ESym->st_shndx = SHN_ABS;
1207     } else if (isa<DefinedCommon>(Body)) {
1208       ESym->st_shndx = SHN_COMMON;
1209       ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
1210     }
1211 
1212     if (Config->EMachine == EM_MIPS) {
1213       // On MIPS we need to mark symbol which has a PLT entry and requires
1214       // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1215       // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1216       // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1217       if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1218         ESym->st_other |= STO_MIPS_PLT;
1219       if (Config->Relocatable) {
1220         auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1221         if (D && D->isMipsPIC())
1222           ESym->st_other |= STO_MIPS_PIC;
1223       }
1224     }
1225     ++ESym;
1226   }
1227 }
1228 
1229 template <class ELFT>
1230 const OutputSectionBase *
1231 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1232   switch (Sym->kind()) {
1233   case SymbolBody::DefinedSyntheticKind:
1234     return cast<DefinedSynthetic>(Sym)->Section;
1235   case SymbolBody::DefinedRegularKind: {
1236     auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1237     if (D.Section)
1238       return D.Section->getOutputSection();
1239     break;
1240   }
1241   case SymbolBody::DefinedCommonKind:
1242     if (!Config->DefineCommon)
1243       return nullptr;
1244     return In<ELFT>::Common->OutSec;
1245   case SymbolBody::SharedKind: {
1246     auto &SS = cast<SharedSymbol<ELFT>>(*Sym);
1247     if (SS.needsCopy())
1248       return SS.getBssSectionForCopy()->OutSec;
1249     break;
1250   }
1251   case SymbolBody::UndefinedKind:
1252   case SymbolBody::LazyArchiveKind:
1253   case SymbolBody::LazyObjectKind:
1254     break;
1255   }
1256   return nullptr;
1257 }
1258 
1259 template <class ELFT>
1260 GnuHashTableSection<ELFT>::GnuHashTableSection()
1261     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t),
1262                              ".gnu.hash") {
1263   this->Entsize = ELFT::Is64Bits ? 0 : 4;
1264 }
1265 
1266 template <class ELFT>
1267 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
1268   if (!NumHashed)
1269     return 0;
1270 
1271   // These values are prime numbers which are not greater than 2^(N-1) + 1.
1272   // In result, for any particular NumHashed we return a prime number
1273   // which is not greater than NumHashed.
1274   static const unsigned Primes[] = {
1275       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
1276       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
1277 
1278   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
1279                                    array_lengthof(Primes) - 1)];
1280 }
1281 
1282 // Bloom filter estimation: at least 8 bits for each hashed symbol.
1283 // GNU Hash table requirement: it should be a power of 2,
1284 //   the minimum value is 1, even for an empty table.
1285 // Expected results for a 32-bit target:
1286 //   calcMaskWords(0..4)   = 1
1287 //   calcMaskWords(5..8)   = 2
1288 //   calcMaskWords(9..16)  = 4
1289 // For a 64-bit target:
1290 //   calcMaskWords(0..8)   = 1
1291 //   calcMaskWords(9..16)  = 2
1292 //   calcMaskWords(17..32) = 4
1293 template <class ELFT>
1294 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
1295   if (!NumHashed)
1296     return 1;
1297   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
1298 }
1299 
1300 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
1301   unsigned NumHashed = Symbols.size();
1302   NBuckets = calcNBuckets(NumHashed);
1303   MaskWords = calcMaskWords(NumHashed);
1304   // Second hash shift estimation: just predefined values.
1305   Shift2 = ELFT::Is64Bits ? 6 : 5;
1306 
1307   this->OutSec->Entsize = this->Entsize;
1308   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1309   this->Size = sizeof(Elf_Word) * 4            // Header
1310                + sizeof(Elf_Off) * MaskWords   // Bloom Filter
1311                + sizeof(Elf_Word) * NBuckets   // Hash Buckets
1312                + sizeof(Elf_Word) * NumHashed; // Hash Values
1313 }
1314 
1315 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1316   writeHeader(Buf);
1317   if (Symbols.empty())
1318     return;
1319   writeBloomFilter(Buf);
1320   writeHashTable(Buf);
1321 }
1322 
1323 template <class ELFT>
1324 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
1325   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1326   *P++ = NBuckets;
1327   *P++ = In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
1328   *P++ = MaskWords;
1329   *P++ = Shift2;
1330   Buf = reinterpret_cast<uint8_t *>(P);
1331 }
1332 
1333 template <class ELFT>
1334 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
1335   unsigned C = sizeof(Elf_Off) * 8;
1336 
1337   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
1338   for (const SymbolData &Sym : Symbols) {
1339     size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
1340     uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
1341                 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
1342     Masks[Pos] |= V;
1343   }
1344   Buf += sizeof(Elf_Off) * MaskWords;
1345 }
1346 
1347 template <class ELFT>
1348 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
1349   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1350   Elf_Word *Values = Buckets + NBuckets;
1351 
1352   int PrevBucket = -1;
1353   int I = 0;
1354   for (const SymbolData &Sym : Symbols) {
1355     int Bucket = Sym.Hash % NBuckets;
1356     assert(PrevBucket <= Bucket);
1357     if (Bucket != PrevBucket) {
1358       Buckets[Bucket] = Sym.Body->DynsymIndex;
1359       PrevBucket = Bucket;
1360       if (I > 0)
1361         Values[I - 1] |= 1;
1362     }
1363     Values[I] = Sym.Hash & ~1;
1364     ++I;
1365   }
1366   if (I > 0)
1367     Values[I - 1] |= 1;
1368 }
1369 
1370 static uint32_t hashGnu(StringRef Name) {
1371   uint32_t H = 5381;
1372   for (uint8_t C : Name)
1373     H = (H << 5) + H + C;
1374   return H;
1375 }
1376 
1377 // Add symbols to this symbol hash table. Note that this function
1378 // destructively sort a given vector -- which is needed because
1379 // GNU-style hash table places some sorting requirements.
1380 template <class ELFT>
1381 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
1382   // Ideally this will just be 'auto' but GCC 6.1 is not able
1383   // to deduce it correctly.
1384   std::vector<SymbolTableEntry>::iterator Mid =
1385       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1386         return S.Symbol->isUndefined();
1387       });
1388   if (Mid == V.end())
1389     return;
1390   for (auto I = Mid, E = V.end(); I != E; ++I) {
1391     SymbolBody *B = I->Symbol;
1392     size_t StrOff = I->StrTabOffset;
1393     Symbols.push_back({B, StrOff, hashGnu(B->getName())});
1394   }
1395 
1396   unsigned NBuckets = calcNBuckets(Symbols.size());
1397   std::stable_sort(Symbols.begin(), Symbols.end(),
1398                    [&](const SymbolData &L, const SymbolData &R) {
1399                      return L.Hash % NBuckets < R.Hash % NBuckets;
1400                    });
1401 
1402   V.erase(Mid, V.end());
1403   for (const SymbolData &Sym : Symbols)
1404     V.push_back({Sym.Body, Sym.STName});
1405 }
1406 
1407 template <class ELFT>
1408 HashTableSection<ELFT>::HashTableSection()
1409     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_HASH, sizeof(Elf_Word), ".hash") {
1410   this->Entsize = sizeof(Elf_Word);
1411 }
1412 
1413 template <class ELFT> void HashTableSection<ELFT>::finalize() {
1414   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1415   this->OutSec->Entsize = this->Entsize;
1416 
1417   unsigned NumEntries = 2;                            // nbucket and nchain.
1418   NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1419 
1420   // Create as many buckets as there are symbols.
1421   // FIXME: This is simplistic. We can try to optimize it, but implementing
1422   // support for SHT_GNU_HASH is probably even more profitable.
1423   NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
1424   this->Size = NumEntries * sizeof(Elf_Word);
1425 }
1426 
1427 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1428   unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
1429   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1430   *P++ = NumSymbols; // nbucket
1431   *P++ = NumSymbols; // nchain
1432 
1433   Elf_Word *Buckets = P;
1434   Elf_Word *Chains = P + NumSymbols;
1435 
1436   for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1437     SymbolBody *Body = S.Symbol;
1438     StringRef Name = Body->getName();
1439     unsigned I = Body->DynsymIndex;
1440     uint32_t Hash = hashSysV(Name) % NumSymbols;
1441     Chains[I] = Buckets[Hash];
1442     Buckets[Hash] = I;
1443   }
1444 }
1445 
1446 template <class ELFT>
1447 PltSection<ELFT>::PltSection(size_t S)
1448     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1449                              ".plt"),
1450       HeaderSize(S) {}
1451 
1452 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
1453   // At beginning of PLT but not the IPLT, we have code to call the dynamic
1454   // linker to resolve dynsyms at runtime. Write such code.
1455   if (HeaderSize != 0)
1456     Target->writePltHeader(Buf);
1457   size_t Off = HeaderSize;
1458   // The IPlt is immediately after the Plt, account for this in RelOff
1459   unsigned PltOff = getPltRelocOff();
1460 
1461   for (auto &I : Entries) {
1462     const SymbolBody *B = I.first;
1463     unsigned RelOff = I.second + PltOff;
1464     uint64_t Got = B->getGotPltVA<ELFT>();
1465     uint64_t Plt = this->getVA() + Off;
1466     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1467     Off += Target->PltEntrySize;
1468   }
1469 }
1470 
1471 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
1472   Sym.PltIndex = Entries.size();
1473   RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1474   if (HeaderSize == 0) {
1475     PltRelocSection = In<ELFT>::RelaIplt;
1476     Sym.IsInIplt = true;
1477   }
1478   unsigned RelOff = PltRelocSection->getRelocOffset();
1479   Entries.push_back(std::make_pair(&Sym, RelOff));
1480 }
1481 
1482 template <class ELFT> size_t PltSection<ELFT>::getSize() const {
1483   return HeaderSize + Entries.size() * Target->PltEntrySize;
1484 }
1485 
1486 // Some architectures such as additional symbols in the PLT section. For
1487 // example ARM uses mapping symbols to aid disassembly
1488 template <class ELFT> void PltSection<ELFT>::addSymbols() {
1489   // The PLT may have symbols defined for the Header, the IPLT has no header
1490   if (HeaderSize != 0)
1491     Target->addPltHeaderSymbols(this);
1492   size_t Off = HeaderSize;
1493   for (size_t I = 0; I < Entries.size(); ++I) {
1494     Target->addPltSymbols(this, Off);
1495     Off += Target->PltEntrySize;
1496   }
1497 }
1498 
1499 template <class ELFT> unsigned PltSection<ELFT>::getPltRelocOff() const {
1500   return (HeaderSize == 0) ? In<ELFT>::Plt->getSize() : 0;
1501 }
1502 
1503 template <class ELFT>
1504 GdbIndexSection<ELFT>::GdbIndexSection()
1505     : SyntheticSection<ELFT>(0, SHT_PROGBITS, 1, ".gdb_index"),
1506       StringPool(llvm::StringTableBuilder::ELF) {}
1507 
1508 template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
1509   for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
1510     if (InputSection<ELFT> *IS = dyn_cast<InputSection<ELFT>>(S))
1511       if (IS->OutSec && IS->Name == ".debug_info")
1512         readDwarf(IS);
1513 }
1514 
1515 // Iterative hash function for symbol's name is described in .gdb_index format
1516 // specification. Note that we use one for version 5 to 7 here, it is different
1517 // for version 4.
1518 static uint32_t hash(StringRef Str) {
1519   uint32_t R = 0;
1520   for (uint8_t C : Str)
1521     R = R * 67 + tolower(C) - 113;
1522   return R;
1523 }
1524 
1525 template <class ELFT>
1526 void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
1527   GdbIndexBuilder<ELFT> Builder(I);
1528   if (ErrorCount)
1529     return;
1530 
1531   size_t CuId = CompilationUnits.size();
1532   std::vector<std::pair<uintX_t, uintX_t>> CuList = Builder.readCUList();
1533   CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
1534 
1535   std::vector<AddressEntry<ELFT>> AddrArea = Builder.readAddressArea(CuId);
1536   AddressArea.insert(AddressArea.end(), AddrArea.begin(), AddrArea.end());
1537 
1538   std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
1539       Builder.readPubNamesAndTypes();
1540 
1541   for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1542     uint32_t Hash = hash(Pair.first);
1543     size_t Offset = StringPool.add(Pair.first);
1544 
1545     bool IsNew;
1546     GdbSymbol *Sym;
1547     std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1548     if (IsNew) {
1549       Sym->CuVectorIndex = CuVectors.size();
1550       CuVectors.push_back({{CuId, Pair.second}});
1551       continue;
1552     }
1553 
1554     std::vector<std::pair<uint32_t, uint8_t>> &CuVec =
1555         CuVectors[Sym->CuVectorIndex];
1556     CuVec.push_back({CuId, Pair.second});
1557   }
1558 }
1559 
1560 template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
1561   if (Finalized)
1562     return;
1563   Finalized = true;
1564 
1565   parseDebugSections();
1566 
1567   // GdbIndex header consist from version fields
1568   // and 5 more fields with different kinds of offsets.
1569   CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1570   SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
1571 
1572   ConstantPoolOffset =
1573       SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1574 
1575   for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1576     CuVectorsOffset.push_back(CuVectorsSize);
1577     CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1578   }
1579   StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1580 
1581   StringPool.finalizeInOrder();
1582 }
1583 
1584 template <class ELFT> size_t GdbIndexSection<ELFT>::getSize() const {
1585   const_cast<GdbIndexSection<ELFT> *>(this)->finalize();
1586   return StringPoolOffset + StringPool.getSize();
1587 }
1588 
1589 template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
1590   write32le(Buf, 7);                       // Write version.
1591   write32le(Buf + 4, CuListOffset);        // CU list offset.
1592   write32le(Buf + 8, CuTypesOffset);       // Types CU list offset.
1593   write32le(Buf + 12, CuTypesOffset);      // Address area offset.
1594   write32le(Buf + 16, SymTabOffset);       // Symbol table offset.
1595   write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
1596   Buf += 24;
1597 
1598   // Write the CU list.
1599   for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1600     write64le(Buf, CU.first);
1601     write64le(Buf + 8, CU.second);
1602     Buf += 16;
1603   }
1604 
1605   // Write the address area.
1606   for (AddressEntry<ELFT> &E : AddressArea) {
1607     uintX_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
1608     write64le(Buf, BaseAddr + E.LowAddress);
1609     write64le(Buf + 8, BaseAddr + E.HighAddress);
1610     write32le(Buf + 16, E.CuIndex);
1611     Buf += 20;
1612   }
1613 
1614   // Write the symbol table.
1615   for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1616     GdbSymbol *Sym = SymbolTable.getSymbol(I);
1617     if (Sym) {
1618       size_t NameOffset =
1619           Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1620       size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1621       write32le(Buf, NameOffset);
1622       write32le(Buf + 4, CuVectorOffset);
1623     }
1624     Buf += 8;
1625   }
1626 
1627   // Write the CU vectors into the constant pool.
1628   for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1629     write32le(Buf, CuVec.size());
1630     Buf += 4;
1631     for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1632       uint32_t Index = P.first;
1633       uint8_t Flags = P.second;
1634       Index |= Flags << 24;
1635       write32le(Buf, Index);
1636       Buf += 4;
1637     }
1638   }
1639 
1640   StringPool.write(Buf);
1641 }
1642 
1643 template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
1644   return !Out<ELFT>::DebugInfo;
1645 }
1646 
1647 template <class ELFT>
1648 EhFrameHeader<ELFT>::EhFrameHeader()
1649     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1650 
1651 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1652 // Each entry of the search table consists of two values,
1653 // the starting PC from where FDEs covers, and the FDE's address.
1654 // It is sorted by PC.
1655 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1656   const endianness E = ELFT::TargetEndianness;
1657 
1658   // Sort the FDE list by their PC and uniqueify. Usually there is only
1659   // one FDE for a PC (i.e. function), but if ICF merges two functions
1660   // into one, there can be more than one FDEs pointing to the address.
1661   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1662   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1663   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1664   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1665 
1666   Buf[0] = 1;
1667   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1668   Buf[2] = DW_EH_PE_udata4;
1669   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1670   write32<E>(Buf + 4, Out<ELFT>::EhFrame->Addr - this->getVA() - 4);
1671   write32<E>(Buf + 8, Fdes.size());
1672   Buf += 12;
1673 
1674   uintX_t VA = this->getVA();
1675   for (FdeData &Fde : Fdes) {
1676     write32<E>(Buf, Fde.Pc - VA);
1677     write32<E>(Buf + 4, Fde.FdeVA - VA);
1678     Buf += 8;
1679   }
1680 }
1681 
1682 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1683   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1684   return 12 + Out<ELFT>::EhFrame->NumFdes * 8;
1685 }
1686 
1687 template <class ELFT>
1688 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1689   Fdes.push_back({Pc, FdeVA});
1690 }
1691 
1692 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1693   return Out<ELFT>::EhFrame->empty();
1694 }
1695 
1696 template <class ELFT>
1697 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1698     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1699                              ".gnu.version_d") {}
1700 
1701 static StringRef getFileDefName() {
1702   if (!Config->SoName.empty())
1703     return Config->SoName;
1704   return Config->OutputFile;
1705 }
1706 
1707 template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1708   FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1709   for (VersionDefinition &V : Config->VersionDefinitions)
1710     V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1711 
1712   this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1713 
1714   // sh_info should be set to the number of definitions. This fact is missed in
1715   // documentation, but confirmed by binutils community:
1716   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1717   this->OutSec->Info = this->Info = getVerDefNum();
1718 }
1719 
1720 template <class ELFT>
1721 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1722                                               StringRef Name, size_t NameOff) {
1723   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1724   Verdef->vd_version = 1;
1725   Verdef->vd_cnt = 1;
1726   Verdef->vd_aux = sizeof(Elf_Verdef);
1727   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1728   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1729   Verdef->vd_ndx = Index;
1730   Verdef->vd_hash = hashSysV(Name);
1731 
1732   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1733   Verdaux->vda_name = NameOff;
1734   Verdaux->vda_next = 0;
1735 }
1736 
1737 template <class ELFT>
1738 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1739   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1740 
1741   for (VersionDefinition &V : Config->VersionDefinitions) {
1742     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1743     writeOne(Buf, V.Id, V.Name, V.NameOff);
1744   }
1745 
1746   // Need to terminate the last version definition.
1747   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1748   Verdef->vd_next = 0;
1749 }
1750 
1751 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1752   return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1753 }
1754 
1755 template <class ELFT>
1756 VersionTableSection<ELFT>::VersionTableSection()
1757     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1758                              ".gnu.version") {}
1759 
1760 template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1761   this->OutSec->Entsize = this->Entsize = sizeof(Elf_Versym);
1762   // At the moment of june 2016 GNU docs does not mention that sh_link field
1763   // should be set, but Sun docs do. Also readelf relies on this field.
1764   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1765 }
1766 
1767 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
1768   return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
1769 }
1770 
1771 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1772   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1773   for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1774     OutVersym->vs_index = S.Symbol->symbol()->VersionId;
1775     ++OutVersym;
1776   }
1777 }
1778 
1779 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
1780   return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
1781 }
1782 
1783 template <class ELFT>
1784 VersionNeedSection<ELFT>::VersionNeedSection()
1785     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
1786                              ".gnu.version_r") {
1787   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1788   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1789   // First identifiers are reserved by verdef section if it exist.
1790   NextIndex = getVerDefNum() + 1;
1791 }
1792 
1793 template <class ELFT>
1794 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1795   if (!SS->Verdef) {
1796     SS->symbol()->VersionId = VER_NDX_GLOBAL;
1797     return;
1798   }
1799   SharedFile<ELFT> *F = SS->file();
1800   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1801   // to create one by adding it to our needed list and creating a dynstr entry
1802   // for the soname.
1803   if (F->VerdefMap.empty())
1804     Needed.push_back({F, In<ELFT>::DynStrTab->addString(F->getSoName())});
1805   typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1806   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1807   // prepare to create one by allocating a version identifier and creating a
1808   // dynstr entry for the version name.
1809   if (NV.Index == 0) {
1810     NV.StrTab = In<ELFT>::DynStrTab->addString(
1811         SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1812     NV.Index = NextIndex++;
1813   }
1814   SS->symbol()->VersionId = NV.Index;
1815 }
1816 
1817 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1818   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1819   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1820   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1821 
1822   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1823     // Create an Elf_Verneed for this DSO.
1824     Verneed->vn_version = 1;
1825     Verneed->vn_cnt = P.first->VerdefMap.size();
1826     Verneed->vn_file = P.second;
1827     Verneed->vn_aux =
1828         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1829     Verneed->vn_next = sizeof(Elf_Verneed);
1830     ++Verneed;
1831 
1832     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1833     // VerdefMap, which will only contain references to needed version
1834     // definitions. Each Elf_Vernaux is based on the information contained in
1835     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1836     // pointers, but is deterministic because the pointers refer to Elf_Verdef
1837     // data structures within a single input file.
1838     for (auto &NV : P.first->VerdefMap) {
1839       Vernaux->vna_hash = NV.first->vd_hash;
1840       Vernaux->vna_flags = 0;
1841       Vernaux->vna_other = NV.second.Index;
1842       Vernaux->vna_name = NV.second.StrTab;
1843       Vernaux->vna_next = sizeof(Elf_Vernaux);
1844       ++Vernaux;
1845     }
1846 
1847     Vernaux[-1].vna_next = 0;
1848   }
1849   Verneed[-1].vn_next = 0;
1850 }
1851 
1852 template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1853   this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1854   this->OutSec->Info = this->Info = Needed.size();
1855 }
1856 
1857 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
1858   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1859   for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1860     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1861   return Size;
1862 }
1863 
1864 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
1865   return getNeedNum() == 0;
1866 }
1867 
1868 template <class ELFT>
1869 MergeSyntheticSection<ELFT>::MergeSyntheticSection(StringRef Name,
1870                                                    uint32_t Type, uintX_t Flags,
1871                                                    uintX_t Alignment)
1872     : SyntheticSection<ELFT>(Flags, Type, Alignment, Name),
1873       Builder(StringTableBuilder::RAW, Alignment) {}
1874 
1875 template <class ELFT>
1876 void MergeSyntheticSection<ELFT>::addSection(MergeInputSection<ELFT> *MS) {
1877   assert(!Finalized);
1878   MS->MergeSec = this;
1879   Sections.push_back(MS);
1880 }
1881 
1882 template <class ELFT> void MergeSyntheticSection<ELFT>::writeTo(uint8_t *Buf) {
1883   Builder.write(Buf);
1884 }
1885 
1886 template <class ELFT>
1887 bool MergeSyntheticSection<ELFT>::shouldTailMerge() const {
1888   return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
1889 }
1890 
1891 template <class ELFT> void MergeSyntheticSection<ELFT>::finalizeTailMerge() {
1892   // Add all string pieces to the string table builder to create section
1893   // contents.
1894   for (MergeInputSection<ELFT> *Sec : Sections)
1895     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
1896       if (Sec->Pieces[I].Live)
1897         Builder.add(Sec->getData(I));
1898 
1899   // Fix the string table content. After this, the contents will never change.
1900   Builder.finalize();
1901 
1902   // finalize() fixed tail-optimized strings, so we can now get
1903   // offsets of strings. Get an offset for each string and save it
1904   // to a corresponding StringPiece for easy access.
1905   for (MergeInputSection<ELFT> *Sec : Sections)
1906     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
1907       if (Sec->Pieces[I].Live)
1908         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
1909 }
1910 
1911 template <class ELFT> void MergeSyntheticSection<ELFT>::finalizeNoTailMerge() {
1912   // Add all string pieces to the string table builder to create section
1913   // contents. Because we are not tail-optimizing, offsets of strings are
1914   // fixed when they are added to the builder (string table builder contains
1915   // a hash table from strings to offsets).
1916   for (MergeInputSection<ELFT> *Sec : Sections)
1917     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
1918       if (Sec->Pieces[I].Live)
1919         Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
1920 
1921   Builder.finalizeInOrder();
1922 }
1923 
1924 template <class ELFT> void MergeSyntheticSection<ELFT>::finalize() {
1925   if (Finalized)
1926     return;
1927   Finalized = true;
1928   if (shouldTailMerge())
1929     finalizeTailMerge();
1930   else
1931     finalizeNoTailMerge();
1932 }
1933 
1934 template <class ELFT> size_t MergeSyntheticSection<ELFT>::getSize() const {
1935   // We should finalize string builder to know the size.
1936   const_cast<MergeSyntheticSection<ELFT> *>(this)->finalize();
1937   return Builder.getSize();
1938 }
1939 
1940 template <class ELFT>
1941 MipsRldMapSection<ELFT>::MipsRldMapSection()
1942     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1943                              sizeof(typename ELFT::uint), ".rld_map") {}
1944 
1945 template <class ELFT> void MipsRldMapSection<ELFT>::writeTo(uint8_t *Buf) {
1946   // Apply filler from linker script.
1947   uint64_t Filler = Script<ELFT>::X->getFiller(this->Name);
1948   Filler = (Filler << 32) | Filler;
1949   memcpy(Buf, &Filler, getSize());
1950 }
1951 
1952 template <class ELFT>
1953 ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
1954     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
1955                              sizeof(typename ELFT::uint), ".ARM.exidx") {}
1956 
1957 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
1958 // This section will have been sorted last in the .ARM.exidx table.
1959 // This table entry will have the form:
1960 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
1961 template <class ELFT>
1962 void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf) {
1963   // Get the InputSection before us, we are by definition last
1964   auto RI = cast<OutputSection<ELFT>>(this->OutSec)->Sections.rbegin();
1965   InputSection<ELFT> *LE = *(++RI);
1966   InputSection<ELFT> *LC = cast<InputSection<ELFT>>(LE->getLinkOrderDep());
1967   uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
1968   uint64_t P = this->getVA();
1969   Target->relocateOne(Buf, R_ARM_PREL31, S - P);
1970   write32le(Buf + 4, 0x1);
1971 }
1972 
1973 template <class ELFT>
1974 ThunkSection<ELFT>::ThunkSection(OutputSectionBase *OS, uint64_t Off)
1975     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
1976                              sizeof(typename ELFT::uint), ".text.thunk") {
1977   this->OutSec = OS;
1978   this->OutSecOff = Off;
1979 }
1980 
1981 template <class ELFT> void ThunkSection<ELFT>::addThunk(Thunk<ELFT> *T) {
1982   uint64_t Off = alignTo(Size, T->alignment);
1983   T->Offset = Off;
1984   Thunks.push_back(T);
1985   T->addSymbols(*this);
1986   Size = Off + T->size();
1987 }
1988 
1989 template <class ELFT> void ThunkSection<ELFT>::writeTo(uint8_t *Buf) {
1990   for (const Thunk<ELFT> *T : Thunks)
1991     T->writeTo(Buf + T->Offset, *this);
1992 }
1993 
1994 template <class ELFT>
1995 InputSection<ELFT> *ThunkSection<ELFT>::getTargetInputSection() const {
1996   const Thunk<ELFT> *T = Thunks.front();
1997   return T->getTargetInputSection();
1998 }
1999 
2000 template InputSection<ELF32LE> *elf::createCommonSection();
2001 template InputSection<ELF32BE> *elf::createCommonSection();
2002 template InputSection<ELF64LE> *elf::createCommonSection();
2003 template InputSection<ELF64BE> *elf::createCommonSection();
2004 
2005 template InputSection<ELF32LE> *elf::createInterpSection();
2006 template InputSection<ELF32BE> *elf::createInterpSection();
2007 template InputSection<ELF64LE> *elf::createInterpSection();
2008 template InputSection<ELF64BE> *elf::createInterpSection();
2009 
2010 template MergeInputSection<ELF32LE> *elf::createCommentSection();
2011 template MergeInputSection<ELF32BE> *elf::createCommentSection();
2012 template MergeInputSection<ELF64LE> *elf::createCommentSection();
2013 template MergeInputSection<ELF64BE> *elf::createCommentSection();
2014 
2015 template SymbolBody *
2016 elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t, ELF32LE::uint,
2017                                 ELF32LE::uint, InputSectionBase<ELF32LE> *);
2018 template SymbolBody *
2019 elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t, ELF32BE::uint,
2020                                 ELF32BE::uint, InputSectionBase<ELF32BE> *);
2021 template SymbolBody *
2022 elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t, ELF64LE::uint,
2023                                 ELF64LE::uint, InputSectionBase<ELF64LE> *);
2024 template SymbolBody *
2025 elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t, ELF64BE::uint,
2026                                 ELF64BE::uint, InputSectionBase<ELF64BE> *);
2027 
2028 template class elf::MipsAbiFlagsSection<ELF32LE>;
2029 template class elf::MipsAbiFlagsSection<ELF32BE>;
2030 template class elf::MipsAbiFlagsSection<ELF64LE>;
2031 template class elf::MipsAbiFlagsSection<ELF64BE>;
2032 
2033 template class elf::MipsOptionsSection<ELF32LE>;
2034 template class elf::MipsOptionsSection<ELF32BE>;
2035 template class elf::MipsOptionsSection<ELF64LE>;
2036 template class elf::MipsOptionsSection<ELF64BE>;
2037 
2038 template class elf::MipsReginfoSection<ELF32LE>;
2039 template class elf::MipsReginfoSection<ELF32BE>;
2040 template class elf::MipsReginfoSection<ELF64LE>;
2041 template class elf::MipsReginfoSection<ELF64BE>;
2042 
2043 template class elf::BuildIdSection<ELF32LE>;
2044 template class elf::BuildIdSection<ELF32BE>;
2045 template class elf::BuildIdSection<ELF64LE>;
2046 template class elf::BuildIdSection<ELF64BE>;
2047 
2048 template class elf::CopyRelSection<ELF32LE>;
2049 template class elf::CopyRelSection<ELF32BE>;
2050 template class elf::CopyRelSection<ELF64LE>;
2051 template class elf::CopyRelSection<ELF64BE>;
2052 
2053 template class elf::GotSection<ELF32LE>;
2054 template class elf::GotSection<ELF32BE>;
2055 template class elf::GotSection<ELF64LE>;
2056 template class elf::GotSection<ELF64BE>;
2057 
2058 template class elf::MipsGotSection<ELF32LE>;
2059 template class elf::MipsGotSection<ELF32BE>;
2060 template class elf::MipsGotSection<ELF64LE>;
2061 template class elf::MipsGotSection<ELF64BE>;
2062 
2063 template class elf::GotPltSection<ELF32LE>;
2064 template class elf::GotPltSection<ELF32BE>;
2065 template class elf::GotPltSection<ELF64LE>;
2066 template class elf::GotPltSection<ELF64BE>;
2067 
2068 template class elf::IgotPltSection<ELF32LE>;
2069 template class elf::IgotPltSection<ELF32BE>;
2070 template class elf::IgotPltSection<ELF64LE>;
2071 template class elf::IgotPltSection<ELF64BE>;
2072 
2073 template class elf::StringTableSection<ELF32LE>;
2074 template class elf::StringTableSection<ELF32BE>;
2075 template class elf::StringTableSection<ELF64LE>;
2076 template class elf::StringTableSection<ELF64BE>;
2077 
2078 template class elf::DynamicSection<ELF32LE>;
2079 template class elf::DynamicSection<ELF32BE>;
2080 template class elf::DynamicSection<ELF64LE>;
2081 template class elf::DynamicSection<ELF64BE>;
2082 
2083 template class elf::RelocationSection<ELF32LE>;
2084 template class elf::RelocationSection<ELF32BE>;
2085 template class elf::RelocationSection<ELF64LE>;
2086 template class elf::RelocationSection<ELF64BE>;
2087 
2088 template class elf::SymbolTableSection<ELF32LE>;
2089 template class elf::SymbolTableSection<ELF32BE>;
2090 template class elf::SymbolTableSection<ELF64LE>;
2091 template class elf::SymbolTableSection<ELF64BE>;
2092 
2093 template class elf::GnuHashTableSection<ELF32LE>;
2094 template class elf::GnuHashTableSection<ELF32BE>;
2095 template class elf::GnuHashTableSection<ELF64LE>;
2096 template class elf::GnuHashTableSection<ELF64BE>;
2097 
2098 template class elf::HashTableSection<ELF32LE>;
2099 template class elf::HashTableSection<ELF32BE>;
2100 template class elf::HashTableSection<ELF64LE>;
2101 template class elf::HashTableSection<ELF64BE>;
2102 
2103 template class elf::PltSection<ELF32LE>;
2104 template class elf::PltSection<ELF32BE>;
2105 template class elf::PltSection<ELF64LE>;
2106 template class elf::PltSection<ELF64BE>;
2107 
2108 template class elf::GdbIndexSection<ELF32LE>;
2109 template class elf::GdbIndexSection<ELF32BE>;
2110 template class elf::GdbIndexSection<ELF64LE>;
2111 template class elf::GdbIndexSection<ELF64BE>;
2112 
2113 template class elf::EhFrameHeader<ELF32LE>;
2114 template class elf::EhFrameHeader<ELF32BE>;
2115 template class elf::EhFrameHeader<ELF64LE>;
2116 template class elf::EhFrameHeader<ELF64BE>;
2117 
2118 template class elf::VersionTableSection<ELF32LE>;
2119 template class elf::VersionTableSection<ELF32BE>;
2120 template class elf::VersionTableSection<ELF64LE>;
2121 template class elf::VersionTableSection<ELF64BE>;
2122 
2123 template class elf::VersionNeedSection<ELF32LE>;
2124 template class elf::VersionNeedSection<ELF32BE>;
2125 template class elf::VersionNeedSection<ELF64LE>;
2126 template class elf::VersionNeedSection<ELF64BE>;
2127 
2128 template class elf::VersionDefinitionSection<ELF32LE>;
2129 template class elf::VersionDefinitionSection<ELF32BE>;
2130 template class elf::VersionDefinitionSection<ELF64LE>;
2131 template class elf::VersionDefinitionSection<ELF64BE>;
2132 
2133 template class elf::MergeSyntheticSection<ELF32LE>;
2134 template class elf::MergeSyntheticSection<ELF32BE>;
2135 template class elf::MergeSyntheticSection<ELF64LE>;
2136 template class elf::MergeSyntheticSection<ELF64BE>;
2137 
2138 template class elf::MipsRldMapSection<ELF32LE>;
2139 template class elf::MipsRldMapSection<ELF32BE>;
2140 template class elf::MipsRldMapSection<ELF64LE>;
2141 template class elf::MipsRldMapSection<ELF64BE>;
2142 
2143 template class elf::ARMExidxSentinelSection<ELF32LE>;
2144 template class elf::ARMExidxSentinelSection<ELF32BE>;
2145 template class elf::ARMExidxSentinelSection<ELF64LE>;
2146 template class elf::ARMExidxSentinelSection<ELF64BE>;
2147 
2148 template class elf::ThunkSection<ELF32LE>;
2149 template class elf::ThunkSection<ELF32BE>;
2150 template class elf::ThunkSection<ELF64LE>;
2151 template class elf::ThunkSection<ELF64BE>;
2152