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