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