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   // If ElfSym::globalOffsetTable is relative to .got and is referenced,
583   // increase numEntries by the number of entries used to emit
584   // ElfSym::globalOffsetTable.
585   if (ElfSym::globalOffsetTable && !target->gotBaseSymInGotPlt)
586     numEntries += target->gotHeaderEntriesNum;
587 }
588 
589 void GotSection::addEntry(Symbol &sym) {
590   sym.gotIndex = numEntries;
591   ++numEntries;
592 }
593 
594 bool GotSection::addDynTlsEntry(Symbol &sym) {
595   if (sym.globalDynIndex != -1U)
596     return false;
597   sym.globalDynIndex = numEntries;
598   // Global Dynamic TLS entries take two GOT slots.
599   numEntries += 2;
600   return true;
601 }
602 
603 // Reserves TLS entries for a TLS module ID and a TLS block offset.
604 // In total it takes two GOT slots.
605 bool GotSection::addTlsIndex() {
606   if (tlsIndexOff != uint32_t(-1))
607     return false;
608   tlsIndexOff = numEntries * config->wordsize;
609   numEntries += 2;
610   return true;
611 }
612 
613 uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
614   return this->getVA() + b.globalDynIndex * config->wordsize;
615 }
616 
617 uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
618   return b.globalDynIndex * config->wordsize;
619 }
620 
621 void GotSection::finalizeContents() {
622   size = numEntries * config->wordsize;
623 }
624 
625 bool GotSection::isNeeded() const {
626   // We need to emit a GOT even if it's empty if there's a relocation that is
627   // relative to GOT(such as GOTOFFREL).
628   return numEntries || hasGotOffRel;
629 }
630 
631 void GotSection::writeTo(uint8_t *buf) {
632   // Buf points to the start of this section's buffer,
633   // whereas InputSectionBase::relocateAlloc() expects its argument
634   // to point to the start of the output section.
635   target->writeGotHeader(buf);
636   relocateAlloc(buf - outSecOff, buf - outSecOff + size);
637 }
638 
639 static uint64_t getMipsPageAddr(uint64_t addr) {
640   return (addr + 0x8000) & ~0xffff;
641 }
642 
643 static uint64_t getMipsPageCount(uint64_t size) {
644   return (size + 0xfffe) / 0xffff + 1;
645 }
646 
647 MipsGotSection::MipsGotSection()
648     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
649                        ".got") {}
650 
651 void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
652                               RelExpr expr) {
653   FileGot &g = getGot(file);
654   if (expr == R_MIPS_GOT_LOCAL_PAGE) {
655     if (const OutputSection *os = sym.getOutputSection())
656       g.pagesMap.insert({os, {}});
657     else
658       g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
659   } else if (sym.isTls())
660     g.tls.insert({&sym, 0});
661   else if (sym.isPreemptible && expr == R_ABS)
662     g.relocs.insert({&sym, 0});
663   else if (sym.isPreemptible)
664     g.global.insert({&sym, 0});
665   else if (expr == R_MIPS_GOT_OFF32)
666     g.local32.insert({{&sym, addend}, 0});
667   else
668     g.local16.insert({{&sym, addend}, 0});
669 }
670 
671 void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
672   getGot(file).dynTlsSymbols.insert({&sym, 0});
673 }
674 
675 void MipsGotSection::addTlsIndex(InputFile &file) {
676   getGot(file).dynTlsSymbols.insert({nullptr, 0});
677 }
678 
679 size_t MipsGotSection::FileGot::getEntriesNum() const {
680   return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
681          tls.size() + dynTlsSymbols.size() * 2;
682 }
683 
684 size_t MipsGotSection::FileGot::getPageEntriesNum() const {
685   size_t num = 0;
686   for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
687     num += p.second.count;
688   return num;
689 }
690 
691 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
692   size_t count = getPageEntriesNum() + local16.size() + global.size();
693   // If there are relocation-only entries in the GOT, TLS entries
694   // are allocated after them. TLS entries should be addressable
695   // by 16-bit index so count both reloc-only and TLS entries.
696   if (!tls.empty() || !dynTlsSymbols.empty())
697     count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
698   return count;
699 }
700 
701 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
702   if (!f.mipsGotIndex.hasValue()) {
703     gots.emplace_back();
704     gots.back().file = &f;
705     f.mipsGotIndex = gots.size() - 1;
706   }
707   return gots[*f.mipsGotIndex];
708 }
709 
710 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
711                                             const Symbol &sym,
712                                             int64_t addend) const {
713   const FileGot &g = gots[*f->mipsGotIndex];
714   uint64_t index = 0;
715   if (const OutputSection *outSec = sym.getOutputSection()) {
716     uint64_t secAddr = getMipsPageAddr(outSec->addr);
717     uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
718     index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
719   } else {
720     index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
721   }
722   return index * config->wordsize;
723 }
724 
725 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
726                                            int64_t addend) const {
727   const FileGot &g = gots[*f->mipsGotIndex];
728   Symbol *sym = const_cast<Symbol *>(&s);
729   if (sym->isTls())
730     return g.tls.lookup(sym) * config->wordsize;
731   if (sym->isPreemptible)
732     return g.global.lookup(sym) * config->wordsize;
733   return g.local16.lookup({sym, addend}) * config->wordsize;
734 }
735 
736 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
737   const FileGot &g = gots[*f->mipsGotIndex];
738   return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
739 }
740 
741 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
742                                             const Symbol &s) const {
743   const FileGot &g = gots[*f->mipsGotIndex];
744   Symbol *sym = const_cast<Symbol *>(&s);
745   return g.dynTlsSymbols.lookup(sym) * config->wordsize;
746 }
747 
748 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
749   if (gots.empty())
750     return nullptr;
751   const FileGot &primGot = gots.front();
752   if (!primGot.global.empty())
753     return primGot.global.front().first;
754   if (!primGot.relocs.empty())
755     return primGot.relocs.front().first;
756   return nullptr;
757 }
758 
759 unsigned MipsGotSection::getLocalEntriesNum() const {
760   if (gots.empty())
761     return headerEntriesNum;
762   return headerEntriesNum + gots.front().getPageEntriesNum() +
763          gots.front().local16.size();
764 }
765 
766 bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
767   FileGot tmp = dst;
768   set_union(tmp.pagesMap, src.pagesMap);
769   set_union(tmp.local16, src.local16);
770   set_union(tmp.global, src.global);
771   set_union(tmp.relocs, src.relocs);
772   set_union(tmp.tls, src.tls);
773   set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
774 
775   size_t count = isPrimary ? headerEntriesNum : 0;
776   count += tmp.getIndexedEntriesNum();
777 
778   if (count * config->wordsize > config->mipsGotSize)
779     return false;
780 
781   std::swap(tmp, dst);
782   return true;
783 }
784 
785 void MipsGotSection::finalizeContents() { updateAllocSize(); }
786 
787 bool MipsGotSection::updateAllocSize() {
788   size = headerEntriesNum * config->wordsize;
789   for (const FileGot &g : gots)
790     size += g.getEntriesNum() * config->wordsize;
791   return false;
792 }
793 
794 void MipsGotSection::build() {
795   if (gots.empty())
796     return;
797 
798   std::vector<FileGot> mergedGots(1);
799 
800   // For each GOT move non-preemptible symbols from the `Global`
801   // to `Local16` list. Preemptible symbol might become non-preemptible
802   // one if, for example, it gets a related copy relocation.
803   for (FileGot &got : gots) {
804     for (auto &p: got.global)
805       if (!p.first->isPreemptible)
806         got.local16.insert({{p.first, 0}, 0});
807     got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
808       return !p.first->isPreemptible;
809     });
810   }
811 
812   // For each GOT remove "reloc-only" entry if there is "global"
813   // entry for the same symbol. And add local entries which indexed
814   // using 32-bit value at the end of 16-bit entries.
815   for (FileGot &got : gots) {
816     got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
817       return got.global.count(p.first);
818     });
819     set_union(got.local16, got.local32);
820     got.local32.clear();
821   }
822 
823   // Evaluate number of "reloc-only" entries in the resulting GOT.
824   // To do that put all unique "reloc-only" and "global" entries
825   // from all GOTs to the future primary GOT.
826   FileGot *primGot = &mergedGots.front();
827   for (FileGot &got : gots) {
828     set_union(primGot->relocs, got.global);
829     set_union(primGot->relocs, got.relocs);
830     got.relocs.clear();
831   }
832 
833   // Evaluate number of "page" entries in each GOT.
834   for (FileGot &got : gots) {
835     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
836          got.pagesMap) {
837       const OutputSection *os = p.first;
838       uint64_t secSize = 0;
839       for (BaseCommand *cmd : os->sectionCommands) {
840         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
841           for (InputSection *isec : isd->sections) {
842             uint64_t off = alignTo(secSize, isec->alignment);
843             secSize = off + isec->getSize();
844           }
845       }
846       p.second.count = getMipsPageCount(secSize);
847     }
848   }
849 
850   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
851   // maximum GOT size. At first, try to fill the primary GOT because
852   // the primary GOT can be accessed in the most effective way. If it
853   // is not possible, try to fill the last GOT in the list, and finally
854   // create a new GOT if both attempts failed.
855   for (FileGot &srcGot : gots) {
856     InputFile *file = srcGot.file;
857     if (tryMergeGots(mergedGots.front(), srcGot, true)) {
858       file->mipsGotIndex = 0;
859     } else {
860       // If this is the first time we failed to merge with the primary GOT,
861       // MergedGots.back() will also be the primary GOT. We must make sure not
862       // to try to merge again with isPrimary=false, as otherwise, if the
863       // inputs are just right, we could allow the primary GOT to become 1 or 2
864       // words bigger due to ignoring the header size.
865       if (mergedGots.size() == 1 ||
866           !tryMergeGots(mergedGots.back(), srcGot, false)) {
867         mergedGots.emplace_back();
868         std::swap(mergedGots.back(), srcGot);
869       }
870       file->mipsGotIndex = mergedGots.size() - 1;
871     }
872   }
873   std::swap(gots, mergedGots);
874 
875   // Reduce number of "reloc-only" entries in the primary GOT
876   // by substracting "global" entries exist in the primary GOT.
877   primGot = &gots.front();
878   primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
879     return primGot->global.count(p.first);
880   });
881 
882   // Calculate indexes for each GOT entry.
883   size_t index = headerEntriesNum;
884   for (FileGot &got : gots) {
885     got.startIndex = &got == primGot ? 0 : index;
886     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
887          got.pagesMap) {
888       // For each output section referenced by GOT page relocations calculate
889       // and save into pagesMap an upper bound of MIPS GOT entries required
890       // to store page addresses of local symbols. We assume the worst case -
891       // each 64kb page of the output section has at least one GOT relocation
892       // against it. And take in account the case when the section intersects
893       // page boundaries.
894       p.second.firstIndex = index;
895       index += p.second.count;
896     }
897     for (auto &p: got.local16)
898       p.second = index++;
899     for (auto &p: got.global)
900       p.second = index++;
901     for (auto &p: got.relocs)
902       p.second = index++;
903     for (auto &p: got.tls)
904       p.second = index++;
905     for (auto &p: got.dynTlsSymbols) {
906       p.second = index;
907       index += 2;
908     }
909   }
910 
911   // Update Symbol::gotIndex field to use this
912   // value later in the `sortMipsSymbols` function.
913   for (auto &p : primGot->global)
914     p.first->gotIndex = p.second;
915   for (auto &p : primGot->relocs)
916     p.first->gotIndex = p.second;
917 
918   // Create dynamic relocations.
919   for (FileGot &got : gots) {
920     // Create dynamic relocations for TLS entries.
921     for (std::pair<Symbol *, size_t> &p : got.tls) {
922       Symbol *s = p.first;
923       uint64_t offset = p.second * config->wordsize;
924       if (s->isPreemptible)
925         mainPart->relaDyn->addReloc(target->tlsGotRel, this, offset, s);
926     }
927     for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
928       Symbol *s = p.first;
929       uint64_t offset = p.second * config->wordsize;
930       if (s == nullptr) {
931         if (!config->isPic)
932           continue;
933         mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, this, offset, s);
934       } else {
935         // When building a shared library we still need a dynamic relocation
936         // for the module index. Therefore only checking for
937         // S->isPreemptible is not sufficient (this happens e.g. for
938         // thread-locals that have been marked as local through a linker script)
939         if (!s->isPreemptible && !config->isPic)
940           continue;
941         mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, this, offset, s);
942         // However, we can skip writing the TLS offset reloc for non-preemptible
943         // symbols since it is known even in shared libraries
944         if (!s->isPreemptible)
945           continue;
946         offset += config->wordsize;
947         mainPart->relaDyn->addReloc(target->tlsOffsetRel, this, offset, s);
948       }
949     }
950 
951     // Do not create dynamic relocations for non-TLS
952     // entries in the primary GOT.
953     if (&got == primGot)
954       continue;
955 
956     // Dynamic relocations for "global" entries.
957     for (const std::pair<Symbol *, size_t> &p : got.global) {
958       uint64_t offset = p.second * config->wordsize;
959       mainPart->relaDyn->addReloc(target->relativeRel, this, offset, p.first);
960     }
961     if (!config->isPic)
962       continue;
963     // Dynamic relocations for "local" entries in case of PIC.
964     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
965          got.pagesMap) {
966       size_t pageCount = l.second.count;
967       for (size_t pi = 0; pi < pageCount; ++pi) {
968         uint64_t offset = (l.second.firstIndex + pi) * config->wordsize;
969         mainPart->relaDyn->addReloc({target->relativeRel, this, offset, l.first,
970                                  int64_t(pi * 0x10000)});
971       }
972     }
973     for (const std::pair<GotEntry, size_t> &p : got.local16) {
974       uint64_t offset = p.second * config->wordsize;
975       mainPart->relaDyn->addReloc({target->relativeRel, this, offset, true,
976                                p.first.first, p.first.second});
977     }
978   }
979 }
980 
981 bool MipsGotSection::isNeeded() const {
982   // We add the .got section to the result for dynamic MIPS target because
983   // its address and properties are mentioned in the .dynamic section.
984   return !config->relocatable;
985 }
986 
987 uint64_t MipsGotSection::getGp(const InputFile *f) const {
988   // For files without related GOT or files refer a primary GOT
989   // returns "common" _gp value. For secondary GOTs calculate
990   // individual _gp values.
991   if (!f || !f->mipsGotIndex.hasValue() || *f->mipsGotIndex == 0)
992     return ElfSym::mipsGp->getVA(0);
993   return getVA() + gots[*f->mipsGotIndex].startIndex * config->wordsize +
994          0x7ff0;
995 }
996 
997 void MipsGotSection::writeTo(uint8_t *buf) {
998   // Set the MSB of the second GOT slot. This is not required by any
999   // MIPS ABI documentation, though.
1000   //
1001   // There is a comment in glibc saying that "The MSB of got[1] of a
1002   // gnu object is set to identify gnu objects," and in GNU gold it
1003   // says "the second entry will be used by some runtime loaders".
1004   // But how this field is being used is unclear.
1005   //
1006   // We are not really willing to mimic other linkers behaviors
1007   // without understanding why they do that, but because all files
1008   // generated by GNU tools have this special GOT value, and because
1009   // we've been doing this for years, it is probably a safe bet to
1010   // keep doing this for now. We really need to revisit this to see
1011   // if we had to do this.
1012   writeUint(buf + config->wordsize, (uint64_t)1 << (config->wordsize * 8 - 1));
1013   for (const FileGot &g : gots) {
1014     auto write = [&](size_t i, const Symbol *s, int64_t a) {
1015       uint64_t va = a;
1016       if (s)
1017         va = s->getVA(a);
1018       writeUint(buf + i * config->wordsize, va);
1019     };
1020     // Write 'page address' entries to the local part of the GOT.
1021     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1022          g.pagesMap) {
1023       size_t pageCount = l.second.count;
1024       uint64_t firstPageAddr = getMipsPageAddr(l.first->addr);
1025       for (size_t pi = 0; pi < pageCount; ++pi)
1026         write(l.second.firstIndex + pi, nullptr, firstPageAddr + pi * 0x10000);
1027     }
1028     // Local, global, TLS, reloc-only  entries.
1029     // If TLS entry has a corresponding dynamic relocations, leave it
1030     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1031     // To calculate the adjustments use offsets for thread-local storage.
1032     // https://www.linux-mips.org/wiki/NPTL
1033     for (const std::pair<GotEntry, size_t> &p : g.local16)
1034       write(p.second, p.first.first, p.first.second);
1035     // Write VA to the primary GOT only. For secondary GOTs that
1036     // will be done by REL32 dynamic relocations.
1037     if (&g == &gots.front())
1038       for (const std::pair<const Symbol *, size_t> &p : g.global)
1039         write(p.second, p.first, 0);
1040     for (const std::pair<Symbol *, size_t> &p : g.relocs)
1041       write(p.second, p.first, 0);
1042     for (const std::pair<Symbol *, size_t> &p : g.tls)
1043       write(p.second, p.first, p.first->isPreemptible ? 0 : -0x7000);
1044     for (const std::pair<Symbol *, size_t> &p : g.dynTlsSymbols) {
1045       if (p.first == nullptr && !config->isPic)
1046         write(p.second, nullptr, 1);
1047       else if (p.first && !p.first->isPreemptible) {
1048         // If we are emitting PIC code with relocations we mustn't write
1049         // anything to the GOT here. When using Elf_Rel relocations the value
1050         // one will be treated as an addend and will cause crashes at runtime
1051         if (!config->isPic)
1052           write(p.second, nullptr, 1);
1053         write(p.second + 1, p.first, -0x8000);
1054       }
1055     }
1056   }
1057 }
1058 
1059 // On PowerPC the .plt section is used to hold the table of function addresses
1060 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1061 // section. I don't know why we have a BSS style type for the section but it is
1062 // consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1063 GotPltSection::GotPltSection()
1064     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
1065                        ".got.plt") {
1066   if (config->emachine == EM_PPC) {
1067     name = ".plt";
1068   } else if (config->emachine == EM_PPC64) {
1069     type = SHT_NOBITS;
1070     name = ".plt";
1071   }
1072 }
1073 
1074 void GotPltSection::addEntry(Symbol &sym) {
1075   assert(sym.pltIndex == entries.size());
1076   entries.push_back(&sym);
1077 }
1078 
1079 size_t GotPltSection::getSize() const {
1080   return (target->gotPltHeaderEntriesNum + entries.size()) * config->wordsize;
1081 }
1082 
1083 void GotPltSection::writeTo(uint8_t *buf) {
1084   target->writeGotPltHeader(buf);
1085   buf += target->gotPltHeaderEntriesNum * config->wordsize;
1086   for (const Symbol *b : entries) {
1087     target->writeGotPlt(buf, *b);
1088     buf += config->wordsize;
1089   }
1090 }
1091 
1092 bool GotPltSection::isNeeded() const {
1093   // We need to emit GOTPLT even if it's empty if there's a relocation relative
1094   // to it.
1095   return !entries.empty() || hasGotPltOffRel;
1096 }
1097 
1098 static StringRef getIgotPltName() {
1099   // On ARM the IgotPltSection is part of the GotSection.
1100   if (config->emachine == EM_ARM)
1101     return ".got";
1102 
1103   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1104   // needs to be named the same.
1105   if (config->emachine == EM_PPC64)
1106     return ".plt";
1107 
1108   return ".got.plt";
1109 }
1110 
1111 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1112 // with the IgotPltSection.
1113 IgotPltSection::IgotPltSection()
1114     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1115                        config->emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1116                        config->wordsize, getIgotPltName()) {}
1117 
1118 void IgotPltSection::addEntry(Symbol &sym) {
1119   assert(sym.pltIndex == entries.size());
1120   entries.push_back(&sym);
1121 }
1122 
1123 size_t IgotPltSection::getSize() const {
1124   return entries.size() * config->wordsize;
1125 }
1126 
1127 void IgotPltSection::writeTo(uint8_t *buf) {
1128   for (const Symbol *b : entries) {
1129     target->writeIgotPlt(buf, *b);
1130     buf += config->wordsize;
1131   }
1132 }
1133 
1134 StringTableSection::StringTableSection(StringRef name, bool dynamic)
1135     : SyntheticSection(dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, name),
1136       dynamic(dynamic) {
1137   // ELF string tables start with a NUL byte.
1138   addString("");
1139 }
1140 
1141 // Adds a string to the string table. If `hashIt` is true we hash and check for
1142 // duplicates. It is optional because the name of global symbols are already
1143 // uniqued and hashing them again has a big cost for a small value: uniquing
1144 // them with some other string that happens to be the same.
1145 unsigned StringTableSection::addString(StringRef s, bool hashIt) {
1146   if (hashIt) {
1147     auto r = stringMap.insert(std::make_pair(s, this->size));
1148     if (!r.second)
1149       return r.first->second;
1150   }
1151   unsigned ret = this->size;
1152   this->size = this->size + s.size() + 1;
1153   strings.push_back(s);
1154   return ret;
1155 }
1156 
1157 void StringTableSection::writeTo(uint8_t *buf) {
1158   for (StringRef s : strings) {
1159     memcpy(buf, s.data(), s.size());
1160     buf[s.size()] = '\0';
1161     buf += s.size() + 1;
1162   }
1163 }
1164 
1165 // Returns the number of entries in .gnu.version_d: the number of
1166 // non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
1167 // Note that we don't support vd_cnt > 1 yet.
1168 static unsigned getVerDefNum() {
1169   return namedVersionDefs().size() + 1;
1170 }
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 // The output section .rela.dyn may include these synthetic sections:
1224 //
1225 // - part.relaDyn
1226 // - in.relaIplt: this is included if in.relaIplt is named .rela.dyn
1227 // - in.relaPlt: this is included if a linker script places .rela.plt inside
1228 //   .rela.dyn
1229 //
1230 // DT_RELASZ is the total size of the included sections.
1231 static std::function<uint64_t()> addRelaSz(RelocationBaseSection *relaDyn) {
1232   return [=]() {
1233     size_t size = relaDyn->getSize();
1234     if (in.relaIplt->getParent() == relaDyn->getParent())
1235       size += in.relaIplt->getSize();
1236     if (in.relaPlt->getParent() == relaDyn->getParent())
1237       size += in.relaPlt->getSize();
1238     return size;
1239   };
1240 }
1241 
1242 // A Linker script may assign the RELA relocation sections to the same
1243 // output section. When this occurs we cannot just use the OutputSection
1244 // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1245 // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1246 static uint64_t addPltRelSz() {
1247   size_t size = in.relaPlt->getSize();
1248   if (in.relaIplt->getParent() == in.relaPlt->getParent() &&
1249       in.relaIplt->name == in.relaPlt->name)
1250     size += in.relaIplt->getSize();
1251   return size;
1252 }
1253 
1254 // Add remaining entries to complete .dynamic contents.
1255 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1256   elf::Partition &part = getPartition();
1257   bool isMain = part.name.empty();
1258 
1259   for (StringRef s : config->filterList)
1260     addInt(DT_FILTER, part.dynStrTab->addString(s));
1261   for (StringRef s : config->auxiliaryList)
1262     addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
1263 
1264   if (!config->rpath.empty())
1265     addInt(config->enableNewDtags ? DT_RUNPATH : DT_RPATH,
1266            part.dynStrTab->addString(config->rpath));
1267 
1268   for (SharedFile *file : sharedFiles)
1269     if (file->isNeeded)
1270       addInt(DT_NEEDED, part.dynStrTab->addString(file->soName));
1271 
1272   if (isMain) {
1273     if (!config->soName.empty())
1274       addInt(DT_SONAME, part.dynStrTab->addString(config->soName));
1275   } else {
1276     if (!config->soName.empty())
1277       addInt(DT_NEEDED, part.dynStrTab->addString(config->soName));
1278     addInt(DT_SONAME, part.dynStrTab->addString(part.name));
1279   }
1280 
1281   // Set DT_FLAGS and DT_FLAGS_1.
1282   uint32_t dtFlags = 0;
1283   uint32_t dtFlags1 = 0;
1284   if (config->bsymbolic)
1285     dtFlags |= DF_SYMBOLIC;
1286   if (config->zGlobal)
1287     dtFlags1 |= DF_1_GLOBAL;
1288   if (config->zInitfirst)
1289     dtFlags1 |= DF_1_INITFIRST;
1290   if (config->zInterpose)
1291     dtFlags1 |= DF_1_INTERPOSE;
1292   if (config->zNodefaultlib)
1293     dtFlags1 |= DF_1_NODEFLIB;
1294   if (config->zNodelete)
1295     dtFlags1 |= DF_1_NODELETE;
1296   if (config->zNodlopen)
1297     dtFlags1 |= DF_1_NOOPEN;
1298   if (config->zNow) {
1299     dtFlags |= DF_BIND_NOW;
1300     dtFlags1 |= DF_1_NOW;
1301   }
1302   if (config->zOrigin) {
1303     dtFlags |= DF_ORIGIN;
1304     dtFlags1 |= DF_1_ORIGIN;
1305   }
1306   if (!config->zText)
1307     dtFlags |= DF_TEXTREL;
1308   if (config->hasStaticTlsModel)
1309     dtFlags |= DF_STATIC_TLS;
1310 
1311   if (dtFlags)
1312     addInt(DT_FLAGS, dtFlags);
1313   if (dtFlags1)
1314     addInt(DT_FLAGS_1, dtFlags1);
1315 
1316   // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1317   // need it for each process, so we don't write it for DSOs. The loader writes
1318   // the pointer into this entry.
1319   //
1320   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1321   // systems (currently only Fuchsia OS) provide other means to give the
1322   // debugger this information. Such systems may choose make .dynamic read-only.
1323   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1324   if (!config->shared && !config->relocatable && !config->zRodynamic)
1325     addInt(DT_DEBUG, 0);
1326 
1327   if (OutputSection *sec = part.dynStrTab->getParent())
1328     this->link = sec->sectionIndex;
1329 
1330   if (part.relaDyn->isNeeded() ||
1331       (in.relaIplt->isNeeded() &&
1332        part.relaDyn->getParent() == in.relaIplt->getParent())) {
1333     addInSec(part.relaDyn->dynamicTag, part.relaDyn);
1334     entries.push_back({part.relaDyn->sizeDynamicTag, addRelaSz(part.relaDyn)});
1335 
1336     bool isRela = config->isRela;
1337     addInt(isRela ? DT_RELAENT : DT_RELENT,
1338            isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1339 
1340     // MIPS dynamic loader does not support RELCOUNT tag.
1341     // The problem is in the tight relation between dynamic
1342     // relocations and GOT. So do not emit this tag on MIPS.
1343     if (config->emachine != EM_MIPS) {
1344       size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
1345       if (config->zCombreloc && numRelativeRels)
1346         addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
1347     }
1348   }
1349   if (part.relrDyn && !part.relrDyn->relocs.empty()) {
1350     addInSec(config->useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1351              part.relrDyn);
1352     addSize(config->useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1353             part.relrDyn->getParent());
1354     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1355            sizeof(Elf_Relr));
1356   }
1357   // .rel[a].plt section usually consists of two parts, containing plt and
1358   // iplt relocations. It is possible to have only iplt relocations in the
1359   // output. In that case relaPlt is empty and have zero offset, the same offset
1360   // as relaIplt has. And we still want to emit proper dynamic tags for that
1361   // case, so here we always use relaPlt as marker for the begining of
1362   // .rel[a].plt section.
1363   if (isMain && (in.relaPlt->isNeeded() || in.relaIplt->isNeeded())) {
1364     addInSec(DT_JMPREL, in.relaPlt);
1365     entries.push_back({DT_PLTRELSZ, addPltRelSz});
1366     switch (config->emachine) {
1367     case EM_MIPS:
1368       addInSec(DT_MIPS_PLTGOT, in.gotPlt);
1369       break;
1370     case EM_SPARCV9:
1371       addInSec(DT_PLTGOT, in.plt);
1372       break;
1373     default:
1374       addInSec(DT_PLTGOT, in.gotPlt);
1375       break;
1376     }
1377     addInt(DT_PLTREL, config->isRela ? DT_RELA : DT_REL);
1378   }
1379 
1380   if (config->emachine == EM_AARCH64) {
1381     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1382       addInt(DT_AARCH64_BTI_PLT, 0);
1383     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)
1384       addInt(DT_AARCH64_PAC_PLT, 0);
1385   }
1386 
1387   addInSec(DT_SYMTAB, part.dynSymTab);
1388   addInt(DT_SYMENT, sizeof(Elf_Sym));
1389   addInSec(DT_STRTAB, part.dynStrTab);
1390   addInt(DT_STRSZ, part.dynStrTab->getSize());
1391   if (!config->zText)
1392     addInt(DT_TEXTREL, 0);
1393   if (part.gnuHashTab)
1394     addInSec(DT_GNU_HASH, part.gnuHashTab);
1395   if (part.hashTab)
1396     addInSec(DT_HASH, part.hashTab);
1397 
1398   if (isMain) {
1399     if (Out::preinitArray) {
1400       addOutSec(DT_PREINIT_ARRAY, Out::preinitArray);
1401       addSize(DT_PREINIT_ARRAYSZ, Out::preinitArray);
1402     }
1403     if (Out::initArray) {
1404       addOutSec(DT_INIT_ARRAY, Out::initArray);
1405       addSize(DT_INIT_ARRAYSZ, Out::initArray);
1406     }
1407     if (Out::finiArray) {
1408       addOutSec(DT_FINI_ARRAY, Out::finiArray);
1409       addSize(DT_FINI_ARRAYSZ, Out::finiArray);
1410     }
1411 
1412     if (Symbol *b = symtab->find(config->init))
1413       if (b->isDefined())
1414         addSym(DT_INIT, b);
1415     if (Symbol *b = symtab->find(config->fini))
1416       if (b->isDefined())
1417         addSym(DT_FINI, b);
1418   }
1419 
1420   bool hasVerNeed = SharedFile::vernauxNum != 0;
1421   if (hasVerNeed || part.verDef)
1422     addInSec(DT_VERSYM, part.verSym);
1423   if (part.verDef) {
1424     addInSec(DT_VERDEF, part.verDef);
1425     addInt(DT_VERDEFNUM, getVerDefNum());
1426   }
1427   if (hasVerNeed) {
1428     addInSec(DT_VERNEED, part.verNeed);
1429     unsigned needNum = 0;
1430     for (SharedFile *f : sharedFiles)
1431       if (!f->vernauxs.empty())
1432         ++needNum;
1433     addInt(DT_VERNEEDNUM, needNum);
1434   }
1435 
1436   if (config->emachine == EM_MIPS) {
1437     addInt(DT_MIPS_RLD_VERSION, 1);
1438     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1439     addInt(DT_MIPS_BASE_ADDRESS, target->getImageBase());
1440     addInt(DT_MIPS_SYMTABNO, part.dynSymTab->getNumSymbols());
1441 
1442     add(DT_MIPS_LOCAL_GOTNO, [] { return in.mipsGot->getLocalEntriesNum(); });
1443 
1444     if (const Symbol *b = in.mipsGot->getFirstGlobalEntry())
1445       addInt(DT_MIPS_GOTSYM, b->dynsymIndex);
1446     else
1447       addInt(DT_MIPS_GOTSYM, part.dynSymTab->getNumSymbols());
1448     addInSec(DT_PLTGOT, in.mipsGot);
1449     if (in.mipsRldMap) {
1450       if (!config->pie)
1451         addInSec(DT_MIPS_RLD_MAP, in.mipsRldMap);
1452       // Store the offset to the .rld_map section
1453       // relative to the address of the tag.
1454       addInSecRelative(DT_MIPS_RLD_MAP_REL, in.mipsRldMap);
1455     }
1456   }
1457 
1458   // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
1459   // glibc assumes the old-style BSS PLT layout which we don't support.
1460   if (config->emachine == EM_PPC)
1461     add(DT_PPC_GOT, [] { return in.got->getVA(); });
1462 
1463   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1464   if (config->emachine == EM_PPC64 && in.plt->isNeeded()) {
1465     // The Glink tag points to 32 bytes before the first lazy symbol resolution
1466     // stub, which starts directly after the header.
1467     entries.push_back({DT_PPC64_GLINK, [=] {
1468                          unsigned offset = target->pltHeaderSize - 32;
1469                          return in.plt->getVA(0) + offset;
1470                        }});
1471   }
1472 
1473   addInt(DT_NULL, 0);
1474 
1475   getParent()->link = this->link;
1476   this->size = entries.size() * this->entsize;
1477 }
1478 
1479 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *buf) {
1480   auto *p = reinterpret_cast<Elf_Dyn *>(buf);
1481 
1482   for (std::pair<int32_t, std::function<uint64_t()>> &kv : entries) {
1483     p->d_tag = kv.first;
1484     p->d_un.d_val = kv.second();
1485     ++p;
1486   }
1487 }
1488 
1489 uint64_t DynamicReloc::getOffset() const {
1490   return inputSec->getVA(offsetInSec);
1491 }
1492 
1493 int64_t DynamicReloc::computeAddend() const {
1494   if (useSymVA)
1495     return sym->getVA(addend);
1496   if (!outputSec)
1497     return addend;
1498   // See the comment in the DynamicReloc ctor.
1499   return getMipsPageAddr(outputSec->addr) + addend;
1500 }
1501 
1502 uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *symTab) const {
1503   if (sym && !useSymVA)
1504     return symTab->getSymbolIndex(sym);
1505   return 0;
1506 }
1507 
1508 RelocationBaseSection::RelocationBaseSection(StringRef name, uint32_t type,
1509                                              int32_t dynamicTag,
1510                                              int32_t sizeDynamicTag)
1511     : SyntheticSection(SHF_ALLOC, type, config->wordsize, name),
1512       dynamicTag(dynamicTag), sizeDynamicTag(sizeDynamicTag) {}
1513 
1514 void RelocationBaseSection::addReloc(RelType dynType, InputSectionBase *isec,
1515                                      uint64_t offsetInSec, Symbol *sym) {
1516   addReloc({dynType, isec, offsetInSec, false, sym, 0});
1517 }
1518 
1519 void RelocationBaseSection::addReloc(RelType dynType,
1520                                      InputSectionBase *inputSec,
1521                                      uint64_t offsetInSec, Symbol *sym,
1522                                      int64_t addend, RelExpr expr,
1523                                      RelType type) {
1524   // Write the addends to the relocated address if required. We skip
1525   // it if the written value would be zero.
1526   if (config->writeAddends && (expr != R_ADDEND || addend != 0))
1527     inputSec->relocations.push_back({expr, type, offsetInSec, addend, sym});
1528   addReloc({dynType, inputSec, offsetInSec, expr != R_ADDEND, sym, addend});
1529 }
1530 
1531 void RelocationBaseSection::addReloc(const DynamicReloc &reloc) {
1532   if (reloc.type == target->relativeRel)
1533     ++numRelativeRelocs;
1534   relocs.push_back(reloc);
1535 }
1536 
1537 void RelocationBaseSection::finalizeContents() {
1538   SymbolTableBaseSection *symTab = getPartition().dynSymTab;
1539 
1540   // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1541   // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1542   // case.
1543   if (symTab && symTab->getParent())
1544     getParent()->link = symTab->getParent()->sectionIndex;
1545   else
1546     getParent()->link = 0;
1547 
1548   if (in.relaPlt == this)
1549     getParent()->info = in.gotPlt->getParent()->sectionIndex;
1550   if (in.relaIplt == this)
1551     getParent()->info = in.igotPlt->getParent()->sectionIndex;
1552 }
1553 
1554 RelrBaseSection::RelrBaseSection()
1555     : SyntheticSection(SHF_ALLOC,
1556                        config->useAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
1557                        config->wordsize, ".relr.dyn") {}
1558 
1559 template <class ELFT>
1560 static void encodeDynamicReloc(SymbolTableBaseSection *symTab,
1561                                typename ELFT::Rela *p,
1562                                const DynamicReloc &rel) {
1563   if (config->isRela)
1564     p->r_addend = rel.computeAddend();
1565   p->r_offset = rel.getOffset();
1566   p->setSymbolAndType(rel.getSymIndex(symTab), rel.type, config->isMips64EL);
1567 }
1568 
1569 template <class ELFT>
1570 RelocationSection<ELFT>::RelocationSection(StringRef name, bool sort)
1571     : RelocationBaseSection(name, config->isRela ? SHT_RELA : SHT_REL,
1572                             config->isRela ? DT_RELA : DT_REL,
1573                             config->isRela ? DT_RELASZ : DT_RELSZ),
1574       sort(sort) {
1575   this->entsize = config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1576 }
1577 
1578 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *buf) {
1579   SymbolTableBaseSection *symTab = getPartition().dynSymTab;
1580 
1581   // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
1582   // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
1583   // is to make results easier to read.
1584   if (sort)
1585     llvm::stable_sort(
1586         relocs, [&](const DynamicReloc &a, const DynamicReloc &b) {
1587           return std::make_tuple(a.type != target->relativeRel,
1588                                  a.getSymIndex(symTab), a.getOffset()) <
1589                  std::make_tuple(b.type != target->relativeRel,
1590                                  b.getSymIndex(symTab), b.getOffset());
1591         });
1592 
1593   for (const DynamicReloc &rel : relocs) {
1594     encodeDynamicReloc<ELFT>(symTab, reinterpret_cast<Elf_Rela *>(buf), rel);
1595     buf += config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1596   }
1597 }
1598 
1599 template <class ELFT>
1600 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1601     StringRef name)
1602     : RelocationBaseSection(
1603           name, config->isRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1604           config->isRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1605           config->isRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1606   this->entsize = 1;
1607 }
1608 
1609 template <class ELFT>
1610 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1611   // This function computes the contents of an Android-format packed relocation
1612   // section.
1613   //
1614   // This format compresses relocations by using relocation groups to factor out
1615   // fields that are common between relocations and storing deltas from previous
1616   // relocations in SLEB128 format (which has a short representation for small
1617   // numbers). A good example of a relocation type with common fields is
1618   // R_*_RELATIVE, which is normally used to represent function pointers in
1619   // vtables. In the REL format, each relative relocation has the same r_info
1620   // field, and is only different from other relative relocations in terms of
1621   // the r_offset field. By sorting relocations by offset, grouping them by
1622   // r_info and representing each relocation with only the delta from the
1623   // previous offset, each 8-byte relocation can be compressed to as little as 1
1624   // byte (or less with run-length encoding). This relocation packer was able to
1625   // reduce the size of the relocation section in an Android Chromium DSO from
1626   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1627   //
1628   // A relocation section consists of a header containing the literal bytes
1629   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1630   // elements are the total number of relocations in the section and an initial
1631   // r_offset value. The remaining elements define a sequence of relocation
1632   // groups. Each relocation group starts with a header consisting of the
1633   // following elements:
1634   //
1635   // - the number of relocations in the relocation group
1636   // - flags for the relocation group
1637   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1638   //   for each relocation in the group.
1639   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1640   //   field for each relocation in the group.
1641   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1642   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1643   //   each relocation in the group.
1644   //
1645   // Following the relocation group header are descriptions of each of the
1646   // relocations in the group. They consist of the following elements:
1647   //
1648   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1649   //   delta for this relocation.
1650   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1651   //   field for this relocation.
1652   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1653   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1654   //   this relocation.
1655 
1656   size_t oldSize = relocData.size();
1657 
1658   relocData = {'A', 'P', 'S', '2'};
1659   raw_svector_ostream os(relocData);
1660   auto add = [&](int64_t v) { encodeSLEB128(v, os); };
1661 
1662   // The format header includes the number of relocations and the initial
1663   // offset (we set this to zero because the first relocation group will
1664   // perform the initial adjustment).
1665   add(relocs.size());
1666   add(0);
1667 
1668   std::vector<Elf_Rela> relatives, nonRelatives;
1669 
1670   for (const DynamicReloc &rel : relocs) {
1671     Elf_Rela r;
1672     encodeDynamicReloc<ELFT>(getPartition().dynSymTab, &r, rel);
1673 
1674     if (r.getType(config->isMips64EL) == target->relativeRel)
1675       relatives.push_back(r);
1676     else
1677       nonRelatives.push_back(r);
1678   }
1679 
1680   llvm::sort(relatives, [](const Elf_Rel &a, const Elf_Rel &b) {
1681     return a.r_offset < b.r_offset;
1682   });
1683 
1684   // Try to find groups of relative relocations which are spaced one word
1685   // apart from one another. These generally correspond to vtable entries. The
1686   // format allows these groups to be encoded using a sort of run-length
1687   // encoding, but each group will cost 7 bytes in addition to the offset from
1688   // the previous group, so it is only profitable to do this for groups of
1689   // size 8 or larger.
1690   std::vector<Elf_Rela> ungroupedRelatives;
1691   std::vector<std::vector<Elf_Rela>> relativeGroups;
1692   for (auto i = relatives.begin(), e = relatives.end(); i != e;) {
1693     std::vector<Elf_Rela> group;
1694     do {
1695       group.push_back(*i++);
1696     } while (i != e && (i - 1)->r_offset + config->wordsize == i->r_offset);
1697 
1698     if (group.size() < 8)
1699       ungroupedRelatives.insert(ungroupedRelatives.end(), group.begin(),
1700                                 group.end());
1701     else
1702       relativeGroups.emplace_back(std::move(group));
1703   }
1704 
1705   unsigned hasAddendIfRela =
1706       config->isRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1707 
1708   uint64_t offset = 0;
1709   uint64_t addend = 0;
1710 
1711   // Emit the run-length encoding for the groups of adjacent relative
1712   // relocations. Each group is represented using two groups in the packed
1713   // format. The first is used to set the current offset to the start of the
1714   // group (and also encodes the first relocation), and the second encodes the
1715   // remaining relocations.
1716   for (std::vector<Elf_Rela> &g : relativeGroups) {
1717     // The first relocation in the group.
1718     add(1);
1719     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1720         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1721     add(g[0].r_offset - offset);
1722     add(target->relativeRel);
1723     if (config->isRela) {
1724       add(g[0].r_addend - addend);
1725       addend = g[0].r_addend;
1726     }
1727 
1728     // The remaining relocations.
1729     add(g.size() - 1);
1730     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1731         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1732     add(config->wordsize);
1733     add(target->relativeRel);
1734     if (config->isRela) {
1735       for (auto i = g.begin() + 1, e = g.end(); i != e; ++i) {
1736         add(i->r_addend - addend);
1737         addend = i->r_addend;
1738       }
1739     }
1740 
1741     offset = g.back().r_offset;
1742   }
1743 
1744   // Now the ungrouped relatives.
1745   if (!ungroupedRelatives.empty()) {
1746     add(ungroupedRelatives.size());
1747     add(RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1748     add(target->relativeRel);
1749     for (Elf_Rela &r : ungroupedRelatives) {
1750       add(r.r_offset - offset);
1751       offset = r.r_offset;
1752       if (config->isRela) {
1753         add(r.r_addend - addend);
1754         addend = r.r_addend;
1755       }
1756     }
1757   }
1758 
1759   // Finally the non-relative relocations.
1760   llvm::sort(nonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1761     return a.r_offset < b.r_offset;
1762   });
1763   if (!nonRelatives.empty()) {
1764     add(nonRelatives.size());
1765     add(hasAddendIfRela);
1766     for (Elf_Rela &r : nonRelatives) {
1767       add(r.r_offset - offset);
1768       offset = r.r_offset;
1769       add(r.r_info);
1770       if (config->isRela) {
1771         add(r.r_addend - addend);
1772         addend = r.r_addend;
1773       }
1774     }
1775   }
1776 
1777   // Don't allow the section to shrink; otherwise the size of the section can
1778   // oscillate infinitely.
1779   if (relocData.size() < oldSize)
1780     relocData.append(oldSize - relocData.size(), 0);
1781 
1782   // Returns whether the section size changed. We need to keep recomputing both
1783   // section layout and the contents of this section until the size converges
1784   // because changing this section's size can affect section layout, which in
1785   // turn can affect the sizes of the LEB-encoded integers stored in this
1786   // section.
1787   return relocData.size() != oldSize;
1788 }
1789 
1790 template <class ELFT> RelrSection<ELFT>::RelrSection() {
1791   this->entsize = config->wordsize;
1792 }
1793 
1794 template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
1795   // This function computes the contents of an SHT_RELR packed relocation
1796   // section.
1797   //
1798   // Proposal for adding SHT_RELR sections to generic-abi is here:
1799   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
1800   //
1801   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
1802   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
1803   //
1804   // i.e. start with an address, followed by any number of bitmaps. The address
1805   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
1806   // relocations each, at subsequent offsets following the last address entry.
1807   //
1808   // The bitmap entries must have 1 in the least significant bit. The assumption
1809   // here is that an address cannot have 1 in lsb. Odd addresses are not
1810   // supported.
1811   //
1812   // Excluding the least significant bit in the bitmap, each non-zero bit in
1813   // the bitmap represents a relocation to be applied to a corresponding machine
1814   // word that follows the base address word. The second least significant bit
1815   // represents the machine word immediately following the initial address, and
1816   // each bit that follows represents the next word, in linear order. As such,
1817   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
1818   // 63 relocations in a 64-bit object.
1819   //
1820   // This encoding has a couple of interesting properties:
1821   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
1822   //    even means address, odd means bitmap.
1823   // 2. Just a simple list of addresses is a valid encoding.
1824 
1825   size_t oldSize = relrRelocs.size();
1826   relrRelocs.clear();
1827 
1828   // Same as Config->Wordsize but faster because this is a compile-time
1829   // constant.
1830   const size_t wordsize = sizeof(typename ELFT::uint);
1831 
1832   // Number of bits to use for the relocation offsets bitmap.
1833   // Must be either 63 or 31.
1834   const size_t nBits = wordsize * 8 - 1;
1835 
1836   // Get offsets for all relative relocations and sort them.
1837   std::vector<uint64_t> offsets;
1838   for (const RelativeReloc &rel : relocs)
1839     offsets.push_back(rel.getOffset());
1840   llvm::sort(offsets);
1841 
1842   // For each leading relocation, find following ones that can be folded
1843   // as a bitmap and fold them.
1844   for (size_t i = 0, e = offsets.size(); i < e;) {
1845     // Add a leading relocation.
1846     relrRelocs.push_back(Elf_Relr(offsets[i]));
1847     uint64_t base = offsets[i] + wordsize;
1848     ++i;
1849 
1850     // Find foldable relocations to construct bitmaps.
1851     while (i < e) {
1852       uint64_t bitmap = 0;
1853 
1854       while (i < e) {
1855         uint64_t delta = offsets[i] - base;
1856 
1857         // If it is too far, it cannot be folded.
1858         if (delta >= nBits * wordsize)
1859           break;
1860 
1861         // If it is not a multiple of wordsize away, it cannot be folded.
1862         if (delta % wordsize)
1863           break;
1864 
1865         // Fold it.
1866         bitmap |= 1ULL << (delta / wordsize);
1867         ++i;
1868       }
1869 
1870       if (!bitmap)
1871         break;
1872 
1873       relrRelocs.push_back(Elf_Relr((bitmap << 1) | 1));
1874       base += nBits * wordsize;
1875     }
1876   }
1877 
1878   return relrRelocs.size() != oldSize;
1879 }
1880 
1881 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &strTabSec)
1882     : SyntheticSection(strTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1883                        strTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1884                        config->wordsize,
1885                        strTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1886       strTabSec(strTabSec) {}
1887 
1888 // Orders symbols according to their positions in the GOT,
1889 // in compliance with MIPS ABI rules.
1890 // See "Global Offset Table" in Chapter 5 in the following document
1891 // for detailed description:
1892 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1893 static bool sortMipsSymbols(const SymbolTableEntry &l,
1894                             const SymbolTableEntry &r) {
1895   // Sort entries related to non-local preemptible symbols by GOT indexes.
1896   // All other entries go to the beginning of a dynsym in arbitrary order.
1897   if (l.sym->isInGot() && r.sym->isInGot())
1898     return l.sym->gotIndex < r.sym->gotIndex;
1899   if (!l.sym->isInGot() && !r.sym->isInGot())
1900     return false;
1901   return !l.sym->isInGot();
1902 }
1903 
1904 void SymbolTableBaseSection::finalizeContents() {
1905   if (OutputSection *sec = strTabSec.getParent())
1906     getParent()->link = sec->sectionIndex;
1907 
1908   if (this->type != SHT_DYNSYM) {
1909     sortSymTabSymbols();
1910     return;
1911   }
1912 
1913   // If it is a .dynsym, there should be no local symbols, but we need
1914   // to do a few things for the dynamic linker.
1915 
1916   // Section's Info field has the index of the first non-local symbol.
1917   // Because the first symbol entry is a null entry, 1 is the first.
1918   getParent()->info = 1;
1919 
1920   if (getPartition().gnuHashTab) {
1921     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1922     getPartition().gnuHashTab->addSymbols(symbols);
1923   } else if (config->emachine == EM_MIPS) {
1924     llvm::stable_sort(symbols, sortMipsSymbols);
1925   }
1926 
1927   // Only the main partition's dynsym indexes are stored in the symbols
1928   // themselves. All other partitions use a lookup table.
1929   if (this == mainPart->dynSymTab) {
1930     size_t i = 0;
1931     for (const SymbolTableEntry &s : symbols)
1932       s.sym->dynsymIndex = ++i;
1933   }
1934 }
1935 
1936 // The ELF spec requires that all local symbols precede global symbols, so we
1937 // sort symbol entries in this function. (For .dynsym, we don't do that because
1938 // symbols for dynamic linking are inherently all globals.)
1939 //
1940 // Aside from above, we put local symbols in groups starting with the STT_FILE
1941 // symbol. That is convenient for purpose of identifying where are local symbols
1942 // coming from.
1943 void SymbolTableBaseSection::sortSymTabSymbols() {
1944   // Move all local symbols before global symbols.
1945   auto e = std::stable_partition(
1946       symbols.begin(), symbols.end(), [](const SymbolTableEntry &s) {
1947         return s.sym->isLocal() || s.sym->computeBinding() == STB_LOCAL;
1948       });
1949   size_t numLocals = e - symbols.begin();
1950   getParent()->info = numLocals + 1;
1951 
1952   // We want to group the local symbols by file. For that we rebuild the local
1953   // part of the symbols vector. We do not need to care about the STT_FILE
1954   // symbols, they are already naturally placed first in each group. That
1955   // happens because STT_FILE is always the first symbol in the object and hence
1956   // precede all other local symbols we add for a file.
1957   MapVector<InputFile *, std::vector<SymbolTableEntry>> arr;
1958   for (const SymbolTableEntry &s : llvm::make_range(symbols.begin(), e))
1959     arr[s.sym->file].push_back(s);
1960 
1961   auto i = symbols.begin();
1962   for (std::pair<InputFile *, std::vector<SymbolTableEntry>> &p : arr)
1963     for (SymbolTableEntry &entry : p.second)
1964       *i++ = entry;
1965 }
1966 
1967 void SymbolTableBaseSection::addSymbol(Symbol *b) {
1968   // Adding a local symbol to a .dynsym is a bug.
1969   assert(this->type != SHT_DYNSYM || !b->isLocal());
1970 
1971   bool hashIt = b->isLocal();
1972   symbols.push_back({b, strTabSec.addString(b->getName(), hashIt)});
1973 }
1974 
1975 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *sym) {
1976   if (this == mainPart->dynSymTab)
1977     return sym->dynsymIndex;
1978 
1979   // Initializes symbol lookup tables lazily. This is used only for -r,
1980   // -emit-relocs and dynsyms in partitions other than the main one.
1981   llvm::call_once(onceFlag, [&] {
1982     symbolIndexMap.reserve(symbols.size());
1983     size_t i = 0;
1984     for (const SymbolTableEntry &e : symbols) {
1985       if (e.sym->type == STT_SECTION)
1986         sectionIndexMap[e.sym->getOutputSection()] = ++i;
1987       else
1988         symbolIndexMap[e.sym] = ++i;
1989     }
1990   });
1991 
1992   // Section symbols are mapped based on their output sections
1993   // to maintain their semantics.
1994   if (sym->type == STT_SECTION)
1995     return sectionIndexMap.lookup(sym->getOutputSection());
1996   return symbolIndexMap.lookup(sym);
1997 }
1998 
1999 template <class ELFT>
2000 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &strTabSec)
2001     : SymbolTableBaseSection(strTabSec) {
2002   this->entsize = sizeof(Elf_Sym);
2003 }
2004 
2005 static BssSection *getCommonSec(Symbol *sym) {
2006   if (!config->defineCommon)
2007     if (auto *d = dyn_cast<Defined>(sym))
2008       return dyn_cast_or_null<BssSection>(d->section);
2009   return nullptr;
2010 }
2011 
2012 static uint32_t getSymSectionIndex(Symbol *sym) {
2013   if (getCommonSec(sym))
2014     return SHN_COMMON;
2015   if (!isa<Defined>(sym) || sym->needsPltAddr)
2016     return SHN_UNDEF;
2017   if (const OutputSection *os = sym->getOutputSection())
2018     return os->sectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
2019                                              : os->sectionIndex;
2020   return SHN_ABS;
2021 }
2022 
2023 // Write the internal symbol table contents to the output symbol table.
2024 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *buf) {
2025   // The first entry is a null entry as per the ELF spec.
2026   memset(buf, 0, sizeof(Elf_Sym));
2027   buf += sizeof(Elf_Sym);
2028 
2029   auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2030 
2031   for (SymbolTableEntry &ent : symbols) {
2032     Symbol *sym = ent.sym;
2033     bool isDefinedHere = type == SHT_SYMTAB || sym->partition == partition;
2034 
2035     // Set st_info and st_other.
2036     eSym->st_other = 0;
2037     if (sym->isLocal()) {
2038       eSym->setBindingAndType(STB_LOCAL, sym->type);
2039     } else {
2040       eSym->setBindingAndType(sym->computeBinding(), sym->type);
2041       eSym->setVisibility(sym->visibility);
2042     }
2043 
2044     // The 3 most significant bits of st_other are used by OpenPOWER ABI.
2045     // See getPPC64GlobalEntryToLocalEntryOffset() for more details.
2046     if (config->emachine == EM_PPC64)
2047       eSym->st_other |= sym->stOther & 0xe0;
2048 
2049     eSym->st_name = ent.strTabOffset;
2050     if (isDefinedHere)
2051       eSym->st_shndx = getSymSectionIndex(ent.sym);
2052     else
2053       eSym->st_shndx = 0;
2054 
2055     // Copy symbol size if it is a defined symbol. st_size is not significant
2056     // for undefined symbols, so whether copying it or not is up to us if that's
2057     // the case. We'll leave it as zero because by not setting a value, we can
2058     // get the exact same outputs for two sets of input files that differ only
2059     // in undefined symbol size in DSOs.
2060     if (eSym->st_shndx == SHN_UNDEF || !isDefinedHere)
2061       eSym->st_size = 0;
2062     else
2063       eSym->st_size = sym->getSize();
2064 
2065     // st_value is usually an address of a symbol, but that has a
2066     // special meaining for uninstantiated common symbols (this can
2067     // occur if -r is given).
2068     if (BssSection *commonSec = getCommonSec(ent.sym))
2069       eSym->st_value = commonSec->alignment;
2070     else if (isDefinedHere)
2071       eSym->st_value = sym->getVA();
2072     else
2073       eSym->st_value = 0;
2074 
2075     ++eSym;
2076   }
2077 
2078   // On MIPS we need to mark symbol which has a PLT entry and requires
2079   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
2080   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
2081   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
2082   if (config->emachine == EM_MIPS) {
2083     auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2084 
2085     for (SymbolTableEntry &ent : symbols) {
2086       Symbol *sym = ent.sym;
2087       if (sym->isInPlt() && sym->needsPltAddr)
2088         eSym->st_other |= STO_MIPS_PLT;
2089       if (isMicroMips()) {
2090         // We already set the less-significant bit for symbols
2091         // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
2092         // records. That allows us to distinguish such symbols in
2093         // the `MIPS<ELFT>::relocateOne()` routine. Now we should
2094         // clear that bit for non-dynamic symbol table, so tools
2095         // like `objdump` will be able to deal with a correct
2096         // symbol position.
2097         if (sym->isDefined() &&
2098             ((sym->stOther & STO_MIPS_MICROMIPS) || sym->needsPltAddr)) {
2099           if (!strTabSec.isDynamic())
2100             eSym->st_value &= ~1;
2101           eSym->st_other |= STO_MIPS_MICROMIPS;
2102         }
2103       }
2104       if (config->relocatable)
2105         if (auto *d = dyn_cast<Defined>(sym))
2106           if (isMipsPIC<ELFT>(d))
2107             eSym->st_other |= STO_MIPS_PIC;
2108       ++eSym;
2109     }
2110   }
2111 }
2112 
2113 SymtabShndxSection::SymtabShndxSection()
2114     : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") {
2115   this->entsize = 4;
2116 }
2117 
2118 void SymtabShndxSection::writeTo(uint8_t *buf) {
2119   // We write an array of 32 bit values, where each value has 1:1 association
2120   // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX,
2121   // we need to write actual index, otherwise, we must write SHN_UNDEF(0).
2122   buf += 4; // Ignore .symtab[0] entry.
2123   for (const SymbolTableEntry &entry : in.symTab->getSymbols()) {
2124     if (getSymSectionIndex(entry.sym) == SHN_XINDEX)
2125       write32(buf, entry.sym->getOutputSection()->sectionIndex);
2126     buf += 4;
2127   }
2128 }
2129 
2130 bool SymtabShndxSection::isNeeded() const {
2131   // SHT_SYMTAB can hold symbols with section indices values up to
2132   // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
2133   // section. Problem is that we reveal the final section indices a bit too
2134   // late, and we do not know them here. For simplicity, we just always create
2135   // a .symtab_shndx section when the amount of output sections is huge.
2136   size_t size = 0;
2137   for (BaseCommand *base : script->sectionCommands)
2138     if (isa<OutputSection>(base))
2139       ++size;
2140   return size >= SHN_LORESERVE;
2141 }
2142 
2143 void SymtabShndxSection::finalizeContents() {
2144   getParent()->link = in.symTab->getParent()->sectionIndex;
2145 }
2146 
2147 size_t SymtabShndxSection::getSize() const {
2148   return in.symTab->getNumSymbols() * 4;
2149 }
2150 
2151 // .hash and .gnu.hash sections contain on-disk hash tables that map
2152 // symbol names to their dynamic symbol table indices. Their purpose
2153 // is to help the dynamic linker resolve symbols quickly. If ELF files
2154 // don't have them, the dynamic linker has to do linear search on all
2155 // dynamic symbols, which makes programs slower. Therefore, a .hash
2156 // section is added to a DSO by default. A .gnu.hash is added if you
2157 // give the -hash-style=gnu or -hash-style=both option.
2158 //
2159 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
2160 // Each ELF file has a list of DSOs that the ELF file depends on and a
2161 // list of dynamic symbols that need to be resolved from any of the
2162 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2163 // where m is the number of DSOs and n is the number of dynamic
2164 // symbols. For modern large programs, both m and n are large.  So
2165 // making each step faster by using hash tables substiantially
2166 // improves time to load programs.
2167 //
2168 // (Note that this is not the only way to design the shared library.
2169 // For instance, the Windows DLL takes a different approach. On
2170 // Windows, each dynamic symbol has a name of DLL from which the symbol
2171 // has to be resolved. That makes the cost of symbol resolution O(n).
2172 // This disables some hacky techniques you can use on Unix such as
2173 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2174 //
2175 // Due to historical reasons, we have two different hash tables, .hash
2176 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2177 // and better version of .hash. .hash is just an on-disk hash table, but
2178 // .gnu.hash has a bloom filter in addition to a hash table to skip
2179 // DSOs very quickly. If you are sure that your dynamic linker knows
2180 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
2181 // safe bet is to specify -hash-style=both for backward compatibilty.
2182 GnuHashTableSection::GnuHashTableSection()
2183     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, config->wordsize, ".gnu.hash") {
2184 }
2185 
2186 void GnuHashTableSection::finalizeContents() {
2187   if (OutputSection *sec = getPartition().dynSymTab->getParent())
2188     getParent()->link = sec->sectionIndex;
2189 
2190   // Computes bloom filter size in word size. We want to allocate 12
2191   // bits for each symbol. It must be a power of two.
2192   if (symbols.empty()) {
2193     maskWords = 1;
2194   } else {
2195     uint64_t numBits = symbols.size() * 12;
2196     maskWords = NextPowerOf2(numBits / (config->wordsize * 8));
2197   }
2198 
2199   size = 16;                            // Header
2200   size += config->wordsize * maskWords; // Bloom filter
2201   size += nBuckets * 4;                 // Hash buckets
2202   size += symbols.size() * 4;           // Hash values
2203 }
2204 
2205 void GnuHashTableSection::writeTo(uint8_t *buf) {
2206   // The output buffer is not guaranteed to be zero-cleared because we pre-
2207   // fill executable sections with trap instructions. This is a precaution
2208   // for that case, which happens only when -no-rosegment is given.
2209   memset(buf, 0, size);
2210 
2211   // Write a header.
2212   write32(buf, nBuckets);
2213   write32(buf + 4, getPartition().dynSymTab->getNumSymbols() - symbols.size());
2214   write32(buf + 8, maskWords);
2215   write32(buf + 12, Shift2);
2216   buf += 16;
2217 
2218   // Write a bloom filter and a hash table.
2219   writeBloomFilter(buf);
2220   buf += config->wordsize * maskWords;
2221   writeHashTable(buf);
2222 }
2223 
2224 // This function writes a 2-bit bloom filter. This bloom filter alone
2225 // usually filters out 80% or more of all symbol lookups [1].
2226 // The dynamic linker uses the hash table only when a symbol is not
2227 // filtered out by a bloom filter.
2228 //
2229 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
2230 //     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
2231 void GnuHashTableSection::writeBloomFilter(uint8_t *buf) {
2232   unsigned c = config->is64 ? 64 : 32;
2233   for (const Entry &sym : symbols) {
2234     // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
2235     // the word using bits [0:5] and [26:31].
2236     size_t i = (sym.hash / c) & (maskWords - 1);
2237     uint64_t val = readUint(buf + i * config->wordsize);
2238     val |= uint64_t(1) << (sym.hash % c);
2239     val |= uint64_t(1) << ((sym.hash >> Shift2) % c);
2240     writeUint(buf + i * config->wordsize, val);
2241   }
2242 }
2243 
2244 void GnuHashTableSection::writeHashTable(uint8_t *buf) {
2245   uint32_t *buckets = reinterpret_cast<uint32_t *>(buf);
2246   uint32_t oldBucket = -1;
2247   uint32_t *values = buckets + nBuckets;
2248   for (auto i = symbols.begin(), e = symbols.end(); i != e; ++i) {
2249     // Write a hash value. It represents a sequence of chains that share the
2250     // same hash modulo value. The last element of each chain is terminated by
2251     // LSB 1.
2252     uint32_t hash = i->hash;
2253     bool isLastInChain = (i + 1) == e || i->bucketIdx != (i + 1)->bucketIdx;
2254     hash = isLastInChain ? hash | 1 : hash & ~1;
2255     write32(values++, hash);
2256 
2257     if (i->bucketIdx == oldBucket)
2258       continue;
2259     // Write a hash bucket. Hash buckets contain indices in the following hash
2260     // value table.
2261     write32(buckets + i->bucketIdx,
2262             getPartition().dynSymTab->getSymbolIndex(i->sym));
2263     oldBucket = i->bucketIdx;
2264   }
2265 }
2266 
2267 static uint32_t hashGnu(StringRef name) {
2268   uint32_t h = 5381;
2269   for (uint8_t c : name)
2270     h = (h << 5) + h + c;
2271   return h;
2272 }
2273 
2274 // Add symbols to this symbol hash table. Note that this function
2275 // destructively sort a given vector -- which is needed because
2276 // GNU-style hash table places some sorting requirements.
2277 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &v) {
2278   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2279   // its type correctly.
2280   std::vector<SymbolTableEntry>::iterator mid =
2281       std::stable_partition(v.begin(), v.end(), [&](const SymbolTableEntry &s) {
2282         return !s.sym->isDefined() || s.sym->partition != partition;
2283       });
2284 
2285   // We chose load factor 4 for the on-disk hash table. For each hash
2286   // collision, the dynamic linker will compare a uint32_t hash value.
2287   // Since the integer comparison is quite fast, we believe we can
2288   // make the load factor even larger. 4 is just a conservative choice.
2289   //
2290   // Note that we don't want to create a zero-sized hash table because
2291   // Android loader as of 2018 doesn't like a .gnu.hash containing such
2292   // table. If that's the case, we create a hash table with one unused
2293   // dummy slot.
2294   nBuckets = std::max<size_t>((v.end() - mid) / 4, 1);
2295 
2296   if (mid == v.end())
2297     return;
2298 
2299   for (SymbolTableEntry &ent : llvm::make_range(mid, v.end())) {
2300     Symbol *b = ent.sym;
2301     uint32_t hash = hashGnu(b->getName());
2302     uint32_t bucketIdx = hash % nBuckets;
2303     symbols.push_back({b, ent.strTabOffset, hash, bucketIdx});
2304   }
2305 
2306   llvm::stable_sort(symbols, [](const Entry &l, const Entry &r) {
2307     return l.bucketIdx < r.bucketIdx;
2308   });
2309 
2310   v.erase(mid, v.end());
2311   for (const Entry &ent : symbols)
2312     v.push_back({ent.sym, ent.strTabOffset});
2313 }
2314 
2315 HashTableSection::HashTableSection()
2316     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2317   this->entsize = 4;
2318 }
2319 
2320 void HashTableSection::finalizeContents() {
2321   SymbolTableBaseSection *symTab = getPartition().dynSymTab;
2322 
2323   if (OutputSection *sec = symTab->getParent())
2324     getParent()->link = sec->sectionIndex;
2325 
2326   unsigned numEntries = 2;               // nbucket and nchain.
2327   numEntries += symTab->getNumSymbols(); // The chain entries.
2328 
2329   // Create as many buckets as there are symbols.
2330   numEntries += symTab->getNumSymbols();
2331   this->size = numEntries * 4;
2332 }
2333 
2334 void HashTableSection::writeTo(uint8_t *buf) {
2335   SymbolTableBaseSection *symTab = getPartition().dynSymTab;
2336 
2337   // See comment in GnuHashTableSection::writeTo.
2338   memset(buf, 0, size);
2339 
2340   unsigned numSymbols = symTab->getNumSymbols();
2341 
2342   uint32_t *p = reinterpret_cast<uint32_t *>(buf);
2343   write32(p++, numSymbols); // nbucket
2344   write32(p++, numSymbols); // nchain
2345 
2346   uint32_t *buckets = p;
2347   uint32_t *chains = p + numSymbols;
2348 
2349   for (const SymbolTableEntry &s : symTab->getSymbols()) {
2350     Symbol *sym = s.sym;
2351     StringRef name = sym->getName();
2352     unsigned i = sym->dynsymIndex;
2353     uint32_t hash = hashSysV(name) % numSymbols;
2354     chains[i] = buckets[hash];
2355     write32(buckets + hash, i);
2356   }
2357 }
2358 
2359 // On PowerPC64 the lazy symbol resolvers go into the `global linkage table`
2360 // in the .glink section, rather then the typical .plt section.
2361 PltSection::PltSection(bool isIplt)
2362     : SyntheticSection(
2363           SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
2364           (config->emachine == EM_PPC || config->emachine == EM_PPC64)
2365               ? ".glink"
2366               : ".plt"),
2367       headerSize(!isIplt || config->zRetpolineplt ? target->pltHeaderSize : 0),
2368       isIplt(isIplt) {
2369   // The PLT needs to be writable on SPARC as the dynamic linker will
2370   // modify the instructions in the PLT entries.
2371   if (config->emachine == EM_SPARCV9)
2372     this->flags |= SHF_WRITE;
2373 }
2374 
2375 void PltSection::writeTo(uint8_t *buf) {
2376   if (config->emachine == EM_PPC) {
2377     writePPC32GlinkSection(buf, entries.size());
2378     return;
2379   }
2380 
2381   // At beginning of PLT or retpoline IPLT, we have code to call the dynamic
2382   // linker to resolve dynsyms at runtime. Write such code.
2383   if (headerSize)
2384     target->writePltHeader(buf);
2385   size_t off = headerSize;
2386 
2387   RelocationBaseSection *relSec = isIplt ? in.relaIplt : in.relaPlt;
2388 
2389   // The IPlt is immediately after the Plt, account for this in relOff
2390   size_t pltOff = isIplt ? in.plt->getSize() : 0;
2391 
2392   for (size_t i = 0, e = entries.size(); i != e; ++i) {
2393     const Symbol *b = entries[i];
2394     unsigned relOff = relSec->entsize * i + pltOff;
2395     uint64_t got = b->getGotPltVA();
2396     uint64_t plt = this->getVA() + off;
2397     target->writePlt(buf + off, got, plt, b->pltIndex, relOff);
2398     off += target->pltEntrySize;
2399   }
2400 }
2401 
2402 template <class ELFT> void PltSection::addEntry(Symbol &sym) {
2403   sym.pltIndex = entries.size();
2404   entries.push_back(&sym);
2405 }
2406 
2407 size_t PltSection::getSize() const {
2408   return headerSize + entries.size() * target->pltEntrySize;
2409 }
2410 
2411 // Some architectures such as additional symbols in the PLT section. For
2412 // example ARM uses mapping symbols to aid disassembly
2413 void PltSection::addSymbols() {
2414   // The PLT may have symbols defined for the Header, the IPLT has no header
2415   if (!isIplt)
2416     target->addPltHeaderSymbols(*this);
2417 
2418   size_t off = headerSize;
2419   for (size_t i = 0; i < entries.size(); ++i) {
2420     target->addPltSymbols(*this, off);
2421     off += target->pltEntrySize;
2422   }
2423 }
2424 
2425 // The string hash function for .gdb_index.
2426 static uint32_t computeGdbHash(StringRef s) {
2427   uint32_t h = 0;
2428   for (uint8_t c : s)
2429     h = h * 67 + toLower(c) - 113;
2430   return h;
2431 }
2432 
2433 GdbIndexSection::GdbIndexSection()
2434     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2435 
2436 // Returns the desired size of an on-disk hash table for a .gdb_index section.
2437 // There's a tradeoff between size and collision rate. We aim 75% utilization.
2438 size_t GdbIndexSection::computeSymtabSize() const {
2439   return std::max<size_t>(NextPowerOf2(symbols.size() * 4 / 3), 1024);
2440 }
2441 
2442 // Compute the output section size.
2443 void GdbIndexSection::initOutputSize() {
2444   size = sizeof(GdbIndexHeader) + computeSymtabSize() * 8;
2445 
2446   for (GdbChunk &chunk : chunks)
2447     size += chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
2448 
2449   // Add the constant pool size if exists.
2450   if (!symbols.empty()) {
2451     GdbSymbol &sym = symbols.back();
2452     size += sym.nameOff + sym.name.size() + 1;
2453   }
2454 }
2455 
2456 static std::vector<InputSection *> getDebugInfoSections() {
2457   std::vector<InputSection *> ret;
2458   for (InputSectionBase *s : inputSections)
2459     if (InputSection *isec = dyn_cast<InputSection>(s))
2460       if (isec->name == ".debug_info")
2461         ret.push_back(isec);
2462   return ret;
2463 }
2464 
2465 static std::vector<GdbIndexSection::CuEntry> readCuList(DWARFContext &dwarf) {
2466   std::vector<GdbIndexSection::CuEntry> ret;
2467   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
2468     ret.push_back({cu->getOffset(), cu->getLength() + 4});
2469   return ret;
2470 }
2471 
2472 static std::vector<GdbIndexSection::AddressEntry>
2473 readAddressAreas(DWARFContext &dwarf, InputSection *sec) {
2474   std::vector<GdbIndexSection::AddressEntry> ret;
2475 
2476   uint32_t cuIdx = 0;
2477   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
2478     if (Error e = cu->tryExtractDIEsIfNeeded(false)) {
2479       error(toString(sec) + ": " + toString(std::move(e)));
2480       return {};
2481     }
2482     Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
2483     if (!ranges) {
2484       error(toString(sec) + ": " + toString(ranges.takeError()));
2485       return {};
2486     }
2487 
2488     ArrayRef<InputSectionBase *> sections = sec->file->getSections();
2489     for (DWARFAddressRange &r : *ranges) {
2490       if (r.SectionIndex == -1ULL)
2491         continue;
2492       InputSectionBase *s = sections[r.SectionIndex];
2493       if (!s || s == &InputSection::discarded || !s->isLive())
2494         continue;
2495       // Range list with zero size has no effect.
2496       if (r.LowPC == r.HighPC)
2497         continue;
2498       auto *isec = cast<InputSection>(s);
2499       uint64_t offset = isec->getOffsetInFile();
2500       ret.push_back({isec, r.LowPC - offset, r.HighPC - offset, cuIdx});
2501     }
2502     ++cuIdx;
2503   }
2504 
2505   return ret;
2506 }
2507 
2508 template <class ELFT>
2509 static std::vector<GdbIndexSection::NameAttrEntry>
2510 readPubNamesAndTypes(const LLDDwarfObj<ELFT> &obj,
2511                      const std::vector<GdbIndexSection::CuEntry> &cus) {
2512   const DWARFSection &pubNames = obj.getGnuPubnamesSection();
2513   const DWARFSection &pubTypes = obj.getGnuPubtypesSection();
2514 
2515   std::vector<GdbIndexSection::NameAttrEntry> ret;
2516   for (const DWARFSection *pub : {&pubNames, &pubTypes}) {
2517     DWARFDebugPubTable table(obj, *pub, config->isLE, true);
2518     for (const DWARFDebugPubTable::Set &set : table.getData()) {
2519       // The value written into the constant pool is kind << 24 | cuIndex. As we
2520       // don't know how many compilation units precede this object to compute
2521       // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
2522       // the number of preceding compilation units later.
2523       uint32_t i = llvm::partition_point(cus,
2524                                          [&](GdbIndexSection::CuEntry cu) {
2525                                            return cu.cuOffset < set.Offset;
2526                                          }) -
2527                    cus.begin();
2528       for (const DWARFDebugPubTable::Entry &ent : set.Entries)
2529         ret.push_back({{ent.Name, computeGdbHash(ent.Name)},
2530                        (ent.Descriptor.toBits() << 24) | i});
2531     }
2532   }
2533   return ret;
2534 }
2535 
2536 // Create a list of symbols from a given list of symbol names and types
2537 // by uniquifying them by name.
2538 static std::vector<GdbIndexSection::GdbSymbol>
2539 createSymbols(ArrayRef<std::vector<GdbIndexSection::NameAttrEntry>> nameAttrs,
2540               const std::vector<GdbIndexSection::GdbChunk> &chunks) {
2541   using GdbSymbol = GdbIndexSection::GdbSymbol;
2542   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
2543 
2544   // For each chunk, compute the number of compilation units preceding it.
2545   uint32_t cuIdx = 0;
2546   std::vector<uint32_t> cuIdxs(chunks.size());
2547   for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
2548     cuIdxs[i] = cuIdx;
2549     cuIdx += chunks[i].compilationUnits.size();
2550   }
2551 
2552   // The number of symbols we will handle in this function is of the order
2553   // of millions for very large executables, so we use multi-threading to
2554   // speed it up.
2555   size_t numShards = 32;
2556   size_t concurrency = 1;
2557   if (threadsEnabled)
2558     concurrency =
2559         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), numShards);
2560 
2561   // A sharded map to uniquify symbols by name.
2562   std::vector<DenseMap<CachedHashStringRef, size_t>> map(numShards);
2563   size_t shift = 32 - countTrailingZeros(numShards);
2564 
2565   // Instantiate GdbSymbols while uniqufying them by name.
2566   std::vector<std::vector<GdbSymbol>> symbols(numShards);
2567   parallelForEachN(0, concurrency, [&](size_t threadId) {
2568     uint32_t i = 0;
2569     for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
2570       for (const NameAttrEntry &ent : entries) {
2571         size_t shardId = ent.name.hash() >> shift;
2572         if ((shardId & (concurrency - 1)) != threadId)
2573           continue;
2574 
2575         uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
2576         size_t &idx = map[shardId][ent.name];
2577         if (idx) {
2578           symbols[shardId][idx - 1].cuVector.push_back(v);
2579           continue;
2580         }
2581 
2582         idx = symbols[shardId].size() + 1;
2583         symbols[shardId].push_back({ent.name, {v}, 0, 0});
2584       }
2585       ++i;
2586     }
2587   });
2588 
2589   size_t numSymbols = 0;
2590   for (ArrayRef<GdbSymbol> v : symbols)
2591     numSymbols += v.size();
2592 
2593   // The return type is a flattened vector, so we'll copy each vector
2594   // contents to Ret.
2595   std::vector<GdbSymbol> ret;
2596   ret.reserve(numSymbols);
2597   for (std::vector<GdbSymbol> &vec : symbols)
2598     for (GdbSymbol &sym : vec)
2599       ret.push_back(std::move(sym));
2600 
2601   // CU vectors and symbol names are adjacent in the output file.
2602   // We can compute their offsets in the output file now.
2603   size_t off = 0;
2604   for (GdbSymbol &sym : ret) {
2605     sym.cuVectorOff = off;
2606     off += (sym.cuVector.size() + 1) * 4;
2607   }
2608   for (GdbSymbol &sym : ret) {
2609     sym.nameOff = off;
2610     off += sym.name.size() + 1;
2611   }
2612 
2613   return ret;
2614 }
2615 
2616 // Returns a newly-created .gdb_index section.
2617 template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
2618   std::vector<InputSection *> sections = getDebugInfoSections();
2619 
2620   // .debug_gnu_pub{names,types} are useless in executables.
2621   // They are present in input object files solely for creating
2622   // a .gdb_index. So we can remove them from the output.
2623   for (InputSectionBase *s : inputSections)
2624     if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
2625       s->markDead();
2626 
2627   std::vector<GdbChunk> chunks(sections.size());
2628   std::vector<std::vector<NameAttrEntry>> nameAttrs(sections.size());
2629 
2630   parallelForEachN(0, sections.size(), [&](size_t i) {
2631     ObjFile<ELFT> *file = sections[i]->getFile<ELFT>();
2632     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
2633 
2634     chunks[i].sec = sections[i];
2635     chunks[i].compilationUnits = readCuList(dwarf);
2636     chunks[i].addressAreas = readAddressAreas(dwarf, sections[i]);
2637     nameAttrs[i] = readPubNamesAndTypes<ELFT>(
2638         static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj()),
2639         chunks[i].compilationUnits);
2640   });
2641 
2642   auto *ret = make<GdbIndexSection>();
2643   ret->chunks = std::move(chunks);
2644   ret->symbols = createSymbols(nameAttrs, ret->chunks);
2645   ret->initOutputSize();
2646   return ret;
2647 }
2648 
2649 void GdbIndexSection::writeTo(uint8_t *buf) {
2650   // Write the header.
2651   auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
2652   uint8_t *start = buf;
2653   hdr->version = 7;
2654   buf += sizeof(*hdr);
2655 
2656   // Write the CU list.
2657   hdr->cuListOff = buf - start;
2658   for (GdbChunk &chunk : chunks) {
2659     for (CuEntry &cu : chunk.compilationUnits) {
2660       write64le(buf, chunk.sec->outSecOff + cu.cuOffset);
2661       write64le(buf + 8, cu.cuLength);
2662       buf += 16;
2663     }
2664   }
2665 
2666   // Write the address area.
2667   hdr->cuTypesOff = buf - start;
2668   hdr->addressAreaOff = buf - start;
2669   uint32_t cuOff = 0;
2670   for (GdbChunk &chunk : chunks) {
2671     for (AddressEntry &e : chunk.addressAreas) {
2672       uint64_t baseAddr = e.section->getVA(0);
2673       write64le(buf, baseAddr + e.lowAddress);
2674       write64le(buf + 8, baseAddr + e.highAddress);
2675       write32le(buf + 16, e.cuIndex + cuOff);
2676       buf += 20;
2677     }
2678     cuOff += chunk.compilationUnits.size();
2679   }
2680 
2681   // Write the on-disk open-addressing hash table containing symbols.
2682   hdr->symtabOff = buf - start;
2683   size_t symtabSize = computeSymtabSize();
2684   uint32_t mask = symtabSize - 1;
2685 
2686   for (GdbSymbol &sym : symbols) {
2687     uint32_t h = sym.name.hash();
2688     uint32_t i = h & mask;
2689     uint32_t step = ((h * 17) & mask) | 1;
2690 
2691     while (read32le(buf + i * 8))
2692       i = (i + step) & mask;
2693 
2694     write32le(buf + i * 8, sym.nameOff);
2695     write32le(buf + i * 8 + 4, sym.cuVectorOff);
2696   }
2697 
2698   buf += symtabSize * 8;
2699 
2700   // Write the string pool.
2701   hdr->constantPoolOff = buf - start;
2702   parallelForEach(symbols, [&](GdbSymbol &sym) {
2703     memcpy(buf + sym.nameOff, sym.name.data(), sym.name.size());
2704   });
2705 
2706   // Write the CU vectors.
2707   for (GdbSymbol &sym : symbols) {
2708     write32le(buf, sym.cuVector.size());
2709     buf += 4;
2710     for (uint32_t val : sym.cuVector) {
2711       write32le(buf, val);
2712       buf += 4;
2713     }
2714   }
2715 }
2716 
2717 bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
2718 
2719 EhFrameHeader::EhFrameHeader()
2720     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
2721 
2722 void EhFrameHeader::writeTo(uint8_t *buf) {
2723   // Unlike most sections, the EhFrameHeader section is written while writing
2724   // another section, namely EhFrameSection, which calls the write() function
2725   // below from its writeTo() function. This is necessary because the contents
2726   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
2727   // don't know which order the sections will be written in.
2728 }
2729 
2730 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2731 // Each entry of the search table consists of two values,
2732 // the starting PC from where FDEs covers, and the FDE's address.
2733 // It is sorted by PC.
2734 void EhFrameHeader::write() {
2735   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
2736   using FdeData = EhFrameSection::FdeData;
2737 
2738   std::vector<FdeData> fdes = getPartition().ehFrame->getFdeData();
2739 
2740   buf[0] = 1;
2741   buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2742   buf[2] = DW_EH_PE_udata4;
2743   buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2744   write32(buf + 4,
2745           getPartition().ehFrame->getParent()->addr - this->getVA() - 4);
2746   write32(buf + 8, fdes.size());
2747   buf += 12;
2748 
2749   for (FdeData &fde : fdes) {
2750     write32(buf, fde.pcRel);
2751     write32(buf + 4, fde.fdeVARel);
2752     buf += 8;
2753   }
2754 }
2755 
2756 size_t EhFrameHeader::getSize() const {
2757   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
2758   return 12 + getPartition().ehFrame->numFdes * 8;
2759 }
2760 
2761 bool EhFrameHeader::isNeeded() const {
2762   return isLive() && getPartition().ehFrame->isNeeded();
2763 }
2764 
2765 VersionDefinitionSection::VersionDefinitionSection()
2766     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2767                        ".gnu.version_d") {}
2768 
2769 StringRef VersionDefinitionSection::getFileDefName() {
2770   if (!getPartition().name.empty())
2771     return getPartition().name;
2772   if (!config->soName.empty())
2773     return config->soName;
2774   return config->outputFile;
2775 }
2776 
2777 void VersionDefinitionSection::finalizeContents() {
2778   fileDefNameOff = getPartition().dynStrTab->addString(getFileDefName());
2779   for (const VersionDefinition &v : namedVersionDefs())
2780     verDefNameOffs.push_back(getPartition().dynStrTab->addString(v.name));
2781 
2782   if (OutputSection *sec = getPartition().dynStrTab->getParent())
2783     getParent()->link = sec->sectionIndex;
2784 
2785   // sh_info should be set to the number of definitions. This fact is missed in
2786   // documentation, but confirmed by binutils community:
2787   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
2788   getParent()->info = getVerDefNum();
2789 }
2790 
2791 void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
2792                                         StringRef name, size_t nameOff) {
2793   uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
2794 
2795   // Write a verdef.
2796   write16(buf, 1);                  // vd_version
2797   write16(buf + 2, flags);          // vd_flags
2798   write16(buf + 4, index);          // vd_ndx
2799   write16(buf + 6, 1);              // vd_cnt
2800   write32(buf + 8, hashSysV(name)); // vd_hash
2801   write32(buf + 12, 20);            // vd_aux
2802   write32(buf + 16, 28);            // vd_next
2803 
2804   // Write a veraux.
2805   write32(buf + 20, nameOff); // vda_name
2806   write32(buf + 24, 0);       // vda_next
2807 }
2808 
2809 void VersionDefinitionSection::writeTo(uint8_t *buf) {
2810   writeOne(buf, 1, getFileDefName(), fileDefNameOff);
2811 
2812   auto nameOffIt = verDefNameOffs.begin();
2813   for (const VersionDefinition &v : namedVersionDefs()) {
2814     buf += EntrySize;
2815     writeOne(buf, v.id, v.name, *nameOffIt++);
2816   }
2817 
2818   // Need to terminate the last version definition.
2819   write32(buf + 16, 0); // vd_next
2820 }
2821 
2822 size_t VersionDefinitionSection::getSize() const {
2823   return EntrySize * getVerDefNum();
2824 }
2825 
2826 // .gnu.version is a table where each entry is 2 byte long.
2827 VersionTableSection::VersionTableSection()
2828     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
2829                        ".gnu.version") {
2830   this->entsize = 2;
2831 }
2832 
2833 void VersionTableSection::finalizeContents() {
2834   // At the moment of june 2016 GNU docs does not mention that sh_link field
2835   // should be set, but Sun docs do. Also readelf relies on this field.
2836   getParent()->link = getPartition().dynSymTab->getParent()->sectionIndex;
2837 }
2838 
2839 size_t VersionTableSection::getSize() const {
2840   return (getPartition().dynSymTab->getSymbols().size() + 1) * 2;
2841 }
2842 
2843 void VersionTableSection::writeTo(uint8_t *buf) {
2844   buf += 2;
2845   for (const SymbolTableEntry &s : getPartition().dynSymTab->getSymbols()) {
2846     write16(buf, s.sym->versionId);
2847     buf += 2;
2848   }
2849 }
2850 
2851 bool VersionTableSection::isNeeded() const {
2852   return getPartition().verDef || getPartition().verNeed->isNeeded();
2853 }
2854 
2855 void elf::addVerneed(Symbol *ss) {
2856   auto &file = cast<SharedFile>(*ss->file);
2857   if (ss->verdefIndex == VER_NDX_GLOBAL) {
2858     ss->versionId = VER_NDX_GLOBAL;
2859     return;
2860   }
2861 
2862   if (file.vernauxs.empty())
2863     file.vernauxs.resize(file.verdefs.size());
2864 
2865   // Select a version identifier for the vernaux data structure, if we haven't
2866   // already allocated one. The verdef identifiers cover the range
2867   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
2868   // getVerDefNum()+1.
2869   if (file.vernauxs[ss->verdefIndex] == 0)
2870     file.vernauxs[ss->verdefIndex] = ++SharedFile::vernauxNum + getVerDefNum();
2871 
2872   ss->versionId = file.vernauxs[ss->verdefIndex];
2873 }
2874 
2875 template <class ELFT>
2876 VersionNeedSection<ELFT>::VersionNeedSection()
2877     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2878                        ".gnu.version_r") {}
2879 
2880 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
2881   for (SharedFile *f : sharedFiles) {
2882     if (f->vernauxs.empty())
2883       continue;
2884     verneeds.emplace_back();
2885     Verneed &vn = verneeds.back();
2886     vn.nameStrTab = getPartition().dynStrTab->addString(f->soName);
2887     for (unsigned i = 0; i != f->vernauxs.size(); ++i) {
2888       if (f->vernauxs[i] == 0)
2889         continue;
2890       auto *verdef =
2891           reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
2892       vn.vernauxs.push_back(
2893           {verdef->vd_hash, f->vernauxs[i],
2894            getPartition().dynStrTab->addString(f->getStringTable().data() +
2895                                                verdef->getAux()->vda_name)});
2896     }
2897   }
2898 
2899   if (OutputSection *sec = getPartition().dynStrTab->getParent())
2900     getParent()->link = sec->sectionIndex;
2901   getParent()->info = verneeds.size();
2902 }
2903 
2904 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
2905   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2906   auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
2907   auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
2908 
2909   for (auto &vn : verneeds) {
2910     // Create an Elf_Verneed for this DSO.
2911     verneed->vn_version = 1;
2912     verneed->vn_cnt = vn.vernauxs.size();
2913     verneed->vn_file = vn.nameStrTab;
2914     verneed->vn_aux =
2915         reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
2916     verneed->vn_next = sizeof(Elf_Verneed);
2917     ++verneed;
2918 
2919     // Create the Elf_Vernauxs for this Elf_Verneed.
2920     for (auto &vna : vn.vernauxs) {
2921       vernaux->vna_hash = vna.hash;
2922       vernaux->vna_flags = 0;
2923       vernaux->vna_other = vna.verneedIndex;
2924       vernaux->vna_name = vna.nameStrTab;
2925       vernaux->vna_next = sizeof(Elf_Vernaux);
2926       ++vernaux;
2927     }
2928 
2929     vernaux[-1].vna_next = 0;
2930   }
2931   verneed[-1].vn_next = 0;
2932 }
2933 
2934 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2935   return verneeds.size() * sizeof(Elf_Verneed) +
2936          SharedFile::vernauxNum * sizeof(Elf_Vernaux);
2937 }
2938 
2939 template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
2940   return SharedFile::vernauxNum != 0;
2941 }
2942 
2943 void MergeSyntheticSection::addSection(MergeInputSection *ms) {
2944   ms->parent = this;
2945   sections.push_back(ms);
2946   assert(alignment == ms->alignment || !(ms->flags & SHF_STRINGS));
2947   alignment = std::max(alignment, ms->alignment);
2948 }
2949 
2950 MergeTailSection::MergeTailSection(StringRef name, uint32_t type,
2951                                    uint64_t flags, uint32_t alignment)
2952     : MergeSyntheticSection(name, type, flags, alignment),
2953       builder(StringTableBuilder::RAW, alignment) {}
2954 
2955 size_t MergeTailSection::getSize() const { return builder.getSize(); }
2956 
2957 void MergeTailSection::writeTo(uint8_t *buf) { builder.write(buf); }
2958 
2959 void MergeTailSection::finalizeContents() {
2960   // Add all string pieces to the string table builder to create section
2961   // contents.
2962   for (MergeInputSection *sec : sections)
2963     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
2964       if (sec->pieces[i].live)
2965         builder.add(sec->getData(i));
2966 
2967   // Fix the string table content. After this, the contents will never change.
2968   builder.finalize();
2969 
2970   // finalize() fixed tail-optimized strings, so we can now get
2971   // offsets of strings. Get an offset for each string and save it
2972   // to a corresponding SectionPiece for easy access.
2973   for (MergeInputSection *sec : sections)
2974     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
2975       if (sec->pieces[i].live)
2976         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
2977 }
2978 
2979 void MergeNoTailSection::writeTo(uint8_t *buf) {
2980   for (size_t i = 0; i < numShards; ++i)
2981     shards[i].write(buf + shardOffsets[i]);
2982 }
2983 
2984 // This function is very hot (i.e. it can take several seconds to finish)
2985 // because sometimes the number of inputs is in an order of magnitude of
2986 // millions. So, we use multi-threading.
2987 //
2988 // For any strings S and T, we know S is not mergeable with T if S's hash
2989 // value is different from T's. If that's the case, we can safely put S and
2990 // T into different string builders without worrying about merge misses.
2991 // We do it in parallel.
2992 void MergeNoTailSection::finalizeContents() {
2993   // Initializes string table builders.
2994   for (size_t i = 0; i < numShards; ++i)
2995     shards.emplace_back(StringTableBuilder::RAW, alignment);
2996 
2997   // Concurrency level. Must be a power of 2 to avoid expensive modulo
2998   // operations in the following tight loop.
2999   size_t concurrency = 1;
3000   if (threadsEnabled)
3001     concurrency =
3002         std::min<size_t>(PowerOf2Floor(hardware_concurrency()), numShards);
3003 
3004   // Add section pieces to the builders.
3005   parallelForEachN(0, concurrency, [&](size_t threadId) {
3006     for (MergeInputSection *sec : sections) {
3007       for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
3008         if (!sec->pieces[i].live)
3009           continue;
3010         size_t shardId = getShardId(sec->pieces[i].hash);
3011         if ((shardId & (concurrency - 1)) == threadId)
3012           sec->pieces[i].outputOff = shards[shardId].add(sec->getData(i));
3013       }
3014     }
3015   });
3016 
3017   // Compute an in-section offset for each shard.
3018   size_t off = 0;
3019   for (size_t i = 0; i < numShards; ++i) {
3020     shards[i].finalizeInOrder();
3021     if (shards[i].getSize() > 0)
3022       off = alignTo(off, alignment);
3023     shardOffsets[i] = off;
3024     off += shards[i].getSize();
3025   }
3026   size = off;
3027 
3028   // So far, section pieces have offsets from beginning of shards, but
3029   // we want offsets from beginning of the whole section. Fix them.
3030   parallelForEach(sections, [&](MergeInputSection *sec) {
3031     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3032       if (sec->pieces[i].live)
3033         sec->pieces[i].outputOff +=
3034             shardOffsets[getShardId(sec->pieces[i].hash)];
3035   });
3036 }
3037 
3038 static MergeSyntheticSection *createMergeSynthetic(StringRef name,
3039                                                    uint32_t type,
3040                                                    uint64_t flags,
3041                                                    uint32_t alignment) {
3042   bool shouldTailMerge = (flags & SHF_STRINGS) && config->optimize >= 2;
3043   if (shouldTailMerge)
3044     return make<MergeTailSection>(name, type, flags, alignment);
3045   return make<MergeNoTailSection>(name, type, flags, alignment);
3046 }
3047 
3048 template <class ELFT> void elf::splitSections() {
3049   // splitIntoPieces needs to be called on each MergeInputSection
3050   // before calling finalizeContents().
3051   parallelForEach(inputSections, [](InputSectionBase *sec) {
3052     if (auto *s = dyn_cast<MergeInputSection>(sec))
3053       s->splitIntoPieces();
3054     else if (auto *eh = dyn_cast<EhInputSection>(sec))
3055       eh->split<ELFT>();
3056   });
3057 }
3058 
3059 // This function scans over the inputsections to create mergeable
3060 // synthetic sections.
3061 //
3062 // It removes MergeInputSections from the input section array and adds
3063 // new synthetic sections at the location of the first input section
3064 // that it replaces. It then finalizes each synthetic section in order
3065 // to compute an output offset for each piece of each input section.
3066 void elf::mergeSections() {
3067   std::vector<MergeSyntheticSection *> mergeSections;
3068   for (InputSectionBase *&s : inputSections) {
3069     MergeInputSection *ms = dyn_cast<MergeInputSection>(s);
3070     if (!ms)
3071       continue;
3072 
3073     // We do not want to handle sections that are not alive, so just remove
3074     // them instead of trying to merge.
3075     if (!ms->isLive()) {
3076       s = nullptr;
3077       continue;
3078     }
3079 
3080     StringRef outsecName = getOutputSectionName(ms);
3081 
3082     auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) {
3083       // While we could create a single synthetic section for two different
3084       // values of Entsize, it is better to take Entsize into consideration.
3085       //
3086       // With a single synthetic section no two pieces with different Entsize
3087       // could be equal, so we may as well have two sections.
3088       //
3089       // Using Entsize in here also allows us to propagate it to the synthetic
3090       // section.
3091       //
3092       // SHF_STRINGS section with different alignments should not be merged.
3093       return sec->name == outsecName && sec->flags == ms->flags &&
3094              sec->entsize == ms->entsize &&
3095              (sec->alignment == ms->alignment || !(sec->flags & SHF_STRINGS));
3096     });
3097     if (i == mergeSections.end()) {
3098       MergeSyntheticSection *syn =
3099           createMergeSynthetic(outsecName, ms->type, ms->flags, ms->alignment);
3100       mergeSections.push_back(syn);
3101       i = std::prev(mergeSections.end());
3102       s = syn;
3103       syn->entsize = ms->entsize;
3104     } else {
3105       s = nullptr;
3106     }
3107     (*i)->addSection(ms);
3108   }
3109   for (auto *ms : mergeSections)
3110     ms->finalizeContents();
3111 
3112   std::vector<InputSectionBase *> &v = inputSections;
3113   v.erase(std::remove(v.begin(), v.end(), nullptr), v.end());
3114 }
3115 
3116 MipsRldMapSection::MipsRldMapSection()
3117     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
3118                        ".rld_map") {}
3119 
3120 ARMExidxSyntheticSection::ARMExidxSyntheticSection()
3121     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
3122                        config->wordsize, ".ARM.exidx") {}
3123 
3124 static InputSection *findExidxSection(InputSection *isec) {
3125   for (InputSection *d : isec->dependentSections)
3126     if (d->type == SHT_ARM_EXIDX)
3127       return d;
3128   return nullptr;
3129 }
3130 
3131 bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
3132   if (isec->type == SHT_ARM_EXIDX) {
3133     exidxSections.push_back(isec);
3134     return true;
3135   }
3136 
3137   if ((isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
3138       isec->getSize() > 0) {
3139     executableSections.push_back(isec);
3140     if (empty && findExidxSection(isec))
3141       empty = false;
3142     return false;
3143   }
3144 
3145   // FIXME: we do not output a relocation section when --emit-relocs is used
3146   // as we do not have relocation sections for linker generated table entries
3147   // and we would have to erase at a late stage relocations from merged entries.
3148   // Given that exception tables are already position independent and a binary
3149   // analyzer could derive the relocations we choose to erase the relocations.
3150   if (config->emitRelocs && isec->type == SHT_REL)
3151     if (InputSectionBase *ex = isec->getRelocatedSection())
3152       if (isa<InputSection>(ex) && ex->type == SHT_ARM_EXIDX)
3153         return true;
3154 
3155   return false;
3156 }
3157 
3158 // References to .ARM.Extab Sections have bit 31 clear and are not the
3159 // special EXIDX_CANTUNWIND bit-pattern.
3160 static bool isExtabRef(uint32_t unwind) {
3161   return (unwind & 0x80000000) == 0 && unwind != 0x1;
3162 }
3163 
3164 // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
3165 // section Prev, where Cur follows Prev in the table. This can be done if the
3166 // unwinding instructions in Cur are identical to Prev. Linker generated
3167 // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
3168 // InputSection.
3169 static bool isDuplicateArmExidxSec(InputSection *prev, InputSection *cur) {
3170 
3171   struct ExidxEntry {
3172     ulittle32_t fn;
3173     ulittle32_t unwind;
3174   };
3175   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
3176   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
3177   ExidxEntry prevEntry = {ulittle32_t(0), ulittle32_t(1)};
3178   if (prev)
3179     prevEntry = prev->getDataAs<ExidxEntry>().back();
3180   if (isExtabRef(prevEntry.unwind))
3181     return false;
3182 
3183   // We consider the unwind instructions of an .ARM.exidx table entry
3184   // a duplicate if the previous unwind instructions if:
3185   // - Both are the special EXIDX_CANTUNWIND.
3186   // - Both are the same inline unwind instructions.
3187   // We do not attempt to follow and check links into .ARM.extab tables as
3188   // consecutive identical entries are rare and the effort to check that they
3189   // are identical is high.
3190 
3191   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
3192   if (cur == nullptr)
3193     return prevEntry.unwind == 1;
3194 
3195   for (const ExidxEntry entry : cur->getDataAs<ExidxEntry>())
3196     if (isExtabRef(entry.unwind) || entry.unwind != prevEntry.unwind)
3197       return false;
3198 
3199   // All table entries in this .ARM.exidx Section can be merged into the
3200   // previous Section.
3201   return true;
3202 }
3203 
3204 // The .ARM.exidx table must be sorted in ascending order of the address of the
3205 // functions the table describes. Optionally duplicate adjacent table entries
3206 // can be removed. At the end of the function the executableSections must be
3207 // sorted in ascending order of address, Sentinel is set to the InputSection
3208 // with the highest address and any InputSections that have mergeable
3209 // .ARM.exidx table entries are removed from it.
3210 void ARMExidxSyntheticSection::finalizeContents() {
3211   if (script->hasSectionsCommand) {
3212     // The executableSections and exidxSections that we use to derive the
3213     // final contents of this SyntheticSection are populated before the
3214     // linker script assigns InputSections to OutputSections. The linker script
3215     // SECTIONS command may have a /DISCARD/ entry that removes executable
3216     // InputSections and their dependent .ARM.exidx section that we recorded
3217     // earlier.
3218     auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
3219     llvm::erase_if(executableSections, isDiscarded);
3220     llvm::erase_if(exidxSections, isDiscarded);
3221   }
3222 
3223   // Sort the executable sections that may or may not have associated
3224   // .ARM.exidx sections by order of ascending address. This requires the
3225   // relative positions of InputSections to be known.
3226   auto compareByFilePosition = [](const InputSection *a,
3227                                   const InputSection *b) {
3228     OutputSection *aOut = a->getParent();
3229     OutputSection *bOut = b->getParent();
3230 
3231     if (aOut != bOut)
3232       return aOut->sectionIndex < bOut->sectionIndex;
3233     return a->outSecOff < b->outSecOff;
3234   };
3235   llvm::stable_sort(executableSections, compareByFilePosition);
3236   sentinel = executableSections.back();
3237   // Optionally merge adjacent duplicate entries.
3238   if (config->mergeArmExidx) {
3239     std::vector<InputSection *> selectedSections;
3240     selectedSections.reserve(executableSections.size());
3241     selectedSections.push_back(executableSections[0]);
3242     size_t prev = 0;
3243     for (size_t i = 1; i < executableSections.size(); ++i) {
3244       InputSection *ex1 = findExidxSection(executableSections[prev]);
3245       InputSection *ex2 = findExidxSection(executableSections[i]);
3246       if (!isDuplicateArmExidxSec(ex1, ex2)) {
3247         selectedSections.push_back(executableSections[i]);
3248         prev = i;
3249       }
3250     }
3251     executableSections = std::move(selectedSections);
3252   }
3253 
3254   size_t offset = 0;
3255   size = 0;
3256   for (InputSection *isec : executableSections) {
3257     if (InputSection *d = findExidxSection(isec)) {
3258       d->outSecOff = offset;
3259       d->parent = getParent();
3260       offset += d->getSize();
3261     } else {
3262       offset += 8;
3263     }
3264   }
3265   // Size includes Sentinel.
3266   size = offset + 8;
3267 }
3268 
3269 InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
3270   return executableSections.front();
3271 }
3272 
3273 // To write the .ARM.exidx table from the ExecutableSections we have three cases
3274 // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
3275 //     We write the .ARM.exidx section contents and apply its relocations.
3276 // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
3277 //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
3278 //     start of the InputSection as the purpose of the linker generated
3279 //     section is to terminate the address range of the previous entry.
3280 // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
3281 //     the table to terminate the address range of the final entry.
3282 void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
3283 
3284   const uint8_t cantUnwindData[8] = {0, 0, 0, 0,  // PREL31 to target
3285                                      1, 0, 0, 0}; // EXIDX_CANTUNWIND
3286 
3287   uint64_t offset = 0;
3288   for (InputSection *isec : executableSections) {
3289     assert(isec->getParent() != nullptr);
3290     if (InputSection *d = findExidxSection(isec)) {
3291       memcpy(buf + offset, d->data().data(), d->data().size());
3292       d->relocateAlloc(buf, buf + d->getSize());
3293       offset += d->getSize();
3294     } else {
3295       // A Linker generated CANTUNWIND section.
3296       memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3297       uint64_t s = isec->getVA();
3298       uint64_t p = getVA() + offset;
3299       target->relocateOne(buf + offset, R_ARM_PREL31, s - p);
3300       offset += 8;
3301     }
3302   }
3303   // Write Sentinel.
3304   memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3305   uint64_t s = sentinel->getVA(sentinel->getSize());
3306   uint64_t p = getVA() + offset;
3307   target->relocateOne(buf + offset, R_ARM_PREL31, s - p);
3308   assert(size == offset + 8);
3309 }
3310 
3311 bool ARMExidxSyntheticSection::classof(const SectionBase *d) {
3312   return d->kind() == InputSectionBase::Synthetic && d->type == SHT_ARM_EXIDX;
3313 }
3314 
3315 ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
3316     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
3317                        config->wordsize, ".text.thunk") {
3318   this->parent = os;
3319   this->outSecOff = off;
3320 }
3321 
3322 void ThunkSection::addThunk(Thunk *t) {
3323   thunks.push_back(t);
3324   t->addSymbols(*this);
3325 }
3326 
3327 void ThunkSection::writeTo(uint8_t *buf) {
3328   for (Thunk *t : thunks)
3329     t->writeTo(buf + t->offset);
3330 }
3331 
3332 InputSection *ThunkSection::getTargetInputSection() const {
3333   if (thunks.empty())
3334     return nullptr;
3335   const Thunk *t = thunks.front();
3336   return t->getTargetInputSection();
3337 }
3338 
3339 bool ThunkSection::assignOffsets() {
3340   uint64_t off = 0;
3341   for (Thunk *t : thunks) {
3342     off = alignTo(off, t->alignment);
3343     t->setOffset(off);
3344     uint32_t size = t->size();
3345     t->getThunkTargetSym()->size = size;
3346     off += size;
3347   }
3348   bool changed = off != size;
3349   size = off;
3350   return changed;
3351 }
3352 
3353 PPC32Got2Section::PPC32Got2Section()
3354     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
3355 
3356 bool PPC32Got2Section::isNeeded() const {
3357   // See the comment below. This is not needed if there is no other
3358   // InputSection.
3359   for (BaseCommand *base : getParent()->sectionCommands)
3360     if (auto *isd = dyn_cast<InputSectionDescription>(base))
3361       for (InputSection *isec : isd->sections)
3362         if (isec != this)
3363           return true;
3364   return false;
3365 }
3366 
3367 void PPC32Got2Section::finalizeContents() {
3368   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
3369   // .got2 . This function computes outSecOff of each .got2 to be used in
3370   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
3371   // to collect input sections named ".got2".
3372   uint32_t offset = 0;
3373   for (BaseCommand *base : getParent()->sectionCommands)
3374     if (auto *isd = dyn_cast<InputSectionDescription>(base)) {
3375       for (InputSection *isec : isd->sections) {
3376         if (isec == this)
3377           continue;
3378         isec->file->ppc32Got2OutSecOff = offset;
3379         offset += (uint32_t)isec->getSize();
3380       }
3381     }
3382 }
3383 
3384 // If linking position-dependent code then the table will store the addresses
3385 // directly in the binary so the section has type SHT_PROGBITS. If linking
3386 // position-independent code the section has type SHT_NOBITS since it will be
3387 // allocated and filled in by the dynamic linker.
3388 PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
3389     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
3390                        config->isPic ? SHT_NOBITS : SHT_PROGBITS, 8,
3391                        ".branch_lt") {}
3392 
3393 void PPC64LongBranchTargetSection::addEntry(Symbol &sym) {
3394   assert(sym.ppc64BranchltIndex == 0xffff);
3395   sym.ppc64BranchltIndex = entries.size();
3396   entries.push_back(&sym);
3397 }
3398 
3399 size_t PPC64LongBranchTargetSection::getSize() const {
3400   return entries.size() * 8;
3401 }
3402 
3403 void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
3404   // If linking non-pic we have the final addresses of the targets and they get
3405   // written to the table directly. For pic the dynamic linker will allocate
3406   // the section and fill it it.
3407   if (config->isPic)
3408     return;
3409 
3410   for (const Symbol *sym : entries) {
3411     assert(sym->getVA());
3412     // Need calls to branch to the local entry-point since a long-branch
3413     // must be a local-call.
3414     write64(buf,
3415             sym->getVA() + getPPC64GlobalEntryToLocalEntryOffset(sym->stOther));
3416     buf += 8;
3417   }
3418 }
3419 
3420 bool PPC64LongBranchTargetSection::isNeeded() const {
3421   // `removeUnusedSyntheticSections()` is called before thunk allocation which
3422   // is too early to determine if this section will be empty or not. We need
3423   // Finalized to keep the section alive until after thunk creation. Finalized
3424   // only gets set to true once `finalizeSections()` is called after thunk
3425   // creation. Becuase of this, if we don't create any long-branch thunks we end
3426   // up with an empty .branch_lt section in the binary.
3427   return !finalized || !entries.empty();
3428 }
3429 
3430 RISCVSdataSection::RISCVSdataSection()
3431     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1, ".sdata") {}
3432 
3433 bool RISCVSdataSection::isNeeded() const {
3434   if (!ElfSym::riscvGlobalPointer)
3435     return false;
3436 
3437   // __global_pointer$ is defined relative to .sdata . If the section does not
3438   // exist, create a dummy one.
3439   for (BaseCommand *base : getParent()->sectionCommands)
3440     if (auto *isd = dyn_cast<InputSectionDescription>(base))
3441       for (InputSection *isec : isd->sections)
3442         if (isec != this)
3443           return false;
3444   return true;
3445 }
3446 
3447 static uint8_t getAbiVersion() {
3448   // MIPS non-PIC executable gets ABI version 1.
3449   if (config->emachine == EM_MIPS) {
3450     if (!config->isPic && !config->relocatable &&
3451         (config->eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
3452       return 1;
3453     return 0;
3454   }
3455 
3456   if (config->emachine == EM_AMDGPU) {
3457     uint8_t ver = objectFiles[0]->abiVersion;
3458     for (InputFile *file : makeArrayRef(objectFiles).slice(1))
3459       if (file->abiVersion != ver)
3460         error("incompatible ABI version: " + toString(file));
3461     return ver;
3462   }
3463 
3464   return 0;
3465 }
3466 
3467 template <typename ELFT> void elf::writeEhdr(uint8_t *buf, Partition &part) {
3468   // For executable segments, the trap instructions are written before writing
3469   // the header. Setting Elf header bytes to zero ensures that any unused bytes
3470   // in header are zero-cleared, instead of having trap instructions.
3471   memset(buf, 0, sizeof(typename ELFT::Ehdr));
3472   memcpy(buf, "\177ELF", 4);
3473 
3474   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3475   eHdr->e_ident[EI_CLASS] = config->is64 ? ELFCLASS64 : ELFCLASS32;
3476   eHdr->e_ident[EI_DATA] = config->isLE ? ELFDATA2LSB : ELFDATA2MSB;
3477   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
3478   eHdr->e_ident[EI_OSABI] = config->osabi;
3479   eHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
3480   eHdr->e_machine = config->emachine;
3481   eHdr->e_version = EV_CURRENT;
3482   eHdr->e_flags = config->eflags;
3483   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
3484   eHdr->e_phnum = part.phdrs.size();
3485   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
3486 
3487   if (!config->relocatable) {
3488     eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
3489     eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
3490   }
3491 }
3492 
3493 template <typename ELFT> void elf::writePhdrs(uint8_t *buf, Partition &part) {
3494   // Write the program header table.
3495   auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
3496   for (PhdrEntry *p : part.phdrs) {
3497     hBuf->p_type = p->p_type;
3498     hBuf->p_flags = p->p_flags;
3499     hBuf->p_offset = p->p_offset;
3500     hBuf->p_vaddr = p->p_vaddr;
3501     hBuf->p_paddr = p->p_paddr;
3502     hBuf->p_filesz = p->p_filesz;
3503     hBuf->p_memsz = p->p_memsz;
3504     hBuf->p_align = p->p_align;
3505     ++hBuf;
3506   }
3507 }
3508 
3509 template <typename ELFT>
3510 PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
3511     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
3512 
3513 template <typename ELFT>
3514 size_t PartitionElfHeaderSection<ELFT>::getSize() const {
3515   return sizeof(typename ELFT::Ehdr);
3516 }
3517 
3518 template <typename ELFT>
3519 void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
3520   writeEhdr<ELFT>(buf, getPartition());
3521 
3522   // Loadable partitions are always ET_DYN.
3523   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3524   eHdr->e_type = ET_DYN;
3525 }
3526 
3527 template <typename ELFT>
3528 PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
3529     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
3530 
3531 template <typename ELFT>
3532 size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
3533   return sizeof(typename ELFT::Phdr) * getPartition().phdrs.size();
3534 }
3535 
3536 template <typename ELFT>
3537 void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
3538   writePhdrs<ELFT>(buf, getPartition());
3539 }
3540 
3541 PartitionIndexSection::PartitionIndexSection()
3542     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
3543 
3544 size_t PartitionIndexSection::getSize() const {
3545   return 12 * (partitions.size() - 1);
3546 }
3547 
3548 void PartitionIndexSection::finalizeContents() {
3549   for (size_t i = 1; i != partitions.size(); ++i)
3550     partitions[i].nameStrTab = mainPart->dynStrTab->addString(partitions[i].name);
3551 }
3552 
3553 void PartitionIndexSection::writeTo(uint8_t *buf) {
3554   uint64_t va = getVA();
3555   for (size_t i = 1; i != partitions.size(); ++i) {
3556     write32(buf, mainPart->dynStrTab->getVA() + partitions[i].nameStrTab - va);
3557     write32(buf + 4, partitions[i].elfHeader->getVA() - (va + 4));
3558 
3559     SyntheticSection *next =
3560         i == partitions.size() - 1 ? in.partEnd : partitions[i + 1].elfHeader;
3561     write32(buf + 8, next->getVA() - partitions[i].elfHeader->getVA());
3562 
3563     va += 12;
3564     buf += 12;
3565   }
3566 }
3567 
3568 InStruct elf::in;
3569 
3570 std::vector<Partition> elf::partitions;
3571 Partition *elf::mainPart;
3572 
3573 template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3574 template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3575 template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3576 template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3577 
3578 template void elf::splitSections<ELF32LE>();
3579 template void elf::splitSections<ELF32BE>();
3580 template void elf::splitSections<ELF64LE>();
3581 template void elf::splitSections<ELF64BE>();
3582 
3583 template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
3584 template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
3585 template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
3586 template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
3587 
3588 template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
3589 template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
3590 template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
3591 template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
3592 
3593 template class elf::MipsAbiFlagsSection<ELF32LE>;
3594 template class elf::MipsAbiFlagsSection<ELF32BE>;
3595 template class elf::MipsAbiFlagsSection<ELF64LE>;
3596 template class elf::MipsAbiFlagsSection<ELF64BE>;
3597 
3598 template class elf::MipsOptionsSection<ELF32LE>;
3599 template class elf::MipsOptionsSection<ELF32BE>;
3600 template class elf::MipsOptionsSection<ELF64LE>;
3601 template class elf::MipsOptionsSection<ELF64BE>;
3602 
3603 template class elf::MipsReginfoSection<ELF32LE>;
3604 template class elf::MipsReginfoSection<ELF32BE>;
3605 template class elf::MipsReginfoSection<ELF64LE>;
3606 template class elf::MipsReginfoSection<ELF64BE>;
3607 
3608 template class elf::DynamicSection<ELF32LE>;
3609 template class elf::DynamicSection<ELF32BE>;
3610 template class elf::DynamicSection<ELF64LE>;
3611 template class elf::DynamicSection<ELF64BE>;
3612 
3613 template class elf::RelocationSection<ELF32LE>;
3614 template class elf::RelocationSection<ELF32BE>;
3615 template class elf::RelocationSection<ELF64LE>;
3616 template class elf::RelocationSection<ELF64BE>;
3617 
3618 template class elf::AndroidPackedRelocationSection<ELF32LE>;
3619 template class elf::AndroidPackedRelocationSection<ELF32BE>;
3620 template class elf::AndroidPackedRelocationSection<ELF64LE>;
3621 template class elf::AndroidPackedRelocationSection<ELF64BE>;
3622 
3623 template class elf::RelrSection<ELF32LE>;
3624 template class elf::RelrSection<ELF32BE>;
3625 template class elf::RelrSection<ELF64LE>;
3626 template class elf::RelrSection<ELF64BE>;
3627 
3628 template class elf::SymbolTableSection<ELF32LE>;
3629 template class elf::SymbolTableSection<ELF32BE>;
3630 template class elf::SymbolTableSection<ELF64LE>;
3631 template class elf::SymbolTableSection<ELF64BE>;
3632 
3633 template class elf::VersionNeedSection<ELF32LE>;
3634 template class elf::VersionNeedSection<ELF32BE>;
3635 template class elf::VersionNeedSection<ELF64LE>;
3636 template class elf::VersionNeedSection<ELF64BE>;
3637 
3638 template void elf::writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
3639 template void elf::writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
3640 template void elf::writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
3641 template void elf::writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
3642 
3643 template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
3644 template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
3645 template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
3646 template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
3647 
3648 template class elf::PartitionElfHeaderSection<ELF32LE>;
3649 template class elf::PartitionElfHeaderSection<ELF32BE>;
3650 template class elf::PartitionElfHeaderSection<ELF64LE>;
3651 template class elf::PartitionElfHeaderSection<ELF64BE>;
3652 
3653 template class elf::PartitionProgramHeadersSection<ELF32LE>;
3654 template class elf::PartitionProgramHeadersSection<ELF32BE>;
3655 template class elf::PartitionProgramHeadersSection<ELF64LE>;
3656 template class elf::PartitionProgramHeadersSection<ELF64BE>;
3657