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