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 "InputFiles.h" 14 #include "LinkerScript.h" 15 #include "OutputSections.h" 16 #include "Relocations.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/Object/Decompressor.h" 24 #include "llvm/Support/Compiler.h" 25 #include "llvm/Support/Compression.h" 26 #include "llvm/Support/Endian.h" 27 #include "llvm/Support/Threading.h" 28 #include "llvm/Support/xxhash.h" 29 #include <mutex> 30 31 using namespace llvm; 32 using namespace llvm::ELF; 33 using namespace llvm::object; 34 using namespace llvm::support; 35 using namespace llvm::support::endian; 36 using namespace llvm::sys; 37 38 using namespace lld; 39 using namespace lld::elf; 40 41 std::vector<InputSectionBase *> elf::InputSections; 42 43 // Returns a string to construct an error message. 44 std::string lld::toString(const InputSectionBase *Sec) { 45 return (toString(Sec->File) + ":(" + Sec->Name + ")").str(); 46 } 47 48 template <class ELFT> 49 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &File, 50 const typename ELFT::Shdr &Hdr) { 51 if (Hdr.sh_type == SHT_NOBITS) 52 return makeArrayRef<uint8_t>(nullptr, Hdr.sh_size); 53 return check(File.getObj().getSectionContents(&Hdr)); 54 } 55 56 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags, 57 uint32_t Type, uint64_t Entsize, 58 uint32_t Link, uint32_t Info, 59 uint32_t Alignment, ArrayRef<uint8_t> Data, 60 StringRef Name, Kind SectionKind) 61 : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info, 62 Link), 63 File(File), Data(Data) { 64 // In order to reduce memory allocation, we assume that mergeable 65 // sections are smaller than 4 GiB, which is not an unreasonable 66 // assumption as of 2017. 67 if (SectionKind == SectionBase::Merge && Data.size() > UINT32_MAX) 68 error(toString(this) + ": section too large"); 69 70 NumRelocations = 0; 71 AreRelocsRela = false; 72 73 // The ELF spec states that a value of 0 means the section has 74 // no alignment constraits. 75 uint32_t V = std::max<uint64_t>(Alignment, 1); 76 if (!isPowerOf2_64(V)) 77 fatal(toString(File) + ": section sh_addralign is not a power of 2"); 78 this->Alignment = V; 79 } 80 81 // Drop SHF_GROUP bit unless we are producing a re-linkable object file. 82 // SHF_GROUP is a marker that a section belongs to some comdat group. 83 // That flag doesn't make sense in an executable. 84 static uint64_t getFlags(uint64_t Flags) { 85 Flags &= ~(uint64_t)SHF_INFO_LINK; 86 if (!Config->Relocatable) 87 Flags &= ~(uint64_t)SHF_GROUP; 88 return Flags; 89 } 90 91 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of 92 // March 2017) fail to infer section types for sections starting with 93 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of 94 // SHF_INIT_ARRAY. As a result, the following assembler directive 95 // creates ".init_array.100" with SHT_PROGBITS, for example. 96 // 97 // .section .init_array.100, "aw" 98 // 99 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle 100 // incorrect inputs as if they were correct from the beginning. 101 static uint64_t getType(uint64_t Type, StringRef Name) { 102 if (Type == SHT_PROGBITS && Name.startswith(".init_array.")) 103 return SHT_INIT_ARRAY; 104 if (Type == SHT_PROGBITS && Name.startswith(".fini_array.")) 105 return SHT_FINI_ARRAY; 106 return Type; 107 } 108 109 template <class ELFT> 110 InputSectionBase::InputSectionBase(ObjFile<ELFT> &File, 111 const typename ELFT::Shdr &Hdr, 112 StringRef Name, Kind SectionKind) 113 : InputSectionBase(&File, getFlags(Hdr.sh_flags), 114 getType(Hdr.sh_type, Name), Hdr.sh_entsize, Hdr.sh_link, 115 Hdr.sh_info, Hdr.sh_addralign, 116 getSectionContents(File, Hdr), Name, SectionKind) { 117 // We reject object files having insanely large alignments even though 118 // they are allowed by the spec. I think 4GB is a reasonable limitation. 119 // We might want to relax this in the future. 120 if (Hdr.sh_addralign > UINT32_MAX) 121 fatal(toString(&File) + ": section sh_addralign is too large"); 122 } 123 124 size_t InputSectionBase::getSize() const { 125 if (auto *S = dyn_cast<SyntheticSection>(this)) 126 return S->getSize(); 127 128 return Data.size(); 129 } 130 131 uint64_t InputSectionBase::getOffsetInFile() const { 132 const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart(); 133 const uint8_t *SecStart = Data.begin(); 134 return SecStart - FileStart; 135 } 136 137 uint64_t SectionBase::getOffset(uint64_t Offset) const { 138 switch (kind()) { 139 case Output: { 140 auto *OS = cast<OutputSection>(this); 141 // For output sections we treat offset -1 as the end of the section. 142 return Offset == uint64_t(-1) ? OS->Size : Offset; 143 } 144 case Regular: 145 case Synthetic: 146 return cast<InputSection>(this)->getOffset(Offset); 147 case EHFrame: 148 // The file crtbeginT.o has relocations pointing to the start of an empty 149 // .eh_frame that is known to be the first in the link. It does that to 150 // identify the start of the output .eh_frame. 151 return Offset; 152 case Merge: 153 const MergeInputSection *MS = cast<MergeInputSection>(this); 154 if (InputSection *IS = MS->getParent()) 155 return IS->getOffset(MS->getParentOffset(Offset)); 156 return MS->getParentOffset(Offset); 157 } 158 llvm_unreachable("invalid section kind"); 159 } 160 161 uint64_t SectionBase::getVA(uint64_t Offset) const { 162 const OutputSection *Out = getOutputSection(); 163 return (Out ? Out->Addr : 0) + getOffset(Offset); 164 } 165 166 OutputSection *SectionBase::getOutputSection() { 167 InputSection *Sec; 168 if (auto *IS = dyn_cast<InputSection>(this)) 169 Sec = IS; 170 else if (auto *MS = dyn_cast<MergeInputSection>(this)) 171 Sec = MS->getParent(); 172 else if (auto *EH = dyn_cast<EhInputSection>(this)) 173 Sec = EH->getParent(); 174 else 175 return cast<OutputSection>(this); 176 return Sec ? Sec->getParent() : nullptr; 177 } 178 179 // Decompress section contents if required. Note that this function 180 // is called from parallelForEach, so it must be thread-safe. 181 void InputSectionBase::maybeDecompress() { 182 if (DecompressBuf) 183 return; 184 if (!(Flags & SHF_COMPRESSED) && !Name.startswith(".zdebug")) 185 return; 186 187 // Decompress a section. 188 Decompressor Dec = check(Decompressor::create(Name, toStringRef(Data), 189 Config->IsLE, Config->Is64)); 190 191 size_t Size = Dec.getDecompressedSize(); 192 DecompressBuf.reset(new char[Size + Name.size()]()); 193 if (Error E = Dec.decompress({DecompressBuf.get(), Size})) 194 fatal(toString(this) + 195 ": decompress failed: " + llvm::toString(std::move(E))); 196 197 Data = makeArrayRef((uint8_t *)DecompressBuf.get(), Size); 198 Flags &= ~(uint64_t)SHF_COMPRESSED; 199 200 // A section name may have been altered if compressed. If that's 201 // the case, restore the original name. (i.e. ".zdebug_" -> ".debug_") 202 if (Name.startswith(".zdebug")) { 203 DecompressBuf[Size] = '.'; 204 memcpy(&DecompressBuf[Size + 1], Name.data() + 2, Name.size() - 2); 205 Name = StringRef(&DecompressBuf[Size], Name.size() - 1); 206 } 207 } 208 209 InputSection *InputSectionBase::getLinkOrderDep() const { 210 assert(Link); 211 assert(Flags & SHF_LINK_ORDER); 212 return cast<InputSection>(File->getSections()[Link]); 213 } 214 215 // Returns a source location string. Used to construct an error message. 216 template <class ELFT> 217 std::string InputSectionBase::getLocation(uint64_t Offset) { 218 // We don't have file for synthetic sections. 219 if (getFile<ELFT>() == nullptr) 220 return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")") 221 .str(); 222 223 // First check if we can get desired values from debugging information. 224 std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset); 225 if (!LineInfo.empty()) 226 return LineInfo; 227 228 // File->SourceFile contains STT_FILE symbol that contains a 229 // source file name. If it's missing, we use an object file name. 230 std::string SrcFile = getFile<ELFT>()->SourceFile; 231 if (SrcFile.empty()) 232 SrcFile = toString(File); 233 234 // Find a function symbol that encloses a given location. 235 for (Symbol *B : File->getSymbols()) 236 if (auto *D = dyn_cast<Defined>(B)) 237 if (D->Section == this && D->Type == STT_FUNC) 238 if (D->Value <= Offset && Offset < D->Value + D->Size) 239 return SrcFile + ":(function " + toString(*D) + ")"; 240 241 // If there's no symbol, print out the offset in the section. 242 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str(); 243 } 244 245 // This function is intended to be used for constructing an error message. 246 // The returned message looks like this: 247 // 248 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42) 249 // 250 // Returns an empty string if there's no way to get line info. 251 std::string InputSectionBase::getSrcMsg(const Symbol &Sym, uint64_t Offset) { 252 // Synthetic sections don't have input files. 253 if (!File) 254 return ""; 255 return File->getSrcMsg(Sym, *this, Offset); 256 } 257 258 // Returns a filename string along with an optional section name. This 259 // function is intended to be used for constructing an error 260 // message. The returned message looks like this: 261 // 262 // path/to/foo.o:(function bar) 263 // 264 // or 265 // 266 // path/to/foo.o:(function bar) in archive path/to/bar.a 267 std::string InputSectionBase::getObjMsg(uint64_t Off) { 268 // Synthetic sections don't have input files. 269 if (!File) 270 return ("<internal>:(" + Name + "+0x" + utohexstr(Off) + ")").str(); 271 std::string Filename = File->getName(); 272 273 std::string Archive; 274 if (!File->ArchiveName.empty()) 275 Archive = " in archive " + File->ArchiveName; 276 277 // Find a symbol that encloses a given location. 278 for (Symbol *B : File->getSymbols()) 279 if (auto *D = dyn_cast<Defined>(B)) 280 if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size) 281 return Filename + ":(" + toString(*D) + ")" + Archive; 282 283 // If there's no symbol, print out the offset in the section. 284 return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive) 285 .str(); 286 } 287 288 InputSection InputSection::Discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), ""); 289 290 InputSection::InputSection(InputFile *F, uint64_t Flags, uint32_t Type, 291 uint32_t Alignment, ArrayRef<uint8_t> Data, 292 StringRef Name, Kind K) 293 : InputSectionBase(F, Flags, Type, 294 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data, 295 Name, K) {} 296 297 template <class ELFT> 298 InputSection::InputSection(ObjFile<ELFT> &F, const typename ELFT::Shdr &Header, 299 StringRef Name) 300 : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {} 301 302 bool InputSection::classof(const SectionBase *S) { 303 return S->kind() == SectionBase::Regular || 304 S->kind() == SectionBase::Synthetic; 305 } 306 307 OutputSection *InputSection::getParent() const { 308 return cast_or_null<OutputSection>(Parent); 309 } 310 311 // Copy SHT_GROUP section contents. Used only for the -r option. 312 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) { 313 // ELFT::Word is the 32-bit integral type in the target endianness. 314 typedef typename ELFT::Word u32; 315 ArrayRef<u32> From = getDataAs<u32>(); 316 auto *To = reinterpret_cast<u32 *>(Buf); 317 318 // The first entry is not a section number but a flag. 319 *To++ = From[0]; 320 321 // Adjust section numbers because section numbers in an input object 322 // files are different in the output. 323 ArrayRef<InputSectionBase *> Sections = File->getSections(); 324 for (uint32_t Idx : From.slice(1)) 325 *To++ = Sections[Idx]->getOutputSection()->SectionIndex; 326 } 327 328 InputSectionBase *InputSection::getRelocatedSection() const { 329 if (!File || (Type != SHT_RELA && Type != SHT_REL)) 330 return nullptr; 331 ArrayRef<InputSectionBase *> Sections = File->getSections(); 332 return Sections[Info]; 333 } 334 335 // This is used for -r and --emit-relocs. We can't use memcpy to copy 336 // relocations because we need to update symbol table offset and section index 337 // for each relocation. So we copy relocations one by one. 338 template <class ELFT, class RelTy> 339 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) { 340 InputSectionBase *Sec = getRelocatedSection(); 341 342 for (const RelTy &Rel : Rels) { 343 RelType Type = Rel.getType(Config->IsMips64EL); 344 Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel); 345 346 auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf); 347 Buf += sizeof(RelTy); 348 349 if (RelTy::IsRela) 350 P->r_addend = getAddend<ELFT>(Rel); 351 352 // Output section VA is zero for -r, so r_offset is an offset within the 353 // section, but for --emit-relocs it is an virtual address. 354 P->r_offset = Sec->getVA(Rel.r_offset); 355 P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Sym), Type, 356 Config->IsMips64EL); 357 358 if (Sym.Type == STT_SECTION) { 359 // We combine multiple section symbols into only one per 360 // section. This means we have to update the addend. That is 361 // trivial for Elf_Rela, but for Elf_Rel we have to write to the 362 // section data. We do that by adding to the Relocation vector. 363 364 // .eh_frame is horribly special and can reference discarded sections. To 365 // avoid having to parse and recreate .eh_frame, we just replace any 366 // relocation in it pointing to discarded sections with R_*_NONE, which 367 // hopefully creates a frame that is ignored at runtime. 368 auto *D = dyn_cast<Defined>(&Sym); 369 if (!D) { 370 error("STT_SECTION symbol should be defined"); 371 continue; 372 } 373 SectionBase *Section = D->Section; 374 if (Section == &InputSection::Discarded) { 375 P->setSymbolAndType(0, 0, false); 376 continue; 377 } 378 379 int64_t Addend = getAddend<ELFT>(Rel); 380 const uint8_t *BufLoc = Sec->Data.begin() + Rel.r_offset; 381 if (!RelTy::IsRela) 382 Addend = Target->getImplicitAddend(BufLoc, Type); 383 384 if (Config->EMachine == EM_MIPS && Config->Relocatable && 385 Target->getRelExpr(Type, Sym, BufLoc) == R_MIPS_GOTREL) { 386 // Some MIPS relocations depend on "gp" value. By default, 387 // this value has 0x7ff0 offset from a .got section. But 388 // relocatable files produced by a complier or a linker 389 // might redefine this default value and we must use it 390 // for a calculation of the relocation result. When we 391 // generate EXE or DSO it's trivial. Generating a relocatable 392 // output is more difficult case because the linker does 393 // not calculate relocations in this mode and loses 394 // individual "gp" values used by each input object file. 395 // As a workaround we add the "gp" value to the relocation 396 // addend and save it back to the file. 397 Addend += Sec->getFile<ELFT>()->MipsGp0; 398 } 399 400 if (RelTy::IsRela) 401 P->r_addend = Sym.getVA(Addend) - Section->getOutputSection()->Addr; 402 else if (Config->Relocatable) 403 Sec->Relocations.push_back({R_ABS, Type, Rel.r_offset, Addend, &Sym}); 404 } 405 } 406 } 407 408 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak 409 // references specially. The general rule is that the value of the symbol in 410 // this context is the address of the place P. A further special case is that 411 // branch relocations to an undefined weak reference resolve to the next 412 // instruction. 413 static uint32_t getARMUndefinedRelativeWeakVA(RelType Type, uint32_t A, 414 uint32_t P) { 415 switch (Type) { 416 // Unresolved branch relocations to weak references resolve to next 417 // instruction, this will be either 2 or 4 bytes on from P. 418 case R_ARM_THM_JUMP11: 419 return P + 2 + A; 420 case R_ARM_CALL: 421 case R_ARM_JUMP24: 422 case R_ARM_PC24: 423 case R_ARM_PLT32: 424 case R_ARM_PREL31: 425 case R_ARM_THM_JUMP19: 426 case R_ARM_THM_JUMP24: 427 return P + 4 + A; 428 case R_ARM_THM_CALL: 429 // We don't want an interworking BLX to ARM 430 return P + 5 + A; 431 // Unresolved non branch pc-relative relocations 432 // R_ARM_TARGET2 which can be resolved relatively is not present as it never 433 // targets a weak-reference. 434 case R_ARM_MOVW_PREL_NC: 435 case R_ARM_MOVT_PREL: 436 case R_ARM_REL32: 437 case R_ARM_THM_MOVW_PREL_NC: 438 case R_ARM_THM_MOVT_PREL: 439 return P + A; 440 } 441 llvm_unreachable("ARM pc-relative relocation expected\n"); 442 } 443 444 // The comment above getARMUndefinedRelativeWeakVA applies to this function. 445 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A, 446 uint64_t P) { 447 switch (Type) { 448 // Unresolved branch relocations to weak references resolve to next 449 // instruction, this is 4 bytes on from P. 450 case R_AARCH64_CALL26: 451 case R_AARCH64_CONDBR19: 452 case R_AARCH64_JUMP26: 453 case R_AARCH64_TSTBR14: 454 return P + 4 + A; 455 // Unresolved non branch pc-relative relocations 456 case R_AARCH64_PREL16: 457 case R_AARCH64_PREL32: 458 case R_AARCH64_PREL64: 459 case R_AARCH64_ADR_PREL_LO21: 460 case R_AARCH64_LD_PREL_LO19: 461 return P + A; 462 } 463 llvm_unreachable("AArch64 pc-relative relocation expected\n"); 464 } 465 466 // ARM SBREL relocations are of the form S + A - B where B is the static base 467 // The ARM ABI defines base to be "addressing origin of the output segment 468 // defining the symbol S". We defined the "addressing origin"/static base to be 469 // the base of the PT_LOAD segment containing the Sym. 470 // The procedure call standard only defines a Read Write Position Independent 471 // RWPI variant so in practice we should expect the static base to be the base 472 // of the RW segment. 473 static uint64_t getARMStaticBase(const Symbol &Sym) { 474 OutputSection *OS = Sym.getOutputSection(); 475 if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec) 476 fatal("SBREL relocation to " + Sym.getName() + " without static base"); 477 return OS->PtLoad->FirstSec->Addr; 478 } 479 480 static uint64_t getRelocTargetVA(const InputFile *File, RelType Type, int64_t A, 481 uint64_t P, const Symbol &Sym, RelExpr Expr) { 482 switch (Expr) { 483 case R_INVALID: 484 return 0; 485 case R_ABS: 486 case R_RELAX_TLS_LD_TO_LE_ABS: 487 case R_RELAX_GOT_PC_NOPIC: 488 return Sym.getVA(A); 489 case R_ADDEND: 490 return A; 491 case R_ARM_SBREL: 492 return Sym.getVA(A) - getARMStaticBase(Sym); 493 case R_GOT: 494 case R_RELAX_TLS_GD_TO_IE_ABS: 495 return Sym.getGotVA() + A; 496 case R_GOTONLY_PC: 497 return InX::Got->getVA() + A - P; 498 case R_GOTONLY_PC_FROM_END: 499 return InX::Got->getVA() + A - P + InX::Got->getSize(); 500 case R_GOTREL: 501 return Sym.getVA(A) - InX::Got->getVA(); 502 case R_GOTREL_FROM_END: 503 return Sym.getVA(A) - InX::Got->getVA() - InX::Got->getSize(); 504 case R_GOT_FROM_END: 505 case R_RELAX_TLS_GD_TO_IE_END: 506 return Sym.getGotOffset() + A - InX::Got->getSize(); 507 case R_TLSLD_GOT_OFF: 508 case R_GOT_OFF: 509 case R_RELAX_TLS_GD_TO_IE_GOT_OFF: 510 return Sym.getGotOffset() + A; 511 case R_GOT_PAGE_PC: 512 case R_RELAX_TLS_GD_TO_IE_PAGE_PC: 513 return getAArch64Page(Sym.getGotVA() + A) - getAArch64Page(P); 514 case R_GOT_PC: 515 case R_RELAX_TLS_GD_TO_IE: 516 return Sym.getGotVA() + A - P; 517 case R_HINT: 518 case R_NONE: 519 case R_TLSDESC_CALL: 520 case R_TLSLD_HINT: 521 llvm_unreachable("cannot relocate hint relocs"); 522 case R_MIPS_GOTREL: 523 return Sym.getVA(A) - InX::MipsGot->getGp(File); 524 case R_MIPS_GOT_GP: 525 return InX::MipsGot->getGp(File) + A; 526 case R_MIPS_GOT_GP_PC: { 527 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target 528 // is _gp_disp symbol. In that case we should use the following 529 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at 530 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 531 // microMIPS variants of these relocations use slightly different 532 // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi() 533 // to correctly handle less-sugnificant bit of the microMIPS symbol. 534 uint64_t V = InX::MipsGot->getGp(File) + A - P; 535 if (Type == R_MIPS_LO16 || Type == R_MICROMIPS_LO16) 536 V += 4; 537 if (Type == R_MICROMIPS_LO16 || Type == R_MICROMIPS_HI16) 538 V -= 1; 539 return V; 540 } 541 case R_MIPS_GOT_LOCAL_PAGE: 542 // If relocation against MIPS local symbol requires GOT entry, this entry 543 // should be initialized by 'page address'. This address is high 16-bits 544 // of sum the symbol's value and the addend. 545 return InX::MipsGot->getVA() + 546 InX::MipsGot->getPageEntryOffset(File, Sym, A) - 547 InX::MipsGot->getGp(File); 548 case R_MIPS_GOT_OFF: 549 case R_MIPS_GOT_OFF32: 550 // In case of MIPS if a GOT relocation has non-zero addend this addend 551 // should be applied to the GOT entry content not to the GOT entry offset. 552 // That is why we use separate expression type. 553 return InX::MipsGot->getVA() + 554 InX::MipsGot->getSymEntryOffset(File, Sym, A) - 555 InX::MipsGot->getGp(File); 556 case R_MIPS_TLSGD: 557 return InX::MipsGot->getVA() + InX::MipsGot->getGlobalDynOffset(File, Sym) - 558 InX::MipsGot->getGp(File); 559 case R_MIPS_TLSLD: 560 return InX::MipsGot->getVA() + InX::MipsGot->getTlsIndexOffset(File) - 561 InX::MipsGot->getGp(File); 562 case R_PAGE_PC: 563 case R_PLT_PAGE_PC: { 564 uint64_t Dest; 565 if (Sym.isUndefWeak()) 566 Dest = getAArch64Page(A); 567 else 568 Dest = getAArch64Page(Sym.getVA(A)); 569 return Dest - getAArch64Page(P); 570 } 571 case R_PC: { 572 uint64_t Dest; 573 if (Sym.isUndefWeak()) { 574 // On ARM and AArch64 a branch to an undefined weak resolves to the 575 // next instruction, otherwise the place. 576 if (Config->EMachine == EM_ARM) 577 Dest = getARMUndefinedRelativeWeakVA(Type, A, P); 578 else if (Config->EMachine == EM_AARCH64) 579 Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P); 580 else 581 Dest = Sym.getVA(A); 582 } else { 583 Dest = Sym.getVA(A); 584 } 585 return Dest - P; 586 } 587 case R_PLT: 588 return Sym.getPltVA() + A; 589 case R_PLT_PC: 590 case R_PPC_CALL_PLT: 591 return Sym.getPltVA() + A - P; 592 case R_PPC_CALL: { 593 uint64_t SymVA = Sym.getVA(A); 594 // If we have an undefined weak symbol, we might get here with a symbol 595 // address of zero. That could overflow, but the code must be unreachable, 596 // so don't bother doing anything at all. 597 if (!SymVA) 598 return 0; 599 600 // PPC64 V2 ABI describes two entry points to a function. The global entry 601 // point sets up the TOC base pointer. When calling a local function, the 602 // call should branch to the local entry point rather than the global entry 603 // point. Section 3.4.1 describes using the 3 most significant bits of the 604 // st_other field to find out how many instructions there are between the 605 // local and global entry point. 606 uint8_t StOther = (Sym.StOther >> 5) & 7; 607 if (StOther == 0 || StOther == 1) 608 return SymVA - P; 609 610 return SymVA - P + (1LL << StOther); 611 } 612 case R_PPC_TOC: 613 return getPPC64TocBase() + A; 614 case R_RELAX_GOT_PC: 615 return Sym.getVA(A) - P; 616 case R_RELAX_TLS_GD_TO_LE: 617 case R_RELAX_TLS_IE_TO_LE: 618 case R_RELAX_TLS_LD_TO_LE: 619 case R_TLS: 620 // A weak undefined TLS symbol resolves to the base of the TLS 621 // block, i.e. gets a value of zero. If we pass --gc-sections to 622 // lld and .tbss is not referenced, it gets reclaimed and we don't 623 // create a TLS program header. Therefore, we resolve this 624 // statically to zero. 625 if (Sym.isTls() && Sym.isUndefWeak()) 626 return 0; 627 628 // For TLS variant 1 the TCB is a fixed size, whereas for TLS variant 2 the 629 // TCB is on unspecified size and content. Targets that implement variant 1 630 // should set TcbSize. 631 if (Target->TcbSize) { 632 // PPC64 V2 ABI has the thread pointer offset into the middle of the TLS 633 // storage area by TlsTpOffset for efficient addressing TCB and up to 634 // 4KB – 8 B of other thread library information (placed before the TCB). 635 // Subtracting this offset will get the address of the first TLS block. 636 if (Target->TlsTpOffset) 637 return Sym.getVA(A) - Target->TlsTpOffset; 638 639 // If thread pointer is not offset into the middle, the first thing in the 640 // TLS storage area is the TCB. Add the TcbSize to get the address of the 641 // first TLS block. 642 return Sym.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align); 643 } 644 return Sym.getVA(A) - Out::TlsPhdr->p_memsz; 645 case R_RELAX_TLS_GD_TO_LE_NEG: 646 case R_NEG_TLS: 647 return Out::TlsPhdr->p_memsz - Sym.getVA(A); 648 case R_SIZE: 649 return Sym.getSize() + A; 650 case R_TLSDESC: 651 return InX::Got->getGlobalDynAddr(Sym) + A; 652 case R_TLSDESC_PAGE: 653 return getAArch64Page(InX::Got->getGlobalDynAddr(Sym) + A) - 654 getAArch64Page(P); 655 case R_TLSGD_GOT: 656 return InX::Got->getGlobalDynOffset(Sym) + A; 657 case R_TLSGD_GOT_FROM_END: 658 return InX::Got->getGlobalDynOffset(Sym) + A - InX::Got->getSize(); 659 case R_TLSGD_PC: 660 return InX::Got->getGlobalDynAddr(Sym) + A - P; 661 case R_TLSLD_GOT_FROM_END: 662 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize(); 663 case R_TLSLD_GOT: 664 return InX::Got->getTlsIndexOff() + A; 665 case R_TLSLD_PC: 666 return InX::Got->getTlsIndexVA() + A - P; 667 } 668 llvm_unreachable("Invalid expression"); 669 } 670 671 // This function applies relocations to sections without SHF_ALLOC bit. 672 // Such sections are never mapped to memory at runtime. Debug sections are 673 // an example. Relocations in non-alloc sections are much easier to 674 // handle than in allocated sections because it will never need complex 675 // treatement such as GOT or PLT (because at runtime no one refers them). 676 // So, we handle relocations for non-alloc sections directly in this 677 // function as a performance optimization. 678 template <class ELFT, class RelTy> 679 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) { 680 const unsigned Bits = sizeof(typename ELFT::uint) * 8; 681 682 for (const RelTy &Rel : Rels) { 683 RelType Type = Rel.getType(Config->IsMips64EL); 684 685 // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations 686 // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed 687 // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we 688 // need to keep this bug-compatible code for a while. 689 if (Config->EMachine == EM_386 && Type == R_386_GOTPC) 690 continue; 691 692 uint64_t Offset = getOffset(Rel.r_offset); 693 uint8_t *BufLoc = Buf + Offset; 694 int64_t Addend = getAddend<ELFT>(Rel); 695 if (!RelTy::IsRela) 696 Addend += Target->getImplicitAddend(BufLoc, Type); 697 698 Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel); 699 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc); 700 if (Expr == R_NONE) 701 continue; 702 703 if (Expr != R_ABS) { 704 std::string Msg = getLocation<ELFT>(Offset) + 705 ": has non-ABS relocation " + toString(Type) + 706 " against symbol '" + toString(Sym) + "'"; 707 if (Expr != R_PC) { 708 error(Msg); 709 return; 710 } 711 712 // If the control reaches here, we found a PC-relative relocation in a 713 // non-ALLOC section. Since non-ALLOC section is not loaded into memory 714 // at runtime, the notion of PC-relative doesn't make sense here. So, 715 // this is a usage error. However, GNU linkers historically accept such 716 // relocations without any errors and relocate them as if they were at 717 // address 0. For bug-compatibilty, we accept them with warnings. We 718 // know Steel Bank Common Lisp as of 2018 have this bug. 719 warn(Msg); 720 Target->relocateOne(BufLoc, Type, 721 SignExtend64<Bits>(Sym.getVA(Addend - Offset))); 722 continue; 723 } 724 725 if (Sym.isTls() && !Out::TlsPhdr) 726 Target->relocateOne(BufLoc, Type, 0); 727 else 728 Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend))); 729 } 730 } 731 732 // This is used when '-r' is given. 733 // For REL targets, InputSection::copyRelocations() may store artificial 734 // relocations aimed to update addends. They are handled in relocateAlloc() 735 // for allocatable sections, and this function does the same for 736 // non-allocatable sections, such as sections with debug information. 737 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) { 738 const unsigned Bits = Config->Is64 ? 64 : 32; 739 740 for (const Relocation &Rel : Sec->Relocations) { 741 // InputSection::copyRelocations() adds only R_ABS relocations. 742 assert(Rel.Expr == R_ABS); 743 uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff; 744 uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits); 745 Target->relocateOne(BufLoc, Rel.Type, TargetVA); 746 } 747 } 748 749 template <class ELFT> 750 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) { 751 if (Flags & SHF_ALLOC) { 752 relocateAlloc(Buf, BufEnd); 753 return; 754 } 755 756 auto *Sec = cast<InputSection>(this); 757 if (Config->Relocatable) 758 relocateNonAllocForRelocatable(Sec, Buf); 759 else if (Sec->AreRelocsRela) 760 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>()); 761 else 762 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>()); 763 } 764 765 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) { 766 assert(Flags & SHF_ALLOC); 767 const unsigned Bits = Config->Wordsize * 8; 768 769 for (const Relocation &Rel : Relocations) { 770 uint64_t Offset = Rel.Offset; 771 if (auto *Sec = dyn_cast<InputSection>(this)) 772 Offset += Sec->OutSecOff; 773 uint8_t *BufLoc = Buf + Offset; 774 RelType Type = Rel.Type; 775 776 uint64_t AddrLoc = getOutputSection()->Addr + Offset; 777 RelExpr Expr = Rel.Expr; 778 uint64_t TargetVA = SignExtend64( 779 getRelocTargetVA(File, Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), 780 Bits); 781 782 switch (Expr) { 783 case R_RELAX_GOT_PC: 784 case R_RELAX_GOT_PC_NOPIC: 785 Target->relaxGot(BufLoc, TargetVA); 786 break; 787 case R_RELAX_TLS_IE_TO_LE: 788 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA); 789 break; 790 case R_RELAX_TLS_LD_TO_LE: 791 case R_RELAX_TLS_LD_TO_LE_ABS: 792 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA); 793 break; 794 case R_RELAX_TLS_GD_TO_LE: 795 case R_RELAX_TLS_GD_TO_LE_NEG: 796 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA); 797 break; 798 case R_RELAX_TLS_GD_TO_IE: 799 case R_RELAX_TLS_GD_TO_IE_ABS: 800 case R_RELAX_TLS_GD_TO_IE_GOT_OFF: 801 case R_RELAX_TLS_GD_TO_IE_PAGE_PC: 802 case R_RELAX_TLS_GD_TO_IE_END: 803 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA); 804 break; 805 case R_PPC_CALL: 806 // If this is a call to __tls_get_addr, it may be part of a TLS 807 // sequence that has been relaxed and turned into a nop. In this 808 // case, we don't want to handle it as a call. 809 if (read32(BufLoc) == 0x60000000) // nop 810 break; 811 812 // Patch a nop (0x60000000) to a ld. 813 if (Rel.Sym->NeedsTocRestore) { 814 if (BufLoc + 8 > BufEnd || read32(BufLoc + 4) != 0x60000000) { 815 error(getErrorLocation(BufLoc) + "call lacks nop, can't restore toc"); 816 break; 817 } 818 write32(BufLoc + 4, 0xe8410018); // ld %r2, 24(%r1) 819 } 820 Target->relocateOne(BufLoc, Type, TargetVA); 821 break; 822 default: 823 Target->relocateOne(BufLoc, Type, TargetVA); 824 break; 825 } 826 } 827 } 828 829 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) { 830 if (Type == SHT_NOBITS) 831 return; 832 833 if (auto *S = dyn_cast<SyntheticSection>(this)) { 834 S->writeTo(Buf + OutSecOff); 835 return; 836 } 837 838 // If -r or --emit-relocs is given, then an InputSection 839 // may be a relocation section. 840 if (Type == SHT_RELA) { 841 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>()); 842 return; 843 } 844 if (Type == SHT_REL) { 845 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>()); 846 return; 847 } 848 849 // If -r is given, we may have a SHT_GROUP section. 850 if (Type == SHT_GROUP) { 851 copyShtGroup<ELFT>(Buf + OutSecOff); 852 return; 853 } 854 855 // Copy section contents from source object file to output file 856 // and then apply relocations. 857 memcpy(Buf + OutSecOff, Data.data(), Data.size()); 858 uint8_t *BufEnd = Buf + OutSecOff + Data.size(); 859 relocate<ELFT>(Buf, BufEnd); 860 } 861 862 void InputSection::replace(InputSection *Other) { 863 Alignment = std::max(Alignment, Other->Alignment); 864 Other->Repl = Repl; 865 Other->Live = false; 866 } 867 868 template <class ELFT> 869 EhInputSection::EhInputSection(ObjFile<ELFT> &F, 870 const typename ELFT::Shdr &Header, 871 StringRef Name) 872 : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {} 873 874 SyntheticSection *EhInputSection::getParent() const { 875 return cast_or_null<SyntheticSection>(Parent); 876 } 877 878 // Returns the index of the first relocation that points to a region between 879 // Begin and Begin+Size. 880 template <class IntTy, class RelTy> 881 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels, 882 unsigned &RelocI) { 883 // Start search from RelocI for fast access. That works because the 884 // relocations are sorted in .eh_frame. 885 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) { 886 const RelTy &Rel = Rels[RelocI]; 887 if (Rel.r_offset < Begin) 888 continue; 889 890 if (Rel.r_offset < Begin + Size) 891 return RelocI; 892 return -1; 893 } 894 return -1; 895 } 896 897 // .eh_frame is a sequence of CIE or FDE records. 898 // This function splits an input section into records and returns them. 899 template <class ELFT> void EhInputSection::split() { 900 if (AreRelocsRela) 901 split<ELFT>(relas<ELFT>()); 902 else 903 split<ELFT>(rels<ELFT>()); 904 } 905 906 template <class ELFT, class RelTy> 907 void EhInputSection::split(ArrayRef<RelTy> Rels) { 908 unsigned RelI = 0; 909 for (size_t Off = 0, End = Data.size(); Off != End;) { 910 size_t Size = readEhRecordSize(this, Off); 911 Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI)); 912 // The empty record is the end marker. 913 if (Size == 4) 914 break; 915 Off += Size; 916 } 917 } 918 919 static size_t findNull(StringRef S, size_t EntSize) { 920 // Optimize the common case. 921 if (EntSize == 1) 922 return S.find(0); 923 924 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) { 925 const char *B = S.begin() + I; 926 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; })) 927 return I; 928 } 929 return StringRef::npos; 930 } 931 932 SyntheticSection *MergeInputSection::getParent() const { 933 return cast_or_null<SyntheticSection>(Parent); 934 } 935 936 // Split SHF_STRINGS section. Such section is a sequence of 937 // null-terminated strings. 938 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) { 939 size_t Off = 0; 940 bool IsAlloc = Flags & SHF_ALLOC; 941 StringRef S = toStringRef(Data); 942 943 while (!S.empty()) { 944 size_t End = findNull(S, EntSize); 945 if (End == StringRef::npos) 946 fatal(toString(this) + ": string is not null terminated"); 947 size_t Size = End + EntSize; 948 949 Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc); 950 S = S.substr(Size); 951 Off += Size; 952 } 953 } 954 955 // Split non-SHF_STRINGS section. Such section is a sequence of 956 // fixed size records. 957 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data, 958 size_t EntSize) { 959 size_t Size = Data.size(); 960 assert((Size % EntSize) == 0); 961 bool IsAlloc = Flags & SHF_ALLOC; 962 963 for (size_t I = 0; I != Size; I += EntSize) 964 Pieces.emplace_back(I, xxHash64(toStringRef(Data.slice(I, EntSize))), 965 !IsAlloc); 966 } 967 968 template <class ELFT> 969 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F, 970 const typename ELFT::Shdr &Header, 971 StringRef Name) 972 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {} 973 974 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type, 975 uint64_t Entsize, ArrayRef<uint8_t> Data, 976 StringRef Name) 977 : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0, 978 /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {} 979 980 // This function is called after we obtain a complete list of input sections 981 // that need to be linked. This is responsible to split section contents 982 // into small chunks for further processing. 983 // 984 // Note that this function is called from parallelForEach. This must be 985 // thread-safe (i.e. no memory allocation from the pools). 986 void MergeInputSection::splitIntoPieces() { 987 assert(Pieces.empty()); 988 989 if (Flags & SHF_STRINGS) 990 splitStrings(Data, Entsize); 991 else 992 splitNonStrings(Data, Entsize); 993 994 OffsetMap.reserve(Pieces.size()); 995 for (size_t I = 0, E = Pieces.size(); I != E; ++I) 996 OffsetMap[Pieces[I].InputOff] = I; 997 } 998 999 template <class It, class T, class Compare> 1000 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) { 1001 size_t Size = std::distance(First, Last); 1002 assert(Size != 0); 1003 while (Size != 1) { 1004 size_t H = Size / 2; 1005 const It MI = First + H; 1006 Size -= H; 1007 First = Comp(Value, *MI) ? First : First + H; 1008 } 1009 return Comp(Value, *First) ? First : First + 1; 1010 } 1011 1012 // Do binary search to get a section piece at a given input offset. 1013 static SectionPiece *findSectionPiece(MergeInputSection *Sec, uint64_t Offset) { 1014 if (Sec->Data.size() <= Offset) 1015 fatal(toString(Sec) + ": entry is past the end of the section"); 1016 1017 // Find the element this offset points to. 1018 auto I = fastUpperBound( 1019 Sec->Pieces.begin(), Sec->Pieces.end(), Offset, 1020 [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; }); 1021 --I; 1022 return &*I; 1023 } 1024 1025 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) { 1026 // Find a piece starting at a given offset. 1027 auto It = OffsetMap.find(Offset); 1028 if (It != OffsetMap.end()) 1029 return &Pieces[It->second]; 1030 1031 // If Offset is not at beginning of a section piece, it is not in the map. 1032 // In that case we need to search from the original section piece vector. 1033 return findSectionPiece(this, Offset); 1034 } 1035 1036 // Returns the offset in an output section for a given input offset. 1037 // Because contents of a mergeable section is not contiguous in output, 1038 // it is not just an addition to a base output offset. 1039 uint64_t MergeInputSection::getParentOffset(uint64_t Offset) const { 1040 // Find a string starting at a given offset. 1041 auto It = OffsetMap.find(Offset); 1042 if (It != OffsetMap.end()) 1043 return Pieces[It->second].OutputOff; 1044 1045 // If Offset is not at beginning of a section piece, it is not in the map. 1046 // In that case we need to search from the original section piece vector. 1047 const SectionPiece &Piece = 1048 *findSectionPiece(const_cast<MergeInputSection *>(this), Offset); 1049 uint64_t Addend = Offset - Piece.InputOff; 1050 return Piece.OutputOff + Addend; 1051 } 1052 1053 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &, 1054 StringRef); 1055 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &, 1056 StringRef); 1057 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &, 1058 StringRef); 1059 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &, 1060 StringRef); 1061 1062 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t); 1063 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t); 1064 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t); 1065 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t); 1066 1067 template void InputSection::writeTo<ELF32LE>(uint8_t *); 1068 template void InputSection::writeTo<ELF32BE>(uint8_t *); 1069 template void InputSection::writeTo<ELF64LE>(uint8_t *); 1070 template void InputSection::writeTo<ELF64BE>(uint8_t *); 1071 1072 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &, 1073 const ELF32LE::Shdr &, StringRef); 1074 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &, 1075 const ELF32BE::Shdr &, StringRef); 1076 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &, 1077 const ELF64LE::Shdr &, StringRef); 1078 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &, 1079 const ELF64BE::Shdr &, StringRef); 1080 1081 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &, 1082 const ELF32LE::Shdr &, StringRef); 1083 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &, 1084 const ELF32BE::Shdr &, StringRef); 1085 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &, 1086 const ELF64LE::Shdr &, StringRef); 1087 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &, 1088 const ELF64BE::Shdr &, StringRef); 1089 1090 template void EhInputSection::split<ELF32LE>(); 1091 template void EhInputSection::split<ELF32BE>(); 1092 template void EhInputSection::split<ELF64LE>(); 1093 template void EhInputSection::split<ELF64BE>(); 1094