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