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