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