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