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 "Bits.h"
19 #include "Config.h"
20 #include "InputFiles.h"
21 #include "LinkerScript.h"
22 #include "OutputSections.h"
23 #include "SymbolTable.h"
24 #include "Symbols.h"
25 #include "Target.h"
26 #include "Writer.h"
27 #include "lld/Common/ErrorHandler.h"
28 #include "lld/Common/Memory.h"
29 #include "lld/Common/Strings.h"
30 #include "lld/Common/Threads.h"
31 #include "lld/Common/Version.h"
32 #include "llvm/ADT/SetOperations.h"
33 #include "llvm/BinaryFormat/Dwarf.h"
34 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
35 #include "llvm/Object/Decompressor.h"
36 #include "llvm/Object/ELFObjectFile.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/MD5.h"
40 #include "llvm/Support/RandomNumberGenerator.h"
41 #include "llvm/Support/SHA1.h"
42 #include "llvm/Support/xxhash.h"
43 #include <cstdlib>
44 #include <thread>
45 
46 using namespace llvm;
47 using namespace llvm::dwarf;
48 using namespace llvm::ELF;
49 using namespace llvm::object;
50 using namespace llvm::support;
51 
52 using namespace lld;
53 using namespace lld::elf;
54 
55 using llvm::support::endian::read32le;
56 using llvm::support::endian::write32le;
57 using llvm::support::endian::write64le;
58 
59 constexpr size_t MergeNoTailSection::NumShards;
60 
61 // Returns an LLD version string.
62 static ArrayRef<uint8_t> getVersion() {
63   // Check LLD_VERSION first for ease of testing.
64   // You can get consistent output by using the environment variable.
65   // This is only for testing.
66   StringRef S = getenv("LLD_VERSION");
67   if (S.empty())
68     S = Saver.save(Twine("Linker: ") + getLLDVersion());
69 
70   // +1 to include the terminating '\0'.
71   return {(const uint8_t *)S.data(), S.size() + 1};
72 }
73 
74 // Creates a .comment section containing LLD version info.
75 // With this feature, you can identify LLD-generated binaries easily
76 // by "readelf --string-dump .comment <file>".
77 // The returned object is a mergeable string section.
78 MergeInputSection *elf::createCommentSection() {
79   return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
80                                  getVersion(), ".comment");
81 }
82 
83 // .MIPS.abiflags section.
84 template <class ELFT>
85 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
86     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
87       Flags(Flags) {
88   this->Entsize = sizeof(Elf_Mips_ABIFlags);
89 }
90 
91 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
92   memcpy(Buf, &Flags, sizeof(Flags));
93 }
94 
95 template <class ELFT>
96 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
97   Elf_Mips_ABIFlags Flags = {};
98   bool Create = false;
99 
100   for (InputSectionBase *Sec : InputSections) {
101     if (Sec->Type != SHT_MIPS_ABIFLAGS)
102       continue;
103     Sec->Live = false;
104     Create = true;
105 
106     std::string Filename = toString(Sec->File);
107     const size_t Size = Sec->Data.size();
108     // Older version of BFD (such as the default FreeBSD linker) concatenate
109     // .MIPS.abiflags instead of merging. To allow for this case (or potential
110     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
111     if (Size < sizeof(Elf_Mips_ABIFlags)) {
112       error(Filename + ": invalid size of .MIPS.abiflags section: got " +
113             Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
114       return nullptr;
115     }
116     auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
117     if (S->version != 0) {
118       error(Filename + ": unexpected .MIPS.abiflags version " +
119             Twine(S->version));
120       return nullptr;
121     }
122 
123     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
124     // select the highest number of ISA/Rev/Ext.
125     Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
126     Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
127     Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
128     Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
129     Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
130     Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
131     Flags.ases |= S->ases;
132     Flags.flags1 |= S->flags1;
133     Flags.flags2 |= S->flags2;
134     Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
135   };
136 
137   if (Create)
138     return make<MipsAbiFlagsSection<ELFT>>(Flags);
139   return nullptr;
140 }
141 
142 // .MIPS.options section.
143 template <class ELFT>
144 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
145     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
146       Reginfo(Reginfo) {
147   this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
148 }
149 
150 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
151   auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
152   Options->kind = ODK_REGINFO;
153   Options->size = getSize();
154 
155   if (!Config->Relocatable)
156     Reginfo.ri_gp_value = InX::MipsGot->getGp();
157   memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
158 }
159 
160 template <class ELFT>
161 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
162   // N64 ABI only.
163   if (!ELFT::Is64Bits)
164     return nullptr;
165 
166   std::vector<InputSectionBase *> Sections;
167   for (InputSectionBase *Sec : InputSections)
168     if (Sec->Type == SHT_MIPS_OPTIONS)
169       Sections.push_back(Sec);
170 
171   if (Sections.empty())
172     return nullptr;
173 
174   Elf_Mips_RegInfo Reginfo = {};
175   for (InputSectionBase *Sec : Sections) {
176     Sec->Live = false;
177 
178     std::string Filename = toString(Sec->File);
179     ArrayRef<uint8_t> D = Sec->Data;
180 
181     while (!D.empty()) {
182       if (D.size() < sizeof(Elf_Mips_Options)) {
183         error(Filename + ": invalid size of .MIPS.options section");
184         break;
185       }
186 
187       auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
188       if (Opt->kind == ODK_REGINFO) {
189         Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
190         Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
191         break;
192       }
193 
194       if (!Opt->size)
195         fatal(Filename + ": zero option descriptor size");
196       D = D.slice(Opt->size);
197     }
198   };
199 
200   return make<MipsOptionsSection<ELFT>>(Reginfo);
201 }
202 
203 // MIPS .reginfo section.
204 template <class ELFT>
205 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
206     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
207       Reginfo(Reginfo) {
208   this->Entsize = sizeof(Elf_Mips_RegInfo);
209 }
210 
211 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
212   if (!Config->Relocatable)
213     Reginfo.ri_gp_value = InX::MipsGot->getGp();
214   memcpy(Buf, &Reginfo, sizeof(Reginfo));
215 }
216 
217 template <class ELFT>
218 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
219   // Section should be alive for O32 and N32 ABIs only.
220   if (ELFT::Is64Bits)
221     return nullptr;
222 
223   std::vector<InputSectionBase *> Sections;
224   for (InputSectionBase *Sec : InputSections)
225     if (Sec->Type == SHT_MIPS_REGINFO)
226       Sections.push_back(Sec);
227 
228   if (Sections.empty())
229     return nullptr;
230 
231   Elf_Mips_RegInfo Reginfo = {};
232   for (InputSectionBase *Sec : Sections) {
233     Sec->Live = false;
234 
235     if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
236       error(toString(Sec->File) + ": invalid size of .reginfo section");
237       return nullptr;
238     }
239 
240     auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
241     Reginfo.ri_gprmask |= R->ri_gprmask;
242     Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
243   };
244 
245   return make<MipsReginfoSection<ELFT>>(Reginfo);
246 }
247 
248 InputSection *elf::createInterpSection() {
249   // StringSaver guarantees that the returned string ends with '\0'.
250   StringRef S = Saver.save(Config->DynamicLinker);
251   ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
252 
253   auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
254                                  ".interp");
255   Sec->Live = true;
256   return Sec;
257 }
258 
259 Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
260                                 uint64_t Size, InputSectionBase &Section) {
261   auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
262                           Value, Size, &Section);
263   if (InX::SymTab)
264     InX::SymTab->addSymbol(S);
265   return S;
266 }
267 
268 static size_t getHashSize() {
269   switch (Config->BuildId) {
270   case BuildIdKind::Fast:
271     return 8;
272   case BuildIdKind::Md5:
273   case BuildIdKind::Uuid:
274     return 16;
275   case BuildIdKind::Sha1:
276     return 20;
277   case BuildIdKind::Hexstring:
278     return Config->BuildIdVector.size();
279   default:
280     llvm_unreachable("unknown BuildIdKind");
281   }
282 }
283 
284 BuildIdSection::BuildIdSection()
285     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
286       HashSize(getHashSize()) {}
287 
288 void BuildIdSection::writeTo(uint8_t *Buf) {
289   write32(Buf, 4);                      // Name size
290   write32(Buf + 4, HashSize);           // Content size
291   write32(Buf + 8, NT_GNU_BUILD_ID);    // Type
292   memcpy(Buf + 12, "GNU", 4);           // Name string
293   HashBuf = Buf + 16;
294 }
295 
296 // Split one uint8 array into small pieces of uint8 arrays.
297 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
298                                             size_t ChunkSize) {
299   std::vector<ArrayRef<uint8_t>> Ret;
300   while (Arr.size() > ChunkSize) {
301     Ret.push_back(Arr.take_front(ChunkSize));
302     Arr = Arr.drop_front(ChunkSize);
303   }
304   if (!Arr.empty())
305     Ret.push_back(Arr);
306   return Ret;
307 }
308 
309 // Computes a hash value of Data using a given hash function.
310 // In order to utilize multiple cores, we first split data into 1MB
311 // chunks, compute a hash for each chunk, and then compute a hash value
312 // of the hash values.
313 void BuildIdSection::computeHash(
314     llvm::ArrayRef<uint8_t> Data,
315     std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
316   std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
317   std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
318 
319   // Compute hash values.
320   parallelForEachN(0, Chunks.size(), [&](size_t I) {
321     HashFn(Hashes.data() + I * HashSize, Chunks[I]);
322   });
323 
324   // Write to the final output buffer.
325   HashFn(HashBuf, Hashes);
326 }
327 
328 BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
329     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
330   this->Bss = true;
331   if (OutputSection *Sec = getParent())
332     Sec->Alignment = std::max(Sec->Alignment, Alignment);
333   this->Size = Size;
334 }
335 
336 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
337   switch (Config->BuildId) {
338   case BuildIdKind::Fast:
339     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
340       write64le(Dest, xxHash64(toStringRef(Arr)));
341     });
342     break;
343   case BuildIdKind::Md5:
344     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
345       memcpy(Dest, MD5::hash(Arr).data(), 16);
346     });
347     break;
348   case BuildIdKind::Sha1:
349     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
350       memcpy(Dest, SHA1::hash(Arr).data(), 20);
351     });
352     break;
353   case BuildIdKind::Uuid:
354     if (auto EC = getRandomBytes(HashBuf, HashSize))
355       error("entropy source failure: " + EC.message());
356     break;
357   case BuildIdKind::Hexstring:
358     memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
359     break;
360   default:
361     llvm_unreachable("unknown BuildIdKind");
362   }
363 }
364 
365 EhFrameSection::EhFrameSection()
366     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
367 
368 // Search for an existing CIE record or create a new one.
369 // CIE records from input object files are uniquified by their contents
370 // and where their relocations point to.
371 template <class ELFT, class RelTy>
372 CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
373   auto *Sec = cast<EhInputSection>(Cie.Sec);
374   if (read32(Cie.data().data() + 4) != 0)
375     fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
376 
377   Symbol *Personality = nullptr;
378   unsigned FirstRelI = Cie.FirstRelocation;
379   if (FirstRelI != (unsigned)-1)
380     Personality =
381         &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
382 
383   // Search for an existing CIE by CIE contents/relocation target pair.
384   CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
385 
386   // If not found, create a new one.
387   if (!Rec) {
388     Rec = make<CieRecord>();
389     Rec->Cie = &Cie;
390     CieRecords.push_back(Rec);
391   }
392   return Rec;
393 }
394 
395 // There is one FDE per function. Returns true if a given FDE
396 // points to a live function.
397 template <class ELFT, class RelTy>
398 bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
399   auto *Sec = cast<EhInputSection>(Fde.Sec);
400   unsigned FirstRelI = Fde.FirstRelocation;
401 
402   // An FDE should point to some function because FDEs are to describe
403   // functions. That's however not always the case due to an issue of
404   // ld.gold with -r. ld.gold may discard only functions and leave their
405   // corresponding FDEs, which results in creating bad .eh_frame sections.
406   // To deal with that, we ignore such FDEs.
407   if (FirstRelI == (unsigned)-1)
408     return false;
409 
410   const RelTy &Rel = Rels[FirstRelI];
411   Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
412 
413   // FDEs for garbage-collected or merged-by-ICF sections are dead.
414   if (auto *D = dyn_cast<Defined>(&B))
415     if (SectionBase *Sec = D->Section)
416       return Sec->Live;
417   return false;
418 }
419 
420 // .eh_frame is a sequence of CIE or FDE records. In general, there
421 // is one CIE record per input object file which is followed by
422 // a list of FDEs. This function searches an existing CIE or create a new
423 // one and associates FDEs to the CIE.
424 template <class ELFT, class RelTy>
425 void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
426   OffsetToCie.clear();
427   for (EhSectionPiece &Piece : Sec->Pieces) {
428     // The empty record is the end marker.
429     if (Piece.Size == 4)
430       return;
431 
432     size_t Offset = Piece.InputOff;
433     uint32_t ID = read32(Piece.data().data() + 4);
434     if (ID == 0) {
435       OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
436       continue;
437     }
438 
439     uint32_t CieOffset = Offset + 4 - ID;
440     CieRecord *Rec = OffsetToCie[CieOffset];
441     if (!Rec)
442       fatal(toString(Sec) + ": invalid CIE reference");
443 
444     if (!isFdeLive<ELFT>(Piece, Rels))
445       continue;
446     Rec->Fdes.push_back(&Piece);
447     NumFdes++;
448   }
449 }
450 
451 template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
452   auto *Sec = cast<EhInputSection>(C);
453   Sec->Parent = this;
454 
455   Alignment = std::max(Alignment, Sec->Alignment);
456   Sections.push_back(Sec);
457 
458   for (auto *DS : Sec->DependentSections)
459     DependentSections.push_back(DS);
460 
461   if (Sec->Pieces.empty())
462     return;
463 
464   if (Sec->AreRelocsRela)
465     addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
466   else
467     addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
468 }
469 
470 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
471   memcpy(Buf, D.data(), D.size());
472 
473   size_t Aligned = alignTo(D.size(), Config->Wordsize);
474 
475   // Zero-clear trailing padding if it exists.
476   memset(Buf + D.size(), 0, Aligned - D.size());
477 
478   // Fix the size field. -4 since size does not include the size field itself.
479   write32(Buf, Aligned - 4);
480 }
481 
482 void EhFrameSection::finalizeContents() {
483   if (this->Size)
484     return; // Already finalized.
485 
486   size_t Off = 0;
487   for (CieRecord *Rec : CieRecords) {
488     Rec->Cie->OutputOff = Off;
489     Off += alignTo(Rec->Cie->Size, Config->Wordsize);
490 
491     for (EhSectionPiece *Fde : Rec->Fdes) {
492       Fde->OutputOff = Off;
493       Off += alignTo(Fde->Size, Config->Wordsize);
494     }
495   }
496 
497   // The LSB standard does not allow a .eh_frame section with zero
498   // Call Frame Information records. glibc unwind-dw2-fde.c
499   // classify_object_over_fdes expects there is a CIE record length 0 as a
500   // terminator. Thus we add one unconditionally.
501   Off += 4;
502 
503   this->Size = Off;
504 }
505 
506 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
507 // to get an FDE from an address to which FDE is applied. This function
508 // returns a list of such pairs.
509 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
510   uint8_t *Buf = getParent()->Loc + OutSecOff;
511   std::vector<FdeData> Ret;
512 
513   for (CieRecord *Rec : CieRecords) {
514     uint8_t Enc = getFdeEncoding(Rec->Cie);
515     for (EhSectionPiece *Fde : Rec->Fdes) {
516       uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
517       uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
518       Ret.push_back({Pc, FdeVA});
519     }
520   }
521   return Ret;
522 }
523 
524 static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
525   switch (Size) {
526   case DW_EH_PE_udata2:
527     return read16(Buf);
528   case DW_EH_PE_udata4:
529     return read32(Buf);
530   case DW_EH_PE_udata8:
531     return read64(Buf);
532   case DW_EH_PE_absptr:
533     return readUint(Buf);
534   }
535   fatal("unknown FDE size encoding");
536 }
537 
538 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
539 // We need it to create .eh_frame_hdr section.
540 uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
541                                   uint8_t Enc) const {
542   // The starting address to which this FDE applies is
543   // stored at FDE + 8 byte.
544   size_t Off = FdeOff + 8;
545   uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
546   if ((Enc & 0x70) == DW_EH_PE_absptr)
547     return Addr;
548   if ((Enc & 0x70) == DW_EH_PE_pcrel)
549     return Addr + getParent()->Addr + Off;
550   fatal("unknown FDE size relative encoding");
551 }
552 
553 void EhFrameSection::writeTo(uint8_t *Buf) {
554   // Write CIE and FDE records.
555   for (CieRecord *Rec : CieRecords) {
556     size_t CieOffset = Rec->Cie->OutputOff;
557     writeCieFde(Buf + CieOffset, Rec->Cie->data());
558 
559     for (EhSectionPiece *Fde : Rec->Fdes) {
560       size_t Off = Fde->OutputOff;
561       writeCieFde(Buf + Off, Fde->data());
562 
563       // FDE's second word should have the offset to an associated CIE.
564       // Write it.
565       write32(Buf + Off + 4, Off + 4 - CieOffset);
566     }
567   }
568 
569   // Apply relocations. .eh_frame section contents are not contiguous
570   // in the output buffer, but relocateAlloc() still works because
571   // getOffset() takes care of discontiguous section pieces.
572   for (EhInputSection *S : Sections)
573     S->relocateAlloc(Buf, nullptr);
574 }
575 
576 GotSection::GotSection()
577     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
578                        Target->GotEntrySize, ".got") {
579   // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the
580   // .got. If there are no references to .TOC. in the symbol table,
581   // ElfSym::GlobalOffsetTable will not be defined and we won't need to save
582   // .TOC. in the .got. When it is defined, we increase NumEntries by the number
583   // of entries used to emit ElfSym::GlobalOffsetTable.
584   if (ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt)
585     NumEntries += Target->GotHeaderEntriesNum;
586 }
587 
588 void GotSection::addEntry(Symbol &Sym) {
589   Sym.GotIndex = NumEntries;
590   ++NumEntries;
591 }
592 
593 bool GotSection::addDynTlsEntry(Symbol &Sym) {
594   if (Sym.GlobalDynIndex != -1U)
595     return false;
596   Sym.GlobalDynIndex = NumEntries;
597   // Global Dynamic TLS entries take two GOT slots.
598   NumEntries += 2;
599   return true;
600 }
601 
602 // Reserves TLS entries for a TLS module ID and a TLS block offset.
603 // In total it takes two GOT slots.
604 bool GotSection::addTlsIndex() {
605   if (TlsIndexOff != uint32_t(-1))
606     return false;
607   TlsIndexOff = NumEntries * Config->Wordsize;
608   NumEntries += 2;
609   return true;
610 }
611 
612 uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
613   return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
614 }
615 
616 uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
617   return B.GlobalDynIndex * Config->Wordsize;
618 }
619 
620 void GotSection::finalizeContents() {
621   Size = NumEntries * Config->Wordsize;
622 }
623 
624 bool GotSection::empty() const {
625   // We need to emit a GOT even if it's empty if there's a relocation that is
626   // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
627   // (i.e. _GLOBAL_OFFSET_TABLE_) that the target defines relative to the .got.
628   return NumEntries == 0 && !HasGotOffRel &&
629          !(ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt);
630 }
631 
632 void GotSection::writeTo(uint8_t *Buf) {
633   // Buf points to the start of this section's buffer,
634   // whereas InputSectionBase::relocateAlloc() expects its argument
635   // to point to the start of the output section.
636   Target->writeGotHeader(Buf);
637   relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
638 }
639 
640 static uint64_t getMipsPageAddr(uint64_t Addr) {
641   return (Addr + 0x8000) & ~0xffff;
642 }
643 
644 static uint64_t getMipsPageCount(uint64_t Size) {
645   return (Size + 0xfffe) / 0xffff + 1;
646 }
647 
648 MipsGotSection::MipsGotSection()
649     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
650                        ".got") {}
651 
652 void MipsGotSection::addEntry(InputFile &File, Symbol &Sym, int64_t Addend,
653                               RelExpr Expr) {
654   FileGot &G = getGot(File);
655   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
656     if (const OutputSection *OS = Sym.getOutputSection())
657       G.PagesMap.insert({OS, {}});
658     else
659       G.Local16.insert({{nullptr, getMipsPageAddr(Sym.getVA(Addend))}, 0});
660   } else if (Sym.isTls())
661     G.Tls.insert({&Sym, 0});
662   else if (Sym.IsPreemptible && Expr == R_ABS)
663     G.Relocs.insert({&Sym, 0});
664   else if (Sym.IsPreemptible)
665     G.Global.insert({&Sym, 0});
666   else if (Expr == R_MIPS_GOT_OFF32)
667     G.Local32.insert({{&Sym, Addend}, 0});
668   else
669     G.Local16.insert({{&Sym, Addend}, 0});
670 }
671 
672 void MipsGotSection::addDynTlsEntry(InputFile &File, Symbol &Sym) {
673   getGot(File).DynTlsSymbols.insert({&Sym, 0});
674 }
675 
676 void MipsGotSection::addTlsIndex(InputFile &File) {
677   getGot(File).DynTlsSymbols.insert({nullptr, 0});
678 }
679 
680 size_t MipsGotSection::FileGot::getEntriesNum() const {
681   return getPageEntriesNum() + Local16.size() + Global.size() + Relocs.size() +
682          Tls.size() + DynTlsSymbols.size() * 2;
683 }
684 
685 size_t MipsGotSection::FileGot::getPageEntriesNum() const {
686   size_t Num = 0;
687   for (const std::pair<const OutputSection *, FileGot::PageBlock> &P : PagesMap)
688     Num += P.second.Count;
689   return Num;
690 }
691 
692 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
693   size_t Count = getPageEntriesNum() + Local16.size() + Global.size();
694   // If there are relocation-only entries in the GOT, TLS entries
695   // are allocated after them. TLS entries should be addressable
696   // by 16-bit index so count both reloc-only and TLS entries.
697   if (!Tls.empty() || !DynTlsSymbols.empty())
698     Count += Relocs.size() + Tls.size() + DynTlsSymbols.size() * 2;
699   return Count;
700 }
701 
702 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &F) {
703   if (!F.MipsGotIndex.hasValue()) {
704     Gots.emplace_back();
705     Gots.back().File = &F;
706     F.MipsGotIndex = Gots.size() - 1;
707   }
708   return Gots[*F.MipsGotIndex];
709 }
710 
711 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *F,
712                                             const Symbol &Sym,
713                                             int64_t Addend) const {
714   const FileGot &G = Gots[*F->MipsGotIndex];
715   uint64_t Index = 0;
716   if (const OutputSection *OutSec = Sym.getOutputSection()) {
717     uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
718     uint64_t SymAddr = getMipsPageAddr(Sym.getVA(Addend));
719     Index = G.PagesMap.lookup(OutSec).FirstIndex + (SymAddr - SecAddr) / 0xffff;
720   } else {
721     Index = G.Local16.lookup({nullptr, getMipsPageAddr(Sym.getVA(Addend))});
722   }
723   return Index * Config->Wordsize;
724 }
725 
726 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *F, const Symbol &S,
727                                            int64_t Addend) const {
728   const FileGot &G = Gots[*F->MipsGotIndex];
729   Symbol *Sym = const_cast<Symbol *>(&S);
730   if (Sym->isTls())
731     return G.Tls.lookup(Sym) * Config->Wordsize;
732   if (Sym->IsPreemptible)
733     return G.Global.lookup(Sym) * Config->Wordsize;
734   return G.Local16.lookup({Sym, Addend}) * Config->Wordsize;
735 }
736 
737 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *F) const {
738   const FileGot &G = Gots[*F->MipsGotIndex];
739   return G.DynTlsSymbols.lookup(nullptr) * Config->Wordsize;
740 }
741 
742 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *F,
743                                             const Symbol &S) const {
744   const FileGot &G = Gots[*F->MipsGotIndex];
745   Symbol *Sym = const_cast<Symbol *>(&S);
746   return G.DynTlsSymbols.lookup(Sym) * Config->Wordsize;
747 }
748 
749 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
750   if (Gots.empty())
751     return nullptr;
752   const FileGot &PrimGot = Gots.front();
753   if (!PrimGot.Global.empty())
754     return PrimGot.Global.front().first;
755   if (!PrimGot.Relocs.empty())
756     return PrimGot.Relocs.front().first;
757   return nullptr;
758 }
759 
760 unsigned MipsGotSection::getLocalEntriesNum() const {
761   if (Gots.empty())
762     return HeaderEntriesNum;
763   return HeaderEntriesNum + Gots.front().getPageEntriesNum() +
764          Gots.front().Local16.size();
765 }
766 
767 bool MipsGotSection::tryMergeGots(FileGot &Dst, FileGot &Src, bool IsPrimary) {
768   FileGot Tmp = Dst;
769   set_union(Tmp.PagesMap, Src.PagesMap);
770   set_union(Tmp.Local16, Src.Local16);
771   set_union(Tmp.Global, Src.Global);
772   set_union(Tmp.Relocs, Src.Relocs);
773   set_union(Tmp.Tls, Src.Tls);
774   set_union(Tmp.DynTlsSymbols, Src.DynTlsSymbols);
775 
776   size_t Count = IsPrimary ? HeaderEntriesNum : 0;
777   Count += Tmp.getIndexedEntriesNum();
778 
779   if (Count * Config->Wordsize > Config->MipsGotSize)
780     return false;
781 
782   std::swap(Tmp, Dst);
783   return true;
784 }
785 
786 void MipsGotSection::finalizeContents() { updateAllocSize(); }
787 
788 bool MipsGotSection::updateAllocSize() {
789   Size = HeaderEntriesNum * Config->Wordsize;
790   for (const FileGot &G : Gots)
791     Size += G.getEntriesNum() * Config->Wordsize;
792   return false;
793 }
794 
795 template <class ELFT> void MipsGotSection::build() {
796   if (Gots.empty())
797     return;
798 
799   std::vector<FileGot> MergedGots(1);
800 
801   // For each GOT move non-preemptible symbols from the `Global`
802   // to `Local16` list. Preemptible symbol might become non-preemptible
803   // one if, for example, it gets a related copy relocation.
804   for (FileGot &Got : Gots) {
805     for (auto &P: Got.Global)
806       if (!P.first->IsPreemptible)
807         Got.Local16.insert({{P.first, 0}, 0});
808     Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
809       return !P.first->IsPreemptible;
810     });
811   }
812 
813   // For each GOT remove "reloc-only" entry if there is "global"
814   // entry for the same symbol. And add local entries which indexed
815   // using 32-bit value at the end of 16-bit entries.
816   for (FileGot &Got : Gots) {
817     Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
818       return Got.Global.count(P.first);
819     });
820     set_union(Got.Local16, Got.Local32);
821     Got.Local32.clear();
822   }
823 
824   // Evaluate number of "reloc-only" entries in the resulting GOT.
825   // To do that put all unique "reloc-only" and "global" entries
826   // from all GOTs to the future primary GOT.
827   FileGot *PrimGot = &MergedGots.front();
828   for (FileGot &Got : Gots) {
829     set_union(PrimGot->Relocs, Got.Global);
830     set_union(PrimGot->Relocs, Got.Relocs);
831     Got.Relocs.clear();
832   }
833 
834   // Evaluate number of "page" entries in each GOT.
835   for (FileGot &Got : Gots) {
836     for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
837          Got.PagesMap) {
838       const OutputSection *OS = P.first;
839       uint64_t SecSize = 0;
840       for (BaseCommand *Cmd : OS->SectionCommands) {
841         if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
842           for (InputSection *IS : ISD->Sections) {
843             uint64_t Off = alignTo(SecSize, IS->Alignment);
844             SecSize = Off + IS->getSize();
845           }
846       }
847       P.second.Count = getMipsPageCount(SecSize);
848     }
849   }
850 
851   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
852   // maximum GOT size. At first, try to fill the primary GOT because
853   // the primary GOT can be accessed in the most effective way. If it
854   // is not possible, try to fill the last GOT in the list, and finally
855   // create a new GOT if both attempts failed.
856   for (FileGot &SrcGot : Gots) {
857     InputFile *File = SrcGot.File;
858     if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
859       File->MipsGotIndex = 0;
860     } else {
861       if (!tryMergeGots(MergedGots.back(), SrcGot, false)) {
862         MergedGots.emplace_back();
863         std::swap(MergedGots.back(), SrcGot);
864       }
865       File->MipsGotIndex = MergedGots.size() - 1;
866     }
867   }
868   std::swap(Gots, MergedGots);
869 
870   // Reduce number of "reloc-only" entries in the primary GOT
871   // by substracting "global" entries exist in the primary GOT.
872   PrimGot = &Gots.front();
873   PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
874     return PrimGot->Global.count(P.first);
875   });
876 
877   // Calculate indexes for each GOT entry.
878   size_t Index = HeaderEntriesNum;
879   for (FileGot &Got : Gots) {
880     Got.StartIndex = &Got == PrimGot ? 0 : Index;
881     for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
882          Got.PagesMap) {
883       // For each output section referenced by GOT page relocations calculate
884       // and save into PagesMap an upper bound of MIPS GOT entries required
885       // to store page addresses of local symbols. We assume the worst case -
886       // each 64kb page of the output section has at least one GOT relocation
887       // against it. And take in account the case when the section intersects
888       // page boundaries.
889       P.second.FirstIndex = Index;
890       Index += P.second.Count;
891     }
892     for (auto &P: Got.Local16)
893       P.second = Index++;
894     for (auto &P: Got.Global)
895       P.second = Index++;
896     for (auto &P: Got.Relocs)
897       P.second = Index++;
898     for (auto &P: Got.Tls)
899       P.second = Index++;
900     for (auto &P: Got.DynTlsSymbols) {
901       P.second = Index;
902       Index += 2;
903     }
904   }
905 
906   // Update Symbol::GotIndex field to use this
907   // value later in the `sortMipsSymbols` function.
908   for (auto &P : PrimGot->Global)
909     P.first->GotIndex = P.second;
910   for (auto &P : PrimGot->Relocs)
911     P.first->GotIndex = P.second;
912 
913   // Create dynamic relocations.
914   for (FileGot &Got : Gots) {
915     // Create dynamic relocations for TLS entries.
916     for (std::pair<Symbol *, size_t> &P : Got.Tls) {
917       Symbol *S = P.first;
918       uint64_t Offset = P.second * Config->Wordsize;
919       if (S->IsPreemptible)
920         InX::RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
921     }
922     for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
923       Symbol *S = P.first;
924       uint64_t Offset = P.second * Config->Wordsize;
925       if (S == nullptr) {
926         if (!Config->Pic)
927           continue;
928         InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
929       } else {
930         // When building a shared library we still need a dynamic relocation
931         // for the module index. Therefore only checking for
932         // S->IsPreemptible is not sufficient (this happens e.g. for
933         // thread-locals that have been marked as local through a linker script)
934         if (!S->IsPreemptible && !Config->Pic)
935           continue;
936         InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
937         // However, we can skip writing the TLS offset reloc for non-preemptible
938         // symbols since it is known even in shared libraries
939         if (!S->IsPreemptible)
940           continue;
941         Offset += Config->Wordsize;
942         InX::RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
943       }
944     }
945 
946     // Do not create dynamic relocations for non-TLS
947     // entries in the primary GOT.
948     if (&Got == PrimGot)
949       continue;
950 
951     // Dynamic relocations for "global" entries.
952     for (const std::pair<Symbol *, size_t> &P : Got.Global) {
953       uint64_t Offset = P.second * Config->Wordsize;
954       InX::RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
955     }
956     if (!Config->Pic)
957       continue;
958     // Dynamic relocations for "local" entries in case of PIC.
959     for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
960          Got.PagesMap) {
961       size_t PageCount = L.second.Count;
962       for (size_t PI = 0; PI < PageCount; ++PI) {
963         uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
964         InX::RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
965                                 int64_t(PI * 0x10000)});
966       }
967     }
968     for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
969       uint64_t Offset = P.second * Config->Wordsize;
970       InX::RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
971                               P.first.first, P.first.second});
972     }
973   }
974 }
975 
976 bool MipsGotSection::empty() const {
977   // We add the .got section to the result for dynamic MIPS target because
978   // its address and properties are mentioned in the .dynamic section.
979   return Config->Relocatable;
980 }
981 
982 uint64_t MipsGotSection::getGp(const InputFile *F) const {
983   // For files without related GOT or files refer a primary GOT
984   // returns "common" _gp value. For secondary GOTs calculate
985   // individual _gp values.
986   if (!F || !F->MipsGotIndex.hasValue() || *F->MipsGotIndex == 0)
987     return ElfSym::MipsGp->getVA(0);
988   return getVA() + Gots[*F->MipsGotIndex].StartIndex * Config->Wordsize +
989          0x7ff0;
990 }
991 
992 void MipsGotSection::writeTo(uint8_t *Buf) {
993   // Set the MSB of the second GOT slot. This is not required by any
994   // MIPS ABI documentation, though.
995   //
996   // There is a comment in glibc saying that "The MSB of got[1] of a
997   // gnu object is set to identify gnu objects," and in GNU gold it
998   // says "the second entry will be used by some runtime loaders".
999   // But how this field is being used is unclear.
1000   //
1001   // We are not really willing to mimic other linkers behaviors
1002   // without understanding why they do that, but because all files
1003   // generated by GNU tools have this special GOT value, and because
1004   // we've been doing this for years, it is probably a safe bet to
1005   // keep doing this for now. We really need to revisit this to see
1006   // if we had to do this.
1007   writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
1008   for (const FileGot &G : Gots) {
1009     auto Write = [&](size_t I, const Symbol *S, int64_t A) {
1010       uint64_t VA = A;
1011       if (S) {
1012         VA = S->getVA(A);
1013         if (S->StOther & STO_MIPS_MICROMIPS)
1014           VA |= 1;
1015       }
1016       writeUint(Buf + I * Config->Wordsize, VA);
1017     };
1018     // Write 'page address' entries to the local part of the GOT.
1019     for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
1020          G.PagesMap) {
1021       size_t PageCount = L.second.Count;
1022       uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
1023       for (size_t PI = 0; PI < PageCount; ++PI)
1024         Write(L.second.FirstIndex + PI, nullptr, FirstPageAddr + PI * 0x10000);
1025     }
1026     // Local, global, TLS, reloc-only  entries.
1027     // If TLS entry has a corresponding dynamic relocations, leave it
1028     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1029     // To calculate the adjustments use offsets for thread-local storage.
1030     // https://www.linux-mips.org/wiki/NPTL
1031     for (const std::pair<GotEntry, size_t> &P : G.Local16)
1032       Write(P.second, P.first.first, P.first.second);
1033     // Write VA to the primary GOT only. For secondary GOTs that
1034     // will be done by REL32 dynamic relocations.
1035     if (&G == &Gots.front())
1036       for (const std::pair<const Symbol *, size_t> &P : G.Global)
1037         Write(P.second, P.first, 0);
1038     for (const std::pair<Symbol *, size_t> &P : G.Relocs)
1039       Write(P.second, P.first, 0);
1040     for (const std::pair<Symbol *, size_t> &P : G.Tls)
1041       Write(P.second, P.first, P.first->IsPreemptible ? 0 : -0x7000);
1042     for (const std::pair<Symbol *, size_t> &P : G.DynTlsSymbols) {
1043       if (P.first == nullptr && !Config->Pic)
1044         Write(P.second, nullptr, 1);
1045       else if (P.first && !P.first->IsPreemptible) {
1046         // If we are emitting PIC code with relocations we mustn't write
1047         // anything to the GOT here. When using Elf_Rel relocations the value
1048         // one will be treated as an addend and will cause crashes at runtime
1049         if (!Config->Pic)
1050           Write(P.second, nullptr, 1);
1051         Write(P.second + 1, P.first, -0x8000);
1052       }
1053     }
1054   }
1055 }
1056 
1057 // On PowerPC the .plt section is used to hold the table of function addresses
1058 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1059 // section. I don't know why we have a BSS style type for the section but it is
1060 // consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1061 GotPltSection::GotPltSection()
1062     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1063                        Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1064                        Target->GotPltEntrySize,
1065                        Config->EMachine == EM_PPC64 ? ".plt" : ".got.plt") {}
1066 
1067 void GotPltSection::addEntry(Symbol &Sym) {
1068   assert(Sym.PltIndex == Entries.size());
1069   Entries.push_back(&Sym);
1070 }
1071 
1072 size_t GotPltSection::getSize() const {
1073   return (Target->GotPltHeaderEntriesNum + Entries.size()) *
1074          Target->GotPltEntrySize;
1075 }
1076 
1077 void GotPltSection::writeTo(uint8_t *Buf) {
1078   Target->writeGotPltHeader(Buf);
1079   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
1080   for (const Symbol *B : Entries) {
1081     Target->writeGotPlt(Buf, *B);
1082     Buf += Config->Wordsize;
1083   }
1084 }
1085 
1086 bool GotPltSection::empty() const {
1087   // We need to emit a GOT.PLT even if it's empty if there's a symbol that
1088   // references the _GLOBAL_OFFSET_TABLE_ and the Target defines the symbol
1089   // relative to the .got.plt section.
1090   return Entries.empty() &&
1091          !(ElfSym::GlobalOffsetTable && Target->GotBaseSymInGotPlt);
1092 }
1093 
1094 static StringRef getIgotPltName() {
1095   // On ARM the IgotPltSection is part of the GotSection.
1096   if (Config->EMachine == EM_ARM)
1097     return ".got";
1098 
1099   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1100   // needs to be named the same.
1101   if (Config->EMachine == EM_PPC64)
1102     return ".plt";
1103 
1104   return ".got.plt";
1105 }
1106 
1107 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1108 // with the IgotPltSection.
1109 IgotPltSection::IgotPltSection()
1110     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1111                        Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1112                        Target->GotPltEntrySize, getIgotPltName()) {}
1113 
1114 void IgotPltSection::addEntry(Symbol &Sym) {
1115   Sym.IsInIgot = true;
1116   assert(Sym.PltIndex == Entries.size());
1117   Entries.push_back(&Sym);
1118 }
1119 
1120 size_t IgotPltSection::getSize() const {
1121   return Entries.size() * Target->GotPltEntrySize;
1122 }
1123 
1124 void IgotPltSection::writeTo(uint8_t *Buf) {
1125   for (const Symbol *B : Entries) {
1126     Target->writeIgotPlt(Buf, *B);
1127     Buf += Config->Wordsize;
1128   }
1129 }
1130 
1131 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
1132     : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
1133       Dynamic(Dynamic) {
1134   // ELF string tables start with a NUL byte.
1135   addString("");
1136 }
1137 
1138 // Adds a string to the string table. If HashIt is true we hash and check for
1139 // duplicates. It is optional because the name of global symbols are already
1140 // uniqued and hashing them again has a big cost for a small value: uniquing
1141 // them with some other string that happens to be the same.
1142 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
1143   if (HashIt) {
1144     auto R = StringMap.insert(std::make_pair(S, this->Size));
1145     if (!R.second)
1146       return R.first->second;
1147   }
1148   unsigned Ret = this->Size;
1149   this->Size = this->Size + S.size() + 1;
1150   Strings.push_back(S);
1151   return Ret;
1152 }
1153 
1154 void StringTableSection::writeTo(uint8_t *Buf) {
1155   for (StringRef S : Strings) {
1156     memcpy(Buf, S.data(), S.size());
1157     Buf[S.size()] = '\0';
1158     Buf += S.size() + 1;
1159   }
1160 }
1161 
1162 // Returns the number of version definition entries. Because the first entry
1163 // is for the version definition itself, it is the number of versioned symbols
1164 // plus one. Note that we don't support multiple versions yet.
1165 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1166 
1167 template <class ELFT>
1168 DynamicSection<ELFT>::DynamicSection()
1169     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1170                        ".dynamic") {
1171   this->Entsize = ELFT::Is64Bits ? 16 : 8;
1172 
1173   // .dynamic section is not writable on MIPS and on Fuchsia OS
1174   // which passes -z rodynamic.
1175   // See "Special Section" in Chapter 4 in the following document:
1176   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1177   if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
1178     this->Flags = SHF_ALLOC;
1179 
1180   // Add strings to .dynstr early so that .dynstr's size will be
1181   // fixed early.
1182   for (StringRef S : Config->FilterList)
1183     addInt(DT_FILTER, InX::DynStrTab->addString(S));
1184   for (StringRef S : Config->AuxiliaryList)
1185     addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
1186 
1187   if (!Config->Rpath.empty())
1188     addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1189            InX::DynStrTab->addString(Config->Rpath));
1190 
1191   for (InputFile *File : SharedFiles) {
1192     SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1193     if (F->IsNeeded)
1194       addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
1195   }
1196   if (!Config->SoName.empty())
1197     addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
1198 }
1199 
1200 template <class ELFT>
1201 void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1202   Entries.push_back({Tag, Fn});
1203 }
1204 
1205 template <class ELFT>
1206 void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1207   Entries.push_back({Tag, [=] { return Val; }});
1208 }
1209 
1210 template <class ELFT>
1211 void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1212   Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1213 }
1214 
1215 template <class ELFT>
1216 void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1217   size_t TagOffset = Entries.size() * Entsize;
1218   Entries.push_back(
1219       {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1220 }
1221 
1222 template <class ELFT>
1223 void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1224   Entries.push_back({Tag, [=] { return Sec->Addr; }});
1225 }
1226 
1227 template <class ELFT>
1228 void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1229   Entries.push_back({Tag, [=] { return Sec->Size; }});
1230 }
1231 
1232 template <class ELFT>
1233 void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1234   Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1235 }
1236 
1237 // Add remaining entries to complete .dynamic contents.
1238 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1239   if (this->Size)
1240     return; // Already finalized.
1241 
1242   // Set DT_FLAGS and DT_FLAGS_1.
1243   uint32_t DtFlags = 0;
1244   uint32_t DtFlags1 = 0;
1245   if (Config->Bsymbolic)
1246     DtFlags |= DF_SYMBOLIC;
1247   if (Config->ZInitfirst)
1248     DtFlags1 |= DF_1_INITFIRST;
1249   if (Config->ZNodelete)
1250     DtFlags1 |= DF_1_NODELETE;
1251   if (Config->ZNodlopen)
1252     DtFlags1 |= DF_1_NOOPEN;
1253   if (Config->ZNow) {
1254     DtFlags |= DF_BIND_NOW;
1255     DtFlags1 |= DF_1_NOW;
1256   }
1257   if (Config->ZOrigin) {
1258     DtFlags |= DF_ORIGIN;
1259     DtFlags1 |= DF_1_ORIGIN;
1260   }
1261   if (!Config->ZText)
1262     DtFlags |= DF_TEXTREL;
1263 
1264   if (DtFlags)
1265     addInt(DT_FLAGS, DtFlags);
1266   if (DtFlags1)
1267     addInt(DT_FLAGS_1, DtFlags1);
1268 
1269   // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1270   // need it for each process, so we don't write it for DSOs. The loader writes
1271   // the pointer into this entry.
1272   //
1273   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1274   // systems (currently only Fuchsia OS) provide other means to give the
1275   // debugger this information. Such systems may choose make .dynamic read-only.
1276   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1277   if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
1278     addInt(DT_DEBUG, 0);
1279 
1280   this->Link = InX::DynStrTab->getParent()->SectionIndex;
1281   if (!InX::RelaDyn->empty()) {
1282     addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1283     addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1284 
1285     bool IsRela = Config->IsRela;
1286     addInt(IsRela ? DT_RELAENT : DT_RELENT,
1287            IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1288 
1289     // MIPS dynamic loader does not support RELCOUNT tag.
1290     // The problem is in the tight relation between dynamic
1291     // relocations and GOT. So do not emit this tag on MIPS.
1292     if (Config->EMachine != EM_MIPS) {
1293       size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1294       if (Config->ZCombreloc && NumRelativeRels)
1295         addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
1296     }
1297   }
1298   if (InX::RelrDyn && !InX::RelrDyn->Relocs.empty()) {
1299     addInSec(Config->UseAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1300              InX::RelrDyn);
1301     addSize(Config->UseAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1302             InX::RelrDyn->getParent());
1303     addInt(Config->UseAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1304            sizeof(Elf_Relr));
1305   }
1306   // .rel[a].plt section usually consists of two parts, containing plt and
1307   // iplt relocations. It is possible to have only iplt relocations in the
1308   // output. In that case RelaPlt is empty and have zero offset, the same offset
1309   // as RelaIplt have. And we still want to emit proper dynamic tags for that
1310   // case, so here we always use RelaPlt as marker for the begining of
1311   // .rel[a].plt section.
1312   if (InX::RelaPlt->getParent()->Live) {
1313     addInSec(DT_JMPREL, InX::RelaPlt);
1314     addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1315     switch (Config->EMachine) {
1316     case EM_MIPS:
1317       addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1318       break;
1319     case EM_SPARCV9:
1320       addInSec(DT_PLTGOT, InX::Plt);
1321       break;
1322     default:
1323       addInSec(DT_PLTGOT, InX::GotPlt);
1324       break;
1325     }
1326     addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
1327   }
1328 
1329   addInSec(DT_SYMTAB, InX::DynSymTab);
1330   addInt(DT_SYMENT, sizeof(Elf_Sym));
1331   addInSec(DT_STRTAB, InX::DynStrTab);
1332   addInt(DT_STRSZ, InX::DynStrTab->getSize());
1333   if (!Config->ZText)
1334     addInt(DT_TEXTREL, 0);
1335   if (InX::GnuHashTab)
1336     addInSec(DT_GNU_HASH, InX::GnuHashTab);
1337   if (InX::HashTab)
1338     addInSec(DT_HASH, InX::HashTab);
1339 
1340   if (Out::PreinitArray) {
1341     addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1342     addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1343   }
1344   if (Out::InitArray) {
1345     addOutSec(DT_INIT_ARRAY, Out::InitArray);
1346     addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1347   }
1348   if (Out::FiniArray) {
1349     addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1350     addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1351   }
1352 
1353   if (Symbol *B = Symtab->find(Config->Init))
1354     if (B->isDefined())
1355       addSym(DT_INIT, B);
1356   if (Symbol *B = Symtab->find(Config->Fini))
1357     if (B->isDefined())
1358       addSym(DT_FINI, B);
1359 
1360   bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1361   if (HasVerNeed || In<ELFT>::VerDef)
1362     addInSec(DT_VERSYM, In<ELFT>::VerSym);
1363   if (In<ELFT>::VerDef) {
1364     addInSec(DT_VERDEF, In<ELFT>::VerDef);
1365     addInt(DT_VERDEFNUM, getVerDefNum());
1366   }
1367   if (HasVerNeed) {
1368     addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1369     addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1370   }
1371 
1372   if (Config->EMachine == EM_MIPS) {
1373     addInt(DT_MIPS_RLD_VERSION, 1);
1374     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1375     addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1376     addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1377 
1378     add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1379 
1380     if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1381       addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1382     else
1383       addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1384     addInSec(DT_PLTGOT, InX::MipsGot);
1385     if (InX::MipsRldMap) {
1386       if (!Config->Pie)
1387         addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1388       // Store the offset to the .rld_map section
1389       // relative to the address of the tag.
1390       addInSecRelative(DT_MIPS_RLD_MAP_REL, InX::MipsRldMap);
1391     }
1392   }
1393 
1394   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1395   if (Config->EMachine == EM_PPC64 && !InX::Plt->empty()) {
1396     // The Glink tag points to 32 bytes before the first lazy symbol resolution
1397     // stub, which starts directly after the header.
1398     Entries.push_back({DT_PPC64_GLINK, [=] {
1399                          unsigned Offset = Target->PltHeaderSize - 32;
1400                          return InX::Plt->getVA(0) + Offset;
1401                        }});
1402   }
1403 
1404   addInt(DT_NULL, 0);
1405 
1406   getParent()->Link = this->Link;
1407   this->Size = Entries.size() * this->Entsize;
1408 }
1409 
1410 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1411   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1412 
1413   for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1414     P->d_tag = KV.first;
1415     P->d_un.d_val = KV.second();
1416     ++P;
1417   }
1418 }
1419 
1420 uint64_t DynamicReloc::getOffset() const {
1421   return InputSec->getVA(OffsetInSec);
1422 }
1423 
1424 int64_t DynamicReloc::computeAddend() const {
1425   if (UseSymVA)
1426     return Sym->getVA(Addend);
1427   if (!OutputSec)
1428     return Addend;
1429   // See the comment in the DynamicReloc ctor.
1430   return getMipsPageAddr(OutputSec->Addr) + Addend;
1431 }
1432 
1433 uint32_t DynamicReloc::getSymIndex() const {
1434   if (Sym && !UseSymVA)
1435     return Sym->DynsymIndex;
1436   return 0;
1437 }
1438 
1439 RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1440                                              int32_t DynamicTag,
1441                                              int32_t SizeDynamicTag)
1442     : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1443       DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
1444 
1445 void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
1446                                      uint64_t OffsetInSec, Symbol *Sym) {
1447   addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1448 }
1449 
1450 void RelocationBaseSection::addReloc(RelType DynType,
1451                                      InputSectionBase *InputSec,
1452                                      uint64_t OffsetInSec, Symbol *Sym,
1453                                      int64_t Addend, RelExpr Expr,
1454                                      RelType Type) {
1455   // Write the addends to the relocated address if required. We skip
1456   // it if the written value would be zero.
1457   if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0))
1458     InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
1459   addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
1460 }
1461 
1462 void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
1463   if (Reloc.Type == Target->RelativeRel)
1464     ++NumRelativeRelocs;
1465   Relocs.push_back(Reloc);
1466 }
1467 
1468 void RelocationBaseSection::finalizeContents() {
1469   // If all relocations are R_*_RELATIVE they don't refer to any
1470   // dynamic symbol and we don't need a dynamic symbol table. If that
1471   // is the case, just use 0 as the link.
1472   Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
1473 
1474   // Set required output section properties.
1475   getParent()->Link = Link;
1476 }
1477 
1478 RelrBaseSection::RelrBaseSection()
1479     : SyntheticSection(SHF_ALLOC,
1480                        Config->UseAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
1481                        Config->Wordsize, ".relr.dyn") {}
1482 
1483 template <class ELFT>
1484 static void encodeDynamicReloc(typename ELFT::Rela *P,
1485                                const DynamicReloc &Rel) {
1486   if (Config->IsRela)
1487     P->r_addend = Rel.computeAddend();
1488   P->r_offset = Rel.getOffset();
1489   P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1490 }
1491 
1492 template <class ELFT>
1493 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1494     : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1495                             Config->IsRela ? DT_RELA : DT_REL,
1496                             Config->IsRela ? DT_RELASZ : DT_RELSZ),
1497       Sort(Sort) {
1498   this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1499 }
1500 
1501 static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) {
1502   bool AIsRel = A.Type == Target->RelativeRel;
1503   bool BIsRel = B.Type == Target->RelativeRel;
1504   if (AIsRel != BIsRel)
1505     return AIsRel;
1506   return A.getSymIndex() < B.getSymIndex();
1507 }
1508 
1509 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1510   if (Sort)
1511     std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1512 
1513   for (const DynamicReloc &Rel : Relocs) {
1514     encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1515     Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1516   }
1517 }
1518 
1519 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1520   return this->Entsize * Relocs.size();
1521 }
1522 
1523 template <class ELFT>
1524 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1525     StringRef Name)
1526     : RelocationBaseSection(
1527           Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1528           Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1529           Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1530   this->Entsize = 1;
1531 }
1532 
1533 template <class ELFT>
1534 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1535   // This function computes the contents of an Android-format packed relocation
1536   // section.
1537   //
1538   // This format compresses relocations by using relocation groups to factor out
1539   // fields that are common between relocations and storing deltas from previous
1540   // relocations in SLEB128 format (which has a short representation for small
1541   // numbers). A good example of a relocation type with common fields is
1542   // R_*_RELATIVE, which is normally used to represent function pointers in
1543   // vtables. In the REL format, each relative relocation has the same r_info
1544   // field, and is only different from other relative relocations in terms of
1545   // the r_offset field. By sorting relocations by offset, grouping them by
1546   // r_info and representing each relocation with only the delta from the
1547   // previous offset, each 8-byte relocation can be compressed to as little as 1
1548   // byte (or less with run-length encoding). This relocation packer was able to
1549   // reduce the size of the relocation section in an Android Chromium DSO from
1550   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1551   //
1552   // A relocation section consists of a header containing the literal bytes
1553   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1554   // elements are the total number of relocations in the section and an initial
1555   // r_offset value. The remaining elements define a sequence of relocation
1556   // groups. Each relocation group starts with a header consisting of the
1557   // following elements:
1558   //
1559   // - the number of relocations in the relocation group
1560   // - flags for the relocation group
1561   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1562   //   for each relocation in the group.
1563   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1564   //   field for each relocation in the group.
1565   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1566   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1567   //   each relocation in the group.
1568   //
1569   // Following the relocation group header are descriptions of each of the
1570   // relocations in the group. They consist of the following elements:
1571   //
1572   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1573   //   delta for this relocation.
1574   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1575   //   field for this relocation.
1576   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1577   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1578   //   this relocation.
1579 
1580   size_t OldSize = RelocData.size();
1581 
1582   RelocData = {'A', 'P', 'S', '2'};
1583   raw_svector_ostream OS(RelocData);
1584   auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1585 
1586   // The format header includes the number of relocations and the initial
1587   // offset (we set this to zero because the first relocation group will
1588   // perform the initial adjustment).
1589   Add(Relocs.size());
1590   Add(0);
1591 
1592   std::vector<Elf_Rela> Relatives, NonRelatives;
1593 
1594   for (const DynamicReloc &Rel : Relocs) {
1595     Elf_Rela R;
1596     encodeDynamicReloc<ELFT>(&R, Rel);
1597 
1598     if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1599       Relatives.push_back(R);
1600     else
1601       NonRelatives.push_back(R);
1602   }
1603 
1604   llvm::sort(Relatives.begin(), Relatives.end(),
1605              [](const Elf_Rel &A, const Elf_Rel &B) {
1606                return A.r_offset < B.r_offset;
1607              });
1608 
1609   // Try to find groups of relative relocations which are spaced one word
1610   // apart from one another. These generally correspond to vtable entries. The
1611   // format allows these groups to be encoded using a sort of run-length
1612   // encoding, but each group will cost 7 bytes in addition to the offset from
1613   // the previous group, so it is only profitable to do this for groups of
1614   // size 8 or larger.
1615   std::vector<Elf_Rela> UngroupedRelatives;
1616   std::vector<std::vector<Elf_Rela>> RelativeGroups;
1617   for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1618     std::vector<Elf_Rela> Group;
1619     do {
1620       Group.push_back(*I++);
1621     } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1622 
1623     if (Group.size() < 8)
1624       UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1625                                 Group.end());
1626     else
1627       RelativeGroups.emplace_back(std::move(Group));
1628   }
1629 
1630   unsigned HasAddendIfRela =
1631       Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1632 
1633   uint64_t Offset = 0;
1634   uint64_t Addend = 0;
1635 
1636   // Emit the run-length encoding for the groups of adjacent relative
1637   // relocations. Each group is represented using two groups in the packed
1638   // format. The first is used to set the current offset to the start of the
1639   // group (and also encodes the first relocation), and the second encodes the
1640   // remaining relocations.
1641   for (std::vector<Elf_Rela> &G : RelativeGroups) {
1642     // The first relocation in the group.
1643     Add(1);
1644     Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1645         RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1646     Add(G[0].r_offset - Offset);
1647     Add(Target->RelativeRel);
1648     if (Config->IsRela) {
1649       Add(G[0].r_addend - Addend);
1650       Addend = G[0].r_addend;
1651     }
1652 
1653     // The remaining relocations.
1654     Add(G.size() - 1);
1655     Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1656         RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1657     Add(Config->Wordsize);
1658     Add(Target->RelativeRel);
1659     if (Config->IsRela) {
1660       for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1661         Add(I->r_addend - Addend);
1662         Addend = I->r_addend;
1663       }
1664     }
1665 
1666     Offset = G.back().r_offset;
1667   }
1668 
1669   // Now the ungrouped relatives.
1670   if (!UngroupedRelatives.empty()) {
1671     Add(UngroupedRelatives.size());
1672     Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1673     Add(Target->RelativeRel);
1674     for (Elf_Rela &R : UngroupedRelatives) {
1675       Add(R.r_offset - Offset);
1676       Offset = R.r_offset;
1677       if (Config->IsRela) {
1678         Add(R.r_addend - Addend);
1679         Addend = R.r_addend;
1680       }
1681     }
1682   }
1683 
1684   // Finally the non-relative relocations.
1685   llvm::sort(NonRelatives.begin(), NonRelatives.end(),
1686              [](const Elf_Rela &A, const Elf_Rela &B) {
1687                return A.r_offset < B.r_offset;
1688              });
1689   if (!NonRelatives.empty()) {
1690     Add(NonRelatives.size());
1691     Add(HasAddendIfRela);
1692     for (Elf_Rela &R : NonRelatives) {
1693       Add(R.r_offset - Offset);
1694       Offset = R.r_offset;
1695       Add(R.r_info);
1696       if (Config->IsRela) {
1697         Add(R.r_addend - Addend);
1698         Addend = R.r_addend;
1699       }
1700     }
1701   }
1702 
1703   // Returns whether the section size changed. We need to keep recomputing both
1704   // section layout and the contents of this section until the size converges
1705   // because changing this section's size can affect section layout, which in
1706   // turn can affect the sizes of the LEB-encoded integers stored in this
1707   // section.
1708   return RelocData.size() != OldSize;
1709 }
1710 
1711 template <class ELFT> RelrSection<ELFT>::RelrSection() {
1712   this->Entsize = Config->Wordsize;
1713 }
1714 
1715 template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
1716   // This function computes the contents of an SHT_RELR packed relocation
1717   // section.
1718   //
1719   // Proposal for adding SHT_RELR sections to generic-abi is here:
1720   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
1721   //
1722   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
1723   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
1724   //
1725   // i.e. start with an address, followed by any number of bitmaps. The address
1726   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
1727   // relocations each, at subsequent offsets following the last address entry.
1728   //
1729   // The bitmap entries must have 1 in the least significant bit. The assumption
1730   // here is that an address cannot have 1 in lsb. Odd addresses are not
1731   // supported.
1732   //
1733   // Excluding the least significant bit in the bitmap, each non-zero bit in
1734   // the bitmap represents a relocation to be applied to a corresponding machine
1735   // word that follows the base address word. The second least significant bit
1736   // represents the machine word immediately following the initial address, and
1737   // each bit that follows represents the next word, in linear order. As such,
1738   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
1739   // 63 relocations in a 64-bit object.
1740   //
1741   // This encoding has a couple of interesting properties:
1742   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
1743   //    even means address, odd means bitmap.
1744   // 2. Just a simple list of addresses is a valid encoding.
1745 
1746   size_t OldSize = RelrRelocs.size();
1747   RelrRelocs.clear();
1748 
1749   // Same as Config->Wordsize but faster because this is a compile-time
1750   // constant.
1751   const size_t Wordsize = sizeof(typename ELFT::uint);
1752 
1753   // Number of bits to use for the relocation offsets bitmap.
1754   // Must be either 63 or 31.
1755   const size_t NBits = Wordsize * 8 - 1;
1756 
1757   // Get offsets for all relative relocations and sort them.
1758   std::vector<uint64_t> Offsets;
1759   for (const RelativeReloc &Rel : Relocs)
1760     Offsets.push_back(Rel.getOffset());
1761   llvm::sort(Offsets.begin(), Offsets.end());
1762 
1763   // For each leading relocation, find following ones that can be folded
1764   // as a bitmap and fold them.
1765   for (size_t I = 0, E = Offsets.size(); I < E;) {
1766     // Add a leading relocation.
1767     RelrRelocs.push_back(Elf_Relr(Offsets[I]));
1768     uint64_t Base = Offsets[I] + Wordsize;
1769     ++I;
1770 
1771     // Find foldable relocations to construct bitmaps.
1772     while (I < E) {
1773       uint64_t Bitmap = 0;
1774 
1775       while (I < E) {
1776         uint64_t Delta = Offsets[I] - Base;
1777 
1778         // If it is too far, it cannot be folded.
1779         if (Delta >= NBits * Wordsize)
1780           break;
1781 
1782         // If it is not a multiple of wordsize away, it cannot be folded.
1783         if (Delta % Wordsize)
1784           break;
1785 
1786         // Fold it.
1787         Bitmap |= 1ULL << (Delta / Wordsize);
1788         ++I;
1789       }
1790 
1791       if (!Bitmap)
1792         break;
1793 
1794       RelrRelocs.push_back(Elf_Relr((Bitmap << 1) | 1));
1795       Base += NBits * Wordsize;
1796     }
1797   }
1798 
1799   return RelrRelocs.size() != OldSize;
1800 }
1801 
1802 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1803     : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1804                        StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1805                        Config->Wordsize,
1806                        StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1807       StrTabSec(StrTabSec) {}
1808 
1809 // Orders symbols according to their positions in the GOT,
1810 // in compliance with MIPS ABI rules.
1811 // See "Global Offset Table" in Chapter 5 in the following document
1812 // for detailed description:
1813 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1814 static bool sortMipsSymbols(const SymbolTableEntry &L,
1815                             const SymbolTableEntry &R) {
1816   // Sort entries related to non-local preemptible symbols by GOT indexes.
1817   // All other entries go to the beginning of a dynsym in arbitrary order.
1818   if (L.Sym->isInGot() && R.Sym->isInGot())
1819     return L.Sym->GotIndex < R.Sym->GotIndex;
1820   if (!L.Sym->isInGot() && !R.Sym->isInGot())
1821     return false;
1822   return !L.Sym->isInGot();
1823 }
1824 
1825 void SymbolTableBaseSection::finalizeContents() {
1826   getParent()->Link = StrTabSec.getParent()->SectionIndex;
1827 
1828   if (this->Type != SHT_DYNSYM)
1829     return;
1830 
1831   // If it is a .dynsym, there should be no local symbols, but we need
1832   // to do a few things for the dynamic linker.
1833 
1834   // Section's Info field has the index of the first non-local symbol.
1835   // Because the first symbol entry is a null entry, 1 is the first.
1836   getParent()->Info = 1;
1837 
1838   if (InX::GnuHashTab) {
1839     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1840     InX::GnuHashTab->addSymbols(Symbols);
1841   } else if (Config->EMachine == EM_MIPS) {
1842     std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1843   }
1844 
1845   size_t I = 0;
1846   for (const SymbolTableEntry &S : Symbols)
1847     S.Sym->DynsymIndex = ++I;
1848 }
1849 
1850 // The ELF spec requires that all local symbols precede global symbols, so we
1851 // sort symbol entries in this function. (For .dynsym, we don't do that because
1852 // symbols for dynamic linking are inherently all globals.)
1853 //
1854 // Aside from above, we put local symbols in groups starting with the STT_FILE
1855 // symbol. That is convenient for purpose of identifying where are local symbols
1856 // coming from.
1857 void SymbolTableBaseSection::postThunkContents() {
1858   if (this->Type == SHT_DYNSYM)
1859     return;
1860 
1861   // Move all local symbols before global symbols.
1862   auto E = std::stable_partition(
1863       Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1864         return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
1865       });
1866   size_t NumLocals = E - Symbols.begin();
1867   getParent()->Info = NumLocals + 1;
1868 
1869   // We want to group the local symbols by file. For that we rebuild the local
1870   // part of the symbols vector. We do not need to care about the STT_FILE
1871   // symbols, they are already naturally placed first in each group. That
1872   // happens because STT_FILE is always the first symbol in the object and hence
1873   // precede all other local symbols we add for a file.
1874   MapVector<InputFile *, std::vector<SymbolTableEntry>> Arr;
1875   for (const SymbolTableEntry &S : llvm::make_range(Symbols.begin(), E))
1876     Arr[S.Sym->File].push_back(S);
1877 
1878   auto I = Symbols.begin();
1879   for (std::pair<InputFile *, std::vector<SymbolTableEntry>> &P : Arr)
1880     for (SymbolTableEntry &Entry : P.second)
1881       *I++ = Entry;
1882 }
1883 
1884 void SymbolTableBaseSection::addSymbol(Symbol *B) {
1885   // Adding a local symbol to a .dynsym is a bug.
1886   assert(this->Type != SHT_DYNSYM || !B->isLocal());
1887 
1888   bool HashIt = B->isLocal();
1889   Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1890 }
1891 
1892 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
1893   // Initializes symbol lookup tables lazily. This is used only
1894   // for -r or -emit-relocs.
1895   llvm::call_once(OnceFlag, [&] {
1896     SymbolIndexMap.reserve(Symbols.size());
1897     size_t I = 0;
1898     for (const SymbolTableEntry &E : Symbols) {
1899       if (E.Sym->Type == STT_SECTION)
1900         SectionIndexMap[E.Sym->getOutputSection()] = ++I;
1901       else
1902         SymbolIndexMap[E.Sym] = ++I;
1903     }
1904   });
1905 
1906   // Section symbols are mapped based on their output sections
1907   // to maintain their semantics.
1908   if (Sym->Type == STT_SECTION)
1909     return SectionIndexMap.lookup(Sym->getOutputSection());
1910   return SymbolIndexMap.lookup(Sym);
1911 }
1912 
1913 template <class ELFT>
1914 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1915     : SymbolTableBaseSection(StrTabSec) {
1916   this->Entsize = sizeof(Elf_Sym);
1917 }
1918 
1919 // Write the internal symbol table contents to the output symbol table.
1920 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1921   // The first entry is a null entry as per the ELF spec.
1922   memset(Buf, 0, sizeof(Elf_Sym));
1923   Buf += sizeof(Elf_Sym);
1924 
1925   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1926 
1927   for (SymbolTableEntry &Ent : Symbols) {
1928     Symbol *Sym = Ent.Sym;
1929 
1930     // Set st_info and st_other.
1931     ESym->st_other = 0;
1932     if (Sym->isLocal()) {
1933       ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1934     } else {
1935       ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1936       ESym->setVisibility(Sym->Visibility);
1937     }
1938 
1939     ESym->st_name = Ent.StrTabOffset;
1940 
1941     // Set a section index.
1942     BssSection *CommonSec = nullptr;
1943     if (!Config->DefineCommon)
1944       if (auto *D = dyn_cast<Defined>(Sym))
1945         CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1946     if (CommonSec)
1947       ESym->st_shndx = SHN_COMMON;
1948     else if (Sym->NeedsPltAddr)
1949       ESym->st_shndx = SHN_UNDEF;
1950     else if (const OutputSection *OutSec = Sym->getOutputSection())
1951       ESym->st_shndx = OutSec->SectionIndex;
1952     else if (isa<Defined>(Sym))
1953       ESym->st_shndx = SHN_ABS;
1954     else
1955       ESym->st_shndx = SHN_UNDEF;
1956 
1957     // Copy symbol size if it is a defined symbol. st_size is not significant
1958     // for undefined symbols, so whether copying it or not is up to us if that's
1959     // the case. We'll leave it as zero because by not setting a value, we can
1960     // get the exact same outputs for two sets of input files that differ only
1961     // in undefined symbol size in DSOs.
1962     if (ESym->st_shndx == SHN_UNDEF)
1963       ESym->st_size = 0;
1964     else
1965       ESym->st_size = Sym->getSize();
1966 
1967     // st_value is usually an address of a symbol, but that has a
1968     // special meaining for uninstantiated common symbols (this can
1969     // occur if -r is given).
1970     if (CommonSec)
1971       ESym->st_value = CommonSec->Alignment;
1972     else
1973       ESym->st_value = Sym->getVA();
1974 
1975     ++ESym;
1976   }
1977 
1978   // On MIPS we need to mark symbol which has a PLT entry and requires
1979   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1980   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1981   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1982   if (Config->EMachine == EM_MIPS) {
1983     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1984 
1985     for (SymbolTableEntry &Ent : Symbols) {
1986       Symbol *Sym = Ent.Sym;
1987       if (Sym->isInPlt() && Sym->NeedsPltAddr)
1988         ESym->st_other |= STO_MIPS_PLT;
1989       if (isMicroMips()) {
1990         // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1991         // a defined microMIPS symbol and symbol should point to its
1992         // PLT entry (in case of microMIPS, PLT entries always contain
1993         // microMIPS code).
1994         if (Sym->isDefined() &&
1995             ((Sym->StOther & STO_MIPS_MICROMIPS) || Sym->NeedsPltAddr)) {
1996           if (StrTabSec.isDynamic())
1997             ESym->st_value |= 1;
1998           ESym->st_other |= STO_MIPS_MICROMIPS;
1999         }
2000       }
2001       if (Config->Relocatable)
2002         if (auto *D = dyn_cast<Defined>(Sym))
2003           if (isMipsPIC<ELFT>(D))
2004             ESym->st_other |= STO_MIPS_PIC;
2005       ++ESym;
2006     }
2007   }
2008 }
2009 
2010 // .hash and .gnu.hash sections contain on-disk hash tables that map
2011 // symbol names to their dynamic symbol table indices. Their purpose
2012 // is to help the dynamic linker resolve symbols quickly. If ELF files
2013 // don't have them, the dynamic linker has to do linear search on all
2014 // dynamic symbols, which makes programs slower. Therefore, a .hash
2015 // section is added to a DSO by default. A .gnu.hash is added if you
2016 // give the -hash-style=gnu or -hash-style=both option.
2017 //
2018 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
2019 // Each ELF file has a list of DSOs that the ELF file depends on and a
2020 // list of dynamic symbols that need to be resolved from any of the
2021 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2022 // where m is the number of DSOs and n is the number of dynamic
2023 // symbols. For modern large programs, both m and n are large.  So
2024 // making each step faster by using hash tables substiantially
2025 // improves time to load programs.
2026 //
2027 // (Note that this is not the only way to design the shared library.
2028 // For instance, the Windows DLL takes a different approach. On
2029 // Windows, each dynamic symbol has a name of DLL from which the symbol
2030 // has to be resolved. That makes the cost of symbol resolution O(n).
2031 // This disables some hacky techniques you can use on Unix such as
2032 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2033 //
2034 // Due to historical reasons, we have two different hash tables, .hash
2035 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2036 // and better version of .hash. .hash is just an on-disk hash table, but
2037 // .gnu.hash has a bloom filter in addition to a hash table to skip
2038 // DSOs very quickly. If you are sure that your dynamic linker knows
2039 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
2040 // safe bet is to specify -hash-style=both for backward compatibilty.
2041 GnuHashTableSection::GnuHashTableSection()
2042     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
2043 }
2044 
2045 void GnuHashTableSection::finalizeContents() {
2046   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
2047 
2048   // Computes bloom filter size in word size. We want to allocate 12
2049   // bits for each symbol. It must be a power of two.
2050   if (Symbols.empty()) {
2051     MaskWords = 1;
2052   } else {
2053     uint64_t NumBits = Symbols.size() * 12;
2054     MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8));
2055   }
2056 
2057   Size = 16;                            // Header
2058   Size += Config->Wordsize * MaskWords; // Bloom filter
2059   Size += NBuckets * 4;                 // Hash buckets
2060   Size += Symbols.size() * 4;           // Hash values
2061 }
2062 
2063 void GnuHashTableSection::writeTo(uint8_t *Buf) {
2064   // The output buffer is not guaranteed to be zero-cleared because we pre-
2065   // fill executable sections with trap instructions. This is a precaution
2066   // for that case, which happens only when -no-rosegment is given.
2067   memset(Buf, 0, Size);
2068 
2069   // Write a header.
2070   write32(Buf, NBuckets);
2071   write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
2072   write32(Buf + 8, MaskWords);
2073   write32(Buf + 12, Shift2);
2074   Buf += 16;
2075 
2076   // Write a bloom filter and a hash table.
2077   writeBloomFilter(Buf);
2078   Buf += Config->Wordsize * MaskWords;
2079   writeHashTable(Buf);
2080 }
2081 
2082 // This function writes a 2-bit bloom filter. This bloom filter alone
2083 // usually filters out 80% or more of all symbol lookups [1].
2084 // The dynamic linker uses the hash table only when a symbol is not
2085 // filtered out by a bloom filter.
2086 //
2087 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
2088 //     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
2089 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
2090   unsigned C = Config->Is64 ? 64 : 32;
2091   for (const Entry &Sym : Symbols) {
2092     size_t I = (Sym.Hash / C) & (MaskWords - 1);
2093     uint64_t Val = readUint(Buf + I * Config->Wordsize);
2094     Val |= uint64_t(1) << (Sym.Hash % C);
2095     Val |= uint64_t(1) << ((Sym.Hash >> Shift2) % C);
2096     writeUint(Buf + I * Config->Wordsize, Val);
2097   }
2098 }
2099 
2100 void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
2101   uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
2102   uint32_t OldBucket = -1;
2103   uint32_t *Values = Buckets + NBuckets;
2104   for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
2105     // Write a hash value. It represents a sequence of chains that share the
2106     // same hash modulo value. The last element of each chain is terminated by
2107     // LSB 1.
2108     uint32_t Hash = I->Hash;
2109     bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
2110     Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
2111     write32(Values++, Hash);
2112 
2113     if (I->BucketIdx == OldBucket)
2114       continue;
2115     // Write a hash bucket. Hash buckets contain indices in the following hash
2116     // value table.
2117     write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
2118     OldBucket = I->BucketIdx;
2119   }
2120 }
2121 
2122 static uint32_t hashGnu(StringRef Name) {
2123   uint32_t H = 5381;
2124   for (uint8_t C : Name)
2125     H = (H << 5) + H + C;
2126   return H;
2127 }
2128 
2129 // Add symbols to this symbol hash table. Note that this function
2130 // destructively sort a given vector -- which is needed because
2131 // GNU-style hash table places some sorting requirements.
2132 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
2133   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2134   // its type correctly.
2135   std::vector<SymbolTableEntry>::iterator Mid =
2136       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
2137         return !S.Sym->isDefined();
2138       });
2139 
2140   // We chose load factor 4 for the on-disk hash table. For each hash
2141   // collision, the dynamic linker will compare a uint32_t hash value.
2142   // Since the integer comparison is quite fast, we believe we can
2143   // make the load factor even larger. 4 is just a conservative choice.
2144   //
2145   // Note that we don't want to create a zero-sized hash table because
2146   // Android loader as of 2018 doesn't like a .gnu.hash containing such
2147   // table. If that's the case, we create a hash table with one unused
2148   // dummy slot.
2149   NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
2150 
2151   if (Mid == V.end())
2152     return;
2153 
2154   for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
2155     Symbol *B = Ent.Sym;
2156     uint32_t Hash = hashGnu(B->getName());
2157     uint32_t BucketIdx = Hash % NBuckets;
2158     Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
2159   }
2160 
2161   std::stable_sort(
2162       Symbols.begin(), Symbols.end(),
2163       [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
2164 
2165   V.erase(Mid, V.end());
2166   for (const Entry &Ent : Symbols)
2167     V.push_back({Ent.Sym, Ent.StrTabOffset});
2168 }
2169 
2170 HashTableSection::HashTableSection()
2171     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2172   this->Entsize = 4;
2173 }
2174 
2175 void HashTableSection::finalizeContents() {
2176   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
2177 
2178   unsigned NumEntries = 2;                       // nbucket and nchain.
2179   NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
2180 
2181   // Create as many buckets as there are symbols.
2182   NumEntries += InX::DynSymTab->getNumSymbols();
2183   this->Size = NumEntries * 4;
2184 }
2185 
2186 void HashTableSection::writeTo(uint8_t *Buf) {
2187   // See comment in GnuHashTableSection::writeTo.
2188   memset(Buf, 0, Size);
2189 
2190   unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
2191 
2192   uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
2193   write32(P++, NumSymbols); // nbucket
2194   write32(P++, NumSymbols); // nchain
2195 
2196   uint32_t *Buckets = P;
2197   uint32_t *Chains = P + NumSymbols;
2198 
2199   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
2200     Symbol *Sym = S.Sym;
2201     StringRef Name = Sym->getName();
2202     unsigned I = Sym->DynsymIndex;
2203     uint32_t Hash = hashSysV(Name) % NumSymbols;
2204     Chains[I] = Buckets[Hash];
2205     write32(Buckets + Hash, I);
2206   }
2207 }
2208 
2209 // On PowerPC64 the lazy symbol resolvers go into the `global linkage table`
2210 // in the .glink section, rather then the typical .plt section.
2211 PltSection::PltSection(bool IsIplt)
2212     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
2213                        Config->EMachine == EM_PPC64 ? ".glink" : ".plt"),
2214       HeaderSize(IsIplt ? 0 : Target->PltHeaderSize), IsIplt(IsIplt) {
2215   // The PLT needs to be writable on SPARC as the dynamic linker will
2216   // modify the instructions in the PLT entries.
2217   if (Config->EMachine == EM_SPARCV9)
2218     this->Flags |= SHF_WRITE;
2219 }
2220 
2221 void PltSection::writeTo(uint8_t *Buf) {
2222   // At beginning of PLT but not the IPLT, we have code to call the dynamic
2223   // linker to resolve dynsyms at runtime. Write such code.
2224   if (!IsIplt)
2225     Target->writePltHeader(Buf);
2226   size_t Off = HeaderSize;
2227   // The IPlt is immediately after the Plt, account for this in RelOff
2228   unsigned PltOff = getPltRelocOff();
2229 
2230   for (auto &I : Entries) {
2231     const Symbol *B = I.first;
2232     unsigned RelOff = I.second + PltOff;
2233     uint64_t Got = B->getGotPltVA();
2234     uint64_t Plt = this->getVA() + Off;
2235     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
2236     Off += Target->PltEntrySize;
2237   }
2238 }
2239 
2240 template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
2241   Sym.PltIndex = Entries.size();
2242   RelocationBaseSection *PltRelocSection = InX::RelaPlt;
2243   if (IsIplt) {
2244     PltRelocSection = InX::RelaIplt;
2245     Sym.IsInIplt = true;
2246   }
2247   unsigned RelOff =
2248       static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
2249   Entries.push_back(std::make_pair(&Sym, RelOff));
2250 }
2251 
2252 size_t PltSection::getSize() const {
2253   return HeaderSize + Entries.size() * Target->PltEntrySize;
2254 }
2255 
2256 // Some architectures such as additional symbols in the PLT section. For
2257 // example ARM uses mapping symbols to aid disassembly
2258 void PltSection::addSymbols() {
2259   // The PLT may have symbols defined for the Header, the IPLT has no header
2260   if (!IsIplt)
2261     Target->addPltHeaderSymbols(*this);
2262   size_t Off = HeaderSize;
2263   for (size_t I = 0; I < Entries.size(); ++I) {
2264     Target->addPltSymbols(*this, Off);
2265     Off += Target->PltEntrySize;
2266   }
2267 }
2268 
2269 unsigned PltSection::getPltRelocOff() const {
2270   return IsIplt ? InX::Plt->getSize() : 0;
2271 }
2272 
2273 // The string hash function for .gdb_index.
2274 static uint32_t computeGdbHash(StringRef S) {
2275   uint32_t H = 0;
2276   for (uint8_t C : S)
2277     H = H * 67 + tolower(C) - 113;
2278   return H;
2279 }
2280 
2281 GdbIndexSection::GdbIndexSection()
2282     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2283 
2284 // Returns the desired size of an on-disk hash table for a .gdb_index section.
2285 // There's a tradeoff between size and collision rate. We aim 75% utilization.
2286 size_t GdbIndexSection::computeSymtabSize() const {
2287   return std::max<size_t>(NextPowerOf2(Symbols.size() * 4 / 3), 1024);
2288 }
2289 
2290 // Compute the output section size.
2291 void GdbIndexSection::initOutputSize() {
2292   Size = sizeof(GdbIndexHeader) + computeSymtabSize() * 8;
2293 
2294   for (GdbChunk &Chunk : Chunks)
2295     Size += Chunk.CompilationUnits.size() * 16 + Chunk.AddressAreas.size() * 20;
2296 
2297   // Add the constant pool size if exists.
2298   if (!Symbols.empty()) {
2299     GdbSymbol &Sym = Symbols.back();
2300     Size += Sym.NameOff + Sym.Name.size() + 1;
2301   }
2302 }
2303 
2304 static std::vector<InputSection *> getDebugInfoSections() {
2305   std::vector<InputSection *> Ret;
2306   for (InputSectionBase *S : InputSections)
2307     if (InputSection *IS = dyn_cast<InputSection>(S))
2308       if (IS->Name == ".debug_info")
2309         Ret.push_back(IS);
2310   return Ret;
2311 }
2312 
2313 static std::vector<GdbIndexSection::CuEntry> readCuList(DWARFContext &Dwarf) {
2314   std::vector<GdbIndexSection::CuEntry> Ret;
2315   for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
2316     Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
2317   return Ret;
2318 }
2319 
2320 static std::vector<GdbIndexSection::AddressEntry>
2321 readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
2322   std::vector<GdbIndexSection::AddressEntry> Ret;
2323 
2324   uint32_t CuIdx = 0;
2325   for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
2326     DWARFAddressRangesVector Ranges;
2327     Cu->collectAddressRanges(Ranges);
2328 
2329     ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
2330     for (DWARFAddressRange &R : Ranges) {
2331       InputSectionBase *S = Sections[R.SectionIndex];
2332       if (!S || S == &InputSection::Discarded || !S->Live)
2333         continue;
2334       // Range list with zero size has no effect.
2335       if (R.LowPC == R.HighPC)
2336         continue;
2337       auto *IS = cast<InputSection>(S);
2338       uint64_t Offset = IS->getOffsetInFile();
2339       Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
2340     }
2341     ++CuIdx;
2342   }
2343   return Ret;
2344 }
2345 
2346 static std::vector<GdbIndexSection::NameTypeEntry>
2347 readPubNamesAndTypes(DWARFContext &Dwarf, uint32_t Idx) {
2348   StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
2349   StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
2350 
2351   std::vector<GdbIndexSection::NameTypeEntry> Ret;
2352   for (StringRef Sec : {Sec1, Sec2}) {
2353     DWARFDebugPubTable Table(Sec, Config->IsLE, true);
2354     for (const DWARFDebugPubTable::Set &Set : Table.getData())
2355       for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
2356         Ret.push_back({{Ent.Name, computeGdbHash(Ent.Name)},
2357                        (Ent.Descriptor.toBits() << 24) | Idx});
2358   }
2359   return Ret;
2360 }
2361 
2362 // Create a list of symbols from a given list of symbol names and types
2363 // by uniquifying them by name.
2364 static std::vector<GdbIndexSection::GdbSymbol>
2365 createSymbols(ArrayRef<std::vector<GdbIndexSection::NameTypeEntry>> NameTypes) {
2366   typedef GdbIndexSection::GdbSymbol GdbSymbol;
2367   typedef GdbIndexSection::NameTypeEntry NameTypeEntry;
2368 
2369   // The number of symbols we will handle in this function is of the order
2370   // of millions for very large executables, so we use multi-threading to
2371   // speed it up.
2372   size_t NumShards = 32;
2373   size_t Concurrency = 1;
2374   if (ThreadsEnabled)
2375     Concurrency =
2376         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
2377 
2378   // A sharded map to uniquify symbols by name.
2379   std::vector<DenseMap<CachedHashStringRef, size_t>> Map(NumShards);
2380   size_t Shift = 32 - countTrailingZeros(NumShards);
2381 
2382   // Instantiate GdbSymbols while uniqufying them by name.
2383   std::vector<std::vector<GdbSymbol>> Symbols(NumShards);
2384   parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2385     for (ArrayRef<NameTypeEntry> Entries : NameTypes) {
2386       for (const NameTypeEntry &Ent : Entries) {
2387         size_t ShardId = Ent.Name.hash() >> Shift;
2388         if ((ShardId & (Concurrency - 1)) != ThreadId)
2389           continue;
2390 
2391         size_t &Idx = Map[ShardId][Ent.Name];
2392         if (Idx) {
2393           Symbols[ShardId][Idx - 1].CuVector.push_back(Ent.Type);
2394           continue;
2395         }
2396 
2397         Idx = Symbols[ShardId].size() + 1;
2398         Symbols[ShardId].push_back({Ent.Name, {Ent.Type}, 0, 0});
2399       }
2400     }
2401   });
2402 
2403   size_t NumSymbols = 0;
2404   for (ArrayRef<GdbSymbol> V : Symbols)
2405     NumSymbols += V.size();
2406 
2407   // The return type is a flattened vector, so we'll copy each vector
2408   // contents to Ret.
2409   std::vector<GdbSymbol> Ret;
2410   Ret.reserve(NumSymbols);
2411   for (std::vector<GdbSymbol> &Vec : Symbols)
2412     for (GdbSymbol &Sym : Vec)
2413       Ret.push_back(std::move(Sym));
2414 
2415   // CU vectors and symbol names are adjacent in the output file.
2416   // We can compute their offsets in the output file now.
2417   size_t Off = 0;
2418   for (GdbSymbol &Sym : Ret) {
2419     Sym.CuVectorOff = Off;
2420     Off += (Sym.CuVector.size() + 1) * 4;
2421   }
2422   for (GdbSymbol &Sym : Ret) {
2423     Sym.NameOff = Off;
2424     Off += Sym.Name.size() + 1;
2425   }
2426 
2427   return Ret;
2428 }
2429 
2430 // Returns a newly-created .gdb_index section.
2431 template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
2432   std::vector<InputSection *> Sections = getDebugInfoSections();
2433 
2434   // .debug_gnu_pub{names,types} are useless in executables.
2435   // They are present in input object files solely for creating
2436   // a .gdb_index. So we can remove them from the output.
2437   for (InputSectionBase *S : InputSections)
2438     if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2439       S->Live = false;
2440 
2441   std::vector<GdbChunk> Chunks(Sections.size());
2442   std::vector<std::vector<NameTypeEntry>> NameTypes(Sections.size());
2443 
2444   parallelForEachN(0, Sections.size(), [&](size_t I) {
2445     ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2446     DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2447 
2448     Chunks[I].Sec = Sections[I];
2449     Chunks[I].CompilationUnits = readCuList(Dwarf);
2450     Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2451     NameTypes[I] = readPubNamesAndTypes(Dwarf, I);
2452   });
2453 
2454   auto *Ret = make<GdbIndexSection>();
2455   Ret->Chunks = std::move(Chunks);
2456   Ret->Symbols = createSymbols(NameTypes);
2457   Ret->initOutputSize();
2458   return Ret;
2459 }
2460 
2461 void GdbIndexSection::writeTo(uint8_t *Buf) {
2462   // Write the header.
2463   auto *Hdr = reinterpret_cast<GdbIndexHeader *>(Buf);
2464   uint8_t *Start = Buf;
2465   Hdr->Version = 7;
2466   Buf += sizeof(*Hdr);
2467 
2468   // Write the CU list.
2469   Hdr->CuListOff = Buf - Start;
2470   for (GdbChunk &Chunk : Chunks) {
2471     for (CuEntry &Cu : Chunk.CompilationUnits) {
2472       write64le(Buf, Chunk.Sec->OutSecOff + Cu.CuOffset);
2473       write64le(Buf + 8, Cu.CuLength);
2474       Buf += 16;
2475     }
2476   }
2477 
2478   // Write the address area.
2479   Hdr->CuTypesOff = Buf - Start;
2480   Hdr->AddressAreaOff = Buf - Start;
2481   uint32_t CuOff = 0;
2482   for (GdbChunk &Chunk : Chunks) {
2483     for (AddressEntry &E : Chunk.AddressAreas) {
2484       uint64_t BaseAddr = E.Section->getVA(0);
2485       write64le(Buf, BaseAddr + E.LowAddress);
2486       write64le(Buf + 8, BaseAddr + E.HighAddress);
2487       write32le(Buf + 16, E.CuIndex + CuOff);
2488       Buf += 20;
2489     }
2490     CuOff += Chunk.CompilationUnits.size();
2491   }
2492 
2493   // Write the on-disk open-addressing hash table containing symbols.
2494   Hdr->SymtabOff = Buf - Start;
2495   size_t SymtabSize = computeSymtabSize();
2496   uint32_t Mask = SymtabSize - 1;
2497 
2498   for (GdbSymbol &Sym : Symbols) {
2499     uint32_t H = Sym.Name.hash();
2500     uint32_t I = H & Mask;
2501     uint32_t Step = ((H * 17) & Mask) | 1;
2502 
2503     while (read32le(Buf + I * 8))
2504       I = (I + Step) & Mask;
2505 
2506     write32le(Buf + I * 8, Sym.NameOff);
2507     write32le(Buf + I * 8 + 4, Sym.CuVectorOff);
2508   }
2509 
2510   Buf += SymtabSize * 8;
2511 
2512   // Write the string pool.
2513   Hdr->ConstantPoolOff = Buf - Start;
2514   for (GdbSymbol &Sym : Symbols)
2515     memcpy(Buf + Sym.NameOff, Sym.Name.data(), Sym.Name.size());
2516 
2517   // Write the CU vectors.
2518   for (GdbSymbol &Sym : Symbols) {
2519     write32le(Buf, Sym.CuVector.size());
2520     Buf += 4;
2521     for (uint32_t Val : Sym.CuVector) {
2522       write32le(Buf, Val);
2523       Buf += 4;
2524     }
2525   }
2526 }
2527 
2528 bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
2529 
2530 EhFrameHeader::EhFrameHeader()
2531     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
2532 
2533 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2534 // Each entry of the search table consists of two values,
2535 // the starting PC from where FDEs covers, and the FDE's address.
2536 // It is sorted by PC.
2537 void EhFrameHeader::writeTo(uint8_t *Buf) {
2538   typedef EhFrameSection::FdeData FdeData;
2539 
2540   std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
2541 
2542   // Sort the FDE list by their PC and uniqueify. Usually there is only
2543   // one FDE for a PC (i.e. function), but if ICF merges two functions
2544   // into one, there can be more than one FDEs pointing to the address.
2545   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2546   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2547   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2548   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2549 
2550   Buf[0] = 1;
2551   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2552   Buf[2] = DW_EH_PE_udata4;
2553   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2554   write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2555   write32(Buf + 8, Fdes.size());
2556   Buf += 12;
2557 
2558   uint64_t VA = this->getVA();
2559   for (FdeData &Fde : Fdes) {
2560     write32(Buf, Fde.Pc - VA);
2561     write32(Buf + 4, Fde.FdeVA - VA);
2562     Buf += 8;
2563   }
2564 }
2565 
2566 size_t EhFrameHeader::getSize() const {
2567   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
2568   return 12 + InX::EhFrame->NumFdes * 8;
2569 }
2570 
2571 bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
2572 
2573 template <class ELFT>
2574 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
2575     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2576                        ".gnu.version_d") {}
2577 
2578 static StringRef getFileDefName() {
2579   if (!Config->SoName.empty())
2580     return Config->SoName;
2581   return Config->OutputFile;
2582 }
2583 
2584 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
2585   FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
2586   for (VersionDefinition &V : Config->VersionDefinitions)
2587     V.NameOff = InX::DynStrTab->addString(V.Name);
2588 
2589   getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2590 
2591   // sh_info should be set to the number of definitions. This fact is missed in
2592   // documentation, but confirmed by binutils community:
2593   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
2594   getParent()->Info = getVerDefNum();
2595 }
2596 
2597 template <class ELFT>
2598 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2599                                               StringRef Name, size_t NameOff) {
2600   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2601   Verdef->vd_version = 1;
2602   Verdef->vd_cnt = 1;
2603   Verdef->vd_aux = sizeof(Elf_Verdef);
2604   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2605   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2606   Verdef->vd_ndx = Index;
2607   Verdef->vd_hash = hashSysV(Name);
2608 
2609   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2610   Verdaux->vda_name = NameOff;
2611   Verdaux->vda_next = 0;
2612 }
2613 
2614 template <class ELFT>
2615 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2616   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2617 
2618   for (VersionDefinition &V : Config->VersionDefinitions) {
2619     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2620     writeOne(Buf, V.Id, V.Name, V.NameOff);
2621   }
2622 
2623   // Need to terminate the last version definition.
2624   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2625   Verdef->vd_next = 0;
2626 }
2627 
2628 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2629   return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2630 }
2631 
2632 template <class ELFT>
2633 VersionTableSection<ELFT>::VersionTableSection()
2634     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
2635                        ".gnu.version") {
2636   this->Entsize = sizeof(Elf_Versym);
2637 }
2638 
2639 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
2640   // At the moment of june 2016 GNU docs does not mention that sh_link field
2641   // should be set, but Sun docs do. Also readelf relies on this field.
2642   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
2643 }
2644 
2645 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2646   return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
2647 }
2648 
2649 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2650   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2651   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
2652     OutVersym->vs_index = S.Sym->VersionId;
2653     ++OutVersym;
2654   }
2655 }
2656 
2657 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2658   return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2659 }
2660 
2661 template <class ELFT>
2662 VersionNeedSection<ELFT>::VersionNeedSection()
2663     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2664                        ".gnu.version_r") {
2665   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2666   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2667   // First identifiers are reserved by verdef section if it exist.
2668   NextIndex = getVerDefNum() + 1;
2669 }
2670 
2671 template <class ELFT> void VersionNeedSection<ELFT>::addSymbol(Symbol *SS) {
2672   auto &File = cast<SharedFile<ELFT>>(*SS->File);
2673   if (SS->VerdefIndex == VER_NDX_GLOBAL) {
2674     SS->VersionId = VER_NDX_GLOBAL;
2675     return;
2676   }
2677 
2678   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2679   // to create one by adding it to our needed list and creating a dynstr entry
2680   // for the soname.
2681   if (File.VerdefMap.empty())
2682     Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)});
2683   const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex];
2684   typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver];
2685 
2686   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2687   // prepare to create one by allocating a version identifier and creating a
2688   // dynstr entry for the version name.
2689   if (NV.Index == 0) {
2690     NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() +
2691                                           Ver->getAux()->vda_name);
2692     NV.Index = NextIndex++;
2693   }
2694   SS->VersionId = NV.Index;
2695 }
2696 
2697 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2698   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2699   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2700   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2701 
2702   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2703     // Create an Elf_Verneed for this DSO.
2704     Verneed->vn_version = 1;
2705     Verneed->vn_cnt = P.first->VerdefMap.size();
2706     Verneed->vn_file = P.second;
2707     Verneed->vn_aux =
2708         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2709     Verneed->vn_next = sizeof(Elf_Verneed);
2710     ++Verneed;
2711 
2712     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2713     // VerdefMap, which will only contain references to needed version
2714     // definitions. Each Elf_Vernaux is based on the information contained in
2715     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2716     // pointers, but is deterministic because the pointers refer to Elf_Verdef
2717     // data structures within a single input file.
2718     for (auto &NV : P.first->VerdefMap) {
2719       Vernaux->vna_hash = NV.first->vd_hash;
2720       Vernaux->vna_flags = 0;
2721       Vernaux->vna_other = NV.second.Index;
2722       Vernaux->vna_name = NV.second.StrTab;
2723       Vernaux->vna_next = sizeof(Elf_Vernaux);
2724       ++Vernaux;
2725     }
2726 
2727     Vernaux[-1].vna_next = 0;
2728   }
2729   Verneed[-1].vn_next = 0;
2730 }
2731 
2732 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2733   getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2734   getParent()->Info = Needed.size();
2735 }
2736 
2737 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2738   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2739   for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2740     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2741   return Size;
2742 }
2743 
2744 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2745   return getNeedNum() == 0;
2746 }
2747 
2748 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2749   MS->Parent = this;
2750   Sections.push_back(MS);
2751 }
2752 
2753 MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2754                                    uint64_t Flags, uint32_t Alignment)
2755     : MergeSyntheticSection(Name, Type, Flags, Alignment),
2756       Builder(StringTableBuilder::RAW, Alignment) {}
2757 
2758 size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2759 
2760 void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2761 
2762 void MergeTailSection::finalizeContents() {
2763   // Add all string pieces to the string table builder to create section
2764   // contents.
2765   for (MergeInputSection *Sec : Sections)
2766     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2767       if (Sec->Pieces[I].Live)
2768         Builder.add(Sec->getData(I));
2769 
2770   // Fix the string table content. After this, the contents will never change.
2771   Builder.finalize();
2772 
2773   // finalize() fixed tail-optimized strings, so we can now get
2774   // offsets of strings. Get an offset for each string and save it
2775   // to a corresponding StringPiece for easy access.
2776   for (MergeInputSection *Sec : Sections)
2777     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2778       if (Sec->Pieces[I].Live)
2779         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2780 }
2781 
2782 void MergeNoTailSection::writeTo(uint8_t *Buf) {
2783   for (size_t I = 0; I < NumShards; ++I)
2784     Shards[I].write(Buf + ShardOffsets[I]);
2785 }
2786 
2787 // This function is very hot (i.e. it can take several seconds to finish)
2788 // because sometimes the number of inputs is in an order of magnitude of
2789 // millions. So, we use multi-threading.
2790 //
2791 // For any strings S and T, we know S is not mergeable with T if S's hash
2792 // value is different from T's. If that's the case, we can safely put S and
2793 // T into different string builders without worrying about merge misses.
2794 // We do it in parallel.
2795 void MergeNoTailSection::finalizeContents() {
2796   // Initializes string table builders.
2797   for (size_t I = 0; I < NumShards; ++I)
2798     Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2799 
2800   // Concurrency level. Must be a power of 2 to avoid expensive modulo
2801   // operations in the following tight loop.
2802   size_t Concurrency = 1;
2803   if (ThreadsEnabled)
2804     Concurrency =
2805         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
2806 
2807   // Add section pieces to the builders.
2808   parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2809     for (MergeInputSection *Sec : Sections) {
2810       for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2811         size_t ShardId = getShardId(Sec->Pieces[I].Hash);
2812         if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live)
2813           Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
2814       }
2815     }
2816   });
2817 
2818   // Compute an in-section offset for each shard.
2819   size_t Off = 0;
2820   for (size_t I = 0; I < NumShards; ++I) {
2821     Shards[I].finalizeInOrder();
2822     if (Shards[I].getSize() > 0)
2823       Off = alignTo(Off, Alignment);
2824     ShardOffsets[I] = Off;
2825     Off += Shards[I].getSize();
2826   }
2827   Size = Off;
2828 
2829   // So far, section pieces have offsets from beginning of shards, but
2830   // we want offsets from beginning of the whole section. Fix them.
2831   parallelForEach(Sections, [&](MergeInputSection *Sec) {
2832     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2833       if (Sec->Pieces[I].Live)
2834         Sec->Pieces[I].OutputOff +=
2835             ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
2836   });
2837 }
2838 
2839 static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2840                                                    uint32_t Type,
2841                                                    uint64_t Flags,
2842                                                    uint32_t Alignment) {
2843   bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2844   if (ShouldTailMerge)
2845     return make<MergeTailSection>(Name, Type, Flags, Alignment);
2846   return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
2847 }
2848 
2849 // Debug sections may be compressed by zlib. Decompress if exists.
2850 void elf::decompressSections() {
2851   parallelForEach(InputSections,
2852                   [](InputSectionBase *Sec) { Sec->maybeDecompress(); });
2853 }
2854 
2855 template <class ELFT> void elf::splitSections() {
2856   // splitIntoPieces needs to be called on each MergeInputSection
2857   // before calling finalizeContents().
2858   parallelForEach(InputSections, [](InputSectionBase *Sec) {
2859     if (auto *S = dyn_cast<MergeInputSection>(Sec))
2860       S->splitIntoPieces();
2861     else if (auto *Eh = dyn_cast<EhInputSection>(Sec))
2862       Eh->split<ELFT>();
2863   });
2864 }
2865 
2866 // This function scans over the inputsections to create mergeable
2867 // synthetic sections.
2868 //
2869 // It removes MergeInputSections from the input section array and adds
2870 // new synthetic sections at the location of the first input section
2871 // that it replaces. It then finalizes each synthetic section in order
2872 // to compute an output offset for each piece of each input section.
2873 void elf::mergeSections() {
2874   std::vector<MergeSyntheticSection *> MergeSections;
2875   for (InputSectionBase *&S : InputSections) {
2876     MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2877     if (!MS)
2878       continue;
2879 
2880     // We do not want to handle sections that are not alive, so just remove
2881     // them instead of trying to merge.
2882     if (!MS->Live)
2883       continue;
2884 
2885     StringRef OutsecName = getOutputSectionName(MS);
2886     uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2887 
2888     auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
2889       // While we could create a single synthetic section for two different
2890       // values of Entsize, it is better to take Entsize into consideration.
2891       //
2892       // With a single synthetic section no two pieces with different Entsize
2893       // could be equal, so we may as well have two sections.
2894       //
2895       // Using Entsize in here also allows us to propagate it to the synthetic
2896       // section.
2897       return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
2898              Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
2899     });
2900     if (I == MergeSections.end()) {
2901       MergeSyntheticSection *Syn =
2902           createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
2903       MergeSections.push_back(Syn);
2904       I = std::prev(MergeSections.end());
2905       S = Syn;
2906       Syn->Entsize = MS->Entsize;
2907     } else {
2908       S = nullptr;
2909     }
2910     (*I)->addSection(MS);
2911   }
2912   for (auto *MS : MergeSections)
2913     MS->finalizeContents();
2914 
2915   std::vector<InputSectionBase *> &V = InputSections;
2916   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2917 }
2918 
2919 MipsRldMapSection::MipsRldMapSection()
2920     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2921                        ".rld_map") {}
2922 
2923 ARMExidxSentinelSection::ARMExidxSentinelSection()
2924     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2925                        Config->Wordsize, ".ARM.exidx") {}
2926 
2927 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
2928 // This section will have been sorted last in the .ARM.exidx table.
2929 // This table entry will have the form:
2930 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
2931 // The sentinel must have the PREL31 value of an address higher than any
2932 // address described by any other table entry.
2933 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
2934   assert(Highest);
2935   uint64_t S = Highest->getVA(Highest->getSize());
2936   uint64_t P = getVA();
2937   Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2938   write32le(Buf + 4, 1);
2939 }
2940 
2941 // The sentinel has to be removed if there are no other .ARM.exidx entries.
2942 bool ARMExidxSentinelSection::empty() const {
2943   for (InputSection *IS : getInputSections(getParent()))
2944     if (!isa<ARMExidxSentinelSection>(IS))
2945       return false;
2946   return true;
2947 }
2948 
2949 bool ARMExidxSentinelSection::classof(const SectionBase *D) {
2950   return D->kind() == InputSectionBase::Synthetic && D->Type == SHT_ARM_EXIDX;
2951 }
2952 
2953 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
2954     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
2955                        Config->Wordsize, ".text.thunk") {
2956   this->Parent = OS;
2957   this->OutSecOff = Off;
2958 }
2959 
2960 void ThunkSection::addThunk(Thunk *T) {
2961   Thunks.push_back(T);
2962   T->addSymbols(*this);
2963 }
2964 
2965 void ThunkSection::writeTo(uint8_t *Buf) {
2966   for (Thunk *T : Thunks)
2967     T->writeTo(Buf + T->Offset);
2968 }
2969 
2970 InputSection *ThunkSection::getTargetInputSection() const {
2971   if (Thunks.empty())
2972     return nullptr;
2973   const Thunk *T = Thunks.front();
2974   return T->getTargetInputSection();
2975 }
2976 
2977 bool ThunkSection::assignOffsets() {
2978   uint64_t Off = 0;
2979   for (Thunk *T : Thunks) {
2980     Off = alignTo(Off, T->Alignment);
2981     T->setOffset(Off);
2982     uint32_t Size = T->size();
2983     T->getThunkTargetSym()->Size = Size;
2984     Off += Size;
2985   }
2986   bool Changed = Off != Size;
2987   Size = Off;
2988   return Changed;
2989 }
2990 
2991 InputSection *InX::ARMAttributes;
2992 BssSection *InX::Bss;
2993 BssSection *InX::BssRelRo;
2994 BuildIdSection *InX::BuildId;
2995 EhFrameHeader *InX::EhFrameHdr;
2996 EhFrameSection *InX::EhFrame;
2997 SyntheticSection *InX::Dynamic;
2998 StringTableSection *InX::DynStrTab;
2999 SymbolTableBaseSection *InX::DynSymTab;
3000 InputSection *InX::Interp;
3001 GdbIndexSection *InX::GdbIndex;
3002 GotSection *InX::Got;
3003 GotPltSection *InX::GotPlt;
3004 GnuHashTableSection *InX::GnuHashTab;
3005 HashTableSection *InX::HashTab;
3006 IgotPltSection *InX::IgotPlt;
3007 MipsGotSection *InX::MipsGot;
3008 MipsRldMapSection *InX::MipsRldMap;
3009 PltSection *InX::Plt;
3010 PltSection *InX::Iplt;
3011 RelocationBaseSection *InX::RelaDyn;
3012 RelrBaseSection *InX::RelrDyn;
3013 RelocationBaseSection *InX::RelaPlt;
3014 RelocationBaseSection *InX::RelaIplt;
3015 StringTableSection *InX::ShStrTab;
3016 StringTableSection *InX::StrTab;
3017 SymbolTableBaseSection *InX::SymTab;
3018 
3019 template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3020 template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3021 template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3022 template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3023 
3024 template void elf::splitSections<ELF32LE>();
3025 template void elf::splitSections<ELF32BE>();
3026 template void elf::splitSections<ELF64LE>();
3027 template void elf::splitSections<ELF64BE>();
3028 
3029 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
3030 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
3031 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
3032 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
3033 
3034 template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
3035 template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
3036 template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
3037 template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
3038 
3039 template void MipsGotSection::build<ELF32LE>();
3040 template void MipsGotSection::build<ELF32BE>();
3041 template void MipsGotSection::build<ELF64LE>();
3042 template void MipsGotSection::build<ELF64BE>();
3043 
3044 template class elf::MipsAbiFlagsSection<ELF32LE>;
3045 template class elf::MipsAbiFlagsSection<ELF32BE>;
3046 template class elf::MipsAbiFlagsSection<ELF64LE>;
3047 template class elf::MipsAbiFlagsSection<ELF64BE>;
3048 
3049 template class elf::MipsOptionsSection<ELF32LE>;
3050 template class elf::MipsOptionsSection<ELF32BE>;
3051 template class elf::MipsOptionsSection<ELF64LE>;
3052 template class elf::MipsOptionsSection<ELF64BE>;
3053 
3054 template class elf::MipsReginfoSection<ELF32LE>;
3055 template class elf::MipsReginfoSection<ELF32BE>;
3056 template class elf::MipsReginfoSection<ELF64LE>;
3057 template class elf::MipsReginfoSection<ELF64BE>;
3058 
3059 template class elf::DynamicSection<ELF32LE>;
3060 template class elf::DynamicSection<ELF32BE>;
3061 template class elf::DynamicSection<ELF64LE>;
3062 template class elf::DynamicSection<ELF64BE>;
3063 
3064 template class elf::RelocationSection<ELF32LE>;
3065 template class elf::RelocationSection<ELF32BE>;
3066 template class elf::RelocationSection<ELF64LE>;
3067 template class elf::RelocationSection<ELF64BE>;
3068 
3069 template class elf::AndroidPackedRelocationSection<ELF32LE>;
3070 template class elf::AndroidPackedRelocationSection<ELF32BE>;
3071 template class elf::AndroidPackedRelocationSection<ELF64LE>;
3072 template class elf::AndroidPackedRelocationSection<ELF64BE>;
3073 
3074 template class elf::RelrSection<ELF32LE>;
3075 template class elf::RelrSection<ELF32BE>;
3076 template class elf::RelrSection<ELF64LE>;
3077 template class elf::RelrSection<ELF64BE>;
3078 
3079 template class elf::SymbolTableSection<ELF32LE>;
3080 template class elf::SymbolTableSection<ELF32BE>;
3081 template class elf::SymbolTableSection<ELF64LE>;
3082 template class elf::SymbolTableSection<ELF64BE>;
3083 
3084 template class elf::VersionTableSection<ELF32LE>;
3085 template class elf::VersionTableSection<ELF32BE>;
3086 template class elf::VersionTableSection<ELF64LE>;
3087 template class elf::VersionTableSection<ELF64BE>;
3088 
3089 template class elf::VersionNeedSection<ELF32LE>;
3090 template class elf::VersionNeedSection<ELF32BE>;
3091 template class elf::VersionNeedSection<ELF64LE>;
3092 template class elf::VersionNeedSection<ELF64BE>;
3093 
3094 template class elf::VersionDefinitionSection<ELF32LE>;
3095 template class elf::VersionDefinitionSection<ELF32BE>;
3096 template class elf::VersionDefinitionSection<ELF64LE>;
3097 template class elf::VersionDefinitionSection<ELF64BE>;
3098