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