1//===- Relocations.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 implements the core relocation processing logic. It analyzes
10// relocations and determines what auxiliary data structures (GOT, PLT, copy
11// relocations) need to be created during linking.
12//
13// The main entry point is scanRelocations<ELFT>(), which calls scanSection()
14// to process all relocations within an input section. For each relocation,
15// scan() analyzes the type and target, and determines whether a synthetic
16// section entry or dynamic relocation is needed.
17//
18// Note: This file analyzes what needs to be done but doesn't apply the
19// actual relocations - that happens later in InputSection::writeTo().
20// Instead, it populates Relocation objects in InputSectionBase::relocations
21// and creates necessary synthetic sections (GOT, PLT, etc.).
22//
23// In addition, this file implements the core Thunk creation logic, called
24// during finalizeAddressDependentContent().
25//
26//===----------------------------------------------------------------------===//
27
28#include "Relocations.h"
29#include "Config.h"
30#include "InputFiles.h"
31#include "LinkerScript.h"
32#include "OutputSections.h"
33#include "RelocScan.h"
34#include "SymbolTable.h"
35#include "Symbols.h"
36#include "SyntheticSections.h"
37#include "Target.h"
38#include "Thunks.h"
39#include "lld/Common/ErrorHandler.h"
40#include "lld/Common/Memory.h"
41#include "llvm/ADT/SmallSet.h"
42#include "llvm/BinaryFormat/ELF.h"
43#include "llvm/Demangle/Demangle.h"
44#include <algorithm>
45
46using namespace llvm;
47using namespace llvm::ELF;
48using namespace llvm::object;
49using namespace llvm::support::endian;
50using namespace lld;
51using namespace lld::elf;
52
53static void printDefinedLocation(ELFSyncStream &s, const Symbol &sym) {
54 s << "\n>>> defined in " << sym.file;
55}
56
57// Construct a message in the following format.
58//
59// >>> defined in /home/alice/src/foo.o
60// >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
61// >>> /home/alice/src/bar.o:(.text+0x1)
62void elf::printLocation(ELFSyncStream &s, InputSectionBase &sec,
63 const Symbol &sym, uint64_t off) {
64 printDefinedLocation(s, sym);
65 s << "\n>>> referenced by ";
66 auto tell = s.tell();
67 s << sec.getSrcMsg(sym, offset: off);
68 if (tell != s.tell())
69 s << "\n>>> ";
70 s << sec.getObjMsg(offset: off);
71}
72
73void elf::reportRangeError(Ctx &ctx, uint8_t *loc, const Relocation &rel,
74 const Twine &v, int64_t min, uint64_t max) {
75 ErrorPlace errPlace = getErrorPlace(ctx, loc);
76 auto diag = Err(ctx);
77 diag << errPlace.loc << "relocation " << rel.type
78 << " out of range: " << v.str() << " is not in [" << min << ", " << max
79 << ']';
80
81 if (rel.sym) {
82 if (!rel.sym->isSection())
83 diag << "; references '" << rel.sym << '\'';
84 else if (auto *d = dyn_cast<Defined>(Val: rel.sym))
85 diag << "; references section '" << d->section->name << "'";
86
87 if (ctx.arg.emachine == EM_X86_64 && rel.type == R_X86_64_PC32 &&
88 rel.sym->getOutputSection() &&
89 (rel.sym->getOutputSection()->flags & SHF_X86_64_LARGE)) {
90 diag << "; R_X86_64_PC32 should not reference a section marked "
91 "SHF_X86_64_LARGE";
92 }
93 }
94 if (!errPlace.srcLoc.empty())
95 diag << "\n>>> referenced by " << errPlace.srcLoc;
96 if (rel.sym && !rel.sym->isSection())
97 printDefinedLocation(s&: diag, sym: *rel.sym);
98
99 if (errPlace.isec && errPlace.isec->name.starts_with(Prefix: ".debug"))
100 diag << "; consider recompiling with -fdebug-types-section to reduce size "
101 "of debug sections";
102}
103
104void elf::reportRangeError(Ctx &ctx, uint8_t *loc, int64_t v, int n,
105 const Symbol &sym, const Twine &msg) {
106 auto diag = Err(ctx);
107 diag << getErrorPlace(ctx, loc).loc << msg << " is out of range: " << v
108 << " is not in [" << llvm::minIntN(N: n) << ", " << llvm::maxIntN(N: n) << "]";
109 if (!sym.getName().empty()) {
110 diag << "; references '" << &sym << '\'';
111 printDefinedLocation(s&: diag, sym);
112 }
113}
114
115// True if non-preemptable symbol always has the same value regardless of where
116// the DSO is loaded.
117bool elf::isAbsolute(const Symbol &sym) {
118 if (sym.isUndefined())
119 return true;
120 if (const auto *dr = dyn_cast<Defined>(Val: &sym))
121 return dr->section == nullptr; // Absolute symbol.
122 return false;
123}
124
125static bool isAbsoluteOrTls(const Symbol &sym) {
126 return isAbsolute(sym) || sym.isTls();
127}
128
129// Returns true if Expr refers a PLT entry.
130static bool needsPlt(RelExpr expr) {
131 return oneof<R_PLT, R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT, R_GOTPLT_GOTREL,
132 R_GOTPLT_PC, RE_LOONGARCH_PLT_PAGE_PC, RE_PPC32_PLTREL,
133 RE_PPC64_CALL_PLT>(expr);
134}
135
136bool lld::elf::needsGot(RelExpr expr) {
137 return oneof<R_GOT, R_GOT_OFF, RE_MIPS_GOT_LOCAL_PAGE, RE_MIPS_GOT_OFF,
138 RE_MIPS_GOT_OFF32, RE_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT,
139 RE_AARCH64_GOT_PAGE, RE_LOONGARCH_GOT, RE_LOONGARCH_GOT_PAGE_PC>(
140 expr);
141}
142
143// True if this expression is of the form Sym - X, where X is a position in the
144// file (PC, or GOT for example).
145static bool isRelExpr(RelExpr expr) {
146 return oneof<R_PC, R_GOTREL, R_GOTPLTREL, RE_ARM_PCA, RE_MIPS_GOTREL,
147 RE_PPC64_CALL, RE_AARCH64_PAGE_PC, R_RELAX_GOT_PC,
148 RE_RISCV_PC_INDIRECT, RE_LOONGARCH_PAGE_PC,
149 RE_LOONGARCH_PC_INDIRECT>(expr);
150}
151
152static RelExpr toPlt(RelExpr expr) {
153 switch (expr) {
154 case RE_LOONGARCH_PAGE_PC:
155 return RE_LOONGARCH_PLT_PAGE_PC;
156 case RE_PPC64_CALL:
157 return RE_PPC64_CALL_PLT;
158 case R_PC:
159 return R_PLT_PC;
160 case R_ABS:
161 return R_PLT;
162 case R_GOTREL:
163 return R_PLT_GOTREL;
164 default:
165 return expr;
166 }
167}
168
169static RelExpr fromPlt(RelExpr expr) {
170 // We decided not to use a plt. Optimize a reference to the plt to a
171 // reference to the symbol itself.
172 switch (expr) {
173 case R_PLT_PC:
174 case RE_PPC32_PLTREL:
175 return R_PC;
176 case RE_LOONGARCH_PLT_PAGE_PC:
177 return RE_LOONGARCH_PAGE_PC;
178 case RE_PPC64_CALL_PLT:
179 return RE_PPC64_CALL;
180 case R_PLT:
181 return R_ABS;
182 case R_PLT_GOTPLT:
183 return R_GOTPLTREL;
184 case R_PLT_GOTREL:
185 return R_GOTREL;
186 default:
187 return expr;
188 }
189}
190
191// Returns true if a given shared symbol is in a read-only segment in a DSO.
192template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
193 using Elf_Phdr = typename ELFT::Phdr;
194
195 // Determine if the symbol is read-only by scanning the DSO's program headers.
196 const auto &file = cast<SharedFile>(Val&: *ss.file);
197 for (const Elf_Phdr &phdr :
198 check(file.template getObj<ELFT>().program_headers()))
199 if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
200 !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
201 ss.value < phdr.p_vaddr + phdr.p_memsz)
202 return true;
203 return false;
204}
205
206// Returns symbols at the same offset as a given symbol, including SS itself.
207//
208// If two or more symbols are at the same offset, and at least one of
209// them are copied by a copy relocation, all of them need to be copied.
210// Otherwise, they would refer to different places at runtime.
211template <class ELFT>
212static SmallPtrSet<SharedSymbol *, 4> getSymbolsAt(Ctx &ctx, SharedSymbol &ss) {
213 using Elf_Sym = typename ELFT::Sym;
214
215 const auto &file = cast<SharedFile>(Val&: *ss.file);
216
217 SmallPtrSet<SharedSymbol *, 4> ret;
218 for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
219 if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
220 s.getType() == STT_TLS || s.st_value != ss.value)
221 continue;
222 StringRef name = check(s.getName(file.getStringTable()));
223 Symbol *sym = ctx.symtab->find(name);
224 if (auto *alias = dyn_cast_or_null<SharedSymbol>(Val: sym))
225 ret.insert(Ptr: alias);
226 }
227
228 // The loop does not check SHT_GNU_verneed, so ret does not contain
229 // non-default version symbols. If ss has a non-default version, ret won't
230 // contain ss. Just add ss unconditionally. If a non-default version alias is
231 // separately copy relocated, it and ss will have different addresses.
232 // Fortunately this case is impractical and fails with GNU ld as well.
233 ret.insert(Ptr: &ss);
234 return ret;
235}
236
237// When a symbol is copy relocated or we create a canonical plt entry, it is
238// effectively a defined symbol. In the case of copy relocation the symbol is
239// in .bss and in the case of a canonical plt entry it is in .plt. This function
240// replaces the existing symbol with a Defined pointing to the appropriate
241// location.
242static void replaceWithDefined(Ctx &ctx, Symbol &sym, SectionBase &sec,
243 uint64_t value, uint64_t size) {
244 Symbol old = sym;
245 Defined(ctx, sym.file, StringRef(), sym.binding, sym.stOther, sym.type, value,
246 size, &sec)
247 .overwrite(sym);
248
249 sym.versionId = old.versionId;
250 sym.isUsedInRegularObj = true;
251 // A copy relocated alias may need a GOT entry.
252 sym.flags.store(i: old.flags.load(m: std::memory_order_relaxed) & NEEDS_GOT,
253 m: std::memory_order_relaxed);
254}
255
256// Reserve space in .bss or .bss.rel.ro for copy relocation.
257//
258// The copy relocation is pretty much a hack. If you use a copy relocation
259// in your program, not only the symbol name but the symbol's size, RW/RO
260// bit and alignment become part of the ABI. In addition to that, if the
261// symbol has aliases, the aliases become part of the ABI. That's subtle,
262// but if you violate that implicit ABI, that can cause very counter-
263// intuitive consequences.
264//
265// So, what is the copy relocation? It's for linking non-position
266// independent code to DSOs. In an ideal world, all references to data
267// exported by DSOs should go indirectly through GOT. But if object files
268// are compiled as non-PIC, all data references are direct. There is no
269// way for the linker to transform the code to use GOT, as machine
270// instructions are already set in stone in object files. This is where
271// the copy relocation takes a role.
272//
273// A copy relocation instructs the dynamic linker to copy data from a DSO
274// to a specified address (which is usually in .bss) at load-time. If the
275// static linker (that's us) finds a direct data reference to a DSO
276// symbol, it creates a copy relocation, so that the symbol can be
277// resolved as if it were in .bss rather than in a DSO.
278//
279// As you can see in this function, we create a copy relocation for the
280// dynamic linker, and the relocation contains not only symbol name but
281// various other information about the symbol. So, such attributes become a
282// part of the ABI.
283//
284// Note for application developers: I can give you a piece of advice if
285// you are writing a shared library. You probably should export only
286// functions from your library. You shouldn't export variables.
287//
288// As an example what can happen when you export variables without knowing
289// the semantics of copy relocations, assume that you have an exported
290// variable of type T. It is an ABI-breaking change to add new members at
291// end of T even though doing that doesn't change the layout of the
292// existing members. That's because the space for the new members are not
293// reserved in .bss unless you recompile the main program. That means they
294// are likely to overlap with other data that happens to be laid out next
295// to the variable in .bss. This kind of issue is sometimes very hard to
296// debug. What's a solution? Instead of exporting a variable V from a DSO,
297// define an accessor getV().
298template <class ELFT> static void addCopyRelSymbol(Ctx &ctx, SharedSymbol &ss) {
299 // Copy relocation against zero-sized symbol doesn't make sense.
300 uint64_t symSize = ss.getSize();
301 if (symSize == 0 || ss.alignment == 0)
302 Err(ctx) << "cannot create a copy relocation for symbol " << &ss;
303
304 // See if this symbol is in a read-only segment. If so, preserve the symbol's
305 // memory protection by reserving space in the .bss.rel.ro section.
306 bool isRO = isReadOnly<ELFT>(ss);
307 BssSection *sec = make<BssSection>(args&: ctx, args: isRO ? ".bss.rel.ro" : ".bss",
308 args&: symSize, args&: ss.alignment);
309 OutputSection *osec = (isRO ? ctx.in.bssRelRo : ctx.in.bss)->getParent();
310
311 // At this point, sectionBases has been migrated to sections. Append sec to
312 // sections.
313 if (osec->commands.empty() ||
314 !isa<InputSectionDescription>(Val: osec->commands.back()))
315 osec->commands.push_back(Elt: make<InputSectionDescription>(args: ""));
316 auto *isd = cast<InputSectionDescription>(Val: osec->commands.back());
317 isd->sections.push_back(Elt: sec);
318 osec->commitSection(isec: sec);
319
320 // Look through the DSO's dynamic symbol table for aliases and create a
321 // dynamic symbol for each one. This causes the copy relocation to correctly
322 // interpose any aliases.
323 for (SharedSymbol *sym : getSymbolsAt<ELFT>(ctx, ss))
324 replaceWithDefined(ctx, sym&: *sym, sec&: *sec, value: 0, size: sym->size);
325
326 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->copyRel, isec&: *sec, offsetInSec: 0, sym&: ss);
327}
328
329// .eh_frame sections are mergeable input sections, so their input
330// offsets are not linearly mapped to output section. For each input
331// offset, we need to find a section piece containing the offset and
332// add the piece's base address to the input offset to compute the
333// output offset. That isn't cheap.
334//
335// This class is to speed up the offset computation. When we process
336// relocations, we access offsets in the monotonically increasing
337// order. So we can optimize for that access pattern.
338//
339// For sections other than .eh_frame, this class doesn't do anything.
340namespace {
341class OffsetGetter {
342public:
343 OffsetGetter() = default;
344 explicit OffsetGetter(EhInputSection &sec) {
345 cies = sec.cies;
346 fdes = sec.fdes;
347 i = cies.begin();
348 j = fdes.begin();
349 }
350
351 // Translates offsets in input sections to offsets in output sections.
352 // Given offset must increase monotonically. We assume that Piece is
353 // sorted by inputOff.
354 uint64_t get(Ctx &ctx, uint64_t off) {
355 while (j != fdes.end() && j->inputOff <= off)
356 ++j;
357 auto it = j;
358 if (j == fdes.begin() || j[-1].inputOff + j[-1].size <= off) {
359 while (i != cies.end() && i->inputOff <= off)
360 ++i;
361 if (i == cies.begin() || i[-1].inputOff + i[-1].size <= off) {
362 Err(ctx) << ".eh_frame: relocation is not in any piece";
363 return 0;
364 }
365 it = i;
366 }
367
368 // Offset -1 means that the piece is dead (i.e. garbage collected).
369 if (it[-1].outputOff == -1)
370 return -1;
371 return it[-1].outputOff + (off - it[-1].inputOff);
372 }
373
374private:
375 ArrayRef<EhSectionPiece> cies, fdes;
376 ArrayRef<EhSectionPiece>::iterator i, j;
377};
378} // namespace
379
380// Custom error message if Sym is defined in a discarded section.
381template <class ELFT>
382static void maybeReportDiscarded(Ctx &ctx, ELFSyncStream &msg, Undefined &sym) {
383 auto *file = dyn_cast<ObjFile<ELFT>>(sym.file);
384 if (!file || !sym.discardedSecIdx)
385 return;
386 ArrayRef<typename ELFT::Shdr> objSections =
387 file->template getELFShdrs<ELFT>();
388
389 if (sym.type == ELF::STT_SECTION) {
390 msg << "relocation refers to a discarded section: ";
391 msg << CHECK2(
392 file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file);
393 } else {
394 msg << "relocation refers to a symbol in a discarded section: " << &sym;
395 }
396 msg << "\n>>> defined in " << file;
397
398 Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
399 if (elfSec.sh_type != SHT_GROUP)
400 return;
401
402 // If the discarded section is a COMDAT.
403 StringRef signature = file->getShtGroupSignature(objSections, elfSec);
404 if (const InputFile *prevailing =
405 ctx.symtab->comdatGroups.lookup(Val: CachedHashStringRef(signature))) {
406 msg << "\n>>> section group signature: " << signature
407 << "\n>>> prevailing definition is in " << prevailing;
408 if (sym.nonPrevailing) {
409 msg << "\n>>> or the symbol in the prevailing group had STB_WEAK "
410 "binding and the symbol in a non-prevailing group had STB_GLOBAL "
411 "binding. Mixing groups with STB_WEAK and STB_GLOBAL binding "
412 "signature is not supported";
413 }
414 }
415}
416
417// Check whether the definition name def is a mangled function name that matches
418// the reference name ref.
419static bool canSuggestExternCForCXX(StringRef ref, StringRef def) {
420 llvm::ItaniumPartialDemangler d;
421 std::string name = def.str();
422 if (d.partialDemangle(MangledName: name.c_str()))
423 return false;
424 char *buf = d.getFunctionName(Buf: nullptr, N: nullptr);
425 if (!buf)
426 return false;
427 bool ret = ref == buf;
428 free(ptr: buf);
429 return ret;
430}
431
432// Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns
433// the suggested symbol, which is either in the symbol table, or in the same
434// file of sym.
435static const Symbol *getAlternativeSpelling(Ctx &ctx, const Undefined &sym,
436 std::string &pre_hint,
437 std::string &post_hint) {
438 DenseMap<StringRef, const Symbol *> map;
439 if (sym.file->kind() == InputFile::ObjKind) {
440 auto *file = cast<ELFFileBase>(Val: sym.file);
441 // If sym is a symbol defined in a discarded section, maybeReportDiscarded()
442 // will give an error. Don't suggest an alternative spelling.
443 if (sym.discardedSecIdx != 0 &&
444 file->getSections()[sym.discardedSecIdx] == &InputSection::discarded)
445 return nullptr;
446
447 // Build a map of local defined symbols.
448 for (const Symbol *s : sym.file->getSymbols())
449 if (s->isLocal() && s->isDefined() && !s->getName().empty())
450 map.try_emplace(Key: s->getName(), Args&: s);
451 }
452
453 auto suggest = [&](StringRef newName) -> const Symbol * {
454 // If defined locally.
455 if (const Symbol *s = map.lookup(Val: newName))
456 return s;
457
458 // If in the symbol table and not undefined.
459 if (const Symbol *s = ctx.symtab->find(name: newName))
460 if (!s->isUndefined())
461 return s;
462
463 return nullptr;
464 };
465
466 // This loop enumerates all strings of Levenshtein distance 1 as typo
467 // correction candidates and suggests the one that exists as a non-undefined
468 // symbol.
469 StringRef name = sym.getName();
470 for (size_t i = 0, e = name.size(); i != e + 1; ++i) {
471 // Insert a character before name[i].
472 std::string newName = (name.substr(Start: 0, N: i) + "0" + name.substr(Start: i)).str();
473 for (char c = '0'; c <= 'z'; ++c) {
474 newName[i] = c;
475 if (const Symbol *s = suggest(newName))
476 return s;
477 }
478 if (i == e)
479 break;
480
481 // Substitute name[i].
482 newName = std::string(name);
483 for (char c = '0'; c <= 'z'; ++c) {
484 newName[i] = c;
485 if (const Symbol *s = suggest(newName))
486 return s;
487 }
488
489 // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is
490 // common.
491 if (i + 1 < e) {
492 newName[i] = name[i + 1];
493 newName[i + 1] = name[i];
494 if (const Symbol *s = suggest(newName))
495 return s;
496 }
497
498 // Delete name[i].
499 newName = (name.substr(Start: 0, N: i) + name.substr(Start: i + 1)).str();
500 if (const Symbol *s = suggest(newName))
501 return s;
502 }
503
504 // Case mismatch, e.g. Foo vs FOO.
505 for (auto &it : map)
506 if (name.equals_insensitive(RHS: it.first))
507 return it.second;
508 for (Symbol *sym : ctx.symtab->getSymbols())
509 if (!sym->isUndefined() && name.equals_insensitive(RHS: sym->getName()))
510 return sym;
511
512 // The reference may be a mangled name while the definition is not. Suggest a
513 // missing extern "C".
514 if (name.starts_with(Prefix: "_Z")) {
515 std::string buf = name.str();
516 llvm::ItaniumPartialDemangler d;
517 if (!d.partialDemangle(MangledName: buf.c_str()))
518 if (char *buf = d.getFunctionName(Buf: nullptr, N: nullptr)) {
519 const Symbol *s = suggest(buf);
520 free(ptr: buf);
521 if (s) {
522 pre_hint = ": extern \"C\" ";
523 return s;
524 }
525 }
526 } else {
527 const Symbol *s = nullptr;
528 for (auto &it : map)
529 if (canSuggestExternCForCXX(ref: name, def: it.first)) {
530 s = it.second;
531 break;
532 }
533 if (!s)
534 for (Symbol *sym : ctx.symtab->getSymbols())
535 if (canSuggestExternCForCXX(ref: name, def: sym->getName())) {
536 s = sym;
537 break;
538 }
539 if (s) {
540 pre_hint = " to declare ";
541 post_hint = " as extern \"C\"?";
542 return s;
543 }
544 }
545
546 return nullptr;
547}
548
549static void reportUndefinedSymbol(Ctx &ctx, const UndefinedDiag &undef,
550 bool correctSpelling) {
551 Undefined &sym = *undef.sym;
552 ELFSyncStream msg(ctx, DiagLevel::None);
553
554 auto visibility = [&]() {
555 switch (sym.visibility()) {
556 case STV_INTERNAL:
557 return "internal ";
558 case STV_HIDDEN:
559 return "hidden ";
560 case STV_PROTECTED:
561 return "protected ";
562 default:
563 return "";
564 }
565 };
566
567 switch (ctx.arg.ekind) {
568 case ELF32LEKind:
569 maybeReportDiscarded<ELF32LE>(ctx, msg, sym);
570 break;
571 case ELF32BEKind:
572 maybeReportDiscarded<ELF32BE>(ctx, msg, sym);
573 break;
574 case ELF64LEKind:
575 maybeReportDiscarded<ELF64LE>(ctx, msg, sym);
576 break;
577 case ELF64BEKind:
578 maybeReportDiscarded<ELF64BE>(ctx, msg, sym);
579 break;
580 default:
581 llvm_unreachable("");
582 }
583 if (msg.str().empty())
584 msg << "undefined " << visibility() << "symbol: " << &sym;
585
586 const size_t maxUndefReferences = 3;
587 for (UndefinedDiag::Loc l :
588 ArrayRef(undef.locs).take_front(N: maxUndefReferences)) {
589 InputSectionBase &sec = *l.sec;
590 uint64_t offset = l.offset;
591
592 msg << "\n>>> referenced by ";
593 // In the absence of line number information, utilize DW_TAG_variable (if
594 // present) for the enclosing symbol (e.g. var in `int *a[] = {&undef};`).
595 Symbol *enclosing = sec.getEnclosingSymbol(offset);
596
597 ELFSyncStream msg1(ctx, DiagLevel::None);
598 auto tell = msg.tell();
599 msg << sec.getSrcMsg(sym: enclosing ? *enclosing : sym, offset);
600 if (tell != msg.tell())
601 msg << "\n>>> ";
602 msg << sec.getObjMsg(offset);
603 }
604
605 if (maxUndefReferences < undef.locs.size())
606 msg << "\n>>> referenced " << (undef.locs.size() - maxUndefReferences)
607 << " more times";
608
609 if (correctSpelling) {
610 std::string pre_hint = ": ", post_hint;
611 if (const Symbol *corrected =
612 getAlternativeSpelling(ctx, sym, pre_hint, post_hint)) {
613 msg << "\n>>> did you mean" << pre_hint << corrected << post_hint
614 << "\n>>> defined in: " << corrected->file;
615 }
616 }
617
618 if (sym.getName().starts_with(Prefix: "_ZTV"))
619 msg << "\n>>> the vtable symbol may be undefined because the class is "
620 "missing its key function "
621 "(see https://lld.llvm.org/missingkeyfunction)";
622 if (ctx.arg.gcSections && ctx.arg.zStartStopGC &&
623 sym.getName().starts_with(Prefix: "__start_")) {
624 msg << "\n>>> the encapsulation symbol needs to be retained under "
625 "--gc-sections properly; consider -z nostart-stop-gc "
626 "(see https://lld.llvm.org/ELF/start-stop-gc)";
627 }
628
629 if (undef.isWarning)
630 Warn(ctx) << msg.str();
631 else
632 ctx.e.error(msg: msg.str(), tag: ErrorTag::SymbolNotFound, args: {sym.getName()});
633}
634
635void elf::reportUndefinedSymbols(Ctx &ctx) {
636 // Find the first "undefined symbol" diagnostic for each diagnostic, and
637 // collect all "referenced from" lines at the first diagnostic.
638 DenseMap<Symbol *, UndefinedDiag *> firstRef;
639 for (UndefinedDiag &undef : ctx.undefErrs) {
640 assert(undef.locs.size() == 1);
641 if (UndefinedDiag *canon = firstRef.lookup(Val: undef.sym)) {
642 canon->locs.push_back(Elt: undef.locs[0]);
643 undef.locs.clear();
644 } else
645 firstRef[undef.sym] = &undef;
646 }
647
648 // Enable spell corrector for the first 2 diagnostics.
649 for (auto [i, undef] : llvm::enumerate(First&: ctx.undefErrs))
650 if (!undef.locs.empty())
651 reportUndefinedSymbol(ctx, undef, correctSpelling: i < 2);
652}
653
654// Report an undefined symbol if necessary.
655// Returns true if the undefined symbol will produce an error message.
656bool RelocScan::maybeReportUndefined(Undefined &sym, uint64_t offset) {
657 std::lock_guard<std::mutex> lock(ctx.relocMutex);
658 // If versioned, issue an error (even if the symbol is weak) because we don't
659 // know the defining filename which is required to construct a Verneed entry.
660 if (sym.hasVersionSuffix) {
661 ctx.undefErrs.push_back(Elt: {.sym: &sym, .locs: {{.sec: sec, .offset: offset}}, .isWarning: false});
662 return true;
663 }
664 if (sym.isWeak())
665 return false;
666
667 bool canBeExternal = !sym.isLocal() && sym.visibility() == STV_DEFAULT;
668 if (ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
669 return false;
670
671 // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
672 // which references a switch table in a discarded .rodata/.text section. The
673 // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
674 // spec says references from outside the group to a STB_LOCAL symbol are not
675 // allowed. Work around the bug.
676 //
677 // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible
678 // because .LC0-.LTOC is not representable if the two labels are in different
679 // .got2
680 if (sym.discardedSecIdx != 0 && (sec->name == ".got2" || sec->name == ".toc"))
681 return false;
682
683 bool isWarning =
684 (ctx.arg.unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
685 ctx.arg.noinhibitExec;
686 ctx.undefErrs.push_back(Elt: {.sym: &sym, .locs: {{.sec: sec, .offset: offset}}, .isWarning: isWarning});
687 return !isWarning;
688}
689
690bool RelocScan::checkTlsLe(uint64_t offset, Symbol &sym, RelType type) {
691 if (!ctx.arg.shared)
692 return false;
693 auto diag = Err(ctx);
694 diag << "relocation " << type << " against " << &sym
695 << " cannot be used with -shared";
696 printLocation(s&: diag, sec&: *sec, sym, off: offset);
697 return true;
698}
699
700template <bool shard = false>
701static void addRelativeReloc(Ctx &ctx, InputSectionBase &isec,
702 uint64_t offsetInSec, Symbol &sym, int64_t addend,
703 RelExpr expr, RelType type) {
704 Partition &part = isec.getPartition(ctx);
705 bool isAArch64Auth =
706 ctx.arg.emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64;
707
708 // Add a relative relocation. If relrDyn section is enabled, and the
709 // relocation offset is guaranteed to be even, add the relocation to
710 // the relrDyn section, otherwise add it to the relaDyn section.
711 // relrDyn sections don't support odd offsets. Also, relrDyn sections
712 // don't store the addend values, so we must write it to the relocated
713 // address.
714 //
715 // When symbol values are determined in finalizeAddressDependentContent,
716 // some .relr.auth.dyn relocations may be moved to .rela.dyn.
717 //
718 // MTE globals may need to store the original addend as well so cannot use
719 // relrDyn. TODO: It should be unambiguous when not using R_ADDEND_NEG below?
720 RelrBaseSection *relrDyn = part.relrDyn.get();
721 if (isAArch64Auth)
722 relrDyn = part.relrAuthDyn.get();
723 if (sym.isTagged())
724 relrDyn = nullptr;
725 if (relrDyn && isec.addralign >= 2 && offsetInSec % 2 == 0) {
726 relrDyn->addRelativeReloc<shard>(isec, offsetInSec, sym, addend, type,
727 expr);
728 return;
729 }
730 RelType relativeType = ctx.target->relativeRel;
731 if (isAArch64Auth)
732 relativeType = R_AARCH64_AUTH_RELATIVE;
733 part.relaDyn->addRelativeReloc<shard>(relativeType, isec, offsetInSec, sym,
734 addend, type, expr);
735 // With MTE globals, we always want to derive the address tag by `ldg`-ing
736 // the symbol. When we have a RELATIVE relocation though, we no longer have
737 // a reference to the symbol. Because of this, when we have an addend that
738 // puts the result of the RELATIVE relocation out-of-bounds of the symbol
739 // (e.g. the addend is outside of [0, sym.getSize()]), the AArch64 MemtagABI
740 // says we should store the offset to the start of the symbol in the target
741 // field. This is described in further detail in:
742 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#841extended-semantics-of-r_aarch64_relative
743 if (sym.isTagged() &&
744 (addend < 0 || static_cast<uint64_t>(addend) >= sym.getSize()))
745 isec.addReloc(r: {.expr: R_ADDEND_NEG, .type: type, .offset: offsetInSec, .addend: addend, .sym: &sym});
746}
747
748template <class PltSection, class GotPltSection>
749static void addPltEntry(Ctx &ctx, PltSection &plt, GotPltSection &gotPlt,
750 RelocationBaseSection &rel, RelType type, Symbol &sym) {
751 plt.addEntry(sym);
752 gotPlt.addEntry(sym);
753 if (sym.isPreemptible)
754 rel.addReloc(
755 {type, &gotPlt, sym.getGotPltOffset(ctx), true, sym, 0, R_ADDEND});
756 else
757 rel.addReloc(
758 {type, &gotPlt, sym.getGotPltOffset(ctx), false, sym, 0, R_ABS});
759}
760
761void elf::addGotEntry(Ctx &ctx, Symbol &sym) {
762 ctx.in.got->addEntry(sym);
763 uint64_t off = sym.getGotOffset(ctx);
764
765 // If preemptible, emit a GLOB_DAT relocation.
766 if (sym.isPreemptible) {
767 ctx.mainPart->relaDyn->addReloc(
768 reloc: {ctx.target->gotRel, ctx.in.got.get(), off, true, sym, 0, R_ADDEND});
769 return;
770 }
771
772 // Otherwise, the value is either a link-time constant or the load base
773 // plus a constant.
774 if (!ctx.arg.isPic || isAbsolute(sym))
775 ctx.in.got->addConstant(r: {.expr: R_ABS, .type: ctx.target->symbolicRel, .offset: off, .addend: 0, .sym: &sym});
776 else
777 addRelativeReloc(ctx, isec&: *ctx.in.got, offsetInSec: off, sym, addend: 0, expr: R_ABS,
778 type: ctx.target->symbolicRel);
779}
780
781static void addGotAuthEntry(Ctx &ctx, Symbol &sym) {
782 ctx.in.got->addEntry(sym);
783 ctx.in.got->addAuthEntry(sym);
784 uint64_t off = sym.getGotOffset(ctx);
785
786 // If preemptible, emit a GLOB_DAT relocation.
787 if (sym.isPreemptible) {
788 ctx.mainPart->relaDyn->addReloc(reloc: {R_AARCH64_AUTH_GLOB_DAT, ctx.in.got.get(),
789 off, true, sym, 0, R_ADDEND});
790 return;
791 }
792
793 // Signed GOT requires dynamic relocation.
794 ctx.in.got->getPartition(ctx).relaDyn->addReloc(
795 reloc: {R_AARCH64_AUTH_RELATIVE, ctx.in.got.get(), off, false, sym, 0, R_ABS});
796}
797
798static void addTpOffsetGotEntry(Ctx &ctx, Symbol &sym) {
799 ctx.in.got->addEntry(sym);
800 uint64_t off = sym.getGotOffset(ctx);
801 if (!sym.isPreemptible && !ctx.arg.shared) {
802 ctx.in.got->addConstant(r: {.expr: R_TPREL, .type: ctx.target->symbolicRel, .offset: off, .addend: 0, .sym: &sym});
803 return;
804 }
805 ctx.mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
806 dynType: ctx.target->tlsGotRel, isec&: *ctx.in.got, offsetInSec: off, sym, addendRelType: ctx.target->symbolicRel);
807}
808
809// Return true if we can define a symbol in the executable that
810// contains the value/function of a symbol defined in a shared
811// library.
812static bool canDefineSymbolInExecutable(Ctx &ctx, Symbol &sym) {
813 // If the symbol has default visibility the symbol defined in the
814 // executable will preempt it.
815 // Note that we want the visibility of the shared symbol itself, not
816 // the visibility of the symbol in the output file we are producing.
817 if (!sym.dsoProtected)
818 return true;
819
820 // If we are allowed to break address equality of functions, defining
821 // a plt entry will allow the program to call the function in the
822 // .so, but the .so and the executable will no agree on the address
823 // of the function. Similar logic for objects.
824 return ((sym.isFunc() && ctx.arg.ignoreFunctionAddressEquality) ||
825 (sym.isObject() && ctx.arg.ignoreDataAddressEquality));
826}
827
828// Returns true if a given relocation can be computed at link-time.
829// This only handles relocation types expected in process().
830//
831// For instance, we know the offset from a relocation to its target at
832// link-time if the relocation is PC-relative and refers a
833// non-interposable function in the same executable. This function
834// will return true for such relocation.
835//
836// If this function returns false, that means we need to emit a
837// dynamic relocation so that the relocation will be fixed at load-time.
838bool RelocScan::isStaticLinkTimeConstant(RelExpr e, RelType type,
839 const Symbol &sym,
840 uint64_t relOff) const {
841 // These expressions always compute a constant
842 if (oneof<R_GOTPLT, R_GOT_OFF, R_RELAX_HINT, RE_MIPS_GOT_LOCAL_PAGE,
843 RE_MIPS_GOTREL, RE_MIPS_GOT_OFF, RE_MIPS_GOT_OFF32,
844 RE_MIPS_GOT_GP_PC, RE_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC,
845 R_GOTPLTONLY_PC, R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT,
846 R_GOTPLT_GOTREL, R_GOTPLT_PC, RE_PPC32_PLTREL, RE_PPC64_CALL_PLT,
847 RE_RISCV_ADD, RE_AARCH64_GOT_PAGE, RE_LOONGARCH_PLT_PAGE_PC,
848 RE_LOONGARCH_GOT, RE_LOONGARCH_GOT_PAGE_PC>(expr: e))
849 return true;
850
851 // These never do, except if the entire file is position dependent or if
852 // only the low bits are used.
853 if (e == R_GOT || e == R_PLT)
854 return ctx.target->usesOnlyLowPageBits(type) || !ctx.arg.isPic;
855 // R_AARCH64_AUTH_ABS64 and iRelSymbolicRel require a dynamic relocation.
856 if (e == RE_AARCH64_AUTH || type == ctx.target->iRelSymbolicRel)
857 return false;
858
859 // The behavior of an undefined weak reference is implementation defined.
860 // (We treat undefined non-weak the same as undefined weak.) For static
861 // -no-pie linking, dynamic relocations are generally avoided (except
862 // IRELATIVE). Emitting dynamic relocations for -shared aligns with its -z
863 // undefs default. Dynamic -no-pie linking and -pie allow flexibility.
864 if (sym.isPreemptible)
865 return sym.isUndefined() && !ctx.arg.isPic;
866 if (!ctx.arg.isPic)
867 return true;
868
869 // Constant when referencing a non-preemptible symbol.
870 if (e == R_SIZE || e == RE_RISCV_LEB128)
871 return true;
872
873 // For the target and the relocation, we want to know if they are
874 // absolute or relative.
875 bool absVal = isAbsoluteOrTls(sym) && e != RE_PPC64_TOCBASE;
876 bool relE = isRelExpr(expr: e);
877 if (absVal && !relE)
878 return true;
879 if (!absVal && relE)
880 return true;
881 if (!absVal && !relE)
882 return ctx.target->usesOnlyLowPageBits(type);
883
884 assert(absVal && relE);
885
886 // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol
887 // in PIC mode. This is a little strange, but it allows us to link function
888 // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers).
889 // Normally such a call will be guarded with a comparison, which will load a
890 // zero from the GOT.
891 if (sym.isUndefined())
892 return true;
893
894 // We set the final symbols values for linker script defined symbols later.
895 // They always can be computed as a link time constant.
896 if (sym.scriptDefined)
897 return true;
898
899 auto diag = Err(ctx);
900 diag << "relocation " << type << " cannot refer to absolute symbol: " << &sym;
901 printLocation(s&: diag, sec&: *sec, sym, off: relOff);
902 return true;
903}
904
905// The reason we have to do this early scan is as follows
906// * To mmap the output file, we need to know the size
907// * For that, we need to know how many dynamic relocs we will have.
908// It might be possible to avoid this by outputting the file with write:
909// * Write the allocated output sections, computing addresses.
910// * Apply relocations, recording which ones require a dynamic reloc.
911// * Write the dynamic relocations.
912// * Write the rest of the file.
913// This would have some drawbacks. For example, we would only know if .rela.dyn
914// is needed after applying relocations. If it is, it will go after rw and rx
915// sections. Given that it is ro, we will need an extra PT_LOAD. This
916// complicates things for the dynamic linker and means we would have to reserve
917// space for the extra PT_LOAD even if we end up not using it.
918void RelocScan::process(RelExpr expr, RelType type, uint64_t offset,
919 Symbol &sym, int64_t addend) const {
920 // If non-ifunc non-preemptible, change PLT to direct call and optimize GOT
921 // indirection.
922 const bool isIfunc = sym.isGnuIFunc();
923 if (!sym.isPreemptible && !isIfunc) {
924 if (expr != R_GOT_PC) {
925 expr = fromPlt(expr);
926 } else if (!isAbsoluteOrTls(sym)) {
927 expr = ctx.target->adjustGotPcExpr(type, addend,
928 loc: sec->content().data() + offset);
929 // If the target adjusted the expression to R_RELAX_GOT_PC, we may end up
930 // needing the GOT if we can't relax everything.
931 if (expr == R_RELAX_GOT_PC)
932 ctx.in.got->hasGotOffRel.store(i: true, m: std::memory_order_relaxed);
933 }
934 }
935
936 // We were asked not to generate PLT entries for ifuncs. Instead, pass the
937 // direct relocation on through.
938 if (LLVM_UNLIKELY(isIfunc) && ctx.arg.zIfuncNoplt) {
939 std::lock_guard<std::mutex> lock(ctx.relocMutex);
940 sym.isExported = true;
941 ctx.mainPart->relaDyn->addSymbolReloc(dynType: type, isec&: *sec, offsetInSec: offset, sym, addend,
942 addendRelType: type);
943 return;
944 }
945
946 if (needsGot(expr)) {
947 if (ctx.arg.emachine == EM_MIPS) {
948 // MIPS ABI has special rules to process GOT entries and doesn't
949 // require relocation entries for them. A special case is TLS
950 // relocations. In that case dynamic loader applies dynamic
951 // relocations to initialize TLS GOT entries.
952 // See "Global Offset Table" in Chapter 5 in the following document
953 // for detailed description:
954 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
955 ctx.in.mipsGot->addEntry(file&: *sec->file, sym, addend, expr);
956 } else if (!sym.isTls() || ctx.arg.emachine != EM_LOONGARCH) {
957 // Many LoongArch TLS relocs reuse the RE_LOONGARCH_GOT type, in which
958 // case the NEEDS_GOT flag shouldn't get set.
959 sym.setFlags(NEEDS_GOT | NEEDS_GOT_NONAUTH);
960 }
961 } else if (needsPlt(expr)) {
962 sym.setFlags(NEEDS_PLT);
963 } else if (LLVM_UNLIKELY(isIfunc)) {
964 sym.setFlags(HAS_DIRECT_RELOC);
965 }
966
967 processAux(expr, type, offset, sym, addend);
968}
969
970// Process relocation after needsGot/needsPlt flags are already handled.
971// This is the bottom half of process(), handling isStaticLinkTimeConstant
972// check, dynamic relocations, copy relocations, and error reporting.
973void RelocScan::processAux(RelExpr expr, RelType type, uint64_t offset,
974 Symbol &sym, int64_t addend) const {
975 const bool isIfunc = sym.isGnuIFunc();
976
977 // If the relocation is known to be a link-time constant, we know no dynamic
978 // relocation will be created, pass the control to relocateAlloc() or
979 // relocateNonAlloc() to resolve it.
980 if (isStaticLinkTimeConstant(e: expr, type, sym, relOff: offset)) {
981 sec->addReloc(r: {.expr: expr, .type: type, .offset: offset, .addend: addend, .sym: &sym});
982 return;
983 }
984
985 // Use a simple -z notext rule that treats all sections except .eh_frame as
986 // writable. GNU ld does not produce dynamic relocations in .eh_frame (and our
987 // SectionBase::getOffset would incorrectly adjust the offset).
988 //
989 // For MIPS, we don't implement GNU ld's DW_EH_PE_absptr to DW_EH_PE_pcrel
990 // conversion. We still emit a dynamic relocation.
991 bool canWrite = (sec->flags & SHF_WRITE) ||
992 !(ctx.arg.zText ||
993 (isa<EhInputSection>(Val: sec) && ctx.arg.emachine != EM_MIPS));
994 if (canWrite) {
995 RelType rel = ctx.target->getDynRel(type);
996 if (oneof<R_GOT, RE_LOONGARCH_GOT>(expr) ||
997 ((rel == ctx.target->symbolicRel ||
998 (ctx.arg.emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64)) &&
999 !sym.isPreemptible)) {
1000 addRelativeReloc<true>(ctx, isec&: *sec, offsetInSec: offset, sym, addend, expr, type);
1001 return;
1002 }
1003 if (rel != 0) {
1004 if (ctx.arg.emachine == EM_MIPS && rel == ctx.target->symbolicRel)
1005 rel = ctx.target->relativeRel;
1006 std::lock_guard<std::mutex> lock(ctx.relocMutex);
1007 Partition &part = sec->getPartition(ctx);
1008 if (LLVM_UNLIKELY(type == ctx.target->iRelSymbolicRel)) {
1009 if (sym.isPreemptible) {
1010 auto diag = Err(ctx);
1011 diag << "relocation " << type
1012 << " cannot be used against preemptible symbol '" << &sym << "'";
1013 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1014 } else if (isIfunc) {
1015 auto diag = Err(ctx);
1016 diag << "relocation " << type
1017 << " cannot be used against ifunc symbol '" << &sym << "'";
1018 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1019 } else {
1020 part.relaDyn->addReloc(reloc: {ctx.target->iRelativeRel, sec, offset, false,
1021 sym, addend, R_ABS});
1022 return;
1023 }
1024 }
1025 part.relaDyn->addSymbolReloc(dynType: rel, isec&: *sec, offsetInSec: offset, sym, addend, addendRelType: type);
1026
1027 // MIPS ABI turns using of GOT and dynamic relocations inside out.
1028 // While regular ABI uses dynamic relocations to fill up GOT entries
1029 // MIPS ABI requires dynamic linker to fills up GOT entries using
1030 // specially sorted dynamic symbol table. This affects even dynamic
1031 // relocations against symbols which do not require GOT entries
1032 // creation explicitly, i.e. do not have any GOT-relocations. So if
1033 // a preemptible symbol has a dynamic relocation we anyway have
1034 // to create a GOT entry for it.
1035 // If a non-preemptible symbol has a dynamic relocation against it,
1036 // dynamic linker takes it st_value, adds offset and writes down
1037 // result of the dynamic relocation. In case of preemptible symbol
1038 // dynamic linker performs symbol resolution, writes the symbol value
1039 // to the GOT entry and reads the GOT entry when it needs to perform
1040 // a dynamic relocation.
1041 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
1042 if (ctx.arg.emachine == EM_MIPS)
1043 ctx.in.mipsGot->addEntry(file&: *sec->file, sym, addend, expr);
1044 return;
1045 }
1046 }
1047
1048 // When producing an executable, we can perform copy relocations (for
1049 // STT_OBJECT) and canonical PLT (for STT_FUNC) if sym is defined by a DSO.
1050 // Copy relocations/canonical PLT entries are unsupported for
1051 // R_AARCH64_AUTH_ABS64.
1052 if (!ctx.arg.shared && sym.isShared() &&
1053 !(ctx.arg.emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64)) {
1054 if (!canDefineSymbolInExecutable(ctx, sym)) {
1055 auto diag = Err(ctx);
1056 diag << "cannot preempt symbol: " << &sym;
1057 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1058 return;
1059 }
1060
1061 if (sym.isObject()) {
1062 // Produce a copy relocation.
1063 if (auto *ss = dyn_cast<SharedSymbol>(Val: &sym)) {
1064 if (!ctx.arg.zCopyreloc) {
1065 auto diag = Err(ctx);
1066 diag << "unresolvable relocation " << type << " against symbol '"
1067 << ss << "'; recompile with -fPIC or remove '-z nocopyreloc'";
1068 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1069 }
1070 sym.setFlags(NEEDS_COPY);
1071 }
1072 sec->addReloc(r: {.expr: expr, .type: type, .offset: offset, .addend: addend, .sym: &sym});
1073 return;
1074 }
1075
1076 // This handles a non PIC program call to function in a shared library. In
1077 // an ideal world, we could just report an error saying the relocation can
1078 // overflow at runtime. In the real world with glibc, crt1.o has a
1079 // R_X86_64_PC32 pointing to libc.so.
1080 //
1081 // The general idea on how to handle such cases is to create a PLT entry and
1082 // use that as the function value.
1083 //
1084 // For the static linking part, we just return a plt expr and everything
1085 // else will use the PLT entry as the address.
1086 //
1087 // The remaining problem is making sure pointer equality still works. We
1088 // need the help of the dynamic linker for that. We let it know that we have
1089 // a direct reference to a so symbol by creating an undefined symbol with a
1090 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
1091 // the value of the symbol we created. This is true even for got entries, so
1092 // pointer equality is maintained. To avoid an infinite loop, the only entry
1093 // that points to the real function is a dedicated got entry used by the
1094 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
1095 // R_386_JMP_SLOT, etc).
1096
1097 // For position independent executable on i386, the plt entry requires ebx
1098 // to be set. This causes two problems:
1099 // * If some code has a direct reference to a function, it was probably
1100 // compiled without -fPIE/-fPIC and doesn't maintain ebx.
1101 // * If a library definition gets preempted to the executable, it will have
1102 // the wrong ebx value.
1103 if (sym.isFunc()) {
1104 if (ctx.arg.pie && ctx.arg.emachine == EM_386) {
1105 auto diag = Err(ctx);
1106 diag << "symbol '" << &sym
1107 << "' cannot be preempted; recompile with -fPIE";
1108 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1109 }
1110 sym.setFlags(NEEDS_COPY | NEEDS_PLT);
1111 sec->addReloc(r: {.expr: expr, .type: type, .offset: offset, .addend: addend, .sym: &sym});
1112 return;
1113 }
1114 }
1115
1116 auto diag = Err(ctx);
1117 diag << "relocation " << type << " cannot be used against ";
1118 if (sym.getName().empty())
1119 diag << "local symbol";
1120 else
1121 diag << "symbol '" << &sym << "'";
1122 diag << "; recompile with -fPIC";
1123 printLocation(s&: diag, sec&: *sec, sym, off: offset);
1124}
1125
1126template <class ELFT, class RelTy>
1127void TargetInfo::scanSectionImpl(InputSectionBase &sec, Relocs<RelTy> rels) {
1128 RelocScan rs(ctx, &sec);
1129 // Many relocations end up in sec.relocations.
1130 sec.relocations.reserve(N: rels.size());
1131
1132 for (auto it = rels.begin(); it != rels.end(); ++it) {
1133 auto type = it->getType(false);
1134 rs.scan<ELFT, RelTy>(it, type, rs.getAddend<ELFT>(*it, type));
1135 }
1136
1137 // Sort relocations by offset for more efficient searching for
1138 // R_RISCV_PCREL_HI20 and the branch-to-branch optimization.
1139 if (ctx.arg.emachine == EM_RISCV || ctx.arg.branchToBranch)
1140 llvm::stable_sort(sec.relocs(),
1141 [](const Relocation &lhs, const Relocation &rhs) {
1142 return lhs.offset < rhs.offset;
1143 });
1144}
1145
1146template <class ELFT> void TargetInfo::scanSection1(InputSectionBase &sec) {
1147 const RelsOrRelas<ELFT> rels = sec.template relsOrRelas<ELFT>();
1148 if (rels.areRelocsCrel())
1149 scanSectionImpl<ELFT>(sec, rels.crels);
1150 else if (rels.areRelocsRel())
1151 scanSectionImpl<ELFT>(sec, rels.rels);
1152 else
1153 scanSectionImpl<ELFT>(sec, rels.relas);
1154}
1155
1156void TargetInfo::scanSection(InputSectionBase &sec) {
1157 invokeELFT(scanSection1, sec);
1158}
1159
1160void RelocScan::scanEhSection(EhInputSection &s) {
1161 sec = &s;
1162 OffsetGetter getter(s);
1163 auto rels = s.rels;
1164 s.relocations.reserve(N: rels.size());
1165 for (auto &r : rels) {
1166 // Ignore R_*_NONE and other marker relocations.
1167 if (r.expr == R_NONE)
1168 continue;
1169 uint64_t offset = getter.get(ctx, off: r.offset);
1170 // Skip if the relocation offset is within a dead piece.
1171 if (offset == uint64_t(-1))
1172 continue;
1173 Symbol *sym = r.sym;
1174 if (sym->isUndefined() &&
1175 maybeReportUndefined(sym&: cast<Undefined>(Val&: *sym), offset))
1176 continue;
1177 process(expr: r.expr, type: r.type, offset, sym&: *sym, addend: r.addend);
1178 }
1179}
1180
1181template <class ELFT> void elf::scanRelocations(Ctx &ctx) {
1182 // Scan all relocations. Each relocation goes through a series of tests to
1183 // determine if it needs special treatment, such as creating GOT, PLT,
1184 // copy relocations, etc. Note that relocations for non-alloc sections are
1185 // directly processed by InputSection::relocateNonAlloc.
1186
1187 // Deterministic parallellism needs sorting relocations which is unsuitable
1188 // for -z nocombreloc. MIPS and PPC64 use global states which are not suitable
1189 // for parallelism.
1190 bool serial = !ctx.arg.zCombreloc || ctx.arg.emachine == EM_MIPS ||
1191 ctx.arg.emachine == EM_PPC64;
1192 parallel::TaskGroup tg;
1193 auto outerFn = [&]() {
1194 for (ELFFileBase *f : ctx.objectFiles) {
1195 auto fn = [f, &ctx]() {
1196 for (InputSectionBase *s : f->getSections()) {
1197 if (s && s->kind() == SectionBase::Regular && s->isLive() &&
1198 (s->flags & SHF_ALLOC) &&
1199 !(s->type == SHT_ARM_EXIDX && ctx.arg.emachine == EM_ARM))
1200 ctx.target->scanSection(sec&: *s);
1201 }
1202 };
1203 if (serial)
1204 fn();
1205 else
1206 tg.spawn(f: fn);
1207 }
1208 auto scanEH = [&] {
1209 RelocScan scanner(ctx);
1210 for (Partition &part : ctx.partitions) {
1211 for (EhInputSection *sec : part.ehFrame->sections)
1212 scanner.scanEhSection(s&: *sec);
1213 if (part.armExidx && part.armExidx->isLive())
1214 for (InputSection *sec : part.armExidx->exidxSections)
1215 if (sec->isLive())
1216 ctx.target->scanSection(sec&: *sec);
1217 }
1218 };
1219 if (serial)
1220 scanEH();
1221 else
1222 tg.spawn(f: scanEH);
1223 };
1224 // If `serial` is true, call `spawn` to ensure that `scanner` runs in a thread
1225 // with valid getThreadIndex().
1226 if (serial)
1227 tg.spawn(f: outerFn);
1228 else
1229 outerFn();
1230}
1231
1232RelocationBaseSection &elf::getIRelativeSection(Ctx &ctx) {
1233 // Prior to Android V, there was a bug that caused RELR relocations to be
1234 // applied after packed relocations. This meant that resolvers referenced by
1235 // IRELATIVE relocations in the packed relocation section would read
1236 // unrelocated globals with RELR relocations when
1237 // --pack-relative-relocs=android+relr is enabled. Work around this by placing
1238 // IRELATIVE in .rela.plt.
1239 return ctx.arg.androidPackDynRelocs ? *ctx.in.relaPlt
1240 : *ctx.mainPart->relaDyn;
1241}
1242
1243static bool handleNonPreemptibleIfunc(Ctx &ctx, Symbol &sym, uint16_t flags) {
1244 // Non-preemptible ifuncs are called via a PLT entry that resolves the actual
1245 // address at runtime. We create an IPLT entry and an IGOTPLT slot. The
1246 // IGOTPLT slot is relocated by an IRELATIVE relocation, whose addend encodes
1247 // the resolver address. At startup, the runtime calls the resolver and
1248 // fills the IGOTPLT slot.
1249 //
1250 // For direct (non-GOT/PLT) relocations, the symbol must have a constant
1251 // address. We achieve this by redirecting the symbol to its IPLT entry
1252 // ("canonicalizing" it), so all references see the same address, and the
1253 // resolver is called exactly once. This may result in two GOT entries: one
1254 // in .got.plt for the IRELATIVE, and one in .got pointing to the canonical
1255 // IPLT entry (for GOT-generating relocations).
1256 //
1257 // We clone the symbol to preserve the original resolver address for the
1258 // IRELATIVE addend. The clone is tracked in ctx.irelativeSyms so that linker
1259 // relaxation can adjust its value when the resolver address changes.
1260 //
1261 // Note: IRELATIVE relocations are needed even in static executables; see
1262 // `addRelIpltSymbols`.
1263 if (!sym.isGnuIFunc() || sym.isPreemptible || ctx.arg.zIfuncNoplt)
1264 return false;
1265 // Skip unreferenced non-preemptible ifunc.
1266 if (!(flags & (NEEDS_GOT | NEEDS_PLT | HAS_DIRECT_RELOC)))
1267 return true;
1268
1269 sym.isInIplt = true;
1270
1271 auto *irelativeSym = makeDefined(args&: cast<Defined>(Val&: sym));
1272 irelativeSym->allocateAux(ctx);
1273 ctx.irelativeSyms.push_back(Elt: irelativeSym);
1274 auto &dyn = getIRelativeSection(ctx);
1275 addPltEntry(ctx, plt&: *ctx.in.iplt, gotPlt&: *ctx.in.igotPlt, rel&: dyn, type: ctx.target->iRelativeRel,
1276 sym&: *irelativeSym);
1277 sym.allocateAux(ctx);
1278 ctx.symAux.back().pltIdx = ctx.symAux[irelativeSym->auxIdx].pltIdx;
1279
1280 if (flags & HAS_DIRECT_RELOC) {
1281 // Change the value to the IPLT and redirect all references to it.
1282 auto &d = cast<Defined>(Val&: sym);
1283 d.section = ctx.in.iplt.get();
1284 d.value = d.getPltIdx(ctx) * ctx.target->ipltEntrySize;
1285 d.size = 0;
1286 // It's important to set the symbol type here so that dynamic loaders
1287 // don't try to call the PLT as if it were an ifunc resolver.
1288 d.type = STT_FUNC;
1289
1290 if (flags & NEEDS_GOT) {
1291 assert(!(flags & NEEDS_GOT_AUTH) &&
1292 "R_AARCH64_AUTH_IRELATIVE is not supported yet");
1293 addGotEntry(ctx, sym);
1294 }
1295 } else if (flags & NEEDS_GOT) {
1296 // Redirect GOT accesses to point to the Igot.
1297 sym.gotInIgot = true;
1298 }
1299 return true;
1300}
1301
1302void elf::postScanRelocations(Ctx &ctx) {
1303 bool needsTlsIe = false;
1304 auto fn = [&](Symbol &sym) {
1305 auto flags = sym.flags.load(m: std::memory_order_relaxed);
1306 if (handleNonPreemptibleIfunc(ctx, sym, flags))
1307 return;
1308
1309 if (sym.isTagged() && sym.isDefined())
1310 ctx.mainPart->memtagGlobalDescriptors->addSymbol(sym);
1311
1312 if (!sym.needsDynReloc())
1313 return;
1314 sym.allocateAux(ctx);
1315
1316 if (flags & NEEDS_GOT) {
1317 if ((flags & NEEDS_GOT_AUTH) && (flags & NEEDS_GOT_NONAUTH)) {
1318 auto diag = Err(ctx);
1319 diag << "both AUTH and non-AUTH GOT entries for '" << sym.getName()
1320 << "' requested, but only one type of GOT entry per symbol is "
1321 "supported";
1322 return;
1323 }
1324 if (flags & NEEDS_GOT_AUTH)
1325 addGotAuthEntry(ctx, sym);
1326 else
1327 addGotEntry(ctx, sym);
1328 }
1329 if (flags & NEEDS_PLT)
1330 addPltEntry(ctx, plt&: *ctx.in.plt, gotPlt&: *ctx.in.gotPlt, rel&: *ctx.in.relaPlt,
1331 type: ctx.target->pltRel, sym);
1332 if (flags & NEEDS_COPY) {
1333 if (sym.isObject()) {
1334 invokeELFT(addCopyRelSymbol, ctx, cast<SharedSymbol>(sym));
1335 // NEEDS_COPY is cleared for sym and its aliases so that in
1336 // later iterations aliases won't cause redundant copies.
1337 assert(!sym.hasFlag(NEEDS_COPY));
1338 } else {
1339 assert(sym.isFunc() && sym.hasFlag(NEEDS_PLT));
1340 if (!sym.isDefined()) {
1341 replaceWithDefined(ctx, sym, sec&: *ctx.in.plt,
1342 value: ctx.target->pltHeaderSize +
1343 ctx.target->pltEntrySize * sym.getPltIdx(ctx),
1344 size: 0);
1345 sym.setFlags(NEEDS_COPY);
1346 if (ctx.arg.emachine == EM_PPC) {
1347 // PPC32 canonical PLT entries are at the beginning of .glink
1348 cast<Defined>(Val&: sym).value = ctx.in.plt->headerSize;
1349 ctx.in.plt->headerSize += 16;
1350 cast<PPC32GlinkSection>(Val&: *ctx.in.plt).canonical_plts.push_back(Elt: &sym);
1351 }
1352 }
1353 }
1354 }
1355
1356 if (!sym.isTls())
1357 return;
1358 bool isLocalInExecutable = !sym.isPreemptible && !ctx.arg.shared;
1359 GotSection *got = ctx.in.got.get();
1360
1361 if (flags & NEEDS_TLSDESC) {
1362 if ((flags & NEEDS_TLSDESC_AUTH) && (flags & NEEDS_TLSDESC_NONAUTH)) {
1363 Err(ctx)
1364 << "both AUTH and non-AUTH TLSDESC entries for '" << sym.getName()
1365 << "' requested, but only one type of TLSDESC entry per symbol is "
1366 "supported";
1367 return;
1368 }
1369 got->addTlsDescEntry(sym);
1370 RelType tlsDescRel = ctx.target->tlsDescRel;
1371 if (flags & NEEDS_TLSDESC_AUTH) {
1372 got->addTlsDescAuthEntry();
1373 tlsDescRel = ELF::R_AARCH64_AUTH_TLSDESC;
1374 }
1375 ctx.mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1376 dynType: tlsDescRel, isec&: *got, offsetInSec: got->getTlsDescOffset(sym), sym, addendRelType: tlsDescRel);
1377 }
1378 if (flags & NEEDS_TLSGD) {
1379 got->addDynTlsEntry(sym);
1380 uint64_t off = got->getGlobalDynOffset(b: sym);
1381 if (isLocalInExecutable)
1382 // Write one to the GOT slot.
1383 got->addConstant(r: {.expr: R_ADDEND, .type: ctx.target->symbolicRel, .offset: off, .addend: 1, .sym: &sym});
1384 else
1385 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->tlsModuleIndexRel,
1386 isec&: *got, offsetInSec: off, sym);
1387
1388 // If the symbol is preemptible we need the dynamic linker to write
1389 // the offset too.
1390 uint64_t offsetOff = off + ctx.arg.wordsize;
1391 if (sym.isPreemptible)
1392 ctx.mainPart->relaDyn->addSymbolReloc(dynType: ctx.target->tlsOffsetRel, isec&: *got,
1393 offsetInSec: offsetOff, sym);
1394 else
1395 got->addConstant(r: {.expr: R_ABS, .type: ctx.target->tlsOffsetRel, .offset: offsetOff, .addend: 0, .sym: &sym});
1396 }
1397 if (flags & NEEDS_GOT_DTPREL) {
1398 got->addEntry(sym);
1399 got->addConstant(
1400 r: {.expr: R_ABS, .type: ctx.target->tlsOffsetRel, .offset: sym.getGotOffset(ctx), .addend: 0, .sym: &sym});
1401 }
1402
1403 if (flags & NEEDS_TLSIE) {
1404 needsTlsIe = true;
1405 addTpOffsetGotEntry(ctx, sym);
1406 }
1407 };
1408
1409 GotSection *got = ctx.in.got.get();
1410 if (ctx.needsTlsLd.load(m: std::memory_order_relaxed) && got->addTlsIndex()) {
1411 if (ctx.arg.shared)
1412 ctx.mainPart->relaDyn->addReloc(
1413 reloc: {ctx.target->tlsModuleIndexRel, got, got->getTlsIndexOff()});
1414 else
1415 got->addConstant(r: {.expr: R_ADDEND, .type: ctx.target->symbolicRel,
1416 .offset: got->getTlsIndexOff(), .addend: 1, .sym: ctx.dummySym});
1417 }
1418
1419 assert(ctx.symAux.size() == 1);
1420 for (Symbol *sym : ctx.symtab->getSymbols())
1421 fn(*sym);
1422
1423 // Local symbols may need the aforementioned non-preemptible ifunc and GOT
1424 // handling. They don't need regular PLT.
1425 for (ELFFileBase *file : ctx.objectFiles)
1426 for (Symbol *sym : file->getLocalSymbols())
1427 fn(*sym);
1428
1429 if (needsTlsIe)
1430 ctx.hasTlsIe.store(i: true, m: std::memory_order_relaxed);
1431
1432 if (ctx.arg.branchToBranch)
1433 ctx.target->applyBranchToBranchOpt();
1434}
1435
1436static bool mergeCmp(const InputSection *a, const InputSection *b) {
1437 // std::merge requires a strict weak ordering.
1438 if (a->outSecOff < b->outSecOff)
1439 return true;
1440
1441 // FIXME dyn_cast<ThunkSection> is non-null for any SyntheticSection.
1442 if (a->outSecOff == b->outSecOff && a != b) {
1443 auto *ta = dyn_cast<ThunkSection>(Val: a);
1444 auto *tb = dyn_cast<ThunkSection>(Val: b);
1445
1446 // Check if Thunk is immediately before any specific Target
1447 // InputSection for example Mips LA25 Thunks.
1448 if (ta && ta->getTargetInputSection() == b)
1449 return true;
1450
1451 // Place Thunk Sections without specific targets before
1452 // non-Thunk Sections.
1453 if (ta && !tb && !ta->getTargetInputSection())
1454 return true;
1455 }
1456
1457 return false;
1458}
1459
1460// Call Fn on every executable InputSection accessed via the linker script
1461// InputSectionDescription::Sections.
1462static void forEachInputSectionDescription(
1463 ArrayRef<OutputSection *> outputSections,
1464 llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
1465 for (OutputSection *os : outputSections) {
1466 if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
1467 continue;
1468 for (SectionCommand *bc : os->commands)
1469 if (auto *isd = dyn_cast<InputSectionDescription>(Val: bc))
1470 fn(os, isd);
1471 }
1472}
1473
1474ThunkCreator::ThunkCreator(Ctx &ctx) : ctx(ctx) {}
1475
1476ThunkCreator::~ThunkCreator() {}
1477
1478// Thunk Implementation
1479//
1480// Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1481// of code that the linker inserts inbetween a caller and a callee. The thunks
1482// are added at link time rather than compile time as the decision on whether
1483// a thunk is needed, such as the caller and callee being out of range, can only
1484// be made at link time.
1485//
1486// It is straightforward to tell given the current state of the program when a
1487// thunk is needed for a particular call. The more difficult part is that
1488// the thunk needs to be placed in the program such that the caller can reach
1489// the thunk and the thunk can reach the callee; furthermore, adding thunks to
1490// the program alters addresses, which can mean more thunks etc.
1491//
1492// In lld we have a synthetic ThunkSection that can hold many Thunks.
1493// The decision to have a ThunkSection act as a container means that we can
1494// more easily handle the most common case of a single block of contiguous
1495// Thunks by inserting just a single ThunkSection.
1496//
1497// The implementation of Thunks in lld is split across these areas
1498// Relocations.cpp : Framework for creating and placing thunks
1499// Thunks.cpp : The code generated for each supported thunk
1500// Target.cpp : Target specific hooks that the framework uses to decide when
1501// a thunk is used
1502// Synthetic.cpp : Implementation of ThunkSection
1503// Writer.cpp : Iteratively call framework until no more Thunks added
1504//
1505// Thunk placement requirements:
1506// Mips LA25 thunks. These must be placed immediately before the callee section
1507// We can assume that the caller is in range of the Thunk. These are modelled
1508// by Thunks that return the section they must precede with
1509// getTargetInputSection().
1510//
1511// ARM interworking and range extension thunks. These thunks must be placed
1512// within range of the caller. All implemented ARM thunks can always reach the
1513// callee as they use an indirect jump via a register that has no range
1514// restrictions.
1515//
1516// Thunk placement algorithm:
1517// For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1518// getTargetInputSection().
1519//
1520// For thunks that must be placed within range of the caller there are many
1521// possible choices given that the maximum range from the caller is usually
1522// much larger than the average InputSection size. Desirable properties include:
1523// - Maximize reuse of thunks by multiple callers
1524// - Minimize number of ThunkSections to simplify insertion
1525// - Handle impact of already added Thunks on addresses
1526// - Simple to understand and implement
1527//
1528// In lld for the first pass, we pre-create one or more ThunkSections per
1529// InputSectionDescription at Target specific intervals. A ThunkSection is
1530// placed so that the estimated end of the ThunkSection is within range of the
1531// start of the InputSectionDescription or the previous ThunkSection. For
1532// example:
1533// InputSectionDescription
1534// Section 0
1535// ...
1536// Section N
1537// ThunkSection 0
1538// Section N + 1
1539// ...
1540// Section N + K
1541// Thunk Section 1
1542//
1543// The intention is that we can add a Thunk to a ThunkSection that is well
1544// spaced enough to service a number of callers without having to do a lot
1545// of work. An important principle is that it is not an error if a Thunk cannot
1546// be placed in a pre-created ThunkSection; when this happens we create a new
1547// ThunkSection placed next to the caller. This allows us to handle the vast
1548// majority of thunks simply, but also handle rare cases where the branch range
1549// is smaller than the target specific spacing.
1550//
1551// The algorithm is expected to create all the thunks that are needed in a
1552// single pass, with a small number of programs needing a second pass due to
1553// the insertion of thunks in the first pass increasing the offset between
1554// callers and callees that were only just in range.
1555//
1556// A consequence of allowing new ThunkSections to be created outside of the
1557// pre-created ThunkSections is that in rare cases calls to Thunks that were in
1558// range in pass K, are out of range in some pass > K due to the insertion of
1559// more Thunks in between the caller and callee. When this happens we retarget
1560// the relocation back to the original target and create another Thunk.
1561
1562// Remove ThunkSections that are empty, this should only be the initial set
1563// precreated on pass 0.
1564
1565// Insert the Thunks for OutputSection OS into their designated place
1566// in the Sections vector, and recalculate the InputSection output section
1567// offsets.
1568// This may invalidate any output section offsets stored outside of InputSection
1569void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
1570 forEachInputSectionDescription(
1571 outputSections, fn: [&](OutputSection *os, InputSectionDescription *isd) {
1572 if (isd->thunkSections.empty())
1573 return;
1574
1575 // Remove any zero sized precreated Thunks.
1576 llvm::erase_if(C&: isd->thunkSections,
1577 P: [](const std::pair<ThunkSection *, uint32_t> &ts) {
1578 return ts.first->getSize() == 0;
1579 });
1580
1581 // ISD->ThunkSections contains all created ThunkSections, including
1582 // those inserted in previous passes. Extract the Thunks created this
1583 // pass and order them in ascending outSecOff.
1584 std::vector<ThunkSection *> newThunks;
1585 for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
1586 if (ts.second == pass)
1587 newThunks.push_back(x: ts.first);
1588 llvm::stable_sort(Range&: newThunks,
1589 C: [](const ThunkSection *a, const ThunkSection *b) {
1590 return a->outSecOff < b->outSecOff;
1591 });
1592
1593 // Merge sorted vectors of Thunks and InputSections by outSecOff
1594 SmallVector<InputSection *, 0> tmp;
1595 tmp.reserve(N: isd->sections.size() + newThunks.size());
1596
1597 std::merge(first1: isd->sections.begin(), last1: isd->sections.end(),
1598 first2: newThunks.begin(), last2: newThunks.end(), result: std::back_inserter(x&: tmp),
1599 comp: mergeCmp);
1600
1601 isd->sections = std::move(tmp);
1602 });
1603}
1604
1605constexpr uint32_t HEXAGON_MASK_END_PACKET = 3 << 14;
1606constexpr uint32_t HEXAGON_END_OF_PACKET = 3 << 14;
1607constexpr uint32_t HEXAGON_END_OF_DUPLEX = 0 << 14;
1608
1609// Return the distance between the packet start and the instruction in the
1610// relocation.
1611static int getHexagonPacketOffset(const InputSection &isec,
1612 const Relocation &rel) {
1613 const ArrayRef<uint8_t> data = isec.content();
1614
1615 // Search back as many as 3 instructions.
1616 for (unsigned i = 0;; i++) {
1617 if (i == 3 || rel.offset < (i + 1) * 4)
1618 return i * 4;
1619 uint32_t instWord =
1620 read32(ctx&: isec.getCtx(), p: data.data() + (rel.offset - (i + 1) * 4));
1621 if (((instWord & HEXAGON_MASK_END_PACKET) == HEXAGON_END_OF_PACKET) ||
1622 ((instWord & HEXAGON_MASK_END_PACKET) == HEXAGON_END_OF_DUPLEX))
1623 return i * 4;
1624 }
1625}
1626
1627static int64_t getPCBias(Ctx &ctx, const InputSection &isec,
1628 const Relocation &rel) {
1629 if (ctx.arg.emachine == EM_ARM) {
1630 switch (rel.type) {
1631 case R_ARM_THM_JUMP19:
1632 case R_ARM_THM_JUMP24:
1633 case R_ARM_THM_CALL:
1634 return 4;
1635 default:
1636 return 8;
1637 }
1638 }
1639 if (ctx.arg.emachine == EM_HEXAGON)
1640 return -getHexagonPacketOffset(isec, rel);
1641 return 0;
1642}
1643
1644// Find or create a ThunkSection within the InputSectionDescription (ISD) that
1645// is in range of Src. An ISD maps to a range of InputSections described by a
1646// linker script section pattern such as { .text .text.* }.
1647ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os,
1648 InputSection *isec,
1649 InputSectionDescription *isd,
1650 const Relocation &rel,
1651 uint64_t src) {
1652 // See the comment in getThunk for -pcBias below.
1653 const int64_t pcBias = getPCBias(ctx, isec: *isec, rel);
1654 for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
1655 ThunkSection *ts = tp.first;
1656 uint64_t tsBase = os->addr + ts->outSecOff - pcBias;
1657 uint64_t tsLimit = tsBase + ts->getSize();
1658 if (ctx.target->inBranchRange(type: rel.type, src,
1659 dst: (src > tsLimit) ? tsBase : tsLimit))
1660 return ts;
1661 }
1662
1663 // No suitable ThunkSection exists. This can happen when there is a branch
1664 // with lower range than the ThunkSection spacing or when there are too
1665 // many Thunks. Create a new ThunkSection as close to the InputSection as
1666 // possible. Error if InputSection is so large we cannot place ThunkSection
1667 // anywhere in Range.
1668 uint64_t thunkSecOff = isec->outSecOff;
1669 if (!ctx.target->inBranchRange(type: rel.type, src,
1670 dst: os->addr + thunkSecOff + rel.addend)) {
1671 thunkSecOff = isec->outSecOff + isec->getSize();
1672 if (!ctx.target->inBranchRange(type: rel.type, src,
1673 dst: os->addr + thunkSecOff + rel.addend))
1674 Fatal(ctx) << "InputSection too large for range extension thunk "
1675 << isec->getObjMsg(offset: src - (os->addr << isec->outSecOff));
1676 }
1677 return addThunkSection(os, isd, off: thunkSecOff);
1678}
1679
1680// Add a Thunk that needs to be placed in a ThunkSection that immediately
1681// precedes its Target.
1682ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
1683 ThunkSection *ts = thunkedSections.lookup(Val: isec);
1684 if (ts)
1685 return ts;
1686
1687 // Find InputSectionRange within Target Output Section (TOS) that the
1688 // InputSection (IS) that we need to precede is in.
1689 OutputSection *tos = isec->getParent();
1690 for (SectionCommand *bc : tos->commands) {
1691 auto *isd = dyn_cast<InputSectionDescription>(Val: bc);
1692 if (!isd || isd->sections.empty())
1693 continue;
1694
1695 InputSection *first = isd->sections.front();
1696 InputSection *last = isd->sections.back();
1697
1698 if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
1699 continue;
1700
1701 ts = addThunkSection(os: tos, isd, off: isec->outSecOff, /*isPrefix=*/true);
1702 thunkedSections[isec] = ts;
1703 return ts;
1704 }
1705
1706 return nullptr;
1707}
1708
1709// Create one or more ThunkSections per OS that can be used to place Thunks.
1710// We attempt to place the ThunkSections using the following desirable
1711// properties:
1712// - Within range of the maximum number of callers
1713// - Minimise the number of ThunkSections
1714//
1715// We follow a simple but conservative heuristic to place ThunkSections at
1716// offsets that are multiples of a Target specific branch range.
1717// For an InputSectionDescription that is smaller than the range, a single
1718// ThunkSection at the end of the range will do.
1719//
1720// For an InputSectionDescription that is more than twice the size of the range,
1721// we place the last ThunkSection at range bytes from the end of the
1722// InputSectionDescription in order to increase the likelihood that the
1723// distance from a thunk to its target will be sufficiently small to
1724// allow for the creation of a short thunk.
1725void ThunkCreator::createInitialThunkSections(
1726 ArrayRef<OutputSection *> outputSections) {
1727 uint32_t thunkSectionSpacing = ctx.target->getThunkSectionSpacing();
1728 forEachInputSectionDescription(
1729 outputSections, fn: [&](OutputSection *os, InputSectionDescription *isd) {
1730 if (isd->sections.empty())
1731 return;
1732
1733 uint32_t isdBegin = isd->sections.front()->outSecOff;
1734 uint32_t isdEnd =
1735 isd->sections.back()->outSecOff + isd->sections.back()->getSize();
1736 uint32_t lastThunkLowerBound = -1;
1737 if (isdEnd - isdBegin > thunkSectionSpacing * 2)
1738 lastThunkLowerBound = isdEnd - thunkSectionSpacing;
1739
1740 uint32_t isecLimit;
1741 uint32_t prevIsecLimit = isdBegin;
1742 uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
1743
1744 for (const InputSection *isec : isd->sections) {
1745 isecLimit = isec->outSecOff + isec->getSize();
1746 if (isecLimit > thunkUpperBound) {
1747 addThunkSection(os, isd, off: prevIsecLimit);
1748 thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
1749 }
1750 if (isecLimit > lastThunkLowerBound)
1751 break;
1752 prevIsecLimit = isecLimit;
1753 }
1754 addThunkSection(os, isd, off: isecLimit);
1755 });
1756}
1757
1758ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
1759 InputSectionDescription *isd,
1760 uint64_t off, bool isPrefix) {
1761 auto *ts = make<ThunkSection>(args&: ctx, args&: os, args&: off);
1762 ts->partition = os->partition;
1763 if ((ctx.arg.fixCortexA53Errata843419 || ctx.arg.fixCortexA8) &&
1764 !isd->sections.empty() && !isPrefix) {
1765 // The errata fixes are sensitive to addresses modulo 4 KiB. When we add
1766 // thunks we disturb the base addresses of sections placed after the thunks
1767 // this makes patches we have generated redundant, and may cause us to
1768 // generate more patches as different instructions are now in sensitive
1769 // locations. When we generate more patches we may force more branches to
1770 // go out of range, causing more thunks to be generated. In pathological
1771 // cases this can cause the address dependent content pass not to converge.
1772 // We fix this by rounding up the size of the ThunkSection to 4KiB, this
1773 // limits the insertion of a ThunkSection on the addresses modulo 4 KiB,
1774 // which means that adding Thunks to the section does not invalidate
1775 // errata patches for following code.
1776 // Rounding up the size to 4KiB has consequences for code-size and can
1777 // trip up linker script defined assertions. For example the linux kernel
1778 // has an assertion that what LLD represents as an InputSectionDescription
1779 // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib.
1780 // We use the heuristic of rounding up the size when both of the following
1781 // conditions are true:
1782 // 1.) The OutputSection is larger than the ThunkSectionSpacing. This
1783 // accounts for the case where no single InputSectionDescription is
1784 // larger than the OutputSection size. This is conservative but simple.
1785 // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent
1786 // any assertion failures that an InputSectionDescription is < 4 KiB
1787 // in size.
1788 //
1789 // isPrefix is a ThunkSection explicitly inserted before its target
1790 // section. We suppress the rounding up of the size of these ThunkSections
1791 // as unlike normal ThunkSections, they are small in size, but when BTI is
1792 // enabled very frequent. This can bloat code-size and push the errata
1793 // patches out of branch range.
1794 uint64_t isdSize = isd->sections.back()->outSecOff +
1795 isd->sections.back()->getSize() -
1796 isd->sections.front()->outSecOff;
1797 if (os->size > ctx.target->getThunkSectionSpacing() && isdSize > 4096)
1798 ts->roundUpSizeForErrata = true;
1799 }
1800 isd->thunkSections.push_back(Elt: {ts, pass});
1801 return ts;
1802}
1803
1804static bool isThunkSectionCompatible(InputSection *source,
1805 SectionBase *target) {
1806 // We can't reuse thunks in different loadable partitions because they might
1807 // not be loaded. But partition 1 (the main partition) will always be loaded.
1808 if (source->partition != target->partition)
1809 return target->partition == 1;
1810 return true;
1811}
1812
1813std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
1814 Relocation &rel, uint64_t src) {
1815 SmallVector<std::unique_ptr<Thunk>, 0> *thunkVec = nullptr;
1816 // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled
1817 // out in the relocation addend. We compensate for the PC bias so that
1818 // an Arm and Thumb relocation to the same destination get the same keyAddend,
1819 // which is usually 0.
1820 const int64_t pcBias = getPCBias(ctx, isec: *isec, rel);
1821 const int64_t keyAddend = rel.addend + pcBias;
1822
1823 // We use a ((section, offset), addend) pair to find the thunk position if
1824 // possible so that we create only one thunk for aliased symbols or ICFed
1825 // sections. There may be multiple relocations sharing the same (section,
1826 // offset + addend) pair. We may revert the relocation back to its original
1827 // non-Thunk target, so we cannot fold offset + addend.
1828 if (auto *d = dyn_cast<Defined>(Val: rel.sym))
1829 if (!d->isInPlt(ctx) && d->section)
1830 thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value},
1831 keyAddend}];
1832 if (!thunkVec)
1833 thunkVec = &thunkedSymbols[{rel.sym, keyAddend}];
1834
1835 // Check existing Thunks for Sym to see if they can be reused
1836 for (auto &t : *thunkVec)
1837 if (isThunkSectionCompatible(source: isec, target: t->getThunkTargetSym()->section) &&
1838 t->isCompatibleWith(*isec, rel) &&
1839 ctx.target->inBranchRange(type: rel.type, src,
1840 dst: t->getThunkTargetSym()->getVA(ctx, addend: -pcBias)))
1841 return std::make_pair(x: t.get(), y: false);
1842
1843 // No existing compatible Thunk in range, create a new one
1844 thunkVec->push_back(Elt: addThunk(ctx, isec: *isec, rel));
1845 return std::make_pair(x: thunkVec->back().get(), y: true);
1846}
1847
1848std::pair<Thunk *, bool> ThunkCreator::getSyntheticLandingPad(Defined &d,
1849 int64_t a) {
1850 auto [it, isNew] = landingPadsBySectionAndAddend.try_emplace(
1851 Key: {{d.section, d.value}, a}, Args: nullptr);
1852 if (isNew)
1853 it->second = addLandingPadThunk(ctx, s&: d, a);
1854 return {it->second.get(), isNew};
1855}
1856
1857// Return true if the relocation target is an in range Thunk.
1858// Return false if the relocation is not to a Thunk. If the relocation target
1859// was originally to a Thunk, but is no longer in range we revert the
1860// relocation back to its original non-Thunk target.
1861bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
1862 if (Thunk *t = thunks.lookup(Val: rel.sym)) {
1863 if (ctx.target->inBranchRange(type: rel.type, src,
1864 dst: rel.sym->getVA(ctx, addend: rel.addend)))
1865 return true;
1866 rel.sym = &t->destination;
1867 rel.addend = t->addend;
1868 if (rel.sym->isInPlt(ctx))
1869 rel.expr = toPlt(expr: rel.expr);
1870 }
1871 return false;
1872}
1873
1874// When indirect branches are restricted, such as AArch64 BTI Thunks may need
1875// to target a linker generated landing pad instead of the target. This needs
1876// to be done once per pass as the need for a BTI thunk is dependent whether
1877// a thunk is short or long. We iterate over all the thunks to make sure we
1878// catch thunks that have been created but are no longer live. Non-live thunks
1879// are not reachable via normalizeExistingThunk() but are still written.
1880bool ThunkCreator::addSyntheticLandingPads() {
1881 bool addressesChanged = false;
1882 for (Thunk *t : allThunks) {
1883 if (!t->needsSyntheticLandingPad())
1884 continue;
1885 Thunk *lpt;
1886 bool isNew;
1887 auto &dr = cast<Defined>(Val&: t->destination);
1888 std::tie(args&: lpt, args&: isNew) = getSyntheticLandingPad(d&: dr, a: t->addend);
1889 if (isNew) {
1890 addressesChanged = true;
1891 getISThunkSec(isec: cast<InputSection>(Val: dr.section))->addThunk(t: lpt);
1892 }
1893 t->landingPad = lpt->getThunkTargetSym();
1894 }
1895 return addressesChanged;
1896}
1897
1898// Process all relocations from the InputSections that have been assigned
1899// to InputSectionDescriptions and redirect through Thunks if needed. The
1900// function should be called iteratively until it returns false.
1901//
1902// PreConditions:
1903// All InputSections that may need a Thunk are reachable from
1904// OutputSectionCommands.
1905//
1906// All OutputSections have an address and all InputSections have an offset
1907// within the OutputSection.
1908//
1909// The offsets between caller (relocation place) and callee
1910// (relocation target) will not be modified outside of createThunks().
1911//
1912// PostConditions:
1913// If return value is true then ThunkSections have been inserted into
1914// OutputSections. All relocations that needed a Thunk based on the information
1915// available to createThunks() on entry have been redirected to a Thunk. Note
1916// that adding Thunks changes offsets between caller and callee so more Thunks
1917// may be required.
1918//
1919// If return value is false then no more Thunks are needed, and createThunks has
1920// made no changes. If the target requires range extension thunks, currently
1921// ARM, then any future change in offset between caller and callee risks a
1922// relocation out of range error.
1923bool ThunkCreator::createThunks(uint32_t pass,
1924 ArrayRef<OutputSection *> outputSections) {
1925 this->pass = pass;
1926 bool addressesChanged = false;
1927
1928 if (pass == 0 && ctx.target->getThunkSectionSpacing())
1929 createInitialThunkSections(outputSections);
1930
1931 if (ctx.arg.emachine == EM_AARCH64)
1932 addressesChanged = addSyntheticLandingPads();
1933
1934 // Create all the Thunks and insert them into synthetic ThunkSections. The
1935 // ThunkSections are later inserted back into InputSectionDescriptions.
1936 // We separate the creation of ThunkSections from the insertion of the
1937 // ThunkSections as ThunkSections are not always inserted into the same
1938 // InputSectionDescription as the caller.
1939 forEachInputSectionDescription(
1940 outputSections, fn: [&](OutputSection *os, InputSectionDescription *isd) {
1941 for (InputSection *isec : isd->sections)
1942 for (Relocation &rel : isec->relocs()) {
1943 uint64_t src = isec->getVA(offset: rel.offset);
1944
1945 // If we are a relocation to an existing Thunk, check if it is
1946 // still in range. If not then Rel will be altered to point to its
1947 // original target so another Thunk can be generated.
1948 if (pass > 0 && normalizeExistingThunk(rel, src))
1949 continue;
1950
1951 if (!ctx.target->needsThunk(expr: rel.expr, relocType: rel.type, file: isec->file, branchAddr: src,
1952 s: *rel.sym, a: rel.addend))
1953 continue;
1954
1955 Thunk *t;
1956 bool isNew;
1957 std::tie(args&: t, args&: isNew) = getThunk(isec, rel, src);
1958
1959 if (isNew) {
1960 // Find or create a ThunkSection for the new Thunk
1961 ThunkSection *ts;
1962 if (auto *tis = t->getTargetInputSection())
1963 ts = getISThunkSec(isec: tis);
1964 else
1965 ts = getISDThunkSec(os, isec, isd, rel, src);
1966 ts->addThunk(t);
1967 thunks[t->getThunkTargetSym()] = t;
1968 allThunks.push_back(x: t);
1969 }
1970
1971 // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1972 rel.sym = t->getThunkTargetSym();
1973 rel.expr = fromPlt(expr: rel.expr);
1974
1975 // On AArch64 and PPC, a jump/call relocation may be encoded as
1976 // STT_SECTION + non-zero addend, clear the addend after
1977 // redirection.
1978 if (ctx.arg.emachine != EM_MIPS)
1979 rel.addend = -getPCBias(ctx, isec: *isec, rel);
1980 }
1981
1982 for (auto &p : isd->thunkSections)
1983 addressesChanged |= p.first->assignOffsets();
1984 });
1985
1986 for (auto &p : thunkedSections)
1987 addressesChanged |= p.second->assignOffsets();
1988
1989 // Merge all created synthetic ThunkSections back into OutputSection
1990 mergeThunks(outputSections);
1991 return addressesChanged;
1992}
1993
1994// The following aid in the conversion of call x@GDPLT to call __tls_get_addr
1995// hexagonNeedsTLSSymbol scans for relocations would require a call to
1996// __tls_get_addr.
1997// hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr.
1998bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) {
1999 bool needTlsSymbol = false;
2000 forEachInputSectionDescription(
2001 outputSections, fn: [&](OutputSection *os, InputSectionDescription *isd) {
2002 for (InputSection *isec : isd->sections)
2003 for (Relocation &rel : isec->relocs())
2004 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
2005 needTlsSymbol = true;
2006 return;
2007 }
2008 });
2009 return needTlsSymbol;
2010}
2011
2012void elf::hexagonTLSSymbolUpdate(Ctx &ctx) {
2013 Symbol *sym = ctx.symtab->find(name: "__tls_get_addr");
2014 if (!sym)
2015 return;
2016 bool needEntry = true;
2017 forEachInputSectionDescription(
2018 outputSections: ctx.outputSections, fn: [&](OutputSection *os, InputSectionDescription *isd) {
2019 for (InputSection *isec : isd->sections)
2020 for (Relocation &rel : isec->relocs())
2021 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
2022 if (needEntry) {
2023 if (sym->auxIdx == 0)
2024 sym->allocateAux(ctx);
2025 addPltEntry(ctx, plt&: *ctx.in.plt, gotPlt&: *ctx.in.gotPlt, rel&: *ctx.in.relaPlt,
2026 type: ctx.target->pltRel, sym&: *sym);
2027 needEntry = false;
2028 }
2029 rel.sym = sym;
2030 }
2031 });
2032}
2033
2034static bool matchesRefTo(const NoCrossRefCommand &cmd, StringRef osec) {
2035 if (cmd.toFirst)
2036 return cmd.outputSections[0] == osec;
2037 return llvm::is_contained(Range: cmd.outputSections, Element: osec);
2038}
2039
2040template <class ELFT, class Rels>
2041static void scanCrossRefs(Ctx &ctx, const NoCrossRefCommand &cmd,
2042 OutputSection *osec, InputSection *sec, Rels rels) {
2043 for (const auto &r : rels) {
2044 Symbol &sym = sec->file->getSymbol(symbolIndex: r.getSymbol(ctx.arg.isMips64EL));
2045 // A legal cross-reference is when the destination output section is
2046 // nullptr, osec for a self-reference, or a section that is described by the
2047 // NOCROSSREFS/NOCROSSREFS_TO command.
2048 auto *dstOsec = sym.getOutputSection();
2049 if (!dstOsec || dstOsec == osec || !matchesRefTo(cmd, osec: dstOsec->name))
2050 continue;
2051
2052 std::string toSymName;
2053 if (!sym.isSection())
2054 toSymName = toStr(ctx, sym);
2055 else if (auto *d = dyn_cast<Defined>(Val: &sym))
2056 toSymName = d->section->name;
2057 Err(ctx) << sec->getLocation(offset: r.r_offset)
2058 << ": prohibited cross reference from '" << osec->name << "' to '"
2059 << toSymName << "' in '" << dstOsec->name << "'";
2060 }
2061}
2062
2063// For each output section described by at least one NOCROSSREFS(_TO) command,
2064// scan relocations from its input sections for prohibited cross references.
2065template <class ELFT> void elf::checkNoCrossRefs(Ctx &ctx) {
2066 for (OutputSection *osec : ctx.outputSections) {
2067 for (const NoCrossRefCommand &noxref : ctx.script->noCrossRefs) {
2068 if (!llvm::is_contained(Range: noxref.outputSections, Element: osec->name) ||
2069 (noxref.toFirst && noxref.outputSections[0] == osec->name))
2070 continue;
2071 for (SectionCommand *cmd : osec->commands) {
2072 auto *isd = dyn_cast<InputSectionDescription>(Val: cmd);
2073 if (!isd)
2074 continue;
2075 parallelForEach(isd->sections, [&](InputSection *sec) {
2076 invokeOnRelocs(*sec, scanCrossRefs<ELFT>, ctx, noxref, osec, sec);
2077 });
2078 }
2079 }
2080 }
2081}
2082
2083template void elf::scanRelocations<ELF32LE>(Ctx &);
2084template void elf::scanRelocations<ELF32BE>(Ctx &);
2085template void elf::scanRelocations<ELF64LE>(Ctx &);
2086template void elf::scanRelocations<ELF64BE>(Ctx &);
2087
2088template void elf::checkNoCrossRefs<ELF32LE>(Ctx &);
2089template void elf::checkNoCrossRefs<ELF32BE>(Ctx &);
2090template void elf::checkNoCrossRefs<ELF64LE>(Ctx &);
2091template void elf::checkNoCrossRefs<ELF64BE>(Ctx &);
2092