]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/SyntheticSections.cpp
Merge ^/head r319251 through r319479.
[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 "Config.h"
19 #include "Error.h"
20 #include "InputFiles.h"
21 #include "LinkerScript.h"
22 #include "Memory.h"
23 #include "OutputSections.h"
24 #include "Strings.h"
25 #include "SymbolTable.h"
26 #include "Target.h"
27 #include "Threads.h"
28 #include "Writer.h"
29 #include "lld/Config/Version.h"
30 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
31 #include "llvm/Object/ELFObjectFile.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/MD5.h"
35 #include "llvm/Support/RandomNumberGenerator.h"
36 #include "llvm/Support/SHA1.h"
37 #include "llvm/Support/xxhash.h"
38 #include <cstdlib>
39
40 using namespace llvm;
41 using namespace llvm::dwarf;
42 using namespace llvm::ELF;
43 using namespace llvm::object;
44 using namespace llvm::support;
45 using namespace llvm::support::endian;
46
47 using namespace lld;
48 using namespace lld::elf;
49
50 uint64_t SyntheticSection::getVA() const {
51   if (OutputSection *Sec = getParent())
52     return Sec->Addr + OutSecOff;
53   return 0;
54 }
55
56 template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
57   std::vector<DefinedCommon *> V;
58   for (Symbol *S : Symtab<ELFT>::X->getSymbols())
59     if (auto *B = dyn_cast<DefinedCommon>(S->body()))
60       V.push_back(B);
61   return V;
62 }
63
64 // Find all common symbols and allocate space for them.
65 template <class ELFT> InputSection *elf::createCommonSection() {
66   if (!Config->DefineCommon)
67     return nullptr;
68
69   // Sort the common symbols by alignment as an heuristic to pack them better.
70   std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
71   if (Syms.empty())
72     return nullptr;
73
74   std::stable_sort(Syms.begin(), Syms.end(),
75                    [](const DefinedCommon *A, const DefinedCommon *B) {
76                      return A->Alignment > B->Alignment;
77                    });
78
79   BssSection *Sec = make<BssSection>("COMMON");
80   for (DefinedCommon *Sym : Syms)
81     Sym->Offset = Sec->reserveSpace(Sym->Size, Sym->Alignment);
82   return Sec;
83 }
84
85 // Returns an LLD version string.
86 static ArrayRef<uint8_t> getVersion() {
87   // Check LLD_VERSION first for ease of testing.
88   // You can get consitent output by using the environment variable.
89   // This is only for testing.
90   StringRef S = getenv("LLD_VERSION");
91   if (S.empty())
92     S = Saver.save(Twine("Linker: ") + getLLDVersion());
93
94   // +1 to include the terminating '\0'.
95   return {(const uint8_t *)S.data(), S.size() + 1};
96 }
97
98 // Creates a .comment section containing LLD version info.
99 // With this feature, you can identify LLD-generated binaries easily
100 // by "readelf --string-dump .comment <file>".
101 // The returned object is a mergeable string section.
102 template <class ELFT> MergeInputSection *elf::createCommentSection() {
103   typename ELFT::Shdr Hdr = {};
104   Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
105   Hdr.sh_type = SHT_PROGBITS;
106   Hdr.sh_entsize = 1;
107   Hdr.sh_addralign = 1;
108
109   auto *Ret =
110       make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
111   Ret->Data = getVersion();
112   Ret->splitIntoPieces();
113   return Ret;
114 }
115
116 // .MIPS.abiflags section.
117 template <class ELFT>
118 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
119     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
120       Flags(Flags) {
121   this->Entsize = sizeof(Elf_Mips_ABIFlags);
122 }
123
124 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
125   memcpy(Buf, &Flags, sizeof(Flags));
126 }
127
128 template <class ELFT>
129 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
130   Elf_Mips_ABIFlags Flags = {};
131   bool Create = false;
132
133   for (InputSectionBase *Sec : InputSections) {
134     if (Sec->Type != SHT_MIPS_ABIFLAGS)
135       continue;
136     Sec->Live = false;
137     Create = true;
138
139     std::string Filename = toString(Sec->getFile<ELFT>());
140     const size_t Size = Sec->Data.size();
141     // Older version of BFD (such as the default FreeBSD linker) concatenate
142     // .MIPS.abiflags instead of merging. To allow for this case (or potential
143     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
144     if (Size < sizeof(Elf_Mips_ABIFlags)) {
145       error(Filename + ": invalid size of .MIPS.abiflags section: got " +
146             Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
147       return nullptr;
148     }
149     auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
150     if (S->version != 0) {
151       error(Filename + ": unexpected .MIPS.abiflags version " +
152             Twine(S->version));
153       return nullptr;
154     }
155
156     // LLD checks ISA compatibility in getMipsEFlags(). Here we just
157     // select the highest number of ISA/Rev/Ext.
158     Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
159     Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
160     Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
161     Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
162     Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
163     Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
164     Flags.ases |= S->ases;
165     Flags.flags1 |= S->flags1;
166     Flags.flags2 |= S->flags2;
167     Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
168   };
169
170   if (Create)
171     return make<MipsAbiFlagsSection<ELFT>>(Flags);
172   return nullptr;
173 }
174
175 // .MIPS.options section.
176 template <class ELFT>
177 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
178     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
179       Reginfo(Reginfo) {
180   this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
181 }
182
183 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
184   auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
185   Options->kind = ODK_REGINFO;
186   Options->size = getSize();
187
188   if (!Config->Relocatable)
189     Reginfo.ri_gp_value = InX::MipsGot->getGp();
190   memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
191 }
192
193 template <class ELFT>
194 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
195   // N64 ABI only.
196   if (!ELFT::Is64Bits)
197     return nullptr;
198
199   Elf_Mips_RegInfo Reginfo = {};
200   bool Create = false;
201
202   for (InputSectionBase *Sec : InputSections) {
203     if (Sec->Type != SHT_MIPS_OPTIONS)
204       continue;
205     Sec->Live = false;
206     Create = true;
207
208     std::string Filename = toString(Sec->getFile<ELFT>());
209     ArrayRef<uint8_t> D = Sec->Data;
210
211     while (!D.empty()) {
212       if (D.size() < sizeof(Elf_Mips_Options)) {
213         error(Filename + ": invalid size of .MIPS.options section");
214         break;
215       }
216
217       auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
218       if (Opt->kind == ODK_REGINFO) {
219         if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
220           error(Filename + ": unsupported non-zero ri_gp_value");
221         Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
222         Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
223         break;
224       }
225
226       if (!Opt->size)
227         fatal(Filename + ": zero option descriptor size");
228       D = D.slice(Opt->size);
229     }
230   };
231
232   if (Create)
233     return make<MipsOptionsSection<ELFT>>(Reginfo);
234   return nullptr;
235 }
236
237 // MIPS .reginfo section.
238 template <class ELFT>
239 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
240     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
241       Reginfo(Reginfo) {
242   this->Entsize = sizeof(Elf_Mips_RegInfo);
243 }
244
245 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
246   if (!Config->Relocatable)
247     Reginfo.ri_gp_value = InX::MipsGot->getGp();
248   memcpy(Buf, &Reginfo, sizeof(Reginfo));
249 }
250
251 template <class ELFT>
252 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
253   // Section should be alive for O32 and N32 ABIs only.
254   if (ELFT::Is64Bits)
255     return nullptr;
256
257   Elf_Mips_RegInfo Reginfo = {};
258   bool Create = false;
259
260   for (InputSectionBase *Sec : InputSections) {
261     if (Sec->Type != SHT_MIPS_REGINFO)
262       continue;
263     Sec->Live = false;
264     Create = true;
265
266     if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
267       error(toString(Sec->getFile<ELFT>()) +
268             ": invalid size of .reginfo section");
269       return nullptr;
270     }
271     auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
272     if (Config->Relocatable && R->ri_gp_value)
273       error(toString(Sec->getFile<ELFT>()) +
274             ": unsupported non-zero ri_gp_value");
275
276     Reginfo.ri_gprmask |= R->ri_gprmask;
277     Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
278   };
279
280   if (Create)
281     return make<MipsReginfoSection<ELFT>>(Reginfo);
282   return nullptr;
283 }
284
285 InputSection *elf::createInterpSection() {
286   // StringSaver guarantees that the returned string ends with '\0'.
287   StringRef S = Saver.save(Config->DynamicLinker);
288   ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
289
290   auto *Sec =
291       make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
292   Sec->Live = true;
293   return Sec;
294 }
295
296 SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
297                                    uint64_t Size, InputSectionBase *Section) {
298   auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
299                                  Value, Size, Section, nullptr);
300   if (InX::SymTab)
301     InX::SymTab->addSymbol(S);
302   return S;
303 }
304
305 static size_t getHashSize() {
306   switch (Config->BuildId) {
307   case BuildIdKind::Fast:
308     return 8;
309   case BuildIdKind::Md5:
310   case BuildIdKind::Uuid:
311     return 16;
312   case BuildIdKind::Sha1:
313     return 20;
314   case BuildIdKind::Hexstring:
315     return Config->BuildIdVector.size();
316   default:
317     llvm_unreachable("unknown BuildIdKind");
318   }
319 }
320
321 BuildIdSection::BuildIdSection()
322     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
323       HashSize(getHashSize()) {}
324
325 void BuildIdSection::writeTo(uint8_t *Buf) {
326   endianness E = Config->Endianness;
327   write32(Buf, 4, E);                   // Name size
328   write32(Buf + 4, HashSize, E);        // Content size
329   write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
330   memcpy(Buf + 12, "GNU", 4);           // Name string
331   HashBuf = Buf + 16;
332 }
333
334 // Split one uint8 array into small pieces of uint8 arrays.
335 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
336                                             size_t ChunkSize) {
337   std::vector<ArrayRef<uint8_t>> Ret;
338   while (Arr.size() > ChunkSize) {
339     Ret.push_back(Arr.take_front(ChunkSize));
340     Arr = Arr.drop_front(ChunkSize);
341   }
342   if (!Arr.empty())
343     Ret.push_back(Arr);
344   return Ret;
345 }
346
347 // Computes a hash value of Data using a given hash function.
348 // In order to utilize multiple cores, we first split data into 1MB
349 // chunks, compute a hash for each chunk, and then compute a hash value
350 // of the hash values.
351 void BuildIdSection::computeHash(
352     llvm::ArrayRef<uint8_t> Data,
353     std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
354   std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
355   std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
356
357   // Compute hash values.
358   parallelForEachN(0, Chunks.size(), [&](size_t I) {
359     HashFn(Hashes.data() + I * HashSize, Chunks[I]);
360   });
361
362   // Write to the final output buffer.
363   HashFn(HashBuf, Hashes);
364 }
365
366 BssSection::BssSection(StringRef Name)
367     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
368
369 size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) {
370   if (OutputSection *Sec = getParent())
371     Sec->updateAlignment(Alignment);
372   this->Size = alignTo(this->Size, Alignment) + Size;
373   this->Alignment = std::max(this->Alignment, Alignment);
374   return this->Size - Size;
375 }
376
377 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
378   switch (Config->BuildId) {
379   case BuildIdKind::Fast:
380     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
381       write64le(Dest, xxHash64(toStringRef(Arr)));
382     });
383     break;
384   case BuildIdKind::Md5:
385     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
386       memcpy(Dest, MD5::hash(Arr).data(), 16);
387     });
388     break;
389   case BuildIdKind::Sha1:
390     computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
391       memcpy(Dest, SHA1::hash(Arr).data(), 20);
392     });
393     break;
394   case BuildIdKind::Uuid:
395     if (getRandomBytes(HashBuf, HashSize))
396       error("entropy source failure");
397     break;
398   case BuildIdKind::Hexstring:
399     memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
400     break;
401   default:
402     llvm_unreachable("unknown BuildIdKind");
403   }
404 }
405
406 template <class ELFT>
407 EhFrameSection<ELFT>::EhFrameSection()
408     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
409
410 // Search for an existing CIE record or create a new one.
411 // CIE records from input object files are uniquified by their contents
412 // and where their relocations point to.
413 template <class ELFT>
414 template <class RelTy>
415 CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
416                                         ArrayRef<RelTy> Rels) {
417   auto *Sec = cast<EhInputSection>(Piece.ID);
418   const endianness E = ELFT::TargetEndianness;
419   if (read32<E>(Piece.data().data() + 4) != 0)
420     fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
421
422   SymbolBody *Personality = nullptr;
423   unsigned FirstRelI = Piece.FirstRelocation;
424   if (FirstRelI != (unsigned)-1)
425     Personality =
426         &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
427
428   // Search for an existing CIE by CIE contents/relocation target pair.
429   CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
430
431   // If not found, create a new one.
432   if (Cie->Piece == nullptr) {
433     Cie->Piece = &Piece;
434     Cies.push_back(Cie);
435   }
436   return Cie;
437 }
438
439 // There is one FDE per function. Returns true if a given FDE
440 // points to a live function.
441 template <class ELFT>
442 template <class RelTy>
443 bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
444                                      ArrayRef<RelTy> Rels) {
445   auto *Sec = cast<EhInputSection>(Piece.ID);
446   unsigned FirstRelI = Piece.FirstRelocation;
447   if (FirstRelI == (unsigned)-1)
448     return false;
449   const RelTy &Rel = Rels[FirstRelI];
450   SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
451   auto *D = dyn_cast<DefinedRegular>(&B);
452   if (!D || !D->Section)
453     return false;
454   auto *Target =
455       cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
456   return Target && Target->Live;
457 }
458
459 // .eh_frame is a sequence of CIE or FDE records. In general, there
460 // is one CIE record per input object file which is followed by
461 // a list of FDEs. This function searches an existing CIE or create a new
462 // one and associates FDEs to the CIE.
463 template <class ELFT>
464 template <class RelTy>
465 void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
466                                          ArrayRef<RelTy> Rels) {
467   const endianness E = ELFT::TargetEndianness;
468
469   DenseMap<size_t, CieRecord *> OffsetToCie;
470   for (EhSectionPiece &Piece : Sec->Pieces) {
471     // The empty record is the end marker.
472     if (Piece.size() == 4)
473       return;
474
475     size_t Offset = Piece.InputOff;
476     uint32_t ID = read32<E>(Piece.data().data() + 4);
477     if (ID == 0) {
478       OffsetToCie[Offset] = addCie(Piece, Rels);
479       continue;
480     }
481
482     uint32_t CieOffset = Offset + 4 - ID;
483     CieRecord *Cie = OffsetToCie[CieOffset];
484     if (!Cie)
485       fatal(toString(Sec) + ": invalid CIE reference");
486
487     if (!isFdeLive(Piece, Rels))
488       continue;
489     Cie->FdePieces.push_back(&Piece);
490     NumFdes++;
491   }
492 }
493
494 template <class ELFT>
495 void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
496   auto *Sec = cast<EhInputSection>(C);
497   Sec->Parent = this;
498   updateAlignment(Sec->Alignment);
499   Sections.push_back(Sec);
500   for (auto *DS : Sec->DependentSections)
501     DependentSections.push_back(DS);
502
503   // .eh_frame is a sequence of CIE or FDE records. This function
504   // splits it into pieces so that we can call
505   // SplitInputSection::getSectionPiece on the section.
506   Sec->split<ELFT>();
507   if (Sec->Pieces.empty())
508     return;
509
510   if (Sec->NumRelocations) {
511     if (Sec->AreRelocsRela)
512       addSectionAux(Sec, Sec->template relas<ELFT>());
513     else
514       addSectionAux(Sec, Sec->template rels<ELFT>());
515     return;
516   }
517   addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
518 }
519
520 template <class ELFT>
521 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
522   memcpy(Buf, D.data(), D.size());
523
524   // Fix the size field. -4 since size does not include the size field itself.
525   const endianness E = ELFT::TargetEndianness;
526   write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
527 }
528
529 template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
530   if (this->Size)
531     return; // Already finalized.
532
533   size_t Off = 0;
534   for (CieRecord *Cie : Cies) {
535     Cie->Piece->OutputOff = Off;
536     Off += alignTo(Cie->Piece->size(), Config->Wordsize);
537
538     for (EhSectionPiece *Fde : Cie->FdePieces) {
539       Fde->OutputOff = Off;
540       Off += alignTo(Fde->size(), Config->Wordsize);
541     }
542   }
543
544   // The LSB standard does not allow a .eh_frame section with zero
545   // Call Frame Information records. Therefore add a CIE record length
546   // 0 as a terminator if this .eh_frame section is empty.
547   if (Off == 0)
548     Off = 4;
549
550   this->Size = Off;
551 }
552
553 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
554   const endianness E = ELFT::TargetEndianness;
555   switch (Size) {
556   case DW_EH_PE_udata2:
557     return read16<E>(Buf);
558   case DW_EH_PE_udata4:
559     return read32<E>(Buf);
560   case DW_EH_PE_udata8:
561     return read64<E>(Buf);
562   case DW_EH_PE_absptr:
563     if (ELFT::Is64Bits)
564       return read64<E>(Buf);
565     return read32<E>(Buf);
566   }
567   fatal("unknown FDE size encoding");
568 }
569
570 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
571 // We need it to create .eh_frame_hdr section.
572 template <class ELFT>
573 uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
574                                         uint8_t Enc) {
575   // The starting address to which this FDE applies is
576   // stored at FDE + 8 byte.
577   size_t Off = FdeOff + 8;
578   uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
579   if ((Enc & 0x70) == DW_EH_PE_absptr)
580     return Addr;
581   if ((Enc & 0x70) == DW_EH_PE_pcrel)
582     return Addr + getParent()->Addr + Off;
583   fatal("unknown FDE size relative encoding");
584 }
585
586 template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
587   const endianness E = ELFT::TargetEndianness;
588   for (CieRecord *Cie : Cies) {
589     size_t CieOffset = Cie->Piece->OutputOff;
590     writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
591
592     for (EhSectionPiece *Fde : Cie->FdePieces) {
593       size_t Off = Fde->OutputOff;
594       writeCieFde<ELFT>(Buf + Off, Fde->data());
595
596       // FDE's second word should have the offset to an associated CIE.
597       // Write it.
598       write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
599     }
600   }
601
602   for (EhInputSection *S : Sections)
603     S->relocateAlloc(Buf, nullptr);
604
605   // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
606   // to get a FDE from an address to which FDE is applied. So here
607   // we obtain two addresses and pass them to EhFrameHdr object.
608   if (In<ELFT>::EhFrameHdr) {
609     for (CieRecord *Cie : Cies) {
610       uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
611       for (SectionPiece *Fde : Cie->FdePieces) {
612         uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
613         uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
614         In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
615       }
616     }
617   }
618 }
619
620 GotSection::GotSection()
621     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
622                        Target->GotEntrySize, ".got") {}
623
624 void GotSection::addEntry(SymbolBody &Sym) {
625   Sym.GotIndex = NumEntries;
626   ++NumEntries;
627 }
628
629 bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
630   if (Sym.GlobalDynIndex != -1U)
631     return false;
632   Sym.GlobalDynIndex = NumEntries;
633   // Global Dynamic TLS entries take two GOT slots.
634   NumEntries += 2;
635   return true;
636 }
637
638 // Reserves TLS entries for a TLS module ID and a TLS block offset.
639 // In total it takes two GOT slots.
640 bool GotSection::addTlsIndex() {
641   if (TlsIndexOff != uint32_t(-1))
642     return false;
643   TlsIndexOff = NumEntries * Config->Wordsize;
644   NumEntries += 2;
645   return true;
646 }
647
648 uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
649   return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
650 }
651
652 uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
653   return B.GlobalDynIndex * Config->Wordsize;
654 }
655
656 void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
657
658 bool GotSection::empty() const {
659   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
660   // we need to emit a GOT even if it's empty.
661   return NumEntries == 0 && !HasGotOffRel;
662 }
663
664 void GotSection::writeTo(uint8_t *Buf) { relocateAlloc(Buf, Buf + Size); }
665
666 MipsGotSection::MipsGotSection()
667     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
668                        ".got") {}
669
670 void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
671   // For "true" local symbols which can be referenced from the same module
672   // only compiler creates two instructions for address loading:
673   //
674   // lw   $8, 0($gp) # R_MIPS_GOT16
675   // addi $8, $8, 0  # R_MIPS_LO16
676   //
677   // The first instruction loads high 16 bits of the symbol address while
678   // the second adds an offset. That allows to reduce number of required
679   // GOT entries because only one global offset table entry is necessary
680   // for every 64 KBytes of local data. So for local symbols we need to
681   // allocate number of GOT entries to hold all required "page" addresses.
682   //
683   // All global symbols (hidden and regular) considered by compiler uniformly.
684   // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
685   // to load address of the symbol. So for each such symbol we need to
686   // allocate dedicated GOT entry to store its address.
687   //
688   // If a symbol is preemptible we need help of dynamic linker to get its
689   // final address. The corresponding GOT entries are allocated in the
690   // "global" part of GOT. Entries for non preemptible global symbol allocated
691   // in the "local" part of GOT.
692   //
693   // See "Global Offset Table" in Chapter 5:
694   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
695   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
696     // At this point we do not know final symbol value so to reduce number
697     // of allocated GOT entries do the following trick. Save all output
698     // sections referenced by GOT relocations. Then later in the `finalize`
699     // method calculate number of "pages" required to cover all saved output
700     // section and allocate appropriate number of GOT entries.
701     PageIndexMap.insert({Sym.getOutputSection(), 0});
702     return;
703   }
704   if (Sym.isTls()) {
705     // GOT entries created for MIPS TLS relocations behave like
706     // almost GOT entries from other ABIs. They go to the end
707     // of the global offset table.
708     Sym.GotIndex = TlsEntries.size();
709     TlsEntries.push_back(&Sym);
710     return;
711   }
712   auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
713     if (S.isInGot() && !A)
714       return;
715     size_t NewIndex = Items.size();
716     if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
717       return;
718     Items.emplace_back(&S, A);
719     if (!A)
720       S.GotIndex = NewIndex;
721   };
722   if (Sym.isPreemptible()) {
723     // Ignore addends for preemptible symbols. They got single GOT entry anyway.
724     AddEntry(Sym, 0, GlobalEntries);
725     Sym.IsInGlobalMipsGot = true;
726   } else if (Expr == R_MIPS_GOT_OFF32) {
727     AddEntry(Sym, Addend, LocalEntries32);
728     Sym.Is32BitMipsGot = true;
729   } else {
730     // Hold local GOT entries accessed via a 16-bit index separately.
731     // That allows to write them in the beginning of the GOT and keep
732     // their indexes as less as possible to escape relocation's overflow.
733     AddEntry(Sym, Addend, LocalEntries);
734   }
735 }
736
737 bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
738   if (Sym.GlobalDynIndex != -1U)
739     return false;
740   Sym.GlobalDynIndex = TlsEntries.size();
741   // Global Dynamic TLS entries take two GOT slots.
742   TlsEntries.push_back(nullptr);
743   TlsEntries.push_back(&Sym);
744   return true;
745 }
746
747 // Reserves TLS entries for a TLS module ID and a TLS block offset.
748 // In total it takes two GOT slots.
749 bool MipsGotSection::addTlsIndex() {
750   if (TlsIndexOff != uint32_t(-1))
751     return false;
752   TlsIndexOff = TlsEntries.size() * Config->Wordsize;
753   TlsEntries.push_back(nullptr);
754   TlsEntries.push_back(nullptr);
755   return true;
756 }
757
758 static uint64_t getMipsPageAddr(uint64_t Addr) {
759   return (Addr + 0x8000) & ~0xffff;
760 }
761
762 static uint64_t getMipsPageCount(uint64_t Size) {
763   return (Size + 0xfffe) / 0xffff + 1;
764 }
765
766 uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
767                                             int64_t Addend) const {
768   const OutputSection *OutSec = B.getOutputSection();
769   uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
770   uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
771   uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
772   assert(Index < PageEntriesNum);
773   return (HeaderEntriesNum + Index) * Config->Wordsize;
774 }
775
776 uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
777                                             int64_t Addend) const {
778   // Calculate offset of the GOT entries block: TLS, global, local.
779   uint64_t Index = HeaderEntriesNum + PageEntriesNum;
780   if (B.isTls())
781     Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
782   else if (B.IsInGlobalMipsGot)
783     Index += LocalEntries.size() + LocalEntries32.size();
784   else if (B.Is32BitMipsGot)
785     Index += LocalEntries.size();
786   // Calculate offset of the GOT entry in the block.
787   if (B.isInGot())
788     Index += B.GotIndex;
789   else {
790     auto It = EntryIndexMap.find({&B, Addend});
791     assert(It != EntryIndexMap.end());
792     Index += It->second;
793   }
794   return Index * Config->Wordsize;
795 }
796
797 uint64_t MipsGotSection::getTlsOffset() const {
798   return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
799 }
800
801 uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
802   return B.GlobalDynIndex * Config->Wordsize;
803 }
804
805 const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
806   return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
807 }
808
809 unsigned MipsGotSection::getLocalEntriesNum() const {
810   return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
811          LocalEntries32.size();
812 }
813
814 void MipsGotSection::finalizeContents() {
815   updateAllocSize();
816 }
817
818 void MipsGotSection::updateAllocSize() {
819   PageEntriesNum = 0;
820   for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
821     // For each output section referenced by GOT page relocations calculate
822     // and save into PageIndexMap an upper bound of MIPS GOT entries required
823     // to store page addresses of local symbols. We assume the worst case -
824     // each 64kb page of the output section has at least one GOT relocation
825     // against it. And take in account the case when the section intersects
826     // page boundaries.
827     P.second = PageEntriesNum;
828     PageEntriesNum += getMipsPageCount(P.first->Size);
829   }
830   Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
831          Config->Wordsize;
832 }
833
834 bool MipsGotSection::empty() const {
835   // We add the .got section to the result for dynamic MIPS target because
836   // its address and properties are mentioned in the .dynamic section.
837   return Config->Relocatable;
838 }
839
840 uint64_t MipsGotSection::getGp() const {
841   return ElfSym::MipsGp->getVA(0);
842 }
843
844 static uint64_t readUint(uint8_t *Buf) {
845   if (Config->Is64)
846     return read64(Buf, Config->Endianness);
847   return read32(Buf, Config->Endianness);
848 }
849
850 static void writeUint(uint8_t *Buf, uint64_t Val) {
851   if (Config->Is64)
852     write64(Buf, Val, Config->Endianness);
853   else
854     write32(Buf, Val, Config->Endianness);
855 }
856
857 void MipsGotSection::writeTo(uint8_t *Buf) {
858   // Set the MSB of the second GOT slot. This is not required by any
859   // MIPS ABI documentation, though.
860   //
861   // There is a comment in glibc saying that "The MSB of got[1] of a
862   // gnu object is set to identify gnu objects," and in GNU gold it
863   // says "the second entry will be used by some runtime loaders".
864   // But how this field is being used is unclear.
865   //
866   // We are not really willing to mimic other linkers behaviors
867   // without understanding why they do that, but because all files
868   // generated by GNU tools have this special GOT value, and because
869   // we've been doing this for years, it is probably a safe bet to
870   // keep doing this for now. We really need to revisit this to see
871   // if we had to do this.
872   writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
873   Buf += HeaderEntriesNum * Config->Wordsize;
874   // Write 'page address' entries to the local part of the GOT.
875   for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
876     size_t PageCount = getMipsPageCount(L.first->Size);
877     uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
878     for (size_t PI = 0; PI < PageCount; ++PI) {
879       uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
880       writeUint(Entry, FirstPageAddr + PI * 0x10000);
881     }
882   }
883   Buf += PageEntriesNum * Config->Wordsize;
884   auto AddEntry = [&](const GotEntry &SA) {
885     uint8_t *Entry = Buf;
886     Buf += Config->Wordsize;
887     const SymbolBody *Body = SA.first;
888     uint64_t VA = Body->getVA(SA.second);
889     writeUint(Entry, VA);
890   };
891   std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
892   std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
893   std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
894   // Initialize TLS-related GOT entries. If the entry has a corresponding
895   // dynamic relocations, leave it initialized by zero. Write down adjusted
896   // TLS symbol's values otherwise. To calculate the adjustments use offsets
897   // for thread-local storage.
898   // https://www.linux-mips.org/wiki/NPTL
899   if (TlsIndexOff != -1U && !Config->Pic)
900     writeUint(Buf + TlsIndexOff, 1);
901   for (const SymbolBody *B : TlsEntries) {
902     if (!B || B->isPreemptible())
903       continue;
904     uint64_t VA = B->getVA();
905     if (B->GotIndex != -1U) {
906       uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
907       writeUint(Entry, VA - 0x7000);
908     }
909     if (B->GlobalDynIndex != -1U) {
910       uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
911       writeUint(Entry, 1);
912       Entry += Config->Wordsize;
913       writeUint(Entry, VA - 0x8000);
914     }
915   }
916 }
917
918 GotPltSection::GotPltSection()
919     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
920                        Target->GotPltEntrySize, ".got.plt") {}
921
922 void GotPltSection::addEntry(SymbolBody &Sym) {
923   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
924   Entries.push_back(&Sym);
925 }
926
927 size_t GotPltSection::getSize() const {
928   return (Target->GotPltHeaderEntriesNum + Entries.size()) *
929          Target->GotPltEntrySize;
930 }
931
932 void GotPltSection::writeTo(uint8_t *Buf) {
933   Target->writeGotPltHeader(Buf);
934   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
935   for (const SymbolBody *B : Entries) {
936     Target->writeGotPlt(Buf, *B);
937     Buf += Config->Wordsize;
938   }
939 }
940
941 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
942 // part of the .got.plt
943 IgotPltSection::IgotPltSection()
944     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
945                        Target->GotPltEntrySize,
946                        Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
947
948 void IgotPltSection::addEntry(SymbolBody &Sym) {
949   Sym.IsInIgot = true;
950   Sym.GotPltIndex = Entries.size();
951   Entries.push_back(&Sym);
952 }
953
954 size_t IgotPltSection::getSize() const {
955   return Entries.size() * Target->GotPltEntrySize;
956 }
957
958 void IgotPltSection::writeTo(uint8_t *Buf) {
959   for (const SymbolBody *B : Entries) {
960     Target->writeIgotPlt(Buf, *B);
961     Buf += Config->Wordsize;
962   }
963 }
964
965 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
966     : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
967       Dynamic(Dynamic) {
968   // ELF string tables start with a NUL byte.
969   addString("");
970 }
971
972 // Adds a string to the string table. If HashIt is true we hash and check for
973 // duplicates. It is optional because the name of global symbols are already
974 // uniqued and hashing them again has a big cost for a small value: uniquing
975 // them with some other string that happens to be the same.
976 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
977   if (HashIt) {
978     auto R = StringMap.insert(std::make_pair(S, this->Size));
979     if (!R.second)
980       return R.first->second;
981   }
982   unsigned Ret = this->Size;
983   this->Size = this->Size + S.size() + 1;
984   Strings.push_back(S);
985   return Ret;
986 }
987
988 void StringTableSection::writeTo(uint8_t *Buf) {
989   for (StringRef S : Strings) {
990     memcpy(Buf, S.data(), S.size());
991     Buf += S.size() + 1;
992   }
993 }
994
995 // Returns the number of version definition entries. Because the first entry
996 // is for the version definition itself, it is the number of versioned symbols
997 // plus one. Note that we don't support multiple versions yet.
998 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
999
1000 template <class ELFT>
1001 DynamicSection<ELFT>::DynamicSection()
1002     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1003                        ".dynamic") {
1004   this->Entsize = ELFT::Is64Bits ? 16 : 8;
1005
1006   // .dynamic section is not writable on MIPS and on Fuchsia OS
1007   // which passes -z rodynamic.
1008   // See "Special Section" in Chapter 4 in the following document:
1009   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1010   if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
1011     this->Flags = SHF_ALLOC;
1012
1013   addEntries();
1014 }
1015
1016 // There are some dynamic entries that don't depend on other sections.
1017 // Such entries can be set early.
1018 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1019   // Add strings to .dynstr early so that .dynstr's size will be
1020   // fixed early.
1021   for (StringRef S : Config->AuxiliaryList)
1022     add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
1023   if (!Config->Rpath.empty())
1024     add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1025          InX::DynStrTab->addString(Config->Rpath)});
1026   for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1027     if (F->isNeeded())
1028       add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
1029   if (!Config->SoName.empty())
1030     add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
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->ZNodelete)
1038     DtFlags1 |= DF_1_NODELETE;
1039   if (Config->ZNodlopen)
1040     DtFlags1 |= DF_1_NOOPEN;
1041   if (Config->ZNow) {
1042     DtFlags |= DF_BIND_NOW;
1043     DtFlags1 |= DF_1_NOW;
1044   }
1045   if (Config->ZOrigin) {
1046     DtFlags |= DF_ORIGIN;
1047     DtFlags1 |= DF_1_ORIGIN;
1048   }
1049
1050   if (DtFlags)
1051     add({DT_FLAGS, DtFlags});
1052   if (DtFlags1)
1053     add({DT_FLAGS_1, DtFlags1});
1054
1055   // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056   // need it for each process, so we don't write it for DSOs. The loader writes
1057   // the pointer into this entry.
1058   //
1059   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060   // systems (currently only Fuchsia OS) provide other means to give the
1061   // debugger this information. Such systems may choose make .dynamic read-only.
1062   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063   if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
1064     add({DT_DEBUG, (uint64_t)0});
1065 }
1066
1067 // Add remaining entries to complete .dynamic contents.
1068 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1069   if (this->Size)
1070     return; // Already finalized.
1071
1072   this->Link = InX::DynStrTab->getParent()->SectionIndex;
1073   if (In<ELFT>::RelaDyn->getParent()->Size > 0) {
1074     bool IsRela = Config->IsRela;
1075     add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
1076     add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent()->Size});
1077     add({IsRela ? DT_RELAENT : DT_RELENT,
1078          uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1079
1080     // MIPS dynamic loader does not support RELCOUNT tag.
1081     // The problem is in the tight relation between dynamic
1082     // relocations and GOT. So do not emit this tag on MIPS.
1083     if (Config->EMachine != EM_MIPS) {
1084       size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
1085       if (Config->ZCombreloc && NumRelativeRels)
1086         add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
1087     }
1088   }
1089   if (In<ELFT>::RelaPlt->getParent()->Size > 0) {
1090     add({DT_JMPREL, In<ELFT>::RelaPlt});
1091     add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent()->Size});
1092     add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
1093          InX::GotPlt});
1094     add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
1095   }
1096
1097   add({DT_SYMTAB, InX::DynSymTab});
1098   add({DT_SYMENT, sizeof(Elf_Sym)});
1099   add({DT_STRTAB, InX::DynStrTab});
1100   add({DT_STRSZ, InX::DynStrTab->getSize()});
1101   if (!Config->ZText)
1102     add({DT_TEXTREL, (uint64_t)0});
1103   if (InX::GnuHashTab)
1104     add({DT_GNU_HASH, InX::GnuHashTab});
1105   if (In<ELFT>::HashTab)
1106     add({DT_HASH, In<ELFT>::HashTab});
1107
1108   if (Out::PreinitArray) {
1109     add({DT_PREINIT_ARRAY, Out::PreinitArray});
1110     add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
1111   }
1112   if (Out::InitArray) {
1113     add({DT_INIT_ARRAY, Out::InitArray});
1114     add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
1115   }
1116   if (Out::FiniArray) {
1117     add({DT_FINI_ARRAY, Out::FiniArray});
1118     add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
1119   }
1120
1121   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
1122     add({DT_INIT, B});
1123   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
1124     add({DT_FINI, B});
1125
1126   bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1127   if (HasVerNeed || In<ELFT>::VerDef)
1128     add({DT_VERSYM, In<ELFT>::VerSym});
1129   if (In<ELFT>::VerDef) {
1130     add({DT_VERDEF, In<ELFT>::VerDef});
1131     add({DT_VERDEFNUM, getVerDefNum()});
1132   }
1133   if (HasVerNeed) {
1134     add({DT_VERNEED, In<ELFT>::VerNeed});
1135     add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
1136   }
1137
1138   if (Config->EMachine == EM_MIPS) {
1139     add({DT_MIPS_RLD_VERSION, 1});
1140     add({DT_MIPS_FLAGS, RHF_NOTPOT});
1141     add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
1142     add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
1143     add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1144     if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
1145       add({DT_MIPS_GOTSYM, B->DynsymIndex});
1146     else
1147       add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
1148     add({DT_PLTGOT, InX::MipsGot});
1149     if (InX::MipsRldMap)
1150       add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
1151   }
1152
1153   getParent()->Link = this->Link;
1154
1155   // +1 for DT_NULL
1156   this->Size = (Entries.size() + 1) * this->Entsize;
1157 }
1158
1159 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1160   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1161
1162   for (const Entry &E : Entries) {
1163     P->d_tag = E.Tag;
1164     switch (E.Kind) {
1165     case Entry::SecAddr:
1166       P->d_un.d_ptr = E.OutSec->Addr;
1167       break;
1168     case Entry::InSecAddr:
1169       P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
1170       break;
1171     case Entry::SecSize:
1172       P->d_un.d_val = E.OutSec->Size;
1173       break;
1174     case Entry::SymAddr:
1175       P->d_un.d_ptr = E.Sym->getVA();
1176       break;
1177     case Entry::PlainInt:
1178       P->d_un.d_val = E.Val;
1179       break;
1180     }
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 template <class ELFT>
1202 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1203     : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
1204                        Config->Wordsize, Name),
1205       Sort(Sort) {
1206   this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1207 }
1208
1209 template <class ELFT>
1210 void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
1211   if (Reloc.Type == Target->RelativeRel)
1212     ++NumRelativeRelocs;
1213   Relocs.push_back(Reloc);
1214 }
1215
1216 template <class ELFT, class RelTy>
1217 static bool compRelocations(const RelTy &A, const RelTy &B) {
1218   bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1219   bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1220   if (AIsRel != BIsRel)
1221     return AIsRel;
1222
1223   return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1224 }
1225
1226 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1227   uint8_t *BufBegin = Buf;
1228   for (const DynamicReloc &Rel : Relocs) {
1229     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
1230     Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1231
1232     if (Config->IsRela)
1233       P->r_addend = Rel.getAddend();
1234     P->r_offset = Rel.getOffset();
1235     if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1236       // Dynamic relocation against MIPS GOT section make deal TLS entries
1237       // allocated in the end of the GOT. We need to adjust the offset to take
1238       // in account 'local' and 'global' GOT entries.
1239       P->r_offset += InX::MipsGot->getTlsOffset();
1240     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1241   }
1242
1243   if (Sort) {
1244     if (Config->IsRela)
1245       std::stable_sort((Elf_Rela *)BufBegin,
1246                        (Elf_Rela *)BufBegin + Relocs.size(),
1247                        compRelocations<ELFT, Elf_Rela>);
1248     else
1249       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1250                        compRelocations<ELFT, Elf_Rel>);
1251   }
1252 }
1253
1254 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1255   return this->Entsize * Relocs.size();
1256 }
1257
1258 template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
1259   this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex
1260                               : InX::SymTab->getParent()->SectionIndex;
1261
1262   // Set required output section properties.
1263   getParent()->Link = this->Link;
1264 }
1265
1266 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1267     : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1268                        StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1269                        Config->Wordsize,
1270                        StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1271       StrTabSec(StrTabSec) {}
1272
1273 // Orders symbols according to their positions in the GOT,
1274 // in compliance with MIPS ABI rules.
1275 // See "Global Offset Table" in Chapter 5 in the following document
1276 // for detailed description:
1277 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1278 static bool sortMipsSymbols(const SymbolTableEntry &L,
1279                             const SymbolTableEntry &R) {
1280   // Sort entries related to non-local preemptible symbols by GOT indexes.
1281   // All other entries go to the first part of GOT in arbitrary order.
1282   bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1283   bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
1284   if (LIsInLocalGot || RIsInLocalGot)
1285     return !RIsInLocalGot;
1286   return L.Symbol->GotIndex < R.Symbol->GotIndex;
1287 }
1288
1289 // Finalize a symbol table. The ELF spec requires that all local
1290 // symbols precede global symbols, so we sort symbol entries in this
1291 // function. (For .dynsym, we don't do that because symbols for
1292 // dynamic linking are inherently all globals.)
1293 void SymbolTableBaseSection::finalizeContents() {
1294   getParent()->Link = StrTabSec.getParent()->SectionIndex;
1295
1296   // If it is a .dynsym, there should be no local symbols, but we need
1297   // to do a few things for the dynamic linker.
1298   if (this->Type == SHT_DYNSYM) {
1299     // Section's Info field has the index of the first non-local symbol.
1300     // Because the first symbol entry is a null entry, 1 is the first.
1301     getParent()->Info = 1;
1302
1303     if (InX::GnuHashTab) {
1304       // NB: It also sorts Symbols to meet the GNU hash table requirements.
1305       InX::GnuHashTab->addSymbols(Symbols);
1306     } else if (Config->EMachine == EM_MIPS) {
1307       std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1308     }
1309
1310     size_t I = 0;
1311     for (const SymbolTableEntry &S : Symbols)
1312       S.Symbol->DynsymIndex = ++I;
1313     return;
1314   }
1315 }
1316
1317 void SymbolTableBaseSection::postThunkContents() {
1318   if (this->Type == SHT_DYNSYM)
1319     return;
1320   // move all local symbols before global symbols.
1321   auto It = std::stable_partition(
1322       Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1323         return S.Symbol->isLocal() ||
1324                S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1325       });
1326   size_t NumLocals = It - Symbols.begin();
1327   getParent()->Info = NumLocals + 1;
1328 }
1329
1330 void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
1331   // Adding a local symbol to a .dynsym is a bug.
1332   assert(this->Type != SHT_DYNSYM || !B->isLocal());
1333
1334   bool HashIt = B->isLocal();
1335   Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1336 }
1337
1338 size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
1339   auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1340     if (E.Symbol == Body)
1341       return true;
1342     // This is used for -r, so we have to handle multiple section
1343     // symbols being combined.
1344     if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
1345       return Body->getOutputSection() == E.Symbol->getOutputSection();
1346     return false;
1347   });
1348   if (I == Symbols.end())
1349     return 0;
1350   return I - Symbols.begin() + 1;
1351 }
1352
1353 template <class ELFT>
1354 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1355     : SymbolTableBaseSection(StrTabSec) {
1356   this->Entsize = sizeof(Elf_Sym);
1357 }
1358
1359 // Write the internal symbol table contents to the output symbol table.
1360 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1361   // The first entry is a null entry as per the ELF spec.
1362   Buf += sizeof(Elf_Sym);
1363
1364   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1365
1366   for (SymbolTableEntry &Ent : Symbols) {
1367     SymbolBody *Body = Ent.Symbol;
1368
1369     // Set st_info and st_other.
1370     if (Body->isLocal()) {
1371       ESym->setBindingAndType(STB_LOCAL, Body->Type);
1372     } else {
1373       ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1374       ESym->setVisibility(Body->symbol()->Visibility);
1375     }
1376
1377     ESym->st_name = Ent.StrTabOffset;
1378     ESym->st_size = Body->getSize<ELFT>();
1379
1380     // Set a section index.
1381     if (const OutputSection *OutSec = Body->getOutputSection())
1382       ESym->st_shndx = OutSec->SectionIndex;
1383     else if (isa<DefinedRegular>(Body))
1384       ESym->st_shndx = SHN_ABS;
1385     else if (isa<DefinedCommon>(Body))
1386       ESym->st_shndx = SHN_COMMON;
1387
1388     // st_value is usually an address of a symbol, but that has a
1389     // special meaining for uninstantiated common symbols (this can
1390     // occur if -r is given).
1391     if (!Config->DefineCommon && isa<DefinedCommon>(Body))
1392       ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
1393     else
1394       ESym->st_value = Body->getVA();
1395
1396     ++ESym;
1397   }
1398
1399   // On MIPS we need to mark symbol which has a PLT entry and requires
1400   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1401   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1402   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1403   if (Config->EMachine == EM_MIPS) {
1404     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1405
1406     for (SymbolTableEntry &Ent : Symbols) {
1407       SymbolBody *Body = Ent.Symbol;
1408       if (Body->isInPlt() && Body->NeedsPltAddr)
1409         ESym->st_other |= STO_MIPS_PLT;
1410
1411       if (Config->Relocatable)
1412         if (auto *D = dyn_cast<DefinedRegular>(Body))
1413           if (D->isMipsPIC<ELFT>())
1414             ESym->st_other |= STO_MIPS_PIC;
1415       ++ESym;
1416     }
1417   }
1418 }
1419
1420 // .hash and .gnu.hash sections contain on-disk hash tables that map
1421 // symbol names to their dynamic symbol table indices. Their purpose
1422 // is to help the dynamic linker resolve symbols quickly. If ELF files
1423 // don't have them, the dynamic linker has to do linear search on all
1424 // dynamic symbols, which makes programs slower. Therefore, a .hash
1425 // section is added to a DSO by default. A .gnu.hash is added if you
1426 // give the -hash-style=gnu or -hash-style=both option.
1427 //
1428 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
1429 // Each ELF file has a list of DSOs that the ELF file depends on and a
1430 // list of dynamic symbols that need to be resolved from any of the
1431 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1432 // where m is the number of DSOs and n is the number of dynamic
1433 // symbols. For modern large programs, both m and n are large.  So
1434 // making each step faster by using hash tables substiantially
1435 // improves time to load programs.
1436 //
1437 // (Note that this is not the only way to design the shared library.
1438 // For instance, the Windows DLL takes a different approach. On
1439 // Windows, each dynamic symbol has a name of DLL from which the symbol
1440 // has to be resolved. That makes the cost of symbol resolution O(n).
1441 // This disables some hacky techniques you can use on Unix such as
1442 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1443 //
1444 // Due to historical reasons, we have two different hash tables, .hash
1445 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1446 // and better version of .hash. .hash is just an on-disk hash table, but
1447 // .gnu.hash has a bloom filter in addition to a hash table to skip
1448 // DSOs very quickly. If you are sure that your dynamic linker knows
1449 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1450 // safe bet is to specify -hash-style=both for backward compatibilty.
1451 GnuHashTableSection::GnuHashTableSection()
1452     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1453 }
1454
1455 void GnuHashTableSection::finalizeContents() {
1456   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1457
1458   // Computes bloom filter size in word size. We want to allocate 8
1459   // bits for each symbol. It must be a power of two.
1460   if (Symbols.empty())
1461     MaskWords = 1;
1462   else
1463     MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
1464
1465   Size = 16;                            // Header
1466   Size += Config->Wordsize * MaskWords; // Bloom filter
1467   Size += NBuckets * 4;                 // Hash buckets
1468   Size += Symbols.size() * 4;           // Hash values
1469 }
1470
1471 void GnuHashTableSection::writeTo(uint8_t *Buf) {
1472   // Write a header.
1473   write32(Buf, NBuckets, Config->Endianness);
1474   write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
1475           Config->Endianness);
1476   write32(Buf + 8, MaskWords, Config->Endianness);
1477   write32(Buf + 12, getShift2(), Config->Endianness);
1478   Buf += 16;
1479
1480   // Write a bloom filter and a hash table.
1481   writeBloomFilter(Buf);
1482   Buf += Config->Wordsize * MaskWords;
1483   writeHashTable(Buf);
1484 }
1485
1486 // This function writes a 2-bit bloom filter. This bloom filter alone
1487 // usually filters out 80% or more of all symbol lookups [1].
1488 // The dynamic linker uses the hash table only when a symbol is not
1489 // filtered out by a bloom filter.
1490 //
1491 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1492 //     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
1493 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
1494   const unsigned C = Config->Wordsize * 8;
1495   for (const Entry &Sym : Symbols) {
1496     size_t I = (Sym.Hash / C) & (MaskWords - 1);
1497     uint64_t Val = readUint(Buf + I * Config->Wordsize);
1498     Val |= uint64_t(1) << (Sym.Hash % C);
1499     Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1500     writeUint(Buf + I * Config->Wordsize, Val);
1501   }
1502 }
1503
1504 void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
1505   // Group symbols by hash value.
1506   std::vector<std::vector<Entry>> Syms(NBuckets);
1507   for (const Entry &Ent : Symbols)
1508     Syms[Ent.Hash % NBuckets].push_back(Ent);
1509
1510   // Write hash buckets. Hash buckets contain indices in the following
1511   // hash value table.
1512   uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
1513   for (size_t I = 0; I < NBuckets; ++I)
1514     if (!Syms[I].empty())
1515       write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
1516
1517   // Write a hash value table. It represents a sequence of chains that
1518   // share the same hash modulo value. The last element of each chain
1519   // is terminated by LSB 1.
1520   uint32_t *Values = Buckets + NBuckets;
1521   size_t I = 0;
1522   for (std::vector<Entry> &Vec : Syms) {
1523     if (Vec.empty())
1524       continue;
1525     for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1526       write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1527     write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
1528   }
1529 }
1530
1531 static uint32_t hashGnu(StringRef Name) {
1532   uint32_t H = 5381;
1533   for (uint8_t C : Name)
1534     H = (H << 5) + H + C;
1535   return H;
1536 }
1537
1538 // Returns a number of hash buckets to accomodate given number of elements.
1539 // We want to choose a moderate number that is not too small (which
1540 // causes too many hash collisions) and not too large (which wastes
1541 // disk space.)
1542 //
1543 // We return a prime number because it (is believed to) achieve good
1544 // hash distribution.
1545 static size_t getBucketSize(size_t NumSymbols) {
1546   // List of largest prime numbers that are not greater than 2^n + 1.
1547   for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1548                    251, 127, 61, 31, 13, 7, 3, 1})
1549     if (N <= NumSymbols)
1550       return N;
1551   return 0;
1552 }
1553
1554 // Add symbols to this symbol hash table. Note that this function
1555 // destructively sort a given vector -- which is needed because
1556 // GNU-style hash table places some sorting requirements.
1557 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
1558   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1559   // its type correctly.
1560   std::vector<SymbolTableEntry>::iterator Mid =
1561       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1562         return S.Symbol->isUndefined();
1563       });
1564   if (Mid == V.end())
1565     return;
1566
1567   for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1568     SymbolBody *B = Ent.Symbol;
1569     Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
1570   }
1571
1572   NBuckets = getBucketSize(Symbols.size());
1573   std::stable_sort(Symbols.begin(), Symbols.end(),
1574                    [&](const Entry &L, const Entry &R) {
1575                      return L.Hash % NBuckets < R.Hash % NBuckets;
1576                    });
1577
1578   V.erase(Mid, V.end());
1579   for (const Entry &Ent : Symbols)
1580     V.push_back({Ent.Body, Ent.StrTabOffset});
1581 }
1582
1583 template <class ELFT>
1584 HashTableSection<ELFT>::HashTableSection()
1585     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1586   this->Entsize = 4;
1587 }
1588
1589 template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
1590   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1591
1592   unsigned NumEntries = 2;                            // nbucket and nchain.
1593   NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
1594
1595   // Create as many buckets as there are symbols.
1596   // FIXME: This is simplistic. We can try to optimize it, but implementing
1597   // support for SHT_GNU_HASH is probably even more profitable.
1598   NumEntries += InX::DynSymTab->getNumSymbols();
1599   this->Size = NumEntries * 4;
1600 }
1601
1602 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1603   // A 32-bit integer type in the target endianness.
1604   typedef typename ELFT::Word Elf_Word;
1605
1606   unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
1607
1608   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1609   *P++ = NumSymbols; // nbucket
1610   *P++ = NumSymbols; // nchain
1611
1612   Elf_Word *Buckets = P;
1613   Elf_Word *Chains = P + NumSymbols;
1614
1615   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
1616     SymbolBody *Body = S.Symbol;
1617     StringRef Name = Body->getName();
1618     unsigned I = Body->DynsymIndex;
1619     uint32_t Hash = hashSysV(Name) % NumSymbols;
1620     Chains[I] = Buckets[Hash];
1621     Buckets[Hash] = I;
1622   }
1623 }
1624
1625 PltSection::PltSection(size_t S)
1626     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
1627       HeaderSize(S) {}
1628
1629 void PltSection::writeTo(uint8_t *Buf) {
1630   // At beginning of PLT but not the IPLT, we have code to call the dynamic
1631   // linker to resolve dynsyms at runtime. Write such code.
1632   if (HeaderSize != 0)
1633     Target->writePltHeader(Buf);
1634   size_t Off = HeaderSize;
1635   // The IPlt is immediately after the Plt, account for this in RelOff
1636   unsigned PltOff = getPltRelocOff();
1637
1638   for (auto &I : Entries) {
1639     const SymbolBody *B = I.first;
1640     unsigned RelOff = I.second + PltOff;
1641     uint64_t Got = B->getGotPltVA();
1642     uint64_t Plt = this->getVA() + Off;
1643     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1644     Off += Target->PltEntrySize;
1645   }
1646 }
1647
1648 template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
1649   Sym.PltIndex = Entries.size();
1650   RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1651   if (HeaderSize == 0) {
1652     PltRelocSection = In<ELFT>::RelaIplt;
1653     Sym.IsInIplt = true;
1654   }
1655   unsigned RelOff = PltRelocSection->getRelocOffset();
1656   Entries.push_back(std::make_pair(&Sym, RelOff));
1657 }
1658
1659 size_t PltSection::getSize() const {
1660   return HeaderSize + Entries.size() * Target->PltEntrySize;
1661 }
1662
1663 // Some architectures such as additional symbols in the PLT section. For
1664 // example ARM uses mapping symbols to aid disassembly
1665 void PltSection::addSymbols() {
1666   // The PLT may have symbols defined for the Header, the IPLT has no header
1667   if (HeaderSize != 0)
1668     Target->addPltHeaderSymbols(this);
1669   size_t Off = HeaderSize;
1670   for (size_t I = 0; I < Entries.size(); ++I) {
1671     Target->addPltSymbols(this, Off);
1672     Off += Target->PltEntrySize;
1673   }
1674 }
1675
1676 unsigned PltSection::getPltRelocOff() const {
1677   return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
1678 }
1679
1680 GdbIndexSection::GdbIndexSection()
1681     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
1682       StringPool(llvm::StringTableBuilder::ELF) {}
1683
1684 // Iterative hash function for symbol's name is described in .gdb_index format
1685 // specification. Note that we use one for version 5 to 7 here, it is different
1686 // for version 4.
1687 static uint32_t hash(StringRef Str) {
1688   uint32_t R = 0;
1689   for (uint8_t C : Str)
1690     R = R * 67 + tolower(C) - 113;
1691   return R;
1692 }
1693
1694 static std::vector<std::pair<uint64_t, uint64_t>>
1695 readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1696   std::vector<std::pair<uint64_t, uint64_t>> Ret;
1697   for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1698     Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1699   return Ret;
1700 }
1701
1702 static InputSection *findSection(ArrayRef<InputSectionBase *> Arr,
1703                                  uint64_t Offset) {
1704   for (InputSectionBase *S : Arr)
1705     if (auto *IS = dyn_cast_or_null<InputSection>(S))
1706       if (IS != &InputSection::Discarded && IS->Live &&
1707           Offset >= IS->getOffsetInFile() &&
1708           Offset < IS->getOffsetInFile() + IS->getSize())
1709         return IS;
1710   return nullptr;
1711 }
1712
1713 static std::vector<AddressEntry>
1714 readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1715   std::vector<AddressEntry> Ret;
1716
1717   for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1718     DWARFAddressRangesVector Ranges;
1719     CU->collectAddressRanges(Ranges);
1720
1721     ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
1722     for (DWARFAddressRange &R : Ranges)
1723       if (InputSection *S = findSection(Sections, R.LowPC))
1724         Ret.push_back({S, R.LowPC - S->getOffsetInFile(),
1725                        R.HighPC - S->getOffsetInFile(), CurrentCU});
1726     ++CurrentCU;
1727   }
1728   return Ret;
1729 }
1730
1731 static std::vector<std::pair<StringRef, uint8_t>>
1732 readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1733   StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1734                       Dwarf.getGnuPubTypesSection()};
1735
1736   std::vector<std::pair<StringRef, uint8_t>> Ret;
1737   for (StringRef D : Data) {
1738     DWARFDebugPubTable PubTable(D, IsLE, true);
1739     for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1740       for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1741         Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1742   }
1743   return Ret;
1744 }
1745
1746 class ObjInfoTy : public llvm::LoadedObjectInfo {
1747   uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1748     auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1749     if (S.getFlags() & ELF::SHF_ALLOC)
1750       return S.getOffset();
1751     return 0;
1752   }
1753
1754   std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1755 };
1756
1757 void GdbIndexSection::readDwarf(InputSection *Sec) {
1758   Expected<std::unique_ptr<object::ObjectFile>> Obj =
1759       object::ObjectFile::createObjectFile(Sec->File->MB);
1760   if (!Obj) {
1761     error(toString(Sec->File) + ": error creating DWARF context");
1762     return;
1763   }
1764
1765   ObjInfoTy ObjInfo;
1766   DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
1767
1768   size_t CuId = CompilationUnits.size();
1769   for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1770     CompilationUnits.push_back(P);
1771
1772   for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
1773     AddressArea.push_back(Ent);
1774
1775   std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
1776       readPubNamesAndTypes(Dwarf, Config->IsLE);
1777
1778   for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1779     uint32_t Hash = hash(Pair.first);
1780     size_t Offset = StringPool.add(Pair.first);
1781
1782     bool IsNew;
1783     GdbSymbol *Sym;
1784     std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1785     if (IsNew) {
1786       Sym->CuVectorIndex = CuVectors.size();
1787       CuVectors.resize(CuVectors.size() + 1);
1788     }
1789
1790     CuVectors[Sym->CuVectorIndex].insert((Pair.second << 24) | (uint32_t)CuId);
1791   }
1792 }
1793
1794 void GdbIndexSection::finalizeContents() {
1795   if (Finalized)
1796     return;
1797   Finalized = true;
1798
1799   for (InputSectionBase *S : InputSections)
1800     if (InputSection *IS = dyn_cast<InputSection>(S))
1801       if (IS->getParent() && IS->Name == ".debug_info")
1802         readDwarf(IS);
1803
1804   SymbolTable.finalizeContents();
1805
1806   // GdbIndex header consist from version fields
1807   // and 5 more fields with different kinds of offsets.
1808   CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1809   SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
1810
1811   ConstantPoolOffset =
1812       SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1813
1814   for (std::set<uint32_t> &CuVec : CuVectors) {
1815     CuVectorsOffset.push_back(CuVectorsSize);
1816     CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1817   }
1818   StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1819
1820   StringPool.finalizeInOrder();
1821 }
1822
1823 size_t GdbIndexSection::getSize() const {
1824   const_cast<GdbIndexSection *>(this)->finalizeContents();
1825   return StringPoolOffset + StringPool.getSize();
1826 }
1827
1828 void GdbIndexSection::writeTo(uint8_t *Buf) {
1829   write32le(Buf, 7);                       // Write version.
1830   write32le(Buf + 4, CuListOffset);        // CU list offset.
1831   write32le(Buf + 8, CuTypesOffset);       // Types CU list offset.
1832   write32le(Buf + 12, CuTypesOffset);      // Address area offset.
1833   write32le(Buf + 16, SymTabOffset);       // Symbol table offset.
1834   write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
1835   Buf += 24;
1836
1837   // Write the CU list.
1838   for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
1839     write64le(Buf, CU.first);
1840     write64le(Buf + 8, CU.second);
1841     Buf += 16;
1842   }
1843
1844   // Write the address area.
1845   for (AddressEntry &E : AddressArea) {
1846     uint64_t BaseAddr = E.Section->getParent()->Addr + E.Section->getOffset(0);
1847     write64le(Buf, BaseAddr + E.LowAddress);
1848     write64le(Buf + 8, BaseAddr + E.HighAddress);
1849     write32le(Buf + 16, E.CuIndex);
1850     Buf += 20;
1851   }
1852
1853   // Write the symbol table.
1854   for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1855     GdbSymbol *Sym = SymbolTable.getSymbol(I);
1856     if (Sym) {
1857       size_t NameOffset =
1858           Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1859       size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1860       write32le(Buf, NameOffset);
1861       write32le(Buf + 4, CuVectorOffset);
1862     }
1863     Buf += 8;
1864   }
1865
1866   // Write the CU vectors into the constant pool.
1867   for (std::set<uint32_t> &CuVec : CuVectors) {
1868     write32le(Buf, CuVec.size());
1869     Buf += 4;
1870     for (uint32_t Val : CuVec) {
1871       write32le(Buf, Val);
1872       Buf += 4;
1873     }
1874   }
1875
1876   StringPool.write(Buf);
1877 }
1878
1879 bool GdbIndexSection::empty() const {
1880   return !Out::DebugInfo;
1881 }
1882
1883 template <class ELFT>
1884 EhFrameHeader<ELFT>::EhFrameHeader()
1885     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1886
1887 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1888 // Each entry of the search table consists of two values,
1889 // the starting PC from where FDEs covers, and the FDE's address.
1890 // It is sorted by PC.
1891 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1892   const endianness E = ELFT::TargetEndianness;
1893
1894   // Sort the FDE list by their PC and uniqueify. Usually there is only
1895   // one FDE for a PC (i.e. function), but if ICF merges two functions
1896   // into one, there can be more than one FDEs pointing to the address.
1897   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1898   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1899   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1900   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1901
1902   Buf[0] = 1;
1903   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1904   Buf[2] = DW_EH_PE_udata4;
1905   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1906   write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4);
1907   write32<E>(Buf + 8, Fdes.size());
1908   Buf += 12;
1909
1910   uint64_t VA = this->getVA();
1911   for (FdeData &Fde : Fdes) {
1912     write32<E>(Buf, Fde.Pc - VA);
1913     write32<E>(Buf + 4, Fde.FdeVA - VA);
1914     Buf += 8;
1915   }
1916 }
1917
1918 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1919   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1920   return 12 + In<ELFT>::EhFrame->NumFdes * 8;
1921 }
1922
1923 template <class ELFT>
1924 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1925   Fdes.push_back({Pc, FdeVA});
1926 }
1927
1928 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1929   return In<ELFT>::EhFrame->empty();
1930 }
1931
1932 template <class ELFT>
1933 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1934     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1935                        ".gnu.version_d") {}
1936
1937 static StringRef getFileDefName() {
1938   if (!Config->SoName.empty())
1939     return Config->SoName;
1940   return Config->OutputFile;
1941 }
1942
1943 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
1944   FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
1945   for (VersionDefinition &V : Config->VersionDefinitions)
1946     V.NameOff = InX::DynStrTab->addString(V.Name);
1947
1948   getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
1949
1950   // sh_info should be set to the number of definitions. This fact is missed in
1951   // documentation, but confirmed by binutils community:
1952   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1953   getParent()->Info = getVerDefNum();
1954 }
1955
1956 template <class ELFT>
1957 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1958                                               StringRef Name, size_t NameOff) {
1959   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1960   Verdef->vd_version = 1;
1961   Verdef->vd_cnt = 1;
1962   Verdef->vd_aux = sizeof(Elf_Verdef);
1963   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1964   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1965   Verdef->vd_ndx = Index;
1966   Verdef->vd_hash = hashSysV(Name);
1967
1968   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1969   Verdaux->vda_name = NameOff;
1970   Verdaux->vda_next = 0;
1971 }
1972
1973 template <class ELFT>
1974 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1975   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1976
1977   for (VersionDefinition &V : Config->VersionDefinitions) {
1978     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1979     writeOne(Buf, V.Id, V.Name, V.NameOff);
1980   }
1981
1982   // Need to terminate the last version definition.
1983   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1984   Verdef->vd_next = 0;
1985 }
1986
1987 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1988   return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1989 }
1990
1991 template <class ELFT>
1992 VersionTableSection<ELFT>::VersionTableSection()
1993     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1994                        ".gnu.version") {
1995   this->Entsize = sizeof(Elf_Versym);
1996 }
1997
1998 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
1999   // At the moment of june 2016 GNU docs does not mention that sh_link field
2000   // should be set, but Sun docs do. Also readelf relies on this field.
2001   getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
2002 }
2003
2004 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2005   return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
2006 }
2007
2008 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2009   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2010   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
2011     OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2012     ++OutVersym;
2013   }
2014 }
2015
2016 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2017   return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2018 }
2019
2020 template <class ELFT>
2021 VersionNeedSection<ELFT>::VersionNeedSection()
2022     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2023                        ".gnu.version_r") {
2024   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2025   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2026   // First identifiers are reserved by verdef section if it exist.
2027   NextIndex = getVerDefNum() + 1;
2028 }
2029
2030 template <class ELFT>
2031 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2032   auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2033   if (!Ver) {
2034     SS->symbol()->VersionId = VER_NDX_GLOBAL;
2035     return;
2036   }
2037
2038   auto *File = cast<SharedFile<ELFT>>(SS->File);
2039
2040   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2041   // to create one by adding it to our needed list and creating a dynstr entry
2042   // for the soname.
2043   if (File->VerdefMap.empty())
2044     Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
2045   typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
2046   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2047   // prepare to create one by allocating a version identifier and creating a
2048   // dynstr entry for the version name.
2049   if (NV.Index == 0) {
2050     NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2051                                           Ver->getAux()->vda_name);
2052     NV.Index = NextIndex++;
2053   }
2054   SS->symbol()->VersionId = NV.Index;
2055 }
2056
2057 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2058   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2059   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2060   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2061
2062   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2063     // Create an Elf_Verneed for this DSO.
2064     Verneed->vn_version = 1;
2065     Verneed->vn_cnt = P.first->VerdefMap.size();
2066     Verneed->vn_file = P.second;
2067     Verneed->vn_aux =
2068         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2069     Verneed->vn_next = sizeof(Elf_Verneed);
2070     ++Verneed;
2071
2072     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2073     // VerdefMap, which will only contain references to needed version
2074     // definitions. Each Elf_Vernaux is based on the information contained in
2075     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2076     // pointers, but is deterministic because the pointers refer to Elf_Verdef
2077     // data structures within a single input file.
2078     for (auto &NV : P.first->VerdefMap) {
2079       Vernaux->vna_hash = NV.first->vd_hash;
2080       Vernaux->vna_flags = 0;
2081       Vernaux->vna_other = NV.second.Index;
2082       Vernaux->vna_name = NV.second.StrTab;
2083       Vernaux->vna_next = sizeof(Elf_Vernaux);
2084       ++Vernaux;
2085     }
2086
2087     Vernaux[-1].vna_next = 0;
2088   }
2089   Verneed[-1].vn_next = 0;
2090 }
2091
2092 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2093   getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2094   getParent()->Info = Needed.size();
2095 }
2096
2097 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2098   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2099   for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2100     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2101   return Size;
2102 }
2103
2104 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2105   return getNeedNum() == 0;
2106 }
2107
2108 MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
2109                                              uint64_t Flags, uint32_t Alignment)
2110     : SyntheticSection(Flags, Type, Alignment, Name),
2111       Builder(StringTableBuilder::RAW, Alignment) {}
2112
2113 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2114   assert(!Finalized);
2115   MS->Parent = this;
2116   Sections.push_back(MS);
2117 }
2118
2119 void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2120
2121 bool MergeSyntheticSection::shouldTailMerge() const {
2122   return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2123 }
2124
2125 void MergeSyntheticSection::finalizeTailMerge() {
2126   // Add all string pieces to the string table builder to create section
2127   // contents.
2128   for (MergeInputSection *Sec : Sections)
2129     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2130       if (Sec->Pieces[I].Live)
2131         Builder.add(Sec->getData(I));
2132
2133   // Fix the string table content. After this, the contents will never change.
2134   Builder.finalize();
2135
2136   // finalize() fixed tail-optimized strings, so we can now get
2137   // offsets of strings. Get an offset for each string and save it
2138   // to a corresponding StringPiece for easy access.
2139   for (MergeInputSection *Sec : Sections)
2140     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2141       if (Sec->Pieces[I].Live)
2142         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2143 }
2144
2145 void MergeSyntheticSection::finalizeNoTailMerge() {
2146   // Add all string pieces to the string table builder to create section
2147   // contents. Because we are not tail-optimizing, offsets of strings are
2148   // fixed when they are added to the builder (string table builder contains
2149   // a hash table from strings to offsets).
2150   for (MergeInputSection *Sec : Sections)
2151     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2152       if (Sec->Pieces[I].Live)
2153         Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2154
2155   Builder.finalizeInOrder();
2156 }
2157
2158 void MergeSyntheticSection::finalizeContents() {
2159   if (Finalized)
2160     return;
2161   Finalized = true;
2162   if (shouldTailMerge())
2163     finalizeTailMerge();
2164   else
2165     finalizeNoTailMerge();
2166 }
2167
2168 size_t MergeSyntheticSection::getSize() const {
2169   // We should finalize string builder to know the size.
2170   const_cast<MergeSyntheticSection *>(this)->finalizeContents();
2171   return Builder.getSize();
2172 }
2173
2174 MipsRldMapSection::MipsRldMapSection()
2175     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2176                        ".rld_map") {}
2177
2178 ARMExidxSentinelSection::ARMExidxSentinelSection()
2179     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2180                        Config->Wordsize, ".ARM.exidx") {}
2181
2182 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
2183 // This section will have been sorted last in the .ARM.exidx table.
2184 // This table entry will have the form:
2185 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
2186 // The sentinel must have the PREL31 value of an address higher than any
2187 // address described by any other table entry.
2188 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
2189   // The Sections are sorted in order of ascending PREL31 address with the
2190   // sentinel last. We need to find the InputSection that precedes the
2191   // sentinel. By construction the Sentinel is in the last
2192   // InputSectionDescription as the InputSection that precedes it.
2193   OutputSectionCommand *C = Script->getCmd(getParent());
2194   auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
2195                           [](const BaseCommand *Base) {
2196                             return isa<InputSectionDescription>(Base);
2197                           });
2198   auto L = cast<InputSectionDescription>(*ISD);
2199   InputSection *Highest = L->Sections[L->Sections.size() - 2];
2200   InputSection *LS = Highest->getLinkOrderDep();
2201   uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
2202   uint64_t P = getVA();
2203   Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2204   write32le(Buf + 4, 0x1);
2205 }
2206
2207 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
2208     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
2209                        Config->Wordsize, ".text.thunk") {
2210   this->Parent = OS;
2211   this->OutSecOff = Off;
2212 }
2213
2214 void ThunkSection::addThunk(Thunk *T) {
2215   uint64_t Off = alignTo(Size, T->alignment);
2216   T->Offset = Off;
2217   Thunks.push_back(T);
2218   T->addSymbols(*this);
2219   Size = Off + T->size();
2220 }
2221
2222 void ThunkSection::writeTo(uint8_t *Buf) {
2223   for (const Thunk *T : Thunks)
2224     T->writeTo(Buf + T->Offset, *this);
2225 }
2226
2227 InputSection *ThunkSection::getTargetInputSection() const {
2228   const Thunk *T = Thunks.front();
2229   return T->getTargetInputSection();
2230 }
2231
2232 InputSection *InX::ARMAttributes;
2233 BssSection *InX::Bss;
2234 BssSection *InX::BssRelRo;
2235 BuildIdSection *InX::BuildId;
2236 InputSection *InX::Common;
2237 SyntheticSection *InX::Dynamic;
2238 StringTableSection *InX::DynStrTab;
2239 SymbolTableBaseSection *InX::DynSymTab;
2240 InputSection *InX::Interp;
2241 GdbIndexSection *InX::GdbIndex;
2242 GotSection *InX::Got;
2243 GotPltSection *InX::GotPlt;
2244 GnuHashTableSection *InX::GnuHashTab;
2245 IgotPltSection *InX::IgotPlt;
2246 MipsGotSection *InX::MipsGot;
2247 MipsRldMapSection *InX::MipsRldMap;
2248 PltSection *InX::Plt;
2249 PltSection *InX::Iplt;
2250 StringTableSection *InX::ShStrTab;
2251 StringTableSection *InX::StrTab;
2252 SymbolTableBaseSection *InX::SymTab;
2253
2254 template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2255 template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2256 template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2257 template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2258
2259 template InputSection *elf::createCommonSection<ELF32LE>();
2260 template InputSection *elf::createCommonSection<ELF32BE>();
2261 template InputSection *elf::createCommonSection<ELF64LE>();
2262 template InputSection *elf::createCommonSection<ELF64BE>();
2263
2264 template MergeInputSection *elf::createCommentSection<ELF32LE>();
2265 template MergeInputSection *elf::createCommentSection<ELF32BE>();
2266 template MergeInputSection *elf::createCommentSection<ELF64LE>();
2267 template MergeInputSection *elf::createCommentSection<ELF64BE>();
2268
2269 template class elf::MipsAbiFlagsSection<ELF32LE>;
2270 template class elf::MipsAbiFlagsSection<ELF32BE>;
2271 template class elf::MipsAbiFlagsSection<ELF64LE>;
2272 template class elf::MipsAbiFlagsSection<ELF64BE>;
2273
2274 template class elf::MipsOptionsSection<ELF32LE>;
2275 template class elf::MipsOptionsSection<ELF32BE>;
2276 template class elf::MipsOptionsSection<ELF64LE>;
2277 template class elf::MipsOptionsSection<ELF64BE>;
2278
2279 template class elf::MipsReginfoSection<ELF32LE>;
2280 template class elf::MipsReginfoSection<ELF32BE>;
2281 template class elf::MipsReginfoSection<ELF64LE>;
2282 template class elf::MipsReginfoSection<ELF64BE>;
2283
2284 template class elf::DynamicSection<ELF32LE>;
2285 template class elf::DynamicSection<ELF32BE>;
2286 template class elf::DynamicSection<ELF64LE>;
2287 template class elf::DynamicSection<ELF64BE>;
2288
2289 template class elf::RelocationSection<ELF32LE>;
2290 template class elf::RelocationSection<ELF32BE>;
2291 template class elf::RelocationSection<ELF64LE>;
2292 template class elf::RelocationSection<ELF64BE>;
2293
2294 template class elf::SymbolTableSection<ELF32LE>;
2295 template class elf::SymbolTableSection<ELF32BE>;
2296 template class elf::SymbolTableSection<ELF64LE>;
2297 template class elf::SymbolTableSection<ELF64BE>;
2298
2299 template class elf::HashTableSection<ELF32LE>;
2300 template class elf::HashTableSection<ELF32BE>;
2301 template class elf::HashTableSection<ELF64LE>;
2302 template class elf::HashTableSection<ELF64BE>;
2303
2304 template class elf::EhFrameHeader<ELF32LE>;
2305 template class elf::EhFrameHeader<ELF32BE>;
2306 template class elf::EhFrameHeader<ELF64LE>;
2307 template class elf::EhFrameHeader<ELF64BE>;
2308
2309 template class elf::VersionTableSection<ELF32LE>;
2310 template class elf::VersionTableSection<ELF32BE>;
2311 template class elf::VersionTableSection<ELF64LE>;
2312 template class elf::VersionTableSection<ELF64BE>;
2313
2314 template class elf::VersionNeedSection<ELF32LE>;
2315 template class elf::VersionNeedSection<ELF32BE>;
2316 template class elf::VersionNeedSection<ELF64LE>;
2317 template class elf::VersionNeedSection<ELF64BE>;
2318
2319 template class elf::VersionDefinitionSection<ELF32LE>;
2320 template class elf::VersionDefinitionSection<ELF32BE>;
2321 template class elf::VersionDefinitionSection<ELF64LE>;
2322 template class elf::VersionDefinitionSection<ELF64BE>;
2323
2324 template class elf::EhFrameSection<ELF32LE>;
2325 template class elf::EhFrameSection<ELF32BE>;
2326 template class elf::EhFrameSection<ELF64LE>;
2327 template class elf::EhFrameSection<ELF64BE>;