1 //===- SyntheticSections.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains linker-synthesized sections. Currently,
10 // synthetic sections are created either output sections or input sections,
11 // but we are rewriting code so that all synthetic sections are created as
12 // input sections.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "SyntheticSections.h"
17 #include "Config.h"
18 #include "InputFiles.h"
19 #include "LinkerScript.h"
20 #include "OutputSections.h"
21 #include "SymbolTable.h"
22 #include "Symbols.h"
23 #include "Target.h"
24 #include "Writer.h"
25 #include "lld/Common/ErrorHandler.h"
26 #include "lld/Common/Memory.h"
27 #include "lld/Common/Strings.h"
28 #include "lld/Common/Threads.h"
29 #include "lld/Common/Version.h"
30 #include "llvm/ADT/SetOperations.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
34 #include "llvm/Object/ELFObjectFile.h"
35 #include "llvm/Support/Compression.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/LEB128.h"
38 #include "llvm/Support/MD5.h"
39 #include <cstdlib>
40 #include <thread>
41 
42 using namespace llvm;
43 using namespace llvm::dwarf;
44 using namespace llvm::ELF;
45 using namespace llvm::object;
46 using namespace llvm::support;
47 
48 using namespace lld;
49 using namespace lld::elf;
50 
51 using llvm::support::endian::read32le;
52 using llvm::support::endian::write32le;
53 using llvm::support::endian::write64le;
54 
55 constexpr size_t MergeNoTailSection::NumShards;
56 
57 static uint64_t readUint(uint8_t *Buf) {
58   return Config->Is64 ? read64(Buf) : read32(Buf);
59 }
60 
61 static void writeUint(uint8_t *Buf, uint64_t Val) {
62   if (Config->Is64)
63     write64(Buf, Val);
64   else
65     write32(Buf, Val);
66 }
67 
68 // Returns an LLD version string.
69 static ArrayRef<uint8_t> getVersion() {
70   // Check LLD_VERSION first for ease of testing.
71   // You can get consistent output by using the environment variable.
72   // This is only for testing.
73   StringRef S = getenv("LLD_VERSION");
74   if (S.empty())
75     S = Saver.save(Twine("Linker: ") + getLLDVersion());
76 
77   // +1 to include the terminating '\0'.
78   return {(const uint8_t *)S.data(), S.size() + 1};
79 }
80 
81 // Creates a .comment section containing LLD version info.
82 // With this feature, you can identify LLD-generated binaries easily
83 // by "readelf --string-dump .comment <file>".
84 // The returned object is a mergeable string section.
85 MergeInputSection *elf::createCommentSection() {
86   return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
87                                  getVersion(), ".comment");
88 }
89 
90 // .MIPS.abiflags section.
91 template <class ELFT>
92 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
93     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
94       Flags(Flags) {
95   this->Entsize = sizeof(Elf_Mips_ABIFlags);
96 }
97 
98 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
99   memcpy(Buf, &Flags, sizeof(Flags));
100 }
101 
102 template <class ELFT>
103 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
104   Elf_Mips_ABIFlags Flags = {};
105   bool Create = false;
106 
107   for (InputSectionBase *Sec : InputSections) {
108     if (Sec->Type != SHT_MIPS_ABIFLAGS)
109       continue;
110     Sec->markDead();
111     Create = true;
112 
113     std::string Filename = toString(Sec->File);
114     const size_t Size = Sec->data().size();
115     // Older version of BFD (such as the default FreeBSD linker) concatenate
116     // .MIPS.abiflags instead of merging. To allow for this case (or potential
117     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
118     if (Size < sizeof(Elf_Mips_ABIFlags)) {
119       error(Filename + ": invalid size of .MIPS.abiflags section: got " +
120             Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
121       return nullptr;
122     }
123     auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
124     if (S->version != 0) {
125       error(Filename + ": unexpected .MIPS.abiflags version " +
126             Twine(S->version));
127       return nullptr;
128     }
129 
130     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
131     // select the highest number of ISA/Rev/Ext.
132     Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
133     Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
134     Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
135     Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
136     Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
137     Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
138     Flags.ases |= S->ases;
139     Flags.flags1 |= S->flags1;
140     Flags.flags2 |= S->flags2;
141     Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
142   };
143 
144   if (Create)
145     return make<MipsAbiFlagsSection<ELFT>>(Flags);
146   return nullptr;
147 }
148 
149 // .MIPS.options section.
150 template <class ELFT>
151 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
152     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
153       Reginfo(Reginfo) {
154   this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
155 }
156 
157 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
158   auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
159   Options->kind = ODK_REGINFO;
160   Options->size = getSize();
161 
162   if (!Config->Relocatable)
163     Reginfo.ri_gp_value = In.MipsGot->getGp();
164   memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
165 }
166 
167 template <class ELFT>
168 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
169   // N64 ABI only.
170   if (!ELFT::Is64Bits)
171     return nullptr;
172 
173   std::vector<InputSectionBase *> Sections;
174   for (InputSectionBase *Sec : InputSections)
175     if (Sec->Type == SHT_MIPS_OPTIONS)
176       Sections.push_back(Sec);
177 
178   if (Sections.empty())
179     return nullptr;
180 
181   Elf_Mips_RegInfo Reginfo = {};
182   for (InputSectionBase *Sec : Sections) {
183     Sec->markDead();
184 
185     std::string Filename = toString(Sec->File);
186     ArrayRef<uint8_t> D = Sec->data();
187 
188     while (!D.empty()) {
189       if (D.size() < sizeof(Elf_Mips_Options)) {
190         error(Filename + ": invalid size of .MIPS.options section");
191         break;
192       }
193 
194       auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
195       if (Opt->kind == ODK_REGINFO) {
196         Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
197         Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
198         break;
199       }
200 
201       if (!Opt->size)
202         fatal(Filename + ": zero option descriptor size");
203       D = D.slice(Opt->size);
204     }
205   };
206 
207   return make<MipsOptionsSection<ELFT>>(Reginfo);
208 }
209 
210 // MIPS .reginfo section.
211 template <class ELFT>
212 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
213     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
214       Reginfo(Reginfo) {
215   this->Entsize = sizeof(Elf_Mips_RegInfo);
216 }
217 
218 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
219   if (!Config->Relocatable)
220     Reginfo.ri_gp_value = In.MipsGot->getGp();
221   memcpy(Buf, &Reginfo, sizeof(Reginfo));
222 }
223 
224 template <class ELFT>
225 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
226   // Section should be alive for O32 and N32 ABIs only.
227   if (ELFT::Is64Bits)
228     return nullptr;
229 
230   std::vector<InputSectionBase *> Sections;
231   for (InputSectionBase *Sec : InputSections)
232     if (Sec->Type == SHT_MIPS_REGINFO)
233       Sections.push_back(Sec);
234 
235   if (Sections.empty())
236     return nullptr;
237 
238   Elf_Mips_RegInfo Reginfo = {};
239   for (InputSectionBase *Sec : Sections) {
240     Sec->markDead();
241 
242     if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
243       error(toString(Sec->File) + ": invalid size of .reginfo section");
244       return nullptr;
245     }
246 
247     auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
248     Reginfo.ri_gprmask |= R->ri_gprmask;
249     Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
250   };
251 
252   return make<MipsReginfoSection<ELFT>>(Reginfo);
253 }
254 
255 InputSection *elf::createInterpSection() {
256   // StringSaver guarantees that the returned string ends with '\0'.
257   StringRef S = Saver.save(Config->DynamicLinker);
258   ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
259 
260   auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
261                                  ".interp");
262   Sec->markLive();
263   return Sec;
264 }
265 
266 Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
267                                 uint64_t Size, InputSectionBase &Section) {
268   auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
269                           Value, Size, &Section);
270   if (In.SymTab)
271     In.SymTab->addSymbol(S);
272   return S;
273 }
274 
275 static size_t getHashSize() {
276   switch (Config->BuildId) {
277   case BuildIdKind::Fast:
278     return 8;
279   case BuildIdKind::Md5:
280   case BuildIdKind::Uuid:
281     return 16;
282   case BuildIdKind::Sha1:
283     return 20;
284   case BuildIdKind::Hexstring:
285     return Config->BuildIdVector.size();
286   default:
287     llvm_unreachable("unknown BuildIdKind");
288   }
289 }
290 
291 // This class represents a linker-synthesized .note.gnu.property section.
292 //
293 // In x86 and AArch64, object files may contain feature flags indicating the
294 // features that they have used. The flags are stored in a .note.gnu.property
295 // section.
296 //
297 // lld reads the sections from input files and merges them by computing AND of
298 // the flags. The result is written as a new .note.gnu.property section.
299 //
300 // If the flag is zero (which indicates that the intersection of the feature
301 // sets is empty, or some input files didn't have .note.gnu.property sections),
302 // we don't create this section.
303 GnuPropertySection::GnuPropertySection()
304     : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE, 4,
305                        ".note.gnu.property") {}
306 
307 void GnuPropertySection::writeTo(uint8_t *Buf) {
308   uint32_t FeatureAndType = Config->EMachine == EM_AARCH64
309                                 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
310                                 : GNU_PROPERTY_X86_FEATURE_1_AND;
311 
312   write32(Buf, 4);                                   // Name size
313   write32(Buf + 4, Config->Is64 ? 16 : 12);          // Content size
314   write32(Buf + 8, NT_GNU_PROPERTY_TYPE_0);          // Type
315   memcpy(Buf + 12, "GNU", 4);                        // Name string
316   write32(Buf + 16, FeatureAndType);                 // Feature type
317   write32(Buf + 20, 4);                              // Feature size
318   write32(Buf + 24, Config->AndFeatures);            // Feature flags
319   if (Config->Is64)
320     write32(Buf + 28, 0); // Padding
321 }
322 
323 size_t GnuPropertySection::getSize() const { return Config->Is64 ? 32 : 28; }
324 
325 BuildIdSection::BuildIdSection()
326     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
327       HashSize(getHashSize()) {}
328 
329 void BuildIdSection::writeTo(uint8_t *Buf) {
330   write32(Buf, 4);                      // Name size
331   write32(Buf + 4, HashSize);           // Content size
332   write32(Buf + 8, NT_GNU_BUILD_ID);    // Type
333   memcpy(Buf + 12, "GNU", 4);           // Name string
334   HashBuf = Buf + 16;
335 }
336 
337 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
338   assert(Buf.size() == HashSize);
339   memcpy(HashBuf, Buf.data(), HashSize);
340 }
341 
342 BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
343     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
344   this->Bss = true;
345   this->Size = Size;
346 }
347 
348 EhFrameSection::EhFrameSection()
349     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
350 
351 // Search for an existing CIE record or create a new one.
352 // CIE records from input object files are uniquified by their contents
353 // and where their relocations point to.
354 template <class ELFT, class RelTy>
355 CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
356   Symbol *Personality = nullptr;
357   unsigned FirstRelI = Cie.FirstRelocation;
358   if (FirstRelI != (unsigned)-1)
359     Personality =
360         &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
361 
362   // Search for an existing CIE by CIE contents/relocation target pair.
363   CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
364 
365   // If not found, create a new one.
366   if (!Rec) {
367     Rec = make<CieRecord>();
368     Rec->Cie = &Cie;
369     CieRecords.push_back(Rec);
370   }
371   return Rec;
372 }
373 
374 // There is one FDE per function. Returns true if a given FDE
375 // points to a live function.
376 template <class ELFT, class RelTy>
377 bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
378   auto *Sec = cast<EhInputSection>(Fde.Sec);
379   unsigned FirstRelI = Fde.FirstRelocation;
380 
381   // An FDE should point to some function because FDEs are to describe
382   // functions. That's however not always the case due to an issue of
383   // ld.gold with -r. ld.gold may discard only functions and leave their
384   // corresponding FDEs, which results in creating bad .eh_frame sections.
385   // To deal with that, we ignore such FDEs.
386   if (FirstRelI == (unsigned)-1)
387     return false;
388 
389   const RelTy &Rel = Rels[FirstRelI];
390   Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
391 
392   // FDEs for garbage-collected or merged-by-ICF sections, or sections in
393   // another partition, are dead.
394   if (auto *D = dyn_cast<Defined>(&B))
395     if (SectionBase *Sec = D->Section)
396       return Sec->Partition == Partition;
397   return false;
398 }
399 
400 // .eh_frame is a sequence of CIE or FDE records. In general, there
401 // is one CIE record per input object file which is followed by
402 // a list of FDEs. This function searches an existing CIE or create a new
403 // one and associates FDEs to the CIE.
404 template <class ELFT, class RelTy>
405 void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
406   OffsetToCie.clear();
407   for (EhSectionPiece &Piece : Sec->Pieces) {
408     // The empty record is the end marker.
409     if (Piece.Size == 4)
410       return;
411 
412     size_t Offset = Piece.InputOff;
413     uint32_t ID = read32(Piece.data().data() + 4);
414     if (ID == 0) {
415       OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
416       continue;
417     }
418 
419     uint32_t CieOffset = Offset + 4 - ID;
420     CieRecord *Rec = OffsetToCie[CieOffset];
421     if (!Rec)
422       fatal(toString(Sec) + ": invalid CIE reference");
423 
424     if (!isFdeLive<ELFT>(Piece, Rels))
425       continue;
426     Rec->Fdes.push_back(&Piece);
427     NumFdes++;
428   }
429 }
430 
431 template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
432   auto *Sec = cast<EhInputSection>(C);
433   Sec->Parent = this;
434 
435   Alignment = std::max(Alignment, Sec->Alignment);
436   Sections.push_back(Sec);
437 
438   for (auto *DS : Sec->DependentSections)
439     DependentSections.push_back(DS);
440 
441   if (Sec->Pieces.empty())
442     return;
443 
444   if (Sec->AreRelocsRela)
445     addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
446   else
447     addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
448 }
449 
450 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
451   memcpy(Buf, D.data(), D.size());
452 
453   size_t Aligned = alignTo(D.size(), Config->Wordsize);
454 
455   // Zero-clear trailing padding if it exists.
456   memset(Buf + D.size(), 0, Aligned - D.size());
457 
458   // Fix the size field. -4 since size does not include the size field itself.
459   write32(Buf, Aligned - 4);
460 }
461 
462 void EhFrameSection::finalizeContents() {
463   assert(!this->Size); // Not finalized.
464   size_t Off = 0;
465   for (CieRecord *Rec : CieRecords) {
466     Rec->Cie->OutputOff = Off;
467     Off += alignTo(Rec->Cie->Size, Config->Wordsize);
468 
469     for (EhSectionPiece *Fde : Rec->Fdes) {
470       Fde->OutputOff = Off;
471       Off += alignTo(Fde->Size, Config->Wordsize);
472     }
473   }
474 
475   // The LSB standard does not allow a .eh_frame section with zero
476   // Call Frame Information records. glibc unwind-dw2-fde.c
477   // classify_object_over_fdes expects there is a CIE record length 0 as a
478   // terminator. Thus we add one unconditionally.
479   Off += 4;
480 
481   this->Size = Off;
482 }
483 
484 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
485 // to get an FDE from an address to which FDE is applied. This function
486 // returns a list of such pairs.
487 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
488   uint8_t *Buf = Out::BufferStart + getParent()->Offset + OutSecOff;
489   std::vector<FdeData> Ret;
490 
491   uint64_t VA = getPartition().EhFrameHdr->getVA();
492   for (CieRecord *Rec : CieRecords) {
493     uint8_t Enc = getFdeEncoding(Rec->Cie);
494     for (EhSectionPiece *Fde : Rec->Fdes) {
495       uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
496       uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
497       if (!isInt<32>(Pc - VA))
498         fatal(toString(Fde->Sec) + ": PC offset is too large: 0x" +
499               Twine::utohexstr(Pc - VA));
500       Ret.push_back({uint32_t(Pc - VA), uint32_t(FdeVA - VA)});
501     }
502   }
503 
504   // Sort the FDE list by their PC and uniqueify. Usually there is only
505   // one FDE for a PC (i.e. function), but if ICF merges two functions
506   // into one, there can be more than one FDEs pointing to the address.
507   auto Less = [](const FdeData &A, const FdeData &B) {
508     return A.PcRel < B.PcRel;
509   };
510   llvm::stable_sort(Ret, Less);
511   auto Eq = [](const FdeData &A, const FdeData &B) {
512     return A.PcRel == B.PcRel;
513   };
514   Ret.erase(std::unique(Ret.begin(), Ret.end(), Eq), Ret.end());
515 
516   return Ret;
517 }
518 
519 static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
520   switch (Size) {
521   case DW_EH_PE_udata2:
522     return read16(Buf);
523   case DW_EH_PE_sdata2:
524     return (int16_t)read16(Buf);
525   case DW_EH_PE_udata4:
526     return read32(Buf);
527   case DW_EH_PE_sdata4:
528     return (int32_t)read32(Buf);
529   case DW_EH_PE_udata8:
530   case DW_EH_PE_sdata8:
531     return read64(Buf);
532   case DW_EH_PE_absptr:
533     return readUint(Buf);
534   }
535   fatal("unknown FDE size encoding");
536 }
537 
538 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
539 // We need it to create .eh_frame_hdr section.
540 uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
541                                   uint8_t Enc) const {
542   // The starting address to which this FDE applies is
543   // stored at FDE + 8 byte.
544   size_t Off = FdeOff + 8;
545   uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0xf);
546   if ((Enc & 0x70) == DW_EH_PE_absptr)
547     return Addr;
548   if ((Enc & 0x70) == DW_EH_PE_pcrel)
549     return Addr + getParent()->Addr + Off;
550   fatal("unknown FDE size relative encoding");
551 }
552 
553 void EhFrameSection::writeTo(uint8_t *Buf) {
554   // Write CIE and FDE records.
555   for (CieRecord *Rec : CieRecords) {
556     size_t CieOffset = Rec->Cie->OutputOff;
557     writeCieFde(Buf + CieOffset, Rec->Cie->data());
558 
559     for (EhSectionPiece *Fde : Rec->Fdes) {
560       size_t Off = Fde->OutputOff;
561       writeCieFde(Buf + Off, Fde->data());
562 
563       // FDE's second word should have the offset to an associated CIE.
564       // Write it.
565       write32(Buf + Off + 4, Off + 4 - CieOffset);
566     }
567   }
568 
569   // Apply relocations. .eh_frame section contents are not contiguous
570   // in the output buffer, but relocateAlloc() still works because
571   // getOffset() takes care of discontiguous section pieces.
572   for (EhInputSection *S : Sections)
573     S->relocateAlloc(Buf, nullptr);
574 
575   if (getPartition().EhFrameHdr && getPartition().EhFrameHdr->getParent())
576     getPartition().EhFrameHdr->write();
577 }
578 
579 GotSection::GotSection()
580     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
581                        ".got") {
582   // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the
583   // .got. If there are no references to .TOC. in the symbol table,
584   // ElfSym::GlobalOffsetTable will not be defined and we won't need to save
585   // .TOC. in the .got. When it is defined, we increase NumEntries by the number
586   // of entries used to emit ElfSym::GlobalOffsetTable.
587   if (ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt)
588     NumEntries += Target->GotHeaderEntriesNum;
589 }
590 
591 void GotSection::addEntry(Symbol &Sym) {
592   Sym.GotIndex = NumEntries;
593   ++NumEntries;
594 }
595 
596 bool GotSection::addDynTlsEntry(Symbol &Sym) {
597   if (Sym.GlobalDynIndex != -1U)
598     return false;
599   Sym.GlobalDynIndex = NumEntries;
600   // Global Dynamic TLS entries take two GOT slots.
601   NumEntries += 2;
602   return true;
603 }
604 
605 // Reserves TLS entries for a TLS module ID and a TLS block offset.
606 // In total it takes two GOT slots.
607 bool GotSection::addTlsIndex() {
608   if (TlsIndexOff != uint32_t(-1))
609     return false;
610   TlsIndexOff = NumEntries * Config->Wordsize;
611   NumEntries += 2;
612   return true;
613 }
614 
615 uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
616   return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
617 }
618 
619 uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
620   return B.GlobalDynIndex * Config->Wordsize;
621 }
622 
623 void GotSection::finalizeContents() {
624   Size = NumEntries * Config->Wordsize;
625 }
626 
627 bool GotSection::isNeeded() const {
628   // We need to emit a GOT even if it's empty if there's a relocation that is
629   // relative to GOT(such as GOTOFFREL).
630   return NumEntries || HasGotOffRel;
631 }
632 
633 void GotSection::writeTo(uint8_t *Buf) {
634   // Buf points to the start of this section's buffer,
635   // whereas InputSectionBase::relocateAlloc() expects its argument
636   // to point to the start of the output section.
637   Target->writeGotHeader(Buf);
638   relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
639 }
640 
641 static uint64_t getMipsPageAddr(uint64_t Addr) {
642   return (Addr + 0x8000) & ~0xffff;
643 }
644 
645 static uint64_t getMipsPageCount(uint64_t Size) {
646   return (Size + 0xfffe) / 0xffff + 1;
647 }
648 
649 MipsGotSection::MipsGotSection()
650     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
651                        ".got") {}
652 
653 void MipsGotSection::addEntry(InputFile &File, Symbol &Sym, int64_t Addend,
654                               RelExpr Expr) {
655   FileGot &G = getGot(File);
656   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
657     if (const OutputSection *OS = Sym.getOutputSection())
658       G.PagesMap.insert({OS, {}});
659     else
660       G.Local16.insert({{nullptr, getMipsPageAddr(Sym.getVA(Addend))}, 0});
661   } else if (Sym.isTls())
662     G.Tls.insert({&Sym, 0});
663   else if (Sym.IsPreemptible && Expr == R_ABS)
664     G.Relocs.insert({&Sym, 0});
665   else if (Sym.IsPreemptible)
666     G.Global.insert({&Sym, 0});
667   else if (Expr == R_MIPS_GOT_OFF32)
668     G.Local32.insert({{&Sym, Addend}, 0});
669   else
670     G.Local16.insert({{&Sym, Addend}, 0});
671 }
672 
673 void MipsGotSection::addDynTlsEntry(InputFile &File, Symbol &Sym) {
674   getGot(File).DynTlsSymbols.insert({&Sym, 0});
675 }
676 
677 void MipsGotSection::addTlsIndex(InputFile &File) {
678   getGot(File).DynTlsSymbols.insert({nullptr, 0});
679 }
680 
681 size_t MipsGotSection::FileGot::getEntriesNum() const {
682   return getPageEntriesNum() + Local16.size() + Global.size() + Relocs.size() +
683          Tls.size() + DynTlsSymbols.size() * 2;
684 }
685 
686 size_t MipsGotSection::FileGot::getPageEntriesNum() const {
687   size_t Num = 0;
688   for (const std::pair<const OutputSection *, FileGot::PageBlock> &P : PagesMap)
689     Num += P.second.Count;
690   return Num;
691 }
692 
693 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
694   size_t Count = getPageEntriesNum() + Local16.size() + Global.size();
695   // If there are relocation-only entries in the GOT, TLS entries
696   // are allocated after them. TLS entries should be addressable
697   // by 16-bit index so count both reloc-only and TLS entries.
698   if (!Tls.empty() || !DynTlsSymbols.empty())
699     Count += Relocs.size() + Tls.size() + DynTlsSymbols.size() * 2;
700   return Count;
701 }
702 
703 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &F) {
704   if (!F.MipsGotIndex.hasValue()) {
705     Gots.emplace_back();
706     Gots.back().File = &F;
707     F.MipsGotIndex = Gots.size() - 1;
708   }
709   return Gots[*F.MipsGotIndex];
710 }
711 
712 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *F,
713                                             const Symbol &Sym,
714                                             int64_t Addend) const {
715   const FileGot &G = Gots[*F->MipsGotIndex];
716   uint64_t Index = 0;
717   if (const OutputSection *OutSec = Sym.getOutputSection()) {
718     uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
719     uint64_t SymAddr = getMipsPageAddr(Sym.getVA(Addend));
720     Index = G.PagesMap.lookup(OutSec).FirstIndex + (SymAddr - SecAddr) / 0xffff;
721   } else {
722     Index = G.Local16.lookup({nullptr, getMipsPageAddr(Sym.getVA(Addend))});
723   }
724   return Index * Config->Wordsize;
725 }
726 
727 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *F, const Symbol &S,
728                                            int64_t Addend) const {
729   const FileGot &G = Gots[*F->MipsGotIndex];
730   Symbol *Sym = const_cast<Symbol *>(&S);
731   if (Sym->isTls())
732     return G.Tls.lookup(Sym) * Config->Wordsize;
733   if (Sym->IsPreemptible)
734     return G.Global.lookup(Sym) * Config->Wordsize;
735   return G.Local16.lookup({Sym, Addend}) * Config->Wordsize;
736 }
737 
738 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *F) const {
739   const FileGot &G = Gots[*F->MipsGotIndex];
740   return G.DynTlsSymbols.lookup(nullptr) * Config->Wordsize;
741 }
742 
743 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *F,
744                                             const Symbol &S) const {
745   const FileGot &G = Gots[*F->MipsGotIndex];
746   Symbol *Sym = const_cast<Symbol *>(&S);
747   return G.DynTlsSymbols.lookup(Sym) * Config->Wordsize;
748 }
749 
750 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
751   if (Gots.empty())
752     return nullptr;
753   const FileGot &PrimGot = Gots.front();
754   if (!PrimGot.Global.empty())
755     return PrimGot.Global.front().first;
756   if (!PrimGot.Relocs.empty())
757     return PrimGot.Relocs.front().first;
758   return nullptr;
759 }
760 
761 unsigned MipsGotSection::getLocalEntriesNum() const {
762   if (Gots.empty())
763     return HeaderEntriesNum;
764   return HeaderEntriesNum + Gots.front().getPageEntriesNum() +
765          Gots.front().Local16.size();
766 }
767 
768 bool MipsGotSection::tryMergeGots(FileGot &Dst, FileGot &Src, bool IsPrimary) {
769   FileGot Tmp = Dst;
770   set_union(Tmp.PagesMap, Src.PagesMap);
771   set_union(Tmp.Local16, Src.Local16);
772   set_union(Tmp.Global, Src.Global);
773   set_union(Tmp.Relocs, Src.Relocs);
774   set_union(Tmp.Tls, Src.Tls);
775   set_union(Tmp.DynTlsSymbols, Src.DynTlsSymbols);
776 
777   size_t Count = IsPrimary ? HeaderEntriesNum : 0;
778   Count += Tmp.getIndexedEntriesNum();
779 
780   if (Count * Config->Wordsize > Config->MipsGotSize)
781     return false;
782 
783   std::swap(Tmp, Dst);
784   return true;
785 }
786 
787 void MipsGotSection::finalizeContents() { updateAllocSize(); }
788 
789 bool MipsGotSection::updateAllocSize() {
790   Size = HeaderEntriesNum * Config->Wordsize;
791   for (const FileGot &G : Gots)
792     Size += G.getEntriesNum() * Config->Wordsize;
793   return false;
794 }
795 
796 void MipsGotSection::build() {
797   if (Gots.empty())
798     return;
799 
800   std::vector<FileGot> MergedGots(1);
801 
802   // For each GOT move non-preemptible symbols from the `Global`
803   // to `Local16` list. Preemptible symbol might become non-preemptible
804   // one if, for example, it gets a related copy relocation.
805   for (FileGot &Got : Gots) {
806     for (auto &P: Got.Global)
807       if (!P.first->IsPreemptible)
808         Got.Local16.insert({{P.first, 0}, 0});
809     Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
810       return !P.first->IsPreemptible;
811     });
812   }
813 
814   // For each GOT remove "reloc-only" entry if there is "global"
815   // entry for the same symbol. And add local entries which indexed
816   // using 32-bit value at the end of 16-bit entries.
817   for (FileGot &Got : Gots) {
818     Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
819       return Got.Global.count(P.first);
820     });
821     set_union(Got.Local16, Got.Local32);
822     Got.Local32.clear();
823   }
824 
825   // Evaluate number of "reloc-only" entries in the resulting GOT.
826   // To do that put all unique "reloc-only" and "global" entries
827   // from all GOTs to the future primary GOT.
828   FileGot *PrimGot = &MergedGots.front();
829   for (FileGot &Got : Gots) {
830     set_union(PrimGot->Relocs, Got.Global);
831     set_union(PrimGot->Relocs, Got.Relocs);
832     Got.Relocs.clear();
833   }
834 
835   // Evaluate number of "page" entries in each GOT.
836   for (FileGot &Got : Gots) {
837     for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
838          Got.PagesMap) {
839       const OutputSection *OS = P.first;
840       uint64_t SecSize = 0;
841       for (BaseCommand *Cmd : OS->SectionCommands) {
842         if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
843           for (InputSection *IS : ISD->Sections) {
844             uint64_t Off = alignTo(SecSize, IS->Alignment);
845             SecSize = Off + IS->getSize();
846           }
847       }
848       P.second.Count = getMipsPageCount(SecSize);
849     }
850   }
851 
852   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
853   // maximum GOT size. At first, try to fill the primary GOT because
854   // the primary GOT can be accessed in the most effective way. If it
855   // is not possible, try to fill the last GOT in the list, and finally
856   // create a new GOT if both attempts failed.
857   for (FileGot &SrcGot : Gots) {
858     InputFile *File = SrcGot.File;
859     if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
860       File->MipsGotIndex = 0;
861     } else {
862       // If this is the first time we failed to merge with the primary GOT,
863       // MergedGots.back() will also be the primary GOT. We must make sure not
864       // to try to merge again with IsPrimary=false, as otherwise, if the
865       // inputs are just right, we could allow the primary GOT to become 1 or 2
866       // words too big due to ignoring the header size.
867       if (MergedGots.size() == 1 ||
868           !tryMergeGots(MergedGots.back(), SrcGot, false)) {
869         MergedGots.emplace_back();
870         std::swap(MergedGots.back(), SrcGot);
871       }
872       File->MipsGotIndex = MergedGots.size() - 1;
873     }
874   }
875   std::swap(Gots, MergedGots);
876 
877   // Reduce number of "reloc-only" entries in the primary GOT
878   // by substracting "global" entries exist in the primary GOT.
879   PrimGot = &Gots.front();
880   PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
881     return PrimGot->Global.count(P.first);
882   });
883 
884   // Calculate indexes for each GOT entry.
885   size_t Index = HeaderEntriesNum;
886   for (FileGot &Got : Gots) {
887     Got.StartIndex = &Got == PrimGot ? 0 : Index;
888     for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
889          Got.PagesMap) {
890       // For each output section referenced by GOT page relocations calculate
891       // and save into PagesMap an upper bound of MIPS GOT entries required
892       // to store page addresses of local symbols. We assume the worst case -
893       // each 64kb page of the output section has at least one GOT relocation
894       // against it. And take in account the case when the section intersects
895       // page boundaries.
896       P.second.FirstIndex = Index;
897       Index += P.second.Count;
898     }
899     for (auto &P: Got.Local16)
900       P.second = Index++;
901     for (auto &P: Got.Global)
902       P.second = Index++;
903     for (auto &P: Got.Relocs)
904       P.second = Index++;
905     for (auto &P: Got.Tls)
906       P.second = Index++;
907     for (auto &P: Got.DynTlsSymbols) {
908       P.second = Index;
909       Index += 2;
910     }
911   }
912 
913   // Update Symbol::GotIndex field to use this
914   // value later in the `sortMipsSymbols` function.
915   for (auto &P : PrimGot->Global)
916     P.first->GotIndex = P.second;
917   for (auto &P : PrimGot->Relocs)
918     P.first->GotIndex = P.second;
919 
920   // Create dynamic relocations.
921   for (FileGot &Got : Gots) {
922     // Create dynamic relocations for TLS entries.
923     for (std::pair<Symbol *, size_t> &P : Got.Tls) {
924       Symbol *S = P.first;
925       uint64_t Offset = P.second * Config->Wordsize;
926       if (S->IsPreemptible)
927         Main->RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
928     }
929     for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
930       Symbol *S = P.first;
931       uint64_t Offset = P.second * Config->Wordsize;
932       if (S == nullptr) {
933         if (!Config->Pic)
934           continue;
935         Main->RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
936       } else {
937         // When building a shared library we still need a dynamic relocation
938         // for the module index. Therefore only checking for
939         // S->IsPreemptible is not sufficient (this happens e.g. for
940         // thread-locals that have been marked as local through a linker script)
941         if (!S->IsPreemptible && !Config->Pic)
942           continue;
943         Main->RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
944         // However, we can skip writing the TLS offset reloc for non-preemptible
945         // symbols since it is known even in shared libraries
946         if (!S->IsPreemptible)
947           continue;
948         Offset += Config->Wordsize;
949         Main->RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
950       }
951     }
952 
953     // Do not create dynamic relocations for non-TLS
954     // entries in the primary GOT.
955     if (&Got == PrimGot)
956       continue;
957 
958     // Dynamic relocations for "global" entries.
959     for (const std::pair<Symbol *, size_t> &P : Got.Global) {
960       uint64_t Offset = P.second * Config->Wordsize;
961       Main->RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
962     }
963     if (!Config->Pic)
964       continue;
965     // Dynamic relocations for "local" entries in case of PIC.
966     for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
967          Got.PagesMap) {
968       size_t PageCount = L.second.Count;
969       for (size_t PI = 0; PI < PageCount; ++PI) {
970         uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
971         Main->RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
972                                  int64_t(PI * 0x10000)});
973       }
974     }
975     for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
976       uint64_t Offset = P.second * Config->Wordsize;
977       Main->RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
978                                P.first.first, P.first.second});
979     }
980   }
981 }
982 
983 bool MipsGotSection::isNeeded() const {
984   // We add the .got section to the result for dynamic MIPS target because
985   // its address and properties are mentioned in the .dynamic section.
986   return !Config->Relocatable;
987 }
988 
989 uint64_t MipsGotSection::getGp(const InputFile *F) const {
990   // For files without related GOT or files refer a primary GOT
991   // returns "common" _gp value. For secondary GOTs calculate
992   // individual _gp values.
993   if (!F || !F->MipsGotIndex.hasValue() || *F->MipsGotIndex == 0)
994     return ElfSym::MipsGp->getVA(0);
995   return getVA() + Gots[*F->MipsGotIndex].StartIndex * Config->Wordsize +
996          0x7ff0;
997 }
998 
999 void MipsGotSection::writeTo(uint8_t *Buf) {
1000   // Set the MSB of the second GOT slot. This is not required by any
1001   // MIPS ABI documentation, though.
1002   //
1003   // There is a comment in glibc saying that "The MSB of got[1] of a
1004   // gnu object is set to identify gnu objects," and in GNU gold it
1005   // says "the second entry will be used by some runtime loaders".
1006   // But how this field is being used is unclear.
1007   //
1008   // We are not really willing to mimic other linkers behaviors
1009   // without understanding why they do that, but because all files
1010   // generated by GNU tools have this special GOT value, and because
1011   // we've been doing this for years, it is probably a safe bet to
1012   // keep doing this for now. We really need to revisit this to see
1013   // if we had to do this.
1014   writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
1015   for (const FileGot &G : Gots) {
1016     auto Write = [&](size_t I, const Symbol *S, int64_t A) {
1017       uint64_t VA = A;
1018       if (S)
1019         VA = S->getVA(A);
1020       writeUint(Buf + I * Config->Wordsize, VA);
1021     };
1022     // Write 'page address' entries to the local part of the GOT.
1023     for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
1024          G.PagesMap) {
1025       size_t PageCount = L.second.Count;
1026       uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
1027       for (size_t PI = 0; PI < PageCount; ++PI)
1028         Write(L.second.FirstIndex + PI, nullptr, FirstPageAddr + PI * 0x10000);
1029     }
1030     // Local, global, TLS, reloc-only  entries.
1031     // If TLS entry has a corresponding dynamic relocations, leave it
1032     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1033     // To calculate the adjustments use offsets for thread-local storage.
1034     // https://www.linux-mips.org/wiki/NPTL
1035     for (const std::pair<GotEntry, size_t> &P : G.Local16)
1036       Write(P.second, P.first.first, P.first.second);
1037     // Write VA to the primary GOT only. For secondary GOTs that
1038     // will be done by REL32 dynamic relocations.
1039     if (&G == &Gots.front())
1040       for (const std::pair<const Symbol *, size_t> &P : G.Global)
1041         Write(P.second, P.first, 0);
1042     for (const std::pair<Symbol *, size_t> &P : G.Relocs)
1043       Write(P.second, P.first, 0);
1044     for (const std::pair<Symbol *, size_t> &P : G.Tls)
1045       Write(P.second, P.first, P.first->IsPreemptible ? 0 : -0x7000);
1046     for (const std::pair<Symbol *, size_t> &P : G.DynTlsSymbols) {
1047       if (P.first == nullptr && !Config->Pic)
1048         Write(P.second, nullptr, 1);
1049       else if (P.first && !P.first->IsPreemptible) {
1050         // If we are emitting PIC code with relocations we mustn't write
1051         // anything to the GOT here. When using Elf_Rel relocations the value
1052         // one will be treated as an addend and will cause crashes at runtime
1053         if (!Config->Pic)
1054           Write(P.second, nullptr, 1);
1055         Write(P.second + 1, P.first, -0x8000);
1056       }
1057     }
1058   }
1059 }
1060 
1061 // On PowerPC the .plt section is used to hold the table of function addresses
1062 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1063 // section. I don't know why we have a BSS style type for the section but it is
1064 // consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1065 GotPltSection::GotPltSection()
1066     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
1067                        ".got.plt") {
1068   if (Config->EMachine == EM_PPC) {
1069     Name = ".plt";
1070   } else if (Config->EMachine == EM_PPC64) {
1071     Type = SHT_NOBITS;
1072     Name = ".plt";
1073   }
1074 }
1075 
1076 void GotPltSection::addEntry(Symbol &Sym) {
1077   assert(Sym.PltIndex == Entries.size());
1078   Entries.push_back(&Sym);
1079 }
1080 
1081 size_t GotPltSection::getSize() const {
1082   return (Target->GotPltHeaderEntriesNum + Entries.size()) * Config->Wordsize;
1083 }
1084 
1085 void GotPltSection::writeTo(uint8_t *Buf) {
1086   Target->writeGotPltHeader(Buf);
1087   Buf += Target->GotPltHeaderEntriesNum * Config->Wordsize;
1088   for (const Symbol *B : Entries) {
1089     Target->writeGotPlt(Buf, *B);
1090     Buf += Config->Wordsize;
1091   }
1092 }
1093 
1094 bool GotPltSection::isNeeded() const {
1095   // We need to emit GOTPLT even if it's empty if there's a relocation relative
1096   // to it.
1097   return !Entries.empty() || HasGotPltOffRel;
1098 }
1099 
1100 static StringRef getIgotPltName() {
1101   // On ARM the IgotPltSection is part of the GotSection.
1102   if (Config->EMachine == EM_ARM)
1103     return ".got";
1104 
1105   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1106   // needs to be named the same.
1107   if (Config->EMachine == EM_PPC64)
1108     return ".plt";
1109 
1110   return ".got.plt";
1111 }
1112 
1113 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1114 // with the IgotPltSection.
1115 IgotPltSection::IgotPltSection()
1116     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1117                        Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1118                        Config->Wordsize, getIgotPltName()) {}
1119 
1120 void IgotPltSection::addEntry(Symbol &Sym) {
1121   assert(Sym.PltIndex == Entries.size());
1122   Entries.push_back(&Sym);
1123 }
1124 
1125 size_t IgotPltSection::getSize() const {
1126   return Entries.size() * Config->Wordsize;
1127 }
1128 
1129 void IgotPltSection::writeTo(uint8_t *Buf) {
1130   for (const Symbol *B : Entries) {
1131     Target->writeIgotPlt(Buf, *B);
1132     Buf += Config->Wordsize;
1133   }
1134 }
1135 
1136 StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
1137     : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
1138       Dynamic(Dynamic) {
1139   // ELF string tables start with a NUL byte.
1140   addString("");
1141 }
1142 
1143 // Adds a string to the string table. If HashIt is true we hash and check for
1144 // duplicates. It is optional because the name of global symbols are already
1145 // uniqued and hashing them again has a big cost for a small value: uniquing
1146 // them with some other string that happens to be the same.
1147 unsigned StringTableSection::addString(StringRef S, bool HashIt) {
1148   if (HashIt) {
1149     auto R = StringMap.insert(std::make_pair(S, this->Size));
1150     if (!R.second)
1151       return R.first->second;
1152   }
1153   unsigned Ret = this->Size;
1154   this->Size = this->Size + S.size() + 1;
1155   Strings.push_back(S);
1156   return Ret;
1157 }
1158 
1159 void StringTableSection::writeTo(uint8_t *Buf) {
1160   for (StringRef S : Strings) {
1161     memcpy(Buf, S.data(), S.size());
1162     Buf[S.size()] = '\0';
1163     Buf += S.size() + 1;
1164   }
1165 }
1166 
1167 // Returns the number of version definition entries. Because the first entry
1168 // is for the version definition itself, it is the number of versioned symbols
1169 // plus one. Note that we don't support multiple versions yet.
1170 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1171 
1172 template <class ELFT>
1173 DynamicSection<ELFT>::DynamicSection()
1174     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1175                        ".dynamic") {
1176   this->Entsize = ELFT::Is64Bits ? 16 : 8;
1177 
1178   // .dynamic section is not writable on MIPS and on Fuchsia OS
1179   // which passes -z rodynamic.
1180   // See "Special Section" in Chapter 4 in the following document:
1181   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1182   if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
1183     this->Flags = SHF_ALLOC;
1184 }
1185 
1186 template <class ELFT>
1187 void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1188   Entries.push_back({Tag, Fn});
1189 }
1190 
1191 template <class ELFT>
1192 void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1193   Entries.push_back({Tag, [=] { return Val; }});
1194 }
1195 
1196 template <class ELFT>
1197 void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1198   Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1199 }
1200 
1201 template <class ELFT>
1202 void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1203   size_t TagOffset = Entries.size() * Entsize;
1204   Entries.push_back(
1205       {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1206 }
1207 
1208 template <class ELFT>
1209 void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1210   Entries.push_back({Tag, [=] { return Sec->Addr; }});
1211 }
1212 
1213 template <class ELFT>
1214 void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1215   Entries.push_back({Tag, [=] { return Sec->Size; }});
1216 }
1217 
1218 template <class ELFT>
1219 void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1220   Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1221 }
1222 
1223 // A Linker script may assign the RELA relocation sections to the same
1224 // output section. When this occurs we cannot just use the OutputSection
1225 // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1226 // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1227 static uint64_t addPltRelSz() {
1228   size_t Size = In.RelaPlt->getSize();
1229   if (In.RelaIplt->getParent() == In.RelaPlt->getParent() &&
1230       In.RelaIplt->Name == In.RelaPlt->Name)
1231     Size += In.RelaIplt->getSize();
1232   return Size;
1233 }
1234 
1235 // Add remaining entries to complete .dynamic contents.
1236 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1237   elf::Partition &Part = getPartition();
1238   bool IsMain = Part.Name.empty();
1239 
1240   for (StringRef S : Config->FilterList)
1241     addInt(DT_FILTER, Part.DynStrTab->addString(S));
1242   for (StringRef S : Config->AuxiliaryList)
1243     addInt(DT_AUXILIARY, Part.DynStrTab->addString(S));
1244 
1245   if (!Config->Rpath.empty())
1246     addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1247            Part.DynStrTab->addString(Config->Rpath));
1248 
1249   for (SharedFile *File : SharedFiles)
1250     if (File->IsNeeded)
1251       addInt(DT_NEEDED, Part.DynStrTab->addString(File->SoName));
1252 
1253   if (IsMain) {
1254     if (!Config->SoName.empty())
1255       addInt(DT_SONAME, Part.DynStrTab->addString(Config->SoName));
1256   } else {
1257     if (!Config->SoName.empty())
1258       addInt(DT_NEEDED, Part.DynStrTab->addString(Config->SoName));
1259     addInt(DT_SONAME, Part.DynStrTab->addString(Part.Name));
1260   }
1261 
1262   // Set DT_FLAGS and DT_FLAGS_1.
1263   uint32_t DtFlags = 0;
1264   uint32_t DtFlags1 = 0;
1265   if (Config->Bsymbolic)
1266     DtFlags |= DF_SYMBOLIC;
1267   if (Config->ZGlobal)
1268     DtFlags1 |= DF_1_GLOBAL;
1269   if (Config->ZInitfirst)
1270     DtFlags1 |= DF_1_INITFIRST;
1271   if (Config->ZInterpose)
1272     DtFlags1 |= DF_1_INTERPOSE;
1273   if (Config->ZNodefaultlib)
1274     DtFlags1 |= DF_1_NODEFLIB;
1275   if (Config->ZNodelete)
1276     DtFlags1 |= DF_1_NODELETE;
1277   if (Config->ZNodlopen)
1278     DtFlags1 |= DF_1_NOOPEN;
1279   if (Config->ZNow) {
1280     DtFlags |= DF_BIND_NOW;
1281     DtFlags1 |= DF_1_NOW;
1282   }
1283   if (Config->ZOrigin) {
1284     DtFlags |= DF_ORIGIN;
1285     DtFlags1 |= DF_1_ORIGIN;
1286   }
1287   if (!Config->ZText)
1288     DtFlags |= DF_TEXTREL;
1289   if (Config->HasStaticTlsModel)
1290     DtFlags |= DF_STATIC_TLS;
1291 
1292   if (DtFlags)
1293     addInt(DT_FLAGS, DtFlags);
1294   if (DtFlags1)
1295     addInt(DT_FLAGS_1, DtFlags1);
1296 
1297   // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1298   // need it for each process, so we don't write it for DSOs. The loader writes
1299   // the pointer into this entry.
1300   //
1301   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1302   // systems (currently only Fuchsia OS) provide other means to give the
1303   // debugger this information. Such systems may choose make .dynamic read-only.
1304   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1305   if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
1306     addInt(DT_DEBUG, 0);
1307 
1308   if (OutputSection *Sec = Part.DynStrTab->getParent())
1309     this->Link = Sec->SectionIndex;
1310 
1311   if (Part.RelaDyn->isNeeded()) {
1312     addInSec(Part.RelaDyn->DynamicTag, Part.RelaDyn);
1313     addSize(Part.RelaDyn->SizeDynamicTag, Part.RelaDyn->getParent());
1314 
1315     bool IsRela = Config->IsRela;
1316     addInt(IsRela ? DT_RELAENT : DT_RELENT,
1317            IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1318 
1319     // MIPS dynamic loader does not support RELCOUNT tag.
1320     // The problem is in the tight relation between dynamic
1321     // relocations and GOT. So do not emit this tag on MIPS.
1322     if (Config->EMachine != EM_MIPS) {
1323       size_t NumRelativeRels = Part.RelaDyn->getRelativeRelocCount();
1324       if (Config->ZCombreloc && NumRelativeRels)
1325         addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
1326     }
1327   }
1328   if (Part.RelrDyn && !Part.RelrDyn->Relocs.empty()) {
1329     addInSec(Config->UseAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1330              Part.RelrDyn);
1331     addSize(Config->UseAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1332             Part.RelrDyn->getParent());
1333     addInt(Config->UseAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1334            sizeof(Elf_Relr));
1335   }
1336   // .rel[a].plt section usually consists of two parts, containing plt and
1337   // iplt relocations. It is possible to have only iplt relocations in the
1338   // output. In that case RelaPlt is empty and have zero offset, the same offset
1339   // as RelaIplt have. And we still want to emit proper dynamic tags for that
1340   // case, so here we always use RelaPlt as marker for the begining of
1341   // .rel[a].plt section.
1342   if (IsMain && In.RelaPlt->getParent()->isLive()) {
1343     addInSec(DT_JMPREL, In.RelaPlt);
1344     Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1345     switch (Config->EMachine) {
1346     case EM_MIPS:
1347       addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1348       break;
1349     case EM_SPARCV9:
1350       addInSec(DT_PLTGOT, In.Plt);
1351       break;
1352     default:
1353       addInSec(DT_PLTGOT, In.GotPlt);
1354       break;
1355     }
1356     addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
1357   }
1358 
1359   if (Config->EMachine == EM_AARCH64) {
1360     if (Config->AndFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1361       addInt(DT_AARCH64_BTI_PLT, 0);
1362     if (Config->AndFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)
1363       addInt(DT_AARCH64_PAC_PLT, 0);
1364   }
1365 
1366   addInSec(DT_SYMTAB, Part.DynSymTab);
1367   addInt(DT_SYMENT, sizeof(Elf_Sym));
1368   addInSec(DT_STRTAB, Part.DynStrTab);
1369   addInt(DT_STRSZ, Part.DynStrTab->getSize());
1370   if (!Config->ZText)
1371     addInt(DT_TEXTREL, 0);
1372   if (Part.GnuHashTab)
1373     addInSec(DT_GNU_HASH, Part.GnuHashTab);
1374   if (Part.HashTab)
1375     addInSec(DT_HASH, Part.HashTab);
1376 
1377   if (IsMain) {
1378     if (Out::PreinitArray) {
1379       addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380       addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381     }
1382     if (Out::InitArray) {
1383       addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384       addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385     }
1386     if (Out::FiniArray) {
1387       addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388       addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389     }
1390 
1391     if (Symbol *B = Symtab->find(Config->Init))
1392       if (B->isDefined())
1393         addSym(DT_INIT, B);
1394     if (Symbol *B = Symtab->find(Config->Fini))
1395       if (B->isDefined())
1396         addSym(DT_FINI, B);
1397   }
1398 
1399   bool HasVerNeed = SharedFile::VernauxNum != 0;
1400   if (HasVerNeed || Part.VerDef)
1401     addInSec(DT_VERSYM, Part.VerSym);
1402   if (Part.VerDef) {
1403     addInSec(DT_VERDEF, Part.VerDef);
1404     addInt(DT_VERDEFNUM, getVerDefNum());
1405   }
1406   if (HasVerNeed) {
1407     addInSec(DT_VERNEED, Part.VerNeed);
1408     unsigned NeedNum = 0;
1409     for (SharedFile *F : SharedFiles)
1410       if (!F->Vernauxs.empty())
1411         ++NeedNum;
1412     addInt(DT_VERNEEDNUM, NeedNum);
1413   }
1414 
1415   if (Config->EMachine == EM_MIPS) {
1416     addInt(DT_MIPS_RLD_VERSION, 1);
1417     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1418     addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1419     addInt(DT_MIPS_SYMTABNO, Part.DynSymTab->getNumSymbols());
1420 
1421     add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1422 
1423     if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1424       addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1425     else
1426       addInt(DT_MIPS_GOTSYM, Part.DynSymTab->getNumSymbols());
1427     addInSec(DT_PLTGOT, In.MipsGot);
1428     if (In.MipsRldMap) {
1429       if (!Config->Pie)
1430         addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1431       // Store the offset to the .rld_map section
1432       // relative to the address of the tag.
1433       addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1434     }
1435   }
1436 
1437   // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
1438   // glibc assumes the old-style BSS PLT layout which we don't support.
1439   if (Config->EMachine == EM_PPC)
1440     add(DT_PPC_GOT, [] { return In.Got->getVA(); });
1441 
1442   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1443   if (Config->EMachine == EM_PPC64 && In.Plt->isNeeded()) {
1444     // The Glink tag points to 32 bytes before the first lazy symbol resolution
1445     // stub, which starts directly after the header.
1446     Entries.push_back({DT_PPC64_GLINK, [=] {
1447                          unsigned Offset = Target->PltHeaderSize - 32;
1448                          return In.Plt->getVA(0) + Offset;
1449                        }});
1450   }
1451 
1452   addInt(DT_NULL, 0);
1453 
1454   getParent()->Link = this->Link;
1455   this->Size = Entries.size() * this->Entsize;
1456 }
1457 
1458 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1459   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1460 
1461   for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1462     P->d_tag = KV.first;
1463     P->d_un.d_val = KV.second();
1464     ++P;
1465   }
1466 }
1467 
1468 uint64_t DynamicReloc::getOffset() const {
1469   return InputSec->getVA(OffsetInSec);
1470 }
1471 
1472 int64_t DynamicReloc::computeAddend() const {
1473   if (UseSymVA)
1474     return Sym->getVA(Addend);
1475   if (!OutputSec)
1476     return Addend;
1477   // See the comment in the DynamicReloc ctor.
1478   return getMipsPageAddr(OutputSec->Addr) + Addend;
1479 }
1480 
1481 uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *SymTab) const {
1482   if (Sym && !UseSymVA)
1483     return SymTab->getSymbolIndex(Sym);
1484   return 0;
1485 }
1486 
1487 RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1488                                              int32_t DynamicTag,
1489                                              int32_t SizeDynamicTag)
1490     : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1491       DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
1492 
1493 void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
1494                                      uint64_t OffsetInSec, Symbol *Sym) {
1495   addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1496 }
1497 
1498 void RelocationBaseSection::addReloc(RelType DynType,
1499                                      InputSectionBase *InputSec,
1500                                      uint64_t OffsetInSec, Symbol *Sym,
1501                                      int64_t Addend, RelExpr Expr,
1502                                      RelType Type) {
1503   // Write the addends to the relocated address if required. We skip
1504   // it if the written value would be zero.
1505   if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0))
1506     InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
1507   addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
1508 }
1509 
1510 void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
1511   if (Reloc.Type == Target->RelativeRel)
1512     ++NumRelativeRelocs;
1513   Relocs.push_back(Reloc);
1514 }
1515 
1516 void RelocationBaseSection::finalizeContents() {
1517   SymbolTableBaseSection *SymTab = getPartition().DynSymTab;
1518 
1519   // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1520   // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1521   // case.
1522   if (SymTab && SymTab->getParent())
1523     getParent()->Link = SymTab->getParent()->SectionIndex;
1524   else
1525     getParent()->Link = 0;
1526 
1527   if (In.RelaPlt == this)
1528     getParent()->Info = In.GotPlt->getParent()->SectionIndex;
1529   if (In.RelaIplt == this)
1530     getParent()->Info = In.IgotPlt->getParent()->SectionIndex;
1531 }
1532 
1533 RelrBaseSection::RelrBaseSection()
1534     : SyntheticSection(SHF_ALLOC,
1535                        Config->UseAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
1536                        Config->Wordsize, ".relr.dyn") {}
1537 
1538 template <class ELFT>
1539 static void encodeDynamicReloc(SymbolTableBaseSection *SymTab,
1540                                typename ELFT::Rela *P,
1541                                const DynamicReloc &Rel) {
1542   if (Config->IsRela)
1543     P->r_addend = Rel.computeAddend();
1544   P->r_offset = Rel.getOffset();
1545   P->setSymbolAndType(Rel.getSymIndex(SymTab), Rel.Type, Config->IsMips64EL);
1546 }
1547 
1548 template <class ELFT>
1549 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1550     : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1551                             Config->IsRela ? DT_RELA : DT_REL,
1552                             Config->IsRela ? DT_RELASZ : DT_RELSZ),
1553       Sort(Sort) {
1554   this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1555 }
1556 
1557 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1558   SymbolTableBaseSection *SymTab = getPartition().DynSymTab;
1559 
1560   // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
1561   // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
1562   // is to make results easier to read.
1563   if (Sort)
1564     llvm::stable_sort(
1565         Relocs, [&](const DynamicReloc &A, const DynamicReloc &B) {
1566           return std::make_tuple(A.Type != Target->RelativeRel,
1567                                  A.getSymIndex(SymTab), A.getOffset()) <
1568                  std::make_tuple(B.Type != Target->RelativeRel,
1569                                  B.getSymIndex(SymTab), B.getOffset());
1570         });
1571 
1572   for (const DynamicReloc &Rel : Relocs) {
1573     encodeDynamicReloc<ELFT>(SymTab, reinterpret_cast<Elf_Rela *>(Buf), Rel);
1574     Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1575   }
1576 }
1577 
1578 template <class ELFT>
1579 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1580     StringRef Name)
1581     : RelocationBaseSection(
1582           Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1583           Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1584           Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1585   this->Entsize = 1;
1586 }
1587 
1588 template <class ELFT>
1589 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1590   // This function computes the contents of an Android-format packed relocation
1591   // section.
1592   //
1593   // This format compresses relocations by using relocation groups to factor out
1594   // fields that are common between relocations and storing deltas from previous
1595   // relocations in SLEB128 format (which has a short representation for small
1596   // numbers). A good example of a relocation type with common fields is
1597   // R_*_RELATIVE, which is normally used to represent function pointers in
1598   // vtables. In the REL format, each relative relocation has the same r_info
1599   // field, and is only different from other relative relocations in terms of
1600   // the r_offset field. By sorting relocations by offset, grouping them by
1601   // r_info and representing each relocation with only the delta from the
1602   // previous offset, each 8-byte relocation can be compressed to as little as 1
1603   // byte (or less with run-length encoding). This relocation packer was able to
1604   // reduce the size of the relocation section in an Android Chromium DSO from
1605   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1606   //
1607   // A relocation section consists of a header containing the literal bytes
1608   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1609   // elements are the total number of relocations in the section and an initial
1610   // r_offset value. The remaining elements define a sequence of relocation
1611   // groups. Each relocation group starts with a header consisting of the
1612   // following elements:
1613   //
1614   // - the number of relocations in the relocation group
1615   // - flags for the relocation group
1616   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1617   //   for each relocation in the group.
1618   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1619   //   field for each relocation in the group.
1620   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1621   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1622   //   each relocation in the group.
1623   //
1624   // Following the relocation group header are descriptions of each of the
1625   // relocations in the group. They consist of the following elements:
1626   //
1627   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1628   //   delta for this relocation.
1629   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1630   //   field for this relocation.
1631   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1632   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1633   //   this relocation.
1634 
1635   size_t OldSize = RelocData.size();
1636 
1637   RelocData = {'A', 'P', 'S', '2'};
1638   raw_svector_ostream OS(RelocData);
1639   auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1640 
1641   // The format header includes the number of relocations and the initial
1642   // offset (we set this to zero because the first relocation group will
1643   // perform the initial adjustment).
1644   Add(Relocs.size());
1645   Add(0);
1646 
1647   std::vector<Elf_Rela> Relatives, NonRelatives;
1648 
1649   for (const DynamicReloc &Rel : Relocs) {
1650     Elf_Rela R;
1651     encodeDynamicReloc<ELFT>(getPartition().DynSymTab, &R, Rel);
1652 
1653     if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1654       Relatives.push_back(R);
1655     else
1656       NonRelatives.push_back(R);
1657   }
1658 
1659   llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) {
1660     return A.r_offset < B.r_offset;
1661   });
1662 
1663   // Try to find groups of relative relocations which are spaced one word
1664   // apart from one another. These generally correspond to vtable entries. The
1665   // format allows these groups to be encoded using a sort of run-length
1666   // encoding, but each group will cost 7 bytes in addition to the offset from
1667   // the previous group, so it is only profitable to do this for groups of
1668   // size 8 or larger.
1669   std::vector<Elf_Rela> UngroupedRelatives;
1670   std::vector<std::vector<Elf_Rela>> RelativeGroups;
1671   for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1672     std::vector<Elf_Rela> Group;
1673     do {
1674       Group.push_back(*I++);
1675     } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1676 
1677     if (Group.size() < 8)
1678       UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1679                                 Group.end());
1680     else
1681       RelativeGroups.emplace_back(std::move(Group));
1682   }
1683 
1684   unsigned HasAddendIfRela =
1685       Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1686 
1687   uint64_t Offset = 0;
1688   uint64_t Addend = 0;
1689 
1690   // Emit the run-length encoding for the groups of adjacent relative
1691   // relocations. Each group is represented using two groups in the packed
1692   // format. The first is used to set the current offset to the start of the
1693   // group (and also encodes the first relocation), and the second encodes the
1694   // remaining relocations.
1695   for (std::vector<Elf_Rela> &G : RelativeGroups) {
1696     // The first relocation in the group.
1697     Add(1);
1698     Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1699         RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1700     Add(G[0].r_offset - Offset);
1701     Add(Target->RelativeRel);
1702     if (Config->IsRela) {
1703       Add(G[0].r_addend - Addend);
1704       Addend = G[0].r_addend;
1705     }
1706 
1707     // The remaining relocations.
1708     Add(G.size() - 1);
1709     Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1710         RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1711     Add(Config->Wordsize);
1712     Add(Target->RelativeRel);
1713     if (Config->IsRela) {
1714       for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1715         Add(I->r_addend - Addend);
1716         Addend = I->r_addend;
1717       }
1718     }
1719 
1720     Offset = G.back().r_offset;
1721   }
1722 
1723   // Now the ungrouped relatives.
1724   if (!UngroupedRelatives.empty()) {
1725     Add(UngroupedRelatives.size());
1726     Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1727     Add(Target->RelativeRel);
1728     for (Elf_Rela &R : UngroupedRelatives) {
1729       Add(R.r_offset - Offset);
1730       Offset = R.r_offset;
1731       if (Config->IsRela) {
1732         Add(R.r_addend - Addend);
1733         Addend = R.r_addend;
1734       }
1735     }
1736   }
1737 
1738   // Finally the non-relative relocations.
1739   llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) {
1740     return A.r_offset < B.r_offset;
1741   });
1742   if (!NonRelatives.empty()) {
1743     Add(NonRelatives.size());
1744     Add(HasAddendIfRela);
1745     for (Elf_Rela &R : NonRelatives) {
1746       Add(R.r_offset - Offset);
1747       Offset = R.r_offset;
1748       Add(R.r_info);
1749       if (Config->IsRela) {
1750         Add(R.r_addend - Addend);
1751         Addend = R.r_addend;
1752       }
1753     }
1754   }
1755 
1756   // Don't allow the section to shrink; otherwise the size of the section can
1757   // oscillate infinitely.
1758   if (RelocData.size() < OldSize)
1759     RelocData.append(OldSize - RelocData.size(), 0);
1760 
1761   // Returns whether the section size changed. We need to keep recomputing both
1762   // section layout and the contents of this section until the size converges
1763   // because changing this section's size can affect section layout, which in
1764   // turn can affect the sizes of the LEB-encoded integers stored in this
1765   // section.
1766   return RelocData.size() != OldSize;
1767 }
1768 
1769 template <class ELFT> RelrSection<ELFT>::RelrSection() {
1770   this->Entsize = Config->Wordsize;
1771 }
1772 
1773 template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
1774   // This function computes the contents of an SHT_RELR packed relocation
1775   // section.
1776   //
1777   // Proposal for adding SHT_RELR sections to generic-abi is here:
1778   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
1779   //
1780   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
1781   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
1782   //
1783   // i.e. start with an address, followed by any number of bitmaps. The address
1784   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
1785   // relocations each, at subsequent offsets following the last address entry.
1786   //
1787   // The bitmap entries must have 1 in the least significant bit. The assumption
1788   // here is that an address cannot have 1 in lsb. Odd addresses are not
1789   // supported.
1790   //
1791   // Excluding the least significant bit in the bitmap, each non-zero bit in
1792   // the bitmap represents a relocation to be applied to a corresponding machine
1793   // word that follows the base address word. The second least significant bit
1794   // represents the machine word immediately following the initial address, and
1795   // each bit that follows represents the next word, in linear order. As such,
1796   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
1797   // 63 relocations in a 64-bit object.
1798   //
1799   // This encoding has a couple of interesting properties:
1800   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
1801   //    even means address, odd means bitmap.
1802   // 2. Just a simple list of addresses is a valid encoding.
1803 
1804   size_t OldSize = RelrRelocs.size();
1805   RelrRelocs.clear();
1806 
1807   // Same as Config->Wordsize but faster because this is a compile-time
1808   // constant.
1809   const size_t Wordsize = sizeof(typename ELFT::uint);
1810 
1811   // Number of bits to use for the relocation offsets bitmap.
1812   // Must be either 63 or 31.
1813   const size_t NBits = Wordsize * 8 - 1;
1814 
1815   // Get offsets for all relative relocations and sort them.
1816   std::vector<uint64_t> Offsets;
1817   for (const RelativeReloc &Rel : Relocs)
1818     Offsets.push_back(Rel.getOffset());
1819   llvm::sort(Offsets);
1820 
1821   // For each leading relocation, find following ones that can be folded
1822   // as a bitmap and fold them.
1823   for (size_t I = 0, E = Offsets.size(); I < E;) {
1824     // Add a leading relocation.
1825     RelrRelocs.push_back(Elf_Relr(Offsets[I]));
1826     uint64_t Base = Offsets[I] + Wordsize;
1827     ++I;
1828 
1829     // Find foldable relocations to construct bitmaps.
1830     while (I < E) {
1831       uint64_t Bitmap = 0;
1832 
1833       while (I < E) {
1834         uint64_t Delta = Offsets[I] - Base;
1835 
1836         // If it is too far, it cannot be folded.
1837         if (Delta >= NBits * Wordsize)
1838           break;
1839 
1840         // If it is not a multiple of wordsize away, it cannot be folded.
1841         if (Delta % Wordsize)
1842           break;
1843 
1844         // Fold it.
1845         Bitmap |= 1ULL << (Delta / Wordsize);
1846         ++I;
1847       }
1848 
1849       if (!Bitmap)
1850         break;
1851 
1852       RelrRelocs.push_back(Elf_Relr((Bitmap << 1) | 1));
1853       Base += NBits * Wordsize;
1854     }
1855   }
1856 
1857   return RelrRelocs.size() != OldSize;
1858 }
1859 
1860 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1861     : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1862                        StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1863                        Config->Wordsize,
1864                        StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1865       StrTabSec(StrTabSec) {}
1866 
1867 // Orders symbols according to their positions in the GOT,
1868 // in compliance with MIPS ABI rules.
1869 // See "Global Offset Table" in Chapter 5 in the following document
1870 // for detailed description:
1871 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1872 static bool sortMipsSymbols(const SymbolTableEntry &L,
1873                             const SymbolTableEntry &R) {
1874   // Sort entries related to non-local preemptible symbols by GOT indexes.
1875   // All other entries go to the beginning of a dynsym in arbitrary order.
1876   if (L.Sym->isInGot() && R.Sym->isInGot())
1877     return L.Sym->GotIndex < R.Sym->GotIndex;
1878   if (!L.Sym->isInGot() && !R.Sym->isInGot())
1879     return false;
1880   return !L.Sym->isInGot();
1881 }
1882 
1883 void SymbolTableBaseSection::finalizeContents() {
1884   if (OutputSection *Sec = StrTabSec.getParent())
1885     getParent()->Link = Sec->SectionIndex;
1886 
1887   if (this->Type != SHT_DYNSYM) {
1888     sortSymTabSymbols();
1889     return;
1890   }
1891 
1892   // If it is a .dynsym, there should be no local symbols, but we need
1893   // to do a few things for the dynamic linker.
1894 
1895   // Section's Info field has the index of the first non-local symbol.
1896   // Because the first symbol entry is a null entry, 1 is the first.
1897   getParent()->Info = 1;
1898 
1899   if (getPartition().GnuHashTab) {
1900     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1901     getPartition().GnuHashTab->addSymbols(Symbols);
1902   } else if (Config->EMachine == EM_MIPS) {
1903     llvm::stable_sort(Symbols, sortMipsSymbols);
1904   }
1905 
1906   // Only the main partition's dynsym indexes are stored in the symbols
1907   // themselves. All other partitions use a lookup table.
1908   if (this == Main->DynSymTab) {
1909     size_t I = 0;
1910     for (const SymbolTableEntry &S : Symbols)
1911       S.Sym->DynsymIndex = ++I;
1912   }
1913 }
1914 
1915 // The ELF spec requires that all local symbols precede global symbols, so we
1916 // sort symbol entries in this function. (For .dynsym, we don't do that because
1917 // symbols for dynamic linking are inherently all globals.)
1918 //
1919 // Aside from above, we put local symbols in groups starting with the STT_FILE
1920 // symbol. That is convenient for purpose of identifying where are local symbols
1921 // coming from.
1922 void SymbolTableBaseSection::sortSymTabSymbols() {
1923   // Move all local symbols before global symbols.
1924   auto E = std::stable_partition(
1925       Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1926         return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
1927       });
1928   size_t NumLocals = E - Symbols.begin();
1929   getParent()->Info = NumLocals + 1;
1930 
1931   // We want to group the local symbols by file. For that we rebuild the local
1932   // part of the symbols vector. We do not need to care about the STT_FILE
1933   // symbols, they are already naturally placed first in each group. That
1934   // happens because STT_FILE is always the first symbol in the object and hence
1935   // precede all other local symbols we add for a file.
1936   MapVector<InputFile *, std::vector<SymbolTableEntry>> Arr;
1937   for (const SymbolTableEntry &S : llvm::make_range(Symbols.begin(), E))
1938     Arr[S.Sym->File].push_back(S);
1939 
1940   auto I = Symbols.begin();
1941   for (std::pair<InputFile *, std::vector<SymbolTableEntry>> &P : Arr)
1942     for (SymbolTableEntry &Entry : P.second)
1943       *I++ = Entry;
1944 }
1945 
1946 void SymbolTableBaseSection::addSymbol(Symbol *B) {
1947   // Adding a local symbol to a .dynsym is a bug.
1948   assert(this->Type != SHT_DYNSYM || !B->isLocal());
1949 
1950   bool HashIt = B->isLocal();
1951   Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1952 }
1953 
1954 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
1955   if (this == Main->DynSymTab)
1956     return Sym->DynsymIndex;
1957 
1958   // Initializes symbol lookup tables lazily. This is used only for -r,
1959   // -emit-relocs and dynsyms in partitions other than the main one.
1960   llvm::call_once(OnceFlag, [&] {
1961     SymbolIndexMap.reserve(Symbols.size());
1962     size_t I = 0;
1963     for (const SymbolTableEntry &E : Symbols) {
1964       if (E.Sym->Type == STT_SECTION)
1965         SectionIndexMap[E.Sym->getOutputSection()] = ++I;
1966       else
1967         SymbolIndexMap[E.Sym] = ++I;
1968     }
1969   });
1970 
1971   // Section symbols are mapped based on their output sections
1972   // to maintain their semantics.
1973   if (Sym->Type == STT_SECTION)
1974     return SectionIndexMap.lookup(Sym->getOutputSection());
1975   return SymbolIndexMap.lookup(Sym);
1976 }
1977 
1978 template <class ELFT>
1979 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1980     : SymbolTableBaseSection(StrTabSec) {
1981   this->Entsize = sizeof(Elf_Sym);
1982 }
1983 
1984 static BssSection *getCommonSec(Symbol *Sym) {
1985   if (!Config->DefineCommon)
1986     if (auto *D = dyn_cast<Defined>(Sym))
1987       return dyn_cast_or_null<BssSection>(D->Section);
1988   return nullptr;
1989 }
1990 
1991 static uint32_t getSymSectionIndex(Symbol *Sym) {
1992   if (getCommonSec(Sym))
1993     return SHN_COMMON;
1994   if (!isa<Defined>(Sym) || Sym->NeedsPltAddr)
1995     return SHN_UNDEF;
1996   if (const OutputSection *OS = Sym->getOutputSection())
1997     return OS->SectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
1998                                              : OS->SectionIndex;
1999   return SHN_ABS;
2000 }
2001 
2002 // Write the internal symbol table contents to the output symbol table.
2003 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
2004   // The first entry is a null entry as per the ELF spec.
2005   memset(Buf, 0, sizeof(Elf_Sym));
2006   Buf += sizeof(Elf_Sym);
2007 
2008   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
2009 
2010   for (SymbolTableEntry &Ent : Symbols) {
2011     Symbol *Sym = Ent.Sym;
2012     bool IsDefinedHere = Type == SHT_SYMTAB || Sym->Partition == Partition;
2013 
2014     // Set st_info and st_other.
2015     ESym->st_other = 0;
2016     if (Sym->isLocal()) {
2017       ESym->setBindingAndType(STB_LOCAL, Sym->Type);
2018     } else {
2019       ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
2020       ESym->setVisibility(Sym->Visibility);
2021     }
2022 
2023     // The 3 most significant bits of st_other are used by OpenPOWER ABI.
2024     // See getPPC64GlobalEntryToLocalEntryOffset() for more details.
2025     if (Config->EMachine == EM_PPC64)
2026       ESym->st_other |= Sym->StOther & 0xe0;
2027 
2028     ESym->st_name = Ent.StrTabOffset;
2029     if (IsDefinedHere)
2030       ESym->st_shndx = getSymSectionIndex(Ent.Sym);
2031     else
2032       ESym->st_shndx = 0;
2033 
2034     // Copy symbol size if it is a defined symbol. st_size is not significant
2035     // for undefined symbols, so whether copying it or not is up to us if that's
2036     // the case. We'll leave it as zero because by not setting a value, we can
2037     // get the exact same outputs for two sets of input files that differ only
2038     // in undefined symbol size in DSOs.
2039     if (ESym->st_shndx == SHN_UNDEF || !IsDefinedHere)
2040       ESym->st_size = 0;
2041     else
2042       ESym->st_size = Sym->getSize();
2043 
2044     // st_value is usually an address of a symbol, but that has a
2045     // special meaining for uninstantiated common symbols (this can
2046     // occur if -r is given).
2047     if (BssSection *CommonSec = getCommonSec(Ent.Sym))
2048       ESym->st_value = CommonSec->Alignment;
2049     else if (IsDefinedHere)
2050       ESym->st_value = Sym->getVA();
2051     else
2052       ESym->st_value = 0;
2053 
2054     ++ESym;
2055   }
2056 
2057   // On MIPS we need to mark symbol which has a PLT entry and requires
2058   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
2059   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
2060   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
2061   if (Config->EMachine == EM_MIPS) {
2062     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
2063 
2064     for (SymbolTableEntry &Ent : Symbols) {
2065       Symbol *Sym = Ent.Sym;
2066       if (Sym->isInPlt() && Sym->NeedsPltAddr)
2067         ESym->st_other |= STO_MIPS_PLT;
2068       if (isMicroMips()) {
2069         // We already set the less-significant bit for symbols
2070         // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
2071         // records. That allows us to distinguish such symbols in
2072         // the `MIPS<ELFT>::relocateOne()` routine. Now we should
2073         // clear that bit for non-dynamic symbol table, so tools
2074         // like `objdump` will be able to deal with a correct
2075         // symbol position.
2076         if (Sym->isDefined() &&
2077             ((Sym->StOther & STO_MIPS_MICROMIPS) || Sym->NeedsPltAddr)) {
2078           if (!StrTabSec.isDynamic())
2079             ESym->st_value &= ~1;
2080           ESym->st_other |= STO_MIPS_MICROMIPS;
2081         }
2082       }
2083       if (Config->Relocatable)
2084         if (auto *D = dyn_cast<Defined>(Sym))
2085           if (isMipsPIC<ELFT>(D))
2086             ESym->st_other |= STO_MIPS_PIC;
2087       ++ESym;
2088     }
2089   }
2090 }
2091 
2092 SymtabShndxSection::SymtabShndxSection()
2093     : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") {
2094   this->Entsize = 4;
2095 }
2096 
2097 void SymtabShndxSection::writeTo(uint8_t *Buf) {
2098   // We write an array of 32 bit values, where each value has 1:1 association
2099   // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX,
2100   // we need to write actual index, otherwise, we must write SHN_UNDEF(0).
2101   Buf += 4; // Ignore .symtab[0] entry.
2102   for (const SymbolTableEntry &Entry : In.SymTab->getSymbols()) {
2103     if (getSymSectionIndex(Entry.Sym) == SHN_XINDEX)
2104       write32(Buf, Entry.Sym->getOutputSection()->SectionIndex);
2105     Buf += 4;
2106   }
2107 }
2108 
2109 bool SymtabShndxSection::isNeeded() const {
2110   // SHT_SYMTAB can hold symbols with section indices values up to
2111   // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
2112   // section. Problem is that we reveal the final section indices a bit too
2113   // late, and we do not know them here. For simplicity, we just always create
2114   // a .symtab_shndx section when the amount of output sections is huge.
2115   size_t Size = 0;
2116   for (BaseCommand *Base : Script->SectionCommands)
2117     if (isa<OutputSection>(Base))
2118       ++Size;
2119   return Size >= SHN_LORESERVE;
2120 }
2121 
2122 void SymtabShndxSection::finalizeContents() {
2123   getParent()->Link = In.SymTab->getParent()->SectionIndex;
2124 }
2125 
2126 size_t SymtabShndxSection::getSize() const {
2127   return In.SymTab->getNumSymbols() * 4;
2128 }
2129 
2130 // .hash and .gnu.hash sections contain on-disk hash tables that map
2131 // symbol names to their dynamic symbol table indices. Their purpose
2132 // is to help the dynamic linker resolve symbols quickly. If ELF files
2133 // don't have them, the dynamic linker has to do linear search on all
2134 // dynamic symbols, which makes programs slower. Therefore, a .hash
2135 // section is added to a DSO by default. A .gnu.hash is added if you
2136 // give the -hash-style=gnu or -hash-style=both option.
2137 //
2138 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
2139 // Each ELF file has a list of DSOs that the ELF file depends on and a
2140 // list of dynamic symbols that need to be resolved from any of the
2141 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2142 // where m is the number of DSOs and n is the number of dynamic
2143 // symbols. For modern large programs, both m and n are large.  So
2144 // making each step faster by using hash tables substiantially
2145 // improves time to load programs.
2146 //
2147 // (Note that this is not the only way to design the shared library.
2148 // For instance, the Windows DLL takes a different approach. On
2149 // Windows, each dynamic symbol has a name of DLL from which the symbol
2150 // has to be resolved. That makes the cost of symbol resolution O(n).
2151 // This disables some hacky techniques you can use on Unix such as
2152 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2153 //
2154 // Due to historical reasons, we have two different hash tables, .hash
2155 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2156 // and better version of .hash. .hash is just an on-disk hash table, but
2157 // .gnu.hash has a bloom filter in addition to a hash table to skip
2158 // DSOs very quickly. If you are sure that your dynamic linker knows
2159 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
2160 // safe bet is to specify -hash-style=both for backward compatibilty.
2161 GnuHashTableSection::GnuHashTableSection()
2162     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
2163 }
2164 
2165 void GnuHashTableSection::finalizeContents() {
2166   if (OutputSection *Sec = getPartition().DynSymTab->getParent())
2167     getParent()->Link = Sec->SectionIndex;
2168 
2169   // Computes bloom filter size in word size. We want to allocate 12
2170   // bits for each symbol. It must be a power of two.
2171   if (Symbols.empty()) {
2172     MaskWords = 1;
2173   } else {
2174     uint64_t NumBits = Symbols.size() * 12;
2175     MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8));
2176   }
2177 
2178   Size = 16;                            // Header
2179   Size += Config->Wordsize * MaskWords; // Bloom filter
2180   Size += NBuckets * 4;                 // Hash buckets
2181   Size += Symbols.size() * 4;           // Hash values
2182 }
2183 
2184 void GnuHashTableSection::writeTo(uint8_t *Buf) {
2185   // The output buffer is not guaranteed to be zero-cleared because we pre-
2186   // fill executable sections with trap instructions. This is a precaution
2187   // for that case, which happens only when -no-rosegment is given.
2188   memset(Buf, 0, Size);
2189 
2190   // Write a header.
2191   write32(Buf, NBuckets);
2192   write32(Buf + 4, getPartition().DynSymTab->getNumSymbols() - Symbols.size());
2193   write32(Buf + 8, MaskWords);
2194   write32(Buf + 12, Shift2);
2195   Buf += 16;
2196 
2197   // Write a bloom filter and a hash table.
2198   writeBloomFilter(Buf);
2199   Buf += Config->Wordsize * MaskWords;
2200   writeHashTable(Buf);
2201 }
2202 
2203 // This function writes a 2-bit bloom filter. This bloom filter alone
2204 // usually filters out 80% or more of all symbol lookups [1].
2205 // The dynamic linker uses the hash table only when a symbol is not
2206 // filtered out by a bloom filter.
2207 //
2208 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
2209 //     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
2210 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
2211   unsigned C = Config->Is64 ? 64 : 32;
2212   for (const Entry &Sym : Symbols) {
2213     // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
2214     // the word using bits [0:5] and [26:31].
2215     size_t I = (Sym.Hash / C) & (MaskWords - 1);
2216     uint64_t Val = readUint(Buf + I * Config->Wordsize);
2217     Val |= uint64_t(1) << (Sym.Hash % C);
2218     Val |= uint64_t(1) << ((Sym.Hash >> Shift2) % C);
2219     writeUint(Buf + I * Config->Wordsize, Val);
2220   }
2221 }
2222 
2223 void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
2224   uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
2225   uint32_t OldBucket = -1;
2226   uint32_t *Values = Buckets + NBuckets;
2227   for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
2228     // Write a hash value. It represents a sequence of chains that share the
2229     // same hash modulo value. The last element of each chain is terminated by
2230     // LSB 1.
2231     uint32_t Hash = I->Hash;
2232     bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
2233     Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
2234     write32(Values++, Hash);
2235 
2236     if (I->BucketIdx == OldBucket)
2237       continue;
2238     // Write a hash bucket. Hash buckets contain indices in the following hash
2239     // value table.
2240     write32(Buckets + I->BucketIdx,
2241             getPartition().DynSymTab->getSymbolIndex(I->Sym));
2242     OldBucket = I->BucketIdx;
2243   }
2244 }
2245 
2246 static uint32_t hashGnu(StringRef Name) {
2247   uint32_t H = 5381;
2248   for (uint8_t C : Name)
2249     H = (H << 5) + H + C;
2250   return H;
2251 }
2252 
2253 // Add symbols to this symbol hash table. Note that this function
2254 // destructively sort a given vector -- which is needed because
2255 // GNU-style hash table places some sorting requirements.
2256 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
2257   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2258   // its type correctly.
2259   std::vector<SymbolTableEntry>::iterator Mid =
2260       std::stable_partition(V.begin(), V.end(), [&](const SymbolTableEntry &S) {
2261         return !S.Sym->isDefined() || S.Sym->Partition != Partition;
2262       });
2263 
2264   // We chose load factor 4 for the on-disk hash table. For each hash
2265   // collision, the dynamic linker will compare a uint32_t hash value.
2266   // Since the integer comparison is quite fast, we believe we can
2267   // make the load factor even larger. 4 is just a conservative choice.
2268   //
2269   // Note that we don't want to create a zero-sized hash table because
2270   // Android loader as of 2018 doesn't like a .gnu.hash containing such
2271   // table. If that's the case, we create a hash table with one unused
2272   // dummy slot.
2273   NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
2274 
2275   if (Mid == V.end())
2276     return;
2277 
2278   for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
2279     Symbol *B = Ent.Sym;
2280     uint32_t Hash = hashGnu(B->getName());
2281     uint32_t BucketIdx = Hash % NBuckets;
2282     Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
2283   }
2284 
2285   llvm::stable_sort(Symbols, [](const Entry &L, const Entry &R) {
2286     return L.BucketIdx < R.BucketIdx;
2287   });
2288 
2289   V.erase(Mid, V.end());
2290   for (const Entry &Ent : Symbols)
2291     V.push_back({Ent.Sym, Ent.StrTabOffset});
2292 }
2293 
2294 HashTableSection::HashTableSection()
2295     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2296   this->Entsize = 4;
2297 }
2298 
2299 void HashTableSection::finalizeContents() {
2300   SymbolTableBaseSection *SymTab = getPartition().DynSymTab;
2301 
2302   if (OutputSection *Sec = SymTab->getParent())
2303     getParent()->Link = Sec->SectionIndex;
2304 
2305   unsigned NumEntries = 2;               // nbucket and nchain.
2306   NumEntries += SymTab->getNumSymbols(); // The chain entries.
2307 
2308   // Create as many buckets as there are symbols.
2309   NumEntries += SymTab->getNumSymbols();
2310   this->Size = NumEntries * 4;
2311 }
2312 
2313 void HashTableSection::writeTo(uint8_t *Buf) {
2314   SymbolTableBaseSection *SymTab = getPartition().DynSymTab;
2315 
2316   // See comment in GnuHashTableSection::writeTo.
2317   memset(Buf, 0, Size);
2318 
2319   unsigned NumSymbols = SymTab->getNumSymbols();
2320 
2321   uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
2322   write32(P++, NumSymbols); // nbucket
2323   write32(P++, NumSymbols); // nchain
2324 
2325   uint32_t *Buckets = P;
2326   uint32_t *Chains = P + NumSymbols;
2327 
2328   for (const SymbolTableEntry &S : SymTab->getSymbols()) {
2329     Symbol *Sym = S.Sym;
2330     StringRef Name = Sym->getName();
2331     unsigned I = Sym->DynsymIndex;
2332     uint32_t Hash = hashSysV(Name) % NumSymbols;
2333     Chains[I] = Buckets[Hash];
2334     write32(Buckets + Hash, I);
2335   }
2336 }
2337 
2338 // On PowerPC64 the lazy symbol resolvers go into the `global linkage table`
2339 // in the .glink section, rather then the typical .plt section.
2340 PltSection::PltSection(bool IsIplt)
2341     : SyntheticSection(
2342           SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
2343           (Config->EMachine == EM_PPC || Config->EMachine == EM_PPC64)
2344               ? ".glink"
2345               : ".plt"),
2346       HeaderSize(!IsIplt || Config->ZRetpolineplt ? Target->PltHeaderSize : 0),
2347       IsIplt(IsIplt) {
2348   // The PLT needs to be writable on SPARC as the dynamic linker will
2349   // modify the instructions in the PLT entries.
2350   if (Config->EMachine == EM_SPARCV9)
2351     this->Flags |= SHF_WRITE;
2352 }
2353 
2354 void PltSection::writeTo(uint8_t *Buf) {
2355   if (Config->EMachine == EM_PPC) {
2356     writePPC32GlinkSection(Buf, Entries.size());
2357     return;
2358   }
2359 
2360   // At beginning of PLT or retpoline IPLT, we have code to call the dynamic
2361   // linker to resolve dynsyms at runtime. Write such code.
2362   if (HeaderSize)
2363     Target->writePltHeader(Buf);
2364   size_t Off = HeaderSize;
2365 
2366   RelocationBaseSection *RelSec = IsIplt ? In.RelaIplt : In.RelaPlt;
2367 
2368   // The IPlt is immediately after the Plt, account for this in RelOff
2369   size_t PltOff = IsIplt ? In.Plt->getSize() : 0;
2370 
2371   for (size_t I = 0, E = Entries.size(); I != E; ++I) {
2372     const Symbol *B = Entries[I];
2373     unsigned RelOff = RelSec->Entsize * I + PltOff;
2374     uint64_t Got = B->getGotPltVA();
2375     uint64_t Plt = this->getVA() + Off;
2376     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
2377     Off += Target->PltEntrySize;
2378   }
2379 }
2380 
2381 template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
2382   Sym.PltIndex = Entries.size();
2383   Entries.push_back(&Sym);
2384 }
2385 
2386 size_t PltSection::getSize() const {
2387   return HeaderSize + Entries.size() * Target->PltEntrySize;
2388 }
2389 
2390 // Some architectures such as additional symbols in the PLT section. For
2391 // example ARM uses mapping symbols to aid disassembly
2392 void PltSection::addSymbols() {
2393   // The PLT may have symbols defined for the Header, the IPLT has no header
2394   if (!IsIplt)
2395     Target->addPltHeaderSymbols(*this);
2396 
2397   size_t Off = HeaderSize;
2398   for (size_t I = 0; I < Entries.size(); ++I) {
2399     Target->addPltSymbols(*this, Off);
2400     Off += Target->PltEntrySize;
2401   }
2402 }
2403 
2404 // The string hash function for .gdb_index.
2405 static uint32_t computeGdbHash(StringRef S) {
2406   uint32_t H = 0;
2407   for (uint8_t C : S)
2408     H = H * 67 + toLower(C) - 113;
2409   return H;
2410 }
2411 
2412 GdbIndexSection::GdbIndexSection()
2413     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2414 
2415 // Returns the desired size of an on-disk hash table for a .gdb_index section.
2416 // There's a tradeoff between size and collision rate. We aim 75% utilization.
2417 size_t GdbIndexSection::computeSymtabSize() const {
2418   return std::max<size_t>(NextPowerOf2(Symbols.size() * 4 / 3), 1024);
2419 }
2420 
2421 // Compute the output section size.
2422 void GdbIndexSection::initOutputSize() {
2423   Size = sizeof(GdbIndexHeader) + computeSymtabSize() * 8;
2424 
2425   for (GdbChunk &Chunk : Chunks)
2426     Size += Chunk.CompilationUnits.size() * 16 + Chunk.AddressAreas.size() * 20;
2427 
2428   // Add the constant pool size if exists.
2429   if (!Symbols.empty()) {
2430     GdbSymbol &Sym = Symbols.back();
2431     Size += Sym.NameOff + Sym.Name.size() + 1;
2432   }
2433 }
2434 
2435 static std::vector<InputSection *> getDebugInfoSections() {
2436   std::vector<InputSection *> Ret;
2437   for (InputSectionBase *S : InputSections)
2438     if (InputSection *IS = dyn_cast<InputSection>(S))
2439       if (IS->Name == ".debug_info")
2440         Ret.push_back(IS);
2441   return Ret;
2442 }
2443 
2444 static std::vector<GdbIndexSection::CuEntry> readCuList(DWARFContext &Dwarf) {
2445   std::vector<GdbIndexSection::CuEntry> Ret;
2446   for (std::unique_ptr<DWARFUnit> &Cu : Dwarf.compile_units())
2447     Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
2448   return Ret;
2449 }
2450 
2451 static std::vector<GdbIndexSection::AddressEntry>
2452 readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
2453   std::vector<GdbIndexSection::AddressEntry> Ret;
2454 
2455   uint32_t CuIdx = 0;
2456   for (std::unique_ptr<DWARFUnit> &Cu : Dwarf.compile_units()) {
2457     Expected<DWARFAddressRangesVector> Ranges = Cu->collectAddressRanges();
2458     if (!Ranges) {
2459       error(toString(Sec) + ": " + toString(Ranges.takeError()));
2460       return {};
2461     }
2462 
2463     ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
2464     for (DWARFAddressRange &R : *Ranges) {
2465       if (R.SectionIndex == -1ULL)
2466         continue;
2467       InputSectionBase *S = Sections[R.SectionIndex];
2468       if (!S || S == &InputSection::Discarded || !S->isLive())
2469         continue;
2470       // Range list with zero size has no effect.
2471       if (R.LowPC == R.HighPC)
2472         continue;
2473       auto *IS = cast<InputSection>(S);
2474       uint64_t Offset = IS->getOffsetInFile();
2475       Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
2476     }
2477     ++CuIdx;
2478   }
2479 
2480   return Ret;
2481 }
2482 
2483 template <class ELFT>
2484 static std::vector<GdbIndexSection::NameAttrEntry>
2485 readPubNamesAndTypes(const LLDDwarfObj<ELFT> &Obj,
2486                      const std::vector<GdbIndexSection::CuEntry> &CUs) {
2487   const DWARFSection &PubNames = Obj.getGnuPubNamesSection();
2488   const DWARFSection &PubTypes = Obj.getGnuPubTypesSection();
2489 
2490   std::vector<GdbIndexSection::NameAttrEntry> Ret;
2491   for (const DWARFSection *Pub : {&PubNames, &PubTypes}) {
2492     DWARFDebugPubTable Table(Obj, *Pub, Config->IsLE, true);
2493     for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
2494       // The value written into the constant pool is Kind << 24 | CuIndex. As we
2495       // don't know how many compilation units precede this object to compute
2496       // CuIndex, we compute (Kind << 24 | CuIndexInThisObject) instead, and add
2497       // the number of preceding compilation units later.
2498       uint32_t I =
2499           lower_bound(CUs, Set.Offset,
2500                       [](GdbIndexSection::CuEntry CU, uint32_t Offset) {
2501                         return CU.CuOffset < Offset;
2502                       }) -
2503           CUs.begin();
2504       for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
2505         Ret.push_back({{Ent.Name, computeGdbHash(Ent.Name)},
2506                        (Ent.Descriptor.toBits() << 24) | I});
2507     }
2508   }
2509   return Ret;
2510 }
2511 
2512 // Create a list of symbols from a given list of symbol names and types
2513 // by uniquifying them by name.
2514 static std::vector<GdbIndexSection::GdbSymbol>
2515 createSymbols(ArrayRef<std::vector<GdbIndexSection::NameAttrEntry>> NameAttrs,
2516               const std::vector<GdbIndexSection::GdbChunk> &Chunks) {
2517   using GdbSymbol = GdbIndexSection::GdbSymbol;
2518   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
2519 
2520   // For each chunk, compute the number of compilation units preceding it.
2521   uint32_t CuIdx = 0;
2522   std::vector<uint32_t> CuIdxs(Chunks.size());
2523   for (uint32_t I = 0, E = Chunks.size(); I != E; ++I) {
2524     CuIdxs[I] = CuIdx;
2525     CuIdx += Chunks[I].CompilationUnits.size();
2526   }
2527 
2528   // The number of symbols we will handle in this function is of the order
2529   // of millions for very large executables, so we use multi-threading to
2530   // speed it up.
2531   size_t NumShards = 32;
2532   size_t Concurrency = 1;
2533   if (ThreadsEnabled)
2534     Concurrency =
2535         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
2536 
2537   // A sharded map to uniquify symbols by name.
2538   std::vector<DenseMap<CachedHashStringRef, size_t>> Map(NumShards);
2539   size_t Shift = 32 - countTrailingZeros(NumShards);
2540 
2541   // Instantiate GdbSymbols while uniqufying them by name.
2542   std::vector<std::vector<GdbSymbol>> Symbols(NumShards);
2543   parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2544     uint32_t I = 0;
2545     for (ArrayRef<NameAttrEntry> Entries : NameAttrs) {
2546       for (const NameAttrEntry &Ent : Entries) {
2547         size_t ShardId = Ent.Name.hash() >> Shift;
2548         if ((ShardId & (Concurrency - 1)) != ThreadId)
2549           continue;
2550 
2551         uint32_t V = Ent.CuIndexAndAttrs + CuIdxs[I];
2552         size_t &Idx = Map[ShardId][Ent.Name];
2553         if (Idx) {
2554           Symbols[ShardId][Idx - 1].CuVector.push_back(V);
2555           continue;
2556         }
2557 
2558         Idx = Symbols[ShardId].size() + 1;
2559         Symbols[ShardId].push_back({Ent.Name, {V}, 0, 0});
2560       }
2561       ++I;
2562     }
2563   });
2564 
2565   size_t NumSymbols = 0;
2566   for (ArrayRef<GdbSymbol> V : Symbols)
2567     NumSymbols += V.size();
2568 
2569   // The return type is a flattened vector, so we'll copy each vector
2570   // contents to Ret.
2571   std::vector<GdbSymbol> Ret;
2572   Ret.reserve(NumSymbols);
2573   for (std::vector<GdbSymbol> &Vec : Symbols)
2574     for (GdbSymbol &Sym : Vec)
2575       Ret.push_back(std::move(Sym));
2576 
2577   // CU vectors and symbol names are adjacent in the output file.
2578   // We can compute their offsets in the output file now.
2579   size_t Off = 0;
2580   for (GdbSymbol &Sym : Ret) {
2581     Sym.CuVectorOff = Off;
2582     Off += (Sym.CuVector.size() + 1) * 4;
2583   }
2584   for (GdbSymbol &Sym : Ret) {
2585     Sym.NameOff = Off;
2586     Off += Sym.Name.size() + 1;
2587   }
2588 
2589   return Ret;
2590 }
2591 
2592 // Returns a newly-created .gdb_index section.
2593 template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
2594   std::vector<InputSection *> Sections = getDebugInfoSections();
2595 
2596   // .debug_gnu_pub{names,types} are useless in executables.
2597   // They are present in input object files solely for creating
2598   // a .gdb_index. So we can remove them from the output.
2599   for (InputSectionBase *S : InputSections)
2600     if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2601       S->markDead();
2602 
2603   std::vector<GdbChunk> Chunks(Sections.size());
2604   std::vector<std::vector<NameAttrEntry>> NameAttrs(Sections.size());
2605 
2606   parallelForEachN(0, Sections.size(), [&](size_t I) {
2607     ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2608     DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2609 
2610     Chunks[I].Sec = Sections[I];
2611     Chunks[I].CompilationUnits = readCuList(Dwarf);
2612     Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2613     NameAttrs[I] = readPubNamesAndTypes<ELFT>(
2614         static_cast<const LLDDwarfObj<ELFT> &>(Dwarf.getDWARFObj()),
2615         Chunks[I].CompilationUnits);
2616   });
2617 
2618   auto *Ret = make<GdbIndexSection>();
2619   Ret->Chunks = std::move(Chunks);
2620   Ret->Symbols = createSymbols(NameAttrs, Ret->Chunks);
2621   Ret->initOutputSize();
2622   return Ret;
2623 }
2624 
2625 void GdbIndexSection::writeTo(uint8_t *Buf) {
2626   // Write the header.
2627   auto *Hdr = reinterpret_cast<GdbIndexHeader *>(Buf);
2628   uint8_t *Start = Buf;
2629   Hdr->Version = 7;
2630   Buf += sizeof(*Hdr);
2631 
2632   // Write the CU list.
2633   Hdr->CuListOff = Buf - Start;
2634   for (GdbChunk &Chunk : Chunks) {
2635     for (CuEntry &Cu : Chunk.CompilationUnits) {
2636       write64le(Buf, Chunk.Sec->OutSecOff + Cu.CuOffset);
2637       write64le(Buf + 8, Cu.CuLength);
2638       Buf += 16;
2639     }
2640   }
2641 
2642   // Write the address area.
2643   Hdr->CuTypesOff = Buf - Start;
2644   Hdr->AddressAreaOff = Buf - Start;
2645   uint32_t CuOff = 0;
2646   for (GdbChunk &Chunk : Chunks) {
2647     for (AddressEntry &E : Chunk.AddressAreas) {
2648       uint64_t BaseAddr = E.Section->getVA(0);
2649       write64le(Buf, BaseAddr + E.LowAddress);
2650       write64le(Buf + 8, BaseAddr + E.HighAddress);
2651       write32le(Buf + 16, E.CuIndex + CuOff);
2652       Buf += 20;
2653     }
2654     CuOff += Chunk.CompilationUnits.size();
2655   }
2656 
2657   // Write the on-disk open-addressing hash table containing symbols.
2658   Hdr->SymtabOff = Buf - Start;
2659   size_t SymtabSize = computeSymtabSize();
2660   uint32_t Mask = SymtabSize - 1;
2661 
2662   for (GdbSymbol &Sym : Symbols) {
2663     uint32_t H = Sym.Name.hash();
2664     uint32_t I = H & Mask;
2665     uint32_t Step = ((H * 17) & Mask) | 1;
2666 
2667     while (read32le(Buf + I * 8))
2668       I = (I + Step) & Mask;
2669 
2670     write32le(Buf + I * 8, Sym.NameOff);
2671     write32le(Buf + I * 8 + 4, Sym.CuVectorOff);
2672   }
2673 
2674   Buf += SymtabSize * 8;
2675 
2676   // Write the string pool.
2677   Hdr->ConstantPoolOff = Buf - Start;
2678   parallelForEach(Symbols, [&](GdbSymbol &Sym) {
2679     memcpy(Buf + Sym.NameOff, Sym.Name.data(), Sym.Name.size());
2680   });
2681 
2682   // Write the CU vectors.
2683   for (GdbSymbol &Sym : Symbols) {
2684     write32le(Buf, Sym.CuVector.size());
2685     Buf += 4;
2686     for (uint32_t Val : Sym.CuVector) {
2687       write32le(Buf, Val);
2688       Buf += 4;
2689     }
2690   }
2691 }
2692 
2693 bool GdbIndexSection::isNeeded() const { return !Chunks.empty(); }
2694 
2695 EhFrameHeader::EhFrameHeader()
2696     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
2697 
2698 void EhFrameHeader::writeTo(uint8_t *Buf) {
2699   // Unlike most sections, the EhFrameHeader section is written while writing
2700   // another section, namely EhFrameSection, which calls the write() function
2701   // below from its writeTo() function. This is necessary because the contents
2702   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
2703   // don't know which order the sections will be written in.
2704 }
2705 
2706 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2707 // Each entry of the search table consists of two values,
2708 // the starting PC from where FDEs covers, and the FDE's address.
2709 // It is sorted by PC.
2710 void EhFrameHeader::write() {
2711   uint8_t *Buf = Out::BufferStart + getParent()->Offset + OutSecOff;
2712   using FdeData = EhFrameSection::FdeData;
2713 
2714   std::vector<FdeData> Fdes = getPartition().EhFrame->getFdeData();
2715 
2716   Buf[0] = 1;
2717   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2718   Buf[2] = DW_EH_PE_udata4;
2719   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2720   write32(Buf + 4,
2721           getPartition().EhFrame->getParent()->Addr - this->getVA() - 4);
2722   write32(Buf + 8, Fdes.size());
2723   Buf += 12;
2724 
2725   for (FdeData &Fde : Fdes) {
2726     write32(Buf, Fde.PcRel);
2727     write32(Buf + 4, Fde.FdeVARel);
2728     Buf += 8;
2729   }
2730 }
2731 
2732 size_t EhFrameHeader::getSize() const {
2733   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
2734   return 12 + getPartition().EhFrame->NumFdes * 8;
2735 }
2736 
2737 bool EhFrameHeader::isNeeded() const {
2738   return isLive() && getPartition().EhFrame->isNeeded();
2739 }
2740 
2741 VersionDefinitionSection::VersionDefinitionSection()
2742     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2743                        ".gnu.version_d") {}
2744 
2745 StringRef VersionDefinitionSection::getFileDefName() {
2746   if (!getPartition().Name.empty())
2747     return getPartition().Name;
2748   if (!Config->SoName.empty())
2749     return Config->SoName;
2750   return Config->OutputFile;
2751 }
2752 
2753 void VersionDefinitionSection::finalizeContents() {
2754   FileDefNameOff = getPartition().DynStrTab->addString(getFileDefName());
2755   for (VersionDefinition &V : Config->VersionDefinitions)
2756     VerDefNameOffs.push_back(getPartition().DynStrTab->addString(V.Name));
2757 
2758   if (OutputSection *Sec = getPartition().DynStrTab->getParent())
2759     getParent()->Link = Sec->SectionIndex;
2760 
2761   // sh_info should be set to the number of definitions. This fact is missed in
2762   // documentation, but confirmed by binutils community:
2763   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
2764   getParent()->Info = getVerDefNum();
2765 }
2766 
2767 void VersionDefinitionSection::writeOne(uint8_t *Buf, uint32_t Index,
2768                                         StringRef Name, size_t NameOff) {
2769   uint16_t Flags = Index == 1 ? VER_FLG_BASE : 0;
2770 
2771   // Write a verdef.
2772   write16(Buf, 1);                  // vd_version
2773   write16(Buf + 2, Flags);          // vd_flags
2774   write16(Buf + 4, Index);          // vd_ndx
2775   write16(Buf + 6, 1);              // vd_cnt
2776   write32(Buf + 8, hashSysV(Name)); // vd_hash
2777   write32(Buf + 12, 20);            // vd_aux
2778   write32(Buf + 16, 28);            // vd_next
2779 
2780   // Write a veraux.
2781   write32(Buf + 20, NameOff); // vda_name
2782   write32(Buf + 24, 0);       // vda_next
2783 }
2784 
2785 void VersionDefinitionSection::writeTo(uint8_t *Buf) {
2786   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2787 
2788   auto NameOffIt = VerDefNameOffs.begin();
2789   for (VersionDefinition &V : Config->VersionDefinitions) {
2790     Buf += EntrySize;
2791     writeOne(Buf, V.Id, V.Name, *NameOffIt++);
2792   }
2793 
2794   // Need to terminate the last version definition.
2795   write32(Buf + 16, 0); // vd_next
2796 }
2797 
2798 size_t VersionDefinitionSection::getSize() const {
2799   return EntrySize * getVerDefNum();
2800 }
2801 
2802 // .gnu.version is a table where each entry is 2 byte long.
2803 VersionTableSection::VersionTableSection()
2804     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
2805                        ".gnu.version") {
2806   this->Entsize = 2;
2807 }
2808 
2809 void VersionTableSection::finalizeContents() {
2810   // At the moment of june 2016 GNU docs does not mention that sh_link field
2811   // should be set, but Sun docs do. Also readelf relies on this field.
2812   getParent()->Link = getPartition().DynSymTab->getParent()->SectionIndex;
2813 }
2814 
2815 size_t VersionTableSection::getSize() const {
2816   return (getPartition().DynSymTab->getSymbols().size() + 1) * 2;
2817 }
2818 
2819 void VersionTableSection::writeTo(uint8_t *Buf) {
2820   Buf += 2;
2821   for (const SymbolTableEntry &S : getPartition().DynSymTab->getSymbols()) {
2822     write16(Buf, S.Sym->VersionId);
2823     Buf += 2;
2824   }
2825 }
2826 
2827 bool VersionTableSection::isNeeded() const {
2828   return getPartition().VerDef || getPartition().VerNeed->isNeeded();
2829 }
2830 
2831 void elf::addVerneed(Symbol *SS) {
2832   auto &File = cast<SharedFile>(*SS->File);
2833   if (SS->VerdefIndex == VER_NDX_GLOBAL) {
2834     SS->VersionId = VER_NDX_GLOBAL;
2835     return;
2836   }
2837 
2838   if (File.Vernauxs.empty())
2839     File.Vernauxs.resize(File.Verdefs.size());
2840 
2841   // Select a version identifier for the vernaux data structure, if we haven't
2842   // already allocated one. The verdef identifiers cover the range
2843   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
2844   // getVerDefNum()+1.
2845   if (File.Vernauxs[SS->VerdefIndex] == 0)
2846     File.Vernauxs[SS->VerdefIndex] = ++SharedFile::VernauxNum + getVerDefNum();
2847 
2848   SS->VersionId = File.Vernauxs[SS->VerdefIndex];
2849 }
2850 
2851 template <class ELFT>
2852 VersionNeedSection<ELFT>::VersionNeedSection()
2853     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2854                        ".gnu.version_r") {}
2855 
2856 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2857   for (SharedFile *F : SharedFiles) {
2858     if (F->Vernauxs.empty())
2859       continue;
2860     Verneeds.emplace_back();
2861     Verneed &VN = Verneeds.back();
2862     VN.NameStrTab = getPartition().DynStrTab->addString(F->SoName);
2863     for (unsigned I = 0; I != F->Vernauxs.size(); ++I) {
2864       if (F->Vernauxs[I] == 0)
2865         continue;
2866       auto *Verdef =
2867           reinterpret_cast<const typename ELFT::Verdef *>(F->Verdefs[I]);
2868       VN.Vernauxs.push_back(
2869           {Verdef->vd_hash, F->Vernauxs[I],
2870            getPartition().DynStrTab->addString(F->getStringTable().data() +
2871                                                Verdef->getAux()->vda_name)});
2872     }
2873   }
2874 
2875   if (OutputSection *Sec = getPartition().DynStrTab->getParent())
2876     getParent()->Link = Sec->SectionIndex;
2877   getParent()->Info = Verneeds.size();
2878 }
2879 
2880 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2881   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2882   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2883   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Verneeds.size());
2884 
2885   for (auto &VN : Verneeds) {
2886     // Create an Elf_Verneed for this DSO.
2887     Verneed->vn_version = 1;
2888     Verneed->vn_cnt = VN.Vernauxs.size();
2889     Verneed->vn_file = VN.NameStrTab;
2890     Verneed->vn_aux =
2891         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2892     Verneed->vn_next = sizeof(Elf_Verneed);
2893     ++Verneed;
2894 
2895     // Create the Elf_Vernauxs for this Elf_Verneed.
2896     for (auto &VNA : VN.Vernauxs) {
2897       Vernaux->vna_hash = VNA.Hash;
2898       Vernaux->vna_flags = 0;
2899       Vernaux->vna_other = VNA.VerneedIndex;
2900       Vernaux->vna_name = VNA.NameStrTab;
2901       Vernaux->vna_next = sizeof(Elf_Vernaux);
2902       ++Vernaux;
2903     }
2904 
2905     Vernaux[-1].vna_next = 0;
2906   }
2907   Verneed[-1].vn_next = 0;
2908 }
2909 
2910 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2911   return Verneeds.size() * sizeof(Elf_Verneed) +
2912          SharedFile::VernauxNum * sizeof(Elf_Vernaux);
2913 }
2914 
2915 template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
2916   return SharedFile::VernauxNum != 0;
2917 }
2918 
2919 void MergeSyntheticSection::addSection(MergeInputSection *MS) {
2920   MS->Parent = this;
2921   Sections.push_back(MS);
2922 }
2923 
2924 MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2925                                    uint64_t Flags, uint32_t Alignment)
2926     : MergeSyntheticSection(Name, Type, Flags, Alignment),
2927       Builder(StringTableBuilder::RAW, Alignment) {}
2928 
2929 size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2930 
2931 void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
2932 
2933 void MergeTailSection::finalizeContents() {
2934   // Add all string pieces to the string table builder to create section
2935   // contents.
2936   for (MergeInputSection *Sec : Sections)
2937     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2938       if (Sec->Pieces[I].Live)
2939         Builder.add(Sec->getData(I));
2940 
2941   // Fix the string table content. After this, the contents will never change.
2942   Builder.finalize();
2943 
2944   // finalize() fixed tail-optimized strings, so we can now get
2945   // offsets of strings. Get an offset for each string and save it
2946   // to a corresponding StringPiece for easy access.
2947   for (MergeInputSection *Sec : Sections)
2948     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2949       if (Sec->Pieces[I].Live)
2950         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2951 }
2952 
2953 void MergeNoTailSection::writeTo(uint8_t *Buf) {
2954   for (size_t I = 0; I < NumShards; ++I)
2955     Shards[I].write(Buf + ShardOffsets[I]);
2956 }
2957 
2958 // This function is very hot (i.e. it can take several seconds to finish)
2959 // because sometimes the number of inputs is in an order of magnitude of
2960 // millions. So, we use multi-threading.
2961 //
2962 // For any strings S and T, we know S is not mergeable with T if S's hash
2963 // value is different from T's. If that's the case, we can safely put S and
2964 // T into different string builders without worrying about merge misses.
2965 // We do it in parallel.
2966 void MergeNoTailSection::finalizeContents() {
2967   // Initializes string table builders.
2968   for (size_t I = 0; I < NumShards; ++I)
2969     Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2970 
2971   // Concurrency level. Must be a power of 2 to avoid expensive modulo
2972   // operations in the following tight loop.
2973   size_t Concurrency = 1;
2974   if (ThreadsEnabled)
2975     Concurrency =
2976         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
2977 
2978   // Add section pieces to the builders.
2979   parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2980     for (MergeInputSection *Sec : Sections) {
2981       for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2982         if (!Sec->Pieces[I].Live)
2983           continue;
2984         size_t ShardId = getShardId(Sec->Pieces[I].Hash);
2985         if ((ShardId & (Concurrency - 1)) == ThreadId)
2986           Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
2987       }
2988     }
2989   });
2990 
2991   // Compute an in-section offset for each shard.
2992   size_t Off = 0;
2993   for (size_t I = 0; I < NumShards; ++I) {
2994     Shards[I].finalizeInOrder();
2995     if (Shards[I].getSize() > 0)
2996       Off = alignTo(Off, Alignment);
2997     ShardOffsets[I] = Off;
2998     Off += Shards[I].getSize();
2999   }
3000   Size = Off;
3001 
3002   // So far, section pieces have offsets from beginning of shards, but
3003   // we want offsets from beginning of the whole section. Fix them.
3004   parallelForEach(Sections, [&](MergeInputSection *Sec) {
3005     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
3006       if (Sec->Pieces[I].Live)
3007         Sec->Pieces[I].OutputOff +=
3008             ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
3009   });
3010 }
3011 
3012 static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
3013                                                    uint32_t Type,
3014                                                    uint64_t Flags,
3015                                                    uint32_t Alignment) {
3016   bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
3017   if (ShouldTailMerge)
3018     return make<MergeTailSection>(Name, Type, Flags, Alignment);
3019   return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
3020 }
3021 
3022 template <class ELFT> void elf::splitSections() {
3023   // splitIntoPieces needs to be called on each MergeInputSection
3024   // before calling finalizeContents().
3025   parallelForEach(InputSections, [](InputSectionBase *Sec) {
3026     if (auto *S = dyn_cast<MergeInputSection>(Sec))
3027       S->splitIntoPieces();
3028     else if (auto *Eh = dyn_cast<EhInputSection>(Sec))
3029       Eh->split<ELFT>();
3030   });
3031 }
3032 
3033 // This function scans over the inputsections to create mergeable
3034 // synthetic sections.
3035 //
3036 // It removes MergeInputSections from the input section array and adds
3037 // new synthetic sections at the location of the first input section
3038 // that it replaces. It then finalizes each synthetic section in order
3039 // to compute an output offset for each piece of each input section.
3040 void elf::mergeSections() {
3041   std::vector<MergeSyntheticSection *> MergeSections;
3042   for (InputSectionBase *&S : InputSections) {
3043     MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
3044     if (!MS)
3045       continue;
3046 
3047     // We do not want to handle sections that are not alive, so just remove
3048     // them instead of trying to merge.
3049     if (!MS->isLive()) {
3050       S = nullptr;
3051       continue;
3052     }
3053 
3054     StringRef OutsecName = getOutputSectionName(MS);
3055 
3056     auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
3057       // While we could create a single synthetic section for two different
3058       // values of Entsize, it is better to take Entsize into consideration.
3059       //
3060       // With a single synthetic section no two pieces with different Entsize
3061       // could be equal, so we may as well have two sections.
3062       //
3063       // Using Entsize in here also allows us to propagate it to the synthetic
3064       // section.
3065       return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
3066              Sec->Entsize == MS->Entsize && Sec->Alignment == MS->Alignment;
3067     });
3068     if (I == MergeSections.end()) {
3069       MergeSyntheticSection *Syn =
3070           createMergeSynthetic(OutsecName, MS->Type, MS->Flags, MS->Alignment);
3071       MergeSections.push_back(Syn);
3072       I = std::prev(MergeSections.end());
3073       S = Syn;
3074       Syn->Entsize = MS->Entsize;
3075     } else {
3076       S = nullptr;
3077     }
3078     (*I)->addSection(MS);
3079   }
3080   for (auto *MS : MergeSections)
3081     MS->finalizeContents();
3082 
3083   std::vector<InputSectionBase *> &V = InputSections;
3084   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
3085 }
3086 
3087 MipsRldMapSection::MipsRldMapSection()
3088     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
3089                        ".rld_map") {}
3090 
3091 ARMExidxSyntheticSection::ARMExidxSyntheticSection()
3092     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
3093                        Config->Wordsize, ".ARM.exidx") {}
3094 
3095 static InputSection *findExidxSection(InputSection *IS) {
3096   for (InputSection *D : IS->DependentSections)
3097     if (D->Type == SHT_ARM_EXIDX)
3098       return D;
3099   return nullptr;
3100 }
3101 
3102 bool ARMExidxSyntheticSection::addSection(InputSection *IS) {
3103   if (IS->Type == SHT_ARM_EXIDX) {
3104     ExidxSections.push_back(IS);
3105     return true;
3106   }
3107 
3108   if ((IS->Flags & SHF_ALLOC) && (IS->Flags & SHF_EXECINSTR) &&
3109       IS->getSize() > 0) {
3110     ExecutableSections.push_back(IS);
3111     if (Empty && findExidxSection(IS))
3112       Empty = false;
3113     return false;
3114   }
3115 
3116   // FIXME: we do not output a relocation section when --emit-relocs is used
3117   // as we do not have relocation sections for linker generated table entries
3118   // and we would have to erase at a late stage relocations from merged entries.
3119   // Given that exception tables are already position independent and a binary
3120   // analyzer could derive the relocations we choose to erase the relocations.
3121   if (Config->EmitRelocs && IS->Type == SHT_REL)
3122     if (InputSectionBase *EX = IS->getRelocatedSection())
3123       if (isa<InputSection>(EX) && EX->Type == SHT_ARM_EXIDX)
3124         return true;
3125 
3126   return false;
3127 }
3128 
3129 // References to .ARM.Extab Sections have bit 31 clear and are not the
3130 // special EXIDX_CANTUNWIND bit-pattern.
3131 static bool isExtabRef(uint32_t Unwind) {
3132   return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
3133 }
3134 
3135 // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
3136 // section Prev, where Cur follows Prev in the table. This can be done if the
3137 // unwinding instructions in Cur are identical to Prev. Linker generated
3138 // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
3139 // InputSection.
3140 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
3141 
3142   struct ExidxEntry {
3143     ulittle32_t Fn;
3144     ulittle32_t Unwind;
3145   };
3146   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
3147   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
3148   ExidxEntry PrevEntry = {ulittle32_t(0), ulittle32_t(1)};
3149   if (Prev)
3150     PrevEntry = Prev->getDataAs<ExidxEntry>().back();
3151   if (isExtabRef(PrevEntry.Unwind))
3152     return false;
3153 
3154   // We consider the unwind instructions of an .ARM.exidx table entry
3155   // a duplicate if the previous unwind instructions if:
3156   // - Both are the special EXIDX_CANTUNWIND.
3157   // - Both are the same inline unwind instructions.
3158   // We do not attempt to follow and check links into .ARM.extab tables as
3159   // consecutive identical entries are rare and the effort to check that they
3160   // are identical is high.
3161 
3162   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
3163   if (Cur == nullptr)
3164     return PrevEntry.Unwind == 1;
3165 
3166   for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>())
3167     if (isExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
3168       return false;
3169 
3170   // All table entries in this .ARM.exidx Section can be merged into the
3171   // previous Section.
3172   return true;
3173 }
3174 
3175 // The .ARM.exidx table must be sorted in ascending order of the address of the
3176 // functions the table describes. Optionally duplicate adjacent table entries
3177 // can be removed. At the end of the function the ExecutableSections must be
3178 // sorted in ascending order of address, Sentinel is set to the InputSection
3179 // with the highest address and any InputSections that have mergeable
3180 // .ARM.exidx table entries are removed from it.
3181 void ARMExidxSyntheticSection::finalizeContents() {
3182   // Sort the executable sections that may or may not have associated
3183   // .ARM.exidx sections by order of ascending address. This requires the
3184   // relative positions of InputSections to be known.
3185   auto CompareByFilePosition = [](const InputSection *A,
3186                                   const InputSection *B) {
3187     OutputSection *AOut = A->getParent();
3188     OutputSection *BOut = B->getParent();
3189 
3190     if (AOut != BOut)
3191       return AOut->SectionIndex < BOut->SectionIndex;
3192     return A->OutSecOff < B->OutSecOff;
3193   };
3194   llvm::stable_sort(ExecutableSections, CompareByFilePosition);
3195   Sentinel = ExecutableSections.back();
3196   // Optionally merge adjacent duplicate entries.
3197   if (Config->MergeArmExidx) {
3198     std::vector<InputSection *> SelectedSections;
3199     SelectedSections.reserve(ExecutableSections.size());
3200     SelectedSections.push_back(ExecutableSections[0]);
3201     size_t Prev = 0;
3202     for (size_t I = 1; I < ExecutableSections.size(); ++I) {
3203       InputSection *EX1 = findExidxSection(ExecutableSections[Prev]);
3204       InputSection *EX2 = findExidxSection(ExecutableSections[I]);
3205       if (!isDuplicateArmExidxSec(EX1, EX2)) {
3206         SelectedSections.push_back(ExecutableSections[I]);
3207         Prev = I;
3208       }
3209     }
3210     ExecutableSections = std::move(SelectedSections);
3211   }
3212 
3213   size_t Offset = 0;
3214   Size = 0;
3215   for (InputSection *IS : ExecutableSections) {
3216     if (InputSection *D = findExidxSection(IS)) {
3217       D->OutSecOff = Offset;
3218       D->Parent = getParent();
3219       Offset += D->getSize();
3220     } else {
3221       Offset += 8;
3222     }
3223   }
3224   // Size includes Sentinel.
3225   Size = Offset + 8;
3226 }
3227 
3228 InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
3229   return ExecutableSections.front();
3230 }
3231 
3232 // To write the .ARM.exidx table from the ExecutableSections we have three cases
3233 // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
3234 //     We write the .ARM.exidx section contents and apply its relocations.
3235 // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
3236 //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
3237 //     start of the InputSection as the purpose of the linker generated
3238 //     section is to terminate the address range of the previous entry.
3239 // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
3240 //     the table to terminate the address range of the final entry.
3241 void ARMExidxSyntheticSection::writeTo(uint8_t *Buf) {
3242 
3243   const uint8_t CantUnwindData[8] = {0, 0, 0, 0,  // PREL31 to target
3244                                      1, 0, 0, 0}; // EXIDX_CANTUNWIND
3245 
3246   uint64_t Offset = 0;
3247   for (InputSection *IS : ExecutableSections) {
3248     assert(IS->getParent() != nullptr);
3249     if (InputSection *D = findExidxSection(IS)) {
3250       memcpy(Buf + Offset, D->data().data(), D->data().size());
3251       D->relocateAlloc(Buf, Buf + D->getSize());
3252       Offset += D->getSize();
3253     } else {
3254       // A Linker generated CANTUNWIND section.
3255       memcpy(Buf + Offset, CantUnwindData, sizeof(CantUnwindData));
3256       uint64_t S = IS->getVA();
3257       uint64_t P = getVA() + Offset;
3258       Target->relocateOne(Buf + Offset, R_ARM_PREL31, S - P);
3259       Offset += 8;
3260     }
3261   }
3262   // Write Sentinel.
3263   memcpy(Buf + Offset, CantUnwindData, sizeof(CantUnwindData));
3264   uint64_t S = Sentinel->getVA(Sentinel->getSize());
3265   uint64_t P = getVA() + Offset;
3266   Target->relocateOne(Buf + Offset, R_ARM_PREL31, S - P);
3267   assert(Size == Offset + 8);
3268 }
3269 
3270 bool ARMExidxSyntheticSection::classof(const SectionBase *D) {
3271   return D->kind() == InputSectionBase::Synthetic && D->Type == SHT_ARM_EXIDX;
3272 }
3273 
3274 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
3275     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
3276                        Config->Wordsize, ".text.thunk") {
3277   this->Parent = OS;
3278   this->OutSecOff = Off;
3279 }
3280 
3281 void ThunkSection::addThunk(Thunk *T) {
3282   Thunks.push_back(T);
3283   T->addSymbols(*this);
3284 }
3285 
3286 void ThunkSection::writeTo(uint8_t *Buf) {
3287   for (Thunk *T : Thunks)
3288     T->writeTo(Buf + T->Offset);
3289 }
3290 
3291 InputSection *ThunkSection::getTargetInputSection() const {
3292   if (Thunks.empty())
3293     return nullptr;
3294   const Thunk *T = Thunks.front();
3295   return T->getTargetInputSection();
3296 }
3297 
3298 bool ThunkSection::assignOffsets() {
3299   uint64_t Off = 0;
3300   for (Thunk *T : Thunks) {
3301     Off = alignTo(Off, T->Alignment);
3302     T->setOffset(Off);
3303     uint32_t Size = T->size();
3304     T->getThunkTargetSym()->Size = Size;
3305     Off += Size;
3306   }
3307   bool Changed = Off != Size;
3308   Size = Off;
3309   return Changed;
3310 }
3311 
3312 PPC32Got2Section::PPC32Got2Section()
3313     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
3314 
3315 bool PPC32Got2Section::isNeeded() const {
3316   // See the comment below. This is not needed if there is no other
3317   // InputSection.
3318   for (BaseCommand *Base : getParent()->SectionCommands)
3319     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
3320       for (InputSection *IS : ISD->Sections)
3321         if (IS != this)
3322           return true;
3323   return false;
3324 }
3325 
3326 void PPC32Got2Section::finalizeContents() {
3327   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
3328   // .got2 . This function computes OutSecOff of each .got2 to be used in
3329   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
3330   // to collect input sections named ".got2".
3331   uint32_t Offset = 0;
3332   for (BaseCommand *Base : getParent()->SectionCommands)
3333     if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
3334       for (InputSection *IS : ISD->Sections) {
3335         if (IS == this)
3336           continue;
3337         IS->File->PPC32Got2OutSecOff = Offset;
3338         Offset += (uint32_t)IS->getSize();
3339       }
3340     }
3341 }
3342 
3343 // If linking position-dependent code then the table will store the addresses
3344 // directly in the binary so the section has type SHT_PROGBITS. If linking
3345 // position-independent code the section has type SHT_NOBITS since it will be
3346 // allocated and filled in by the dynamic linker.
3347 PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
3348     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
3349                        Config->Pic ? SHT_NOBITS : SHT_PROGBITS, 8,
3350                        ".branch_lt") {}
3351 
3352 void PPC64LongBranchTargetSection::addEntry(Symbol &Sym) {
3353   assert(Sym.PPC64BranchltIndex == 0xffff);
3354   Sym.PPC64BranchltIndex = Entries.size();
3355   Entries.push_back(&Sym);
3356 }
3357 
3358 size_t PPC64LongBranchTargetSection::getSize() const {
3359   return Entries.size() * 8;
3360 }
3361 
3362 void PPC64LongBranchTargetSection::writeTo(uint8_t *Buf) {
3363   // If linking non-pic we have the final addresses of the targets and they get
3364   // written to the table directly. For pic the dynamic linker will allocate
3365   // the section and fill it it.
3366   if (Config->Pic)
3367     return;
3368 
3369   for (const Symbol *Sym : Entries) {
3370     assert(Sym->getVA());
3371     // Need calls to branch to the local entry-point since a long-branch
3372     // must be a local-call.
3373     write64(Buf,
3374             Sym->getVA() + getPPC64GlobalEntryToLocalEntryOffset(Sym->StOther));
3375     Buf += 8;
3376   }
3377 }
3378 
3379 bool PPC64LongBranchTargetSection::isNeeded() const {
3380   // `removeUnusedSyntheticSections()` is called before thunk allocation which
3381   // is too early to determine if this section will be empty or not. We need
3382   // Finalized to keep the section alive until after thunk creation. Finalized
3383   // only gets set to true once `finalizeSections()` is called after thunk
3384   // creation. Becuase of this, if we don't create any long-branch thunks we end
3385   // up with an empty .branch_lt section in the binary.
3386   return !Finalized || !Entries.empty();
3387 }
3388 
3389 RISCVSdataSection::RISCVSdataSection()
3390     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1, ".sdata") {}
3391 
3392 bool RISCVSdataSection::isNeeded() const {
3393   if (!ElfSym::RISCVGlobalPointer)
3394     return false;
3395 
3396   // __global_pointer$ is defined relative to .sdata . If the section does not
3397   // exist, create a dummy one.
3398   for (BaseCommand *Base : getParent()->SectionCommands)
3399     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
3400       for (InputSection *IS : ISD->Sections)
3401         if (IS != this)
3402           return false;
3403   return true;
3404 }
3405 
3406 static uint8_t getAbiVersion() {
3407   // MIPS non-PIC executable gets ABI version 1.
3408   if (Config->EMachine == EM_MIPS) {
3409     if (!Config->Pic && !Config->Relocatable &&
3410         (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
3411       return 1;
3412     return 0;
3413   }
3414 
3415   if (Config->EMachine == EM_AMDGPU) {
3416     uint8_t Ver = ObjectFiles[0]->ABIVersion;
3417     for (InputFile *File : makeArrayRef(ObjectFiles).slice(1))
3418       if (File->ABIVersion != Ver)
3419         error("incompatible ABI version: " + toString(File));
3420     return Ver;
3421   }
3422 
3423   return 0;
3424 }
3425 
3426 template <typename ELFT> void elf::writeEhdr(uint8_t *Buf, Partition &Part) {
3427   // For executable segments, the trap instructions are written before writing
3428   // the header. Setting Elf header bytes to zero ensures that any unused bytes
3429   // in header are zero-cleared, instead of having trap instructions.
3430   memset(Buf, 0, sizeof(typename ELFT::Ehdr));
3431   memcpy(Buf, "\177ELF", 4);
3432 
3433   auto *EHdr = reinterpret_cast<typename ELFT::Ehdr *>(Buf);
3434   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
3435   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
3436   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
3437   EHdr->e_ident[EI_OSABI] = Config->OSABI;
3438   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
3439   EHdr->e_machine = Config->EMachine;
3440   EHdr->e_version = EV_CURRENT;
3441   EHdr->e_flags = Config->EFlags;
3442   EHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
3443   EHdr->e_phnum = Part.Phdrs.size();
3444   EHdr->e_shentsize = sizeof(typename ELFT::Shdr);
3445 
3446   if (!Config->Relocatable) {
3447     EHdr->e_phoff = sizeof(typename ELFT::Ehdr);
3448     EHdr->e_phentsize = sizeof(typename ELFT::Phdr);
3449   }
3450 }
3451 
3452 template <typename ELFT> void elf::writePhdrs(uint8_t *Buf, Partition &Part) {
3453   // Write the program header table.
3454   auto *HBuf = reinterpret_cast<typename ELFT::Phdr *>(Buf);
3455   for (PhdrEntry *P : Part.Phdrs) {
3456     HBuf->p_type = P->p_type;
3457     HBuf->p_flags = P->p_flags;
3458     HBuf->p_offset = P->p_offset;
3459     HBuf->p_vaddr = P->p_vaddr;
3460     HBuf->p_paddr = P->p_paddr;
3461     HBuf->p_filesz = P->p_filesz;
3462     HBuf->p_memsz = P->p_memsz;
3463     HBuf->p_align = P->p_align;
3464     ++HBuf;
3465   }
3466 }
3467 
3468 template <typename ELFT>
3469 PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
3470     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
3471 
3472 template <typename ELFT>
3473 size_t PartitionElfHeaderSection<ELFT>::getSize() const {
3474   return sizeof(typename ELFT::Ehdr);
3475 }
3476 
3477 template <typename ELFT>
3478 void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *Buf) {
3479   writeEhdr<ELFT>(Buf, getPartition());
3480 
3481   // Loadable partitions are always ET_DYN.
3482   auto *EHdr = reinterpret_cast<typename ELFT::Ehdr *>(Buf);
3483   EHdr->e_type = ET_DYN;
3484 }
3485 
3486 template <typename ELFT>
3487 PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
3488     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
3489 
3490 template <typename ELFT>
3491 size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
3492   return sizeof(typename ELFT::Phdr) * getPartition().Phdrs.size();
3493 }
3494 
3495 template <typename ELFT>
3496 void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *Buf) {
3497   writePhdrs<ELFT>(Buf, getPartition());
3498 }
3499 
3500 PartitionIndexSection::PartitionIndexSection()
3501     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
3502 
3503 size_t PartitionIndexSection::getSize() const {
3504   return 12 * (Partitions.size() - 1);
3505 }
3506 
3507 void PartitionIndexSection::finalizeContents() {
3508   for (size_t I = 1; I != Partitions.size(); ++I)
3509     Partitions[I].NameStrTab = Main->DynStrTab->addString(Partitions[I].Name);
3510 }
3511 
3512 void PartitionIndexSection::writeTo(uint8_t *Buf) {
3513   uint64_t VA = getVA();
3514   for (size_t I = 1; I != Partitions.size(); ++I) {
3515     write32(Buf, Main->DynStrTab->getVA() + Partitions[I].NameStrTab - VA);
3516     write32(Buf + 4, Partitions[I].ElfHeader->getVA() - (VA + 4));
3517 
3518     SyntheticSection *Next =
3519         I == Partitions.size() - 1 ? In.PartEnd : Partitions[I + 1].ElfHeader;
3520     write32(Buf + 8, Next->getVA() - Partitions[I].ElfHeader->getVA());
3521 
3522     VA += 12;
3523     Buf += 12;
3524   }
3525 }
3526 
3527 InStruct elf::In;
3528 
3529 std::vector<Partition> elf::Partitions;
3530 Partition *elf::Main;
3531 
3532 template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3533 template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3534 template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3535 template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3536 
3537 template void elf::splitSections<ELF32LE>();
3538 template void elf::splitSections<ELF32BE>();
3539 template void elf::splitSections<ELF64LE>();
3540 template void elf::splitSections<ELF64BE>();
3541 
3542 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
3543 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
3544 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
3545 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
3546 
3547 template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
3548 template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
3549 template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
3550 template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
3551 
3552 template class elf::MipsAbiFlagsSection<ELF32LE>;
3553 template class elf::MipsAbiFlagsSection<ELF32BE>;
3554 template class elf::MipsAbiFlagsSection<ELF64LE>;
3555 template class elf::MipsAbiFlagsSection<ELF64BE>;
3556 
3557 template class elf::MipsOptionsSection<ELF32LE>;
3558 template class elf::MipsOptionsSection<ELF32BE>;
3559 template class elf::MipsOptionsSection<ELF64LE>;
3560 template class elf::MipsOptionsSection<ELF64BE>;
3561 
3562 template class elf::MipsReginfoSection<ELF32LE>;
3563 template class elf::MipsReginfoSection<ELF32BE>;
3564 template class elf::MipsReginfoSection<ELF64LE>;
3565 template class elf::MipsReginfoSection<ELF64BE>;
3566 
3567 template class elf::DynamicSection<ELF32LE>;
3568 template class elf::DynamicSection<ELF32BE>;
3569 template class elf::DynamicSection<ELF64LE>;
3570 template class elf::DynamicSection<ELF64BE>;
3571 
3572 template class elf::RelocationSection<ELF32LE>;
3573 template class elf::RelocationSection<ELF32BE>;
3574 template class elf::RelocationSection<ELF64LE>;
3575 template class elf::RelocationSection<ELF64BE>;
3576 
3577 template class elf::AndroidPackedRelocationSection<ELF32LE>;
3578 template class elf::AndroidPackedRelocationSection<ELF32BE>;
3579 template class elf::AndroidPackedRelocationSection<ELF64LE>;
3580 template class elf::AndroidPackedRelocationSection<ELF64BE>;
3581 
3582 template class elf::RelrSection<ELF32LE>;
3583 template class elf::RelrSection<ELF32BE>;
3584 template class elf::RelrSection<ELF64LE>;
3585 template class elf::RelrSection<ELF64BE>;
3586 
3587 template class elf::SymbolTableSection<ELF32LE>;
3588 template class elf::SymbolTableSection<ELF32BE>;
3589 template class elf::SymbolTableSection<ELF64LE>;
3590 template class elf::SymbolTableSection<ELF64BE>;
3591 
3592 template class elf::VersionNeedSection<ELF32LE>;
3593 template class elf::VersionNeedSection<ELF32BE>;
3594 template class elf::VersionNeedSection<ELF64LE>;
3595 template class elf::VersionNeedSection<ELF64BE>;
3596 
3597 template void elf::writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
3598 template void elf::writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
3599 template void elf::writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
3600 template void elf::writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
3601 
3602 template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
3603 template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
3604 template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
3605 template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
3606 
3607 template class elf::PartitionElfHeaderSection<ELF32LE>;
3608 template class elf::PartitionElfHeaderSection<ELF32BE>;
3609 template class elf::PartitionElfHeaderSection<ELF64LE>;
3610 template class elf::PartitionElfHeaderSection<ELF64BE>;
3611 
3612 template class elf::PartitionProgramHeadersSection<ELF32LE>;
3613 template class elf::PartitionProgramHeadersSection<ELF32BE>;
3614 template class elf::PartitionProgramHeadersSection<ELF64LE>;
3615 template class elf::PartitionProgramHeadersSection<ELF64BE>;
3616