1 //===- Relocations.cpp ----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains platform-independent functions to process relocations. 10 // I'll describe the overview of this file here. 11 // 12 // Simple relocations are easy to handle for the linker. For example, 13 // for R_X86_64_PC64 relocs, the linker just has to fix up locations 14 // with the relative offsets to the target symbols. It would just be 15 // reading records from relocation sections and applying them to output. 16 // 17 // But not all relocations are that easy to handle. For example, for 18 // R_386_GOTOFF relocs, the linker has to create new GOT entries for 19 // symbols if they don't exist, and fix up locations with GOT entry 20 // offsets from the beginning of GOT section. So there is more than 21 // fixing addresses in relocation processing. 22 // 23 // ELF defines a large number of complex relocations. 24 // 25 // The functions in this file analyze relocations and do whatever needs 26 // to be done. It includes, but not limited to, the following. 27 // 28 // - create GOT/PLT entries 29 // - create new relocations in .dynsym to let the dynamic linker resolve 30 // them at runtime (since ELF supports dynamic linking, not all 31 // relocations can be resolved at link-time) 32 // - create COPY relocs and reserve space in .bss 33 // - replace expensive relocs (in terms of runtime cost) with cheap ones 34 // - error out infeasible combinations such as PIC and non-relative relocs 35 // 36 // Note that the functions in this file don't actually apply relocations 37 // because it doesn't know about the output file nor the output file buffer. 38 // It instead stores Relocation objects to InputSection's Relocations 39 // vector to let it apply later in InputSection::writeTo. 40 // 41 //===----------------------------------------------------------------------===// 42 43 #include "Relocations.h" 44 #include "Config.h" 45 #include "LinkerScript.h" 46 #include "OutputSections.h" 47 #include "SymbolTable.h" 48 #include "Symbols.h" 49 #include "SyntheticSections.h" 50 #include "Target.h" 51 #include "Thunks.h" 52 #include "lld/Common/ErrorHandler.h" 53 #include "lld/Common/Memory.h" 54 #include "llvm/ADT/SmallSet.h" 55 #include "llvm/Demangle/Demangle.h" 56 #include "llvm/Support/Endian.h" 57 #include <algorithm> 58 59 using namespace llvm; 60 using namespace llvm::ELF; 61 using namespace llvm::object; 62 using namespace llvm::support::endian; 63 using namespace lld; 64 using namespace lld::elf; 65 66 static Optional<std::string> getLinkerScriptLocation(const Symbol &sym) { 67 for (SectionCommand *cmd : script->sectionCommands) 68 if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) 69 if (assign->sym == &sym) 70 return assign->location; 71 return None; 72 } 73 74 static std::string getDefinedLocation(const Symbol &sym) { 75 const char msg[] = "\n>>> defined in "; 76 if (sym.file) 77 return msg + toString(sym.file); 78 if (Optional<std::string> loc = getLinkerScriptLocation(sym)) 79 return msg + *loc; 80 return ""; 81 } 82 83 // Construct a message in the following format. 84 // 85 // >>> defined in /home/alice/src/foo.o 86 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12) 87 // >>> /home/alice/src/bar.o:(.text+0x1) 88 static std::string getLocation(InputSectionBase &s, const Symbol &sym, 89 uint64_t off) { 90 std::string msg = getDefinedLocation(sym) + "\n>>> referenced by "; 91 std::string src = s.getSrcMsg(sym, off); 92 if (!src.empty()) 93 msg += src + "\n>>> "; 94 return msg + s.getObjMsg(off); 95 } 96 97 void elf::reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v, 98 int64_t min, uint64_t max) { 99 ErrorPlace errPlace = getErrorPlace(loc); 100 std::string hint; 101 if (rel.sym && !rel.sym->isSection()) 102 hint = "; references " + lld::toString(*rel.sym); 103 if (!errPlace.srcLoc.empty()) 104 hint += "\n>>> referenced by " + errPlace.srcLoc; 105 if (rel.sym && !rel.sym->isSection()) 106 hint += getDefinedLocation(*rel.sym); 107 108 if (errPlace.isec && errPlace.isec->name.startswith(".debug")) 109 hint += "; consider recompiling with -fdebug-types-section to reduce size " 110 "of debug sections"; 111 112 errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) + 113 " out of range: " + v.str() + " is not in [" + Twine(min).str() + 114 ", " + Twine(max).str() + "]" + hint); 115 } 116 117 void elf::reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym, 118 const Twine &msg) { 119 ErrorPlace errPlace = getErrorPlace(loc); 120 std::string hint; 121 if (!sym.getName().empty()) 122 hint = "; references " + lld::toString(sym) + getDefinedLocation(sym); 123 errorOrWarn(errPlace.loc + msg + " is out of range: " + Twine(v) + 124 " is not in [" + Twine(llvm::minIntN(n)) + ", " + 125 Twine(llvm::maxIntN(n)) + "]" + hint); 126 } 127 128 // Build a bitmask with one bit set for each 64 subset of RelExpr. 129 static constexpr uint64_t buildMask() { return 0; } 130 131 template <typename... Tails> 132 static constexpr uint64_t buildMask(int head, Tails... tails) { 133 return (0 <= head && head < 64 ? uint64_t(1) << head : 0) | 134 buildMask(tails...); 135 } 136 137 // Return true if `Expr` is one of `Exprs`. 138 // There are more than 64 but less than 128 RelExprs, so we divide the set of 139 // exprs into [0, 64) and [64, 128) and represent each range as a constant 140 // 64-bit mask. Then we decide which mask to test depending on the value of 141 // expr and use a simple shift and bitwise-and to test for membership. 142 template <RelExpr... Exprs> static bool oneof(RelExpr expr) { 143 assert(0 <= expr && (int)expr < 128 && 144 "RelExpr is too large for 128-bit mask!"); 145 146 if (expr >= 64) 147 return (uint64_t(1) << (expr - 64)) & buildMask((Exprs - 64)...); 148 return (uint64_t(1) << expr) & buildMask(Exprs...); 149 } 150 151 static RelType getMipsPairType(RelType type, bool isLocal) { 152 switch (type) { 153 case R_MIPS_HI16: 154 return R_MIPS_LO16; 155 case R_MIPS_GOT16: 156 // In case of global symbol, the R_MIPS_GOT16 relocation does not 157 // have a pair. Each global symbol has a unique entry in the GOT 158 // and a corresponding instruction with help of the R_MIPS_GOT16 159 // relocation loads an address of the symbol. In case of local 160 // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold 161 // the high 16 bits of the symbol's value. A paired R_MIPS_LO16 162 // relocations handle low 16 bits of the address. That allows 163 // to allocate only one GOT entry for every 64 KBytes of local data. 164 return isLocal ? R_MIPS_LO16 : R_MIPS_NONE; 165 case R_MICROMIPS_GOT16: 166 return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE; 167 case R_MIPS_PCHI16: 168 return R_MIPS_PCLO16; 169 case R_MICROMIPS_HI16: 170 return R_MICROMIPS_LO16; 171 default: 172 return R_MIPS_NONE; 173 } 174 } 175 176 // True if non-preemptable symbol always has the same value regardless of where 177 // the DSO is loaded. 178 static bool isAbsolute(const Symbol &sym) { 179 if (sym.isUndefWeak()) 180 return true; 181 if (const auto *dr = dyn_cast<Defined>(&sym)) 182 return dr->section == nullptr; // Absolute symbol. 183 return false; 184 } 185 186 static bool isAbsoluteValue(const Symbol &sym) { 187 return isAbsolute(sym) || sym.isTls(); 188 } 189 190 // Returns true if Expr refers a PLT entry. 191 static bool needsPlt(RelExpr expr) { 192 return oneof<R_PLT, R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT>( 193 expr); 194 } 195 196 // Returns true if Expr refers a GOT entry. Note that this function 197 // returns false for TLS variables even though they need GOT, because 198 // TLS variables uses GOT differently than the regular variables. 199 static bool needsGot(RelExpr expr) { 200 return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF, 201 R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT, 202 R_AARCH64_GOT_PAGE>(expr); 203 } 204 205 // True if this expression is of the form Sym - X, where X is a position in the 206 // file (PC, or GOT for example). 207 static bool isRelExpr(RelExpr expr) { 208 return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL, 209 R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC, 210 R_RISCV_PC_INDIRECT, R_PPC64_RELAX_GOT_PC>(expr); 211 } 212 213 214 static RelExpr toPlt(RelExpr expr) { 215 switch (expr) { 216 case R_PPC64_CALL: 217 return R_PPC64_CALL_PLT; 218 case R_PC: 219 return R_PLT_PC; 220 case R_ABS: 221 return R_PLT; 222 default: 223 return expr; 224 } 225 } 226 227 static RelExpr fromPlt(RelExpr expr) { 228 // We decided not to use a plt. Optimize a reference to the plt to a 229 // reference to the symbol itself. 230 switch (expr) { 231 case R_PLT_PC: 232 case R_PPC32_PLTREL: 233 return R_PC; 234 case R_PPC64_CALL_PLT: 235 return R_PPC64_CALL; 236 case R_PLT: 237 return R_ABS; 238 case R_PLT_GOTPLT: 239 return R_GOTPLTREL; 240 default: 241 return expr; 242 } 243 } 244 245 // Returns true if a given shared symbol is in a read-only segment in a DSO. 246 template <class ELFT> static bool isReadOnly(SharedSymbol &ss) { 247 using Elf_Phdr = typename ELFT::Phdr; 248 249 // Determine if the symbol is read-only by scanning the DSO's program headers. 250 const SharedFile &file = ss.getFile(); 251 for (const Elf_Phdr &phdr : 252 check(file.template getObj<ELFT>().program_headers())) 253 if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) && 254 !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr && 255 ss.value < phdr.p_vaddr + phdr.p_memsz) 256 return true; 257 return false; 258 } 259 260 // Returns symbols at the same offset as a given symbol, including SS itself. 261 // 262 // If two or more symbols are at the same offset, and at least one of 263 // them are copied by a copy relocation, all of them need to be copied. 264 // Otherwise, they would refer to different places at runtime. 265 template <class ELFT> 266 static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) { 267 using Elf_Sym = typename ELFT::Sym; 268 269 SharedFile &file = ss.getFile(); 270 271 SmallSet<SharedSymbol *, 4> ret; 272 for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) { 273 if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS || 274 s.getType() == STT_TLS || s.st_value != ss.value) 275 continue; 276 StringRef name = check(s.getName(file.getStringTable())); 277 Symbol *sym = symtab->find(name); 278 if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym)) 279 ret.insert(alias); 280 } 281 282 // The loop does not check SHT_GNU_verneed, so ret does not contain 283 // non-default version symbols. If ss has a non-default version, ret won't 284 // contain ss. Just add ss unconditionally. If a non-default version alias is 285 // separately copy relocated, it and ss will have different addresses. 286 // Fortunately this case is impractical and fails with GNU ld as well. 287 ret.insert(&ss); 288 return ret; 289 } 290 291 // When a symbol is copy relocated or we create a canonical plt entry, it is 292 // effectively a defined symbol. In the case of copy relocation the symbol is 293 // in .bss and in the case of a canonical plt entry it is in .plt. This function 294 // replaces the existing symbol with a Defined pointing to the appropriate 295 // location. 296 static void replaceWithDefined(Symbol &sym, SectionBase &sec, uint64_t value, 297 uint64_t size) { 298 Symbol old = sym; 299 300 sym.replace(Defined{sym.file, StringRef(), sym.binding, sym.stOther, 301 sym.type, value, size, &sec}); 302 303 sym.auxIdx = old.auxIdx; 304 sym.verdefIndex = old.verdefIndex; 305 sym.exportDynamic = true; 306 sym.isUsedInRegularObj = true; 307 // A copy relocated alias may need a GOT entry. 308 sym.needsGot = old.needsGot; 309 } 310 311 // Reserve space in .bss or .bss.rel.ro for copy relocation. 312 // 313 // The copy relocation is pretty much a hack. If you use a copy relocation 314 // in your program, not only the symbol name but the symbol's size, RW/RO 315 // bit and alignment become part of the ABI. In addition to that, if the 316 // symbol has aliases, the aliases become part of the ABI. That's subtle, 317 // but if you violate that implicit ABI, that can cause very counter- 318 // intuitive consequences. 319 // 320 // So, what is the copy relocation? It's for linking non-position 321 // independent code to DSOs. In an ideal world, all references to data 322 // exported by DSOs should go indirectly through GOT. But if object files 323 // are compiled as non-PIC, all data references are direct. There is no 324 // way for the linker to transform the code to use GOT, as machine 325 // instructions are already set in stone in object files. This is where 326 // the copy relocation takes a role. 327 // 328 // A copy relocation instructs the dynamic linker to copy data from a DSO 329 // to a specified address (which is usually in .bss) at load-time. If the 330 // static linker (that's us) finds a direct data reference to a DSO 331 // symbol, it creates a copy relocation, so that the symbol can be 332 // resolved as if it were in .bss rather than in a DSO. 333 // 334 // As you can see in this function, we create a copy relocation for the 335 // dynamic linker, and the relocation contains not only symbol name but 336 // various other information about the symbol. So, such attributes become a 337 // part of the ABI. 338 // 339 // Note for application developers: I can give you a piece of advice if 340 // you are writing a shared library. You probably should export only 341 // functions from your library. You shouldn't export variables. 342 // 343 // As an example what can happen when you export variables without knowing 344 // the semantics of copy relocations, assume that you have an exported 345 // variable of type T. It is an ABI-breaking change to add new members at 346 // end of T even though doing that doesn't change the layout of the 347 // existing members. That's because the space for the new members are not 348 // reserved in .bss unless you recompile the main program. That means they 349 // are likely to overlap with other data that happens to be laid out next 350 // to the variable in .bss. This kind of issue is sometimes very hard to 351 // debug. What's a solution? Instead of exporting a variable V from a DSO, 352 // define an accessor getV(). 353 template <class ELFT> static void addCopyRelSymbolImpl(SharedSymbol &ss) { 354 // Copy relocation against zero-sized symbol doesn't make sense. 355 uint64_t symSize = ss.getSize(); 356 if (symSize == 0 || ss.alignment == 0) 357 fatal("cannot create a copy relocation for symbol " + toString(ss)); 358 359 // See if this symbol is in a read-only segment. If so, preserve the symbol's 360 // memory protection by reserving space in the .bss.rel.ro section. 361 bool isRO = isReadOnly<ELFT>(ss); 362 BssSection *sec = 363 make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment); 364 OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent(); 365 366 // At this point, sectionBases has been migrated to sections. Append sec to 367 // sections. 368 if (osec->commands.empty() || 369 !isa<InputSectionDescription>(osec->commands.back())) 370 osec->commands.push_back(make<InputSectionDescription>("")); 371 auto *isd = cast<InputSectionDescription>(osec->commands.back()); 372 isd->sections.push_back(sec); 373 osec->commitSection(sec); 374 375 // Look through the DSO's dynamic symbol table for aliases and create a 376 // dynamic symbol for each one. This causes the copy relocation to correctly 377 // interpose any aliases. 378 for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss)) 379 replaceWithDefined(*sym, *sec, 0, sym->size); 380 381 mainPart->relaDyn->addSymbolReloc(target->copyRel, *sec, 0, ss); 382 } 383 384 static void addCopyRelSymbol(SharedSymbol &ss) { 385 const SharedFile &file = ss.getFile(); 386 switch (file.ekind) { 387 case ELF32LEKind: 388 addCopyRelSymbolImpl<ELF32LE>(ss); 389 break; 390 case ELF32BEKind: 391 addCopyRelSymbolImpl<ELF32BE>(ss); 392 break; 393 case ELF64LEKind: 394 addCopyRelSymbolImpl<ELF64LE>(ss); 395 break; 396 case ELF64BEKind: 397 addCopyRelSymbolImpl<ELF64BE>(ss); 398 break; 399 default: 400 llvm_unreachable(""); 401 } 402 } 403 404 // .eh_frame sections are mergeable input sections, so their input 405 // offsets are not linearly mapped to output section. For each input 406 // offset, we need to find a section piece containing the offset and 407 // add the piece's base address to the input offset to compute the 408 // output offset. That isn't cheap. 409 // 410 // This class is to speed up the offset computation. When we process 411 // relocations, we access offsets in the monotonically increasing 412 // order. So we can optimize for that access pattern. 413 // 414 // For sections other than .eh_frame, this class doesn't do anything. 415 namespace { 416 class OffsetGetter { 417 public: 418 explicit OffsetGetter(InputSectionBase &sec) { 419 if (auto *eh = dyn_cast<EhInputSection>(&sec)) 420 pieces = eh->pieces; 421 } 422 423 // Translates offsets in input sections to offsets in output sections. 424 // Given offset must increase monotonically. We assume that Piece is 425 // sorted by inputOff. 426 uint64_t get(uint64_t off) { 427 if (pieces.empty()) 428 return off; 429 430 while (i != pieces.size() && pieces[i].inputOff + pieces[i].size <= off) 431 ++i; 432 if (i == pieces.size()) 433 fatal(".eh_frame: relocation is not in any piece"); 434 435 // Pieces must be contiguous, so there must be no holes in between. 436 assert(pieces[i].inputOff <= off && "Relocation not in any piece"); 437 438 // Offset -1 means that the piece is dead (i.e. garbage collected). 439 if (pieces[i].outputOff == -1) 440 return -1; 441 return pieces[i].outputOff + off - pieces[i].inputOff; 442 } 443 444 private: 445 ArrayRef<EhSectionPiece> pieces; 446 size_t i = 0; 447 }; 448 449 // This class encapsulates states needed to scan relocations for one 450 // InputSectionBase. 451 class RelocationScanner { 452 public: 453 explicit RelocationScanner(InputSectionBase &sec) 454 : sec(sec), getter(sec), config(elf::config.get()), target(*elf::target) { 455 } 456 template <class ELFT, class RelTy> void scan(ArrayRef<RelTy> rels); 457 458 private: 459 InputSectionBase &sec; 460 OffsetGetter getter; 461 const Configuration *const config; 462 const TargetInfo ⌖ 463 464 // End of relocations, used by Mips/PPC64. 465 const void *end = nullptr; 466 467 template <class RelTy> RelType getMipsN32RelType(RelTy *&rel) const; 468 template <class ELFT, class RelTy> 469 int64_t computeMipsAddend(const RelTy &rel, RelExpr expr, bool isLocal) const; 470 template <class ELFT, class RelTy> 471 int64_t computeAddend(const RelTy &rel, RelExpr expr, bool isLocal) const; 472 bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym, 473 uint64_t relOff) const; 474 void processAux(RelExpr expr, RelType type, uint64_t offset, Symbol &sym, 475 int64_t addend) const; 476 template <class ELFT, class RelTy> void scanOne(RelTy *&i); 477 }; 478 } // namespace 479 480 // MIPS has an odd notion of "paired" relocations to calculate addends. 481 // For example, if a relocation is of R_MIPS_HI16, there must be a 482 // R_MIPS_LO16 relocation after that, and an addend is calculated using 483 // the two relocations. 484 template <class ELFT, class RelTy> 485 int64_t RelocationScanner::computeMipsAddend(const RelTy &rel, RelExpr expr, 486 bool isLocal) const { 487 if (expr == R_MIPS_GOTREL && isLocal) 488 return sec.getFile<ELFT>()->mipsGp0; 489 490 // The ABI says that the paired relocation is used only for REL. 491 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 492 if (RelTy::IsRela) 493 return 0; 494 495 RelType type = rel.getType(config->isMips64EL); 496 uint32_t pairTy = getMipsPairType(type, isLocal); 497 if (pairTy == R_MIPS_NONE) 498 return 0; 499 500 const uint8_t *buf = sec.data().data(); 501 uint32_t symIndex = rel.getSymbol(config->isMips64EL); 502 503 // To make things worse, paired relocations might not be contiguous in 504 // the relocation table, so we need to do linear search. *sigh* 505 for (const RelTy *ri = &rel; ri != static_cast<const RelTy *>(end); ++ri) 506 if (ri->getType(config->isMips64EL) == pairTy && 507 ri->getSymbol(config->isMips64EL) == symIndex) 508 return target.getImplicitAddend(buf + ri->r_offset, pairTy); 509 510 warn("can't find matching " + toString(pairTy) + " relocation for " + 511 toString(type)); 512 return 0; 513 } 514 515 // Returns an addend of a given relocation. If it is RELA, an addend 516 // is in a relocation itself. If it is REL, we need to read it from an 517 // input section. 518 template <class ELFT, class RelTy> 519 int64_t RelocationScanner::computeAddend(const RelTy &rel, RelExpr expr, 520 bool isLocal) const { 521 int64_t addend; 522 RelType type = rel.getType(config->isMips64EL); 523 524 if (RelTy::IsRela) { 525 addend = getAddend<ELFT>(rel); 526 } else { 527 const uint8_t *buf = sec.data().data(); 528 addend = target.getImplicitAddend(buf + rel.r_offset, type); 529 } 530 531 if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC) 532 addend += getPPC64TocBase(); 533 if (config->emachine == EM_MIPS) 534 addend += computeMipsAddend<ELFT>(rel, expr, isLocal); 535 536 return addend; 537 } 538 539 // Custom error message if Sym is defined in a discarded section. 540 template <class ELFT> 541 static std::string maybeReportDiscarded(Undefined &sym) { 542 auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file); 543 if (!file || !sym.discardedSecIdx || 544 file->getSections()[sym.discardedSecIdx] != &InputSection::discarded) 545 return ""; 546 ArrayRef<typename ELFT::Shdr> objSections = 547 file->template getELFShdrs<ELFT>(); 548 549 std::string msg; 550 if (sym.type == ELF::STT_SECTION) { 551 msg = "relocation refers to a discarded section: "; 552 msg += CHECK( 553 file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file); 554 } else { 555 msg = "relocation refers to a symbol in a discarded section: " + 556 toString(sym); 557 } 558 msg += "\n>>> defined in " + toString(file); 559 560 Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1]; 561 if (elfSec.sh_type != SHT_GROUP) 562 return msg; 563 564 // If the discarded section is a COMDAT. 565 StringRef signature = file->getShtGroupSignature(objSections, elfSec); 566 if (const InputFile *prevailing = 567 symtab->comdatGroups.lookup(CachedHashStringRef(signature))) 568 msg += "\n>>> section group signature: " + signature.str() + 569 "\n>>> prevailing definition is in " + toString(prevailing); 570 return msg; 571 } 572 573 // Undefined diagnostics are collected in a vector and emitted once all of 574 // them are known, so that some postprocessing on the list of undefined symbols 575 // can happen before lld emits diagnostics. 576 struct UndefinedDiag { 577 Undefined *sym; 578 struct Loc { 579 InputSectionBase *sec; 580 uint64_t offset; 581 }; 582 std::vector<Loc> locs; 583 bool isWarning; 584 }; 585 586 static std::vector<UndefinedDiag> undefs; 587 588 // Check whether the definition name def is a mangled function name that matches 589 // the reference name ref. 590 static bool canSuggestExternCForCXX(StringRef ref, StringRef def) { 591 llvm::ItaniumPartialDemangler d; 592 std::string name = def.str(); 593 if (d.partialDemangle(name.c_str())) 594 return false; 595 char *buf = d.getFunctionName(nullptr, nullptr); 596 if (!buf) 597 return false; 598 bool ret = ref == buf; 599 free(buf); 600 return ret; 601 } 602 603 // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns 604 // the suggested symbol, which is either in the symbol table, or in the same 605 // file of sym. 606 static const Symbol *getAlternativeSpelling(const Undefined &sym, 607 std::string &pre_hint, 608 std::string &post_hint) { 609 DenseMap<StringRef, const Symbol *> map; 610 if (sym.file && sym.file->kind() == InputFile::ObjKind) { 611 auto *file = cast<ELFFileBase>(sym.file); 612 // If sym is a symbol defined in a discarded section, maybeReportDiscarded() 613 // will give an error. Don't suggest an alternative spelling. 614 if (file && sym.discardedSecIdx != 0 && 615 file->getSections()[sym.discardedSecIdx] == &InputSection::discarded) 616 return nullptr; 617 618 // Build a map of local defined symbols. 619 for (const Symbol *s : sym.file->getSymbols()) 620 if (s->isLocal() && s->isDefined() && !s->getName().empty()) 621 map.try_emplace(s->getName(), s); 622 } 623 624 auto suggest = [&](StringRef newName) -> const Symbol * { 625 // If defined locally. 626 if (const Symbol *s = map.lookup(newName)) 627 return s; 628 629 // If in the symbol table and not undefined. 630 if (const Symbol *s = symtab->find(newName)) 631 if (!s->isUndefined()) 632 return s; 633 634 return nullptr; 635 }; 636 637 // This loop enumerates all strings of Levenshtein distance 1 as typo 638 // correction candidates and suggests the one that exists as a non-undefined 639 // symbol. 640 StringRef name = sym.getName(); 641 for (size_t i = 0, e = name.size(); i != e + 1; ++i) { 642 // Insert a character before name[i]. 643 std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str(); 644 for (char c = '0'; c <= 'z'; ++c) { 645 newName[i] = c; 646 if (const Symbol *s = suggest(newName)) 647 return s; 648 } 649 if (i == e) 650 break; 651 652 // Substitute name[i]. 653 newName = std::string(name); 654 for (char c = '0'; c <= 'z'; ++c) { 655 newName[i] = c; 656 if (const Symbol *s = suggest(newName)) 657 return s; 658 } 659 660 // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is 661 // common. 662 if (i + 1 < e) { 663 newName[i] = name[i + 1]; 664 newName[i + 1] = name[i]; 665 if (const Symbol *s = suggest(newName)) 666 return s; 667 } 668 669 // Delete name[i]. 670 newName = (name.substr(0, i) + name.substr(i + 1)).str(); 671 if (const Symbol *s = suggest(newName)) 672 return s; 673 } 674 675 // Case mismatch, e.g. Foo vs FOO. 676 for (auto &it : map) 677 if (name.equals_insensitive(it.first)) 678 return it.second; 679 for (Symbol *sym : symtab->symbols()) 680 if (!sym->isUndefined() && name.equals_insensitive(sym->getName())) 681 return sym; 682 683 // The reference may be a mangled name while the definition is not. Suggest a 684 // missing extern "C". 685 if (name.startswith("_Z")) { 686 std::string buf = name.str(); 687 llvm::ItaniumPartialDemangler d; 688 if (!d.partialDemangle(buf.c_str())) 689 if (char *buf = d.getFunctionName(nullptr, nullptr)) { 690 const Symbol *s = suggest(buf); 691 free(buf); 692 if (s) { 693 pre_hint = ": extern \"C\" "; 694 return s; 695 } 696 } 697 } else { 698 const Symbol *s = nullptr; 699 for (auto &it : map) 700 if (canSuggestExternCForCXX(name, it.first)) { 701 s = it.second; 702 break; 703 } 704 if (!s) 705 for (Symbol *sym : symtab->symbols()) 706 if (canSuggestExternCForCXX(name, sym->getName())) { 707 s = sym; 708 break; 709 } 710 if (s) { 711 pre_hint = " to declare "; 712 post_hint = " as extern \"C\"?"; 713 return s; 714 } 715 } 716 717 return nullptr; 718 } 719 720 static void reportUndefinedSymbol(const UndefinedDiag &undef, 721 bool correctSpelling) { 722 Undefined &sym = *undef.sym; 723 724 auto visibility = [&]() -> std::string { 725 switch (sym.visibility) { 726 case STV_INTERNAL: 727 return "internal "; 728 case STV_HIDDEN: 729 return "hidden "; 730 case STV_PROTECTED: 731 return "protected "; 732 default: 733 return ""; 734 } 735 }; 736 737 std::string msg; 738 switch (config->ekind) { 739 case ELF32LEKind: 740 msg = maybeReportDiscarded<ELF32LE>(sym); 741 break; 742 case ELF32BEKind: 743 msg = maybeReportDiscarded<ELF32BE>(sym); 744 break; 745 case ELF64LEKind: 746 msg = maybeReportDiscarded<ELF64LE>(sym); 747 break; 748 case ELF64BEKind: 749 msg = maybeReportDiscarded<ELF64BE>(sym); 750 break; 751 default: 752 llvm_unreachable(""); 753 } 754 if (msg.empty()) 755 msg = "undefined " + visibility() + "symbol: " + toString(sym); 756 757 const size_t maxUndefReferences = 3; 758 size_t i = 0; 759 for (UndefinedDiag::Loc l : undef.locs) { 760 if (i >= maxUndefReferences) 761 break; 762 InputSectionBase &sec = *l.sec; 763 uint64_t offset = l.offset; 764 765 msg += "\n>>> referenced by "; 766 std::string src = sec.getSrcMsg(sym, offset); 767 if (!src.empty()) 768 msg += src + "\n>>> "; 769 msg += sec.getObjMsg(offset); 770 i++; 771 } 772 773 if (i < undef.locs.size()) 774 msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times") 775 .str(); 776 777 if (correctSpelling) { 778 std::string pre_hint = ": ", post_hint; 779 if (const Symbol *corrected = 780 getAlternativeSpelling(sym, pre_hint, post_hint)) { 781 msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint; 782 if (corrected->file) 783 msg += "\n>>> defined in: " + toString(corrected->file); 784 } 785 } 786 787 if (sym.getName().startswith("_ZTV")) 788 msg += 789 "\n>>> the vtable symbol may be undefined because the class is missing " 790 "its key function (see https://lld.llvm.org/missingkeyfunction)"; 791 if (config->gcSections && config->zStartStopGC && 792 sym.getName().startswith("__start_")) { 793 msg += "\n>>> the encapsulation symbol needs to be retained under " 794 "--gc-sections properly; consider -z nostart-stop-gc " 795 "(see https://lld.llvm.org/ELF/start-stop-gc)"; 796 } 797 798 if (undef.isWarning) 799 warn(msg); 800 else 801 error(msg, ErrorTag::SymbolNotFound, {sym.getName()}); 802 } 803 804 void elf::reportUndefinedSymbols() { 805 // Find the first "undefined symbol" diagnostic for each diagnostic, and 806 // collect all "referenced from" lines at the first diagnostic. 807 DenseMap<Symbol *, UndefinedDiag *> firstRef; 808 for (UndefinedDiag &undef : undefs) { 809 assert(undef.locs.size() == 1); 810 if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) { 811 canon->locs.push_back(undef.locs[0]); 812 undef.locs.clear(); 813 } else 814 firstRef[undef.sym] = &undef; 815 } 816 817 // Enable spell corrector for the first 2 diagnostics. 818 for (auto it : enumerate(undefs)) 819 if (!it.value().locs.empty()) 820 reportUndefinedSymbol(it.value(), it.index() < 2); 821 undefs.clear(); 822 } 823 824 // Report an undefined symbol if necessary. 825 // Returns true if the undefined symbol will produce an error message. 826 static bool maybeReportUndefined(Undefined &sym, InputSectionBase &sec, 827 uint64_t offset) { 828 // If versioned, issue an error (even if the symbol is weak) because we don't 829 // know the defining filename which is required to construct a Verneed entry. 830 if (sym.hasVersionSuffix) { 831 undefs.push_back({&sym, {{&sec, offset}}, false}); 832 return true; 833 } 834 if (sym.isWeak()) 835 return false; 836 837 bool canBeExternal = !sym.isLocal() && sym.visibility == STV_DEFAULT; 838 if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal) 839 return false; 840 841 // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc 842 // which references a switch table in a discarded .rodata/.text section. The 843 // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF 844 // spec says references from outside the group to a STB_LOCAL symbol are not 845 // allowed. Work around the bug. 846 // 847 // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible 848 // because .LC0-.LTOC is not representable if the two labels are in different 849 // .got2 850 if (sym.discardedSecIdx != 0 && (sec.name == ".got2" || sec.name == ".toc")) 851 return false; 852 853 bool isWarning = 854 (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) || 855 config->noinhibitExec; 856 undefs.push_back({&sym, {{&sec, offset}}, isWarning}); 857 return !isWarning; 858 } 859 860 // MIPS N32 ABI treats series of successive relocations with the same offset 861 // as a single relocation. The similar approach used by N64 ABI, but this ABI 862 // packs all relocations into the single relocation record. Here we emulate 863 // this for the N32 ABI. Iterate over relocation with the same offset and put 864 // theirs types into the single bit-set. 865 template <class RelTy> 866 RelType RelocationScanner::getMipsN32RelType(RelTy *&rel) const { 867 RelType type = 0; 868 uint64_t offset = rel->r_offset; 869 870 int n = 0; 871 while (rel != static_cast<const RelTy *>(end) && rel->r_offset == offset) 872 type |= (rel++)->getType(config->isMips64EL) << (8 * n++); 873 return type; 874 } 875 876 static void addRelativeReloc(InputSectionBase &isec, uint64_t offsetInSec, 877 Symbol &sym, int64_t addend, RelExpr expr, 878 RelType type) { 879 Partition &part = isec.getPartition(); 880 881 // Add a relative relocation. If relrDyn section is enabled, and the 882 // relocation offset is guaranteed to be even, add the relocation to 883 // the relrDyn section, otherwise add it to the relaDyn section. 884 // relrDyn sections don't support odd offsets. Also, relrDyn sections 885 // don't store the addend values, so we must write it to the relocated 886 // address. 887 if (part.relrDyn && isec.alignment >= 2 && offsetInSec % 2 == 0) { 888 isec.relocations.push_back({expr, type, offsetInSec, addend, &sym}); 889 part.relrDyn->relocs.push_back({&isec, offsetInSec}); 890 return; 891 } 892 part.relaDyn->addRelativeReloc(target->relativeRel, isec, offsetInSec, sym, 893 addend, type, expr); 894 } 895 896 template <class PltSection, class GotPltSection> 897 static void addPltEntry(PltSection &plt, GotPltSection &gotPlt, 898 RelocationBaseSection &rel, RelType type, Symbol &sym) { 899 plt.addEntry(sym); 900 gotPlt.addEntry(sym); 901 rel.addReloc({type, &gotPlt, sym.getGotPltOffset(), 902 sym.isPreemptible ? DynamicReloc::AgainstSymbol 903 : DynamicReloc::AddendOnlyWithTargetVA, 904 sym, 0, R_ABS}); 905 } 906 907 static void addGotEntry(Symbol &sym) { 908 in.got->addEntry(sym); 909 uint64_t off = sym.getGotOffset(); 910 911 // If preemptible, emit a GLOB_DAT relocation. 912 if (sym.isPreemptible) { 913 mainPart->relaDyn->addReloc({target->gotRel, in.got.get(), off, 914 DynamicReloc::AgainstSymbol, sym, 0, R_ABS}); 915 return; 916 } 917 918 // Otherwise, the value is either a link-time constant or the load base 919 // plus a constant. 920 if (!config->isPic || isAbsolute(sym)) 921 in.got->relocations.push_back({R_ABS, target->symbolicRel, off, 0, &sym}); 922 else 923 addRelativeReloc(*in.got, off, sym, 0, R_ABS, target->symbolicRel); 924 } 925 926 static void addTpOffsetGotEntry(Symbol &sym) { 927 in.got->addEntry(sym); 928 uint64_t off = sym.getGotOffset(); 929 if (!sym.isPreemptible && !config->isPic) { 930 in.got->relocations.push_back({R_TPREL, target->symbolicRel, off, 0, &sym}); 931 return; 932 } 933 mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible( 934 target->tlsGotRel, *in.got, off, sym, target->symbolicRel); 935 } 936 937 // Return true if we can define a symbol in the executable that 938 // contains the value/function of a symbol defined in a shared 939 // library. 940 static bool canDefineSymbolInExecutable(Symbol &sym) { 941 // If the symbol has default visibility the symbol defined in the 942 // executable will preempt it. 943 // Note that we want the visibility of the shared symbol itself, not 944 // the visibility of the symbol in the output file we are producing. That is 945 // why we use Sym.stOther. 946 if ((sym.stOther & 0x3) == STV_DEFAULT) 947 return true; 948 949 // If we are allowed to break address equality of functions, defining 950 // a plt entry will allow the program to call the function in the 951 // .so, but the .so and the executable will no agree on the address 952 // of the function. Similar logic for objects. 953 return ((sym.isFunc() && config->ignoreFunctionAddressEquality) || 954 (sym.isObject() && config->ignoreDataAddressEquality)); 955 } 956 957 // Returns true if a given relocation can be computed at link-time. 958 // This only handles relocation types expected in processRelocAux. 959 // 960 // For instance, we know the offset from a relocation to its target at 961 // link-time if the relocation is PC-relative and refers a 962 // non-interposable function in the same executable. This function 963 // will return true for such relocation. 964 // 965 // If this function returns false, that means we need to emit a 966 // dynamic relocation so that the relocation will be fixed at load-time. 967 bool RelocationScanner::isStaticLinkTimeConstant(RelExpr e, RelType type, 968 const Symbol &sym, 969 uint64_t relOff) const { 970 // These expressions always compute a constant 971 if (oneof<R_GOTPLT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, 972 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, 973 R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC, 974 R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT, 975 R_PPC64_RELAX_TOC, R_RISCV_ADD, R_AARCH64_GOT_PAGE>(e)) 976 return true; 977 978 // These never do, except if the entire file is position dependent or if 979 // only the low bits are used. 980 if (e == R_GOT || e == R_PLT) 981 return target.usesOnlyLowPageBits(type) || !config->isPic; 982 983 if (sym.isPreemptible) 984 return false; 985 if (!config->isPic) 986 return true; 987 988 // The size of a non preemptible symbol is a constant. 989 if (e == R_SIZE) 990 return true; 991 992 // For the target and the relocation, we want to know if they are 993 // absolute or relative. 994 bool absVal = isAbsoluteValue(sym); 995 bool relE = isRelExpr(e); 996 if (absVal && !relE) 997 return true; 998 if (!absVal && relE) 999 return true; 1000 if (!absVal && !relE) 1001 return target.usesOnlyLowPageBits(type); 1002 1003 assert(absVal && relE); 1004 1005 // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol 1006 // in PIC mode. This is a little strange, but it allows us to link function 1007 // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers). 1008 // Normally such a call will be guarded with a comparison, which will load a 1009 // zero from the GOT. 1010 if (sym.isUndefWeak()) 1011 return true; 1012 1013 // We set the final symbols values for linker script defined symbols later. 1014 // They always can be computed as a link time constant. 1015 if (sym.scriptDefined) 1016 return true; 1017 1018 error("relocation " + toString(type) + " cannot refer to absolute symbol: " + 1019 toString(sym) + getLocation(sec, sym, relOff)); 1020 return true; 1021 } 1022 1023 // The reason we have to do this early scan is as follows 1024 // * To mmap the output file, we need to know the size 1025 // * For that, we need to know how many dynamic relocs we will have. 1026 // It might be possible to avoid this by outputting the file with write: 1027 // * Write the allocated output sections, computing addresses. 1028 // * Apply relocations, recording which ones require a dynamic reloc. 1029 // * Write the dynamic relocations. 1030 // * Write the rest of the file. 1031 // This would have some drawbacks. For example, we would only know if .rela.dyn 1032 // is needed after applying relocations. If it is, it will go after rw and rx 1033 // sections. Given that it is ro, we will need an extra PT_LOAD. This 1034 // complicates things for the dynamic linker and means we would have to reserve 1035 // space for the extra PT_LOAD even if we end up not using it. 1036 void RelocationScanner::processAux(RelExpr expr, RelType type, uint64_t offset, 1037 Symbol &sym, int64_t addend) const { 1038 // If the relocation is known to be a link-time constant, we know no dynamic 1039 // relocation will be created, pass the control to relocateAlloc() or 1040 // relocateNonAlloc() to resolve it. 1041 // 1042 // The behavior of an undefined weak reference is implementation defined. For 1043 // non-link-time constants, we resolve relocations statically (let 1044 // relocate{,Non}Alloc() resolve them) for -no-pie and try producing dynamic 1045 // relocations for -pie and -shared. 1046 // 1047 // The general expectation of -no-pie static linking is that there is no 1048 // dynamic relocation (except IRELATIVE). Emitting dynamic relocations for 1049 // -shared matches the spirit of its -z undefs default. -pie has freedom on 1050 // choices, and we choose dynamic relocations to be consistent with the 1051 // handling of GOT-generating relocations. 1052 if (isStaticLinkTimeConstant(expr, type, sym, offset) || 1053 (!config->isPic && sym.isUndefWeak())) { 1054 sec.relocations.push_back({expr, type, offset, addend, &sym}); 1055 return; 1056 } 1057 1058 bool canWrite = (sec.flags & SHF_WRITE) || !config->zText; 1059 if (canWrite) { 1060 RelType rel = target.getDynRel(type); 1061 if (expr == R_GOT || (rel == target.symbolicRel && !sym.isPreemptible)) { 1062 addRelativeReloc(sec, offset, sym, addend, expr, type); 1063 return; 1064 } else if (rel != 0) { 1065 if (config->emachine == EM_MIPS && rel == target.symbolicRel) 1066 rel = target.relativeRel; 1067 sec.getPartition().relaDyn->addSymbolReloc(rel, sec, offset, sym, addend, 1068 type); 1069 1070 // MIPS ABI turns using of GOT and dynamic relocations inside out. 1071 // While regular ABI uses dynamic relocations to fill up GOT entries 1072 // MIPS ABI requires dynamic linker to fills up GOT entries using 1073 // specially sorted dynamic symbol table. This affects even dynamic 1074 // relocations against symbols which do not require GOT entries 1075 // creation explicitly, i.e. do not have any GOT-relocations. So if 1076 // a preemptible symbol has a dynamic relocation we anyway have 1077 // to create a GOT entry for it. 1078 // If a non-preemptible symbol has a dynamic relocation against it, 1079 // dynamic linker takes it st_value, adds offset and writes down 1080 // result of the dynamic relocation. In case of preemptible symbol 1081 // dynamic linker performs symbol resolution, writes the symbol value 1082 // to the GOT entry and reads the GOT entry when it needs to perform 1083 // a dynamic relocation. 1084 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 1085 if (config->emachine == EM_MIPS) 1086 in.mipsGot->addEntry(*sec.file, sym, addend, expr); 1087 return; 1088 } 1089 } 1090 1091 // When producing an executable, we can perform copy relocations (for 1092 // STT_OBJECT) and canonical PLT (for STT_FUNC). 1093 if (!config->shared) { 1094 if (!canDefineSymbolInExecutable(sym)) { 1095 errorOrWarn("cannot preempt symbol: " + toString(sym) + 1096 getLocation(sec, sym, offset)); 1097 return; 1098 } 1099 1100 if (sym.isObject()) { 1101 // Produce a copy relocation. 1102 if (auto *ss = dyn_cast<SharedSymbol>(&sym)) { 1103 if (!config->zCopyreloc) 1104 error("unresolvable relocation " + toString(type) + 1105 " against symbol '" + toString(*ss) + 1106 "'; recompile with -fPIC or remove '-z nocopyreloc'" + 1107 getLocation(sec, sym, offset)); 1108 sym.needsCopy = true; 1109 } 1110 sec.relocations.push_back({expr, type, offset, addend, &sym}); 1111 return; 1112 } 1113 1114 // This handles a non PIC program call to function in a shared library. In 1115 // an ideal world, we could just report an error saying the relocation can 1116 // overflow at runtime. In the real world with glibc, crt1.o has a 1117 // R_X86_64_PC32 pointing to libc.so. 1118 // 1119 // The general idea on how to handle such cases is to create a PLT entry and 1120 // use that as the function value. 1121 // 1122 // For the static linking part, we just return a plt expr and everything 1123 // else will use the PLT entry as the address. 1124 // 1125 // The remaining problem is making sure pointer equality still works. We 1126 // need the help of the dynamic linker for that. We let it know that we have 1127 // a direct reference to a so symbol by creating an undefined symbol with a 1128 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to 1129 // the value of the symbol we created. This is true even for got entries, so 1130 // pointer equality is maintained. To avoid an infinite loop, the only entry 1131 // that points to the real function is a dedicated got entry used by the 1132 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT, 1133 // R_386_JMP_SLOT, etc). 1134 1135 // For position independent executable on i386, the plt entry requires ebx 1136 // to be set. This causes two problems: 1137 // * If some code has a direct reference to a function, it was probably 1138 // compiled without -fPIE/-fPIC and doesn't maintain ebx. 1139 // * If a library definition gets preempted to the executable, it will have 1140 // the wrong ebx value. 1141 if (sym.isFunc()) { 1142 if (config->pie && config->emachine == EM_386) 1143 errorOrWarn("symbol '" + toString(sym) + 1144 "' cannot be preempted; recompile with -fPIE" + 1145 getLocation(sec, sym, offset)); 1146 sym.needsCopy = true; 1147 sym.needsPlt = true; 1148 sec.relocations.push_back({expr, type, offset, addend, &sym}); 1149 return; 1150 } 1151 } 1152 1153 errorOrWarn("relocation " + toString(type) + " cannot be used against " + 1154 (sym.getName().empty() ? "local symbol" 1155 : "symbol '" + toString(sym) + "'") + 1156 "; recompile with -fPIC" + getLocation(sec, sym, offset)); 1157 } 1158 1159 // This function is similar to the `handleTlsRelocation`. MIPS does not 1160 // support any relaxations for TLS relocations so by factoring out MIPS 1161 // handling in to the separate function we can simplify the code and do not 1162 // pollute other `handleTlsRelocation` by MIPS `ifs` statements. 1163 // Mips has a custom MipsGotSection that handles the writing of GOT entries 1164 // without dynamic relocations. 1165 static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym, 1166 InputSectionBase &c, uint64_t offset, 1167 int64_t addend, RelExpr expr) { 1168 if (expr == R_MIPS_TLSLD) { 1169 in.mipsGot->addTlsIndex(*c.file); 1170 c.relocations.push_back({expr, type, offset, addend, &sym}); 1171 return 1; 1172 } 1173 if (expr == R_MIPS_TLSGD) { 1174 in.mipsGot->addDynTlsEntry(*c.file, sym); 1175 c.relocations.push_back({expr, type, offset, addend, &sym}); 1176 return 1; 1177 } 1178 return 0; 1179 } 1180 1181 // Notes about General Dynamic and Local Dynamic TLS models below. They may 1182 // require the generation of a pair of GOT entries that have associated dynamic 1183 // relocations. The pair of GOT entries created are of the form GOT[e0] Module 1184 // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of 1185 // symbol in TLS block. 1186 // 1187 // Returns the number of relocations processed. 1188 static unsigned handleTlsRelocation(RelType type, Symbol &sym, 1189 InputSectionBase &c, uint64_t offset, 1190 int64_t addend, RelExpr expr) { 1191 if (!sym.isTls()) 1192 return 0; 1193 1194 if (config->emachine == EM_MIPS) 1195 return handleMipsTlsRelocation(type, sym, c, offset, addend, expr); 1196 1197 if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC, 1198 R_TLSDESC_GOTPLT>(expr) && 1199 config->shared) { 1200 if (expr != R_TLSDESC_CALL) { 1201 sym.needsTlsDesc = true; 1202 c.relocations.push_back({expr, type, offset, addend, &sym}); 1203 } 1204 return 1; 1205 } 1206 1207 // ARM, Hexagon and RISC-V do not support GD/LD to IE/LE relaxation. For 1208 // PPC64, if the file has missing R_PPC64_TLSGD/R_PPC64_TLSLD, disable 1209 // relaxation as well. 1210 bool toExecRelax = !config->shared && config->emachine != EM_ARM && 1211 config->emachine != EM_HEXAGON && 1212 config->emachine != EM_RISCV && 1213 !c.file->ppc64DisableTLSRelax; 1214 1215 // If we are producing an executable and the symbol is non-preemptable, it 1216 // must be defined and the code sequence can be relaxed to use Local-Exec. 1217 // 1218 // ARM and RISC-V do not support any relaxations for TLS relocations, however, 1219 // we can omit the DTPMOD dynamic relocations and resolve them at link time 1220 // because them are always 1. This may be necessary for static linking as 1221 // DTPMOD may not be expected at load time. 1222 bool isLocalInExecutable = !sym.isPreemptible && !config->shared; 1223 1224 // Local Dynamic is for access to module local TLS variables, while still 1225 // being suitable for being dynamically loaded via dlopen. GOT[e0] is the 1226 // module index, with a special value of 0 for the current module. GOT[e1] is 1227 // unused. There only needs to be one module index entry. 1228 if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>( 1229 expr)) { 1230 // Local-Dynamic relocs can be relaxed to Local-Exec. 1231 if (toExecRelax) { 1232 c.relocations.push_back( 1233 {target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE), type, offset, 1234 addend, &sym}); 1235 return target->getTlsGdRelaxSkip(type); 1236 } 1237 if (expr == R_TLSLD_HINT) 1238 return 1; 1239 config->needsTlsLd = true; 1240 c.relocations.push_back({expr, type, offset, addend, &sym}); 1241 return 1; 1242 } 1243 1244 // Local-Dynamic relocs can be relaxed to Local-Exec. 1245 if (expr == R_DTPREL) { 1246 if (toExecRelax) 1247 expr = target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE); 1248 c.relocations.push_back({expr, type, offset, addend, &sym}); 1249 return 1; 1250 } 1251 1252 // Local-Dynamic sequence where offset of tls variable relative to dynamic 1253 // thread pointer is stored in the got. This cannot be relaxed to Local-Exec. 1254 if (expr == R_TLSLD_GOT_OFF) { 1255 sym.needsGotDtprel = true; 1256 c.relocations.push_back({expr, type, offset, addend, &sym}); 1257 return 1; 1258 } 1259 1260 if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC, 1261 R_TLSDESC_GOTPLT, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) { 1262 if (!toExecRelax) { 1263 sym.needsTlsGd = true; 1264 c.relocations.push_back({expr, type, offset, addend, &sym}); 1265 return 1; 1266 } 1267 1268 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec 1269 // depending on the symbol being locally defined or not. 1270 if (sym.isPreemptible) { 1271 sym.needsTlsGdToIe = true; 1272 c.relocations.push_back( 1273 {target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_IE), type, offset, 1274 addend, &sym}); 1275 } else { 1276 c.relocations.push_back( 1277 {target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_LE), type, offset, 1278 addend, &sym}); 1279 } 1280 return target->getTlsGdRelaxSkip(type); 1281 } 1282 1283 if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF, 1284 R_TLSIE_HINT>(expr)) { 1285 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally 1286 // defined. 1287 if (toExecRelax && isLocalInExecutable) { 1288 c.relocations.push_back( 1289 {R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym}); 1290 } else if (expr != R_TLSIE_HINT) { 1291 sym.needsTlsIe = true; 1292 // R_GOT needs a relative relocation for PIC on i386 and Hexagon. 1293 if (expr == R_GOT && config->isPic && !target->usesOnlyLowPageBits(type)) 1294 addRelativeReloc(c, offset, sym, addend, expr, type); 1295 else 1296 c.relocations.push_back({expr, type, offset, addend, &sym}); 1297 } 1298 return 1; 1299 } 1300 1301 return 0; 1302 } 1303 1304 template <class ELFT, class RelTy> void RelocationScanner::scanOne(RelTy *&i) { 1305 const RelTy &rel = *i; 1306 uint32_t symIndex = rel.getSymbol(config->isMips64EL); 1307 Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex); 1308 RelType type; 1309 1310 // Deal with MIPS oddity. 1311 if (config->mipsN32Abi) { 1312 type = getMipsN32RelType(i); 1313 } else { 1314 type = rel.getType(config->isMips64EL); 1315 ++i; 1316 } 1317 1318 // Get an offset in an output section this relocation is applied to. 1319 uint64_t offset = getter.get(rel.r_offset); 1320 if (offset == uint64_t(-1)) 1321 return; 1322 1323 // Error if the target symbol is undefined. Symbol index 0 may be used by 1324 // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them. 1325 if (sym.isUndefined() && symIndex != 0 && 1326 maybeReportUndefined(cast<Undefined>(sym), sec, offset)) 1327 return; 1328 1329 const uint8_t *relocatedAddr = sec.data().begin() + offset; 1330 RelExpr expr = target.getRelExpr(type, sym, relocatedAddr); 1331 1332 // Ignore R_*_NONE and other marker relocations. 1333 if (expr == R_NONE) 1334 return; 1335 1336 // Read an addend. 1337 int64_t addend = computeAddend<ELFT>(rel, expr, sym.isLocal()); 1338 1339 if (config->emachine == EM_PPC64) { 1340 // We can separate the small code model relocations into 2 categories: 1341 // 1) Those that access the compiler generated .toc sections. 1342 // 2) Those that access the linker allocated got entries. 1343 // lld allocates got entries to symbols on demand. Since we don't try to 1344 // sort the got entries in any way, we don't have to track which objects 1345 // have got-based small code model relocs. The .toc sections get placed 1346 // after the end of the linker allocated .got section and we do sort those 1347 // so sections addressed with small code model relocations come first. 1348 if (type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS) 1349 sec.file->ppc64SmallCodeModelTocRelocs = true; 1350 1351 // Record the TOC entry (.toc + addend) as not relaxable. See the comment in 1352 // InputSectionBase::relocateAlloc(). 1353 if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) && 1354 cast<Defined>(sym).section->name == ".toc") 1355 ppc64noTocRelax.insert({&sym, addend}); 1356 1357 if ((type == R_PPC64_TLSGD && expr == R_TLSDESC_CALL) || 1358 (type == R_PPC64_TLSLD && expr == R_TLSLD_HINT)) { 1359 if (i == end) { 1360 errorOrWarn("R_PPC64_TLSGD/R_PPC64_TLSLD may not be the last " 1361 "relocation" + 1362 getLocation(sec, sym, offset)); 1363 return; 1364 } 1365 1366 // Offset the 4-byte aligned R_PPC64_TLSGD by one byte in the NOTOC case, 1367 // so we can discern it later from the toc-case. 1368 if (i->getType(/*isMips64EL=*/false) == R_PPC64_REL24_NOTOC) 1369 ++offset; 1370 } 1371 } 1372 1373 // If the relocation does not emit a GOT or GOTPLT entry but its computation 1374 // uses their addresses, we need GOT or GOTPLT to be created. 1375 // 1376 // The 5 types that relative GOTPLT are all x86 and x86-64 specific. 1377 if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_PLT_GOTPLT, 1378 R_TLSDESC_GOTPLT, R_TLSGD_GOTPLT>(expr)) { 1379 in.gotPlt->hasGotPltOffRel = true; 1380 } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC32_PLTREL, R_PPC64_TOCBASE, 1381 R_PPC64_RELAX_TOC>(expr)) { 1382 in.got->hasGotOffRel = true; 1383 } 1384 1385 // Process TLS relocations, including relaxing TLS relocations. Note that 1386 // R_TPREL and R_TPREL_NEG relocations are resolved in processAux. 1387 if (expr == R_TPREL || expr == R_TPREL_NEG) { 1388 if (config->shared) { 1389 errorOrWarn("relocation " + toString(type) + " against " + toString(sym) + 1390 " cannot be used with -shared" + 1391 getLocation(sec, sym, offset)); 1392 return; 1393 } 1394 } else if (unsigned processed = 1395 handleTlsRelocation(type, sym, sec, offset, addend, expr)) { 1396 i += (processed - 1); 1397 return; 1398 } 1399 1400 // Relax relocations. 1401 // 1402 // If we know that a PLT entry will be resolved within the same ELF module, we 1403 // can skip PLT access and directly jump to the destination function. For 1404 // example, if we are linking a main executable, all dynamic symbols that can 1405 // be resolved within the executable will actually be resolved that way at 1406 // runtime, because the main executable is always at the beginning of a search 1407 // list. We can leverage that fact. 1408 if (!sym.isPreemptible && (!sym.isGnuIFunc() || config->zIfuncNoplt)) { 1409 if (expr != R_GOT_PC) { 1410 // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call 1411 // stub type. It should be ignored if optimized to R_PC. 1412 if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL) 1413 addend &= ~0x8000; 1414 // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into 1415 // call __tls_get_addr even if the symbol is non-preemptible. 1416 if (!(config->emachine == EM_HEXAGON && 1417 (type == R_HEX_GD_PLT_B22_PCREL || 1418 type == R_HEX_GD_PLT_B22_PCREL_X || 1419 type == R_HEX_GD_PLT_B32_PCREL_X))) 1420 expr = fromPlt(expr); 1421 } else if (!isAbsoluteValue(sym)) { 1422 expr = target.adjustGotPcExpr(type, addend, relocatedAddr); 1423 } 1424 } 1425 1426 // We were asked not to generate PLT entries for ifuncs. Instead, pass the 1427 // direct relocation on through. 1428 if (sym.isGnuIFunc() && config->zIfuncNoplt) { 1429 sym.exportDynamic = true; 1430 mainPart->relaDyn->addSymbolReloc(type, sec, offset, sym, addend, type); 1431 return; 1432 } 1433 1434 if (needsGot(expr)) { 1435 if (config->emachine == EM_MIPS) { 1436 // MIPS ABI has special rules to process GOT entries and doesn't 1437 // require relocation entries for them. A special case is TLS 1438 // relocations. In that case dynamic loader applies dynamic 1439 // relocations to initialize TLS GOT entries. 1440 // See "Global Offset Table" in Chapter 5 in the following document 1441 // for detailed description: 1442 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1443 in.mipsGot->addEntry(*sec.file, sym, addend, expr); 1444 } else { 1445 sym.needsGot = true; 1446 } 1447 } else if (needsPlt(expr)) { 1448 sym.needsPlt = true; 1449 } else { 1450 sym.hasDirectReloc = true; 1451 } 1452 1453 processAux(expr, type, offset, sym, addend); 1454 } 1455 1456 // R_PPC64_TLSGD/R_PPC64_TLSLD is required to mark `bl __tls_get_addr` for 1457 // General Dynamic/Local Dynamic code sequences. If a GD/LD GOT relocation is 1458 // found but no R_PPC64_TLSGD/R_PPC64_TLSLD is seen, we assume that the 1459 // instructions are generated by very old IBM XL compilers. Work around the 1460 // issue by disabling GD/LD to IE/LE relaxation. 1461 template <class RelTy> 1462 static void checkPPC64TLSRelax(InputSectionBase &sec, ArrayRef<RelTy> rels) { 1463 // Skip if sec is synthetic (sec.file is null) or if sec has been marked. 1464 if (!sec.file || sec.file->ppc64DisableTLSRelax) 1465 return; 1466 bool hasGDLD = false; 1467 for (const RelTy &rel : rels) { 1468 RelType type = rel.getType(false); 1469 switch (type) { 1470 case R_PPC64_TLSGD: 1471 case R_PPC64_TLSLD: 1472 return; // Found a marker 1473 case R_PPC64_GOT_TLSGD16: 1474 case R_PPC64_GOT_TLSGD16_HA: 1475 case R_PPC64_GOT_TLSGD16_HI: 1476 case R_PPC64_GOT_TLSGD16_LO: 1477 case R_PPC64_GOT_TLSLD16: 1478 case R_PPC64_GOT_TLSLD16_HA: 1479 case R_PPC64_GOT_TLSLD16_HI: 1480 case R_PPC64_GOT_TLSLD16_LO: 1481 hasGDLD = true; 1482 break; 1483 } 1484 } 1485 if (hasGDLD) { 1486 sec.file->ppc64DisableTLSRelax = true; 1487 warn(toString(sec.file) + 1488 ": disable TLS relaxation due to R_PPC64_GOT_TLS* relocations without " 1489 "R_PPC64_TLSGD/R_PPC64_TLSLD relocations"); 1490 } 1491 } 1492 1493 template <class ELFT, class RelTy> 1494 void RelocationScanner::scan(ArrayRef<RelTy> rels) { 1495 // Not all relocations end up in Sec.Relocations, but a lot do. 1496 sec.relocations.reserve(rels.size()); 1497 1498 if (config->emachine == EM_PPC64) 1499 checkPPC64TLSRelax<RelTy>(sec, rels); 1500 1501 // For EhInputSection, OffsetGetter expects the relocations to be sorted by 1502 // r_offset. In rare cases (.eh_frame pieces are reordered by a linker 1503 // script), the relocations may be unordered. 1504 SmallVector<RelTy, 0> storage; 1505 if (isa<EhInputSection>(sec)) 1506 rels = sortRels(rels, storage); 1507 1508 end = static_cast<const void *>(rels.end()); 1509 for (auto i = rels.begin(); i != end;) 1510 scanOne<ELFT>(i); 1511 1512 // Sort relocations by offset for more efficient searching for 1513 // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64. 1514 if (config->emachine == EM_RISCV || 1515 (config->emachine == EM_PPC64 && sec.name == ".toc")) 1516 llvm::stable_sort(sec.relocations, 1517 [](const Relocation &lhs, const Relocation &rhs) { 1518 return lhs.offset < rhs.offset; 1519 }); 1520 } 1521 1522 template <class ELFT> void elf::scanRelocations(InputSectionBase &s) { 1523 RelocationScanner scanner(s); 1524 const RelsOrRelas<ELFT> rels = s.template relsOrRelas<ELFT>(); 1525 if (rels.areRelocsRel()) 1526 scanner.template scan<ELFT>(rels.rels); 1527 else 1528 scanner.template scan<ELFT>(rels.relas); 1529 } 1530 1531 static bool handleNonPreemptibleIfunc(Symbol &sym) { 1532 // Handle a reference to a non-preemptible ifunc. These are special in a 1533 // few ways: 1534 // 1535 // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have 1536 // a fixed value. But assuming that all references to the ifunc are 1537 // GOT-generating or PLT-generating, the handling of an ifunc is 1538 // relatively straightforward. We create a PLT entry in Iplt, which is 1539 // usually at the end of .plt, which makes an indirect call using a 1540 // matching GOT entry in igotPlt, which is usually at the end of .got.plt. 1541 // The GOT entry is relocated using an IRELATIVE relocation in relaIplt, 1542 // which is usually at the end of .rela.plt. Unlike most relocations in 1543 // .rela.plt, which may be evaluated lazily without -z now, dynamic 1544 // loaders evaluate IRELATIVE relocs eagerly, which means that for 1545 // IRELATIVE relocs only, GOT-generating relocations can point directly to 1546 // .got.plt without requiring a separate GOT entry. 1547 // 1548 // - Despite the fact that an ifunc does not have a fixed value, compilers 1549 // that are not passed -fPIC will assume that they do, and will emit 1550 // direct (non-GOT-generating, non-PLT-generating) relocations to the 1551 // symbol. This means that if a direct relocation to the symbol is 1552 // seen, the linker must set a value for the symbol, and this value must 1553 // be consistent no matter what type of reference is made to the symbol. 1554 // This can be done by creating a PLT entry for the symbol in the way 1555 // described above and making it canonical, that is, making all references 1556 // point to the PLT entry instead of the resolver. In lld we also store 1557 // the address of the PLT entry in the dynamic symbol table, which means 1558 // that the symbol will also have the same value in other modules. 1559 // Because the value loaded from the GOT needs to be consistent with 1560 // the value computed using a direct relocation, a non-preemptible ifunc 1561 // may end up with two GOT entries, one in .got.plt that points to the 1562 // address returned by the resolver and is used only by the PLT entry, 1563 // and another in .got that points to the PLT entry and is used by 1564 // GOT-generating relocations. 1565 // 1566 // - The fact that these symbols do not have a fixed value makes them an 1567 // exception to the general rule that a statically linked executable does 1568 // not require any form of dynamic relocation. To handle these relocations 1569 // correctly, the IRELATIVE relocations are stored in an array which a 1570 // statically linked executable's startup code must enumerate using the 1571 // linker-defined symbols __rela?_iplt_{start,end}. 1572 if (!sym.isGnuIFunc() || sym.isPreemptible || config->zIfuncNoplt) 1573 return false; 1574 // Skip unreferenced non-preemptible ifunc. 1575 if (!(sym.needsGot || sym.needsPlt || sym.hasDirectReloc)) 1576 return true; 1577 1578 sym.isInIplt = true; 1579 1580 // Create an Iplt and the associated IRELATIVE relocation pointing to the 1581 // original section/value pairs. For non-GOT non-PLT relocation case below, we 1582 // may alter section/value, so create a copy of the symbol to make 1583 // section/value fixed. 1584 auto *directSym = makeDefined(cast<Defined>(sym)); 1585 directSym->allocateAux(); 1586 addPltEntry(*in.iplt, *in.igotPlt, *in.relaIplt, target->iRelativeRel, 1587 *directSym); 1588 sym.allocateAux(); 1589 symAux.back().pltIdx = symAux[directSym->auxIdx].pltIdx; 1590 1591 if (sym.hasDirectReloc) { 1592 // Change the value to the IPLT and redirect all references to it. 1593 auto &d = cast<Defined>(sym); 1594 d.section = in.iplt.get(); 1595 d.value = d.getPltIdx() * target->ipltEntrySize; 1596 d.size = 0; 1597 // It's important to set the symbol type here so that dynamic loaders 1598 // don't try to call the PLT as if it were an ifunc resolver. 1599 d.type = STT_FUNC; 1600 1601 if (sym.needsGot) 1602 addGotEntry(sym); 1603 } else if (sym.needsGot) { 1604 // Redirect GOT accesses to point to the Igot. 1605 sym.gotInIgot = true; 1606 } 1607 return true; 1608 } 1609 1610 void elf::postScanRelocations() { 1611 auto fn = [](Symbol &sym) { 1612 if (handleNonPreemptibleIfunc(sym)) 1613 return; 1614 if (!sym.needsDynReloc()) 1615 return; 1616 sym.allocateAux(); 1617 1618 if (sym.needsGot) 1619 addGotEntry(sym); 1620 if (sym.needsPlt) 1621 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, sym); 1622 if (sym.needsCopy) { 1623 if (sym.isObject()) { 1624 addCopyRelSymbol(cast<SharedSymbol>(sym)); 1625 // needsCopy is cleared for sym and its aliases so that in later 1626 // iterations aliases won't cause redundant copies. 1627 assert(!sym.needsCopy); 1628 } else { 1629 assert(sym.isFunc() && sym.needsPlt); 1630 if (!sym.isDefined()) { 1631 replaceWithDefined(sym, *in.plt, 1632 target->pltHeaderSize + 1633 target->pltEntrySize * sym.getPltIdx(), 1634 0); 1635 sym.needsCopy = true; 1636 if (config->emachine == EM_PPC) { 1637 // PPC32 canonical PLT entries are at the beginning of .glink 1638 cast<Defined>(sym).value = in.plt->headerSize; 1639 in.plt->headerSize += 16; 1640 cast<PPC32GlinkSection>(*in.plt).canonical_plts.push_back(&sym); 1641 } 1642 } 1643 } 1644 } 1645 1646 if (!sym.isTls()) 1647 return; 1648 bool isLocalInExecutable = !sym.isPreemptible && !config->shared; 1649 1650 if (sym.needsTlsDesc) { 1651 in.got->addTlsDescEntry(sym); 1652 mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible( 1653 target->tlsDescRel, *in.got, in.got->getTlsDescOffset(sym), sym, 1654 target->tlsDescRel); 1655 } 1656 if (sym.needsTlsGd) { 1657 in.got->addDynTlsEntry(sym); 1658 uint64_t off = in.got->getGlobalDynOffset(sym); 1659 if (isLocalInExecutable) 1660 // Write one to the GOT slot. 1661 in.got->relocations.push_back( 1662 {R_ADDEND, target->symbolicRel, off, 1, &sym}); 1663 else 1664 mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *in.got, 1665 off, sym); 1666 1667 // If the symbol is preemptible we need the dynamic linker to write 1668 // the offset too. 1669 uint64_t offsetOff = off + config->wordsize; 1670 if (sym.isPreemptible) 1671 mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *in.got, 1672 offsetOff, sym); 1673 else 1674 in.got->relocations.push_back( 1675 {R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym}); 1676 } 1677 if (sym.needsTlsGdToIe) { 1678 in.got->addEntry(sym); 1679 mainPart->relaDyn->addSymbolReloc(target->tlsGotRel, *in.got, 1680 sym.getGotOffset(), sym); 1681 } 1682 if (sym.needsGotDtprel) { 1683 in.got->addEntry(sym); 1684 in.got->relocations.push_back( 1685 {R_ABS, target->tlsOffsetRel, sym.getGotOffset(), 0, &sym}); 1686 } 1687 1688 if (sym.needsTlsIe && !sym.needsTlsGdToIe) 1689 addTpOffsetGotEntry(sym); 1690 }; 1691 1692 if (config->needsTlsLd && in.got->addTlsIndex()) { 1693 static Undefined dummy(nullptr, "", STB_LOCAL, 0, 0); 1694 if (config->shared) 1695 mainPart->relaDyn->addReloc( 1696 {target->tlsModuleIndexRel, in.got.get(), in.got->getTlsIndexOff()}); 1697 else 1698 in.got->relocations.push_back( 1699 {R_ADDEND, target->symbolicRel, in.got->getTlsIndexOff(), 1, &dummy}); 1700 } 1701 1702 assert(symAux.empty()); 1703 for (Symbol *sym : symtab->symbols()) 1704 fn(*sym); 1705 1706 // Local symbols may need the aforementioned non-preemptible ifunc and GOT 1707 // handling. They don't need regular PLT. 1708 for (ELFFileBase *file : objectFiles) 1709 for (Symbol *sym : file->getLocalSymbols()) 1710 fn(*sym); 1711 } 1712 1713 static bool mergeCmp(const InputSection *a, const InputSection *b) { 1714 // std::merge requires a strict weak ordering. 1715 if (a->outSecOff < b->outSecOff) 1716 return true; 1717 1718 if (a->outSecOff == b->outSecOff) { 1719 auto *ta = dyn_cast<ThunkSection>(a); 1720 auto *tb = dyn_cast<ThunkSection>(b); 1721 1722 // Check if Thunk is immediately before any specific Target 1723 // InputSection for example Mips LA25 Thunks. 1724 if (ta && ta->getTargetInputSection() == b) 1725 return true; 1726 1727 // Place Thunk Sections without specific targets before 1728 // non-Thunk Sections. 1729 if (ta && !tb && !ta->getTargetInputSection()) 1730 return true; 1731 } 1732 1733 return false; 1734 } 1735 1736 // Call Fn on every executable InputSection accessed via the linker script 1737 // InputSectionDescription::Sections. 1738 static void forEachInputSectionDescription( 1739 ArrayRef<OutputSection *> outputSections, 1740 llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) { 1741 for (OutputSection *os : outputSections) { 1742 if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR)) 1743 continue; 1744 for (SectionCommand *bc : os->commands) 1745 if (auto *isd = dyn_cast<InputSectionDescription>(bc)) 1746 fn(os, isd); 1747 } 1748 } 1749 1750 // Thunk Implementation 1751 // 1752 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces 1753 // of code that the linker inserts inbetween a caller and a callee. The thunks 1754 // are added at link time rather than compile time as the decision on whether 1755 // a thunk is needed, such as the caller and callee being out of range, can only 1756 // be made at link time. 1757 // 1758 // It is straightforward to tell given the current state of the program when a 1759 // thunk is needed for a particular call. The more difficult part is that 1760 // the thunk needs to be placed in the program such that the caller can reach 1761 // the thunk and the thunk can reach the callee; furthermore, adding thunks to 1762 // the program alters addresses, which can mean more thunks etc. 1763 // 1764 // In lld we have a synthetic ThunkSection that can hold many Thunks. 1765 // The decision to have a ThunkSection act as a container means that we can 1766 // more easily handle the most common case of a single block of contiguous 1767 // Thunks by inserting just a single ThunkSection. 1768 // 1769 // The implementation of Thunks in lld is split across these areas 1770 // Relocations.cpp : Framework for creating and placing thunks 1771 // Thunks.cpp : The code generated for each supported thunk 1772 // Target.cpp : Target specific hooks that the framework uses to decide when 1773 // a thunk is used 1774 // Synthetic.cpp : Implementation of ThunkSection 1775 // Writer.cpp : Iteratively call framework until no more Thunks added 1776 // 1777 // Thunk placement requirements: 1778 // Mips LA25 thunks. These must be placed immediately before the callee section 1779 // We can assume that the caller is in range of the Thunk. These are modelled 1780 // by Thunks that return the section they must precede with 1781 // getTargetInputSection(). 1782 // 1783 // ARM interworking and range extension thunks. These thunks must be placed 1784 // within range of the caller. All implemented ARM thunks can always reach the 1785 // callee as they use an indirect jump via a register that has no range 1786 // restrictions. 1787 // 1788 // Thunk placement algorithm: 1789 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before 1790 // getTargetInputSection(). 1791 // 1792 // For thunks that must be placed within range of the caller there are many 1793 // possible choices given that the maximum range from the caller is usually 1794 // much larger than the average InputSection size. Desirable properties include: 1795 // - Maximize reuse of thunks by multiple callers 1796 // - Minimize number of ThunkSections to simplify insertion 1797 // - Handle impact of already added Thunks on addresses 1798 // - Simple to understand and implement 1799 // 1800 // In lld for the first pass, we pre-create one or more ThunkSections per 1801 // InputSectionDescription at Target specific intervals. A ThunkSection is 1802 // placed so that the estimated end of the ThunkSection is within range of the 1803 // start of the InputSectionDescription or the previous ThunkSection. For 1804 // example: 1805 // InputSectionDescription 1806 // Section 0 1807 // ... 1808 // Section N 1809 // ThunkSection 0 1810 // Section N + 1 1811 // ... 1812 // Section N + K 1813 // Thunk Section 1 1814 // 1815 // The intention is that we can add a Thunk to a ThunkSection that is well 1816 // spaced enough to service a number of callers without having to do a lot 1817 // of work. An important principle is that it is not an error if a Thunk cannot 1818 // be placed in a pre-created ThunkSection; when this happens we create a new 1819 // ThunkSection placed next to the caller. This allows us to handle the vast 1820 // majority of thunks simply, but also handle rare cases where the branch range 1821 // is smaller than the target specific spacing. 1822 // 1823 // The algorithm is expected to create all the thunks that are needed in a 1824 // single pass, with a small number of programs needing a second pass due to 1825 // the insertion of thunks in the first pass increasing the offset between 1826 // callers and callees that were only just in range. 1827 // 1828 // A consequence of allowing new ThunkSections to be created outside of the 1829 // pre-created ThunkSections is that in rare cases calls to Thunks that were in 1830 // range in pass K, are out of range in some pass > K due to the insertion of 1831 // more Thunks in between the caller and callee. When this happens we retarget 1832 // the relocation back to the original target and create another Thunk. 1833 1834 // Remove ThunkSections that are empty, this should only be the initial set 1835 // precreated on pass 0. 1836 1837 // Insert the Thunks for OutputSection OS into their designated place 1838 // in the Sections vector, and recalculate the InputSection output section 1839 // offsets. 1840 // This may invalidate any output section offsets stored outside of InputSection 1841 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) { 1842 forEachInputSectionDescription( 1843 outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 1844 if (isd->thunkSections.empty()) 1845 return; 1846 1847 // Remove any zero sized precreated Thunks. 1848 llvm::erase_if(isd->thunkSections, 1849 [](const std::pair<ThunkSection *, uint32_t> &ts) { 1850 return ts.first->getSize() == 0; 1851 }); 1852 1853 // ISD->ThunkSections contains all created ThunkSections, including 1854 // those inserted in previous passes. Extract the Thunks created this 1855 // pass and order them in ascending outSecOff. 1856 std::vector<ThunkSection *> newThunks; 1857 for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections) 1858 if (ts.second == pass) 1859 newThunks.push_back(ts.first); 1860 llvm::stable_sort(newThunks, 1861 [](const ThunkSection *a, const ThunkSection *b) { 1862 return a->outSecOff < b->outSecOff; 1863 }); 1864 1865 // Merge sorted vectors of Thunks and InputSections by outSecOff 1866 SmallVector<InputSection *, 0> tmp; 1867 tmp.reserve(isd->sections.size() + newThunks.size()); 1868 1869 std::merge(isd->sections.begin(), isd->sections.end(), 1870 newThunks.begin(), newThunks.end(), std::back_inserter(tmp), 1871 mergeCmp); 1872 1873 isd->sections = std::move(tmp); 1874 }); 1875 } 1876 1877 // Find or create a ThunkSection within the InputSectionDescription (ISD) that 1878 // is in range of Src. An ISD maps to a range of InputSections described by a 1879 // linker script section pattern such as { .text .text.* }. 1880 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os, 1881 InputSection *isec, 1882 InputSectionDescription *isd, 1883 const Relocation &rel, 1884 uint64_t src) { 1885 for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) { 1886 ThunkSection *ts = tp.first; 1887 uint64_t tsBase = os->addr + ts->outSecOff + rel.addend; 1888 uint64_t tsLimit = tsBase + ts->getSize() + rel.addend; 1889 if (target->inBranchRange(rel.type, src, 1890 (src > tsLimit) ? tsBase : tsLimit)) 1891 return ts; 1892 } 1893 1894 // No suitable ThunkSection exists. This can happen when there is a branch 1895 // with lower range than the ThunkSection spacing or when there are too 1896 // many Thunks. Create a new ThunkSection as close to the InputSection as 1897 // possible. Error if InputSection is so large we cannot place ThunkSection 1898 // anywhere in Range. 1899 uint64_t thunkSecOff = isec->outSecOff; 1900 if (!target->inBranchRange(rel.type, src, 1901 os->addr + thunkSecOff + rel.addend)) { 1902 thunkSecOff = isec->outSecOff + isec->getSize(); 1903 if (!target->inBranchRange(rel.type, src, 1904 os->addr + thunkSecOff + rel.addend)) 1905 fatal("InputSection too large for range extension thunk " + 1906 isec->getObjMsg(src - (os->addr + isec->outSecOff))); 1907 } 1908 return addThunkSection(os, isd, thunkSecOff); 1909 } 1910 1911 // Add a Thunk that needs to be placed in a ThunkSection that immediately 1912 // precedes its Target. 1913 ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) { 1914 ThunkSection *ts = thunkedSections.lookup(isec); 1915 if (ts) 1916 return ts; 1917 1918 // Find InputSectionRange within Target Output Section (TOS) that the 1919 // InputSection (IS) that we need to precede is in. 1920 OutputSection *tos = isec->getParent(); 1921 for (SectionCommand *bc : tos->commands) { 1922 auto *isd = dyn_cast<InputSectionDescription>(bc); 1923 if (!isd || isd->sections.empty()) 1924 continue; 1925 1926 InputSection *first = isd->sections.front(); 1927 InputSection *last = isd->sections.back(); 1928 1929 if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff) 1930 continue; 1931 1932 ts = addThunkSection(tos, isd, isec->outSecOff); 1933 thunkedSections[isec] = ts; 1934 return ts; 1935 } 1936 1937 return nullptr; 1938 } 1939 1940 // Create one or more ThunkSections per OS that can be used to place Thunks. 1941 // We attempt to place the ThunkSections using the following desirable 1942 // properties: 1943 // - Within range of the maximum number of callers 1944 // - Minimise the number of ThunkSections 1945 // 1946 // We follow a simple but conservative heuristic to place ThunkSections at 1947 // offsets that are multiples of a Target specific branch range. 1948 // For an InputSectionDescription that is smaller than the range, a single 1949 // ThunkSection at the end of the range will do. 1950 // 1951 // For an InputSectionDescription that is more than twice the size of the range, 1952 // we place the last ThunkSection at range bytes from the end of the 1953 // InputSectionDescription in order to increase the likelihood that the 1954 // distance from a thunk to its target will be sufficiently small to 1955 // allow for the creation of a short thunk. 1956 void ThunkCreator::createInitialThunkSections( 1957 ArrayRef<OutputSection *> outputSections) { 1958 uint32_t thunkSectionSpacing = target->getThunkSectionSpacing(); 1959 1960 forEachInputSectionDescription( 1961 outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 1962 if (isd->sections.empty()) 1963 return; 1964 1965 uint32_t isdBegin = isd->sections.front()->outSecOff; 1966 uint32_t isdEnd = 1967 isd->sections.back()->outSecOff + isd->sections.back()->getSize(); 1968 uint32_t lastThunkLowerBound = -1; 1969 if (isdEnd - isdBegin > thunkSectionSpacing * 2) 1970 lastThunkLowerBound = isdEnd - thunkSectionSpacing; 1971 1972 uint32_t isecLimit; 1973 uint32_t prevIsecLimit = isdBegin; 1974 uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing; 1975 1976 for (const InputSection *isec : isd->sections) { 1977 isecLimit = isec->outSecOff + isec->getSize(); 1978 if (isecLimit > thunkUpperBound) { 1979 addThunkSection(os, isd, prevIsecLimit); 1980 thunkUpperBound = prevIsecLimit + thunkSectionSpacing; 1981 } 1982 if (isecLimit > lastThunkLowerBound) 1983 break; 1984 prevIsecLimit = isecLimit; 1985 } 1986 addThunkSection(os, isd, isecLimit); 1987 }); 1988 } 1989 1990 ThunkSection *ThunkCreator::addThunkSection(OutputSection *os, 1991 InputSectionDescription *isd, 1992 uint64_t off) { 1993 auto *ts = make<ThunkSection>(os, off); 1994 ts->partition = os->partition; 1995 if ((config->fixCortexA53Errata843419 || config->fixCortexA8) && 1996 !isd->sections.empty()) { 1997 // The errata fixes are sensitive to addresses modulo 4 KiB. When we add 1998 // thunks we disturb the base addresses of sections placed after the thunks 1999 // this makes patches we have generated redundant, and may cause us to 2000 // generate more patches as different instructions are now in sensitive 2001 // locations. When we generate more patches we may force more branches to 2002 // go out of range, causing more thunks to be generated. In pathological 2003 // cases this can cause the address dependent content pass not to converge. 2004 // We fix this by rounding up the size of the ThunkSection to 4KiB, this 2005 // limits the insertion of a ThunkSection on the addresses modulo 4 KiB, 2006 // which means that adding Thunks to the section does not invalidate 2007 // errata patches for following code. 2008 // Rounding up the size to 4KiB has consequences for code-size and can 2009 // trip up linker script defined assertions. For example the linux kernel 2010 // has an assertion that what LLD represents as an InputSectionDescription 2011 // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib. 2012 // We use the heuristic of rounding up the size when both of the following 2013 // conditions are true: 2014 // 1.) The OutputSection is larger than the ThunkSectionSpacing. This 2015 // accounts for the case where no single InputSectionDescription is 2016 // larger than the OutputSection size. This is conservative but simple. 2017 // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent 2018 // any assertion failures that an InputSectionDescription is < 4 KiB 2019 // in size. 2020 uint64_t isdSize = isd->sections.back()->outSecOff + 2021 isd->sections.back()->getSize() - 2022 isd->sections.front()->outSecOff; 2023 if (os->size > target->getThunkSectionSpacing() && isdSize > 4096) 2024 ts->roundUpSizeForErrata = true; 2025 } 2026 isd->thunkSections.push_back({ts, pass}); 2027 return ts; 2028 } 2029 2030 static bool isThunkSectionCompatible(InputSection *source, 2031 SectionBase *target) { 2032 // We can't reuse thunks in different loadable partitions because they might 2033 // not be loaded. But partition 1 (the main partition) will always be loaded. 2034 if (source->partition != target->partition) 2035 return target->partition == 1; 2036 return true; 2037 } 2038 2039 static int64_t getPCBias(RelType type) { 2040 if (config->emachine != EM_ARM) 2041 return 0; 2042 switch (type) { 2043 case R_ARM_THM_JUMP19: 2044 case R_ARM_THM_JUMP24: 2045 case R_ARM_THM_CALL: 2046 return 4; 2047 default: 2048 return 8; 2049 } 2050 } 2051 2052 std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec, 2053 Relocation &rel, uint64_t src) { 2054 std::vector<Thunk *> *thunkVec = nullptr; 2055 // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled 2056 // out in the relocation addend. We compensate for the PC bias so that 2057 // an Arm and Thumb relocation to the same destination get the same keyAddend, 2058 // which is usually 0. 2059 const int64_t pcBias = getPCBias(rel.type); 2060 const int64_t keyAddend = rel.addend + pcBias; 2061 2062 // We use a ((section, offset), addend) pair to find the thunk position if 2063 // possible so that we create only one thunk for aliased symbols or ICFed 2064 // sections. There may be multiple relocations sharing the same (section, 2065 // offset + addend) pair. We may revert the relocation back to its original 2066 // non-Thunk target, so we cannot fold offset + addend. 2067 if (auto *d = dyn_cast<Defined>(rel.sym)) 2068 if (!d->isInPlt() && d->section) 2069 thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value}, 2070 keyAddend}]; 2071 if (!thunkVec) 2072 thunkVec = &thunkedSymbols[{rel.sym, keyAddend}]; 2073 2074 // Check existing Thunks for Sym to see if they can be reused 2075 for (Thunk *t : *thunkVec) 2076 if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) && 2077 t->isCompatibleWith(*isec, rel) && 2078 target->inBranchRange(rel.type, src, 2079 t->getThunkTargetSym()->getVA(-pcBias))) 2080 return std::make_pair(t, false); 2081 2082 // No existing compatible Thunk in range, create a new one 2083 Thunk *t = addThunk(*isec, rel); 2084 thunkVec->push_back(t); 2085 return std::make_pair(t, true); 2086 } 2087 2088 // Return true if the relocation target is an in range Thunk. 2089 // Return false if the relocation is not to a Thunk. If the relocation target 2090 // was originally to a Thunk, but is no longer in range we revert the 2091 // relocation back to its original non-Thunk target. 2092 bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) { 2093 if (Thunk *t = thunks.lookup(rel.sym)) { 2094 if (target->inBranchRange(rel.type, src, rel.sym->getVA(rel.addend))) 2095 return true; 2096 rel.sym = &t->destination; 2097 rel.addend = t->addend; 2098 if (rel.sym->isInPlt()) 2099 rel.expr = toPlt(rel.expr); 2100 } 2101 return false; 2102 } 2103 2104 // Process all relocations from the InputSections that have been assigned 2105 // to InputSectionDescriptions and redirect through Thunks if needed. The 2106 // function should be called iteratively until it returns false. 2107 // 2108 // PreConditions: 2109 // All InputSections that may need a Thunk are reachable from 2110 // OutputSectionCommands. 2111 // 2112 // All OutputSections have an address and all InputSections have an offset 2113 // within the OutputSection. 2114 // 2115 // The offsets between caller (relocation place) and callee 2116 // (relocation target) will not be modified outside of createThunks(). 2117 // 2118 // PostConditions: 2119 // If return value is true then ThunkSections have been inserted into 2120 // OutputSections. All relocations that needed a Thunk based on the information 2121 // available to createThunks() on entry have been redirected to a Thunk. Note 2122 // that adding Thunks changes offsets between caller and callee so more Thunks 2123 // may be required. 2124 // 2125 // If return value is false then no more Thunks are needed, and createThunks has 2126 // made no changes. If the target requires range extension thunks, currently 2127 // ARM, then any future change in offset between caller and callee risks a 2128 // relocation out of range error. 2129 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> outputSections) { 2130 bool addressesChanged = false; 2131 2132 if (pass == 0 && target->getThunkSectionSpacing()) 2133 createInitialThunkSections(outputSections); 2134 2135 // Create all the Thunks and insert them into synthetic ThunkSections. The 2136 // ThunkSections are later inserted back into InputSectionDescriptions. 2137 // We separate the creation of ThunkSections from the insertion of the 2138 // ThunkSections as ThunkSections are not always inserted into the same 2139 // InputSectionDescription as the caller. 2140 forEachInputSectionDescription( 2141 outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 2142 for (InputSection *isec : isd->sections) 2143 for (Relocation &rel : isec->relocations) { 2144 uint64_t src = isec->getVA(rel.offset); 2145 2146 // If we are a relocation to an existing Thunk, check if it is 2147 // still in range. If not then Rel will be altered to point to its 2148 // original target so another Thunk can be generated. 2149 if (pass > 0 && normalizeExistingThunk(rel, src)) 2150 continue; 2151 2152 if (!target->needsThunk(rel.expr, rel.type, isec->file, src, 2153 *rel.sym, rel.addend)) 2154 continue; 2155 2156 Thunk *t; 2157 bool isNew; 2158 std::tie(t, isNew) = getThunk(isec, rel, src); 2159 2160 if (isNew) { 2161 // Find or create a ThunkSection for the new Thunk 2162 ThunkSection *ts; 2163 if (auto *tis = t->getTargetInputSection()) 2164 ts = getISThunkSec(tis); 2165 else 2166 ts = getISDThunkSec(os, isec, isd, rel, src); 2167 ts->addThunk(t); 2168 thunks[t->getThunkTargetSym()] = t; 2169 } 2170 2171 // Redirect relocation to Thunk, we never go via the PLT to a Thunk 2172 rel.sym = t->getThunkTargetSym(); 2173 rel.expr = fromPlt(rel.expr); 2174 2175 // On AArch64 and PPC, a jump/call relocation may be encoded as 2176 // STT_SECTION + non-zero addend, clear the addend after 2177 // redirection. 2178 if (config->emachine != EM_MIPS) 2179 rel.addend = -getPCBias(rel.type); 2180 } 2181 2182 for (auto &p : isd->thunkSections) 2183 addressesChanged |= p.first->assignOffsets(); 2184 }); 2185 2186 for (auto &p : thunkedSections) 2187 addressesChanged |= p.second->assignOffsets(); 2188 2189 // Merge all created synthetic ThunkSections back into OutputSection 2190 mergeThunks(outputSections); 2191 ++pass; 2192 return addressesChanged; 2193 } 2194 2195 // The following aid in the conversion of call x@GDPLT to call __tls_get_addr 2196 // hexagonNeedsTLSSymbol scans for relocations would require a call to 2197 // __tls_get_addr. 2198 // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr. 2199 bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) { 2200 bool needTlsSymbol = false; 2201 forEachInputSectionDescription( 2202 outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 2203 for (InputSection *isec : isd->sections) 2204 for (Relocation &rel : isec->relocations) 2205 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) { 2206 needTlsSymbol = true; 2207 return; 2208 } 2209 }); 2210 return needTlsSymbol; 2211 } 2212 2213 void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) { 2214 Symbol *sym = symtab->find("__tls_get_addr"); 2215 if (!sym) 2216 return; 2217 bool needEntry = true; 2218 forEachInputSectionDescription( 2219 outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 2220 for (InputSection *isec : isd->sections) 2221 for (Relocation &rel : isec->relocations) 2222 if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) { 2223 if (needEntry) { 2224 sym->allocateAux(); 2225 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, 2226 *sym); 2227 needEntry = false; 2228 } 2229 rel.sym = sym; 2230 } 2231 }); 2232 } 2233 2234 template void elf::scanRelocations<ELF32LE>(InputSectionBase &); 2235 template void elf::scanRelocations<ELF32BE>(InputSectionBase &); 2236 template void elf::scanRelocations<ELF64LE>(InputSectionBase &); 2237 template void elf::scanRelocations<ELF64BE>(InputSectionBase &); 2238