1//===- SyntheticSections.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains linker-synthesized sections. Currently,
10// synthetic sections are created either output sections or input sections,
11// but we are rewriting code so that all synthetic sections are created as
12// input sections.
13//
14//===----------------------------------------------------------------------===//
15
16#include "SyntheticSections.h"
17#include "Config.h"
18#include "DWARF.h"
19#include "EhFrame.h"
20#include "InputFiles.h"
21#include "LinkerScript.h"
22#include "OutputSections.h"
23#include "SymbolTable.h"
24#include "Symbols.h"
25#include "Target.h"
26#include "Thunks.h"
27#include "Writer.h"
28#include "lld/Common/Version.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Sequence.h"
31#include "llvm/ADT/SetOperations.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/BinaryFormat/Dwarf.h"
34#include "llvm/BinaryFormat/ELF.h"
35#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
36#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
37#include "llvm/Support/DJB.h"
38#include "llvm/Support/Endian.h"
39#include "llvm/Support/LEB128.h"
40#include "llvm/Support/Parallel.h"
41#include "llvm/Support/TimeProfiler.h"
42#include <cinttypes>
43#include <cstdlib>
44
45using namespace llvm;
46using namespace llvm::dwarf;
47using namespace llvm::ELF;
48using namespace llvm::object;
49using namespace llvm::support;
50using namespace lld;
51using namespace lld::elf;
52
53using llvm::support::endian::read32le;
54using llvm::support::endian::write32le;
55using llvm::support::endian::write64le;
56
57static uint64_t readUint(Ctx &ctx, uint8_t *buf) {
58 return ctx.arg.is64 ? read64(ctx, p: buf) : read32(ctx, p: buf);
59}
60
61static void writeUint(Ctx &ctx, uint8_t *buf, uint64_t val) {
62 if (ctx.arg.is64)
63 write64(ctx, p: buf, v: val);
64 else
65 write32(ctx, p: buf, v: val);
66}
67
68// Returns an LLD version string.
69static ArrayRef<uint8_t> getVersion(Ctx &ctx) {
70 // Check LLD_VERSION first for ease of testing.
71 // You can get consistent output by using the environment variable.
72 // This is only for testing.
73 StringRef s = getenv(name: "LLD_VERSION");
74 if (s.empty())
75 s = ctx.saver.save(S: Twine("Linker: ") + getLLDVersion());
76
77 // +1 to include the terminating '\0'.
78 return {(const uint8_t *)s.data(), s.size() + 1};
79}
80
81// Creates a .comment section containing LLD version info.
82// With this feature, you can identify LLD-generated binaries easily
83// by "readelf --string-dump .comment <file>".
84// The returned object is a mergeable string section.
85MergeInputSection *elf::createCommentSection(Ctx &ctx) {
86 auto *sec =
87 make<MergeInputSection>(args&: ctx, args: ".comment", args: SHT_PROGBITS,
88 args: SHF_MERGE | SHF_STRINGS, args: 1, args: getVersion(ctx));
89 sec->splitIntoPieces();
90 return sec;
91}
92
93// .MIPS.abiflags section.
94template <class ELFT>
95MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Ctx &ctx,
96 Elf_Mips_ABIFlags flags)
97 : SyntheticSection(ctx, ".MIPS.abiflags", SHT_MIPS_ABIFLAGS, SHF_ALLOC, 8),
98 flags(flags) {
99 this->entsize = sizeof(Elf_Mips_ABIFlags);
100}
101
102template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *buf) {
103 memcpy(buf, &flags, sizeof(flags));
104}
105
106template <class ELFT>
107std::unique_ptr<MipsAbiFlagsSection<ELFT>>
108MipsAbiFlagsSection<ELFT>::create(Ctx &ctx) {
109 Elf_Mips_ABIFlags flags = {};
110 bool create = false;
111
112 for (InputSectionBase *sec : ctx.inputSections) {
113 if (sec->type != SHT_MIPS_ABIFLAGS)
114 continue;
115 sec->markDead();
116 create = true;
117
118 const size_t size = sec->content().size();
119 // Older version of BFD (such as the default FreeBSD linker) concatenate
120 // .MIPS.abiflags instead of merging. To allow for this case (or potential
121 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
122 if (size < sizeof(Elf_Mips_ABIFlags)) {
123 Err(ctx) << sec->file << ": invalid size of .MIPS.abiflags section: got "
124 << size << " instead of " << sizeof(Elf_Mips_ABIFlags);
125 return nullptr;
126 }
127 auto *s =
128 reinterpret_cast<const Elf_Mips_ABIFlags *>(sec->content().data());
129 if (s->version != 0) {
130 Err(ctx) << sec->file << ": unexpected .MIPS.abiflags version "
131 << s->version;
132 return nullptr;
133 }
134
135 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
136 // select the highest number of ISA/Rev/Ext.
137 flags.isa_level = std::max(flags.isa_level, s->isa_level);
138 flags.isa_rev = std::max(flags.isa_rev, s->isa_rev);
139 flags.isa_ext = std::max(flags.isa_ext, s->isa_ext);
140 flags.gpr_size = std::max(flags.gpr_size, s->gpr_size);
141 flags.cpr1_size = std::max(flags.cpr1_size, s->cpr1_size);
142 flags.cpr2_size = std::max(flags.cpr2_size, s->cpr2_size);
143 flags.ases |= s->ases;
144 flags.flags1 |= s->flags1;
145 flags.flags2 |= s->flags2;
146 flags.fp_abi =
147 elf::getMipsFpAbiFlag(ctx, file: sec->file, oldFlag: flags.fp_abi, newFlag: s->fp_abi);
148 };
149
150 if (create)
151 return std::make_unique<MipsAbiFlagsSection<ELFT>>(ctx, flags);
152 return nullptr;
153}
154
155// .MIPS.options section.
156template <class ELFT>
157MipsOptionsSection<ELFT>::MipsOptionsSection(Ctx &ctx, Elf_Mips_RegInfo reginfo)
158 : SyntheticSection(ctx, ".MIPS.options", SHT_MIPS_OPTIONS, SHF_ALLOC, 8),
159 reginfo(reginfo) {
160 this->entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
161}
162
163template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *buf) {
164 auto *options = reinterpret_cast<Elf_Mips_Options *>(buf);
165 options->kind = ODK_REGINFO;
166 options->size = getSize();
167
168 if (!ctx.arg.relocatable)
169 reginfo.ri_gp_value = ctx.in.mipsGot->getGp();
170 memcpy(buf + sizeof(Elf_Mips_Options), &reginfo, sizeof(reginfo));
171}
172
173template <class ELFT>
174std::unique_ptr<MipsOptionsSection<ELFT>>
175MipsOptionsSection<ELFT>::create(Ctx &ctx) {
176 // N64 ABI only.
177 if (!ELFT::Is64Bits)
178 return nullptr;
179
180 SmallVector<InputSectionBase *, 0> sections;
181 for (InputSectionBase *sec : ctx.inputSections)
182 if (sec->type == SHT_MIPS_OPTIONS)
183 sections.push_back(Elt: sec);
184
185 if (sections.empty())
186 return nullptr;
187
188 Elf_Mips_RegInfo reginfo = {};
189 for (InputSectionBase *sec : sections) {
190 sec->markDead();
191
192 ArrayRef<uint8_t> d = sec->content();
193 while (!d.empty()) {
194 if (d.size() < sizeof(Elf_Mips_Options)) {
195 Err(ctx) << sec->file << ": invalid size of .MIPS.options section";
196 break;
197 }
198
199 auto *opt = reinterpret_cast<const Elf_Mips_Options *>(d.data());
200 if (opt->kind == ODK_REGINFO) {
201 reginfo.ri_gprmask |= opt->getRegInfo().ri_gprmask;
202 sec->getFile<ELFT>()->mipsGp0 = opt->getRegInfo().ri_gp_value;
203 break;
204 }
205
206 if (!opt->size) {
207 Err(ctx) << sec->file << ": zero option descriptor size";
208 break;
209 }
210 d = d.slice(opt->size);
211 }
212 };
213
214 return std::make_unique<MipsOptionsSection<ELFT>>(ctx, reginfo);
215}
216
217// MIPS .reginfo section.
218template <class ELFT>
219MipsReginfoSection<ELFT>::MipsReginfoSection(Ctx &ctx, Elf_Mips_RegInfo reginfo)
220 : SyntheticSection(ctx, ".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC, 4),
221 reginfo(reginfo) {
222 this->entsize = sizeof(Elf_Mips_RegInfo);
223}
224
225template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *buf) {
226 if (!ctx.arg.relocatable)
227 reginfo.ri_gp_value = ctx.in.mipsGot->getGp();
228 memcpy(buf, &reginfo, sizeof(reginfo));
229}
230
231template <class ELFT>
232std::unique_ptr<MipsReginfoSection<ELFT>>
233MipsReginfoSection<ELFT>::create(Ctx &ctx) {
234 // Section should be alive for O32 and N32 ABIs only.
235 if (ELFT::Is64Bits)
236 return nullptr;
237
238 SmallVector<InputSectionBase *, 0> sections;
239 for (InputSectionBase *sec : ctx.inputSections)
240 if (sec->type == SHT_MIPS_REGINFO)
241 sections.push_back(Elt: sec);
242
243 if (sections.empty())
244 return nullptr;
245
246 Elf_Mips_RegInfo reginfo = {};
247 for (InputSectionBase *sec : sections) {
248 sec->markDead();
249
250 if (sec->content().size() != sizeof(Elf_Mips_RegInfo)) {
251 Err(ctx) << sec->file << ": invalid size of .reginfo section";
252 return nullptr;
253 }
254
255 auto *r = reinterpret_cast<const Elf_Mips_RegInfo *>(sec->content().data());
256 reginfo.ri_gprmask |= r->ri_gprmask;
257 sec->getFile<ELFT>()->mipsGp0 = r->ri_gp_value;
258 };
259
260 return std::make_unique<MipsReginfoSection<ELFT>>(ctx, reginfo);
261}
262
263InputSection *elf::createInterpSection(Ctx &ctx) {
264 // StringSaver guarantees that the returned string ends with '\0'.
265 StringRef s = ctx.saver.save(S: ctx.arg.dynamicLinker);
266 ArrayRef<uint8_t> contents = {(const uint8_t *)s.data(), s.size() + 1};
267
268 return make<InputSection>(args&: ctx.internalFile, args: ".interp", args: SHT_PROGBITS,
269 args: SHF_ALLOC,
270 /*addralign=*/args: 1, /*entsize=*/args: 0, args&: contents);
271}
272
273Defined *elf::addSyntheticLocal(Ctx &ctx, StringRef name, uint8_t type,
274 uint64_t value, uint64_t size,
275 InputSectionBase &section) {
276 Defined *s = makeDefined(args&: ctx, args&: section.file, args&: name, args: STB_LOCAL, args: STV_DEFAULT,
277 args&: type, args&: value, args&: size, args: &section);
278 if (ctx.in.symTab)
279 ctx.in.symTab->addSymbol(sym: s);
280
281 if (ctx.arg.emachine == EM_ARM && !ctx.arg.isLE && ctx.arg.armBe8 &&
282 (section.flags & SHF_EXECINSTR))
283 // Adding Linker generated mapping symbols to the arm specific mapping
284 // symbols list.
285 addArmSyntheticSectionMappingSymbol(s);
286
287 return s;
288}
289
290static size_t getHashSize(Ctx &ctx) {
291 switch (ctx.arg.buildId) {
292 case BuildIdKind::Fast:
293 return 8;
294 case BuildIdKind::Md5:
295 case BuildIdKind::Uuid:
296 return 16;
297 case BuildIdKind::Sha1:
298 return 20;
299 case BuildIdKind::Hexstring:
300 return ctx.arg.buildIdVector.size();
301 default:
302 llvm_unreachable("unknown BuildIdKind");
303 }
304}
305
306// This class represents a linker-synthesized .note.gnu.property section.
307//
308// In x86 and AArch64, object files may contain feature flags indicating the
309// features that they have used. The flags are stored in a .note.gnu.property
310// section.
311//
312// lld reads the sections from input files and merges them by computing AND of
313// the flags. The result is written as a new .note.gnu.property section.
314//
315// If the flag is zero (which indicates that the intersection of the feature
316// sets is empty, or some input files didn't have .note.gnu.property sections),
317// we don't create this section.
318GnuPropertySection::GnuPropertySection(Ctx &ctx)
319 : SyntheticSection(ctx, ".note.gnu.property", SHT_NOTE, SHF_ALLOC,
320 ctx.arg.wordsize) {}
321
322void GnuPropertySection::writeTo(uint8_t *buf) {
323 uint32_t featureAndType;
324 switch (ctx.arg.emachine) {
325 case EM_386:
326 case EM_X86_64:
327 featureAndType = GNU_PROPERTY_X86_FEATURE_1_AND;
328 break;
329 case EM_AARCH64:
330 featureAndType = GNU_PROPERTY_AARCH64_FEATURE_1_AND;
331 break;
332 case EM_RISCV:
333 featureAndType = GNU_PROPERTY_RISCV_FEATURE_1_AND;
334 break;
335 default:
336 llvm_unreachable(
337 "target machine does not support .note.gnu.property section");
338 }
339
340 write32(ctx, p: buf, v: 4); // Name size
341 write32(ctx, p: buf + 4, v: getSize() - 16); // Content size
342 write32(ctx, p: buf + 8, v: NT_GNU_PROPERTY_TYPE_0); // Type
343 memcpy(dest: buf + 12, src: "GNU", n: 4); // Name string
344
345 unsigned offset = 16;
346 if (ctx.arg.andFeatures != 0) {
347 write32(ctx, p: buf + offset + 0, v: featureAndType); // Feature type
348 write32(ctx, p: buf + offset + 4, v: 4); // Feature size
349 write32(ctx, p: buf + offset + 8, v: ctx.arg.andFeatures); // Feature flags
350 if (ctx.arg.is64)
351 write32(ctx, p: buf + offset + 12, v: 0); // Padding
352 offset += 16;
353 }
354
355 if (ctx.aarch64PauthAbiCoreInfo) {
356 write32(ctx, p: buf + offset + 0, v: GNU_PROPERTY_AARCH64_FEATURE_PAUTH);
357 write32(ctx, p: buf + offset + 4, v: AArch64PauthAbiCoreInfo::size());
358 write64(ctx, p: buf + offset + 8, v: ctx.aarch64PauthAbiCoreInfo->platform);
359 write64(ctx, p: buf + offset + 16, v: ctx.aarch64PauthAbiCoreInfo->version);
360 }
361}
362
363size_t GnuPropertySection::getSize() const {
364 uint32_t contentSize = 0;
365 if (ctx.arg.andFeatures != 0)
366 contentSize += ctx.arg.is64 ? 16 : 12;
367 if (ctx.aarch64PauthAbiCoreInfo)
368 contentSize += 4 + 4 + AArch64PauthAbiCoreInfo::size();
369 assert(contentSize != 0);
370 return contentSize + 16;
371}
372
373BuildIdSection::BuildIdSection(Ctx &ctx)
374 : SyntheticSection(ctx, ".note.gnu.build-id", SHT_NOTE, SHF_ALLOC, 4),
375 hashSize(getHashSize(ctx)) {}
376
377void BuildIdSection::writeTo(uint8_t *buf) {
378 write32(ctx, p: buf, v: 4); // Name size
379 write32(ctx, p: buf + 4, v: hashSize); // Content size
380 write32(ctx, p: buf + 8, v: NT_GNU_BUILD_ID); // Type
381 memcpy(dest: buf + 12, src: "GNU", n: 4); // Name string
382 hashBuf = buf + 16;
383}
384
385void BuildIdSection::writeBuildId(ArrayRef<uint8_t> buf) {
386 assert(buf.size() == hashSize);
387 memcpy(dest: hashBuf, src: buf.data(), n: hashSize);
388}
389
390BssSection::BssSection(Ctx &ctx, StringRef name, uint64_t size,
391 uint32_t alignment)
392 : SyntheticSection(ctx, name, SHT_NOBITS, SHF_ALLOC | SHF_WRITE,
393 alignment) {
394 this->bss = true;
395 this->size = size;
396}
397
398EhFrameSection::EhFrameSection(Ctx &ctx)
399 : SyntheticSection(ctx, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, 1) {}
400
401// Search for an existing CIE record or create a new one.
402// CIE records from input object files are uniquified by their contents
403// and where their relocations point to.
404CieRecord *EhFrameSection::addCie(EhSectionPiece &cie,
405 ArrayRef<Relocation> rels) {
406 Symbol *personality = nullptr;
407 unsigned firstRelI = cie.firstRelocation;
408 if (firstRelI != (unsigned)-1)
409 personality = rels[firstRelI].sym;
410
411 // Search for an existing CIE by CIE contents/relocation target pair.
412 CieRecord *&rec = cieMap[{cie.data(), personality}];
413
414 // If not found, create a new one.
415 if (!rec) {
416 rec = make<CieRecord>();
417 rec->cie = &cie;
418 cieRecords.push_back(Elt: rec);
419 }
420 return rec;
421}
422
423// There is one FDE per function. Returns a non-null pointer to the function
424// symbol if the given FDE points to a live function.
425Defined *EhFrameSection::isFdeLive(EhSectionPiece &fde,
426 ArrayRef<Relocation> rels) {
427 // An FDE should point to some function because FDEs are to describe
428 // functions. That's however not always the case due to an issue of
429 // ld.gold with -r. ld.gold may discard only functions and leave their
430 // corresponding FDEs, which results in creating bad .eh_frame sections.
431 // To deal with that, we ignore such FDEs.
432 unsigned firstRelI = fde.firstRelocation;
433 if (firstRelI == (unsigned)-1)
434 return nullptr;
435
436 // FDEs for garbage-collected or merged-by-ICF sections, or sections in
437 // another partition, are dead.
438 if (auto *d = dyn_cast<Defined>(Val: rels[firstRelI].sym))
439 if (!d->folded && d->section && d->section->partition == partition)
440 return d;
441 return nullptr;
442}
443
444// .eh_frame is a sequence of CIE or FDE records. In general, there
445// is one CIE record per input object file which is followed by
446// a list of FDEs. This function searches an existing CIE or create a new
447// one and associates FDEs to the CIE.
448template <endianness e> void EhFrameSection::addRecords(EhInputSection *sec) {
449 auto rels = sec->rels;
450 offsetToCie.clear();
451 for (EhSectionPiece &cie : sec->cies)
452 offsetToCie[cie.inputOff] = addCie(cie, rels);
453 for (EhSectionPiece &fde : sec->fdes) {
454 uint32_t id = endian::read32<e>(fde.data().data() + 4);
455 CieRecord *rec = offsetToCie[fde.inputOff + 4 - id];
456 if (!rec)
457 Fatal(ctx) << sec << ": invalid CIE reference";
458
459 if (!isFdeLive(fde, rels))
460 continue;
461 rec->fdes.push_back(Elt: &fde);
462 numFdes++;
463 }
464}
465
466// Used by ICF<ELFT>::handleLSDA(). This function is very similar to
467// EhFrameSection::addRecords().
468template <class ELFT>
469void EhFrameSection::iterateFDEWithLSDAAux(
470 EhInputSection &sec, DenseSet<size_t> &ciesWithLSDA,
471 llvm::function_ref<void(InputSection &)> fn) {
472 for (EhSectionPiece &cie : sec.cies)
473 if (hasLSDA(p: cie))
474 ciesWithLSDA.insert(V: cie.inputOff);
475 for (EhSectionPiece &fde : sec.fdes) {
476 uint32_t id = endian::read32<ELFT::Endianness>(fde.data().data() + 4);
477 if (!ciesWithLSDA.contains(V: fde.inputOff + 4 - id))
478 continue;
479
480 // The CIE has a LSDA argument. Call fn with d's section.
481 if (Defined *d = isFdeLive(fde, rels: sec.rels))
482 if (auto *s = dyn_cast_or_null<InputSection>(Val: d->section))
483 fn(*s);
484 }
485}
486
487template <class ELFT>
488void EhFrameSection::iterateFDEWithLSDA(
489 llvm::function_ref<void(InputSection &)> fn) {
490 DenseSet<size_t> ciesWithLSDA;
491 for (EhInputSection *sec : sections) {
492 ciesWithLSDA.clear();
493 iterateFDEWithLSDAAux<ELFT>(*sec, ciesWithLSDA, fn);
494 }
495}
496
497static void writeCieFde(Ctx &ctx, uint8_t *buf, ArrayRef<uint8_t> d) {
498 memcpy(dest: buf, src: d.data(), n: d.size());
499 // Fix the size field. -4 since size does not include the size field itself.
500 write32(ctx, p: buf, v: d.size() - 4);
501}
502
503void EhFrameSection::finalizeContents() {
504 assert(!this->size); // Not finalized.
505
506 switch (ctx.arg.ekind) {
507 case ELFNoneKind:
508 llvm_unreachable("invalid ekind");
509 case ELF32LEKind:
510 case ELF64LEKind:
511 for (EhInputSection *sec : sections)
512 if (sec->isLive())
513 addRecords<endianness::little>(sec);
514 break;
515 case ELF32BEKind:
516 case ELF64BEKind:
517 for (EhInputSection *sec : sections)
518 if (sec->isLive())
519 addRecords<endianness::big>(sec);
520 break;
521 }
522
523 size_t off = 0;
524 for (CieRecord *rec : cieRecords) {
525 rec->cie->outputOff = off;
526 off += rec->cie->size;
527
528 for (EhSectionPiece *fde : rec->fdes) {
529 fde->outputOff = off;
530 off += fde->size;
531 }
532 }
533
534 // The LSB standard does not allow a .eh_frame section with zero
535 // Call Frame Information records. glibc unwind-dw2-fde.c
536 // classify_object_over_fdes expects there is a CIE record length 0 as a
537 // terminator. Thus we add one unconditionally.
538 off += 4;
539
540 this->size = off;
541}
542
543void EhFrameSection::writeTo(uint8_t *buf) {
544 // Write CIE and FDE records.
545 for (CieRecord *rec : cieRecords) {
546 size_t cieOffset = rec->cie->outputOff;
547 writeCieFde(ctx, buf: buf + cieOffset, d: rec->cie->data());
548
549 for (EhSectionPiece *fde : rec->fdes) {
550 size_t off = fde->outputOff;
551 writeCieFde(ctx, buf: buf + off, d: fde->data());
552
553 // FDE's second word should have the offset to an associated CIE.
554 // Write it.
555 write32(ctx, p: buf + off + 4, v: off + 4 - cieOffset);
556 }
557 }
558
559 // Apply relocations to .eh_frame entries. This includes CIE personality
560 // pointers, FDE initial_location fields, and LSDA pointers.
561 for (EhInputSection *s : sections)
562 ctx.target->relocateEh(sec&: *s, buf);
563
564 EhFrameHeader *hdr = getPartition(ctx).ehFrameHdr.get();
565 if (!hdr || !hdr->getParent())
566 return;
567
568 // Write the .eh_frame_hdr section using cached FDE data from updateAllocSize.
569 bool large = hdr->large;
570 int64_t ehFramePtr = getParent()->addr - hdr->getVA() - 4;
571 auto writeField = [&](uint8_t *buf, uint64_t val) {
572 large ? write64(ctx, p: buf, v: val) : write32(ctx, p: buf, v: val);
573 };
574
575 uint8_t *hdrBuf = ctx.bufferStart + hdr->getParent()->offset + hdr->outSecOff;
576 // version
577 hdrBuf[0] = 1;
578 // eh_frame_ptr_enc
579 hdrBuf[1] = DW_EH_PE_pcrel | (large ? DW_EH_PE_sdata8 : DW_EH_PE_sdata4);
580 // fde_count_enc
581 hdrBuf[2] = DW_EH_PE_udata4;
582 // table_enc
583 hdrBuf[3] = DW_EH_PE_datarel | (large ? DW_EH_PE_sdata8 : DW_EH_PE_sdata4);
584 hdrBuf += 4;
585 writeField(hdrBuf, ehFramePtr);
586 hdrBuf += large ? 8 : 4;
587 write32(ctx, p: hdrBuf, v: hdr->fdes.size());
588 hdrBuf += 4;
589 for (const FdeData &fde : hdr->fdes) {
590 writeField(hdrBuf, fde.pcRel);
591 writeField(hdrBuf + (large ? 8 : 4), fde.fdeVARel);
592 hdrBuf += large ? 16 : 8;
593 }
594}
595
596EhFrameHeader::EhFrameHeader(Ctx &ctx)
597 : SyntheticSection(ctx, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, 4) {}
598
599void EhFrameHeader::writeTo(uint8_t *buf) {
600 // The section content is written during EhFrameSection::writeTo.
601}
602
603bool EhFrameHeader::isNeeded() const {
604 return isLive() && getPartition(ctx).ehFrame->isNeeded();
605}
606
607void EhFrameHeader::finalizeContents() {
608 // Compute size: 4-byte header + eh_frame_ptr + fde_count + FDE table.
609 // Initially `large` is false; updateAllocSize may set it to true if addresses
610 // exceed the 32-bit range, then call finalizeContents again.
611 auto numFdes = getPartition(ctx).ehFrame->numFdes;
612 size = 4 + (large ? 8 : 4) + 4 + numFdes * (large ? 16 : 8);
613}
614
615bool EhFrameHeader::updateAllocSize(Ctx &ctx) {
616 // This is called after `finalizeSynthetic`, so in the typical case without
617 // .relr.dyn, this function will not change the size and assignAddresses
618 // will not need another iteration.
619 EhFrameSection *ehFrame = getPartition(ctx).ehFrame.get();
620 uint64_t hdrVA = getVA();
621 int64_t ehFramePtr = ehFrame->getParent()->addr - hdrVA - 4;
622 // Determine if 64-bit encodings are needed.
623 bool newLarge = !isInt<32>(x: ehFramePtr);
624
625 // Collect FDE entries. For each FDE, compute pcRel and fdeVARel relative to
626 // .eh_frame_hdr's VA.
627 fdes.clear();
628 for (CieRecord *rec : ehFrame->getCieRecords()) {
629 uint8_t enc = getFdeEncoding(p: rec->cie);
630 if ((enc & 0x70) != DW_EH_PE_absptr && (enc & 0x70) != DW_EH_PE_pcrel) {
631 Err(ctx) << "unknown FDE size encoding";
632 continue;
633 }
634 for (EhSectionPiece *fde : rec->fdes) {
635 // The FDE has passed `isFdeLive`, so the first relocation's symbol is a
636 // live Defined.
637 auto *isec = cast<EhInputSection>(Val: fde->sec);
638 auto &reloc = isec->rels[fde->firstRelocation];
639 assert(isa<Defined>(reloc.sym) && "isFdeLive should have checked this");
640 int64_t pcRel = reloc.sym->getVA(ctx) + reloc.addend - hdrVA;
641 int64_t fdeVARel = ehFrame->getParent()->addr + fde->outputOff - hdrVA;
642 fdes.push_back(Elt: {.pcRel: pcRel, .fdeVARel: fdeVARel});
643 newLarge |= !isInt<32>(x: pcRel) || !isInt<32>(x: fdeVARel);
644 }
645 }
646
647 // Sort the FDE list by their PC and uniquify. Usually there is only one FDE
648 // at an address, but there can be more than one FDEs pointing to the address.
649 llvm::stable_sort(
650 Range&: fdes, C: [](const EhFrameSection::FdeData &a,
651 const EhFrameSection::FdeData &b) { return a.pcRel < b.pcRel; });
652 fdes.erase(CS: llvm::unique(R&: fdes,
653 P: [](const EhFrameSection::FdeData &a,
654 const EhFrameSection::FdeData &b) {
655 return a.pcRel == b.pcRel;
656 }),
657 CE: fdes.end());
658 ehFrame->numFdes = fdes.size();
659
660 large = newLarge;
661
662 // Compute size.
663 size_t oldSize = size;
664 finalizeContents();
665 return size != oldSize;
666}
667
668GotSection::GotSection(Ctx &ctx)
669 : SyntheticSection(ctx, ".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE,
670 ctx.target->gotEntrySize) {
671 numEntries = ctx.target->gotHeaderEntriesNum;
672}
673
674void GotSection::addEntry(const Symbol &sym) {
675 assert(sym.auxIdx == ctx.symAux.size() - 1);
676 ctx.symAux.back().gotIdx = numEntries++;
677}
678
679void GotSection::addAuthEntry(const Symbol &sym) {
680 authEntries.push_back(
681 Elt: {.offset: (numEntries - 1) * ctx.target->gotEntrySize, .isSymbolFunc: sym.isFunc()});
682}
683
684bool GotSection::addTlsDescEntry(const Symbol &sym) {
685 assert(sym.auxIdx == ctx.symAux.size() - 1);
686 ctx.symAux.back().tlsDescIdx = numEntries;
687 numEntries += 2;
688 return true;
689}
690
691void GotSection::addTlsDescAuthEntry() {
692 authEntries.push_back(Elt: {.offset: (numEntries - 2) * ctx.target->gotEntrySize, .isSymbolFunc: true});
693 authEntries.push_back(Elt: {.offset: (numEntries - 1) * ctx.target->gotEntrySize, .isSymbolFunc: false});
694}
695
696bool GotSection::addDynTlsEntry(const Symbol &sym) {
697 assert(sym.auxIdx == ctx.symAux.size() - 1);
698 ctx.symAux.back().tlsGdIdx = numEntries;
699 // Global Dynamic TLS entries take two GOT slots.
700 numEntries += 2;
701 return true;
702}
703
704// Reserves TLS entries for a TLS module ID and a TLS block offset.
705// In total it takes two GOT slots.
706bool GotSection::addTlsIndex() {
707 if (tlsIndexOff != uint32_t(-1))
708 return false;
709 tlsIndexOff = numEntries * ctx.target->gotEntrySize;
710 numEntries += 2;
711 return true;
712}
713
714uint32_t GotSection::getTlsDescOffset(const Symbol &sym) const {
715 return sym.getTlsDescIdx(ctx) * ctx.target->gotEntrySize;
716}
717
718uint64_t GotSection::getTlsDescAddr(const Symbol &sym) const {
719 return getVA() + getTlsDescOffset(sym);
720}
721
722uint64_t GotSection::getGlobalDynAddr(const Symbol &b) const {
723 return this->getVA() + b.getTlsGdIdx(ctx) * ctx.target->gotEntrySize;
724}
725
726uint64_t GotSection::getGlobalDynOffset(const Symbol &b) const {
727 return b.getTlsGdIdx(ctx) * ctx.target->gotEntrySize;
728}
729
730void GotSection::finalizeContents() {
731 if (ctx.arg.emachine == EM_PPC64 &&
732 numEntries <= ctx.target->gotHeaderEntriesNum &&
733 !ctx.sym.globalOffsetTable)
734 size = 0;
735 else
736 size = numEntries * ctx.target->gotEntrySize;
737}
738
739bool GotSection::isNeeded() const {
740 // Needed if the GOT symbol is used or the number of entries is more than just
741 // the header. A GOT with just the header may not be needed.
742 return hasGotOffRel || numEntries > ctx.target->gotHeaderEntriesNum;
743}
744
745void GotSection::writeTo(uint8_t *buf) {
746 // On PPC64 .got may be needed but empty. Skip the write.
747 if (size == 0)
748 return;
749 ctx.target->writeGotHeader(buf);
750 ctx.target->relocateAlloc(sec&: *this, buf);
751 for (const AuthEntryInfo &authEntry : authEntries) {
752 // https://github.com/ARM-software/abi-aa/blob/2024Q3/pauthabielf64/pauthabielf64.rst#default-signing-schema
753 // Signed GOT entries use the IA key for symbols of type STT_FUNC and the
754 // DA key for all other symbol types, with the address of the GOT entry as
755 // the modifier. The static linker must encode the signing schema into the
756 // GOT slot.
757 //
758 // https://github.com/ARM-software/abi-aa/blob/2024Q3/pauthabielf64/pauthabielf64.rst#encoding-the-signing-schema
759 // If address diversity is set and the discriminator
760 // is 0 then modifier = Place
761 uint8_t *dest = buf + authEntry.offset;
762 uint64_t key = authEntry.isSymbolFunc ? /*IA=*/0b00 : /*DA=*/0b10;
763 uint64_t addrDiversity = 1;
764 write64(ctx, p: dest, v: (addrDiversity << 63) | (key << 60));
765 }
766}
767
768static uint64_t getMipsPageCount(uint64_t size) {
769 return (size + 0xfffe) / 0xffff + 1;
770}
771
772MipsGotSection::MipsGotSection(Ctx &ctx)
773 : SyntheticSection(ctx, ".got", SHT_PROGBITS,
774 SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, 16) {}
775
776void MipsGotSection::addConstant(const Relocation &r) {
777 relocations.push_back(Elt: r);
778}
779
780void MipsGotSection::addEntry(InputFile &file, Symbol &sym, int64_t addend,
781 RelExpr expr) {
782 FileGot &g = getGot(f&: file);
783 if (expr == RE_MIPS_GOT_LOCAL_PAGE) {
784 if (const OutputSection *os = sym.getOutputSection())
785 g.pagesMap.insert(KV: {os, {&sym}});
786 else
787 g.local16.insert(KV: {{nullptr, getMipsPageAddr(addr: sym.getVA(ctx, addend))}, 0});
788 } else if (sym.isTls())
789 g.tls.insert(KV: {&sym, 0});
790 else if (sym.isPreemptible && expr == R_ABS)
791 g.relocs.insert(KV: {&sym, 0});
792 else if (sym.isPreemptible)
793 g.global.insert(KV: {&sym, 0});
794 else if (expr == RE_MIPS_GOT_OFF32)
795 g.local32.insert(KV: {{&sym, addend}, 0});
796 else
797 g.local16.insert(KV: {{&sym, addend}, 0});
798}
799
800void MipsGotSection::addDynTlsEntry(InputFile &file, Symbol &sym) {
801 getGot(f&: file).dynTlsSymbols.insert(KV: {&sym, 0});
802}
803
804void MipsGotSection::addTlsIndex(InputFile &file) {
805 getGot(f&: file).dynTlsSymbols.insert(KV: {nullptr, 0});
806}
807
808size_t MipsGotSection::FileGot::getEntriesNum() const {
809 return getPageEntriesNum() + local16.size() + global.size() + relocs.size() +
810 tls.size() + dynTlsSymbols.size() * 2;
811}
812
813size_t MipsGotSection::FileGot::getPageEntriesNum() const {
814 size_t num = 0;
815 for (const std::pair<const OutputSection *, FileGot::PageBlock> &p : pagesMap)
816 num += p.second.count;
817 return num;
818}
819
820size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
821 size_t count = getPageEntriesNum() + local16.size() + global.size();
822 // If there are relocation-only entries in the GOT, TLS entries
823 // are allocated after them. TLS entries should be addressable
824 // by 16-bit index so count both reloc-only and TLS entries.
825 if (!tls.empty() || !dynTlsSymbols.empty())
826 count += relocs.size() + tls.size() + dynTlsSymbols.size() * 2;
827 return count;
828}
829
830MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &f) {
831 if (f.mipsGotIndex == uint32_t(-1)) {
832 gots.emplace_back();
833 gots.back().file = &f;
834 f.mipsGotIndex = gots.size() - 1;
835 }
836 return gots[f.mipsGotIndex];
837}
838
839uint64_t MipsGotSection::getPageEntryOffset(const InputFile *f,
840 const Symbol &sym,
841 int64_t addend) const {
842 const FileGot &g = gots[f->mipsGotIndex];
843 uint64_t index = 0;
844 if (const OutputSection *outSec = sym.getOutputSection()) {
845 uint64_t secAddr = getMipsPageAddr(addr: outSec->addr);
846 uint64_t symAddr = getMipsPageAddr(addr: sym.getVA(ctx, addend));
847 index = g.pagesMap.lookup(Key: outSec).firstIndex + (symAddr - secAddr) / 0xffff;
848 } else {
849 index =
850 g.local16.lookup(Key: {nullptr, getMipsPageAddr(addr: sym.getVA(ctx, addend))});
851 }
852 return index * ctx.arg.wordsize;
853}
854
855uint64_t MipsGotSection::getSymEntryOffset(const InputFile *f, const Symbol &s,
856 int64_t addend) const {
857 const FileGot &g = gots[f->mipsGotIndex];
858 Symbol *sym = const_cast<Symbol *>(&s);
859 if (sym->isTls())
860 return g.tls.lookup(Key: sym) * ctx.arg.wordsize;
861 if (sym->isPreemptible)
862 return g.global.lookup(Key: sym) * ctx.arg.wordsize;
863 return g.local16.lookup(Key: {sym, addend}) * ctx.arg.wordsize;
864}
865
866uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *f) const {
867 const FileGot &g = gots[f->mipsGotIndex];
868 return g.dynTlsSymbols.lookup(Key: nullptr) * ctx.arg.wordsize;
869}
870
871uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *f,
872 const Symbol &s) const {
873 const FileGot &g = gots[f->mipsGotIndex];
874 Symbol *sym = const_cast<Symbol *>(&s);
875 return g.dynTlsSymbols.lookup(Key: sym) * ctx.arg.wordsize;
876}
877
878const Symbol *MipsGotSection::getFirstGlobalEntry() const {
879 if (gots.empty())
880 return nullptr;
881 const FileGot &primGot = gots.front();
882 if (!primGot.global.empty())
883 return primGot.global.front().first;
884 if (!primGot.relocs.empty())
885 return primGot.relocs.front().first;
886 return nullptr;
887}
888
889unsigned MipsGotSection::getLocalEntriesNum() const {
890 if (gots.empty())
891 return headerEntriesNum;
892 return headerEntriesNum + gots.front().getPageEntriesNum() +
893 gots.front().local16.size();
894}
895
896bool MipsGotSection::tryMergeGots(FileGot &dst, FileGot &src, bool isPrimary) {
897 FileGot tmp = dst;
898 set_union(S1&: tmp.pagesMap, S2: src.pagesMap);
899 set_union(S1&: tmp.local16, S2: src.local16);
900 set_union(S1&: tmp.global, S2: src.global);
901 set_union(S1&: tmp.relocs, S2: src.relocs);
902 set_union(S1&: tmp.tls, S2: src.tls);
903 set_union(S1&: tmp.dynTlsSymbols, S2: src.dynTlsSymbols);
904
905 size_t count = isPrimary ? headerEntriesNum : 0;
906 count += tmp.getIndexedEntriesNum();
907
908 if (count * ctx.arg.wordsize > ctx.arg.mipsGotSize)
909 return false;
910
911 std::swap(a&: tmp, b&: dst);
912 return true;
913}
914
915void MipsGotSection::finalizeContents() { updateAllocSize(ctx); }
916
917bool MipsGotSection::updateAllocSize(Ctx &ctx) {
918 size = headerEntriesNum * ctx.arg.wordsize;
919 for (const FileGot &g : gots)
920 size += g.getEntriesNum() * ctx.arg.wordsize;
921 return false;
922}
923
924void MipsGotSection::build() {
925 if (gots.empty())
926 return;
927
928 std::vector<FileGot> mergedGots(1);
929
930 // For each GOT move non-preemptible symbols from the `Global`
931 // to `Local16` list. Preemptible symbol might become non-preemptible
932 // one if, for example, it gets a related copy relocation.
933 for (FileGot &got : gots) {
934 for (auto &p: got.global)
935 if (!p.first->isPreemptible)
936 got.local16.insert(KV: {{p.first, 0}, 0});
937 got.global.remove_if(Pred: [&](const std::pair<Symbol *, size_t> &p) {
938 return !p.first->isPreemptible;
939 });
940 }
941
942 // For each GOT remove "reloc-only" entry if there is "global"
943 // entry for the same symbol. And add local entries which indexed
944 // using 32-bit value at the end of 16-bit entries.
945 for (FileGot &got : gots) {
946 got.relocs.remove_if(Pred: [&](const std::pair<Symbol *, size_t> &p) {
947 return got.global.contains(Key: p.first);
948 });
949 set_union(S1&: got.local16, S2: got.local32);
950 got.local32.clear();
951 }
952
953 // Evaluate number of "reloc-only" entries in the resulting GOT.
954 // To do that put all unique "reloc-only" and "global" entries
955 // from all GOTs to the future primary GOT.
956 FileGot *primGot = &mergedGots.front();
957 for (FileGot &got : gots) {
958 set_union(S1&: primGot->relocs, S2: got.global);
959 set_union(S1&: primGot->relocs, S2: got.relocs);
960 got.relocs.clear();
961 }
962
963 // Evaluate number of "page" entries in each GOT.
964 for (FileGot &got : gots) {
965 for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
966 got.pagesMap) {
967 const OutputSection *os = p.first;
968 uint64_t secSize = 0;
969 for (SectionCommand *cmd : os->commands) {
970 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd))
971 for (InputSection *isec : isd->sections) {
972 uint64_t off = alignToPowerOf2(Value: secSize, Align: isec->addralign);
973 secSize = off + isec->getSize();
974 }
975 }
976 p.second.count = getMipsPageCount(size: secSize);
977 }
978 }
979
980 // Merge GOTs. Try to join as much as possible GOTs but do not exceed
981 // maximum GOT size. At first, try to fill the primary GOT because
982 // the primary GOT can be accessed in the most effective way. If it
983 // is not possible, try to fill the last GOT in the list, and finally
984 // create a new GOT if both attempts failed.
985 for (FileGot &srcGot : gots) {
986 InputFile *file = srcGot.file;
987 if (tryMergeGots(dst&: mergedGots.front(), src&: srcGot, isPrimary: true)) {
988 file->mipsGotIndex = 0;
989 } else {
990 // If this is the first time we failed to merge with the primary GOT,
991 // MergedGots.back() will also be the primary GOT. We must make sure not
992 // to try to merge again with isPrimary=false, as otherwise, if the
993 // inputs are just right, we could allow the primary GOT to become 1 or 2
994 // words bigger due to ignoring the header size.
995 if (mergedGots.size() == 1 ||
996 !tryMergeGots(dst&: mergedGots.back(), src&: srcGot, isPrimary: false)) {
997 mergedGots.emplace_back();
998 std::swap(a&: mergedGots.back(), b&: srcGot);
999 }
1000 file->mipsGotIndex = mergedGots.size() - 1;
1001 }
1002 }
1003 std::swap(x&: gots, y&: mergedGots);
1004
1005 // Reduce number of "reloc-only" entries in the primary GOT
1006 // by subtracting "global" entries in the primary GOT.
1007 primGot = &gots.front();
1008 primGot->relocs.remove_if(Pred: [&](const std::pair<Symbol *, size_t> &p) {
1009 return primGot->global.contains(Key: p.first);
1010 });
1011
1012 // Calculate indexes for each GOT entry.
1013 size_t index = headerEntriesNum;
1014 for (FileGot &got : gots) {
1015 got.startIndex = &got == primGot ? 0 : index;
1016 for (std::pair<const OutputSection *, FileGot::PageBlock> &p :
1017 got.pagesMap) {
1018 // For each output section referenced by GOT page relocations calculate
1019 // and save into pagesMap an upper bound of MIPS GOT entries required
1020 // to store page addresses of local symbols. We assume the worst case -
1021 // each 64kb page of the output section has at least one GOT relocation
1022 // against it. And take in account the case when the section intersects
1023 // page boundaries.
1024 p.second.firstIndex = index;
1025 index += p.second.count;
1026 }
1027 for (auto &p: got.local16)
1028 p.second = index++;
1029 for (auto &p: got.global)
1030 p.second = index++;
1031 for (auto &p: got.relocs)
1032 p.second = index++;
1033 for (auto &p: got.tls)
1034 p.second = index++;
1035 for (auto &p: got.dynTlsSymbols) {
1036 p.second = index;
1037 index += 2;
1038 }
1039 }
1040
1041 // Update SymbolAux::gotIdx field to use this
1042 // value later in the `sortMipsSymbols` function.
1043 for (auto &p : primGot->global) {
1044 if (p.first->auxIdx == 0)
1045 p.first->allocateAux(ctx);
1046 ctx.symAux.back().gotIdx = p.second;
1047 }
1048 for (auto &p : primGot->relocs) {
1049 if (p.first->auxIdx == 0)
1050 p.first->allocateAux(ctx);
1051 ctx.symAux.back().gotIdx = p.second;
1052 }
1053
1054 // Create relocations.
1055 //
1056 // Note the primary GOT's local and global relocations are implicit, and the
1057 // MIPS ABI requires the VA be written even for the global entries, so we
1058 // treat both as constants here.
1059 for (FileGot &got : gots) {
1060 // Create relocations for TLS entries.
1061 for (std::pair<Symbol *, size_t> &p : got.tls) {
1062 Symbol *s = p.first;
1063 uint64_t offset = p.second * ctx.arg.wordsize;
1064 // When building a shared library we still need a dynamic relocation
1065 // for the TP-relative offset as we don't know how much other data will
1066 // be allocated before us in the static TLS block.
1067 if (!s->isPreemptible && !ctx.arg.shared)
1068 addConstant(r: {.expr: R_TPREL, .type: ctx.target->symbolicRel, .offset: offset, .addend: 0, .sym: s});
1069 else
1070 ctx.mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1071 dynType: ctx.target->tlsGotRel, isec&: *this, offsetInSec: offset, sym&: *s, addendRelType: ctx.target->symbolicRel);
1072 }
1073 for (std::pair<Symbol *, size_t> &p : got.dynTlsSymbols) {
1074 Symbol *s = p.first;
1075 uint64_t offset = p.second * ctx.arg.wordsize;
1076 if (s == nullptr) {
1077 if (ctx.arg.shared)
1078 ctx.mainPart->relaDyn->addReloc(
1079 reloc: {ctx.target->tlsModuleIndexRel, this, offset});
1080 else
1081 addConstant(
1082 r: {.expr: R_ADDEND, .type: ctx.target->symbolicRel, .offset: offset, .addend: 1, .sym: ctx.dummySym});
1083 } else {
1084 // When building a shared library we still need a dynamic relocation
1085 // for the module index. Therefore only checking for
1086 // S->isPreemptible is not sufficient (this happens e.g. for
1087 // thread-locals that have been marked as local through a linker script)
1088 if (!s->isPreemptible && !ctx.arg.shared)
1089 // Write one to the GOT slot.
1090 addConstant(r: {.expr: R_ADDEND, .type: ctx.target->symbolicRel, .offset: offset, .addend: 1, .sym: s});
1091 else
1092 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->tlsModuleIndexRel,
1093 isec&: *this, offsetInSec: offset, sym&: *s);
1094 offset += ctx.arg.wordsize;
1095 // However, we can skip writing the TLS offset reloc for non-preemptible
1096 // symbols since it is known even in shared libraries
1097 if (s->isPreemptible)
1098 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->tlsOffsetRel, isec&: *this,
1099 offsetInSec: offset, sym&: *s);
1100 else
1101 addConstant(r: {.expr: R_ABS, .type: ctx.target->tlsOffsetRel, .offset: offset, .addend: 0, .sym: s});
1102 }
1103 }
1104
1105 // Relocations for "global" entries.
1106 for (const std::pair<Symbol *, size_t> &p : got.global) {
1107 uint64_t offset = p.second * ctx.arg.wordsize;
1108 if (&got == primGot)
1109 addConstant(r: {.expr: R_ABS, .type: ctx.target->relativeRel, .offset: offset, .addend: 0, .sym: p.first});
1110 else
1111 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->relativeRel, isec&: *this,
1112 offsetInSec: offset, sym&: *p.first);
1113 }
1114 // Relocation-only entries exist as dummy entries for dynamic symbols that
1115 // aren't otherwise in the primary GOT, as the ABI requires an entry for
1116 // each dynamic symbol. Secondary GOTs have no need for them.
1117 assert((got.relocs.empty() || &got == primGot) &&
1118 "Relocation-only entries should only be in the primary GOT");
1119 for (const std::pair<Symbol *, size_t> &p : got.relocs) {
1120 uint64_t offset = p.second * ctx.arg.wordsize;
1121 addConstant(r: {.expr: R_ABS, .type: ctx.target->relativeRel, .offset: offset, .addend: 0, .sym: p.first});
1122 }
1123
1124 // Relocations for "local" entries
1125 for (const std::pair<const OutputSection *, FileGot::PageBlock> &l :
1126 got.pagesMap) {
1127 size_t pageCount = l.second.count;
1128 for (size_t pi = 0; pi < pageCount; ++pi) {
1129 uint64_t offset = (l.second.firstIndex + pi) * ctx.arg.wordsize;
1130 int64_t addend = int64_t(pi * 0x10000);
1131 if (!ctx.arg.isPic || &got == primGot)
1132 addConstant(r: {.expr: RE_MIPS_OSEC_LOCAL_PAGE, .type: ctx.target->relativeRel, .offset: offset,
1133 .addend: addend, .sym: l.second.repSym});
1134 else
1135 ctx.mainPart->relaDyn->addRelativeReloc(
1136 dynType: ctx.target->relativeRel, isec&: *this, offsetInSec: offset, sym&: *l.second.repSym, addend,
1137 addendRelType: ctx.target->relativeRel, expr: RE_MIPS_OSEC_LOCAL_PAGE);
1138 }
1139 }
1140 for (const std::pair<GotEntry, size_t> &p : got.local16) {
1141 uint64_t offset = p.second * ctx.arg.wordsize;
1142 if (p.first.first == nullptr)
1143 addConstant(r: {.expr: R_ADDEND, .type: ctx.target->relativeRel, .offset: offset, .addend: p.first.second,
1144 .sym: ctx.dummySym});
1145 else if (!ctx.arg.isPic || &got == primGot)
1146 addConstant(r: {.expr: R_ABS, .type: ctx.target->relativeRel, .offset: offset, .addend: p.first.second,
1147 .sym: p.first.first});
1148 else
1149 ctx.mainPart->relaDyn->addRelativeReloc(
1150 dynType: ctx.target->relativeRel, isec&: *this, offsetInSec: offset, sym&: *p.first.first,
1151 addend: p.first.second, addendRelType: ctx.target->relativeRel, expr: R_ABS);
1152 }
1153 }
1154}
1155
1156bool MipsGotSection::isNeeded() const {
1157 // We add the .got section to the result for dynamic MIPS target because
1158 // its address and properties are mentioned in the .dynamic section.
1159 return !ctx.arg.relocatable;
1160}
1161
1162uint64_t MipsGotSection::getGp(const InputFile *f) const {
1163 // For files without related GOT or files refer a primary GOT
1164 // returns "common" _gp value. For secondary GOTs calculate
1165 // individual _gp values.
1166 if (!f || f->mipsGotIndex == uint32_t(-1) || f->mipsGotIndex == 0)
1167 return ctx.sym.mipsGp->getVA(ctx, addend: 0);
1168 return getVA() + gots[f->mipsGotIndex].startIndex * ctx.arg.wordsize + 0x7ff0;
1169}
1170
1171void MipsGotSection::writeTo(uint8_t *buf) {
1172 // Set the MSB of the second GOT slot. This is not required by any
1173 // MIPS ABI documentation, though.
1174 //
1175 // There is a comment in glibc saying that "The MSB of got[1] of a
1176 // gnu object is set to identify gnu objects," and in GNU gold it
1177 // says "the second entry will be used by some runtime loaders".
1178 // But how this field is being used is unclear.
1179 //
1180 // We are not really willing to mimic other linkers behaviors
1181 // without understanding why they do that, but because all files
1182 // generated by GNU tools have this special GOT value, and because
1183 // we've been doing this for years, it is probably a safe bet to
1184 // keep doing this for now. We really need to revisit this to see
1185 // if we had to do this.
1186 writeUint(ctx, buf: buf + ctx.arg.wordsize,
1187 val: (uint64_t)1 << (ctx.arg.wordsize * 8 - 1));
1188 ctx.target->relocateAlloc(sec&: *this, buf);
1189}
1190
1191// On PowerPC the .plt section is used to hold the table of function addresses
1192// instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1193// section. I don't know why we have a BSS style type for the section but it is
1194// consistent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1195GotPltSection::GotPltSection(Ctx &ctx)
1196 : SyntheticSection(ctx, ".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE,
1197 ctx.target->gotEntrySize) {
1198 if (ctx.arg.emachine == EM_PPC) {
1199 name = ".plt";
1200 } else if (ctx.arg.emachine == EM_PPC64) {
1201 type = SHT_NOBITS;
1202 name = ".plt";
1203 }
1204}
1205
1206void GotPltSection::addEntry(Symbol &sym) {
1207 assert(sym.auxIdx == ctx.symAux.size() - 1 &&
1208 ctx.symAux.back().pltIdx == entries.size());
1209 entries.push_back(Elt: &sym);
1210}
1211
1212size_t GotPltSection::getSize() const {
1213 return (ctx.target->gotPltHeaderEntriesNum + entries.size()) *
1214 ctx.target->gotEntrySize;
1215}
1216
1217void GotPltSection::writeTo(uint8_t *buf) {
1218 ctx.target->writeGotPltHeader(buf);
1219 buf += ctx.target->gotPltHeaderEntriesNum * ctx.target->gotEntrySize;
1220 for (const Symbol *b : entries) {
1221 ctx.target->writeGotPlt(buf, s: *b);
1222 buf += ctx.target->gotEntrySize;
1223 }
1224}
1225
1226bool GotPltSection::isNeeded() const {
1227 // We need to emit GOTPLT even if it's empty if there's a relocation relative
1228 // to it.
1229 return !entries.empty() || hasGotPltOffRel;
1230}
1231
1232static StringRef getIgotPltName(Ctx &ctx) {
1233 // On ARM the IgotPltSection is part of the GotSection.
1234 if (ctx.arg.emachine == EM_ARM)
1235 return ".got";
1236
1237 // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1238 // needs to be named the same.
1239 if (ctx.arg.emachine == EM_PPC64)
1240 return ".plt";
1241
1242 return ".got.plt";
1243}
1244
1245// On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1246// with the IgotPltSection.
1247IgotPltSection::IgotPltSection(Ctx &ctx)
1248 : SyntheticSection(ctx, getIgotPltName(ctx),
1249 ctx.arg.emachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1250 SHF_ALLOC | SHF_WRITE, ctx.target->gotEntrySize) {}
1251
1252void IgotPltSection::addEntry(Symbol &sym) {
1253 assert(ctx.symAux.back().pltIdx == entries.size());
1254 entries.push_back(Elt: &sym);
1255}
1256
1257size_t IgotPltSection::getSize() const {
1258 return entries.size() * ctx.target->gotEntrySize;
1259}
1260
1261void IgotPltSection::writeTo(uint8_t *buf) {
1262 for (const Symbol *b : entries) {
1263 ctx.target->writeIgotPlt(buf, s: *b);
1264 buf += ctx.target->gotEntrySize;
1265 }
1266}
1267
1268StringTableSection::StringTableSection(Ctx &ctx, StringRef name, bool dynamic)
1269 : SyntheticSection(ctx, name, SHT_STRTAB, dynamic ? (uint64_t)SHF_ALLOC : 0,
1270 1),
1271 dynamic(dynamic) {
1272 // ELF string tables start with a NUL byte.
1273 strings.push_back(Elt: "");
1274 stringMap.try_emplace(Key: CachedHashStringRef(""), Args: 0);
1275 size = 1;
1276}
1277
1278// Adds a string to the string table. If `hashIt` is true we hash and check for
1279// duplicates. It is optional because the name of global symbols are already
1280// uniqued and hashing them again has a big cost for a small value: uniquing
1281// them with some other string that happens to be the same.
1282unsigned StringTableSection::addString(StringRef s, bool hashIt) {
1283 if (hashIt) {
1284 auto r = stringMap.try_emplace(Key: CachedHashStringRef(s), Args&: size);
1285 if (!r.second)
1286 return r.first->second;
1287 }
1288 if (s.empty())
1289 return 0;
1290 unsigned ret = this->size;
1291 this->size = this->size + s.size() + 1;
1292 strings.push_back(Elt: s);
1293 return ret;
1294}
1295
1296void StringTableSection::writeTo(uint8_t *buf) {
1297 for (StringRef s : strings) {
1298 memcpy(dest: buf, src: s.data(), n: s.size());
1299 buf[s.size()] = '\0';
1300 buf += s.size() + 1;
1301 }
1302}
1303
1304// Returns the number of entries in .gnu.version_d: the number of
1305// non-VER_NDX_LOCAL-non-VER_NDX_GLOBAL definitions, plus 1.
1306// Note that we don't support vd_cnt > 1 yet.
1307static unsigned getVerDefNum(Ctx &ctx) {
1308 return namedVersionDefs(ctx).size() + 1;
1309}
1310
1311template <class ELFT>
1312DynamicSection<ELFT>::DynamicSection(Ctx &ctx)
1313 : SyntheticSection(ctx, ".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE,
1314 ctx.arg.wordsize) {
1315 this->entsize = ELFT::Is64Bits ? 16 : 8;
1316
1317 // .dynamic section is not writable on MIPS and on Fuchsia OS
1318 // which passes -z rodynamic.
1319 // See "Special Section" in Chapter 4 in the following document:
1320 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1321 if (ctx.arg.emachine == EM_MIPS || ctx.arg.zRodynamic)
1322 this->flags = SHF_ALLOC;
1323}
1324
1325// The output section .rela.dyn may include these synthetic sections:
1326//
1327// - part.relaDyn
1328// - ctx.in.relaPlt: this is included if a linker script places .rela.plt inside
1329// .rela.dyn
1330//
1331// DT_RELASZ is the total size of the included sections.
1332static uint64_t addRelaSz(Ctx &ctx, const RelocationBaseSection &relaDyn) {
1333 size_t size = relaDyn.getSize();
1334 if (ctx.in.relaPlt->getParent() == relaDyn.getParent())
1335 size += ctx.in.relaPlt->getSize();
1336 return size;
1337}
1338
1339// A Linker script may assign the RELA relocation sections to the same
1340// output section. When this occurs we cannot just use the OutputSection
1341// Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1342// overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1343static uint64_t addPltRelSz(Ctx &ctx) { return ctx.in.relaPlt->getSize(); }
1344
1345// Add remaining entries to complete .dynamic contents.
1346template <class ELFT>
1347std::vector<std::pair<int32_t, uint64_t>>
1348DynamicSection<ELFT>::computeContents() {
1349 elf::Partition &part = getPartition(ctx);
1350 bool isMain = part.name.empty();
1351 std::vector<std::pair<int32_t, uint64_t>> entries;
1352
1353 auto addInt = [&](int32_t tag, uint64_t val) {
1354 entries.emplace_back(args&: tag, args&: val);
1355 };
1356 auto addInSec = [&](int32_t tag, const InputSection &sec) {
1357 entries.emplace_back(args&: tag, args: sec.getVA());
1358 };
1359
1360 for (StringRef s : ctx.arg.filterList)
1361 addInt(DT_FILTER, part.dynStrTab->addString(s));
1362 for (StringRef s : ctx.arg.auxiliaryList)
1363 addInt(DT_AUXILIARY, part.dynStrTab->addString(s));
1364
1365 if (!ctx.arg.rpath.empty())
1366 addInt(ctx.arg.enableNewDtags ? DT_RUNPATH : DT_RPATH,
1367 part.dynStrTab->addString(s: ctx.arg.rpath));
1368
1369 for (SharedFile *file : ctx.sharedFiles)
1370 if (file->isNeeded)
1371 addInt(DT_NEEDED, part.dynStrTab->addString(s: file->soName));
1372
1373 if (isMain) {
1374 if (!ctx.arg.soName.empty())
1375 addInt(DT_SONAME, part.dynStrTab->addString(s: ctx.arg.soName));
1376 } else {
1377 if (!ctx.arg.soName.empty())
1378 addInt(DT_NEEDED, part.dynStrTab->addString(s: ctx.arg.soName));
1379 addInt(DT_SONAME, part.dynStrTab->addString(s: part.name));
1380 }
1381
1382 // Set DT_FLAGS and DT_FLAGS_1.
1383 uint32_t dtFlags = 0;
1384 uint32_t dtFlags1 = 0;
1385 if (ctx.arg.bsymbolic == BsymbolicKind::All)
1386 dtFlags |= DF_SYMBOLIC;
1387 if (ctx.arg.zGlobal)
1388 dtFlags1 |= DF_1_GLOBAL;
1389 if (ctx.arg.zInitfirst)
1390 dtFlags1 |= DF_1_INITFIRST;
1391 if (ctx.arg.zInterpose)
1392 dtFlags1 |= DF_1_INTERPOSE;
1393 if (ctx.arg.zNodefaultlib)
1394 dtFlags1 |= DF_1_NODEFLIB;
1395 if (ctx.arg.zNodelete)
1396 dtFlags1 |= DF_1_NODELETE;
1397 if (ctx.arg.zNodlopen)
1398 dtFlags1 |= DF_1_NOOPEN;
1399 if (ctx.arg.pie)
1400 dtFlags1 |= DF_1_PIE;
1401 if (ctx.arg.zNow) {
1402 dtFlags |= DF_BIND_NOW;
1403 dtFlags1 |= DF_1_NOW;
1404 }
1405 if (ctx.arg.zOrigin) {
1406 dtFlags |= DF_ORIGIN;
1407 dtFlags1 |= DF_1_ORIGIN;
1408 }
1409 if (!ctx.arg.zText)
1410 dtFlags |= DF_TEXTREL;
1411 if (ctx.hasTlsIe && ctx.arg.shared)
1412 dtFlags |= DF_STATIC_TLS;
1413
1414 if (dtFlags)
1415 addInt(DT_FLAGS, dtFlags);
1416 if (dtFlags1)
1417 addInt(DT_FLAGS_1, dtFlags1);
1418
1419 // DT_DEBUG is a pointer to debug information used by debuggers at runtime. We
1420 // need it for each process, so we don't write it for DSOs. The loader writes
1421 // the pointer into this entry.
1422 //
1423 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1424 // systems (currently only Fuchsia OS) provide other means to give the
1425 // debugger this information. Such systems may choose make .dynamic read-only.
1426 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1427 if (!ctx.arg.shared && !ctx.arg.relocatable && !ctx.arg.zRodynamic)
1428 addInt(DT_DEBUG, 0);
1429
1430 if (part.relaDyn->isNeeded()) {
1431 addInSec(part.relaDyn->dynamicTag, *part.relaDyn);
1432 entries.emplace_back(part.relaDyn->sizeDynamicTag,
1433 addRelaSz(ctx, *part.relaDyn));
1434
1435 bool isRela = ctx.arg.isRela;
1436 addInt(isRela ? DT_RELAENT : DT_RELENT,
1437 isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
1438
1439 // MIPS dynamic loader does not support RELCOUNT tag.
1440 // The problem is in the tight relation between dynamic
1441 // relocations and GOT. So do not emit this tag on MIPS.
1442 if (ctx.arg.emachine != EM_MIPS) {
1443 size_t numRelativeRels = part.relaDyn->getRelativeRelocCount();
1444 if (ctx.arg.zCombreloc && numRelativeRels)
1445 addInt(isRela ? DT_RELACOUNT : DT_RELCOUNT, numRelativeRels);
1446 }
1447 }
1448 if (part.relrDyn && part.relrDyn->getParent() &&
1449 !part.relrDyn->relocs.empty()) {
1450 addInSec(ctx.arg.useAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1451 *part.relrDyn);
1452 addInt(ctx.arg.useAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1453 part.relrDyn->getParent()->size);
1454 addInt(ctx.arg.useAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1455 sizeof(Elf_Relr));
1456 }
1457 if (part.relrAuthDyn && part.relrAuthDyn->getParent() &&
1458 !part.relrAuthDyn->relocs.empty()) {
1459 addInSec(DT_AARCH64_AUTH_RELR, *part.relrAuthDyn);
1460 addInt(DT_AARCH64_AUTH_RELRSZ, part.relrAuthDyn->getParent()->size);
1461 addInt(DT_AARCH64_AUTH_RELRENT, sizeof(Elf_Relr));
1462 }
1463 if (isMain && ctx.in.relaPlt->isNeeded()) {
1464 addInSec(DT_JMPREL, *ctx.in.relaPlt);
1465 entries.emplace_back(DT_PLTRELSZ, addPltRelSz(ctx));
1466 switch (ctx.arg.emachine) {
1467 case EM_MIPS:
1468 addInSec(DT_MIPS_PLTGOT, *ctx.in.gotPlt);
1469 break;
1470 case EM_S390:
1471 addInSec(DT_PLTGOT, *ctx.in.got);
1472 break;
1473 case EM_SPARCV9:
1474 addInSec(DT_PLTGOT, *ctx.in.plt);
1475 break;
1476 case EM_AARCH64:
1477 if (llvm::find_if(ctx.in.relaPlt->relocs, [&ctx = ctx](
1478 const DynamicReloc &r) {
1479 return r.type == ctx.target->pltRel &&
1480 r.sym->stOther & STO_AARCH64_VARIANT_PCS;
1481 }) != ctx.in.relaPlt->relocs.end())
1482 addInt(DT_AARCH64_VARIANT_PCS, 0);
1483 addInSec(DT_PLTGOT, *ctx.in.gotPlt);
1484 break;
1485 case EM_RISCV:
1486 if (llvm::any_of(ctx.in.relaPlt->relocs, [&ctx = ctx](
1487 const DynamicReloc &r) {
1488 return r.type == ctx.target->pltRel &&
1489 (r.sym->stOther & STO_RISCV_VARIANT_CC);
1490 }))
1491 addInt(DT_RISCV_VARIANT_CC, 0);
1492 [[fallthrough]];
1493 default:
1494 addInSec(DT_PLTGOT, *ctx.in.gotPlt);
1495 break;
1496 }
1497 addInt(DT_PLTREL, ctx.arg.isRela ? DT_RELA : DT_REL);
1498 }
1499
1500 if (ctx.arg.emachine == EM_AARCH64) {
1501 if (ctx.arg.andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
1502 addInt(DT_AARCH64_BTI_PLT, 0);
1503 if (ctx.arg.zPacPlt)
1504 addInt(DT_AARCH64_PAC_PLT, 0);
1505
1506 if (hasMemtag(ctx)) {
1507 addInt(DT_AARCH64_MEMTAG_MODE, ctx.arg.androidMemtagMode == NT_MEMTAG_LEVEL_ASYNC);
1508 addInt(DT_AARCH64_MEMTAG_HEAP, ctx.arg.androidMemtagHeap);
1509 addInt(DT_AARCH64_MEMTAG_STACK, ctx.arg.androidMemtagStack);
1510 if (ctx.mainPart->memtagGlobalDescriptors->isNeeded()) {
1511 addInSec(DT_AARCH64_MEMTAG_GLOBALS,
1512 *ctx.mainPart->memtagGlobalDescriptors);
1513 addInt(DT_AARCH64_MEMTAG_GLOBALSSZ,
1514 ctx.mainPart->memtagGlobalDescriptors->getSize());
1515 }
1516 }
1517 }
1518
1519 addInSec(DT_SYMTAB, *part.dynSymTab);
1520 addInt(DT_SYMENT, sizeof(Elf_Sym));
1521 addInSec(DT_STRTAB, *part.dynStrTab);
1522 addInt(DT_STRSZ, part.dynStrTab->getSize());
1523 if (!ctx.arg.zText)
1524 addInt(DT_TEXTREL, 0);
1525 if (part.gnuHashTab && part.gnuHashTab->getParent())
1526 addInSec(DT_GNU_HASH, *part.gnuHashTab);
1527 if (part.hashTab && part.hashTab->getParent())
1528 addInSec(DT_HASH, *part.hashTab);
1529
1530 if (isMain) {
1531 if (ctx.out.preinitArray) {
1532 addInt(DT_PREINIT_ARRAY, ctx.out.preinitArray->addr);
1533 addInt(DT_PREINIT_ARRAYSZ, ctx.out.preinitArray->size);
1534 }
1535 if (ctx.out.initArray) {
1536 addInt(DT_INIT_ARRAY, ctx.out.initArray->addr);
1537 addInt(DT_INIT_ARRAYSZ, ctx.out.initArray->size);
1538 }
1539 if (ctx.out.finiArray) {
1540 addInt(DT_FINI_ARRAY, ctx.out.finiArray->addr);
1541 addInt(DT_FINI_ARRAYSZ, ctx.out.finiArray->size);
1542 }
1543
1544 if (Symbol *b = ctx.symtab->find(name: ctx.arg.init))
1545 if (b->isDefined())
1546 addInt(DT_INIT, b->getVA(ctx));
1547 if (Symbol *b = ctx.symtab->find(name: ctx.arg.fini))
1548 if (b->isDefined())
1549 addInt(DT_FINI, b->getVA(ctx));
1550 }
1551
1552 if (part.verSym && part.verSym->isNeeded())
1553 addInSec(DT_VERSYM, *part.verSym);
1554 if (part.verDef && part.verDef->isLive()) {
1555 addInSec(DT_VERDEF, *part.verDef);
1556 addInt(DT_VERDEFNUM, getVerDefNum(ctx));
1557 }
1558 if (part.verNeed && part.verNeed->isNeeded()) {
1559 addInSec(DT_VERNEED, *part.verNeed);
1560 unsigned needNum = 0;
1561 for (SharedFile *f : ctx.sharedFiles)
1562 if (!f->verneedInfo.empty())
1563 ++needNum;
1564 addInt(DT_VERNEEDNUM, needNum);
1565 }
1566
1567 if (ctx.arg.emachine == EM_MIPS) {
1568 addInt(DT_MIPS_RLD_VERSION, 1);
1569 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1570 addInt(DT_MIPS_BASE_ADDRESS, ctx.target->getImageBase());
1571 addInt(DT_MIPS_SYMTABNO, part.dynSymTab->getNumSymbols());
1572 addInt(DT_MIPS_LOCAL_GOTNO, ctx.in.mipsGot->getLocalEntriesNum());
1573
1574 if (const Symbol *b = ctx.in.mipsGot->getFirstGlobalEntry())
1575 addInt(DT_MIPS_GOTSYM, b->dynsymIndex);
1576 else
1577 addInt(DT_MIPS_GOTSYM, part.dynSymTab->getNumSymbols());
1578 addInSec(DT_PLTGOT, *ctx.in.mipsGot);
1579 if (ctx.in.mipsRldMap) {
1580 if (!ctx.arg.pie)
1581 addInSec(DT_MIPS_RLD_MAP, *ctx.in.mipsRldMap);
1582 // Store the offset to the .rld_map section
1583 // relative to the address of the tag.
1584 addInt(DT_MIPS_RLD_MAP_REL,
1585 ctx.in.mipsRldMap->getVA() - (getVA() + entries.size() * entsize));
1586 }
1587 }
1588
1589 // DT_PPC_GOT indicates to glibc Secure PLT is used. If DT_PPC_GOT is absent,
1590 // glibc assumes the old-style BSS PLT layout which we don't support.
1591 if (ctx.arg.emachine == EM_PPC)
1592 addInSec(DT_PPC_GOT, *ctx.in.got);
1593
1594 // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1595 if (ctx.arg.emachine == EM_PPC64 && ctx.in.plt->isNeeded()) {
1596 // The Glink tag points to 32 bytes before the first lazy symbol resolution
1597 // stub, which starts directly after the header.
1598 addInt(DT_PPC64_GLINK,
1599 ctx.in.plt->getVA() + ctx.target->pltHeaderSize - 32);
1600 }
1601
1602 if (ctx.arg.emachine == EM_PPC64)
1603 addInt(DT_PPC64_OPT, ctx.target->ppc64DynamicSectionOpt);
1604
1605 addInt(DT_NULL, 0);
1606 return entries;
1607}
1608
1609template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1610 if (OutputSection *sec = getPartition(ctx).dynStrTab->getParent())
1611 getParent()->link = sec->sectionIndex;
1612 this->size = computeContents().size() * this->entsize;
1613}
1614
1615template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *buf) {
1616 auto *p = reinterpret_cast<Elf_Dyn *>(buf);
1617
1618 for (std::pair<int32_t, uint64_t> kv : computeContents()) {
1619 p->d_tag = kv.first;
1620 p->d_un.d_val = kv.second;
1621 ++p;
1622 }
1623}
1624
1625uint64_t DynamicReloc::getOffset() const {
1626 return inputSec->getVA(offset: offsetInSec);
1627}
1628
1629int64_t DynamicReloc::computeAddend(Ctx &ctx) const {
1630 assert(!isFinal && "addend already computed");
1631 uint64_t ca = inputSec->getRelocTargetVA(
1632 ctx, r: Relocation{.expr: expr, .type: type, .offset: 0, .addend: addend, .sym: sym}, p: getOffset());
1633 return ctx.arg.is64 ? ca : SignExtend64<32>(x: ca);
1634}
1635
1636uint32_t DynamicReloc::getSymIndex(SymbolTableBaseSection *symTab) const {
1637 if (!needsDynSymIndex())
1638 return 0;
1639
1640 size_t index = symTab->getSymbolIndex(sym: *sym);
1641 assert((index != 0 ||
1642 (type != symTab->ctx.target->gotRel &&
1643 type != symTab->ctx.target->pltRel) ||
1644 !symTab->ctx.mainPart->dynSymTab->getParent()) &&
1645 "GOT or PLT relocation must refer to symbol in dynamic symbol table");
1646 return index;
1647}
1648
1649RelocationBaseSection::RelocationBaseSection(Ctx &ctx, StringRef name,
1650 uint32_t type, int32_t dynamicTag,
1651 int32_t sizeDynamicTag,
1652 bool combreloc,
1653 unsigned concurrency)
1654 : SyntheticSection(ctx, name, type, SHF_ALLOC, ctx.arg.wordsize),
1655 dynamicTag(dynamicTag), sizeDynamicTag(sizeDynamicTag),
1656 relocsVec(concurrency), combreloc(combreloc) {}
1657
1658void RelocationBaseSection::addSymbolReloc(
1659 RelType dynType, InputSectionBase &isec, uint64_t offsetInSec, Symbol &sym,
1660 int64_t addend, std::optional<RelType> addendRelType) {
1661 addReloc(isAgainstSymbol: true, dynType, sec&: isec, offsetInSec, sym, addend, expr: R_ADDEND,
1662 addendRelType: addendRelType ? *addendRelType : ctx.target->noneRel);
1663}
1664
1665void RelocationBaseSection::addAddendOnlyRelocIfNonPreemptible(
1666 RelType dynType, InputSectionBase &isec, uint64_t offsetInSec, Symbol &sym,
1667 RelType addendRelType) {
1668 // No need to write an addend to the section for preemptible symbols.
1669 if (sym.isPreemptible)
1670 addReloc(reloc: {dynType, &isec, offsetInSec, true, sym, 0, R_ADDEND});
1671 else
1672 addReloc(isAgainstSymbol: false, dynType, sec&: isec, offsetInSec, sym, addend: 0, expr: R_ABS, addendRelType);
1673}
1674
1675void RelocationBaseSection::mergeRels() {
1676 size_t newSize = relocs.size();
1677 for (const auto &v : relocsVec)
1678 newSize += v.size();
1679 relocs.reserve(N: newSize);
1680 for (const auto &v : relocsVec)
1681 llvm::append_range(C&: relocs, R: v);
1682 relocsVec.clear();
1683}
1684
1685void RelocationBaseSection::partitionRels() {
1686 if (!combreloc)
1687 return;
1688 const RelType relativeRel = ctx.target->relativeRel;
1689 numRelativeRelocs =
1690 std::stable_partition(first: relocs.begin(), last: relocs.end(),
1691 pred: [=](auto &r) { return r.type == relativeRel; }) -
1692 relocs.begin();
1693}
1694
1695void RelocationBaseSection::finalizeContents() {
1696 mergeRels();
1697 // Compute DT_RELACOUNT to be used by part.dynamic.
1698 partitionRels();
1699 SymbolTableBaseSection *symTab = getPartition(ctx).dynSymTab.get();
1700
1701 // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1702 // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1703 // case.
1704 if (symTab && symTab->getParent())
1705 getParent()->link = symTab->getParent()->sectionIndex;
1706 else
1707 getParent()->link = 0;
1708
1709 if (ctx.in.relaPlt.get() == this && ctx.in.gotPlt->getParent()) {
1710 getParent()->flags |= ELF::SHF_INFO_LINK;
1711 getParent()->info = ctx.in.gotPlt->getParent()->sectionIndex;
1712 }
1713}
1714
1715void DynamicReloc::finalize(Ctx &ctx, SymbolTableBaseSection *symt) {
1716 r_offset = getOffset();
1717 r_sym = getSymIndex(symTab: symt);
1718 addend = computeAddend(ctx);
1719 isFinal = true; // Catch errors
1720}
1721
1722void RelocationBaseSection::computeRels() {
1723 SymbolTableBaseSection *symTab = getPartition(ctx).dynSymTab.get();
1724 parallelForEach(R&: relocs, Fn: [&ctx = ctx, symTab](DynamicReloc &rel) {
1725 rel.finalize(ctx, symt: symTab);
1726 });
1727
1728 auto irelative = std::stable_partition(
1729 first: relocs.begin() + numRelativeRelocs, last: relocs.end(),
1730 pred: [t = ctx.target->iRelativeRel](auto &r) { return r.type != t; });
1731
1732 // Sort by (!IsRelative,SymIndex,r_offset). DT_REL[A]COUNT requires us to
1733 // place R_*_RELATIVE first. SymIndex is to improve locality, while r_offset
1734 // is to make results easier to read.
1735 if (combreloc) {
1736 auto nonRelative = relocs.begin() + numRelativeRelocs;
1737 parallelSort(Start: relocs.begin(), End: nonRelative,
1738 Comp: [&](auto &a, auto &b) { return a.r_offset < b.r_offset; });
1739 // Non-relative relocations are few, so don't bother with parallelSort.
1740 llvm::sort(Start: nonRelative, End: irelative, Comp: [&](auto &a, auto &b) {
1741 return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset);
1742 });
1743 }
1744}
1745
1746template <class ELFT>
1747RelocationSection<ELFT>::RelocationSection(Ctx &ctx, StringRef name,
1748 bool combreloc, unsigned concurrency)
1749 : RelocationBaseSection(ctx, name, ctx.arg.isRela ? SHT_RELA : SHT_REL,
1750 ctx.arg.isRela ? DT_RELA : DT_REL,
1751 ctx.arg.isRela ? DT_RELASZ : DT_RELSZ, combreloc,
1752 concurrency) {
1753 this->entsize = ctx.arg.isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1754}
1755
1756template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *buf) {
1757 computeRels();
1758 for (const DynamicReloc &rel : relocs) {
1759 auto *p = reinterpret_cast<Elf_Rela *>(buf);
1760 p->r_offset = rel.r_offset;
1761 p->setSymbolAndType(rel.r_sym, rel.type, ctx.arg.isMips64EL);
1762 if (ctx.arg.isRela)
1763 p->r_addend = rel.addend;
1764 buf += ctx.arg.isRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1765 }
1766}
1767
1768RelrBaseSection::RelrBaseSection(Ctx &ctx, unsigned concurrency,
1769 bool isAArch64Auth)
1770 : SyntheticSection(
1771 ctx, isAArch64Auth ? ".relr.auth.dyn" : ".relr.dyn",
1772 isAArch64Auth
1773 ? SHT_AARCH64_AUTH_RELR
1774 : (ctx.arg.useAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR),
1775 SHF_ALLOC, ctx.arg.wordsize),
1776 relocsVec(concurrency) {}
1777
1778void RelrBaseSection::mergeRels() {
1779 size_t newSize = relocs.size();
1780 for (const auto &v : relocsVec)
1781 newSize += v.size();
1782 relocs.reserve(N: newSize);
1783 for (const auto &v : relocsVec)
1784 llvm::append_range(C&: relocs, R: v);
1785 relocsVec.clear();
1786}
1787
1788void RelrBaseSection::finalizeContents() { mergeRels(); }
1789
1790template <class ELFT>
1791AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1792 Ctx &ctx, StringRef name, unsigned concurrency)
1793 : RelocationBaseSection(
1794 ctx, name, ctx.arg.isRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1795 ctx.arg.isRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1796 ctx.arg.isRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ,
1797 /*combreloc=*/false, concurrency) {
1798 this->entsize = 1;
1799}
1800
1801template <class ELFT>
1802bool AndroidPackedRelocationSection<ELFT>::updateAllocSize(Ctx &ctx) {
1803 // This function computes the contents of an Android-format packed relocation
1804 // section.
1805 //
1806 // This format compresses relocations by using relocation groups to factor out
1807 // fields that are common between relocations and storing deltas from previous
1808 // relocations in SLEB128 format (which has a short representation for small
1809 // numbers). A good example of a relocation type with common fields is
1810 // R_*_RELATIVE, which is normally used to represent function pointers in
1811 // vtables. In the REL format, each relative relocation has the same r_info
1812 // field, and is only different from other relative relocations in terms of
1813 // the r_offset field. By sorting relocations by offset, grouping them by
1814 // r_info and representing each relocation with only the delta from the
1815 // previous offset, each 8-byte relocation can be compressed to as little as 1
1816 // byte (or less with run-length encoding). This relocation packer was able to
1817 // reduce the size of the relocation section in an Android Chromium DSO from
1818 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1819 //
1820 // A relocation section consists of a header containing the literal bytes
1821 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1822 // elements are the total number of relocations in the section and an initial
1823 // r_offset value. The remaining elements define a sequence of relocation
1824 // groups. Each relocation group starts with a header consisting of the
1825 // following elements:
1826 //
1827 // - the number of relocations in the relocation group
1828 // - flags for the relocation group
1829 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1830 // for each relocation in the group.
1831 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1832 // field for each relocation in the group.
1833 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1834 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1835 // each relocation in the group.
1836 //
1837 // Following the relocation group header are descriptions of each of the
1838 // relocations in the group. They consist of the following elements:
1839 //
1840 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1841 // delta for this relocation.
1842 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1843 // field for this relocation.
1844 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1845 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1846 // this relocation.
1847
1848 size_t oldSize = relocData.size();
1849
1850 relocData = {'A', 'P', 'S', '2'};
1851 raw_svector_ostream os(relocData);
1852 auto add = [&](int64_t v) { encodeSLEB128(Value: v, OS&: os); };
1853
1854 // The format header includes the number of relocations and the initial
1855 // offset (we set this to zero because the first relocation group will
1856 // perform the initial adjustment).
1857 add(relocs.size());
1858 add(0);
1859
1860 std::vector<Elf_Rela> relatives, nonRelatives;
1861
1862 for (const DynamicReloc &rel : relocs) {
1863 Elf_Rela r;
1864 r.r_offset = rel.getOffset();
1865 r.setSymbolAndType(rel.getSymIndex(symTab: getPartition(ctx).dynSymTab.get()),
1866 rel.type, false);
1867 r.r_addend = ctx.arg.isRela ? rel.computeAddend(ctx) : 0;
1868
1869 if (r.getType(ctx.arg.isMips64EL) == ctx.target->relativeRel)
1870 relatives.push_back(r);
1871 else
1872 nonRelatives.push_back(r);
1873 }
1874
1875 llvm::sort(relatives, [](const Elf_Rel &a, const Elf_Rel &b) {
1876 return a.r_offset < b.r_offset;
1877 });
1878
1879 // Try to find groups of relative relocations which are spaced one word
1880 // apart from one another. These generally correspond to vtable entries. The
1881 // format allows these groups to be encoded using a sort of run-length
1882 // encoding, but each group will cost 7 bytes in addition to the offset from
1883 // the previous group, so it is only profitable to do this for groups of
1884 // size 8 or larger.
1885 std::vector<Elf_Rela> ungroupedRelatives;
1886 std::vector<std::vector<Elf_Rela>> relativeGroups;
1887 for (auto i = relatives.begin(), e = relatives.end(); i != e;) {
1888 std::vector<Elf_Rela> group;
1889 do {
1890 group.push_back(*i++);
1891 } while (i != e && (i - 1)->r_offset + ctx.arg.wordsize == i->r_offset);
1892
1893 if (group.size() < 8)
1894 ungroupedRelatives.insert(ungroupedRelatives.end(), group.begin(),
1895 group.end());
1896 else
1897 relativeGroups.emplace_back(std::move(group));
1898 }
1899
1900 // For non-relative relocations, we would like to:
1901 // 1. Have relocations with the same symbol offset to be consecutive, so
1902 // that the runtime linker can speed-up symbol lookup by implementing an
1903 // 1-entry cache.
1904 // 2. Group relocations by r_info to reduce the size of the relocation
1905 // section.
1906 // Since the symbol offset is the high bits in r_info, sorting by r_info
1907 // allows us to do both.
1908 //
1909 // For Rela, we also want to sort by r_addend when r_info is the same. This
1910 // enables us to group by r_addend as well.
1911 llvm::sort(nonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1912 return std::tie(a.r_info, a.r_addend, a.r_offset) <
1913 std::tie(b.r_info, b.r_addend, b.r_offset);
1914 });
1915
1916 // Group relocations with the same r_info. Note that each group emits a group
1917 // header and that may make the relocation section larger. It is hard to
1918 // estimate the size of a group header as the encoded size of that varies
1919 // based on r_info. However, we can approximate this trade-off by the number
1920 // of values encoded. Each group header contains 3 values, and each relocation
1921 // in a group encodes one less value, as compared to when it is not grouped.
1922 // Therefore, we only group relocations if there are 3 or more of them with
1923 // the same r_info.
1924 //
1925 // For Rela, the addend for most non-relative relocations is zero, and thus we
1926 // can usually get a smaller relocation section if we group relocations with 0
1927 // addend as well.
1928 std::vector<Elf_Rela> ungroupedNonRelatives;
1929 std::vector<std::vector<Elf_Rela>> nonRelativeGroups;
1930 for (auto i = nonRelatives.begin(), e = nonRelatives.end(); i != e;) {
1931 auto j = i + 1;
1932 while (j != e && i->r_info == j->r_info &&
1933 (!ctx.arg.isRela || i->r_addend == j->r_addend))
1934 ++j;
1935 if (j - i < 3 || (ctx.arg.isRela && i->r_addend != 0))
1936 ungroupedNonRelatives.insert(ungroupedNonRelatives.end(), i, j);
1937 else
1938 nonRelativeGroups.emplace_back(i, j);
1939 i = j;
1940 }
1941
1942 // Sort ungrouped relocations by offset to minimize the encoded length.
1943 llvm::sort(ungroupedNonRelatives, [](const Elf_Rela &a, const Elf_Rela &b) {
1944 return a.r_offset < b.r_offset;
1945 });
1946
1947 unsigned hasAddendIfRela =
1948 ctx.arg.isRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1949
1950 uint64_t offset = 0;
1951 uint64_t addend = 0;
1952
1953 // Emit the run-length encoding for the groups of adjacent relative
1954 // relocations. Each group is represented using two groups in the packed
1955 // format. The first is used to set the current offset to the start of the
1956 // group (and also encodes the first relocation), and the second encodes the
1957 // remaining relocations.
1958 for (std::vector<Elf_Rela> &g : relativeGroups) {
1959 // The first relocation in the group.
1960 add(1);
1961 add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1962 RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1963 add(g[0].r_offset - offset);
1964 add(ctx.target->relativeRel);
1965 if (ctx.arg.isRela) {
1966 add(g[0].r_addend - addend);
1967 addend = g[0].r_addend;
1968 }
1969
1970 // The remaining relocations.
1971 add(g.size() - 1);
1972 add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1973 RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1974 add(ctx.arg.wordsize);
1975 add(ctx.target->relativeRel);
1976 if (ctx.arg.isRela) {
1977 for (const auto &i : llvm::drop_begin(g)) {
1978 add(i.r_addend - addend);
1979 addend = i.r_addend;
1980 }
1981 }
1982
1983 offset = g.back().r_offset;
1984 }
1985
1986 // Now the ungrouped relatives.
1987 if (!ungroupedRelatives.empty()) {
1988 add(ungroupedRelatives.size());
1989 add(RELOCATION_GROUPED_BY_INFO_FLAG | hasAddendIfRela);
1990 add(ctx.target->relativeRel);
1991 for (Elf_Rela &r : ungroupedRelatives) {
1992 add(r.r_offset - offset);
1993 offset = r.r_offset;
1994 if (ctx.arg.isRela) {
1995 add(r.r_addend - addend);
1996 addend = r.r_addend;
1997 }
1998 }
1999 }
2000
2001 // Grouped non-relatives.
2002 for (ArrayRef<Elf_Rela> g : nonRelativeGroups) {
2003 add(g.size());
2004 add(RELOCATION_GROUPED_BY_INFO_FLAG);
2005 add(g[0].r_info);
2006 for (const Elf_Rela &r : g) {
2007 add(r.r_offset - offset);
2008 offset = r.r_offset;
2009 }
2010 addend = 0;
2011 }
2012
2013 // Finally the ungrouped non-relative relocations.
2014 if (!ungroupedNonRelatives.empty()) {
2015 add(ungroupedNonRelatives.size());
2016 add(hasAddendIfRela);
2017 for (Elf_Rela &r : ungroupedNonRelatives) {
2018 add(r.r_offset - offset);
2019 offset = r.r_offset;
2020 add(r.r_info);
2021 if (ctx.arg.isRela) {
2022 add(r.r_addend - addend);
2023 addend = r.r_addend;
2024 }
2025 }
2026 }
2027
2028 // Don't allow the section to shrink; otherwise the size of the section can
2029 // oscillate infinitely.
2030 if (relocData.size() < oldSize)
2031 relocData.append(NumInputs: oldSize - relocData.size(), Elt: 0);
2032
2033 // Returns whether the section size changed. We need to keep recomputing both
2034 // section layout and the contents of this section until the size converges
2035 // because changing this section's size can affect section layout, which in
2036 // turn can affect the sizes of the LEB-encoded integers stored in this
2037 // section.
2038 return relocData.size() != oldSize;
2039}
2040
2041template <class ELFT>
2042RelrSection<ELFT>::RelrSection(Ctx &ctx, unsigned concurrency,
2043 bool isAArch64Auth)
2044 : RelrBaseSection(ctx, concurrency, isAArch64Auth) {
2045 this->entsize = ctx.arg.wordsize;
2046}
2047
2048template <class ELFT> bool RelrSection<ELFT>::updateAllocSize(Ctx &ctx) {
2049 // This function computes the contents of an SHT_RELR packed relocation
2050 // section.
2051 //
2052 // Proposal for adding SHT_RELR sections to generic-abi is here:
2053 // https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
2054 //
2055 // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
2056 // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
2057 //
2058 // i.e. start with an address, followed by any number of bitmaps. The address
2059 // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
2060 // relocations each, at subsequent offsets following the last address entry.
2061 //
2062 // The bitmap entries must have 1 in the least significant bit. The assumption
2063 // here is that an address cannot have 1 in lsb. Odd addresses are not
2064 // supported.
2065 //
2066 // Excluding the least significant bit in the bitmap, each non-zero bit in
2067 // the bitmap represents a relocation to be applied to a corresponding machine
2068 // word that follows the base address word. The second least significant bit
2069 // represents the machine word immediately following the initial address, and
2070 // each bit that follows represents the next word, in linear order. As such,
2071 // a single bitmap can encode up to 31 relocations in a 32-bit object, and
2072 // 63 relocations in a 64-bit object.
2073 //
2074 // This encoding has a couple of interesting properties:
2075 // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
2076 // even means address, odd means bitmap.
2077 // 2. Just a simple list of addresses is a valid encoding.
2078
2079 size_t oldSize = relrRelocs.size();
2080 relrRelocs.clear();
2081
2082 const size_t wordsize = sizeof(typename ELFT::uint);
2083
2084 // Number of bits to use for the relocation offsets bitmap.
2085 // Must be either 63 or 31.
2086 const size_t nBits = wordsize * 8 - 1;
2087
2088 // Get offsets for all relative relocations and sort them.
2089 std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]);
2090 for (auto [i, r] : llvm::enumerate(relocs))
2091 offsets[i] = r.getOffset();
2092 llvm::sort(offsets.get(), offsets.get() + relocs.size());
2093
2094 // For each leading relocation, find following ones that can be folded
2095 // as a bitmap and fold them.
2096 for (size_t i = 0, e = relocs.size(); i != e;) {
2097 // Add a leading relocation.
2098 relrRelocs.push_back(Elf_Relr(offsets[i]));
2099 uint64_t base = offsets[i] + wordsize;
2100 ++i;
2101
2102 // Find foldable relocations to construct bitmaps.
2103 for (;;) {
2104 uint64_t bitmap = 0;
2105 for (; i != e; ++i) {
2106 uint64_t d = offsets[i] - base;
2107 if (d >= nBits * wordsize || d % wordsize)
2108 break;
2109 bitmap |= uint64_t(1) << (d / wordsize);
2110 }
2111 if (!bitmap)
2112 break;
2113 relrRelocs.push_back(Elf_Relr((bitmap << 1) | 1));
2114 base += nBits * wordsize;
2115 }
2116 }
2117
2118 // Don't allow the section to shrink; otherwise the size of the section can
2119 // oscillate infinitely. Trailing 1s do not decode to more relocations.
2120 if (relrRelocs.size() < oldSize) {
2121 Log(ctx) << ".relr.dyn needs " << (oldSize - relrRelocs.size())
2122 << " padding word(s)";
2123 relrRelocs.resize(oldSize, Elf_Relr(1));
2124 }
2125
2126 return relrRelocs.size() != oldSize;
2127}
2128
2129SymbolTableBaseSection::SymbolTableBaseSection(Ctx &ctx,
2130 StringTableSection &strTabSec)
2131 : SyntheticSection(ctx, strTabSec.isDynamic() ? ".dynsym" : ".symtab",
2132 strTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
2133 strTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
2134 ctx.arg.wordsize),
2135 strTabSec(strTabSec) {}
2136
2137// Orders symbols according to their positions in the GOT,
2138// in compliance with MIPS ABI rules.
2139// See "Global Offset Table" in Chapter 5 in the following document
2140// for detailed description:
2141// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2142static void sortMipsSymbols(Ctx &ctx, SmallVector<SymbolTableEntry, 0> &syms) {
2143 llvm::stable_sort(Range&: syms,
2144 C: [&](const SymbolTableEntry &l, const SymbolTableEntry &r) {
2145 // Sort entries related to non-local preemptible symbols
2146 // by GOT indexes. All other entries go to the beginning
2147 // of a dynsym in arbitrary order.
2148 if (l.sym->isInGot(ctx) && r.sym->isInGot(ctx))
2149 return l.sym->getGotIdx(ctx) < r.sym->getGotIdx(ctx);
2150 if (!l.sym->isInGot(ctx) && !r.sym->isInGot(ctx))
2151 return false;
2152 return !l.sym->isInGot(ctx);
2153 });
2154}
2155
2156void SymbolTableBaseSection::finalizeContents() {
2157 if (OutputSection *sec = strTabSec.getParent())
2158 getParent()->link = sec->sectionIndex;
2159
2160 if (this->type != SHT_DYNSYM) {
2161 sortSymTabSymbols();
2162 return;
2163 }
2164
2165 // If it is a .dynsym, there should be no local symbols, but we need
2166 // to do a few things for the dynamic linker.
2167
2168 // Section's Info field has the index of the first non-local symbol.
2169 // Because the first symbol entry is a null entry, 1 is the first.
2170 getParent()->info = 1;
2171
2172 if (getPartition(ctx).gnuHashTab) {
2173 // NB: It also sorts Symbols to meet the GNU hash table requirements.
2174 getPartition(ctx).gnuHashTab->addSymbols(symbols);
2175 } else if (ctx.arg.emachine == EM_MIPS) {
2176 sortMipsSymbols(ctx, syms&: symbols);
2177 }
2178
2179 // Only the main partition's dynsym indexes are stored in the symbols
2180 // themselves. All other partitions use a lookup table.
2181 if (this == ctx.mainPart->dynSymTab.get()) {
2182 size_t i = 0;
2183 for (const SymbolTableEntry &s : symbols)
2184 s.sym->dynsymIndex = ++i;
2185 }
2186}
2187
2188// The ELF spec requires that all local symbols precede global symbols, so we
2189// sort symbol entries in this function. (For .dynsym, we don't do that because
2190// symbols for dynamic linking are inherently all globals.)
2191//
2192// Aside from above, we put local symbols in groups starting with the STT_FILE
2193// symbol. That is convenient for purpose of identifying where are local symbols
2194// coming from.
2195void SymbolTableBaseSection::sortSymTabSymbols() {
2196 // Move all local symbols before global symbols.
2197 auto e = std::stable_partition(
2198 first: symbols.begin(), last: symbols.end(),
2199 pred: [](const SymbolTableEntry &s) { return s.sym->isLocal(); });
2200 size_t numLocals = e - symbols.begin();
2201 getParent()->info = numLocals + 1;
2202
2203 // We want to group the local symbols by file. For that we rebuild the local
2204 // part of the symbols vector. We do not need to care about the STT_FILE
2205 // symbols, they are already naturally placed first in each group. That
2206 // happens because STT_FILE is always the first symbol in the object and hence
2207 // precede all other local symbols we add for a file.
2208 MapVector<InputFile *, SmallVector<SymbolTableEntry, 0>> arr;
2209 for (const SymbolTableEntry &s : llvm::make_range(x: symbols.begin(), y: e))
2210 arr[s.sym->file].push_back(Elt: s);
2211
2212 auto i = symbols.begin();
2213 for (auto &p : arr)
2214 for (SymbolTableEntry &entry : p.second)
2215 *i++ = entry;
2216}
2217
2218void SymbolTableBaseSection::addSymbol(Symbol *b) {
2219 // Adding a local symbol to a .dynsym is a bug.
2220 assert(this->type != SHT_DYNSYM || !b->isLocal());
2221 symbols.push_back(Elt: {.sym: b, .strTabOffset: strTabSec.addString(s: b->getName(), hashIt: false)});
2222}
2223
2224size_t SymbolTableBaseSection::getSymbolIndex(const Symbol &sym) {
2225 if (this == ctx.mainPart->dynSymTab.get())
2226 return sym.dynsymIndex;
2227
2228 // Initializes symbol lookup tables lazily. This is used only for -r,
2229 // --emit-relocs and dynsyms in partitions other than the main one.
2230 llvm::call_once(flag&: onceFlag, F: [&] {
2231 symbolIndexMap.reserve(NumEntries: symbols.size());
2232 size_t i = 0;
2233 for (const SymbolTableEntry &e : symbols) {
2234 if (e.sym->type == STT_SECTION)
2235 sectionIndexMap[e.sym->getOutputSection()] = ++i;
2236 else
2237 symbolIndexMap[e.sym] = ++i;
2238 }
2239 });
2240
2241 // Section symbols are mapped based on their output sections
2242 // to maintain their semantics.
2243 if (sym.type == STT_SECTION)
2244 return sectionIndexMap.lookup(Val: sym.getOutputSection());
2245 return symbolIndexMap.lookup(Val: &sym);
2246}
2247
2248template <class ELFT>
2249SymbolTableSection<ELFT>::SymbolTableSection(Ctx &ctx,
2250 StringTableSection &strTabSec)
2251 : SymbolTableBaseSection(ctx, strTabSec) {
2252 this->entsize = sizeof(Elf_Sym);
2253}
2254
2255static BssSection *getCommonSec(bool relocatable, Symbol *sym) {
2256 if (relocatable)
2257 if (auto *d = dyn_cast<Defined>(Val: sym))
2258 return dyn_cast_or_null<BssSection>(Val: d->section);
2259 return nullptr;
2260}
2261
2262static uint32_t getSymSectionIndex(Symbol *sym) {
2263 assert(!(sym->hasFlag(NEEDS_COPY) && sym->isObject()));
2264 if (!isa<Defined>(Val: sym) || sym->hasFlag(bit: NEEDS_COPY))
2265 return SHN_UNDEF;
2266 if (const OutputSection *os = sym->getOutputSection())
2267 return os->sectionIndex >= SHN_LORESERVE ? (uint32_t)SHN_XINDEX
2268 : os->sectionIndex;
2269 return SHN_ABS;
2270}
2271
2272// Write the internal symbol table contents to the output symbol table.
2273template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *buf) {
2274 // The first entry is a null entry as per the ELF spec.
2275 buf += sizeof(Elf_Sym);
2276
2277 auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2278 bool relocatable = ctx.arg.relocatable;
2279 for (SymbolTableEntry &ent : symbols) {
2280 Symbol *sym = ent.sym;
2281 bool isDefinedHere = type == SHT_SYMTAB || sym->partition == partition;
2282
2283 // Set st_name, st_info and st_other.
2284 eSym->st_name = ent.strTabOffset;
2285 eSym->setBindingAndType(sym->binding, sym->type);
2286 eSym->st_other = sym->stOther;
2287
2288 if (BssSection *commonSec = getCommonSec(relocatable, sym)) {
2289 // When -r is specified, a COMMON symbol is not allocated. Its st_shndx
2290 // holds SHN_COMMON and st_value holds the alignment.
2291 eSym->st_shndx = SHN_COMMON;
2292 eSym->st_value = commonSec->addralign;
2293 eSym->st_size = cast<Defined>(Val: sym)->size;
2294 } else {
2295 const uint32_t shndx = getSymSectionIndex(sym);
2296 if (isDefinedHere) {
2297 eSym->st_shndx = shndx;
2298 eSym->st_value = sym->getVA(ctx);
2299 // Copy symbol size if it is a defined symbol. st_size is not
2300 // significant for undefined symbols, so whether copying it or not is up
2301 // to us if that's the case. We'll leave it as zero because by not
2302 // setting a value, we can get the exact same outputs for two sets of
2303 // input files that differ only in undefined symbol size in DSOs.
2304 eSym->st_size = shndx != SHN_UNDEF ? cast<Defined>(Val: sym)->size : 0;
2305 } else {
2306 eSym->st_shndx = 0;
2307 eSym->st_value = 0;
2308 eSym->st_size = 0;
2309 }
2310 }
2311
2312 ++eSym;
2313 }
2314
2315 // On MIPS we need to mark symbol which has a PLT entry and requires
2316 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
2317 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
2318 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
2319 if (ctx.arg.emachine == EM_MIPS) {
2320 auto *eSym = reinterpret_cast<Elf_Sym *>(buf);
2321
2322 for (SymbolTableEntry &ent : symbols) {
2323 Symbol *sym = ent.sym;
2324 if (sym->isInPlt(ctx) && sym->hasFlag(bit: NEEDS_COPY))
2325 eSym->st_other |= STO_MIPS_PLT;
2326 if (isMicroMips(ctx)) {
2327 // We already set the less-significant bit for symbols
2328 // marked by the `STO_MIPS_MICROMIPS` flag and for microMIPS PLT
2329 // records. That allows us to distinguish such symbols in
2330 // the `MIPS<ELFT>::relocate()` routine. Now we should
2331 // clear that bit for non-dynamic symbol table, so tools
2332 // like `objdump` will be able to deal with a correct
2333 // symbol position.
2334 if (sym->isDefined() &&
2335 ((sym->stOther & STO_MIPS_MICROMIPS) || sym->hasFlag(bit: NEEDS_COPY))) {
2336 if (!strTabSec.isDynamic())
2337 eSym->st_value &= ~1;
2338 eSym->st_other |= STO_MIPS_MICROMIPS;
2339 }
2340 }
2341 if (ctx.arg.relocatable)
2342 if (auto *d = dyn_cast<Defined>(Val: sym))
2343 if (isMipsPIC<ELFT>(d))
2344 eSym->st_other |= STO_MIPS_PIC;
2345 ++eSym;
2346 }
2347 }
2348}
2349
2350SymtabShndxSection::SymtabShndxSection(Ctx &ctx)
2351 : SyntheticSection(ctx, ".symtab_shndx", SHT_SYMTAB_SHNDX, 0, 4) {
2352 this->entsize = 4;
2353}
2354
2355void SymtabShndxSection::writeTo(uint8_t *buf) {
2356 // We write an array of 32 bit values, where each value has 1:1 association
2357 // with an entry in ctx.in.symTab if the corresponding entry contains
2358 // SHN_XINDEX, we need to write actual index, otherwise, we must write
2359 // SHN_UNDEF(0).
2360 buf += 4; // Ignore .symtab[0] entry.
2361 bool relocatable = ctx.arg.relocatable;
2362 for (const SymbolTableEntry &entry : ctx.in.symTab->getSymbols()) {
2363 if (!getCommonSec(relocatable, sym: entry.sym) &&
2364 getSymSectionIndex(sym: entry.sym) == SHN_XINDEX)
2365 write32(ctx, p: buf, v: entry.sym->getOutputSection()->sectionIndex);
2366 buf += 4;
2367 }
2368}
2369
2370bool SymtabShndxSection::isNeeded() const {
2371 // SHT_SYMTAB can hold symbols with section indices values up to
2372 // SHN_LORESERVE. If we need more, we want to use extension SHT_SYMTAB_SHNDX
2373 // section. Problem is that we reveal the final section indices a bit too
2374 // late, and we do not know them here. For simplicity, we just always create
2375 // a .symtab_shndx section when the amount of output sections is huge.
2376 size_t size = 0;
2377 for (SectionCommand *cmd : ctx.script->sectionCommands)
2378 if (isa<OutputDesc>(Val: cmd))
2379 ++size;
2380 return size >= SHN_LORESERVE;
2381}
2382
2383void SymtabShndxSection::finalizeContents() {
2384 getParent()->link = ctx.in.symTab->getParent()->sectionIndex;
2385}
2386
2387size_t SymtabShndxSection::getSize() const {
2388 return ctx.in.symTab->getNumSymbols() * 4;
2389}
2390
2391// .hash and .gnu.hash sections contain on-disk hash tables that map
2392// symbol names to their dynamic symbol table indices. Their purpose
2393// is to help the dynamic linker resolve symbols quickly. If ELF files
2394// don't have them, the dynamic linker has to do linear search on all
2395// dynamic symbols, which makes programs slower. Therefore, a .hash
2396// section is added to a DSO by default.
2397//
2398// The Unix semantics of resolving dynamic symbols is somewhat expensive.
2399// Each ELF file has a list of DSOs that the ELF file depends on and a
2400// list of dynamic symbols that need to be resolved from any of the
2401// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
2402// where m is the number of DSOs and n is the number of dynamic
2403// symbols. For modern large programs, both m and n are large. So
2404// making each step faster by using hash tables substantially
2405// improves time to load programs.
2406//
2407// (Note that this is not the only way to design the shared library.
2408// For instance, the Windows DLL takes a different approach. On
2409// Windows, each dynamic symbol has a name of DLL from which the symbol
2410// has to be resolved. That makes the cost of symbol resolution O(n).
2411// This disables some hacky techniques you can use on Unix such as
2412// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
2413//
2414// Due to historical reasons, we have two different hash tables, .hash
2415// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
2416// and better version of .hash. .hash is just an on-disk hash table, but
2417// .gnu.hash has a bloom filter in addition to a hash table to skip
2418// DSOs very quickly. If you are sure that your dynamic linker knows
2419// about .gnu.hash, you want to specify --hash-style=gnu. Otherwise, a
2420// safe bet is to specify --hash-style=both for backward compatibility.
2421GnuHashTableSection::GnuHashTableSection(Ctx &ctx)
2422 : SyntheticSection(ctx, ".gnu.hash", SHT_GNU_HASH, SHF_ALLOC,
2423 ctx.arg.wordsize) {}
2424
2425void GnuHashTableSection::finalizeContents() {
2426 if (OutputSection *sec = getPartition(ctx).dynSymTab->getParent())
2427 getParent()->link = sec->sectionIndex;
2428
2429 // Computes bloom filter size in word size. We want to allocate 12
2430 // bits for each symbol. It must be a power of two.
2431 if (symbols.empty()) {
2432 maskWords = 1;
2433 } else {
2434 uint64_t numBits = symbols.size() * 12;
2435 maskWords = NextPowerOf2(A: numBits / (ctx.arg.wordsize * 8));
2436 }
2437
2438 size = 16; // Header
2439 size += ctx.arg.wordsize * maskWords; // Bloom filter
2440 size += nBuckets * 4; // Hash buckets
2441 size += symbols.size() * 4; // Hash values
2442}
2443
2444void GnuHashTableSection::writeTo(uint8_t *buf) {
2445 // Write a header.
2446 write32(ctx, p: buf, v: nBuckets);
2447 write32(ctx, p: buf + 4,
2448 v: getPartition(ctx).dynSymTab->getNumSymbols() - symbols.size());
2449 write32(ctx, p: buf + 8, v: maskWords);
2450 write32(ctx, p: buf + 12, v: Shift2);
2451 buf += 16;
2452
2453 // Write the 2-bit bloom filter.
2454 const unsigned c = ctx.arg.is64 ? 64 : 32;
2455 for (const Entry &sym : symbols) {
2456 // When C = 64, we choose a word with bits [6:...] and set 1 to two bits in
2457 // the word using bits [0:5] and [26:31].
2458 size_t i = (sym.hash / c) & (maskWords - 1);
2459 uint64_t val = readUint(ctx, buf: buf + i * ctx.arg.wordsize);
2460 val |= uint64_t(1) << (sym.hash % c);
2461 val |= uint64_t(1) << ((sym.hash >> Shift2) % c);
2462 writeUint(ctx, buf: buf + i * ctx.arg.wordsize, val);
2463 }
2464 buf += ctx.arg.wordsize * maskWords;
2465
2466 // Write the hash table.
2467 uint32_t *buckets = reinterpret_cast<uint32_t *>(buf);
2468 uint32_t oldBucket = -1;
2469 uint32_t *values = buckets + nBuckets;
2470 for (auto i = symbols.begin(), e = symbols.end(); i != e; ++i) {
2471 // Write a hash value. It represents a sequence of chains that share the
2472 // same hash modulo value. The last element of each chain is terminated by
2473 // LSB 1.
2474 uint32_t hash = i->hash;
2475 bool isLastInChain = (i + 1) == e || i->bucketIdx != (i + 1)->bucketIdx;
2476 hash = isLastInChain ? hash | 1 : hash & ~1;
2477 write32(ctx, p: values++, v: hash);
2478
2479 if (i->bucketIdx == oldBucket)
2480 continue;
2481 // Write a hash bucket. Hash buckets contain indices in the following hash
2482 // value table.
2483 write32(ctx, p: buckets + i->bucketIdx,
2484 v: getPartition(ctx).dynSymTab->getSymbolIndex(sym: *i->sym));
2485 oldBucket = i->bucketIdx;
2486 }
2487}
2488
2489// Add symbols to this symbol hash table. Note that this function
2490// destructively sort a given vector -- which is needed because
2491// GNU-style hash table places some sorting requirements.
2492void GnuHashTableSection::addSymbols(SmallVectorImpl<SymbolTableEntry> &v) {
2493 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2494 // its type correctly.
2495 auto mid =
2496 std::stable_partition(first: v.begin(), last: v.end(), pred: [&](const SymbolTableEntry &s) {
2497 return !s.sym->isDefined() || s.sym->partition != partition;
2498 });
2499
2500 // We chose load factor 4 for the on-disk hash table. For each hash
2501 // collision, the dynamic linker will compare a uint32_t hash value.
2502 // Since the integer comparison is quite fast, we believe we can
2503 // make the load factor even larger. 4 is just a conservative choice.
2504 //
2505 // Note that we don't want to create a zero-sized hash table because
2506 // Android loader as of 2018 doesn't like a .gnu.hash containing such
2507 // table. If that's the case, we create a hash table with one unused
2508 // dummy slot.
2509 nBuckets = std::max<size_t>(a: (v.end() - mid) / 4, b: 1);
2510
2511 if (mid == v.end())
2512 return;
2513
2514 for (SymbolTableEntry &ent : llvm::make_range(x: mid, y: v.end())) {
2515 Symbol *b = ent.sym;
2516 uint32_t hash = hashGnu(Name: b->getName());
2517 uint32_t bucketIdx = hash % nBuckets;
2518 symbols.push_back(Elt: {.sym: b, .strTabOffset: ent.strTabOffset, .hash: hash, .bucketIdx: bucketIdx});
2519 }
2520
2521 llvm::sort(C&: symbols, Comp: [](const Entry &l, const Entry &r) {
2522 return std::tie(args: l.bucketIdx, args: l.strTabOffset) <
2523 std::tie(args: r.bucketIdx, args: r.strTabOffset);
2524 });
2525
2526 v.erase(CS: mid, CE: v.end());
2527 for (const Entry &ent : symbols)
2528 v.push_back(Elt: {.sym: ent.sym, .strTabOffset: ent.strTabOffset});
2529}
2530
2531HashTableSection::HashTableSection(Ctx &ctx)
2532 : SyntheticSection(ctx, ".hash", SHT_HASH, SHF_ALLOC, 4) {
2533 this->entsize = 4;
2534}
2535
2536void HashTableSection::finalizeContents() {
2537 SymbolTableBaseSection *symTab = getPartition(ctx).dynSymTab.get();
2538
2539 if (OutputSection *sec = symTab->getParent())
2540 getParent()->link = sec->sectionIndex;
2541
2542 unsigned numEntries = 2; // nbucket and nchain.
2543 numEntries += symTab->getNumSymbols(); // The chain entries.
2544
2545 // Create as many buckets as there are symbols.
2546 numEntries += symTab->getNumSymbols();
2547 this->size = numEntries * 4;
2548}
2549
2550void HashTableSection::writeTo(uint8_t *buf) {
2551 SymbolTableBaseSection *symTab = getPartition(ctx).dynSymTab.get();
2552 unsigned numSymbols = symTab->getNumSymbols();
2553
2554 uint32_t *p = reinterpret_cast<uint32_t *>(buf);
2555 write32(ctx, p: p++, v: numSymbols); // nbucket
2556 write32(ctx, p: p++, v: numSymbols); // nchain
2557
2558 uint32_t *buckets = p;
2559 uint32_t *chains = p + numSymbols;
2560
2561 for (const SymbolTableEntry &s : symTab->getSymbols()) {
2562 Symbol *sym = s.sym;
2563 StringRef name = sym->getName();
2564 unsigned i = sym->dynsymIndex;
2565 uint32_t hash = hashSysV(SymbolName: name) % numSymbols;
2566 chains[i] = buckets[hash];
2567 write32(ctx, p: buckets + hash, v: i);
2568 }
2569}
2570
2571PltSection::PltSection(Ctx &ctx)
2572 : SyntheticSection(ctx, ".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR,
2573 16),
2574 headerSize(ctx.target->pltHeaderSize) {
2575 // On AArch64, PLT entries only do loads from the .got.plt section, so the
2576 // .plt section can be marked with the SHF_AARCH64_PURECODE section flag.
2577 if (ctx.arg.emachine == EM_AARCH64)
2578 this->flags |= SHF_AARCH64_PURECODE;
2579
2580 // On PowerPC, this section contains lazy symbol resolvers.
2581 if (ctx.arg.emachine == EM_PPC64) {
2582 name = ".glink";
2583 addralign = 4;
2584 }
2585
2586 // On x86 when IBT is enabled, this section contains the second PLT (lazy
2587 // symbol resolvers).
2588 if ((ctx.arg.emachine == EM_386 || ctx.arg.emachine == EM_X86_64) &&
2589 (ctx.arg.andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT))
2590 name = ".plt.sec";
2591
2592 // The PLT needs to be writable on SPARC as the dynamic linker will
2593 // modify the instructions in the PLT entries.
2594 if (ctx.arg.emachine == EM_SPARCV9)
2595 this->flags |= SHF_WRITE;
2596}
2597
2598void PltSection::writeTo(uint8_t *buf) {
2599 // At beginning of PLT, we have code to call the dynamic
2600 // linker to resolve dynsyms at runtime. Write such code.
2601 ctx.target->writePltHeader(buf);
2602 size_t off = headerSize;
2603
2604 for (const Symbol *sym : entries) {
2605 ctx.target->writePlt(buf: buf + off, sym: *sym, pltEntryAddr: getVA() + off);
2606 off += ctx.target->pltEntrySize;
2607 }
2608}
2609
2610void PltSection::addEntry(Symbol &sym) {
2611 assert(sym.auxIdx == ctx.symAux.size() - 1);
2612 ctx.symAux.back().pltIdx = entries.size();
2613 entries.push_back(Elt: &sym);
2614}
2615
2616size_t PltSection::getSize() const {
2617 return headerSize + entries.size() * ctx.target->pltEntrySize;
2618}
2619
2620bool PltSection::isNeeded() const {
2621 // For -z retpolineplt, .iplt needs the .plt header.
2622 return !entries.empty() || (ctx.arg.zRetpolineplt && ctx.in.iplt->isNeeded());
2623}
2624
2625// Used by ARM to add mapping symbols in the PLT section, which aid
2626// disassembly.
2627void PltSection::addSymbols() {
2628 ctx.target->addPltHeaderSymbols(isec&: *this);
2629
2630 size_t off = headerSize;
2631 for (size_t i = 0; i < entries.size(); ++i) {
2632 ctx.target->addPltSymbols(isec&: *this, off);
2633 off += ctx.target->pltEntrySize;
2634 }
2635}
2636
2637IpltSection::IpltSection(Ctx &ctx)
2638 : SyntheticSection(ctx, ".iplt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR,
2639 16) {
2640 // On AArch64, PLT entries only do loads from the .got.plt section, so the
2641 // .iplt section can be marked with the SHF_AARCH64_PURECODE section flag.
2642 if (ctx.arg.emachine == EM_AARCH64)
2643 this->flags |= SHF_AARCH64_PURECODE;
2644
2645 if (ctx.arg.emachine == EM_PPC || ctx.arg.emachine == EM_PPC64) {
2646 name = ".glink";
2647 addralign = 4;
2648 }
2649}
2650
2651void IpltSection::writeTo(uint8_t *buf) {
2652 uint32_t off = 0;
2653 for (const Symbol *sym : entries) {
2654 ctx.target->writeIplt(buf: buf + off, sym: *sym, pltEntryAddr: getVA() + off);
2655 off += ctx.target->ipltEntrySize;
2656 }
2657}
2658
2659size_t IpltSection::getSize() const {
2660 return entries.size() * ctx.target->ipltEntrySize;
2661}
2662
2663void IpltSection::addEntry(Symbol &sym) {
2664 assert(sym.auxIdx == ctx.symAux.size() - 1);
2665 ctx.symAux.back().pltIdx = entries.size();
2666 entries.push_back(Elt: &sym);
2667}
2668
2669// ARM uses mapping symbols to aid disassembly.
2670void IpltSection::addSymbols() {
2671 size_t off = 0;
2672 for (size_t i = 0, e = entries.size(); i != e; ++i) {
2673 ctx.target->addPltSymbols(isec&: *this, off);
2674 off += ctx.target->pltEntrySize;
2675 }
2676}
2677
2678PPC32GlinkSection::PPC32GlinkSection(Ctx &ctx) : PltSection(ctx) {
2679 name = ".glink";
2680 addralign = 4;
2681}
2682
2683void PPC32GlinkSection::writeTo(uint8_t *buf) {
2684 writePPC32GlinkSection(ctx, buf, numEntries: entries.size());
2685}
2686
2687size_t PPC32GlinkSection::getSize() const {
2688 return headerSize + entries.size() * ctx.target->pltEntrySize + footerSize;
2689}
2690
2691// This is an x86-only extra PLT section and used only when a security
2692// enhancement feature called CET is enabled. In this comment, I'll explain what
2693// the feature is and why we have two PLT sections if CET is enabled.
2694//
2695// So, what does CET do? CET introduces a new restriction to indirect jump
2696// instructions. CET works this way. Assume that CET is enabled. Then, if you
2697// execute an indirect jump instruction, the processor verifies that a special
2698// "landing pad" instruction (which is actually a repurposed NOP instruction and
2699// now called "endbr32" or "endbr64") is at the jump target. If the jump target
2700// does not start with that instruction, the processor raises an exception
2701// instead of continuing executing code.
2702//
2703// If CET is enabled, the compiler emits endbr to all locations where indirect
2704// jumps may jump to.
2705//
2706// This mechanism makes it extremely hard to transfer the control to a middle of
2707// a function that is not supporsed to be a indirect jump target, preventing
2708// certain types of attacks such as ROP or JOP.
2709//
2710// Note that the processors in the market as of 2019 don't actually support the
2711// feature. Only the spec is available at the moment.
2712//
2713// Now, I'll explain why we have this extra PLT section for CET.
2714//
2715// Since you can indirectly jump to a PLT entry, we have to make PLT entries
2716// start with endbr. The problem is there's no extra space for endbr (which is 4
2717// bytes long), as the PLT entry is only 16 bytes long and all bytes are already
2718// used.
2719//
2720// In order to deal with the issue, we split a PLT entry into two PLT entries.
2721// Remember that each PLT entry contains code to jump to an address read from
2722// .got.plt AND code to resolve a dynamic symbol lazily. With the 2-PLT scheme,
2723// the former code is written to .plt.sec, and the latter code is written to
2724// .plt.
2725//
2726// Lazy symbol resolution in the 2-PLT scheme works in the usual way, except
2727// that the regular .plt is now called .plt.sec and .plt is repurposed to
2728// contain only code for lazy symbol resolution.
2729//
2730// In other words, this is how the 2-PLT scheme works. Application code is
2731// supposed to jump to .plt.sec to call an external function. Each .plt.sec
2732// entry contains code to read an address from a corresponding .got.plt entry
2733// and jump to that address. Addresses in .got.plt initially point to .plt, so
2734// when an application calls an external function for the first time, the
2735// control is transferred to a function that resolves a symbol name from
2736// external shared object files. That function then rewrites a .got.plt entry
2737// with a resolved address, so that the subsequent function calls directly jump
2738// to a desired location from .plt.sec.
2739//
2740// There is an open question as to whether the 2-PLT scheme was desirable or
2741// not. We could have simply extended the PLT entry size to 32-bytes to
2742// accommodate endbr, and that scheme would have been much simpler than the
2743// 2-PLT scheme. One reason to split PLT was, by doing that, we could keep hot
2744// code (.plt.sec) from cold code (.plt). But as far as I know no one proved
2745// that the optimization actually makes a difference.
2746//
2747// That said, the 2-PLT scheme is a part of the ABI, debuggers and other tools
2748// depend on it, so we implement the ABI.
2749IBTPltSection::IBTPltSection(Ctx &ctx)
2750 : SyntheticSection(ctx, ".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR,
2751 16) {}
2752
2753void IBTPltSection::writeTo(uint8_t *buf) {
2754 ctx.target->writeIBTPlt(buf, numEntries: ctx.in.plt->getNumEntries());
2755}
2756
2757size_t IBTPltSection::getSize() const {
2758 // 16 is the header size of .plt.
2759 return 16 + ctx.in.plt->getNumEntries() * ctx.target->pltEntrySize;
2760}
2761
2762bool IBTPltSection::isNeeded() const { return ctx.in.plt->getNumEntries() > 0; }
2763
2764RelroPaddingSection::RelroPaddingSection(Ctx &ctx)
2765 : SyntheticSection(ctx, ".relro_padding", SHT_NOBITS, SHF_ALLOC | SHF_WRITE,
2766 1) {}
2767
2768PaddingSection::PaddingSection(Ctx &ctx, uint64_t amount, OutputSection *parent)
2769 : SyntheticSection(ctx, ".padding", SHT_PROGBITS, SHF_ALLOC, 1) {
2770 size = amount;
2771 this->parent = parent;
2772}
2773
2774void PaddingSection::writeTo(uint8_t *buf) {
2775 std::array<uint8_t, 4> filler = getParent()->getFiller(ctx);
2776 uint8_t *end = buf + size;
2777 for (; buf + 4 <= end; buf += 4)
2778 memcpy(dest: buf, src: &filler[0], n: 4);
2779 memcpy(dest: buf, src: &filler[0], n: end - buf);
2780}
2781
2782// The string hash function for .gdb_index.
2783static uint32_t computeGdbHash(StringRef s) {
2784 uint32_t h = 0;
2785 for (uint8_t c : s)
2786 h = h * 67 + toLower(x: c) - 113;
2787 return h;
2788}
2789
2790// 4-byte alignment ensures that values in the hash lookup table and the name
2791// table are aligned.
2792DebugNamesBaseSection::DebugNamesBaseSection(Ctx &ctx)
2793 : SyntheticSection(ctx, ".debug_names", SHT_PROGBITS, 0, 4) {}
2794
2795// Get the size of the .debug_names section header in bytes for DWARF32:
2796static uint32_t getDebugNamesHeaderSize(uint32_t augmentationStringSize) {
2797 return /* unit length */ 4 +
2798 /* version */ 2 +
2799 /* padding */ 2 +
2800 /* CU count */ 4 +
2801 /* TU count */ 4 +
2802 /* Foreign TU count */ 4 +
2803 /* Bucket Count */ 4 +
2804 /* Name Count */ 4 +
2805 /* Abbrev table size */ 4 +
2806 /* Augmentation string size */ 4 +
2807 /* Augmentation string */ augmentationStringSize;
2808}
2809
2810static Expected<DebugNamesBaseSection::IndexEntry *>
2811readEntry(uint64_t &offset, const DWARFDebugNames::NameIndex &ni,
2812 uint64_t entriesBase, DWARFDataExtractor &namesExtractor,
2813 const LLDDWARFSection &namesSec) {
2814 auto ie = makeThreadLocal<DebugNamesBaseSection::IndexEntry>();
2815 ie->poolOffset = offset;
2816 Error err = Error::success();
2817 uint64_t ulebVal = namesExtractor.getULEB128(offset_ptr: &offset, Err: &err);
2818 if (err)
2819 return createStringError(EC: inconvertibleErrorCode(),
2820 Fmt: "invalid abbrev code: %s",
2821 Vals: llvm::toString(E: std::move(err)).c_str());
2822 if (!isUInt<32>(x: ulebVal))
2823 return createStringError(EC: inconvertibleErrorCode(),
2824 Fmt: "abbrev code too large for DWARF32: %" PRIu64,
2825 Vals: ulebVal);
2826 ie->abbrevCode = static_cast<uint32_t>(ulebVal);
2827 auto it = ni.getAbbrevs().find_as(Val: ie->abbrevCode);
2828 if (it == ni.getAbbrevs().end())
2829 return createStringError(EC: inconvertibleErrorCode(),
2830 Fmt: "abbrev code not found in abbrev table: %" PRIu32,
2831 Vals: ie->abbrevCode);
2832
2833 DebugNamesBaseSection::AttrValue attr, cuAttr = {.attrValue: 0, .attrSize: 0};
2834 for (DWARFDebugNames::AttributeEncoding a : it->Attributes) {
2835 if (a.Index == dwarf::DW_IDX_parent) {
2836 if (a.Form == dwarf::DW_FORM_ref4) {
2837 attr.attrValue = namesExtractor.getU32(offset_ptr: &offset, Err: &err);
2838 attr.attrSize = 4;
2839 ie->parentOffset = entriesBase + attr.attrValue;
2840 } else if (a.Form != DW_FORM_flag_present)
2841 return createStringError(EC: inconvertibleErrorCode(),
2842 S: "invalid form for DW_IDX_parent");
2843 } else {
2844 switch (a.Form) {
2845 case DW_FORM_data1:
2846 case DW_FORM_ref1: {
2847 attr.attrValue = namesExtractor.getU8(offset_ptr: &offset, Err: &err);
2848 attr.attrSize = 1;
2849 break;
2850 }
2851 case DW_FORM_data2:
2852 case DW_FORM_ref2: {
2853 attr.attrValue = namesExtractor.getU16(offset_ptr: &offset, Err: &err);
2854 attr.attrSize = 2;
2855 break;
2856 }
2857 case DW_FORM_data4:
2858 case DW_FORM_ref4: {
2859 attr.attrValue = namesExtractor.getU32(offset_ptr: &offset, Err: &err);
2860 attr.attrSize = 4;
2861 break;
2862 }
2863 default:
2864 return createStringError(
2865 EC: inconvertibleErrorCode(),
2866 Fmt: "unrecognized form encoding %d in abbrev table", Vals: a.Form);
2867 }
2868 }
2869 if (err)
2870 return createStringError(EC: inconvertibleErrorCode(),
2871 Fmt: "error while reading attributes: %s",
2872 Vals: llvm::toString(E: std::move(err)).c_str());
2873 if (a.Index == DW_IDX_compile_unit)
2874 cuAttr = attr;
2875 else if (a.Form != DW_FORM_flag_present)
2876 ie->attrValues.push_back(Elt: attr);
2877 }
2878 // Canonicalize abbrev by placing the CU/TU index at the end.
2879 ie->attrValues.push_back(Elt: cuAttr);
2880 return ie;
2881}
2882
2883void DebugNamesBaseSection::parseDebugNames(
2884 Ctx &ctx, InputChunk &inputChunk, OutputChunk &chunk,
2885 DWARFDataExtractor &namesExtractor, DataExtractor &strExtractor,
2886 function_ref<SmallVector<uint32_t, 0>(
2887 uint32_t numCus, const DWARFDebugNames::Header &,
2888 const DWARFDebugNames::DWARFDebugNamesOffsets &)>
2889 readOffsets) {
2890 const LLDDWARFSection &namesSec = inputChunk.section;
2891 DenseMap<uint32_t, IndexEntry *> offsetMap;
2892 // Number of CUs seen in previous NameIndex sections within current chunk.
2893 uint32_t numCus = 0;
2894 for (const DWARFDebugNames::NameIndex &ni : *inputChunk.llvmDebugNames) {
2895 NameData &nd = inputChunk.nameData.emplace_back();
2896 nd.hdr = ni.getHeader();
2897 if (nd.hdr.Format != DwarfFormat::DWARF32) {
2898 Err(ctx) << namesSec.sec
2899 << ": found DWARF64, which is currently unsupported";
2900 return;
2901 }
2902 if (nd.hdr.Version != 5) {
2903 Err(ctx) << namesSec.sec << ": unsupported version: " << nd.hdr.Version;
2904 return;
2905 }
2906 uint32_t dwarfSize = dwarf::getDwarfOffsetByteSize(Format: DwarfFormat::DWARF32);
2907 DWARFDebugNames::DWARFDebugNamesOffsets locs = ni.getOffsets();
2908 if (locs.EntriesBase > namesExtractor.getData().size()) {
2909 Err(ctx) << namesSec.sec << ": entry pool start is beyond end of section";
2910 return;
2911 }
2912
2913 SmallVector<uint32_t, 0> entryOffsets = readOffsets(numCus, nd.hdr, locs);
2914
2915 // Read the entry pool.
2916 offsetMap.clear();
2917 nd.nameEntries.resize(N: nd.hdr.NameCount);
2918 for (auto i : seq(Size: nd.hdr.NameCount)) {
2919 NameEntry &ne = nd.nameEntries[i];
2920 uint64_t strOffset = locs.StringOffsetsBase + i * dwarfSize;
2921 ne.stringOffset = strOffset;
2922 uint64_t strp = namesExtractor.getRelocatedValue(Size: dwarfSize, Off: &strOffset);
2923 StringRef name = strExtractor.getCStrRef(OffsetPtr: &strp);
2924 ne.name = name.data();
2925 ne.hashValue = caseFoldingDjbHash(Buffer: name);
2926
2927 // Read a series of index entries that end with abbreviation code 0.
2928 uint64_t offset = locs.EntriesBase + entryOffsets[i];
2929 while (offset < namesSec.Data.size() && namesSec.Data[offset] != 0) {
2930 // Read & store all entries (for the same string).
2931 Expected<IndexEntry *> ieOrErr =
2932 readEntry(offset, ni, entriesBase: locs.EntriesBase, namesExtractor, namesSec);
2933 if (!ieOrErr) {
2934 Err(ctx) << namesSec.sec << ": " << ieOrErr.takeError();
2935 return;
2936 }
2937 ne.indexEntries.push_back(Elt: std::move(*ieOrErr));
2938 }
2939 if (offset >= namesSec.Data.size())
2940 Err(ctx) << namesSec.sec << ": index entry is out of bounds";
2941
2942 for (IndexEntry &ie : ne.entries())
2943 offsetMap[ie.poolOffset] = &ie;
2944 }
2945
2946 // Assign parent pointers, which will be used to update DW_IDX_parent index
2947 // attributes. Note: offsetMap[0] does not exist, so parentOffset == 0 will
2948 // get parentEntry == null as well.
2949 for (NameEntry &ne : nd.nameEntries)
2950 for (IndexEntry &ie : ne.entries())
2951 ie.parentEntry = offsetMap.lookup(Val: ie.parentOffset);
2952 numCus += nd.hdr.CompUnitCount;
2953 }
2954}
2955
2956// Compute the form for output DW_IDX_compile_unit attributes, similar to
2957// DIEInteger::BestForm. The input form (often DW_FORM_data1) may not hold all
2958// the merged CU indices.
2959std::pair<uint8_t, dwarf::Form> static getMergedCuCountForm(
2960 uint32_t compUnitCount) {
2961 if (compUnitCount > UINT16_MAX)
2962 return {4, DW_FORM_data4};
2963 if (compUnitCount > UINT8_MAX)
2964 return {2, DW_FORM_data2};
2965 return {1, DW_FORM_data1};
2966}
2967
2968void DebugNamesBaseSection::computeHdrAndAbbrevTable(
2969 MutableArrayRef<InputChunk> inputChunks) {
2970 TimeTraceScope timeScope("Merge .debug_names", "hdr and abbrev table");
2971 size_t numCu = 0;
2972 hdr.Format = DwarfFormat::DWARF32;
2973 hdr.Version = 5;
2974 hdr.CompUnitCount = 0;
2975 hdr.LocalTypeUnitCount = 0;
2976 hdr.ForeignTypeUnitCount = 0;
2977 hdr.AugmentationStringSize = 0;
2978
2979 // Compute CU and TU counts.
2980 for (auto i : seq(Size: numChunks)) {
2981 InputChunk &inputChunk = inputChunks[i];
2982 inputChunk.baseCuIdx = numCu;
2983 numCu += chunks[i].compUnits.size();
2984 for (const NameData &nd : inputChunk.nameData) {
2985 hdr.CompUnitCount += nd.hdr.CompUnitCount;
2986 // TODO: We don't handle type units yet, so LocalTypeUnitCount &
2987 // ForeignTypeUnitCount are left as 0.
2988 if (nd.hdr.LocalTypeUnitCount || nd.hdr.ForeignTypeUnitCount)
2989 Warn(ctx) << inputChunk.section.sec
2990 << ": type units are not implemented";
2991 // If augmentation strings are not identical, use an empty string.
2992 if (i == 0) {
2993 hdr.AugmentationStringSize = nd.hdr.AugmentationStringSize;
2994 hdr.AugmentationString = nd.hdr.AugmentationString;
2995 } else if (hdr.AugmentationString != nd.hdr.AugmentationString) {
2996 // There are conflicting augmentation strings, so it's best for the
2997 // merged index to not use an augmentation string.
2998 hdr.AugmentationStringSize = 0;
2999 hdr.AugmentationString.clear();
3000 }
3001 }
3002 }
3003
3004 // Create the merged abbrev table, uniquifyinng the input abbrev tables and
3005 // computing mapping from old (per-cu) abbrev codes to new (merged) abbrev
3006 // codes.
3007 FoldingSet<Abbrev> abbrevSet;
3008 // Determine the form for the DW_IDX_compile_unit attributes in the merged
3009 // index. The input form may not be big enough for all CU indices.
3010 dwarf::Form cuAttrForm = getMergedCuCountForm(compUnitCount: hdr.CompUnitCount).second;
3011 for (InputChunk &inputChunk : inputChunks) {
3012 for (auto [i, ni] : enumerate(First&: *inputChunk.llvmDebugNames)) {
3013 for (const DWARFDebugNames::Abbrev &oldAbbrev : ni.getAbbrevs()) {
3014 // Canonicalize abbrev by placing the CU/TU index at the end,
3015 // similar to 'parseDebugNames'.
3016 Abbrev abbrev;
3017 DWARFDebugNames::AttributeEncoding cuAttr(DW_IDX_compile_unit,
3018 cuAttrForm);
3019 abbrev.code = oldAbbrev.Code;
3020 abbrev.tag = oldAbbrev.Tag;
3021 for (DWARFDebugNames::AttributeEncoding a : oldAbbrev.Attributes) {
3022 if (a.Index == DW_IDX_compile_unit)
3023 cuAttr.Index = a.Index;
3024 else
3025 abbrev.attributes.push_back(Elt: {a.Index, a.Form});
3026 }
3027 // Put the CU/TU index at the end of the attributes list.
3028 abbrev.attributes.push_back(Elt: cuAttr);
3029
3030 // Profile the abbrev, get or assign a new code, then record the abbrev
3031 // code mapping.
3032 FoldingSetNodeID id;
3033 abbrev.Profile(id);
3034 uint32_t newCode;
3035 void *insertPos;
3036 if (Abbrev *existing = abbrevSet.FindNodeOrInsertPos(ID: id, InsertPos&: insertPos)) {
3037 // Found it; we've already seen an identical abbreviation.
3038 newCode = existing->code;
3039 } else {
3040 Abbrev *abbrev2 =
3041 new (abbrevAlloc.Allocate()) Abbrev(std::move(abbrev));
3042 abbrevSet.InsertNode(N: abbrev2, InsertPos: insertPos);
3043 abbrevTable.push_back(Elt: abbrev2);
3044 newCode = abbrevTable.size();
3045 abbrev2->code = newCode;
3046 }
3047 inputChunk.nameData[i].abbrevCodeMap[oldAbbrev.Code] = newCode;
3048 }
3049 }
3050 }
3051
3052 // Compute the merged abbrev table.
3053 raw_svector_ostream os(abbrevTableBuf);
3054 for (Abbrev *abbrev : abbrevTable) {
3055 encodeULEB128(Value: abbrev->code, OS&: os);
3056 encodeULEB128(Value: abbrev->tag, OS&: os);
3057 for (DWARFDebugNames::AttributeEncoding a : abbrev->attributes) {
3058 encodeULEB128(Value: a.Index, OS&: os);
3059 encodeULEB128(Value: a.Form, OS&: os);
3060 }
3061 os.write(Ptr: "\0", Size: 2); // attribute specification end
3062 }
3063 os.write(C: 0); // abbrev table end
3064 hdr.AbbrevTableSize = abbrevTableBuf.size();
3065}
3066
3067void DebugNamesBaseSection::Abbrev::Profile(FoldingSetNodeID &id) const {
3068 id.AddInteger(I: tag);
3069 for (const DWARFDebugNames::AttributeEncoding &attr : attributes) {
3070 id.AddInteger(I: attr.Index);
3071 id.AddInteger(I: attr.Form);
3072 }
3073}
3074
3075std::pair<uint32_t, uint32_t> DebugNamesBaseSection::computeEntryPool(
3076 MutableArrayRef<InputChunk> inputChunks) {
3077 TimeTraceScope timeScope("Merge .debug_names", "entry pool");
3078 // Collect and de-duplicate all the names (preserving all the entries).
3079 // Speed it up using multithreading, as the number of symbols can be in the
3080 // order of millions.
3081 const size_t concurrency =
3082 bit_floor(Value: std::min<size_t>(a: ctx.arg.threadCount, b: numShards));
3083 const size_t shift = 32 - countr_zero(Val: numShards);
3084 const uint8_t cuAttrSize = getMergedCuCountForm(compUnitCount: hdr.CompUnitCount).first;
3085 DenseMap<CachedHashStringRef, size_t> maps[numShards];
3086
3087 parallelFor(Begin: 0, End: concurrency, Fn: [&](size_t threadId) {
3088 for (auto i : seq(Size: numChunks)) {
3089 InputChunk &inputChunk = inputChunks[i];
3090 for (auto j : seq(Size: inputChunk.nameData.size())) {
3091 NameData &nd = inputChunk.nameData[j];
3092 // Deduplicate the NameEntry records (based on the string/name),
3093 // appending all IndexEntries from duplicate NameEntry records to
3094 // the single preserved copy.
3095 for (NameEntry &ne : nd.nameEntries) {
3096 auto shardId = ne.hashValue >> shift;
3097 if ((shardId & (concurrency - 1)) != threadId)
3098 continue;
3099
3100 ne.chunkIdx = i;
3101 for (IndexEntry &ie : ne.entries()) {
3102 // Update the IndexEntry's abbrev code to match the merged
3103 // abbreviations.
3104 ie.abbrevCode = nd.abbrevCodeMap[ie.abbrevCode];
3105 // Update the DW_IDX_compile_unit attribute (the last one after
3106 // canonicalization) to have correct merged offset value and size.
3107 auto &back = ie.attrValues.back();
3108 back.attrValue += inputChunk.baseCuIdx + j;
3109 back.attrSize = cuAttrSize;
3110 }
3111
3112 auto &nameVec = nameVecs[shardId];
3113 auto [it, inserted] = maps[shardId].try_emplace(
3114 Key: CachedHashStringRef(ne.name, ne.hashValue), Args: nameVec.size());
3115 if (inserted)
3116 nameVec.push_back(Elt: std::move(ne));
3117 else
3118 nameVec[it->second].indexEntries.append(RHS: std::move(ne.indexEntries));
3119 }
3120 }
3121 }
3122 });
3123
3124 // Compute entry offsets in parallel. First, compute offsets relative to the
3125 // current shard.
3126 uint32_t offsets[numShards];
3127 parallelFor(Begin: 0, End: numShards, Fn: [&](size_t shard) {
3128 uint32_t offset = 0;
3129 for (NameEntry &ne : nameVecs[shard]) {
3130 ne.entryOffset = offset;
3131 for (IndexEntry &ie : ne.entries()) {
3132 ie.poolOffset = offset;
3133 offset += getULEB128Size(Value: ie.abbrevCode);
3134 for (AttrValue value : ie.attrValues)
3135 offset += value.attrSize;
3136 }
3137 ++offset; // index entry sentinel
3138 }
3139 offsets[shard] = offset;
3140 });
3141 // Then add shard offsets.
3142 std::partial_sum(first: offsets, last: std::end(arr&: offsets), result: offsets);
3143 parallelFor(Begin: 1, End: numShards, Fn: [&](size_t shard) {
3144 uint32_t offset = offsets[shard - 1];
3145 for (NameEntry &ne : nameVecs[shard]) {
3146 ne.entryOffset += offset;
3147 for (IndexEntry &ie : ne.entries())
3148 ie.poolOffset += offset;
3149 }
3150 });
3151
3152 // Update the DW_IDX_parent entries that refer to real parents (have
3153 // DW_FORM_ref4).
3154 parallelFor(Begin: 0, End: numShards, Fn: [&](size_t shard) {
3155 for (NameEntry &ne : nameVecs[shard]) {
3156 for (IndexEntry &ie : ne.entries()) {
3157 if (!ie.parentEntry)
3158 continue;
3159 // Abbrevs are indexed starting at 1; vector starts at 0. (abbrevCode
3160 // corresponds to position in the merged table vector).
3161 const Abbrev *abbrev = abbrevTable[ie.abbrevCode - 1];
3162 for (const auto &[a, v] : zip_equal(t: abbrev->attributes, u&: ie.attrValues))
3163 if (a.Index == DW_IDX_parent && a.Form == DW_FORM_ref4)
3164 v.attrValue = ie.parentEntry->poolOffset;
3165 }
3166 }
3167 });
3168
3169 // Return (entry pool size, number of entries).
3170 uint32_t num = 0;
3171 for (auto &map : maps)
3172 num += map.size();
3173 return {offsets[numShards - 1], num};
3174}
3175
3176void DebugNamesBaseSection::init(
3177 function_ref<void(InputFile *, InputChunk &, OutputChunk &)> parseFile) {
3178 TimeTraceScope timeScope("Merge .debug_names");
3179 // Collect and remove input .debug_names sections. Save InputSection pointers
3180 // to relocate string offsets in `writeTo`.
3181 SetVector<InputFile *> files;
3182 for (InputSectionBase *s : ctx.inputSections) {
3183 InputSection *isec = dyn_cast<InputSection>(Val: s);
3184 if (!isec)
3185 continue;
3186 if (!(s->flags & SHF_ALLOC) && s->name == ".debug_names") {
3187 s->markDead();
3188 inputSections.push_back(Elt: isec);
3189 files.insert(X: isec->file);
3190 }
3191 }
3192
3193 // Parse input .debug_names sections and extract InputChunk and OutputChunk
3194 // data. OutputChunk contains CU information, which will be needed by
3195 // `writeTo`.
3196 auto inputChunksPtr = std::make_unique<InputChunk[]>(num: files.size());
3197 MutableArrayRef<InputChunk> inputChunks(inputChunksPtr.get(), files.size());
3198 numChunks = files.size();
3199 chunks = std::make_unique<OutputChunk[]>(num: files.size());
3200 {
3201 TimeTraceScope timeScope("Merge .debug_names", "parse");
3202 parallelFor(Begin: 0, End: files.size(), Fn: [&](size_t i) {
3203 parseFile(files[i], inputChunks[i], chunks[i]);
3204 });
3205 }
3206
3207 // Compute section header (except unit_length), abbrev table, and entry pool.
3208 computeHdrAndAbbrevTable(inputChunks);
3209 uint32_t entryPoolSize;
3210 std::tie(args&: entryPoolSize, args&: hdr.NameCount) = computeEntryPool(inputChunks);
3211 hdr.BucketCount = dwarf::getDebugNamesBucketCount(UniqueHashCount: hdr.NameCount);
3212
3213 // Compute the section size. Subtract 4 to get the unit_length for DWARF32.
3214 uint32_t hdrSize = getDebugNamesHeaderSize(augmentationStringSize: hdr.AugmentationStringSize);
3215 size = findDebugNamesOffsets(EndOfHeaderOffset: hdrSize, Hdr: hdr).EntriesBase + entryPoolSize;
3216 hdr.UnitLength = size - 4;
3217}
3218
3219template <class ELFT>
3220DebugNamesSection<ELFT>::DebugNamesSection(Ctx &ctx)
3221 : DebugNamesBaseSection(ctx) {
3222 init(parseFile: [&](InputFile *f, InputChunk &inputChunk, OutputChunk &chunk) {
3223 auto *file = cast<ObjFile<ELFT>>(f);
3224 DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
3225 auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
3226 chunk.infoSec = dobj.getInfoSection();
3227 DWARFDataExtractor namesExtractor(dobj, dobj.getNamesSection(),
3228 ELFT::Endianness == endianness::little,
3229 ELFT::Is64Bits ? 8 : 4);
3230 // .debug_str is needed to get symbol names from string offsets.
3231 DataExtractor strExtractor(dobj.getStrSection(),
3232 ELFT::Endianness == endianness::little,
3233 ELFT::Is64Bits ? 8 : 4);
3234 inputChunk.section = dobj.getNamesSection();
3235
3236 inputChunk.llvmDebugNames.emplace(args&: namesExtractor, args&: strExtractor);
3237 if (Error e = inputChunk.llvmDebugNames->extract()) {
3238 Err(ctx) << dobj.getNamesSection().sec << ": " << std::move(e);
3239 }
3240 parseDebugNames(
3241 ctx, inputChunk, chunk, namesExtractor, strExtractor,
3242 readOffsets: [&chunk, namesData = dobj.getNamesSection().Data.data()](
3243 uint32_t numCus, const DWARFDebugNames::Header &hdr,
3244 const DWARFDebugNames::DWARFDebugNamesOffsets &locs) {
3245 // Read CU offsets, which are relocated by .debug_info + X
3246 // relocations. Record the section offset to be relocated by
3247 // `finalizeContents`.
3248 chunk.compUnits.resize_for_overwrite(N: numCus + hdr.CompUnitCount);
3249 for (auto i : seq(Size: hdr.CompUnitCount))
3250 chunk.compUnits[numCus + i] = locs.CUsBase + i * 4;
3251
3252 // Read entry offsets.
3253 const char *p = namesData + locs.EntryOffsetsBase;
3254 SmallVector<uint32_t, 0> entryOffsets;
3255 entryOffsets.resize_for_overwrite(N: hdr.NameCount);
3256 for (uint32_t &offset : entryOffsets)
3257 offset = endian::readNext<uint32_t, ELFT::Endianness, unaligned>(p);
3258 return entryOffsets;
3259 });
3260 });
3261}
3262
3263template <class ELFT>
3264template <class RelTy>
3265void DebugNamesSection<ELFT>::getNameRelocs(
3266 const InputFile &file, DenseMap<uint32_t, uint32_t> &relocs,
3267 Relocs<RelTy> rels) {
3268 for (const RelTy &rel : rels) {
3269 Symbol &sym = file.getRelocTargetSym(rel);
3270 relocs[rel.r_offset] = sym.getVA(ctx, addend: getAddend<ELFT>(rel));
3271 }
3272}
3273
3274template <class ELFT> void DebugNamesSection<ELFT>::finalizeContents() {
3275 // Get relocations of .debug_names sections.
3276 auto relocs = std::make_unique<DenseMap<uint32_t, uint32_t>[]>(numChunks);
3277 parallelFor(0, numChunks, [&](size_t i) {
3278 InputSection *sec = inputSections[i];
3279 invokeOnRelocs(*sec, getNameRelocs, *sec->file, relocs.get()[i]);
3280
3281 // Relocate CU offsets with .debug_info + X relocations.
3282 OutputChunk &chunk = chunks.get()[i];
3283 for (auto [j, cuOffset] : enumerate(First&: chunk.compUnits))
3284 cuOffset = relocs.get()[i].lookup(cuOffset);
3285 });
3286
3287 // Relocate string offsets in the name table with .debug_str + X relocations.
3288 parallelForEach(nameVecs, [&](auto &nameVec) {
3289 for (NameEntry &ne : nameVec)
3290 ne.stringOffset = relocs.get()[ne.chunkIdx].lookup(ne.stringOffset);
3291 });
3292}
3293
3294template <class ELFT> void DebugNamesSection<ELFT>::writeTo(uint8_t *buf) {
3295 [[maybe_unused]] const uint8_t *const beginBuf = buf;
3296 // Write the header.
3297 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.UnitLength);
3298 endian::writeNext<uint16_t, ELFT::Endianness>(buf, hdr.Version);
3299 buf += 2; // padding
3300 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.CompUnitCount);
3301 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.LocalTypeUnitCount);
3302 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.ForeignTypeUnitCount);
3303 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.BucketCount);
3304 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.NameCount);
3305 endian::writeNext<uint32_t, ELFT::Endianness>(buf, hdr.AbbrevTableSize);
3306 endian::writeNext<uint32_t, ELFT::Endianness>(buf,
3307 hdr.AugmentationStringSize);
3308 memcpy(buf, hdr.AugmentationString.c_str(), hdr.AugmentationString.size());
3309 buf += hdr.AugmentationStringSize;
3310
3311 // Write the CU list.
3312 for (auto &chunk : getChunks())
3313 for (uint32_t cuOffset : chunk.compUnits)
3314 endian::writeNext<uint32_t, ELFT::Endianness>(buf, cuOffset);
3315
3316 // TODO: Write the local TU list, then the foreign TU list..
3317
3318 // Write the hash lookup table.
3319 SmallVector<SmallVector<NameEntry *, 0>, 0> buckets(hdr.BucketCount);
3320 // Symbols enter into a bucket whose index is the hash modulo bucket_count.
3321 for (auto &nameVec : nameVecs)
3322 for (NameEntry &ne : nameVec)
3323 buckets[ne.hashValue % hdr.BucketCount].push_back(&ne);
3324
3325 // Write buckets (accumulated bucket counts).
3326 uint32_t bucketIdx = 1;
3327 for (const SmallVector<NameEntry *, 0> &bucket : buckets) {
3328 if (!bucket.empty())
3329 endian::write32<ELFT::Endianness>(buf, bucketIdx);
3330 buf += 4;
3331 bucketIdx += bucket.size();
3332 }
3333 // Write the hashes.
3334 for (const SmallVector<NameEntry *, 0> &bucket : buckets)
3335 for (const NameEntry *e : bucket)
3336 endian::writeNext<uint32_t, ELFT::Endianness>(buf, e->hashValue);
3337
3338 // Write the name table. The name entries are ordered by bucket_idx and
3339 // correspond one-to-one with the hash lookup table.
3340 //
3341 // First, write the relocated string offsets.
3342 for (const SmallVector<NameEntry *, 0> &bucket : buckets)
3343 for (const NameEntry *ne : bucket)
3344 endian::writeNext<uint32_t, ELFT::Endianness>(buf, ne->stringOffset);
3345
3346 // Then write the entry offsets.
3347 for (const SmallVector<NameEntry *, 0> &bucket : buckets)
3348 for (const NameEntry *ne : bucket)
3349 endian::writeNext<uint32_t, ELFT::Endianness>(buf, ne->entryOffset);
3350
3351 // Write the abbrev table.
3352 buf = llvm::copy(abbrevTableBuf, buf);
3353
3354 // Write the entry pool. Unlike the name table, the name entries follow the
3355 // nameVecs order computed by `computeEntryPool`.
3356 for (auto &nameVec : nameVecs) {
3357 for (NameEntry &ne : nameVec) {
3358 // Write all the entries for the string.
3359 for (const IndexEntry &ie : ne.entries()) {
3360 buf += encodeULEB128(Value: ie.abbrevCode, p: buf);
3361 for (AttrValue value : ie.attrValues) {
3362 switch (value.attrSize) {
3363 case 1:
3364 *buf++ = value.attrValue;
3365 break;
3366 case 2:
3367 endian::writeNext<uint16_t, ELFT::Endianness>(buf, value.attrValue);
3368 break;
3369 case 4:
3370 endian::writeNext<uint32_t, ELFT::Endianness>(buf, value.attrValue);
3371 break;
3372 default:
3373 llvm_unreachable("invalid attrSize");
3374 }
3375 }
3376 }
3377 ++buf; // index entry sentinel
3378 }
3379 }
3380 assert(uint64_t(buf - beginBuf) == size);
3381}
3382
3383GdbIndexSection::GdbIndexSection(Ctx &ctx)
3384 : SyntheticSection(ctx, ".gdb_index", SHT_PROGBITS, 0, 1) {}
3385
3386// Returns the desired size of an on-disk hash table for a .gdb_index section.
3387// There's a tradeoff between size and collision rate. We aim 75% utilization.
3388size_t GdbIndexSection::computeSymtabSize() const {
3389 return std::max<size_t>(a: NextPowerOf2(A: symbols.size() * 4 / 3), b: 1024);
3390}
3391
3392static SmallVector<GdbIndexSection::CuEntry, 0>
3393readCuList(DWARFContext &dwarf) {
3394 SmallVector<GdbIndexSection::CuEntry, 0> ret;
3395 for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units())
3396 ret.push_back(Elt: {.cuOffset: cu->getOffset(), .cuLength: cu->getLength() + 4});
3397 return ret;
3398}
3399
3400static SmallVector<GdbIndexSection::AddressEntry, 0>
3401readAddressAreas(Ctx &ctx, DWARFContext &dwarf, InputSection *sec) {
3402 SmallVector<GdbIndexSection::AddressEntry, 0> ret;
3403
3404 uint32_t cuIdx = 0;
3405 for (std::unique_ptr<DWARFUnit> &cu : dwarf.compile_units()) {
3406 if (Error e = cu->tryExtractDIEsIfNeeded(CUDieOnly: false)) {
3407 Warn(ctx) << sec << ": " << std::move(e);
3408 return {};
3409 }
3410 Expected<DWARFAddressRangesVector> ranges = cu->collectAddressRanges();
3411 if (!ranges) {
3412 Warn(ctx) << sec << ": " << ranges.takeError();
3413 return {};
3414 }
3415
3416 ArrayRef<InputSectionBase *> sections = sec->file->getSections();
3417 for (DWARFAddressRange &r : *ranges) {
3418 if (r.SectionIndex == -1ULL)
3419 continue;
3420 // Range list with zero size has no effect.
3421 InputSectionBase *s = sections[r.SectionIndex];
3422 if (s && s != &InputSection::discarded && s->isLive())
3423 if (r.LowPC != r.HighPC)
3424 ret.push_back(Elt: {.section: cast<InputSection>(Val: s), .lowAddress: r.LowPC, .highAddress: r.HighPC, .cuIndex: cuIdx});
3425 }
3426 ++cuIdx;
3427 }
3428
3429 return ret;
3430}
3431
3432template <class ELFT>
3433static SmallVector<GdbIndexSection::NameAttrEntry, 0>
3434readPubNamesAndTypes(Ctx &ctx, const LLDDwarfObj<ELFT> &obj,
3435 const SmallVectorImpl<GdbIndexSection::CuEntry> &cus) {
3436 const LLDDWARFSection &pubNames = obj.getGnuPubnamesSection();
3437 const LLDDWARFSection &pubTypes = obj.getGnuPubtypesSection();
3438
3439 SmallVector<GdbIndexSection::NameAttrEntry, 0> ret;
3440 for (const LLDDWARFSection *pub : {&pubNames, &pubTypes}) {
3441 DWARFDataExtractor data(obj, *pub, ELFT::Endianness == endianness::little,
3442 ELFT::Is64Bits ? 8 : 4);
3443 DWARFDebugPubTable table;
3444 table.extract(Data: data, /*GnuStyle=*/true, RecoverableErrorHandler: [&](Error e) {
3445 Warn(ctx) << pub->sec << ": " << std::move(e);
3446 });
3447 for (const DWARFDebugPubTable::Set &set : table.getData()) {
3448 // The value written into the constant pool is kind << 24 | cuIndex. As we
3449 // don't know how many compilation units precede this object to compute
3450 // cuIndex, we compute (kind << 24 | cuIndexInThisObject) instead, and add
3451 // the number of preceding compilation units later.
3452 uint32_t i = llvm::partition_point(cus,
3453 [&](GdbIndexSection::CuEntry cu) {
3454 return cu.cuOffset < set.Offset;
3455 }) -
3456 cus.begin();
3457 for (const DWARFDebugPubTable::Entry &ent : set.Entries)
3458 ret.push_back(Elt: {.name: {ent.Name, computeGdbHash(s: ent.Name)},
3459 .cuIndexAndAttrs: (ent.Descriptor.toBits() << 24) | i});
3460 }
3461 }
3462 return ret;
3463}
3464
3465// Create a list of symbols from a given list of symbol names and types
3466// by uniquifying them by name.
3467static std::pair<SmallVector<GdbIndexSection::GdbSymbol, 0>, size_t>
3468createSymbols(
3469 Ctx &ctx,
3470 ArrayRef<SmallVector<GdbIndexSection::NameAttrEntry, 0>> nameAttrs,
3471 const SmallVector<GdbIndexSection::GdbChunk, 0> &chunks) {
3472 using GdbSymbol = GdbIndexSection::GdbSymbol;
3473 using NameAttrEntry = GdbIndexSection::NameAttrEntry;
3474
3475 // For each chunk, compute the number of compilation units preceding it.
3476 uint32_t cuIdx = 0;
3477 std::unique_ptr<uint32_t[]> cuIdxs(new uint32_t[chunks.size()]);
3478 for (uint32_t i = 0, e = chunks.size(); i != e; ++i) {
3479 cuIdxs[i] = cuIdx;
3480 cuIdx += chunks[i].compilationUnits.size();
3481 }
3482
3483 // Collect the compilation unitss for each unique name. Speed it up using
3484 // multi-threading as the number of symbols can be in the order of millions.
3485 // Shard GdbSymbols by hash's high bits.
3486 constexpr size_t numShards = 32;
3487 const size_t concurrency =
3488 llvm::bit_floor(Value: std::min<size_t>(a: ctx.arg.threadCount, b: numShards));
3489 const size_t shift = 32 - llvm::countr_zero(Val: numShards);
3490 auto map =
3491 std::make_unique<DenseMap<CachedHashStringRef, size_t>[]>(num: numShards);
3492 auto symbols = std::make_unique<SmallVector<GdbSymbol, 0>[]>(num: numShards);
3493 parallelFor(Begin: 0, End: concurrency, Fn: [&](size_t threadId) {
3494 uint32_t i = 0;
3495 for (ArrayRef<NameAttrEntry> entries : nameAttrs) {
3496 for (const NameAttrEntry &ent : entries) {
3497 size_t shardId = ent.name.hash() >> shift;
3498 if ((shardId & (concurrency - 1)) != threadId)
3499 continue;
3500
3501 uint32_t v = ent.cuIndexAndAttrs + cuIdxs[i];
3502 auto [it, inserted] =
3503 map[shardId].try_emplace(Key: ent.name, Args: symbols[shardId].size());
3504 if (inserted)
3505 symbols[shardId].push_back(Elt: {.name: ent.name, .cuVector: {v}, .nameOff: 0, .cuVectorOff: 0});
3506 else
3507 symbols[shardId][it->second].cuVector.push_back(Elt: v);
3508 }
3509 ++i;
3510 }
3511 });
3512
3513 size_t numSymbols = 0;
3514 for (ArrayRef<GdbSymbol> v : ArrayRef(symbols.get(), numShards))
3515 numSymbols += v.size();
3516
3517 // The return type is a flattened vector, so we'll copy each vector
3518 // contents to Ret.
3519 SmallVector<GdbSymbol, 0> ret;
3520 ret.reserve(N: numSymbols);
3521 for (SmallVector<GdbSymbol, 0> &vec :
3522 MutableArrayRef(symbols.get(), numShards))
3523 for (GdbSymbol &sym : vec)
3524 ret.push_back(Elt: std::move(sym));
3525
3526 // CU vectors and symbol names are adjacent in the output file.
3527 // We can compute their offsets in the output file now.
3528 size_t off = 0;
3529 for (GdbSymbol &sym : ret) {
3530 sym.cuVectorOff = off;
3531 off += (sym.cuVector.size() + 1) * 4;
3532 }
3533 for (GdbSymbol &sym : ret) {
3534 sym.nameOff = off;
3535 off += sym.name.size() + 1;
3536 }
3537 // If off overflows, the last symbol's nameOff likely overflows.
3538 if (!isUInt<32>(x: off))
3539 Err(ctx) << "--gdb-index: constant pool size (" << off
3540 << ") exceeds UINT32_MAX";
3541
3542 return {ret, off};
3543}
3544
3545// Returns a newly-created .gdb_index section.
3546template <class ELFT>
3547std::unique_ptr<GdbIndexSection> GdbIndexSection::create(Ctx &ctx) {
3548 llvm::TimeTraceScope timeScope("Create gdb index");
3549
3550 // Collect InputFiles with .debug_info. See the comment in
3551 // LLDDwarfObj<ELFT>::LLDDwarfObj. If we do lightweight parsing in the future,
3552 // note that isec->data() may uncompress the full content, which should be
3553 // parallelized.
3554 SetVector<InputFile *> files;
3555 for (InputSectionBase *s : ctx.inputSections) {
3556 InputSection *isec = dyn_cast<InputSection>(Val: s);
3557 if (!isec)
3558 continue;
3559 // .debug_gnu_pub{names,types} are useless in executables.
3560 // They are present in input object files solely for creating
3561 // a .gdb_index. So we can remove them from the output.
3562 if (s->name == ".debug_gnu_pubnames" || s->name == ".debug_gnu_pubtypes")
3563 s->markDead();
3564 else if (isec->name == ".debug_info")
3565 files.insert(X: isec->file);
3566 }
3567 // Drop .rel[a].debug_gnu_pub{names,types} for --emit-relocs.
3568 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3569 if (auto *isec = dyn_cast<InputSection>(Val: s))
3570 if (InputSectionBase *rel = isec->getRelocatedSection())
3571 return !rel->isLive();
3572 return !s->isLive();
3573 });
3574
3575 SmallVector<GdbChunk, 0> chunks(files.size());
3576 SmallVector<SmallVector<NameAttrEntry, 0>, 0> nameAttrs(files.size());
3577
3578 parallelFor(0, files.size(), [&](size_t i) {
3579 // To keep memory usage low, we don't want to keep cached DWARFContext, so
3580 // avoid getDwarf() here.
3581 ObjFile<ELFT> *file = cast<ObjFile<ELFT>>(files[i]);
3582 DWARFContext dwarf(std::make_unique<LLDDwarfObj<ELFT>>(file));
3583 auto &dobj = static_cast<const LLDDwarfObj<ELFT> &>(dwarf.getDWARFObj());
3584
3585 // If the are multiple compile units .debug_info (very rare ld -r --unique),
3586 // this only picks the last one. Other address ranges are lost.
3587 chunks[i].sec = dobj.getInfoSection();
3588 chunks[i].compilationUnits = readCuList(dwarf);
3589 chunks[i].addressAreas = readAddressAreas(ctx, dwarf, sec: chunks[i].sec);
3590 nameAttrs[i] =
3591 readPubNamesAndTypes<ELFT>(ctx, dobj, chunks[i].compilationUnits);
3592 });
3593
3594 auto ret = std::make_unique<GdbIndexSection>(args&: ctx);
3595 ret->chunks = std::move(chunks);
3596 std::tie(args&: ret->symbols, args&: ret->size) =
3597 createSymbols(ctx, nameAttrs, chunks: ret->chunks);
3598
3599 // Count the areas other than the constant pool.
3600 ret->size += sizeof(GdbIndexHeader) + ret->computeSymtabSize() * 8;
3601 for (GdbChunk &chunk : ret->chunks)
3602 ret->size +=
3603 chunk.compilationUnits.size() * 16 + chunk.addressAreas.size() * 20;
3604
3605 return ret;
3606}
3607
3608void GdbIndexSection::writeTo(uint8_t *buf) {
3609 // Write the header.
3610 auto *hdr = reinterpret_cast<GdbIndexHeader *>(buf);
3611 uint8_t *start = buf;
3612 hdr->version = 7;
3613 buf += sizeof(*hdr);
3614
3615 // Write the CU list.
3616 hdr->cuListOff = buf - start;
3617 for (GdbChunk &chunk : chunks) {
3618 for (CuEntry &cu : chunk.compilationUnits) {
3619 write64le(P: buf, V: chunk.sec->outSecOff + cu.cuOffset);
3620 write64le(P: buf + 8, V: cu.cuLength);
3621 buf += 16;
3622 }
3623 }
3624
3625 // Write the address area.
3626 hdr->cuTypesOff = buf - start;
3627 hdr->addressAreaOff = buf - start;
3628 uint32_t cuOff = 0;
3629 for (GdbChunk &chunk : chunks) {
3630 for (AddressEntry &e : chunk.addressAreas) {
3631 // In the case of ICF there may be duplicate address range entries.
3632 const uint64_t baseAddr = e.section->repl->getVA(offset: 0);
3633 write64le(P: buf, V: baseAddr + e.lowAddress);
3634 write64le(P: buf + 8, V: baseAddr + e.highAddress);
3635 write32le(P: buf + 16, V: e.cuIndex + cuOff);
3636 buf += 20;
3637 }
3638 cuOff += chunk.compilationUnits.size();
3639 }
3640
3641 // Write the on-disk open-addressing hash table containing symbols.
3642 hdr->symtabOff = buf - start;
3643 size_t symtabSize = computeSymtabSize();
3644 uint32_t mask = symtabSize - 1;
3645
3646 for (GdbSymbol &sym : symbols) {
3647 uint32_t h = sym.name.hash();
3648 uint32_t i = h & mask;
3649 uint32_t step = ((h * 17) & mask) | 1;
3650
3651 while (read32le(P: buf + i * 8))
3652 i = (i + step) & mask;
3653
3654 write32le(P: buf + i * 8, V: sym.nameOff);
3655 write32le(P: buf + i * 8 + 4, V: sym.cuVectorOff);
3656 }
3657
3658 buf += symtabSize * 8;
3659
3660 // Write the string pool.
3661 hdr->constantPoolOff = buf - start;
3662 parallelForEach(R&: symbols, Fn: [&](GdbSymbol &sym) {
3663 memcpy(dest: buf + sym.nameOff, src: sym.name.data(), n: sym.name.size());
3664 });
3665
3666 // Write the CU vectors.
3667 for (GdbSymbol &sym : symbols) {
3668 write32le(P: buf, V: sym.cuVector.size());
3669 buf += 4;
3670 for (uint32_t val : sym.cuVector) {
3671 write32le(P: buf, V: val);
3672 buf += 4;
3673 }
3674 }
3675}
3676
3677bool GdbIndexSection::isNeeded() const { return !chunks.empty(); }
3678
3679VersionDefinitionSection::VersionDefinitionSection(Ctx &ctx)
3680 : SyntheticSection(ctx, ".gnu.version_d", SHT_GNU_verdef, SHF_ALLOC,
3681 sizeof(uint32_t)) {}
3682
3683StringRef VersionDefinitionSection::getFileDefName() {
3684 if (!getPartition(ctx).name.empty())
3685 return getPartition(ctx).name;
3686 if (!ctx.arg.soName.empty())
3687 return ctx.arg.soName;
3688 return ctx.arg.outputFile;
3689}
3690
3691void VersionDefinitionSection::finalizeContents() {
3692 fileDefNameOff = getPartition(ctx).dynStrTab->addString(s: getFileDefName());
3693 for (const VersionDefinition &v : namedVersionDefs(ctx))
3694 verDefNameOffs.push_back(Elt: getPartition(ctx).dynStrTab->addString(s: v.name));
3695
3696 if (OutputSection *sec = getPartition(ctx).dynStrTab->getParent())
3697 getParent()->link = sec->sectionIndex;
3698
3699 // sh_info should be set to the number of definitions. This fact is missed in
3700 // documentation, but confirmed by binutils community:
3701 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
3702 getParent()->info = getVerDefNum(ctx);
3703}
3704
3705void VersionDefinitionSection::writeOne(uint8_t *buf, uint32_t index,
3706 StringRef name, size_t nameOff) {
3707 uint16_t flags = index == 1 ? VER_FLG_BASE : 0;
3708
3709 // Write a verdef.
3710 write16(ctx, p: buf, v: 1); // vd_version
3711 write16(ctx, p: buf + 2, v: flags); // vd_flags
3712 write16(ctx, p: buf + 4, v: index); // vd_ndx
3713 write16(ctx, p: buf + 6, v: 1); // vd_cnt
3714 write32(ctx, p: buf + 8, v: hashSysV(SymbolName: name)); // vd_hash
3715 write32(ctx, p: buf + 12, v: 20); // vd_aux
3716 write32(ctx, p: buf + 16, v: 28); // vd_next
3717
3718 // Write a veraux.
3719 write32(ctx, p: buf + 20, v: nameOff); // vda_name
3720 write32(ctx, p: buf + 24, v: 0); // vda_next
3721}
3722
3723void VersionDefinitionSection::writeTo(uint8_t *buf) {
3724 writeOne(buf, index: 1, name: getFileDefName(), nameOff: fileDefNameOff);
3725
3726 auto nameOffIt = verDefNameOffs.begin();
3727 for (const VersionDefinition &v : namedVersionDefs(ctx)) {
3728 buf += EntrySize;
3729 writeOne(buf, index: v.id, name: v.name, nameOff: *nameOffIt++);
3730 }
3731
3732 // Need to terminate the last version definition.
3733 write32(ctx, p: buf + 16, v: 0); // vd_next
3734}
3735
3736size_t VersionDefinitionSection::getSize() const {
3737 return EntrySize * getVerDefNum(ctx);
3738}
3739
3740// .gnu.version is a table where each entry is 2 byte long.
3741VersionTableSection::VersionTableSection(Ctx &ctx)
3742 : SyntheticSection(ctx, ".gnu.version", SHT_GNU_versym, SHF_ALLOC,
3743 sizeof(uint16_t)) {
3744 this->entsize = 2;
3745}
3746
3747void VersionTableSection::finalizeContents() {
3748 if (OutputSection *osec = getPartition(ctx).dynSymTab->getParent())
3749 getParent()->link = osec->sectionIndex;
3750}
3751
3752size_t VersionTableSection::getSize() const {
3753 return (getPartition(ctx).dynSymTab->getSymbols().size() + 1) * 2;
3754}
3755
3756void VersionTableSection::writeTo(uint8_t *buf) {
3757 buf += 2;
3758 for (const SymbolTableEntry &s : getPartition(ctx).dynSymTab->getSymbols()) {
3759 // For an unextracted lazy symbol (undefined weak), it must have been
3760 // converted to Undefined.
3761 assert(!s.sym->isLazy());
3762 // Undefined symbols should use index 0 when unversioned.
3763 write16(ctx, p: buf, v: s.sym->isUndefined() ? 0 : s.sym->versionId);
3764 buf += 2;
3765 }
3766}
3767
3768bool VersionTableSection::isNeeded() const {
3769 return isLive() &&
3770 (getPartition(ctx).verDef || getPartition(ctx).verNeed->isNeeded());
3771}
3772
3773void elf::addVerneed(Ctx &ctx, Symbol &ss) {
3774 auto &file = cast<SharedFile>(Val&: *ss.file);
3775 if (ss.versionId == VER_NDX_GLOBAL)
3776 return;
3777
3778 if (file.verneedInfo.empty())
3779 file.verneedInfo.resize(N: file.verdefs.size());
3780
3781 // Select a version identifier for the vernaux data structure, if we haven't
3782 // already allocated one. The verdef identifiers cover the range
3783 // [1..getVerDefNum(ctx)]; this causes the vernaux identifiers to start from
3784 // getVerDefNum(ctx)+1.
3785 if (file.verneedInfo[ss.versionId].id == 0)
3786 file.verneedInfo[ss.versionId].id = ++ctx.vernauxNum + getVerDefNum(ctx);
3787 file.verneedInfo[ss.versionId].weak &= ss.isWeak();
3788
3789 ss.versionId = file.verneedInfo[ss.versionId].id;
3790}
3791
3792template <class ELFT>
3793VersionNeedSection<ELFT>::VersionNeedSection(Ctx &ctx)
3794 : SyntheticSection(ctx, ".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC,
3795 sizeof(uint32_t)) {}
3796
3797template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
3798 for (SharedFile *f : ctx.sharedFiles) {
3799 if (f->verneedInfo.empty())
3800 continue;
3801 verneeds.emplace_back();
3802 Verneed &vn = verneeds.back();
3803 vn.nameStrTab = getPartition(ctx).dynStrTab->addString(f->soName);
3804 bool isLibc = ctx.arg.relrGlibc && f->soName.starts_with(Prefix: "libc.so.");
3805 bool isGlibc2 = false;
3806 for (unsigned i = 0; i != f->verneedInfo.size(); ++i) {
3807 if (f->verneedInfo[i].id == 0)
3808 continue;
3809 // Each Verdef has one or more Verdaux entries. The first Verdaux gives
3810 // the version name; subsequent entries (if any) are parent versions
3811 // (e.g., v2 {} v1;). We only use the first one, as parent versions have
3812 // no rtld behavior difference in practice.
3813 auto *verdef =
3814 reinterpret_cast<const typename ELFT::Verdef *>(f->verdefs[i]);
3815 StringRef ver(f->getStringTable().data() + verdef->getAux()->vda_name);
3816 if (isLibc && ver.starts_with(Prefix: "GLIBC_2."))
3817 isGlibc2 = true;
3818 vn.vernauxs.push_back({verdef->vd_hash, f->verneedInfo[i],
3819 getPartition(ctx).dynStrTab->addString(ver)});
3820 }
3821 if (isGlibc2) {
3822 const char *ver = "GLIBC_ABI_DT_RELR";
3823 vn.vernauxs.push_back(
3824 {hashSysV(SymbolName: ver),
3825 {uint16_t(++ctx.vernauxNum + getVerDefNum(ctx)), false},
3826 getPartition(ctx).dynStrTab->addString(ver)});
3827 }
3828 }
3829
3830 if (OutputSection *sec = getPartition(ctx).dynStrTab->getParent())
3831 getParent()->link = sec->sectionIndex;
3832 getParent()->info = verneeds.size();
3833}
3834
3835template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *buf) {
3836 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
3837 auto *verneed = reinterpret_cast<Elf_Verneed *>(buf);
3838 auto *vernaux = reinterpret_cast<Elf_Vernaux *>(verneed + verneeds.size());
3839
3840 for (auto &vn : verneeds) {
3841 // Create an Elf_Verneed for this DSO.
3842 verneed->vn_version = 1;
3843 verneed->vn_cnt = vn.vernauxs.size();
3844 verneed->vn_file = vn.nameStrTab;
3845 verneed->vn_aux =
3846 reinterpret_cast<char *>(vernaux) - reinterpret_cast<char *>(verneed);
3847 verneed->vn_next = sizeof(Elf_Verneed);
3848 ++verneed;
3849
3850 // Create the Elf_Vernauxs for this Elf_Verneed.
3851 for (auto &vna : vn.vernauxs) {
3852 vernaux->vna_hash = vna.hash;
3853 vernaux->vna_flags = vna.verneedInfo.weak ? VER_FLG_WEAK : 0;
3854 vernaux->vna_other = vna.verneedInfo.id;
3855 vernaux->vna_name = vna.nameStrTab;
3856 vernaux->vna_next = sizeof(Elf_Vernaux);
3857 ++vernaux;
3858 }
3859
3860 vernaux[-1].vna_next = 0;
3861 }
3862 verneed[-1].vn_next = 0;
3863}
3864
3865template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
3866 return verneeds.size() * sizeof(Elf_Verneed) +
3867 ctx.vernauxNum * sizeof(Elf_Vernaux);
3868}
3869
3870template <class ELFT> bool VersionNeedSection<ELFT>::isNeeded() const {
3871 return isLive() && ctx.vernauxNum != 0;
3872}
3873
3874void MergeSyntheticSection::addSection(MergeInputSection *ms) {
3875 ms->parent = this;
3876 sections.push_back(Elt: ms);
3877 assert(addralign == ms->addralign || !(ms->flags & SHF_STRINGS));
3878 addralign = std::max(a: addralign, b: ms->addralign);
3879}
3880
3881MergeTailSection::MergeTailSection(Ctx &ctx, StringRef name, uint32_t type,
3882 uint64_t flags, uint32_t alignment)
3883 : MergeSyntheticSection(ctx, name, type, flags, alignment),
3884 builder(StringTableBuilder::RAW, llvm::Align(alignment)) {}
3885
3886size_t MergeTailSection::getSize() const { return builder.getSize(); }
3887
3888void MergeTailSection::writeTo(uint8_t *buf) { builder.write(Buf: buf); }
3889
3890void MergeTailSection::finalizeContents() {
3891 // Add all string pieces to the string table builder to create section
3892 // contents.
3893 for (MergeInputSection *sec : sections)
3894 for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3895 if (sec->pieces[i].live)
3896 builder.add(S: sec->getData(i));
3897
3898 // Fix the string table content. After this, the contents will never change.
3899 builder.finalize();
3900
3901 // finalize() fixed tail-optimized strings, so we can now get
3902 // offsets of strings. Get an offset for each string and save it
3903 // to a corresponding SectionPiece for easy access.
3904 for (MergeInputSection *sec : sections)
3905 for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
3906 if (sec->pieces[i].live)
3907 sec->pieces[i].outputOff = builder.getOffset(S: sec->getData(i));
3908}
3909
3910void MergeNoTailSection::writeTo(uint8_t *buf) {
3911 parallelFor(Begin: 0, End: numShards,
3912 Fn: [&](size_t i) { shards[i].write(Buf: buf + shardOffsets[i]); });
3913}
3914
3915// This function is very hot (i.e. it can take several seconds to finish)
3916// because sometimes the number of inputs is in an order of magnitude of
3917// millions. So, we use multi-threading.
3918//
3919// For any strings S and T, we know S is not mergeable with T if S's hash
3920// value is different from T's. If that's the case, we can safely put S and
3921// T into different string builders without worrying about merge misses.
3922// We do it in parallel.
3923void MergeNoTailSection::finalizeContents() {
3924 // Initializes string table builders.
3925 for (size_t i = 0; i < numShards; ++i)
3926 shards.emplace_back(Args: StringTableBuilder::RAW, Args: llvm::Align(addralign));
3927
3928 // Concurrency level. Must be a power of 2 to avoid expensive modulo
3929 // operations in the following tight loop.
3930 const size_t concurrency =
3931 llvm::bit_floor(Value: std::min<size_t>(a: ctx.arg.threadCount, b: numShards));
3932
3933 // Add section pieces to the builders.
3934 parallelFor(Begin: 0, End: concurrency, Fn: [&](size_t threadId) {
3935 for (MergeInputSection *sec : sections) {
3936 for (size_t i = 0, e = sec->pieces.size(); i != e; ++i) {
3937 if (!sec->pieces[i].live)
3938 continue;
3939 size_t shardId = getShardId(hash: sec->pieces[i].hash);
3940 if ((shardId & (concurrency - 1)) == threadId)
3941 sec->pieces[i].outputOff = shards[shardId].add(S: sec->getData(i));
3942 }
3943 }
3944 });
3945
3946 // Compute an in-section offset for each shard.
3947 size_t off = 0;
3948 for (size_t i = 0; i < numShards; ++i) {
3949 shards[i].finalizeInOrder();
3950 if (shards[i].getSize() > 0)
3951 off = alignToPowerOf2(Value: off, Align: addralign);
3952 shardOffsets[i] = off;
3953 off += shards[i].getSize();
3954 }
3955 size = off;
3956
3957 // So far, section pieces have offsets from beginning of shards, but
3958 // we want offsets from beginning of the whole section. Fix them.
3959 parallelForEach(R&: sections, Fn: [&](MergeInputSection *sec) {
3960 for (SectionPiece &piece : sec->pieces)
3961 if (piece.live)
3962 piece.outputOff += shardOffsets[getShardId(hash: piece.hash)];
3963 });
3964}
3965
3966template <class ELFT> void elf::splitSections(Ctx &ctx) {
3967 llvm::TimeTraceScope timeScope("Split sections");
3968 // splitIntoPieces needs to be called on each MergeInputSection
3969 // before calling finalizeContents().
3970 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
3971 for (InputSectionBase *sec : file->getSections()) {
3972 if (!sec)
3973 continue;
3974 if (auto *s = dyn_cast<MergeInputSection>(Val: sec))
3975 s->splitIntoPieces();
3976 else if (auto *eh = dyn_cast<EhInputSection>(Val: sec))
3977 eh->split<ELFT>();
3978 }
3979 });
3980}
3981
3982void elf::combineEhSections(Ctx &ctx) {
3983 llvm::TimeTraceScope timeScope("Combine EH sections");
3984 for (EhInputSection *sec : ctx.ehInputSections) {
3985 EhFrameSection &eh = *sec->getPartition(ctx).ehFrame;
3986 sec->parent = &eh;
3987 eh.addralign = std::max(a: eh.addralign, b: sec->addralign);
3988 eh.sections.push_back(Elt: sec);
3989 llvm::append_range(C&: eh.dependentSections, R&: sec->dependentSections);
3990 }
3991
3992 if (!ctx.mainPart->armExidx)
3993 return;
3994 llvm::erase_if(C&: ctx.inputSections, P: [&](InputSectionBase *s) {
3995 // Ignore dead sections and the partition end marker (.part.end),
3996 // whose partition number is out of bounds.
3997 if (!s->isLive() || s->partition == 255)
3998 return false;
3999 Partition &part = s->getPartition(ctx);
4000 return s->kind() == SectionBase::Regular && part.armExidx &&
4001 part.armExidx->addSection(isec: cast<InputSection>(Val: s));
4002 });
4003}
4004
4005MipsRldMapSection::MipsRldMapSection(Ctx &ctx)
4006 : SyntheticSection(ctx, ".rld_map", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE,
4007 ctx.arg.wordsize) {}
4008
4009ARMExidxSyntheticSection::ARMExidxSyntheticSection(Ctx &ctx)
4010 : SyntheticSection(ctx, ".ARM.exidx", SHT_ARM_EXIDX,
4011 SHF_ALLOC | SHF_LINK_ORDER, ctx.arg.wordsize) {}
4012
4013static InputSection *findExidxSection(InputSection *isec) {
4014 for (InputSection *d : isec->dependentSections)
4015 if (d->type == SHT_ARM_EXIDX && d->isLive())
4016 return d;
4017 return nullptr;
4018}
4019
4020static bool isValidExidxSectionDep(InputSection *isec) {
4021 return (isec->flags & SHF_ALLOC) && (isec->flags & SHF_EXECINSTR) &&
4022 isec->getSize() > 0;
4023}
4024
4025bool ARMExidxSyntheticSection::addSection(InputSection *isec) {
4026 if (isec->type == SHT_ARM_EXIDX) {
4027 if (InputSection *dep = isec->getLinkOrderDep())
4028 if (isValidExidxSectionDep(isec: dep)) {
4029 exidxSections.push_back(Elt: isec);
4030 // Every exidxSection is 8 bytes, we need an estimate of
4031 // size before assignAddresses can be called. Final size
4032 // will only be known after finalize is called.
4033 size += 8;
4034 }
4035 return true;
4036 }
4037
4038 if (isValidExidxSectionDep(isec)) {
4039 executableSections.push_back(Elt: isec);
4040 return false;
4041 }
4042
4043 // FIXME: we do not output a relocation section when --emit-relocs is used
4044 // as we do not have relocation sections for linker generated table entries
4045 // and we would have to erase at a late stage relocations from merged entries.
4046 // Given that exception tables are already position independent and a binary
4047 // analyzer could derive the relocations we choose to erase the relocations.
4048 if (ctx.arg.emitRelocs && isec->type == SHT_REL)
4049 if (InputSectionBase *ex = isec->getRelocatedSection())
4050 if (isa<InputSection>(Val: ex) && ex->type == SHT_ARM_EXIDX)
4051 return true;
4052
4053 return false;
4054}
4055
4056// References to .ARM.Extab Sections have bit 31 clear and are not the
4057// special EXIDX_CANTUNWIND bit-pattern.
4058static bool isExtabRef(uint32_t unwind) {
4059 return (unwind & 0x80000000) == 0 && unwind != 0x1;
4060}
4061
4062// Return true if the .ARM.exidx section Cur can be merged into the .ARM.exidx
4063// section Prev, where Cur follows Prev in the table. This can be done if the
4064// unwinding instructions in Cur are identical to Prev. Linker generated
4065// EXIDX_CANTUNWIND entries are represented by nullptr as they do not have an
4066// InputSection.
4067static bool isDuplicateArmExidxSec(Ctx &ctx, InputSection *prev,
4068 InputSection *cur) {
4069 // Get the last table Entry from the previous .ARM.exidx section. If Prev is
4070 // nullptr then it will be a synthesized EXIDX_CANTUNWIND entry.
4071 uint32_t prevUnwind = 1;
4072 if (prev)
4073 prevUnwind =
4074 read32(ctx, p: prev->content().data() + prev->content().size() - 4);
4075 if (isExtabRef(unwind: prevUnwind))
4076 return false;
4077
4078 // We consider the unwind instructions of an .ARM.exidx table entry
4079 // a duplicate if the previous unwind instructions if:
4080 // - Both are the special EXIDX_CANTUNWIND.
4081 // - Both are the same inline unwind instructions.
4082 // We do not attempt to follow and check links into .ARM.extab tables as
4083 // consecutive identical entries are rare and the effort to check that they
4084 // are identical is high.
4085
4086 // If Cur is nullptr then this is synthesized EXIDX_CANTUNWIND entry.
4087 if (cur == nullptr)
4088 return prevUnwind == 1;
4089
4090 for (uint32_t offset = 4; offset < (uint32_t)cur->content().size(); offset +=8) {
4091 uint32_t curUnwind = read32(ctx, p: cur->content().data() + offset);
4092 if (isExtabRef(unwind: curUnwind) || curUnwind != prevUnwind)
4093 return false;
4094 }
4095 // All table entries in this .ARM.exidx Section can be merged into the
4096 // previous Section.
4097 return true;
4098}
4099
4100// The .ARM.exidx table must be sorted in ascending order of the address of the
4101// functions the table describes. std::optionally duplicate adjacent table
4102// entries can be removed. At the end of the function the executableSections
4103// must be sorted in ascending order of address, Sentinel is set to the
4104// InputSection with the highest address and any InputSections that have
4105// mergeable .ARM.exidx table entries are removed from it.
4106void ARMExidxSyntheticSection::finalizeContents() {
4107 // Ensure that any fixed-point iterations after the first see the original set
4108 // of sections.
4109 if (!originalExecutableSections.empty())
4110 executableSections = originalExecutableSections;
4111 else if (ctx.arg.enableNonContiguousRegions)
4112 originalExecutableSections = executableSections;
4113
4114 // The executableSections and exidxSections that we use to derive the final
4115 // contents of this SyntheticSection are populated before
4116 // processSectionCommands() and ICF. A /DISCARD/ entry in SECTIONS command or
4117 // ICF may remove executable InputSections and their dependent .ARM.exidx
4118 // section that we recorded earlier.
4119 auto isDiscarded = [](const InputSection *isec) { return !isec->isLive(); };
4120 llvm::erase_if(C&: exidxSections, P: isDiscarded);
4121 // We need to remove discarded InputSections and InputSections without
4122 // .ARM.exidx sections that if we generated the .ARM.exidx it would be out
4123 // of range.
4124 auto isDiscardedOrOutOfRange = [this](InputSection *isec) {
4125 if (!isec->isLive())
4126 return true;
4127 if (findExidxSection(isec))
4128 return false;
4129 int64_t off = static_cast<int64_t>(isec->getVA() - getVA());
4130 return off != llvm::SignExtend64(X: off, B: 31);
4131 };
4132 llvm::erase_if(C&: executableSections, P: isDiscardedOrOutOfRange);
4133
4134 // Sort the executable sections that may or may not have associated
4135 // .ARM.exidx sections by order of ascending address. This requires the
4136 // relative positions of InputSections and OutputSections to be known.
4137 auto compareByFilePosition = [](const InputSection *a,
4138 const InputSection *b) {
4139 OutputSection *aOut = a->getParent();
4140 OutputSection *bOut = b->getParent();
4141
4142 if (aOut != bOut)
4143 return aOut->addr < bOut->addr;
4144 return a->outSecOff < b->outSecOff;
4145 };
4146 llvm::stable_sort(Range&: executableSections, C: compareByFilePosition);
4147 sentinel = executableSections.back();
4148 // std::optionally merge adjacent duplicate entries.
4149 if (ctx.arg.mergeArmExidx) {
4150 SmallVector<InputSection *, 0> selectedSections;
4151 selectedSections.reserve(N: executableSections.size());
4152 selectedSections.push_back(Elt: executableSections[0]);
4153 size_t prev = 0;
4154 for (size_t i = 1; i < executableSections.size(); ++i) {
4155 InputSection *ex1 = findExidxSection(isec: executableSections[prev]);
4156 InputSection *ex2 = findExidxSection(isec: executableSections[i]);
4157 if (!isDuplicateArmExidxSec(ctx, prev: ex1, cur: ex2)) {
4158 selectedSections.push_back(Elt: executableSections[i]);
4159 prev = i;
4160 }
4161 }
4162 executableSections = std::move(selectedSections);
4163 }
4164 // offset is within the SyntheticSection.
4165 size_t offset = 0;
4166 size = 0;
4167 for (InputSection *isec : executableSections) {
4168 if (InputSection *d = findExidxSection(isec)) {
4169 d->outSecOff = offset;
4170 d->parent = getParent();
4171 offset += d->getSize();
4172 } else {
4173 offset += 8;
4174 }
4175 }
4176 // Size includes Sentinel.
4177 size = offset + 8;
4178}
4179
4180InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
4181 return executableSections.front();
4182}
4183
4184// To write the .ARM.exidx table from the ExecutableSections we have three cases
4185// 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
4186// We write the .ARM.exidx section contents and apply its relocations.
4187// 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
4188// must write the contents of an EXIDX_CANTUNWIND directly. We use the
4189// start of the InputSection as the purpose of the linker generated
4190// section is to terminate the address range of the previous entry.
4191// 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
4192// the table to terminate the address range of the final entry.
4193void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {
4194
4195 // A linker generated CANTUNWIND entry is made up of two words:
4196 // 0x0 with R_ARM_PREL31 relocation to target.
4197 // 0x1 with EXIDX_CANTUNWIND.
4198 uint64_t offset = 0;
4199 for (InputSection *isec : executableSections) {
4200 assert(isec->getParent() != nullptr);
4201 if (InputSection *d = findExidxSection(isec)) {
4202 for (int dataOffset = 0; dataOffset != (int)d->content().size();
4203 dataOffset += 4)
4204 write32(ctx, p: buf + offset + dataOffset,
4205 v: read32(ctx, p: d->content().data() + dataOffset));
4206 // Recalculate outSecOff as finalizeAddressDependentContent()
4207 // may have altered syntheticSection outSecOff.
4208 d->outSecOff = offset + outSecOff;
4209 ctx.target->relocateAlloc(sec&: *d, buf: buf + offset);
4210 offset += d->getSize();
4211 } else {
4212 // A Linker generated CANTUNWIND section.
4213 write32(ctx, p: buf + offset + 0, v: 0x0);
4214 write32(ctx, p: buf + offset + 4, v: 0x1);
4215 uint64_t s = isec->getVA();
4216 uint64_t p = getVA() + offset;
4217 ctx.target->relocateNoSym(loc: buf + offset, type: R_ARM_PREL31, val: s - p);
4218 offset += 8;
4219 }
4220 }
4221 // Write Sentinel CANTUNWIND entry.
4222 write32(ctx, p: buf + offset + 0, v: 0x0);
4223 write32(ctx, p: buf + offset + 4, v: 0x1);
4224 uint64_t s = sentinel->getVA(offset: sentinel->getSize());
4225 uint64_t p = getVA() + offset;
4226 ctx.target->relocateNoSym(loc: buf + offset, type: R_ARM_PREL31, val: s - p);
4227 assert(size == offset + 8);
4228}
4229
4230bool ARMExidxSyntheticSection::isNeeded() const {
4231 return llvm::any_of(Range: exidxSections,
4232 P: [](InputSection *isec) { return isec->isLive(); });
4233}
4234
4235ThunkSection::ThunkSection(Ctx &ctx, OutputSection *os, uint64_t off)
4236 : SyntheticSection(ctx, ".text.thunk", SHT_PROGBITS,
4237 SHF_ALLOC | SHF_EXECINSTR,
4238 ctx.arg.emachine == EM_PPC64 ? 16 : 4) {
4239 this->parent = os;
4240 this->outSecOff = off;
4241}
4242
4243size_t ThunkSection::getSize() const {
4244 if (roundUpSizeForErrata)
4245 return alignTo(Value: size, Align: 4096);
4246 return size;
4247}
4248
4249void ThunkSection::addThunk(Thunk *t) {
4250 thunks.push_back(Elt: t);
4251 t->addSymbols(isec&: *this);
4252}
4253
4254void ThunkSection::writeTo(uint8_t *buf) {
4255 for (Thunk *t : thunks)
4256 t->writeTo(buf: buf + t->offset);
4257}
4258
4259InputSection *ThunkSection::getTargetInputSection() const {
4260 if (thunks.empty())
4261 return nullptr;
4262 const Thunk *t = thunks.front();
4263 return t->getTargetInputSection();
4264}
4265
4266bool ThunkSection::assignOffsets() {
4267 uint64_t off = 0;
4268 bool changed = false;
4269 for (Thunk *t : thunks) {
4270 if (t->alignment > addralign) {
4271 addralign = t->alignment;
4272 changed = true;
4273 }
4274 off = alignToPowerOf2(Value: off, Align: t->alignment);
4275 t->setOffset(off);
4276 uint32_t size = t->size();
4277 t->getThunkTargetSym()->size = size;
4278 off += size;
4279 }
4280 if (off != size)
4281 changed = true;
4282 size = off;
4283 return changed;
4284}
4285
4286PPC32Got2Section::PPC32Got2Section(Ctx &ctx)
4287 : SyntheticSection(ctx, ".got2", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE, 4) {}
4288
4289bool PPC32Got2Section::isNeeded() const {
4290 // See the comment below. This is not needed if there is no other
4291 // InputSection.
4292 for (SectionCommand *cmd : getParent()->commands)
4293 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd))
4294 for (InputSection *isec : isd->sections)
4295 if (isec != this)
4296 return true;
4297 return false;
4298}
4299
4300void PPC32Got2Section::finalizeContents() {
4301 // PPC32 may create multiple GOT sections for -fPIC/-fPIE, one per file in
4302 // .got2 . This function computes outSecOff of each .got2 to be used in
4303 // PPC32PltCallStub::writeTo(). The purpose of this empty synthetic section is
4304 // to collect input sections named ".got2".
4305 for (SectionCommand *cmd : getParent()->commands)
4306 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd)) {
4307 for (InputSection *isec : isd->sections) {
4308 // isec->file may be nullptr for MergeSyntheticSection.
4309 if (isec != this && isec->file)
4310 isec->file->ppc32Got2 = isec;
4311 }
4312 }
4313}
4314
4315// If linking position-dependent code then the table will store the addresses
4316// directly in the binary so the section has type SHT_PROGBITS. If linking
4317// position-independent code the section has type SHT_NOBITS since it will be
4318// allocated and filled in by the dynamic linker.
4319PPC64LongBranchTargetSection::PPC64LongBranchTargetSection(Ctx &ctx)
4320 : SyntheticSection(ctx, ".branch_lt",
4321 ctx.arg.isPic ? SHT_NOBITS : SHT_PROGBITS,
4322 SHF_ALLOC | SHF_WRITE, 8) {}
4323
4324uint64_t PPC64LongBranchTargetSection::getEntryVA(const Symbol *sym,
4325 int64_t addend) {
4326 return getVA() + entry_index.find(Val: {sym, addend})->second * 8;
4327}
4328
4329std::optional<uint32_t>
4330PPC64LongBranchTargetSection::addEntry(const Symbol *sym, int64_t addend) {
4331 auto res =
4332 entry_index.try_emplace(Key: std::make_pair(x&: sym, y&: addend), Args: entries.size());
4333 if (!res.second)
4334 return std::nullopt;
4335 entries.emplace_back(Args&: sym, Args&: addend);
4336 return res.first->second;
4337}
4338
4339size_t PPC64LongBranchTargetSection::getSize() const {
4340 return entries.size() * 8;
4341}
4342
4343void PPC64LongBranchTargetSection::writeTo(uint8_t *buf) {
4344 // If linking non-pic we have the final addresses of the targets and they get
4345 // written to the table directly. For pic the dynamic linker will allocate
4346 // the section and fill it.
4347 if (ctx.arg.isPic)
4348 return;
4349
4350 for (auto entry : entries) {
4351 const Symbol *sym = entry.first;
4352 int64_t addend = entry.second;
4353 assert(sym->getVA(ctx));
4354 // Need calls to branch to the local entry-point since a long-branch
4355 // must be a local-call.
4356 write64(ctx, p: buf,
4357 v: sym->getVA(ctx, addend) +
4358 getPPC64GlobalEntryToLocalEntryOffset(ctx, stOther: sym->stOther));
4359 buf += 8;
4360 }
4361}
4362
4363bool PPC64LongBranchTargetSection::isNeeded() const {
4364 // `removeUnusedSyntheticSections()` is called before thunk allocation which
4365 // is too early to determine if this section will be empty or not. We need
4366 // Finalized to keep the section alive until after thunk creation. Finalized
4367 // only gets set to true once `finalizeSections()` is called after thunk
4368 // creation. Because of this, if we don't create any long-branch thunks we end
4369 // up with an empty .branch_lt section in the binary.
4370 return !finalized || !entries.empty();
4371}
4372
4373static uint8_t getAbiVersion(Ctx &ctx) {
4374 // MIPS non-PIC executable gets ABI version 1.
4375 if (ctx.arg.emachine == EM_MIPS) {
4376 if (!ctx.arg.isPic && !ctx.arg.relocatable &&
4377 (ctx.arg.eflags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
4378 return 1;
4379 return 0;
4380 }
4381
4382 if (ctx.arg.emachine == EM_AMDGPU && !ctx.objectFiles.empty()) {
4383 uint8_t ver = ctx.objectFiles[0]->abiVersion;
4384 for (InputFile *file : ArrayRef(ctx.objectFiles).slice(N: 1))
4385 if (file->abiVersion != ver)
4386 Err(ctx) << "incompatible ABI version: " << file;
4387 return ver;
4388 }
4389
4390 return 0;
4391}
4392
4393template <typename ELFT>
4394void elf::writeEhdr(Ctx &ctx, uint8_t *buf, Partition &part) {
4395 memcpy(dest: buf, src: "\177ELF", n: 4);
4396
4397 auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
4398 eHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
4399 eHdr->e_ident[EI_DATA] =
4400 ELFT::Endianness == endianness::little ? ELFDATA2LSB : ELFDATA2MSB;
4401 eHdr->e_ident[EI_VERSION] = EV_CURRENT;
4402 eHdr->e_ident[EI_OSABI] = ctx.arg.osabi;
4403 eHdr->e_ident[EI_ABIVERSION] = getAbiVersion(ctx);
4404 eHdr->e_machine = ctx.arg.emachine;
4405 eHdr->e_version = EV_CURRENT;
4406 eHdr->e_flags = ctx.arg.eflags;
4407 eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
4408 eHdr->e_phnum = part.phdrs.size();
4409 eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
4410
4411 if (!ctx.arg.relocatable) {
4412 eHdr->e_phoff = sizeof(typename ELFT::Ehdr);
4413 eHdr->e_phentsize = sizeof(typename ELFT::Phdr);
4414 }
4415}
4416
4417template <typename ELFT> void elf::writePhdrs(uint8_t *buf, Partition &part) {
4418 // Write the program header table.
4419 auto *hBuf = reinterpret_cast<typename ELFT::Phdr *>(buf);
4420 for (std::unique_ptr<PhdrEntry> &p : part.phdrs) {
4421 hBuf->p_type = p->p_type;
4422 hBuf->p_flags = p->p_flags;
4423 hBuf->p_offset = p->p_offset;
4424 hBuf->p_vaddr = p->p_vaddr;
4425 hBuf->p_paddr = p->p_paddr;
4426 hBuf->p_filesz = p->p_filesz;
4427 hBuf->p_memsz = p->p_memsz;
4428 hBuf->p_align = p->p_align;
4429 ++hBuf;
4430 }
4431}
4432
4433template <typename ELFT>
4434PartitionElfHeaderSection<ELFT>::PartitionElfHeaderSection(Ctx &ctx)
4435 : SyntheticSection(ctx, "", SHT_LLVM_PART_EHDR, SHF_ALLOC, 1) {}
4436
4437template <typename ELFT>
4438size_t PartitionElfHeaderSection<ELFT>::getSize() const {
4439 return sizeof(typename ELFT::Ehdr);
4440}
4441
4442template <typename ELFT>
4443void PartitionElfHeaderSection<ELFT>::writeTo(uint8_t *buf) {
4444 writeEhdr<ELFT>(ctx, buf, getPartition(ctx));
4445
4446 // Loadable partitions are always ET_DYN.
4447 auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
4448 eHdr->e_type = ET_DYN;
4449}
4450
4451template <typename ELFT>
4452PartitionProgramHeadersSection<ELFT>::PartitionProgramHeadersSection(Ctx &ctx)
4453 : SyntheticSection(ctx, ".phdrs", SHT_LLVM_PART_PHDR, SHF_ALLOC, 1) {}
4454
4455template <typename ELFT>
4456size_t PartitionProgramHeadersSection<ELFT>::getSize() const {
4457 return sizeof(typename ELFT::Phdr) * getPartition(ctx).phdrs.size();
4458}
4459
4460template <typename ELFT>
4461void PartitionProgramHeadersSection<ELFT>::writeTo(uint8_t *buf) {
4462 writePhdrs<ELFT>(buf, getPartition(ctx));
4463}
4464
4465PartitionIndexSection::PartitionIndexSection(Ctx &ctx)
4466 : SyntheticSection(ctx, ".rodata", SHT_PROGBITS, SHF_ALLOC, 4) {}
4467
4468size_t PartitionIndexSection::getSize() const {
4469 return 12 * (ctx.partitions.size() - 1);
4470}
4471
4472void PartitionIndexSection::finalizeContents() {
4473 for (size_t i = 1; i != ctx.partitions.size(); ++i)
4474 ctx.partitions[i].nameStrTab =
4475 ctx.mainPart->dynStrTab->addString(s: ctx.partitions[i].name);
4476}
4477
4478void PartitionIndexSection::writeTo(uint8_t *buf) {
4479 uint64_t va = getVA();
4480 for (size_t i = 1; i != ctx.partitions.size(); ++i) {
4481 write32(ctx, p: buf,
4482 v: ctx.mainPart->dynStrTab->getVA() + ctx.partitions[i].nameStrTab -
4483 va);
4484 write32(ctx, p: buf + 4, v: ctx.partitions[i].elfHeader->getVA() - (va + 4));
4485
4486 SyntheticSection *next = i == ctx.partitions.size() - 1
4487 ? ctx.in.partEnd.get()
4488 : ctx.partitions[i + 1].elfHeader.get();
4489 write32(ctx, p: buf + 8, v: next->getVA() - ctx.partitions[i].elfHeader->getVA());
4490
4491 va += 12;
4492 buf += 12;
4493 }
4494}
4495
4496static bool needsInterpSection(Ctx &ctx) {
4497 return !ctx.arg.relocatable && !ctx.arg.shared &&
4498 !ctx.arg.dynamicLinker.empty() && ctx.script->needsInterpSection();
4499}
4500
4501bool elf::hasMemtag(Ctx &ctx) {
4502 return ctx.arg.emachine == EM_AARCH64 &&
4503 ctx.arg.androidMemtagMode != ELF::NT_MEMTAG_LEVEL_NONE;
4504}
4505
4506// Fully static executables don't support MTE globals at this point in time, as
4507// we currently rely on:
4508// - A dynamic loader to process relocations, and
4509// - Dynamic entries.
4510// This restriction could be removed in future by re-using some of the ideas
4511// that ifuncs use in fully static executables.
4512bool elf::canHaveMemtagGlobals(Ctx &ctx) {
4513 return hasMemtag(ctx) &&
4514 (ctx.arg.relocatable || ctx.arg.shared || needsInterpSection(ctx));
4515}
4516
4517constexpr char kMemtagAndroidNoteName[] = "Android";
4518void MemtagAndroidNote::writeTo(uint8_t *buf) {
4519 static_assert(
4520 sizeof(kMemtagAndroidNoteName) == 8,
4521 "Android 11 & 12 have an ABI that the note name is 8 bytes long. Keep it "
4522 "that way for backwards compatibility.");
4523
4524 write32(ctx, p: buf, v: sizeof(kMemtagAndroidNoteName));
4525 write32(ctx, p: buf + 4, v: sizeof(uint32_t));
4526 write32(ctx, p: buf + 8, v: ELF::NT_ANDROID_TYPE_MEMTAG);
4527 memcpy(dest: buf + 12, src: kMemtagAndroidNoteName, n: sizeof(kMemtagAndroidNoteName));
4528 buf += 12 + alignTo(Value: sizeof(kMemtagAndroidNoteName), Align: 4);
4529
4530 uint32_t value = 0;
4531 value |= ctx.arg.androidMemtagMode;
4532 if (ctx.arg.androidMemtagHeap)
4533 value |= ELF::NT_MEMTAG_HEAP;
4534 // Note, MTE stack is an ABI break. Attempting to run an MTE stack-enabled
4535 // binary on Android 11 or 12 will result in a checkfail in the loader.
4536 if (ctx.arg.androidMemtagStack)
4537 value |= ELF::NT_MEMTAG_STACK;
4538 write32(ctx, p: buf, v: value); // note value
4539}
4540
4541size_t MemtagAndroidNote::getSize() const {
4542 return sizeof(llvm::ELF::Elf64_Nhdr) +
4543 /*namesz=*/alignTo(Value: sizeof(kMemtagAndroidNoteName), Align: 4) +
4544 /*descsz=*/sizeof(uint32_t);
4545}
4546
4547void PackageMetadataNote::writeTo(uint8_t *buf) {
4548 write32(ctx, p: buf, v: 4);
4549 write32(ctx, p: buf + 4, v: ctx.arg.packageMetadata.size() + 1);
4550 write32(ctx, p: buf + 8, v: FDO_PACKAGING_METADATA);
4551 memcpy(dest: buf + 12, src: "FDO", n: 4);
4552 memcpy(dest: buf + 16, src: ctx.arg.packageMetadata.data(),
4553 n: ctx.arg.packageMetadata.size());
4554}
4555
4556size_t PackageMetadataNote::getSize() const {
4557 return sizeof(llvm::ELF::Elf64_Nhdr) + 4 +
4558 alignTo(Value: ctx.arg.packageMetadata.size() + 1, Align: 4);
4559}
4560
4561// Helper function, return the size of the ULEB128 for 'v', optionally writing
4562// it to `*(buf + offset)` if `buf` is non-null.
4563static size_t computeOrWriteULEB128(uint64_t v, uint8_t *buf, size_t offset) {
4564 if (buf)
4565 return encodeULEB128(Value: v, p: buf + offset);
4566 return getULEB128Size(Value: v);
4567}
4568
4569// https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
4570constexpr uint64_t kMemtagStepSizeBits = 3;
4571constexpr uint64_t kMemtagGranuleSize = 16;
4572static size_t
4573createMemtagGlobalDescriptors(Ctx &ctx,
4574 const SmallVector<const Symbol *, 0> &symbols,
4575 uint8_t *buf = nullptr) {
4576 size_t sectionSize = 0;
4577 uint64_t lastGlobalEnd = 0;
4578
4579 for (const Symbol *sym : symbols) {
4580 if (!includeInSymtab(ctx, *sym))
4581 continue;
4582 const uint64_t addr = sym->getVA(ctx);
4583 const uint64_t size = sym->getSize();
4584
4585 if (addr <= kMemtagGranuleSize && buf != nullptr)
4586 Err(ctx) << "address of the tagged symbol \"" << sym->getName()
4587 << "\" falls in the ELF header. This is indicative of a "
4588 "compiler/linker bug";
4589 if (addr % kMemtagGranuleSize != 0)
4590 Err(ctx) << "address of the tagged symbol \"" << sym->getName()
4591 << "\" at 0x" << Twine::utohexstr(Val: addr)
4592 << "\" is not granule (16-byte) aligned";
4593 if (size == 0)
4594 Err(ctx) << "size of the tagged symbol \"" << sym->getName()
4595 << "\" is not allowed to be zero";
4596 if (size % kMemtagGranuleSize != 0)
4597 Err(ctx) << "size of the tagged symbol \"" << sym->getName()
4598 << "\" (size 0x" << Twine::utohexstr(Val: size)
4599 << ") is not granule (16-byte) aligned";
4600
4601 const uint64_t sizeToEncode = size / kMemtagGranuleSize;
4602 const uint64_t stepToEncode = ((addr - lastGlobalEnd) / kMemtagGranuleSize)
4603 << kMemtagStepSizeBits;
4604 if (sizeToEncode < (1 << kMemtagStepSizeBits)) {
4605 sectionSize += computeOrWriteULEB128(v: stepToEncode | sizeToEncode, buf, offset: sectionSize);
4606 } else {
4607 sectionSize += computeOrWriteULEB128(v: stepToEncode, buf, offset: sectionSize);
4608 sectionSize += computeOrWriteULEB128(v: sizeToEncode - 1, buf, offset: sectionSize);
4609 }
4610 lastGlobalEnd = addr + size;
4611 }
4612
4613 return sectionSize;
4614}
4615
4616bool MemtagGlobalDescriptors::updateAllocSize(Ctx &ctx) {
4617 size_t oldSize = getSize();
4618 llvm::stable_sort(Range&: symbols, C: [&ctx = ctx](const Symbol *s1, const Symbol *s2) {
4619 return s1->getVA(ctx) < s2->getVA(ctx);
4620 });
4621 return oldSize != getSize();
4622}
4623
4624void MemtagGlobalDescriptors::writeTo(uint8_t *buf) {
4625 createMemtagGlobalDescriptors(ctx, symbols, buf);
4626}
4627
4628size_t MemtagGlobalDescriptors::getSize() const {
4629 return createMemtagGlobalDescriptors(ctx, symbols);
4630}
4631
4632static OutputSection *findSection(Ctx &ctx, StringRef name) {
4633 for (SectionCommand *cmd : ctx.script->sectionCommands)
4634 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
4635 if (osd->osec.name == name)
4636 return &osd->osec;
4637 return nullptr;
4638}
4639
4640static Defined *addOptionalRegular(Ctx &ctx, StringRef name, SectionBase *sec,
4641 uint64_t val, uint8_t stOther = STV_HIDDEN) {
4642 Symbol *s = ctx.symtab->find(name);
4643 if (!s || s->isDefined() || s->isCommon())
4644 return nullptr;
4645
4646 s->resolve(ctx, other: Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
4647 stOther, STT_NOTYPE, val,
4648 /*size=*/0, sec});
4649 s->isUsedInRegularObj = true;
4650 return cast<Defined>(Val: s);
4651}
4652
4653template <class ELFT> void elf::createSyntheticSections(Ctx &ctx) {
4654 // Add the .interp section first because it is not a SyntheticSection.
4655 // The removeUnusedSyntheticSections() function relies on the
4656 // SyntheticSections coming last.
4657 if (needsInterpSection(ctx)) {
4658 for (size_t i = 1; i <= ctx.partitions.size(); ++i) {
4659 InputSection *sec = createInterpSection(ctx);
4660 sec->partition = i;
4661 ctx.inputSections.push_back(Elt: sec);
4662 }
4663 }
4664
4665 auto add = [&](SyntheticSection &sec) { ctx.inputSections.push_back(Elt: &sec); };
4666
4667 if (ctx.arg.zSectionHeader)
4668 ctx.in.shStrTab =
4669 std::make_unique<StringTableSection>(args&: ctx, args: ".shstrtab", args: false);
4670
4671 ctx.out.programHeaders =
4672 std::make_unique<OutputSection>(args&: ctx, args: "", args: 0, args: SHF_ALLOC);
4673 ctx.out.programHeaders->addralign = ctx.arg.wordsize;
4674
4675 if (ctx.arg.strip != StripPolicy::All) {
4676 ctx.in.strTab = std::make_unique<StringTableSection>(args&: ctx, args: ".strtab", args: false);
4677 ctx.in.symTab =
4678 std::make_unique<SymbolTableSection<ELFT>>(ctx, *ctx.in.strTab);
4679 ctx.in.symTabShndx = std::make_unique<SymtabShndxSection>(args&: ctx);
4680 }
4681
4682 ctx.in.bss = std::make_unique<BssSection>(args&: ctx, args: ".bss", args: 0, args: 1);
4683 add(*ctx.in.bss);
4684
4685 // If there is a SECTIONS command and a .data.rel.ro section name use name
4686 // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
4687 // This makes sure our relro is contiguous.
4688 bool hasDataRelRo =
4689 ctx.script->hasSectionsCommand && findSection(ctx, name: ".data.rel.ro");
4690 ctx.in.bssRelRo = std::make_unique<BssSection>(
4691 args&: ctx, args: hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", args: 0, args: 1);
4692 add(*ctx.in.bssRelRo);
4693
4694 // Add MIPS-specific sections.
4695 if (ctx.arg.emachine == EM_MIPS) {
4696 if (!ctx.arg.shared && ctx.hasDynsym) {
4697 ctx.in.mipsRldMap = std::make_unique<MipsRldMapSection>(args&: ctx);
4698 add(*ctx.in.mipsRldMap);
4699 }
4700 if ((ctx.in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create(ctx)))
4701 add(*ctx.in.mipsAbiFlags);
4702 if ((ctx.in.mipsOptions = MipsOptionsSection<ELFT>::create(ctx)))
4703 add(*ctx.in.mipsOptions);
4704 if ((ctx.in.mipsReginfo = MipsReginfoSection<ELFT>::create(ctx)))
4705 add(*ctx.in.mipsReginfo);
4706 }
4707
4708 StringRef relaDynName = ctx.arg.isRela ? ".rela.dyn" : ".rel.dyn";
4709
4710 const unsigned threadCount = ctx.arg.threadCount;
4711 for (Partition &part : ctx.partitions) {
4712 auto add = [&](SyntheticSection &sec) {
4713 sec.partition = part.getNumber(ctx);
4714 ctx.inputSections.push_back(Elt: &sec);
4715 };
4716
4717 if (!part.name.empty()) {
4718 part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>(ctx);
4719 part.elfHeader->name = part.name;
4720 add(*part.elfHeader);
4721
4722 part.programHeaders =
4723 std::make_unique<PartitionProgramHeadersSection<ELFT>>(ctx);
4724 add(*part.programHeaders);
4725 }
4726
4727 if (ctx.arg.buildId != BuildIdKind::None) {
4728 part.buildId = std::make_unique<BuildIdSection>(args&: ctx);
4729 add(*part.buildId);
4730 }
4731
4732 // dynSymTab is always present to simplify several finalizeSections
4733 // functions.
4734 part.dynStrTab = std::make_unique<StringTableSection>(args&: ctx, args: ".dynstr", args: true);
4735 part.dynSymTab =
4736 std::make_unique<SymbolTableSection<ELFT>>(ctx, *part.dynStrTab);
4737
4738 if (ctx.arg.relocatable)
4739 continue;
4740 part.dynamic = std::make_unique<DynamicSection<ELFT>>(ctx);
4741
4742 if (hasMemtag(ctx)) {
4743 part.memtagAndroidNote = std::make_unique<MemtagAndroidNote>(args&: ctx);
4744 add(*part.memtagAndroidNote);
4745 if (canHaveMemtagGlobals(ctx)) {
4746 part.memtagGlobalDescriptors =
4747 std::make_unique<MemtagGlobalDescriptors>(args&: ctx);
4748 add(*part.memtagGlobalDescriptors);
4749 }
4750 }
4751
4752 if (ctx.arg.androidPackDynRelocs)
4753 part.relaDyn = std::make_unique<AndroidPackedRelocationSection<ELFT>>(
4754 ctx, relaDynName, threadCount);
4755 else
4756 part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
4757 ctx, relaDynName, ctx.arg.zCombreloc, threadCount);
4758
4759 if (ctx.hasDynsym) {
4760 add(*part.dynSymTab);
4761
4762 part.verSym = std::make_unique<VersionTableSection>(args&: ctx);
4763 add(*part.verSym);
4764
4765 if (!namedVersionDefs(ctx).empty()) {
4766 part.verDef = std::make_unique<VersionDefinitionSection>(args&: ctx);
4767 add(*part.verDef);
4768 }
4769
4770 part.verNeed = std::make_unique<VersionNeedSection<ELFT>>(ctx);
4771 add(*part.verNeed);
4772
4773 if (ctx.arg.gnuHash) {
4774 part.gnuHashTab = std::make_unique<GnuHashTableSection>(args&: ctx);
4775 add(*part.gnuHashTab);
4776 }
4777
4778 if (ctx.arg.sysvHash) {
4779 part.hashTab = std::make_unique<HashTableSection>(args&: ctx);
4780 add(*part.hashTab);
4781 }
4782
4783 add(*part.dynamic);
4784 add(*part.dynStrTab);
4785 }
4786 add(*part.relaDyn);
4787
4788 if (ctx.arg.relrPackDynRelocs) {
4789 part.relrDyn = std::make_unique<RelrSection<ELFT>>(ctx, threadCount);
4790 add(*part.relrDyn);
4791 part.relrAuthDyn = std::make_unique<RelrSection<ELFT>>(
4792 ctx, threadCount, /*isAArch64Auth=*/true);
4793 add(*part.relrAuthDyn);
4794 }
4795
4796 if (ctx.arg.ehFrameHdr) {
4797 part.ehFrameHdr = std::make_unique<EhFrameHeader>(args&: ctx);
4798 add(*part.ehFrameHdr);
4799 }
4800 part.ehFrame = std::make_unique<EhFrameSection>(args&: ctx);
4801 add(*part.ehFrame);
4802
4803 if (ctx.arg.emachine == EM_ARM) {
4804 // This section replaces all the individual .ARM.exidx InputSections.
4805 part.armExidx = std::make_unique<ARMExidxSyntheticSection>(args&: ctx);
4806 add(*part.armExidx);
4807 }
4808
4809 if (!ctx.arg.packageMetadata.empty()) {
4810 part.packageMetadataNote = std::make_unique<PackageMetadataNote>(args&: ctx);
4811 add(*part.packageMetadataNote);
4812 }
4813 }
4814
4815 if (ctx.partitions.size() != 1) {
4816 // Create the partition end marker. This needs to be in partition number 255
4817 // so that it is sorted after all other partitions. It also has other
4818 // special handling (see createPhdrs() and combineEhSections()).
4819 ctx.in.partEnd =
4820 std::make_unique<BssSection>(args&: ctx, args: ".part.end", args&: ctx.arg.maxPageSize, args: 1);
4821 ctx.in.partEnd->partition = 255;
4822 add(*ctx.in.partEnd);
4823
4824 ctx.in.partIndex = std::make_unique<PartitionIndexSection>(args&: ctx);
4825 addOptionalRegular(ctx, name: "__part_index_begin", sec: ctx.in.partIndex.get(), val: 0);
4826 addOptionalRegular(ctx, name: "__part_index_end", sec: ctx.in.partIndex.get(),
4827 val: ctx.in.partIndex->getSize());
4828 add(*ctx.in.partIndex);
4829 }
4830
4831 // Add .got. MIPS' .got is so different from the other archs,
4832 // it has its own class.
4833 if (ctx.arg.emachine == EM_MIPS) {
4834 ctx.in.mipsGot = std::make_unique<MipsGotSection>(args&: ctx);
4835 add(*ctx.in.mipsGot);
4836 } else {
4837 ctx.in.got = std::make_unique<GotSection>(args&: ctx);
4838 add(*ctx.in.got);
4839 }
4840
4841 if (ctx.arg.emachine == EM_PPC) {
4842 ctx.in.ppc32Got2 = std::make_unique<PPC32Got2Section>(args&: ctx);
4843 add(*ctx.in.ppc32Got2);
4844 }
4845
4846 if (ctx.arg.emachine == EM_PPC64) {
4847 ctx.in.ppc64LongBranchTarget =
4848 std::make_unique<PPC64LongBranchTargetSection>(args&: ctx);
4849 add(*ctx.in.ppc64LongBranchTarget);
4850 }
4851
4852 ctx.in.gotPlt = std::make_unique<GotPltSection>(args&: ctx);
4853 add(*ctx.in.gotPlt);
4854 ctx.in.igotPlt = std::make_unique<IgotPltSection>(args&: ctx);
4855 add(*ctx.in.igotPlt);
4856 // Add .relro_padding if DATA_SEGMENT_RELRO_END is used; otherwise, add the
4857 // section in the absence of PHDRS/SECTIONS commands.
4858 if (ctx.arg.zRelro &&
4859 ((ctx.script->phdrsCommands.empty() && !ctx.script->hasSectionsCommand) ||
4860 ctx.script->seenRelroEnd)) {
4861 ctx.in.relroPadding = std::make_unique<RelroPaddingSection>(args&: ctx);
4862 add(*ctx.in.relroPadding);
4863 }
4864
4865 if (ctx.arg.emachine == EM_ARM) {
4866 ctx.in.armCmseSGSection = std::make_unique<ArmCmseSGSection>(args&: ctx);
4867 add(*ctx.in.armCmseSGSection);
4868 }
4869
4870 // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
4871 // it as a relocation and ensure the referenced section is created.
4872 if (ctx.sym.globalOffsetTable && ctx.arg.emachine != EM_MIPS) {
4873 if (ctx.target->gotBaseSymInGotPlt)
4874 ctx.in.gotPlt->hasGotPltOffRel = true;
4875 else
4876 ctx.in.got->hasGotOffRel = true;
4877 }
4878
4879 // We always need to add rel[a].plt to output if it has entries.
4880 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
4881 ctx.in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
4882 ctx, ctx.arg.isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false,
4883 /*threadCount=*/1);
4884 add(*ctx.in.relaPlt);
4885
4886 if ((ctx.arg.emachine == EM_386 || ctx.arg.emachine == EM_X86_64) &&
4887 (ctx.arg.andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
4888 ctx.in.ibtPlt = std::make_unique<IBTPltSection>(args&: ctx);
4889 add(*ctx.in.ibtPlt);
4890 }
4891
4892 if (ctx.arg.emachine == EM_PPC)
4893 ctx.in.plt = std::make_unique<PPC32GlinkSection>(args&: ctx);
4894 else
4895 ctx.in.plt = std::make_unique<PltSection>(args&: ctx);
4896 add(*ctx.in.plt);
4897 ctx.in.iplt = std::make_unique<IpltSection>(args&: ctx);
4898 add(*ctx.in.iplt);
4899
4900 if (ctx.arg.andFeatures || ctx.aarch64PauthAbiCoreInfo) {
4901 ctx.in.gnuProperty = std::make_unique<GnuPropertySection>(args&: ctx);
4902 add(*ctx.in.gnuProperty);
4903 }
4904
4905 if (ctx.arg.debugNames) {
4906 ctx.in.debugNames = std::make_unique<DebugNamesSection<ELFT>>(ctx);
4907 add(*ctx.in.debugNames);
4908 }
4909
4910 if (ctx.arg.gdbIndex) {
4911 ctx.in.gdbIndex = GdbIndexSection::create<ELFT>(ctx);
4912 add(*ctx.in.gdbIndex);
4913 }
4914
4915 // .note.GNU-stack is always added when we are creating a re-linkable
4916 // object file. Other linkers are using the presence of this marker
4917 // section to control the executable-ness of the stack area, but that
4918 // is irrelevant these days. Stack area should always be non-executable
4919 // by default. So we emit this section unconditionally.
4920 if (ctx.arg.relocatable) {
4921 ctx.in.gnuStack = std::make_unique<GnuStackSection>(args&: ctx);
4922 add(*ctx.in.gnuStack);
4923 }
4924
4925 if (ctx.in.symTab)
4926 add(*ctx.in.symTab);
4927 if (ctx.in.symTabShndx)
4928 add(*ctx.in.symTabShndx);
4929 if (ctx.in.shStrTab)
4930 add(*ctx.in.shStrTab);
4931 if (ctx.in.strTab)
4932 add(*ctx.in.strTab);
4933}
4934
4935template void elf::splitSections<ELF32LE>(Ctx &);
4936template void elf::splitSections<ELF32BE>(Ctx &);
4937template void elf::splitSections<ELF64LE>(Ctx &);
4938template void elf::splitSections<ELF64BE>(Ctx &);
4939
4940template void EhFrameSection::iterateFDEWithLSDA<ELF32LE>(
4941 function_ref<void(InputSection &)>);
4942template void EhFrameSection::iterateFDEWithLSDA<ELF32BE>(
4943 function_ref<void(InputSection &)>);
4944template void EhFrameSection::iterateFDEWithLSDA<ELF64LE>(
4945 function_ref<void(InputSection &)>);
4946template void EhFrameSection::iterateFDEWithLSDA<ELF64BE>(
4947 function_ref<void(InputSection &)>);
4948
4949template class elf::SymbolTableSection<ELF32LE>;
4950template class elf::SymbolTableSection<ELF32BE>;
4951template class elf::SymbolTableSection<ELF64LE>;
4952template class elf::SymbolTableSection<ELF64BE>;
4953
4954template void elf::writeEhdr<ELF32LE>(Ctx &, uint8_t *Buf, Partition &Part);
4955template void elf::writeEhdr<ELF32BE>(Ctx &, uint8_t *Buf, Partition &Part);
4956template void elf::writeEhdr<ELF64LE>(Ctx &, uint8_t *Buf, Partition &Part);
4957template void elf::writeEhdr<ELF64BE>(Ctx &, uint8_t *Buf, Partition &Part);
4958
4959template void elf::writePhdrs<ELF32LE>(uint8_t *Buf, Partition &Part);
4960template void elf::writePhdrs<ELF32BE>(uint8_t *Buf, Partition &Part);
4961template void elf::writePhdrs<ELF64LE>(uint8_t *Buf, Partition &Part);
4962template void elf::writePhdrs<ELF64BE>(uint8_t *Buf, Partition &Part);
4963
4964template void elf::createSyntheticSections<ELF32LE>(Ctx &);
4965template void elf::createSyntheticSections<ELF32BE>(Ctx &);
4966template void elf::createSyntheticSections<ELF64LE>(Ctx &);
4967template void elf::createSyntheticSections<ELF64BE>(Ctx &);
4968