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