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