[NFC][opt] Improve help message (#97805)
[llvm-project.git] / lld / ELF / Relocations.cpp
blobda4724d8f653613a853c45851001d80a0f0c5126
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 contains platform-independent functions to process relocations.
10 // I'll describe the overview of this file here.
12 // Simple relocations are easy to handle for the linker. For example,
13 // for R_X86_64_PC64 relocs, the linker just has to fix up locations
14 // with the relative offsets to the target symbols. It would just be
15 // reading records from relocation sections and applying them to output.
17 // But not all relocations are that easy to handle. For example, for
18 // R_386_GOTOFF relocs, the linker has to create new GOT entries for
19 // symbols if they don't exist, and fix up locations with GOT entry
20 // offsets from the beginning of GOT section. So there is more than
21 // fixing addresses in relocation processing.
23 // ELF defines a large number of complex relocations.
25 // The functions in this file analyze relocations and do whatever needs
26 // to be done. It includes, but not limited to, the following.
28 // - create GOT/PLT entries
29 // - create new relocations in .dynsym to let the dynamic linker resolve
30 // them at runtime (since ELF supports dynamic linking, not all
31 // relocations can be resolved at link-time)
32 // - create COPY relocs and reserve space in .bss
33 // - replace expensive relocs (in terms of runtime cost) with cheap ones
34 // - error out infeasible combinations such as PIC and non-relative relocs
36 // Note that the functions in this file don't actually apply relocations
37 // because it doesn't know about the output file nor the output file buffer.
38 // It instead stores Relocation objects to InputSection's Relocations
39 // vector to let it apply later in InputSection::writeTo.
41 //===----------------------------------------------------------------------===//
43 #include "Relocations.h"
44 #include "Config.h"
45 #include "InputFiles.h"
46 #include "LinkerScript.h"
47 #include "OutputSections.h"
48 #include "SymbolTable.h"
49 #include "Symbols.h"
50 #include "SyntheticSections.h"
51 #include "Target.h"
52 #include "Thunks.h"
53 #include "lld/Common/ErrorHandler.h"
54 #include "lld/Common/Memory.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/BinaryFormat/ELF.h"
57 #include "llvm/Demangle/Demangle.h"
58 #include "llvm/Support/Endian.h"
59 #include <algorithm>
61 using namespace llvm;
62 using namespace llvm::ELF;
63 using namespace llvm::object;
64 using namespace llvm::support::endian;
65 using namespace lld;
66 using namespace lld::elf;
68 static std::optional<std::string> getLinkerScriptLocation(const Symbol &sym) {
69 for (SectionCommand *cmd : script->sectionCommands)
70 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
71 if (assign->sym == &sym)
72 return assign->location;
73 return std::nullopt;
76 static std::string getDefinedLocation(const Symbol &sym) {
77 const char msg[] = "\n>>> defined in ";
78 if (sym.file)
79 return msg + toString(sym.file);
80 if (std::optional<std::string> loc = getLinkerScriptLocation(sym))
81 return msg + *loc;
82 return "";
85 // Construct a message in the following format.
87 // >>> defined in /home/alice/src/foo.o
88 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
89 // >>> /home/alice/src/bar.o:(.text+0x1)
90 static std::string getLocation(InputSectionBase &s, const Symbol &sym,
91 uint64_t off) {
92 std::string msg = getDefinedLocation(sym) + "\n>>> referenced by ";
93 std::string src = s.getSrcMsg(sym, off);
94 if (!src.empty())
95 msg += src + "\n>>> ";
96 return msg + s.getObjMsg(off);
99 void elf::reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v,
100 int64_t min, uint64_t max) {
101 ErrorPlace errPlace = getErrorPlace(loc);
102 std::string hint;
103 if (rel.sym) {
104 if (!rel.sym->isSection())
105 hint = "; references '" + lld::toString(*rel.sym) + '\'';
106 else if (auto *d = dyn_cast<Defined>(rel.sym))
107 hint = ("; references section '" + d->section->name + "'").str();
109 if (config->emachine == EM_X86_64 && rel.type == R_X86_64_PC32 &&
110 rel.sym->getOutputSection() &&
111 (rel.sym->getOutputSection()->flags & SHF_X86_64_LARGE)) {
112 hint += "; R_X86_64_PC32 should not reference a section marked "
113 "SHF_X86_64_LARGE";
116 if (!errPlace.srcLoc.empty())
117 hint += "\n>>> referenced by " + errPlace.srcLoc;
118 if (rel.sym && !rel.sym->isSection())
119 hint += getDefinedLocation(*rel.sym);
121 if (errPlace.isec && errPlace.isec->name.starts_with(".debug"))
122 hint += "; consider recompiling with -fdebug-types-section to reduce size "
123 "of debug sections";
125 errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) +
126 " out of range: " + v.str() + " is not in [" + Twine(min).str() +
127 ", " + Twine(max).str() + "]" + hint);
130 void elf::reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,
131 const Twine &msg) {
132 ErrorPlace errPlace = getErrorPlace(loc);
133 std::string hint;
134 if (!sym.getName().empty())
135 hint =
136 "; references '" + lld::toString(sym) + '\'' + getDefinedLocation(sym);
137 errorOrWarn(errPlace.loc + msg + " is out of range: " + Twine(v) +
138 " is not in [" + Twine(llvm::minIntN(n)) + ", " +
139 Twine(llvm::maxIntN(n)) + "]" + hint);
142 // Build a bitmask with one bit set for each 64 subset of RelExpr.
143 static constexpr uint64_t buildMask() { return 0; }
145 template <typename... Tails>
146 static constexpr uint64_t buildMask(int head, Tails... tails) {
147 return (0 <= head && head < 64 ? uint64_t(1) << head : 0) |
148 buildMask(tails...);
151 // Return true if `Expr` is one of `Exprs`.
152 // There are more than 64 but less than 128 RelExprs, so we divide the set of
153 // exprs into [0, 64) and [64, 128) and represent each range as a constant
154 // 64-bit mask. Then we decide which mask to test depending on the value of
155 // expr and use a simple shift and bitwise-and to test for membership.
156 template <RelExpr... Exprs> static bool oneof(RelExpr expr) {
157 assert(0 <= expr && (int)expr < 128 &&
158 "RelExpr is too large for 128-bit mask!");
160 if (expr >= 64)
161 return (uint64_t(1) << (expr - 64)) & buildMask((Exprs - 64)...);
162 return (uint64_t(1) << expr) & buildMask(Exprs...);
165 static RelType getMipsPairType(RelType type, bool isLocal) {
166 switch (type) {
167 case R_MIPS_HI16:
168 return R_MIPS_LO16;
169 case R_MIPS_GOT16:
170 // In case of global symbol, the R_MIPS_GOT16 relocation does not
171 // have a pair. Each global symbol has a unique entry in the GOT
172 // and a corresponding instruction with help of the R_MIPS_GOT16
173 // relocation loads an address of the symbol. In case of local
174 // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
175 // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
176 // relocations handle low 16 bits of the address. That allows
177 // to allocate only one GOT entry for every 64 KBytes of local data.
178 return isLocal ? R_MIPS_LO16 : R_MIPS_NONE;
179 case R_MICROMIPS_GOT16:
180 return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
181 case R_MIPS_PCHI16:
182 return R_MIPS_PCLO16;
183 case R_MICROMIPS_HI16:
184 return R_MICROMIPS_LO16;
185 default:
186 return R_MIPS_NONE;
190 // True if non-preemptable symbol always has the same value regardless of where
191 // the DSO is loaded.
192 static bool isAbsolute(const Symbol &sym) {
193 if (sym.isUndefWeak())
194 return true;
195 if (const auto *dr = dyn_cast<Defined>(&sym))
196 return dr->section == nullptr; // Absolute symbol.
197 return false;
200 static bool isAbsoluteValue(const Symbol &sym) {
201 return isAbsolute(sym) || sym.isTls();
204 // Returns true if Expr refers a PLT entry.
205 static bool needsPlt(RelExpr expr) {
206 return oneof<R_PLT, R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT, R_GOTPLT_GOTREL,
207 R_GOTPLT_PC, R_LOONGARCH_PLT_PAGE_PC, R_PPC32_PLTREL,
208 R_PPC64_CALL_PLT>(expr);
211 bool lld::elf::needsGot(RelExpr expr) {
212 return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
213 R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT,
214 R_AARCH64_GOT_PAGE, R_LOONGARCH_GOT, R_LOONGARCH_GOT_PAGE_PC>(
215 expr);
218 // True if this expression is of the form Sym - X, where X is a position in the
219 // file (PC, or GOT for example).
220 static bool isRelExpr(RelExpr expr) {
221 return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_ARM_PCA, R_MIPS_GOTREL,
222 R_PPC64_CALL, R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC,
223 R_RELAX_GOT_PC, R_RISCV_PC_INDIRECT, R_PPC64_RELAX_GOT_PC,
224 R_LOONGARCH_PAGE_PC>(expr);
227 static RelExpr toPlt(RelExpr expr) {
228 switch (expr) {
229 case R_LOONGARCH_PAGE_PC:
230 return R_LOONGARCH_PLT_PAGE_PC;
231 case R_PPC64_CALL:
232 return R_PPC64_CALL_PLT;
233 case R_PC:
234 return R_PLT_PC;
235 case R_ABS:
236 return R_PLT;
237 case R_GOTREL:
238 return R_PLT_GOTREL;
239 default:
240 return expr;
244 static RelExpr fromPlt(RelExpr expr) {
245 // We decided not to use a plt. Optimize a reference to the plt to a
246 // reference to the symbol itself.
247 switch (expr) {
248 case R_PLT_PC:
249 case R_PPC32_PLTREL:
250 return R_PC;
251 case R_LOONGARCH_PLT_PAGE_PC:
252 return R_LOONGARCH_PAGE_PC;
253 case R_PPC64_CALL_PLT:
254 return R_PPC64_CALL;
255 case R_PLT:
256 return R_ABS;
257 case R_PLT_GOTPLT:
258 return R_GOTPLTREL;
259 case R_PLT_GOTREL:
260 return R_GOTREL;
261 default:
262 return expr;
266 // Returns true if a given shared symbol is in a read-only segment in a DSO.
267 template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
268 using Elf_Phdr = typename ELFT::Phdr;
270 // Determine if the symbol is read-only by scanning the DSO's program headers.
271 const auto &file = cast<SharedFile>(*ss.file);
272 for (const Elf_Phdr &phdr :
273 check(file.template getObj<ELFT>().program_headers()))
274 if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
275 !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
276 ss.value < phdr.p_vaddr + phdr.p_memsz)
277 return true;
278 return false;
281 // Returns symbols at the same offset as a given symbol, including SS itself.
283 // If two or more symbols are at the same offset, and at least one of
284 // them are copied by a copy relocation, all of them need to be copied.
285 // Otherwise, they would refer to different places at runtime.
286 template <class ELFT>
287 static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) {
288 using Elf_Sym = typename ELFT::Sym;
290 const auto &file = cast<SharedFile>(*ss.file);
292 SmallSet<SharedSymbol *, 4> ret;
293 for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
294 if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
295 s.getType() == STT_TLS || s.st_value != ss.value)
296 continue;
297 StringRef name = check(s.getName(file.getStringTable()));
298 Symbol *sym = symtab.find(name);
299 if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym))
300 ret.insert(alias);
303 // The loop does not check SHT_GNU_verneed, so ret does not contain
304 // non-default version symbols. If ss has a non-default version, ret won't
305 // contain ss. Just add ss unconditionally. If a non-default version alias is
306 // separately copy relocated, it and ss will have different addresses.
307 // Fortunately this case is impractical and fails with GNU ld as well.
308 ret.insert(&ss);
309 return ret;
312 // When a symbol is copy relocated or we create a canonical plt entry, it is
313 // effectively a defined symbol. In the case of copy relocation the symbol is
314 // in .bss and in the case of a canonical plt entry it is in .plt. This function
315 // replaces the existing symbol with a Defined pointing to the appropriate
316 // location.
317 static void replaceWithDefined(Symbol &sym, SectionBase &sec, uint64_t value,
318 uint64_t size) {
319 Symbol old = sym;
320 Defined(sym.file, StringRef(), sym.binding, sym.stOther, sym.type, value,
321 size, &sec)
322 .overwrite(sym);
324 sym.versionId = old.versionId;
325 sym.exportDynamic = true;
326 sym.isUsedInRegularObj = true;
327 // A copy relocated alias may need a GOT entry.
328 sym.flags.store(old.flags.load(std::memory_order_relaxed) & NEEDS_GOT,
329 std::memory_order_relaxed);
332 // Reserve space in .bss or .bss.rel.ro for copy relocation.
334 // The copy relocation is pretty much a hack. If you use a copy relocation
335 // in your program, not only the symbol name but the symbol's size, RW/RO
336 // bit and alignment become part of the ABI. In addition to that, if the
337 // symbol has aliases, the aliases become part of the ABI. That's subtle,
338 // but if you violate that implicit ABI, that can cause very counter-
339 // intuitive consequences.
341 // So, what is the copy relocation? It's for linking non-position
342 // independent code to DSOs. In an ideal world, all references to data
343 // exported by DSOs should go indirectly through GOT. But if object files
344 // are compiled as non-PIC, all data references are direct. There is no
345 // way for the linker to transform the code to use GOT, as machine
346 // instructions are already set in stone in object files. This is where
347 // the copy relocation takes a role.
349 // A copy relocation instructs the dynamic linker to copy data from a DSO
350 // to a specified address (which is usually in .bss) at load-time. If the
351 // static linker (that's us) finds a direct data reference to a DSO
352 // symbol, it creates a copy relocation, so that the symbol can be
353 // resolved as if it were in .bss rather than in a DSO.
355 // As you can see in this function, we create a copy relocation for the
356 // dynamic linker, and the relocation contains not only symbol name but
357 // various other information about the symbol. So, such attributes become a
358 // part of the ABI.
360 // Note for application developers: I can give you a piece of advice if
361 // you are writing a shared library. You probably should export only
362 // functions from your library. You shouldn't export variables.
364 // As an example what can happen when you export variables without knowing
365 // the semantics of copy relocations, assume that you have an exported
366 // variable of type T. It is an ABI-breaking change to add new members at
367 // end of T even though doing that doesn't change the layout of the
368 // existing members. That's because the space for the new members are not
369 // reserved in .bss unless you recompile the main program. That means they
370 // are likely to overlap with other data that happens to be laid out next
371 // to the variable in .bss. This kind of issue is sometimes very hard to
372 // debug. What's a solution? Instead of exporting a variable V from a DSO,
373 // define an accessor getV().
374 template <class ELFT> static void addCopyRelSymbol(SharedSymbol &ss) {
375 // Copy relocation against zero-sized symbol doesn't make sense.
376 uint64_t symSize = ss.getSize();
377 if (symSize == 0 || ss.alignment == 0)
378 fatal("cannot create a copy relocation for symbol " + toString(ss));
380 // See if this symbol is in a read-only segment. If so, preserve the symbol's
381 // memory protection by reserving space in the .bss.rel.ro section.
382 bool isRO = isReadOnly<ELFT>(ss);
383 BssSection *sec =
384 make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment);
385 OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent();
387 // At this point, sectionBases has been migrated to sections. Append sec to
388 // sections.
389 if (osec->commands.empty() ||
390 !isa<InputSectionDescription>(osec->commands.back()))
391 osec->commands.push_back(make<InputSectionDescription>(""));
392 auto *isd = cast<InputSectionDescription>(osec->commands.back());
393 isd->sections.push_back(sec);
394 osec->commitSection(sec);
396 // Look through the DSO's dynamic symbol table for aliases and create a
397 // dynamic symbol for each one. This causes the copy relocation to correctly
398 // interpose any aliases.
399 for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss))
400 replaceWithDefined(*sym, *sec, 0, sym->size);
402 mainPart->relaDyn->addSymbolReloc(target->copyRel, *sec, 0, ss);
405 // .eh_frame sections are mergeable input sections, so their input
406 // offsets are not linearly mapped to output section. For each input
407 // offset, we need to find a section piece containing the offset and
408 // add the piece's base address to the input offset to compute the
409 // output offset. That isn't cheap.
411 // This class is to speed up the offset computation. When we process
412 // relocations, we access offsets in the monotonically increasing
413 // order. So we can optimize for that access pattern.
415 // For sections other than .eh_frame, this class doesn't do anything.
416 namespace {
417 class OffsetGetter {
418 public:
419 OffsetGetter() = default;
420 explicit OffsetGetter(InputSectionBase &sec) {
421 if (auto *eh = dyn_cast<EhInputSection>(&sec)) {
422 cies = eh->cies;
423 fdes = eh->fdes;
424 i = cies.begin();
425 j = fdes.begin();
429 // Translates offsets in input sections to offsets in output sections.
430 // Given offset must increase monotonically. We assume that Piece is
431 // sorted by inputOff.
432 uint64_t get(uint64_t off) {
433 if (cies.empty())
434 return off;
436 while (j != fdes.end() && j->inputOff <= off)
437 ++j;
438 auto it = j;
439 if (j == fdes.begin() || j[-1].inputOff + j[-1].size <= off) {
440 while (i != cies.end() && i->inputOff <= off)
441 ++i;
442 if (i == cies.begin() || i[-1].inputOff + i[-1].size <= off)
443 fatal(".eh_frame: relocation is not in any piece");
444 it = i;
447 // Offset -1 means that the piece is dead (i.e. garbage collected).
448 if (it[-1].outputOff == -1)
449 return -1;
450 return it[-1].outputOff + (off - it[-1].inputOff);
453 private:
454 ArrayRef<EhSectionPiece> cies, fdes;
455 ArrayRef<EhSectionPiece>::iterator i, j;
458 // This class encapsulates states needed to scan relocations for one
459 // InputSectionBase.
460 class RelocationScanner {
461 public:
462 template <class ELFT> void scanSection(InputSectionBase &s);
464 private:
465 InputSectionBase *sec;
466 OffsetGetter getter;
468 // End of relocations, used by Mips/PPC64.
469 const void *end = nullptr;
471 template <class RelTy> RelType getMipsN32RelType(RelTy *&rel) const;
472 template <class ELFT, class RelTy>
473 int64_t computeMipsAddend(const RelTy &rel, RelExpr expr, bool isLocal) const;
474 bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym,
475 uint64_t relOff) const;
476 void processAux(RelExpr expr, RelType type, uint64_t offset, Symbol &sym,
477 int64_t addend) const;
478 template <class ELFT, class RelTy> void scanOne(RelTy *&i);
479 template <class ELFT, class RelTy> void scan(ArrayRef<RelTy> rels);
481 } // namespace
483 // MIPS has an odd notion of "paired" relocations to calculate addends.
484 // For example, if a relocation is of R_MIPS_HI16, there must be a
485 // R_MIPS_LO16 relocation after that, and an addend is calculated using
486 // the two relocations.
487 template <class ELFT, class RelTy>
488 int64_t RelocationScanner::computeMipsAddend(const RelTy &rel, RelExpr expr,
489 bool isLocal) const {
490 if (expr == R_MIPS_GOTREL && isLocal)
491 return sec->getFile<ELFT>()->mipsGp0;
493 // The ABI says that the paired relocation is used only for REL.
494 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
495 // This generalises to relocation types with implicit addends.
496 if (RelTy::HasAddend)
497 return 0;
499 RelType type = rel.getType(config->isMips64EL);
500 uint32_t pairTy = getMipsPairType(type, isLocal);
501 if (pairTy == R_MIPS_NONE)
502 return 0;
504 const uint8_t *buf = sec->content().data();
505 uint32_t symIndex = rel.getSymbol(config->isMips64EL);
507 // To make things worse, paired relocations might not be contiguous in
508 // the relocation table, so we need to do linear search. *sigh*
509 for (const RelTy *ri = &rel; ri != static_cast<const RelTy *>(end); ++ri)
510 if (ri->getType(config->isMips64EL) == pairTy &&
511 ri->getSymbol(config->isMips64EL) == symIndex)
512 return target->getImplicitAddend(buf + ri->r_offset, pairTy);
514 warn("can't find matching " + toString(pairTy) + " relocation for " +
515 toString(type));
516 return 0;
519 // Custom error message if Sym is defined in a discarded section.
520 template <class ELFT>
521 static std::string maybeReportDiscarded(Undefined &sym) {
522 auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file);
523 if (!file || !sym.discardedSecIdx)
524 return "";
525 ArrayRef<typename ELFT::Shdr> objSections =
526 file->template getELFShdrs<ELFT>();
528 std::string msg;
529 if (sym.type == ELF::STT_SECTION) {
530 msg = "relocation refers to a discarded section: ";
531 msg += CHECK(
532 file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file);
533 } else {
534 msg = "relocation refers to a symbol in a discarded section: " +
535 toString(sym);
537 msg += "\n>>> defined in " + toString(file);
539 Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
540 if (elfSec.sh_type != SHT_GROUP)
541 return msg;
543 // If the discarded section is a COMDAT.
544 StringRef signature = file->getShtGroupSignature(objSections, elfSec);
545 if (const InputFile *prevailing =
546 symtab.comdatGroups.lookup(CachedHashStringRef(signature))) {
547 msg += "\n>>> section group signature: " + signature.str() +
548 "\n>>> prevailing definition is in " + toString(prevailing);
549 if (sym.nonPrevailing) {
550 msg += "\n>>> or the symbol in the prevailing group had STB_WEAK "
551 "binding and the symbol in a non-prevailing group had STB_GLOBAL "
552 "binding. Mixing groups with STB_WEAK and STB_GLOBAL binding "
553 "signature is not supported";
556 return msg;
559 namespace {
560 // Undefined diagnostics are collected in a vector and emitted once all of
561 // them are known, so that some postprocessing on the list of undefined symbols
562 // can happen before lld emits diagnostics.
563 struct UndefinedDiag {
564 Undefined *sym;
565 struct Loc {
566 InputSectionBase *sec;
567 uint64_t offset;
569 std::vector<Loc> locs;
570 bool isWarning;
573 std::vector<UndefinedDiag> undefs;
574 std::mutex relocMutex;
577 // Check whether the definition name def is a mangled function name that matches
578 // the reference name ref.
579 static bool canSuggestExternCForCXX(StringRef ref, StringRef def) {
580 llvm::ItaniumPartialDemangler d;
581 std::string name = def.str();
582 if (d.partialDemangle(name.c_str()))
583 return false;
584 char *buf = d.getFunctionName(nullptr, nullptr);
585 if (!buf)
586 return false;
587 bool ret = ref == buf;
588 free(buf);
589 return ret;
592 // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns
593 // the suggested symbol, which is either in the symbol table, or in the same
594 // file of sym.
595 static const Symbol *getAlternativeSpelling(const Undefined &sym,
596 std::string &pre_hint,
597 std::string &post_hint) {
598 DenseMap<StringRef, const Symbol *> map;
599 if (sym.file && sym.file->kind() == InputFile::ObjKind) {
600 auto *file = cast<ELFFileBase>(sym.file);
601 // If sym is a symbol defined in a discarded section, maybeReportDiscarded()
602 // will give an error. Don't suggest an alternative spelling.
603 if (file && sym.discardedSecIdx != 0 &&
604 file->getSections()[sym.discardedSecIdx] == &InputSection::discarded)
605 return nullptr;
607 // Build a map of local defined symbols.
608 for (const Symbol *s : sym.file->getSymbols())
609 if (s->isLocal() && s->isDefined() && !s->getName().empty())
610 map.try_emplace(s->getName(), s);
613 auto suggest = [&](StringRef newName) -> const Symbol * {
614 // If defined locally.
615 if (const Symbol *s = map.lookup(newName))
616 return s;
618 // If in the symbol table and not undefined.
619 if (const Symbol *s = symtab.find(newName))
620 if (!s->isUndefined())
621 return s;
623 return nullptr;
626 // This loop enumerates all strings of Levenshtein distance 1 as typo
627 // correction candidates and suggests the one that exists as a non-undefined
628 // symbol.
629 StringRef name = sym.getName();
630 for (size_t i = 0, e = name.size(); i != e + 1; ++i) {
631 // Insert a character before name[i].
632 std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str();
633 for (char c = '0'; c <= 'z'; ++c) {
634 newName[i] = c;
635 if (const Symbol *s = suggest(newName))
636 return s;
638 if (i == e)
639 break;
641 // Substitute name[i].
642 newName = std::string(name);
643 for (char c = '0'; c <= 'z'; ++c) {
644 newName[i] = c;
645 if (const Symbol *s = suggest(newName))
646 return s;
649 // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is
650 // common.
651 if (i + 1 < e) {
652 newName[i] = name[i + 1];
653 newName[i + 1] = name[i];
654 if (const Symbol *s = suggest(newName))
655 return s;
658 // Delete name[i].
659 newName = (name.substr(0, i) + name.substr(i + 1)).str();
660 if (const Symbol *s = suggest(newName))
661 return s;
664 // Case mismatch, e.g. Foo vs FOO.
665 for (auto &it : map)
666 if (name.equals_insensitive(it.first))
667 return it.second;
668 for (Symbol *sym : symtab.getSymbols())
669 if (!sym->isUndefined() && name.equals_insensitive(sym->getName()))
670 return sym;
672 // The reference may be a mangled name while the definition is not. Suggest a
673 // missing extern "C".
674 if (name.starts_with("_Z")) {
675 std::string buf = name.str();
676 llvm::ItaniumPartialDemangler d;
677 if (!d.partialDemangle(buf.c_str()))
678 if (char *buf = d.getFunctionName(nullptr, nullptr)) {
679 const Symbol *s = suggest(buf);
680 free(buf);
681 if (s) {
682 pre_hint = ": extern \"C\" ";
683 return s;
686 } else {
687 const Symbol *s = nullptr;
688 for (auto &it : map)
689 if (canSuggestExternCForCXX(name, it.first)) {
690 s = it.second;
691 break;
693 if (!s)
694 for (Symbol *sym : symtab.getSymbols())
695 if (canSuggestExternCForCXX(name, sym->getName())) {
696 s = sym;
697 break;
699 if (s) {
700 pre_hint = " to declare ";
701 post_hint = " as extern \"C\"?";
702 return s;
706 return nullptr;
709 static void reportUndefinedSymbol(const UndefinedDiag &undef,
710 bool correctSpelling) {
711 Undefined &sym = *undef.sym;
713 auto visibility = [&]() -> std::string {
714 switch (sym.visibility()) {
715 case STV_INTERNAL:
716 return "internal ";
717 case STV_HIDDEN:
718 return "hidden ";
719 case STV_PROTECTED:
720 return "protected ";
721 default:
722 return "";
726 std::string msg;
727 switch (config->ekind) {
728 case ELF32LEKind:
729 msg = maybeReportDiscarded<ELF32LE>(sym);
730 break;
731 case ELF32BEKind:
732 msg = maybeReportDiscarded<ELF32BE>(sym);
733 break;
734 case ELF64LEKind:
735 msg = maybeReportDiscarded<ELF64LE>(sym);
736 break;
737 case ELF64BEKind:
738 msg = maybeReportDiscarded<ELF64BE>(sym);
739 break;
740 default:
741 llvm_unreachable("");
743 if (msg.empty())
744 msg = "undefined " + visibility() + "symbol: " + toString(sym);
746 const size_t maxUndefReferences = 3;
747 size_t i = 0;
748 for (UndefinedDiag::Loc l : undef.locs) {
749 if (i >= maxUndefReferences)
750 break;
751 InputSectionBase &sec = *l.sec;
752 uint64_t offset = l.offset;
754 msg += "\n>>> referenced by ";
755 // In the absence of line number information, utilize DW_TAG_variable (if
756 // present) for the enclosing symbol (e.g. var in `int *a[] = {&undef};`).
757 Symbol *enclosing = sec.getEnclosingSymbol(offset);
758 std::string src = sec.getSrcMsg(enclosing ? *enclosing : sym, offset);
759 if (!src.empty())
760 msg += src + "\n>>> ";
761 msg += sec.getObjMsg(offset);
762 i++;
765 if (i < undef.locs.size())
766 msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times")
767 .str();
769 if (correctSpelling) {
770 std::string pre_hint = ": ", post_hint;
771 if (const Symbol *corrected =
772 getAlternativeSpelling(sym, pre_hint, post_hint)) {
773 msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint;
774 if (corrected->file)
775 msg += "\n>>> defined in: " + toString(corrected->file);
779 if (sym.getName().starts_with("_ZTV"))
780 msg +=
781 "\n>>> the vtable symbol may be undefined because the class is missing "
782 "its key function (see https://lld.llvm.org/missingkeyfunction)";
783 if (config->gcSections && config->zStartStopGC &&
784 sym.getName().starts_with("__start_")) {
785 msg += "\n>>> the encapsulation symbol needs to be retained under "
786 "--gc-sections properly; consider -z nostart-stop-gc "
787 "(see https://lld.llvm.org/ELF/start-stop-gc)";
790 if (undef.isWarning)
791 warn(msg);
792 else
793 error(msg, ErrorTag::SymbolNotFound, {sym.getName()});
796 void elf::reportUndefinedSymbols() {
797 // Find the first "undefined symbol" diagnostic for each diagnostic, and
798 // collect all "referenced from" lines at the first diagnostic.
799 DenseMap<Symbol *, UndefinedDiag *> firstRef;
800 for (UndefinedDiag &undef : undefs) {
801 assert(undef.locs.size() == 1);
802 if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) {
803 canon->locs.push_back(undef.locs[0]);
804 undef.locs.clear();
805 } else
806 firstRef[undef.sym] = &undef;
809 // Enable spell corrector for the first 2 diagnostics.
810 for (const auto &[i, undef] : llvm::enumerate(undefs))
811 if (!undef.locs.empty())
812 reportUndefinedSymbol(undef, i < 2);
813 undefs.clear();
816 // Report an undefined symbol if necessary.
817 // Returns true if the undefined symbol will produce an error message.
818 static bool maybeReportUndefined(Undefined &sym, InputSectionBase &sec,
819 uint64_t offset) {
820 std::lock_guard<std::mutex> lock(relocMutex);
821 // If versioned, issue an error (even if the symbol is weak) because we don't
822 // know the defining filename which is required to construct a Verneed entry.
823 if (sym.hasVersionSuffix) {
824 undefs.push_back({&sym, {{&sec, offset}}, false});
825 return true;
827 if (sym.isWeak())
828 return false;
830 bool canBeExternal = !sym.isLocal() && sym.visibility() == STV_DEFAULT;
831 if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
832 return false;
834 // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
835 // which references a switch table in a discarded .rodata/.text section. The
836 // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
837 // spec says references from outside the group to a STB_LOCAL symbol are not
838 // allowed. Work around the bug.
840 // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible
841 // because .LC0-.LTOC is not representable if the two labels are in different
842 // .got2
843 if (sym.discardedSecIdx != 0 && (sec.name == ".got2" || sec.name == ".toc"))
844 return false;
846 bool isWarning =
847 (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
848 config->noinhibitExec;
849 undefs.push_back({&sym, {{&sec, offset}}, isWarning});
850 return !isWarning;
853 // MIPS N32 ABI treats series of successive relocations with the same offset
854 // as a single relocation. The similar approach used by N64 ABI, but this ABI
855 // packs all relocations into the single relocation record. Here we emulate
856 // this for the N32 ABI. Iterate over relocation with the same offset and put
857 // theirs types into the single bit-set.
858 template <class RelTy>
859 RelType RelocationScanner::getMipsN32RelType(RelTy *&rel) const {
860 RelType type = 0;
861 uint64_t offset = rel->r_offset;
863 int n = 0;
864 while (rel != static_cast<const RelTy *>(end) && rel->r_offset == offset)
865 type |= (rel++)->getType(config->isMips64EL) << (8 * n++);
866 return type;
869 template <bool shard = false>
870 static void addRelativeReloc(InputSectionBase &isec, uint64_t offsetInSec,
871 Symbol &sym, int64_t addend, RelExpr expr,
872 RelType type) {
873 Partition &part = isec.getPartition();
875 if (sym.isTagged()) {
876 std::lock_guard<std::mutex> lock(relocMutex);
877 part.relaDyn->addRelativeReloc(target->relativeRel, isec, offsetInSec, sym,
878 addend, type, expr);
879 // With MTE globals, we always want to derive the address tag by `ldg`-ing
880 // the symbol. When we have a RELATIVE relocation though, we no longer have
881 // a reference to the symbol. Because of this, when we have an addend that
882 // puts the result of the RELATIVE relocation out-of-bounds of the symbol
883 // (e.g. the addend is outside of [0, sym.getSize()]), the AArch64 MemtagABI
884 // says we should store the offset to the start of the symbol in the target
885 // field. This is described in further detail in:
886 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#841extended-semantics-of-r_aarch64_relative
887 if (addend < 0 || static_cast<uint64_t>(addend) >= sym.getSize())
888 isec.relocations.push_back({expr, type, offsetInSec, addend, &sym});
889 return;
892 // Add a relative relocation. If relrDyn section is enabled, and the
893 // relocation offset is guaranteed to be even, add the relocation to
894 // the relrDyn section, otherwise add it to the relaDyn section.
895 // relrDyn sections don't support odd offsets. Also, relrDyn sections
896 // don't store the addend values, so we must write it to the relocated
897 // address.
898 if (part.relrDyn && isec.addralign >= 2 && offsetInSec % 2 == 0) {
899 isec.addReloc({expr, type, offsetInSec, addend, &sym});
900 if (shard)
901 part.relrDyn->relocsVec[parallel::getThreadIndex()].push_back(
902 {&isec, isec.relocs().size() - 1});
903 else
904 part.relrDyn->relocs.push_back({&isec, isec.relocs().size() - 1});
905 return;
907 part.relaDyn->addRelativeReloc<shard>(target->relativeRel, isec, offsetInSec,
908 sym, addend, type, expr);
911 template <class PltSection, class GotPltSection>
912 static void addPltEntry(PltSection &plt, GotPltSection &gotPlt,
913 RelocationBaseSection &rel, RelType type, Symbol &sym) {
914 plt.addEntry(sym);
915 gotPlt.addEntry(sym);
916 rel.addReloc({type, &gotPlt, sym.getGotPltOffset(),
917 sym.isPreemptible ? DynamicReloc::AgainstSymbol
918 : DynamicReloc::AddendOnlyWithTargetVA,
919 sym, 0, R_ABS});
922 void elf::addGotEntry(Symbol &sym) {
923 in.got->addEntry(sym);
924 uint64_t off = sym.getGotOffset();
926 // If preemptible, emit a GLOB_DAT relocation.
927 if (sym.isPreemptible) {
928 mainPart->relaDyn->addReloc({target->gotRel, in.got.get(), off,
929 DynamicReloc::AgainstSymbol, sym, 0, R_ABS});
930 return;
933 // Otherwise, the value is either a link-time constant or the load base
934 // plus a constant.
935 if (!config->isPic || isAbsolute(sym))
936 in.got->addConstant({R_ABS, target->symbolicRel, off, 0, &sym});
937 else
938 addRelativeReloc(*in.got, off, sym, 0, R_ABS, target->symbolicRel);
941 static void addTpOffsetGotEntry(Symbol &sym) {
942 in.got->addEntry(sym);
943 uint64_t off = sym.getGotOffset();
944 if (!sym.isPreemptible && !config->shared) {
945 in.got->addConstant({R_TPREL, target->symbolicRel, off, 0, &sym});
946 return;
948 mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
949 target->tlsGotRel, *in.got, off, sym, target->symbolicRel);
952 // Return true if we can define a symbol in the executable that
953 // contains the value/function of a symbol defined in a shared
954 // library.
955 static bool canDefineSymbolInExecutable(Symbol &sym) {
956 // If the symbol has default visibility the symbol defined in the
957 // executable will preempt it.
958 // Note that we want the visibility of the shared symbol itself, not
959 // the visibility of the symbol in the output file we are producing.
960 if (!sym.dsoProtected)
961 return true;
963 // If we are allowed to break address equality of functions, defining
964 // a plt entry will allow the program to call the function in the
965 // .so, but the .so and the executable will no agree on the address
966 // of the function. Similar logic for objects.
967 return ((sym.isFunc() && config->ignoreFunctionAddressEquality) ||
968 (sym.isObject() && config->ignoreDataAddressEquality));
971 // Returns true if a given relocation can be computed at link-time.
972 // This only handles relocation types expected in processAux.
974 // For instance, we know the offset from a relocation to its target at
975 // link-time if the relocation is PC-relative and refers a
976 // non-interposable function in the same executable. This function
977 // will return true for such relocation.
979 // If this function returns false, that means we need to emit a
980 // dynamic relocation so that the relocation will be fixed at load-time.
981 bool RelocationScanner::isStaticLinkTimeConstant(RelExpr e, RelType type,
982 const Symbol &sym,
983 uint64_t relOff) const {
984 // These expressions always compute a constant
985 if (oneof<R_GOTPLT, R_GOT_OFF, R_RELAX_HINT, R_MIPS_GOT_LOCAL_PAGE,
986 R_MIPS_GOTREL, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
987 R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
988 R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT, R_GOTPLT_GOTREL, R_GOTPLT_PC,
989 R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PPC64_RELAX_TOC, R_RISCV_ADD,
990 R_AARCH64_GOT_PAGE, R_LOONGARCH_PLT_PAGE_PC, R_LOONGARCH_GOT,
991 R_LOONGARCH_GOT_PAGE_PC>(e))
992 return true;
994 // These never do, except if the entire file is position dependent or if
995 // only the low bits are used.
996 if (e == R_GOT || e == R_PLT)
997 return target->usesOnlyLowPageBits(type) || !config->isPic;
999 // R_AARCH64_AUTH_ABS64 requires a dynamic relocation.
1000 if (sym.isPreemptible || e == R_AARCH64_AUTH)
1001 return false;
1002 if (!config->isPic)
1003 return true;
1005 // Constant when referencing a non-preemptible symbol.
1006 if (e == R_SIZE || e == R_RISCV_LEB128)
1007 return true;
1009 // For the target and the relocation, we want to know if they are
1010 // absolute or relative.
1011 bool absVal = isAbsoluteValue(sym);
1012 bool relE = isRelExpr(e);
1013 if (absVal && !relE)
1014 return true;
1015 if (!absVal && relE)
1016 return true;
1017 if (!absVal && !relE)
1018 return target->usesOnlyLowPageBits(type);
1020 assert(absVal && relE);
1022 // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol
1023 // in PIC mode. This is a little strange, but it allows us to link function
1024 // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers).
1025 // Normally such a call will be guarded with a comparison, which will load a
1026 // zero from the GOT.
1027 if (sym.isUndefWeak())
1028 return true;
1030 // We set the final symbols values for linker script defined symbols later.
1031 // They always can be computed as a link time constant.
1032 if (sym.scriptDefined)
1033 return true;
1035 error("relocation " + toString(type) + " cannot refer to absolute symbol: " +
1036 toString(sym) + getLocation(*sec, sym, relOff));
1037 return true;
1040 // The reason we have to do this early scan is as follows
1041 // * To mmap the output file, we need to know the size
1042 // * For that, we need to know how many dynamic relocs we will have.
1043 // It might be possible to avoid this by outputting the file with write:
1044 // * Write the allocated output sections, computing addresses.
1045 // * Apply relocations, recording which ones require a dynamic reloc.
1046 // * Write the dynamic relocations.
1047 // * Write the rest of the file.
1048 // This would have some drawbacks. For example, we would only know if .rela.dyn
1049 // is needed after applying relocations. If it is, it will go after rw and rx
1050 // sections. Given that it is ro, we will need an extra PT_LOAD. This
1051 // complicates things for the dynamic linker and means we would have to reserve
1052 // space for the extra PT_LOAD even if we end up not using it.
1053 void RelocationScanner::processAux(RelExpr expr, RelType type, uint64_t offset,
1054 Symbol &sym, int64_t addend) const {
1055 // If non-ifunc non-preemptible, change PLT to direct call and optimize GOT
1056 // indirection.
1057 const bool isIfunc = sym.isGnuIFunc();
1058 if (!sym.isPreemptible && (!isIfunc || config->zIfuncNoplt)) {
1059 if (expr != R_GOT_PC) {
1060 // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call
1061 // stub type. It should be ignored if optimized to R_PC.
1062 if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL)
1063 addend &= ~0x8000;
1064 // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into
1065 // call __tls_get_addr even if the symbol is non-preemptible.
1066 if (!(config->emachine == EM_HEXAGON &&
1067 (type == R_HEX_GD_PLT_B22_PCREL ||
1068 type == R_HEX_GD_PLT_B22_PCREL_X ||
1069 type == R_HEX_GD_PLT_B32_PCREL_X)))
1070 expr = fromPlt(expr);
1071 } else if (!isAbsoluteValue(sym)) {
1072 expr =
1073 target->adjustGotPcExpr(type, addend, sec->content().data() + offset);
1074 // If the target adjusted the expression to R_RELAX_GOT_PC, we may end up
1075 // needing the GOT if we can't relax everything.
1076 if (expr == R_RELAX_GOT_PC)
1077 in.got->hasGotOffRel.store(true, std::memory_order_relaxed);
1081 // We were asked not to generate PLT entries for ifuncs. Instead, pass the
1082 // direct relocation on through.
1083 if (LLVM_UNLIKELY(isIfunc) && config->zIfuncNoplt) {
1084 std::lock_guard<std::mutex> lock(relocMutex);
1085 sym.exportDynamic = true;
1086 mainPart->relaDyn->addSymbolReloc(type, *sec, offset, sym, addend, type);
1087 return;
1090 if (needsGot(expr)) {
1091 if (config->emachine == EM_MIPS) {
1092 // MIPS ABI has special rules to process GOT entries and doesn't
1093 // require relocation entries for them. A special case is TLS
1094 // relocations. In that case dynamic loader applies dynamic
1095 // relocations to initialize TLS GOT entries.
1096 // See "Global Offset Table" in Chapter 5 in the following document
1097 // for detailed description:
1098 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1099 in.mipsGot->addEntry(*sec->file, sym, addend, expr);
1100 } else if (!sym.isTls() || config->emachine != EM_LOONGARCH) {
1101 // Many LoongArch TLS relocs reuse the R_LOONGARCH_GOT type, in which
1102 // case the NEEDS_GOT flag shouldn't get set.
1103 sym.setFlags(NEEDS_GOT);
1105 } else if (needsPlt(expr)) {
1106 sym.setFlags(NEEDS_PLT);
1107 } else if (LLVM_UNLIKELY(isIfunc)) {
1108 sym.setFlags(HAS_DIRECT_RELOC);
1111 // If the relocation is known to be a link-time constant, we know no dynamic
1112 // relocation will be created, pass the control to relocateAlloc() or
1113 // relocateNonAlloc() to resolve it.
1115 // The behavior of an undefined weak reference is implementation defined. For
1116 // non-link-time constants, we resolve relocations statically (let
1117 // relocate{,Non}Alloc() resolve them) for -no-pie and try producing dynamic
1118 // relocations for -pie and -shared.
1120 // The general expectation of -no-pie static linking is that there is no
1121 // dynamic relocation (except IRELATIVE). Emitting dynamic relocations for
1122 // -shared matches the spirit of its -z undefs default. -pie has freedom on
1123 // choices, and we choose dynamic relocations to be consistent with the
1124 // handling of GOT-generating relocations.
1125 if (isStaticLinkTimeConstant(expr, type, sym, offset) ||
1126 (!config->isPic && sym.isUndefWeak())) {
1127 sec->addReloc({expr, type, offset, addend, &sym});
1128 return;
1131 // Use a simple -z notext rule that treats all sections except .eh_frame as
1132 // writable. GNU ld does not produce dynamic relocations in .eh_frame (and our
1133 // SectionBase::getOffset would incorrectly adjust the offset).
1135 // For MIPS, we don't implement GNU ld's DW_EH_PE_absptr to DW_EH_PE_pcrel
1136 // conversion. We still emit a dynamic relocation.
1137 bool canWrite = (sec->flags & SHF_WRITE) ||
1138 !(config->zText ||
1139 (isa<EhInputSection>(sec) && config->emachine != EM_MIPS));
1140 if (canWrite) {
1141 RelType rel = target->getDynRel(type);
1142 if (oneof<R_GOT, R_LOONGARCH_GOT>(expr) ||
1143 (rel == target->symbolicRel && !sym.isPreemptible)) {
1144 addRelativeReloc<true>(*sec, offset, sym, addend, expr, type);
1145 return;
1147 if (rel != 0) {
1148 if (config->emachine == EM_MIPS && rel == target->symbolicRel)
1149 rel = target->relativeRel;
1150 std::lock_guard<std::mutex> lock(relocMutex);
1151 Partition &part = sec->getPartition();
1152 if (config->emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64) {
1153 // For a preemptible symbol, we can't use a relative relocation. For an
1154 // undefined symbol, we can't compute offset at link-time and use a
1155 // relative relocation. Use a symbolic relocation instead.
1156 if (sym.isPreemptible) {
1157 part.relaDyn->addSymbolReloc(type, *sec, offset, sym, addend, type);
1158 } else if (part.relrAuthDyn && sec->addralign >= 2 && offset % 2 == 0) {
1159 // When symbol values are determined in
1160 // finalizeAddressDependentContent, some .relr.auth.dyn relocations
1161 // may be moved to .rela.dyn.
1162 sec->addReloc({expr, type, offset, addend, &sym});
1163 part.relrAuthDyn->relocs.push_back({sec, sec->relocs().size() - 1});
1164 } else {
1165 part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, sec, offset,
1166 DynamicReloc::AddendOnlyWithTargetVA, sym,
1167 addend, R_ABS});
1169 return;
1171 part.relaDyn->addSymbolReloc(rel, *sec, offset, sym, addend, type);
1173 // MIPS ABI turns using of GOT and dynamic relocations inside out.
1174 // While regular ABI uses dynamic relocations to fill up GOT entries
1175 // MIPS ABI requires dynamic linker to fills up GOT entries using
1176 // specially sorted dynamic symbol table. This affects even dynamic
1177 // relocations against symbols which do not require GOT entries
1178 // creation explicitly, i.e. do not have any GOT-relocations. So if
1179 // a preemptible symbol has a dynamic relocation we anyway have
1180 // to create a GOT entry for it.
1181 // If a non-preemptible symbol has a dynamic relocation against it,
1182 // dynamic linker takes it st_value, adds offset and writes down
1183 // result of the dynamic relocation. In case of preemptible symbol
1184 // dynamic linker performs symbol resolution, writes the symbol value
1185 // to the GOT entry and reads the GOT entry when it needs to perform
1186 // a dynamic relocation.
1187 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
1188 if (config->emachine == EM_MIPS)
1189 in.mipsGot->addEntry(*sec->file, sym, addend, expr);
1190 return;
1194 // When producing an executable, we can perform copy relocations (for
1195 // STT_OBJECT) and canonical PLT (for STT_FUNC) if sym is defined by a DSO.
1196 // Copy relocations/canonical PLT entries are unsupported for
1197 // R_AARCH64_AUTH_ABS64.
1198 if (!config->shared && sym.isShared() &&
1199 !(config->emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64)) {
1200 if (!canDefineSymbolInExecutable(sym)) {
1201 errorOrWarn("cannot preempt symbol: " + toString(sym) +
1202 getLocation(*sec, sym, offset));
1203 return;
1206 if (sym.isObject()) {
1207 // Produce a copy relocation.
1208 if (auto *ss = dyn_cast<SharedSymbol>(&sym)) {
1209 if (!config->zCopyreloc)
1210 error("unresolvable relocation " + toString(type) +
1211 " against symbol '" + toString(*ss) +
1212 "'; recompile with -fPIC or remove '-z nocopyreloc'" +
1213 getLocation(*sec, sym, offset));
1214 sym.setFlags(NEEDS_COPY);
1216 sec->addReloc({expr, type, offset, addend, &sym});
1217 return;
1220 // This handles a non PIC program call to function in a shared library. In
1221 // an ideal world, we could just report an error saying the relocation can
1222 // overflow at runtime. In the real world with glibc, crt1.o has a
1223 // R_X86_64_PC32 pointing to libc.so.
1225 // The general idea on how to handle such cases is to create a PLT entry and
1226 // use that as the function value.
1228 // For the static linking part, we just return a plt expr and everything
1229 // else will use the PLT entry as the address.
1231 // The remaining problem is making sure pointer equality still works. We
1232 // need the help of the dynamic linker for that. We let it know that we have
1233 // a direct reference to a so symbol by creating an undefined symbol with a
1234 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
1235 // the value of the symbol we created. This is true even for got entries, so
1236 // pointer equality is maintained. To avoid an infinite loop, the only entry
1237 // that points to the real function is a dedicated got entry used by the
1238 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
1239 // R_386_JMP_SLOT, etc).
1241 // For position independent executable on i386, the plt entry requires ebx
1242 // to be set. This causes two problems:
1243 // * If some code has a direct reference to a function, it was probably
1244 // compiled without -fPIE/-fPIC and doesn't maintain ebx.
1245 // * If a library definition gets preempted to the executable, it will have
1246 // the wrong ebx value.
1247 if (sym.isFunc()) {
1248 if (config->pie && config->emachine == EM_386)
1249 errorOrWarn("symbol '" + toString(sym) +
1250 "' cannot be preempted; recompile with -fPIE" +
1251 getLocation(*sec, sym, offset));
1252 sym.setFlags(NEEDS_COPY | NEEDS_PLT);
1253 sec->addReloc({expr, type, offset, addend, &sym});
1254 return;
1258 errorOrWarn("relocation " + toString(type) + " cannot be used against " +
1259 (sym.getName().empty() ? "local symbol"
1260 : "symbol '" + toString(sym) + "'") +
1261 "; recompile with -fPIC" + getLocation(*sec, sym, offset));
1264 // This function is similar to the `handleTlsRelocation`. MIPS does not
1265 // support any relaxations for TLS relocations so by factoring out MIPS
1266 // handling in to the separate function we can simplify the code and do not
1267 // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
1268 // Mips has a custom MipsGotSection that handles the writing of GOT entries
1269 // without dynamic relocations.
1270 static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym,
1271 InputSectionBase &c, uint64_t offset,
1272 int64_t addend, RelExpr expr) {
1273 if (expr == R_MIPS_TLSLD) {
1274 in.mipsGot->addTlsIndex(*c.file);
1275 c.addReloc({expr, type, offset, addend, &sym});
1276 return 1;
1278 if (expr == R_MIPS_TLSGD) {
1279 in.mipsGot->addDynTlsEntry(*c.file, sym);
1280 c.addReloc({expr, type, offset, addend, &sym});
1281 return 1;
1283 return 0;
1286 // Notes about General Dynamic and Local Dynamic TLS models below. They may
1287 // require the generation of a pair of GOT entries that have associated dynamic
1288 // relocations. The pair of GOT entries created are of the form GOT[e0] Module
1289 // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of
1290 // symbol in TLS block.
1292 // Returns the number of relocations processed.
1293 static unsigned handleTlsRelocation(RelType type, Symbol &sym,
1294 InputSectionBase &c, uint64_t offset,
1295 int64_t addend, RelExpr expr) {
1296 if (expr == R_TPREL || expr == R_TPREL_NEG) {
1297 if (config->shared) {
1298 errorOrWarn("relocation " + toString(type) + " against " + toString(sym) +
1299 " cannot be used with -shared" + getLocation(c, sym, offset));
1300 return 1;
1302 return 0;
1305 if (config->emachine == EM_MIPS)
1306 return handleMipsTlsRelocation(type, sym, c, offset, addend, expr);
1308 // LoongArch does not yet implement transition from TLSDESC to LE/IE, so
1309 // generate TLSDESC dynamic relocation for the dynamic linker to handle.
1310 if (config->emachine == EM_LOONGARCH &&
1311 oneof<R_LOONGARCH_TLSDESC_PAGE_PC, R_TLSDESC, R_TLSDESC_CALL>(expr)) {
1312 if (expr != R_TLSDESC_CALL) {
1313 sym.setFlags(NEEDS_TLSDESC);
1314 c.addReloc({expr, type, offset, addend, &sym});
1316 return 1;
1319 bool isRISCV = config->emachine == EM_RISCV;
1321 if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1322 R_TLSDESC_GOTPLT>(expr) &&
1323 config->shared) {
1324 // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} reference a label. Do not
1325 // set NEEDS_TLSDESC on the label.
1326 if (expr != R_TLSDESC_CALL) {
1327 if (!isRISCV || type == R_RISCV_TLSDESC_HI20)
1328 sym.setFlags(NEEDS_TLSDESC);
1329 c.addReloc({expr, type, offset, addend, &sym});
1331 return 1;
1334 // ARM, Hexagon, LoongArch and RISC-V do not support GD/LD to IE/LE
1335 // optimizations.
1336 // RISC-V supports TLSDESC to IE/LE optimizations.
1337 // For PPC64, if the file has missing R_PPC64_TLSGD/R_PPC64_TLSLD, disable
1338 // optimization as well.
1339 bool execOptimize =
1340 !config->shared && config->emachine != EM_ARM &&
1341 config->emachine != EM_HEXAGON && config->emachine != EM_LOONGARCH &&
1342 !(isRISCV && expr != R_TLSDESC_PC && expr != R_TLSDESC_CALL) &&
1343 !c.file->ppc64DisableTLSRelax;
1345 // If we are producing an executable and the symbol is non-preemptable, it
1346 // must be defined and the code sequence can be optimized to use Local-Exec.
1348 // ARM and RISC-V do not support any relaxations for TLS relocations, however,
1349 // we can omit the DTPMOD dynamic relocations and resolve them at link time
1350 // because them are always 1. This may be necessary for static linking as
1351 // DTPMOD may not be expected at load time.
1352 bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1354 // Local Dynamic is for access to module local TLS variables, while still
1355 // being suitable for being dynamically loaded via dlopen. GOT[e0] is the
1356 // module index, with a special value of 0 for the current module. GOT[e1] is
1357 // unused. There only needs to be one module index entry.
1358 if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(expr)) {
1359 // Local-Dynamic relocs can be optimized to Local-Exec.
1360 if (execOptimize) {
1361 c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE), type,
1362 offset, addend, &sym});
1363 return target->getTlsGdRelaxSkip(type);
1365 if (expr == R_TLSLD_HINT)
1366 return 1;
1367 ctx.needsTlsLd.store(true, std::memory_order_relaxed);
1368 c.addReloc({expr, type, offset, addend, &sym});
1369 return 1;
1372 // Local-Dynamic relocs can be optimized to Local-Exec.
1373 if (expr == R_DTPREL) {
1374 if (execOptimize)
1375 expr = target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE);
1376 c.addReloc({expr, type, offset, addend, &sym});
1377 return 1;
1380 // Local-Dynamic sequence where offset of tls variable relative to dynamic
1381 // thread pointer is stored in the got. This cannot be optimized to
1382 // Local-Exec.
1383 if (expr == R_TLSLD_GOT_OFF) {
1384 sym.setFlags(NEEDS_GOT_DTPREL);
1385 c.addReloc({expr, type, offset, addend, &sym});
1386 return 1;
1389 if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1390 R_TLSDESC_GOTPLT, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC,
1391 R_LOONGARCH_TLSGD_PAGE_PC>(expr)) {
1392 if (!execOptimize) {
1393 sym.setFlags(NEEDS_TLSGD);
1394 c.addReloc({expr, type, offset, addend, &sym});
1395 return 1;
1398 // Global-Dynamic/TLSDESC can be optimized to Initial-Exec or Local-Exec
1399 // depending on the symbol being locally defined or not.
1401 // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} reference a non-preemptible
1402 // label, so the LE optimization will be categorized as
1403 // R_RELAX_TLS_GD_TO_LE. We fix the categorization in RISCV::relocateAlloc.
1404 if (sym.isPreemptible) {
1405 sym.setFlags(NEEDS_TLSGD_TO_IE);
1406 c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_IE), type,
1407 offset, addend, &sym});
1408 } else {
1409 c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_LE), type,
1410 offset, addend, &sym});
1412 return target->getTlsGdRelaxSkip(type);
1415 if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC,
1416 R_LOONGARCH_GOT_PAGE_PC, R_GOT_OFF, R_TLSIE_HINT>(expr)) {
1417 ctx.hasTlsIe.store(true, std::memory_order_relaxed);
1418 // Initial-Exec relocs can be optimized to Local-Exec if the symbol is
1419 // locally defined. This is not supported on SystemZ.
1420 if (execOptimize && isLocalInExecutable && config->emachine != EM_S390) {
1421 c.addReloc({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym});
1422 } else if (expr != R_TLSIE_HINT) {
1423 sym.setFlags(NEEDS_TLSIE);
1424 // R_GOT needs a relative relocation for PIC on i386 and Hexagon.
1425 if (expr == R_GOT && config->isPic && !target->usesOnlyLowPageBits(type))
1426 addRelativeReloc<true>(c, offset, sym, addend, expr, type);
1427 else
1428 c.addReloc({expr, type, offset, addend, &sym});
1430 return 1;
1433 return 0;
1436 template <class ELFT, class RelTy> void RelocationScanner::scanOne(RelTy *&i) {
1437 const RelTy &rel = *i;
1438 uint32_t symIndex = rel.getSymbol(config->isMips64EL);
1439 Symbol &sym = sec->getFile<ELFT>()->getSymbol(symIndex);
1440 RelType type;
1441 if constexpr (ELFT::Is64Bits) {
1442 type = rel.getType(config->isMips64EL);
1443 ++i;
1444 } else {
1445 if (config->mipsN32Abi) {
1446 type = getMipsN32RelType(i);
1447 } else {
1448 type = rel.getType(config->isMips64EL);
1449 ++i;
1452 // Get an offset in an output section this relocation is applied to.
1453 uint64_t offset = getter.get(rel.r_offset);
1454 if (offset == uint64_t(-1))
1455 return;
1457 RelExpr expr = target->getRelExpr(type, sym, sec->content().data() + offset);
1458 int64_t addend = RelTy::HasAddend
1459 ? getAddend<ELFT>(rel)
1460 : target->getImplicitAddend(
1461 sec->content().data() + rel.r_offset, type);
1462 if (LLVM_UNLIKELY(config->emachine == EM_MIPS))
1463 addend += computeMipsAddend<ELFT>(rel, expr, sym.isLocal());
1464 else if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC)
1465 addend += getPPC64TocBase();
1467 // Ignore R_*_NONE and other marker relocations.
1468 if (expr == R_NONE)
1469 return;
1471 // Error if the target symbol is undefined. Symbol index 0 may be used by
1472 // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1473 if (sym.isUndefined() && symIndex != 0 &&
1474 maybeReportUndefined(cast<Undefined>(sym), *sec, offset))
1475 return;
1477 if (config->emachine == EM_PPC64) {
1478 // We can separate the small code model relocations into 2 categories:
1479 // 1) Those that access the compiler generated .toc sections.
1480 // 2) Those that access the linker allocated got entries.
1481 // lld allocates got entries to symbols on demand. Since we don't try to
1482 // sort the got entries in any way, we don't have to track which objects
1483 // have got-based small code model relocs. The .toc sections get placed
1484 // after the end of the linker allocated .got section and we do sort those
1485 // so sections addressed with small code model relocations come first.
1486 if (type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS)
1487 sec->file->ppc64SmallCodeModelTocRelocs = true;
1489 // Record the TOC entry (.toc + addend) as not relaxable. See the comment in
1490 // InputSectionBase::relocateAlloc().
1491 if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) &&
1492 cast<Defined>(sym).section->name == ".toc")
1493 ppc64noTocRelax.insert({&sym, addend});
1495 if ((type == R_PPC64_TLSGD && expr == R_TLSDESC_CALL) ||
1496 (type == R_PPC64_TLSLD && expr == R_TLSLD_HINT)) {
1497 if (i == end) {
1498 errorOrWarn("R_PPC64_TLSGD/R_PPC64_TLSLD may not be the last "
1499 "relocation" +
1500 getLocation(*sec, sym, offset));
1501 return;
1504 // Offset the 4-byte aligned R_PPC64_TLSGD by one byte in the NOTOC case,
1505 // so we can discern it later from the toc-case.
1506 if (i->getType(/*isMips64EL=*/false) == R_PPC64_REL24_NOTOC)
1507 ++offset;
1511 // If the relocation does not emit a GOT or GOTPLT entry but its computation
1512 // uses their addresses, we need GOT or GOTPLT to be created.
1514 // The 5 types that relative GOTPLT are all x86 and x86-64 specific.
1515 if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_PLT_GOTPLT,
1516 R_TLSDESC_GOTPLT, R_TLSGD_GOTPLT>(expr)) {
1517 in.gotPlt->hasGotPltOffRel.store(true, std::memory_order_relaxed);
1518 } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC32_PLTREL, R_PPC64_TOCBASE,
1519 R_PPC64_RELAX_TOC>(expr)) {
1520 in.got->hasGotOffRel.store(true, std::memory_order_relaxed);
1523 // Process TLS relocations, including TLS optimizations. Note that
1524 // R_TPREL and R_TPREL_NEG relocations are resolved in processAux.
1526 // Some RISCV TLSDESC relocations reference a local NOTYPE symbol,
1527 // but we need to process them in handleTlsRelocation.
1528 if (sym.isTls() || oneof<R_TLSDESC_PC, R_TLSDESC_CALL>(expr)) {
1529 if (unsigned processed =
1530 handleTlsRelocation(type, sym, *sec, offset, addend, expr)) {
1531 i += processed - 1;
1532 return;
1536 processAux(expr, type, offset, sym, addend);
1539 // R_PPC64_TLSGD/R_PPC64_TLSLD is required to mark `bl __tls_get_addr` for
1540 // General Dynamic/Local Dynamic code sequences. If a GD/LD GOT relocation is
1541 // found but no R_PPC64_TLSGD/R_PPC64_TLSLD is seen, we assume that the
1542 // instructions are generated by very old IBM XL compilers. Work around the
1543 // issue by disabling GD/LD to IE/LE relaxation.
1544 template <class RelTy>
1545 static void checkPPC64TLSRelax(InputSectionBase &sec, ArrayRef<RelTy> rels) {
1546 // Skip if sec is synthetic (sec.file is null) or if sec has been marked.
1547 if (!sec.file || sec.file->ppc64DisableTLSRelax)
1548 return;
1549 bool hasGDLD = false;
1550 for (const RelTy &rel : rels) {
1551 RelType type = rel.getType(false);
1552 switch (type) {
1553 case R_PPC64_TLSGD:
1554 case R_PPC64_TLSLD:
1555 return; // Found a marker
1556 case R_PPC64_GOT_TLSGD16:
1557 case R_PPC64_GOT_TLSGD16_HA:
1558 case R_PPC64_GOT_TLSGD16_HI:
1559 case R_PPC64_GOT_TLSGD16_LO:
1560 case R_PPC64_GOT_TLSLD16:
1561 case R_PPC64_GOT_TLSLD16_HA:
1562 case R_PPC64_GOT_TLSLD16_HI:
1563 case R_PPC64_GOT_TLSLD16_LO:
1564 hasGDLD = true;
1565 break;
1568 if (hasGDLD) {
1569 sec.file->ppc64DisableTLSRelax = true;
1570 warn(toString(sec.file) +
1571 ": disable TLS relaxation due to R_PPC64_GOT_TLS* relocations without "
1572 "R_PPC64_TLSGD/R_PPC64_TLSLD relocations");
1576 template <class ELFT, class RelTy>
1577 void RelocationScanner::scan(ArrayRef<RelTy> rels) {
1578 // Not all relocations end up in Sec->Relocations, but a lot do.
1579 sec->relocations.reserve(rels.size());
1581 if (config->emachine == EM_PPC64)
1582 checkPPC64TLSRelax<RelTy>(*sec, rels);
1584 // For EhInputSection, OffsetGetter expects the relocations to be sorted by
1585 // r_offset. In rare cases (.eh_frame pieces are reordered by a linker
1586 // script), the relocations may be unordered.
1587 // On SystemZ, all sections need to be sorted by r_offset, to allow TLS
1588 // relaxation to be handled correctly - see SystemZ::getTlsGdRelaxSkip.
1589 SmallVector<RelTy, 0> storage;
1590 if (isa<EhInputSection>(sec) || config->emachine == EM_S390)
1591 rels = sortRels(rels, storage);
1593 end = static_cast<const void *>(rels.end());
1594 for (auto i = rels.begin(); i != end;)
1595 scanOne<ELFT>(i);
1597 // Sort relocations by offset for more efficient searching for
1598 // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
1599 if (config->emachine == EM_RISCV ||
1600 (config->emachine == EM_PPC64 && sec->name == ".toc"))
1601 llvm::stable_sort(sec->relocs(),
1602 [](const Relocation &lhs, const Relocation &rhs) {
1603 return lhs.offset < rhs.offset;
1607 template <class ELFT> void RelocationScanner::scanSection(InputSectionBase &s) {
1608 sec = &s;
1609 getter = OffsetGetter(s);
1610 const RelsOrRelas<ELFT> rels = s.template relsOrRelas<ELFT>();
1611 if (rels.areRelocsRel())
1612 scan<ELFT>(rels.rels);
1613 else
1614 scan<ELFT>(rels.relas);
1617 template <class ELFT> void elf::scanRelocations() {
1618 // Scan all relocations. Each relocation goes through a series of tests to
1619 // determine if it needs special treatment, such as creating GOT, PLT,
1620 // copy relocations, etc. Note that relocations for non-alloc sections are
1621 // directly processed by InputSection::relocateNonAlloc.
1623 // Deterministic parallellism needs sorting relocations which is unsuitable
1624 // for -z nocombreloc. MIPS and PPC64 use global states which are not suitable
1625 // for parallelism.
1626 bool serial = !config->zCombreloc || config->emachine == EM_MIPS ||
1627 config->emachine == EM_PPC64;
1628 parallel::TaskGroup tg;
1629 for (ELFFileBase *f : ctx.objectFiles) {
1630 auto fn = [f]() {
1631 RelocationScanner scanner;
1632 for (InputSectionBase *s : f->getSections()) {
1633 if (s && s->kind() == SectionBase::Regular && s->isLive() &&
1634 (s->flags & SHF_ALLOC) &&
1635 !(s->type == SHT_ARM_EXIDX && config->emachine == EM_ARM))
1636 scanner.template scanSection<ELFT>(*s);
1639 tg.spawn(fn, serial);
1642 tg.spawn([] {
1643 RelocationScanner scanner;
1644 for (Partition &part : partitions) {
1645 for (EhInputSection *sec : part.ehFrame->sections)
1646 scanner.template scanSection<ELFT>(*sec);
1647 if (part.armExidx && part.armExidx->isLive())
1648 for (InputSection *sec : part.armExidx->exidxSections)
1649 if (sec->isLive())
1650 scanner.template scanSection<ELFT>(*sec);
1655 static bool handleNonPreemptibleIfunc(Symbol &sym, uint16_t flags) {
1656 // Handle a reference to a non-preemptible ifunc. These are special in a
1657 // few ways:
1659 // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
1660 // a fixed value. But assuming that all references to the ifunc are
1661 // GOT-generating or PLT-generating, the handling of an ifunc is
1662 // relatively straightforward. We create a PLT entry in Iplt, which is
1663 // usually at the end of .plt, which makes an indirect call using a
1664 // matching GOT entry in igotPlt, which is usually at the end of .got.plt.
1665 // The GOT entry is relocated using an IRELATIVE relocation in relaDyn,
1666 // which is usually at the end of .rela.dyn.
1668 // - Despite the fact that an ifunc does not have a fixed value, compilers
1669 // that are not passed -fPIC will assume that they do, and will emit
1670 // direct (non-GOT-generating, non-PLT-generating) relocations to the
1671 // symbol. This means that if a direct relocation to the symbol is
1672 // seen, the linker must set a value for the symbol, and this value must
1673 // be consistent no matter what type of reference is made to the symbol.
1674 // This can be done by creating a PLT entry for the symbol in the way
1675 // described above and making it canonical, that is, making all references
1676 // point to the PLT entry instead of the resolver. In lld we also store
1677 // the address of the PLT entry in the dynamic symbol table, which means
1678 // that the symbol will also have the same value in other modules.
1679 // Because the value loaded from the GOT needs to be consistent with
1680 // the value computed using a direct relocation, a non-preemptible ifunc
1681 // may end up with two GOT entries, one in .got.plt that points to the
1682 // address returned by the resolver and is used only by the PLT entry,
1683 // and another in .got that points to the PLT entry and is used by
1684 // GOT-generating relocations.
1686 // - The fact that these symbols do not have a fixed value makes them an
1687 // exception to the general rule that a statically linked executable does
1688 // not require any form of dynamic relocation. To handle these relocations
1689 // correctly, the IRELATIVE relocations are stored in an array which a
1690 // statically linked executable's startup code must enumerate using the
1691 // linker-defined symbols __rela?_iplt_{start,end}.
1692 if (!sym.isGnuIFunc() || sym.isPreemptible || config->zIfuncNoplt)
1693 return false;
1694 // Skip unreferenced non-preemptible ifunc.
1695 if (!(flags & (NEEDS_GOT | NEEDS_PLT | HAS_DIRECT_RELOC)))
1696 return true;
1698 sym.isInIplt = true;
1700 // Create an Iplt and the associated IRELATIVE relocation pointing to the
1701 // original section/value pairs. For non-GOT non-PLT relocation case below, we
1702 // may alter section/value, so create a copy of the symbol to make
1703 // section/value fixed.
1705 // Prior to Android V, there was a bug that caused RELR relocations to be
1706 // applied after packed relocations. This meant that resolvers referenced by
1707 // IRELATIVE relocations in the packed relocation section would read
1708 // unrelocated globals with RELR relocations when
1709 // --pack-relative-relocs=android+relr is enabled. Work around this by placing
1710 // IRELATIVE in .rela.plt.
1711 auto *directSym = makeDefined(cast<Defined>(sym));
1712 directSym->allocateAux();
1713 auto &dyn = config->androidPackDynRelocs ? *in.relaPlt : *mainPart->relaDyn;
1714 addPltEntry(*in.iplt, *in.igotPlt, dyn, target->iRelativeRel, *directSym);
1715 sym.allocateAux();
1716 symAux.back().pltIdx = symAux[directSym->auxIdx].pltIdx;
1718 if (flags & HAS_DIRECT_RELOC) {
1719 // Change the value to the IPLT and redirect all references to it.
1720 auto &d = cast<Defined>(sym);
1721 d.section = in.iplt.get();
1722 d.value = d.getPltIdx() * target->ipltEntrySize;
1723 d.size = 0;
1724 // It's important to set the symbol type here so that dynamic loaders
1725 // don't try to call the PLT as if it were an ifunc resolver.
1726 d.type = STT_FUNC;
1728 if (flags & NEEDS_GOT)
1729 addGotEntry(sym);
1730 } else if (flags & NEEDS_GOT) {
1731 // Redirect GOT accesses to point to the Igot.
1732 sym.gotInIgot = true;
1734 return true;
1737 void elf::postScanRelocations() {
1738 auto fn = [](Symbol &sym) {
1739 auto flags = sym.flags.load(std::memory_order_relaxed);
1740 if (handleNonPreemptibleIfunc(sym, flags))
1741 return;
1743 if (sym.isTagged() && sym.isDefined())
1744 mainPart->memtagGlobalDescriptors->addSymbol(sym);
1746 if (!sym.needsDynReloc())
1747 return;
1748 sym.allocateAux();
1750 if (flags & NEEDS_GOT)
1751 addGotEntry(sym);
1752 if (flags & NEEDS_PLT)
1753 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, sym);
1754 if (flags & NEEDS_COPY) {
1755 if (sym.isObject()) {
1756 invokeELFT(addCopyRelSymbol, cast<SharedSymbol>(sym));
1757 // NEEDS_COPY is cleared for sym and its aliases so that in
1758 // later iterations aliases won't cause redundant copies.
1759 assert(!sym.hasFlag(NEEDS_COPY));
1760 } else {
1761 assert(sym.isFunc() && sym.hasFlag(NEEDS_PLT));
1762 if (!sym.isDefined()) {
1763 replaceWithDefined(sym, *in.plt,
1764 target->pltHeaderSize +
1765 target->pltEntrySize * sym.getPltIdx(),
1767 sym.setFlags(NEEDS_COPY);
1768 if (config->emachine == EM_PPC) {
1769 // PPC32 canonical PLT entries are at the beginning of .glink
1770 cast<Defined>(sym).value = in.plt->headerSize;
1771 in.plt->headerSize += 16;
1772 cast<PPC32GlinkSection>(*in.plt).canonical_plts.push_back(&sym);
1778 if (!sym.isTls())
1779 return;
1780 bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1781 GotSection *got = in.got.get();
1783 if (flags & NEEDS_TLSDESC) {
1784 got->addTlsDescEntry(sym);
1785 mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1786 target->tlsDescRel, *got, got->getTlsDescOffset(sym), sym,
1787 target->tlsDescRel);
1789 if (flags & NEEDS_TLSGD) {
1790 got->addDynTlsEntry(sym);
1791 uint64_t off = got->getGlobalDynOffset(sym);
1792 if (isLocalInExecutable)
1793 // Write one to the GOT slot.
1794 got->addConstant({R_ADDEND, target->symbolicRel, off, 1, &sym});
1795 else
1796 mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *got, off,
1797 sym);
1799 // If the symbol is preemptible we need the dynamic linker to write
1800 // the offset too.
1801 uint64_t offsetOff = off + config->wordsize;
1802 if (sym.isPreemptible)
1803 mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *got, offsetOff,
1804 sym);
1805 else
1806 got->addConstant({R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym});
1808 if (flags & NEEDS_TLSGD_TO_IE) {
1809 got->addEntry(sym);
1810 mainPart->relaDyn->addSymbolReloc(target->tlsGotRel, *got,
1811 sym.getGotOffset(), sym);
1813 if (flags & NEEDS_GOT_DTPREL) {
1814 got->addEntry(sym);
1815 got->addConstant(
1816 {R_ABS, target->tlsOffsetRel, sym.getGotOffset(), 0, &sym});
1819 if ((flags & NEEDS_TLSIE) && !(flags & NEEDS_TLSGD_TO_IE))
1820 addTpOffsetGotEntry(sym);
1823 GotSection *got = in.got.get();
1824 if (ctx.needsTlsLd.load(std::memory_order_relaxed) && got->addTlsIndex()) {
1825 static Undefined dummy(ctx.internalFile, "", STB_LOCAL, 0, 0);
1826 if (config->shared)
1827 mainPart->relaDyn->addReloc(
1828 {target->tlsModuleIndexRel, got, got->getTlsIndexOff()});
1829 else
1830 got->addConstant(
1831 {R_ADDEND, target->symbolicRel, got->getTlsIndexOff(), 1, &dummy});
1834 assert(symAux.size() == 1);
1835 for (Symbol *sym : symtab.getSymbols())
1836 fn(*sym);
1838 // Local symbols may need the aforementioned non-preemptible ifunc and GOT
1839 // handling. They don't need regular PLT.
1840 for (ELFFileBase *file : ctx.objectFiles)
1841 for (Symbol *sym : file->getLocalSymbols())
1842 fn(*sym);
1845 static bool mergeCmp(const InputSection *a, const InputSection *b) {
1846 // std::merge requires a strict weak ordering.
1847 if (a->outSecOff < b->outSecOff)
1848 return true;
1850 // FIXME dyn_cast<ThunkSection> is non-null for any SyntheticSection.
1851 if (a->outSecOff == b->outSecOff && a != b) {
1852 auto *ta = dyn_cast<ThunkSection>(a);
1853 auto *tb = dyn_cast<ThunkSection>(b);
1855 // Check if Thunk is immediately before any specific Target
1856 // InputSection for example Mips LA25 Thunks.
1857 if (ta && ta->getTargetInputSection() == b)
1858 return true;
1860 // Place Thunk Sections without specific targets before
1861 // non-Thunk Sections.
1862 if (ta && !tb && !ta->getTargetInputSection())
1863 return true;
1866 return false;
1869 // Call Fn on every executable InputSection accessed via the linker script
1870 // InputSectionDescription::Sections.
1871 static void forEachInputSectionDescription(
1872 ArrayRef<OutputSection *> outputSections,
1873 llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
1874 for (OutputSection *os : outputSections) {
1875 if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
1876 continue;
1877 for (SectionCommand *bc : os->commands)
1878 if (auto *isd = dyn_cast<InputSectionDescription>(bc))
1879 fn(os, isd);
1883 // Thunk Implementation
1885 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1886 // of code that the linker inserts inbetween a caller and a callee. The thunks
1887 // are added at link time rather than compile time as the decision on whether
1888 // a thunk is needed, such as the caller and callee being out of range, can only
1889 // be made at link time.
1891 // It is straightforward to tell given the current state of the program when a
1892 // thunk is needed for a particular call. The more difficult part is that
1893 // the thunk needs to be placed in the program such that the caller can reach
1894 // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1895 // the program alters addresses, which can mean more thunks etc.
1897 // In lld we have a synthetic ThunkSection that can hold many Thunks.
1898 // The decision to have a ThunkSection act as a container means that we can
1899 // more easily handle the most common case of a single block of contiguous
1900 // Thunks by inserting just a single ThunkSection.
1902 // The implementation of Thunks in lld is split across these areas
1903 // Relocations.cpp : Framework for creating and placing thunks
1904 // Thunks.cpp : The code generated for each supported thunk
1905 // Target.cpp : Target specific hooks that the framework uses to decide when
1906 // a thunk is used
1907 // Synthetic.cpp : Implementation of ThunkSection
1908 // Writer.cpp : Iteratively call framework until no more Thunks added
1910 // Thunk placement requirements:
1911 // Mips LA25 thunks. These must be placed immediately before the callee section
1912 // We can assume that the caller is in range of the Thunk. These are modelled
1913 // by Thunks that return the section they must precede with
1914 // getTargetInputSection().
1916 // ARM interworking and range extension thunks. These thunks must be placed
1917 // within range of the caller. All implemented ARM thunks can always reach the
1918 // callee as they use an indirect jump via a register that has no range
1919 // restrictions.
1921 // Thunk placement algorithm:
1922 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1923 // getTargetInputSection().
1925 // For thunks that must be placed within range of the caller there are many
1926 // possible choices given that the maximum range from the caller is usually
1927 // much larger than the average InputSection size. Desirable properties include:
1928 // - Maximize reuse of thunks by multiple callers
1929 // - Minimize number of ThunkSections to simplify insertion
1930 // - Handle impact of already added Thunks on addresses
1931 // - Simple to understand and implement
1933 // In lld for the first pass, we pre-create one or more ThunkSections per
1934 // InputSectionDescription at Target specific intervals. A ThunkSection is
1935 // placed so that the estimated end of the ThunkSection is within range of the
1936 // start of the InputSectionDescription or the previous ThunkSection. For
1937 // example:
1938 // InputSectionDescription
1939 // Section 0
1940 // ...
1941 // Section N
1942 // ThunkSection 0
1943 // Section N + 1
1944 // ...
1945 // Section N + K
1946 // Thunk Section 1
1948 // The intention is that we can add a Thunk to a ThunkSection that is well
1949 // spaced enough to service a number of callers without having to do a lot
1950 // of work. An important principle is that it is not an error if a Thunk cannot
1951 // be placed in a pre-created ThunkSection; when this happens we create a new
1952 // ThunkSection placed next to the caller. This allows us to handle the vast
1953 // majority of thunks simply, but also handle rare cases where the branch range
1954 // is smaller than the target specific spacing.
1956 // The algorithm is expected to create all the thunks that are needed in a
1957 // single pass, with a small number of programs needing a second pass due to
1958 // the insertion of thunks in the first pass increasing the offset between
1959 // callers and callees that were only just in range.
1961 // A consequence of allowing new ThunkSections to be created outside of the
1962 // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1963 // range in pass K, are out of range in some pass > K due to the insertion of
1964 // more Thunks in between the caller and callee. When this happens we retarget
1965 // the relocation back to the original target and create another Thunk.
1967 // Remove ThunkSections that are empty, this should only be the initial set
1968 // precreated on pass 0.
1970 // Insert the Thunks for OutputSection OS into their designated place
1971 // in the Sections vector, and recalculate the InputSection output section
1972 // offsets.
1973 // This may invalidate any output section offsets stored outside of InputSection
1974 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
1975 forEachInputSectionDescription(
1976 outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
1977 if (isd->thunkSections.empty())
1978 return;
1980 // Remove any zero sized precreated Thunks.
1981 llvm::erase_if(isd->thunkSections,
1982 [](const std::pair<ThunkSection *, uint32_t> &ts) {
1983 return ts.first->getSize() == 0;
1986 // ISD->ThunkSections contains all created ThunkSections, including
1987 // those inserted in previous passes. Extract the Thunks created this
1988 // pass and order them in ascending outSecOff.
1989 std::vector<ThunkSection *> newThunks;
1990 for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
1991 if (ts.second == pass)
1992 newThunks.push_back(ts.first);
1993 llvm::stable_sort(newThunks,
1994 [](const ThunkSection *a, const ThunkSection *b) {
1995 return a->outSecOff < b->outSecOff;
1998 // Merge sorted vectors of Thunks and InputSections by outSecOff
1999 SmallVector<InputSection *, 0> tmp;
2000 tmp.reserve(isd->sections.size() + newThunks.size());
2002 std::merge(isd->sections.begin(), isd->sections.end(),
2003 newThunks.begin(), newThunks.end(), std::back_inserter(tmp),
2004 mergeCmp);
2006 isd->sections = std::move(tmp);
2010 static int64_t getPCBias(RelType type) {
2011 if (config->emachine != EM_ARM)
2012 return 0;
2013 switch (type) {
2014 case R_ARM_THM_JUMP19:
2015 case R_ARM_THM_JUMP24:
2016 case R_ARM_THM_CALL:
2017 return 4;
2018 default:
2019 return 8;
2023 // Find or create a ThunkSection within the InputSectionDescription (ISD) that
2024 // is in range of Src. An ISD maps to a range of InputSections described by a
2025 // linker script section pattern such as { .text .text.* }.
2026 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os,
2027 InputSection *isec,
2028 InputSectionDescription *isd,
2029 const Relocation &rel,
2030 uint64_t src) {
2031 // See the comment in getThunk for -pcBias below.
2032 const int64_t pcBias = getPCBias(rel.type);
2033 for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
2034 ThunkSection *ts = tp.first;
2035 uint64_t tsBase = os->addr + ts->outSecOff - pcBias;
2036 uint64_t tsLimit = tsBase + ts->getSize();
2037 if (target->inBranchRange(rel.type, src,
2038 (src > tsLimit) ? tsBase : tsLimit))
2039 return ts;
2042 // No suitable ThunkSection exists. This can happen when there is a branch
2043 // with lower range than the ThunkSection spacing or when there are too
2044 // many Thunks. Create a new ThunkSection as close to the InputSection as
2045 // possible. Error if InputSection is so large we cannot place ThunkSection
2046 // anywhere in Range.
2047 uint64_t thunkSecOff = isec->outSecOff;
2048 if (!target->inBranchRange(rel.type, src,
2049 os->addr + thunkSecOff + rel.addend)) {
2050 thunkSecOff = isec->outSecOff + isec->getSize();
2051 if (!target->inBranchRange(rel.type, src,
2052 os->addr + thunkSecOff + rel.addend))
2053 fatal("InputSection too large for range extension thunk " +
2054 isec->getObjMsg(src - (os->addr + isec->outSecOff)));
2056 return addThunkSection(os, isd, thunkSecOff);
2059 // Add a Thunk that needs to be placed in a ThunkSection that immediately
2060 // precedes its Target.
2061 ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
2062 ThunkSection *ts = thunkedSections.lookup(isec);
2063 if (ts)
2064 return ts;
2066 // Find InputSectionRange within Target Output Section (TOS) that the
2067 // InputSection (IS) that we need to precede is in.
2068 OutputSection *tos = isec->getParent();
2069 for (SectionCommand *bc : tos->commands) {
2070 auto *isd = dyn_cast<InputSectionDescription>(bc);
2071 if (!isd || isd->sections.empty())
2072 continue;
2074 InputSection *first = isd->sections.front();
2075 InputSection *last = isd->sections.back();
2077 if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
2078 continue;
2080 ts = addThunkSection(tos, isd, isec->outSecOff);
2081 thunkedSections[isec] = ts;
2082 return ts;
2085 return nullptr;
2088 // Create one or more ThunkSections per OS that can be used to place Thunks.
2089 // We attempt to place the ThunkSections using the following desirable
2090 // properties:
2091 // - Within range of the maximum number of callers
2092 // - Minimise the number of ThunkSections
2094 // We follow a simple but conservative heuristic to place ThunkSections at
2095 // offsets that are multiples of a Target specific branch range.
2096 // For an InputSectionDescription that is smaller than the range, a single
2097 // ThunkSection at the end of the range will do.
2099 // For an InputSectionDescription that is more than twice the size of the range,
2100 // we place the last ThunkSection at range bytes from the end of the
2101 // InputSectionDescription in order to increase the likelihood that the
2102 // distance from a thunk to its target will be sufficiently small to
2103 // allow for the creation of a short thunk.
2104 void ThunkCreator::createInitialThunkSections(
2105 ArrayRef<OutputSection *> outputSections) {
2106 uint32_t thunkSectionSpacing = target->getThunkSectionSpacing();
2108 forEachInputSectionDescription(
2109 outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
2110 if (isd->sections.empty())
2111 return;
2113 uint32_t isdBegin = isd->sections.front()->outSecOff;
2114 uint32_t isdEnd =
2115 isd->sections.back()->outSecOff + isd->sections.back()->getSize();
2116 uint32_t lastThunkLowerBound = -1;
2117 if (isdEnd - isdBegin > thunkSectionSpacing * 2)
2118 lastThunkLowerBound = isdEnd - thunkSectionSpacing;
2120 uint32_t isecLimit;
2121 uint32_t prevIsecLimit = isdBegin;
2122 uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
2124 for (const InputSection *isec : isd->sections) {
2125 isecLimit = isec->outSecOff + isec->getSize();
2126 if (isecLimit > thunkUpperBound) {
2127 addThunkSection(os, isd, prevIsecLimit);
2128 thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
2130 if (isecLimit > lastThunkLowerBound)
2131 break;
2132 prevIsecLimit = isecLimit;
2134 addThunkSection(os, isd, isecLimit);
2138 ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
2139 InputSectionDescription *isd,
2140 uint64_t off) {
2141 auto *ts = make<ThunkSection>(os, off);
2142 ts->partition = os->partition;
2143 if ((config->fixCortexA53Errata843419 || config->fixCortexA8) &&
2144 !isd->sections.empty()) {
2145 // The errata fixes are sensitive to addresses modulo 4 KiB. When we add
2146 // thunks we disturb the base addresses of sections placed after the thunks
2147 // this makes patches we have generated redundant, and may cause us to
2148 // generate more patches as different instructions are now in sensitive
2149 // locations. When we generate more patches we may force more branches to
2150 // go out of range, causing more thunks to be generated. In pathological
2151 // cases this can cause the address dependent content pass not to converge.
2152 // We fix this by rounding up the size of the ThunkSection to 4KiB, this
2153 // limits the insertion of a ThunkSection on the addresses modulo 4 KiB,
2154 // which means that adding Thunks to the section does not invalidate
2155 // errata patches for following code.
2156 // Rounding up the size to 4KiB has consequences for code-size and can
2157 // trip up linker script defined assertions. For example the linux kernel
2158 // has an assertion that what LLD represents as an InputSectionDescription
2159 // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib.
2160 // We use the heuristic of rounding up the size when both of the following
2161 // conditions are true:
2162 // 1.) The OutputSection is larger than the ThunkSectionSpacing. This
2163 // accounts for the case where no single InputSectionDescription is
2164 // larger than the OutputSection size. This is conservative but simple.
2165 // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent
2166 // any assertion failures that an InputSectionDescription is < 4 KiB
2167 // in size.
2168 uint64_t isdSize = isd->sections.back()->outSecOff +
2169 isd->sections.back()->getSize() -
2170 isd->sections.front()->outSecOff;
2171 if (os->size > target->getThunkSectionSpacing() && isdSize > 4096)
2172 ts->roundUpSizeForErrata = true;
2174 isd->thunkSections.push_back({ts, pass});
2175 return ts;
2178 static bool isThunkSectionCompatible(InputSection *source,
2179 SectionBase *target) {
2180 // We can't reuse thunks in different loadable partitions because they might
2181 // not be loaded. But partition 1 (the main partition) will always be loaded.
2182 if (source->partition != target->partition)
2183 return target->partition == 1;
2184 return true;
2187 std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
2188 Relocation &rel, uint64_t src) {
2189 std::vector<Thunk *> *thunkVec = nullptr;
2190 // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled
2191 // out in the relocation addend. We compensate for the PC bias so that
2192 // an Arm and Thumb relocation to the same destination get the same keyAddend,
2193 // which is usually 0.
2194 const int64_t pcBias = getPCBias(rel.type);
2195 const int64_t keyAddend = rel.addend + pcBias;
2197 // We use a ((section, offset), addend) pair to find the thunk position if
2198 // possible so that we create only one thunk for aliased symbols or ICFed
2199 // sections. There may be multiple relocations sharing the same (section,
2200 // offset + addend) pair. We may revert the relocation back to its original
2201 // non-Thunk target, so we cannot fold offset + addend.
2202 if (auto *d = dyn_cast<Defined>(rel.sym))
2203 if (!d->isInPlt() && d->section)
2204 thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value},
2205 keyAddend}];
2206 if (!thunkVec)
2207 thunkVec = &thunkedSymbols[{rel.sym, keyAddend}];
2209 // Check existing Thunks for Sym to see if they can be reused
2210 for (Thunk *t : *thunkVec)
2211 if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) &&
2212 t->isCompatibleWith(*isec, rel) &&
2213 target->inBranchRange(rel.type, src,
2214 t->getThunkTargetSym()->getVA(-pcBias)))
2215 return std::make_pair(t, false);
2217 // No existing compatible Thunk in range, create a new one
2218 Thunk *t = addThunk(*isec, rel);
2219 thunkVec->push_back(t);
2220 return std::make_pair(t, true);
2223 // Return true if the relocation target is an in range Thunk.
2224 // Return false if the relocation is not to a Thunk. If the relocation target
2225 // was originally to a Thunk, but is no longer in range we revert the
2226 // relocation back to its original non-Thunk target.
2227 bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
2228 if (Thunk *t = thunks.lookup(rel.sym)) {
2229 if (target->inBranchRange(rel.type, src, rel.sym->getVA(rel.addend)))
2230 return true;
2231 rel.sym = &t->destination;
2232 rel.addend = t->addend;
2233 if (rel.sym->isInPlt())
2234 rel.expr = toPlt(rel.expr);
2236 return false;
2239 // Process all relocations from the InputSections that have been assigned
2240 // to InputSectionDescriptions and redirect through Thunks if needed. The
2241 // function should be called iteratively until it returns false.
2243 // PreConditions:
2244 // All InputSections that may need a Thunk are reachable from
2245 // OutputSectionCommands.
2247 // All OutputSections have an address and all InputSections have an offset
2248 // within the OutputSection.
2250 // The offsets between caller (relocation place) and callee
2251 // (relocation target) will not be modified outside of createThunks().
2253 // PostConditions:
2254 // If return value is true then ThunkSections have been inserted into
2255 // OutputSections. All relocations that needed a Thunk based on the information
2256 // available to createThunks() on entry have been redirected to a Thunk. Note
2257 // that adding Thunks changes offsets between caller and callee so more Thunks
2258 // may be required.
2260 // If return value is false then no more Thunks are needed, and createThunks has
2261 // made no changes. If the target requires range extension thunks, currently
2262 // ARM, then any future change in offset between caller and callee risks a
2263 // relocation out of range error.
2264 bool ThunkCreator::createThunks(uint32_t pass,
2265 ArrayRef<OutputSection *> outputSections) {
2266 this->pass = pass;
2267 bool addressesChanged = false;
2269 if (pass == 0 && target->getThunkSectionSpacing())
2270 createInitialThunkSections(outputSections);
2272 // Create all the Thunks and insert them into synthetic ThunkSections. The
2273 // ThunkSections are later inserted back into InputSectionDescriptions.
2274 // We separate the creation of ThunkSections from the insertion of the
2275 // ThunkSections as ThunkSections are not always inserted into the same
2276 // InputSectionDescription as the caller.
2277 forEachInputSectionDescription(
2278 outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
2279 for (InputSection *isec : isd->sections)
2280 for (Relocation &rel : isec->relocs()) {
2281 uint64_t src = isec->getVA(rel.offset);
2283 // If we are a relocation to an existing Thunk, check if it is
2284 // still in range. If not then Rel will be altered to point to its
2285 // original target so another Thunk can be generated.
2286 if (pass > 0 && normalizeExistingThunk(rel, src))
2287 continue;
2289 if (!target->needsThunk(rel.expr, rel.type, isec->file, src,
2290 *rel.sym, rel.addend))
2291 continue;
2293 Thunk *t;
2294 bool isNew;
2295 std::tie(t, isNew) = getThunk(isec, rel, src);
2297 if (isNew) {
2298 // Find or create a ThunkSection for the new Thunk
2299 ThunkSection *ts;
2300 if (auto *tis = t->getTargetInputSection())
2301 ts = getISThunkSec(tis);
2302 else
2303 ts = getISDThunkSec(os, isec, isd, rel, src);
2304 ts->addThunk(t);
2305 thunks[t->getThunkTargetSym()] = t;
2308 // Redirect relocation to Thunk, we never go via the PLT to a Thunk
2309 rel.sym = t->getThunkTargetSym();
2310 rel.expr = fromPlt(rel.expr);
2312 // On AArch64 and PPC, a jump/call relocation may be encoded as
2313 // STT_SECTION + non-zero addend, clear the addend after
2314 // redirection.
2315 if (config->emachine != EM_MIPS)
2316 rel.addend = -getPCBias(rel.type);
2319 for (auto &p : isd->thunkSections)
2320 addressesChanged |= p.first->assignOffsets();
2323 for (auto &p : thunkedSections)
2324 addressesChanged |= p.second->assignOffsets();
2326 // Merge all created synthetic ThunkSections back into OutputSection
2327 mergeThunks(outputSections);
2328 return addressesChanged;
2331 // The following aid in the conversion of call x@GDPLT to call __tls_get_addr
2332 // hexagonNeedsTLSSymbol scans for relocations would require a call to
2333 // __tls_get_addr.
2334 // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr.
2335 bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) {
2336 bool needTlsSymbol = false;
2337 forEachInputSectionDescription(
2338 outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
2339 for (InputSection *isec : isd->sections)
2340 for (Relocation &rel : isec->relocs())
2341 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
2342 needTlsSymbol = true;
2343 return;
2346 return needTlsSymbol;
2349 void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) {
2350 Symbol *sym = symtab.find("__tls_get_addr");
2351 if (!sym)
2352 return;
2353 bool needEntry = true;
2354 forEachInputSectionDescription(
2355 outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
2356 for (InputSection *isec : isd->sections)
2357 for (Relocation &rel : isec->relocs())
2358 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
2359 if (needEntry) {
2360 sym->allocateAux();
2361 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel,
2362 *sym);
2363 needEntry = false;
2365 rel.sym = sym;
2370 template void elf::scanRelocations<ELF32LE>();
2371 template void elf::scanRelocations<ELF32BE>();
2372 template void elf::scanRelocations<ELF64LE>();
2373 template void elf::scanRelocations<ELF64BE>();