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