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