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