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