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