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> unsigned MipsGotSection<ELFT>::getGp() const {
614   return ElfSym<ELFT>::MipsGp->template getVA<ELFT>(0);
615 }
616 
617 template <class ELFT>
618 static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
619   typedef typename ELFT::uint uintX_t;
620   write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
621 }
622 
623 template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
624   // Set the MSB of the second GOT slot. This is not required by any
625   // MIPS ABI documentation, though.
626   //
627   // There is a comment in glibc saying that "The MSB of got[1] of a
628   // gnu object is set to identify gnu objects," and in GNU gold it
629   // says "the second entry will be used by some runtime loaders".
630   // But how this field is being used is unclear.
631   //
632   // We are not really willing to mimic other linkers behaviors
633   // without understanding why they do that, but because all files
634   // generated by GNU tools have this special GOT value, and because
635   // we've been doing this for years, it is probably a safe bet to
636   // keep doing this for now. We really need to revisit this to see
637   // if we had to do this.
638   auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
639   P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
640   Buf += HeaderEntriesNum * sizeof(uintX_t);
641   // Write 'page address' entries to the local part of the GOT.
642   for (std::pair<const OutputSectionBase *, size_t> &L : PageIndexMap) {
643     size_t PageCount = getMipsPageCount(L.first->Size);
644     uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
645     for (size_t PI = 0; PI < PageCount; ++PI) {
646       uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
647       writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
648     }
649   }
650   Buf += PageEntriesNum * sizeof(uintX_t);
651   auto AddEntry = [&](const GotEntry &SA) {
652     uint8_t *Entry = Buf;
653     Buf += sizeof(uintX_t);
654     const SymbolBody *Body = SA.first;
655     uintX_t VA = Body->template getVA<ELFT>(SA.second);
656     writeUint<ELFT>(Entry, VA);
657   };
658   std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
659   std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
660   std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
661   // Initialize TLS-related GOT entries. If the entry has a corresponding
662   // dynamic relocations, leave it initialized by zero. Write down adjusted
663   // TLS symbol's values otherwise. To calculate the adjustments use offsets
664   // for thread-local storage.
665   // https://www.linux-mips.org/wiki/NPTL
666   if (TlsIndexOff != -1U && !Config->Pic)
667     writeUint<ELFT>(Buf + TlsIndexOff, 1);
668   for (const SymbolBody *B : TlsEntries) {
669     if (!B || B->isPreemptible())
670       continue;
671     uintX_t VA = B->getVA<ELFT>();
672     if (B->GotIndex != -1U) {
673       uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
674       writeUint<ELFT>(Entry, VA - 0x7000);
675     }
676     if (B->GlobalDynIndex != -1U) {
677       uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
678       writeUint<ELFT>(Entry, 1);
679       Entry += sizeof(uintX_t);
680       writeUint<ELFT>(Entry, VA - 0x8000);
681     }
682   }
683 }
684 
685 template <class ELFT>
686 GotPltSection<ELFT>::GotPltSection()
687     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
688                              Target->GotPltEntrySize, ".got.plt") {}
689 
690 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
691   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
692   Entries.push_back(&Sym);
693 }
694 
695 template <class ELFT> size_t GotPltSection<ELFT>::getSize() const {
696   return (Target->GotPltHeaderEntriesNum + Entries.size()) *
697          Target->GotPltEntrySize;
698 }
699 
700 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
701   Target->writeGotPltHeader(Buf);
702   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
703   for (const SymbolBody *B : Entries) {
704     Target->writeGotPlt(Buf, *B);
705     Buf += sizeof(uintX_t);
706   }
707 }
708 
709 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
710 // part of the .got.plt
711 template <class ELFT>
712 IgotPltSection<ELFT>::IgotPltSection()
713     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
714                              Target->GotPltEntrySize,
715                              Config->EMachine == EM_ARM ? ".got" : ".got.plt") {
716 }
717 
718 template <class ELFT> void IgotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
719   Sym.IsInIgot = true;
720   Sym.GotPltIndex = Entries.size();
721   Entries.push_back(&Sym);
722 }
723 
724 template <class ELFT> size_t IgotPltSection<ELFT>::getSize() const {
725   return Entries.size() * Target->GotPltEntrySize;
726 }
727 
728 template <class ELFT> void IgotPltSection<ELFT>::writeTo(uint8_t *Buf) {
729   for (const SymbolBody *B : Entries) {
730     if (Config->EMachine == EM_ARM)
731       // On ARM we are actually part of the Got and not GotPlt.
732       write32le(Buf, B->getVA<ELFT>());
733     else
734       Target->writeGotPlt(Buf, *B);
735     Buf += sizeof(uintX_t);
736   }
737 }
738 
739 template <class ELFT>
740 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
741     : SyntheticSection<ELFT>(Dynamic ? (uintX_t)SHF_ALLOC : 0, SHT_STRTAB, 1,
742                              Name),
743       Dynamic(Dynamic) {}
744 
745 // Adds a string to the string table. If HashIt is true we hash and check for
746 // duplicates. It is optional because the name of global symbols are already
747 // uniqued and hashing them again has a big cost for a small value: uniquing
748 // them with some other string that happens to be the same.
749 template <class ELFT>
750 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
751   if (HashIt) {
752     auto R = StringMap.insert(std::make_pair(S, this->Size));
753     if (!R.second)
754       return R.first->second;
755   }
756   unsigned Ret = this->Size;
757   this->Size = this->Size + S.size() + 1;
758   Strings.push_back(S);
759   return Ret;
760 }
761 
762 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
763   // ELF string tables start with NUL byte, so advance the pointer by one.
764   ++Buf;
765   for (StringRef S : Strings) {
766     memcpy(Buf, S.data(), S.size());
767     Buf += S.size() + 1;
768   }
769 }
770 
771 // Returns the number of version definition entries. Because the first entry
772 // is for the version definition itself, it is the number of versioned symbols
773 // plus one. Note that we don't support multiple versions yet.
774 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
775 
776 template <class ELFT>
777 DynamicSection<ELFT>::DynamicSection()
778     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC,
779                              sizeof(uintX_t), ".dynamic") {
780   this->Entsize = ELFT::Is64Bits ? 16 : 8;
781   // .dynamic section is not writable on MIPS.
782   // See "Special Section" in Chapter 4 in the following document:
783   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
784   if (Config->EMachine == EM_MIPS)
785     this->Flags = SHF_ALLOC;
786 
787   addEntries();
788 }
789 
790 // There are some dynamic entries that don't depend on other sections.
791 // Such entries can be set early.
792 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
793   // Add strings to .dynstr early so that .dynstr's size will be
794   // fixed early.
795   for (StringRef S : Config->AuxiliaryList)
796     add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
797   if (!Config->RPath.empty())
798     add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
799          In<ELFT>::DynStrTab->addString(Config->RPath)});
800   for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
801     if (F->isNeeded())
802       add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
803   if (!Config->SoName.empty())
804     add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
805 
806   // Set DT_FLAGS and DT_FLAGS_1.
807   uint32_t DtFlags = 0;
808   uint32_t DtFlags1 = 0;
809   if (Config->Bsymbolic)
810     DtFlags |= DF_SYMBOLIC;
811   if (Config->ZNodelete)
812     DtFlags1 |= DF_1_NODELETE;
813   if (Config->ZNow) {
814     DtFlags |= DF_BIND_NOW;
815     DtFlags1 |= DF_1_NOW;
816   }
817   if (Config->ZOrigin) {
818     DtFlags |= DF_ORIGIN;
819     DtFlags1 |= DF_1_ORIGIN;
820   }
821 
822   if (DtFlags)
823     add({DT_FLAGS, DtFlags});
824   if (DtFlags1)
825     add({DT_FLAGS_1, DtFlags1});
826 
827   if (!Config->Shared && !Config->Relocatable)
828     add({DT_DEBUG, (uint64_t)0});
829 }
830 
831 // Add remaining entries to complete .dynamic contents.
832 template <class ELFT> void DynamicSection<ELFT>::finalize() {
833   if (this->Size)
834     return; // Already finalized.
835 
836   this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
837   if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
838     bool IsRela = Config->Rela;
839     add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
840     add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
841     add({IsRela ? DT_RELAENT : DT_RELENT,
842          uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
843 
844     // MIPS dynamic loader does not support RELCOUNT tag.
845     // The problem is in the tight relation between dynamic
846     // relocations and GOT. So do not emit this tag on MIPS.
847     if (Config->EMachine != EM_MIPS) {
848       size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
849       if (Config->ZCombreloc && NumRelativeRels)
850         add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
851     }
852   }
853   if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
854     add({DT_JMPREL, In<ELFT>::RelaPlt});
855     add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
856     add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
857          In<ELFT>::GotPlt});
858     add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
859   }
860 
861   add({DT_SYMTAB, In<ELFT>::DynSymTab});
862   add({DT_SYMENT, sizeof(Elf_Sym)});
863   add({DT_STRTAB, In<ELFT>::DynStrTab});
864   add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
865   if (In<ELFT>::GnuHashTab)
866     add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
867   if (In<ELFT>::HashTab)
868     add({DT_HASH, In<ELFT>::HashTab});
869 
870   if (Out<ELFT>::PreinitArray) {
871     add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
872     add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
873   }
874   if (Out<ELFT>::InitArray) {
875     add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
876     add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
877   }
878   if (Out<ELFT>::FiniArray) {
879     add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
880     add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
881   }
882 
883   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
884     add({DT_INIT, B});
885   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
886     add({DT_FINI, B});
887 
888   bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
889   if (HasVerNeed || In<ELFT>::VerDef)
890     add({DT_VERSYM, In<ELFT>::VerSym});
891   if (In<ELFT>::VerDef) {
892     add({DT_VERDEF, In<ELFT>::VerDef});
893     add({DT_VERDEFNUM, getVerDefNum()});
894   }
895   if (HasVerNeed) {
896     add({DT_VERNEED, In<ELFT>::VerNeed});
897     add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
898   }
899 
900   if (Config->EMachine == EM_MIPS) {
901     add({DT_MIPS_RLD_VERSION, 1});
902     add({DT_MIPS_FLAGS, RHF_NOTPOT});
903     add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
904     add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
905     add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
906     if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
907       add({DT_MIPS_GOTSYM, B->DynsymIndex});
908     else
909       add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
910     add({DT_PLTGOT, In<ELFT>::MipsGot});
911     if (In<ELFT>::MipsRldMap)
912       add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
913   }
914 
915   this->OutSec->Entsize = this->Entsize;
916   this->OutSec->Link = this->Link;
917 
918   // +1 for DT_NULL
919   this->Size = (Entries.size() + 1) * this->Entsize;
920 }
921 
922 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
923   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
924 
925   for (const Entry &E : Entries) {
926     P->d_tag = E.Tag;
927     switch (E.Kind) {
928     case Entry::SecAddr:
929       P->d_un.d_ptr = E.OutSec->Addr;
930       break;
931     case Entry::InSecAddr:
932       P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
933       break;
934     case Entry::SecSize:
935       P->d_un.d_val = E.OutSec->Size;
936       break;
937     case Entry::SymAddr:
938       P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
939       break;
940     case Entry::PlainInt:
941       P->d_un.d_val = E.Val;
942       break;
943     }
944     ++P;
945   }
946 }
947 
948 template <class ELFT>
949 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
950   if (OutputSec)
951     return OutputSec->Addr + OffsetInSec;
952   return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
953 }
954 
955 template <class ELFT>
956 typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
957   if (UseSymVA)
958     return Sym->getVA<ELFT>(Addend);
959   return Addend;
960 }
961 
962 template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
963   if (Sym && !UseSymVA)
964     return Sym->DynsymIndex;
965   return 0;
966 }
967 
968 template <class ELFT>
969 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
970     : SyntheticSection<ELFT>(SHF_ALLOC, Config->Rela ? SHT_RELA : SHT_REL,
971                              sizeof(uintX_t), Name),
972       Sort(Sort) {
973   this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
974 }
975 
976 template <class ELFT>
977 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
978   if (Reloc.Type == Target->RelativeRel)
979     ++NumRelativeRelocs;
980   Relocs.push_back(Reloc);
981 }
982 
983 template <class ELFT, class RelTy>
984 static bool compRelocations(const RelTy &A, const RelTy &B) {
985   bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
986   bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
987   if (AIsRel != BIsRel)
988     return AIsRel;
989 
990   return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
991 }
992 
993 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
994   uint8_t *BufBegin = Buf;
995   for (const DynamicReloc<ELFT> &Rel : Relocs) {
996     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
997     Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
998 
999     if (Config->Rela)
1000       P->r_addend = Rel.getAddend();
1001     P->r_offset = Rel.getOffset();
1002     if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
1003       // Dynamic relocation against MIPS GOT section make deal TLS entries
1004       // allocated in the end of the GOT. We need to adjust the offset to take
1005       // in account 'local' and 'global' GOT entries.
1006       P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
1007     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
1008   }
1009 
1010   if (Sort) {
1011     if (Config->Rela)
1012       std::stable_sort((Elf_Rela *)BufBegin,
1013                        (Elf_Rela *)BufBegin + Relocs.size(),
1014                        compRelocations<ELFT, Elf_Rela>);
1015     else
1016       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1017                        compRelocations<ELFT, Elf_Rel>);
1018   }
1019 }
1020 
1021 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1022   return this->Entsize * Relocs.size();
1023 }
1024 
1025 template <class ELFT> void RelocationSection<ELFT>::finalize() {
1026   this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1027                                    : In<ELFT>::SymTab->OutSec->SectionIndex;
1028 
1029   // Set required output section properties.
1030   this->OutSec->Link = this->Link;
1031   this->OutSec->Entsize = this->Entsize;
1032 }
1033 
1034 template <class ELFT>
1035 SymbolTableSection<ELFT>::SymbolTableSection(
1036     StringTableSection<ELFT> &StrTabSec)
1037     : SyntheticSection<ELFT>(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1038                              StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1039                              sizeof(uintX_t),
1040                              StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1041       StrTabSec(StrTabSec) {
1042   this->Entsize = sizeof(Elf_Sym);
1043 }
1044 
1045 // Orders symbols according to their positions in the GOT,
1046 // in compliance with MIPS ABI rules.
1047 // See "Global Offset Table" in Chapter 5 in the following document
1048 // for detailed description:
1049 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1050 static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
1051   // Sort entries related to non-local preemptible symbols by GOT indexes.
1052   // All other entries go to the first part of GOT in arbitrary order.
1053   bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1054   bool RIsInLocalGot = !R->IsInGlobalMipsGot;
1055   if (LIsInLocalGot || RIsInLocalGot)
1056     return !RIsInLocalGot;
1057   return L->GotIndex < R->GotIndex;
1058 }
1059 
1060 static uint8_t getSymbolBinding(SymbolBody *Body) {
1061   Symbol *S = Body->symbol();
1062   if (Config->Relocatable)
1063     return S->Binding;
1064   uint8_t Visibility = S->Visibility;
1065   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1066     return STB_LOCAL;
1067   if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
1068     return STB_GLOBAL;
1069   return S->Binding;
1070 }
1071 
1072 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1073   this->OutSec->Link = this->Link = StrTabSec.OutSec->SectionIndex;
1074   this->OutSec->Info = this->Info = NumLocals + 1;
1075   this->OutSec->Entsize = this->Entsize;
1076 
1077   if (Config->Relocatable) {
1078     size_t I = NumLocals;
1079     for (const SymbolTableEntry &S : Symbols)
1080       S.Symbol->DynsymIndex = ++I;
1081     return;
1082   }
1083 
1084   if (!StrTabSec.isDynamic()) {
1085     std::stable_sort(Symbols.begin(), Symbols.end(),
1086                      [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1087                        return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1088                               getSymbolBinding(R.Symbol) != STB_LOCAL;
1089                      });
1090     return;
1091   }
1092   if (In<ELFT>::GnuHashTab)
1093     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1094     In<ELFT>::GnuHashTab->addSymbols(Symbols);
1095   else if (Config->EMachine == EM_MIPS)
1096     std::stable_sort(Symbols.begin(), Symbols.end(),
1097                      [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1098                        return sortMipsSymbols(L.Symbol, R.Symbol);
1099                      });
1100   size_t I = 0;
1101   for (const SymbolTableEntry &S : Symbols)
1102     S.Symbol->DynsymIndex = ++I;
1103 }
1104 
1105 template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1106   Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1107 }
1108 
1109 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1110   Buf += sizeof(Elf_Sym);
1111 
1112   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1113   // .dynsym only contains global symbols.
1114   if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1115     writeLocalSymbols(Buf);
1116 
1117   writeGlobalSymbols(Buf);
1118 }
1119 
1120 template <class ELFT>
1121 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1122   // Iterate over all input object files to copy their local symbols
1123   // to the output symbol table pointed by Buf.
1124   for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
1125     for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1126          File->KeptLocalSyms) {
1127       const DefinedRegular<ELFT> &Body = *P.first;
1128       InputSectionBase<ELFT> *Section = Body.Section;
1129       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1130 
1131       if (!Section) {
1132         ESym->st_shndx = SHN_ABS;
1133         ESym->st_value = Body.Value;
1134       } else {
1135         const OutputSectionBase *OutSec = Section->OutSec;
1136         ESym->st_shndx = OutSec->SectionIndex;
1137         ESym->st_value = OutSec->Addr + Section->getOffset(Body);
1138       }
1139       ESym->st_name = P.second;
1140       ESym->st_size = Body.template getSize<ELFT>();
1141       ESym->setBindingAndType(STB_LOCAL, Body.Type);
1142       Buf += sizeof(*ESym);
1143     }
1144   }
1145 }
1146 
1147 template <class ELFT>
1148 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1149   // Write the internal symbol table contents to the output symbol table
1150   // pointed by Buf.
1151   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1152   for (const SymbolTableEntry &S : Symbols) {
1153     SymbolBody *Body = S.Symbol;
1154     size_t StrOff = S.StrTabOffset;
1155 
1156     uint8_t Type = Body->Type;
1157     uintX_t Size = Body->getSize<ELFT>();
1158 
1159     ESym->setBindingAndType(getSymbolBinding(Body), Type);
1160     ESym->st_size = Size;
1161     ESym->st_name = StrOff;
1162     ESym->setVisibility(Body->symbol()->Visibility);
1163     ESym->st_value = Body->getVA<ELFT>();
1164 
1165     if (const OutputSectionBase *OutSec = getOutputSection(Body))
1166       ESym->st_shndx = OutSec->SectionIndex;
1167     else if (isa<DefinedRegular<ELFT>>(Body))
1168       ESym->st_shndx = SHN_ABS;
1169 
1170     if (Config->EMachine == EM_MIPS) {
1171       // On MIPS we need to mark symbol which has a PLT entry and requires
1172       // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1173       // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1174       // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1175       if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1176         ESym->st_other |= STO_MIPS_PLT;
1177       if (Config->Relocatable) {
1178         auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1179         if (D && D->isMipsPIC())
1180           ESym->st_other |= STO_MIPS_PIC;
1181       }
1182     }
1183     ++ESym;
1184   }
1185 }
1186 
1187 template <class ELFT>
1188 const OutputSectionBase *
1189 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1190   switch (Sym->kind()) {
1191   case SymbolBody::DefinedSyntheticKind:
1192     return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1193   case SymbolBody::DefinedRegularKind: {
1194     auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1195     if (D.Section)
1196       return D.Section->OutSec;
1197     break;
1198   }
1199   case SymbolBody::DefinedCommonKind:
1200     return In<ELFT>::Common->OutSec;
1201   case SymbolBody::SharedKind:
1202     if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1203       return Out<ELFT>::Bss;
1204     break;
1205   case SymbolBody::UndefinedKind:
1206   case SymbolBody::LazyArchiveKind:
1207   case SymbolBody::LazyObjectKind:
1208     break;
1209   }
1210   return nullptr;
1211 }
1212 
1213 template <class ELFT>
1214 GnuHashTableSection<ELFT>::GnuHashTableSection()
1215     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t),
1216                              ".gnu.hash") {
1217   this->Entsize = ELFT::Is64Bits ? 0 : 4;
1218 }
1219 
1220 template <class ELFT>
1221 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
1222   if (!NumHashed)
1223     return 0;
1224 
1225   // These values are prime numbers which are not greater than 2^(N-1) + 1.
1226   // In result, for any particular NumHashed we return a prime number
1227   // which is not greater than NumHashed.
1228   static const unsigned Primes[] = {
1229       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
1230       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
1231 
1232   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
1233                                    array_lengthof(Primes) - 1)];
1234 }
1235 
1236 // Bloom filter estimation: at least 8 bits for each hashed symbol.
1237 // GNU Hash table requirement: it should be a power of 2,
1238 //   the minimum value is 1, even for an empty table.
1239 // Expected results for a 32-bit target:
1240 //   calcMaskWords(0..4)   = 1
1241 //   calcMaskWords(5..8)   = 2
1242 //   calcMaskWords(9..16)  = 4
1243 // For a 64-bit target:
1244 //   calcMaskWords(0..8)   = 1
1245 //   calcMaskWords(9..16)  = 2
1246 //   calcMaskWords(17..32) = 4
1247 template <class ELFT>
1248 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
1249   if (!NumHashed)
1250     return 1;
1251   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
1252 }
1253 
1254 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
1255   unsigned NumHashed = Symbols.size();
1256   NBuckets = calcNBuckets(NumHashed);
1257   MaskWords = calcMaskWords(NumHashed);
1258   // Second hash shift estimation: just predefined values.
1259   Shift2 = ELFT::Is64Bits ? 6 : 5;
1260 
1261   this->OutSec->Entsize = this->Entsize;
1262   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1263   this->Size = sizeof(Elf_Word) * 4            // Header
1264                + sizeof(Elf_Off) * MaskWords   // Bloom Filter
1265                + sizeof(Elf_Word) * NBuckets   // Hash Buckets
1266                + sizeof(Elf_Word) * NumHashed; // Hash Values
1267 }
1268 
1269 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1270   writeHeader(Buf);
1271   if (Symbols.empty())
1272     return;
1273   writeBloomFilter(Buf);
1274   writeHashTable(Buf);
1275 }
1276 
1277 template <class ELFT>
1278 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
1279   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1280   *P++ = NBuckets;
1281   *P++ = In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
1282   *P++ = MaskWords;
1283   *P++ = Shift2;
1284   Buf = reinterpret_cast<uint8_t *>(P);
1285 }
1286 
1287 template <class ELFT>
1288 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
1289   unsigned C = sizeof(Elf_Off) * 8;
1290 
1291   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
1292   for (const SymbolData &Sym : Symbols) {
1293     size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
1294     uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
1295                 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
1296     Masks[Pos] |= V;
1297   }
1298   Buf += sizeof(Elf_Off) * MaskWords;
1299 }
1300 
1301 template <class ELFT>
1302 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
1303   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1304   Elf_Word *Values = Buckets + NBuckets;
1305 
1306   int PrevBucket = -1;
1307   int I = 0;
1308   for (const SymbolData &Sym : Symbols) {
1309     int Bucket = Sym.Hash % NBuckets;
1310     assert(PrevBucket <= Bucket);
1311     if (Bucket != PrevBucket) {
1312       Buckets[Bucket] = Sym.Body->DynsymIndex;
1313       PrevBucket = Bucket;
1314       if (I > 0)
1315         Values[I - 1] |= 1;
1316     }
1317     Values[I] = Sym.Hash & ~1;
1318     ++I;
1319   }
1320   if (I > 0)
1321     Values[I - 1] |= 1;
1322 }
1323 
1324 static uint32_t hashGnu(StringRef Name) {
1325   uint32_t H = 5381;
1326   for (uint8_t C : Name)
1327     H = (H << 5) + H + C;
1328   return H;
1329 }
1330 
1331 // Add symbols to this symbol hash table. Note that this function
1332 // destructively sort a given vector -- which is needed because
1333 // GNU-style hash table places some sorting requirements.
1334 template <class ELFT>
1335 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
1336   // Ideally this will just be 'auto' but GCC 6.1 is not able
1337   // to deduce it correctly.
1338   std::vector<SymbolTableEntry>::iterator Mid =
1339       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1340         return S.Symbol->isUndefined();
1341       });
1342   if (Mid == V.end())
1343     return;
1344   for (auto I = Mid, E = V.end(); I != E; ++I) {
1345     SymbolBody *B = I->Symbol;
1346     size_t StrOff = I->StrTabOffset;
1347     Symbols.push_back({B, StrOff, hashGnu(B->getName())});
1348   }
1349 
1350   unsigned NBuckets = calcNBuckets(Symbols.size());
1351   std::stable_sort(Symbols.begin(), Symbols.end(),
1352                    [&](const SymbolData &L, const SymbolData &R) {
1353                      return L.Hash % NBuckets < R.Hash % NBuckets;
1354                    });
1355 
1356   V.erase(Mid, V.end());
1357   for (const SymbolData &Sym : Symbols)
1358     V.push_back({Sym.Body, Sym.STName});
1359 }
1360 
1361 template <class ELFT>
1362 HashTableSection<ELFT>::HashTableSection()
1363     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_HASH, sizeof(Elf_Word), ".hash") {
1364   this->Entsize = sizeof(Elf_Word);
1365 }
1366 
1367 template <class ELFT> void HashTableSection<ELFT>::finalize() {
1368   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1369   this->OutSec->Entsize = this->Entsize;
1370 
1371   unsigned NumEntries = 2;                            // nbucket and nchain.
1372   NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1373 
1374   // Create as many buckets as there are symbols.
1375   // FIXME: This is simplistic. We can try to optimize it, but implementing
1376   // support for SHT_GNU_HASH is probably even more profitable.
1377   NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
1378   this->Size = NumEntries * sizeof(Elf_Word);
1379 }
1380 
1381 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1382   unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
1383   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1384   *P++ = NumSymbols; // nbucket
1385   *P++ = NumSymbols; // nchain
1386 
1387   Elf_Word *Buckets = P;
1388   Elf_Word *Chains = P + NumSymbols;
1389 
1390   for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1391     SymbolBody *Body = S.Symbol;
1392     StringRef Name = Body->getName();
1393     unsigned I = Body->DynsymIndex;
1394     uint32_t Hash = hashSysV(Name) % NumSymbols;
1395     Chains[I] = Buckets[Hash];
1396     Buckets[Hash] = I;
1397   }
1398 }
1399 
1400 template <class ELFT>
1401 PltSection<ELFT>::PltSection()
1402     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1403                              ".plt") {}
1404 
1405 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
1406   // At beginning of PLT, we have code to call the dynamic linker
1407   // to resolve dynsyms at runtime. Write such code.
1408   Target->writePltHeader(Buf);
1409   size_t Off = Target->PltHeaderSize;
1410 
1411   for (auto &I : Entries) {
1412     const SymbolBody *B = I.first;
1413     unsigned RelOff = I.second;
1414     uint64_t Got = B->getGotPltVA<ELFT>();
1415     uint64_t Plt = this->getVA() + Off;
1416     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1417     Off += Target->PltEntrySize;
1418   }
1419 }
1420 
1421 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
1422   Sym.PltIndex = Entries.size();
1423   unsigned RelOff = In<ELFT>::RelaPlt->getRelocOffset();
1424   Entries.push_back(std::make_pair(&Sym, RelOff));
1425 }
1426 
1427 template <class ELFT> size_t PltSection<ELFT>::getSize() const {
1428   return Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
1429 }
1430 
1431 template <class ELFT>
1432 IpltSection<ELFT>::IpltSection()
1433     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1434                              ".plt") {}
1435 
1436 template <class ELFT> void IpltSection<ELFT>::writeTo(uint8_t *Buf) {
1437   // The IRelative relocations do not support lazy binding so no header is
1438   // needed
1439   size_t Off = 0;
1440   for (auto &I : Entries) {
1441     const SymbolBody *B = I.first;
1442     unsigned RelOff = I.second + In<ELFT>::Plt->getSize();
1443     uint64_t Got = B->getGotPltVA<ELFT>();
1444     uint64_t Plt = this->getVA() + Off;
1445     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1446     Off += Target->PltEntrySize;
1447   }
1448 }
1449 
1450 template <class ELFT> void IpltSection<ELFT>::addEntry(SymbolBody &Sym) {
1451   Sym.PltIndex = Entries.size();
1452   Sym.IsInIplt = true;
1453   unsigned RelOff = In<ELFT>::RelaIplt->getRelocOffset();
1454   Entries.push_back(std::make_pair(&Sym, RelOff));
1455 }
1456 
1457 template <class ELFT> size_t IpltSection<ELFT>::getSize() const {
1458   return Entries.size() * Target->PltEntrySize;
1459 }
1460 
1461 template <class ELFT>
1462 GdbIndexSection<ELFT>::GdbIndexSection()
1463     : SyntheticSection<ELFT>(0, SHT_PROGBITS, 1, ".gdb_index") {}
1464 
1465 template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
1466   std::vector<InputSection<ELFT> *> &IS =
1467       static_cast<OutputSection<ELFT> *>(Out<ELFT>::DebugInfo)->Sections;
1468 
1469   for (InputSection<ELFT> *I : IS)
1470     readDwarf(I);
1471 }
1472 
1473 template <class ELFT>
1474 void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
1475   std::vector<std::pair<uintX_t, uintX_t>> CuList = readCuList(I);
1476   CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
1477 }
1478 
1479 template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
1480   parseDebugSections();
1481 
1482   // GdbIndex header consist from version fields
1483   // and 5 more fields with different kinds of offsets.
1484   CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1485 }
1486 
1487 template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
1488   write32le(Buf, 7);                  // Write Version
1489   write32le(Buf + 4, CuListOffset);   // CU list offset
1490   write32le(Buf + 8, CuTypesOffset);  // Types CU list offset
1491   write32le(Buf + 12, CuTypesOffset); // Address area offset
1492   write32le(Buf + 16, CuTypesOffset); // Symbol table offset
1493   write32le(Buf + 20, CuTypesOffset); // Constant pool offset
1494   Buf += 24;
1495 
1496   // Write the CU list.
1497   for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1498     write64le(Buf, CU.first);
1499     write64le(Buf + 8, CU.second);
1500     Buf += 16;
1501   }
1502 }
1503 
1504 template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
1505   return !Out<ELFT>::DebugInfo;
1506 }
1507 
1508 template <class ELFT>
1509 EhFrameHeader<ELFT>::EhFrameHeader()
1510     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1511 
1512 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1513 // Each entry of the search table consists of two values,
1514 // the starting PC from where FDEs covers, and the FDE's address.
1515 // It is sorted by PC.
1516 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1517   const endianness E = ELFT::TargetEndianness;
1518 
1519   // Sort the FDE list by their PC and uniqueify. Usually there is only
1520   // one FDE for a PC (i.e. function), but if ICF merges two functions
1521   // into one, there can be more than one FDEs pointing to the address.
1522   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1523   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1524   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1525   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1526 
1527   Buf[0] = 1;
1528   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1529   Buf[2] = DW_EH_PE_udata4;
1530   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1531   write32<E>(Buf + 4, Out<ELFT>::EhFrame->Addr - this->getVA() - 4);
1532   write32<E>(Buf + 8, Fdes.size());
1533   Buf += 12;
1534 
1535   uintX_t VA = this->getVA();
1536   for (FdeData &Fde : Fdes) {
1537     write32<E>(Buf, Fde.Pc - VA);
1538     write32<E>(Buf + 4, Fde.FdeVA - VA);
1539     Buf += 8;
1540   }
1541 }
1542 
1543 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1544   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1545   return 12 + Out<ELFT>::EhFrame->NumFdes * 8;
1546 }
1547 
1548 template <class ELFT>
1549 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1550   Fdes.push_back({Pc, FdeVA});
1551 }
1552 
1553 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1554   return Out<ELFT>::EhFrame->empty();
1555 }
1556 
1557 template <class ELFT>
1558 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1559     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1560                              ".gnu.version_d") {}
1561 
1562 static StringRef getFileDefName() {
1563   if (!Config->SoName.empty())
1564     return Config->SoName;
1565   return Config->OutputFile;
1566 }
1567 
1568 template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1569   FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1570   for (VersionDefinition &V : Config->VersionDefinitions)
1571     V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1572 
1573   this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1574 
1575   // sh_info should be set to the number of definitions. This fact is missed in
1576   // documentation, but confirmed by binutils community:
1577   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1578   this->OutSec->Info = this->Info = getVerDefNum();
1579 }
1580 
1581 template <class ELFT>
1582 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1583                                               StringRef Name, size_t NameOff) {
1584   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1585   Verdef->vd_version = 1;
1586   Verdef->vd_cnt = 1;
1587   Verdef->vd_aux = sizeof(Elf_Verdef);
1588   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1589   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1590   Verdef->vd_ndx = Index;
1591   Verdef->vd_hash = hashSysV(Name);
1592 
1593   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1594   Verdaux->vda_name = NameOff;
1595   Verdaux->vda_next = 0;
1596 }
1597 
1598 template <class ELFT>
1599 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1600   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1601 
1602   for (VersionDefinition &V : Config->VersionDefinitions) {
1603     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1604     writeOne(Buf, V.Id, V.Name, V.NameOff);
1605   }
1606 
1607   // Need to terminate the last version definition.
1608   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1609   Verdef->vd_next = 0;
1610 }
1611 
1612 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1613   return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1614 }
1615 
1616 template <class ELFT>
1617 VersionTableSection<ELFT>::VersionTableSection()
1618     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1619                              ".gnu.version") {}
1620 
1621 template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1622   this->OutSec->Entsize = this->Entsize = sizeof(Elf_Versym);
1623   // At the moment of june 2016 GNU docs does not mention that sh_link field
1624   // should be set, but Sun docs do. Also readelf relies on this field.
1625   this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1626 }
1627 
1628 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
1629   return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
1630 }
1631 
1632 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1633   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1634   for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1635     OutVersym->vs_index = S.Symbol->symbol()->VersionId;
1636     ++OutVersym;
1637   }
1638 }
1639 
1640 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
1641   return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
1642 }
1643 
1644 template <class ELFT>
1645 VersionNeedSection<ELFT>::VersionNeedSection()
1646     : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
1647                              ".gnu.version_r") {
1648   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1649   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1650   // First identifiers are reserved by verdef section if it exist.
1651   NextIndex = getVerDefNum() + 1;
1652 }
1653 
1654 template <class ELFT>
1655 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1656   if (!SS->Verdef) {
1657     SS->symbol()->VersionId = VER_NDX_GLOBAL;
1658     return;
1659   }
1660   SharedFile<ELFT> *F = SS->file();
1661   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1662   // to create one by adding it to our needed list and creating a dynstr entry
1663   // for the soname.
1664   if (F->VerdefMap.empty())
1665     Needed.push_back({F, In<ELFT>::DynStrTab->addString(F->getSoName())});
1666   typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1667   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1668   // prepare to create one by allocating a version identifier and creating a
1669   // dynstr entry for the version name.
1670   if (NV.Index == 0) {
1671     NV.StrTab = In<ELFT>::DynStrTab->addString(
1672         SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1673     NV.Index = NextIndex++;
1674   }
1675   SS->symbol()->VersionId = NV.Index;
1676 }
1677 
1678 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1679   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1680   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1681   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1682 
1683   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1684     // Create an Elf_Verneed for this DSO.
1685     Verneed->vn_version = 1;
1686     Verneed->vn_cnt = P.first->VerdefMap.size();
1687     Verneed->vn_file = P.second;
1688     Verneed->vn_aux =
1689         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1690     Verneed->vn_next = sizeof(Elf_Verneed);
1691     ++Verneed;
1692 
1693     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1694     // VerdefMap, which will only contain references to needed version
1695     // definitions. Each Elf_Vernaux is based on the information contained in
1696     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1697     // pointers, but is deterministic because the pointers refer to Elf_Verdef
1698     // data structures within a single input file.
1699     for (auto &NV : P.first->VerdefMap) {
1700       Vernaux->vna_hash = NV.first->vd_hash;
1701       Vernaux->vna_flags = 0;
1702       Vernaux->vna_other = NV.second.Index;
1703       Vernaux->vna_name = NV.second.StrTab;
1704       Vernaux->vna_next = sizeof(Elf_Vernaux);
1705       ++Vernaux;
1706     }
1707 
1708     Vernaux[-1].vna_next = 0;
1709   }
1710   Verneed[-1].vn_next = 0;
1711 }
1712 
1713 template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1714   this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1715   this->OutSec->Info = this->Info = Needed.size();
1716 }
1717 
1718 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
1719   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1720   for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1721     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1722   return Size;
1723 }
1724 
1725 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
1726   return getNeedNum() == 0;
1727 }
1728 
1729 template <class ELFT>
1730 MipsRldMapSection<ELFT>::MipsRldMapSection()
1731     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1732                              sizeof(typename ELFT::uint), ".rld_map") {}
1733 
1734 template <class ELFT> void MipsRldMapSection<ELFT>::writeTo(uint8_t *Buf) {
1735   // Apply filler from linker script.
1736   uint64_t Filler = Script<ELFT>::X->getFiller(this->Name);
1737   Filler = (Filler << 32) | Filler;
1738   memcpy(Buf, &Filler, getSize());
1739 }
1740 
1741 template <class ELFT>
1742 ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
1743     : SyntheticSection<ELFT>(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
1744                              sizeof(typename ELFT::uint), ".ARM.exidx") {}
1745 
1746 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
1747 // This section will have been sorted last in the .ARM.exidx table.
1748 // This table entry will have the form:
1749 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
1750 template <class ELFT> void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf){
1751   // Get the InputSection before us, we are by definition last
1752   auto RI = cast<OutputSection<ELFT>>(this->OutSec)->Sections.rbegin();
1753   InputSection<ELFT> *LE = *(++RI);
1754   InputSection<ELFT> *LC = cast<InputSection<ELFT>>(LE->getLinkOrderDep());
1755   uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
1756   uint64_t P = this->getVA();
1757   Target->relocateOne(Buf, R_ARM_PREL31, S - P);
1758   write32le(Buf + 4, 0x1);
1759 }
1760 
1761 template InputSection<ELF32LE> *elf::createCommonSection();
1762 template InputSection<ELF32BE> *elf::createCommonSection();
1763 template InputSection<ELF64LE> *elf::createCommonSection();
1764 template InputSection<ELF64BE> *elf::createCommonSection();
1765 
1766 template InputSection<ELF32LE> *elf::createInterpSection();
1767 template InputSection<ELF32BE> *elf::createInterpSection();
1768 template InputSection<ELF64LE> *elf::createInterpSection();
1769 template InputSection<ELF64BE> *elf::createInterpSection();
1770 
1771 template MergeInputSection<ELF32LE> *elf::createCommentSection();
1772 template MergeInputSection<ELF32BE> *elf::createCommentSection();
1773 template MergeInputSection<ELF64LE> *elf::createCommentSection();
1774 template MergeInputSection<ELF64BE> *elf::createCommentSection();
1775 
1776 template class elf::MipsAbiFlagsSection<ELF32LE>;
1777 template class elf::MipsAbiFlagsSection<ELF32BE>;
1778 template class elf::MipsAbiFlagsSection<ELF64LE>;
1779 template class elf::MipsAbiFlagsSection<ELF64BE>;
1780 
1781 template class elf::MipsOptionsSection<ELF32LE>;
1782 template class elf::MipsOptionsSection<ELF32BE>;
1783 template class elf::MipsOptionsSection<ELF64LE>;
1784 template class elf::MipsOptionsSection<ELF64BE>;
1785 
1786 template class elf::MipsReginfoSection<ELF32LE>;
1787 template class elf::MipsReginfoSection<ELF32BE>;
1788 template class elf::MipsReginfoSection<ELF64LE>;
1789 template class elf::MipsReginfoSection<ELF64BE>;
1790 
1791 template class elf::BuildIdSection<ELF32LE>;
1792 template class elf::BuildIdSection<ELF32BE>;
1793 template class elf::BuildIdSection<ELF64LE>;
1794 template class elf::BuildIdSection<ELF64BE>;
1795 
1796 template class elf::GotSection<ELF32LE>;
1797 template class elf::GotSection<ELF32BE>;
1798 template class elf::GotSection<ELF64LE>;
1799 template class elf::GotSection<ELF64BE>;
1800 
1801 template class elf::MipsGotSection<ELF32LE>;
1802 template class elf::MipsGotSection<ELF32BE>;
1803 template class elf::MipsGotSection<ELF64LE>;
1804 template class elf::MipsGotSection<ELF64BE>;
1805 
1806 template class elf::GotPltSection<ELF32LE>;
1807 template class elf::GotPltSection<ELF32BE>;
1808 template class elf::GotPltSection<ELF64LE>;
1809 template class elf::GotPltSection<ELF64BE>;
1810 
1811 template class elf::IgotPltSection<ELF32LE>;
1812 template class elf::IgotPltSection<ELF32BE>;
1813 template class elf::IgotPltSection<ELF64LE>;
1814 template class elf::IgotPltSection<ELF64BE>;
1815 
1816 template class elf::StringTableSection<ELF32LE>;
1817 template class elf::StringTableSection<ELF32BE>;
1818 template class elf::StringTableSection<ELF64LE>;
1819 template class elf::StringTableSection<ELF64BE>;
1820 
1821 template class elf::DynamicSection<ELF32LE>;
1822 template class elf::DynamicSection<ELF32BE>;
1823 template class elf::DynamicSection<ELF64LE>;
1824 template class elf::DynamicSection<ELF64BE>;
1825 
1826 template class elf::RelocationSection<ELF32LE>;
1827 template class elf::RelocationSection<ELF32BE>;
1828 template class elf::RelocationSection<ELF64LE>;
1829 template class elf::RelocationSection<ELF64BE>;
1830 
1831 template class elf::SymbolTableSection<ELF32LE>;
1832 template class elf::SymbolTableSection<ELF32BE>;
1833 template class elf::SymbolTableSection<ELF64LE>;
1834 template class elf::SymbolTableSection<ELF64BE>;
1835 
1836 template class elf::GnuHashTableSection<ELF32LE>;
1837 template class elf::GnuHashTableSection<ELF32BE>;
1838 template class elf::GnuHashTableSection<ELF64LE>;
1839 template class elf::GnuHashTableSection<ELF64BE>;
1840 
1841 template class elf::HashTableSection<ELF32LE>;
1842 template class elf::HashTableSection<ELF32BE>;
1843 template class elf::HashTableSection<ELF64LE>;
1844 template class elf::HashTableSection<ELF64BE>;
1845 
1846 template class elf::PltSection<ELF32LE>;
1847 template class elf::PltSection<ELF32BE>;
1848 template class elf::PltSection<ELF64LE>;
1849 template class elf::PltSection<ELF64BE>;
1850 
1851 template class elf::IpltSection<ELF32LE>;
1852 template class elf::IpltSection<ELF32BE>;
1853 template class elf::IpltSection<ELF64LE>;
1854 template class elf::IpltSection<ELF64BE>;
1855 
1856 template class elf::GdbIndexSection<ELF32LE>;
1857 template class elf::GdbIndexSection<ELF32BE>;
1858 template class elf::GdbIndexSection<ELF64LE>;
1859 template class elf::GdbIndexSection<ELF64BE>;
1860 
1861 template class elf::EhFrameHeader<ELF32LE>;
1862 template class elf::EhFrameHeader<ELF32BE>;
1863 template class elf::EhFrameHeader<ELF64LE>;
1864 template class elf::EhFrameHeader<ELF64BE>;
1865 
1866 template class elf::VersionTableSection<ELF32LE>;
1867 template class elf::VersionTableSection<ELF32BE>;
1868 template class elf::VersionTableSection<ELF64LE>;
1869 template class elf::VersionTableSection<ELF64BE>;
1870 
1871 template class elf::VersionNeedSection<ELF32LE>;
1872 template class elf::VersionNeedSection<ELF32BE>;
1873 template class elf::VersionNeedSection<ELF64LE>;
1874 template class elf::VersionNeedSection<ELF64BE>;
1875 
1876 template class elf::VersionDefinitionSection<ELF32LE>;
1877 template class elf::VersionDefinitionSection<ELF32BE>;
1878 template class elf::VersionDefinitionSection<ELF64LE>;
1879 template class elf::VersionDefinitionSection<ELF64BE>;
1880 
1881 template class elf::MipsRldMapSection<ELF32LE>;
1882 template class elf::MipsRldMapSection<ELF32BE>;
1883 template class elf::MipsRldMapSection<ELF64LE>;
1884 template class elf::MipsRldMapSection<ELF64BE>;
1885 
1886 template class elf::ARMExidxSentinelSection<ELF32LE>;
1887 template class elf::ARMExidxSentinelSection<ELF32BE>;
1888 template class elf::ARMExidxSentinelSection<ELF64LE>;
1889 template class elf::ARMExidxSentinelSection<ELF64BE>;
1890