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