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