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