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. 11 // 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. 16 // 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. 22 // 23 // ELF defines a large number of complex relocations. 24 // 25 // The functions in this file analyze relocations and do whatever needs 26 // to be done. It includes, but not limited to, the following. 27 // 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 35 // 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. 40 // 41 //===----------------------------------------------------------------------===// 42 43 #include "Relocations.h" 44 #include "Config.h" 45 #include "LinkerScript.h" 46 #include "OutputSections.h" 47 #include "SymbolTable.h" 48 #include "Symbols.h" 49 #include "SyntheticSections.h" 50 #include "Target.h" 51 #include "Thunks.h" 52 #include "lld/Common/ErrorHandler.h" 53 #include "lld/Common/Memory.h" 54 #include "lld/Common/Strings.h" 55 #include "llvm/ADT/SmallSet.h" 56 #include "llvm/Support/Endian.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include <algorithm> 59 60 using namespace llvm; 61 using namespace llvm::ELF; 62 using namespace llvm::object; 63 using namespace llvm::support::endian; 64 65 using namespace lld; 66 using namespace lld::elf; 67 68 static Optional<std::string> getLinkerScriptLocation(const Symbol &Sym) { 69 for (BaseCommand *Base : Script->SectionCommands) 70 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) 71 if (Cmd->Sym == &Sym) 72 return Cmd->Location; 73 return None; 74 } 75 76 // Construct a message in the following format. 77 // 78 // >>> defined in /home/alice/src/foo.o 79 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12) 80 // >>> /home/alice/src/bar.o:(.text+0x1) 81 static std::string getLocation(InputSectionBase &S, const Symbol &Sym, 82 uint64_t Off) { 83 std::string Msg = "\n>>> defined in "; 84 if (Sym.File) 85 Msg += toString(Sym.File); 86 else if (Optional<std::string> Loc = getLinkerScriptLocation(Sym)) 87 Msg += *Loc; 88 89 Msg += "\n>>> referenced by "; 90 std::string Src = S.getSrcMsg(Sym, Off); 91 if (!Src.empty()) 92 Msg += Src + "\n>>> "; 93 return Msg + S.getObjMsg(Off); 94 } 95 96 namespace { 97 // Build a bitmask with one bit set for each RelExpr. 98 // 99 // Constexpr function arguments can't be used in static asserts, so we 100 // use template arguments to build the mask. 101 // But function template partial specializations don't exist (needed 102 // for base case of the recursion), so we need a dummy struct. 103 template <RelExpr... Exprs> struct RelExprMaskBuilder { 104 static inline uint64_t build() { return 0; } 105 }; 106 107 // Specialization for recursive case. 108 template <RelExpr Head, RelExpr... Tail> 109 struct RelExprMaskBuilder<Head, Tail...> { 110 static inline uint64_t build() { 111 static_assert(0 <= Head && Head < 64, 112 "RelExpr is too large for 64-bit mask!"); 113 return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build(); 114 } 115 }; 116 } // namespace 117 118 // Return true if `Expr` is one of `Exprs`. 119 // There are fewer than 64 RelExpr's, so we can represent any set of 120 // RelExpr's as a constant bit mask and test for membership with a 121 // couple cheap bitwise operations. 122 template <RelExpr... Exprs> bool oneof(RelExpr Expr) { 123 assert(0 <= Expr && (int)Expr < 64 && 124 "RelExpr is too large for 64-bit mask!"); 125 return (uint64_t(1) << Expr) & RelExprMaskBuilder<Exprs...>::build(); 126 } 127 128 // This function is similar to the `handleTlsRelocation`. MIPS does not 129 // support any relaxations for TLS relocations so by factoring out MIPS 130 // handling in to the separate function we can simplify the code and do not 131 // pollute other `handleTlsRelocation` by MIPS `ifs` statements. 132 // Mips has a custom MipsGotSection that handles the writing of GOT entries 133 // without dynamic relocations. 134 static unsigned handleMipsTlsRelocation(RelType Type, Symbol &Sym, 135 InputSectionBase &C, uint64_t Offset, 136 int64_t Addend, RelExpr Expr) { 137 if (Expr == R_MIPS_TLSLD) { 138 In.MipsGot->addTlsIndex(*C.File); 139 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 140 return 1; 141 } 142 if (Expr == R_MIPS_TLSGD) { 143 In.MipsGot->addDynTlsEntry(*C.File, Sym); 144 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 145 return 1; 146 } 147 return 0; 148 } 149 150 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not 151 // support any relaxations for TLS relocations. ARM is logically similar to Mips 152 // in how it handles TLS, but Mips uses its own custom GOT which handles some 153 // of the cases that ARM uses GOT relocations for. 154 // 155 // We look for TLS global dynamic and local dynamic relocations, these may 156 // require the generation of a pair of GOT entries that have associated 157 // dynamic relocations. When the results of the dynamic relocations can be 158 // resolved at static link time we do so. This is necessary for static linking 159 // as there will be no dynamic loader to resolve them at load-time. 160 // 161 // The pair of GOT entries created are of the form 162 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time) 163 // GOT[e1] Offset of symbol in TLS block 164 static unsigned handleARMTlsRelocation(RelType Type, Symbol &Sym, 165 InputSectionBase &C, uint64_t Offset, 166 int64_t Addend, RelExpr Expr) { 167 // The Dynamic TLS Module Index Relocation for a symbol defined in an 168 // executable is always 1. If the target Symbol is not preemptible then 169 // we know the offset into the TLS block at static link time. 170 bool NeedDynId = Sym.IsPreemptible || Config->Shared; 171 bool NeedDynOff = Sym.IsPreemptible; 172 173 auto AddTlsReloc = [&](uint64_t Off, RelType Type, Symbol *Dest, bool Dyn) { 174 if (Dyn) 175 In.RelaDyn->addReloc(Type, In.Got, Off, Dest); 176 else 177 In.Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest}); 178 }; 179 180 // Local Dynamic is for access to module local TLS variables, while still 181 // being suitable for being dynamically loaded via dlopen. 182 // GOT[e0] is the module index, with a special value of 0 for the current 183 // module. GOT[e1] is unused. There only needs to be one module index entry. 184 if (Expr == R_TLSLD_PC && In.Got->addTlsIndex()) { 185 AddTlsReloc(In.Got->getTlsIndexOff(), Target->TlsModuleIndexRel, 186 NeedDynId ? nullptr : &Sym, NeedDynId); 187 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 188 return 1; 189 } 190 191 // Global Dynamic is the most general purpose access model. When we know 192 // the module index and offset of symbol in TLS block we can fill these in 193 // using static GOT relocations. 194 if (Expr == R_TLSGD_PC) { 195 if (In.Got->addDynTlsEntry(Sym)) { 196 uint64_t Off = In.Got->getGlobalDynOffset(Sym); 197 AddTlsReloc(Off, Target->TlsModuleIndexRel, &Sym, NeedDynId); 198 AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Sym, 199 NeedDynOff); 200 } 201 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 202 return 1; 203 } 204 return 0; 205 } 206 207 // Returns the number of relocations processed. 208 template <class ELFT> 209 static unsigned 210 handleTlsRelocation(RelType Type, Symbol &Sym, InputSectionBase &C, 211 typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) { 212 if (!Sym.isTls()) 213 return 0; 214 215 if (Config->EMachine == EM_ARM) 216 return handleARMTlsRelocation(Type, Sym, C, Offset, Addend, Expr); 217 if (Config->EMachine == EM_MIPS) 218 return handleMipsTlsRelocation(Type, Sym, C, Offset, Addend, Expr); 219 220 if (oneof<R_TLSDESC, R_AARCH64_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) && 221 Config->Shared) { 222 if (In.Got->addDynTlsEntry(Sym)) { 223 uint64_t Off = In.Got->getGlobalDynOffset(Sym); 224 In.RelaDyn->addReloc( 225 {Target->TlsDescRel, In.Got, Off, !Sym.IsPreemptible, &Sym, 0}); 226 } 227 if (Expr != R_TLSDESC_CALL) 228 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 229 return 1; 230 } 231 232 if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>( 233 Expr)) { 234 // Local-Dynamic relocs can be relaxed to Local-Exec. 235 if (!Config->Shared) { 236 C.Relocations.push_back( 237 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_LD_TO_LE), Type, 238 Offset, Addend, &Sym}); 239 return Target->getTlsGdRelaxSkip(Type); 240 } 241 if (Expr == R_TLSLD_HINT) 242 return 1; 243 if (In.Got->addTlsIndex()) 244 In.RelaDyn->addReloc(Target->TlsModuleIndexRel, In.Got, 245 In.Got->getTlsIndexOff(), nullptr); 246 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 247 return 1; 248 } 249 250 // Local-Dynamic relocs can be relaxed to Local-Exec. 251 if (Expr == R_ABS && !Config->Shared) { 252 C.Relocations.push_back( 253 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_LD_TO_LE), Type, 254 Offset, Addend, &Sym}); 255 return 1; 256 } 257 258 // Local-Dynamic sequence where offset of tls variable relative to dynamic 259 // thread pointer is stored in the got. 260 if (Expr == R_TLSLD_GOT_OFF) { 261 // Local-Dynamic relocs can be relaxed to local-exec 262 if (!Config->Shared) { 263 C.Relocations.push_back({R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Sym}); 264 return 1; 265 } 266 if (!Sym.isInGot()) { 267 In.Got->addEntry(Sym); 268 uint64_t Off = Sym.getGotOffset(); 269 In.Got->Relocations.push_back( 270 {R_ABS, Target->TlsOffsetRel, Off, 0, &Sym}); 271 } 272 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 273 return 1; 274 } 275 276 if (oneof<R_TLSDESC, R_AARCH64_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD_GOT, 277 R_TLSGD_GOTPLT, R_TLSGD_PC>(Expr)) { 278 if (Config->Shared) { 279 if (In.Got->addDynTlsEntry(Sym)) { 280 uint64_t Off = In.Got->getGlobalDynOffset(Sym); 281 In.RelaDyn->addReloc(Target->TlsModuleIndexRel, In.Got, Off, &Sym); 282 283 // If the symbol is preemptible we need the dynamic linker to write 284 // the offset too. 285 uint64_t OffsetOff = Off + Config->Wordsize; 286 if (Sym.IsPreemptible) 287 In.RelaDyn->addReloc(Target->TlsOffsetRel, In.Got, OffsetOff, &Sym); 288 else 289 In.Got->Relocations.push_back( 290 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Sym}); 291 } 292 C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 293 return 1; 294 } 295 296 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec 297 // depending on the symbol being locally defined or not. 298 if (Sym.IsPreemptible) { 299 C.Relocations.push_back( 300 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type, 301 Offset, Addend, &Sym}); 302 if (!Sym.isInGot()) { 303 In.Got->addEntry(Sym); 304 In.RelaDyn->addReloc(Target->TlsGotRel, In.Got, Sym.getGotOffset(), 305 &Sym); 306 } 307 } else { 308 C.Relocations.push_back( 309 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, 310 Offset, Addend, &Sym}); 311 } 312 return Target->getTlsGdRelaxSkip(Type); 313 } 314 315 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally 316 // defined. 317 if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF, 318 R_TLSIE_HINT>(Expr) && 319 !Config->Shared && !Sym.IsPreemptible) { 320 C.Relocations.push_back({R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Sym}); 321 return 1; 322 } 323 324 if (Expr == R_TLSIE_HINT) 325 return 1; 326 return 0; 327 } 328 329 static RelType getMipsPairType(RelType Type, bool IsLocal) { 330 switch (Type) { 331 case R_MIPS_HI16: 332 return R_MIPS_LO16; 333 case R_MIPS_GOT16: 334 // In case of global symbol, the R_MIPS_GOT16 relocation does not 335 // have a pair. Each global symbol has a unique entry in the GOT 336 // and a corresponding instruction with help of the R_MIPS_GOT16 337 // relocation loads an address of the symbol. In case of local 338 // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold 339 // the high 16 bits of the symbol's value. A paired R_MIPS_LO16 340 // relocations handle low 16 bits of the address. That allows 341 // to allocate only one GOT entry for every 64 KBytes of local data. 342 return IsLocal ? R_MIPS_LO16 : R_MIPS_NONE; 343 case R_MICROMIPS_GOT16: 344 return IsLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE; 345 case R_MIPS_PCHI16: 346 return R_MIPS_PCLO16; 347 case R_MICROMIPS_HI16: 348 return R_MICROMIPS_LO16; 349 default: 350 return R_MIPS_NONE; 351 } 352 } 353 354 // True if non-preemptable symbol always has the same value regardless of where 355 // the DSO is loaded. 356 static bool isAbsolute(const Symbol &Sym) { 357 if (Sym.isUndefWeak()) 358 return true; 359 if (const auto *DR = dyn_cast<Defined>(&Sym)) 360 return DR->Section == nullptr; // Absolute symbol. 361 return false; 362 } 363 364 static bool isAbsoluteValue(const Symbol &Sym) { 365 return isAbsolute(Sym) || Sym.isTls(); 366 } 367 368 // Returns true if Expr refers a PLT entry. 369 static bool needsPlt(RelExpr Expr) { 370 return oneof<R_PLT_PC, R_PPC_CALL_PLT, R_PLT>(Expr); 371 } 372 373 // Returns true if Expr refers a GOT entry. Note that this function 374 // returns false for TLS variables even though they need GOT, because 375 // TLS variables uses GOT differently than the regular variables. 376 static bool needsGot(RelExpr Expr) { 377 return oneof<R_GOT, R_GOT_OFF, R_HEXAGON_GOT, R_MIPS_GOT_LOCAL_PAGE, 378 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, 379 R_GOT_PC, R_GOTPLT>(Expr); 380 } 381 382 // True if this expression is of the form Sym - X, where X is a position in the 383 // file (PC, or GOT for example). 384 static bool isRelExpr(RelExpr Expr) { 385 return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC_CALL, 386 R_PPC_CALL_PLT, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC>(Expr); 387 } 388 389 // Returns true if a given relocation can be computed at link-time. 390 // 391 // For instance, we know the offset from a relocation to its target at 392 // link-time if the relocation is PC-relative and refers a 393 // non-interposable function in the same executable. This function 394 // will return true for such relocation. 395 // 396 // If this function returns false, that means we need to emit a 397 // dynamic relocation so that the relocation will be fixed at load-time. 398 static bool isStaticLinkTimeConstant(RelExpr E, RelType Type, const Symbol &Sym, 399 InputSectionBase &S, uint64_t RelOff) { 400 // These expressions always compute a constant 401 if (oneof<R_GOTPLT, R_GOT_OFF, R_HEXAGON_GOT, R_TLSLD_GOT_OFF, 402 R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, R_MIPS_GOT_OFF, 403 R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, R_MIPS_TLSGD, 404 R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, 405 R_GOTPLTONLY_PC, R_PLT_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, 406 R_TLSGD_PC, R_PPC_CALL_PLT, R_TLSDESC_CALL, R_AARCH64_TLSDESC_PAGE, 407 R_HINT, R_TLSLD_HINT, R_TLSIE_HINT>(E)) 408 return true; 409 410 // These never do, except if the entire file is position dependent or if 411 // only the low bits are used. 412 if (E == R_GOT || E == R_PLT || E == R_TLSDESC) 413 return Target->usesOnlyLowPageBits(Type) || !Config->Pic; 414 415 if (Sym.IsPreemptible) 416 return false; 417 if (!Config->Pic) 418 return true; 419 420 // The size of a non preemptible symbol is a constant. 421 if (E == R_SIZE) 422 return true; 423 424 // For the target and the relocation, we want to know if they are 425 // absolute or relative. 426 bool AbsVal = isAbsoluteValue(Sym); 427 bool RelE = isRelExpr(E); 428 if (AbsVal && !RelE) 429 return true; 430 if (!AbsVal && RelE) 431 return true; 432 if (!AbsVal && !RelE) 433 return Target->usesOnlyLowPageBits(Type); 434 435 // Relative relocation to an absolute value. This is normally unrepresentable, 436 // but if the relocation refers to a weak undefined symbol, we allow it to 437 // resolve to the image base. This is a little strange, but it allows us to 438 // link function calls to such symbols. Normally such a call will be guarded 439 // with a comparison, which will load a zero from the GOT. 440 // Another special case is MIPS _gp_disp symbol which represents offset 441 // between start of a function and '_gp' value and defined as absolute just 442 // to simplify the code. 443 assert(AbsVal && RelE); 444 if (Sym.isUndefWeak()) 445 return true; 446 447 error("relocation " + toString(Type) + " cannot refer to absolute symbol: " + 448 toString(Sym) + getLocation(S, Sym, RelOff)); 449 return true; 450 } 451 452 static RelExpr toPlt(RelExpr Expr) { 453 switch (Expr) { 454 case R_PPC_CALL: 455 return R_PPC_CALL_PLT; 456 case R_PC: 457 return R_PLT_PC; 458 case R_ABS: 459 return R_PLT; 460 default: 461 return Expr; 462 } 463 } 464 465 static RelExpr fromPlt(RelExpr Expr) { 466 // We decided not to use a plt. Optimize a reference to the plt to a 467 // reference to the symbol itself. 468 switch (Expr) { 469 case R_PLT_PC: 470 return R_PC; 471 case R_PPC_CALL_PLT: 472 return R_PPC_CALL; 473 case R_PLT: 474 return R_ABS; 475 default: 476 return Expr; 477 } 478 } 479 480 // Returns true if a given shared symbol is in a read-only segment in a DSO. 481 template <class ELFT> static bool isReadOnly(SharedSymbol &SS) { 482 using Elf_Phdr = typename ELFT::Phdr; 483 484 // Determine if the symbol is read-only by scanning the DSO's program headers. 485 const SharedFile &File = SS.getFile(); 486 for (const Elf_Phdr &Phdr : 487 check(File.template getObj<ELFT>().program_headers())) 488 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) && 489 !(Phdr.p_flags & ELF::PF_W) && SS.Value >= Phdr.p_vaddr && 490 SS.Value < Phdr.p_vaddr + Phdr.p_memsz) 491 return true; 492 return false; 493 } 494 495 // Returns symbols at the same offset as a given symbol, including SS itself. 496 // 497 // If two or more symbols are at the same offset, and at least one of 498 // them are copied by a copy relocation, all of them need to be copied. 499 // Otherwise, they would refer to different places at runtime. 500 template <class ELFT> 501 static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &SS) { 502 using Elf_Sym = typename ELFT::Sym; 503 504 SharedFile &File = SS.getFile(); 505 506 SmallSet<SharedSymbol *, 4> Ret; 507 for (const Elf_Sym &S : File.template getGlobalELFSyms<ELFT>()) { 508 if (S.st_shndx == SHN_UNDEF || S.st_shndx == SHN_ABS || 509 S.getType() == STT_TLS || S.st_value != SS.Value) 510 continue; 511 StringRef Name = check(S.getName(File.getStringTable())); 512 Symbol *Sym = Symtab->find(Name); 513 if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym)) 514 Ret.insert(Alias); 515 } 516 return Ret; 517 } 518 519 // When a symbol is copy relocated or we create a canonical plt entry, it is 520 // effectively a defined symbol. In the case of copy relocation the symbol is 521 // in .bss and in the case of a canonical plt entry it is in .plt. This function 522 // replaces the existing symbol with a Defined pointing to the appropriate 523 // location. 524 static void replaceWithDefined(Symbol &Sym, SectionBase *Sec, uint64_t Value, 525 uint64_t Size) { 526 Symbol Old = Sym; 527 replaceSymbol<Defined>(&Sym, Sym.File, Sym.getName(), Sym.Binding, 528 Sym.StOther, Sym.Type, Value, Size, Sec); 529 Sym.PltIndex = Old.PltIndex; 530 Sym.GotIndex = Old.GotIndex; 531 Sym.VerdefIndex = Old.VerdefIndex; 532 Sym.PPC64BranchltIndex = Old.PPC64BranchltIndex; 533 Sym.IsPreemptible = true; 534 Sym.ExportDynamic = true; 535 Sym.IsUsedInRegularObj = true; 536 Sym.Used = true; 537 } 538 539 // Reserve space in .bss or .bss.rel.ro for copy relocation. 540 // 541 // The copy relocation is pretty much a hack. If you use a copy relocation 542 // in your program, not only the symbol name but the symbol's size, RW/RO 543 // bit and alignment become part of the ABI. In addition to that, if the 544 // symbol has aliases, the aliases become part of the ABI. That's subtle, 545 // but if you violate that implicit ABI, that can cause very counter- 546 // intuitive consequences. 547 // 548 // So, what is the copy relocation? It's for linking non-position 549 // independent code to DSOs. In an ideal world, all references to data 550 // exported by DSOs should go indirectly through GOT. But if object files 551 // are compiled as non-PIC, all data references are direct. There is no 552 // way for the linker to transform the code to use GOT, as machine 553 // instructions are already set in stone in object files. This is where 554 // the copy relocation takes a role. 555 // 556 // A copy relocation instructs the dynamic linker to copy data from a DSO 557 // to a specified address (which is usually in .bss) at load-time. If the 558 // static linker (that's us) finds a direct data reference to a DSO 559 // symbol, it creates a copy relocation, so that the symbol can be 560 // resolved as if it were in .bss rather than in a DSO. 561 // 562 // As you can see in this function, we create a copy relocation for the 563 // dynamic linker, and the relocation contains not only symbol name but 564 // various other informtion about the symbol. So, such attributes become a 565 // part of the ABI. 566 // 567 // Note for application developers: I can give you a piece of advice if 568 // you are writing a shared library. You probably should export only 569 // functions from your library. You shouldn't export variables. 570 // 571 // As an example what can happen when you export variables without knowing 572 // the semantics of copy relocations, assume that you have an exported 573 // variable of type T. It is an ABI-breaking change to add new members at 574 // end of T even though doing that doesn't change the layout of the 575 // existing members. That's because the space for the new members are not 576 // reserved in .bss unless you recompile the main program. That means they 577 // are likely to overlap with other data that happens to be laid out next 578 // to the variable in .bss. This kind of issue is sometimes very hard to 579 // debug. What's a solution? Instead of exporting a varaible V from a DSO, 580 // define an accessor getV(). 581 template <class ELFT> static void addCopyRelSymbol(SharedSymbol &SS) { 582 // Copy relocation against zero-sized symbol doesn't make sense. 583 uint64_t SymSize = SS.getSize(); 584 if (SymSize == 0 || SS.Alignment == 0) 585 fatal("cannot create a copy relocation for symbol " + toString(SS)); 586 587 // See if this symbol is in a read-only segment. If so, preserve the symbol's 588 // memory protection by reserving space in the .bss.rel.ro section. 589 bool IsReadOnly = isReadOnly<ELFT>(SS); 590 BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss", 591 SymSize, SS.Alignment); 592 if (IsReadOnly) 593 In.BssRelRo->getParent()->addSection(Sec); 594 else 595 In.Bss->getParent()->addSection(Sec); 596 597 // Look through the DSO's dynamic symbol table for aliases and create a 598 // dynamic symbol for each one. This causes the copy relocation to correctly 599 // interpose any aliases. 600 for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) 601 replaceWithDefined(*Sym, Sec, 0, Sym->Size); 602 603 In.RelaDyn->addReloc(Target->CopyRel, Sec, 0, &SS); 604 } 605 606 // MIPS has an odd notion of "paired" relocations to calculate addends. 607 // For example, if a relocation is of R_MIPS_HI16, there must be a 608 // R_MIPS_LO16 relocation after that, and an addend is calculated using 609 // the two relocations. 610 template <class ELFT, class RelTy> 611 static int64_t computeMipsAddend(const RelTy &Rel, const RelTy *End, 612 InputSectionBase &Sec, RelExpr Expr, 613 bool IsLocal) { 614 if (Expr == R_MIPS_GOTREL && IsLocal) 615 return Sec.getFile<ELFT>()->MipsGp0; 616 617 // The ABI says that the paired relocation is used only for REL. 618 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 619 if (RelTy::IsRela) 620 return 0; 621 622 RelType Type = Rel.getType(Config->IsMips64EL); 623 uint32_t PairTy = getMipsPairType(Type, IsLocal); 624 if (PairTy == R_MIPS_NONE) 625 return 0; 626 627 const uint8_t *Buf = Sec.data().data(); 628 uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL); 629 630 // To make things worse, paired relocations might not be contiguous in 631 // the relocation table, so we need to do linear search. *sigh* 632 for (const RelTy *RI = &Rel; RI != End; ++RI) 633 if (RI->getType(Config->IsMips64EL) == PairTy && 634 RI->getSymbol(Config->IsMips64EL) == SymIndex) 635 return Target->getImplicitAddend(Buf + RI->r_offset, PairTy); 636 637 warn("can't find matching " + toString(PairTy) + " relocation for " + 638 toString(Type)); 639 return 0; 640 } 641 642 // Returns an addend of a given relocation. If it is RELA, an addend 643 // is in a relocation itself. If it is REL, we need to read it from an 644 // input section. 645 template <class ELFT, class RelTy> 646 static int64_t computeAddend(const RelTy &Rel, const RelTy *End, 647 InputSectionBase &Sec, RelExpr Expr, 648 bool IsLocal) { 649 int64_t Addend; 650 RelType Type = Rel.getType(Config->IsMips64EL); 651 652 if (RelTy::IsRela) { 653 Addend = getAddend<ELFT>(Rel); 654 } else { 655 const uint8_t *Buf = Sec.data().data(); 656 Addend = Target->getImplicitAddend(Buf + Rel.r_offset, Type); 657 } 658 659 if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC) 660 Addend += getPPC64TocBase(); 661 if (Config->EMachine == EM_MIPS) 662 Addend += computeMipsAddend<ELFT>(Rel, End, Sec, Expr, IsLocal); 663 664 return Addend; 665 } 666 667 // Report an undefined symbol if necessary. 668 // Returns true if this function printed out an error message. 669 static bool maybeReportUndefined(Symbol &Sym, InputSectionBase &Sec, 670 uint64_t Offset) { 671 if (Sym.isLocal() || !Sym.isUndefined() || Sym.isWeak()) 672 return false; 673 674 bool CanBeExternal = 675 Sym.computeBinding() != STB_LOCAL && Sym.Visibility == STV_DEFAULT; 676 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal) 677 return false; 678 679 std::string Msg = "undefined "; 680 if (Sym.Visibility == STV_INTERNAL) 681 Msg += "internal "; 682 else if (Sym.Visibility == STV_HIDDEN) 683 Msg += "hidden "; 684 else if (Sym.Visibility == STV_PROTECTED) 685 Msg += "protected "; 686 Msg += "symbol: " + toString(Sym) + "\n>>> referenced by "; 687 688 std::string Src = Sec.getSrcMsg(Sym, Offset); 689 if (!Src.empty()) 690 Msg += Src + "\n>>> "; 691 Msg += Sec.getObjMsg(Offset); 692 693 if (Sym.getName().startswith("_ZTV")) 694 Msg += "\nthe vtable symbol may be undefined because the class is missing " 695 "its key function (see https://lld.llvm.org/missingkeyfunction)"; 696 697 if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) || 698 Config->NoinhibitExec) { 699 warn(Msg); 700 return false; 701 } 702 703 error(Msg); 704 return true; 705 } 706 707 // MIPS N32 ABI treats series of successive relocations with the same offset 708 // as a single relocation. The similar approach used by N64 ABI, but this ABI 709 // packs all relocations into the single relocation record. Here we emulate 710 // this for the N32 ABI. Iterate over relocation with the same offset and put 711 // theirs types into the single bit-set. 712 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) { 713 RelType Type = 0; 714 uint64_t Offset = Rel->r_offset; 715 716 int N = 0; 717 while (Rel != End && Rel->r_offset == Offset) 718 Type |= (Rel++)->getType(Config->IsMips64EL) << (8 * N++); 719 return Type; 720 } 721 722 // .eh_frame sections are mergeable input sections, so their input 723 // offsets are not linearly mapped to output section. For each input 724 // offset, we need to find a section piece containing the offset and 725 // add the piece's base address to the input offset to compute the 726 // output offset. That isn't cheap. 727 // 728 // This class is to speed up the offset computation. When we process 729 // relocations, we access offsets in the monotonically increasing 730 // order. So we can optimize for that access pattern. 731 // 732 // For sections other than .eh_frame, this class doesn't do anything. 733 namespace { 734 class OffsetGetter { 735 public: 736 explicit OffsetGetter(InputSectionBase &Sec) { 737 if (auto *Eh = dyn_cast<EhInputSection>(&Sec)) 738 Pieces = Eh->Pieces; 739 } 740 741 // Translates offsets in input sections to offsets in output sections. 742 // Given offset must increase monotonically. We assume that Piece is 743 // sorted by InputOff. 744 uint64_t get(uint64_t Off) { 745 if (Pieces.empty()) 746 return Off; 747 748 while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off) 749 ++I; 750 if (I == Pieces.size()) 751 fatal(".eh_frame: relocation is not in any piece"); 752 753 // Pieces must be contiguous, so there must be no holes in between. 754 assert(Pieces[I].InputOff <= Off && "Relocation not in any piece"); 755 756 // Offset -1 means that the piece is dead (i.e. garbage collected). 757 if (Pieces[I].OutputOff == -1) 758 return -1; 759 return Pieces[I].OutputOff + Off - Pieces[I].InputOff; 760 } 761 762 private: 763 ArrayRef<EhSectionPiece> Pieces; 764 size_t I = 0; 765 }; 766 } // namespace 767 768 static void addRelativeReloc(InputSectionBase *IS, uint64_t OffsetInSec, 769 Symbol *Sym, int64_t Addend, RelExpr Expr, 770 RelType Type) { 771 // Add a relative relocation. If RelrDyn section is enabled, and the 772 // relocation offset is guaranteed to be even, add the relocation to 773 // the RelrDyn section, otherwise add it to the RelaDyn section. 774 // RelrDyn sections don't support odd offsets. Also, RelrDyn sections 775 // don't store the addend values, so we must write it to the relocated 776 // address. 777 if (In.RelrDyn && IS->Alignment >= 2 && OffsetInSec % 2 == 0) { 778 IS->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym}); 779 In.RelrDyn->Relocs.push_back({IS, OffsetInSec}); 780 return; 781 } 782 In.RelaDyn->addReloc(Target->RelativeRel, IS, OffsetInSec, Sym, Addend, Expr, 783 Type); 784 } 785 786 template <class ELFT, class GotPltSection> 787 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt, 788 RelocationBaseSection *Rel, RelType Type, Symbol &Sym) { 789 Plt->addEntry<ELFT>(Sym); 790 GotPlt->addEntry(Sym); 791 Rel->addReloc( 792 {Type, GotPlt, Sym.getGotPltOffset(), !Sym.IsPreemptible, &Sym, 0}); 793 } 794 795 static void addGotEntry(Symbol &Sym) { 796 In.Got->addEntry(Sym); 797 798 RelExpr Expr = Sym.isTls() ? R_TLS : R_ABS; 799 uint64_t Off = Sym.getGotOffset(); 800 801 // If a GOT slot value can be calculated at link-time, which is now, 802 // we can just fill that out. 803 // 804 // (We don't actually write a value to a GOT slot right now, but we 805 // add a static relocation to a Relocations vector so that 806 // InputSection::relocate will do the work for us. We may be able 807 // to just write a value now, but it is a TODO.) 808 bool IsLinkTimeConstant = 809 !Sym.IsPreemptible && (!Config->Pic || isAbsolute(Sym)); 810 if (IsLinkTimeConstant) { 811 In.Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym}); 812 return; 813 } 814 815 // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that 816 // the GOT slot will be fixed at load-time. 817 if (!Sym.isTls() && !Sym.IsPreemptible && Config->Pic && !isAbsolute(Sym)) { 818 addRelativeReloc(In.Got, Off, &Sym, 0, R_ABS, Target->GotRel); 819 return; 820 } 821 In.RelaDyn->addReloc(Sym.isTls() ? Target->TlsGotRel : Target->GotRel, In.Got, 822 Off, &Sym, 0, Sym.IsPreemptible ? R_ADDEND : R_ABS, 823 Target->GotRel); 824 } 825 826 // Return true if we can define a symbol in the executable that 827 // contains the value/function of a symbol defined in a shared 828 // library. 829 static bool canDefineSymbolInExecutable(Symbol &Sym) { 830 // If the symbol has default visibility the symbol defined in the 831 // executable will preempt it. 832 // Note that we want the visibility of the shared symbol itself, not 833 // the visibility of the symbol in the output file we are producing. That is 834 // why we use Sym.StOther. 835 if ((Sym.StOther & 0x3) == STV_DEFAULT) 836 return true; 837 838 // If we are allowed to break address equality of functions, defining 839 // a plt entry will allow the program to call the function in the 840 // .so, but the .so and the executable will no agree on the address 841 // of the function. Similar logic for objects. 842 return ((Sym.isFunc() && Config->IgnoreFunctionAddressEquality) || 843 (Sym.isObject() && Config->IgnoreDataAddressEquality)); 844 } 845 846 // The reason we have to do this early scan is as follows 847 // * To mmap the output file, we need to know the size 848 // * For that, we need to know how many dynamic relocs we will have. 849 // It might be possible to avoid this by outputting the file with write: 850 // * Write the allocated output sections, computing addresses. 851 // * Apply relocations, recording which ones require a dynamic reloc. 852 // * Write the dynamic relocations. 853 // * Write the rest of the file. 854 // This would have some drawbacks. For example, we would only know if .rela.dyn 855 // is needed after applying relocations. If it is, it will go after rw and rx 856 // sections. Given that it is ro, we will need an extra PT_LOAD. This 857 // complicates things for the dynamic linker and means we would have to reserve 858 // space for the extra PT_LOAD even if we end up not using it. 859 template <class ELFT, class RelTy> 860 static void processRelocAux(InputSectionBase &Sec, RelExpr Expr, RelType Type, 861 uint64_t Offset, Symbol &Sym, const RelTy &Rel, 862 int64_t Addend) { 863 if (isStaticLinkTimeConstant(Expr, Type, Sym, Sec, Offset)) { 864 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 865 return; 866 } 867 bool CanWrite = (Sec.Flags & SHF_WRITE) || !Config->ZText; 868 if (CanWrite) { 869 // R_GOT refers to a position in the got, even if the symbol is preemptible. 870 bool IsPreemptibleValue = Sym.IsPreemptible && Expr != R_GOT; 871 872 if (!IsPreemptibleValue) { 873 addRelativeReloc(&Sec, Offset, &Sym, Addend, Expr, Type); 874 return; 875 } else if (RelType Rel = Target->getDynRel(Type)) { 876 In.RelaDyn->addReloc(Rel, &Sec, Offset, &Sym, Addend, R_ADDEND, Type); 877 878 // MIPS ABI turns using of GOT and dynamic relocations inside out. 879 // While regular ABI uses dynamic relocations to fill up GOT entries 880 // MIPS ABI requires dynamic linker to fills up GOT entries using 881 // specially sorted dynamic symbol table. This affects even dynamic 882 // relocations against symbols which do not require GOT entries 883 // creation explicitly, i.e. do not have any GOT-relocations. So if 884 // a preemptible symbol has a dynamic relocation we anyway have 885 // to create a GOT entry for it. 886 // If a non-preemptible symbol has a dynamic relocation against it, 887 // dynamic linker takes it st_value, adds offset and writes down 888 // result of the dynamic relocation. In case of preemptible symbol 889 // dynamic linker performs symbol resolution, writes the symbol value 890 // to the GOT entry and reads the GOT entry when it needs to perform 891 // a dynamic relocation. 892 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 893 if (Config->EMachine == EM_MIPS) 894 In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr); 895 return; 896 } 897 } 898 899 // If the relocation is to a weak undef, and we are producing 900 // executable, give up on it and produce a non preemptible 0. 901 if (!Config->Shared && Sym.isUndefWeak()) { 902 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 903 return; 904 } 905 906 if (!CanWrite && (Config->Pic && !isRelExpr(Expr))) { 907 error( 908 "can't create dynamic relocation " + toString(Type) + " against " + 909 (Sym.getName().empty() ? "local symbol" : "symbol: " + toString(Sym)) + 910 " in readonly segment; recompile object files with -fPIC " 911 "or pass '-Wl,-z,notext' to allow text relocations in the output" + 912 getLocation(Sec, Sym, Offset)); 913 return; 914 } 915 916 // Copy relocations are only possible if we are creating an executable. 917 if (Config->Shared) { 918 errorOrWarn("relocation " + toString(Type) + 919 " cannot be used against symbol " + toString(Sym) + 920 "; recompile with -fPIC" + getLocation(Sec, Sym, Offset)); 921 return; 922 } 923 924 // If the symbol is undefined we already reported any relevant errors. 925 if (Sym.isUndefined()) 926 return; 927 928 if (!canDefineSymbolInExecutable(Sym)) { 929 error("cannot preempt symbol: " + toString(Sym) + 930 getLocation(Sec, Sym, Offset)); 931 return; 932 } 933 934 if (Sym.isObject()) { 935 // Produce a copy relocation. 936 if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) { 937 if (!Config->ZCopyreloc) 938 error("unresolvable relocation " + toString(Type) + 939 " against symbol '" + toString(*SS) + 940 "'; recompile with -fPIC or remove '-z nocopyreloc'" + 941 getLocation(Sec, Sym, Offset)); 942 addCopyRelSymbol<ELFT>(*SS); 943 } 944 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 945 return; 946 } 947 948 if (Sym.isFunc()) { 949 // This handles a non PIC program call to function in a shared library. In 950 // an ideal world, we could just report an error saying the relocation can 951 // overflow at runtime. In the real world with glibc, crt1.o has a 952 // R_X86_64_PC32 pointing to libc.so. 953 // 954 // The general idea on how to handle such cases is to create a PLT entry and 955 // use that as the function value. 956 // 957 // For the static linking part, we just return a plt expr and everything 958 // else will use the PLT entry as the address. 959 // 960 // The remaining problem is making sure pointer equality still works. We 961 // need the help of the dynamic linker for that. We let it know that we have 962 // a direct reference to a so symbol by creating an undefined symbol with a 963 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to 964 // the value of the symbol we created. This is true even for got entries, so 965 // pointer equality is maintained. To avoid an infinite loop, the only entry 966 // that points to the real function is a dedicated got entry used by the 967 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT, 968 // R_386_JMP_SLOT, etc). 969 970 // For position independent executable on i386, the plt entry requires ebx 971 // to be set. This causes two problems: 972 // * If some code has a direct reference to a function, it was probably 973 // compiled without -fPIE/-fPIC and doesn't maintain ebx. 974 // * If a library definition gets preempted to the executable, it will have 975 // the wrong ebx value. 976 if (Config->Pie && Config->EMachine == EM_386) 977 errorOrWarn("symbol '" + toString(Sym) + 978 "' cannot be preempted; recompile with -fPIE" + 979 getLocation(Sec, Sym, Offset)); 980 if (!Sym.isInPlt()) 981 addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym); 982 if (!Sym.isDefined()) 983 replaceWithDefined( 984 Sym, In.Plt, 985 Target->PltHeaderSize + Target->PltEntrySize * Sym.PltIndex, 0); 986 Sym.NeedsPltAddr = true; 987 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym}); 988 return; 989 } 990 991 errorOrWarn("symbol '" + toString(Sym) + "' has no type" + 992 getLocation(Sec, Sym, Offset)); 993 } 994 995 struct IRelativeReloc { 996 RelType Type; 997 InputSectionBase *Sec; 998 uint64_t Offset; 999 Symbol *Sym; 1000 }; 1001 1002 static std::vector<IRelativeReloc> IRelativeRelocs; 1003 1004 template <class ELFT, class RelTy> 1005 static void scanReloc(InputSectionBase &Sec, OffsetGetter &GetOffset, RelTy *&I, 1006 RelTy *End) { 1007 const RelTy &Rel = *I; 1008 Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel); 1009 RelType Type; 1010 1011 // Deal with MIPS oddity. 1012 if (Config->MipsN32Abi) { 1013 Type = getMipsN32RelType(I, End); 1014 } else { 1015 Type = Rel.getType(Config->IsMips64EL); 1016 ++I; 1017 } 1018 1019 // Get an offset in an output section this relocation is applied to. 1020 uint64_t Offset = GetOffset.get(Rel.r_offset); 1021 if (Offset == uint64_t(-1)) 1022 return; 1023 1024 // Skip if the target symbol is an erroneous undefined symbol. 1025 if (maybeReportUndefined(Sym, Sec, Rel.r_offset)) 1026 return; 1027 1028 const uint8_t *RelocatedAddr = Sec.data().begin() + Rel.r_offset; 1029 RelExpr Expr = Target->getRelExpr(Type, Sym, RelocatedAddr); 1030 1031 // Ignore "hint" relocations because they are only markers for relaxation. 1032 if (oneof<R_HINT, R_NONE>(Expr)) 1033 return; 1034 1035 // We can separate the small code model relocations into 2 categories: 1036 // 1) Those that access the compiler generated .toc sections. 1037 // 2) Those that access the linker allocated got entries. 1038 // lld allocates got entries to symbols on demand. Since we don't try to sort 1039 // the got entries in any way, we don't have to track which objects have 1040 // got-based small code model relocs. The .toc sections get placed after the 1041 // end of the linker allocated .got section and we do sort those so sections 1042 // addressed with small code model relocations come first. 1043 if (Config->EMachine == EM_PPC64 && isPPC64SmallCodeModelTocReloc(Type)) 1044 Sec.File->PPC64SmallCodeModelTocRelocs = true; 1045 1046 if (Sym.isGnuIFunc() && !Config->ZText && Config->WarnIfuncTextrel) { 1047 warn("using ifunc symbols when text relocations are allowed may produce " 1048 "a binary that will segfault, if the object file is linked with " 1049 "old version of glibc (glibc 2.28 and earlier). If this applies to " 1050 "you, consider recompiling the object files without -fPIC and " 1051 "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to " 1052 "turn off this warning." + 1053 getLocation(Sec, Sym, Offset)); 1054 } 1055 1056 // Relax relocations. 1057 // 1058 // If we know that a PLT entry will be resolved within the same ELF module, we 1059 // can skip PLT access and directly jump to the destination function. For 1060 // example, if we are linking a main exectuable, all dynamic symbols that can 1061 // be resolved within the executable will actually be resolved that way at 1062 // runtime, because the main exectuable is always at the beginning of a search 1063 // list. We can leverage that fact. 1064 if (!Sym.IsPreemptible && !Sym.isGnuIFunc()) { 1065 if (Expr == R_GOT_PC && !isAbsoluteValue(Sym)) 1066 Expr = Target->adjustRelaxExpr(Type, RelocatedAddr, Expr); 1067 else 1068 Expr = fromPlt(Expr); 1069 } 1070 1071 // If the relocation does not emit a GOT or GOTPLT entry but its computation 1072 // uses their addresses, we need GOT or GOTPLT to be created. 1073 // 1074 // The 4 types that relative GOTPLT are all x86 and x86-64 specific. 1075 if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_TLSGD_GOTPLT>(Expr)) { 1076 In.GotPlt->HasGotPltOffRel = true; 1077 } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC_TOC>(Expr)) { 1078 In.Got->HasGotOffRel = true; 1079 } 1080 1081 // Read an addend. 1082 int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Sym.isLocal()); 1083 1084 // Process some TLS relocations, including relaxing TLS relocations. 1085 // Note that this function does not handle all TLS relocations. 1086 if (unsigned Processed = 1087 handleTlsRelocation<ELFT>(Type, Sym, Sec, Offset, Addend, Expr)) { 1088 I += (Processed - 1); 1089 return; 1090 } 1091 1092 // Non-preemptible ifuncs require special handling. First, handle the usual 1093 // case where the symbol isn't one of these. 1094 if (!Sym.isGnuIFunc() || Sym.IsPreemptible) { 1095 // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol. 1096 if (needsPlt(Expr) && !Sym.isInPlt()) 1097 addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym); 1098 1099 // Create a GOT slot if a relocation needs GOT. 1100 if (needsGot(Expr)) { 1101 if (Config->EMachine == EM_MIPS) { 1102 // MIPS ABI has special rules to process GOT entries and doesn't 1103 // require relocation entries for them. A special case is TLS 1104 // relocations. In that case dynamic loader applies dynamic 1105 // relocations to initialize TLS GOT entries. 1106 // See "Global Offset Table" in Chapter 5 in the following document 1107 // for detailed description: 1108 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1109 In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr); 1110 } else if (!Sym.isInGot()) { 1111 addGotEntry(Sym); 1112 } 1113 } 1114 } else { 1115 // Handle a reference to a non-preemptible ifunc. These are special in a 1116 // few ways: 1117 // 1118 // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have 1119 // a fixed value. But assuming that all references to the ifunc are 1120 // GOT-generating or PLT-generating, the handling of an ifunc is 1121 // relatively straightforward. We create a PLT entry in Iplt, which is 1122 // usually at the end of .plt, which makes an indirect call using a 1123 // matching GOT entry in IgotPlt, which is usually at the end of .got.plt. 1124 // The GOT entry is relocated using an IRELATIVE relocation in RelaIplt, 1125 // which is usually at the end of .rela.plt. Unlike most relocations in 1126 // .rela.plt, which may be evaluated lazily without -z now, dynamic 1127 // loaders evaluate IRELATIVE relocs eagerly, which means that for 1128 // IRELATIVE relocs only, GOT-generating relocations can point directly to 1129 // .got.plt without requiring a separate GOT entry. 1130 // 1131 // - Despite the fact that an ifunc does not have a fixed value, compilers 1132 // that are not passed -fPIC will assume that they do, and will emit 1133 // direct (non-GOT-generating, non-PLT-generating) relocations to the 1134 // symbol. This means that if a direct relocation to the symbol is 1135 // seen, the linker must set a value for the symbol, and this value must 1136 // be consistent no matter what type of reference is made to the symbol. 1137 // This can be done by creating a PLT entry for the symbol in the way 1138 // described above and making it canonical, that is, making all references 1139 // point to the PLT entry instead of the resolver. In lld we also store 1140 // the address of the PLT entry in the dynamic symbol table, which means 1141 // that the symbol will also have the same value in other modules. 1142 // Because the value loaded from the GOT needs to be consistent with 1143 // the value computed using a direct relocation, a non-preemptible ifunc 1144 // may end up with two GOT entries, one in .got.plt that points to the 1145 // address returned by the resolver and is used only by the PLT entry, 1146 // and another in .got that points to the PLT entry and is used by 1147 // GOT-generating relocations. 1148 // 1149 // - The fact that these symbols do not have a fixed value makes them an 1150 // exception to the general rule that a statically linked executable does 1151 // not require any form of dynamic relocation. To handle these relocations 1152 // correctly, the IRELATIVE relocations are stored in an array which a 1153 // statically linked executable's startup code must enumerate using the 1154 // linker-defined symbols __rela?_iplt_{start,end}. 1155 // 1156 // - An absolute relocation to a non-preemptible ifunc (such as a global 1157 // variable containing a pointer to the ifunc) needs to be relocated in 1158 // the exact same way as a GOT entry, so we can avoid needing to make the 1159 // PLT entry canonical by translating such relocations into IRELATIVE 1160 // relocations in the RelaIplt. 1161 if (!Sym.isInPlt()) { 1162 // Create PLT and GOTPLT slots for the symbol. 1163 Sym.IsInIplt = true; 1164 1165 // Create a copy of the symbol to use as the target of the IRELATIVE 1166 // relocation in the IgotPlt. This is in case we make the PLT canonical 1167 // later, which would overwrite the original symbol. 1168 // 1169 // FIXME: Creating a copy of the symbol here is a bit of a hack. All 1170 // that's really needed to create the IRELATIVE is the section and value, 1171 // so ideally we should just need to copy those. 1172 auto *DirectSym = make<Defined>(cast<Defined>(Sym)); 1173 addPltEntry<ELFT>(In.Iplt, In.IgotPlt, In.RelaIplt, Target->IRelativeRel, 1174 *DirectSym); 1175 Sym.PltIndex = DirectSym->PltIndex; 1176 } 1177 if (Expr == R_ABS && Addend == 0 && (Sec.Flags & SHF_WRITE)) { 1178 // We might be able to represent this as an IRELATIVE. But we don't know 1179 // yet whether some later relocation will make the symbol point to a 1180 // canonical PLT, which would make this either a dynamic RELATIVE (PIC) or 1181 // static (non-PIC) relocation. So we keep a record of the information 1182 // required to process the relocation, and after scanRelocs() has been 1183 // called on all relocations, the relocation is resolved by 1184 // addIRelativeRelocs(). 1185 IRelativeRelocs.push_back({Type, &Sec, Offset, &Sym}); 1186 return; 1187 } 1188 if (needsGot(Expr)) { 1189 // Redirect GOT accesses to point to the Igot. 1190 // 1191 // This field is also used to keep track of whether we ever needed a GOT 1192 // entry. If we did and we make the PLT canonical later, we'll need to 1193 // create a GOT entry pointing to the PLT entry for Sym. 1194 Sym.GotInIgot = true; 1195 } else if (!needsPlt(Expr)) { 1196 // Make the ifunc's PLT entry canonical by changing the value of its 1197 // symbol to redirect all references to point to it. 1198 unsigned EntryOffset = Sym.PltIndex * Target->PltEntrySize; 1199 if (Config->ZRetpolineplt) 1200 EntryOffset += Target->PltHeaderSize; 1201 1202 auto &D = cast<Defined>(Sym); 1203 D.Section = In.Iplt; 1204 D.Value = EntryOffset; 1205 D.Size = 0; 1206 // It's important to set the symbol type here so that dynamic loaders 1207 // don't try to call the PLT as if it were an ifunc resolver. 1208 D.Type = STT_FUNC; 1209 1210 if (Sym.GotInIgot) { 1211 // We previously encountered a GOT generating reference that we 1212 // redirected to the Igot. Now that the PLT entry is canonical we must 1213 // clear the redirection to the Igot and add a GOT entry. As we've 1214 // changed the symbol type to STT_FUNC future GOT generating references 1215 // will naturally use this GOT entry. 1216 // 1217 // We don't need to worry about creating a MIPS GOT here because ifuncs 1218 // aren't a thing on MIPS. 1219 Sym.GotInIgot = false; 1220 addGotEntry(Sym); 1221 } 1222 } 1223 } 1224 1225 processRelocAux<ELFT>(Sec, Expr, Type, Offset, Sym, Rel, Addend); 1226 } 1227 1228 template <class ELFT, class RelTy> 1229 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { 1230 OffsetGetter GetOffset(Sec); 1231 1232 // Not all relocations end up in Sec.Relocations, but a lot do. 1233 Sec.Relocations.reserve(Rels.size()); 1234 1235 for (auto I = Rels.begin(), End = Rels.end(); I != End;) 1236 scanReloc<ELFT>(Sec, GetOffset, I, End); 1237 1238 // Sort relocations by offset to binary search for R_RISCV_PCREL_HI20 1239 if (Config->EMachine == EM_RISCV) 1240 std::stable_sort(Sec.Relocations.begin(), Sec.Relocations.end(), 1241 [](const Relocation &LHS, const Relocation &RHS) { 1242 return LHS.Offset < RHS.Offset; 1243 }); 1244 } 1245 1246 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) { 1247 if (S.AreRelocsRela) 1248 scanRelocs<ELFT>(S, S.relas<ELFT>()); 1249 else 1250 scanRelocs<ELFT>(S, S.rels<ELFT>()); 1251 } 1252 1253 // Figure out which representation to use for any absolute relocs to 1254 // non-preemptible ifuncs that we visited during scanRelocs(). 1255 void elf::addIRelativeRelocs() { 1256 for (IRelativeReloc &R : IRelativeRelocs) { 1257 if (R.Sym->Type == STT_GNU_IFUNC) 1258 In.RelaIplt->addReloc( 1259 {Target->IRelativeRel, R.Sec, R.Offset, true, R.Sym, 0}); 1260 else if (Config->Pic) 1261 addRelativeReloc(R.Sec, R.Offset, R.Sym, 0, R_ABS, R.Type); 1262 else 1263 R.Sec->Relocations.push_back({R_ABS, R.Type, R.Offset, 0, R.Sym}); 1264 } 1265 IRelativeRelocs.clear(); 1266 } 1267 1268 static bool mergeCmp(const InputSection *A, const InputSection *B) { 1269 // std::merge requires a strict weak ordering. 1270 if (A->OutSecOff < B->OutSecOff) 1271 return true; 1272 1273 if (A->OutSecOff == B->OutSecOff) { 1274 auto *TA = dyn_cast<ThunkSection>(A); 1275 auto *TB = dyn_cast<ThunkSection>(B); 1276 1277 // Check if Thunk is immediately before any specific Target 1278 // InputSection for example Mips LA25 Thunks. 1279 if (TA && TA->getTargetInputSection() == B) 1280 return true; 1281 1282 // Place Thunk Sections without specific targets before 1283 // non-Thunk Sections. 1284 if (TA && !TB && !TA->getTargetInputSection()) 1285 return true; 1286 } 1287 1288 return false; 1289 } 1290 1291 // Call Fn on every executable InputSection accessed via the linker script 1292 // InputSectionDescription::Sections. 1293 static void forEachInputSectionDescription( 1294 ArrayRef<OutputSection *> OutputSections, 1295 llvm::function_ref<void(OutputSection *, InputSectionDescription *)> Fn) { 1296 for (OutputSection *OS : OutputSections) { 1297 if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR)) 1298 continue; 1299 for (BaseCommand *BC : OS->SectionCommands) 1300 if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) 1301 Fn(OS, ISD); 1302 } 1303 } 1304 1305 // Thunk Implementation 1306 // 1307 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces 1308 // of code that the linker inserts inbetween a caller and a callee. The thunks 1309 // are added at link time rather than compile time as the decision on whether 1310 // a thunk is needed, such as the caller and callee being out of range, can only 1311 // be made at link time. 1312 // 1313 // It is straightforward to tell given the current state of the program when a 1314 // thunk is needed for a particular call. The more difficult part is that 1315 // the thunk needs to be placed in the program such that the caller can reach 1316 // the thunk and the thunk can reach the callee; furthermore, adding thunks to 1317 // the program alters addresses, which can mean more thunks etc. 1318 // 1319 // In lld we have a synthetic ThunkSection that can hold many Thunks. 1320 // The decision to have a ThunkSection act as a container means that we can 1321 // more easily handle the most common case of a single block of contiguous 1322 // Thunks by inserting just a single ThunkSection. 1323 // 1324 // The implementation of Thunks in lld is split across these areas 1325 // Relocations.cpp : Framework for creating and placing thunks 1326 // Thunks.cpp : The code generated for each supported thunk 1327 // Target.cpp : Target specific hooks that the framework uses to decide when 1328 // a thunk is used 1329 // Synthetic.cpp : Implementation of ThunkSection 1330 // Writer.cpp : Iteratively call framework until no more Thunks added 1331 // 1332 // Thunk placement requirements: 1333 // Mips LA25 thunks. These must be placed immediately before the callee section 1334 // We can assume that the caller is in range of the Thunk. These are modelled 1335 // by Thunks that return the section they must precede with 1336 // getTargetInputSection(). 1337 // 1338 // ARM interworking and range extension thunks. These thunks must be placed 1339 // within range of the caller. All implemented ARM thunks can always reach the 1340 // callee as they use an indirect jump via a register that has no range 1341 // restrictions. 1342 // 1343 // Thunk placement algorithm: 1344 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before 1345 // getTargetInputSection(). 1346 // 1347 // For thunks that must be placed within range of the caller there are many 1348 // possible choices given that the maximum range from the caller is usually 1349 // much larger than the average InputSection size. Desirable properties include: 1350 // - Maximize reuse of thunks by multiple callers 1351 // - Minimize number of ThunkSections to simplify insertion 1352 // - Handle impact of already added Thunks on addresses 1353 // - Simple to understand and implement 1354 // 1355 // In lld for the first pass, we pre-create one or more ThunkSections per 1356 // InputSectionDescription at Target specific intervals. A ThunkSection is 1357 // placed so that the estimated end of the ThunkSection is within range of the 1358 // start of the InputSectionDescription or the previous ThunkSection. For 1359 // example: 1360 // InputSectionDescription 1361 // Section 0 1362 // ... 1363 // Section N 1364 // ThunkSection 0 1365 // Section N + 1 1366 // ... 1367 // Section N + K 1368 // Thunk Section 1 1369 // 1370 // The intention is that we can add a Thunk to a ThunkSection that is well 1371 // spaced enough to service a number of callers without having to do a lot 1372 // of work. An important principle is that it is not an error if a Thunk cannot 1373 // be placed in a pre-created ThunkSection; when this happens we create a new 1374 // ThunkSection placed next to the caller. This allows us to handle the vast 1375 // majority of thunks simply, but also handle rare cases where the branch range 1376 // is smaller than the target specific spacing. 1377 // 1378 // The algorithm is expected to create all the thunks that are needed in a 1379 // single pass, with a small number of programs needing a second pass due to 1380 // the insertion of thunks in the first pass increasing the offset between 1381 // callers and callees that were only just in range. 1382 // 1383 // A consequence of allowing new ThunkSections to be created outside of the 1384 // pre-created ThunkSections is that in rare cases calls to Thunks that were in 1385 // range in pass K, are out of range in some pass > K due to the insertion of 1386 // more Thunks in between the caller and callee. When this happens we retarget 1387 // the relocation back to the original target and create another Thunk. 1388 1389 // Remove ThunkSections that are empty, this should only be the initial set 1390 // precreated on pass 0. 1391 1392 // Insert the Thunks for OutputSection OS into their designated place 1393 // in the Sections vector, and recalculate the InputSection output section 1394 // offsets. 1395 // This may invalidate any output section offsets stored outside of InputSection 1396 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> OutputSections) { 1397 forEachInputSectionDescription( 1398 OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) { 1399 if (ISD->ThunkSections.empty()) 1400 return; 1401 1402 // Remove any zero sized precreated Thunks. 1403 llvm::erase_if(ISD->ThunkSections, 1404 [](const std::pair<ThunkSection *, uint32_t> &TS) { 1405 return TS.first->getSize() == 0; 1406 }); 1407 1408 // ISD->ThunkSections contains all created ThunkSections, including 1409 // those inserted in previous passes. Extract the Thunks created this 1410 // pass and order them in ascending OutSecOff. 1411 std::vector<ThunkSection *> NewThunks; 1412 for (const std::pair<ThunkSection *, uint32_t> TS : ISD->ThunkSections) 1413 if (TS.second == Pass) 1414 NewThunks.push_back(TS.first); 1415 std::stable_sort(NewThunks.begin(), NewThunks.end(), 1416 [](const ThunkSection *A, const ThunkSection *B) { 1417 return A->OutSecOff < B->OutSecOff; 1418 }); 1419 1420 // Merge sorted vectors of Thunks and InputSections by OutSecOff 1421 std::vector<InputSection *> Tmp; 1422 Tmp.reserve(ISD->Sections.size() + NewThunks.size()); 1423 1424 std::merge(ISD->Sections.begin(), ISD->Sections.end(), 1425 NewThunks.begin(), NewThunks.end(), std::back_inserter(Tmp), 1426 mergeCmp); 1427 1428 ISD->Sections = std::move(Tmp); 1429 }); 1430 } 1431 1432 // Find or create a ThunkSection within the InputSectionDescription (ISD) that 1433 // is in range of Src. An ISD maps to a range of InputSections described by a 1434 // linker script section pattern such as { .text .text.* }. 1435 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *OS, InputSection *IS, 1436 InputSectionDescription *ISD, 1437 uint32_t Type, uint64_t Src) { 1438 for (std::pair<ThunkSection *, uint32_t> TP : ISD->ThunkSections) { 1439 ThunkSection *TS = TP.first; 1440 uint64_t TSBase = OS->Addr + TS->OutSecOff; 1441 uint64_t TSLimit = TSBase + TS->getSize(); 1442 if (Target->inBranchRange(Type, Src, (Src > TSLimit) ? TSBase : TSLimit)) 1443 return TS; 1444 } 1445 1446 // No suitable ThunkSection exists. This can happen when there is a branch 1447 // with lower range than the ThunkSection spacing or when there are too 1448 // many Thunks. Create a new ThunkSection as close to the InputSection as 1449 // possible. Error if InputSection is so large we cannot place ThunkSection 1450 // anywhere in Range. 1451 uint64_t ThunkSecOff = IS->OutSecOff; 1452 if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) { 1453 ThunkSecOff = IS->OutSecOff + IS->getSize(); 1454 if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) 1455 fatal("InputSection too large for range extension thunk " + 1456 IS->getObjMsg(Src - (OS->Addr + IS->OutSecOff))); 1457 } 1458 return addThunkSection(OS, ISD, ThunkSecOff); 1459 } 1460 1461 // Add a Thunk that needs to be placed in a ThunkSection that immediately 1462 // precedes its Target. 1463 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) { 1464 ThunkSection *TS = ThunkedSections.lookup(IS); 1465 if (TS) 1466 return TS; 1467 1468 // Find InputSectionRange within Target Output Section (TOS) that the 1469 // InputSection (IS) that we need to precede is in. 1470 OutputSection *TOS = IS->getParent(); 1471 for (BaseCommand *BC : TOS->SectionCommands) { 1472 auto *ISD = dyn_cast<InputSectionDescription>(BC); 1473 if (!ISD || ISD->Sections.empty()) 1474 continue; 1475 1476 InputSection *First = ISD->Sections.front(); 1477 InputSection *Last = ISD->Sections.back(); 1478 1479 if (IS->OutSecOff < First->OutSecOff || Last->OutSecOff < IS->OutSecOff) 1480 continue; 1481 1482 TS = addThunkSection(TOS, ISD, IS->OutSecOff); 1483 ThunkedSections[IS] = TS; 1484 return TS; 1485 } 1486 1487 return nullptr; 1488 } 1489 1490 // Create one or more ThunkSections per OS that can be used to place Thunks. 1491 // We attempt to place the ThunkSections using the following desirable 1492 // properties: 1493 // - Within range of the maximum number of callers 1494 // - Minimise the number of ThunkSections 1495 // 1496 // We follow a simple but conservative heuristic to place ThunkSections at 1497 // offsets that are multiples of a Target specific branch range. 1498 // For an InputSectionDescription that is smaller than the range, a single 1499 // ThunkSection at the end of the range will do. 1500 // 1501 // For an InputSectionDescription that is more than twice the size of the range, 1502 // we place the last ThunkSection at range bytes from the end of the 1503 // InputSectionDescription in order to increase the likelihood that the 1504 // distance from a thunk to its target will be sufficiently small to 1505 // allow for the creation of a short thunk. 1506 void ThunkCreator::createInitialThunkSections( 1507 ArrayRef<OutputSection *> OutputSections) { 1508 uint32_t ThunkSectionSpacing = Target->getThunkSectionSpacing(); 1509 1510 forEachInputSectionDescription( 1511 OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) { 1512 if (ISD->Sections.empty()) 1513 return; 1514 1515 uint32_t ISDBegin = ISD->Sections.front()->OutSecOff; 1516 uint32_t ISDEnd = 1517 ISD->Sections.back()->OutSecOff + ISD->Sections.back()->getSize(); 1518 uint32_t LastThunkLowerBound = -1; 1519 if (ISDEnd - ISDBegin > ThunkSectionSpacing * 2) 1520 LastThunkLowerBound = ISDEnd - ThunkSectionSpacing; 1521 1522 uint32_t ISLimit; 1523 uint32_t PrevISLimit = ISDBegin; 1524 uint32_t ThunkUpperBound = ISDBegin + ThunkSectionSpacing; 1525 1526 for (const InputSection *IS : ISD->Sections) { 1527 ISLimit = IS->OutSecOff + IS->getSize(); 1528 if (ISLimit > ThunkUpperBound) { 1529 addThunkSection(OS, ISD, PrevISLimit); 1530 ThunkUpperBound = PrevISLimit + ThunkSectionSpacing; 1531 } 1532 if (ISLimit > LastThunkLowerBound) 1533 break; 1534 PrevISLimit = ISLimit; 1535 } 1536 addThunkSection(OS, ISD, ISLimit); 1537 }); 1538 } 1539 1540 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS, 1541 InputSectionDescription *ISD, 1542 uint64_t Off) { 1543 auto *TS = make<ThunkSection>(OS, Off); 1544 ISD->ThunkSections.push_back({TS, Pass}); 1545 return TS; 1546 } 1547 1548 std::pair<Thunk *, bool> ThunkCreator::getThunk(Symbol &Sym, RelType Type, 1549 uint64_t Src) { 1550 std::vector<Thunk *> *ThunkVec = nullptr; 1551 1552 // We use (section, offset) pair to find the thunk position if possible so 1553 // that we create only one thunk for aliased symbols or ICFed sections. 1554 if (auto *D = dyn_cast<Defined>(&Sym)) 1555 if (!D->isInPlt() && D->Section) 1556 ThunkVec = &ThunkedSymbolsBySection[{D->Section->Repl, D->Value}]; 1557 if (!ThunkVec) 1558 ThunkVec = &ThunkedSymbols[&Sym]; 1559 1560 // Check existing Thunks for Sym to see if they can be reused 1561 for (Thunk *T : *ThunkVec) 1562 if (T->isCompatibleWith(Type) && 1563 Target->inBranchRange(Type, Src, T->getThunkTargetSym()->getVA())) 1564 return std::make_pair(T, false); 1565 1566 // No existing compatible Thunk in range, create a new one 1567 Thunk *T = addThunk(Type, Sym); 1568 ThunkVec->push_back(T); 1569 return std::make_pair(T, true); 1570 } 1571 1572 // Return true if the relocation target is an in range Thunk. 1573 // Return false if the relocation is not to a Thunk. If the relocation target 1574 // was originally to a Thunk, but is no longer in range we revert the 1575 // relocation back to its original non-Thunk target. 1576 bool ThunkCreator::normalizeExistingThunk(Relocation &Rel, uint64_t Src) { 1577 if (Thunk *T = Thunks.lookup(Rel.Sym)) { 1578 if (Target->inBranchRange(Rel.Type, Src, Rel.Sym->getVA())) 1579 return true; 1580 Rel.Sym = &T->Destination; 1581 if (Rel.Sym->isInPlt()) 1582 Rel.Expr = toPlt(Rel.Expr); 1583 } 1584 return false; 1585 } 1586 1587 // Process all relocations from the InputSections that have been assigned 1588 // to InputSectionDescriptions and redirect through Thunks if needed. The 1589 // function should be called iteratively until it returns false. 1590 // 1591 // PreConditions: 1592 // All InputSections that may need a Thunk are reachable from 1593 // OutputSectionCommands. 1594 // 1595 // All OutputSections have an address and all InputSections have an offset 1596 // within the OutputSection. 1597 // 1598 // The offsets between caller (relocation place) and callee 1599 // (relocation target) will not be modified outside of createThunks(). 1600 // 1601 // PostConditions: 1602 // If return value is true then ThunkSections have been inserted into 1603 // OutputSections. All relocations that needed a Thunk based on the information 1604 // available to createThunks() on entry have been redirected to a Thunk. Note 1605 // that adding Thunks changes offsets between caller and callee so more Thunks 1606 // may be required. 1607 // 1608 // If return value is false then no more Thunks are needed, and createThunks has 1609 // made no changes. If the target requires range extension thunks, currently 1610 // ARM, then any future change in offset between caller and callee risks a 1611 // relocation out of range error. 1612 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) { 1613 bool AddressesChanged = false; 1614 1615 if (Pass == 0 && Target->getThunkSectionSpacing()) 1616 createInitialThunkSections(OutputSections); 1617 1618 // With Thunk Size much smaller than branch range we expect to 1619 // converge quickly; if we get to 10 something has gone wrong. 1620 if (Pass == 10) 1621 fatal("thunk creation not converged"); 1622 1623 // Create all the Thunks and insert them into synthetic ThunkSections. The 1624 // ThunkSections are later inserted back into InputSectionDescriptions. 1625 // We separate the creation of ThunkSections from the insertion of the 1626 // ThunkSections as ThunkSections are not always inserted into the same 1627 // InputSectionDescription as the caller. 1628 forEachInputSectionDescription( 1629 OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) { 1630 for (InputSection *IS : ISD->Sections) 1631 for (Relocation &Rel : IS->Relocations) { 1632 uint64_t Src = IS->getVA(Rel.Offset); 1633 1634 // If we are a relocation to an existing Thunk, check if it is 1635 // still in range. If not then Rel will be altered to point to its 1636 // original target so another Thunk can be generated. 1637 if (Pass > 0 && normalizeExistingThunk(Rel, Src)) 1638 continue; 1639 1640 if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Src, 1641 *Rel.Sym)) 1642 continue; 1643 1644 Thunk *T; 1645 bool IsNew; 1646 std::tie(T, IsNew) = getThunk(*Rel.Sym, Rel.Type, Src); 1647 1648 if (IsNew) { 1649 // Find or create a ThunkSection for the new Thunk 1650 ThunkSection *TS; 1651 if (auto *TIS = T->getTargetInputSection()) 1652 TS = getISThunkSec(TIS); 1653 else 1654 TS = getISDThunkSec(OS, IS, ISD, Rel.Type, Src); 1655 TS->addThunk(T); 1656 Thunks[T->getThunkTargetSym()] = T; 1657 } 1658 1659 // Redirect relocation to Thunk, we never go via the PLT to a Thunk 1660 Rel.Sym = T->getThunkTargetSym(); 1661 Rel.Expr = fromPlt(Rel.Expr); 1662 } 1663 1664 for (auto &P : ISD->ThunkSections) 1665 AddressesChanged |= P.first->assignOffsets(); 1666 }); 1667 1668 for (auto &P : ThunkedSections) 1669 AddressesChanged |= P.second->assignOffsets(); 1670 1671 // Merge all created synthetic ThunkSections back into OutputSection 1672 mergeThunks(OutputSections); 1673 ++Pass; 1674 return AddressesChanged; 1675 } 1676 1677 template void elf::scanRelocations<ELF32LE>(InputSectionBase &); 1678 template void elf::scanRelocations<ELF32BE>(InputSectionBase &); 1679 template void elf::scanRelocations<ELF64LE>(InputSectionBase &); 1680 template void elf::scanRelocations<ELF64BE>(InputSectionBase &); 1681