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