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