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