]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/SyntheticSections.cpp
Merge ^/head r318380 through r318559.
[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 (this->OutSec)
52     return this->OutSec->Addr + this->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 (OutSec)
371     OutSec->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->EHSec = 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 + this->OutSec->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->template relocate<ELFT>(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 = this->OutSec->Addr + Fde->OutputOff;
614         In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
615       }
616     }
617   }
618 }
619
620 GotBaseSection::GotBaseSection()
621     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
622                        Target->GotEntrySize, ".got") {}
623
624 void GotBaseSection::addEntry(SymbolBody &Sym) {
625   Sym.GotIndex = NumEntries;
626   ++NumEntries;
627 }
628
629 bool GotBaseSection::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 GotBaseSection::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 GotBaseSection::getGlobalDynAddr(const SymbolBody &B) const {
649   return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
650 }
651
652 uint64_t GotBaseSection::getGlobalDynOffset(const SymbolBody &B) const {
653   return B.GlobalDynIndex * Config->Wordsize;
654 }
655
656 void GotBaseSection::finalizeContents() {
657   Size = NumEntries * Config->Wordsize;
658 }
659
660 bool GotBaseSection::empty() const {
661   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
662   // we need to emit a GOT even if it's empty.
663   return NumEntries == 0 && !HasGotOffRel;
664 }
665
666 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
667   this->template relocate<ELFT>(Buf, Buf + Size);
668 }
669
670 MipsGotSection::MipsGotSection()
671     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
672                        ".got") {}
673
674 void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
675   // For "true" local symbols which can be referenced from the same module
676   // only compiler creates two instructions for address loading:
677   //
678   // lw   $8, 0($gp) # R_MIPS_GOT16
679   // addi $8, $8, 0  # R_MIPS_LO16
680   //
681   // The first instruction loads high 16 bits of the symbol address while
682   // the second adds an offset. That allows to reduce number of required
683   // GOT entries because only one global offset table entry is necessary
684   // for every 64 KBytes of local data. So for local symbols we need to
685   // allocate number of GOT entries to hold all required "page" addresses.
686   //
687   // All global symbols (hidden and regular) considered by compiler uniformly.
688   // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
689   // to load address of the symbol. So for each such symbol we need to
690   // allocate dedicated GOT entry to store its address.
691   //
692   // If a symbol is preemptible we need help of dynamic linker to get its
693   // final address. The corresponding GOT entries are allocated in the
694   // "global" part of GOT. Entries for non preemptible global symbol allocated
695   // in the "local" part of GOT.
696   //
697   // See "Global Offset Table" in Chapter 5:
698   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
699   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
700     // At this point we do not know final symbol value so to reduce number
701     // of allocated GOT entries do the following trick. Save all output
702     // sections referenced by GOT relocations. Then later in the `finalize`
703     // method calculate number of "pages" required to cover all saved output
704     // section and allocate appropriate number of GOT entries.
705     auto *DefSym = cast<DefinedRegular>(&Sym);
706     PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
707     return;
708   }
709   if (Sym.isTls()) {
710     // GOT entries created for MIPS TLS relocations behave like
711     // almost GOT entries from other ABIs. They go to the end
712     // of the global offset table.
713     Sym.GotIndex = TlsEntries.size();
714     TlsEntries.push_back(&Sym);
715     return;
716   }
717   auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
718     if (S.isInGot() && !A)
719       return;
720     size_t NewIndex = Items.size();
721     if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
722       return;
723     Items.emplace_back(&S, A);
724     if (!A)
725       S.GotIndex = NewIndex;
726   };
727   if (Sym.isPreemptible()) {
728     // Ignore addends for preemptible symbols. They got single GOT entry anyway.
729     AddEntry(Sym, 0, GlobalEntries);
730     Sym.IsInGlobalMipsGot = true;
731   } else if (Expr == R_MIPS_GOT_OFF32) {
732     AddEntry(Sym, Addend, LocalEntries32);
733     Sym.Is32BitMipsGot = true;
734   } else {
735     // Hold local GOT entries accessed via a 16-bit index separately.
736     // That allows to write them in the beginning of the GOT and keep
737     // their indexes as less as possible to escape relocation's overflow.
738     AddEntry(Sym, Addend, LocalEntries);
739   }
740 }
741
742 bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
743   if (Sym.GlobalDynIndex != -1U)
744     return false;
745   Sym.GlobalDynIndex = TlsEntries.size();
746   // Global Dynamic TLS entries take two GOT slots.
747   TlsEntries.push_back(nullptr);
748   TlsEntries.push_back(&Sym);
749   return true;
750 }
751
752 // Reserves TLS entries for a TLS module ID and a TLS block offset.
753 // In total it takes two GOT slots.
754 bool MipsGotSection::addTlsIndex() {
755   if (TlsIndexOff != uint32_t(-1))
756     return false;
757   TlsIndexOff = TlsEntries.size() * Config->Wordsize;
758   TlsEntries.push_back(nullptr);
759   TlsEntries.push_back(nullptr);
760   return true;
761 }
762
763 static uint64_t getMipsPageAddr(uint64_t Addr) {
764   return (Addr + 0x8000) & ~0xffff;
765 }
766
767 static uint64_t getMipsPageCount(uint64_t Size) {
768   return (Size + 0xfffe) / 0xffff + 1;
769 }
770
771 uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
772                                             int64_t Addend) const {
773   const OutputSection *OutSec =
774       cast<DefinedRegular>(&B)->Section->getOutputSection();
775   uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
776   uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
777   uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
778   assert(Index < PageEntriesNum);
779   return (HeaderEntriesNum + Index) * Config->Wordsize;
780 }
781
782 uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
783                                             int64_t Addend) const {
784   // Calculate offset of the GOT entries block: TLS, global, local.
785   uint64_t Index = HeaderEntriesNum + PageEntriesNum;
786   if (B.isTls())
787     Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
788   else if (B.IsInGlobalMipsGot)
789     Index += LocalEntries.size() + LocalEntries32.size();
790   else if (B.Is32BitMipsGot)
791     Index += LocalEntries.size();
792   // Calculate offset of the GOT entry in the block.
793   if (B.isInGot())
794     Index += B.GotIndex;
795   else {
796     auto It = EntryIndexMap.find({&B, Addend});
797     assert(It != EntryIndexMap.end());
798     Index += It->second;
799   }
800   return Index * Config->Wordsize;
801 }
802
803 uint64_t MipsGotSection::getTlsOffset() const {
804   return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
805 }
806
807 uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
808   return B.GlobalDynIndex * Config->Wordsize;
809 }
810
811 const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
812   return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
813 }
814
815 unsigned MipsGotSection::getLocalEntriesNum() const {
816   return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
817          LocalEntries32.size();
818 }
819
820 void MipsGotSection::finalizeContents() {
821   updateAllocSize();
822 }
823
824 void MipsGotSection::updateAllocSize() {
825   PageEntriesNum = 0;
826   for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
827     // For each output section referenced by GOT page relocations calculate
828     // and save into PageIndexMap an upper bound of MIPS GOT entries required
829     // to store page addresses of local symbols. We assume the worst case -
830     // each 64kb page of the output section has at least one GOT relocation
831     // against it. And take in account the case when the section intersects
832     // page boundaries.
833     P.second = PageEntriesNum;
834     PageEntriesNum += getMipsPageCount(P.first->Size);
835   }
836   Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
837          Config->Wordsize;
838 }
839
840 bool MipsGotSection::empty() const {
841   // We add the .got section to the result for dynamic MIPS target because
842   // its address and properties are mentioned in the .dynamic section.
843   return Config->Relocatable;
844 }
845
846 uint64_t MipsGotSection::getGp() const {
847   return ElfSym::MipsGp->getVA(0);
848 }
849
850 static uint64_t readUint(uint8_t *Buf) {
851   if (Config->Is64)
852     return read64(Buf, Config->Endianness);
853   return read32(Buf, Config->Endianness);
854 }
855
856 static void writeUint(uint8_t *Buf, uint64_t Val) {
857   if (Config->Is64)
858     write64(Buf, Val, Config->Endianness);
859   else
860     write32(Buf, Val, Config->Endianness);
861 }
862
863 void MipsGotSection::writeTo(uint8_t *Buf) {
864   // Set the MSB of the second GOT slot. This is not required by any
865   // MIPS ABI documentation, though.
866   //
867   // There is a comment in glibc saying that "The MSB of got[1] of a
868   // gnu object is set to identify gnu objects," and in GNU gold it
869   // says "the second entry will be used by some runtime loaders".
870   // But how this field is being used is unclear.
871   //
872   // We are not really willing to mimic other linkers behaviors
873   // without understanding why they do that, but because all files
874   // generated by GNU tools have this special GOT value, and because
875   // we've been doing this for years, it is probably a safe bet to
876   // keep doing this for now. We really need to revisit this to see
877   // if we had to do this.
878   writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
879   Buf += HeaderEntriesNum * Config->Wordsize;
880   // Write 'page address' entries to the local part of the GOT.
881   for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
882     size_t PageCount = getMipsPageCount(L.first->Size);
883     uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
884     for (size_t PI = 0; PI < PageCount; ++PI) {
885       uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
886       writeUint(Entry, FirstPageAddr + PI * 0x10000);
887     }
888   }
889   Buf += PageEntriesNum * Config->Wordsize;
890   auto AddEntry = [&](const GotEntry &SA) {
891     uint8_t *Entry = Buf;
892     Buf += Config->Wordsize;
893     const SymbolBody *Body = SA.first;
894     uint64_t VA = Body->getVA(SA.second);
895     writeUint(Entry, VA);
896   };
897   std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
898   std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
899   std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
900   // Initialize TLS-related GOT entries. If the entry has a corresponding
901   // dynamic relocations, leave it initialized by zero. Write down adjusted
902   // TLS symbol's values otherwise. To calculate the adjustments use offsets
903   // for thread-local storage.
904   // https://www.linux-mips.org/wiki/NPTL
905   if (TlsIndexOff != -1U && !Config->Pic)
906     writeUint(Buf + TlsIndexOff, 1);
907   for (const SymbolBody *B : TlsEntries) {
908     if (!B || B->isPreemptible())
909       continue;
910     uint64_t VA = B->getVA();
911     if (B->GotIndex != -1U) {
912       uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
913       writeUint(Entry, VA - 0x7000);
914     }
915     if (B->GlobalDynIndex != -1U) {
916       uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
917       writeUint(Entry, 1);
918       Entry += Config->Wordsize;
919       writeUint(Entry, VA - 0x8000);
920     }
921   }
922 }
923
924 GotPltSection::GotPltSection()
925     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
926                        Target->GotPltEntrySize, ".got.plt") {}
927
928 void GotPltSection::addEntry(SymbolBody &Sym) {
929   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
930   Entries.push_back(&Sym);
931 }
932
933 size_t GotPltSection::getSize() const {
934   return (Target->GotPltHeaderEntriesNum + Entries.size()) *
935          Target->GotPltEntrySize;
936 }
937
938 void GotPltSection::writeTo(uint8_t *Buf) {
939   Target->writeGotPltHeader(Buf);
940   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
941   for (const SymbolBody *B : Entries) {
942     Target->writeGotPlt(Buf, *B);
943     Buf += Config->Wordsize;
944   }
945 }
946
947 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is
948 // part of the .got.plt
949 IgotPltSection::IgotPltSection()
950     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
951                        Target->GotPltEntrySize,
952                        Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
953
954 void IgotPltSection::addEntry(SymbolBody &Sym) {
955   Sym.IsInIgot = true;
956   Sym.GotPltIndex = Entries.size();
957   Entries.push_back(&Sym);
958 }
959
960 size_t IgotPltSection::getSize() const {
961   return Entries.size() * Target->GotPltEntrySize;
962 }
963
964 void IgotPltSection::writeTo(uint8_t *Buf) {
965   for (const SymbolBody *B : Entries) {
966     Target->writeIgotPlt(Buf, *B);
967     Buf += Config->Wordsize;
968   }
969 }
970
971 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
972     : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
973       Dynamic(Dynamic) {
974   // ELF string tables start with a NUL byte.
975   addString("");
976 }
977
978 // Adds a string to the string table. If HashIt is true we hash and check for
979 // duplicates. It is optional because the name of global symbols are already
980 // uniqued and hashing them again has a big cost for a small value: uniquing
981 // them with some other string that happens to be the same.
982 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
983   if (HashIt) {
984     auto R = StringMap.insert(std::make_pair(S, this->Size));
985     if (!R.second)
986       return R.first->second;
987   }
988   unsigned Ret = this->Size;
989   this->Size = this->Size + S.size() + 1;
990   Strings.push_back(S);
991   return Ret;
992 }
993
994 void StringTableSection::writeTo(uint8_t *Buf) {
995   for (StringRef S : Strings) {
996     memcpy(Buf, S.data(), S.size());
997     Buf += S.size() + 1;
998   }
999 }
1000
1001 // Returns the number of version definition entries. Because the first entry
1002 // is for the version definition itself, it is the number of versioned symbols
1003 // plus one. Note that we don't support multiple versions yet.
1004 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1005
1006 template <class ELFT>
1007 DynamicSection<ELFT>::DynamicSection()
1008     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1009                        ".dynamic") {
1010   this->Entsize = ELFT::Is64Bits ? 16 : 8;
1011
1012   // .dynamic section is not writable on MIPS.
1013   // See "Special Section" in Chapter 4 in the following document:
1014   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1015   if (Config->EMachine == EM_MIPS)
1016     this->Flags = SHF_ALLOC;
1017
1018   addEntries();
1019 }
1020
1021 // There are some dynamic entries that don't depend on other sections.
1022 // Such entries can be set early.
1023 template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1024   // Add strings to .dynstr early so that .dynstr's size will be
1025   // fixed early.
1026   for (StringRef S : Config->AuxiliaryList)
1027     add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
1028   if (!Config->Rpath.empty())
1029     add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1030          InX::DynStrTab->addString(Config->Rpath)});
1031   for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1032     if (F->isNeeded())
1033       add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
1034   if (!Config->SoName.empty())
1035     add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
1036
1037   // Set DT_FLAGS and DT_FLAGS_1.
1038   uint32_t DtFlags = 0;
1039   uint32_t DtFlags1 = 0;
1040   if (Config->Bsymbolic)
1041     DtFlags |= DF_SYMBOLIC;
1042   if (Config->ZNodelete)
1043     DtFlags1 |= DF_1_NODELETE;
1044   if (Config->ZNodlopen)
1045     DtFlags1 |= DF_1_NOOPEN;
1046   if (Config->ZNow) {
1047     DtFlags |= DF_BIND_NOW;
1048     DtFlags1 |= DF_1_NOW;
1049   }
1050   if (Config->ZOrigin) {
1051     DtFlags |= DF_ORIGIN;
1052     DtFlags1 |= DF_1_ORIGIN;
1053   }
1054
1055   if (DtFlags)
1056     add({DT_FLAGS, DtFlags});
1057   if (DtFlags1)
1058     add({DT_FLAGS_1, DtFlags1});
1059
1060   if (!Config->Shared && !Config->Relocatable)
1061     add({DT_DEBUG, (uint64_t)0});
1062 }
1063
1064 // Add remaining entries to complete .dynamic contents.
1065 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1066   if (this->Size)
1067     return; // Already finalized.
1068
1069   this->Link = InX::DynStrTab->OutSec->SectionIndex;
1070   if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
1071     bool IsRela = Config->IsRela;
1072     add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
1073     add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
1074     add({IsRela ? DT_RELAENT : DT_RELENT,
1075          uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1076
1077     // MIPS dynamic loader does not support RELCOUNT tag.
1078     // The problem is in the tight relation between dynamic
1079     // relocations and GOT. So do not emit this tag on MIPS.
1080     if (Config->EMachine != EM_MIPS) {
1081       size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
1082       if (Config->ZCombreloc && NumRelativeRels)
1083         add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
1084     }
1085   }
1086   if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
1087     add({DT_JMPREL, In<ELFT>::RelaPlt});
1088     add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
1089     add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
1090          InX::GotPlt});
1091     add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
1092   }
1093
1094   add({DT_SYMTAB, InX::DynSymTab});
1095   add({DT_SYMENT, sizeof(Elf_Sym)});
1096   add({DT_STRTAB, InX::DynStrTab});
1097   add({DT_STRSZ, InX::DynStrTab->getSize()});
1098   if (!Config->ZText)
1099     add({DT_TEXTREL, (uint64_t)0});
1100   if (InX::GnuHashTab)
1101     add({DT_GNU_HASH, InX::GnuHashTab});
1102   if (In<ELFT>::HashTab)
1103     add({DT_HASH, In<ELFT>::HashTab});
1104
1105   if (Out::PreinitArray) {
1106     add({DT_PREINIT_ARRAY, Out::PreinitArray});
1107     add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
1108   }
1109   if (Out::InitArray) {
1110     add({DT_INIT_ARRAY, Out::InitArray});
1111     add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
1112   }
1113   if (Out::FiniArray) {
1114     add({DT_FINI_ARRAY, Out::FiniArray});
1115     add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
1116   }
1117
1118   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
1119     add({DT_INIT, B});
1120   if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
1121     add({DT_FINI, B});
1122
1123   bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1124   if (HasVerNeed || In<ELFT>::VerDef)
1125     add({DT_VERSYM, In<ELFT>::VerSym});
1126   if (In<ELFT>::VerDef) {
1127     add({DT_VERDEF, In<ELFT>::VerDef});
1128     add({DT_VERDEFNUM, getVerDefNum()});
1129   }
1130   if (HasVerNeed) {
1131     add({DT_VERNEED, In<ELFT>::VerNeed});
1132     add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
1133   }
1134
1135   if (Config->EMachine == EM_MIPS) {
1136     add({DT_MIPS_RLD_VERSION, 1});
1137     add({DT_MIPS_FLAGS, RHF_NOTPOT});
1138     add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
1139     add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
1140     add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1141     if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
1142       add({DT_MIPS_GOTSYM, B->DynsymIndex});
1143     else
1144       add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
1145     add({DT_PLTGOT, InX::MipsGot});
1146     if (InX::MipsRldMap)
1147       add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
1148   }
1149
1150   this->OutSec->Link = this->Link;
1151
1152   // +1 for DT_NULL
1153   this->Size = (Entries.size() + 1) * this->Entsize;
1154 }
1155
1156 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1157   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1158
1159   for (const Entry &E : Entries) {
1160     P->d_tag = E.Tag;
1161     switch (E.Kind) {
1162     case Entry::SecAddr:
1163       P->d_un.d_ptr = E.OutSec->Addr;
1164       break;
1165     case Entry::InSecAddr:
1166       P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1167       break;
1168     case Entry::SecSize:
1169       P->d_un.d_val = E.OutSec->Size;
1170       break;
1171     case Entry::SymAddr:
1172       P->d_un.d_ptr = E.Sym->getVA();
1173       break;
1174     case Entry::PlainInt:
1175       P->d_un.d_val = E.Val;
1176       break;
1177     }
1178     ++P;
1179   }
1180 }
1181
1182 uint64_t DynamicReloc::getOffset() const {
1183   return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
1184 }
1185
1186 int64_t DynamicReloc::getAddend() const {
1187   if (UseSymVA)
1188     return Sym->getVA(Addend);
1189   return Addend;
1190 }
1191
1192 uint32_t DynamicReloc::getSymIndex() const {
1193   if (Sym && !UseSymVA)
1194     return Sym->DynsymIndex;
1195   return 0;
1196 }
1197
1198 template <class ELFT>
1199 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1200     : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
1201                        Config->Wordsize, Name),
1202       Sort(Sort) {
1203   this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1204 }
1205
1206 template <class ELFT>
1207 void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
1208   if (Reloc.Type == Target->RelativeRel)
1209     ++NumRelativeRelocs;
1210   Relocs.push_back(Reloc);
1211 }
1212
1213 template <class ELFT, class RelTy>
1214 static bool compRelocations(const RelTy &A, const RelTy &B) {
1215   bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1216   bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1217   if (AIsRel != BIsRel)
1218     return AIsRel;
1219
1220   return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1221 }
1222
1223 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1224   uint8_t *BufBegin = Buf;
1225   for (const DynamicReloc &Rel : Relocs) {
1226     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
1227     Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1228
1229     if (Config->IsRela)
1230       P->r_addend = Rel.getAddend();
1231     P->r_offset = Rel.getOffset();
1232     if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1233       // Dynamic relocation against MIPS GOT section make deal TLS entries
1234       // allocated in the end of the GOT. We need to adjust the offset to take
1235       // in account 'local' and 'global' GOT entries.
1236       P->r_offset += InX::MipsGot->getTlsOffset();
1237     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1238   }
1239
1240   if (Sort) {
1241     if (Config->IsRela)
1242       std::stable_sort((Elf_Rela *)BufBegin,
1243                        (Elf_Rela *)BufBegin + Relocs.size(),
1244                        compRelocations<ELFT, Elf_Rela>);
1245     else
1246       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1247                        compRelocations<ELFT, Elf_Rel>);
1248   }
1249 }
1250
1251 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1252   return this->Entsize * Relocs.size();
1253 }
1254
1255 template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
1256   this->Link = InX::DynSymTab ? InX::DynSymTab->OutSec->SectionIndex
1257                               : InX::SymTab->OutSec->SectionIndex;
1258
1259   // Set required output section properties.
1260   this->OutSec->Link = this->Link;
1261 }
1262
1263 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1264     : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1265                        StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1266                        Config->Wordsize,
1267                        StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1268       StrTabSec(StrTabSec) {}
1269
1270 // Orders symbols according to their positions in the GOT,
1271 // in compliance with MIPS ABI rules.
1272 // See "Global Offset Table" in Chapter 5 in the following document
1273 // for detailed description:
1274 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1275 static bool sortMipsSymbols(const SymbolTableEntry &L,
1276                             const SymbolTableEntry &R) {
1277   // Sort entries related to non-local preemptible symbols by GOT indexes.
1278   // All other entries go to the first part of GOT in arbitrary order.
1279   bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1280   bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
1281   if (LIsInLocalGot || RIsInLocalGot)
1282     return !RIsInLocalGot;
1283   return L.Symbol->GotIndex < R.Symbol->GotIndex;
1284 }
1285
1286 // Finalize a symbol table. The ELF spec requires that all local
1287 // symbols precede global symbols, so we sort symbol entries in this
1288 // function. (For .dynsym, we don't do that because symbols for
1289 // dynamic linking are inherently all globals.)
1290 void SymbolTableBaseSection::finalizeContents() {
1291   this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
1292
1293   // If it is a .dynsym, there should be no local symbols, but we need
1294   // to do a few things for the dynamic linker.
1295   if (this->Type == SHT_DYNSYM) {
1296     // Section's Info field has the index of the first non-local symbol.
1297     // Because the first symbol entry is a null entry, 1 is the first.
1298     this->OutSec->Info = 1;
1299
1300     if (InX::GnuHashTab) {
1301       // NB: It also sorts Symbols to meet the GNU hash table requirements.
1302       InX::GnuHashTab->addSymbols(Symbols);
1303     } else if (Config->EMachine == EM_MIPS) {
1304       std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1305     }
1306
1307     size_t I = 0;
1308     for (const SymbolTableEntry &S : Symbols)
1309       S.Symbol->DynsymIndex = ++I;
1310     return;
1311   }
1312 }
1313
1314 void SymbolTableBaseSection::postThunkContents() {
1315   if (this->Type == SHT_DYNSYM)
1316     return;
1317   // move all local symbols before global symbols.
1318   auto It = std::stable_partition(
1319       Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1320         return S.Symbol->isLocal() ||
1321                S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1322       });
1323   size_t NumLocals = It - Symbols.begin();
1324   this->OutSec->Info = NumLocals + 1;
1325 }
1326
1327 void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
1328   // Adding a local symbol to a .dynsym is a bug.
1329   assert(this->Type != SHT_DYNSYM || !B->isLocal());
1330
1331   bool HashIt = B->isLocal();
1332   Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1333 }
1334
1335 size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
1336   auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1337     if (E.Symbol == Body)
1338       return true;
1339     // This is used for -r, so we have to handle multiple section
1340     // symbols being combined.
1341     if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
1342       return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1343              cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
1344     return false;
1345   });
1346   if (I == Symbols.end())
1347     return 0;
1348   return I - Symbols.begin() + 1;
1349 }
1350
1351 template <class ELFT>
1352 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1353     : SymbolTableBaseSection(StrTabSec) {
1354   this->Entsize = sizeof(Elf_Sym);
1355 }
1356
1357 // Write the internal symbol table contents to the output symbol table.
1358 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1359   // The first entry is a null entry as per the ELF spec.
1360   Buf += sizeof(Elf_Sym);
1361
1362   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1363
1364   for (SymbolTableEntry &Ent : Symbols) {
1365     SymbolBody *Body = Ent.Symbol;
1366
1367     // Set st_info and st_other.
1368     if (Body->isLocal()) {
1369       ESym->setBindingAndType(STB_LOCAL, Body->Type);
1370     } else {
1371       ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1372       ESym->setVisibility(Body->symbol()->Visibility);
1373     }
1374
1375     ESym->st_name = Ent.StrTabOffset;
1376     ESym->st_size = Body->getSize<ELFT>();
1377
1378     // Set a section index.
1379     if (const OutputSection *OutSec = Body->getOutputSection())
1380       ESym->st_shndx = OutSec->SectionIndex;
1381     else if (isa<DefinedRegular>(Body))
1382       ESym->st_shndx = SHN_ABS;
1383     else if (isa<DefinedCommon>(Body))
1384       ESym->st_shndx = SHN_COMMON;
1385
1386     // st_value is usually an address of a symbol, but that has a
1387     // special meaining for uninstantiated common symbols (this can
1388     // occur if -r is given).
1389     if (!Config->DefineCommon && isa<DefinedCommon>(Body))
1390       ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
1391     else
1392       ESym->st_value = Body->getVA();
1393
1394     ++ESym;
1395   }
1396
1397   // On MIPS we need to mark symbol which has a PLT entry and requires
1398   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1399   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1400   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1401   if (Config->EMachine == EM_MIPS) {
1402     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1403
1404     for (SymbolTableEntry &Ent : Symbols) {
1405       SymbolBody *Body = Ent.Symbol;
1406       if (Body->isInPlt() && Body->NeedsPltAddr)
1407         ESym->st_other |= STO_MIPS_PLT;
1408
1409       if (Config->Relocatable)
1410         if (auto *D = dyn_cast<DefinedRegular>(Body))
1411           if (D->isMipsPIC<ELFT>())
1412             ESym->st_other |= STO_MIPS_PIC;
1413       ++ESym;
1414     }
1415   }
1416 }
1417
1418 // .hash and .gnu.hash sections contain on-disk hash tables that map
1419 // symbol names to their dynamic symbol table indices. Their purpose
1420 // is to help the dynamic linker resolve symbols quickly. If ELF files
1421 // don't have them, the dynamic linker has to do linear search on all
1422 // dynamic symbols, which makes programs slower. Therefore, a .hash
1423 // section is added to a DSO by default. A .gnu.hash is added if you
1424 // give the -hash-style=gnu or -hash-style=both option.
1425 //
1426 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
1427 // Each ELF file has a list of DSOs that the ELF file depends on and a
1428 // list of dynamic symbols that need to be resolved from any of the
1429 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1430 // where m is the number of DSOs and n is the number of dynamic
1431 // symbols. For modern large programs, both m and n are large.  So
1432 // making each step faster by using hash tables substiantially
1433 // improves time to load programs.
1434 //
1435 // (Note that this is not the only way to design the shared library.
1436 // For instance, the Windows DLL takes a different approach. On
1437 // Windows, each dynamic symbol has a name of DLL from which the symbol
1438 // has to be resolved. That makes the cost of symbol resolution O(n).
1439 // This disables some hacky techniques you can use on Unix such as
1440 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1441 //
1442 // Due to historical reasons, we have two different hash tables, .hash
1443 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1444 // and better version of .hash. .hash is just an on-disk hash table, but
1445 // .gnu.hash has a bloom filter in addition to a hash table to skip
1446 // DSOs very quickly. If you are sure that your dynamic linker knows
1447 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1448 // safe bet is to specify -hash-style=both for backward compatibilty.
1449 GnuHashTableSection::GnuHashTableSection()
1450     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1451 }
1452
1453 void GnuHashTableSection::finalizeContents() {
1454   this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
1455
1456   // Computes bloom filter size in word size. We want to allocate 8
1457   // bits for each symbol. It must be a power of two.
1458   if (Symbols.empty())
1459     MaskWords = 1;
1460   else
1461     MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
1462
1463   Size = 16;                            // Header
1464   Size += Config->Wordsize * MaskWords; // Bloom filter
1465   Size += NBuckets * 4;                 // Hash buckets
1466   Size += Symbols.size() * 4;           // Hash values
1467 }
1468
1469 void GnuHashTableSection::writeTo(uint8_t *Buf) {
1470   // Write a header.
1471   write32(Buf, NBuckets, Config->Endianness);
1472   write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
1473           Config->Endianness);
1474   write32(Buf + 8, MaskWords, Config->Endianness);
1475   write32(Buf + 12, getShift2(), Config->Endianness);
1476   Buf += 16;
1477
1478   // Write a bloom filter and a hash table.
1479   writeBloomFilter(Buf);
1480   Buf += Config->Wordsize * MaskWords;
1481   writeHashTable(Buf);
1482 }
1483
1484 // This function writes a 2-bit bloom filter. This bloom filter alone
1485 // usually filters out 80% or more of all symbol lookups [1].
1486 // The dynamic linker uses the hash table only when a symbol is not
1487 // filtered out by a bloom filter.
1488 //
1489 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1490 //     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
1491 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
1492   const unsigned C = Config->Wordsize * 8;
1493   for (const Entry &Sym : Symbols) {
1494     size_t I = (Sym.Hash / C) & (MaskWords - 1);
1495     uint64_t Val = readUint(Buf + I * Config->Wordsize);
1496     Val |= uint64_t(1) << (Sym.Hash % C);
1497     Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1498     writeUint(Buf + I * Config->Wordsize, Val);
1499   }
1500 }
1501
1502 void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
1503   // Group symbols by hash value.
1504   std::vector<std::vector<Entry>> Syms(NBuckets);
1505   for (const Entry &Ent : Symbols)
1506     Syms[Ent.Hash % NBuckets].push_back(Ent);
1507
1508   // Write hash buckets. Hash buckets contain indices in the following
1509   // hash value table.
1510   uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
1511   for (size_t I = 0; I < NBuckets; ++I)
1512     if (!Syms[I].empty())
1513       write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
1514
1515   // Write a hash value table. It represents a sequence of chains that
1516   // share the same hash modulo value. The last element of each chain
1517   // is terminated by LSB 1.
1518   uint32_t *Values = Buckets + NBuckets;
1519   size_t I = 0;
1520   for (std::vector<Entry> &Vec : Syms) {
1521     if (Vec.empty())
1522       continue;
1523     for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1524       write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1525     write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
1526   }
1527 }
1528
1529 static uint32_t hashGnu(StringRef Name) {
1530   uint32_t H = 5381;
1531   for (uint8_t C : Name)
1532     H = (H << 5) + H + C;
1533   return H;
1534 }
1535
1536 // Returns a number of hash buckets to accomodate given number of elements.
1537 // We want to choose a moderate number that is not too small (which
1538 // causes too many hash collisions) and not too large (which wastes
1539 // disk space.)
1540 //
1541 // We return a prime number because it (is believed to) achieve good
1542 // hash distribution.
1543 static size_t getBucketSize(size_t NumSymbols) {
1544   // List of largest prime numbers that are not greater than 2^n + 1.
1545   for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1546                    251, 127, 61, 31, 13, 7, 3, 1})
1547     if (N <= NumSymbols)
1548       return N;
1549   return 0;
1550 }
1551
1552 // Add symbols to this symbol hash table. Note that this function
1553 // destructively sort a given vector -- which is needed because
1554 // GNU-style hash table places some sorting requirements.
1555 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
1556   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1557   // its type correctly.
1558   std::vector<SymbolTableEntry>::iterator Mid =
1559       std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1560         return S.Symbol->isUndefined();
1561       });
1562   if (Mid == V.end())
1563     return;
1564
1565   for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1566     SymbolBody *B = Ent.Symbol;
1567     Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
1568   }
1569
1570   NBuckets = getBucketSize(Symbols.size());
1571   std::stable_sort(Symbols.begin(), Symbols.end(),
1572                    [&](const Entry &L, const Entry &R) {
1573                      return L.Hash % NBuckets < R.Hash % NBuckets;
1574                    });
1575
1576   V.erase(Mid, V.end());
1577   for (const Entry &Ent : Symbols)
1578     V.push_back({Ent.Body, Ent.StrTabOffset});
1579 }
1580
1581 template <class ELFT>
1582 HashTableSection<ELFT>::HashTableSection()
1583     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1584   this->Entsize = 4;
1585 }
1586
1587 template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
1588   this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
1589
1590   unsigned NumEntries = 2;                            // nbucket and nchain.
1591   NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
1592
1593   // Create as many buckets as there are symbols.
1594   // FIXME: This is simplistic. We can try to optimize it, but implementing
1595   // support for SHT_GNU_HASH is probably even more profitable.
1596   NumEntries += InX::DynSymTab->getNumSymbols();
1597   this->Size = NumEntries * 4;
1598 }
1599
1600 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1601   // A 32-bit integer type in the target endianness.
1602   typedef typename ELFT::Word Elf_Word;
1603
1604   unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
1605
1606   auto *P = reinterpret_cast<Elf_Word *>(Buf);
1607   *P++ = NumSymbols; // nbucket
1608   *P++ = NumSymbols; // nchain
1609
1610   Elf_Word *Buckets = P;
1611   Elf_Word *Chains = P + NumSymbols;
1612
1613   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
1614     SymbolBody *Body = S.Symbol;
1615     StringRef Name = Body->getName();
1616     unsigned I = Body->DynsymIndex;
1617     uint32_t Hash = hashSysV(Name) % NumSymbols;
1618     Chains[I] = Buckets[Hash];
1619     Buckets[Hash] = I;
1620   }
1621 }
1622
1623 PltSection::PltSection(size_t S)
1624     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
1625       HeaderSize(S) {}
1626
1627 void PltSection::writeTo(uint8_t *Buf) {
1628   // At beginning of PLT but not the IPLT, we have code to call the dynamic
1629   // linker to resolve dynsyms at runtime. Write such code.
1630   if (HeaderSize != 0)
1631     Target->writePltHeader(Buf);
1632   size_t Off = HeaderSize;
1633   // The IPlt is immediately after the Plt, account for this in RelOff
1634   unsigned PltOff = getPltRelocOff();
1635
1636   for (auto &I : Entries) {
1637     const SymbolBody *B = I.first;
1638     unsigned RelOff = I.second + PltOff;
1639     uint64_t Got = B->getGotPltVA();
1640     uint64_t Plt = this->getVA() + Off;
1641     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1642     Off += Target->PltEntrySize;
1643   }
1644 }
1645
1646 template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
1647   Sym.PltIndex = Entries.size();
1648   RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1649   if (HeaderSize == 0) {
1650     PltRelocSection = In<ELFT>::RelaIplt;
1651     Sym.IsInIplt = true;
1652   }
1653   unsigned RelOff = PltRelocSection->getRelocOffset();
1654   Entries.push_back(std::make_pair(&Sym, RelOff));
1655 }
1656
1657 size_t PltSection::getSize() const {
1658   return HeaderSize + Entries.size() * Target->PltEntrySize;
1659 }
1660
1661 // Some architectures such as additional symbols in the PLT section. For
1662 // example ARM uses mapping symbols to aid disassembly
1663 void PltSection::addSymbols() {
1664   // The PLT may have symbols defined for the Header, the IPLT has no header
1665   if (HeaderSize != 0)
1666     Target->addPltHeaderSymbols(this);
1667   size_t Off = HeaderSize;
1668   for (size_t I = 0; I < Entries.size(); ++I) {
1669     Target->addPltSymbols(this, Off);
1670     Off += Target->PltEntrySize;
1671   }
1672 }
1673
1674 unsigned PltSection::getPltRelocOff() const {
1675   return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
1676 }
1677
1678 GdbIndexSection::GdbIndexSection()
1679     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
1680       StringPool(llvm::StringTableBuilder::ELF) {}
1681
1682 // Iterative hash function for symbol's name is described in .gdb_index format
1683 // specification. Note that we use one for version 5 to 7 here, it is different
1684 // for version 4.
1685 static uint32_t hash(StringRef Str) {
1686   uint32_t R = 0;
1687   for (uint8_t C : Str)
1688     R = R * 67 + tolower(C) - 113;
1689   return R;
1690 }
1691
1692 static std::vector<std::pair<uint64_t, uint64_t>>
1693 readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1694   std::vector<std::pair<uint64_t, uint64_t>> Ret;
1695   for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1696     Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1697   return Ret;
1698 }
1699
1700 static InputSection *findSection(ArrayRef<InputSectionBase *> Arr,
1701                                  uint64_t Offset) {
1702   for (InputSectionBase *S : Arr)
1703     if (auto *IS = dyn_cast_or_null<InputSection>(S))
1704       if (IS != &InputSection::Discarded && IS->Live &&
1705           Offset >= IS->getOffsetInFile() &&
1706           Offset < IS->getOffsetInFile() + IS->getSize())
1707         return IS;
1708   return nullptr;
1709 }
1710
1711 static std::vector<AddressEntry>
1712 readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1713   std::vector<AddressEntry> Ret;
1714
1715   for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1716     DWARFAddressRangesVector Ranges;
1717     CU->collectAddressRanges(Ranges);
1718
1719     ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
1720     for (DWARFAddressRange &R : Ranges)
1721       if (InputSection *S = findSection(Sections, R.LowPC))
1722         Ret.push_back({S, R.LowPC - S->getOffsetInFile(),
1723                        R.HighPC - S->getOffsetInFile(), CurrentCU});
1724     ++CurrentCU;
1725   }
1726   return Ret;
1727 }
1728
1729 static std::vector<std::pair<StringRef, uint8_t>>
1730 readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1731   StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1732                       Dwarf.getGnuPubTypesSection()};
1733
1734   std::vector<std::pair<StringRef, uint8_t>> Ret;
1735   for (StringRef D : Data) {
1736     DWARFDebugPubTable PubTable(D, IsLE, true);
1737     for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1738       for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1739         Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1740   }
1741   return Ret;
1742 }
1743
1744 class ObjInfoTy : public llvm::LoadedObjectInfo {
1745   uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1746     auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1747     if (S.getFlags() & ELF::SHF_ALLOC)
1748       return S.getOffset();
1749     return 0;
1750   }
1751
1752   std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1753 };
1754
1755 void GdbIndexSection::readDwarf(InputSection *Sec) {
1756   Expected<std::unique_ptr<object::ObjectFile>> Obj =
1757       object::ObjectFile::createObjectFile(Sec->File->MB);
1758   if (!Obj) {
1759     error(toString(Sec->File) + ": error creating DWARF context");
1760     return;
1761   }
1762
1763   ObjInfoTy ObjInfo;
1764   DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
1765
1766   size_t CuId = CompilationUnits.size();
1767   for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1768     CompilationUnits.push_back(P);
1769
1770   for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
1771     AddressArea.push_back(Ent);
1772
1773   std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
1774       readPubNamesAndTypes(Dwarf, Config->IsLE);
1775
1776   for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1777     uint32_t Hash = hash(Pair.first);
1778     size_t Offset = StringPool.add(Pair.first);
1779
1780     bool IsNew;
1781     GdbSymbol *Sym;
1782     std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1783     if (IsNew) {
1784       Sym->CuVectorIndex = CuVectors.size();
1785       CuVectors.push_back({{CuId, Pair.second}});
1786       continue;
1787     }
1788
1789     CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
1790   }
1791 }
1792
1793 void GdbIndexSection::finalizeContents() {
1794   if (Finalized)
1795     return;
1796   Finalized = true;
1797
1798   for (InputSectionBase *S : InputSections)
1799     if (InputSection *IS = dyn_cast<InputSection>(S))
1800       if (IS->OutSec && IS->Name == ".debug_info")
1801         readDwarf(IS);
1802
1803   SymbolTable.finalizeContents();
1804
1805   // GdbIndex header consist from version fields
1806   // and 5 more fields with different kinds of offsets.
1807   CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1808   SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
1809
1810   ConstantPoolOffset =
1811       SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1812
1813   for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1814     CuVectorsOffset.push_back(CuVectorsSize);
1815     CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1816   }
1817   StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1818
1819   StringPool.finalizeInOrder();
1820 }
1821
1822 size_t GdbIndexSection::getSize() const {
1823   const_cast<GdbIndexSection *>(this)->finalizeContents();
1824   return StringPoolOffset + StringPool.getSize();
1825 }
1826
1827 void GdbIndexSection::writeTo(uint8_t *Buf) {
1828   write32le(Buf, 7);                       // Write version.
1829   write32le(Buf + 4, CuListOffset);        // CU list offset.
1830   write32le(Buf + 8, CuTypesOffset);       // Types CU list offset.
1831   write32le(Buf + 12, CuTypesOffset);      // Address area offset.
1832   write32le(Buf + 16, SymTabOffset);       // Symbol table offset.
1833   write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
1834   Buf += 24;
1835
1836   // Write the CU list.
1837   for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
1838     write64le(Buf, CU.first);
1839     write64le(Buf + 8, CU.second);
1840     Buf += 16;
1841   }
1842
1843   // Write the address area.
1844   for (AddressEntry &E : AddressArea) {
1845     uint64_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
1846     write64le(Buf, BaseAddr + E.LowAddress);
1847     write64le(Buf + 8, BaseAddr + E.HighAddress);
1848     write32le(Buf + 16, E.CuIndex);
1849     Buf += 20;
1850   }
1851
1852   // Write the symbol table.
1853   for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1854     GdbSymbol *Sym = SymbolTable.getSymbol(I);
1855     if (Sym) {
1856       size_t NameOffset =
1857           Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1858       size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1859       write32le(Buf, NameOffset);
1860       write32le(Buf + 4, CuVectorOffset);
1861     }
1862     Buf += 8;
1863   }
1864
1865   // Write the CU vectors into the constant pool.
1866   for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1867     write32le(Buf, CuVec.size());
1868     Buf += 4;
1869     for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1870       uint32_t Index = P.first;
1871       uint8_t Flags = P.second;
1872       Index |= Flags << 24;
1873       write32le(Buf, Index);
1874       Buf += 4;
1875     }
1876   }
1877
1878   StringPool.write(Buf);
1879 }
1880
1881 bool GdbIndexSection::empty() const {
1882   return !Out::DebugInfo;
1883 }
1884
1885 template <class ELFT>
1886 EhFrameHeader<ELFT>::EhFrameHeader()
1887     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1888
1889 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
1890 // Each entry of the search table consists of two values,
1891 // the starting PC from where FDEs covers, and the FDE's address.
1892 // It is sorted by PC.
1893 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1894   const endianness E = ELFT::TargetEndianness;
1895
1896   // Sort the FDE list by their PC and uniqueify. Usually there is only
1897   // one FDE for a PC (i.e. function), but if ICF merges two functions
1898   // into one, there can be more than one FDEs pointing to the address.
1899   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1900   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1901   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1902   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1903
1904   Buf[0] = 1;
1905   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1906   Buf[2] = DW_EH_PE_udata4;
1907   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1908   write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
1909   write32<E>(Buf + 8, Fdes.size());
1910   Buf += 12;
1911
1912   uint64_t VA = this->getVA();
1913   for (FdeData &Fde : Fdes) {
1914     write32<E>(Buf, Fde.Pc - VA);
1915     write32<E>(Buf + 4, Fde.FdeVA - VA);
1916     Buf += 8;
1917   }
1918 }
1919
1920 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1921   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1922   return 12 + In<ELFT>::EhFrame->NumFdes * 8;
1923 }
1924
1925 template <class ELFT>
1926 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1927   Fdes.push_back({Pc, FdeVA});
1928 }
1929
1930 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1931   return In<ELFT>::EhFrame->empty();
1932 }
1933
1934 template <class ELFT>
1935 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1936     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1937                        ".gnu.version_d") {}
1938
1939 static StringRef getFileDefName() {
1940   if (!Config->SoName.empty())
1941     return Config->SoName;
1942   return Config->OutputFile;
1943 }
1944
1945 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
1946   FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
1947   for (VersionDefinition &V : Config->VersionDefinitions)
1948     V.NameOff = InX::DynStrTab->addString(V.Name);
1949
1950   this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex;
1951
1952   // sh_info should be set to the number of definitions. This fact is missed in
1953   // documentation, but confirmed by binutils community:
1954   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1955   this->OutSec->Info = getVerDefNum();
1956 }
1957
1958 template <class ELFT>
1959 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1960                                               StringRef Name, size_t NameOff) {
1961   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1962   Verdef->vd_version = 1;
1963   Verdef->vd_cnt = 1;
1964   Verdef->vd_aux = sizeof(Elf_Verdef);
1965   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1966   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1967   Verdef->vd_ndx = Index;
1968   Verdef->vd_hash = hashSysV(Name);
1969
1970   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1971   Verdaux->vda_name = NameOff;
1972   Verdaux->vda_next = 0;
1973 }
1974
1975 template <class ELFT>
1976 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1977   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1978
1979   for (VersionDefinition &V : Config->VersionDefinitions) {
1980     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1981     writeOne(Buf, V.Id, V.Name, V.NameOff);
1982   }
1983
1984   // Need to terminate the last version definition.
1985   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1986   Verdef->vd_next = 0;
1987 }
1988
1989 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1990   return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1991 }
1992
1993 template <class ELFT>
1994 VersionTableSection<ELFT>::VersionTableSection()
1995     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1996                        ".gnu.version") {
1997   this->Entsize = sizeof(Elf_Versym);
1998 }
1999
2000 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
2001   // At the moment of june 2016 GNU docs does not mention that sh_link field
2002   // should be set, but Sun docs do. Also readelf relies on this field.
2003   this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
2004 }
2005
2006 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2007   return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
2008 }
2009
2010 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2011   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2012   for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
2013     OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2014     ++OutVersym;
2015   }
2016 }
2017
2018 template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2019   return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2020 }
2021
2022 template <class ELFT>
2023 VersionNeedSection<ELFT>::VersionNeedSection()
2024     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2025                        ".gnu.version_r") {
2026   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2027   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2028   // First identifiers are reserved by verdef section if it exist.
2029   NextIndex = getVerDefNum() + 1;
2030 }
2031
2032 template <class ELFT>
2033 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2034   auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2035   if (!Ver) {
2036     SS->symbol()->VersionId = VER_NDX_GLOBAL;
2037     return;
2038   }
2039
2040   auto *File = cast<SharedFile<ELFT>>(SS->File);
2041
2042   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2043   // to create one by adding it to our needed list and creating a dynstr entry
2044   // for the soname.
2045   if (File->VerdefMap.empty())
2046     Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
2047   typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
2048   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2049   // prepare to create one by allocating a version identifier and creating a
2050   // dynstr entry for the version name.
2051   if (NV.Index == 0) {
2052     NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2053                                           Ver->getAux()->vda_name);
2054     NV.Index = NextIndex++;
2055   }
2056   SS->symbol()->VersionId = NV.Index;
2057 }
2058
2059 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2060   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2061   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2062   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2063
2064   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2065     // Create an Elf_Verneed for this DSO.
2066     Verneed->vn_version = 1;
2067     Verneed->vn_cnt = P.first->VerdefMap.size();
2068     Verneed->vn_file = P.second;
2069     Verneed->vn_aux =
2070         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2071     Verneed->vn_next = sizeof(Elf_Verneed);
2072     ++Verneed;
2073
2074     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2075     // VerdefMap, which will only contain references to needed version
2076     // definitions. Each Elf_Vernaux is based on the information contained in
2077     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2078     // pointers, but is deterministic because the pointers refer to Elf_Verdef
2079     // data structures within a single input file.
2080     for (auto &NV : P.first->VerdefMap) {
2081       Vernaux->vna_hash = NV.first->vd_hash;
2082       Vernaux->vna_flags = 0;
2083       Vernaux->vna_other = NV.second.Index;
2084       Vernaux->vna_name = NV.second.StrTab;
2085       Vernaux->vna_next = sizeof(Elf_Vernaux);
2086       ++Vernaux;
2087     }
2088
2089     Vernaux[-1].vna_next = 0;
2090   }
2091   Verneed[-1].vn_next = 0;
2092 }
2093
2094 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2095   this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex;
2096   this->OutSec->Info = Needed.size();
2097 }
2098
2099 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2100   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2101   for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2102     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2103   return Size;
2104 }
2105
2106 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2107   return getNeedNum() == 0;
2108 }
2109
2110 MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
2111                                              uint64_t Flags, uint32_t Alignment)
2112     : SyntheticSection(Flags, Type, Alignment, Name),
2113       Builder(StringTableBuilder::RAW, Alignment) {}
2114
2115 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2116   assert(!Finalized);
2117   MS->MergeSec = this;
2118   Sections.push_back(MS);
2119 }
2120
2121 void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2122
2123 bool MergeSyntheticSection::shouldTailMerge() const {
2124   return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2125 }
2126
2127 void MergeSyntheticSection::finalizeTailMerge() {
2128   // Add all string pieces to the string table builder to create section
2129   // contents.
2130   for (MergeInputSection *Sec : Sections)
2131     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2132       if (Sec->Pieces[I].Live)
2133         Builder.add(Sec->getData(I));
2134
2135   // Fix the string table content. After this, the contents will never change.
2136   Builder.finalize();
2137
2138   // finalize() fixed tail-optimized strings, so we can now get
2139   // offsets of strings. Get an offset for each string and save it
2140   // to a corresponding StringPiece for easy access.
2141   for (MergeInputSection *Sec : Sections)
2142     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2143       if (Sec->Pieces[I].Live)
2144         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2145 }
2146
2147 void MergeSyntheticSection::finalizeNoTailMerge() {
2148   // Add all string pieces to the string table builder to create section
2149   // contents. Because we are not tail-optimizing, offsets of strings are
2150   // fixed when they are added to the builder (string table builder contains
2151   // a hash table from strings to offsets).
2152   for (MergeInputSection *Sec : Sections)
2153     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2154       if (Sec->Pieces[I].Live)
2155         Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2156
2157   Builder.finalizeInOrder();
2158 }
2159
2160 void MergeSyntheticSection::finalizeContents() {
2161   if (Finalized)
2162     return;
2163   Finalized = true;
2164   if (shouldTailMerge())
2165     finalizeTailMerge();
2166   else
2167     finalizeNoTailMerge();
2168 }
2169
2170 size_t MergeSyntheticSection::getSize() const {
2171   // We should finalize string builder to know the size.
2172   const_cast<MergeSyntheticSection *>(this)->finalizeContents();
2173   return Builder.getSize();
2174 }
2175
2176 MipsRldMapSection::MipsRldMapSection()
2177     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2178                        ".rld_map") {}
2179
2180 void MipsRldMapSection::writeTo(uint8_t *Buf) {
2181   // Apply filler from linker script.
2182   Optional<uint32_t> Fill = Script->getFiller(this->OutSec);
2183   if (!Fill || *Fill == 0)
2184     return;
2185
2186   uint64_t Filler = *Fill;
2187   Filler = (Filler << 32) | Filler;
2188   memcpy(Buf, &Filler, getSize());
2189 }
2190
2191 ARMExidxSentinelSection::ARMExidxSentinelSection()
2192     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2193                        Config->Wordsize, ".ARM.exidx") {}
2194
2195 // Write a terminating sentinel entry to the end of the .ARM.exidx table.
2196 // This section will have been sorted last in the .ARM.exidx table.
2197 // This table entry will have the form:
2198 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
2199 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
2200   // Get the InputSection before us, we are by definition last
2201   auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
2202   InputSection *LE = *(++RI);
2203   InputSection *LC = cast<InputSection>(LE->getLinkOrderDep());
2204   uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
2205   uint64_t P = this->getVA();
2206   Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2207   write32le(Buf + 4, 0x1);
2208 }
2209
2210 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
2211     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
2212                        Config->Wordsize, ".text.thunk") {
2213   this->OutSec = OS;
2214   this->OutSecOff = Off;
2215 }
2216
2217 void ThunkSection::addThunk(Thunk *T) {
2218   uint64_t Off = alignTo(Size, T->alignment);
2219   T->Offset = Off;
2220   Thunks.push_back(T);
2221   T->addSymbols(*this);
2222   Size = Off + T->size();
2223 }
2224
2225 void ThunkSection::writeTo(uint8_t *Buf) {
2226   for (const Thunk *T : Thunks)
2227     T->writeTo(Buf + T->Offset, *this);
2228 }
2229
2230 InputSection *ThunkSection::getTargetInputSection() const {
2231   const Thunk *T = Thunks.front();
2232   return T->getTargetInputSection();
2233 }
2234
2235 InputSection *InX::ARMAttributes;
2236 BssSection *InX::Bss;
2237 BssSection *InX::BssRelRo;
2238 BuildIdSection *InX::BuildId;
2239 InputSection *InX::Common;
2240 SyntheticSection *InX::Dynamic;
2241 StringTableSection *InX::DynStrTab;
2242 SymbolTableBaseSection *InX::DynSymTab;
2243 InputSection *InX::Interp;
2244 GdbIndexSection *InX::GdbIndex;
2245 GotBaseSection *InX::Got;
2246 GotPltSection *InX::GotPlt;
2247 GnuHashTableSection *InX::GnuHashTab;
2248 IgotPltSection *InX::IgotPlt;
2249 MipsGotSection *InX::MipsGot;
2250 MipsRldMapSection *InX::MipsRldMap;
2251 PltSection *InX::Plt;
2252 PltSection *InX::Iplt;
2253 StringTableSection *InX::ShStrTab;
2254 StringTableSection *InX::StrTab;
2255 SymbolTableBaseSection *InX::SymTab;
2256
2257 template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2258 template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2259 template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2260 template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2261
2262 template InputSection *elf::createCommonSection<ELF32LE>();
2263 template InputSection *elf::createCommonSection<ELF32BE>();
2264 template InputSection *elf::createCommonSection<ELF64LE>();
2265 template InputSection *elf::createCommonSection<ELF64BE>();
2266
2267 template MergeInputSection *elf::createCommentSection<ELF32LE>();
2268 template MergeInputSection *elf::createCommentSection<ELF32BE>();
2269 template MergeInputSection *elf::createCommentSection<ELF64LE>();
2270 template MergeInputSection *elf::createCommentSection<ELF64BE>();
2271
2272 template class elf::MipsAbiFlagsSection<ELF32LE>;
2273 template class elf::MipsAbiFlagsSection<ELF32BE>;
2274 template class elf::MipsAbiFlagsSection<ELF64LE>;
2275 template class elf::MipsAbiFlagsSection<ELF64BE>;
2276
2277 template class elf::MipsOptionsSection<ELF32LE>;
2278 template class elf::MipsOptionsSection<ELF32BE>;
2279 template class elf::MipsOptionsSection<ELF64LE>;
2280 template class elf::MipsOptionsSection<ELF64BE>;
2281
2282 template class elf::MipsReginfoSection<ELF32LE>;
2283 template class elf::MipsReginfoSection<ELF32BE>;
2284 template class elf::MipsReginfoSection<ELF64LE>;
2285 template class elf::MipsReginfoSection<ELF64BE>;
2286
2287 template class elf::GotSection<ELF32LE>;
2288 template class elf::GotSection<ELF32BE>;
2289 template class elf::GotSection<ELF64LE>;
2290 template class elf::GotSection<ELF64BE>;
2291
2292 template class elf::DynamicSection<ELF32LE>;
2293 template class elf::DynamicSection<ELF32BE>;
2294 template class elf::DynamicSection<ELF64LE>;
2295 template class elf::DynamicSection<ELF64BE>;
2296
2297 template class elf::RelocationSection<ELF32LE>;
2298 template class elf::RelocationSection<ELF32BE>;
2299 template class elf::RelocationSection<ELF64LE>;
2300 template class elf::RelocationSection<ELF64BE>;
2301
2302 template class elf::SymbolTableSection<ELF32LE>;
2303 template class elf::SymbolTableSection<ELF32BE>;
2304 template class elf::SymbolTableSection<ELF64LE>;
2305 template class elf::SymbolTableSection<ELF64BE>;
2306
2307 template class elf::HashTableSection<ELF32LE>;
2308 template class elf::HashTableSection<ELF32BE>;
2309 template class elf::HashTableSection<ELF64LE>;
2310 template class elf::HashTableSection<ELF64BE>;
2311
2312 template class elf::EhFrameHeader<ELF32LE>;
2313 template class elf::EhFrameHeader<ELF32BE>;
2314 template class elf::EhFrameHeader<ELF64LE>;
2315 template class elf::EhFrameHeader<ELF64BE>;
2316
2317 template class elf::VersionTableSection<ELF32LE>;
2318 template class elf::VersionTableSection<ELF32BE>;
2319 template class elf::VersionTableSection<ELF64LE>;
2320 template class elf::VersionTableSection<ELF64BE>;
2321
2322 template class elf::VersionNeedSection<ELF32LE>;
2323 template class elf::VersionNeedSection<ELF32BE>;
2324 template class elf::VersionNeedSection<ELF64LE>;
2325 template class elf::VersionNeedSection<ELF64BE>;
2326
2327 template class elf::VersionDefinitionSection<ELF32LE>;
2328 template class elf::VersionDefinitionSection<ELF32BE>;
2329 template class elf::VersionDefinitionSection<ELF64LE>;
2330 template class elf::VersionDefinitionSection<ELF64BE>;
2331
2332 template class elf::EhFrameSection<ELF32LE>;
2333 template class elf::EhFrameSection<ELF32BE>;
2334 template class elf::EhFrameSection<ELF64LE>;
2335 template class elf::EhFrameSection<ELF64BE>;