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