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