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