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