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