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 "OutputSections.h" 47 #include "Strings.h" 48 #include "SymbolTable.h" 49 #include "SyntheticSections.h" 50 #include "Target.h" 51 #include "Thunks.h" 52 53 #include "llvm/Support/Endian.h" 54 #include "llvm/Support/raw_ostream.h" 55 56 using namespace llvm; 57 using namespace llvm::ELF; 58 using namespace llvm::object; 59 using namespace llvm::support::endian; 60 61 namespace lld { 62 namespace elf { 63 64 static bool refersToGotEntry(RelExpr Expr) { 65 return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF, 66 R_MIPS_GOT_OFF32, R_MIPS_TLSGD, R_MIPS_TLSLD, 67 R_GOT_PAGE_PC, R_GOT_PC, R_GOT_FROM_END, R_TLSGD, 68 R_TLSGD_PC, R_TLSDESC, R_TLSDESC_PAGE>(Expr); 69 } 70 71 static bool isPreemptible(const SymbolBody &Body, uint32_t Type) { 72 // In case of MIPS GP-relative relocations always resolve to a definition 73 // in a regular input file, ignoring the one-definition rule. So we, 74 // for example, should not attempt to create a dynamic relocation even 75 // if the target symbol is preemptible. There are two two MIPS GP-relative 76 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16 77 // can be against a preemptible symbol. 78 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all 79 // relocation types occupy eight bit. In case of N64 ABI we extract first 80 // relocation from 3-in-1 packet because only the first relocation can 81 // be against a real symbol. 82 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16) 83 return false; 84 return Body.isPreemptible(); 85 } 86 87 // This function is similar to the `handleTlsRelocation`. ARM and MIPS do not 88 // support any relaxations for TLS relocations so by factoring out ARM and MIPS 89 // handling in to the separate function we can simplify the code and do not 90 // pollute `handleTlsRelocation` by ARM and MIPS `ifs` statements. 91 template <class ELFT, class GOT> 92 static unsigned handleNoRelaxTlsRelocation( 93 GOT *Got, uint32_t Type, SymbolBody &Body, InputSectionBase<ELFT> &C, 94 typename ELFT::uint Offset, typename ELFT::uint Addend, RelExpr Expr) { 95 typedef typename ELFT::uint uintX_t; 96 auto addModuleReloc = [](SymbolBody &Body, GOT *Got, uintX_t Off, bool LD) { 97 // The Dynamic TLS Module Index Relocation can be statically resolved to 1 98 // if we know that we are linking an executable. For ARM we resolve the 99 // relocation when writing the Got. MIPS has a custom Got implementation 100 // that writes the Module index in directly. 101 if (!Body.isPreemptible() && !Config->Pic && Config->EMachine == EM_ARM) 102 Got->Relocations.push_back( 103 {R_ABS, Target->TlsModuleIndexRel, Off, 0, &Body}); 104 else { 105 SymbolBody *Dest = LD ? nullptr : &Body; 106 In<ELFT>::RelaDyn->addReloc( 107 {Target->TlsModuleIndexRel, Got, Off, false, Dest, 0}); 108 } 109 }; 110 if (Expr == R_MIPS_TLSLD || Expr == R_TLSLD_PC) { 111 if (Got->addTlsIndex() && (Config->Pic || Config->EMachine == EM_ARM)) 112 addModuleReloc(Body, Got, Got->getTlsIndexOff(), true); 113 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 114 return 1; 115 } 116 if (Target->isTlsGlobalDynamicRel(Type)) { 117 if (Got->addDynTlsEntry(Body) && 118 (Body.isPreemptible() || Config->EMachine == EM_ARM)) { 119 uintX_t Off = Got->getGlobalDynOffset(Body); 120 addModuleReloc(Body, Got, Off, false); 121 if (Body.isPreemptible()) 122 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Got, 123 Off + (uintX_t)sizeof(uintX_t), false, 124 &Body, 0}); 125 } 126 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 127 return 1; 128 } 129 return 0; 130 } 131 132 // Returns the number of relocations processed. 133 template <class ELFT> 134 static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body, 135 InputSectionBase<ELFT> &C, 136 typename ELFT::uint Offset, 137 typename ELFT::uint Addend, RelExpr Expr) { 138 if (!(C.Flags & SHF_ALLOC)) 139 return 0; 140 141 if (!Body.isTls()) 142 return 0; 143 144 typedef typename ELFT::uint uintX_t; 145 146 if (Config->EMachine == EM_ARM) 147 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::Got, Type, Body, C, 148 Offset, Addend, Expr); 149 if (Config->EMachine == EM_MIPS) 150 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::MipsGot, Type, Body, C, 151 Offset, Addend, Expr); 152 153 bool IsPreemptible = isPreemptible(Body, Type); 154 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC_CALL) && 155 Config->Shared) { 156 if (In<ELFT>::Got->addDynTlsEntry(Body)) { 157 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body); 158 In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off, 159 !IsPreemptible, &Body, 0}); 160 } 161 if (Expr != R_TLSDESC_CALL) 162 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 163 return 1; 164 } 165 166 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) { 167 // Local-Dynamic relocs can be relaxed to Local-Exec. 168 if (!Config->Shared) { 169 C.Relocations.push_back( 170 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body}); 171 return 2; 172 } 173 if (In<ELFT>::Got->addTlsIndex()) 174 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got, 175 In<ELFT>::Got->getTlsIndexOff(), false, 176 nullptr, 0}); 177 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 178 return 1; 179 } 180 181 // Local-Dynamic relocs can be relaxed to Local-Exec. 182 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) { 183 C.Relocations.push_back( 184 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body}); 185 return 1; 186 } 187 188 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_TLSDESC_CALL || 189 Target->isTlsGlobalDynamicRel(Type)) { 190 if (Config->Shared) { 191 if (In<ELFT>::Got->addDynTlsEntry(Body)) { 192 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body); 193 In<ELFT>::RelaDyn->addReloc( 194 {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0}); 195 196 // If the symbol is preemptible we need the dynamic linker to write 197 // the offset too. 198 uintX_t OffsetOff = Off + (uintX_t)sizeof(uintX_t); 199 if (IsPreemptible) 200 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got, 201 OffsetOff, false, &Body, 0}); 202 else 203 In<ELFT>::Got->Relocations.push_back( 204 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body}); 205 } 206 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 207 return 1; 208 } 209 210 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec 211 // depending on the symbol being locally defined or not. 212 if (IsPreemptible) { 213 C.Relocations.push_back( 214 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type, 215 Offset, Addend, &Body}); 216 if (!Body.isInGot()) { 217 In<ELFT>::Got->addEntry(Body); 218 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got, 219 Body.getGotOffset<ELFT>(), false, &Body, 220 0}); 221 } 222 return Target->TlsGdRelaxSkip; 223 } 224 C.Relocations.push_back( 225 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, 226 Offset, Addend, &Body}); 227 return Target->TlsGdRelaxSkip; 228 } 229 230 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally 231 // defined. 232 if (Target->isTlsInitialExecRel(Type) && !Config->Shared && !IsPreemptible) { 233 C.Relocations.push_back( 234 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body}); 235 return 1; 236 } 237 return 0; 238 } 239 240 template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) { 241 return read32<E>(Loc) & 0xffff; 242 } 243 244 template <class RelTy> 245 static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) { 246 switch (Rel->getType(Config->Mips64EL)) { 247 case R_MIPS_HI16: 248 return R_MIPS_LO16; 249 case R_MIPS_GOT16: 250 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE; 251 case R_MIPS_PCHI16: 252 return R_MIPS_PCLO16; 253 case R_MICROMIPS_HI16: 254 return R_MICROMIPS_LO16; 255 default: 256 return R_MIPS_NONE; 257 } 258 } 259 260 template <class ELFT, class RelTy> 261 static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc, 262 SymbolBody &Sym, const RelTy *Rel, 263 const RelTy *End) { 264 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL); 265 uint32_t Type = getMipsPairType(Rel, Sym); 266 267 // Some MIPS relocations use addend calculated from addend of the relocation 268 // itself and addend of paired relocation. ABI requires to compute such 269 // combined addend in case of REL relocation record format only. 270 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 271 if (RelTy::IsRela || Type == R_MIPS_NONE) 272 return 0; 273 274 for (const RelTy *RI = Rel; RI != End; ++RI) { 275 if (RI->getType(Config->Mips64EL) != Type) 276 continue; 277 if (RI->getSymbol(Config->Mips64EL) != SymIndex) 278 continue; 279 const endianness E = ELFT::TargetEndianness; 280 return ((read32<E>(BufLoc) & 0xffff) << 16) + 281 readSignedLo16<E>(Buf + RI->r_offset); 282 } 283 warn("can't find matching " + toString(Type) + " relocation for " + 284 toString(Rel->getType(Config->Mips64EL))); 285 return 0; 286 } 287 288 // True if non-preemptable symbol always has the same value regardless of where 289 // the DSO is loaded. 290 template <class ELFT> static bool isAbsolute(const SymbolBody &Body) { 291 if (Body.isUndefined()) 292 return !Body.isLocal() && Body.symbol()->isWeak(); 293 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body)) 294 return DR->Section == nullptr; // Absolute symbol. 295 return false; 296 } 297 298 template <class ELFT> static bool isAbsoluteValue(const SymbolBody &Body) { 299 return isAbsolute<ELFT>(Body) || Body.isTls(); 300 } 301 302 static bool needsPlt(RelExpr Expr) { 303 return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC, 304 R_THUNK_PLT_PC>(Expr); 305 } 306 307 // True if this expression is of the form Sym - X, where X is a position in the 308 // file (PC, or GOT for example). 309 static bool isRelExpr(RelExpr Expr) { 310 return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL, 311 R_PAGE_PC, R_RELAX_GOT_PC, R_THUNK_PC, R_THUNK_PLT_PC>( 312 Expr); 313 } 314 315 template <class ELFT> 316 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type, 317 const SymbolBody &Body, 318 InputSectionBase<ELFT> &S, 319 typename ELFT::uint RelOff) { 320 // These expressions always compute a constant 321 if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, 322 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_TLSGD, 323 R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC, R_TLSGD_PC, R_TLSGD, 324 R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT, 325 R_THUNK_PC, R_THUNK_PLT_PC>(E)) 326 return true; 327 328 // These never do, except if the entire file is position dependent or if 329 // only the low bits are used. 330 if (E == R_GOT || E == R_PLT || E == R_TLSDESC) 331 return Target->usesOnlyLowPageBits(Type) || !Config->Pic; 332 333 if (isPreemptible(Body, Type)) 334 return false; 335 336 if (!Config->Pic) 337 return true; 338 339 bool AbsVal = isAbsoluteValue<ELFT>(Body); 340 bool RelE = isRelExpr(E); 341 if (AbsVal && !RelE) 342 return true; 343 if (!AbsVal && RelE) 344 return true; 345 346 // Relative relocation to an absolute value. This is normally unrepresentable, 347 // but if the relocation refers to a weak undefined symbol, we allow it to 348 // resolve to the image base. This is a little strange, but it allows us to 349 // link function calls to such symbols. Normally such a call will be guarded 350 // with a comparison, which will load a zero from the GOT. 351 // Another special case is MIPS _gp_disp symbol which represents offset 352 // between start of a function and '_gp' value and defined as absolute just 353 // to simplify the code. 354 if (AbsVal && RelE) { 355 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) 356 return true; 357 if (&Body == ElfSym<ELFT>::MipsGpDisp) 358 return true; 359 error(S.getLocation(RelOff) + ": relocation " + toString(Type) + 360 " cannot refer to absolute symbol '" + toString(Body) + 361 "' defined in " + toString(Body.File)); 362 return true; 363 } 364 365 return Target->usesOnlyLowPageBits(Type); 366 } 367 368 static RelExpr toPlt(RelExpr Expr) { 369 if (Expr == R_PPC_OPD) 370 return R_PPC_PLT_OPD; 371 if (Expr == R_PC) 372 return R_PLT_PC; 373 if (Expr == R_PAGE_PC) 374 return R_PLT_PAGE_PC; 375 if (Expr == R_ABS) 376 return R_PLT; 377 return Expr; 378 } 379 380 static RelExpr fromPlt(RelExpr Expr) { 381 // We decided not to use a plt. Optimize a reference to the plt to a 382 // reference to the symbol itself. 383 if (Expr == R_PLT_PC) 384 return R_PC; 385 if (Expr == R_PPC_PLT_OPD) 386 return R_PPC_OPD; 387 if (Expr == R_PLT) 388 return R_ABS; 389 return Expr; 390 } 391 392 template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) { 393 typedef typename ELFT::uint uintX_t; 394 395 uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign; 396 uintX_t SymValue = SS->Sym.st_value; 397 int TrailingZeros = 398 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue)); 399 return 1 << TrailingZeros; 400 } 401 402 template <class ELFT> static bool isReadOnly(SharedSymbol<ELFT> *SS) { 403 typedef typename ELFT::uint uintX_t; 404 typedef typename ELFT::Phdr Elf_Phdr; 405 406 // Determine if the symbol is read-only by scanning the DSO's program headers. 407 uintX_t Value = SS->Sym.st_value; 408 for (const Elf_Phdr &Phdr : check(SS->file()->getObj().program_headers())) 409 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) && 410 !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr && 411 Value < Phdr.p_vaddr + Phdr.p_memsz) 412 return true; 413 return false; 414 } 415 416 // Reserve space in .bss or .bss.rel.ro for copy relocation. 417 template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) { 418 typedef typename ELFT::uint uintX_t; 419 typedef typename ELFT::Sym Elf_Sym; 420 421 // Copy relocation against zero-sized symbol doesn't make sense. 422 uintX_t SymSize = SS->template getSize<ELFT>(); 423 if (SymSize == 0) 424 fatal("cannot create a copy relocation for symbol " + toString(*SS)); 425 426 // See if this symbol is in a read-only segment. If so, preserve the symbol's 427 // memory protection by reserving space in the .bss.rel.ro section. 428 bool IsReadOnly = isReadOnly(SS); 429 OutputSection<ELFT> *CopySec = 430 IsReadOnly ? Out<ELFT>::BssRelRo : Out<ELFT>::Bss; 431 432 uintX_t Alignment = getAlignment(SS); 433 uintX_t Off = alignTo(CopySec->Size, Alignment); 434 CopySec->Size = Off + SymSize; 435 CopySec->updateAlignment(Alignment); 436 uintX_t Shndx = SS->Sym.st_shndx; 437 uintX_t Value = SS->Sym.st_value; 438 // Look through the DSO's dynamic symbol table for aliases and create a 439 // dynamic symbol for each one. This causes the copy relocation to correctly 440 // interpose any aliases. 441 for (const Elf_Sym &S : SS->file()->getGlobalSymbols()) { 442 if (S.st_shndx != Shndx || S.st_value != Value) 443 continue; 444 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>( 445 Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable())))); 446 if (!Alias) 447 continue; 448 Alias->CopyIsInBssRelRo = IsReadOnly; 449 Alias->CopyOffset = Off; 450 Alias->NeedsCopyOrPltAddr = true; 451 Alias->symbol()->IsUsedInRegularObj = true; 452 } 453 In<ELFT>::RelaDyn->addReloc({Target->CopyRel, CopySec, Off, false, SS, 0}); 454 } 455 456 template <class ELFT> 457 static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body, 458 bool IsWrite, RelExpr Expr, uint32_t Type, 459 const uint8_t *Data, InputSectionBase<ELFT> &S, 460 typename ELFT::uint RelOff) { 461 bool Preemptible = isPreemptible(Body, Type); 462 if (Body.isGnuIFunc()) { 463 Expr = toPlt(Expr); 464 } else if (!Preemptible) { 465 if (needsPlt(Expr)) 466 Expr = fromPlt(Expr); 467 if (Expr == R_GOT_PC && !isAbsoluteValue<ELFT>(Body)) 468 Expr = Target->adjustRelaxExpr(Type, Data, Expr); 469 } 470 Expr = Target->getThunkExpr(Expr, Type, File, Body); 471 472 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff)) 473 return Expr; 474 475 // This relocation would require the dynamic linker to write a value to read 476 // only memory. We can hack around it if we are producing an executable and 477 // the refered symbol can be preemepted to refer to the executable. 478 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) { 479 error(S.getLocation(RelOff) + ": can't create dynamic relocation " + 480 toString(Type) + " against " + 481 (Body.getName().empty() ? "local symbol in readonly segment" 482 : "symbol '" + toString(Body) + "'") + 483 " defined in " + toString(Body.File)); 484 return Expr; 485 } 486 if (Body.getVisibility() != STV_DEFAULT) { 487 error(S.getLocation(RelOff) + ": cannot preempt symbol '" + toString(Body) + 488 "' defined in " + toString(Body.File)); 489 return Expr; 490 } 491 if (Body.isObject()) { 492 // Produce a copy relocation. 493 auto *B = cast<SharedSymbol<ELFT>>(&Body); 494 if (!B->needsCopy()) 495 addCopyRelSymbol(B); 496 return Expr; 497 } 498 if (Body.isFunc()) { 499 // This handles a non PIC program call to function in a shared library. In 500 // an ideal world, we could just report an error saying the relocation can 501 // overflow at runtime. In the real world with glibc, crt1.o has a 502 // R_X86_64_PC32 pointing to libc.so. 503 // 504 // The general idea on how to handle such cases is to create a PLT entry and 505 // use that as the function value. 506 // 507 // For the static linking part, we just return a plt expr and everything 508 // else will use the the PLT entry as the address. 509 // 510 // The remaining problem is making sure pointer equality still works. We 511 // need the help of the dynamic linker for that. We let it know that we have 512 // a direct reference to a so symbol by creating an undefined symbol with a 513 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to 514 // the value of the symbol we created. This is true even for got entries, so 515 // pointer equality is maintained. To avoid an infinite loop, the only entry 516 // that points to the real function is a dedicated got entry used by the 517 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT, 518 // R_386_JMP_SLOT, etc). 519 Body.NeedsCopyOrPltAddr = true; 520 return toPlt(Expr); 521 } 522 error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) + 523 " is missing type"); 524 525 return Expr; 526 } 527 528 template <class ELFT, class RelTy> 529 static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File, 530 const uint8_t *SectionData, 531 const RelTy *End, const RelTy &RI, 532 RelExpr Expr, SymbolBody &Body) { 533 typedef typename ELFT::uint uintX_t; 534 535 uint32_t Type = RI.getType(Config->Mips64EL); 536 uintX_t Addend = getAddend<ELFT>(RI); 537 const uint8_t *BufLoc = SectionData + RI.r_offset; 538 if (!RelTy::IsRela) 539 Addend += Target->getImplicitAddend(BufLoc, Type); 540 if (Config->EMachine == EM_MIPS) { 541 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End); 542 if (Type == R_MIPS_LO16 && Expr == R_PC) 543 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp 544 // symbol. In that case we should use the following formula for 545 // calculation "AHL + GP - P + 4". Let's add 4 right here. 546 // For details see p. 4-19 at 547 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 548 Addend += 4; 549 if (Expr == R_MIPS_GOTREL && Body.isLocal()) 550 Addend += File.MipsGp0; 551 } 552 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC) 553 Addend += getPPC64TocBase(); 554 return Addend; 555 } 556 557 template <class ELFT> 558 static void reportUndefined(SymbolBody &Sym, InputSectionBase<ELFT> &S, 559 typename ELFT::uint Offset) { 560 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore) 561 return; 562 563 if (Config->Shared && Sym.symbol()->Visibility == STV_DEFAULT && 564 Config->UnresolvedSymbols != UnresolvedPolicy::NoUndef) 565 return; 566 567 std::string Msg = 568 S.getLocation(Offset) + ": undefined symbol '" + toString(Sym) + "'"; 569 570 if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn) 571 warn(Msg); 572 else 573 error(Msg); 574 } 575 576 template <class RelTy> 577 static std::pair<uint32_t, uint32_t> 578 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) { 579 // MIPS N32 ABI treats series of successive relocations with the same offset 580 // as a single relocation. The similar approach used by N64 ABI, but this ABI 581 // packs all relocations into the single relocation record. Here we emulate 582 // this for the N32 ABI. Iterate over relocation with the same offset and put 583 // theirs types into the single bit-set. 584 uint32_t Processed = 0; 585 for (; I != E && Offset == I->r_offset; ++I) { 586 ++Processed; 587 Type |= I->getType(Config->Mips64EL) << (8 * Processed); 588 } 589 return std::make_pair(Type, Processed); 590 } 591 592 // The reason we have to do this early scan is as follows 593 // * To mmap the output file, we need to know the size 594 // * For that, we need to know how many dynamic relocs we will have. 595 // It might be possible to avoid this by outputting the file with write: 596 // * Write the allocated output sections, computing addresses. 597 // * Apply relocations, recording which ones require a dynamic reloc. 598 // * Write the dynamic relocations. 599 // * Write the rest of the file. 600 // This would have some drawbacks. For example, we would only know if .rela.dyn 601 // is needed after applying relocations. If it is, it will go after rw and rx 602 // sections. Given that it is ro, we will need an extra PT_LOAD. This 603 // complicates things for the dynamic linker and means we would have to reserve 604 // space for the extra PT_LOAD even if we end up not using it. 605 template <class ELFT, class RelTy> 606 static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) { 607 typedef typename ELFT::uint uintX_t; 608 609 bool IsWrite = C.Flags & SHF_WRITE; 610 611 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) { 612 In<ELFT>::RelaDyn->addReloc(Reloc); 613 }; 614 615 const elf::ObjectFile<ELFT> *File = C.getFile(); 616 ArrayRef<uint8_t> SectionData = C.Data; 617 const uint8_t *Buf = SectionData.begin(); 618 619 ArrayRef<EhSectionPiece> Pieces; 620 if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C)) 621 Pieces = Eh->Pieces; 622 623 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin(); 624 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end(); 625 626 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) { 627 const RelTy &RI = *I; 628 SymbolBody &Body = File->getRelocTargetSym(RI); 629 uint32_t Type = RI.getType(Config->Mips64EL); 630 631 if (Config->MipsN32Abi) { 632 uint32_t Processed; 633 std::tie(Type, Processed) = 634 mergeMipsN32RelTypes(Type, RI.r_offset, I + 1, E); 635 I += Processed; 636 } 637 638 // We only report undefined symbols if they are referenced somewhere in the 639 // code. 640 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak()) 641 reportUndefined(Body, C, RI.r_offset); 642 643 RelExpr Expr = Target->getRelExpr(Type, Body); 644 bool Preemptible = isPreemptible(Body, Type); 645 Expr = adjustExpr(*File, Body, IsWrite, Expr, Type, Buf + RI.r_offset, C, 646 RI.r_offset); 647 if (ErrorCount) 648 continue; 649 650 // Skip a relocation that points to a dead piece 651 // in a eh_frame section. 652 while (PieceI != PieceE && 653 (PieceI->InputOff + PieceI->size() <= RI.r_offset)) 654 ++PieceI; 655 656 // Compute the offset of this section in the output section. We do it here 657 // to try to compute it only once. 658 uintX_t Offset; 659 if (PieceI != PieceE) { 660 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece"); 661 if (PieceI->OutputOff == -1) 662 continue; 663 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff; 664 } else { 665 Offset = RI.r_offset; 666 } 667 668 // This relocation does not require got entry, but it is relative to got and 669 // needs it to be created. Here we request for that. 670 if (Expr == R_GOTONLY_PC || Expr == R_GOTONLY_PC_FROM_END || 671 Expr == R_GOTREL || Expr == R_GOTREL_FROM_END || Expr == R_PPC_TOC) 672 In<ELFT>::Got->HasGotOffRel = true; 673 674 uintX_t Addend = computeAddend(*File, Buf, E, RI, Expr, Body); 675 676 if (unsigned Processed = 677 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) { 678 I += (Processed - 1); 679 continue; 680 } 681 682 // Ignore "hint" and TLS Descriptor call relocation because they are 683 // only markers for relaxation. 684 if (isRelExprOneOf<R_HINT, R_TLSDESC_CALL>(Expr)) 685 continue; 686 687 if (needsPlt(Expr) || 688 isRelExprOneOf<R_THUNK_ABS, R_THUNK_PC, R_THUNK_PLT_PC>(Expr) || 689 refersToGotEntry(Expr) || !isPreemptible(Body, Type)) { 690 // If the relocation points to something in the file, we can process it. 691 bool Constant = 692 isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, C, RI.r_offset); 693 694 // If the output being produced is position independent, the final value 695 // is still not known. In that case we still need some help from the 696 // dynamic linker. We can however do better than just copying the incoming 697 // relocation. We can process some of it and and just ask the dynamic 698 // linker to add the load address. 699 if (!Constant) 700 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend}); 701 702 // If the produced value is a constant, we just remember to write it 703 // when outputting this section. We also have to do it if the format 704 // uses Elf_Rel, since in that case the written value is the addend. 705 if (Constant || !RelTy::IsRela) 706 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); 707 } else { 708 // We don't know anything about the finaly symbol. Just ask the dynamic 709 // linker to handle the relocation for us. 710 if (!Target->isPicRel(Type)) 711 error(C.getLocation(Offset) + ": relocation " + toString(Type) + 712 " cannot be used against shared object; recompile with -fPIC."); 713 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend}); 714 715 // MIPS ABI turns using of GOT and dynamic relocations inside out. 716 // While regular ABI uses dynamic relocations to fill up GOT entries 717 // MIPS ABI requires dynamic linker to fills up GOT entries using 718 // specially sorted dynamic symbol table. This affects even dynamic 719 // relocations against symbols which do not require GOT entries 720 // creation explicitly, i.e. do not have any GOT-relocations. So if 721 // a preemptible symbol has a dynamic relocation we anyway have 722 // to create a GOT entry for it. 723 // If a non-preemptible symbol has a dynamic relocation against it, 724 // dynamic linker takes it st_value, adds offset and writes down 725 // result of the dynamic relocation. In case of preemptible symbol 726 // dynamic linker performs symbol resolution, writes the symbol value 727 // to the GOT entry and reads the GOT entry when it needs to perform 728 // a dynamic relocation. 729 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 730 if (Config->EMachine == EM_MIPS) 731 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr); 732 continue; 733 } 734 735 // At this point we are done with the relocated position. Some relocations 736 // also require us to create a got or plt entry. 737 738 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol. 739 if (needsPlt(Expr)) { 740 if (Body.isInPlt()) 741 continue; 742 743 if (Body.isGnuIFunc() && !Preemptible) { 744 In<ELFT>::Iplt->addEntry(Body); 745 In<ELFT>::IgotPlt->addEntry(Body); 746 In<ELFT>::RelaIplt->addReloc({Target->IRelativeRel, In<ELFT>::IgotPlt, 747 Body.getGotPltOffset<ELFT>(), 748 !Preemptible, &Body, 0}); 749 } else { 750 In<ELFT>::Plt->addEntry(Body); 751 In<ELFT>::GotPlt->addEntry(Body); 752 In<ELFT>::RelaPlt->addReloc({Target->PltRel, In<ELFT>::GotPlt, 753 Body.getGotPltOffset<ELFT>(), !Preemptible, 754 &Body, 0}); 755 } 756 continue; 757 } 758 759 if (refersToGotEntry(Expr)) { 760 if (Config->EMachine == EM_MIPS) { 761 // MIPS ABI has special rules to process GOT entries and doesn't 762 // require relocation entries for them. A special case is TLS 763 // relocations. In that case dynamic loader applies dynamic 764 // relocations to initialize TLS GOT entries. 765 // See "Global Offset Table" in Chapter 5 in the following document 766 // for detailed description: 767 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 768 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr); 769 if (Body.isTls() && Body.isPreemptible()) 770 AddDyn({Target->TlsGotRel, In<ELFT>::MipsGot, 771 Body.getGotOffset<ELFT>(), false, &Body, 0}); 772 continue; 773 } 774 775 if (Body.isInGot()) 776 continue; 777 778 In<ELFT>::Got->addEntry(Body); 779 uintX_t Off = Body.getGotOffset<ELFT>(); 780 uint32_t DynType; 781 RelExpr GotRE = R_ABS; 782 if (Body.isTls()) { 783 DynType = Target->TlsGotRel; 784 GotRE = R_TLS; 785 } else if (!Preemptible && Config->Pic && !isAbsolute<ELFT>(Body)) 786 DynType = Target->RelativeRel; 787 else 788 DynType = Target->GotRel; 789 790 // FIXME: this logic is almost duplicated above. 791 bool Constant = !Preemptible && !(Config->Pic && !isAbsolute<ELFT>(Body)); 792 if (!Constant) 793 AddDyn({DynType, In<ELFT>::Got, Off, !Preemptible, &Body, 0}); 794 if (Constant || (!RelTy::IsRela && !Preemptible)) 795 In<ELFT>::Got->Relocations.push_back({GotRE, DynType, Off, 0, &Body}); 796 continue; 797 } 798 } 799 } 800 801 template <class ELFT> void scanRelocations(InputSectionBase<ELFT> &S) { 802 if (S.AreRelocsRela) 803 scanRelocs(S, S.relas()); 804 else 805 scanRelocs(S, S.rels()); 806 } 807 808 template <class ELFT, class RelTy> 809 static void createThunks(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) { 810 const elf::ObjectFile<ELFT> *File = C.getFile(); 811 for (const RelTy &Rel : Rels) { 812 SymbolBody &Body = File->getRelocTargetSym(Rel); 813 uint32_t Type = Rel.getType(Config->Mips64EL); 814 RelExpr Expr = Target->getRelExpr(Type, Body); 815 if (!isPreemptible(Body, Type) && needsPlt(Expr)) 816 Expr = fromPlt(Expr); 817 Expr = Target->getThunkExpr(Expr, Type, *File, Body); 818 // Some targets might require creation of thunks for relocations. 819 // Now we support only MIPS which requires LA25 thunk to call PIC 820 // code from non-PIC one, and ARM which requires interworking. 821 if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) { 822 auto *Sec = cast<InputSection<ELFT>>(&C); 823 addThunk<ELFT>(Type, Body, *Sec); 824 } 825 } 826 } 827 828 template <class ELFT> void createThunks(InputSectionBase<ELFT> &S) { 829 if (S.AreRelocsRela) 830 createThunks(S, S.relas()); 831 else 832 createThunks(S, S.rels()); 833 } 834 835 template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &); 836 template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &); 837 template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &); 838 template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &); 839 840 template void createThunks<ELF32LE>(InputSectionBase<ELF32LE> &); 841 template void createThunks<ELF32BE>(InputSectionBase<ELF32BE> &); 842 template void createThunks<ELF64LE>(InputSectionBase<ELF64LE> &); 843 template void createThunks<ELF64BE>(InputSectionBase<ELF64BE> &); 844 } 845 } 846