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