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