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