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