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