1 //===- InputSection.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 #include "InputSection.h" 10 #include "Config.h" 11 #include "EhFrame.h" 12 #include "InputFiles.h" 13 #include "LinkerScript.h" 14 #include "OutputSections.h" 15 #include "Relocations.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "SyntheticSections.h" 19 #include "Target.h" 20 #include "Thunks.h" 21 #include "lld/Common/CommonLinkerContext.h" 22 #include "llvm/Support/Compiler.h" 23 #include "llvm/Support/Compression.h" 24 #include "llvm/Support/Endian.h" 25 #include "llvm/Support/Threading.h" 26 #include "llvm/Support/xxhash.h" 27 #include <algorithm> 28 #include <mutex> 29 #include <set> 30 #include <vector> 31 32 using namespace llvm; 33 using namespace llvm::ELF; 34 using namespace llvm::object; 35 using namespace llvm::support; 36 using namespace llvm::support::endian; 37 using namespace llvm::sys; 38 using namespace lld; 39 using namespace lld::elf; 40 41 SmallVector<InputSectionBase *, 0> elf::inputSections; 42 DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax; 43 44 // Returns a string to construct an error message. 45 std::string lld::toString(const InputSectionBase *sec) { 46 return (toString(sec->file) + ":(" + sec->name + ")").str(); 47 } 48 49 template <class ELFT> 50 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file, 51 const typename ELFT::Shdr &hdr) { 52 if (hdr.sh_type == SHT_NOBITS) 53 return makeArrayRef<uint8_t>(nullptr, hdr.sh_size); 54 return check(file.getObj().getSectionContents(hdr)); 55 } 56 57 InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags, 58 uint32_t type, uint64_t entsize, 59 uint32_t link, uint32_t info, 60 uint32_t alignment, ArrayRef<uint8_t> data, 61 StringRef name, Kind sectionKind) 62 : SectionBase(sectionKind, name, flags, entsize, alignment, type, info, 63 link), 64 file(file), rawData(data) { 65 // In order to reduce memory allocation, we assume that mergeable 66 // sections are smaller than 4 GiB, which is not an unreasonable 67 // assumption as of 2017. 68 if (sectionKind == SectionBase::Merge && rawData.size() > UINT32_MAX) 69 error(toString(this) + ": section too large"); 70 71 // The ELF spec states that a value of 0 means the section has 72 // no alignment constraints. 73 uint32_t v = std::max<uint32_t>(alignment, 1); 74 if (!isPowerOf2_64(v)) 75 fatal(toString(this) + ": sh_addralign is not a power of 2"); 76 this->alignment = v; 77 78 // In ELF, each section can be compressed by zlib, and if compressed, 79 // section name may be mangled by appending "z" (e.g. ".zdebug_info"). 80 // If that's the case, demangle section name so that we can handle a 81 // section as if it weren't compressed. 82 if ((flags & SHF_COMPRESSED) || name.startswith(".zdebug")) { 83 if (!zlib::isAvailable()) 84 error(toString(file) + ": contains a compressed section, " + 85 "but zlib is not available"); 86 invokeELFT(parseCompressedHeader); 87 } 88 } 89 90 // Drop SHF_GROUP bit unless we are producing a re-linkable object file. 91 // SHF_GROUP is a marker that a section belongs to some comdat group. 92 // That flag doesn't make sense in an executable. 93 static uint64_t getFlags(uint64_t flags) { 94 flags &= ~(uint64_t)SHF_INFO_LINK; 95 if (!config->relocatable) 96 flags &= ~(uint64_t)SHF_GROUP; 97 return flags; 98 } 99 100 template <class ELFT> 101 InputSectionBase::InputSectionBase(ObjFile<ELFT> &file, 102 const typename ELFT::Shdr &hdr, 103 StringRef name, Kind sectionKind) 104 : InputSectionBase(&file, getFlags(hdr.sh_flags), hdr.sh_type, 105 hdr.sh_entsize, hdr.sh_link, hdr.sh_info, 106 hdr.sh_addralign, getSectionContents(file, hdr), name, 107 sectionKind) { 108 // We reject object files having insanely large alignments even though 109 // they are allowed by the spec. I think 4GB is a reasonable limitation. 110 // We might want to relax this in the future. 111 if (hdr.sh_addralign > UINT32_MAX) 112 fatal(toString(&file) + ": section sh_addralign is too large"); 113 } 114 115 size_t InputSectionBase::getSize() const { 116 if (auto *s = dyn_cast<SyntheticSection>(this)) 117 return s->getSize(); 118 if (uncompressedSize >= 0) 119 return uncompressedSize; 120 return rawData.size() - bytesDropped; 121 } 122 123 void InputSectionBase::uncompress() const { 124 size_t size = uncompressedSize; 125 char *uncompressedBuf; 126 { 127 static std::mutex mu; 128 std::lock_guard<std::mutex> lock(mu); 129 uncompressedBuf = bAlloc().Allocate<char>(size); 130 } 131 132 if (Error e = zlib::uncompress(toStringRef(rawData), uncompressedBuf, size)) 133 fatal(toString(this) + 134 ": uncompress failed: " + llvm::toString(std::move(e))); 135 rawData = makeArrayRef((uint8_t *)uncompressedBuf, size); 136 uncompressedSize = -1; 137 } 138 139 template <class ELFT> RelsOrRelas<ELFT> InputSectionBase::relsOrRelas() const { 140 if (relSecIdx == 0) 141 return {}; 142 RelsOrRelas<ELFT> ret; 143 typename ELFT::Shdr shdr = 144 cast<ELFFileBase>(file)->getELFShdrs<ELFT>()[relSecIdx]; 145 if (shdr.sh_type == SHT_REL) { 146 ret.rels = makeArrayRef(reinterpret_cast<const typename ELFT::Rel *>( 147 file->mb.getBufferStart() + shdr.sh_offset), 148 shdr.sh_size / sizeof(typename ELFT::Rel)); 149 } else { 150 assert(shdr.sh_type == SHT_RELA); 151 ret.relas = makeArrayRef(reinterpret_cast<const typename ELFT::Rela *>( 152 file->mb.getBufferStart() + shdr.sh_offset), 153 shdr.sh_size / sizeof(typename ELFT::Rela)); 154 } 155 return ret; 156 } 157 158 uint64_t SectionBase::getOffset(uint64_t offset) const { 159 switch (kind()) { 160 case Output: { 161 auto *os = cast<OutputSection>(this); 162 // For output sections we treat offset -1 as the end of the section. 163 return offset == uint64_t(-1) ? os->size : offset; 164 } 165 case Regular: 166 case Synthetic: 167 return cast<InputSection>(this)->outSecOff + offset; 168 case EHFrame: 169 // The file crtbeginT.o has relocations pointing to the start of an empty 170 // .eh_frame that is known to be the first in the link. It does that to 171 // identify the start of the output .eh_frame. 172 return offset; 173 case Merge: 174 const MergeInputSection *ms = cast<MergeInputSection>(this); 175 if (InputSection *isec = ms->getParent()) 176 return isec->outSecOff + ms->getParentOffset(offset); 177 return ms->getParentOffset(offset); 178 } 179 llvm_unreachable("invalid section kind"); 180 } 181 182 uint64_t SectionBase::getVA(uint64_t offset) const { 183 const OutputSection *out = getOutputSection(); 184 return (out ? out->addr : 0) + getOffset(offset); 185 } 186 187 OutputSection *SectionBase::getOutputSection() { 188 InputSection *sec; 189 if (auto *isec = dyn_cast<InputSection>(this)) 190 sec = isec; 191 else if (auto *ms = dyn_cast<MergeInputSection>(this)) 192 sec = ms->getParent(); 193 else if (auto *eh = dyn_cast<EhInputSection>(this)) 194 sec = eh->getParent(); 195 else 196 return cast<OutputSection>(this); 197 return sec ? sec->getParent() : nullptr; 198 } 199 200 // When a section is compressed, `rawData` consists with a header followed 201 // by zlib-compressed data. This function parses a header to initialize 202 // `uncompressedSize` member and remove the header from `rawData`. 203 template <typename ELFT> void InputSectionBase::parseCompressedHeader() { 204 // Old-style header 205 if (!(flags & SHF_COMPRESSED)) { 206 assert(name.startswith(".zdebug")); 207 if (!toStringRef(rawData).startswith("ZLIB")) { 208 error(toString(this) + ": corrupted compressed section header"); 209 return; 210 } 211 rawData = rawData.slice(4); 212 213 if (rawData.size() < 8) { 214 error(toString(this) + ": corrupted compressed section header"); 215 return; 216 } 217 218 uncompressedSize = read64be(rawData.data()); 219 rawData = rawData.slice(8); 220 221 // Restore the original section name. 222 // (e.g. ".zdebug_info" -> ".debug_info") 223 name = saver().save("." + name.substr(2)); 224 return; 225 } 226 227 flags &= ~(uint64_t)SHF_COMPRESSED; 228 229 // New-style header 230 if (rawData.size() < sizeof(typename ELFT::Chdr)) { 231 error(toString(this) + ": corrupted compressed section"); 232 return; 233 } 234 235 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(rawData.data()); 236 if (hdr->ch_type != ELFCOMPRESS_ZLIB) { 237 error(toString(this) + ": unsupported compression type"); 238 return; 239 } 240 241 uncompressedSize = hdr->ch_size; 242 alignment = std::max<uint32_t>(hdr->ch_addralign, 1); 243 rawData = rawData.slice(sizeof(*hdr)); 244 } 245 246 InputSection *InputSectionBase::getLinkOrderDep() const { 247 assert(flags & SHF_LINK_ORDER); 248 if (!link) 249 return nullptr; 250 return cast<InputSection>(file->getSections()[link]); 251 } 252 253 // Find a function symbol that encloses a given location. 254 Defined *InputSectionBase::getEnclosingFunction(uint64_t offset) { 255 for (Symbol *b : file->getSymbols()) 256 if (Defined *d = dyn_cast<Defined>(b)) 257 if (d->section == this && d->type == STT_FUNC && d->value <= offset && 258 offset < d->value + d->size) 259 return d; 260 return nullptr; 261 } 262 263 // Returns an object file location string. Used to construct an error message. 264 std::string InputSectionBase::getLocation(uint64_t offset) { 265 std::string secAndOffset = 266 (name + "+0x" + Twine::utohexstr(offset) + ")").str(); 267 268 // We don't have file for synthetic sections. 269 if (file == nullptr) 270 return (config->outputFile + ":(" + secAndOffset).str(); 271 272 std::string filename = toString(file); 273 if (Defined *d = getEnclosingFunction(offset)) 274 return filename + ":(function " + toString(*d) + ": " + secAndOffset; 275 276 return filename + ":(" + secAndOffset; 277 } 278 279 // This function is intended to be used for constructing an error message. 280 // The returned message looks like this: 281 // 282 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42) 283 // 284 // Returns an empty string if there's no way to get line info. 285 std::string InputSectionBase::getSrcMsg(const Symbol &sym, uint64_t offset) { 286 return file->getSrcMsg(sym, *this, offset); 287 } 288 289 // Returns a filename string along with an optional section name. This 290 // function is intended to be used for constructing an error 291 // message. The returned message looks like this: 292 // 293 // path/to/foo.o:(function bar) 294 // 295 // or 296 // 297 // path/to/foo.o:(function bar) in archive path/to/bar.a 298 std::string InputSectionBase::getObjMsg(uint64_t off) { 299 std::string filename = std::string(file->getName()); 300 301 std::string archive; 302 if (!file->archiveName.empty()) 303 archive = (" in archive " + file->archiveName).str(); 304 305 // Find a symbol that encloses a given location. 306 for (Symbol *b : file->getSymbols()) 307 if (auto *d = dyn_cast<Defined>(b)) 308 if (d->section == this && d->value <= off && off < d->value + d->size) 309 return filename + ":(" + toString(*d) + ")" + archive; 310 311 // If there's no symbol, print out the offset in the section. 312 return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive) 313 .str(); 314 } 315 316 InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), ""); 317 318 InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type, 319 uint32_t alignment, ArrayRef<uint8_t> data, 320 StringRef name, Kind k) 321 : InputSectionBase(f, flags, type, 322 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, alignment, data, 323 name, k) {} 324 325 template <class ELFT> 326 InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header, 327 StringRef name) 328 : InputSectionBase(f, header, name, InputSectionBase::Regular) {} 329 330 bool InputSection::classof(const SectionBase *s) { 331 return s->kind() == SectionBase::Regular || 332 s->kind() == SectionBase::Synthetic; 333 } 334 335 OutputSection *InputSection::getParent() const { 336 return cast_or_null<OutputSection>(parent); 337 } 338 339 // Copy SHT_GROUP section contents. Used only for the -r option. 340 template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) { 341 // ELFT::Word is the 32-bit integral type in the target endianness. 342 using u32 = typename ELFT::Word; 343 ArrayRef<u32> from = getDataAs<u32>(); 344 auto *to = reinterpret_cast<u32 *>(buf); 345 346 // The first entry is not a section number but a flag. 347 *to++ = from[0]; 348 349 // Adjust section numbers because section numbers in an input object files are 350 // different in the output. We also need to handle combined or discarded 351 // members. 352 ArrayRef<InputSectionBase *> sections = file->getSections(); 353 DenseSet<uint32_t> seen; 354 for (uint32_t idx : from.slice(1)) { 355 OutputSection *osec = sections[idx]->getOutputSection(); 356 if (osec && seen.insert(osec->sectionIndex).second) 357 *to++ = osec->sectionIndex; 358 } 359 } 360 361 InputSectionBase *InputSection::getRelocatedSection() const { 362 if (!file || (type != SHT_RELA && type != SHT_REL)) 363 return nullptr; 364 ArrayRef<InputSectionBase *> sections = file->getSections(); 365 return sections[info]; 366 } 367 368 // This is used for -r and --emit-relocs. We can't use memcpy to copy 369 // relocations because we need to update symbol table offset and section index 370 // for each relocation. So we copy relocations one by one. 371 template <class ELFT, class RelTy> 372 void InputSection::copyRelocations(uint8_t *buf, ArrayRef<RelTy> rels) { 373 const TargetInfo &target = *elf::target; 374 InputSectionBase *sec = getRelocatedSection(); 375 376 for (const RelTy &rel : rels) { 377 RelType type = rel.getType(config->isMips64EL); 378 const ObjFile<ELFT> *file = getFile<ELFT>(); 379 Symbol &sym = file->getRelocTargetSym(rel); 380 381 auto *p = reinterpret_cast<typename ELFT::Rela *>(buf); 382 buf += sizeof(RelTy); 383 384 if (RelTy::IsRela) 385 p->r_addend = getAddend<ELFT>(rel); 386 387 // Output section VA is zero for -r, so r_offset is an offset within the 388 // section, but for --emit-relocs it is a virtual address. 389 p->r_offset = sec->getVA(rel.r_offset); 390 p->setSymbolAndType(in.symTab->getSymbolIndex(&sym), type, 391 config->isMips64EL); 392 393 if (sym.type == STT_SECTION) { 394 // We combine multiple section symbols into only one per 395 // section. This means we have to update the addend. That is 396 // trivial for Elf_Rela, but for Elf_Rel we have to write to the 397 // section data. We do that by adding to the Relocation vector. 398 399 // .eh_frame is horribly special and can reference discarded sections. To 400 // avoid having to parse and recreate .eh_frame, we just replace any 401 // relocation in it pointing to discarded sections with R_*_NONE, which 402 // hopefully creates a frame that is ignored at runtime. Also, don't warn 403 // on .gcc_except_table and debug sections. 404 // 405 // See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc 406 auto *d = dyn_cast<Defined>(&sym); 407 if (!d) { 408 if (!isDebugSection(*sec) && sec->name != ".eh_frame" && 409 sec->name != ".gcc_except_table" && sec->name != ".got2" && 410 sec->name != ".toc") { 411 uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx; 412 Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx]; 413 warn("relocation refers to a discarded section: " + 414 CHECK(file->getObj().getSectionName(sec), file) + 415 "\n>>> referenced by " + getObjMsg(p->r_offset)); 416 } 417 p->setSymbolAndType(0, 0, false); 418 continue; 419 } 420 SectionBase *section = d->section; 421 if (!section->isLive()) { 422 p->setSymbolAndType(0, 0, false); 423 continue; 424 } 425 426 int64_t addend = getAddend<ELFT>(rel); 427 const uint8_t *bufLoc = sec->data().begin() + rel.r_offset; 428 if (!RelTy::IsRela) 429 addend = target.getImplicitAddend(bufLoc, type); 430 431 if (config->emachine == EM_MIPS && 432 target.getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) { 433 // Some MIPS relocations depend on "gp" value. By default, 434 // this value has 0x7ff0 offset from a .got section. But 435 // relocatable files produced by a compiler or a linker 436 // might redefine this default value and we must use it 437 // for a calculation of the relocation result. When we 438 // generate EXE or DSO it's trivial. Generating a relocatable 439 // output is more difficult case because the linker does 440 // not calculate relocations in this mode and loses 441 // individual "gp" values used by each input object file. 442 // As a workaround we add the "gp" value to the relocation 443 // addend and save it back to the file. 444 addend += sec->getFile<ELFT>()->mipsGp0; 445 } 446 447 if (RelTy::IsRela) 448 p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr; 449 else if (config->relocatable && type != target.noneRel) 450 sec->relocations.push_back({R_ABS, type, rel.r_offset, addend, &sym}); 451 } else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 && 452 p->r_addend >= 0x8000 && sec->file->ppc32Got2) { 453 // Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24 454 // indicates that r30 is relative to the input section .got2 455 // (r_addend>=0x8000), after linking, r30 should be relative to the output 456 // section .got2 . To compensate for the shift, adjust r_addend by 457 // ppc32Got->outSecOff. 458 p->r_addend += sec->file->ppc32Got2->outSecOff; 459 } 460 } 461 } 462 463 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak 464 // references specially. The general rule is that the value of the symbol in 465 // this context is the address of the place P. A further special case is that 466 // branch relocations to an undefined weak reference resolve to the next 467 // instruction. 468 static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a, 469 uint32_t p) { 470 switch (type) { 471 // Unresolved branch relocations to weak references resolve to next 472 // instruction, this will be either 2 or 4 bytes on from P. 473 case R_ARM_THM_JUMP8: 474 case R_ARM_THM_JUMP11: 475 return p + 2 + a; 476 case R_ARM_CALL: 477 case R_ARM_JUMP24: 478 case R_ARM_PC24: 479 case R_ARM_PLT32: 480 case R_ARM_PREL31: 481 case R_ARM_THM_JUMP19: 482 case R_ARM_THM_JUMP24: 483 return p + 4 + a; 484 case R_ARM_THM_CALL: 485 // We don't want an interworking BLX to ARM 486 return p + 5 + a; 487 // Unresolved non branch pc-relative relocations 488 // R_ARM_TARGET2 which can be resolved relatively is not present as it never 489 // targets a weak-reference. 490 case R_ARM_MOVW_PREL_NC: 491 case R_ARM_MOVT_PREL: 492 case R_ARM_REL32: 493 case R_ARM_THM_ALU_PREL_11_0: 494 case R_ARM_THM_MOVW_PREL_NC: 495 case R_ARM_THM_MOVT_PREL: 496 case R_ARM_THM_PC12: 497 return p + a; 498 // p + a is unrepresentable as negative immediates can't be encoded. 499 case R_ARM_THM_PC8: 500 return p; 501 } 502 llvm_unreachable("ARM pc-relative relocation expected\n"); 503 } 504 505 // The comment above getARMUndefinedRelativeWeakVA applies to this function. 506 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) { 507 switch (type) { 508 // Unresolved branch relocations to weak references resolve to next 509 // instruction, this is 4 bytes on from P. 510 case R_AARCH64_CALL26: 511 case R_AARCH64_CONDBR19: 512 case R_AARCH64_JUMP26: 513 case R_AARCH64_TSTBR14: 514 return p + 4; 515 // Unresolved non branch pc-relative relocations 516 case R_AARCH64_PREL16: 517 case R_AARCH64_PREL32: 518 case R_AARCH64_PREL64: 519 case R_AARCH64_ADR_PREL_LO21: 520 case R_AARCH64_LD_PREL_LO19: 521 case R_AARCH64_PLT32: 522 return p; 523 } 524 llvm_unreachable("AArch64 pc-relative relocation expected\n"); 525 } 526 527 static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) { 528 switch (type) { 529 case R_RISCV_BRANCH: 530 case R_RISCV_JAL: 531 case R_RISCV_CALL: 532 case R_RISCV_CALL_PLT: 533 case R_RISCV_RVC_BRANCH: 534 case R_RISCV_RVC_JUMP: 535 return p; 536 default: 537 return 0; 538 } 539 } 540 541 // ARM SBREL relocations are of the form S + A - B where B is the static base 542 // The ARM ABI defines base to be "addressing origin of the output segment 543 // defining the symbol S". We defined the "addressing origin"/static base to be 544 // the base of the PT_LOAD segment containing the Sym. 545 // The procedure call standard only defines a Read Write Position Independent 546 // RWPI variant so in practice we should expect the static base to be the base 547 // of the RW segment. 548 static uint64_t getARMStaticBase(const Symbol &sym) { 549 OutputSection *os = sym.getOutputSection(); 550 if (!os || !os->ptLoad || !os->ptLoad->firstSec) 551 fatal("SBREL relocation to " + sym.getName() + " without static base"); 552 return os->ptLoad->firstSec->addr; 553 } 554 555 // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually 556 // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA 557 // is calculated using PCREL_HI20's symbol. 558 // 559 // This function returns the R_RISCV_PCREL_HI20 relocation from 560 // R_RISCV_PCREL_LO12's symbol and addend. 561 static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) { 562 const Defined *d = cast<Defined>(sym); 563 if (!d->section) { 564 error("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " + 565 sym->getName()); 566 return nullptr; 567 } 568 InputSection *isec = cast<InputSection>(d->section); 569 570 if (addend != 0) 571 warn("non-zero addend in R_RISCV_PCREL_LO12 relocation to " + 572 isec->getObjMsg(d->value) + " is ignored"); 573 574 // Relocations are sorted by offset, so we can use std::equal_range to do 575 // binary search. 576 Relocation r; 577 r.offset = d->value; 578 auto range = 579 std::equal_range(isec->relocations.begin(), isec->relocations.end(), r, 580 [](const Relocation &lhs, const Relocation &rhs) { 581 return lhs.offset < rhs.offset; 582 }); 583 584 for (auto it = range.first; it != range.second; ++it) 585 if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 || 586 it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20) 587 return &*it; 588 589 error("R_RISCV_PCREL_LO12 relocation points to " + isec->getObjMsg(d->value) + 590 " without an associated R_RISCV_PCREL_HI20 relocation"); 591 return nullptr; 592 } 593 594 // A TLS symbol's virtual address is relative to the TLS segment. Add a 595 // target-specific adjustment to produce a thread-pointer-relative offset. 596 static int64_t getTlsTpOffset(const Symbol &s) { 597 // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0. 598 if (&s == ElfSym::tlsModuleBase) 599 return 0; 600 601 // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2 602 // while most others use Variant 1. At run time TP will be aligned to p_align. 603 604 // Variant 1. TP will be followed by an optional gap (which is the size of 2 605 // pointers on ARM/AArch64, 0 on other targets), followed by alignment 606 // padding, then the static TLS blocks. The alignment padding is added so that 607 // (TP + gap + padding) is congruent to p_vaddr modulo p_align. 608 // 609 // Variant 2. Static TLS blocks, followed by alignment padding are placed 610 // before TP. The alignment padding is added so that (TP - padding - 611 // p_memsz) is congruent to p_vaddr modulo p_align. 612 PhdrEntry *tls = Out::tlsPhdr; 613 switch (config->emachine) { 614 // Variant 1. 615 case EM_ARM: 616 case EM_AARCH64: 617 return s.getVA(0) + config->wordsize * 2 + 618 ((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1)); 619 case EM_MIPS: 620 case EM_PPC: 621 case EM_PPC64: 622 // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is 623 // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library 624 // data and 0xf000 of the program's TLS segment. 625 return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000; 626 case EM_RISCV: 627 return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)); 628 629 // Variant 2. 630 case EM_HEXAGON: 631 case EM_SPARCV9: 632 case EM_386: 633 case EM_X86_64: 634 return s.getVA(0) - tls->p_memsz - 635 ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1)); 636 default: 637 llvm_unreachable("unhandled Config->EMachine"); 638 } 639 } 640 641 uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type, 642 int64_t a, uint64_t p, 643 const Symbol &sym, RelExpr expr) { 644 switch (expr) { 645 case R_ABS: 646 case R_DTPREL: 647 case R_RELAX_TLS_LD_TO_LE_ABS: 648 case R_RELAX_GOT_PC_NOPIC: 649 case R_RISCV_ADD: 650 return sym.getVA(a); 651 case R_ADDEND: 652 return a; 653 case R_ARM_SBREL: 654 return sym.getVA(a) - getARMStaticBase(sym); 655 case R_GOT: 656 case R_RELAX_TLS_GD_TO_IE_ABS: 657 return sym.getGotVA() + a; 658 case R_GOTONLY_PC: 659 return in.got->getVA() + a - p; 660 case R_GOTPLTONLY_PC: 661 return in.gotPlt->getVA() + a - p; 662 case R_GOTREL: 663 case R_PPC64_RELAX_TOC: 664 return sym.getVA(a) - in.got->getVA(); 665 case R_GOTPLTREL: 666 return sym.getVA(a) - in.gotPlt->getVA(); 667 case R_GOTPLT: 668 case R_RELAX_TLS_GD_TO_IE_GOTPLT: 669 return sym.getGotVA() + a - in.gotPlt->getVA(); 670 case R_TLSLD_GOT_OFF: 671 case R_GOT_OFF: 672 case R_RELAX_TLS_GD_TO_IE_GOT_OFF: 673 return sym.getGotOffset() + a; 674 case R_AARCH64_GOT_PAGE_PC: 675 case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC: 676 return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p); 677 case R_AARCH64_GOT_PAGE: 678 return sym.getGotVA() + a - getAArch64Page(in.got->getVA()); 679 case R_GOT_PC: 680 case R_RELAX_TLS_GD_TO_IE: 681 return sym.getGotVA() + a - p; 682 case R_MIPS_GOTREL: 683 return sym.getVA(a) - in.mipsGot->getGp(file); 684 case R_MIPS_GOT_GP: 685 return in.mipsGot->getGp(file) + a; 686 case R_MIPS_GOT_GP_PC: { 687 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target 688 // is _gp_disp symbol. In that case we should use the following 689 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at 690 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 691 // microMIPS variants of these relocations use slightly different 692 // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi() 693 // to correctly handle less-significant bit of the microMIPS symbol. 694 uint64_t v = in.mipsGot->getGp(file) + a - p; 695 if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16) 696 v += 4; 697 if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16) 698 v -= 1; 699 return v; 700 } 701 case R_MIPS_GOT_LOCAL_PAGE: 702 // If relocation against MIPS local symbol requires GOT entry, this entry 703 // should be initialized by 'page address'. This address is high 16-bits 704 // of sum the symbol's value and the addend. 705 return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) - 706 in.mipsGot->getGp(file); 707 case R_MIPS_GOT_OFF: 708 case R_MIPS_GOT_OFF32: 709 // In case of MIPS if a GOT relocation has non-zero addend this addend 710 // should be applied to the GOT entry content not to the GOT entry offset. 711 // That is why we use separate expression type. 712 return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) - 713 in.mipsGot->getGp(file); 714 case R_MIPS_TLSGD: 715 return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) - 716 in.mipsGot->getGp(file); 717 case R_MIPS_TLSLD: 718 return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) - 719 in.mipsGot->getGp(file); 720 case R_AARCH64_PAGE_PC: { 721 uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a); 722 return getAArch64Page(val) - getAArch64Page(p); 723 } 724 case R_RISCV_PC_INDIRECT: { 725 if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a)) 726 return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(), 727 *hiRel->sym, hiRel->expr); 728 return 0; 729 } 730 case R_PC: 731 case R_ARM_PCA: { 732 uint64_t dest; 733 if (expr == R_ARM_PCA) 734 // Some PC relative ARM (Thumb) relocations align down the place. 735 p = p & 0xfffffffc; 736 if (sym.isUndefined()) { 737 // On ARM and AArch64 a branch to an undefined weak resolves to the next 738 // instruction, otherwise the place. On RISCV, resolve an undefined weak 739 // to the same instruction to cause an infinite loop (making the user 740 // aware of the issue) while ensuring no overflow. 741 // Note: if the symbol is hidden, its binding has been converted to local, 742 // so we just check isUndefined() here. 743 if (config->emachine == EM_ARM) 744 dest = getARMUndefinedRelativeWeakVA(type, a, p); 745 else if (config->emachine == EM_AARCH64) 746 dest = getAArch64UndefinedRelativeWeakVA(type, p) + a; 747 else if (config->emachine == EM_PPC) 748 dest = p; 749 else if (config->emachine == EM_RISCV) 750 dest = getRISCVUndefinedRelativeWeakVA(type, p) + a; 751 else 752 dest = sym.getVA(a); 753 } else { 754 dest = sym.getVA(a); 755 } 756 return dest - p; 757 } 758 case R_PLT: 759 return sym.getPltVA() + a; 760 case R_PLT_PC: 761 case R_PPC64_CALL_PLT: 762 return sym.getPltVA() + a - p; 763 case R_PLT_GOTPLT: 764 return sym.getPltVA() + a - in.gotPlt->getVA(); 765 case R_PPC32_PLTREL: 766 // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30 767 // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for 768 // target VA computation. 769 return sym.getPltVA() - p; 770 case R_PPC64_CALL: { 771 uint64_t symVA = sym.getVA(a); 772 // If we have an undefined weak symbol, we might get here with a symbol 773 // address of zero. That could overflow, but the code must be unreachable, 774 // so don't bother doing anything at all. 775 if (!symVA) 776 return 0; 777 778 // PPC64 V2 ABI describes two entry points to a function. The global entry 779 // point is used for calls where the caller and callee (may) have different 780 // TOC base pointers and r2 needs to be modified to hold the TOC base for 781 // the callee. For local calls the caller and callee share the same 782 // TOC base and so the TOC pointer initialization code should be skipped by 783 // branching to the local entry point. 784 return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther); 785 } 786 case R_PPC64_TOCBASE: 787 return getPPC64TocBase() + a; 788 case R_RELAX_GOT_PC: 789 case R_PPC64_RELAX_GOT_PC: 790 return sym.getVA(a) - p; 791 case R_RELAX_TLS_GD_TO_LE: 792 case R_RELAX_TLS_IE_TO_LE: 793 case R_RELAX_TLS_LD_TO_LE: 794 case R_TPREL: 795 // It is not very clear what to return if the symbol is undefined. With 796 // --noinhibit-exec, even a non-weak undefined reference may reach here. 797 // Just return A, which matches R_ABS, and the behavior of some dynamic 798 // loaders. 799 if (sym.isUndefined()) 800 return a; 801 return getTlsTpOffset(sym) + a; 802 case R_RELAX_TLS_GD_TO_LE_NEG: 803 case R_TPREL_NEG: 804 if (sym.isUndefined()) 805 return a; 806 return -getTlsTpOffset(sym) + a; 807 case R_SIZE: 808 return sym.getSize() + a; 809 case R_TLSDESC: 810 return in.got->getTlsDescAddr(sym) + a; 811 case R_TLSDESC_PC: 812 return in.got->getTlsDescAddr(sym) + a - p; 813 case R_TLSDESC_GOTPLT: 814 return in.got->getTlsDescAddr(sym) + a - in.gotPlt->getVA(); 815 case R_AARCH64_TLSDESC_PAGE: 816 return getAArch64Page(in.got->getTlsDescAddr(sym) + a) - getAArch64Page(p); 817 case R_TLSGD_GOT: 818 return in.got->getGlobalDynOffset(sym) + a; 819 case R_TLSGD_GOTPLT: 820 return in.got->getGlobalDynAddr(sym) + a - in.gotPlt->getVA(); 821 case R_TLSGD_PC: 822 return in.got->getGlobalDynAddr(sym) + a - p; 823 case R_TLSLD_GOTPLT: 824 return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA(); 825 case R_TLSLD_GOT: 826 return in.got->getTlsIndexOff() + a; 827 case R_TLSLD_PC: 828 return in.got->getTlsIndexVA() + a - p; 829 default: 830 llvm_unreachable("invalid expression"); 831 } 832 } 833 834 // This function applies relocations to sections without SHF_ALLOC bit. 835 // Such sections are never mapped to memory at runtime. Debug sections are 836 // an example. Relocations in non-alloc sections are much easier to 837 // handle than in allocated sections because it will never need complex 838 // treatment such as GOT or PLT (because at runtime no one refers them). 839 // So, we handle relocations for non-alloc sections directly in this 840 // function as a performance optimization. 841 template <class ELFT, class RelTy> 842 void InputSection::relocateNonAlloc(uint8_t *buf, ArrayRef<RelTy> rels) { 843 const unsigned bits = sizeof(typename ELFT::uint) * 8; 844 const TargetInfo &target = *elf::target; 845 const bool isDebug = isDebugSection(*this); 846 const bool isDebugLocOrRanges = 847 isDebug && (name == ".debug_loc" || name == ".debug_ranges"); 848 const bool isDebugLine = isDebug && name == ".debug_line"; 849 Optional<uint64_t> tombstone; 850 for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc)) 851 if (patAndValue.first.match(this->name)) { 852 tombstone = patAndValue.second; 853 break; 854 } 855 856 for (const RelTy &rel : rels) { 857 RelType type = rel.getType(config->isMips64EL); 858 859 // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations 860 // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed 861 // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we 862 // need to keep this bug-compatible code for a while. 863 if (config->emachine == EM_386 && type == R_386_GOTPC) 864 continue; 865 866 uint64_t offset = rel.r_offset; 867 uint8_t *bufLoc = buf + offset; 868 int64_t addend = getAddend<ELFT>(rel); 869 if (!RelTy::IsRela) 870 addend += target.getImplicitAddend(bufLoc, type); 871 872 Symbol &sym = getFile<ELFT>()->getRelocTargetSym(rel); 873 RelExpr expr = target.getRelExpr(type, sym, bufLoc); 874 if (expr == R_NONE) 875 continue; 876 877 if (tombstone || 878 (isDebug && (type == target.symbolicRel || expr == R_DTPREL))) { 879 // Resolve relocations in .debug_* referencing (discarded symbols or ICF 880 // folded section symbols) to a tombstone value. Resolving to addend is 881 // unsatisfactory because the result address range may collide with a 882 // valid range of low address, or leave multiple CUs claiming ownership of 883 // the same range of code, which may confuse consumers. 884 // 885 // To address the problems, we use -1 as a tombstone value for most 886 // .debug_* sections. We have to ignore the addend because we don't want 887 // to resolve an address attribute (which may have a non-zero addend) to 888 // -1+addend (wrap around to a low address). 889 // 890 // R_DTPREL type relocations represent an offset into the dynamic thread 891 // vector. The computed value is st_value plus a non-negative offset. 892 // Negative values are invalid, so -1 can be used as the tombstone value. 893 // 894 // If the referenced symbol is discarded (made Undefined), or the 895 // section defining the referenced symbol is garbage collected, 896 // sym.getOutputSection() is nullptr. `ds->folded` catches the ICF folded 897 // case. However, resolving a relocation in .debug_line to -1 would stop 898 // debugger users from setting breakpoints on the folded-in function, so 899 // exclude .debug_line. 900 // 901 // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value 902 // (base address selection entry), use 1 (which is used by GNU ld for 903 // .debug_ranges). 904 // 905 // TODO To reduce disruption, we use 0 instead of -1 as the tombstone 906 // value. Enable -1 in a future release. 907 auto *ds = dyn_cast<Defined>(&sym); 908 if (!sym.getOutputSection() || (ds && ds->folded && !isDebugLine)) { 909 // If -z dead-reloc-in-nonalloc= is specified, respect it. 910 const uint64_t value = tombstone ? SignExtend64<bits>(*tombstone) 911 : (isDebugLocOrRanges ? 1 : 0); 912 target.relocateNoSym(bufLoc, type, value); 913 continue; 914 } 915 } 916 917 // For a relocatable link, only tombstone values are applied. 918 if (config->relocatable) 919 continue; 920 921 if (expr == R_SIZE) { 922 target.relocateNoSym(bufLoc, type, 923 SignExtend64<bits>(sym.getSize() + addend)); 924 continue; 925 } 926 927 // R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC 928 // sections. 929 if (expr == R_ABS || expr == R_DTPREL || expr == R_GOTPLTREL || 930 expr == R_RISCV_ADD) { 931 target.relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend))); 932 continue; 933 } 934 935 std::string msg = getLocation(offset) + ": has non-ABS relocation " + 936 toString(type) + " against symbol '" + toString(sym) + 937 "'"; 938 if (expr != R_PC && expr != R_ARM_PCA) { 939 error(msg); 940 return; 941 } 942 943 // If the control reaches here, we found a PC-relative relocation in a 944 // non-ALLOC section. Since non-ALLOC section is not loaded into memory 945 // at runtime, the notion of PC-relative doesn't make sense here. So, 946 // this is a usage error. However, GNU linkers historically accept such 947 // relocations without any errors and relocate them as if they were at 948 // address 0. For bug-compatibilty, we accept them with warnings. We 949 // know Steel Bank Common Lisp as of 2018 have this bug. 950 warn(msg); 951 target.relocateNoSym( 952 bufLoc, type, 953 SignExtend64<bits>(sym.getVA(addend - offset - outSecOff))); 954 } 955 } 956 957 // This is used when '-r' is given. 958 // For REL targets, InputSection::copyRelocations() may store artificial 959 // relocations aimed to update addends. They are handled in relocateAlloc() 960 // for allocatable sections, and this function does the same for 961 // non-allocatable sections, such as sections with debug information. 962 static void relocateNonAllocForRelocatable(InputSection *sec, uint8_t *buf) { 963 const unsigned bits = config->is64 ? 64 : 32; 964 965 for (const Relocation &rel : sec->relocations) { 966 // InputSection::copyRelocations() adds only R_ABS relocations. 967 assert(rel.expr == R_ABS); 968 uint8_t *bufLoc = buf + rel.offset; 969 uint64_t targetVA = SignExtend64(rel.sym->getVA(rel.addend), bits); 970 target->relocate(bufLoc, rel, targetVA); 971 } 972 } 973 974 template <class ELFT> 975 void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) { 976 if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack)) 977 adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd); 978 979 if (flags & SHF_ALLOC) { 980 relocateAlloc(buf, bufEnd); 981 return; 982 } 983 984 auto *sec = cast<InputSection>(this); 985 if (config->relocatable) 986 relocateNonAllocForRelocatable(sec, buf); 987 // For a relocatable link, also call relocateNonAlloc() to rewrite applicable 988 // locations with tombstone values. 989 const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>(); 990 if (rels.areRelocsRel()) 991 sec->relocateNonAlloc<ELFT>(buf, rels.rels); 992 else 993 sec->relocateNonAlloc<ELFT>(buf, rels.relas); 994 } 995 996 void InputSectionBase::relocateAlloc(uint8_t *buf, uint8_t *bufEnd) { 997 assert(flags & SHF_ALLOC); 998 const unsigned bits = config->wordsize * 8; 999 const TargetInfo &target = *elf::target; 1000 uint64_t lastPPCRelaxedRelocOff = UINT64_C(-1); 1001 AArch64Relaxer aarch64relaxer(relocations); 1002 for (size_t i = 0, size = relocations.size(); i != size; ++i) { 1003 const Relocation &rel = relocations[i]; 1004 if (rel.expr == R_NONE) 1005 continue; 1006 uint64_t offset = rel.offset; 1007 uint8_t *bufLoc = buf + offset; 1008 1009 uint64_t secAddr = getOutputSection()->addr; 1010 if (auto *sec = dyn_cast<InputSection>(this)) 1011 secAddr += sec->outSecOff; 1012 const uint64_t addrLoc = secAddr + offset; 1013 const uint64_t targetVA = 1014 SignExtend64(getRelocTargetVA(file, rel.type, rel.addend, addrLoc, 1015 *rel.sym, rel.expr), 1016 bits); 1017 switch (rel.expr) { 1018 case R_RELAX_GOT_PC: 1019 case R_RELAX_GOT_PC_NOPIC: 1020 target.relaxGot(bufLoc, rel, targetVA); 1021 break; 1022 case R_AARCH64_GOT_PAGE_PC: 1023 if (i + 1 < size && aarch64relaxer.tryRelaxAdrpLdr( 1024 rel, relocations[i + 1], secAddr, buf)) { 1025 ++i; 1026 continue; 1027 } 1028 target.relocate(bufLoc, rel, targetVA); 1029 break; 1030 case R_AARCH64_PAGE_PC: 1031 if (i + 1 < size && aarch64relaxer.tryRelaxAdrpAdd( 1032 rel, relocations[i + 1], secAddr, buf)) { 1033 ++i; 1034 continue; 1035 } 1036 target.relocate(bufLoc, rel, targetVA); 1037 break; 1038 case R_PPC64_RELAX_GOT_PC: { 1039 // The R_PPC64_PCREL_OPT relocation must appear immediately after 1040 // R_PPC64_GOT_PCREL34 in the relocations table at the same offset. 1041 // We can only relax R_PPC64_PCREL_OPT if we have also relaxed 1042 // the associated R_PPC64_GOT_PCREL34 since only the latter has an 1043 // associated symbol. So save the offset when relaxing R_PPC64_GOT_PCREL34 1044 // and only relax the other if the saved offset matches. 1045 if (rel.type == R_PPC64_GOT_PCREL34) 1046 lastPPCRelaxedRelocOff = offset; 1047 if (rel.type == R_PPC64_PCREL_OPT && offset != lastPPCRelaxedRelocOff) 1048 break; 1049 target.relaxGot(bufLoc, rel, targetVA); 1050 break; 1051 } 1052 case R_PPC64_RELAX_TOC: 1053 // rel.sym refers to the STT_SECTION symbol associated to the .toc input 1054 // section. If an R_PPC64_TOC16_LO (.toc + addend) references the TOC 1055 // entry, there may be R_PPC64_TOC16_HA not paired with 1056 // R_PPC64_TOC16_LO_DS. Don't relax. This loses some relaxation 1057 // opportunities but is safe. 1058 if (ppc64noTocRelax.count({rel.sym, rel.addend}) || 1059 !tryRelaxPPC64TocIndirection(rel, bufLoc)) 1060 target.relocate(bufLoc, rel, targetVA); 1061 break; 1062 case R_RELAX_TLS_IE_TO_LE: 1063 target.relaxTlsIeToLe(bufLoc, rel, targetVA); 1064 break; 1065 case R_RELAX_TLS_LD_TO_LE: 1066 case R_RELAX_TLS_LD_TO_LE_ABS: 1067 target.relaxTlsLdToLe(bufLoc, rel, targetVA); 1068 break; 1069 case R_RELAX_TLS_GD_TO_LE: 1070 case R_RELAX_TLS_GD_TO_LE_NEG: 1071 target.relaxTlsGdToLe(bufLoc, rel, targetVA); 1072 break; 1073 case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC: 1074 case R_RELAX_TLS_GD_TO_IE: 1075 case R_RELAX_TLS_GD_TO_IE_ABS: 1076 case R_RELAX_TLS_GD_TO_IE_GOT_OFF: 1077 case R_RELAX_TLS_GD_TO_IE_GOTPLT: 1078 target.relaxTlsGdToIe(bufLoc, rel, targetVA); 1079 break; 1080 case R_PPC64_CALL: 1081 // If this is a call to __tls_get_addr, it may be part of a TLS 1082 // sequence that has been relaxed and turned into a nop. In this 1083 // case, we don't want to handle it as a call. 1084 if (read32(bufLoc) == 0x60000000) // nop 1085 break; 1086 1087 // Patch a nop (0x60000000) to a ld. 1088 if (rel.sym->needsTocRestore) { 1089 // gcc/gfortran 5.4, 6.3 and earlier versions do not add nop for 1090 // recursive calls even if the function is preemptible. This is not 1091 // wrong in the common case where the function is not preempted at 1092 // runtime. Just ignore. 1093 if ((bufLoc + 8 > bufEnd || read32(bufLoc + 4) != 0x60000000) && 1094 rel.sym->file != file) { 1095 // Use substr(6) to remove the "__plt_" prefix. 1096 errorOrWarn(getErrorLocation(bufLoc) + "call to " + 1097 lld::toString(*rel.sym).substr(6) + 1098 " lacks nop, can't restore toc"); 1099 break; 1100 } 1101 write32(bufLoc + 4, 0xe8410018); // ld %r2, 24(%r1) 1102 } 1103 target.relocate(bufLoc, rel, targetVA); 1104 break; 1105 default: 1106 target.relocate(bufLoc, rel, targetVA); 1107 break; 1108 } 1109 } 1110 1111 // Apply jumpInstrMods. jumpInstrMods are created when the opcode of 1112 // a jmp insn must be modified to shrink the jmp insn or to flip the jmp 1113 // insn. This is primarily used to relax and optimize jumps created with 1114 // basic block sections. 1115 if (jumpInstrMod) { 1116 target.applyJumpInstrMod(buf + jumpInstrMod->offset, jumpInstrMod->original, 1117 jumpInstrMod->size); 1118 } 1119 } 1120 1121 // For each function-defining prologue, find any calls to __morestack, 1122 // and replace them with calls to __morestack_non_split. 1123 static void switchMorestackCallsToMorestackNonSplit( 1124 DenseSet<Defined *> &prologues, 1125 SmallVector<Relocation *, 0> &morestackCalls) { 1126 1127 // If the target adjusted a function's prologue, all calls to 1128 // __morestack inside that function should be switched to 1129 // __morestack_non_split. 1130 Symbol *moreStackNonSplit = symtab->find("__morestack_non_split"); 1131 if (!moreStackNonSplit) { 1132 error("mixing split-stack objects requires a definition of " 1133 "__morestack_non_split"); 1134 return; 1135 } 1136 1137 // Sort both collections to compare addresses efficiently. 1138 llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) { 1139 return l->offset < r->offset; 1140 }); 1141 std::vector<Defined *> functions(prologues.begin(), prologues.end()); 1142 llvm::sort(functions, [](const Defined *l, const Defined *r) { 1143 return l->value < r->value; 1144 }); 1145 1146 auto it = morestackCalls.begin(); 1147 for (Defined *f : functions) { 1148 // Find the first call to __morestack within the function. 1149 while (it != morestackCalls.end() && (*it)->offset < f->value) 1150 ++it; 1151 // Adjust all calls inside the function. 1152 while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) { 1153 (*it)->sym = moreStackNonSplit; 1154 ++it; 1155 } 1156 } 1157 } 1158 1159 static bool enclosingPrologueAttempted(uint64_t offset, 1160 const DenseSet<Defined *> &prologues) { 1161 for (Defined *f : prologues) 1162 if (f->value <= offset && offset < f->value + f->size) 1163 return true; 1164 return false; 1165 } 1166 1167 // If a function compiled for split stack calls a function not 1168 // compiled for split stack, then the caller needs its prologue 1169 // adjusted to ensure that the called function will have enough stack 1170 // available. Find those functions, and adjust their prologues. 1171 template <class ELFT> 1172 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf, 1173 uint8_t *end) { 1174 DenseSet<Defined *> prologues; 1175 SmallVector<Relocation *, 0> morestackCalls; 1176 1177 for (Relocation &rel : relocations) { 1178 // Ignore calls into the split-stack api. 1179 if (rel.sym->getName().startswith("__morestack")) { 1180 if (rel.sym->getName().equals("__morestack")) 1181 morestackCalls.push_back(&rel); 1182 continue; 1183 } 1184 1185 // A relocation to non-function isn't relevant. Sometimes 1186 // __morestack is not marked as a function, so this check comes 1187 // after the name check. 1188 if (rel.sym->type != STT_FUNC) 1189 continue; 1190 1191 // If the callee's-file was compiled with split stack, nothing to do. In 1192 // this context, a "Defined" symbol is one "defined by the binary currently 1193 // being produced". So an "undefined" symbol might be provided by a shared 1194 // library. It is not possible to tell how such symbols were compiled, so be 1195 // conservative. 1196 if (Defined *d = dyn_cast<Defined>(rel.sym)) 1197 if (InputSection *isec = cast_or_null<InputSection>(d->section)) 1198 if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack) 1199 continue; 1200 1201 if (enclosingPrologueAttempted(rel.offset, prologues)) 1202 continue; 1203 1204 if (Defined *f = getEnclosingFunction(rel.offset)) { 1205 prologues.insert(f); 1206 if (target->adjustPrologueForCrossSplitStack(buf + f->value, end, 1207 f->stOther)) 1208 continue; 1209 if (!getFile<ELFT>()->someNoSplitStack) 1210 error(lld::toString(this) + ": " + f->getName() + 1211 " (with -fsplit-stack) calls " + rel.sym->getName() + 1212 " (without -fsplit-stack), but couldn't adjust its prologue"); 1213 } 1214 } 1215 1216 if (target->needsMoreStackNonSplit) 1217 switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls); 1218 } 1219 1220 template <class ELFT> void InputSection::writeTo(uint8_t *buf) { 1221 if (auto *s = dyn_cast<SyntheticSection>(this)) { 1222 s->writeTo(buf); 1223 return; 1224 } 1225 1226 if (LLVM_UNLIKELY(type == SHT_NOBITS)) 1227 return; 1228 // If -r or --emit-relocs is given, then an InputSection 1229 // may be a relocation section. 1230 if (LLVM_UNLIKELY(type == SHT_RELA)) { 1231 copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rela>()); 1232 return; 1233 } 1234 if (LLVM_UNLIKELY(type == SHT_REL)) { 1235 copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rel>()); 1236 return; 1237 } 1238 1239 // If -r is given, we may have a SHT_GROUP section. 1240 if (LLVM_UNLIKELY(type == SHT_GROUP)) { 1241 copyShtGroup<ELFT>(buf); 1242 return; 1243 } 1244 1245 // If this is a compressed section, uncompress section contents directly 1246 // to the buffer. 1247 if (uncompressedSize >= 0) { 1248 size_t size = uncompressedSize; 1249 if (Error e = zlib::uncompress(toStringRef(rawData), (char *)buf, size)) 1250 fatal(toString(this) + 1251 ": uncompress failed: " + llvm::toString(std::move(e))); 1252 uint8_t *bufEnd = buf + size; 1253 relocate<ELFT>(buf, bufEnd); 1254 return; 1255 } 1256 1257 // Copy section contents from source object file to output file 1258 // and then apply relocations. 1259 memcpy(buf, rawData.data(), rawData.size()); 1260 relocate<ELFT>(buf, buf + rawData.size()); 1261 } 1262 1263 void InputSection::replace(InputSection *other) { 1264 alignment = std::max(alignment, other->alignment); 1265 1266 // When a section is replaced with another section that was allocated to 1267 // another partition, the replacement section (and its associated sections) 1268 // need to be placed in the main partition so that both partitions will be 1269 // able to access it. 1270 if (partition != other->partition) { 1271 partition = 1; 1272 for (InputSection *isec : dependentSections) 1273 isec->partition = 1; 1274 } 1275 1276 other->repl = repl; 1277 other->markDead(); 1278 } 1279 1280 template <class ELFT> 1281 EhInputSection::EhInputSection(ObjFile<ELFT> &f, 1282 const typename ELFT::Shdr &header, 1283 StringRef name) 1284 : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {} 1285 1286 SyntheticSection *EhInputSection::getParent() const { 1287 return cast_or_null<SyntheticSection>(parent); 1288 } 1289 1290 // Returns the index of the first relocation that points to a region between 1291 // Begin and Begin+Size. 1292 template <class IntTy, class RelTy> 1293 static unsigned getReloc(IntTy begin, IntTy size, const ArrayRef<RelTy> &rels, 1294 unsigned &relocI) { 1295 // Start search from RelocI for fast access. That works because the 1296 // relocations are sorted in .eh_frame. 1297 for (unsigned n = rels.size(); relocI < n; ++relocI) { 1298 const RelTy &rel = rels[relocI]; 1299 if (rel.r_offset < begin) 1300 continue; 1301 1302 if (rel.r_offset < begin + size) 1303 return relocI; 1304 return -1; 1305 } 1306 return -1; 1307 } 1308 1309 // .eh_frame is a sequence of CIE or FDE records. 1310 // This function splits an input section into records and returns them. 1311 template <class ELFT> void EhInputSection::split() { 1312 const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>(); 1313 // getReloc expects the relocations to be sorted by r_offset. See the comment 1314 // in scanRelocs. 1315 if (rels.areRelocsRel()) { 1316 SmallVector<typename ELFT::Rel, 0> storage; 1317 split<ELFT>(sortRels(rels.rels, storage)); 1318 } else { 1319 SmallVector<typename ELFT::Rela, 0> storage; 1320 split<ELFT>(sortRels(rels.relas, storage)); 1321 } 1322 } 1323 1324 template <class ELFT, class RelTy> 1325 void EhInputSection::split(ArrayRef<RelTy> rels) { 1326 ArrayRef<uint8_t> d = rawData; 1327 const char *msg = nullptr; 1328 unsigned relI = 0; 1329 while (!d.empty()) { 1330 if (d.size() < 4) { 1331 msg = "CIE/FDE too small"; 1332 break; 1333 } 1334 uint64_t size = endian::read32<ELFT::TargetEndianness>(d.data()); 1335 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead, 1336 // but we do not support that format yet. 1337 if (size == UINT32_MAX) { 1338 msg = "CIE/FDE too large"; 1339 break; 1340 } 1341 size += 4; 1342 if (size > d.size()) { 1343 msg = "CIE/FDE ends past the end of the section"; 1344 break; 1345 } 1346 1347 uint64_t off = d.data() - rawData.data(); 1348 pieces.emplace_back(off, this, size, getReloc(off, size, rels, relI)); 1349 d = d.slice(size); 1350 } 1351 if (msg) 1352 errorOrWarn("corrupted .eh_frame: " + Twine(msg) + "\n>>> defined in " + 1353 getObjMsg(d.data() - rawData.data())); 1354 } 1355 1356 static size_t findNull(StringRef s, size_t entSize) { 1357 for (unsigned i = 0, n = s.size(); i != n; i += entSize) { 1358 const char *b = s.begin() + i; 1359 if (std::all_of(b, b + entSize, [](char c) { return c == 0; })) 1360 return i; 1361 } 1362 llvm_unreachable(""); 1363 } 1364 1365 SyntheticSection *MergeInputSection::getParent() const { 1366 return cast_or_null<SyntheticSection>(parent); 1367 } 1368 1369 // Split SHF_STRINGS section. Such section is a sequence of 1370 // null-terminated strings. 1371 void MergeInputSection::splitStrings(StringRef s, size_t entSize) { 1372 const bool live = !(flags & SHF_ALLOC) || !config->gcSections; 1373 const char *p = s.data(), *end = s.data() + s.size(); 1374 if (!std::all_of(end - entSize, end, [](char c) { return c == 0; })) 1375 fatal(toString(this) + ": string is not null terminated"); 1376 if (entSize == 1) { 1377 // Optimize the common case. 1378 do { 1379 size_t size = strlen(p) + 1; 1380 pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live); 1381 p += size; 1382 } while (p != end); 1383 } else { 1384 do { 1385 size_t size = findNull(StringRef(p, end - p), entSize) + entSize; 1386 pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live); 1387 p += size; 1388 } while (p != end); 1389 } 1390 } 1391 1392 // Split non-SHF_STRINGS section. Such section is a sequence of 1393 // fixed size records. 1394 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data, 1395 size_t entSize) { 1396 size_t size = data.size(); 1397 assert((size % entSize) == 0); 1398 const bool live = !(flags & SHF_ALLOC) || !config->gcSections; 1399 1400 pieces.resize_for_overwrite(size / entSize); 1401 for (size_t i = 0, j = 0; i != size; i += entSize, j++) 1402 pieces[j] = {i, (uint32_t)xxHash64(data.slice(i, entSize)), live}; 1403 } 1404 1405 template <class ELFT> 1406 MergeInputSection::MergeInputSection(ObjFile<ELFT> &f, 1407 const typename ELFT::Shdr &header, 1408 StringRef name) 1409 : InputSectionBase(f, header, name, InputSectionBase::Merge) {} 1410 1411 MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type, 1412 uint64_t entsize, ArrayRef<uint8_t> data, 1413 StringRef name) 1414 : InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0, 1415 /*Alignment*/ entsize, data, name, SectionBase::Merge) {} 1416 1417 // This function is called after we obtain a complete list of input sections 1418 // that need to be linked. This is responsible to split section contents 1419 // into small chunks for further processing. 1420 // 1421 // Note that this function is called from parallelForEach. This must be 1422 // thread-safe (i.e. no memory allocation from the pools). 1423 void MergeInputSection::splitIntoPieces() { 1424 assert(pieces.empty()); 1425 1426 if (flags & SHF_STRINGS) 1427 splitStrings(toStringRef(data()), entsize); 1428 else 1429 splitNonStrings(data(), entsize); 1430 } 1431 1432 SectionPiece *MergeInputSection::getSectionPiece(uint64_t offset) { 1433 if (this->data().size() <= offset) 1434 fatal(toString(this) + ": offset is outside the section"); 1435 1436 // If Offset is not at beginning of a section piece, it is not in the map. 1437 // In that case we need to do a binary search of the original section piece vector. 1438 auto it = partition_point( 1439 pieces, [=](SectionPiece p) { return p.inputOff <= offset; }); 1440 return &it[-1]; 1441 } 1442 1443 // Returns the offset in an output section for a given input offset. 1444 // Because contents of a mergeable section is not contiguous in output, 1445 // it is not just an addition to a base output offset. 1446 uint64_t MergeInputSection::getParentOffset(uint64_t offset) const { 1447 // If Offset is not at beginning of a section piece, it is not in the map. 1448 // In that case we need to search from the original section piece vector. 1449 const SectionPiece &piece = *getSectionPiece(offset); 1450 uint64_t addend = offset - piece.inputOff; 1451 return piece.outputOff + addend; 1452 } 1453 1454 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &, 1455 StringRef); 1456 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &, 1457 StringRef); 1458 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &, 1459 StringRef); 1460 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &, 1461 StringRef); 1462 1463 template void InputSection::writeTo<ELF32LE>(uint8_t *); 1464 template void InputSection::writeTo<ELF32BE>(uint8_t *); 1465 template void InputSection::writeTo<ELF64LE>(uint8_t *); 1466 template void InputSection::writeTo<ELF64BE>(uint8_t *); 1467 1468 template RelsOrRelas<ELF32LE> InputSectionBase::relsOrRelas<ELF32LE>() const; 1469 template RelsOrRelas<ELF32BE> InputSectionBase::relsOrRelas<ELF32BE>() const; 1470 template RelsOrRelas<ELF64LE> InputSectionBase::relsOrRelas<ELF64LE>() const; 1471 template RelsOrRelas<ELF64BE> InputSectionBase::relsOrRelas<ELF64BE>() const; 1472 1473 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &, 1474 const ELF32LE::Shdr &, StringRef); 1475 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &, 1476 const ELF32BE::Shdr &, StringRef); 1477 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &, 1478 const ELF64LE::Shdr &, StringRef); 1479 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &, 1480 const ELF64BE::Shdr &, StringRef); 1481 1482 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &, 1483 const ELF32LE::Shdr &, StringRef); 1484 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &, 1485 const ELF32BE::Shdr &, StringRef); 1486 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &, 1487 const ELF64LE::Shdr &, StringRef); 1488 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &, 1489 const ELF64BE::Shdr &, StringRef); 1490 1491 template void EhInputSection::split<ELF32LE>(); 1492 template void EhInputSection::split<ELF32BE>(); 1493 template void EhInputSection::split<ELF64LE>(); 1494 template void EhInputSection::split<ELF64BE>(); 1495