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