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 "llvm/Support/TimeProfiler.h"
40 #include <cstdlib>
41 #include <thread>
42 
43 using namespace llvm;
44 using namespace llvm::dwarf;
45 using namespace llvm::ELF;
46 using namespace llvm::object;
47 using namespace llvm::support;
48 
49 using llvm::support::endian::read32le;
50 using llvm::support::endian::write32le;
51 using llvm::support::endian::write64le;
52 
53 namespace lld {
54 namespace elf {
55 constexpr size_t MergeNoTailSection::numShards;
56 
57 static uint64_t readUint(uint8_t *buf) {
58   return config->is64 ? read64(buf) : read32(buf);
59 }
60 
61 static void writeUint(uint8_t *buf, uint64_t val) {
62   if (config->is64)
63     write64(buf, val);
64   else
65     write32(buf, val);
66 }
67 
68 // Returns an LLD version string.
69 static ArrayRef<uint8_t> getVersion() {
70   // Check LLD_VERSION first for ease of testing.
71   // You can get consistent output by using the environment variable.
72   // This is only for testing.
73   StringRef s = getenv("LLD_VERSION");
74   if (s.empty())
75     s = saver.save(Twine("Linker: ") + getLLDVersion());
76 
77   // +1 to include the terminating '\0'.
78   return {(const uint8_t *)s.data(), s.size() + 1};
79 }
80 
81 // Creates a .comment section containing LLD version info.
82 // With this feature, you can identify LLD-generated binaries easily
83 // by "readelf --string-dump .comment <file>".
84 // The returned object is a mergeable string section.
85 MergeInputSection *createCommentSection() {
86   return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
87                                  getVersion(), ".comment");
88 }
89 
90 // .MIPS.abiflags section.
91 template <class ELFT>
92 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags flags)
93     : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
94       flags(flags) {
95   this->entsize = sizeof(Elf_Mips_ABIFlags);
96 }
97 
98 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
99   memcpy(buf, &flags, sizeof(flags));
100 }
101 
102 template <class ELFT>
103 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
104   Elf_Mips_ABIFlags flags = {};
105   bool create = false;
106 
107   for (InputSectionBase *sec : inputSections) {
108     if (sec->type != SHT_MIPS_ABIFLAGS)
109       continue;
110     sec->markDead();
111     create = true;
112 
113     std::string filename = toString(sec->file);
114     const size_t size = sec->data().size();
115     // Older version of BFD (such as the default FreeBSD linker) concatenate
116     // .MIPS.abiflags instead of merging. To allow for this case (or potential
117     // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
118     if (size < sizeof(Elf_Mips_ABIFlags)) {
119       error(filename + ": invalid size of .MIPS.abiflags section: got " +
120             Twine(size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
121       return nullptr;
122     }
123     auto *s = reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->data().data());
124     if (s->version != 0) {
125       error(filename + ": unexpected .MIPS.abiflags version " +
126             Twine(s->version));
127       return nullptr;
128     }
129 
130     // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
131     // select the highest number of ISA/Rev/Ext.
132     flags.isa_level = std::max(flags.isa_level, s->isa_level);
133     flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
134     flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
135     flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
136     flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
137     flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
138     flags.ases |= s->ases;
139     flags.flags1 |= s->flags1;
140     flags.flags2 |= s->flags2;
141     flags.fp_abi = getMipsFpAbiFlag(flags.fp_abi, s->fp_abi, filename);
142   };
143 
144   if (create)
145     return make<MipsAbiFlagsSection<ELFT>>(flags);
146   return nullptr;
147 }
148 
149 // .MIPS.options section.
150 template <class ELFT>
151 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo reginfo)
152     : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
153       reginfo(reginfo) {
154   this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
155 }
156 
157 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
158   auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
159   options->kind = ODK_REGINFO;
160   options->size = getSize();
161 
162   if (!config->relocatable)
163     reginfo.ri_gp_value = in.mipsGot->getGp();
164   memcpy(buf + sizeof(Elf_Mips_Options), &reginfo, sizeof(reginfo));
165 }
166 
167 template <class ELFT>
168 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
169   // N64 ABI only.
170   if (!ELFT::Is64Bits)
171     return nullptr;
172 
173   std::vector<InputSectionBase *> sections;
174   for (InputSectionBase *sec : inputSections)
175     if (sec->type == SHT_MIPS_OPTIONS)
176       sections.push_back(sec);
177 
178   if (sections.empty())
179     return nullptr;
180 
181   Elf_Mips_RegInfo reginfo = {};
182   for (InputSectionBase *sec : sections) {
183     sec->markDead();
184 
185     std::string filename = toString(sec->file);
186     ArrayRef<uint8_t> d = sec->data();
187 
188     while (!d.empty()) {
189       if (d.size() < sizeof(Elf_Mips_Options)) {
190         error(filename + ": invalid size of .MIPS.options section");
191         break;
192       }
193 
194       auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
195       if (opt->kind == ODK_REGINFO) {
196         reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
197         sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
198         break;
199       }
200 
201       if (!opt->size)
202         fatal(filename + ": zero option descriptor size");
203       d = d.slice(opt->size);
204     }
205   };
206 
207   return make<MipsOptionsSection<ELFT>>(reginfo);
208 }
209 
210 // MIPS .reginfo section.
211 template <class ELFT>
212 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo reginfo)
213     : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
214       reginfo(reginfo) {
215   this->entsize = sizeof(Elf_Mips_RegInfo);
216 }
217 
218 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
219   if (!config->relocatable)
220     reginfo.ri_gp_value = in.mipsGot->getGp();
221   memcpy(buf, &reginfo, sizeof(reginfo));
222 }
223 
224 template <class ELFT>
225 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
226   // Section should be alive for O32 and N32 ABIs only.
227   if (ELFT::Is64Bits)
228     return nullptr;
229 
230   std::vector<InputSectionBase *> sections;
231   for (InputSectionBase *sec : inputSections)
232     if (sec->type == SHT_MIPS_REGINFO)
233       sections.push_back(sec);
234 
235   if (sections.empty())
236     return nullptr;
237 
238   Elf_Mips_RegInfo reginfo = {};
239   for (InputSectionBase *sec : sections) {
240     sec->markDead();
241 
242     if (sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
243       error(toString(sec->file) + ": invalid size of .reginfo section");
244       return nullptr;
245     }
246 
247     auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->data().data());
248     reginfo.ri_gprmask |= r->ri_gprmask;
249     sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
250   };
251 
252   return make<MipsReginfoSection<ELFT>>(reginfo);
253 }
254 
255 InputSection *createInterpSection() {
256   // StringSaver guarantees that the returned string ends with '\0'.
257   StringRef s = saver.save(config->dynamicLinker);
258   ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
259 
260   return make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, contents,
261                             ".interp");
262 }
263 
264 Defined *addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
265                            uint64_t size, InputSectionBase &section) {
266   auto *s = make<Defined>(section.file, name, STB_LOCAL, STV_DEFAULT, type,
267                           value, size, &section);
268   if (in.symTab)
269     in.symTab->addSymbol(s);
270   return s;
271 }
272 
273 static size_t getHashSize() {
274   switch (config->buildId) {
275   case BuildIdKind::Fast:
276     return 8;
277   case BuildIdKind::Md5:
278   case BuildIdKind::Uuid:
279     return 16;
280   case BuildIdKind::Sha1:
281     return 20;
282   case BuildIdKind::Hexstring:
283     return config->buildIdVector.size();
284   default:
285     llvm_unreachable("unknown BuildIdKind");
286   }
287 }
288 
289 // This class represents a linker-synthesized .note.gnu.property section.
290 //
291 // In x86 and AArch64, object files may contain feature flags indicating the
292 // features that they have used. The flags are stored in a .note.gnu.property
293 // section.
294 //
295 // lld reads the sections from input files and merges them by computing AND of
296 // the flags. The result is written as a new .note.gnu.property section.
297 //
298 // If the flag is zero (which indicates that the intersection of the feature
299 // sets is empty, or some input files didn't have .note.gnu.property sections),
300 // we don't create this section.
301 GnuPropertySection::GnuPropertySection()
302     : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
303                        config->wordsize, ".note.gnu.property") {}
304 
305 void GnuPropertySection::writeTo(uint8_t *buf) {
306   uint32_t featureAndType = config->emachine == EM_AARCH64
307                                 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
308                                 : GNU_PROPERTY_X86_FEATURE_1_AND;
309 
310   write32(buf, 4);                                   // Name size
311   write32(buf + 4, config->is64 ? 16 : 12);          // Content size
312   write32(buf + 8, NT_GNU_PROPERTY_TYPE_0);          // Type
313   memcpy(buf + 12, "GNU", 4);                        // Name string
314   write32(buf + 16, featureAndType);                 // Feature type
315   write32(buf + 20, 4);                              // Feature size
316   write32(buf + 24, config->andFeatures);            // Feature flags
317   if (config->is64)
318     write32(buf + 28, 0); // Padding
319 }
320 
321 size_t GnuPropertySection::getSize() const { return config->is64 ? 32 : 28; }
322 
323 BuildIdSection::BuildIdSection()
324     : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
325       hashSize(getHashSize()) {}
326 
327 void BuildIdSection::writeTo(uint8_t *buf) {
328   write32(buf, 4);                      // Name size
329   write32(buf + 4, hashSize);           // Content size
330   write32(buf + 8, NT_GNU_BUILD_ID);    // Type
331   memcpy(buf + 12, "GNU", 4);           // Name string
332   hashBuf = buf + 16;
333 }
334 
335 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
336   assert(buf.size() == hashSize);
337   memcpy(hashBuf, buf.data(), hashSize);
338 }
339 
340 BssSection::BssSection(StringRef name, uint64_t size, uint32_t alignment)
341     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, alignment, name) {
342   this->bss = true;
343   this->size = size;
344 }
345 
346 EhFrameSection::EhFrameSection()
347     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
348 
349 // Search for an existing CIE record or create a new one.
350 // CIE records from input object files are uniquified by their contents
351 // and where their relocations point to.
352 template <class ELFT, class RelTy>
353 CieRecord *EhFrameSection::addCie(EhSectionPiece &cie, ArrayRef<RelTy> rels) {
354   Symbol *personality = nullptr;
355   unsigned firstRelI = cie.firstRelocation;
356   if (firstRelI != (unsigned)-1)
357     personality =
358         &cie.sec->template getFile<ELFT>()->getRelocTargetSym(rels[firstRelI]);
359 
360   // Search for an existing CIE by CIE contents/relocation target pair.
361   CieRecord *&rec = cieMap[{cie.data(), personality}];
362 
363   // If not found, create a new one.
364   if (!rec) {
365     rec = make<CieRecord>();
366     rec->cie = &cie;
367     cieRecords.push_back(rec);
368   }
369   return rec;
370 }
371 
372 // There is one FDE per function. Returns true if a given FDE
373 // points to a live function.
374 template <class ELFT, class RelTy>
375 bool EhFrameSection::isFdeLive(EhSectionPiece &fde, ArrayRef<RelTy> rels) {
376   auto *sec = cast<EhInputSection>(fde.sec);
377   unsigned firstRelI = fde.firstRelocation;
378 
379   // An FDE should point to some function because FDEs are to describe
380   // functions. That's however not always the case due to an issue of
381   // ld.gold with -r. ld.gold may discard only functions and leave their
382   // corresponding FDEs, which results in creating bad .eh_frame sections.
383   // To deal with that, we ignore such FDEs.
384   if (firstRelI == (unsigned)-1)
385     return false;
386 
387   const RelTy &rel = rels[firstRelI];
388   Symbol &b = sec->template getFile<ELFT>()->getRelocTargetSym(rel);
389 
390   // FDEs for garbage-collected or merged-by-ICF sections, or sections in
391   // another partition, are dead.
392   if (auto *d = dyn_cast<Defined>(&b))
393     if (SectionBase *sec = d->section)
394       return sec->partition == partition;
395   return false;
396 }
397 
398 // .eh_frame is a sequence of CIE or FDE records. In general, there
399 // is one CIE record per input object file which is followed by
400 // a list of FDEs. This function searches an existing CIE or create a new
401 // one and associates FDEs to the CIE.
402 template <class ELFT, class RelTy>
403 void EhFrameSection::addRecords(EhInputSection *sec, ArrayRef<RelTy> rels) {
404   offsetToCie.clear();
405   for (EhSectionPiece &piece : sec->pieces) {
406     // The empty record is the end marker.
407     if (piece.size == 4)
408       return;
409 
410     size_t offset = piece.inputOff;
411     uint32_t id = read32(piece.data().data() + 4);
412     if (id == 0) {
413       offsetToCie[offset] = addCie<ELFT>(piece, rels);
414       continue;
415     }
416 
417     uint32_t cieOffset = offset + 4 - id;
418     CieRecord *rec = offsetToCie[cieOffset];
419     if (!rec)
420       fatal(toString(sec) + ": invalid CIE reference");
421 
422     if (!isFdeLive<ELFT>(piece, rels))
423       continue;
424     rec->fdes.push_back(&piece);
425     numFdes++;
426   }
427 }
428 
429 template <class ELFT>
430 void EhFrameSection::addSectionAux(EhInputSection *sec) {
431   if (!sec->isLive())
432     return;
433   if (sec->areRelocsRela)
434     addRecords<ELFT>(sec, sec->template relas<ELFT>());
435   else
436     addRecords<ELFT>(sec, sec->template rels<ELFT>());
437 }
438 
439 void EhFrameSection::addSection(EhInputSection *sec) {
440   sec->parent = this;
441 
442   alignment = std::max(alignment, sec->alignment);
443   sections.push_back(sec);
444 
445   for (auto *ds : sec->dependentSections)
446     dependentSections.push_back(ds);
447 }
448 
449 static void writeCieFde(uint8_t *buf, ArrayRef<uint8_t> d) {
450   memcpy(buf, d.data(), d.size());
451 
452   size_t aligned = alignTo(d.size(), config->wordsize);
453 
454   // Zero-clear trailing padding if it exists.
455   memset(buf + d.size(), 0, aligned - d.size());
456 
457   // Fix the size field. -4 since size does not include the size field itself.
458   write32(buf, aligned - 4);
459 }
460 
461 void EhFrameSection::finalizeContents() {
462   assert(!this->size); // Not finalized.
463 
464   switch (config->ekind) {
465   case ELFNoneKind:
466     llvm_unreachable("invalid ekind");
467   case ELF32LEKind:
468     for (EhInputSection *sec : sections)
469       addSectionAux<ELF32LE>(sec);
470     break;
471   case ELF32BEKind:
472     for (EhInputSection *sec : sections)
473       addSectionAux<ELF32BE>(sec);
474     break;
475   case ELF64LEKind:
476     for (EhInputSection *sec : sections)
477       addSectionAux<ELF64LE>(sec);
478     break;
479   case ELF64BEKind:
480     for (EhInputSection *sec : sections)
481       addSectionAux<ELF64BE>(sec);
482     break;
483   }
484 
485   size_t off = 0;
486   for (CieRecord *rec : cieRecords) {
487     rec->cie->outputOff = off;
488     off += alignTo(rec->cie->size, config->wordsize);
489 
490     for (EhSectionPiece *fde : rec->fdes) {
491       fde->outputOff = off;
492       off += alignTo(fde->size, config->wordsize);
493     }
494   }
495 
496   // The LSB standard does not allow a .eh_frame section with zero
497   // Call Frame Information records. glibc unwind-dw2-fde.c
498   // classify_object_over_fdes expects there is a CIE record length 0 as a
499   // terminator. Thus we add one unconditionally.
500   off += 4;
501 
502   this->size = off;
503 }
504 
505 // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
506 // to get an FDE from an address to which FDE is applied. This function
507 // returns a list of such pairs.
508 std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
509   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
510   std::vector<FdeData> ret;
511 
512   uint64_t va = getPartition().ehFrameHdr->getVA();
513   for (CieRecord *rec : cieRecords) {
514     uint8_t enc = getFdeEncoding(rec->cie);
515     for (EhSectionPiece *fde : rec->fdes) {
516       uint64_t pc = getFdePc(buf, fde->outputOff, enc);
517       uint64_t fdeVA = getParent()->addr + fde->outputOff;
518       if (!isInt<32>(pc - va))
519         fatal(toString(fde->sec) + ": PC offset is too large: 0x" +
520               Twine::utohexstr(pc - va));
521       ret.push_back({uint32_t(pc - va), uint32_t(fdeVA - va)});
522     }
523   }
524 
525   // Sort the FDE list by their PC and uniqueify. Usually there is only
526   // one FDE for a PC (i.e. function), but if ICF merges two functions
527   // into one, there can be more than one FDEs pointing to the address.
528   auto less = [](const FdeData &a, const FdeData &b) {
529     return a.pcRel < b.pcRel;
530   };
531   llvm::stable_sort(ret, less);
532   auto eq = [](const FdeData &a, const FdeData &b) {
533     return a.pcRel == b.pcRel;
534   };
535   ret.erase(std::unique(ret.begin(), ret.end(), eq), ret.end());
536 
537   return ret;
538 }
539 
540 static uint64_t readFdeAddr(uint8_t *buf, int size) {
541   switch (size) {
542   case DW_EH_PE_udata2:
543     return read16(buf);
544   case DW_EH_PE_sdata2:
545     return (int16_t)read16(buf);
546   case DW_EH_PE_udata4:
547     return read32(buf);
548   case DW_EH_PE_sdata4:
549     return (int32_t)read32(buf);
550   case DW_EH_PE_udata8:
551   case DW_EH_PE_sdata8:
552     return read64(buf);
553   case DW_EH_PE_absptr:
554     return readUint(buf);
555   }
556   fatal("unknown FDE size encoding");
557 }
558 
559 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
560 // We need it to create .eh_frame_hdr section.
561 uint64_t EhFrameSection::getFdePc(uint8_t *buf, size_t fdeOff,
562                                   uint8_t enc) const {
563   // The starting address to which this FDE applies is
564   // stored at FDE + 8 byte.
565   size_t off = fdeOff + 8;
566   uint64_t addr = readFdeAddr(buf + off, enc & 0xf);
567   if ((enc & 0x70) == DW_EH_PE_absptr)
568     return addr;
569   if ((enc & 0x70) == DW_EH_PE_pcrel)
570     return addr + getParent()->addr + off;
571   fatal("unknown FDE size relative encoding");
572 }
573 
574 void EhFrameSection::writeTo(uint8_t *buf) {
575   // Write CIE and FDE records.
576   for (CieRecord *rec : cieRecords) {
577     size_t cieOffset = rec->cie->outputOff;
578     writeCieFde(buf + cieOffset, rec->cie->data());
579 
580     for (EhSectionPiece *fde : rec->fdes) {
581       size_t off = fde->outputOff;
582       writeCieFde(buf + off, fde->data());
583 
584       // FDE's second word should have the offset to an associated CIE.
585       // Write it.
586       write32(buf + off + 4, off + 4 - cieOffset);
587     }
588   }
589 
590   // Apply relocations. .eh_frame section contents are not contiguous
591   // in the output buffer, but relocateAlloc() still works because
592   // getOffset() takes care of discontiguous section pieces.
593   for (EhInputSection *s : sections)
594     s->relocateAlloc(buf, nullptr);
595 
596   if (getPartition().ehFrameHdr && getPartition().ehFrameHdr->getParent())
597     getPartition().ehFrameHdr->write();
598 }
599 
600 GotSection::GotSection()
601     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
602                        ".got") {
603   // If ElfSym::globalOffsetTable is relative to .got and is referenced,
604   // increase numEntries by the number of entries used to emit
605   // ElfSym::globalOffsetTable.
606   if (ElfSym::globalOffsetTable && !target->gotBaseSymInGotPlt)
607     numEntries += target->gotHeaderEntriesNum;
608 }
609 
610 void GotSection::addEntry(Symbol &sym) {
611   sym.gotIndex = numEntries;
612   ++numEntries;
613 }
614 
615 bool GotSection::addDynTlsEntry(Symbol &sym) {
616   if (sym.globalDynIndex != -1U)
617     return false;
618   sym.globalDynIndex = numEntries;
619   // Global Dynamic TLS entries take two GOT slots.
620   numEntries += 2;
621   return true;
622 }
623 
624 // Reserves TLS entries for a TLS module ID and a TLS block offset.
625 // In total it takes two GOT slots.
626 bool GotSection::addTlsIndex() {
627   if (tlsIndexOff != uint32_t(-1))
628     return false;
629   tlsIndexOff = numEntries * config->wordsize;
630   numEntries += 2;
631   return true;
632 }
633 
634 uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
635   return this->getVA() + b.globalDynIndex * config->wordsize;
636 }
637 
638 uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
639   return b.globalDynIndex * config->wordsize;
640 }
641 
642 void GotSection::finalizeContents() {
643   size = numEntries * config->wordsize;
644 }
645 
646 bool GotSection::isNeeded() const {
647   // We need to emit a GOT even if it's empty if there's a relocation that is
648   // relative to GOT(such as GOTOFFREL).
649   return numEntries || hasGotOffRel;
650 }
651 
652 void GotSection::writeTo(uint8_t *buf) {
653   // Buf points to the start of this section's buffer,
654   // whereas InputSectionBase::relocateAlloc() expects its argument
655   // to point to the start of the output section.
656   target->writeGotHeader(buf);
657   relocateAlloc(buf - outSecOff, buf - outSecOff + size);
658 }
659 
660 static uint64_t getMipsPageAddr(uint64_t addr) {
661   return (addr + 0x8000) & ~0xffff;
662 }
663 
664 static uint64_t getMipsPageCount(uint64_t size) {
665   return (size + 0xfffe) / 0xffff + 1;
666 }
667 
668 MipsGotSection::MipsGotSection()
669     : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
670                        ".got") {}
671 
672 void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
673                               RelExpr expr) {
674   FileGot &g = getGot(file);
675   if (expr == R_MIPS_GOT_LOCAL_PAGE) {
676     if (const OutputSection *os = sym.getOutputSection())
677       g.pagesMap.insert({os, {}});
678     else
679       g.local16.insert({{nullptr, getMipsPageAddr(sym.getVA(addend))}, 0});
680   } else if (sym.isTls())
681     g.tls.insert({&sym, 0});
682   else if (sym.isPreemptible && expr == R_ABS)
683     g.relocs.insert({&sym, 0});
684   else if (sym.isPreemptible)
685     g.global.insert({&sym, 0});
686   else if (expr == R_MIPS_GOT_OFF32)
687     g.local32.insert({{&sym, addend}, 0});
688   else
689     g.local16.insert({{&sym, addend}, 0});
690 }
691 
692 void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
693   getGot(file).dynTlsSymbols.insert({&sym, 0});
694 }
695 
696 void MipsGotSection::addTlsIndex(InputFile &file) {
697   getGot(file).dynTlsSymbols.insert({nullptr, 0});
698 }
699 
700 size_t MipsGotSection::FileGot::getEntriesNum() const {
701   return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
702          tls.size() + dynTlsSymbols.size() * 2;
703 }
704 
705 size_t MipsGotSection::FileGot::getPageEntriesNum() const {
706   size_t num = 0;
707   for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
708     num += p.second.count;
709   return num;
710 }
711 
712 size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
713   size_t count = getPageEntriesNum() + local16.size() + global.size();
714   // If there are relocation-only entries in the GOT, TLS entries
715   // are allocated after them. TLS entries should be addressable
716   // by 16-bit index so count both reloc-only and TLS entries.
717   if (!tls.empty() || !dynTlsSymbols.empty())
718     count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
719   return count;
720 }
721 
722 MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
723   if (!f.mipsGotIndex.hasValue()) {
724     gots.emplace_back();
725     gots.back().file = &f;
726     f.mipsGotIndex = gots.size() - 1;
727   }
728   return gots[*f.mipsGotIndex];
729 }
730 
731 uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
732                                             const Symbol &sym,
733                                             int64_t addend) const {
734   const FileGot &g = gots[*f->mipsGotIndex];
735   uint64_t index = 0;
736   if (const OutputSection *outSec = sym.getOutputSection()) {
737     uint64_t secAddr = getMipsPageAddr(outSec->addr);
738     uint64_t symAddr = getMipsPageAddr(sym.getVA(addend));
739     index = g.pagesMap.lookup(outSec).firstIndex + (symAddr - secAddr) / 0xffff;
740   } else {
741     index = g.local16.lookup({nullptr, getMipsPageAddr(sym.getVA(addend))});
742   }
743   return index * config->wordsize;
744 }
745 
746 uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
747                                            int64_t addend) const {
748   const FileGot &g = gots[*f->mipsGotIndex];
749   Symbol *sym = const_cast<Symbol *>(&s);
750   if (sym->isTls())
751     return g.tls.lookup(sym) * config->wordsize;
752   if (sym->isPreemptible)
753     return g.global.lookup(sym) * config->wordsize;
754   return g.local16.lookup({sym, addend}) * config->wordsize;
755 }
756 
757 uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
758   const FileGot &g = gots[*f->mipsGotIndex];
759   return g.dynTlsSymbols.lookup(nullptr) * config->wordsize;
760 }
761 
762 uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
763                                             const Symbol &s) const {
764   const FileGot &g = gots[*f->mipsGotIndex];
765   Symbol *sym = const_cast<Symbol *>(&s);
766   return g.dynTlsSymbols.lookup(sym) * config->wordsize;
767 }
768 
769 const Symbol *MipsGotSection::getFirstGlobalEntry() const {
770   if (gots.empty())
771     return nullptr;
772   const FileGot &primGot = gots.front();
773   if (!primGot.global.empty())
774     return primGot.global.front().first;
775   if (!primGot.relocs.empty())
776     return primGot.relocs.front().first;
777   return nullptr;
778 }
779 
780 unsigned MipsGotSection::getLocalEntriesNum() const {
781   if (gots.empty())
782     return headerEntriesNum;
783   return headerEntriesNum + gots.front().getPageEntriesNum() +
784          gots.front().local16.size();
785 }
786 
787 bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
788   FileGot tmp = dst;
789   set_union(tmp.pagesMap, src.pagesMap);
790   set_union(tmp.local16, src.local16);
791   set_union(tmp.global, src.global);
792   set_union(tmp.relocs, src.relocs);
793   set_union(tmp.tls, src.tls);
794   set_union(tmp.dynTlsSymbols, src.dynTlsSymbols);
795 
796   size_t count = isPrimary ? headerEntriesNum : 0;
797   count += tmp.getIndexedEntriesNum();
798 
799   if (count * config->wordsize > config->mipsGotSize)
800     return false;
801 
802   std::swap(tmp, dst);
803   return true;
804 }
805 
806 void MipsGotSection::finalizeContents() { updateAllocSize(); }
807 
808 bool MipsGotSection::updateAllocSize() {
809   size = headerEntriesNum * config->wordsize;
810   for (const FileGot &g : gots)
811     size += g.getEntriesNum() * config->wordsize;
812   return false;
813 }
814 
815 void MipsGotSection::build() {
816   if (gots.empty())
817     return;
818 
819   std::vector<FileGot> mergedGots(1);
820 
821   // For each GOT move non-preemptible symbols from the `Global`
822   // to `Local16` list. Preemptible symbol might become non-preemptible
823   // one if, for example, it gets a related copy relocation.
824   for (FileGot &got : gots) {
825     for (auto &p: got.global)
826       if (!p.first->isPreemptible)
827         got.local16.insert({{p.first, 0}, 0});
828     got.global.remove_if([&](const std::pair<Symbol *, size_t> &p) {
829       return !p.first->isPreemptible;
830     });
831   }
832 
833   // For each GOT remove "reloc-only" entry if there is "global"
834   // entry for the same symbol. And add local entries which indexed
835   // using 32-bit value at the end of 16-bit entries.
836   for (FileGot &got : gots) {
837     got.relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
838       return got.global.count(p.first);
839     });
840     set_union(got.local16, got.local32);
841     got.local32.clear();
842   }
843 
844   // Evaluate number of "reloc-only" entries in the resulting GOT.
845   // To do that put all unique "reloc-only" and "global" entries
846   // from all GOTs to the future primary GOT.
847   FileGot *primGot = &mergedGots.front();
848   for (FileGot &got : gots) {
849     set_union(primGot->relocs, got.global);
850     set_union(primGot->relocs, got.relocs);
851     got.relocs.clear();
852   }
853 
854   // Evaluate number of "page" entries in each GOT.
855   for (FileGot &got : gots) {
856     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
857          got.pagesMap) {
858       const OutputSection *os = p.first;
859       uint64_t secSize = 0;
860       for (BaseCommand *cmd : os->sectionCommands) {
861         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
862           for (InputSection *isec : isd->sections) {
863             uint64_t off = alignTo(secSize, isec->alignment);
864             secSize = off + isec->getSize();
865           }
866       }
867       p.second.count = getMipsPageCount(secSize);
868     }
869   }
870 
871   // Merge GOTs. Try to join as much as possible GOTs but do not exceed
872   // maximum GOT size. At first, try to fill the primary GOT because
873   // the primary GOT can be accessed in the most effective way. If it
874   // is not possible, try to fill the last GOT in the list, and finally
875   // create a new GOT if both attempts failed.
876   for (FileGot &srcGot : gots) {
877     InputFile *file = srcGot.file;
878     if (tryMergeGots(mergedGots.front(), srcGot, true)) {
879       file->mipsGotIndex = 0;
880     } else {
881       // If this is the first time we failed to merge with the primary GOT,
882       // MergedGots.back() will also be the primary GOT. We must make sure not
883       // to try to merge again with isPrimary=false, as otherwise, if the
884       // inputs are just right, we could allow the primary GOT to become 1 or 2
885       // words bigger due to ignoring the header size.
886       if (mergedGots.size() == 1 ||
887           !tryMergeGots(mergedGots.back(), srcGot, false)) {
888         mergedGots.emplace_back();
889         std::swap(mergedGots.back(), srcGot);
890       }
891       file->mipsGotIndex = mergedGots.size() - 1;
892     }
893   }
894   std::swap(gots, mergedGots);
895 
896   // Reduce number of "reloc-only" entries in the primary GOT
897   // by subtracting "global" entries in the primary GOT.
898   primGot = &gots.front();
899   primGot->relocs.remove_if([&](const std::pair<Symbol *, size_t> &p) {
900     return primGot->global.count(p.first);
901   });
902 
903   // Calculate indexes for each GOT entry.
904   size_t index = headerEntriesNum;
905   for (FileGot &got : gots) {
906     got.startIndex = &got == primGot ? 0 : index;
907     for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
908          got.pagesMap) {
909       // For each output section referenced by GOT page relocations calculate
910       // and save into pagesMap an upper bound of MIPS GOT entries required
911       // to store page addresses of local symbols. We assume the worst case -
912       // each 64kb page of the output section has at least one GOT relocation
913       // against it. And take in account the case when the section intersects
914       // page boundaries.
915       p.second.firstIndex = index;
916       index += p.second.count;
917     }
918     for (auto &p: got.local16)
919       p.second = index++;
920     for (auto &p: got.global)
921       p.second = index++;
922     for (auto &p: got.relocs)
923       p.second = index++;
924     for (auto &p: got.tls)
925       p.second = index++;
926     for (auto &p: got.dynTlsSymbols) {
927       p.second = index;
928       index += 2;
929     }
930   }
931 
932   // Update Symbol::gotIndex field to use this
933   // value later in the `sortMipsSymbols` function.
934   for (auto &p : primGot->global)
935     p.first->gotIndex = p.second;
936   for (auto &p : primGot->relocs)
937     p.first->gotIndex = p.second;
938 
939   // Create dynamic relocations.
940   for (FileGot &got : gots) {
941     // Create dynamic relocations for TLS entries.
942     for (std::pair<Symbol *, size_t> &p : got.tls) {
943       Symbol *s = p.first;
944       uint64_t offset = p.second * config->wordsize;
945       if (s->isPreemptible)
946         mainPart->relaDyn->addReloc(target->tlsGotRel, this, offset, s);
947     }
948     for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
949       Symbol *s = p.first;
950       uint64_t offset = p.second * config->wordsize;
951       if (s == nullptr) {
952         if (!config->isPic)
953           continue;
954         mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, this, offset, s);
955       } else {
956         // When building a shared library we still need a dynamic relocation
957         // for the module index. Therefore only checking for
958         // S->isPreemptible is not sufficient (this happens e.g. for
959         // thread-locals that have been marked as local through a linker script)
960         if (!s->isPreemptible && !config->isPic)
961           continue;
962         mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, this, offset, s);
963         // However, we can skip writing the TLS offset reloc for non-preemptible
964         // symbols since it is known even in shared libraries
965         if (!s->isPreemptible)
966           continue;
967         offset += config->wordsize;
968         mainPart->relaDyn->addReloc(target->tlsOffsetRel, this, offset, s);
969       }
970     }
971 
972     // Do not create dynamic relocations for non-TLS
973     // entries in the primary GOT.
974     if (&got == primGot)
975       continue;
976 
977     // Dynamic relocations for "global" entries.
978     for (const std::pair<Symbol *, size_t> &p : got.global) {
979       uint64_t offset = p.second * config->wordsize;
980       mainPart->relaDyn->addReloc(target->relativeRel, this, offset, p.first);
981     }
982     if (!config->isPic)
983       continue;
984     // Dynamic relocations for "local" entries in case of PIC.
985     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
986          got.pagesMap) {
987       size_t pageCount = l.second.count;
988       for (size_t pi = 0; pi < pageCount; ++pi) {
989         uint64_t offset = (l.second.firstIndex + pi) * config->wordsize;
990         mainPart->relaDyn->addReloc({target->relativeRel, this, offset, l.first,
991                                  int64_t(pi * 0x10000)});
992       }
993     }
994     for (const std::pair<GotEntry, size_t> &p : got.local16) {
995       uint64_t offset = p.second * config->wordsize;
996       mainPart->relaDyn->addReloc({target->relativeRel, this, offset, true,
997                                p.first.first, p.first.second});
998     }
999   }
1000 }
1001 
1002 bool MipsGotSection::isNeeded() const {
1003   // We add the .got section to the result for dynamic MIPS target because
1004   // its address and properties are mentioned in the .dynamic section.
1005   return !config->relocatable;
1006 }
1007 
1008 uint64_t MipsGotSection::getGp(const InputFile *f) const {
1009   // For files without related GOT or files refer a primary GOT
1010   // returns "common" _gp value. For secondary GOTs calculate
1011   // individual _gp values.
1012   if (!f || !f->mipsGotIndex.hasValue() || *f->mipsGotIndex == 0)
1013     return ElfSym::mipsGp->getVA(0);
1014   return getVA() + gots[*f->mipsGotIndex].startIndex * config->wordsize +
1015          0x7ff0;
1016 }
1017 
1018 void MipsGotSection::writeTo(uint8_t *buf) {
1019   // Set the MSB of the second GOT slot. This is not required by any
1020   // MIPS ABI documentation, though.
1021   //
1022   // There is a comment in glibc saying that "The MSB of got[1] of a
1023   // gnu object is set to identify gnu objects," and in GNU gold it
1024   // says "the second entry will be used by some runtime loaders".
1025   // But how this field is being used is unclear.
1026   //
1027   // We are not really willing to mimic other linkers behaviors
1028   // without understanding why they do that, but because all files
1029   // generated by GNU tools have this special GOT value, and because
1030   // we've been doing this for years, it is probably a safe bet to
1031   // keep doing this for now. We really need to revisit this to see
1032   // if we had to do this.
1033   writeUint(buf + config->wordsize, (uint64_t)1 << (config->wordsize * 8 - 1));
1034   for (const FileGot &g : gots) {
1035     auto write = [&](size_t i, const Symbol *s, int64_t a) {
1036       uint64_t va = a;
1037       if (s)
1038         va = s->getVA(a);
1039       writeUint(buf + i * config->wordsize, va);
1040     };
1041     // Write 'page address' entries to the local part of the GOT.
1042     for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1043          g.pagesMap) {
1044       size_t pageCount = l.second.count;
1045       uint64_t firstPageAddr = getMipsPageAddr(l.first->addr);
1046       for (size_t pi = 0; pi < pageCount; ++pi)
1047         write(l.second.firstIndex + pi, nullptr, firstPageAddr + pi * 0x10000);
1048     }
1049     // Local, global, TLS, reloc-only  entries.
1050     // If TLS entry has a corresponding dynamic relocations, leave it
1051     // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1052     // To calculate the adjustments use offsets for thread-local storage.
1053     // https://www.linux-mips.org/wiki/NPTL
1054     for (const std::pair<GotEntry, size_t> &p : g.local16)
1055       write(p.second, p.first.first, p.first.second);
1056     // Write VA to the primary GOT only. For secondary GOTs that
1057     // will be done by REL32 dynamic relocations.
1058     if (&g == &gots.front())
1059       for (const std::pair<Symbol *, size_t> &p : g.global)
1060         write(p.second, p.first, 0);
1061     for (const std::pair<Symbol *, size_t> &p : g.relocs)
1062       write(p.second, p.first, 0);
1063     for (const std::pair<Symbol *, size_t> &p : g.tls)
1064       write(p.second, p.first, p.first->isPreemptible ? 0 : -0x7000);
1065     for (const std::pair<Symbol *, size_t> &p : g.dynTlsSymbols) {
1066       if (p.first == nullptr && !config->isPic)
1067         write(p.second, nullptr, 1);
1068       else if (p.first && !p.first->isPreemptible) {
1069         // If we are emitting PIC code with relocations we mustn't write
1070         // anything to the GOT here. When using Elf_Rel relocations the value
1071         // one will be treated as an addend and will cause crashes at runtime
1072         if (!config->isPic)
1073           write(p.second, nullptr, 1);
1074         write(p.second + 1, p.first, -0x8000);
1075       }
1076     }
1077   }
1078 }
1079 
1080 // On PowerPC the .plt section is used to hold the table of function addresses
1081 // instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1082 // section. I don't know why we have a BSS style type for the section but it is
1083 // consistent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1084 GotPltSection::GotPltSection()
1085     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
1086                        ".got.plt") {
1087   if (config->emachine == EM_PPC) {
1088     name = ".plt";
1089   } else if (config->emachine == EM_PPC64) {
1090     type = SHT_NOBITS;
1091     name = ".plt";
1092   }
1093 }
1094 
1095 void GotPltSection::addEntry(Symbol &sym) {
1096   assert(sym.pltIndex == entries.size());
1097   entries.push_back(&sym);
1098 }
1099 
1100 size_t GotPltSection::getSize() const {
1101   return (target->gotPltHeaderEntriesNum + entries.size()) * config->wordsize;
1102 }
1103 
1104 void GotPltSection::writeTo(uint8_t *buf) {
1105   target->writeGotPltHeader(buf);
1106   buf += target->gotPltHeaderEntriesNum * config->wordsize;
1107   for (const Symbol *b : entries) {
1108     target->writeGotPlt(buf, *b);
1109     buf += config->wordsize;
1110   }
1111 }
1112 
1113 bool GotPltSection::isNeeded() const {
1114   // We need to emit GOTPLT even if it's empty if there's a relocation relative
1115   // to it.
1116   return !entries.empty() || hasGotPltOffRel;
1117 }
1118 
1119 static StringRef getIgotPltName() {
1120   // On ARM the IgotPltSection is part of the GotSection.
1121   if (config->emachine == EM_ARM)
1122     return ".got";
1123 
1124   // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1125   // needs to be named the same.
1126   if (config->emachine == EM_PPC64)
1127     return ".plt";
1128 
1129   return ".got.plt";
1130 }
1131 
1132 // On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1133 // with the IgotPltSection.
1134 IgotPltSection::IgotPltSection()
1135     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1136                        config->emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1137                        config->wordsize, getIgotPltName()) {}
1138 
1139 void IgotPltSection::addEntry(Symbol &sym) {
1140   assert(sym.pltIndex == entries.size());
1141   entries.push_back(&sym);
1142 }
1143 
1144 size_t IgotPltSection::getSize() const {
1145   return entries.size() * config->wordsize;
1146 }
1147 
1148 void IgotPltSection::writeTo(uint8_t *buf) {
1149   for (const Symbol *b : entries) {
1150     target->writeIgotPlt(buf, *b);
1151     buf += config->wordsize;
1152   }
1153 }
1154 
1155 StringTableSection::StringTableSection(StringRef name, bool dynamic)
1156     : SyntheticSection(dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, name),
1157       dynamic(dynamic) {
1158   // ELF string tables start with a NUL byte.
1159   addString("");
1160 }
1161 
1162 // Adds a string to the string table. If `hashIt` is true we hash and check for
1163 // duplicates. It is optional because the name of global symbols are already
1164 // uniqued and hashing them again has a big cost for a small value: uniquing
1165 // them with some other string that happens to be the same.
1166 unsigned StringTableSection::addString(StringRef s, bool hashIt) {
1167   if (hashIt) {
1168     auto r = stringMap.insert(std::make_pair(s, this->size));
1169     if (!r.second)
1170       return r.first->second;
1171   }
1172   unsigned ret = this->size;
1173   this->size = this->size + s.size() + 1;
1174   strings.push_back(s);
1175   return ret;
1176 }
1177 
1178 void StringTableSection::writeTo(uint8_t *buf) {
1179   for (StringRef s : strings) {
1180     memcpy(buf, s.data(), s.size());
1181     buf[s.size()] = '\0';
1182     buf += s.size() + 1;
1183   }
1184 }
1185 
1186 // Returns the number of entries in .gnu.version_d: the number of
1187 // non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
1188 // Note that we don't support vd_cnt > 1 yet.
1189 static unsigned getVerDefNum() {
1190   return namedVersionDefs().size() + 1;
1191 }
1192 
1193 template <class ELFT>
1194 DynamicSection<ELFT>::DynamicSection()
1195     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, config->wordsize,
1196                        ".dynamic") {
1197   this->entsize = ELFT::Is64Bits ? 16 : 8;
1198 
1199   // .dynamic section is not writable on MIPS and on Fuchsia OS
1200   // which passes -z rodynamic.
1201   // See "Special Section" in Chapter 4 in the following document:
1202   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1203   if (config->emachine == EM_MIPS || config->zRodynamic)
1204     this->flags = SHF_ALLOC;
1205 }
1206 
1207 template <class ELFT>
1208 void DynamicSection<ELFT>::add(int32_t tag, std::function<uint64_t()> fn) {
1209   entries.push_back({tag, fn});
1210 }
1211 
1212 template <class ELFT>
1213 void DynamicSection<ELFT>::addInt(int32_t tag, uint64_t val) {
1214   entries.push_back({tag, [=] { return val; }});
1215 }
1216 
1217 template <class ELFT>
1218 void DynamicSection<ELFT>::addInSec(int32_t tag, InputSection *sec) {
1219   entries.push_back({tag, [=] { return sec->getVA(0); }});
1220 }
1221 
1222 template <class ELFT>
1223 void DynamicSection<ELFT>::addInSecRelative(int32_t tag, InputSection *sec) {
1224   size_t tagOffset = entries.size() * entsize;
1225   entries.push_back(
1226       {tag, [=] { return sec->getVA(0) - (getVA() + tagOffset); }});
1227 }
1228 
1229 template <class ELFT>
1230 void DynamicSection<ELFT>::addOutSec(int32_t tag, OutputSection *sec) {
1231   entries.push_back({tag, [=] { return sec->addr; }});
1232 }
1233 
1234 template <class ELFT>
1235 void DynamicSection<ELFT>::addSize(int32_t tag, OutputSection *sec) {
1236   entries.push_back({tag, [=] { return sec->size; }});
1237 }
1238 
1239 template <class ELFT>
1240 void DynamicSection<ELFT>::addSym(int32_t tag, Symbol *sym) {
1241   entries.push_back({tag, [=] { return sym->getVA(); }});
1242 }
1243 
1244 // The output section .rela.dyn may include these synthetic sections:
1245 //
1246 // - part.relaDyn
1247 // - in.relaIplt: this is included if in.relaIplt is named .rela.dyn
1248 // - in.relaPlt: this is included if a linker script places .rela.plt inside
1249 //   .rela.dyn
1250 //
1251 // DT_RELASZ is the total size of the included sections.
1252 static std::function<uint64_t()> addRelaSz(RelocationBaseSection *relaDyn) {
1253   return [=]() {
1254     size_t size = relaDyn->getSize();
1255     if (in.relaIplt->getParent() == relaDyn->getParent())
1256       size += in.relaIplt->getSize();
1257     if (in.relaPlt->getParent() == relaDyn->getParent())
1258       size += in.relaPlt->getSize();
1259     return size;
1260   };
1261 }
1262 
1263 // A Linker script may assign the RELA relocation sections to the same
1264 // output section. When this occurs we cannot just use the OutputSection
1265 // Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1266 // overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1267 static uint64_t addPltRelSz() {
1268   size_t size = in.relaPlt->getSize();
1269   if (in.relaIplt->getParent() == in.relaPlt->getParent() &&
1270       in.relaIplt->name == in.relaPlt->name)
1271     size += in.relaIplt->getSize();
1272   return size;
1273 }
1274 
1275 // Add remaining entries to complete .dynamic contents.
1276 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1277   Partition &part = getPartition();
1278   bool isMain = part.name.empty();
1279 
1280   for (StringRef s : config->filterList)
1281     addInt(DT_FILTER, part.dynStrTab->addString(s));
1282   for (StringRef s : config->auxiliaryList)
1283     addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
1284 
1285   if (!config->rpath.empty())
1286     addInt(config->enableNewDtags ? DT_RUNPATH : DT_RPATH,
1287            part.dynStrTab->addString(config->rpath));
1288 
1289   for (SharedFile *file : sharedFiles)
1290     if (file->isNeeded)
1291       addInt(DT_NEEDED, part.dynStrTab->addString(file->soName));
1292 
1293   if (isMain) {
1294     if (!config->soName.empty())
1295       addInt(DT_SONAME, part.dynStrTab->addString(config->soName));
1296   } else {
1297     if (!config->soName.empty())
1298       addInt(DT_NEEDED, part.dynStrTab->addString(config->soName));
1299     addInt(DT_SONAME, part.dynStrTab->addString(part.name));
1300   }
1301 
1302   // Set DT_FLAGS and DT_FLAGS_1.
1303   uint32_t dtFlags = 0;
1304   uint32_t dtFlags1 = 0;
1305   if (config->bsymbolic)
1306     dtFlags |= DF_SYMBOLIC;
1307   if (config->zGlobal)
1308     dtFlags1 |= DF_1_GLOBAL;
1309   if (config->zInitfirst)
1310     dtFlags1 |= DF_1_INITFIRST;
1311   if (config->zInterpose)
1312     dtFlags1 |= DF_1_INTERPOSE;
1313   if (config->zNodefaultlib)
1314     dtFlags1 |= DF_1_NODEFLIB;
1315   if (config->zNodelete)
1316     dtFlags1 |= DF_1_NODELETE;
1317   if (config->zNodlopen)
1318     dtFlags1 |= DF_1_NOOPEN;
1319   if (config->zNow) {
1320     dtFlags |= DF_BIND_NOW;
1321     dtFlags1 |= DF_1_NOW;
1322   }
1323   if (config->zOrigin) {
1324     dtFlags |= DF_ORIGIN;
1325     dtFlags1 |= DF_1_ORIGIN;
1326   }
1327   if (!config->zText)
1328     dtFlags |= DF_TEXTREL;
1329   if (config->hasStaticTlsModel)
1330     dtFlags |= DF_STATIC_TLS;
1331 
1332   if (dtFlags)
1333     addInt(DT_FLAGS, dtFlags);
1334   if (dtFlags1)
1335     addInt(DT_FLAGS_1, dtFlags1);
1336 
1337   // DT_DEBUG is a pointer to debug information used by debuggers at runtime. We
1338   // need it for each process, so we don't write it for DSOs. The loader writes
1339   // the pointer into this entry.
1340   //
1341   // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1342   // systems (currently only Fuchsia OS) provide other means to give the
1343   // debugger this information. Such systems may choose make .dynamic read-only.
1344   // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1345   if (!config->shared && !config->relocatable && !config->zRodynamic)
1346     addInt(DT_DEBUG, 0);
1347 
1348   if (OutputSection *sec = part.dynStrTab->getParent())
1349     this->link = sec->sectionIndex;
1350 
1351   if (part.relaDyn->isNeeded() ||
1352       (in.relaIplt->isNeeded() &&
1353        part.relaDyn->getParent() == in.relaIplt->getParent())) {
1354     addInSec(part.relaDyn->dynamicTag, part.relaDyn);
1355     entries.push_back({part.relaDyn->sizeDynamicTag, addRelaSz(part.relaDyn)});
1356 
1357     bool isRela = config->isRela;
1358     addInt(isRela ? DT_RELAENT : DT_RELENT,
1359            isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1360 
1361     // MIPS dynamic loader does not support RELCOUNT tag.
1362     // The problem is in the tight relation between dynamic
1363     // relocations and GOT. So do not emit this tag on MIPS.
1364     if (config->emachine != EM_MIPS) {
1365       size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
1366       if (config->zCombreloc && numRelativeRels)
1367         addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
1368     }
1369   }
1370   if (part.relrDyn && !part.relrDyn->relocs.empty()) {
1371     addInSec(config->useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1372              part.relrDyn);
1373     addSize(config->useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1374             part.relrDyn->getParent());
1375     addInt(config->useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1376            sizeof(Elf_Relr));
1377   }
1378   // .rel[a].plt section usually consists of two parts, containing plt and
1379   // iplt relocations. It is possible to have only iplt relocations in the
1380   // output. In that case relaPlt is empty and have zero offset, the same offset
1381   // as relaIplt has. And we still want to emit proper dynamic tags for that
1382   // case, so here we always use relaPlt as marker for the beginning of
1383   // .rel[a].plt section.
1384   if (isMain && (in.relaPlt->isNeeded() || in.relaIplt->isNeeded())) {
1385     addInSec(DT_JMPREL, in.relaPlt);
1386     entries.push_back({DT_PLTRELSZ, addPltRelSz});
1387     switch (config->emachine) {
1388     case EM_MIPS:
1389       addInSec(DT_MIPS_PLTGOT, in.gotPlt);
1390       break;
1391     case EM_SPARCV9:
1392       addInSec(DT_PLTGOT, in.plt);
1393       break;
1394     default:
1395       addInSec(DT_PLTGOT, in.gotPlt);
1396       break;
1397     }
1398     addInt(DT_PLTREL, config->isRela ? DT_RELA : DT_REL);
1399   }
1400 
1401   if (config->emachine == EM_AARCH64) {
1402     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1403       addInt(DT_AARCH64_BTI_PLT, 0);
1404     if (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)
1405       addInt(DT_AARCH64_PAC_PLT, 0);
1406   }
1407 
1408   addInSec(DT_SYMTAB, part.dynSymTab);
1409   addInt(DT_SYMENT, sizeof(Elf_Sym));
1410   addInSec(DT_STRTAB, part.dynStrTab);
1411   addInt(DT_STRSZ, part.dynStrTab->getSize());
1412   if (!config->zText)
1413     addInt(DT_TEXTREL, 0);
1414   if (part.gnuHashTab)
1415     addInSec(DT_GNU_HASH, part.gnuHashTab);
1416   if (part.hashTab)
1417     addInSec(DT_HASH, part.hashTab);
1418 
1419   if (isMain) {
1420     if (Out::preinitArray) {
1421       addOutSec(DT_PREINIT_ARRAY, Out::preinitArray);
1422       addSize(DT_PREINIT_ARRAYSZ, Out::preinitArray);
1423     }
1424     if (Out::initArray) {
1425       addOutSec(DT_INIT_ARRAY, Out::initArray);
1426       addSize(DT_INIT_ARRAYSZ, Out::initArray);
1427     }
1428     if (Out::finiArray) {
1429       addOutSec(DT_FINI_ARRAY, Out::finiArray);
1430       addSize(DT_FINI_ARRAYSZ, Out::finiArray);
1431     }
1432 
1433     if (Symbol *b = symtab->find(config->init))
1434       if (b->isDefined())
1435         addSym(DT_INIT, b);
1436     if (Symbol *b = symtab->find(config->fini))
1437       if (b->isDefined())
1438         addSym(DT_FINI, b);
1439   }
1440 
1441   if (part.verSym && part.verSym->isNeeded())
1442     addInSec(DT_VERSYM, part.verSym);
1443   if (part.verDef && part.verDef->isLive()) {
1444     addInSec(DT_VERDEF, part.verDef);
1445     addInt(DT_VERDEFNUM, getVerDefNum());
1446   }
1447   if (part.verNeed && part.verNeed->isNeeded()) {
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>::relocate()` 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 PltSection::PltSection()
2447     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
2448       headerSize(target->pltHeaderSize) {
2449   // On PowerPC, this section contains lazy symbol resolvers.
2450   if (config->emachine == EM_PPC || config->emachine == EM_PPC64) {
2451     name = ".glink";
2452     alignment = 4;
2453     // PLTresolve is at the end.
2454     if (config->emachine == EM_PPC)
2455       footerSize = 64;
2456   }
2457 
2458   // On x86 when IBT is enabled, this section contains the second PLT (lazy
2459   // symbol resolvers).
2460   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
2461       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT))
2462     name = ".plt.sec";
2463 
2464   // The PLT needs to be writable on SPARC as the dynamic linker will
2465   // modify the instructions in the PLT entries.
2466   if (config->emachine == EM_SPARCV9)
2467     this->flags |= SHF_WRITE;
2468 }
2469 
2470 void PltSection::writeTo(uint8_t *buf) {
2471   if (config->emachine == EM_PPC) {
2472     writePPC32GlinkSection(buf, entries.size());
2473     return;
2474   }
2475 
2476   // At beginning of PLT, we have code to call the dynamic
2477   // linker to resolve dynsyms at runtime. Write such code.
2478   target->writePltHeader(buf);
2479   size_t off = headerSize;
2480 
2481   for (const Symbol *sym : entries) {
2482     target->writePlt(buf + off, *sym, getVA() + off);
2483     off += target->pltEntrySize;
2484   }
2485 }
2486 
2487 void PltSection::addEntry(Symbol &sym) {
2488   sym.pltIndex = entries.size();
2489   entries.push_back(&sym);
2490 }
2491 
2492 size_t PltSection::getSize() const {
2493   return headerSize + entries.size() * target->pltEntrySize + footerSize;
2494 }
2495 
2496 bool PltSection::isNeeded() const {
2497   // For -z retpolineplt, .iplt needs the .plt header.
2498   return !entries.empty() || (config->zRetpolineplt && in.iplt->isNeeded());
2499 }
2500 
2501 // Used by ARM to add mapping symbols in the PLT section, which aid
2502 // disassembly.
2503 void PltSection::addSymbols() {
2504   target->addPltHeaderSymbols(*this);
2505 
2506   size_t off = headerSize;
2507   for (size_t i = 0; i < entries.size(); ++i) {
2508     target->addPltSymbols(*this, off);
2509     off += target->pltEntrySize;
2510   }
2511 }
2512 
2513 IpltSection::IpltSection()
2514     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".iplt") {
2515   if (config->emachine == EM_PPC || config->emachine == EM_PPC64) {
2516     name = ".glink";
2517     alignment = 4;
2518   }
2519 }
2520 
2521 void IpltSection::writeTo(uint8_t *buf) {
2522   uint32_t off = 0;
2523   for (const Symbol *sym : entries) {
2524     target->writeIplt(buf + off, *sym, getVA() + off);
2525     off += target->ipltEntrySize;
2526   }
2527 }
2528 
2529 size_t IpltSection::getSize() const {
2530   return entries.size() * target->ipltEntrySize;
2531 }
2532 
2533 void IpltSection::addEntry(Symbol &sym) {
2534   sym.pltIndex = entries.size();
2535   entries.push_back(&sym);
2536 }
2537 
2538 // ARM uses mapping symbols to aid disassembly.
2539 void IpltSection::addSymbols() {
2540   size_t off = 0;
2541   for (size_t i = 0, e = entries.size(); i != e; ++i) {
2542     target->addPltSymbols(*this, off);
2543     off += target->pltEntrySize;
2544   }
2545 }
2546 
2547 // This is an x86-only extra PLT section and used only when a security
2548 // enhancement feature called CET is enabled. In this comment, I'll explain what
2549 // the feature is and why we have two PLT sections if CET is enabled.
2550 //
2551 // So, what does CET do? CET introduces a new restriction to indirect jump
2552 // instructions. CET works this way. Assume that CET is enabled. Then, if you
2553 // execute an indirect jump instruction, the processor verifies that a special
2554 // "landing pad" instruction (which is actually a repurposed NOP instruction and
2555 // now called "endbr32" or "endbr64") is at the jump target. If the jump target
2556 // does not start with that instruction, the processor raises an exception
2557 // instead of continuing executing code.
2558 //
2559 // If CET is enabled, the compiler emits endbr to all locations where indirect
2560 // jumps may jump to.
2561 //
2562 // This mechanism makes it extremely hard to transfer the control to a middle of
2563 // a function that is not supporsed to be a indirect jump target, preventing
2564 // certain types of attacks such as ROP or JOP.
2565 //
2566 // Note that the processors in the market as of 2019 don't actually support the
2567 // feature. Only the spec is available at the moment.
2568 //
2569 // Now, I'll explain why we have this extra PLT section for CET.
2570 //
2571 // Since you can indirectly jump to a PLT entry, we have to make PLT entries
2572 // start with endbr. The problem is there's no extra space for endbr (which is 4
2573 // bytes long), as the PLT entry is only 16 bytes long and all bytes are already
2574 // used.
2575 //
2576 // In order to deal with the issue, we split a PLT entry into two PLT entries.
2577 // Remember that each PLT entry contains code to jump to an address read from
2578 // .got.plt AND code to resolve a dynamic symbol lazily. With the 2-PLT scheme,
2579 // the former code is written to .plt.sec, and the latter code is written to
2580 // .plt.
2581 //
2582 // Lazy symbol resolution in the 2-PLT scheme works in the usual way, except
2583 // that the regular .plt is now called .plt.sec and .plt is repurposed to
2584 // contain only code for lazy symbol resolution.
2585 //
2586 // In other words, this is how the 2-PLT scheme works. Application code is
2587 // supposed to jump to .plt.sec to call an external function. Each .plt.sec
2588 // entry contains code to read an address from a corresponding .got.plt entry
2589 // and jump to that address. Addresses in .got.plt initially point to .plt, so
2590 // when an application calls an external function for the first time, the
2591 // control is transferred to a function that resolves a symbol name from
2592 // external shared object files. That function then rewrites a .got.plt entry
2593 // with a resolved address, so that the subsequent function calls directly jump
2594 // to a desired location from .plt.sec.
2595 //
2596 // There is an open question as to whether the 2-PLT scheme was desirable or
2597 // not. We could have simply extended the PLT entry size to 32-bytes to
2598 // accommodate endbr, and that scheme would have been much simpler than the
2599 // 2-PLT scheme. One reason to split PLT was, by doing that, we could keep hot
2600 // code (.plt.sec) from cold code (.plt). But as far as I know no one proved
2601 // that the optimization actually makes a difference.
2602 //
2603 // That said, the 2-PLT scheme is a part of the ABI, debuggers and other tools
2604 // depend on it, so we implement the ABI.
2605 IBTPltSection::IBTPltSection()
2606     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt") {}
2607 
2608 void IBTPltSection::writeTo(uint8_t *buf) {
2609   target->writeIBTPlt(buf, in.plt->getNumEntries());
2610 }
2611 
2612 size_t IBTPltSection::getSize() const {
2613   // 16 is the header size of .plt.
2614   return 16 + in.plt->getNumEntries() * target->pltEntrySize;
2615 }
2616 
2617 // The string hash function for .gdb_index.
2618 static uint32_t computeGdbHash(StringRef s) {
2619   uint32_t h = 0;
2620   for (uint8_t c : s)
2621     h = h * 67 + toLower(c) - 113;
2622   return h;
2623 }
2624 
2625 GdbIndexSection::GdbIndexSection()
2626     : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index") {}
2627 
2628 // Returns the desired size of an on-disk hash table for a .gdb_index section.
2629 // There's a tradeoff between size and collision rate. We aim 75% utilization.
2630 size_t GdbIndexSection::computeSymtabSize() const {
2631   return std::max<size_t>(NextPowerOf2(symbols.size() * 4 / 3), 1024);
2632 }
2633 
2634 // Compute the output section size.
2635 void GdbIndexSection::initOutputSize() {
2636   size = sizeof(GdbIndexHeader) + computeSymtabSize() * 8;
2637 
2638   for (GdbChunk &chunk : chunks)
2639     size += chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
2640 
2641   // Add the constant pool size if exists.
2642   if (!symbols.empty()) {
2643     GdbSymbol &sym = symbols.back();
2644     size += sym.nameOff + sym.name.size() + 1;
2645   }
2646 }
2647 
2648 static std::vector<InputSection *> getDebugInfoSections() {
2649   std::vector<InputSection *> ret;
2650   for (InputSectionBase *s : inputSections)
2651     if (InputSection *isec = dyn_cast<InputSection>(s))
2652       if (isec->name == ".debug_info")
2653         ret.push_back(isec);
2654   return ret;
2655 }
2656 
2657 static std::vector<GdbIndexSection::CuEntry> readCuList(DWARFContext &dwarf) {
2658   std::vector<GdbIndexSection::CuEntry> ret;
2659   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
2660     ret.push_back({cu->getOffset(), cu->getLength() + 4});
2661   return ret;
2662 }
2663 
2664 static std::vector<GdbIndexSection::AddressEntry>
2665 readAddressAreas(DWARFContext &dwarf, InputSection *sec) {
2666   std::vector<GdbIndexSection::AddressEntry> ret;
2667 
2668   uint32_t cuIdx = 0;
2669   for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
2670     if (Error e = cu->tryExtractDIEsIfNeeded(false)) {
2671       error(toString(sec) + ": " + toString(std::move(e)));
2672       return {};
2673     }
2674     Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
2675     if (!ranges) {
2676       error(toString(sec) + ": " + toString(ranges.takeError()));
2677       return {};
2678     }
2679 
2680     ArrayRef<InputSectionBase *> sections = sec->file->getSections();
2681     for (DWARFAddressRange &r : *ranges) {
2682       if (r.SectionIndex == -1ULL)
2683         continue;
2684       InputSectionBase *s = sections[r.SectionIndex];
2685       if (!s || s == &InputSection::discarded || !s->isLive())
2686         continue;
2687       // Range list with zero size has no effect.
2688       if (r.LowPC == r.HighPC)
2689         continue;
2690       auto *isec = cast<InputSection>(s);
2691       uint64_t offset = isec->getOffsetInFile();
2692       ret.push_back({isec, r.LowPC - offset, r.HighPC - offset, cuIdx});
2693     }
2694     ++cuIdx;
2695   }
2696 
2697   return ret;
2698 }
2699 
2700 template <class ELFT>
2701 static std::vector<GdbIndexSection::NameAttrEntry>
2702 readPubNamesAndTypes(const LLDDwarfObj<ELFT> &obj,
2703                      const std::vector<GdbIndexSection::CuEntry> &cus) {
2704   const DWARFSection &pubNames = obj.getGnuPubnamesSection();
2705   const DWARFSection &pubTypes = obj.getGnuPubtypesSection();
2706 
2707   std::vector<GdbIndexSection::NameAttrEntry> ret;
2708   for (const DWARFSection *pub : {&pubNames, &pubTypes}) {
2709     DWARFDebugPubTable table(obj, *pub, config->isLE, true);
2710     for (const DWARFDebugPubTable::Set &set : table.getData()) {
2711       // The value written into the constant pool is kind << 24 | cuIndex. As we
2712       // don't know how many compilation units precede this object to compute
2713       // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
2714       // the number of preceding compilation units later.
2715       uint32_t i = llvm::partition_point(cus,
2716                                          [&](GdbIndexSection::CuEntry cu) {
2717                                            return cu.cuOffset < set.Offset;
2718                                          }) -
2719                    cus.begin();
2720       for (const DWARFDebugPubTable::Entry &ent : set.Entries)
2721         ret.push_back({{ent.Name, computeGdbHash(ent.Name)},
2722                        (ent.Descriptor.toBits() << 24) | i});
2723     }
2724   }
2725   return ret;
2726 }
2727 
2728 // Create a list of symbols from a given list of symbol names and types
2729 // by uniquifying them by name.
2730 static std::vector<GdbIndexSection::GdbSymbol>
2731 createSymbols(ArrayRef<std::vector<GdbIndexSection::NameAttrEntry>> nameAttrs,
2732               const std::vector<GdbIndexSection::GdbChunk> &chunks) {
2733   using GdbSymbol = GdbIndexSection::GdbSymbol;
2734   using NameAttrEntry = GdbIndexSection::NameAttrEntry;
2735 
2736   // For each chunk, compute the number of compilation units preceding it.
2737   uint32_t cuIdx = 0;
2738   std::vector<uint32_t> cuIdxs(chunks.size());
2739   for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
2740     cuIdxs[i] = cuIdx;
2741     cuIdx += chunks[i].compilationUnits.size();
2742   }
2743 
2744   // The number of symbols we will handle in this function is of the order
2745   // of millions for very large executables, so we use multi-threading to
2746   // speed it up.
2747   size_t numShards = 32;
2748   size_t concurrency = 1;
2749   if (threadsEnabled)
2750     concurrency = std::min<size_t>(
2751         hardware_concurrency().compute_thread_count(), numShards);
2752 
2753   // A sharded map to uniquify symbols by name.
2754   std::vector<DenseMap<CachedHashStringRef, size_t>> map(numShards);
2755   size_t shift = 32 - countTrailingZeros(numShards);
2756 
2757   // Instantiate GdbSymbols while uniqufying them by name.
2758   std::vector<std::vector<GdbSymbol>> symbols(numShards);
2759   parallelForEachN(0, concurrency, [&](size_t threadId) {
2760     uint32_t i = 0;
2761     for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
2762       for (const NameAttrEntry &ent : entries) {
2763         size_t shardId = ent.name.hash() >> shift;
2764         if ((shardId & (concurrency - 1)) != threadId)
2765           continue;
2766 
2767         uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
2768         size_t &idx = map[shardId][ent.name];
2769         if (idx) {
2770           symbols[shardId][idx - 1].cuVector.push_back(v);
2771           continue;
2772         }
2773 
2774         idx = symbols[shardId].size() + 1;
2775         symbols[shardId].push_back({ent.name, {v}, 0, 0});
2776       }
2777       ++i;
2778     }
2779   });
2780 
2781   size_t numSymbols = 0;
2782   for (ArrayRef<GdbSymbol> v : symbols)
2783     numSymbols += v.size();
2784 
2785   // The return type is a flattened vector, so we'll copy each vector
2786   // contents to Ret.
2787   std::vector<GdbSymbol> ret;
2788   ret.reserve(numSymbols);
2789   for (std::vector<GdbSymbol> &vec : symbols)
2790     for (GdbSymbol &sym : vec)
2791       ret.push_back(std::move(sym));
2792 
2793   // CU vectors and symbol names are adjacent in the output file.
2794   // We can compute their offsets in the output file now.
2795   size_t off = 0;
2796   for (GdbSymbol &sym : ret) {
2797     sym.cuVectorOff = off;
2798     off += (sym.cuVector.size() + 1) * 4;
2799   }
2800   for (GdbSymbol &sym : ret) {
2801     sym.nameOff = off;
2802     off += sym.name.size() + 1;
2803   }
2804 
2805   return ret;
2806 }
2807 
2808 // Returns a newly-created .gdb_index section.
2809 template <class ELFT> GdbIndexSection *GdbIndexSection::create() {
2810   std::vector<InputSection *> sections = getDebugInfoSections();
2811 
2812   // .debug_gnu_pub{names,types} are useless in executables.
2813   // They are present in input object files solely for creating
2814   // a .gdb_index. So we can remove them from the output.
2815   for (InputSectionBase *s : inputSections)
2816     if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
2817       s->markDead();
2818 
2819   std::vector<GdbChunk> chunks(sections.size());
2820   std::vector<std::vector<NameAttrEntry>> nameAttrs(sections.size());
2821 
2822   parallelForEachN(0, sections.size(), [&](size_t i) {
2823     ObjFile<ELFT> *file = sections[i]->getFile<ELFT>();
2824     DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
2825 
2826     chunks[i].sec = sections[i];
2827     chunks[i].compilationUnits = readCuList(dwarf);
2828     chunks[i].addressAreas = readAddressAreas(dwarf, sections[i]);
2829     nameAttrs[i] = readPubNamesAndTypes<ELFT>(
2830         static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj()),
2831         chunks[i].compilationUnits);
2832   });
2833 
2834   auto *ret = make<GdbIndexSection>();
2835   ret->chunks = std::move(chunks);
2836   ret->symbols = createSymbols(nameAttrs, ret->chunks);
2837   ret->initOutputSize();
2838   return ret;
2839 }
2840 
2841 void GdbIndexSection::writeTo(uint8_t *buf) {
2842   // Write the header.
2843   auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
2844   uint8_t *start = buf;
2845   hdr->version = 7;
2846   buf += sizeof(*hdr);
2847 
2848   // Write the CU list.
2849   hdr->cuListOff = buf - start;
2850   for (GdbChunk &chunk : chunks) {
2851     for (CuEntry &cu : chunk.compilationUnits) {
2852       write64le(buf, chunk.sec->outSecOff + cu.cuOffset);
2853       write64le(buf + 8, cu.cuLength);
2854       buf += 16;
2855     }
2856   }
2857 
2858   // Write the address area.
2859   hdr->cuTypesOff = buf - start;
2860   hdr->addressAreaOff = buf - start;
2861   uint32_t cuOff = 0;
2862   for (GdbChunk &chunk : chunks) {
2863     for (AddressEntry &e : chunk.addressAreas) {
2864       uint64_t baseAddr = e.section->getVA(0);
2865       write64le(buf, baseAddr + e.lowAddress);
2866       write64le(buf + 8, baseAddr + e.highAddress);
2867       write32le(buf + 16, e.cuIndex + cuOff);
2868       buf += 20;
2869     }
2870     cuOff += chunk.compilationUnits.size();
2871   }
2872 
2873   // Write the on-disk open-addressing hash table containing symbols.
2874   hdr->symtabOff = buf - start;
2875   size_t symtabSize = computeSymtabSize();
2876   uint32_t mask = symtabSize - 1;
2877 
2878   for (GdbSymbol &sym : symbols) {
2879     uint32_t h = sym.name.hash();
2880     uint32_t i = h & mask;
2881     uint32_t step = ((h * 17) & mask) | 1;
2882 
2883     while (read32le(buf + i * 8))
2884       i = (i + step) & mask;
2885 
2886     write32le(buf + i * 8, sym.nameOff);
2887     write32le(buf + i * 8 + 4, sym.cuVectorOff);
2888   }
2889 
2890   buf += symtabSize * 8;
2891 
2892   // Write the string pool.
2893   hdr->constantPoolOff = buf - start;
2894   parallelForEach(symbols, [&](GdbSymbol &sym) {
2895     memcpy(buf + sym.nameOff, sym.name.data(), sym.name.size());
2896   });
2897 
2898   // Write the CU vectors.
2899   for (GdbSymbol &sym : symbols) {
2900     write32le(buf, sym.cuVector.size());
2901     buf += 4;
2902     for (uint32_t val : sym.cuVector) {
2903       write32le(buf, val);
2904       buf += 4;
2905     }
2906   }
2907 }
2908 
2909 bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
2910 
2911 EhFrameHeader::EhFrameHeader()
2912     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
2913 
2914 void EhFrameHeader::writeTo(uint8_t *buf) {
2915   // Unlike most sections, the EhFrameHeader section is written while writing
2916   // another section, namely EhFrameSection, which calls the write() function
2917   // below from its writeTo() function. This is necessary because the contents
2918   // of EhFrameHeader depend on the relocated contents of EhFrameSection and we
2919   // don't know which order the sections will be written in.
2920 }
2921 
2922 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
2923 // Each entry of the search table consists of two values,
2924 // the starting PC from where FDEs covers, and the FDE's address.
2925 // It is sorted by PC.
2926 void EhFrameHeader::write() {
2927   uint8_t *buf = Out::bufferStart + getParent()->offset + outSecOff;
2928   using FdeData = EhFrameSection::FdeData;
2929 
2930   std::vector<FdeData> fdes = getPartition().ehFrame->getFdeData();
2931 
2932   buf[0] = 1;
2933   buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2934   buf[2] = DW_EH_PE_udata4;
2935   buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
2936   write32(buf + 4,
2937           getPartition().ehFrame->getParent()->addr - this->getVA() - 4);
2938   write32(buf + 8, fdes.size());
2939   buf += 12;
2940 
2941   for (FdeData &fde : fdes) {
2942     write32(buf, fde.pcRel);
2943     write32(buf + 4, fde.fdeVARel);
2944     buf += 8;
2945   }
2946 }
2947 
2948 size_t EhFrameHeader::getSize() const {
2949   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
2950   return 12 + getPartition().ehFrame->numFdes * 8;
2951 }
2952 
2953 bool EhFrameHeader::isNeeded() const {
2954   return isLive() && getPartition().ehFrame->isNeeded();
2955 }
2956 
2957 VersionDefinitionSection::VersionDefinitionSection()
2958     : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2959                        ".gnu.version_d") {}
2960 
2961 StringRef VersionDefinitionSection::getFileDefName() {
2962   if (!getPartition().name.empty())
2963     return getPartition().name;
2964   if (!config->soName.empty())
2965     return config->soName;
2966   return config->outputFile;
2967 }
2968 
2969 void VersionDefinitionSection::finalizeContents() {
2970   fileDefNameOff = getPartition().dynStrTab->addString(getFileDefName());
2971   for (const VersionDefinition &v : namedVersionDefs())
2972     verDefNameOffs.push_back(getPartition().dynStrTab->addString(v.name));
2973 
2974   if (OutputSection *sec = getPartition().dynStrTab->getParent())
2975     getParent()->link = sec->sectionIndex;
2976 
2977   // sh_info should be set to the number of definitions. This fact is missed in
2978   // documentation, but confirmed by binutils community:
2979   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
2980   getParent()->info = getVerDefNum();
2981 }
2982 
2983 void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
2984                                         StringRef name, size_t nameOff) {
2985   uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
2986 
2987   // Write a verdef.
2988   write16(buf, 1);                  // vd_version
2989   write16(buf + 2, flags);          // vd_flags
2990   write16(buf + 4, index);          // vd_ndx
2991   write16(buf + 6, 1);              // vd_cnt
2992   write32(buf + 8, hashSysV(name)); // vd_hash
2993   write32(buf + 12, 20);            // vd_aux
2994   write32(buf + 16, 28);            // vd_next
2995 
2996   // Write a veraux.
2997   write32(buf + 20, nameOff); // vda_name
2998   write32(buf + 24, 0);       // vda_next
2999 }
3000 
3001 void VersionDefinitionSection::writeTo(uint8_t *buf) {
3002   writeOne(buf, 1, getFileDefName(), fileDefNameOff);
3003 
3004   auto nameOffIt = verDefNameOffs.begin();
3005   for (const VersionDefinition &v : namedVersionDefs()) {
3006     buf += EntrySize;
3007     writeOne(buf, v.id, v.name, *nameOffIt++);
3008   }
3009 
3010   // Need to terminate the last version definition.
3011   write32(buf + 16, 0); // vd_next
3012 }
3013 
3014 size_t VersionDefinitionSection::getSize() const {
3015   return EntrySize * getVerDefNum();
3016 }
3017 
3018 // .gnu.version is a table where each entry is 2 byte long.
3019 VersionTableSection::VersionTableSection()
3020     : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
3021                        ".gnu.version") {
3022   this->entsize = 2;
3023 }
3024 
3025 void VersionTableSection::finalizeContents() {
3026   // At the moment of june 2016 GNU docs does not mention that sh_link field
3027   // should be set, but Sun docs do. Also readelf relies on this field.
3028   getParent()->link = getPartition().dynSymTab->getParent()->sectionIndex;
3029 }
3030 
3031 size_t VersionTableSection::getSize() const {
3032   return (getPartition().dynSymTab->getSymbols().size() + 1) * 2;
3033 }
3034 
3035 void VersionTableSection::writeTo(uint8_t *buf) {
3036   buf += 2;
3037   for (const SymbolTableEntry &s : getPartition().dynSymTab->getSymbols()) {
3038     write16(buf, s.sym->versionId);
3039     buf += 2;
3040   }
3041 }
3042 
3043 bool VersionTableSection::isNeeded() const {
3044   return isLive() &&
3045          (getPartition().verDef || getPartition().verNeed->isNeeded());
3046 }
3047 
3048 void addVerneed(Symbol *ss) {
3049   auto &file = cast<SharedFile>(*ss->file);
3050   if (ss->verdefIndex == VER_NDX_GLOBAL) {
3051     ss->versionId = VER_NDX_GLOBAL;
3052     return;
3053   }
3054 
3055   if (file.vernauxs.empty())
3056     file.vernauxs.resize(file.verdefs.size());
3057 
3058   // Select a version identifier for the vernaux data structure, if we haven't
3059   // already allocated one. The verdef identifiers cover the range
3060   // [1..getVerDefNum()]; this causes the vernaux identifiers to start from
3061   // getVerDefNum()+1.
3062   if (file.vernauxs[ss->verdefIndex] == 0)
3063     file.vernauxs[ss->verdefIndex] = ++SharedFile::vernauxNum + getVerDefNum();
3064 
3065   ss->versionId = file.vernauxs[ss->verdefIndex];
3066 }
3067 
3068 template <class ELFT>
3069 VersionNeedSection<ELFT>::VersionNeedSection()
3070     : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
3071                        ".gnu.version_r") {}
3072 
3073 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
3074   for (SharedFile *f : sharedFiles) {
3075     if (f->vernauxs.empty())
3076       continue;
3077     verneeds.emplace_back();
3078     Verneed &vn = verneeds.back();
3079     vn.nameStrTab = getPartition().dynStrTab->addString(f->soName);
3080     for (unsigned i = 0; i != f->vernauxs.size(); ++i) {
3081       if (f->vernauxs[i] == 0)
3082         continue;
3083       auto *verdef =
3084           reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
3085       vn.vernauxs.push_back(
3086           {verdef->vd_hash, f->vernauxs[i],
3087            getPartition().dynStrTab->addString(f->getStringTable().data() +
3088                                                verdef->getAux()->vda_name)});
3089     }
3090   }
3091 
3092   if (OutputSection *sec = getPartition().dynStrTab->getParent())
3093     getParent()->link = sec->sectionIndex;
3094   getParent()->info = verneeds.size();
3095 }
3096 
3097 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
3098   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
3099   auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
3100   auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
3101 
3102   for (auto &vn : verneeds) {
3103     // Create an Elf_Verneed for this DSO.
3104     verneed->vn_version = 1;
3105     verneed->vn_cnt = vn.vernauxs.size();
3106     verneed->vn_file = vn.nameStrTab;
3107     verneed->vn_aux =
3108         reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
3109     verneed->vn_next = sizeof(Elf_Verneed);
3110     ++verneed;
3111 
3112     // Create the Elf_Vernauxs for this Elf_Verneed.
3113     for (auto &vna : vn.vernauxs) {
3114       vernaux->vna_hash = vna.hash;
3115       vernaux->vna_flags = 0;
3116       vernaux->vna_other = vna.verneedIndex;
3117       vernaux->vna_name = vna.nameStrTab;
3118       vernaux->vna_next = sizeof(Elf_Vernaux);
3119       ++vernaux;
3120     }
3121 
3122     vernaux[-1].vna_next = 0;
3123   }
3124   verneed[-1].vn_next = 0;
3125 }
3126 
3127 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
3128   return verneeds.size() * sizeof(Elf_Verneed) +
3129          SharedFile::vernauxNum * sizeof(Elf_Vernaux);
3130 }
3131 
3132 template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
3133   return isLive() && SharedFile::vernauxNum != 0;
3134 }
3135 
3136 void MergeSyntheticSection::addSection(MergeInputSection *ms) {
3137   ms->parent = this;
3138   sections.push_back(ms);
3139   assert(alignment == ms->alignment || !(ms->flags & SHF_STRINGS));
3140   alignment = std::max(alignment, ms->alignment);
3141 }
3142 
3143 MergeTailSection::MergeTailSection(StringRef name, uint32_t type,
3144                                    uint64_t flags, uint32_t alignment)
3145     : MergeSyntheticSection(name, type, flags, alignment),
3146       builder(StringTableBuilder::RAW, alignment) {}
3147 
3148 size_t MergeTailSection::getSize() const { return builder.getSize(); }
3149 
3150 void MergeTailSection::writeTo(uint8_t *buf) { builder.write(buf); }
3151 
3152 void MergeTailSection::finalizeContents() {
3153   // Add all string pieces to the string table builder to create section
3154   // contents.
3155   for (MergeInputSection *sec : sections)
3156     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3157       if (sec->pieces[i].live)
3158         builder.add(sec->getData(i));
3159 
3160   // Fix the string table content. After this, the contents will never change.
3161   builder.finalize();
3162 
3163   // finalize() fixed tail-optimized strings, so we can now get
3164   // offsets of strings. Get an offset for each string and save it
3165   // to a corresponding SectionPiece for easy access.
3166   for (MergeInputSection *sec : sections)
3167     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3168       if (sec->pieces[i].live)
3169         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
3170 }
3171 
3172 void MergeNoTailSection::writeTo(uint8_t *buf) {
3173   for (size_t i = 0; i < numShards; ++i)
3174     shards[i].write(buf + shardOffsets[i]);
3175 }
3176 
3177 // This function is very hot (i.e. it can take several seconds to finish)
3178 // because sometimes the number of inputs is in an order of magnitude of
3179 // millions. So, we use multi-threading.
3180 //
3181 // For any strings S and T, we know S is not mergeable with T if S's hash
3182 // value is different from T's. If that's the case, we can safely put S and
3183 // T into different string builders without worrying about merge misses.
3184 // We do it in parallel.
3185 void MergeNoTailSection::finalizeContents() {
3186   // Initializes string table builders.
3187   for (size_t i = 0; i < numShards; ++i)
3188     shards.emplace_back(StringTableBuilder::RAW, alignment);
3189 
3190   // Concurrency level. Must be a power of 2 to avoid expensive modulo
3191   // operations in the following tight loop.
3192   size_t concurrency = 1;
3193   if (threadsEnabled)
3194     concurrency = std::min<size_t>(
3195         hardware_concurrency().compute_thread_count(), numShards);
3196 
3197   // Add section pieces to the builders.
3198   parallelForEachN(0, concurrency, [&](size_t threadId) {
3199     for (MergeInputSection *sec : sections) {
3200       for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
3201         if (!sec->pieces[i].live)
3202           continue;
3203         size_t shardId = getShardId(sec->pieces[i].hash);
3204         if ((shardId & (concurrency - 1)) == threadId)
3205           sec->pieces[i].outputOff = shards[shardId].add(sec->getData(i));
3206       }
3207     }
3208   });
3209 
3210   // Compute an in-section offset for each shard.
3211   size_t off = 0;
3212   for (size_t i = 0; i < numShards; ++i) {
3213     shards[i].finalizeInOrder();
3214     if (shards[i].getSize() > 0)
3215       off = alignTo(off, alignment);
3216     shardOffsets[i] = off;
3217     off += shards[i].getSize();
3218   }
3219   size = off;
3220 
3221   // So far, section pieces have offsets from beginning of shards, but
3222   // we want offsets from beginning of the whole section. Fix them.
3223   parallelForEach(sections, [&](MergeInputSection *sec) {
3224     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3225       if (sec->pieces[i].live)
3226         sec->pieces[i].outputOff +=
3227             shardOffsets[getShardId(sec->pieces[i].hash)];
3228   });
3229 }
3230 
3231 MergeSyntheticSection *createMergeSynthetic(StringRef name, uint32_t type,
3232                                             uint64_t flags,
3233                                             uint32_t alignment) {
3234   bool shouldTailMerge = (flags & SHF_STRINGS) && config->optimize >= 2;
3235   if (shouldTailMerge)
3236     return make<MergeTailSection>(name, type, flags, alignment);
3237   return make<MergeNoTailSection>(name, type, flags, alignment);
3238 }
3239 
3240 template <class ELFT> void splitSections() {
3241   llvm::TimeTraceScope timeScope("Split sections");
3242   // splitIntoPieces needs to be called on each MergeInputSection
3243   // before calling finalizeContents().
3244   parallelForEach(inputSections, [](InputSectionBase *sec) {
3245     if (auto *s = dyn_cast<MergeInputSection>(sec))
3246       s->splitIntoPieces();
3247     else if (auto *eh = dyn_cast<EhInputSection>(sec))
3248       eh->split<ELFT>();
3249   });
3250 }
3251 
3252 MipsRldMapSection::MipsRldMapSection()
3253     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, config->wordsize,
3254                        ".rld_map") {}
3255 
3256 ARMExidxSyntheticSection::ARMExidxSyntheticSection()
3257     : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
3258                        config->wordsize, ".ARM.exidx") {}
3259 
3260 static InputSection *findExidxSection(InputSection *isec) {
3261   for (InputSection *d : isec->dependentSections)
3262     if (d->type == SHT_ARM_EXIDX)
3263       return d;
3264   return nullptr;
3265 }
3266 
3267 static bool isValidExidxSectionDep(InputSection *isec) {
3268   return (isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
3269          isec->getSize() > 0;
3270 }
3271 
3272 bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
3273   if (isec->type == SHT_ARM_EXIDX) {
3274     if (InputSection *dep = isec->getLinkOrderDep())
3275       if (isValidExidxSectionDep(dep))
3276         exidxSections.push_back(isec);
3277     return true;
3278   }
3279 
3280   if (isValidExidxSectionDep(isec)) {
3281     executableSections.push_back(isec);
3282     return false;
3283   }
3284 
3285   // FIXME: we do not output a relocation section when --emit-relocs is used
3286   // as we do not have relocation sections for linker generated table entries
3287   // and we would have to erase at a late stage relocations from merged entries.
3288   // Given that exception tables are already position independent and a binary
3289   // analyzer could derive the relocations we choose to erase the relocations.
3290   if (config->emitRelocs && isec->type == SHT_REL)
3291     if (InputSectionBase *ex = isec->getRelocatedSection())
3292       if (isa<InputSection>(ex) && ex->type == SHT_ARM_EXIDX)
3293         return true;
3294 
3295   return false;
3296 }
3297 
3298 // References to .ARM.Extab Sections have bit 31 clear and are not the
3299 // special EXIDX_CANTUNWIND bit-pattern.
3300 static bool isExtabRef(uint32_t unwind) {
3301   return (unwind & 0x80000000) == 0 && unwind != 0x1;
3302 }
3303 
3304 // Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
3305 // section Prev, where Cur follows Prev in the table. This can be done if the
3306 // unwinding instructions in Cur are identical to Prev. Linker generated
3307 // EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
3308 // InputSection.
3309 static bool isDuplicateArmExidxSec(InputSection *prev, InputSection *cur) {
3310 
3311   struct ExidxEntry {
3312     ulittle32_t fn;
3313     ulittle32_t unwind;
3314   };
3315   // Get the last table Entry from the previous .ARM.exidx section. If Prev is
3316   // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
3317   ExidxEntry prevEntry = {ulittle32_t(0), ulittle32_t(1)};
3318   if (prev)
3319     prevEntry = prev->getDataAs<ExidxEntry>().back();
3320   if (isExtabRef(prevEntry.unwind))
3321     return false;
3322 
3323   // We consider the unwind instructions of an .ARM.exidx table entry
3324   // a duplicate if the previous unwind instructions if:
3325   // - Both are the special EXIDX_CANTUNWIND.
3326   // - Both are the same inline unwind instructions.
3327   // We do not attempt to follow and check links into .ARM.extab tables as
3328   // consecutive identical entries are rare and the effort to check that they
3329   // are identical is high.
3330 
3331   // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
3332   if (cur == nullptr)
3333     return prevEntry.unwind == 1;
3334 
3335   for (const ExidxEntry entry : cur->getDataAs<ExidxEntry>())
3336     if (isExtabRef(entry.unwind) || entry.unwind != prevEntry.unwind)
3337       return false;
3338 
3339   // All table entries in this .ARM.exidx Section can be merged into the
3340   // previous Section.
3341   return true;
3342 }
3343 
3344 // The .ARM.exidx table must be sorted in ascending order of the address of the
3345 // functions the table describes. Optionally duplicate adjacent table entries
3346 // can be removed. At the end of the function the executableSections must be
3347 // sorted in ascending order of address, Sentinel is set to the InputSection
3348 // with the highest address and any InputSections that have mergeable
3349 // .ARM.exidx table entries are removed from it.
3350 void ARMExidxSyntheticSection::finalizeContents() {
3351   // The executableSections and exidxSections that we use to derive the final
3352   // contents of this SyntheticSection are populated before
3353   // processSectionCommands() and ICF. A /DISCARD/ entry in SECTIONS command or
3354   // ICF may remove executable InputSections and their dependent .ARM.exidx
3355   // section that we recorded earlier.
3356   auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
3357   llvm::erase_if(executableSections, isDiscarded);
3358   llvm::erase_if(exidxSections, isDiscarded);
3359 
3360   // Sort the executable sections that may or may not have associated
3361   // .ARM.exidx sections by order of ascending address. This requires the
3362   // relative positions of InputSections to be known.
3363   auto compareByFilePosition = [](const InputSection *a,
3364                                   const InputSection *b) {
3365     OutputSection *aOut = a->getParent();
3366     OutputSection *bOut = b->getParent();
3367 
3368     if (aOut != bOut)
3369       return aOut->sectionIndex < bOut->sectionIndex;
3370     return a->outSecOff < b->outSecOff;
3371   };
3372   llvm::stable_sort(executableSections, compareByFilePosition);
3373   sentinel = executableSections.back();
3374   // Optionally merge adjacent duplicate entries.
3375   if (config->mergeArmExidx) {
3376     std::vector<InputSection *> selectedSections;
3377     selectedSections.reserve(executableSections.size());
3378     selectedSections.push_back(executableSections[0]);
3379     size_t prev = 0;
3380     for (size_t i = 1; i < executableSections.size(); ++i) {
3381       InputSection *ex1 = findExidxSection(executableSections[prev]);
3382       InputSection *ex2 = findExidxSection(executableSections[i]);
3383       if (!isDuplicateArmExidxSec(ex1, ex2)) {
3384         selectedSections.push_back(executableSections[i]);
3385         prev = i;
3386       }
3387     }
3388     executableSections = std::move(selectedSections);
3389   }
3390 
3391   size_t offset = 0;
3392   size = 0;
3393   for (InputSection *isec : executableSections) {
3394     if (InputSection *d = findExidxSection(isec)) {
3395       d->outSecOff = offset;
3396       d->parent = getParent();
3397       offset += d->getSize();
3398     } else {
3399       offset += 8;
3400     }
3401   }
3402   // Size includes Sentinel.
3403   size = offset + 8;
3404 }
3405 
3406 InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
3407   return executableSections.front();
3408 }
3409 
3410 // To write the .ARM.exidx table from the ExecutableSections we have three cases
3411 // 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
3412 //     We write the .ARM.exidx section contents and apply its relocations.
3413 // 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
3414 //     must write the contents of an EXIDX_CANTUNWIND directly. We use the
3415 //     start of the InputSection as the purpose of the linker generated
3416 //     section is to terminate the address range of the previous entry.
3417 // 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
3418 //     the table to terminate the address range of the final entry.
3419 void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
3420 
3421   const uint8_t cantUnwindData[8] = {0, 0, 0, 0,  // PREL31 to target
3422                                      1, 0, 0, 0}; // EXIDX_CANTUNWIND
3423 
3424   uint64_t offset = 0;
3425   for (InputSection *isec : executableSections) {
3426     assert(isec->getParent() != nullptr);
3427     if (InputSection *d = findExidxSection(isec)) {
3428       memcpy(buf + offset, d->data().data(), d->data().size());
3429       d->relocateAlloc(buf, buf + d->getSize());
3430       offset += d->getSize();
3431     } else {
3432       // A Linker generated CANTUNWIND section.
3433       memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3434       uint64_t s = isec->getVA();
3435       uint64_t p = getVA() + offset;
3436       target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3437       offset += 8;
3438     }
3439   }
3440   // Write Sentinel.
3441   memcpy(buf + offset, cantUnwindData, sizeof(cantUnwindData));
3442   uint64_t s = sentinel->getVA(sentinel->getSize());
3443   uint64_t p = getVA() + offset;
3444   target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
3445   assert(size == offset + 8);
3446 }
3447 
3448 bool ARMExidxSyntheticSection::isNeeded() const {
3449   return llvm::find_if(exidxSections, [](InputSection *isec) {
3450            return isec->isLive();
3451          }) != exidxSections.end();
3452 }
3453 
3454 bool ARMExidxSyntheticSection::classof(const SectionBase *d) {
3455   return d->kind() == InputSectionBase::Synthetic && d->type == SHT_ARM_EXIDX;
3456 }
3457 
3458 ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
3459     : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 4,
3460                        ".text.thunk") {
3461   this->parent = os;
3462   this->outSecOff = off;
3463 }
3464 
3465 size_t ThunkSection::getSize() const {
3466   if (roundUpSizeForErrata)
3467     return alignTo(size, 4096);
3468   return size;
3469 }
3470 
3471 void ThunkSection::addThunk(Thunk *t) {
3472   thunks.push_back(t);
3473   t->addSymbols(*this);
3474 }
3475 
3476 void ThunkSection::writeTo(uint8_t *buf) {
3477   for (Thunk *t : thunks)
3478     t->writeTo(buf + t->offset);
3479 }
3480 
3481 InputSection *ThunkSection::getTargetInputSection() const {
3482   if (thunks.empty())
3483     return nullptr;
3484   const Thunk *t = thunks.front();
3485   return t->getTargetInputSection();
3486 }
3487 
3488 bool ThunkSection::assignOffsets() {
3489   uint64_t off = 0;
3490   for (Thunk *t : thunks) {
3491     off = alignTo(off, t->alignment);
3492     t->setOffset(off);
3493     uint32_t size = t->size();
3494     t->getThunkTargetSym()->size = size;
3495     off += size;
3496   }
3497   bool changed = off != size;
3498   size = off;
3499   return changed;
3500 }
3501 
3502 PPC32Got2Section::PPC32Got2Section()
3503     : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 4, ".got2") {}
3504 
3505 bool PPC32Got2Section::isNeeded() const {
3506   // See the comment below. This is not needed if there is no other
3507   // InputSection.
3508   for (BaseCommand *base : getParent()->sectionCommands)
3509     if (auto *isd = dyn_cast<InputSectionDescription>(base))
3510       for (InputSection *isec : isd->sections)
3511         if (isec != this)
3512           return true;
3513   return false;
3514 }
3515 
3516 void PPC32Got2Section::finalizeContents() {
3517   // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
3518   // .got2 . This function computes outSecOff of each .got2 to be used in
3519   // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
3520   // to collect input sections named ".got2".
3521   uint32_t offset = 0;
3522   for (BaseCommand *base : getParent()->sectionCommands)
3523     if (auto *isd = dyn_cast<InputSectionDescription>(base)) {
3524       for (InputSection *isec : isd->sections) {
3525         if (isec == this)
3526           continue;
3527         isec->file->ppc32Got2OutSecOff = offset;
3528         offset += (uint32_t)isec->getSize();
3529       }
3530     }
3531 }
3532 
3533 // If linking position-dependent code then the table will store the addresses
3534 // directly in the binary so the section has type SHT_PROGBITS. If linking
3535 // position-independent code the section has type SHT_NOBITS since it will be
3536 // allocated and filled in by the dynamic linker.
3537 PPC64LongBranchTargetSection::PPC64LongBranchTargetSection()
3538     : SyntheticSection(SHF_ALLOC | SHF_WRITE,
3539                        config->isPic ? SHT_NOBITS : SHT_PROGBITS, 8,
3540                        ".branch_lt") {}
3541 
3542 uint64_t PPC64LongBranchTargetSection::getEntryVA(const Symbol *sym,
3543                                                   int64_t addend) {
3544   return getVA() + entry_index.find({sym, addend})->second * 8;
3545 }
3546 
3547 Optional<uint32_t> PPC64LongBranchTargetSection::addEntry(const Symbol *sym,
3548                                                           int64_t addend) {
3549   auto res =
3550       entry_index.try_emplace(std::make_pair(sym, addend), entries.size());
3551   if (!res.second)
3552     return None;
3553   entries.emplace_back(sym, addend);
3554   return res.first->second;
3555 }
3556 
3557 size_t PPC64LongBranchTargetSection::getSize() const {
3558   return entries.size() * 8;
3559 }
3560 
3561 void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
3562   // If linking non-pic we have the final addresses of the targets and they get
3563   // written to the table directly. For pic the dynamic linker will allocate
3564   // the section and fill it it.
3565   if (config->isPic)
3566     return;
3567 
3568   for (auto entry : entries) {
3569     const Symbol *sym = entry.first;
3570     int64_t addend = entry.second;
3571     assert(sym->getVA());
3572     // Need calls to branch to the local entry-point since a long-branch
3573     // must be a local-call.
3574     write64(buf, sym->getVA(addend) +
3575                      getPPC64GlobalEntryToLocalEntryOffset(sym->stOther));
3576     buf += 8;
3577   }
3578 }
3579 
3580 bool PPC64LongBranchTargetSection::isNeeded() const {
3581   // `removeUnusedSyntheticSections()` is called before thunk allocation which
3582   // is too early to determine if this section will be empty or not. We need
3583   // Finalized to keep the section alive until after thunk creation. Finalized
3584   // only gets set to true once `finalizeSections()` is called after thunk
3585   // creation. Because of this, if we don't create any long-branch thunks we end
3586   // up with an empty .branch_lt section in the binary.
3587   return !finalized || !entries.empty();
3588 }
3589 
3590 static uint8_t getAbiVersion() {
3591   // MIPS non-PIC executable gets ABI version 1.
3592   if (config->emachine == EM_MIPS) {
3593     if (!config->isPic && !config->relocatable &&
3594         (config->eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
3595       return 1;
3596     return 0;
3597   }
3598 
3599   if (config->emachine == EM_AMDGPU) {
3600     uint8_t ver = objectFiles[0]->abiVersion;
3601     for (InputFile *file : makeArrayRef(objectFiles).slice(1))
3602       if (file->abiVersion != ver)
3603         error("incompatible ABI version: " + toString(file));
3604     return ver;
3605   }
3606 
3607   return 0;
3608 }
3609 
3610 template <typename ELFT> void writeEhdr(uint8_t *buf, Partition &part) {
3611   // For executable segments, the trap instructions are written before writing
3612   // the header. Setting Elf header bytes to zero ensures that any unused bytes
3613   // in header are zero-cleared, instead of having trap instructions.
3614   memset(buf, 0, sizeof(typename ELFT::Ehdr));
3615   memcpy(buf, "\177ELF", 4);
3616 
3617   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3618   eHdr->e_ident[EI_CLASS] = config->is64 ? ELFCLASS64 : ELFCLASS32;
3619   eHdr->e_ident[EI_DATA] = config->isLE ? ELFDATA2LSB : ELFDATA2MSB;
3620   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
3621   eHdr->e_ident[EI_OSABI] = config->osabi;
3622   eHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
3623   eHdr->e_machine = config->emachine;
3624   eHdr->e_version = EV_CURRENT;
3625   eHdr->e_flags = config->eflags;
3626   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
3627   eHdr->e_phnum = part.phdrs.size();
3628   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
3629 
3630   if (!config->relocatable) {
3631     eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
3632     eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
3633   }
3634 }
3635 
3636 template <typename ELFT> void writePhdrs(uint8_t *buf, Partition &part) {
3637   // Write the program header table.
3638   auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
3639   for (PhdrEntry *p : part.phdrs) {
3640     hBuf->p_type = p->p_type;
3641     hBuf->p_flags = p->p_flags;
3642     hBuf->p_offset = p->p_offset;
3643     hBuf->p_vaddr = p->p_vaddr;
3644     hBuf->p_paddr = p->p_paddr;
3645     hBuf->p_filesz = p->p_filesz;
3646     hBuf->p_memsz = p->p_memsz;
3647     hBuf->p_align = p->p_align;
3648     ++hBuf;
3649   }
3650 }
3651 
3652 template <typename ELFT>
3653 PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection()
3654     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_EHDR, 1, "") {}
3655 
3656 template <typename ELFT>
3657 size_t PartitionElfHeaderSection<ELFT>::getSize() const {
3658   return sizeof(typename ELFT::Ehdr);
3659 }
3660 
3661 template <typename ELFT>
3662 void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
3663   writeEhdr<ELFT>(buf, getPartition());
3664 
3665   // Loadable partitions are always ET_DYN.
3666   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
3667   eHdr->e_type = ET_DYN;
3668 }
3669 
3670 template <typename ELFT>
3671 PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection()
3672     : SyntheticSection(SHF_ALLOC, SHT_LLVM_PART_PHDR, 1, ".phdrs") {}
3673 
3674 template <typename ELFT>
3675 size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
3676   return sizeof(typename ELFT::Phdr) * getPartition().phdrs.size();
3677 }
3678 
3679 template <typename ELFT>
3680 void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
3681   writePhdrs<ELFT>(buf, getPartition());
3682 }
3683 
3684 PartitionIndexSection::PartitionIndexSection()
3685     : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".rodata") {}
3686 
3687 size_t PartitionIndexSection::getSize() const {
3688   return 12 * (partitions.size() - 1);
3689 }
3690 
3691 void PartitionIndexSection::finalizeContents() {
3692   for (size_t i = 1; i != partitions.size(); ++i)
3693     partitions[i].nameStrTab = mainPart->dynStrTab->addString(partitions[i].name);
3694 }
3695 
3696 void PartitionIndexSection::writeTo(uint8_t *buf) {
3697   uint64_t va = getVA();
3698   for (size_t i = 1; i != partitions.size(); ++i) {
3699     write32(buf, mainPart->dynStrTab->getVA() + partitions[i].nameStrTab - va);
3700     write32(buf + 4, partitions[i].elfHeader->getVA() - (va + 4));
3701 
3702     SyntheticSection *next =
3703         i == partitions.size() - 1 ? in.partEnd : partitions[i + 1].elfHeader;
3704     write32(buf + 8, next->getVA() - partitions[i].elfHeader->getVA());
3705 
3706     va += 12;
3707     buf += 12;
3708   }
3709 }
3710 
3711 InStruct in;
3712 
3713 std::vector<Partition> partitions;
3714 Partition *mainPart;
3715 
3716 template GdbIndexSection *GdbIndexSection::create<ELF32LE>();
3717 template GdbIndexSection *GdbIndexSection::create<ELF32BE>();
3718 template GdbIndexSection *GdbIndexSection::create<ELF64LE>();
3719 template GdbIndexSection *GdbIndexSection::create<ELF64BE>();
3720 
3721 template void splitSections<ELF32LE>();
3722 template void splitSections<ELF32BE>();
3723 template void splitSections<ELF64LE>();
3724 template void splitSections<ELF64BE>();
3725 
3726 template class MipsAbiFlagsSection<ELF32LE>;
3727 template class MipsAbiFlagsSection<ELF32BE>;
3728 template class MipsAbiFlagsSection<ELF64LE>;
3729 template class MipsAbiFlagsSection<ELF64BE>;
3730 
3731 template class MipsOptionsSection<ELF32LE>;
3732 template class MipsOptionsSection<ELF32BE>;
3733 template class MipsOptionsSection<ELF64LE>;
3734 template class MipsOptionsSection<ELF64BE>;
3735 
3736 template class MipsReginfoSection<ELF32LE>;
3737 template class MipsReginfoSection<ELF32BE>;
3738 template class MipsReginfoSection<ELF64LE>;
3739 template class MipsReginfoSection<ELF64BE>;
3740 
3741 template class DynamicSection<ELF32LE>;
3742 template class DynamicSection<ELF32BE>;
3743 template class DynamicSection<ELF64LE>;
3744 template class DynamicSection<ELF64BE>;
3745 
3746 template class RelocationSection<ELF32LE>;
3747 template class RelocationSection<ELF32BE>;
3748 template class RelocationSection<ELF64LE>;
3749 template class RelocationSection<ELF64BE>;
3750 
3751 template class AndroidPackedRelocationSection<ELF32LE>;
3752 template class AndroidPackedRelocationSection<ELF32BE>;
3753 template class AndroidPackedRelocationSection<ELF64LE>;
3754 template class AndroidPackedRelocationSection<ELF64BE>;
3755 
3756 template class RelrSection<ELF32LE>;
3757 template class RelrSection<ELF32BE>;
3758 template class RelrSection<ELF64LE>;
3759 template class RelrSection<ELF64BE>;
3760 
3761 template class SymbolTableSection<ELF32LE>;
3762 template class SymbolTableSection<ELF32BE>;
3763 template class SymbolTableSection<ELF64LE>;
3764 template class SymbolTableSection<ELF64BE>;
3765 
3766 template class VersionNeedSection<ELF32LE>;
3767 template class VersionNeedSection<ELF32BE>;
3768 template class VersionNeedSection<ELF64LE>;
3769 template class VersionNeedSection<ELF64BE>;
3770 
3771 template void writeEhdr<ELF32LE>(uint8_t *Buf, Partition &Part);
3772 template void writeEhdr<ELF32BE>(uint8_t *Buf, Partition &Part);
3773 template void writeEhdr<ELF64LE>(uint8_t *Buf, Partition &Part);
3774 template void writeEhdr<ELF64BE>(uint8_t *Buf, Partition &Part);
3775 
3776 template void writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
3777 template void writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
3778 template void writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
3779 template void writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
3780 
3781 template class PartitionElfHeaderSection<ELF32LE>;
3782 template class PartitionElfHeaderSection<ELF32BE>;
3783 template class PartitionElfHeaderSection<ELF64LE>;
3784 template class PartitionElfHeaderSection<ELF64BE>;
3785 
3786 template class PartitionProgramHeadersSection<ELF32LE>;
3787 template class PartitionProgramHeadersSection<ELF32BE>;
3788 template class PartitionProgramHeadersSection<ELF64LE>;
3789 template class PartitionProgramHeadersSection<ELF64BE>;
3790 
3791 } // namespace elf
3792 } // namespace lld
3793