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 "Memory.h" 48 #include "OutputSections.h" 49 #include "Strings.h" 50 #include "SymbolTable.h" 51 #include "SyntheticSections.h" 52 #include "Target.h" 53 #include "Thunks.h" 54 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 template <class ELFT> 73 static std::string getLocation(InputSectionBase &S, const SymbolBody &Sym, 74 uint64_t Off) { 75 std::string Msg = 76 "\n>>> defined in " + toString(Sym.getFile()) + "\n>>> referenced by "; 77 std::string Src = S.getSrcMsg<ELFT>(Off); 78 if (!Src.empty()) 79 Msg += Src + "\n>>> "; 80 return Msg + S.getObjMsg<ELFT>(Off); 81 } 82 83 static bool isPreemptible(const SymbolBody &Body, uint32_t Type) { 84 // In case of MIPS GP-relative relocations always resolve to a definition 85 // in a regular input file, ignoring the one-definition rule. So we, 86 // for example, should not attempt to create a dynamic relocation even 87 // if the target symbol is preemptible. There are two two MIPS GP-relative 88 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16 89 // can be against a preemptible symbol. 90 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all 91 // relocation types occupy eight bit. In case of N64 ABI we extract first 92 // relocation from 3-in-1 packet because only the first relocation can 93 // be against a real symbol. 94 if (Config->EMachine == EM_MIPS) { 95 Type &= 0xff; 96 if (Type == R_MIPS_GPREL16 || Type == R_MICROMIPS_GPREL16 || 97 Type == R_MICROMIPS_GPREL7_S2) 98 return false; 99 } 100 return Body.isPreemptible(); 101 } 102 103 // This function is similar to the `handleTlsRelocation`. MIPS does not 104 // support any relaxations for TLS relocations so by factoring out MIPS 105 // handling in to the separate function we can simplify the code and do not 106 // pollute other `handleTlsRelocation` by MIPS `ifs` statements. 107 // Mips has a custom MipsGotSection that handles the writing of GOT entries 108 // without dynamic relocations. 109 template <class ELFT> 110 static unsigned handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body, 111 InputSectionBase &C, uint64_t Offset, 112 int64_t Addend, RelExpr Expr) { 113 if (Expr == R_MIPS_TLSLD) { 114 if (InX::MipsGot->addTlsIndex() && Config->Pic) 115 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::MipsGot, 116 InX::MipsGot->getTlsIndexOff(), false, 117 nullptr, 0}); 118 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 119 return 1; 120 } 121 122 if (Expr == R_MIPS_TLSGD) { 123 if (InX::MipsGot->addDynTlsEntry(Body) && Body.isPreemptible()) { 124 uint64_t Off = InX::MipsGot->getGlobalDynOffset(Body); 125 In<ELFT>::RelaDyn->addReloc( 126 {Target->TlsModuleIndexRel, InX::MipsGot, Off, false, &Body, 0}); 127 if (Body.isPreemptible()) 128 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, InX::MipsGot, 129 Off + Config->Wordsize, false, &Body, 0}); 130 } 131 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 132 return 1; 133 } 134 return 0; 135 } 136 137 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not 138 // support any relaxations for TLS relocations. ARM is logically similar to Mips 139 // in how it handles TLS, but Mips uses its own custom GOT which handles some 140 // of the cases that ARM uses GOT relocations for. 141 // 142 // We look for TLS global dynamic and local dynamic relocations, these may 143 // require the generation of a pair of GOT entries that have associated 144 // dynamic relocations. When the results of the dynamic relocations can be 145 // resolved at static link time we do so. This is necessary for static linking 146 // as there will be no dynamic loader to resolve them at load-time. 147 // 148 // The pair of GOT entries created are of the form 149 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time) 150 // GOT[e1] Offset of symbol in TLS block 151 template <class ELFT> 152 static unsigned handleARMTlsRelocation(uint32_t Type, SymbolBody &Body, 153 InputSectionBase &C, uint64_t Offset, 154 int64_t Addend, RelExpr Expr) { 155 // The Dynamic TLS Module Index Relocation for a symbol defined in an 156 // executable is always 1. If the target Symbol is not preemptible then 157 // we know the offset into the TLS block at static link time. 158 bool NeedDynId = Body.isPreemptible() || Config->Shared; 159 bool NeedDynOff = Body.isPreemptible(); 160 161 auto AddTlsReloc = [&](uint64_t Off, uint32_t Type, SymbolBody *Dest, 162 bool Dyn) { 163 if (Dyn) 164 In<ELFT>::RelaDyn->addReloc({Type, InX::Got, Off, false, Dest, 0}); 165 else 166 InX::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest}); 167 }; 168 169 // Local Dynamic is for access to module local TLS variables, while still 170 // being suitable for being dynamically loaded via dlopen. 171 // GOT[e0] is the module index, with a special value of 0 for the current 172 // module. GOT[e1] is unused. There only needs to be one module index entry. 173 if (Expr == R_TLSLD_PC && InX::Got->addTlsIndex()) { 174 AddTlsReloc(InX::Got->getTlsIndexOff(), Target->TlsModuleIndexRel, 175 NeedDynId ? nullptr : &Body, NeedDynId); 176 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 177 return 1; 178 } 179 180 // Global Dynamic is the most general purpose access model. When we know 181 // the module index and offset of symbol in TLS block we can fill these in 182 // using static GOT relocations. 183 if (Expr == R_TLSGD_PC) { 184 if (InX::Got->addDynTlsEntry(Body)) { 185 uint64_t Off = InX::Got->getGlobalDynOffset(Body); 186 AddTlsReloc(Off, Target->TlsModuleIndexRel, &Body, NeedDynId); 187 AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Body, 188 NeedDynOff); 189 } 190 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 191 return 1; 192 } 193 return 0; 194 } 195 196 // Returns the number of relocations processed. 197 template <class ELFT> 198 static unsigned 199 handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, 200 typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) { 201 if (!(C.Flags & SHF_ALLOC)) 202 return 0; 203 204 if (!Body.isTls()) 205 return 0; 206 207 if (Config->EMachine == EM_ARM) 208 return handleARMTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr); 209 if (Config->EMachine == EM_MIPS) 210 return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr); 211 212 bool IsPreemptible = isPreemptible(Body, Type); 213 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) && 214 Config->Shared) { 215 if (InX::Got->addDynTlsEntry(Body)) { 216 uint64_t Off = InX::Got->getGlobalDynOffset(Body); 217 In<ELFT>::RelaDyn->addReloc( 218 {Target->TlsDescRel, InX::Got, Off, !IsPreemptible, &Body, 0}); 219 } 220 if (Expr != R_TLSDESC_CALL) 221 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 222 return 1; 223 } 224 225 if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) { 226 // Local-Dynamic relocs can be relaxed to Local-Exec. 227 if (!Config->Shared) { 228 C.Relocations.push_back( 229 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body}); 230 return 2; 231 } 232 if (InX::Got->addTlsIndex()) 233 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::Got, 234 InX::Got->getTlsIndexOff(), false, nullptr, 235 0}); 236 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 237 return 1; 238 } 239 240 // Local-Dynamic relocs can be relaxed to Local-Exec. 241 if (isRelExprOneOf<R_ABS, R_TLSLD, R_TLSLD_PC>(Expr) && !Config->Shared) { 242 C.Relocations.push_back( 243 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body}); 244 return 1; 245 } 246 247 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD, 248 R_TLSGD_PC>(Expr)) { 249 if (Config->Shared) { 250 if (InX::Got->addDynTlsEntry(Body)) { 251 uint64_t Off = InX::Got->getGlobalDynOffset(Body); 252 In<ELFT>::RelaDyn->addReloc( 253 {Target->TlsModuleIndexRel, InX::Got, Off, false, &Body, 0}); 254 255 // If the symbol is preemptible we need the dynamic linker to write 256 // the offset too. 257 uint64_t OffsetOff = Off + Config->Wordsize; 258 if (IsPreemptible) 259 In<ELFT>::RelaDyn->addReloc( 260 {Target->TlsOffsetRel, InX::Got, OffsetOff, false, &Body, 0}); 261 else 262 InX::Got->Relocations.push_back( 263 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body}); 264 } 265 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 266 return 1; 267 } 268 269 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec 270 // depending on the symbol being locally defined or not. 271 if (IsPreemptible) { 272 C.Relocations.push_back( 273 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type, 274 Offset, Addend, &Body}); 275 if (!Body.isInGot()) { 276 InX::Got->addEntry(Body); 277 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::Got, 278 Body.getGotOffset(), false, &Body, 0}); 279 } 280 } else { 281 C.Relocations.push_back( 282 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, 283 Offset, Addend, &Body}); 284 } 285 return Target->TlsGdRelaxSkip; 286 } 287 288 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally 289 // defined. 290 if (isRelExprOneOf<R_GOT, R_GOT_FROM_END, R_GOT_PC, R_GOT_PAGE_PC>(Expr) && 291 !Config->Shared && !IsPreemptible) { 292 C.Relocations.push_back( 293 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body}); 294 return 1; 295 } 296 297 if (Expr == R_TLSDESC_CALL) 298 return 1; 299 return 0; 300 } 301 302 static uint32_t getMipsPairType(uint32_t Type, const SymbolBody &Sym) { 303 switch (Type) { 304 case R_MIPS_HI16: 305 return R_MIPS_LO16; 306 case R_MIPS_GOT16: 307 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE; 308 case R_MICROMIPS_GOT16: 309 return Sym.isLocal() ? R_MICROMIPS_LO16 : R_MIPS_NONE; 310 case R_MIPS_PCHI16: 311 return R_MIPS_PCLO16; 312 case R_MICROMIPS_HI16: 313 return R_MICROMIPS_LO16; 314 default: 315 return R_MIPS_NONE; 316 } 317 } 318 319 // True if non-preemptable symbol always has the same value regardless of where 320 // the DSO is loaded. 321 static bool isAbsolute(const SymbolBody &Body) { 322 if (Body.isUndefWeak()) 323 return true; 324 if (const auto *DR = dyn_cast<DefinedRegular>(&Body)) 325 return DR->Section == nullptr; // Absolute symbol. 326 return false; 327 } 328 329 static bool isAbsoluteValue(const SymbolBody &Body) { 330 return isAbsolute(Body) || Body.isTls(); 331 } 332 333 // Returns true if Expr refers a PLT entry. 334 static bool needsPlt(RelExpr Expr) { 335 return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr); 336 } 337 338 // Returns true if Expr refers a GOT entry. Note that this function 339 // returns false for TLS variables even though they need GOT, because 340 // TLS variables uses GOT differently than the regular variables. 341 static bool needsGot(RelExpr Expr) { 342 return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF, 343 R_MIPS_GOT_OFF32, R_GOT_PAGE_PC, R_GOT_PC, 344 R_GOT_FROM_END>(Expr); 345 } 346 347 // True if this expression is of the form Sym - X, where X is a position in the 348 // file (PC, or GOT for example). 349 static bool isRelExpr(RelExpr Expr) { 350 return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL, 351 R_PAGE_PC, R_RELAX_GOT_PC>(Expr); 352 } 353 354 // Returns true if a given relocation can be computed at link-time. 355 // 356 // For instance, we know the offset from a relocation to its target at 357 // link-time if the relocation is PC-relative and refers a 358 // non-interposable function in the same executable. This function 359 // will return true for such relocation. 360 // 361 // If this function returns false, that means we need to emit a 362 // dynamic relocation so that the relocation will be fixed at load-time. 363 template <class ELFT> 364 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type, 365 const SymbolBody &Body, 366 InputSectionBase &S, uint64_t RelOff) { 367 // These expressions always compute a constant 368 if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, 369 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, 370 R_MIPS_TLSGD, R_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, 371 R_GOTONLY_PC_FROM_END, R_PLT_PC, R_TLSGD_PC, R_TLSGD, 372 R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT>(E)) 373 return true; 374 375 // These never do, except if the entire file is position dependent or if 376 // only the low bits are used. 377 if (E == R_GOT || E == R_PLT || E == R_TLSDESC) 378 return Target->usesOnlyLowPageBits(Type) || !Config->Pic; 379 380 if (isPreemptible(Body, Type)) 381 return false; 382 if (!Config->Pic) 383 return true; 384 385 // For the target and the relocation, we want to know if they are 386 // absolute or relative. 387 bool AbsVal = isAbsoluteValue(Body); 388 bool RelE = isRelExpr(E); 389 if (AbsVal && !RelE) 390 return true; 391 if (!AbsVal && RelE) 392 return true; 393 if (!AbsVal && !RelE) 394 return Target->usesOnlyLowPageBits(Type); 395 396 // Relative relocation to an absolute value. This is normally unrepresentable, 397 // but if the relocation refers to a weak undefined symbol, we allow it to 398 // resolve to the image base. This is a little strange, but it allows us to 399 // link function calls to such symbols. Normally such a call will be guarded 400 // with a comparison, which will load a zero from the GOT. 401 // Another special case is MIPS _gp_disp symbol which represents offset 402 // between start of a function and '_gp' value and defined as absolute just 403 // to simplify the code. 404 assert(AbsVal && RelE); 405 if (Body.isUndefWeak()) 406 return true; 407 408 error("relocation " + toString(Type) + " cannot refer to absolute symbol: " + 409 toString(Body) + getLocation<ELFT>(S, Body, RelOff)); 410 return true; 411 } 412 413 static RelExpr toPlt(RelExpr Expr) { 414 if (Expr == R_PPC_OPD) 415 return R_PPC_PLT_OPD; 416 if (Expr == R_PC) 417 return R_PLT_PC; 418 if (Expr == R_PAGE_PC) 419 return R_PLT_PAGE_PC; 420 if (Expr == R_ABS) 421 return R_PLT; 422 return Expr; 423 } 424 425 static RelExpr fromPlt(RelExpr Expr) { 426 // We decided not to use a plt. Optimize a reference to the plt to a 427 // reference to the symbol itself. 428 if (Expr == R_PLT_PC) 429 return R_PC; 430 if (Expr == R_PPC_PLT_OPD) 431 return R_PPC_OPD; 432 if (Expr == R_PLT) 433 return R_ABS; 434 return Expr; 435 } 436 437 // Returns true if a given shared symbol is in a read-only segment in a DSO. 438 template <class ELFT> static bool isReadOnly(SharedSymbol *SS) { 439 typedef typename ELFT::Phdr Elf_Phdr; 440 uint64_t Value = SS->getValue<ELFT>(); 441 442 // Determine if the symbol is read-only by scanning the DSO's program headers. 443 const SharedFile<ELFT> *File = SS->getFile<ELFT>(); 444 for (const Elf_Phdr &Phdr : check(File->getObj().program_headers())) 445 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) && 446 !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr && 447 Value < Phdr.p_vaddr + Phdr.p_memsz) 448 return true; 449 return false; 450 } 451 452 // Returns symbols at the same offset as a given symbol, including SS itself. 453 // 454 // If two or more symbols are at the same offset, and at least one of 455 // them are copied by a copy relocation, all of them need to be copied. 456 // Otherwise, they would refer different places at runtime. 457 template <class ELFT> 458 static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol *SS) { 459 typedef typename ELFT::Sym Elf_Sym; 460 461 SharedFile<ELFT> *File = SS->getFile<ELFT>(); 462 uint64_t Shndx = SS->getShndx<ELFT>(); 463 uint64_t Value = SS->getValue<ELFT>(); 464 465 std::vector<SharedSymbol *> Ret; 466 for (const Elf_Sym &S : File->getGlobalELFSyms()) { 467 if (S.st_shndx != Shndx || S.st_value != Value) 468 continue; 469 StringRef Name = check(S.getName(File->getStringTable())); 470 SymbolBody *Sym = Symtab->find(Name); 471 if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym)) 472 Ret.push_back(Alias); 473 } 474 return Ret; 475 } 476 477 // Reserve space in .bss or .bss.rel.ro for copy relocation. 478 // 479 // The copy relocation is pretty much a hack. If you use a copy relocation 480 // in your program, not only the symbol name but the symbol's size, RW/RO 481 // bit and alignment become part of the ABI. In addition to that, if the 482 // symbol has aliases, the aliases become part of the ABI. That's subtle, 483 // but if you violate that implicit ABI, that can cause very counter- 484 // intuitive consequences. 485 // 486 // So, what is the copy relocation? It's for linking non-position 487 // independent code to DSOs. In an ideal world, all references to data 488 // exported by DSOs should go indirectly through GOT. But if object files 489 // are compiled as non-PIC, all data references are direct. There is no 490 // way for the linker to transform the code to use GOT, as machine 491 // instructions are already set in stone in object files. This is where 492 // the copy relocation takes a role. 493 // 494 // A copy relocation instructs the dynamic linker to copy data from a DSO 495 // to a specified address (which is usually in .bss) at load-time. If the 496 // static linker (that's us) finds a direct data reference to a DSO 497 // symbol, it creates a copy relocation, so that the symbol can be 498 // resolved as if it were in .bss rather than in a DSO. 499 // 500 // As you can see in this function, we create a copy relocation for the 501 // dynamic linker, and the relocation contains not only symbol name but 502 // various other informtion about the symbol. So, such attributes become a 503 // part of the ABI. 504 // 505 // Note for application developers: I can give you a piece of advice if 506 // you are writing a shared library. You probably should export only 507 // functions from your library. You shouldn't export variables. 508 // 509 // As an example what can happen when you export variables without knowing 510 // the semantics of copy relocations, assume that you have an exported 511 // variable of type T. It is an ABI-breaking change to add new members at 512 // end of T even though doing that doesn't change the layout of the 513 // existing members. That's because the space for the new members are not 514 // reserved in .bss unless you recompile the main program. That means they 515 // are likely to overlap with other data that happens to be laid out next 516 // to the variable in .bss. This kind of issue is sometimes very hard to 517 // debug. What's a solution? Instead of exporting a varaible V from a DSO, 518 // define an accessor getV(). 519 template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) { 520 // Copy relocation against zero-sized symbol doesn't make sense. 521 uint64_t SymSize = SS->template getSize<ELFT>(); 522 if (SymSize == 0) 523 fatal("cannot create a copy relocation for symbol " + toString(*SS)); 524 525 // See if this symbol is in a read-only segment. If so, preserve the symbol's 526 // memory protection by reserving space in the .bss.rel.ro section. 527 bool IsReadOnly = isReadOnly<ELFT>(SS); 528 BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss"); 529 Sec->reserveSpace(SymSize, SS->getAlignment<ELFT>()); 530 if (IsReadOnly) 531 InX::BssRelRo->getParent()->addSection(Sec); 532 else 533 InX::Bss->getParent()->addSection(Sec); 534 535 // Look through the DSO's dynamic symbol table for aliases and create a 536 // dynamic symbol for each one. This causes the copy relocation to correctly 537 // interpose any aliases. 538 for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) { 539 Sym->CopyRelSec = Sec; 540 Sym->IsPreemptible = false; 541 Sym->symbol()->IsUsedInRegularObj = true; 542 } 543 544 In<ELFT>::RelaDyn->addReloc({Target->CopyRel, Sec, 0, false, SS, 0}); 545 } 546 547 static void errorOrWarn(const Twine &Msg) { 548 if (!Config->NoinhibitExec) 549 error(Msg); 550 else 551 warn(Msg); 552 } 553 554 template <class ELFT> 555 static RelExpr adjustExpr(SymbolBody &Body, RelExpr Expr, uint32_t Type, 556 const uint8_t *Data, InputSectionBase &S, 557 typename ELFT::uint RelOff) { 558 if (Body.isGnuIFunc()) { 559 Expr = toPlt(Expr); 560 } else if (!isPreemptible(Body, Type)) { 561 if (needsPlt(Expr)) 562 Expr = fromPlt(Expr); 563 if (Expr == R_GOT_PC && !isAbsoluteValue(Body)) 564 Expr = Target->adjustRelaxExpr(Type, Data, Expr); 565 } 566 567 bool IsWrite = !Config->ZText || (S.Flags & SHF_WRITE); 568 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff)) 569 return Expr; 570 571 // If we got here we know that this relocation would require the dynamic 572 // linker to write a value to read only memory. 573 574 // If the relocation is to a weak undef, give up on it and produce a 575 // non preemptible 0. 576 if (Body.isUndefWeak()) { 577 Body.IsPreemptible = false; 578 return Expr; 579 } 580 581 // We can hack around it if we are producing an executable and 582 // the refered symbol can be preemepted to refer to the executable. 583 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) { 584 error("can't create dynamic relocation " + toString(Type) + " against " + 585 (Body.getName().empty() ? "local symbol" 586 : "symbol: " + toString(Body)) + 587 " in readonly segment; recompile object files with -fPIC" + 588 getLocation<ELFT>(S, Body, RelOff)); 589 return Expr; 590 } 591 592 if (Body.getVisibility() != STV_DEFAULT) { 593 error("cannot preempt symbol: " + toString(Body) + 594 getLocation<ELFT>(S, Body, RelOff)); 595 return Expr; 596 } 597 598 if (Body.isObject()) { 599 // Produce a copy relocation. 600 auto *B = cast<SharedSymbol>(&Body); 601 if (!B->CopyRelSec) { 602 if (Config->ZNocopyreloc) 603 error("unresolvable relocation " + toString(Type) + 604 " against symbol '" + toString(*B) + 605 "'; recompile with -fPIC or remove '-z nocopyreloc'" + 606 getLocation<ELFT>(S, Body, RelOff)); 607 608 addCopyRelSymbol<ELFT>(B); 609 } 610 return Expr; 611 } 612 613 if (Body.isFunc()) { 614 // This handles a non PIC program call to function in a shared library. In 615 // an ideal world, we could just report an error saying the relocation can 616 // overflow at runtime. In the real world with glibc, crt1.o has a 617 // R_X86_64_PC32 pointing to libc.so. 618 // 619 // The general idea on how to handle such cases is to create a PLT entry and 620 // use that as the function value. 621 // 622 // For the static linking part, we just return a plt expr and everything 623 // else will use the the PLT entry as the address. 624 // 625 // The remaining problem is making sure pointer equality still works. We 626 // need the help of the dynamic linker for that. We let it know that we have 627 // a direct reference to a so symbol by creating an undefined symbol with a 628 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to 629 // the value of the symbol we created. This is true even for got entries, so 630 // pointer equality is maintained. To avoid an infinite loop, the only entry 631 // that points to the real function is a dedicated got entry used by the 632 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT, 633 // R_386_JMP_SLOT, etc). 634 Body.NeedsPltAddr = true; 635 Body.IsPreemptible = false; 636 return toPlt(Expr); 637 } 638 639 errorOrWarn("symbol '" + toString(Body) + "' defined in " + 640 toString(Body.getFile()) + " has no type"); 641 return Expr; 642 } 643 644 // Returns an addend of a given relocation. If it is RELA, an addend 645 // is in a relocation itself. If it is REL, we need to read it from an 646 // input section. 647 template <class ELFT, class RelTy> 648 static int64_t computeAddend(const RelTy &Rel, const uint8_t *Buf) { 649 uint32_t Type = Rel.getType(Config->IsMips64EL); 650 int64_t A = RelTy::IsRela 651 ? getAddend<ELFT>(Rel) 652 : Target->getImplicitAddend(Buf + Rel.r_offset, Type); 653 654 if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC) 655 A += getPPC64TocBase(); 656 return A; 657 } 658 659 // MIPS has an odd notion of "paired" relocations to calculate addends. 660 // For example, if a relocation is of R_MIPS_HI16, there must be a 661 // R_MIPS_LO16 relocation after that, and an addend is calculated using 662 // the two relocations. 663 template <class ELFT, class RelTy> 664 static int64_t computeMipsAddend(const RelTy &Rel, InputSectionBase &Sec, 665 RelExpr Expr, SymbolBody &Body, 666 const RelTy *End) { 667 if (Expr == R_MIPS_GOTREL && Body.isLocal()) 668 return Sec.getFile<ELFT>()->MipsGp0; 669 670 // The ABI says that the paired relocation is used only for REL. 671 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 672 if (RelTy::IsRela) 673 return 0; 674 675 uint32_t Type = Rel.getType(Config->IsMips64EL); 676 uint32_t PairTy = getMipsPairType(Type, Body); 677 if (PairTy == R_MIPS_NONE) 678 return 0; 679 680 const uint8_t *Buf = Sec.Data.data(); 681 uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL); 682 683 // To make things worse, paired relocations might not be contiguous in 684 // the relocation table, so we need to do linear search. *sigh* 685 for (const RelTy *RI = &Rel; RI != End; ++RI) { 686 if (RI->getType(Config->IsMips64EL) != PairTy) 687 continue; 688 if (RI->getSymbol(Config->IsMips64EL) != SymIndex) 689 continue; 690 691 return Target->getImplicitAddend(Buf + RI->r_offset, PairTy); 692 } 693 694 warn("can't find matching " + toString(PairTy) + " relocation for " + 695 toString(Type)); 696 return 0; 697 } 698 699 template <class ELFT> 700 static void reportUndefined(SymbolBody &Sym, InputSectionBase &S, 701 uint64_t Offset) { 702 if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll) 703 return; 704 705 bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL && 706 Sym.getVisibility() == STV_DEFAULT; 707 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal) 708 return; 709 710 std::string Msg = 711 "undefined symbol: " + toString(Sym) + "\n>>> referenced by "; 712 713 std::string Src = S.getSrcMsg<ELFT>(Offset); 714 if (!Src.empty()) 715 Msg += Src + "\n>>> "; 716 Msg += S.getObjMsg<ELFT>(Offset); 717 718 if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) 719 warn(Msg); 720 else 721 errorOrWarn(Msg); 722 } 723 724 template <class RelTy> 725 static std::pair<uint32_t, uint32_t> 726 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) { 727 // MIPS N32 ABI treats series of successive relocations with the same offset 728 // as a single relocation. The similar approach used by N64 ABI, but this ABI 729 // packs all relocations into the single relocation record. Here we emulate 730 // this for the N32 ABI. Iterate over relocation with the same offset and put 731 // theirs types into the single bit-set. 732 uint32_t Processed = 0; 733 for (; I != E && Offset == I->r_offset; ++I) { 734 ++Processed; 735 Type |= I->getType(Config->IsMips64EL) << (8 * Processed); 736 } 737 return std::make_pair(Type, Processed); 738 } 739 740 // .eh_frame sections are mergeable input sections, so their input 741 // offsets are not linearly mapped to output section. For each input 742 // offset, we need to find a section piece containing the offset and 743 // add the piece's base address to the input offset to compute the 744 // output offset. That isn't cheap. 745 // 746 // This class is to speed up the offset computation. When we process 747 // relocations, we access offsets in the monotonically increasing 748 // order. So we can optimize for that access pattern. 749 // 750 // For sections other than .eh_frame, this class doesn't do anything. 751 namespace { 752 class OffsetGetter { 753 public: 754 explicit OffsetGetter(InputSectionBase &Sec) { 755 if (auto *Eh = dyn_cast<EhInputSection>(&Sec)) { 756 P = Eh->Pieces; 757 Size = Eh->Pieces.size(); 758 } 759 } 760 761 // Translates offsets in input sections to offsets in output sections. 762 // Given offset must increase monotonically. We assume that P is 763 // sorted by InputOff. 764 uint64_t get(uint64_t Off) { 765 if (P.empty()) 766 return Off; 767 768 while (I != Size && P[I].InputOff + P[I].Size <= Off) 769 ++I; 770 if (I == Size) 771 return Off; 772 773 // P must be contiguous, so there must be no holes in between. 774 assert(P[I].InputOff <= Off && "Relocation not in any piece"); 775 776 // Offset -1 means that the piece is dead (i.e. garbage collected). 777 if (P[I].OutputOff == -1) 778 return -1; 779 return P[I].OutputOff + Off - P[I].InputOff; 780 } 781 782 private: 783 ArrayRef<EhSectionPiece> P; 784 size_t I = 0; 785 size_t Size; 786 }; 787 } // namespace 788 789 template <class ELFT, class GotPltSection> 790 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt, 791 RelocationSection<ELFT> *Rel, uint32_t Type, 792 SymbolBody &Sym, bool UseSymVA) { 793 Plt->addEntry<ELFT>(Sym); 794 GotPlt->addEntry(Sym); 795 Rel->addReloc({Type, GotPlt, Sym.getGotPltOffset(), UseSymVA, &Sym, 0}); 796 } 797 798 template <class ELFT> 799 static void addGotEntry(SymbolBody &Sym, bool Preemptible) { 800 InX::Got->addEntry(Sym); 801 802 uint64_t Off = Sym.getGotOffset(); 803 uint32_t DynType; 804 RelExpr Expr = R_ABS; 805 806 if (Sym.isTls()) { 807 DynType = Target->TlsGotRel; 808 Expr = R_TLS; 809 } else if (!Preemptible && Config->Pic && !isAbsolute(Sym)) { 810 DynType = Target->RelativeRel; 811 } else { 812 DynType = Target->GotRel; 813 } 814 815 bool Constant = !Preemptible && !(Config->Pic && !isAbsolute(Sym)); 816 if (!Constant) 817 In<ELFT>::RelaDyn->addReloc( 818 {DynType, InX::Got, Off, !Preemptible, &Sym, 0}); 819 820 if (Constant || (!Config->IsRela && !Preemptible)) 821 InX::Got->Relocations.push_back({Expr, DynType, Off, 0, &Sym}); 822 } 823 824 // The reason we have to do this early scan is as follows 825 // * To mmap the output file, we need to know the size 826 // * For that, we need to know how many dynamic relocs we will have. 827 // It might be possible to avoid this by outputting the file with write: 828 // * Write the allocated output sections, computing addresses. 829 // * Apply relocations, recording which ones require a dynamic reloc. 830 // * Write the dynamic relocations. 831 // * Write the rest of the file. 832 // This would have some drawbacks. For example, we would only know if .rela.dyn 833 // is needed after applying relocations. If it is, it will go after rw and rx 834 // sections. Given that it is ro, we will need an extra PT_LOAD. This 835 // complicates things for the dynamic linker and means we would have to reserve 836 // space for the extra PT_LOAD even if we end up not using it. 837 template <class ELFT, class RelTy> 838 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { 839 OffsetGetter GetOffset(Sec); 840 841 for (auto I = Rels.begin(), End = Rels.end(); I != End; ++I) { 842 const RelTy &Rel = *I; 843 SymbolBody &Body = Sec.getFile<ELFT>()->getRelocTargetSym(Rel); 844 uint32_t Type = Rel.getType(Config->IsMips64EL); 845 846 if (Config->MipsN32Abi) { 847 uint32_t Processed; 848 std::tie(Type, Processed) = 849 mergeMipsN32RelTypes(Type, Rel.r_offset, I + 1, End); 850 I += Processed; 851 } 852 853 // Compute the offset of this section in the output section. 854 uint64_t Offset = GetOffset.get(Rel.r_offset); 855 if (Offset == uint64_t(-1)) 856 continue; 857 858 // Report undefined symbols. The fact that we report undefined 859 // symbols here means that we report undefined symbols only when 860 // they have relocations pointing to them. We don't care about 861 // undefined symbols that are in dead-stripped sections. 862 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak()) 863 reportUndefined<ELFT>(Body, Sec, Rel.r_offset); 864 865 RelExpr Expr = Target->getRelExpr(Type, Body, *Sec.File, 866 Sec.Data.begin() + Rel.r_offset); 867 868 // Ignore "hint" relocations because they are only markers for relaxation. 869 if (isRelExprOneOf<R_HINT, R_NONE>(Expr)) 870 continue; 871 872 bool Preemptible = isPreemptible(Body, Type); 873 Expr = adjustExpr<ELFT>(Body, Expr, Type, Sec.Data.data() + Rel.r_offset, 874 Sec, Rel.r_offset); 875 if (ErrorCount) 876 continue; 877 878 // This relocation does not require got entry, but it is relative to got and 879 // needs it to be created. Here we request for that. 880 if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL, 881 R_GOTREL_FROM_END, R_PPC_TOC>(Expr)) 882 InX::Got->HasGotOffRel = true; 883 884 // Read an addend. 885 int64_t Addend = computeAddend<ELFT>(Rel, Sec.Data.data()); 886 if (Config->EMachine == EM_MIPS) 887 Addend += computeMipsAddend<ELFT>(Rel, Sec, Expr, Body, End); 888 889 // Process some TLS relocations, including relaxing TLS relocations. 890 // Note that this function does not handle all TLS relocations. 891 if (unsigned Processed = 892 handleTlsRelocation<ELFT>(Type, Body, Sec, Offset, Addend, Expr)) { 893 I += (Processed - 1); 894 continue; 895 } 896 897 // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol. 898 if (needsPlt(Expr) && !Body.isInPlt()) { 899 if (Body.isGnuIFunc() && !Preemptible) 900 addPltEntry(InX::Iplt, InX::IgotPlt, In<ELFT>::RelaIplt, 901 Target->IRelativeRel, Body, true); 902 else 903 addPltEntry(InX::Plt, InX::GotPlt, In<ELFT>::RelaPlt, Target->PltRel, 904 Body, !Preemptible); 905 } 906 907 // Create a GOT slot if a relocation needs GOT. 908 if (needsGot(Expr)) { 909 if (Config->EMachine == EM_MIPS) { 910 // MIPS ABI has special rules to process GOT entries and doesn't 911 // require relocation entries for them. A special case is TLS 912 // relocations. In that case dynamic loader applies dynamic 913 // relocations to initialize TLS GOT entries. 914 // See "Global Offset Table" in Chapter 5 in the following document 915 // for detailed description: 916 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 917 InX::MipsGot->addEntry(Body, Addend, Expr); 918 if (Body.isTls() && Body.isPreemptible()) 919 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::MipsGot, 920 Body.getGotOffset(), false, &Body, 0}); 921 } else if (!Body.isInGot()) { 922 addGotEntry<ELFT>(Body, Preemptible); 923 } 924 } 925 926 if (!needsPlt(Expr) && !needsGot(Expr) && isPreemptible(Body, Type)) { 927 // We don't know anything about the finaly symbol. Just ask the dynamic 928 // linker to handle the relocation for us. 929 if (!Target->isPicRel(Type)) 930 errorOrWarn( 931 "relocation " + toString(Type) + 932 " cannot be used against shared object; recompile with -fPIC" + 933 getLocation<ELFT>(Sec, Body, Offset)); 934 935 In<ELFT>::RelaDyn->addReloc( 936 {Target->getDynRel(Type), &Sec, Offset, false, &Body, Addend}); 937 938 // MIPS ABI turns using of GOT and dynamic relocations inside out. 939 // While regular ABI uses dynamic relocations to fill up GOT entries 940 // MIPS ABI requires dynamic linker to fills up GOT entries using 941 // specially sorted dynamic symbol table. This affects even dynamic 942 // relocations against symbols which do not require GOT entries 943 // creation explicitly, i.e. do not have any GOT-relocations. So if 944 // a preemptible symbol has a dynamic relocation we anyway have 945 // to create a GOT entry for it. 946 // If a non-preemptible symbol has a dynamic relocation against it, 947 // dynamic linker takes it st_value, adds offset and writes down 948 // result of the dynamic relocation. In case of preemptible symbol 949 // dynamic linker performs symbol resolution, writes the symbol value 950 // to the GOT entry and reads the GOT entry when it needs to perform 951 // a dynamic relocation. 952 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 953 if (Config->EMachine == EM_MIPS) 954 InX::MipsGot->addEntry(Body, Addend, Expr); 955 continue; 956 } 957 958 // If the relocation points to something in the file, we can process it. 959 bool IsConstant = 960 isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, Sec, Rel.r_offset); 961 962 // The size is not going to change, so we fold it in here. 963 if (Expr == R_SIZE) 964 Addend += Body.getSize<ELFT>(); 965 966 // If the output being produced is position independent, the final value 967 // is still not known. In that case we still need some help from the 968 // dynamic linker. We can however do better than just copying the incoming 969 // relocation. We can process some of it and and just ask the dynamic 970 // linker to add the load address. 971 if (!IsConstant) 972 In<ELFT>::RelaDyn->addReloc( 973 {Target->RelativeRel, &Sec, Offset, true, &Body, Addend}); 974 975 // If the produced value is a constant, we just remember to write it 976 // when outputting this section. We also have to do it if the format 977 // uses Elf_Rel, since in that case the written value is the addend. 978 if (IsConstant || !RelTy::IsRela) 979 Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 980 } 981 } 982 983 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) { 984 if (S.AreRelocsRela) 985 scanRelocs<ELFT>(S, S.relas<ELFT>()); 986 else 987 scanRelocs<ELFT>(S, S.rels<ELFT>()); 988 } 989 990 // Insert the Thunks for OutputSection OS into their designated place 991 // in the Sections vector, and recalculate the InputSection output section 992 // offsets. 993 // This may invalidate any output section offsets stored outside of InputSection 994 void ThunkCreator::mergeThunks() { 995 for (auto &KV : ThunkSections) { 996 std::vector<InputSection *> *ISR = KV.first; 997 std::vector<ThunkSection *> &Thunks = KV.second; 998 999 // Order Thunks in ascending OutSecOff 1000 auto ThunkCmp = [](const ThunkSection *A, const ThunkSection *B) { 1001 return A->OutSecOff < B->OutSecOff; 1002 }; 1003 std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp); 1004 1005 // Merge sorted vectors of Thunks and InputSections by OutSecOff 1006 std::vector<InputSection *> Tmp; 1007 Tmp.reserve(ISR->size() + Thunks.size()); 1008 auto MergeCmp = [](const InputSection *A, const InputSection *B) { 1009 // std::merge requires a strict weak ordering. 1010 if (A->OutSecOff < B->OutSecOff) 1011 return true; 1012 if (A->OutSecOff == B->OutSecOff) 1013 // Check if Thunk is immediately before any specific Target InputSection 1014 // for example Mips LA25 Thunks. 1015 if (auto *TA = dyn_cast<ThunkSection>(A)) 1016 if (TA && TA->getTargetInputSection() == B) 1017 return true; 1018 return false; 1019 }; 1020 std::merge(ISR->begin(), ISR->end(), Thunks.begin(), Thunks.end(), 1021 std::back_inserter(Tmp), MergeCmp); 1022 *ISR = std::move(Tmp); 1023 } 1024 } 1025 1026 static uint32_t findEndOfFirstNonExec(OutputSection &Cmd) { 1027 for (BaseCommand *Base : Cmd.Commands) 1028 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) 1029 for (auto *IS : ISD->Sections) 1030 if ((IS->Flags & SHF_EXECINSTR) == 0) 1031 return IS->OutSecOff + IS->getSize(); 1032 return 0; 1033 } 1034 1035 ThunkSection *ThunkCreator::getOSThunkSec(OutputSection *OS, 1036 std::vector<InputSection *> *ISR) { 1037 if (CurTS == nullptr) { 1038 uint32_t Off = findEndOfFirstNonExec(*OS); 1039 CurTS = addThunkSection(OS, ISR, Off); 1040 } 1041 return CurTS; 1042 } 1043 1044 // Add a Thunk that needs to be placed in a ThunkSection that immediately 1045 // precedes its Target. 1046 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) { 1047 ThunkSection *TS = ThunkedSections.lookup(IS); 1048 if (TS) 1049 return TS; 1050 1051 // Find InputSectionRange within Target Output Section (TOS) that the 1052 // InputSection (IS) that we need to precede is in. 1053 OutputSection *TOS = IS->getParent(); 1054 std::vector<InputSection *> *Range = nullptr; 1055 for (BaseCommand *BC : TOS->Commands) 1056 if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) { 1057 InputSection *first = ISD->Sections.front(); 1058 InputSection *last = ISD->Sections.back(); 1059 if (IS->OutSecOff >= first->OutSecOff && 1060 IS->OutSecOff <= last->OutSecOff) { 1061 Range = &ISD->Sections; 1062 break; 1063 } 1064 } 1065 TS = addThunkSection(TOS, Range, IS->OutSecOff); 1066 ThunkedSections[IS] = TS; 1067 return TS; 1068 } 1069 1070 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS, 1071 std::vector<InputSection *> *ISR, 1072 uint64_t Off) { 1073 auto *TS = make<ThunkSection>(OS, Off); 1074 ThunkSections[ISR].push_back(TS); 1075 return TS; 1076 } 1077 1078 std::pair<Thunk *, bool> ThunkCreator::getThunk(SymbolBody &Body, 1079 uint32_t Type) { 1080 auto Res = ThunkedSymbols.insert({&Body, std::vector<Thunk *>()}); 1081 if (!Res.second) { 1082 // Check existing Thunks for Body to see if they can be reused 1083 for (Thunk *ET : Res.first->second) 1084 if (ET->isCompatibleWith(Type)) 1085 return std::make_pair(ET, false); 1086 } 1087 // No existing compatible Thunk in range, create a new one 1088 Thunk *T = addThunk(Type, Body); 1089 Res.first->second.push_back(T); 1090 return std::make_pair(T, true); 1091 } 1092 1093 // Call Fn on every executable InputSection accessed via the linker script 1094 // InputSectionDescription::Sections. 1095 void ThunkCreator::forEachExecInputSection( 1096 ArrayRef<OutputSection *> OutputSections, 1097 std::function<void(OutputSection *, std::vector<InputSection *> *, 1098 InputSection *)> 1099 Fn) { 1100 for (OutputSection *OS : OutputSections) { 1101 if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR)) 1102 continue; 1103 for (BaseCommand *BC : OS->Commands) 1104 if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) { 1105 CurTS = nullptr; 1106 for (InputSection *IS : ISD->Sections) 1107 Fn(OS, &ISD->Sections, IS); 1108 } 1109 } 1110 } 1111 1112 // Process all relocations from the InputSections that have been assigned 1113 // to OutputSections and redirect through Thunks if needed. 1114 // 1115 // createThunks must be called after scanRelocs has created the Relocations for 1116 // each InputSection. It must be called before the static symbol table is 1117 // finalized. If any Thunks are added to an OutputSection the output section 1118 // offsets of the InputSections will change. 1119 // 1120 // FIXME: All Thunks are assumed to be in range of the relocation. Range 1121 // extension Thunks are not yet supported. 1122 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) { 1123 if (Pass > 0) 1124 ThunkSections.clear(); 1125 1126 // Create all the Thunks and insert them into synthetic ThunkSections. The 1127 // ThunkSections are later inserted back into the OutputSection. 1128 1129 // We separate the creation of ThunkSections from the insertion of the 1130 // ThunkSections back into the OutputSection as ThunkSections are not always 1131 // inserted into the same OutputSection as the caller. 1132 forEachExecInputSection(OutputSections, [&](OutputSection *OS, 1133 std::vector<InputSection *> *ISR, 1134 InputSection *IS) { 1135 for (Relocation &Rel : IS->Relocations) { 1136 SymbolBody &Body = *Rel.Sym; 1137 if (Thunks.find(&Body) != Thunks.end() || 1138 !Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Body)) 1139 continue; 1140 Thunk *T; 1141 bool IsNew; 1142 std::tie(T, IsNew) = getThunk(Body, Rel.Type); 1143 if (IsNew) { 1144 // Find or create a ThunkSection for the new Thunk 1145 ThunkSection *TS; 1146 if (auto *TIS = T->getTargetInputSection()) 1147 TS = getISThunkSec(TIS); 1148 else 1149 TS = getOSThunkSec(OS, ISR); 1150 TS->addThunk(T); 1151 Thunks[T->ThunkSym] = T; 1152 } 1153 // Redirect relocation to Thunk, we never go via the PLT to a Thunk 1154 Rel.Sym = T->ThunkSym; 1155 Rel.Expr = fromPlt(Rel.Expr); 1156 } 1157 }); 1158 // Merge all created synthetic ThunkSections back into OutputSection 1159 mergeThunks(); 1160 ++Pass; 1161 return !ThunkSections.empty(); 1162 } 1163 1164 template void elf::scanRelocations<ELF32LE>(InputSectionBase &); 1165 template void elf::scanRelocations<ELF32BE>(InputSectionBase &); 1166 template void elf::scanRelocations<ELF64LE>(InputSectionBase &); 1167 template void elf::scanRelocations<ELF64BE>(InputSectionBase &); 1168