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