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