1 //===- Relocations.cpp ----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains platform-independent functions to process relocations.
11 // I'll describe the overview of this file here.
13 // Simple relocations are easy to handle for the linker. For example,
14 // for R_X86_64_PC64 relocs, the linker just has to fix up locations
15 // with the relative offsets to the target symbols. It would just be
16 // reading records from relocation sections and applying them to output.
18 // But not all relocations are that easy to handle. For example, for
19 // R_386_GOTOFF relocs, the linker has to create new GOT entries for
20 // symbols if they don't exist, and fix up locations with GOT entry
21 // offsets from the beginning of GOT section. So there is more than
22 // fixing addresses in relocation processing.
24 // ELF defines a large number of complex relocations.
26 // The functions in this file analyze relocations and do whatever needs
27 // to be done. It includes, but not limited to, the following.
29 // - create GOT/PLT entries
30 // - create new relocations in .dynsym to let the dynamic linker resolve
31 // them at runtime (since ELF supports dynamic linking, not all
32 // relocations can be resolved at link-time)
33 // - create COPY relocs and reserve space in .bss
34 // - replace expensive relocs (in terms of runtime cost) with cheap ones
35 // - error out infeasible combinations such as PIC and non-relative relocs
37 // Note that the functions in this file don't actually apply relocations
38 // because it doesn't know about the output file nor the output file buffer.
39 // It instead stores Relocation objects to InputSection's Relocations
40 // vector to let it apply later in InputSection::writeTo.
42 //===----------------------------------------------------------------------===//
44 #include "Relocations.h"
47 #include "OutputSections.h"
49 #include "SymbolTable.h"
50 #include "SyntheticSections.h"
54 #include "llvm/Support/Endian.h"
55 #include "llvm/Support/raw_ostream.h"
59 using namespace llvm::ELF;
60 using namespace llvm::object;
61 using namespace llvm::support::endian;
64 using namespace lld::elf;
66 // Construct a message in the following format.
68 // >>> defined in /home/alice/src/foo.o
69 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
70 // >>> /home/alice/src/bar.o:(.text+0x1)
72 static std::string getLocation(InputSectionBase &S, const SymbolBody &Sym,
75 "\n>>> defined in " + toString(Sym.File) + "\n>>> referenced by ";
76 std::string Src = S.getSrcMsg<ELFT>(Off);
78 Msg += Src + "\n>>> ";
79 return Msg + S.getObjMsg<ELFT>(Off);
82 static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
83 // In case of MIPS GP-relative relocations always resolve to a definition
84 // in a regular input file, ignoring the one-definition rule. So we,
85 // for example, should not attempt to create a dynamic relocation even
86 // if the target symbol is preemptible. There are two two MIPS GP-relative
87 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
88 // can be against a preemptible symbol.
89 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
90 // relocation types occupy eight bit. In case of N64 ABI we extract first
91 // relocation from 3-in-1 packet because only the first relocation can
92 // be against a real symbol.
93 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
95 return Body.isPreemptible();
98 // This function is similar to the `handleTlsRelocation`. MIPS does not
99 // support any relaxations for TLS relocations so by factoring out MIPS
100 // handling in to the separate function we can simplify the code and do not
101 // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
102 // Mips has a custom MipsGotSection that handles the writing of GOT entries
103 // without dynamic relocations.
104 template <class ELFT>
105 static unsigned handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body,
106 InputSectionBase &C, uint64_t Offset,
107 int64_t Addend, RelExpr Expr) {
108 if (Expr == R_MIPS_TLSLD) {
109 if (InX::MipsGot->addTlsIndex() && Config->Pic)
110 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::MipsGot,
111 InX::MipsGot->getTlsIndexOff(), false,
113 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
117 if (Expr == R_MIPS_TLSGD) {
118 if (InX::MipsGot->addDynTlsEntry(Body) && Body.isPreemptible()) {
119 uint64_t Off = InX::MipsGot->getGlobalDynOffset(Body);
120 In<ELFT>::RelaDyn->addReloc(
121 {Target->TlsModuleIndexRel, InX::MipsGot, Off, false, &Body, 0});
122 if (Body.isPreemptible())
123 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, InX::MipsGot,
124 Off + Config->Wordsize, false, &Body, 0});
126 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
132 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not
133 // support any relaxations for TLS relocations. ARM is logically similar to Mips
134 // in how it handles TLS, but Mips uses its own custom GOT which handles some
135 // of the cases that ARM uses GOT relocations for.
137 // We look for TLS global dynamic and local dynamic relocations, these may
138 // require the generation of a pair of GOT entries that have associated
139 // dynamic relocations. When the results of the dynamic relocations can be
140 // resolved at static link time we do so. This is necessary for static linking
141 // as there will be no dynamic loader to resolve them at load-time.
143 // The pair of GOT entries created are of the form
144 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time)
145 // GOT[e1] Offset of symbol in TLS block
146 template <class ELFT>
147 static unsigned handleARMTlsRelocation(uint32_t Type, SymbolBody &Body,
148 InputSectionBase &C, uint64_t Offset,
149 int64_t Addend, RelExpr Expr) {
150 // The Dynamic TLS Module Index Relocation for a symbol defined in an
151 // executable is always 1. If the target Symbol is not preemtible then
152 // we know the offset into the TLS block at static link time.
153 bool NeedDynId = Body.isPreemptible() || Config->Shared;
154 bool NeedDynOff = Body.isPreemptible();
156 auto AddTlsReloc = [&](uint64_t Off, uint32_t Type, SymbolBody *Dest,
159 In<ELFT>::RelaDyn->addReloc({Type, InX::Got, Off, false, Dest, 0});
161 InX::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest});
164 // Local Dynamic is for access to module local TLS variables, while still
165 // being suitable for being dynamically loaded via dlopen.
166 // GOT[e0] is the module index, with a special value of 0 for the current
167 // module. GOT[e1] is unused. There only needs to be one module index entry.
168 if (Expr == R_TLSLD_PC && InX::Got->addTlsIndex()) {
169 AddTlsReloc(InX::Got->getTlsIndexOff(), Target->TlsModuleIndexRel,
170 NeedDynId ? nullptr : &Body, NeedDynId);
171 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
175 // Global Dynamic is the most general purpose access model. When we know
176 // the module index and offset of symbol in TLS block we can fill these in
177 // using static GOT relocations.
178 if (Expr == R_TLSGD_PC) {
179 if (InX::Got->addDynTlsEntry(Body)) {
180 uint64_t Off = InX::Got->getGlobalDynOffset(Body);
181 AddTlsReloc(Off, Target->TlsModuleIndexRel, &Body, NeedDynId);
182 AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Body,
185 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
191 // Returns the number of relocations processed.
192 template <class ELFT>
194 handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C,
195 typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
196 if (!(C.Flags & SHF_ALLOC))
202 if (Config->EMachine == EM_ARM)
203 return handleARMTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
204 if (Config->EMachine == EM_MIPS)
205 return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
207 bool IsPreemptible = isPreemptible(Body, Type);
208 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
210 if (InX::Got->addDynTlsEntry(Body)) {
211 uint64_t Off = InX::Got->getGlobalDynOffset(Body);
212 In<ELFT>::RelaDyn->addReloc(
213 {Target->TlsDescRel, InX::Got, Off, !IsPreemptible, &Body, 0});
215 if (Expr != R_TLSDESC_CALL)
216 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
220 if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
221 // Local-Dynamic relocs can be relaxed to Local-Exec.
222 if (!Config->Shared) {
223 C.Relocations.push_back(
224 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
227 if (InX::Got->addTlsIndex())
228 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::Got,
229 InX::Got->getTlsIndexOff(), false, nullptr,
231 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
235 // Local-Dynamic relocs can be relaxed to Local-Exec.
236 if (isRelExprOneOf<R_ABS, R_TLSLD, R_TLSLD_PC>(Expr) && !Config->Shared) {
237 C.Relocations.push_back(
238 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
242 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD,
244 if (Config->Shared) {
245 if (InX::Got->addDynTlsEntry(Body)) {
246 uint64_t Off = InX::Got->getGlobalDynOffset(Body);
247 In<ELFT>::RelaDyn->addReloc(
248 {Target->TlsModuleIndexRel, InX::Got, Off, false, &Body, 0});
250 // If the symbol is preemptible we need the dynamic linker to write
252 uint64_t OffsetOff = Off + Config->Wordsize;
254 In<ELFT>::RelaDyn->addReloc(
255 {Target->TlsOffsetRel, InX::Got, OffsetOff, false, &Body, 0});
257 InX::Got->Relocations.push_back(
258 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
260 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
264 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
265 // depending on the symbol being locally defined or not.
267 C.Relocations.push_back(
268 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
269 Offset, Addend, &Body});
270 if (!Body.isInGot()) {
271 InX::Got->addEntry(Body);
272 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::Got,
273 Body.getGotOffset(), false, &Body, 0});
276 C.Relocations.push_back(
277 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
278 Offset, Addend, &Body});
280 return Target->TlsGdRelaxSkip;
283 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
285 if (isRelExprOneOf<R_GOT, R_GOT_FROM_END, R_GOT_PC, R_GOT_PAGE_PC>(Expr) &&
286 !Config->Shared && !IsPreemptible) {
287 C.Relocations.push_back(
288 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
292 if (Expr == R_TLSDESC_CALL)
297 static uint32_t getMipsPairType(uint32_t Type, const SymbolBody &Sym) {
302 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
304 return R_MIPS_PCLO16;
305 case R_MICROMIPS_HI16:
306 return R_MICROMIPS_LO16;
312 // True if non-preemptable symbol always has the same value regardless of where
313 // the DSO is loaded.
314 static bool isAbsolute(const SymbolBody &Body) {
315 if (Body.isUndefined())
316 return !Body.isLocal() && Body.symbol()->isWeak();
317 if (const auto *DR = dyn_cast<DefinedRegular>(&Body))
318 return DR->Section == nullptr; // Absolute symbol.
322 static bool isAbsoluteValue(const SymbolBody &Body) {
323 return isAbsolute(Body) || Body.isTls();
326 // Returns true if Expr refers a PLT entry.
327 static bool needsPlt(RelExpr Expr) {
328 return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
331 // Returns true if Expr refers a GOT entry. Note that this function
332 // returns false for TLS variables even though they need GOT, because
333 // TLS variables uses GOT differently than the regular variables.
334 static bool needsGot(RelExpr Expr) {
335 return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
336 R_MIPS_GOT_OFF32, R_GOT_PAGE_PC, R_GOT_PC,
337 R_GOT_FROM_END>(Expr);
340 // True if this expression is of the form Sym - X, where X is a position in the
341 // file (PC, or GOT for example).
342 static bool isRelExpr(RelExpr Expr) {
343 return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
344 R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
347 // Returns true if a given relocation can be computed at link-time.
349 // For instance, we know the offset from a relocation to its target at
350 // link-time if the relocation is PC-relative and refers a
351 // non-interposable function in the same executable. This function
352 // will return true for such relocation.
354 // If this function returns false, that means we need to emit a
355 // dynamic relocation so that the relocation will be fixed at load-time.
356 template <class ELFT>
357 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
358 const SymbolBody &Body,
359 InputSectionBase &S, uint64_t RelOff) {
360 // These expressions always compute a constant
361 if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
362 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
363 R_MIPS_TLSGD, R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC,
364 R_TLSGD_PC, R_TLSGD, R_PPC_PLT_OPD, R_TLSDESC_CALL,
365 R_TLSDESC_PAGE, R_HINT>(E))
368 // These never do, except if the entire file is position dependent or if
369 // only the low bits are used.
370 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
371 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
373 if (isPreemptible(Body, Type))
378 // For the target and the relocation, we want to know if they are
379 // absolute or relative.
380 bool AbsVal = isAbsoluteValue(Body);
381 bool RelE = isRelExpr(E);
386 if (!AbsVal && !RelE)
387 return Target->usesOnlyLowPageBits(Type);
389 // Relative relocation to an absolute value. This is normally unrepresentable,
390 // but if the relocation refers to a weak undefined symbol, we allow it to
391 // resolve to the image base. This is a little strange, but it allows us to
392 // link function calls to such symbols. Normally such a call will be guarded
393 // with a comparison, which will load a zero from the GOT.
394 // Another special case is MIPS _gp_disp symbol which represents offset
395 // between start of a function and '_gp' value and defined as absolute just
396 // to simplify the code.
397 assert(AbsVal && RelE);
398 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
401 error("relocation " + toString(Type) + " cannot refer to absolute symbol: " +
402 toString(Body) + getLocation<ELFT>(S, Body, RelOff));
406 static RelExpr toPlt(RelExpr Expr) {
407 if (Expr == R_PPC_OPD)
408 return R_PPC_PLT_OPD;
411 if (Expr == R_PAGE_PC)
412 return R_PLT_PAGE_PC;
418 static RelExpr fromPlt(RelExpr Expr) {
419 // We decided not to use a plt. Optimize a reference to the plt to a
420 // reference to the symbol itself.
421 if (Expr == R_PLT_PC)
423 if (Expr == R_PPC_PLT_OPD)
430 // Returns true if a given shared symbol is in a read-only segment in a DSO.
431 template <class ELFT> static bool isReadOnly(SharedSymbol *SS) {
432 typedef typename ELFT::Phdr Elf_Phdr;
433 uint64_t Value = SS->getValue<ELFT>();
435 // Determine if the symbol is read-only by scanning the DSO's program headers.
436 auto *File = cast<SharedFile<ELFT>>(SS->File);
437 for (const Elf_Phdr &Phdr : check(File->getObj().program_headers()))
438 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
439 !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
440 Value < Phdr.p_vaddr + Phdr.p_memsz)
445 // Returns symbols at the same offset as a given symbol, including SS itself.
447 // If two or more symbols are at the same offset, and at least one of
448 // them are copied by a copy relocation, all of them need to be copied.
449 // Otherwise, they would refer different places at runtime.
450 template <class ELFT>
451 static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol *SS) {
452 typedef typename ELFT::Sym Elf_Sym;
454 auto *File = cast<SharedFile<ELFT>>(SS->File);
455 uint64_t Shndx = SS->getShndx<ELFT>();
456 uint64_t Value = SS->getValue<ELFT>();
458 std::vector<SharedSymbol *> Ret;
459 for (const Elf_Sym &S : File->getGlobalSymbols()) {
460 if (S.st_shndx != Shndx || S.st_value != Value)
462 StringRef Name = check(S.getName(File->getStringTable()));
463 SymbolBody *Sym = Symtab<ELFT>::X->find(Name);
464 if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
465 Ret.push_back(Alias);
470 // Reserve space in .bss or .bss.rel.ro for copy relocation.
472 // The copy relocation is pretty much a hack. If you use a copy relocation
473 // in your program, not only the symbol name but the symbol's size, RW/RO
474 // bit and alignment become part of the ABI. In addition to that, if the
475 // symbol has aliases, the aliases become part of the ABI. That's subtle,
476 // but if you violate that implicit ABI, that can cause very counter-
477 // intuitive consequences.
479 // So, what is the copy relocation? It's for linking non-position
480 // independent code to DSOs. In an ideal world, all references to data
481 // exported by DSOs should go indirectly through GOT. But if object files
482 // are compiled as non-PIC, all data references are direct. There is no
483 // way for the linker to transform the code to use GOT, as machine
484 // instructions are already set in stone in object files. This is where
485 // the copy relocation takes a role.
487 // A copy relocation instructs the dynamic linker to copy data from a DSO
488 // to a specified address (which is usually in .bss) at load-time. If the
489 // static linker (that's us) finds a direct data reference to a DSO
490 // symbol, it creates a copy relocation, so that the symbol can be
491 // resolved as if it were in .bss rather than in a DSO.
493 // As you can see in this function, we create a copy relocation for the
494 // dynamic linker, and the relocation contains not only symbol name but
495 // various other informtion about the symbol. So, such attributes become a
498 // Note for application developers: I can give you a piece of advice if
499 // you are writing a shared library. You probably should export only
500 // functions from your library. You shouldn't export variables.
502 // As an example what can happen when you export variables without knowing
503 // the semantics of copy relocations, assume that you have an exported
504 // variable of type T. It is an ABI-breaking change to add new members at
505 // end of T even though doing that doesn't change the layout of the
506 // existing members. That's because the space for the new members are not
507 // reserved in .bss unless you recompile the main program. That means they
508 // are likely to overlap with other data that happens to be laid out next
509 // to the variable in .bss. This kind of issue is sometimes very hard to
510 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
511 // define an accessor getV().
512 template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) {
513 // Copy relocation against zero-sized symbol doesn't make sense.
514 uint64_t SymSize = SS->template getSize<ELFT>();
516 fatal("cannot create a copy relocation for symbol " + toString(*SS));
518 // See if this symbol is in a read-only segment. If so, preserve the symbol's
519 // memory protection by reserving space in the .bss.rel.ro section.
520 bool IsReadOnly = isReadOnly<ELFT>(SS);
521 BssSection *Sec = IsReadOnly ? InX::BssRelRo : InX::Bss;
522 uint64_t Off = Sec->reserveSpace(SymSize, SS->getAlignment<ELFT>());
524 // Look through the DSO's dynamic symbol table for aliases and create a
525 // dynamic symbol for each one. This causes the copy relocation to correctly
526 // interpose any aliases.
527 for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) {
528 Sym->NeedsCopy = true;
529 Sym->CopyRelSec = Sec;
530 Sym->CopyRelSecOff = Off;
531 Sym->symbol()->IsUsedInRegularObj = true;
534 In<ELFT>::RelaDyn->addReloc({Target->CopyRel, Sec, Off, false, SS, 0});
537 template <class ELFT>
538 static RelExpr adjustExpr(SymbolBody &Body, RelExpr Expr, uint32_t Type,
539 const uint8_t *Data, InputSectionBase &S,
540 typename ELFT::uint RelOff) {
541 if (Body.isGnuIFunc()) {
543 } else if (!isPreemptible(Body, Type)) {
545 Expr = fromPlt(Expr);
546 if (Expr == R_GOT_PC && !isAbsoluteValue(Body))
547 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
550 bool IsWrite = !Config->ZText || (S.Flags & SHF_WRITE);
551 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
554 // This relocation would require the dynamic linker to write a value to read
555 // only memory. We can hack around it if we are producing an executable and
556 // the refered symbol can be preemepted to refer to the executable.
557 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
558 error("can't create dynamic relocation " + toString(Type) + " against " +
559 (Body.getName().empty() ? "local symbol in readonly segment"
560 : "symbol: " + toString(Body)) +
561 getLocation<ELFT>(S, Body, RelOff));
565 if (Body.getVisibility() != STV_DEFAULT) {
566 error("cannot preempt symbol: " + toString(Body) +
567 getLocation<ELFT>(S, Body, RelOff));
571 if (Body.isObject()) {
572 // Produce a copy relocation.
573 auto *B = cast<SharedSymbol>(&Body);
575 if (Config->ZNocopyreloc)
576 error("unresolvable relocation " + toString(Type) +
577 " against symbol '" + toString(*B) +
578 "'; recompile with -fPIC or remove '-z nocopyreloc'" +
579 getLocation<ELFT>(S, Body, RelOff));
581 addCopyRelSymbol<ELFT>(B);
587 // This handles a non PIC program call to function in a shared library. In
588 // an ideal world, we could just report an error saying the relocation can
589 // overflow at runtime. In the real world with glibc, crt1.o has a
590 // R_X86_64_PC32 pointing to libc.so.
592 // The general idea on how to handle such cases is to create a PLT entry and
593 // use that as the function value.
595 // For the static linking part, we just return a plt expr and everything
596 // else will use the the PLT entry as the address.
598 // The remaining problem is making sure pointer equality still works. We
599 // need the help of the dynamic linker for that. We let it know that we have
600 // a direct reference to a so symbol by creating an undefined symbol with a
601 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
602 // the value of the symbol we created. This is true even for got entries, so
603 // pointer equality is maintained. To avoid an infinite loop, the only entry
604 // that points to the real function is a dedicated got entry used by the
605 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
606 // R_386_JMP_SLOT, etc).
607 Body.NeedsPltAddr = true;
611 error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) +
616 // Returns an addend of a given relocation. If it is RELA, an addend
617 // is in a relocation itself. If it is REL, we need to read it from an
619 template <class ELFT, class RelTy>
620 static int64_t computeAddend(const RelTy &Rel, const uint8_t *Buf) {
621 uint32_t Type = Rel.getType(Config->IsMips64EL);
622 int64_t A = RelTy::IsRela
623 ? getAddend<ELFT>(Rel)
624 : Target->getImplicitAddend(Buf + Rel.r_offset, Type);
626 if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
627 A += getPPC64TocBase();
631 // MIPS has an odd notion of "paired" relocations to calculate addends.
632 // For example, if a relocation is of R_MIPS_HI16, there must be a
633 // R_MIPS_LO16 relocation after that, and an addend is calculated using
634 // the two relocations.
635 template <class ELFT, class RelTy>
636 static int64_t computeMipsAddend(const RelTy &Rel, InputSectionBase &Sec,
637 RelExpr Expr, SymbolBody &Body,
639 if (Expr == R_MIPS_GOTREL && Body.isLocal())
640 return Sec.getFile<ELFT>()->MipsGp0;
642 // The ABI says that the paired relocation is used only for REL.
643 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
647 uint32_t Type = Rel.getType(Config->IsMips64EL);
648 uint32_t PairTy = getMipsPairType(Type, Body);
649 if (PairTy == R_MIPS_NONE)
652 const uint8_t *Buf = Sec.Data.data();
653 uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
655 // To make things worse, paired relocations might not be contiguous in
656 // the relocation table, so we need to do linear search. *sigh*
657 for (const RelTy *RI = &Rel; RI != End; ++RI) {
658 if (RI->getType(Config->IsMips64EL) != PairTy)
660 if (RI->getSymbol(Config->IsMips64EL) != SymIndex)
663 endianness E = Config->Endianness;
664 int32_t Hi = (read32(Buf + Rel.r_offset, E) & 0xffff) << 16;
665 int32_t Lo = SignExtend32<16>(read32(Buf + RI->r_offset, E));
669 warn("can't find matching " + toString(PairTy) + " relocation for " +
674 template <class ELFT>
675 static void reportUndefined(SymbolBody &Sym, InputSectionBase &S,
677 if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll)
680 bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
681 Sym.getVisibility() == STV_DEFAULT;
682 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
686 "undefined symbol: " + toString(Sym) + "\n>>> referenced by ";
688 std::string Src = S.getSrcMsg<ELFT>(Offset);
690 Msg += Src + "\n>>> ";
691 Msg += S.getObjMsg<ELFT>(Offset);
693 if (Config->UnresolvedSymbols == UnresolvedPolicy::WarnAll ||
694 (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal)) {
701 template <class RelTy>
702 static std::pair<uint32_t, uint32_t>
703 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
704 // MIPS N32 ABI treats series of successive relocations with the same offset
705 // as a single relocation. The similar approach used by N64 ABI, but this ABI
706 // packs all relocations into the single relocation record. Here we emulate
707 // this for the N32 ABI. Iterate over relocation with the same offset and put
708 // theirs types into the single bit-set.
709 uint32_t Processed = 0;
710 for (; I != E && Offset == I->r_offset; ++I) {
712 Type |= I->getType(Config->IsMips64EL) << (8 * Processed);
714 return std::make_pair(Type, Processed);
717 // .eh_frame sections are mergeable input sections, so their input
718 // offsets are not linearly mapped to output section. For each input
719 // offset, we need to find a section piece containing the offset and
720 // add the piece's base address to the input offset to compute the
721 // output offset. That isn't cheap.
723 // This class is to speed up the offset computation. When we process
724 // relocations, we access offsets in the monotonically increasing
725 // order. So we can optimize for that access pattern.
727 // For sections other than .eh_frame, this class doesn't do anything.
731 explicit OffsetGetter(InputSectionBase &Sec) {
732 if (auto *Eh = dyn_cast<EhInputSection>(&Sec)) {
734 Size = Eh->Pieces.size();
738 // Translates offsets in input sections to offsets in output sections.
739 // Given offset must increase monotonically. We assume that P is
740 // sorted by InputOff.
741 uint64_t get(uint64_t Off) {
745 while (I != Size && P[I].InputOff + P[I].size() <= Off)
750 // P must be contiguous, so there must be no holes in between.
751 assert(P[I].InputOff <= Off && "Relocation not in any piece");
753 // Offset -1 means that the piece is dead (i.e. garbage collected).
754 if (P[I].OutputOff == -1)
756 return P[I].OutputOff + Off - P[I].InputOff;
760 ArrayRef<EhSectionPiece> P;
766 template <class ELFT, class GotPltSection>
767 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
768 RelocationSection<ELFT> *Rel, uint32_t Type,
769 SymbolBody &Sym, bool UseSymVA) {
770 Plt->addEntry<ELFT>(Sym);
771 GotPlt->addEntry(Sym);
772 Rel->addReloc({Type, GotPlt, Sym.getGotPltOffset(), UseSymVA, &Sym, 0});
775 template <class ELFT>
776 static void addGotEntry(SymbolBody &Sym, bool Preemptible) {
777 InX::Got->addEntry(Sym);
779 uint64_t Off = Sym.getGotOffset();
781 RelExpr Expr = R_ABS;
784 DynType = Target->TlsGotRel;
786 } else if (!Preemptible && Config->Pic && !isAbsolute(Sym)) {
787 DynType = Target->RelativeRel;
789 DynType = Target->GotRel;
792 bool Constant = !Preemptible && !(Config->Pic && !isAbsolute(Sym));
794 In<ELFT>::RelaDyn->addReloc(
795 {DynType, InX::Got, Off, !Preemptible, &Sym, 0});
797 if (Constant || (!Config->IsRela && !Preemptible))
798 InX::Got->Relocations.push_back({Expr, DynType, Off, 0, &Sym});
801 // The reason we have to do this early scan is as follows
802 // * To mmap the output file, we need to know the size
803 // * For that, we need to know how many dynamic relocs we will have.
804 // It might be possible to avoid this by outputting the file with write:
805 // * Write the allocated output sections, computing addresses.
806 // * Apply relocations, recording which ones require a dynamic reloc.
807 // * Write the dynamic relocations.
808 // * Write the rest of the file.
809 // This would have some drawbacks. For example, we would only know if .rela.dyn
810 // is needed after applying relocations. If it is, it will go after rw and rx
811 // sections. Given that it is ro, we will need an extra PT_LOAD. This
812 // complicates things for the dynamic linker and means we would have to reserve
813 // space for the extra PT_LOAD even if we end up not using it.
814 template <class ELFT, class RelTy>
815 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
816 OffsetGetter GetOffset(Sec);
818 for (auto I = Rels.begin(), End = Rels.end(); I != End; ++I) {
819 const RelTy &Rel = *I;
820 SymbolBody &Body = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
821 uint32_t Type = Rel.getType(Config->IsMips64EL);
823 if (Config->MipsN32Abi) {
825 std::tie(Type, Processed) =
826 mergeMipsN32RelTypes(Type, Rel.r_offset, I + 1, End);
830 // Compute the offset of this section in the output section.
831 uint64_t Offset = GetOffset.get(Rel.r_offset);
832 if (Offset == uint64_t(-1))
835 // Report undefined symbols. The fact that we report undefined
836 // symbols here means that we report undefined symbols only when
837 // they have relocations pointing to them. We don't care about
838 // undefined symbols that are in dead-stripped sections.
839 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
840 reportUndefined<ELFT>(Body, Sec, Rel.r_offset);
843 Target->getRelExpr(Type, Body, Sec.Data.begin() + Rel.r_offset);
845 // Ignore "hint" relocations because they are only markers for relaxation.
846 if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
849 bool Preemptible = isPreemptible(Body, Type);
850 Expr = adjustExpr<ELFT>(Body, Expr, Type, Sec.Data.data() + Rel.r_offset,
855 // This relocation does not require got entry, but it is relative to got and
856 // needs it to be created. Here we request for that.
857 if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
858 R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
859 InX::Got->HasGotOffRel = true;
862 int64_t Addend = computeAddend<ELFT>(Rel, Sec.Data.data());
863 if (Config->EMachine == EM_MIPS)
864 Addend += computeMipsAddend<ELFT>(Rel, Sec, Expr, Body, End);
866 // Process some TLS relocations, including relaxing TLS relocations.
867 // Note that this function does not handle all TLS relocations.
868 if (unsigned Processed =
869 handleTlsRelocation<ELFT>(Type, Body, Sec, Offset, Addend, Expr)) {
870 I += (Processed - 1);
874 // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
875 if (needsPlt(Expr) && !Body.isInPlt()) {
876 if (Body.isGnuIFunc() && !Preemptible)
877 addPltEntry(InX::Iplt, InX::IgotPlt, In<ELFT>::RelaIplt,
878 Target->IRelativeRel, Body, true);
880 addPltEntry(InX::Plt, InX::GotPlt, In<ELFT>::RelaPlt, Target->PltRel,
884 // Create a GOT slot if a relocation needs GOT.
885 if (needsGot(Expr)) {
886 if (Config->EMachine == EM_MIPS) {
887 // MIPS ABI has special rules to process GOT entries and doesn't
888 // require relocation entries for them. A special case is TLS
889 // relocations. In that case dynamic loader applies dynamic
890 // relocations to initialize TLS GOT entries.
891 // See "Global Offset Table" in Chapter 5 in the following document
892 // for detailed description:
893 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
894 InX::MipsGot->addEntry(Body, Addend, Expr);
895 if (Body.isTls() && Body.isPreemptible())
896 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::MipsGot,
897 Body.getGotOffset(), false, &Body, 0});
898 } else if (!Body.isInGot()) {
899 addGotEntry<ELFT>(Body, Preemptible);
903 if (!needsPlt(Expr) && !needsGot(Expr) && isPreemptible(Body, Type)) {
904 // We don't know anything about the finaly symbol. Just ask the dynamic
905 // linker to handle the relocation for us.
906 if (!Target->isPicRel(Type))
907 error("relocation " + toString(Type) +
908 " cannot be used against shared object; recompile with -fPIC" +
909 getLocation<ELFT>(Sec, Body, Offset));
911 In<ELFT>::RelaDyn->addReloc(
912 {Target->getDynRel(Type), &Sec, Offset, false, &Body, Addend});
914 // MIPS ABI turns using of GOT and dynamic relocations inside out.
915 // While regular ABI uses dynamic relocations to fill up GOT entries
916 // MIPS ABI requires dynamic linker to fills up GOT entries using
917 // specially sorted dynamic symbol table. This affects even dynamic
918 // relocations against symbols which do not require GOT entries
919 // creation explicitly, i.e. do not have any GOT-relocations. So if
920 // a preemptible symbol has a dynamic relocation we anyway have
921 // to create a GOT entry for it.
922 // If a non-preemptible symbol has a dynamic relocation against it,
923 // dynamic linker takes it st_value, adds offset and writes down
924 // result of the dynamic relocation. In case of preemptible symbol
925 // dynamic linker performs symbol resolution, writes the symbol value
926 // to the GOT entry and reads the GOT entry when it needs to perform
927 // a dynamic relocation.
928 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
929 if (Config->EMachine == EM_MIPS)
930 InX::MipsGot->addEntry(Body, Addend, Expr);
934 // If the relocation points to something in the file, we can process it.
936 isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, Sec, Rel.r_offset);
938 // The size is not going to change, so we fold it in here.
940 Addend += Body.getSize<ELFT>();
942 // If the output being produced is position independent, the final value
943 // is still not known. In that case we still need some help from the
944 // dynamic linker. We can however do better than just copying the incoming
945 // relocation. We can process some of it and and just ask the dynamic
946 // linker to add the load address.
948 In<ELFT>::RelaDyn->addReloc(
949 {Target->RelativeRel, &Sec, Offset, true, &Body, Addend});
951 // If the produced value is a constant, we just remember to write it
952 // when outputting this section. We also have to do it if the format
953 // uses Elf_Rel, since in that case the written value is the addend.
954 if (IsConstant || !RelTy::IsRela)
955 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
959 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
961 scanRelocs<ELFT>(S, S.relas<ELFT>());
963 scanRelocs<ELFT>(S, S.rels<ELFT>());
966 // Insert the Thunks for OutputSection OS into their designated place
967 // in the Sections vector, and recalculate the InputSection output section
969 // This may invalidate any output section offsets stored outside of InputSection
970 void ThunkCreator::mergeThunks(OutputSection *OS,
971 std::vector<ThunkSection *> &Thunks) {
972 // Order Thunks in ascending OutSecOff
973 auto ThunkCmp = [](const ThunkSection *A, const ThunkSection *B) {
974 return A->OutSecOff < B->OutSecOff;
976 std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
978 // Merge sorted vectors of Thunks and InputSections by OutSecOff
979 std::vector<InputSection *> Tmp;
980 Tmp.reserve(OS->Sections.size() + Thunks.size());
981 auto MergeCmp = [](const InputSection *A, const InputSection *B) {
982 // std::merge requires a strict weak ordering.
983 if (A->OutSecOff < B->OutSecOff)
985 if (A->OutSecOff == B->OutSecOff)
986 // Check if Thunk is immediately before any specific Target InputSection
987 // for example Mips LA25 Thunks.
988 if (auto *TA = dyn_cast<ThunkSection>(A))
989 if (TA && TA->getTargetInputSection() == B)
993 std::merge(OS->Sections.begin(), OS->Sections.end(), Thunks.begin(),
994 Thunks.end(), std::back_inserter(Tmp), MergeCmp);
995 OS->Sections = std::move(Tmp);
999 ThunkSection *ThunkCreator::getOSThunkSec(ThunkSection *&TS,
1000 OutputSection *OS) {
1001 if (TS == nullptr) {
1003 for (auto *IS : OS->Sections) {
1004 Off = IS->OutSecOff + IS->getSize();
1005 if ((IS->Flags & SHF_EXECINSTR) == 0)
1008 TS = make<ThunkSection>(OS, Off);
1009 ThunkSections[OS].push_back(TS);
1014 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS, OutputSection *OS) {
1015 ThunkSection *TS = ThunkedSections.lookup(IS);
1018 auto *TOS = cast<OutputSection>(IS->OutSec);
1019 TS = make<ThunkSection>(TOS, IS->OutSecOff);
1020 ThunkSections[TOS].push_back(TS);
1021 ThunkedSections[IS] = TS;
1025 std::pair<Thunk *, bool> ThunkCreator::getThunk(SymbolBody &Body,
1027 auto res = ThunkedSymbols.insert({&Body, nullptr});
1029 res.first->second = addThunk(Type, Body);
1030 return std::make_pair(res.first->second, res.second);
1033 // Process all relocations from the InputSections that have been assigned
1034 // to OutputSections and redirect through Thunks if needed.
1036 // createThunks must be called after scanRelocs has created the Relocations for
1037 // each InputSection. It must be called before the static symbol table is
1038 // finalized. If any Thunks are added to an OutputSection the output section
1039 // offsets of the InputSections will change.
1041 // FIXME: All Thunks are assumed to be in range of the relocation. Range
1042 // extension Thunks are not yet supported.
1043 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1044 // Create all the Thunks and insert them into synthetic ThunkSections. The
1045 // ThunkSections are later inserted back into the OutputSection.
1047 // We separate the creation of ThunkSections from the insertion of the
1048 // ThunkSections back into the OutputSection as ThunkSections are not always
1049 // inserted into the same OutputSection as the caller.
1050 for (OutputSection *OS : OutputSections) {
1051 ThunkSection *OSTS = nullptr;
1052 for (InputSection *IS : OS->Sections) {
1053 for (Relocation &Rel : IS->Relocations) {
1054 SymbolBody &Body = *Rel.Sym;
1055 if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Body))
1059 std::tie(T, IsNew) = getThunk(Body, Rel.Type);
1061 // Find or create a ThunkSection for the new Thunk
1063 if (auto *TIS = T->getTargetInputSection())
1064 TS = getISThunkSec(TIS, OS);
1066 TS = getOSThunkSec(OSTS, OS);
1069 // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1070 Rel.Sym = T->ThunkSym;
1071 Rel.Expr = fromPlt(Rel.Expr);
1076 // Merge all created synthetic ThunkSections back into OutputSection
1077 for (auto &KV : ThunkSections)
1078 mergeThunks(KV.first, KV.second);
1079 return !ThunkSections.empty();
1082 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1083 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1084 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1085 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);