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