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 "DWARF.h"
19 #include "EhFrame.h"
20 #include "InputFiles.h"
21 #include "LinkerScript.h"
22 #include "OutputSections.h"
23 #include "SymbolTable.h"
24 #include "Symbols.h"
25 #include "Target.h"
26 #include "Thunks.h"
27 #include "Writer.h"
28 #include "lld/Common/CommonLinkerContext.h"
29 #include "lld/Common/DWARF.h"
30 #include "lld/Common/Strings.h"
31 #include "lld/Common/Version.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SetOperations.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/BinaryFormat/Dwarf.h"
36 #include "llvm/BinaryFormat/ELF.h"
37 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/Parallel.h"
41 #include "llvm/Support/TimeProfiler.h"
42 #include <cstdlib>
43 
44 using namespace llvm;
45 using namespace llvm::dwarf;
46 using namespace llvm::ELF;
47 using namespace llvm::object;
48 using namespace llvm::support;
49 using namespace lld;
50 using namespace lld::elf;
51 
52 using llvm::support::endian::read32le;
53 using llvm::support::endian::write32le;
54 using llvm::support::endian::write64le;
55 
56 constexpr size_t MergeNoTailSection::numShards;
57 
58 static uint64_t readUint(uint8_t *buf) {
59   return config->is64 ? read64(buf) : read32(buf);
60 }
61 
62 static void writeUint(uint8_t *buf, uint64_t val) {
63   if (config->is64)
64     write64(buf, val);
65   else
66     write32(buf, val);
67 }
68 
69 // Returns an LLD version string.
70 static ArrayRef<uint8_t> getVersion() {
71   // Check LLD_VERSION first for ease of testing.
72   // You can get consistent output by using the environment variable.
73   // This is only for testing.
74   StringRef s = getenv("LLD_VERSION");
75   if (s.empty())
76     s = saver().save(Twine("Linker: ") + getLLDVersion());
77 
78   // +1 to include the terminating '\0'.
79   return {(const uint8_t *)s.data(), s.size() + 1};
80 }
81 
82 // Creates a .comment section containing LLD version info.
83 // With this feature, you can identify LLD-generated binaries easily
84 // by "readelf --string-dump .comment <file>".
85 // The returned object is a mergeable string section.
86 MergeInputSection *elf::createCommentSection() {
87   auto *sec = make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
88                                       getVersion(), ".comment");
89   sec->splitIntoPieces();
90   return sec;
91 }
92 
93 // .MIPS.abiflags section.
94 template <class ELFT>
95 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)
96     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
97       flags(flags) {
98   this->entsize = sizeof(Elf_Mips_ABIFlags);
99 }
100 
101 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
102   memcpy(buf, &flags, sizeof(flags));
103 }
104 
105 template <class ELFT>
106 std::unique_ptr<MipsAbiFlagsSection<ELFT>> MipsAbiFlagsSection<ELFT>::create() {
107   Elf_Mips_ABIFlags flags = {};
108   bool create = false;
109 
110   for (InputSectionBase *sec : ctx.inputSections) {
111     if (sec->type != SHT_MIPS_ABIFLAGS)
112       continue;
113     sec->markDead();
114     create = true;
115 
116     std::string filename = toString(sec->file);
117     const size_t size = sec->content().size();
118     // Older version of BFD (such as the default FreeBSD linker) concatenate
119     // .MIPS.abiflags instead of merging. To allow for this case (or potential
120     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
121     if (size < sizeof(Elf_Mips_ABIFlags)) {
122       error(filename + ": invalid size of .MIPS.abiflags section: got " +
123             Twine(size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
124       return nullptr;
125     }
126     auto *s =
127         reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->content().data());
128     if (s->version != 0) {
129       error(filename + ": unexpected .MIPS.abiflags version " +
130             Twine(s->version));
131       return nullptr;
132     }
133 
134     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
135     // select the highest number of ISA/Rev/Ext.
136     flags.isa_level = std::max(flags.isa_level, s->isa_level);
137     flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
138     flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
139     flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
140     flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
141     flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
142     flags.ases |= s->ases;
143     flags.flags1 |= s->flags1;
144     flags.flags2 |= s->flags2;
145     flags.fp_abi = elf::getMipsFpAbiFlag(flags.fp_abi, s->fp_abi, filename);
146   };
147 
148   if (create)
149     return std::make_unique<MipsAbiFlagsSection<ELFT>>(flags);
150   return nullptr;
151 }
152 
153 // .MIPS.options section.
154 template <class ELFT>
155 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo reginfo)
156     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
157       reginfo(reginfo) {
158   this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
159 }
160 
161 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
162   auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
163   options->kind = ODK_REGINFO;
164   options->size = getSize();
165 
166   if (!config->relocatable)
167     reginfo.ri_gp_value = in.mipsGot->getGp();
168   memcpy(buf + sizeof(Elf_Mips_Options), &reginfo, sizeof(reginfo));
169 }
170 
171 template <class ELFT>
172 std::unique_ptr<MipsOptionsSection<ELFT>> MipsOptionsSection<ELFT>::create() {
173   // N64 ABI only.
174   if (!ELFT::Is64Bits)
175     return nullptr;
176 
177   SmallVector<InputSectionBase *, 0> sections;
178   for (InputSectionBase *sec : ctx.inputSections)
179     if (sec->type == SHT_MIPS_OPTIONS)
180       sections.push_back(sec);
181 
182   if (sections.empty())
183     return nullptr;
184 
185   Elf_Mips_RegInfo reginfo = {};
186   for (InputSectionBase *sec : sections) {
187     sec->markDead();
188 
189     std::string filename = toString(sec->file);
190     ArrayRef<uint8_t> d = sec->content();
191 
192     while (!d.empty()) {
193       if (d.size() < sizeof(Elf_Mips_Options)) {
194         error(filename + ": invalid size of .MIPS.options section");
195         break;
196       }
197 
198       auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
199       if (opt->kind == ODK_REGINFO) {
200         reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
201         sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
202         break;
203       }
204 
205       if (!opt->size)
206         fatal(filename + ": zero option descriptor size");
207       d = d.slice(opt->size);
208     }
209   };
210 
211   return std::make_unique<MipsOptionsSection<ELFT>>(reginfo);
212 }
213 
214 // MIPS .reginfo section.
215 template <class ELFT>
216 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo reginfo)
217     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
218       reginfo(reginfo) {
219   this->entsize = sizeof(Elf_Mips_RegInfo);
220 }
221 
222 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
223   if (!config->relocatable)
224     reginfo.ri_gp_value = in.mipsGot->getGp();
225   memcpy(buf, &reginfo, sizeof(reginfo));
226 }
227 
228 template <class ELFT>
229 std::unique_ptr<MipsReginfoSection<ELFT>> MipsReginfoSection<ELFT>::create() {
230   // Section should be alive for O32 and N32 ABIs only.
231   if (ELFT::Is64Bits)
232     return nullptr;
233 
234   SmallVector<InputSectionBase *, 0> sections;
235   for (InputSectionBase *sec : ctx.inputSections)
236     if (sec->type == SHT_MIPS_REGINFO)
237       sections.push_back(sec);
238 
239   if (sections.empty())
240     return nullptr;
241 
242   Elf_Mips_RegInfo reginfo = {};
243   for (InputSectionBase *sec : sections) {
244     sec->markDead();
245 
246     if (sec->content().size() != sizeof(Elf_Mips_RegInfo)) {
247       error(toString(sec->file) + ": invalid size of .reginfo section");
248       return nullptr;
249     }
250 
251     auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->content().data());
252     reginfo.ri_gprmask |= r->ri_gprmask;
253     sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
254   };
255 
256   return std::make_unique<MipsReginfoSection<ELFT>>(reginfo);
257 }
258 
259 InputSection *elf::createInterpSection() {
260   // StringSaver guarantees that the returned string ends with '\0'.
261   StringRef s = saver().save(config->dynamicLinker);
262   ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
263 
264   return make<InputSection>(ctx.internalFile, SHF_ALLOC, SHT_PROGBITS, 1,
265                             contents, ".interp");
266 }
267 
268 Defined *elf::addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
269                                 uint64_t size, InputSectionBase &section) {
270   Defined *s = makeDefined(section.file, name, STB_LOCAL, STV_DEFAULT, type,
271                            value, size, &section);
272   if (in.symTab)
273     in.symTab->addSymbol(s);
274 
275   if (config->emachine == EM_ARM && !config->isLE && config->armBe8 &&
276       (section.flags & SHF_EXECINSTR))
277     // Adding Linker generated mapping symbols to the arm specific mapping
278     // symbols list.
279     addArmSyntheticSectionMappingSymbol(s);
280 
281   return s;
282 }
283 
284 static size_t getHashSize() {
285   switch (config->buildId) {
286   case BuildIdKind::Fast:
287     return 8;
288   case BuildIdKind::Md5:
289   case BuildIdKind::Uuid:
290     return 16;
291   case BuildIdKind::Sha1:
292     return 20;
293   case BuildIdKind::Hexstring:
294     return config->buildIdVector.size();
295   default:
296     llvm_unreachable("unknown BuildIdKind");
297   }
298 }
299 
300 // This class represents a linker-synthesized .note.gnu.property section.
301 //
302 // In x86 and AArch64, object files may contain feature flags indicating the
303 // features that they have used. The flags are stored in a .note.gnu.property
304 // section.
305 //
306 // lld reads the sections from input files and merges them by computing AND of
307 // the flags. The result is written as a new .note.gnu.property section.
308 //
309 // If the flag is zero (which indicates that the intersection of the feature
310 // sets is empty, or some input files didn't have .note.gnu.property sections),
311 // we don't create this section.
312 GnuPropertySection::GnuPropertySection()
313     : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
314                        config->wordsize, ".note.gnu.property") {}
315 
316 void GnuPropertySection::writeTo(uint8_t *buf) {
317   uint32_t featureAndType = config->emachine == EM_AARCH64
318                                 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
319                                 : GNU_PROPERTY_X86_FEATURE_1_AND;
320 
321   write32(buf, 4);                                   // Name size
322   write32(buf + 4, config->is64 ? 16 : 12);          // Content size
323   write32(buf + 8, NT_GNU_PROPERTY_TYPE_0);          // Type
324   memcpy(buf + 12, "GNU", 4);                        // Name string
325   write32(buf + 16, featureAndType);                 // Feature type
326   write32(buf + 20, 4);                              // Feature size
327   write32(buf + 24, config->andFeatures);            // Feature flags
328   if (config->is64)
329     write32(buf + 28, 0); // Padding
330 }
331 
332 size_t GnuPropertySection::getSize() const { return config->is64 ? 32 : 28; }
333 
334 BuildIdSection::BuildIdSection()
335     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
336       hashSize(getHashSize()) {}
337 
338 void BuildIdSection::writeTo(uint8_t *buf) {
339   write32(buf, 4);                      // Name size
340   write32(buf + 4, hashSize);           // Content size
341   write32(buf + 8, NT_GNU_BUILD_ID);    // Type
342   memcpy(buf + 12, "GNU", 4);           // Name string
343   hashBuf = buf + 16;
344 }
345 
346 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
347   assert(buf.size() == hashSize);
348   memcpy(hashBuf, buf.data(), hashSize);
349 }
350 
351 BssSection::BssSection(StringRef name, uint64_t size, uint32_t alignment)
352     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, alignment, name) {
353   this->bss = true;
354   this->size = size;
355 }
356 
357 EhFrameSection::EhFrameSection()
358     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
359 
360 // Search for an existing CIE record or create a new one.
361 // CIE records from input object files are uniquified by their contents
362 // and where their relocations point to.
363 template <class ELFT, class RelTy>
364 CieRecord *EhFrameSection::addCie(EhSectionPiece &cie, ArrayRef<RelTy> rels) {
365   Symbol *personality = nullptr;
366   unsigned firstRelI = cie.firstRelocation;
367   if (firstRelI != (unsigned)-1)
368     personality =
369         &cie.sec->template getFile<ELFT>()->getRelocTargetSym(rels[firstRelI]);
370 
371   // Search for an existing CIE by CIE contents/relocation target pair.
372   CieRecord *&rec = cieMap[{cie.data(), personality}];
373 
374   // If not found, create a new one.
375   if (!rec) {
376     rec = make<CieRecord>();
377     rec->cie = &cie;
378     cieRecords.push_back(rec);
379   }
380   return rec;
381 }
382 
383 // There is one FDE per function. Returns a non-null pointer to the function
384 // symbol if the given FDE points to a live function.
385 template <class ELFT, class RelTy>
386 Defined *EhFrameSection::isFdeLive(EhSectionPiece &fde, ArrayRef<RelTy> rels) {
387   auto *sec = cast<EhInputSection>(fde.sec);
388   unsigned firstRelI = fde.firstRelocation;
389 
390   // An FDE should point to some function because FDEs are to describe
391   // functions. That's however not always the case due to an issue of
392   // ld.gold with -r. ld.gold may discard only functions and leave their
393   // corresponding FDEs, which results in creating bad .eh_frame sections.
394   // To deal with that, we ignore such FDEs.
395   if (firstRelI == (unsigned)-1)
396     return nullptr;
397 
398   const RelTy &rel = rels[firstRelI];
399   Symbol &b = sec->template getFile<ELFT>()->getRelocTargetSym(rel);
400 
401   // FDEs for garbage-collected or merged-by-ICF sections, or sections in
402   // another partition, are dead.
403   if (auto *d = dyn_cast<Defined>(&b))
404     if (!d->folded && d->section && d->section->partition == partition)
405       return d;
406   return nullptr;
407 }
408 
409 // .eh_frame is a sequence of CIE or FDE records. In general, there
410 // is one CIE record per input object file which is followed by
411 // a list of FDEs. This function searches an existing CIE or create a new
412 // one and associates FDEs to the CIE.
413 template <class ELFT, class RelTy>
414 void EhFrameSection::addRecords(EhInputSection *sec, ArrayRef<RelTy> rels) {
415   offsetToCie.clear();
416   for (EhSectionPiece &cie : sec->cies)
417     offsetToCie[cie.inputOff] = addCie<ELFT>(cie, rels);
418   for (EhSectionPiece &fde : sec->fdes) {
419     uint32_t id = endian::read32<ELFT::TargetEndianness>(fde.data().data() + 4);
420     CieRecord *rec = offsetToCie[fde.inputOff + 4 - id];
421     if (!rec)
422       fatal(toString(sec) + ": invalid CIE reference");
423 
424     if (!isFdeLive<ELFT>(fde, rels))
425       continue;
426     rec->fdes.push_back(&fde);
427     numFdes++;
428   }
429 }
430 
431 template <class ELFT>
432 void EhFrameSection::addSectionAux(EhInputSection *sec) {
433   if (!sec->isLive())
434     return;
435   const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
436   if (rels.areRelocsRel())
437     addRecords<ELFT>(sec, rels.rels);
438   else
439     addRecords<ELFT>(sec, rels.relas);
440 }
441 
442 // Used by ICF<ELFT>::handleLSDA(). This function is very similar to
443 // EhFrameSection::addRecords().
444 template <class ELFT, class RelTy>
445 void EhFrameSection::iterateFDEWithLSDAAux(
446     EhInputSection &sec, ArrayRef<RelTy> rels, DenseSet<size_t> &ciesWithLSDA,
447     llvm::function_ref<void(InputSection &)> fn) {
448   for (EhSectionPiece &cie : sec.cies)
449     if (hasLSDA(cie))
450       ciesWithLSDA.insert(cie.inputOff);
451   for (EhSectionPiece &fde : sec.fdes) {
452     uint32_t id = endian::read32<ELFT::TargetEndianness>(fde.data().data() + 4);
453     if (!ciesWithLSDA.contains(fde.inputOff + 4 - id))
454       continue;
455 
456     // The CIE has a LSDA argument. Call fn with d's section.
457     if (Defined *d = isFdeLive<ELFT>(fde, rels))
458       if (auto *s = dyn_cast_or_null<InputSection>(d->section))
459         fn(*s);
460   }
461 }
462 
463 template <class ELFT>
464 void EhFrameSection::iterateFDEWithLSDA(
465     llvm::function_ref<void(InputSection &)> fn) {
466   DenseSet<size_t> ciesWithLSDA;
467   for (EhInputSection *sec : sections) {
468     ciesWithLSDA.clear();
469     const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
470     if (rels.areRelocsRel())
471       iterateFDEWithLSDAAux<ELFT>(*sec, rels.rels, ciesWithLSDA, fn);
472     else
473       iterateFDEWithLSDAAux<ELFT>(*sec, rels.relas, ciesWithLSDA, fn);
474   }
475 }
476 
477 static void writeCieFde(uint8_t *buf, ArrayRef<uint8_t> d) {
478   memcpy(buf, d.data(), d.size());
479   // Fix the size field. -4 since size does not include the size field itself.
480   write32(buf, d.size() - 4);
481 }
482 
483 void EhFrameSection::finalizeContents() {
484   assert(!this->size); // Not finalized.
485 
486   switch (config->ekind) {
487   case ELFNoneKind:
488     llvm_unreachable("invalid ekind");
489   case ELF32LEKind:
490     for (EhInputSection *sec : sections)
491       addSectionAux<ELF32LE>(sec);
492     break;
493   case ELF32BEKind:
494     for (EhInputSection *sec : sections)
495       addSectionAux<ELF32BE>(sec);
496     break;
497   case ELF64LEKind:
498     for (EhInputSection *sec : sections)
499       addSectionAux<ELF64LE>(sec);
500     break;
501   case ELF64BEKind:
502     for (EhInputSection *sec : sections)
503       addSectionAux<ELF64BE>(sec);
504     break;
505   }
506 
507   size_t off = 0;
508   for (CieRecord *rec : cieRecords) {
509     rec->cie->outputOff = off;
510     off += rec->cie->size;
511 
512     for (EhSectionPiece *fde : rec->fdes) {
513       fde->outputOff = off;
514       off += fde->size;
515     }
516   }
517 
518   // The LSB standard does not allow a .eh_frame section with zero
519   // Call Frame Information records. glibc unwind-dw2-fde.c
520   // classify_object_over_fdes expects there is a CIE record length 0 as a
521   // terminator. Thus we add one unconditionally.
522   off += 4;
523 
524   this->size = off;
525 }
526 
527 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
528 // to get an FDE from an address to which FDE is applied. This function
529 // returns a list of such pairs.
530 SmallVector<EhFrameSection::FdeData, 0> EhFrameSection::getFdeData() const {
531   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
532   SmallVector<FdeData, 0> ret;
533 
534   uint64_t va = getPartition().ehFrameHdr->getVA();
535   for (CieRecord *rec : cieRecords) {
536     uint8_t enc = getFdeEncoding(rec->cie);
537     for (EhSectionPiece *fde : rec->fdes) {
538       uint64_t pc = getFdePc(buf, fde->outputOff, enc);
539       uint64_t fdeVA = getParent()->addr + fde->outputOff;
540       if (!isInt<32>(pc - va))
541         fatal(toString(fde->sec) + ": PC offset is too large: 0x" +
542               Twine::utohexstr(pc - va));
543       ret.push_back({uint32_t(pc - va), uint32_t(fdeVA - va)});
544     }
545   }
546 
547   // Sort the FDE list by their PC and uniqueify. Usually there is only
548   // one FDE for a PC (i.e. function), but if ICF merges two functions
549   // into one, there can be more than one FDEs pointing to the address.
550   auto less = [](const FdeData &a, const FdeData &b) {
551     return a.pcRel < b.pcRel;
552   };
553   llvm::stable_sort(ret, less);
554   auto eq = [](const FdeData &a, const FdeData &b) {
555     return a.pcRel == b.pcRel;
556   };
557   ret.erase(std::unique(ret.begin(), ret.end(), eq), ret.end());
558 
559   return ret;
560 }
561 
562 static uint64_t readFdeAddr(uint8_t *buf, int size) {
563   switch (size) {
564   case DW_EH_PE_udata2:
565     return read16(buf);
566   case DW_EH_PE_sdata2:
567     return (int16_t)read16(buf);
568   case DW_EH_PE_udata4:
569     return read32(buf);
570   case DW_EH_PE_sdata4:
571     return (int32_t)read32(buf);
572   case DW_EH_PE_udata8:
573   case DW_EH_PE_sdata8:
574     return read64(buf);
575   case DW_EH_PE_absptr:
576     return readUint(buf);
577   }
578   fatal("unknown FDE size encoding");
579 }
580 
581 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
582 // We need it to create .eh_frame_hdr section.
583 uint64_t EhFrameSection::getFdePc(uint8_t *buf, size_t fdeOff,
584                                   uint8_t enc) const {
585   // The starting address to which this FDE applies is
586   // stored at FDE + 8 byte. And this offset is within
587   // the .eh_frame section.
588   size_t off = fdeOff + 8;
589   uint64_t addr = readFdeAddr(buf + off, enc & 0xf);
590   if ((enc & 0x70) == DW_EH_PE_absptr)
591     return addr;
592   if ((enc & 0x70) == DW_EH_PE_pcrel)
593     return addr + getParent()->addr + off + outSecOff;
594   fatal("unknown FDE size relative encoding");
595 }
596 
597 void EhFrameSection::writeTo(uint8_t *buf) {
598   // Write CIE and FDE records.
599   for (CieRecord *rec : cieRecords) {
600     size_t cieOffset = rec->cie->outputOff;
601     writeCieFde(buf + cieOffset, rec->cie->data());
602 
603     for (EhSectionPiece *fde : rec->fdes) {
604       size_t off = fde->outputOff;
605       writeCieFde(buf + off, fde->data());
606 
607       // FDE's second word should have the offset to an associated CIE.
608       // Write it.
609       write32(buf + off + 4, off + 4 - cieOffset);
610     }
611   }
612 
613   // Apply relocations. .eh_frame section contents are not contiguous
614   // in the output buffer, but relocateAlloc() still works because
615   // getOffset() takes care of discontiguous section pieces.
616   for (EhInputSection *s : sections)
617     target->relocateAlloc(*s, buf);
618 
619   if (getPartition().ehFrameHdr && getPartition().ehFrameHdr->getParent())
620     getPartition().ehFrameHdr->write();
621 }
622 
623 GotSection::GotSection()
624     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
625                        target->gotEntrySize, ".got") {
626   numEntries = target->gotHeaderEntriesNum;
627 }
628 
629 void GotSection::addConstant(const Relocation &r) { relocations.push_back(r); }
630 void GotSection::addEntry(Symbol &sym) {
631   assert(sym.auxIdx == symAux.size() - 1);
632   symAux.back().gotIdx = numEntries++;
633 }
634 
635 bool GotSection::addTlsDescEntry(Symbol &sym) {
636   assert(sym.auxIdx == symAux.size() - 1);
637   symAux.back().tlsDescIdx = numEntries;
638   numEntries += 2;
639   return true;
640 }
641 
642 bool GotSection::addDynTlsEntry(Symbol &sym) {
643   assert(sym.auxIdx == symAux.size() - 1);
644   symAux.back().tlsGdIdx = numEntries;
645   // Global Dynamic TLS entries take two GOT slots.
646   numEntries += 2;
647   return true;
648 }
649 
650 // Reserves TLS entries for a TLS module ID and a TLS block offset.
651 // In total it takes two GOT slots.
652 bool GotSection::addTlsIndex() {
653   if (tlsIndexOff != uint32_t(-1))
654     return false;
655   tlsIndexOff = numEntries * config->wordsize;
656   numEntries += 2;
657   return true;
658 }
659 
660 uint32_t GotSection::getTlsDescOffset(const Symbol &sym) const {
661   return sym.getTlsDescIdx() * config->wordsize;
662 }
663 
664 uint64_t GotSection::getTlsDescAddr(const Symbol &sym) const {
665   return getVA() + getTlsDescOffset(sym);
666 }
667 
668 uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
669   return this->getVA() + b.getTlsGdIdx() * config->wordsize;
670 }
671 
672 uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
673   return b.getTlsGdIdx() * config->wordsize;
674 }
675 
676 void GotSection::finalizeContents() {
677   if (config->emachine == EM_PPC64 &&
678       numEntries <= target->gotHeaderEntriesNum && !ElfSym::globalOffsetTable)
679     size = 0;
680   else
681     size = numEntries * config->wordsize;
682 }
683 
684 bool GotSection::isNeeded() const {
685   // Needed if the GOT symbol is used or the number of entries is more than just
686   // the header. A GOT with just the header may not be needed.
687   return hasGotOffRel || numEntries > target->gotHeaderEntriesNum;
688 }
689 
690 void GotSection::writeTo(uint8_t *buf) {
691   // On PPC64 .got may be needed but empty. Skip the write.
692   if (size == 0)
693     return;
694   target->writeGotHeader(buf);
695   target->relocateAlloc(*this, buf);
696 }
697 
698 static uint64_t getMipsPageAddr(uint64_t addr) {
699   return (addr + 0x8000) & ~0xffff;
700 }
701 
702 static uint64_t getMipsPageCount(uint64_t size) {
703   return (size + 0xfffe) / 0xffff + 1;
704 }
705 
706 MipsGotSection::MipsGotSection()
707     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
708                        ".got") {}
709 
710 void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
711                               RelExpr expr) {
712   FileGot &g = getGot(file);
713   if (expr == R_MIPS_GOT_LOCAL_PAGE) {
714     if (const OutputSection *os = sym.getOutputSection())
715       g.pagesMap.insert({os, {}});
716     else
717       g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
718   } else if (sym.isTls())
719     g.tls.insert({&sym, 0});
720   else if (sym.isPreemptible && expr == R_ABS)
721     g.relocs.insert({&sym, 0});
722   else if (sym.isPreemptible)
723     g.global.insert({&sym, 0});
724   else if (expr == R_MIPS_GOT_OFF32)
725     g.local32.insert({{&sym, addend}, 0});
726   else
727     g.local16.insert({{&sym, addend}, 0});
728 }
729 
730 void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
731   getGot(file).dynTlsSymbols.insert({&sym, 0});
732 }
733 
734 void MipsGotSection::addTlsIndex(InputFile &file) {
735   getGot(file).dynTlsSymbols.insert({nullptr, 0});
736 }
737 
738 size_t MipsGotSection::FileGot::getEntriesNum() const {
739   return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
740          tls.size() + dynTlsSymbols.size() * 2;
741 }
742 
743 size_t MipsGotSection::FileGot::getPageEntriesNum() const {
744   size_t num = 0;
745   for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
746     num += p.second.count;
747   return num;
748 }
749 
750 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
751   size_t count = getPageEntriesNum() + local16.size() + global.size();
752   // If there are relocation-only entries in the GOT, TLS entries
753   // are allocated after them. TLS entries should be addressable
754   // by 16-bit index so count both reloc-only and TLS entries.
755   if (!tls.empty() || !dynTlsSymbols.empty())
756     count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
757   return count;
758 }
759 
760 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
761   if (f.mipsGotIndex == uint32_t(-1)) {
762     gots.emplace_back();
763     gots.back().file = &f;
764     f.mipsGotIndex = gots.size() - 1;
765   }
766   return gots[f.mipsGotIndex];
767 }
768 
769 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
770                                             const Symbol &sym,
771                                             int64_t addend) const {
772   const FileGot &g = gots[f->mipsGotIndex];
773   uint64_t index = 0;
774   if (const OutputSection *outSec = sym.getOutputSection()) {
775     uint64_t secAddr = getMipsPageAddr(outSec->addr);
776     uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
777     index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
778   } else {
779     index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
780   }
781   return index * config->wordsize;
782 }
783 
784 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
785                                            int64_t addend) const {
786   const FileGot &g = gots[f->mipsGotIndex];
787   Symbol *sym = const_cast<Symbol *>(&s);
788   if (sym->isTls())
789     return g.tls.lookup(sym) * config->wordsize;
790   if (sym->isPreemptible)
791     return g.global.lookup(sym) * config->wordsize;
792   return g.local16.lookup({sym, addend}) * config->wordsize;
793 }
794 
795 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
796   const FileGot &g = gots[f->mipsGotIndex];
797   return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
798 }
799 
800 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
801                                             const Symbol &s) const {
802   const FileGot &g = gots[f->mipsGotIndex];
803   Symbol *sym = const_cast<Symbol *>(&s);
804   return g.dynTlsSymbols.lookup(sym) * config->wordsize;
805 }
806 
807 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
808   if (gots.empty())
809     return nullptr;
810   const FileGot &primGot = gots.front();
811   if (!primGot.global.empty())
812     return primGot.global.front().first;
813   if (!primGot.relocs.empty())
814     return primGot.relocs.front().first;
815   return nullptr;
816 }
817 
818 unsigned MipsGotSection::getLocalEntriesNum() const {
819   if (gots.empty())
820     return headerEntriesNum;
821   return headerEntriesNum + gots.front().getPageEntriesNum() +
822          gots.front().local16.size();
823 }
824 
825 bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
826   FileGot tmp = dst;
827   set_union(tmp.pagesMap, src.pagesMap);
828   set_union(tmp.local16, src.local16);
829   set_union(tmp.global, src.global);
830   set_union(tmp.relocs, src.relocs);
831   set_union(tmp.tls, src.tls);
832   set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
833 
834   size_t count = isPrimary ? headerEntriesNum : 0;
835   count += tmp.getIndexedEntriesNum();
836 
837   if (count * config->wordsize > config->mipsGotSize)
838     return false;
839 
840   std::swap(tmp, dst);
841   return true;
842 }
843 
844 void MipsGotSection::finalizeContents() { updateAllocSize(); }
845 
846 bool MipsGotSection::updateAllocSize() {
847   size = headerEntriesNum * config->wordsize;
848   for (const FileGot &g : gots)
849     size += g.getEntriesNum() * config->wordsize;
850   return false;
851 }
852 
853 void MipsGotSection::build() {
854   if (gots.empty())
855     return;
856 
857   std::vector<FileGot> mergedGots(1);
858 
859   // For each GOT move non-preemptible symbols from the `Global`
860   // to `Local16` list. Preemptible symbol might become non-preemptible
861   // one if, for example, it gets a related copy relocation.
862   for (FileGot &got : gots) {
863     for (auto &p: got.global)
864       if (!p.first->isPreemptible)
865         got.local16.insert({{p.first, 0}, 0});
866     got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
867       return !p.first->isPreemptible;
868     });
869   }
870 
871   // For each GOT remove "reloc-only" entry if there is "global"
872   // entry for the same symbol. And add local entries which indexed
873   // using 32-bit value at the end of 16-bit entries.
874   for (FileGot &got : gots) {
875     got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
876       return got.global.count(p.first);
877     });
878     set_union(got.local16, got.local32);
879     got.local32.clear();
880   }
881 
882   // Evaluate number of "reloc-only" entries in the resulting GOT.
883   // To do that put all unique "reloc-only" and "global" entries
884   // from all GOTs to the future primary GOT.
885   FileGot *primGot = &mergedGots.front();
886   for (FileGot &got : gots) {
887     set_union(primGot->relocs, got.global);
888     set_union(primGot->relocs, got.relocs);
889     got.relocs.clear();
890   }
891 
892   // Evaluate number of "page" entries in each GOT.
893   for (FileGot &got : gots) {
894     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
895          got.pagesMap) {
896       const OutputSection *os = p.first;
897       uint64_t secSize = 0;
898       for (SectionCommand *cmd : os->commands) {
899         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
900           for (InputSection *isec : isd->sections) {
901             uint64_t off = alignToPowerOf2(secSize, isec->addralign);
902             secSize = off + isec->getSize();
903           }
904       }
905       p.second.count = getMipsPageCount(secSize);
906     }
907   }
908 
909   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
910   // maximum GOT size. At first, try to fill the primary GOT because
911   // the primary GOT can be accessed in the most effective way. If it
912   // is not possible, try to fill the last GOT in the list, and finally
913   // create a new GOT if both attempts failed.
914   for (FileGot &srcGot : gots) {
915     InputFile *file = srcGot.file;
916     if (tryMergeGots(mergedGots.front(), srcGot, true)) {
917       file->mipsGotIndex = 0;
918     } else {
919       // If this is the first time we failed to merge with the primary GOT,
920       // MergedGots.back() will also be the primary GOT. We must make sure not
921       // to try to merge again with isPrimary=false, as otherwise, if the
922       // inputs are just right, we could allow the primary GOT to become 1 or 2
923       // words bigger due to ignoring the header size.
924       if (mergedGots.size() == 1 ||
925           !tryMergeGots(mergedGots.back(), srcGot, false)) {
926         mergedGots.emplace_back();
927         std::swap(mergedGots.back(), srcGot);
928       }
929       file->mipsGotIndex = mergedGots.size() - 1;
930     }
931   }
932   std::swap(gots, mergedGots);
933 
934   // Reduce number of "reloc-only" entries in the primary GOT
935   // by subtracting "global" entries in the primary GOT.
936   primGot = &gots.front();
937   primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
938     return primGot->global.count(p.first);
939   });
940 
941   // Calculate indexes for each GOT entry.
942   size_t index = headerEntriesNum;
943   for (FileGot &got : gots) {
944     got.startIndex = &got == primGot ? 0 : index;
945     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
946          got.pagesMap) {
947       // For each output section referenced by GOT page relocations calculate
948       // and save into pagesMap an upper bound of MIPS GOT entries required
949       // to store page addresses of local symbols. We assume the worst case -
950       // each 64kb page of the output section has at least one GOT relocation
951       // against it. And take in account the case when the section intersects
952       // page boundaries.
953       p.second.firstIndex = index;
954       index += p.second.count;
955     }
956     for (auto &p: got.local16)
957       p.second = index++;
958     for (auto &p: got.global)
959       p.second = index++;
960     for (auto &p: got.relocs)
961       p.second = index++;
962     for (auto &p: got.tls)
963       p.second = index++;
964     for (auto &p: got.dynTlsSymbols) {
965       p.second = index;
966       index += 2;
967     }
968   }
969 
970   // Update SymbolAux::gotIdx field to use this
971   // value later in the `sortMipsSymbols` function.
972   for (auto &p : primGot->global) {
973     if (p.first->auxIdx == 0)
974       p.first->allocateAux();
975     symAux.back().gotIdx = p.second;
976   }
977   for (auto &p : primGot->relocs) {
978     if (p.first->auxIdx == 0)
979       p.first->allocateAux();
980     symAux.back().gotIdx = p.second;
981   }
982 
983   // Create dynamic relocations.
984   for (FileGot &got : gots) {
985     // Create dynamic relocations for TLS entries.
986     for (std::pair<Symbol *, size_t> &p : got.tls) {
987       Symbol *s = p.first;
988       uint64_t offset = p.second * config->wordsize;
989       // When building a shared library we still need a dynamic relocation
990       // for the TP-relative offset as we don't know how much other data will
991       // be allocated before us in the static TLS block.
992       if (s->isPreemptible || config->shared)
993         mainPart->relaDyn->addReloc({target->tlsGotRel, this, offset,
994                                      DynamicReloc::AgainstSymbolWithTargetVA,
995                                      *s, 0, R_ABS});
996     }
997     for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
998       Symbol *s = p.first;
999       uint64_t offset = p.second * config->wordsize;
1000       if (s == nullptr) {
1001         if (!config->shared)
1002           continue;
1003         mainPart->relaDyn->addReloc({target->tlsModuleIndexRel, this, offset});
1004       } else {
1005         // When building a shared library we still need a dynamic relocation
1006         // for the module index. Therefore only checking for
1007         // S->isPreemptible is not sufficient (this happens e.g. for
1008         // thread-locals that have been marked as local through a linker script)
1009         if (!s->isPreemptible && !config->shared)
1010           continue;
1011         mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *this,
1012                                           offset, *s);
1013         // However, we can skip writing the TLS offset reloc for non-preemptible
1014         // symbols since it is known even in shared libraries
1015         if (!s->isPreemptible)
1016           continue;
1017         offset += config->wordsize;
1018         mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *this, offset,
1019                                           *s);
1020       }
1021     }
1022 
1023     // Do not create dynamic relocations for non-TLS
1024     // entries in the primary GOT.
1025     if (&got == primGot)
1026       continue;
1027 
1028     // Dynamic relocations for "global" entries.
1029     for (const std::pair<Symbol *, size_t> &p : got.global) {
1030       uint64_t offset = p.second * config->wordsize;
1031       mainPart->relaDyn->addSymbolReloc(target->relativeRel, *this, offset,
1032                                         *p.first);
1033     }
1034     if (!config->isPic)
1035       continue;
1036     // Dynamic relocations for "local" entries in case of PIC.
1037     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1038          got.pagesMap) {
1039       size_t pageCount = l.second.count;
1040       for (size_t pi = 0; pi < pageCount; ++pi) {
1041         uint64_t offset = (l.second.firstIndex + pi) * config->wordsize;
1042         mainPart->relaDyn->addReloc({target->relativeRel, this, offset, l.first,
1043                                      int64_t(pi * 0x10000)});
1044       }
1045     }
1046     for (const std::pair<GotEntry, size_t> &p : got.local16) {
1047       uint64_t offset = p.second * config->wordsize;
1048       mainPart->relaDyn->addReloc({target->relativeRel, this, offset,
1049                                    DynamicReloc::AddendOnlyWithTargetVA,
1050                                    *p.first.first, p.first.second, R_ABS});
1051     }
1052   }
1053 }
1054 
1055 bool MipsGotSection::isNeeded() const {
1056   // We add the .got section to the result for dynamic MIPS target because
1057   // its address and properties are mentioned in the .dynamic section.
1058   return !config->relocatable;
1059 }
1060 
1061 uint64_t MipsGotSection::getGp(const InputFile *f) const {
1062   // For files without related GOT or files refer a primary GOT
1063   // returns "common" _gp value. For secondary GOTs calculate
1064   // individual _gp values.
1065   if (!f || f->mipsGotIndex == uint32_t(-1) || f->mipsGotIndex == 0)
1066     return ElfSym::mipsGp->getVA(0);
1067   return getVA() + gots[f->mipsGotIndex].startIndex * config->wordsize + 0x7ff0;
1068 }
1069 
1070 void MipsGotSection::writeTo(uint8_t *buf) {
1071   // Set the MSB of the second GOT slot. This is not required by any
1072   // MIPS ABI documentation, though.
1073   //
1074   // There is a comment in glibc saying that "The MSB of got[1] of a
1075   // gnu object is set to identify gnu objects," and in GNU gold it
1076   // says "the second entry will be used by some runtime loaders".
1077   // But how this field is being used is unclear.
1078   //
1079   // We are not really willing to mimic other linkers behaviors
1080   // without understanding why they do that, but because all files
1081   // generated by GNU tools have this special GOT value, and because
1082   // we've been doing this for years, it is probably a safe bet to
1083   // keep doing this for now. We really need to revisit this to see
1084   // if we had to do this.
1085   writeUint(buf + config->wordsize, (uint64_t)1 << (config->wordsize * 8 - 1));
1086   for (const FileGot &g : gots) {
1087     auto write = [&](size_t i, const Symbol *s, int64_t a) {
1088       uint64_t va = a;
1089       if (s)
1090         va = s->getVA(a);
1091       writeUint(buf + i * config->wordsize, va);
1092     };
1093     // Write 'page address' entries to the local part of the GOT.
1094     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1095          g.pagesMap) {
1096       size_t pageCount = l.second.count;
1097       uint64_t firstPageAddr = getMipsPageAddr(l.first->addr);
1098       for (size_t pi = 0; pi < pageCount; ++pi)
1099         write(l.second.firstIndex + pi, nullptr, firstPageAddr + pi * 0x10000);
1100     }
1101     // Local, global, TLS, reloc-only  entries.
1102     // If TLS entry has a corresponding dynamic relocations, leave it
1103     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1104     // To calculate the adjustments use offsets for thread-local storage.
1105     // http://web.archive.org/web/20190324223224/https://www.linux-mips.org/wiki/NPTL
1106     for (const std::pair<GotEntry, size_t> &p : g.local16)
1107       write(p.second, p.first.first, p.first.second);
1108     // Write VA to the primary GOT only. For secondary GOTs that
1109     // will be done by REL32 dynamic relocations.
1110     if (&g == &gots.front())
1111       for (const std::pair<Symbol *, size_t> &p : g.global)
1112         write(p.second, p.first, 0);
1113     for (const std::pair<Symbol *, size_t> &p : g.relocs)
1114       write(p.second, p.first, 0);
1115     for (const std::pair<Symbol *, size_t> &p : g.tls)
1116       write(p.second, p.first,
1117             p.first->isPreemptible || config->shared ? 0 : -0x7000);
1118     for (const std::pair<Symbol *, size_t> &p : g.dynTlsSymbols) {
1119       if (p.first == nullptr && !config->shared)
1120         write(p.second, nullptr, 1);
1121       else if (p.first && !p.first->isPreemptible) {
1122         // If we are emitting a shared library with relocations we mustn't write
1123         // anything to the GOT here. When using Elf_Rel relocations the value
1124         // one will be treated as an addend and will cause crashes at runtime
1125         if (!config->shared)
1126           write(p.second, nullptr, 1);
1127         write(p.second + 1, p.first, -0x8000);
1128       }
1129     }
1130   }
1131 }
1132 
1133 // On PowerPC the .plt section is used to hold the table of function addresses
1134 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1135 // section. I don't know why we have a BSS style type for the section but it is
1136 // consistent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1137 GotPltSection::GotPltSection()
1138     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
1139                        ".got.plt") {
1140   if (config->emachine == EM_PPC) {
1141     name = ".plt";
1142   } else if (config->emachine == EM_PPC64) {
1143     type = SHT_NOBITS;
1144     name = ".plt";
1145   }
1146 }
1147 
1148 void GotPltSection::addEntry(Symbol &sym) {
1149   assert(sym.auxIdx == symAux.size() - 1 &&
1150          symAux.back().pltIdx == entries.size());
1151   entries.push_back(&sym);
1152 }
1153 
1154 size_t GotPltSection::getSize() const {
1155   return (target->gotPltHeaderEntriesNum + entries.size()) *
1156          target->gotEntrySize;
1157 }
1158 
1159 void GotPltSection::writeTo(uint8_t *buf) {
1160   target->writeGotPltHeader(buf);
1161   buf += target->gotPltHeaderEntriesNum * target->gotEntrySize;
1162   for (const Symbol *b : entries) {
1163     target->writeGotPlt(buf, *b);
1164     buf += target->gotEntrySize;
1165   }
1166 }
1167 
1168 bool GotPltSection::isNeeded() const {
1169   // We need to emit GOTPLT even if it's empty if there's a relocation relative
1170   // to it.
1171   return !entries.empty() || hasGotPltOffRel;
1172 }
1173 
1174 static StringRef getIgotPltName() {
1175   // On ARM the IgotPltSection is part of the GotSection.
1176   if (config->emachine == EM_ARM)
1177     return ".got";
1178 
1179   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1180   // needs to be named the same.
1181   if (config->emachine == EM_PPC64)
1182     return ".plt";
1183 
1184   return ".got.plt";
1185 }
1186 
1187 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1188 // with the IgotPltSection.
1189 IgotPltSection::IgotPltSection()
1190     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1191                        config->emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1192                        target->gotEntrySize, getIgotPltName()) {}
1193 
1194 void IgotPltSection::addEntry(Symbol &sym) {
1195   assert(symAux.back().pltIdx == entries.size());
1196   entries.push_back(&sym);
1197 }
1198 
1199 size_t IgotPltSection::getSize() const {
1200   return entries.size() * target->gotEntrySize;
1201 }
1202 
1203 void IgotPltSection::writeTo(uint8_t *buf) {
1204   for (const Symbol *b : entries) {
1205     target->writeIgotPlt(buf, *b);
1206     buf += target->gotEntrySize;
1207   }
1208 }
1209 
1210 StringTableSection::StringTableSection(StringRef name, bool dynamic)
1211     : SyntheticSection(dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, name),
1212       dynamic(dynamic) {
1213   // ELF string tables start with a NUL byte.
1214   strings.push_back("");
1215   stringMap.try_emplace(CachedHashStringRef(""), 0);
1216   size = 1;
1217 }
1218 
1219 // Adds a string to the string table. If `hashIt` is true we hash and check for
1220 // duplicates. It is optional because the name of global symbols are already
1221 // uniqued and hashing them again has a big cost for a small value: uniquing
1222 // them with some other string that happens to be the same.
1223 unsigned StringTableSection::addString(StringRef s, bool hashIt) {
1224   if (hashIt) {
1225     auto r = stringMap.try_emplace(CachedHashStringRef(s), size);
1226     if (!r.second)
1227       return r.first->second;
1228   }
1229   if (s.empty())
1230     return 0;
1231   unsigned ret = this->size;
1232   this->size = this->size + s.size() + 1;
1233   strings.push_back(s);
1234   return ret;
1235 }
1236 
1237 void StringTableSection::writeTo(uint8_t *buf) {
1238   for (StringRef s : strings) {
1239     memcpy(buf, s.data(), s.size());
1240     buf[s.size()] = '\0';
1241     buf += s.size() + 1;
1242   }
1243 }
1244 
1245 // Returns the number of entries in .gnu.version_d: the number of
1246 // non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
1247 // Note that we don't support vd_cnt > 1 yet.
1248 static unsigned getVerDefNum() {
1249   return namedVersionDefs().size() + 1;
1250 }
1251 
1252 template <class ELFT>
1253 DynamicSection<ELFT>::DynamicSection()
1254     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, config->wordsize,
1255                        ".dynamic") {
1256   this->entsize = ELFT::Is64Bits ? 16 : 8;
1257 
1258   // .dynamic section is not writable on MIPS and on Fuchsia OS
1259   // which passes -z rodynamic.
1260   // See "Special Section" in Chapter 4 in the following document:
1261   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1262   if (config->emachine == EM_MIPS || config->zRodynamic)
1263     this->flags = SHF_ALLOC;
1264 }
1265 
1266 // The output section .rela.dyn may include these synthetic sections:
1267 //
1268 // - part.relaDyn
1269 // - in.relaIplt: this is included if in.relaIplt is named .rela.dyn
1270 // - in.relaPlt: this is included if a linker script places .rela.plt inside
1271 //   .rela.dyn
1272 //
1273 // DT_RELASZ is the total size of the included sections.
1274 static uint64_t addRelaSz(const RelocationBaseSection &relaDyn) {
1275   size_t size = relaDyn.getSize();
1276   if (in.relaIplt->getParent() == relaDyn.getParent())
1277     size += in.relaIplt->getSize();
1278   if (in.relaPlt->getParent() == relaDyn.getParent())
1279     size += in.relaPlt->getSize();
1280   return size;
1281 }
1282 
1283 // A Linker script may assign the RELA relocation sections to the same
1284 // output section. When this occurs we cannot just use the OutputSection
1285 // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1286 // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1287 static uint64_t addPltRelSz() {
1288   size_t size = in.relaPlt->getSize();
1289   if (in.relaIplt->getParent() == in.relaPlt->getParent() &&
1290       in.relaIplt->name == in.relaPlt->name)
1291     size += in.relaIplt->getSize();
1292   return size;
1293 }
1294 
1295 // Add remaining entries to complete .dynamic contents.
1296 template <class ELFT>
1297 std::vector<std::pair<int32_t, uint64_t>>
1298 DynamicSection<ELFT>::computeContents() {
1299   elf::Partition &part = getPartition();
1300   bool isMain = part.name.empty();
1301   std::vector<std::pair<int32_t, uint64_t>> entries;
1302 
1303   auto addInt = [&](int32_t tag, uint64_t val) {
1304     entries.emplace_back(tag, val);
1305   };
1306   auto addInSec = [&](int32_t tag, const InputSection &sec) {
1307     entries.emplace_back(tag, sec.getVA());
1308   };
1309 
1310   for (StringRef s : config->filterList)
1311     addInt(DT_FILTER, part.dynStrTab->addString(s));
1312   for (StringRef s : config->auxiliaryList)
1313     addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
1314 
1315   if (!config->rpath.empty())
1316     addInt(config->enableNewDtags ? DT_RUNPATH : DT_RPATH,
1317            part.dynStrTab->addString(config->rpath));
1318 
1319   for (SharedFile *file : ctx.sharedFiles)
1320     if (file->isNeeded)
1321       addInt(DT_NEEDED, part.dynStrTab->addString(file->soName));
1322 
1323   if (isMain) {
1324     if (!config->soName.empty())
1325       addInt(DT_SONAME, part.dynStrTab->addString(config->soName));
1326   } else {
1327     if (!config->soName.empty())
1328       addInt(DT_NEEDED, part.dynStrTab->addString(config->soName));
1329     addInt(DT_SONAME, part.dynStrTab->addString(part.name));
1330   }
1331 
1332   // Set DT_FLAGS and DT_FLAGS_1.
1333   uint32_t dtFlags = 0;
1334   uint32_t dtFlags1 = 0;
1335   if (config->bsymbolic == BsymbolicKind::All)
1336     dtFlags |= DF_SYMBOLIC;
1337   if (config->zGlobal)
1338     dtFlags1 |= DF_1_GLOBAL;
1339   if (config->zInitfirst)
1340     dtFlags1 |= DF_1_INITFIRST;
1341   if (config->zInterpose)
1342     dtFlags1 |= DF_1_INTERPOSE;
1343   if (config->zNodefaultlib)
1344     dtFlags1 |= DF_1_NODEFLIB;
1345   if (config->zNodelete)
1346     dtFlags1 |= DF_1_NODELETE;
1347   if (config->zNodlopen)
1348     dtFlags1 |= DF_1_NOOPEN;
1349   if (config->pie)
1350     dtFlags1 |= DF_1_PIE;
1351   if (config->zNow) {
1352     dtFlags |= DF_BIND_NOW;
1353     dtFlags1 |= DF_1_NOW;
1354   }
1355   if (config->zOrigin) {
1356     dtFlags |= DF_ORIGIN;
1357     dtFlags1 |= DF_1_ORIGIN;
1358   }
1359   if (!config->zText)
1360     dtFlags |= DF_TEXTREL;
1361   if (ctx.hasTlsIe && config->shared)
1362     dtFlags |= DF_STATIC_TLS;
1363 
1364   if (dtFlags)
1365     addInt(DT_FLAGS, dtFlags);
1366   if (dtFlags1)
1367     addInt(DT_FLAGS_1, dtFlags1);
1368 
1369   // DT_DEBUG is a pointer to debug information used by debuggers at runtime. We
1370   // need it for each process, so we don't write it for DSOs. The loader writes
1371   // the pointer into this entry.
1372   //
1373   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1374   // systems (currently only Fuchsia OS) provide other means to give the
1375   // debugger this information. Such systems may choose make .dynamic read-only.
1376   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1377   if (!config->shared && !config->relocatable && !config->zRodynamic)
1378     addInt(DT_DEBUG, 0);
1379 
1380   if (part.relaDyn->isNeeded() ||
1381       (in.relaIplt->isNeeded() &&
1382        part.relaDyn->getParent() == in.relaIplt->getParent())) {
1383     addInSec(part.relaDyn->dynamicTag, *part.relaDyn);
1384     entries.emplace_back(part.relaDyn->sizeDynamicTag,
1385                          addRelaSz(*part.relaDyn));
1386 
1387     bool isRela = config->isRela;
1388     addInt(isRela ? DT_RELAENT : DT_RELENT,
1389            isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1390 
1391     // MIPS dynamic loader does not support RELCOUNT tag.
1392     // The problem is in the tight relation between dynamic
1393     // relocations and GOT. So do not emit this tag on MIPS.
1394     if (config->emachine != EM_MIPS) {
1395       size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
1396       if (config->zCombreloc && numRelativeRels)
1397         addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
1398     }
1399   }
1400   if (part.relrDyn && part.relrDyn->getParent() &&
1401       !part.relrDyn->relocs.empty()) {
1402     addInSec(config->useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1403              *part.relrDyn);
1404     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1405            part.relrDyn->getParent()->size);
1406     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1407            sizeof(Elf_Relr));
1408   }
1409   // .rel[a].plt section usually consists of two parts, containing plt and
1410   // iplt relocations. It is possible to have only iplt relocations in the
1411   // output. In that case relaPlt is empty and have zero offset, the same offset
1412   // as relaIplt has. And we still want to emit proper dynamic tags for that
1413   // case, so here we always use relaPlt as marker for the beginning of
1414   // .rel[a].plt section.
1415   if (isMain && (in.relaPlt->isNeeded() || in.relaIplt->isNeeded())) {
1416     addInSec(DT_JMPREL, *in.relaPlt);
1417     entries.emplace_back(DT_PLTRELSZ, addPltRelSz());
1418     switch (config->emachine) {
1419     case EM_MIPS:
1420       addInSec(DT_MIPS_PLTGOT, *in.gotPlt);
1421       break;
1422     case EM_S390:
1423       addInSec(DT_PLTGOT, *in.got);
1424       break;
1425     case EM_SPARCV9:
1426       addInSec(DT_PLTGOT, *in.plt);
1427       break;
1428     case EM_AARCH64:
1429       if (llvm::find_if(in.relaPlt->relocs, [](const DynamicReloc &r) {
1430            return r.type == target->pltRel &&
1431                   r.sym->stOther & STO_AARCH64_VARIANT_PCS;
1432           }) != in.relaPlt->relocs.end())
1433         addInt(DT_AARCH64_VARIANT_PCS, 0);
1434       addInSec(DT_PLTGOT, *in.gotPlt);
1435       break;
1436     case EM_RISCV:
1437       if (llvm::any_of(in.relaPlt->relocs, [](const DynamicReloc &r) {
1438             return r.type == target->pltRel &&
1439                    (r.sym->stOther & STO_RISCV_VARIANT_CC);
1440           }))
1441         addInt(DT_RISCV_VARIANT_CC, 0);
1442       [[fallthrough]];
1443     default:
1444       addInSec(DT_PLTGOT, *in.gotPlt);
1445       break;
1446     }
1447     addInt(DT_PLTREL, config->isRela ? DT_RELA : DT_REL);
1448   }
1449 
1450   if (config->emachine == EM_AARCH64) {
1451     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1452       addInt(DT_AARCH64_BTI_PLT, 0);
1453     if (config->zPacPlt)
1454       addInt(DT_AARCH64_PAC_PLT, 0);
1455 
1456     if (hasMemtag()) {
1457       addInt(DT_AARCH64_MEMTAG_MODE, config->androidMemtagMode == NT_MEMTAG_LEVEL_ASYNC);
1458       addInt(DT_AARCH64_MEMTAG_HEAP, config->androidMemtagHeap);
1459       addInt(DT_AARCH64_MEMTAG_STACK, config->androidMemtagStack);
1460       if (mainPart->memtagGlobalDescriptors->isNeeded()) {
1461         addInSec(DT_AARCH64_MEMTAG_GLOBALS, *mainPart->memtagGlobalDescriptors);
1462         addInt(DT_AARCH64_MEMTAG_GLOBALSSZ,
1463                mainPart->memtagGlobalDescriptors->getSize());
1464       }
1465     }
1466   }
1467 
1468   addInSec(DT_SYMTAB, *part.dynSymTab);
1469   addInt(DT_SYMENT, sizeof(Elf_Sym));
1470   addInSec(DT_STRTAB, *part.dynStrTab);
1471   addInt(DT_STRSZ, part.dynStrTab->getSize());
1472   if (!config->zText)
1473     addInt(DT_TEXTREL, 0);
1474   if (part.gnuHashTab && part.gnuHashTab->getParent())
1475     addInSec(DT_GNU_HASH, *part.gnuHashTab);
1476   if (part.hashTab && part.hashTab->getParent())
1477     addInSec(DT_HASH, *part.hashTab);
1478 
1479   if (isMain) {
1480     if (Out::preinitArray) {
1481       addInt(DT_PREINIT_ARRAY, Out::preinitArray->addr);
1482       addInt(DT_PREINIT_ARRAYSZ, Out::preinitArray->size);
1483     }
1484     if (Out::initArray) {
1485       addInt(DT_INIT_ARRAY, Out::initArray->addr);
1486       addInt(DT_INIT_ARRAYSZ, Out::initArray->size);
1487     }
1488     if (Out::finiArray) {
1489       addInt(DT_FINI_ARRAY, Out::finiArray->addr);
1490       addInt(DT_FINI_ARRAYSZ, Out::finiArray->size);
1491     }
1492 
1493     if (Symbol *b = symtab.find(config->init))
1494       if (b->isDefined())
1495         addInt(DT_INIT, b->getVA());
1496     if (Symbol *b = symtab.find(config->fini))
1497       if (b->isDefined())
1498         addInt(DT_FINI, b->getVA());
1499   }
1500 
1501   if (part.verSym && part.verSym->isNeeded())
1502     addInSec(DT_VERSYM, *part.verSym);
1503   if (part.verDef && part.verDef->isLive()) {
1504     addInSec(DT_VERDEF, *part.verDef);
1505     addInt(DT_VERDEFNUM, getVerDefNum());
1506   }
1507   if (part.verNeed && part.verNeed->isNeeded()) {
1508     addInSec(DT_VERNEED, *part.verNeed);
1509     unsigned needNum = 0;
1510     for (SharedFile *f : ctx.sharedFiles)
1511       if (!f->vernauxs.empty())
1512         ++needNum;
1513     addInt(DT_VERNEEDNUM, needNum);
1514   }
1515 
1516   if (config->emachine == EM_MIPS) {
1517     addInt(DT_MIPS_RLD_VERSION, 1);
1518     addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1519     addInt(DT_MIPS_BASE_ADDRESS, target->getImageBase());
1520     addInt(DT_MIPS_SYMTABNO, part.dynSymTab->getNumSymbols());
1521     addInt(DT_MIPS_LOCAL_GOTNO, in.mipsGot->getLocalEntriesNum());
1522 
1523     if (const Symbol *b = in.mipsGot->getFirstGlobalEntry())
1524       addInt(DT_MIPS_GOTSYM, b->dynsymIndex);
1525     else
1526       addInt(DT_MIPS_GOTSYM, part.dynSymTab->getNumSymbols());
1527     addInSec(DT_PLTGOT, *in.mipsGot);
1528     if (in.mipsRldMap) {
1529       if (!config->pie)
1530         addInSec(DT_MIPS_RLD_MAP, *in.mipsRldMap);
1531       // Store the offset to the .rld_map section
1532       // relative to the address of the tag.
1533       addInt(DT_MIPS_RLD_MAP_REL,
1534              in.mipsRldMap->getVA() - (getVA() + entries.size() * entsize));
1535     }
1536   }
1537 
1538   // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
1539   // glibc assumes the old-style BSS PLT layout which we don't support.
1540   if (config->emachine == EM_PPC)
1541     addInSec(DT_PPC_GOT, *in.got);
1542 
1543   // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1544   if (config->emachine == EM_PPC64 && in.plt->isNeeded()) {
1545     // The Glink tag points to 32 bytes before the first lazy symbol resolution
1546     // stub, which starts directly after the header.
1547     addInt(DT_PPC64_GLINK, in.plt->getVA() + target->pltHeaderSize - 32);
1548   }
1549 
1550   if (config->emachine == EM_PPC64)
1551     addInt(DT_PPC64_OPT, getPPC64TargetInfo()->ppc64DynamicSectionOpt);
1552 
1553   addInt(DT_NULL, 0);
1554   return entries;
1555 }
1556 
1557 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1558   if (OutputSection *sec = getPartition().dynStrTab->getParent())
1559     getParent()->link = sec->sectionIndex;
1560   this->size = computeContents().size() * this->entsize;
1561 }
1562 
1563 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *buf) {
1564   auto *p = reinterpret_cast<Elf_Dyn *>(buf);
1565 
1566   for (std::pair<int32_t, uint64_t> kv : computeContents()) {
1567     p->d_tag = kv.first;
1568     p->d_un.d_val = kv.second;
1569     ++p;
1570   }
1571 }
1572 
1573 uint64_t DynamicReloc::getOffset() const {
1574   return inputSec->getVA(offsetInSec);
1575 }
1576 
1577 int64_t DynamicReloc::computeAddend() const {
1578   switch (kind) {
1579   case AddendOnly:
1580     assert(sym == nullptr);
1581     return addend;
1582   case AgainstSymbol:
1583     assert(sym != nullptr);
1584     return addend;
1585   case AddendOnlyWithTargetVA:
1586   case AgainstSymbolWithTargetVA: {
1587     uint64_t ca = InputSection::getRelocTargetVA(inputSec->file, type, addend,
1588                                                  getOffset(), *sym, expr);
1589     return config->is64 ? ca : SignExtend64<32>(ca);
1590   }
1591   case MipsMultiGotPage:
1592     assert(sym == nullptr);
1593     return getMipsPageAddr(outputSec->addr) + addend;
1594   }
1595   llvm_unreachable("Unknown DynamicReloc::Kind enum");
1596 }
1597 
1598 uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *symTab) const {
1599   if (!needsDynSymIndex())
1600     return 0;
1601 
1602   size_t index = symTab->getSymbolIndex(sym);
1603   assert((index != 0 || (type != target->gotRel && type != target->pltRel) ||
1604           !mainPart->dynSymTab->getParent()) &&
1605          "GOT or PLT relocation must refer to symbol in dynamic symbol table");
1606   return index;
1607 }
1608 
1609 RelocationBaseSection::RelocationBaseSection(StringRef name, uint32_t type,
1610                                              int32_t dynamicTag,
1611                                              int32_t sizeDynamicTag,
1612                                              bool combreloc,
1613                                              unsigned concurrency)
1614     : SyntheticSection(SHF_ALLOC, type, config->wordsize, name),
1615       dynamicTag(dynamicTag), sizeDynamicTag(sizeDynamicTag),
1616       relocsVec(concurrency), combreloc(combreloc) {}
1617 
1618 void RelocationBaseSection::addSymbolReloc(
1619     RelType dynType, InputSectionBase &isec, uint64_t offsetInSec, Symbol &sym,
1620     int64_t addend, std::optional<RelType> addendRelType) {
1621   addReloc(DynamicReloc::AgainstSymbol, dynType, isec, offsetInSec, sym, addend,
1622            R_ADDEND, addendRelType ? *addendRelType : target->noneRel);
1623 }
1624 
1625 void RelocationBaseSection::addAddendOnlyRelocIfNonPreemptible(
1626     RelType dynType, GotSection &sec, uint64_t offsetInSec, Symbol &sym,
1627     RelType addendRelType) {
1628   // No need to write an addend to the section for preemptible symbols.
1629   if (sym.isPreemptible)
1630     addReloc({dynType, &sec, offsetInSec, DynamicReloc::AgainstSymbol, sym, 0,
1631               R_ABS});
1632   else
1633     addReloc(DynamicReloc::AddendOnlyWithTargetVA, dynType, sec, offsetInSec,
1634              sym, 0, R_ABS, addendRelType);
1635 }
1636 
1637 void RelocationBaseSection::mergeRels() {
1638   size_t newSize = relocs.size();
1639   for (const auto &v : relocsVec)
1640     newSize += v.size();
1641   relocs.reserve(newSize);
1642   for (const auto &v : relocsVec)
1643     llvm::append_range(relocs, v);
1644   relocsVec.clear();
1645 }
1646 
1647 void RelocationBaseSection::partitionRels() {
1648   if (!combreloc)
1649     return;
1650   const RelType relativeRel = target->relativeRel;
1651   numRelativeRelocs =
1652       llvm::partition(relocs, [=](auto &r) { return r.type == relativeRel; }) -
1653       relocs.begin();
1654 }
1655 
1656 void RelocationBaseSection::finalizeContents() {
1657   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
1658 
1659   // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1660   // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1661   // case.
1662   if (symTab && symTab->getParent())
1663     getParent()->link = symTab->getParent()->sectionIndex;
1664   else
1665     getParent()->link = 0;
1666 
1667   if (in.relaPlt.get() == this && in.gotPlt->getParent()) {
1668     getParent()->flags |= ELF::SHF_INFO_LINK;
1669     getParent()->info = in.gotPlt->getParent()->sectionIndex;
1670   }
1671   if (in.relaIplt.get() == this && in.igotPlt->getParent()) {
1672     getParent()->flags |= ELF::SHF_INFO_LINK;
1673     getParent()->info = in.igotPlt->getParent()->sectionIndex;
1674   }
1675 }
1676 
1677 void DynamicReloc::computeRaw(SymbolTableBaseSection *symtab) {
1678   r_offset = getOffset();
1679   r_sym = getSymIndex(symtab);
1680   addend = computeAddend();
1681   kind = AddendOnly; // Catch errors
1682 }
1683 
1684 void RelocationBaseSection::computeRels() {
1685   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
1686   parallelForEach(relocs,
1687                   [symTab](DynamicReloc &rel) { rel.computeRaw(symTab); });
1688   // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
1689   // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
1690   // is to make results easier to read.
1691   if (combreloc) {
1692     auto nonRelative = relocs.begin() + numRelativeRelocs;
1693     parallelSort(relocs.begin(), nonRelative,
1694                  [&](auto &a, auto &b) { return a.r_offset < b.r_offset; });
1695     // Non-relative relocations are few, so don't bother with parallelSort.
1696     llvm::sort(nonRelative, relocs.end(), [&](auto &a, auto &b) {
1697       return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset);
1698     });
1699   }
1700 }
1701 
1702 template <class ELFT>
1703 RelocationSection<ELFT>::RelocationSection(StringRef name, bool combreloc,
1704                                            unsigned concurrency)
1705     : RelocationBaseSection(name, config->isRela ? SHT_RELA : SHT_REL,
1706                             config->isRela ? DT_RELA : DT_REL,
1707                             config->isRela ? DT_RELASZ : DT_RELSZ, combreloc,
1708                             concurrency) {
1709   this->entsize = config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1710 }
1711 
1712 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *buf) {
1713   computeRels();
1714   for (const DynamicReloc &rel : relocs) {
1715     auto *p = reinterpret_cast<Elf_Rela *>(buf);
1716     p->r_offset = rel.r_offset;
1717     p->setSymbolAndType(rel.r_sym, rel.type, config->isMips64EL);
1718     if (config->isRela)
1719       p->r_addend = rel.addend;
1720     buf += config->isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1721   }
1722 }
1723 
1724 RelrBaseSection::RelrBaseSection(unsigned concurrency)
1725     : SyntheticSection(SHF_ALLOC,
1726                        config->useAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
1727                        config->wordsize, ".relr.dyn"),
1728       relocsVec(concurrency) {}
1729 
1730 void RelrBaseSection::mergeRels() {
1731   size_t newSize = relocs.size();
1732   for (const auto &v : relocsVec)
1733     newSize += v.size();
1734   relocs.reserve(newSize);
1735   for (const auto &v : relocsVec)
1736     llvm::append_range(relocs, v);
1737   relocsVec.clear();
1738 }
1739 
1740 template <class ELFT>
1741 AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1742     StringRef name, unsigned concurrency)
1743     : RelocationBaseSection(
1744           name, config->isRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1745           config->isRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1746           config->isRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ,
1747           /*combreloc=*/false, concurrency) {
1748   this->entsize = 1;
1749 }
1750 
1751 template <class ELFT>
1752 bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1753   // This function computes the contents of an Android-format packed relocation
1754   // section.
1755   //
1756   // This format compresses relocations by using relocation groups to factor out
1757   // fields that are common between relocations and storing deltas from previous
1758   // relocations in SLEB128 format (which has a short representation for small
1759   // numbers). A good example of a relocation type with common fields is
1760   // R_*_RELATIVE, which is normally used to represent function pointers in
1761   // vtables. In the REL format, each relative relocation has the same r_info
1762   // field, and is only different from other relative relocations in terms of
1763   // the r_offset field. By sorting relocations by offset, grouping them by
1764   // r_info and representing each relocation with only the delta from the
1765   // previous offset, each 8-byte relocation can be compressed to as little as 1
1766   // byte (or less with run-length encoding). This relocation packer was able to
1767   // reduce the size of the relocation section in an Android Chromium DSO from
1768   // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1769   //
1770   // A relocation section consists of a header containing the literal bytes
1771   // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1772   // elements are the total number of relocations in the section and an initial
1773   // r_offset value. The remaining elements define a sequence of relocation
1774   // groups. Each relocation group starts with a header consisting of the
1775   // following elements:
1776   //
1777   // - the number of relocations in the relocation group
1778   // - flags for the relocation group
1779   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1780   //   for each relocation in the group.
1781   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1782   //   field for each relocation in the group.
1783   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1784   //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1785   //   each relocation in the group.
1786   //
1787   // Following the relocation group header are descriptions of each of the
1788   // relocations in the group. They consist of the following elements:
1789   //
1790   // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1791   //   delta for this relocation.
1792   // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1793   //   field for this relocation.
1794   // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1795   //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1796   //   this relocation.
1797 
1798   size_t oldSize = relocData.size();
1799 
1800   relocData = {'A', 'P', 'S', '2'};
1801   raw_svector_ostream os(relocData);
1802   auto add = [&](int64_t v) { encodeSLEB128(v, os); };
1803 
1804   // The format header includes the number of relocations and the initial
1805   // offset (we set this to zero because the first relocation group will
1806   // perform the initial adjustment).
1807   add(relocs.size());
1808   add(0);
1809 
1810   std::vector<Elf_Rela> relatives, nonRelatives;
1811 
1812   for (const DynamicReloc &rel : relocs) {
1813     Elf_Rela r;
1814     r.r_offset = rel.getOffset();
1815     r.setSymbolAndType(rel.getSymIndex(getPartition().dynSymTab.get()),
1816                        rel.type, false);
1817     r.r_addend = config->isRela ? rel.computeAddend() : 0;
1818 
1819     if (r.getType(config->isMips64EL) == target->relativeRel)
1820       relatives.push_back(r);
1821     else
1822       nonRelatives.push_back(r);
1823   }
1824 
1825   llvm::sort(relatives, [](const Elf_Rel &a, const Elf_Rel &b) {
1826     return a.r_offset < b.r_offset;
1827   });
1828 
1829   // Try to find groups of relative relocations which are spaced one word
1830   // apart from one another. These generally correspond to vtable entries. The
1831   // format allows these groups to be encoded using a sort of run-length
1832   // encoding, but each group will cost 7 bytes in addition to the offset from
1833   // the previous group, so it is only profitable to do this for groups of
1834   // size 8 or larger.
1835   std::vector<Elf_Rela> ungroupedRelatives;
1836   std::vector<std::vector<Elf_Rela>> relativeGroups;
1837   for (auto i = relatives.begin(), e = relatives.end(); i != e;) {
1838     std::vector<Elf_Rela> group;
1839     do {
1840       group.push_back(*i++);
1841     } while (i != e && (i - 1)->r_offset + config->wordsize == i->r_offset);
1842 
1843     if (group.size() < 8)
1844       ungroupedRelatives.insert(ungroupedRelatives.end(), group.begin(),
1845                                 group.end());
1846     else
1847       relativeGroups.emplace_back(std::move(group));
1848   }
1849 
1850   // For non-relative relocations, we would like to:
1851   //   1. Have relocations with the same symbol offset to be consecutive, so
1852   //      that the runtime linker can speed-up symbol lookup by implementing an
1853   //      1-entry cache.
1854   //   2. Group relocations by r_info to reduce the size of the relocation
1855   //      section.
1856   // Since the symbol offset is the high bits in r_info, sorting by r_info
1857   // allows us to do both.
1858   //
1859   // For Rela, we also want to sort by r_addend when r_info is the same. This
1860   // enables us to group by r_addend as well.
1861   llvm::sort(nonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1862     if (a.r_info != b.r_info)
1863       return a.r_info < b.r_info;
1864     if (a.r_addend != b.r_addend)
1865       return a.r_addend < b.r_addend;
1866     return a.r_offset < b.r_offset;
1867   });
1868 
1869   // Group relocations with the same r_info. Note that each group emits a group
1870   // header and that may make the relocation section larger. It is hard to
1871   // estimate the size of a group header as the encoded size of that varies
1872   // based on r_info. However, we can approximate this trade-off by the number
1873   // of values encoded. Each group header contains 3 values, and each relocation
1874   // in a group encodes one less value, as compared to when it is not grouped.
1875   // Therefore, we only group relocations if there are 3 or more of them with
1876   // the same r_info.
1877   //
1878   // For Rela, the addend for most non-relative relocations is zero, and thus we
1879   // can usually get a smaller relocation section if we group relocations with 0
1880   // addend as well.
1881   std::vector<Elf_Rela> ungroupedNonRelatives;
1882   std::vector<std::vector<Elf_Rela>> nonRelativeGroups;
1883   for (auto i = nonRelatives.begin(), e = nonRelatives.end(); i != e;) {
1884     auto j = i + 1;
1885     while (j != e && i->r_info == j->r_info &&
1886            (!config->isRela || i->r_addend == j->r_addend))
1887       ++j;
1888     if (j - i < 3 || (config->isRela && i->r_addend != 0))
1889       ungroupedNonRelatives.insert(ungroupedNonRelatives.end(), i, j);
1890     else
1891       nonRelativeGroups.emplace_back(i, j);
1892     i = j;
1893   }
1894 
1895   // Sort ungrouped relocations by offset to minimize the encoded length.
1896   llvm::sort(ungroupedNonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1897     return a.r_offset < b.r_offset;
1898   });
1899 
1900   unsigned hasAddendIfRela =
1901       config->isRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1902 
1903   uint64_t offset = 0;
1904   uint64_t addend = 0;
1905 
1906   // Emit the run-length encoding for the groups of adjacent relative
1907   // relocations. Each group is represented using two groups in the packed
1908   // format. The first is used to set the current offset to the start of the
1909   // group (and also encodes the first relocation), and the second encodes the
1910   // remaining relocations.
1911   for (std::vector<Elf_Rela> &g : relativeGroups) {
1912     // The first relocation in the group.
1913     add(1);
1914     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1915         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1916     add(g[0].r_offset - offset);
1917     add(target->relativeRel);
1918     if (config->isRela) {
1919       add(g[0].r_addend - addend);
1920       addend = g[0].r_addend;
1921     }
1922 
1923     // The remaining relocations.
1924     add(g.size() - 1);
1925     add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1926         RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1927     add(config->wordsize);
1928     add(target->relativeRel);
1929     if (config->isRela) {
1930       for (const auto &i : llvm::drop_begin(g)) {
1931         add(i.r_addend - addend);
1932         addend = i.r_addend;
1933       }
1934     }
1935 
1936     offset = g.back().r_offset;
1937   }
1938 
1939   // Now the ungrouped relatives.
1940   if (!ungroupedRelatives.empty()) {
1941     add(ungroupedRelatives.size());
1942     add(RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1943     add(target->relativeRel);
1944     for (Elf_Rela &r : ungroupedRelatives) {
1945       add(r.r_offset - offset);
1946       offset = r.r_offset;
1947       if (config->isRela) {
1948         add(r.r_addend - addend);
1949         addend = r.r_addend;
1950       }
1951     }
1952   }
1953 
1954   // Grouped non-relatives.
1955   for (ArrayRef<Elf_Rela> g : nonRelativeGroups) {
1956     add(g.size());
1957     add(RELOCATION_GROUPED_BY_INFO_FLAG);
1958     add(g[0].r_info);
1959     for (const Elf_Rela &r : g) {
1960       add(r.r_offset - offset);
1961       offset = r.r_offset;
1962     }
1963     addend = 0;
1964   }
1965 
1966   // Finally the ungrouped non-relative relocations.
1967   if (!ungroupedNonRelatives.empty()) {
1968     add(ungroupedNonRelatives.size());
1969     add(hasAddendIfRela);
1970     for (Elf_Rela &r : ungroupedNonRelatives) {
1971       add(r.r_offset - offset);
1972       offset = r.r_offset;
1973       add(r.r_info);
1974       if (config->isRela) {
1975         add(r.r_addend - addend);
1976         addend = r.r_addend;
1977       }
1978     }
1979   }
1980 
1981   // Don't allow the section to shrink; otherwise the size of the section can
1982   // oscillate infinitely.
1983   if (relocData.size() < oldSize)
1984     relocData.append(oldSize - relocData.size(), 0);
1985 
1986   // Returns whether the section size changed. We need to keep recomputing both
1987   // section layout and the contents of this section until the size converges
1988   // because changing this section's size can affect section layout, which in
1989   // turn can affect the sizes of the LEB-encoded integers stored in this
1990   // section.
1991   return relocData.size() != oldSize;
1992 }
1993 
1994 template <class ELFT>
1995 RelrSection<ELFT>::RelrSection(unsigned concurrency)
1996     : RelrBaseSection(concurrency) {
1997   this->entsize = config->wordsize;
1998 }
1999 
2000 template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
2001   // This function computes the contents of an SHT_RELR packed relocation
2002   // section.
2003   //
2004   // Proposal for adding SHT_RELR sections to generic-abi is here:
2005   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
2006   //
2007   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
2008   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
2009   //
2010   // i.e. start with an address, followed by any number of bitmaps. The address
2011   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
2012   // relocations each, at subsequent offsets following the last address entry.
2013   //
2014   // The bitmap entries must have 1 in the least significant bit. The assumption
2015   // here is that an address cannot have 1 in lsb. Odd addresses are not
2016   // supported.
2017   //
2018   // Excluding the least significant bit in the bitmap, each non-zero bit in
2019   // the bitmap represents a relocation to be applied to a corresponding machine
2020   // word that follows the base address word. The second least significant bit
2021   // represents the machine word immediately following the initial address, and
2022   // each bit that follows represents the next word, in linear order. As such,
2023   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
2024   // 63 relocations in a 64-bit object.
2025   //
2026   // This encoding has a couple of interesting properties:
2027   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
2028   //    even means address, odd means bitmap.
2029   // 2. Just a simple list of addresses is a valid encoding.
2030 
2031   size_t oldSize = relrRelocs.size();
2032   relrRelocs.clear();
2033 
2034   // Same as Config->Wordsize but faster because this is a compile-time
2035   // constant.
2036   const size_t wordsize = sizeof(typename ELFT::uint);
2037 
2038   // Number of bits to use for the relocation offsets bitmap.
2039   // Must be either 63 or 31.
2040   const size_t nBits = wordsize * 8 - 1;
2041 
2042   // Get offsets for all relative relocations and sort them.
2043   std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]);
2044   for (auto [i, r] : llvm::enumerate(relocs))
2045     offsets[i] = r.getOffset();
2046   llvm::sort(offsets.get(), offsets.get() + relocs.size());
2047 
2048   // For each leading relocation, find following ones that can be folded
2049   // as a bitmap and fold them.
2050   for (size_t i = 0, e = relocs.size(); i != e;) {
2051     // Add a leading relocation.
2052     relrRelocs.push_back(Elf_Relr(offsets[i]));
2053     uint64_t base = offsets[i] + wordsize;
2054     ++i;
2055 
2056     // Find foldable relocations to construct bitmaps.
2057     for (;;) {
2058       uint64_t bitmap = 0;
2059       for (; i != e; ++i) {
2060         uint64_t d = offsets[i] - base;
2061         if (d >= nBits * wordsize || d % wordsize)
2062           break;
2063         bitmap |= uint64_t(1) << (d / wordsize);
2064       }
2065       if (!bitmap)
2066         break;
2067       relrRelocs.push_back(Elf_Relr((bitmap << 1) | 1));
2068       base += nBits * wordsize;
2069     }
2070   }
2071 
2072   // Don't allow the section to shrink; otherwise the size of the section can
2073   // oscillate infinitely. Trailing 1s do not decode to more relocations.
2074   if (relrRelocs.size() < oldSize) {
2075     log(".relr.dyn needs " + Twine(oldSize - relrRelocs.size()) +
2076         " padding word(s)");
2077     relrRelocs.resize(oldSize, Elf_Relr(1));
2078   }
2079 
2080   return relrRelocs.size() != oldSize;
2081 }
2082 
2083 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &strTabSec)
2084     : SyntheticSection(strTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
2085                        strTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
2086                        config->wordsize,
2087                        strTabSec.isDynamic() ? ".dynsym" : ".symtab"),
2088       strTabSec(strTabSec) {}
2089 
2090 // Orders symbols according to their positions in the GOT,
2091 // in compliance with MIPS ABI rules.
2092 // See "Global Offset Table" in Chapter 5 in the following document
2093 // for detailed description:
2094 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2095 static bool sortMipsSymbols(const SymbolTableEntry &l,
2096                             const SymbolTableEntry &r) {
2097   // Sort entries related to non-local preemptible symbols by GOT indexes.
2098   // All other entries go to the beginning of a dynsym in arbitrary order.
2099   if (l.sym->isInGot() && r.sym->isInGot())
2100     return l.sym->getGotIdx() < r.sym->getGotIdx();
2101   if (!l.sym->isInGot() && !r.sym->isInGot())
2102     return false;
2103   return !l.sym->isInGot();
2104 }
2105 
2106 void SymbolTableBaseSection::finalizeContents() {
2107   if (OutputSection *sec = strTabSec.getParent())
2108     getParent()->link = sec->sectionIndex;
2109 
2110   if (this->type != SHT_DYNSYM) {
2111     sortSymTabSymbols();
2112     return;
2113   }
2114 
2115   // If it is a .dynsym, there should be no local symbols, but we need
2116   // to do a few things for the dynamic linker.
2117 
2118   // Section's Info field has the index of the first non-local symbol.
2119   // Because the first symbol entry is a null entry, 1 is the first.
2120   getParent()->info = 1;
2121 
2122   if (getPartition().gnuHashTab) {
2123     // NB: It also sorts Symbols to meet the GNU hash table requirements.
2124     getPartition().gnuHashTab->addSymbols(symbols);
2125   } else if (config->emachine == EM_MIPS) {
2126     llvm::stable_sort(symbols, sortMipsSymbols);
2127   }
2128 
2129   // Only the main partition's dynsym indexes are stored in the symbols
2130   // themselves. All other partitions use a lookup table.
2131   if (this == mainPart->dynSymTab.get()) {
2132     size_t i = 0;
2133     for (const SymbolTableEntry &s : symbols)
2134       s.sym->dynsymIndex = ++i;
2135   }
2136 }
2137 
2138 // The ELF spec requires that all local symbols precede global symbols, so we
2139 // sort symbol entries in this function. (For .dynsym, we don't do that because
2140 // symbols for dynamic linking are inherently all globals.)
2141 //
2142 // Aside from above, we put local symbols in groups starting with the STT_FILE
2143 // symbol. That is convenient for purpose of identifying where are local symbols
2144 // coming from.
2145 void SymbolTableBaseSection::sortSymTabSymbols() {
2146   // Move all local symbols before global symbols.
2147   auto e = std::stable_partition(
2148       symbols.begin(), symbols.end(),
2149       [](const SymbolTableEntry &s) { return s.sym->isLocal(); });
2150   size_t numLocals = e - symbols.begin();
2151   getParent()->info = numLocals + 1;
2152 
2153   // We want to group the local symbols by file. For that we rebuild the local
2154   // part of the symbols vector. We do not need to care about the STT_FILE
2155   // symbols, they are already naturally placed first in each group. That
2156   // happens because STT_FILE is always the first symbol in the object and hence
2157   // precede all other local symbols we add for a file.
2158   MapVector<InputFile *, SmallVector<SymbolTableEntry, 0>> arr;
2159   for (const SymbolTableEntry &s : llvm::make_range(symbols.begin(), e))
2160     arr[s.sym->file].push_back(s);
2161 
2162   auto i = symbols.begin();
2163   for (auto &p : arr)
2164     for (SymbolTableEntry &entry : p.second)
2165       *i++ = entry;
2166 }
2167 
2168 void SymbolTableBaseSection::addSymbol(Symbol *b) {
2169   // Adding a local symbol to a .dynsym is a bug.
2170   assert(this->type != SHT_DYNSYM || !b->isLocal());
2171   symbols.push_back({b, strTabSec.addString(b->getName(), false)});
2172 }
2173 
2174 size_t SymbolTableBaseSection::getSymbolIndex(Symbol *sym) {
2175   if (this == mainPart->dynSymTab.get())
2176     return sym->dynsymIndex;
2177 
2178   // Initializes symbol lookup tables lazily. This is used only for -r,
2179   // --emit-relocs and dynsyms in partitions other than the main one.
2180   llvm::call_once(onceFlag, [&] {
2181     symbolIndexMap.reserve(symbols.size());
2182     size_t i = 0;
2183     for (const SymbolTableEntry &e : symbols) {
2184       if (e.sym->type == STT_SECTION)
2185         sectionIndexMap[e.sym->getOutputSection()] = ++i;
2186       else
2187         symbolIndexMap[e.sym] = ++i;
2188     }
2189   });
2190 
2191   // Section symbols are mapped based on their output sections
2192   // to maintain their semantics.
2193   if (sym->type == STT_SECTION)
2194     return sectionIndexMap.lookup(sym->getOutputSection());
2195   return symbolIndexMap.lookup(sym);
2196 }
2197 
2198 template <class ELFT>
2199 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &strTabSec)
2200     : SymbolTableBaseSection(strTabSec) {
2201   this->entsize = sizeof(Elf_Sym);
2202 }
2203 
2204 static BssSection *getCommonSec(Symbol *sym) {
2205   if (config->relocatable)
2206     if (auto *d = dyn_cast<Defined>(sym))
2207       return dyn_cast_or_null<BssSection>(d->section);
2208   return nullptr;
2209 }
2210 
2211 static uint32_t getSymSectionIndex(Symbol *sym) {
2212   assert(!(sym->hasFlag(NEEDS_COPY) && sym->isObject()));
2213   if (!isa<Defined>(sym) || sym->hasFlag(NEEDS_COPY))
2214     return SHN_UNDEF;
2215   if (const OutputSection *os = sym->getOutputSection())
2216     return os->sectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
2217                                              : os->sectionIndex;
2218   return SHN_ABS;
2219 }
2220 
2221 // Write the internal symbol table contents to the output symbol table.
2222 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *buf) {
2223   // The first entry is a null entry as per the ELF spec.
2224   buf += sizeof(Elf_Sym);
2225 
2226   auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2227 
2228   for (SymbolTableEntry &ent : symbols) {
2229     Symbol *sym = ent.sym;
2230     bool isDefinedHere = type == SHT_SYMTAB || sym->partition == partition;
2231 
2232     // Set st_name, st_info and st_other.
2233     eSym->st_name = ent.strTabOffset;
2234     eSym->setBindingAndType(sym->binding, sym->type);
2235     eSym->st_other = sym->stOther;
2236 
2237     if (BssSection *commonSec = getCommonSec(sym)) {
2238       // When -r is specified, a COMMON symbol is not allocated. Its st_shndx
2239       // holds SHN_COMMON and st_value holds the alignment.
2240       eSym->st_shndx = SHN_COMMON;
2241       eSym->st_value = commonSec->addralign;
2242       eSym->st_size = cast<Defined>(sym)->size;
2243     } else {
2244       const uint32_t shndx = getSymSectionIndex(sym);
2245       if (isDefinedHere) {
2246         eSym->st_shndx = shndx;
2247         eSym->st_value = sym->getVA();
2248         // Copy symbol size if it is a defined symbol. st_size is not
2249         // significant for undefined symbols, so whether copying it or not is up
2250         // to us if that's the case. We'll leave it as zero because by not
2251         // setting a value, we can get the exact same outputs for two sets of
2252         // input files that differ only in undefined symbol size in DSOs.
2253         eSym->st_size = shndx != SHN_UNDEF ? cast<Defined>(sym)->size : 0;
2254       } else {
2255         eSym->st_shndx = 0;
2256         eSym->st_value = 0;
2257         eSym->st_size = 0;
2258       }
2259     }
2260 
2261     ++eSym;
2262   }
2263 
2264   // On MIPS we need to mark symbol which has a PLT entry and requires
2265   // pointer equality by STO_MIPS_PLT flag. That is necessary to help
2266   // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
2267   // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
2268   if (config->emachine == EM_MIPS) {
2269     auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2270 
2271     for (SymbolTableEntry &ent : symbols) {
2272       Symbol *sym = ent.sym;
2273       if (sym->isInPlt() && sym->hasFlag(NEEDS_COPY))
2274         eSym->st_other |= STO_MIPS_PLT;
2275       if (isMicroMips()) {
2276         // We already set the less-significant bit for symbols
2277         // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
2278         // records. That allows us to distinguish such symbols in
2279         // the `MIPS<ELFT>::relocate()` routine. Now we should
2280         // clear that bit for non-dynamic symbol table, so tools
2281         // like `objdump` will be able to deal with a correct
2282         // symbol position.
2283         if (sym->isDefined() &&
2284             ((sym->stOther & STO_MIPS_MICROMIPS) || sym->hasFlag(NEEDS_COPY))) {
2285           if (!strTabSec.isDynamic())
2286             eSym->st_value &= ~1;
2287           eSym->st_other |= STO_MIPS_MICROMIPS;
2288         }
2289       }
2290       if (config->relocatable)
2291         if (auto *d = dyn_cast<Defined>(sym))
2292           if (isMipsPIC<ELFT>(d))
2293             eSym->st_other |= STO_MIPS_PIC;
2294       ++eSym;
2295     }
2296   }
2297 }
2298 
2299 SymtabShndxSection::SymtabShndxSection()
2300     : SyntheticSection(0, SHT_SYMTAB_SHNDX, 4, ".symtab_shndx") {
2301   this->entsize = 4;
2302 }
2303 
2304 void SymtabShndxSection::writeTo(uint8_t *buf) {
2305   // We write an array of 32 bit values, where each value has 1:1 association
2306   // with an entry in .symtab. If the corresponding entry contains SHN_XINDEX,
2307   // we need to write actual index, otherwise, we must write SHN_UNDEF(0).
2308   buf += 4; // Ignore .symtab[0] entry.
2309   for (const SymbolTableEntry &entry : in.symTab->getSymbols()) {
2310     if (!getCommonSec(entry.sym) && getSymSectionIndex(entry.sym) == SHN_XINDEX)
2311       write32(buf, entry.sym->getOutputSection()->sectionIndex);
2312     buf += 4;
2313   }
2314 }
2315 
2316 bool SymtabShndxSection::isNeeded() const {
2317   // SHT_SYMTAB can hold symbols with section indices values up to
2318   // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
2319   // section. Problem is that we reveal the final section indices a bit too
2320   // late, and we do not know them here. For simplicity, we just always create
2321   // a .symtab_shndx section when the amount of output sections is huge.
2322   size_t size = 0;
2323   for (SectionCommand *cmd : script->sectionCommands)
2324     if (isa<OutputDesc>(cmd))
2325       ++size;
2326   return size >= SHN_LORESERVE;
2327 }
2328 
2329 void SymtabShndxSection::finalizeContents() {
2330   getParent()->link = in.symTab->getParent()->sectionIndex;
2331 }
2332 
2333 size_t SymtabShndxSection::getSize() const {
2334   return in.symTab->getNumSymbols() * 4;
2335 }
2336 
2337 // .hash and .gnu.hash sections contain on-disk hash tables that map
2338 // symbol names to their dynamic symbol table indices. Their purpose
2339 // is to help the dynamic linker resolve symbols quickly. If ELF files
2340 // don't have them, the dynamic linker has to do linear search on all
2341 // dynamic symbols, which makes programs slower. Therefore, a .hash
2342 // section is added to a DSO by default.
2343 //
2344 // The Unix semantics of resolving dynamic symbols is somewhat expensive.
2345 // Each ELF file has a list of DSOs that the ELF file depends on and a
2346 // list of dynamic symbols that need to be resolved from any of the
2347 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2348 // where m is the number of DSOs and n is the number of dynamic
2349 // symbols. For modern large programs, both m and n are large.  So
2350 // making each step faster by using hash tables substantially
2351 // improves time to load programs.
2352 //
2353 // (Note that this is not the only way to design the shared library.
2354 // For instance, the Windows DLL takes a different approach. On
2355 // Windows, each dynamic symbol has a name of DLL from which the symbol
2356 // has to be resolved. That makes the cost of symbol resolution O(n).
2357 // This disables some hacky techniques you can use on Unix such as
2358 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2359 //
2360 // Due to historical reasons, we have two different hash tables, .hash
2361 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2362 // and better version of .hash. .hash is just an on-disk hash table, but
2363 // .gnu.hash has a bloom filter in addition to a hash table to skip
2364 // DSOs very quickly. If you are sure that your dynamic linker knows
2365 // about .gnu.hash, you want to specify --hash-style=gnu. Otherwise, a
2366 // safe bet is to specify --hash-style=both for backward compatibility.
2367 GnuHashTableSection::GnuHashTableSection()
2368     : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, config->wordsize, ".gnu.hash") {
2369 }
2370 
2371 void GnuHashTableSection::finalizeContents() {
2372   if (OutputSection *sec = getPartition().dynSymTab->getParent())
2373     getParent()->link = sec->sectionIndex;
2374 
2375   // Computes bloom filter size in word size. We want to allocate 12
2376   // bits for each symbol. It must be a power of two.
2377   if (symbols.empty()) {
2378     maskWords = 1;
2379   } else {
2380     uint64_t numBits = symbols.size() * 12;
2381     maskWords = NextPowerOf2(numBits / (config->wordsize * 8));
2382   }
2383 
2384   size = 16;                            // Header
2385   size += config->wordsize * maskWords; // Bloom filter
2386   size += nBuckets * 4;                 // Hash buckets
2387   size += symbols.size() * 4;           // Hash values
2388 }
2389 
2390 void GnuHashTableSection::writeTo(uint8_t *buf) {
2391   // Write a header.
2392   write32(buf, nBuckets);
2393   write32(buf + 4, getPartition().dynSymTab->getNumSymbols() - symbols.size());
2394   write32(buf + 8, maskWords);
2395   write32(buf + 12, Shift2);
2396   buf += 16;
2397 
2398   // Write the 2-bit bloom filter.
2399   const unsigned c = config->is64 ? 64 : 32;
2400   for (const Entry &sym : symbols) {
2401     // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
2402     // the word using bits [0:5] and [26:31].
2403     size_t i = (sym.hash / c) & (maskWords - 1);
2404     uint64_t val = readUint(buf + i * config->wordsize);
2405     val |= uint64_t(1) << (sym.hash % c);
2406     val |= uint64_t(1) << ((sym.hash >> Shift2) % c);
2407     writeUint(buf + i * config->wordsize, val);
2408   }
2409   buf += config->wordsize * maskWords;
2410 
2411   // Write the hash table.
2412   uint32_t *buckets = reinterpret_cast<uint32_t *>(buf);
2413   uint32_t oldBucket = -1;
2414   uint32_t *values = buckets + nBuckets;
2415   for (auto i = symbols.begin(), e = symbols.end(); i != e; ++i) {
2416     // Write a hash value. It represents a sequence of chains that share the
2417     // same hash modulo value. The last element of each chain is terminated by
2418     // LSB 1.
2419     uint32_t hash = i->hash;
2420     bool isLastInChain = (i + 1) == e || i->bucketIdx != (i + 1)->bucketIdx;
2421     hash = isLastInChain ? hash | 1 : hash & ~1;
2422     write32(values++, hash);
2423 
2424     if (i->bucketIdx == oldBucket)
2425       continue;
2426     // Write a hash bucket. Hash buckets contain indices in the following hash
2427     // value table.
2428     write32(buckets + i->bucketIdx,
2429             getPartition().dynSymTab->getSymbolIndex(i->sym));
2430     oldBucket = i->bucketIdx;
2431   }
2432 }
2433 
2434 // Add symbols to this symbol hash table. Note that this function
2435 // destructively sort a given vector -- which is needed because
2436 // GNU-style hash table places some sorting requirements.
2437 void GnuHashTableSection::addSymbols(SmallVectorImpl<SymbolTableEntry> &v) {
2438   // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2439   // its type correctly.
2440   auto mid =
2441       std::stable_partition(v.begin(), v.end(), [&](const SymbolTableEntry &s) {
2442         return !s.sym->isDefined() || s.sym->partition != partition;
2443       });
2444 
2445   // We chose load factor 4 for the on-disk hash table. For each hash
2446   // collision, the dynamic linker will compare a uint32_t hash value.
2447   // Since the integer comparison is quite fast, we believe we can
2448   // make the load factor even larger. 4 is just a conservative choice.
2449   //
2450   // Note that we don't want to create a zero-sized hash table because
2451   // Android loader as of 2018 doesn't like a .gnu.hash containing such
2452   // table. If that's the case, we create a hash table with one unused
2453   // dummy slot.
2454   nBuckets = std::max<size_t>((v.end() - mid) / 4, 1);
2455 
2456   if (mid == v.end())
2457     return;
2458 
2459   for (SymbolTableEntry &ent : llvm::make_range(mid, v.end())) {
2460     Symbol *b = ent.sym;
2461     uint32_t hash = hashGnu(b->getName());
2462     uint32_t bucketIdx = hash % nBuckets;
2463     symbols.push_back({b, ent.strTabOffset, hash, bucketIdx});
2464   }
2465 
2466   llvm::sort(symbols, [](const Entry &l, const Entry &r) {
2467     return std::tie(l.bucketIdx, l.strTabOffset) <
2468            std::tie(r.bucketIdx, r.strTabOffset);
2469   });
2470 
2471   v.erase(mid, v.end());
2472   for (const Entry &ent : symbols)
2473     v.push_back({ent.sym, ent.strTabOffset});
2474 }
2475 
2476 HashTableSection::HashTableSection()
2477     : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2478   this->entsize = 4;
2479 }
2480 
2481 void HashTableSection::finalizeContents() {
2482   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
2483 
2484   if (OutputSection *sec = symTab->getParent())
2485     getParent()->link = sec->sectionIndex;
2486 
2487   unsigned numEntries = 2;               // nbucket and nchain.
2488   numEntries += symTab->getNumSymbols(); // The chain entries.
2489 
2490   // Create as many buckets as there are symbols.
2491   numEntries += symTab->getNumSymbols();
2492   this->size = numEntries * 4;
2493 }
2494 
2495 void HashTableSection::writeTo(uint8_t *buf) {
2496   SymbolTableBaseSection *symTab = getPartition().dynSymTab.get();
2497   unsigned numSymbols = symTab->getNumSymbols();
2498 
2499   uint32_t *p = reinterpret_cast<uint32_t *>(buf);
2500   write32(p++, numSymbols); // nbucket
2501   write32(p++, numSymbols); // nchain
2502 
2503   uint32_t *buckets = p;
2504   uint32_t *chains = p + numSymbols;
2505 
2506   for (const SymbolTableEntry &s : symTab->getSymbols()) {
2507     Symbol *sym = s.sym;
2508     StringRef name = sym->getName();
2509     unsigned i = sym->dynsymIndex;
2510     uint32_t hash = hashSysV(name) % numSymbols;
2511     chains[i] = buckets[hash];
2512     write32(buckets + hash, i);
2513   }
2514 }
2515 
2516 PltSection::PltSection()
2517     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
2518       headerSize(target->pltHeaderSize) {
2519   // On PowerPC, this section contains lazy symbol resolvers.
2520   if (config->emachine == EM_PPC64) {
2521     name = ".glink";
2522     addralign = 4;
2523   }
2524 
2525   // On x86 when IBT is enabled, this section contains the second PLT (lazy
2526   // symbol resolvers).
2527   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
2528       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT))
2529     name = ".plt.sec";
2530 
2531   // The PLT needs to be writable on SPARC as the dynamic linker will
2532   // modify the instructions in the PLT entries.
2533   if (config->emachine == EM_SPARCV9)
2534     this->flags |= SHF_WRITE;
2535 }
2536 
2537 void PltSection::writeTo(uint8_t *buf) {
2538   // At beginning of PLT, we have code to call the dynamic
2539   // linker to resolve dynsyms at runtime. Write such code.
2540   target->writePltHeader(buf);
2541   size_t off = headerSize;
2542 
2543   for (const Symbol *sym : entries) {
2544     target->writePlt(buf + off, *sym, getVA() + off);
2545     off += target->pltEntrySize;
2546   }
2547 }
2548 
2549 void PltSection::addEntry(Symbol &sym) {
2550   assert(sym.auxIdx == symAux.size() - 1);
2551   symAux.back().pltIdx = entries.size();
2552   entries.push_back(&sym);
2553 }
2554 
2555 size_t PltSection::getSize() const {
2556   return headerSize + entries.size() * target->pltEntrySize;
2557 }
2558 
2559 bool PltSection::isNeeded() const {
2560   // For -z retpolineplt, .iplt needs the .plt header.
2561   return !entries.empty() || (config->zRetpolineplt && in.iplt->isNeeded());
2562 }
2563 
2564 // Used by ARM to add mapping symbols in the PLT section, which aid
2565 // disassembly.
2566 void PltSection::addSymbols() {
2567   target->addPltHeaderSymbols(*this);
2568 
2569   size_t off = headerSize;
2570   for (size_t i = 0; i < entries.size(); ++i) {
2571     target->addPltSymbols(*this, off);
2572     off += target->pltEntrySize;
2573   }
2574 }
2575 
2576 IpltSection::IpltSection()
2577     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".iplt") {
2578   if (config->emachine == EM_PPC || config->emachine == EM_PPC64) {
2579     name = ".glink";
2580     addralign = 4;
2581   }
2582 }
2583 
2584 void IpltSection::writeTo(uint8_t *buf) {
2585   uint32_t off = 0;
2586   for (const Symbol *sym : entries) {
2587     target->writeIplt(buf + off, *sym, getVA() + off);
2588     off += target->ipltEntrySize;
2589   }
2590 }
2591 
2592 size_t IpltSection::getSize() const {
2593   return entries.size() * target->ipltEntrySize;
2594 }
2595 
2596 void IpltSection::addEntry(Symbol &sym) {
2597   assert(sym.auxIdx == symAux.size() - 1);
2598   symAux.back().pltIdx = entries.size();
2599   entries.push_back(&sym);
2600 }
2601 
2602 // ARM uses mapping symbols to aid disassembly.
2603 void IpltSection::addSymbols() {
2604   size_t off = 0;
2605   for (size_t i = 0, e = entries.size(); i != e; ++i) {
2606     target->addPltSymbols(*this, off);
2607     off += target->pltEntrySize;
2608   }
2609 }
2610 
2611 PPC32GlinkSection::PPC32GlinkSection() {
2612   name = ".glink";
2613   addralign = 4;
2614 }
2615 
2616 void PPC32GlinkSection::writeTo(uint8_t *buf) {
2617   writePPC32GlinkSection(buf, entries.size());
2618 }
2619 
2620 size_t PPC32GlinkSection::getSize() const {
2621   return headerSize + entries.size() * target->pltEntrySize + footerSize;
2622 }
2623 
2624 // This is an x86-only extra PLT section and used only when a security
2625 // enhancement feature called CET is enabled. In this comment, I'll explain what
2626 // the feature is and why we have two PLT sections if CET is enabled.
2627 //
2628 // So, what does CET do? CET introduces a new restriction to indirect jump
2629 // instructions. CET works this way. Assume that CET is enabled. Then, if you
2630 // execute an indirect jump instruction, the processor verifies that a special
2631 // "landing pad" instruction (which is actually a repurposed NOP instruction and
2632 // now called "endbr32" or "endbr64") is at the jump target. If the jump target
2633 // does not start with that instruction, the processor raises an exception
2634 // instead of continuing executing code.
2635 //
2636 // If CET is enabled, the compiler emits endbr to all locations where indirect
2637 // jumps may jump to.
2638 //
2639 // This mechanism makes it extremely hard to transfer the control to a middle of
2640 // a function that is not supporsed to be a indirect jump target, preventing
2641 // certain types of attacks such as ROP or JOP.
2642 //
2643 // Note that the processors in the market as of 2019 don't actually support the
2644 // feature. Only the spec is available at the moment.
2645 //
2646 // Now, I'll explain why we have this extra PLT section for CET.
2647 //
2648 // Since you can indirectly jump to a PLT entry, we have to make PLT entries
2649 // start with endbr. The problem is there's no extra space for endbr (which is 4
2650 // bytes long), as the PLT entry is only 16 bytes long and all bytes are already
2651 // used.
2652 //
2653 // In order to deal with the issue, we split a PLT entry into two PLT entries.
2654 // Remember that each PLT entry contains code to jump to an address read from
2655 // .got.plt AND code to resolve a dynamic symbol lazily. With the 2-PLT scheme,
2656 // the former code is written to .plt.sec, and the latter code is written to
2657 // .plt.
2658 //
2659 // Lazy symbol resolution in the 2-PLT scheme works in the usual way, except
2660 // that the regular .plt is now called .plt.sec and .plt is repurposed to
2661 // contain only code for lazy symbol resolution.
2662 //
2663 // In other words, this is how the 2-PLT scheme works. Application code is
2664 // supposed to jump to .plt.sec to call an external function. Each .plt.sec
2665 // entry contains code to read an address from a corresponding .got.plt entry
2666 // and jump to that address. Addresses in .got.plt initially point to .plt, so
2667 // when an application calls an external function for the first time, the
2668 // control is transferred to a function that resolves a symbol name from
2669 // external shared object files. That function then rewrites a .got.plt entry
2670 // with a resolved address, so that the subsequent function calls directly jump
2671 // to a desired location from .plt.sec.
2672 //
2673 // There is an open question as to whether the 2-PLT scheme was desirable or
2674 // not. We could have simply extended the PLT entry size to 32-bytes to
2675 // accommodate endbr, and that scheme would have been much simpler than the
2676 // 2-PLT scheme. One reason to split PLT was, by doing that, we could keep hot
2677 // code (.plt.sec) from cold code (.plt). But as far as I know no one proved
2678 // that the optimization actually makes a difference.
2679 //
2680 // That said, the 2-PLT scheme is a part of the ABI, debuggers and other tools
2681 // depend on it, so we implement the ABI.
2682 IBTPltSection::IBTPltSection()
2683     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt") {}
2684 
2685 void IBTPltSection::writeTo(uint8_t *buf) {
2686   target->writeIBTPlt(buf, in.plt->getNumEntries());
2687 }
2688 
2689 size_t IBTPltSection::getSize() const {
2690   // 16 is the header size of .plt.
2691   return 16 + in.plt->getNumEntries() * target->pltEntrySize;
2692 }
2693 
2694 bool IBTPltSection::isNeeded() const { return in.plt->getNumEntries() > 0; }
2695 
2696 RelroPaddingSection::RelroPaddingSection()
2697     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1, ".relro_padding") {
2698 }
2699 
2700 // The string hash function for .gdb_index.
2701 static uint32_t computeGdbHash(StringRef s) {
2702   uint32_t h = 0;
2703   for (uint8_t c : s)
2704     h = h * 67 + toLower(c) - 113;
2705   return h;
2706 }
2707 
2708 GdbIndexSection::GdbIndexSection()
2709     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2710 
2711 // Returns the desired size of an on-disk hash table for a .gdb_index section.
2712 // There's a tradeoff between size and collision rate. We aim 75% utilization.
2713 size_t GdbIndexSection::computeSymtabSize() const {
2714   return std::max<size_t>(NextPowerOf2(symbols.size() * 4 / 3), 1024);
2715 }
2716 
2717 static SmallVector<GdbIndexSection::CuEntry, 0>
2718 readCuList(DWARFContext &dwarf) {
2719   SmallVector<GdbIndexSection::CuEntry, 0> ret;
2720   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
2721     ret.push_back({cu->getOffset(), cu->getLength() + 4});
2722   return ret;
2723 }
2724 
2725 static SmallVector<GdbIndexSection::AddressEntry, 0>
2726 readAddressAreas(DWARFContext &dwarf, InputSection *sec) {
2727   SmallVector<GdbIndexSection::AddressEntry, 0> ret;
2728 
2729   uint32_t cuIdx = 0;
2730   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
2731     if (Error e = cu->tryExtractDIEsIfNeeded(false)) {
2732       warn(toString(sec) + ": " + toString(std::move(e)));
2733       return {};
2734     }
2735     Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
2736     if (!ranges) {
2737       warn(toString(sec) + ": " + toString(ranges.takeError()));
2738       return {};
2739     }
2740 
2741     ArrayRef<InputSectionBase *> sections = sec->file->getSections();
2742     for (DWARFAddressRange &r : *ranges) {
2743       if (r.SectionIndex == -1ULL)
2744         continue;
2745       // Range list with zero size has no effect.
2746       InputSectionBase *s = sections[r.SectionIndex];
2747       if (s && s != &InputSection::discarded && s->isLive())
2748         if (r.LowPC != r.HighPC)
2749           ret.push_back({cast<InputSection>(s), r.LowPC, r.HighPC, cuIdx});
2750     }
2751     ++cuIdx;
2752   }
2753 
2754   return ret;
2755 }
2756 
2757 template <class ELFT>
2758 static SmallVector<GdbIndexSection::NameAttrEntry, 0>
2759 readPubNamesAndTypes(const LLDDwarfObj<ELFT> &obj,
2760                      const SmallVectorImpl<GdbIndexSection::CuEntry> &cus) {
2761   const LLDDWARFSection &pubNames = obj.getGnuPubnamesSection();
2762   const LLDDWARFSection &pubTypes = obj.getGnuPubtypesSection();
2763 
2764   SmallVector<GdbIndexSection::NameAttrEntry, 0> ret;
2765   for (const LLDDWARFSection *pub : {&pubNames, &pubTypes}) {
2766     DWARFDataExtractor data(obj, *pub, config->isLE, config->wordsize);
2767     DWARFDebugPubTable table;
2768     table.extract(data, /*GnuStyle=*/true, [&](Error e) {
2769       warn(toString(pub->sec) + ": " + toString(std::move(e)));
2770     });
2771     for (const DWARFDebugPubTable::Set &set : table.getData()) {
2772       // The value written into the constant pool is kind << 24 | cuIndex. As we
2773       // don't know how many compilation units precede this object to compute
2774       // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
2775       // the number of preceding compilation units later.
2776       uint32_t i = llvm::partition_point(cus,
2777                                          [&](GdbIndexSection::CuEntry cu) {
2778                                            return cu.cuOffset < set.Offset;
2779                                          }) -
2780                    cus.begin();
2781       for (const DWARFDebugPubTable::Entry &ent : set.Entries)
2782         ret.push_back({{ent.Name, computeGdbHash(ent.Name)},
2783                        (ent.Descriptor.toBits() << 24) | i});
2784     }
2785   }
2786   return ret;
2787 }
2788 
2789 // Create a list of symbols from a given list of symbol names and types
2790 // by uniquifying them by name.
2791 static std::pair<SmallVector<GdbIndexSection::GdbSymbol, 0>, size_t>
2792 createSymbols(
2793     ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry, 0>> nameAttrs,
2794     const SmallVector<GdbIndexSection::GdbChunk, 0> &chunks) {
2795   using GdbSymbol = GdbIndexSection::GdbSymbol;
2796   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
2797 
2798   // For each chunk, compute the number of compilation units preceding it.
2799   uint32_t cuIdx = 0;
2800   std::unique_ptr<uint32_t[]> cuIdxs(new uint32_t[chunks.size()]);
2801   for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
2802     cuIdxs[i] = cuIdx;
2803     cuIdx += chunks[i].compilationUnits.size();
2804   }
2805 
2806   // The number of symbols we will handle in this function is of the order
2807   // of millions for very large executables, so we use multi-threading to
2808   // speed it up.
2809   constexpr size_t numShards = 32;
2810   const size_t concurrency =
2811       llvm::bit_floor(std::min<size_t>(config->threadCount, numShards));
2812 
2813   // A sharded map to uniquify symbols by name.
2814   auto map =
2815       std::make_unique<DenseMap<CachedHashStringRef, size_t>[]>(numShards);
2816   size_t shift = 32 - llvm::countr_zero(numShards);
2817 
2818   // Instantiate GdbSymbols while uniqufying them by name.
2819   auto symbols = std::make_unique<SmallVector<GdbSymbol, 0>[]>(numShards);
2820 
2821   parallelFor(0, concurrency, [&](size_t threadId) {
2822     uint32_t i = 0;
2823     for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
2824       for (const NameAttrEntry &ent : entries) {
2825         size_t shardId = ent.name.hash() >> shift;
2826         if ((shardId & (concurrency - 1)) != threadId)
2827           continue;
2828 
2829         uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
2830         size_t &idx = map[shardId][ent.name];
2831         if (idx) {
2832           symbols[shardId][idx - 1].cuVector.push_back(v);
2833           continue;
2834         }
2835 
2836         idx = symbols[shardId].size() + 1;
2837         symbols[shardId].push_back({ent.name, {v}, 0, 0});
2838       }
2839       ++i;
2840     }
2841   });
2842 
2843   size_t numSymbols = 0;
2844   for (ArrayRef<GdbSymbol> v : ArrayRef(symbols.get(), numShards))
2845     numSymbols += v.size();
2846 
2847   // The return type is a flattened vector, so we'll copy each vector
2848   // contents to Ret.
2849   SmallVector<GdbSymbol, 0> ret;
2850   ret.reserve(numSymbols);
2851   for (SmallVector<GdbSymbol, 0> &vec :
2852        MutableArrayRef(symbols.get(), numShards))
2853     for (GdbSymbol &sym : vec)
2854       ret.push_back(std::move(sym));
2855 
2856   // CU vectors and symbol names are adjacent in the output file.
2857   // We can compute their offsets in the output file now.
2858   size_t off = 0;
2859   for (GdbSymbol &sym : ret) {
2860     sym.cuVectorOff = off;
2861     off += (sym.cuVector.size() + 1) * 4;
2862   }
2863   for (GdbSymbol &sym : ret) {
2864     sym.nameOff = off;
2865     off += sym.name.size() + 1;
2866   }
2867   // If off overflows, the last symbol's nameOff likely overflows.
2868   if (!isUInt<32>(off))
2869     errorOrWarn("--gdb-index: constant pool size (" + Twine(off) +
2870                 ") exceeds UINT32_MAX");
2871 
2872   return {ret, off};
2873 }
2874 
2875 // Returns a newly-created .gdb_index section.
2876 template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
2877   llvm::TimeTraceScope timeScope("Create gdb index");
2878 
2879   // Collect InputFiles with .debug_info. See the comment in
2880   // LLDDwarfObj<ELFT>::LLDDwarfObj. If we do lightweight parsing in the future,
2881   // note that isec->data() may uncompress the full content, which should be
2882   // parallelized.
2883   SetVector<InputFile *> files;
2884   for (InputSectionBase *s : ctx.inputSections) {
2885     InputSection *isec = dyn_cast<InputSection>(s);
2886     if (!isec)
2887       continue;
2888     // .debug_gnu_pub{names,types} are useless in executables.
2889     // They are present in input object files solely for creating
2890     // a .gdb_index. So we can remove them from the output.
2891     if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
2892       s->markDead();
2893     else if (isec->name == ".debug_info")
2894       files.insert(isec->file);
2895   }
2896   // Drop .rel[a].debug_gnu_pub{names,types} for --emit-relocs.
2897   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
2898     if (auto *isec = dyn_cast<InputSection>(s))
2899       if (InputSectionBase *rel = isec->getRelocatedSection())
2900         return !rel->isLive();
2901     return !s->isLive();
2902   });
2903 
2904   SmallVector<GdbChunk, 0> chunks(files.size());
2905   SmallVector<SmallVector<NameAttrEntry, 0>, 0> nameAttrs(files.size());
2906 
2907   parallelFor(0, files.size(), [&](size_t i) {
2908     // To keep memory usage low, we don't want to keep cached DWARFContext, so
2909     // avoid getDwarf() here.
2910     ObjFile<ELFT> *file = cast<ObjFile<ELFT>>(files[i]);
2911     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
2912     auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
2913 
2914     // If the are multiple compile units .debug_info (very rare ld -r --unique),
2915     // this only picks the last one. Other address ranges are lost.
2916     chunks[i].sec = dobj.getInfoSection();
2917     chunks[i].compilationUnits = readCuList(dwarf);
2918     chunks[i].addressAreas = readAddressAreas(dwarf, chunks[i].sec);
2919     nameAttrs[i] = readPubNamesAndTypes<ELFT>(dobj, chunks[i].compilationUnits);
2920   });
2921 
2922   auto *ret = make<GdbIndexSection>();
2923   ret->chunks = std::move(chunks);
2924   std::tie(ret->symbols, ret->size) = createSymbols(nameAttrs, ret->chunks);
2925 
2926   // Count the areas other than the constant pool.
2927   ret->size += sizeof(GdbIndexHeader) + ret->computeSymtabSize() * 8;
2928   for (GdbChunk &chunk : ret->chunks)
2929     ret->size +=
2930         chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
2931 
2932   return ret;
2933 }
2934 
2935 void GdbIndexSection::writeTo(uint8_t *buf) {
2936   // Write the header.
2937   auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
2938   uint8_t *start = buf;
2939   hdr->version = 7;
2940   buf += sizeof(*hdr);
2941 
2942   // Write the CU list.
2943   hdr->cuListOff = buf - start;
2944   for (GdbChunk &chunk : chunks) {
2945     for (CuEntry &cu : chunk.compilationUnits) {
2946       write64le(buf, chunk.sec->outSecOff + cu.cuOffset);
2947       write64le(buf + 8, cu.cuLength);
2948       buf += 16;
2949     }
2950   }
2951 
2952   // Write the address area.
2953   hdr->cuTypesOff = buf - start;
2954   hdr->addressAreaOff = buf - start;
2955   uint32_t cuOff = 0;
2956   for (GdbChunk &chunk : chunks) {
2957     for (AddressEntry &e : chunk.addressAreas) {
2958       // In the case of ICF there may be duplicate address range entries.
2959       const uint64_t baseAddr = e.section->repl->getVA(0);
2960       write64le(buf, baseAddr + e.lowAddress);
2961       write64le(buf + 8, baseAddr + e.highAddress);
2962       write32le(buf + 16, e.cuIndex + cuOff);
2963       buf += 20;
2964     }
2965     cuOff += chunk.compilationUnits.size();
2966   }
2967 
2968   // Write the on-disk open-addressing hash table containing symbols.
2969   hdr->symtabOff = buf - start;
2970   size_t symtabSize = computeSymtabSize();
2971   uint32_t mask = symtabSize - 1;
2972 
2973   for (GdbSymbol &sym : symbols) {
2974     uint32_t h = sym.name.hash();
2975     uint32_t i = h & mask;
2976     uint32_t step = ((h * 17) & mask) | 1;
2977 
2978     while (read32le(buf + i * 8))
2979       i = (i + step) & mask;
2980 
2981     write32le(buf + i * 8, sym.nameOff);
2982     write32le(buf + i * 8 + 4, sym.cuVectorOff);
2983   }
2984 
2985   buf += symtabSize * 8;
2986 
2987   // Write the string pool.
2988   hdr->constantPoolOff = buf - start;
2989   parallelForEach(symbols, [&](GdbSymbol &sym) {
2990     memcpy(buf + sym.nameOff, sym.name.data(), sym.name.size());
2991   });
2992 
2993   // Write the CU vectors.
2994   for (GdbSymbol &sym : symbols) {
2995     write32le(buf, sym.cuVector.size());
2996     buf += 4;
2997     for (uint32_t val : sym.cuVector) {
2998       write32le(buf, val);
2999       buf += 4;
3000     }
3001   }
3002 }
3003 
3004 bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
3005 
3006 EhFrameHeader::EhFrameHeader()
3007     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
3008 
3009 void EhFrameHeader::writeTo(uint8_t *buf) {
3010   // Unlike most sections, the EhFrameHeader section is written while writing
3011   // another section, namely EhFrameSection, which calls the write() function
3012   // below from its writeTo() function. This is necessary because the contents
3013   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
3014   // don't know which order the sections will be written in.
3015 }
3016 
3017 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
3018 // Each entry of the search table consists of two values,
3019 // the starting PC from where FDEs covers, and the FDE's address.
3020 // It is sorted by PC.
3021 void EhFrameHeader::write() {
3022   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
3023   using FdeData = EhFrameSection::FdeData;
3024   SmallVector<FdeData, 0> fdes = getPartition().ehFrame->getFdeData();
3025 
3026   buf[0] = 1;
3027   buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
3028   buf[2] = DW_EH_PE_udata4;
3029   buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
3030   write32(buf + 4,
3031           getPartition().ehFrame->getParent()->addr - this->getVA() - 4);
3032   write32(buf + 8, fdes.size());
3033   buf += 12;
3034 
3035   for (FdeData &fde : fdes) {
3036     write32(buf, fde.pcRel);
3037     write32(buf + 4, fde.fdeVARel);
3038     buf += 8;
3039   }
3040 }
3041 
3042 size_t EhFrameHeader::getSize() const {
3043   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
3044   return 12 + getPartition().ehFrame->numFdes * 8;
3045 }
3046 
3047 bool EhFrameHeader::isNeeded() const {
3048   return isLive() && getPartition().ehFrame->isNeeded();
3049 }
3050 
3051 VersionDefinitionSection::VersionDefinitionSection()
3052     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
3053                        ".gnu.version_d") {}
3054 
3055 StringRef VersionDefinitionSection::getFileDefName() {
3056   if (!getPartition().name.empty())
3057     return getPartition().name;
3058   if (!config->soName.empty())
3059     return config->soName;
3060   return config->outputFile;
3061 }
3062 
3063 void VersionDefinitionSection::finalizeContents() {
3064   fileDefNameOff = getPartition().dynStrTab->addString(getFileDefName());
3065   for (const VersionDefinition &v : namedVersionDefs())
3066     verDefNameOffs.push_back(getPartition().dynStrTab->addString(v.name));
3067 
3068   if (OutputSection *sec = getPartition().dynStrTab->getParent())
3069     getParent()->link = sec->sectionIndex;
3070 
3071   // sh_info should be set to the number of definitions. This fact is missed in
3072   // documentation, but confirmed by binutils community:
3073   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
3074   getParent()->info = getVerDefNum();
3075 }
3076 
3077 void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
3078                                         StringRef name, size_t nameOff) {
3079   uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
3080 
3081   // Write a verdef.
3082   write16(buf, 1);                  // vd_version
3083   write16(buf + 2, flags);          // vd_flags
3084   write16(buf + 4, index);          // vd_ndx
3085   write16(buf + 6, 1);              // vd_cnt
3086   write32(buf + 8, hashSysV(name)); // vd_hash
3087   write32(buf + 12, 20);            // vd_aux
3088   write32(buf + 16, 28);            // vd_next
3089 
3090   // Write a veraux.
3091   write32(buf + 20, nameOff); // vda_name
3092   write32(buf + 24, 0);       // vda_next
3093 }
3094 
3095 void VersionDefinitionSection::writeTo(uint8_t *buf) {
3096   writeOne(buf, 1, getFileDefName(), fileDefNameOff);
3097 
3098   auto nameOffIt = verDefNameOffs.begin();
3099   for (const VersionDefinition &v : namedVersionDefs()) {
3100     buf += EntrySize;
3101     writeOne(buf, v.id, v.name, *nameOffIt++);
3102   }
3103 
3104   // Need to terminate the last version definition.
3105   write32(buf + 16, 0); // vd_next
3106 }
3107 
3108 size_t VersionDefinitionSection::getSize() const {
3109   return EntrySize * getVerDefNum();
3110 }
3111 
3112 // .gnu.version is a table where each entry is 2 byte long.
3113 VersionTableSection::VersionTableSection()
3114     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
3115                        ".gnu.version") {
3116   this->entsize = 2;
3117 }
3118 
3119 void VersionTableSection::finalizeContents() {
3120   // At the moment of june 2016 GNU docs does not mention that sh_link field
3121   // should be set, but Sun docs do. Also readelf relies on this field.
3122   getParent()->link = getPartition().dynSymTab->getParent()->sectionIndex;
3123 }
3124 
3125 size_t VersionTableSection::getSize() const {
3126   return (getPartition().dynSymTab->getSymbols().size() + 1) * 2;
3127 }
3128 
3129 void VersionTableSection::writeTo(uint8_t *buf) {
3130   buf += 2;
3131   for (const SymbolTableEntry &s : getPartition().dynSymTab->getSymbols()) {
3132     // For an unextracted lazy symbol (undefined weak), it must have been
3133     // converted to Undefined and have VER_NDX_GLOBAL version here.
3134     assert(!s.sym->isLazy());
3135     write16(buf, s.sym->versionId);
3136     buf += 2;
3137   }
3138 }
3139 
3140 bool VersionTableSection::isNeeded() const {
3141   return isLive() &&
3142          (getPartition().verDef || getPartition().verNeed->isNeeded());
3143 }
3144 
3145 void elf::addVerneed(Symbol *ss) {
3146   auto &file = cast<SharedFile>(*ss->file);
3147   if (ss->versionId == VER_NDX_GLOBAL)
3148     return;
3149 
3150   if (file.vernauxs.empty())
3151     file.vernauxs.resize(file.verdefs.size());
3152 
3153   // Select a version identifier for the vernaux data structure, if we haven't
3154   // already allocated one. The verdef identifiers cover the range
3155   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
3156   // getVerDefNum()+1.
3157   if (file.vernauxs[ss->versionId] == 0)
3158     file.vernauxs[ss->versionId] = ++SharedFile::vernauxNum + getVerDefNum();
3159 
3160   ss->versionId = file.vernauxs[ss->versionId];
3161 }
3162 
3163 template <class ELFT>
3164 VersionNeedSection<ELFT>::VersionNeedSection()
3165     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
3166                        ".gnu.version_r") {}
3167 
3168 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
3169   for (SharedFile *f : ctx.sharedFiles) {
3170     if (f->vernauxs.empty())
3171       continue;
3172     verneeds.emplace_back();
3173     Verneed &vn = verneeds.back();
3174     vn.nameStrTab = getPartition().dynStrTab->addString(f->soName);
3175     bool isLibc = config->relrGlibc && f->soName.starts_with("libc.so.");
3176     bool isGlibc2 = false;
3177     for (unsigned i = 0; i != f->vernauxs.size(); ++i) {
3178       if (f->vernauxs[i] == 0)
3179         continue;
3180       auto *verdef =
3181           reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
3182       StringRef ver(f->getStringTable().data() + verdef->getAux()->vda_name);
3183       if (isLibc && ver.starts_with("GLIBC_2."))
3184         isGlibc2 = true;
3185       vn.vernauxs.push_back({verdef->vd_hash, f->vernauxs[i],
3186                              getPartition().dynStrTab->addString(ver)});
3187     }
3188     if (isGlibc2) {
3189       const char *ver = "GLIBC_ABI_DT_RELR";
3190       vn.vernauxs.push_back({hashSysV(ver),
3191                              ++SharedFile::vernauxNum + getVerDefNum(),
3192                              getPartition().dynStrTab->addString(ver)});
3193     }
3194   }
3195 
3196   if (OutputSection *sec = getPartition().dynStrTab->getParent())
3197     getParent()->link = sec->sectionIndex;
3198   getParent()->info = verneeds.size();
3199 }
3200 
3201 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
3202   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
3203   auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
3204   auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
3205 
3206   for (auto &vn : verneeds) {
3207     // Create an Elf_Verneed for this DSO.
3208     verneed->vn_version = 1;
3209     verneed->vn_cnt = vn.vernauxs.size();
3210     verneed->vn_file = vn.nameStrTab;
3211     verneed->vn_aux =
3212         reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
3213     verneed->vn_next = sizeof(Elf_Verneed);
3214     ++verneed;
3215 
3216     // Create the Elf_Vernauxs for this Elf_Verneed.
3217     for (auto &vna : vn.vernauxs) {
3218       vernaux->vna_hash = vna.hash;
3219       vernaux->vna_flags = 0;
3220       vernaux->vna_other = vna.verneedIndex;
3221       vernaux->vna_name = vna.nameStrTab;
3222       vernaux->vna_next = sizeof(Elf_Vernaux);
3223       ++vernaux;
3224     }
3225 
3226     vernaux[-1].vna_next = 0;
3227   }
3228   verneed[-1].vn_next = 0;
3229 }
3230 
3231 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
3232   return verneeds.size() * sizeof(Elf_Verneed) +
3233          SharedFile::vernauxNum * sizeof(Elf_Vernaux);
3234 }
3235 
3236 template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
3237   return isLive() && SharedFile::vernauxNum != 0;
3238 }
3239 
3240 void MergeSyntheticSection::addSection(MergeInputSection *ms) {
3241   ms->parent = this;
3242   sections.push_back(ms);
3243   assert(addralign == ms->addralign || !(ms->flags & SHF_STRINGS));
3244   addralign = std::max(addralign, ms->addralign);
3245 }
3246 
3247 MergeTailSection::MergeTailSection(StringRef name, uint32_t type,
3248                                    uint64_t flags, uint32_t alignment)
3249     : MergeSyntheticSection(name, type, flags, alignment),
3250       builder(StringTableBuilder::RAW, llvm::Align(alignment)) {}
3251 
3252 size_t MergeTailSection::getSize() const { return builder.getSize(); }
3253 
3254 void MergeTailSection::writeTo(uint8_t *buf) { builder.write(buf); }
3255 
3256 void MergeTailSection::finalizeContents() {
3257   // Add all string pieces to the string table builder to create section
3258   // contents.
3259   for (MergeInputSection *sec : sections)
3260     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3261       if (sec->pieces[i].live)
3262         builder.add(sec->getData(i));
3263 
3264   // Fix the string table content. After this, the contents will never change.
3265   builder.finalize();
3266 
3267   // finalize() fixed tail-optimized strings, so we can now get
3268   // offsets of strings. Get an offset for each string and save it
3269   // to a corresponding SectionPiece for easy access.
3270   for (MergeInputSection *sec : sections)
3271     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3272       if (sec->pieces[i].live)
3273         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
3274 }
3275 
3276 void MergeNoTailSection::writeTo(uint8_t *buf) {
3277   parallelFor(0, numShards,
3278               [&](size_t i) { shards[i].write(buf + shardOffsets[i]); });
3279 }
3280 
3281 // This function is very hot (i.e. it can take several seconds to finish)
3282 // because sometimes the number of inputs is in an order of magnitude of
3283 // millions. So, we use multi-threading.
3284 //
3285 // For any strings S and T, we know S is not mergeable with T if S's hash
3286 // value is different from T's. If that's the case, we can safely put S and
3287 // T into different string builders without worrying about merge misses.
3288 // We do it in parallel.
3289 void MergeNoTailSection::finalizeContents() {
3290   // Initializes string table builders.
3291   for (size_t i = 0; i < numShards; ++i)
3292     shards.emplace_back(StringTableBuilder::RAW, llvm::Align(addralign));
3293 
3294   // Concurrency level. Must be a power of 2 to avoid expensive modulo
3295   // operations in the following tight loop.
3296   const size_t concurrency =
3297       llvm::bit_floor(std::min<size_t>(config->threadCount, numShards));
3298 
3299   // Add section pieces to the builders.
3300   parallelFor(0, concurrency, [&](size_t threadId) {
3301     for (MergeInputSection *sec : sections) {
3302       for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
3303         if (!sec->pieces[i].live)
3304           continue;
3305         size_t shardId = getShardId(sec->pieces[i].hash);
3306         if ((shardId & (concurrency - 1)) == threadId)
3307           sec->pieces[i].outputOff = shards[shardId].add(sec->getData(i));
3308       }
3309     }
3310   });
3311 
3312   // Compute an in-section offset for each shard.
3313   size_t off = 0;
3314   for (size_t i = 0; i < numShards; ++i) {
3315     shards[i].finalizeInOrder();
3316     if (shards[i].getSize() > 0)
3317       off = alignToPowerOf2(off, addralign);
3318     shardOffsets[i] = off;
3319     off += shards[i].getSize();
3320   }
3321   size = off;
3322 
3323   // So far, section pieces have offsets from beginning of shards, but
3324   // we want offsets from beginning of the whole section. Fix them.
3325   parallelForEach(sections, [&](MergeInputSection *sec) {
3326     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3327       if (sec->pieces[i].live)
3328         sec->pieces[i].outputOff +=
3329             shardOffsets[getShardId(sec->pieces[i].hash)];
3330   });
3331 }
3332 
3333 template <class ELFT> void elf::splitSections() {
3334   llvm::TimeTraceScope timeScope("Split sections");
3335   // splitIntoPieces needs to be called on each MergeInputSection
3336   // before calling finalizeContents().
3337   parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
3338     for (InputSectionBase *sec : file->getSections()) {
3339       if (!sec)
3340         continue;
3341       if (auto *s = dyn_cast<MergeInputSection>(sec))
3342         s->splitIntoPieces();
3343       else if (auto *eh = dyn_cast<EhInputSection>(sec))
3344         eh->split<ELFT>();
3345     }
3346   });
3347 }
3348 
3349 void elf::combineEhSections() {
3350   llvm::TimeTraceScope timeScope("Combine EH sections");
3351   for (EhInputSection *sec : ctx.ehInputSections) {
3352     EhFrameSection &eh = *sec->getPartition().ehFrame;
3353     sec->parent = &eh;
3354     eh.addralign = std::max(eh.addralign, sec->addralign);
3355     eh.sections.push_back(sec);
3356     llvm::append_range(eh.dependentSections, sec->dependentSections);
3357   }
3358 
3359   if (!mainPart->armExidx)
3360     return;
3361   llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3362     // Ignore dead sections and the partition end marker (.part.end),
3363     // whose partition number is out of bounds.
3364     if (!s->isLive() || s->partition == 255)
3365       return false;
3366     Partition &part = s->getPartition();
3367     return s->kind() == SectionBase::Regular && part.armExidx &&
3368            part.armExidx->addSection(cast<InputSection>(s));
3369   });
3370 }
3371 
3372 MipsRldMapSection::MipsRldMapSection()
3373     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
3374                        ".rld_map") {}
3375 
3376 ARMExidxSyntheticSection::ARMExidxSyntheticSection()
3377     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
3378                        config->wordsize, ".ARM.exidx") {}
3379 
3380 static InputSection *findExidxSection(InputSection *isec) {
3381   for (InputSection *d : isec->dependentSections)
3382     if (d->type == SHT_ARM_EXIDX && d->isLive())
3383       return d;
3384   return nullptr;
3385 }
3386 
3387 static bool isValidExidxSectionDep(InputSection *isec) {
3388   return (isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
3389          isec->getSize() > 0;
3390 }
3391 
3392 bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
3393   if (isec->type == SHT_ARM_EXIDX) {
3394     if (InputSection *dep = isec->getLinkOrderDep())
3395       if (isValidExidxSectionDep(dep)) {
3396         exidxSections.push_back(isec);
3397         // Every exidxSection is 8 bytes, we need an estimate of
3398         // size before assignAddresses can be called. Final size
3399         // will only be known after finalize is called.
3400         size += 8;
3401       }
3402     return true;
3403   }
3404 
3405   if (isValidExidxSectionDep(isec)) {
3406     executableSections.push_back(isec);
3407     return false;
3408   }
3409 
3410   // FIXME: we do not output a relocation section when --emit-relocs is used
3411   // as we do not have relocation sections for linker generated table entries
3412   // and we would have to erase at a late stage relocations from merged entries.
3413   // Given that exception tables are already position independent and a binary
3414   // analyzer could derive the relocations we choose to erase the relocations.
3415   if (config->emitRelocs && isec->type == SHT_REL)
3416     if (InputSectionBase *ex = isec->getRelocatedSection())
3417       if (isa<InputSection>(ex) && ex->type == SHT_ARM_EXIDX)
3418         return true;
3419 
3420   return false;
3421 }
3422 
3423 // References to .ARM.Extab Sections have bit 31 clear and are not the
3424 // special EXIDX_CANTUNWIND bit-pattern.
3425 static bool isExtabRef(uint32_t unwind) {
3426   return (unwind & 0x80000000) == 0 && unwind != 0x1;
3427 }
3428 
3429 // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
3430 // section Prev, where Cur follows Prev in the table. This can be done if the
3431 // unwinding instructions in Cur are identical to Prev. Linker generated
3432 // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
3433 // InputSection.
3434 static bool isDuplicateArmExidxSec(InputSection *prev, InputSection *cur) {
3435   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
3436   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
3437   uint32_t prevUnwind = 1;
3438   if (prev)
3439     prevUnwind = read32(prev->content().data() + prev->content().size() - 4);
3440   if (isExtabRef(prevUnwind))
3441     return false;
3442 
3443   // We consider the unwind instructions of an .ARM.exidx table entry
3444   // a duplicate if the previous unwind instructions if:
3445   // - Both are the special EXIDX_CANTUNWIND.
3446   // - Both are the same inline unwind instructions.
3447   // We do not attempt to follow and check links into .ARM.extab tables as
3448   // consecutive identical entries are rare and the effort to check that they
3449   // are identical is high.
3450 
3451   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
3452   if (cur == nullptr)
3453     return prevUnwind == 1;
3454 
3455   for (uint32_t offset = 4; offset < (uint32_t)cur->content().size(); offset +=8) {
3456     uint32_t curUnwind = read32(cur->content().data() + offset);
3457     if (isExtabRef(curUnwind) || curUnwind != prevUnwind)
3458       return false;
3459   }
3460   // All table entries in this .ARM.exidx Section can be merged into the
3461   // previous Section.
3462   return true;
3463 }
3464 
3465 // The .ARM.exidx table must be sorted in ascending order of the address of the
3466 // functions the table describes. std::optionally duplicate adjacent table
3467 // entries can be removed. At the end of the function the executableSections
3468 // must be sorted in ascending order of address, Sentinel is set to the
3469 // InputSection with the highest address and any InputSections that have
3470 // mergeable .ARM.exidx table entries are removed from it.
3471 void ARMExidxSyntheticSection::finalizeContents() {
3472   // The executableSections and exidxSections that we use to derive the final
3473   // contents of this SyntheticSection are populated before
3474   // processSectionCommands() and ICF. A /DISCARD/ entry in SECTIONS command or
3475   // ICF may remove executable InputSections and their dependent .ARM.exidx
3476   // section that we recorded earlier.
3477   auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
3478   llvm::erase_if(exidxSections, isDiscarded);
3479   // We need to remove discarded InputSections and InputSections without
3480   // .ARM.exidx sections that if we generated the .ARM.exidx it would be out
3481   // of range.
3482   auto isDiscardedOrOutOfRange = [this](InputSection *isec) {
3483     if (!isec->isLive())
3484       return true;
3485     if (findExidxSection(isec))
3486       return false;
3487     int64_t off = static_cast<int64_t>(isec->getVA() - getVA());
3488     return off != llvm::SignExtend64(off, 31);
3489   };
3490   llvm::erase_if(executableSections, isDiscardedOrOutOfRange);
3491 
3492   // Sort the executable sections that may or may not have associated
3493   // .ARM.exidx sections by order of ascending address. This requires the
3494   // relative positions of InputSections and OutputSections to be known.
3495   auto compareByFilePosition = [](const InputSection *a,
3496                                   const InputSection *b) {
3497     OutputSection *aOut = a->getParent();
3498     OutputSection *bOut = b->getParent();
3499 
3500     if (aOut != bOut)
3501       return aOut->addr < bOut->addr;
3502     return a->outSecOff < b->outSecOff;
3503   };
3504   llvm::stable_sort(executableSections, compareByFilePosition);
3505   sentinel = executableSections.back();
3506   // std::optionally merge adjacent duplicate entries.
3507   if (config->mergeArmExidx) {
3508     SmallVector<InputSection *, 0> selectedSections;
3509     selectedSections.reserve(executableSections.size());
3510     selectedSections.push_back(executableSections[0]);
3511     size_t prev = 0;
3512     for (size_t i = 1; i < executableSections.size(); ++i) {
3513       InputSection *ex1 = findExidxSection(executableSections[prev]);
3514       InputSection *ex2 = findExidxSection(executableSections[i]);
3515       if (!isDuplicateArmExidxSec(ex1, ex2)) {
3516         selectedSections.push_back(executableSections[i]);
3517         prev = i;
3518       }
3519     }
3520     executableSections = std::move(selectedSections);
3521   }
3522   // offset is within the SyntheticSection.
3523   size_t offset = 0;
3524   size = 0;
3525   for (InputSection *isec : executableSections) {
3526     if (InputSection *d = findExidxSection(isec)) {
3527       d->outSecOff = offset;
3528       d->parent = getParent();
3529       offset += d->getSize();
3530     } else {
3531       offset += 8;
3532     }
3533   }
3534   // Size includes Sentinel.
3535   size = offset + 8;
3536 }
3537 
3538 InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
3539   return executableSections.front();
3540 }
3541 
3542 // To write the .ARM.exidx table from the ExecutableSections we have three cases
3543 // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
3544 //     We write the .ARM.exidx section contents and apply its relocations.
3545 // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
3546 //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
3547 //     start of the InputSection as the purpose of the linker generated
3548 //     section is to terminate the address range of the previous entry.
3549 // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
3550 //     the table to terminate the address range of the final entry.
3551 void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
3552 
3553   // A linker generated CANTUNWIND entry is made up of two words:
3554   // 0x0 with R_ARM_PREL31 relocation to target.
3555   // 0x1 with EXIDX_CANTUNWIND.
3556   uint64_t offset = 0;
3557   for (InputSection *isec : executableSections) {
3558     assert(isec->getParent() != nullptr);
3559     if (InputSection *d = findExidxSection(isec)) {
3560       for (int dataOffset = 0; dataOffset != (int)d->content().size();
3561            dataOffset += 4)
3562         write32(buf + offset + dataOffset,
3563                 read32(d->content().data() + dataOffset));
3564       // Recalculate outSecOff as finalizeAddressDependentContent()
3565       // may have altered syntheticSection outSecOff.
3566       d->outSecOff = offset + outSecOff;
3567       target->relocateAlloc(*d, buf + offset);
3568       offset += d->getSize();
3569     } else {
3570       // A Linker generated CANTUNWIND section.
3571       write32(buf + offset + 0, 0x0);
3572       write32(buf + offset + 4, 0x1);
3573       uint64_t s = isec->getVA();
3574       uint64_t p = getVA() + offset;
3575       target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3576       offset += 8;
3577     }
3578   }
3579   // Write Sentinel CANTUNWIND entry.
3580   write32(buf + offset + 0, 0x0);
3581   write32(buf + offset + 4, 0x1);
3582   uint64_t s = sentinel->getVA(sentinel->getSize());
3583   uint64_t p = getVA() + offset;
3584   target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3585   assert(size == offset + 8);
3586 }
3587 
3588 bool ARMExidxSyntheticSection::isNeeded() const {
3589   return llvm::any_of(exidxSections,
3590                       [](InputSection *isec) { return isec->isLive(); });
3591 }
3592 
3593 ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
3594     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
3595                        config->emachine == EM_PPC64 ? 16 : 4, ".text.thunk") {
3596   this->parent = os;
3597   this->outSecOff = off;
3598 }
3599 
3600 size_t ThunkSection::getSize() const {
3601   if (roundUpSizeForErrata)
3602     return alignTo(size, 4096);
3603   return size;
3604 }
3605 
3606 void ThunkSection::addThunk(Thunk *t) {
3607   thunks.push_back(t);
3608   t->addSymbols(*this);
3609 }
3610 
3611 void ThunkSection::writeTo(uint8_t *buf) {
3612   for (Thunk *t : thunks)
3613     t->writeTo(buf + t->offset);
3614 }
3615 
3616 InputSection *ThunkSection::getTargetInputSection() const {
3617   if (thunks.empty())
3618     return nullptr;
3619   const Thunk *t = thunks.front();
3620   return t->getTargetInputSection();
3621 }
3622 
3623 bool ThunkSection::assignOffsets() {
3624   uint64_t off = 0;
3625   for (Thunk *t : thunks) {
3626     off = alignToPowerOf2(off, t->alignment);
3627     t->setOffset(off);
3628     uint32_t size = t->size();
3629     t->getThunkTargetSym()->size = size;
3630     off += size;
3631   }
3632   bool changed = off != size;
3633   size = off;
3634   return changed;
3635 }
3636 
3637 PPC32Got2Section::PPC32Got2Section()
3638     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
3639 
3640 bool PPC32Got2Section::isNeeded() const {
3641   // See the comment below. This is not needed if there is no other
3642   // InputSection.
3643   for (SectionCommand *cmd : getParent()->commands)
3644     if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
3645       for (InputSection *isec : isd->sections)
3646         if (isec != this)
3647           return true;
3648   return false;
3649 }
3650 
3651 void PPC32Got2Section::finalizeContents() {
3652   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
3653   // .got2 . This function computes outSecOff of each .got2 to be used in
3654   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
3655   // to collect input sections named ".got2".
3656   for (SectionCommand *cmd : getParent()->commands)
3657     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
3658       for (InputSection *isec : isd->sections) {
3659         // isec->file may be nullptr for MergeSyntheticSection.
3660         if (isec != this && isec->file)
3661           isec->file->ppc32Got2 = isec;
3662       }
3663     }
3664 }
3665 
3666 // If linking position-dependent code then the table will store the addresses
3667 // directly in the binary so the section has type SHT_PROGBITS. If linking
3668 // position-independent code the section has type SHT_NOBITS since it will be
3669 // allocated and filled in by the dynamic linker.
3670 PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
3671     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
3672                        config->isPic ? SHT_NOBITS : SHT_PROGBITS, 8,
3673                        ".branch_lt") {}
3674 
3675 uint64_t PPC64LongBranchTargetSection::getEntryVA(const Symbol *sym,
3676                                                   int64_t addend) {
3677   return getVA() + entry_index.find({sym, addend})->second * 8;
3678 }
3679 
3680 std::optional<uint32_t>
3681 PPC64LongBranchTargetSection::addEntry(const Symbol *sym, int64_t addend) {
3682   auto res =
3683       entry_index.try_emplace(std::make_pair(sym, addend), entries.size());
3684   if (!res.second)
3685     return std::nullopt;
3686   entries.emplace_back(sym, addend);
3687   return res.first->second;
3688 }
3689 
3690 size_t PPC64LongBranchTargetSection::getSize() const {
3691   return entries.size() * 8;
3692 }
3693 
3694 void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
3695   // If linking non-pic we have the final addresses of the targets and they get
3696   // written to the table directly. For pic the dynamic linker will allocate
3697   // the section and fill it.
3698   if (config->isPic)
3699     return;
3700 
3701   for (auto entry : entries) {
3702     const Symbol *sym = entry.first;
3703     int64_t addend = entry.second;
3704     assert(sym->getVA());
3705     // Need calls to branch to the local entry-point since a long-branch
3706     // must be a local-call.
3707     write64(buf, sym->getVA(addend) +
3708                      getPPC64GlobalEntryToLocalEntryOffset(sym->stOther));
3709     buf += 8;
3710   }
3711 }
3712 
3713 bool PPC64LongBranchTargetSection::isNeeded() const {
3714   // `removeUnusedSyntheticSections()` is called before thunk allocation which
3715   // is too early to determine if this section will be empty or not. We need
3716   // Finalized to keep the section alive until after thunk creation. Finalized
3717   // only gets set to true once `finalizeSections()` is called after thunk
3718   // creation. Because of this, if we don't create any long-branch thunks we end
3719   // up with an empty .branch_lt section in the binary.
3720   return !finalized || !entries.empty();
3721 }
3722 
3723 static uint8_t getAbiVersion() {
3724   // MIPS non-PIC executable gets ABI version 1.
3725   if (config->emachine == EM_MIPS) {
3726     if (!config->isPic && !config->relocatable &&
3727         (config->eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
3728       return 1;
3729     return 0;
3730   }
3731 
3732   if (config->emachine == EM_AMDGPU && !ctx.objectFiles.empty()) {
3733     uint8_t ver = ctx.objectFiles[0]->abiVersion;
3734     for (InputFile *file : ArrayRef(ctx.objectFiles).slice(1))
3735       if (file->abiVersion != ver)
3736         error("incompatible ABI version: " + toString(file));
3737     return ver;
3738   }
3739 
3740   return 0;
3741 }
3742 
3743 template <typename ELFT> void elf::writeEhdr(uint8_t *buf, Partition &part) {
3744   memcpy(buf, "\177ELF", 4);
3745 
3746   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3747   eHdr->e_ident[EI_CLASS] = config->is64 ? ELFCLASS64 : ELFCLASS32;
3748   eHdr->e_ident[EI_DATA] = config->isLE ? ELFDATA2LSB : ELFDATA2MSB;
3749   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
3750   eHdr->e_ident[EI_OSABI] = config->osabi;
3751   eHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
3752   eHdr->e_machine = config->emachine;
3753   eHdr->e_version = EV_CURRENT;
3754   eHdr->e_flags = config->eflags;
3755   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
3756   eHdr->e_phnum = part.phdrs.size();
3757   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
3758 
3759   if (!config->relocatable) {
3760     eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
3761     eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
3762   }
3763 }
3764 
3765 template <typename ELFT> void elf::writePhdrs(uint8_t *buf, Partition &part) {
3766   // Write the program header table.
3767   auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
3768   for (PhdrEntry *p : part.phdrs) {
3769     hBuf->p_type = p->p_type;
3770     hBuf->p_flags = p->p_flags;
3771     hBuf->p_offset = p->p_offset;
3772     hBuf->p_vaddr = p->p_vaddr;
3773     hBuf->p_paddr = p->p_paddr;
3774     hBuf->p_filesz = p->p_filesz;
3775     hBuf->p_memsz = p->p_memsz;
3776     hBuf->p_align = p->p_align;
3777     ++hBuf;
3778   }
3779 }
3780 
3781 template <typename ELFT>
3782 PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
3783     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
3784 
3785 template <typename ELFT>
3786 size_t PartitionElfHeaderSection<ELFT>::getSize() const {
3787   return sizeof(typename ELFT::Ehdr);
3788 }
3789 
3790 template <typename ELFT>
3791 void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
3792   writeEhdr<ELFT>(buf, getPartition());
3793 
3794   // Loadable partitions are always ET_DYN.
3795   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3796   eHdr->e_type = ET_DYN;
3797 }
3798 
3799 template <typename ELFT>
3800 PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
3801     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
3802 
3803 template <typename ELFT>
3804 size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
3805   return sizeof(typename ELFT::Phdr) * getPartition().phdrs.size();
3806 }
3807 
3808 template <typename ELFT>
3809 void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
3810   writePhdrs<ELFT>(buf, getPartition());
3811 }
3812 
3813 PartitionIndexSection::PartitionIndexSection()
3814     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
3815 
3816 size_t PartitionIndexSection::getSize() const {
3817   return 12 * (partitions.size() - 1);
3818 }
3819 
3820 void PartitionIndexSection::finalizeContents() {
3821   for (size_t i = 1; i != partitions.size(); ++i)
3822     partitions[i].nameStrTab = mainPart->dynStrTab->addString(partitions[i].name);
3823 }
3824 
3825 void PartitionIndexSection::writeTo(uint8_t *buf) {
3826   uint64_t va = getVA();
3827   for (size_t i = 1; i != partitions.size(); ++i) {
3828     write32(buf, mainPart->dynStrTab->getVA() + partitions[i].nameStrTab - va);
3829     write32(buf + 4, partitions[i].elfHeader->getVA() - (va + 4));
3830 
3831     SyntheticSection *next = i == partitions.size() - 1
3832                                  ? in.partEnd.get()
3833                                  : partitions[i + 1].elfHeader.get();
3834     write32(buf + 8, next->getVA() - partitions[i].elfHeader->getVA());
3835 
3836     va += 12;
3837     buf += 12;
3838   }
3839 }
3840 
3841 void InStruct::reset() {
3842   attributes.reset();
3843   riscvAttributes.reset();
3844   bss.reset();
3845   bssRelRo.reset();
3846   got.reset();
3847   gotPlt.reset();
3848   igotPlt.reset();
3849   relroPadding.reset();
3850   armCmseSGSection.reset();
3851   ppc64LongBranchTarget.reset();
3852   mipsAbiFlags.reset();
3853   mipsGot.reset();
3854   mipsOptions.reset();
3855   mipsReginfo.reset();
3856   mipsRldMap.reset();
3857   partEnd.reset();
3858   partIndex.reset();
3859   plt.reset();
3860   iplt.reset();
3861   ppc32Got2.reset();
3862   ibtPlt.reset();
3863   relaPlt.reset();
3864   relaIplt.reset();
3865   shStrTab.reset();
3866   strTab.reset();
3867   symTab.reset();
3868   symTabShndx.reset();
3869 }
3870 
3871 constexpr char kMemtagAndroidNoteName[] = "Android";
3872 void MemtagAndroidNote::writeTo(uint8_t *buf) {
3873   static_assert(
3874       sizeof(kMemtagAndroidNoteName) == 8,
3875       "Android 11 & 12 have an ABI that the note name is 8 bytes long. Keep it "
3876       "that way for backwards compatibility.");
3877 
3878   write32(buf, sizeof(kMemtagAndroidNoteName));
3879   write32(buf + 4, sizeof(uint32_t));
3880   write32(buf + 8, ELF::NT_ANDROID_TYPE_MEMTAG);
3881   memcpy(buf + 12, kMemtagAndroidNoteName, sizeof(kMemtagAndroidNoteName));
3882   buf += 12 + alignTo(sizeof(kMemtagAndroidNoteName), 4);
3883 
3884   uint32_t value = 0;
3885   value |= config->androidMemtagMode;
3886   if (config->androidMemtagHeap)
3887     value |= ELF::NT_MEMTAG_HEAP;
3888   // Note, MTE stack is an ABI break. Attempting to run an MTE stack-enabled
3889   // binary on Android 11 or 12 will result in a checkfail in the loader.
3890   if (config->androidMemtagStack)
3891     value |= ELF::NT_MEMTAG_STACK;
3892   write32(buf, value); // note value
3893 }
3894 
3895 size_t MemtagAndroidNote::getSize() const {
3896   return sizeof(llvm::ELF::Elf64_Nhdr) +
3897          /*namesz=*/alignTo(sizeof(kMemtagAndroidNoteName), 4) +
3898          /*descsz=*/sizeof(uint32_t);
3899 }
3900 
3901 void PackageMetadataNote::writeTo(uint8_t *buf) {
3902   write32(buf, 4);
3903   write32(buf + 4, config->packageMetadata.size() + 1);
3904   write32(buf + 8, FDO_PACKAGING_METADATA);
3905   memcpy(buf + 12, "FDO", 4);
3906   memcpy(buf + 16, config->packageMetadata.data(),
3907          config->packageMetadata.size());
3908 }
3909 
3910 size_t PackageMetadataNote::getSize() const {
3911   return sizeof(llvm::ELF::Elf64_Nhdr) + 4 +
3912          alignTo(config->packageMetadata.size() + 1, 4);
3913 }
3914 
3915 // Helper function, return the size of the ULEB128 for 'v', optionally writing
3916 // it to `*(buf + offset)` if `buf` is non-null.
3917 static size_t computeOrWriteULEB128(uint64_t v, uint8_t *buf, size_t offset) {
3918   if (buf)
3919     return encodeULEB128(v, buf + offset);
3920   return getULEB128Size(v);
3921 }
3922 
3923 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
3924 constexpr uint64_t kMemtagStepSizeBits = 3;
3925 constexpr uint64_t kMemtagGranuleSize = 16;
3926 static size_t
3927 createMemtagGlobalDescriptors(const SmallVector<const Symbol *, 0> &symbols,
3928                               uint8_t *buf = nullptr) {
3929   size_t sectionSize = 0;
3930   uint64_t lastGlobalEnd = 0;
3931 
3932   for (const Symbol *sym : symbols) {
3933     if (!includeInSymtab(*sym))
3934       continue;
3935     const uint64_t addr = sym->getVA();
3936     const uint64_t size = sym->getSize();
3937 
3938     if (addr <= kMemtagGranuleSize && buf != nullptr)
3939       errorOrWarn("address of the tagged symbol \"" + sym->getName() +
3940                   "\" falls in the ELF header. This is indicative of a "
3941                   "compiler/linker bug");
3942     if (addr % kMemtagGranuleSize != 0)
3943       errorOrWarn("address of the tagged symbol \"" + sym->getName() +
3944                   "\" at 0x" + Twine::utohexstr(addr) +
3945                   "\" is not granule (16-byte) aligned");
3946     if (size == 0)
3947       errorOrWarn("size of the tagged symbol \"" + sym->getName() +
3948                   "\" is not allowed to be zero");
3949     if (size % kMemtagGranuleSize != 0)
3950       errorOrWarn("size of the tagged symbol \"" + sym->getName() +
3951                   "\" (size 0x" + Twine::utohexstr(size) +
3952                   ") is not granule (16-byte) aligned");
3953 
3954     const uint64_t sizeToEncode = size / kMemtagGranuleSize;
3955     const uint64_t stepToEncode = ((addr - lastGlobalEnd) / kMemtagGranuleSize)
3956                                   << kMemtagStepSizeBits;
3957     if (sizeToEncode < (1 << kMemtagStepSizeBits)) {
3958       sectionSize += computeOrWriteULEB128(stepToEncode | sizeToEncode, buf, sectionSize);
3959     } else {
3960       sectionSize += computeOrWriteULEB128(stepToEncode, buf, sectionSize);
3961       sectionSize += computeOrWriteULEB128(sizeToEncode - 1, buf, sectionSize);
3962     }
3963     lastGlobalEnd = addr + size;
3964   }
3965 
3966   return sectionSize;
3967 }
3968 
3969 bool MemtagGlobalDescriptors::updateAllocSize() {
3970   size_t oldSize = getSize();
3971   std::stable_sort(symbols.begin(), symbols.end(),
3972                    [](const Symbol *s1, const Symbol *s2) {
3973                      return s1->getVA() < s2->getVA();
3974                    });
3975   return oldSize != getSize();
3976 }
3977 
3978 void MemtagGlobalDescriptors::writeTo(uint8_t *buf) {
3979   createMemtagGlobalDescriptors(symbols, buf);
3980 }
3981 
3982 size_t MemtagGlobalDescriptors::getSize() const {
3983   return createMemtagGlobalDescriptors(symbols);
3984 }
3985 
3986 InStruct elf::in;
3987 
3988 std::vector<Partition> elf::partitions;
3989 Partition *elf::mainPart;
3990 
3991 template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3992 template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3993 template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3994 template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3995 
3996 template void elf::splitSections<ELF32LE>();
3997 template void elf::splitSections<ELF32BE>();
3998 template void elf::splitSections<ELF64LE>();
3999 template void elf::splitSections<ELF64BE>();
4000 
4001 template class elf::MipsAbiFlagsSection<ELF32LE>;
4002 template class elf::MipsAbiFlagsSection<ELF32BE>;
4003 template class elf::MipsAbiFlagsSection<ELF64LE>;
4004 template class elf::MipsAbiFlagsSection<ELF64BE>;
4005 
4006 template class elf::MipsOptionsSection<ELF32LE>;
4007 template class elf::MipsOptionsSection<ELF32BE>;
4008 template class elf::MipsOptionsSection<ELF64LE>;
4009 template class elf::MipsOptionsSection<ELF64BE>;
4010 
4011 template void EhFrameSection::iterateFDEWithLSDA<ELF32LE>(
4012     function_ref<void(InputSection &)>);
4013 template void EhFrameSection::iterateFDEWithLSDA<ELF32BE>(
4014     function_ref<void(InputSection &)>);
4015 template void EhFrameSection::iterateFDEWithLSDA<ELF64LE>(
4016     function_ref<void(InputSection &)>);
4017 template void EhFrameSection::iterateFDEWithLSDA<ELF64BE>(
4018     function_ref<void(InputSection &)>);
4019 
4020 template class elf::MipsReginfoSection<ELF32LE>;
4021 template class elf::MipsReginfoSection<ELF32BE>;
4022 template class elf::MipsReginfoSection<ELF64LE>;
4023 template class elf::MipsReginfoSection<ELF64BE>;
4024 
4025 template class elf::DynamicSection<ELF32LE>;
4026 template class elf::DynamicSection<ELF32BE>;
4027 template class elf::DynamicSection<ELF64LE>;
4028 template class elf::DynamicSection<ELF64BE>;
4029 
4030 template class elf::RelocationSection<ELF32LE>;
4031 template class elf::RelocationSection<ELF32BE>;
4032 template class elf::RelocationSection<ELF64LE>;
4033 template class elf::RelocationSection<ELF64BE>;
4034 
4035 template class elf::AndroidPackedRelocationSection<ELF32LE>;
4036 template class elf::AndroidPackedRelocationSection<ELF32BE>;
4037 template class elf::AndroidPackedRelocationSection<ELF64LE>;
4038 template class elf::AndroidPackedRelocationSection<ELF64BE>;
4039 
4040 template class elf::RelrSection<ELF32LE>;
4041 template class elf::RelrSection<ELF32BE>;
4042 template class elf::RelrSection<ELF64LE>;
4043 template class elf::RelrSection<ELF64BE>;
4044 
4045 template class elf::SymbolTableSection<ELF32LE>;
4046 template class elf::SymbolTableSection<ELF32BE>;
4047 template class elf::SymbolTableSection<ELF64LE>;
4048 template class elf::SymbolTableSection<ELF64BE>;
4049 
4050 template class elf::VersionNeedSection<ELF32LE>;
4051 template class elf::VersionNeedSection<ELF32BE>;
4052 template class elf::VersionNeedSection<ELF64LE>;
4053 template class elf::VersionNeedSection<ELF64BE>;
4054 
4055 template void elf::writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
4056 template void elf::writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
4057 template void elf::writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
4058 template void elf::writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
4059 
4060 template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
4061 template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
4062 template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
4063 template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
4064 
4065 template class elf::PartitionElfHeaderSection<ELF32LE>;
4066 template class elf::PartitionElfHeaderSection<ELF32BE>;
4067 template class elf::PartitionElfHeaderSection<ELF64LE>;
4068 template class elf::PartitionElfHeaderSection<ELF64BE>;
4069 
4070 template class elf::PartitionProgramHeadersSection<ELF32LE>;
4071 template class elf::PartitionProgramHeadersSection<ELF32BE>;
4072 template class elf::PartitionProgramHeadersSection<ELF64LE>;
4073 template class elf::PartitionProgramHeadersSection<ELF64BE>;
4074