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