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