1 //===- InputSection.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "InputSection.h" 11 #include "Config.h" 12 #include "EhFrame.h" 13 #include "Error.h" 14 #include "InputFiles.h" 15 #include "LinkerScript.h" 16 #include "Memory.h" 17 #include "OutputSections.h" 18 #include "Relocations.h" 19 #include "SyntheticSections.h" 20 #include "Target.h" 21 #include "Thunks.h" 22 #include "llvm/Object/Decompressor.h" 23 #include "llvm/Support/Compression.h" 24 #include "llvm/Support/Endian.h" 25 #include <mutex> 26 27 using namespace llvm; 28 using namespace llvm::ELF; 29 using namespace llvm::object; 30 using namespace llvm::support; 31 using namespace llvm::support::endian; 32 33 using namespace lld; 34 using namespace lld::elf; 35 36 // Returns a string to construct an error message. 37 template <class ELFT> 38 std::string lld::toString(const InputSectionBase<ELFT> *Sec) { 39 // File can be absent if section is synthetic. 40 std::string FileName = 41 Sec->getFile() ? Sec->getFile()->getName() : "<internal>"; 42 return (FileName + ":(" + Sec->Name + ")").str(); 43 } 44 45 template <class ELFT> 46 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File, 47 const typename ELFT::Shdr *Hdr) { 48 if (!File || Hdr->sh_type == SHT_NOBITS) 49 return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size); 50 return check(File->getObj().getSectionContents(Hdr)); 51 } 52 53 template <class ELFT> 54 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File, 55 uintX_t Flags, uint32_t Type, 56 uintX_t Entsize, uint32_t Link, 57 uint32_t Info, uintX_t Addralign, 58 ArrayRef<uint8_t> Data, StringRef Name, 59 Kind SectionKind) 60 : InputSectionData(SectionKind, Name, Data, 61 !Config->GcSections || !(Flags & SHF_ALLOC)), 62 File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link), 63 Info(Info), Repl(this) { 64 NumRelocations = 0; 65 AreRelocsRela = false; 66 67 // The ELF spec states that a value of 0 means the section has 68 // no alignment constraits. 69 uint64_t V = std::max<uint64_t>(Addralign, 1); 70 if (!isPowerOf2_64(V)) 71 fatal(toString(File) + ": section sh_addralign is not a power of 2"); 72 73 // We reject object files having insanely large alignments even though 74 // they are allowed by the spec. I think 4GB is a reasonable limitation. 75 // We might want to relax this in the future. 76 if (V > UINT32_MAX) 77 fatal(toString(File) + ": section sh_addralign is too large"); 78 Alignment = V; 79 } 80 81 template <class ELFT> 82 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File, 83 const Elf_Shdr *Hdr, StringRef Name, 84 Kind SectionKind) 85 : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK, Hdr->sh_type, 86 Hdr->sh_entsize, Hdr->sh_link, Hdr->sh_info, 87 Hdr->sh_addralign, getSectionContents(File, Hdr), Name, 88 SectionKind) { 89 this->Offset = Hdr->sh_offset; 90 } 91 92 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const { 93 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this)) 94 return S->getSize(); 95 96 return Data.size(); 97 } 98 99 template <class ELFT> 100 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const { 101 switch (kind()) { 102 case Regular: 103 return cast<InputSection<ELFT>>(this)->OutSecOff + Offset; 104 case Synthetic: 105 // For synthetic sections we treat offset -1 as the end of the section. 106 // The same approach is used for synthetic symbols (DefinedSynthetic). 107 return cast<InputSection<ELFT>>(this)->OutSecOff + 108 (Offset == uintX_t(-1) ? getSize() : Offset); 109 case EHFrame: 110 // The file crtbeginT.o has relocations pointing to the start of an empty 111 // .eh_frame that is known to be the first in the link. It does that to 112 // identify the start of the output .eh_frame. 113 return Offset; 114 case Merge: 115 const MergeInputSection<ELFT> *MS = cast<MergeInputSection<ELFT>>(this); 116 if (MS->MergeSec) 117 return MS->MergeSec->OutSecOff + MS->getOffset(Offset); 118 return MS->getOffset(Offset); 119 } 120 llvm_unreachable("invalid section kind"); 121 } 122 123 template <class ELFT> 124 OutputSectionBase *InputSectionBase<ELFT>::getOutputSection() const { 125 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(this)) 126 return MS->MergeSec ? MS->MergeSec->OutSec : nullptr; 127 return OutSec; 128 } 129 130 // Uncompress section contents. Note that this function is called 131 // from parallel_for_each, so it must be thread-safe. 132 template <class ELFT> void InputSectionBase<ELFT>::uncompress() { 133 Decompressor Dec = check(Decompressor::create( 134 Name, toStringRef(Data), ELFT::TargetEndianness == llvm::support::little, 135 ELFT::Is64Bits)); 136 137 size_t Size = Dec.getDecompressedSize(); 138 char *OutputBuf; 139 { 140 static std::mutex Mu; 141 std::lock_guard<std::mutex> Lock(Mu); 142 OutputBuf = BAlloc.Allocate<char>(Size); 143 } 144 145 if (Error E = Dec.decompress({OutputBuf, Size})) 146 fatal(toString(this) + 147 ": decompress failed: " + llvm::toString(std::move(E))); 148 Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size); 149 } 150 151 template <class ELFT> 152 typename ELFT::uint 153 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const { 154 return getOffset(Sym.Value); 155 } 156 157 template <class ELFT> 158 InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const { 159 if ((Flags & SHF_LINK_ORDER) && Link != 0) 160 return getFile()->getSections()[Link]; 161 return nullptr; 162 } 163 164 // Returns a source location string. Used to construct an error message. 165 template <class ELFT> 166 std::string InputSectionBase<ELFT>::getLocation(typename ELFT::uint Offset) { 167 // First check if we can get desired values from debugging information. 168 std::string LineInfo = File->getLineInfo(this, Offset); 169 if (!LineInfo.empty()) 170 return LineInfo; 171 172 // File->SourceFile contains STT_FILE symbol that contains a 173 // source file name. If it's missing, we use an object file name. 174 std::string SrcFile = File->SourceFile; 175 if (SrcFile.empty()) 176 SrcFile = toString(File); 177 178 // Find a function symbol that encloses a given location. 179 for (SymbolBody *B : File->getSymbols()) 180 if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B)) 181 if (D->Section == this && D->Type == STT_FUNC) 182 if (D->Value <= Offset && Offset < D->Value + D->Size) 183 return SrcFile + ":(function " + toString(*D) + ")"; 184 185 // If there's no symbol, print out the offset in the section. 186 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str(); 187 } 188 189 template <class ELFT> 190 InputSection<ELFT>::InputSection() : InputSectionBase<ELFT>() {} 191 192 template <class ELFT> 193 InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type, 194 uintX_t Addralign, ArrayRef<uint8_t> Data, 195 StringRef Name, Kind K) 196 : InputSectionBase<ELFT>(nullptr, Flags, Type, 197 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign, 198 Data, Name, K) {} 199 200 template <class ELFT> 201 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F, 202 const Elf_Shdr *Header, StringRef Name) 203 : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {} 204 205 template <class ELFT> 206 bool InputSection<ELFT>::classof(const InputSectionData *S) { 207 return S->kind() == Base::Regular || S->kind() == Base::Synthetic; 208 } 209 210 template <class ELFT> 211 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() { 212 assert(this->Type == SHT_RELA || this->Type == SHT_REL); 213 ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections(); 214 return Sections[this->Info]; 215 } 216 217 // This is used for -r and --emit-relocs. We can't use memcpy to copy 218 // relocations because we need to update symbol table offset and section index 219 // for each relocation. So we copy relocations one by one. 220 template <class ELFT> 221 template <class RelTy> 222 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) { 223 InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection(); 224 225 // Loop is slow and have complexity O(N*M), where N - amount of 226 // relocations and M - amount of symbols in symbol table. 227 // That happens because getSymbolIndex(...) call below performs 228 // simple linear search. 229 for (const RelTy &Rel : Rels) { 230 uint32_t Type = Rel.getType(Config->Mips64EL); 231 SymbolBody &Body = this->File->getRelocTargetSym(Rel); 232 233 Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf); 234 Buf += sizeof(RelTy); 235 236 if (Config->Rela) 237 P->r_addend = getAddend<ELFT>(Rel); 238 239 // Output section VA is zero for -r, so r_offset is an offset within the 240 // section, but for --emit-relocs it is an virtual address. 241 P->r_offset = RelocatedSection->OutSec->Addr + 242 RelocatedSection->getOffset(Rel.r_offset); 243 P->setSymbolAndType(In<ELFT>::SymTab->getSymbolIndex(&Body), Type, 244 Config->Mips64EL); 245 } 246 } 247 248 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A, 249 uint32_t P) { 250 switch (Type) { 251 case R_ARM_THM_JUMP11: 252 return P + 2; 253 case R_ARM_CALL: 254 case R_ARM_JUMP24: 255 case R_ARM_PC24: 256 case R_ARM_PLT32: 257 case R_ARM_PREL31: 258 case R_ARM_THM_JUMP19: 259 case R_ARM_THM_JUMP24: 260 return P + 4; 261 case R_ARM_THM_CALL: 262 // We don't want an interworking BLX to ARM 263 return P + 5; 264 default: 265 return A; 266 } 267 } 268 269 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A, 270 uint64_t P) { 271 switch (Type) { 272 case R_AARCH64_CALL26: 273 case R_AARCH64_CONDBR19: 274 case R_AARCH64_JUMP26: 275 case R_AARCH64_TSTBR14: 276 return P + 4; 277 default: 278 return A; 279 } 280 } 281 282 template <class ELFT> 283 static typename ELFT::uint 284 getRelocTargetVA(uint32_t Type, typename ELFT::uint A, typename ELFT::uint P, 285 const SymbolBody &Body, RelExpr Expr) { 286 switch (Expr) { 287 case R_HINT: 288 case R_TLSDESC_CALL: 289 llvm_unreachable("cannot relocate hint relocs"); 290 case R_TLSLD: 291 return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize(); 292 case R_TLSLD_PC: 293 return In<ELFT>::Got->getTlsIndexVA() + A - P; 294 case R_PPC_TOC: 295 return getPPC64TocBase() + A; 296 case R_TLSGD: 297 return In<ELFT>::Got->getGlobalDynOffset(Body) + A - 298 In<ELFT>::Got->getSize(); 299 case R_TLSGD_PC: 300 return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P; 301 case R_TLSDESC: 302 return In<ELFT>::Got->getGlobalDynAddr(Body) + A; 303 case R_TLSDESC_PAGE: 304 return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) - 305 getAArch64Page(P); 306 case R_PLT: 307 return Body.getPltVA<ELFT>() + A; 308 case R_PLT_PC: 309 case R_PPC_PLT_OPD: 310 return Body.getPltVA<ELFT>() + A - P; 311 case R_SIZE: 312 return Body.getSize<ELFT>() + A; 313 case R_GOTREL: 314 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA(); 315 case R_GOTREL_FROM_END: 316 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA() - 317 In<ELFT>::Got->getSize(); 318 case R_RELAX_TLS_GD_TO_IE_END: 319 case R_GOT_FROM_END: 320 return Body.getGotOffset<ELFT>() + A - In<ELFT>::Got->getSize(); 321 case R_RELAX_TLS_GD_TO_IE_ABS: 322 case R_GOT: 323 return Body.getGotVA<ELFT>() + A; 324 case R_RELAX_TLS_GD_TO_IE_PAGE_PC: 325 case R_GOT_PAGE_PC: 326 return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P); 327 case R_RELAX_TLS_GD_TO_IE: 328 case R_GOT_PC: 329 return Body.getGotVA<ELFT>() + A - P; 330 case R_GOTONLY_PC: 331 return In<ELFT>::Got->getVA() + A - P; 332 case R_GOTONLY_PC_FROM_END: 333 return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize(); 334 case R_RELAX_TLS_LD_TO_LE: 335 case R_RELAX_TLS_IE_TO_LE: 336 case R_RELAX_TLS_GD_TO_LE: 337 case R_TLS: 338 // A weak undefined TLS symbol resolves to the base of the TLS 339 // block, i.e. gets a value of zero. If we pass --gc-sections to 340 // lld and .tbss is not referenced, it gets reclaimed and we don't 341 // create a TLS program header. Therefore, we resolve this 342 // statically to zero. 343 if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) && 344 Body.symbol()->isWeak()) 345 return 0; 346 if (Target->TcbSize) 347 return Body.getVA<ELFT>(A) + 348 alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align); 349 return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz; 350 case R_RELAX_TLS_GD_TO_LE_NEG: 351 case R_NEG_TLS: 352 return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A); 353 case R_ABS: 354 case R_RELAX_GOT_PC_NOPIC: 355 return Body.getVA<ELFT>(A); 356 case R_GOT_OFF: 357 return Body.getGotOffset<ELFT>() + A; 358 case R_MIPS_GOT_LOCAL_PAGE: 359 // If relocation against MIPS local symbol requires GOT entry, this entry 360 // should be initialized by 'page address'. This address is high 16-bits 361 // of sum the symbol's value and the addend. 362 return In<ELFT>::MipsGot->getVA() + 363 In<ELFT>::MipsGot->getPageEntryOffset(Body, A) - 364 In<ELFT>::MipsGot->getGp(); 365 case R_MIPS_GOT_OFF: 366 case R_MIPS_GOT_OFF32: 367 // In case of MIPS if a GOT relocation has non-zero addend this addend 368 // should be applied to the GOT entry content not to the GOT entry offset. 369 // That is why we use separate expression type. 370 return In<ELFT>::MipsGot->getVA() + 371 In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) - 372 In<ELFT>::MipsGot->getGp(); 373 case R_MIPS_GOTREL: 374 return Body.getVA<ELFT>(A) - In<ELFT>::MipsGot->getGp(); 375 case R_MIPS_TLSGD: 376 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() + 377 In<ELFT>::MipsGot->getGlobalDynOffset(Body) - 378 In<ELFT>::MipsGot->getGp(); 379 case R_MIPS_TLSLD: 380 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() + 381 In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp(); 382 case R_PPC_OPD: { 383 uint64_t SymVA = Body.getVA<ELFT>(A); 384 // If we have an undefined weak symbol, we might get here with a symbol 385 // address of zero. That could overflow, but the code must be unreachable, 386 // so don't bother doing anything at all. 387 if (!SymVA) 388 return 0; 389 if (Out<ELF64BE>::Opd) { 390 // If this is a local call, and we currently have the address of a 391 // function-descriptor, get the underlying code address instead. 392 uint64_t OpdStart = Out<ELF64BE>::Opd->Addr; 393 uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->Size; 394 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd; 395 if (InOpd) 396 SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]); 397 } 398 return SymVA - P; 399 } 400 case R_PC: 401 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) { 402 // On ARM and AArch64 a branch to an undefined weak resolves to the 403 // next instruction, otherwise the place. 404 if (Config->EMachine == EM_ARM) 405 return getARMUndefinedRelativeWeakVA(Type, A, P); 406 if (Config->EMachine == EM_AARCH64) 407 return getAArch64UndefinedRelativeWeakVA(Type, A, P); 408 } 409 case R_RELAX_GOT_PC: 410 return Body.getVA<ELFT>(A) - P; 411 case R_PLT_PAGE_PC: 412 case R_PAGE_PC: 413 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) 414 return getAArch64Page(A); 415 return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P); 416 } 417 llvm_unreachable("Invalid expression"); 418 } 419 420 // This function applies relocations to sections without SHF_ALLOC bit. 421 // Such sections are never mapped to memory at runtime. Debug sections are 422 // an example. Relocations in non-alloc sections are much easier to 423 // handle than in allocated sections because it will never need complex 424 // treatement such as GOT or PLT (because at runtime no one refers them). 425 // So, we handle relocations for non-alloc sections directly in this 426 // function as a performance optimization. 427 template <class ELFT> 428 template <class RelTy> 429 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) { 430 for (const RelTy &Rel : Rels) { 431 uint32_t Type = Rel.getType(Config->Mips64EL); 432 uintX_t Offset = this->getOffset(Rel.r_offset); 433 uint8_t *BufLoc = Buf + Offset; 434 uintX_t Addend = getAddend<ELFT>(Rel); 435 if (!RelTy::IsRela) 436 Addend += Target->getImplicitAddend(BufLoc, Type); 437 438 SymbolBody &Sym = this->File->getRelocTargetSym(Rel); 439 if (Target->getRelExpr(Type, Sym) != R_ABS) { 440 error(this->getLocation(Offset) + ": has non-ABS reloc"); 441 return; 442 } 443 444 uintX_t AddrLoc = this->OutSec->Addr + Offset; 445 uint64_t SymVA = 0; 446 if (!Sym.isTls() || Out<ELFT>::TlsPhdr) 447 SymVA = SignExtend64<sizeof(uintX_t) * 8>( 448 getRelocTargetVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS)); 449 Target->relocateOne(BufLoc, Type, SymVA); 450 } 451 } 452 453 template <class ELFT> 454 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) { 455 // scanReloc function in Writer.cpp constructs Relocations 456 // vector only for SHF_ALLOC'ed sections. For other sections, 457 // we handle relocations directly here. 458 auto *IS = dyn_cast<InputSection<ELFT>>(this); 459 if (IS && !(IS->Flags & SHF_ALLOC)) { 460 if (IS->AreRelocsRela) 461 IS->relocateNonAlloc(Buf, IS->relas()); 462 else 463 IS->relocateNonAlloc(Buf, IS->rels()); 464 return; 465 } 466 467 const unsigned Bits = sizeof(uintX_t) * 8; 468 for (const Relocation &Rel : Relocations) { 469 uintX_t Offset = getOffset(Rel.Offset); 470 uint8_t *BufLoc = Buf + Offset; 471 uint32_t Type = Rel.Type; 472 uintX_t A = Rel.Addend; 473 474 uintX_t AddrLoc = OutSec->Addr + Offset; 475 RelExpr Expr = Rel.Expr; 476 uint64_t TargetVA = SignExtend64<Bits>( 477 getRelocTargetVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr)); 478 479 switch (Expr) { 480 case R_RELAX_GOT_PC: 481 case R_RELAX_GOT_PC_NOPIC: 482 Target->relaxGot(BufLoc, TargetVA); 483 break; 484 case R_RELAX_TLS_IE_TO_LE: 485 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA); 486 break; 487 case R_RELAX_TLS_LD_TO_LE: 488 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA); 489 break; 490 case R_RELAX_TLS_GD_TO_LE: 491 case R_RELAX_TLS_GD_TO_LE_NEG: 492 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA); 493 break; 494 case R_RELAX_TLS_GD_TO_IE: 495 case R_RELAX_TLS_GD_TO_IE_ABS: 496 case R_RELAX_TLS_GD_TO_IE_PAGE_PC: 497 case R_RELAX_TLS_GD_TO_IE_END: 498 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA); 499 break; 500 case R_PPC_PLT_OPD: 501 // Patch a nop (0x60000000) to a ld. 502 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000) 503 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1) 504 // fallthrough 505 default: 506 Target->relocateOne(BufLoc, Type, TargetVA); 507 break; 508 } 509 } 510 } 511 512 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) { 513 if (this->Type == SHT_NOBITS) 514 return; 515 516 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this)) { 517 S->writeTo(Buf + OutSecOff); 518 return; 519 } 520 521 // If -r or --emit-relocs is given, then an InputSection 522 // may be a relocation section. 523 if (this->Type == SHT_RELA) { 524 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rela>()); 525 return; 526 } 527 if (this->Type == SHT_REL) { 528 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rel>()); 529 return; 530 } 531 532 // Copy section contents from source object file to output file. 533 ArrayRef<uint8_t> Data = this->Data; 534 memcpy(Buf + OutSecOff, Data.data(), Data.size()); 535 536 // Iterate over all relocation sections that apply to this section. 537 uint8_t *BufEnd = Buf + OutSecOff + Data.size(); 538 this->relocate(Buf, BufEnd); 539 } 540 541 template <class ELFT> 542 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) { 543 this->Alignment = std::max(this->Alignment, Other->Alignment); 544 Other->Repl = this->Repl; 545 Other->Live = false; 546 } 547 548 template <class ELFT> 549 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F, 550 const Elf_Shdr *Header, StringRef Name) 551 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) { 552 // Mark .eh_frame sections as live by default because there are 553 // usually no relocations that point to .eh_frames. Otherwise, 554 // the garbage collector would drop all .eh_frame sections. 555 this->Live = true; 556 } 557 558 template <class ELFT> 559 bool EhInputSection<ELFT>::classof(const InputSectionData *S) { 560 return S->kind() == InputSectionBase<ELFT>::EHFrame; 561 } 562 563 // Returns the index of the first relocation that points to a region between 564 // Begin and Begin+Size. 565 template <class IntTy, class RelTy> 566 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels, 567 unsigned &RelocI) { 568 // Start search from RelocI for fast access. That works because the 569 // relocations are sorted in .eh_frame. 570 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) { 571 const RelTy &Rel = Rels[RelocI]; 572 if (Rel.r_offset < Begin) 573 continue; 574 575 if (Rel.r_offset < Begin + Size) 576 return RelocI; 577 return -1; 578 } 579 return -1; 580 } 581 582 // .eh_frame is a sequence of CIE or FDE records. 583 // This function splits an input section into records and returns them. 584 template <class ELFT> void EhInputSection<ELFT>::split() { 585 // Early exit if already split. 586 if (!this->Pieces.empty()) 587 return; 588 589 if (this->NumRelocations) { 590 if (this->AreRelocsRela) 591 split(this->relas()); 592 else 593 split(this->rels()); 594 return; 595 } 596 split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr)); 597 } 598 599 template <class ELFT> 600 template <class RelTy> 601 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) { 602 ArrayRef<uint8_t> Data = this->Data; 603 unsigned RelI = 0; 604 for (size_t Off = 0, End = Data.size(); Off != End;) { 605 size_t Size = readEhRecordSize<ELFT>(this, Off); 606 this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI)); 607 // The empty record is the end marker. 608 if (Size == 4) 609 break; 610 Off += Size; 611 } 612 } 613 614 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) { 615 // Optimize the common case. 616 StringRef S((const char *)A.data(), A.size()); 617 if (EntSize == 1) 618 return S.find(0); 619 620 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) { 621 const char *B = S.begin() + I; 622 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; })) 623 return I; 624 } 625 return StringRef::npos; 626 } 627 628 // Split SHF_STRINGS section. Such section is a sequence of 629 // null-terminated strings. 630 template <class ELFT> 631 void MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data, 632 size_t EntSize) { 633 size_t Off = 0; 634 bool IsAlloc = this->Flags & SHF_ALLOC; 635 while (!Data.empty()) { 636 size_t End = findNull(Data, EntSize); 637 if (End == StringRef::npos) 638 fatal(toString(this) + ": string is not null terminated"); 639 size_t Size = End + EntSize; 640 Pieces.emplace_back(Off, !IsAlloc); 641 Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size)))); 642 Data = Data.slice(Size); 643 Off += Size; 644 } 645 } 646 647 // Split non-SHF_STRINGS section. Such section is a sequence of 648 // fixed size records. 649 template <class ELFT> 650 void MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data, 651 size_t EntSize) { 652 size_t Size = Data.size(); 653 assert((Size % EntSize) == 0); 654 bool IsAlloc = this->Flags & SHF_ALLOC; 655 for (unsigned I = 0, N = Size; I != N; I += EntSize) { 656 Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize)))); 657 Pieces.emplace_back(I, !IsAlloc); 658 } 659 } 660 661 template <class ELFT> 662 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F, 663 const Elf_Shdr *Header, 664 StringRef Name) 665 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {} 666 667 // This function is called after we obtain a complete list of input sections 668 // that need to be linked. This is responsible to split section contents 669 // into small chunks for further processing. 670 // 671 // Note that this function is called from parallel_for_each. This must be 672 // thread-safe (i.e. no memory allocation from the pools). 673 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() { 674 ArrayRef<uint8_t> Data = this->Data; 675 uintX_t EntSize = this->Entsize; 676 if (this->Flags & SHF_STRINGS) 677 splitStrings(Data, EntSize); 678 else 679 splitNonStrings(Data, EntSize); 680 681 if (Config->GcSections && (this->Flags & SHF_ALLOC)) 682 for (uintX_t Off : LiveOffsets) 683 this->getSectionPiece(Off)->Live = true; 684 } 685 686 template <class ELFT> 687 bool MergeInputSection<ELFT>::classof(const InputSectionData *S) { 688 return S->kind() == InputSectionBase<ELFT>::Merge; 689 } 690 691 // Do binary search to get a section piece at a given input offset. 692 template <class ELFT> 693 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) { 694 auto *This = static_cast<const MergeInputSection<ELFT> *>(this); 695 return const_cast<SectionPiece *>(This->getSectionPiece(Offset)); 696 } 697 698 template <class It, class T, class Compare> 699 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) { 700 size_t Size = std::distance(First, Last); 701 assert(Size != 0); 702 while (Size != 1) { 703 size_t H = Size / 2; 704 const It MI = First + H; 705 Size -= H; 706 First = Comp(Value, *MI) ? First : First + H; 707 } 708 return Comp(Value, *First) ? First : First + 1; 709 } 710 711 template <class ELFT> 712 const SectionPiece * 713 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const { 714 uintX_t Size = this->Data.size(); 715 if (Offset >= Size) 716 fatal(toString(this) + ": entry is past the end of the section"); 717 718 // Find the element this offset points to. 719 auto I = fastUpperBound( 720 Pieces.begin(), Pieces.end(), Offset, 721 [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; }); 722 --I; 723 return &*I; 724 } 725 726 // Returns the offset in an output section for a given input offset. 727 // Because contents of a mergeable section is not contiguous in output, 728 // it is not just an addition to a base output offset. 729 template <class ELFT> 730 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const { 731 // Initialize OffsetMap lazily. 732 std::call_once(InitOffsetMap, [&] { 733 OffsetMap.reserve(Pieces.size()); 734 for (const SectionPiece &Piece : Pieces) 735 OffsetMap[Piece.InputOff] = Piece.OutputOff; 736 }); 737 738 // Find a string starting at a given offset. 739 auto It = OffsetMap.find(Offset); 740 if (It != OffsetMap.end()) 741 return It->second; 742 743 if (!this->Live) 744 return 0; 745 746 // If Offset is not at beginning of a section piece, it is not in the map. 747 // In that case we need to search from the original section piece vector. 748 const SectionPiece &Piece = *this->getSectionPiece(Offset); 749 if (!Piece.Live) 750 return 0; 751 752 uintX_t Addend = Offset - Piece.InputOff; 753 return Piece.OutputOff + Addend; 754 } 755 756 template class elf::InputSectionBase<ELF32LE>; 757 template class elf::InputSectionBase<ELF32BE>; 758 template class elf::InputSectionBase<ELF64LE>; 759 template class elf::InputSectionBase<ELF64BE>; 760 761 template class elf::InputSection<ELF32LE>; 762 template class elf::InputSection<ELF32BE>; 763 template class elf::InputSection<ELF64LE>; 764 template class elf::InputSection<ELF64BE>; 765 766 template class elf::EhInputSection<ELF32LE>; 767 template class elf::EhInputSection<ELF32BE>; 768 template class elf::EhInputSection<ELF64LE>; 769 template class elf::EhInputSection<ELF64BE>; 770 771 template class elf::MergeInputSection<ELF32LE>; 772 template class elf::MergeInputSection<ELF32BE>; 773 template class elf::MergeInputSection<ELF64LE>; 774 template class elf::MergeInputSection<ELF64BE>; 775 776 template std::string lld::toString(const InputSectionBase<ELF32LE> *); 777 template std::string lld::toString(const InputSectionBase<ELF32BE> *); 778 template std::string lld::toString(const InputSectionBase<ELF64LE> *); 779 template std::string lld::toString(const InputSectionBase<ELF64BE> *); 780