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