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->Repl->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 is used for calls where the caller and callee (may) have different 635 // TOC base pointers and r2 needs to be modified to hold the TOC base for 636 // the callee. For local calls the caller and callee share the same 637 // TOC base and so the TOC pointer initialization code should be skipped by 638 // branching to the local entry point. 639 return SymVA - P + getPPC64GlobalEntryToLocalEntryOffset(Sym.StOther); 640 } 641 case R_PPC_TOC: 642 return getPPC64TocBase() + A; 643 case R_RELAX_GOT_PC: 644 return Sym.getVA(A) - P; 645 case R_RELAX_TLS_GD_TO_LE: 646 case R_RELAX_TLS_IE_TO_LE: 647 case R_RELAX_TLS_LD_TO_LE: 648 case R_TLS: 649 // A weak undefined TLS symbol resolves to the base of the TLS 650 // block, i.e. gets a value of zero. If we pass --gc-sections to 651 // lld and .tbss is not referenced, it gets reclaimed and we don't 652 // create a TLS program header. Therefore, we resolve this 653 // statically to zero. 654 if (Sym.isTls() && Sym.isUndefWeak()) 655 return 0; 656 657 // For TLS variant 1 the TCB is a fixed size, whereas for TLS variant 2 the 658 // TCB is on unspecified size and content. Targets that implement variant 1 659 // should set TcbSize. 660 if (Target->TcbSize) { 661 // PPC64 V2 ABI has the thread pointer offset into the middle of the TLS 662 // storage area by TlsTpOffset for efficient addressing TCB and up to 663 // 4KB – 8 B of other thread library information (placed before the TCB). 664 // Subtracting this offset will get the address of the first TLS block. 665 if (Target->TlsTpOffset) 666 return Sym.getVA(A) - Target->TlsTpOffset; 667 668 // If thread pointer is not offset into the middle, the first thing in the 669 // TLS storage area is the TCB. Add the TcbSize to get the address of the 670 // first TLS block. 671 return Sym.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align); 672 } 673 return Sym.getVA(A) - Out::TlsPhdr->p_memsz; 674 case R_RELAX_TLS_GD_TO_LE_NEG: 675 case R_NEG_TLS: 676 return Out::TlsPhdr->p_memsz - Sym.getVA(A); 677 case R_SIZE: 678 return Sym.getSize() + A; 679 case R_TLSDESC: 680 return InX::Got->getGlobalDynAddr(Sym) + A; 681 case R_TLSDESC_PAGE: 682 return getAArch64Page(InX::Got->getGlobalDynAddr(Sym) + A) - 683 getAArch64Page(P); 684 case R_TLSGD_GOT: 685 return InX::Got->getGlobalDynOffset(Sym) + A; 686 case R_TLSGD_GOT_FROM_END: 687 return InX::Got->getGlobalDynOffset(Sym) + A - InX::Got->getSize(); 688 case R_TLSGD_PC: 689 return InX::Got->getGlobalDynAddr(Sym) + A - P; 690 case R_TLSLD_GOT_FROM_END: 691 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize(); 692 case R_TLSLD_GOT: 693 return InX::Got->getTlsIndexOff() + A; 694 case R_TLSLD_PC: 695 return InX::Got->getTlsIndexVA() + A - P; 696 default: 697 llvm_unreachable("invalid expression"); 698 } 699 } 700 701 // This function applies relocations to sections without SHF_ALLOC bit. 702 // Such sections are never mapped to memory at runtime. Debug sections are 703 // an example. Relocations in non-alloc sections are much easier to 704 // handle than in allocated sections because it will never need complex 705 // treatement such as GOT or PLT (because at runtime no one refers them). 706 // So, we handle relocations for non-alloc sections directly in this 707 // function as a performance optimization. 708 template <class ELFT, class RelTy> 709 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) { 710 const unsigned Bits = sizeof(typename ELFT::uint) * 8; 711 712 for (const RelTy &Rel : Rels) { 713 RelType Type = Rel.getType(Config->IsMips64EL); 714 715 // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations 716 // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed 717 // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we 718 // need to keep this bug-compatible code for a while. 719 if (Config->EMachine == EM_386 && Type == R_386_GOTPC) 720 continue; 721 722 uint64_t Offset = getOffset(Rel.r_offset); 723 uint8_t *BufLoc = Buf + Offset; 724 int64_t Addend = getAddend<ELFT>(Rel); 725 if (!RelTy::IsRela) 726 Addend += Target->getImplicitAddend(BufLoc, Type); 727 728 Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel); 729 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc); 730 if (Expr == R_NONE) 731 continue; 732 733 if (Expr != R_ABS) { 734 std::string Msg = getLocation<ELFT>(Offset) + 735 ": has non-ABS relocation " + toString(Type) + 736 " against symbol '" + toString(Sym) + "'"; 737 if (Expr != R_PC) { 738 error(Msg); 739 return; 740 } 741 742 // If the control reaches here, we found a PC-relative relocation in a 743 // non-ALLOC section. Since non-ALLOC section is not loaded into memory 744 // at runtime, the notion of PC-relative doesn't make sense here. So, 745 // this is a usage error. However, GNU linkers historically accept such 746 // relocations without any errors and relocate them as if they were at 747 // address 0. For bug-compatibilty, we accept them with warnings. We 748 // know Steel Bank Common Lisp as of 2018 have this bug. 749 warn(Msg); 750 Target->relocateOne(BufLoc, Type, 751 SignExtend64<Bits>(Sym.getVA(Addend - Offset))); 752 continue; 753 } 754 755 if (Sym.isTls() && !Out::TlsPhdr) 756 Target->relocateOne(BufLoc, Type, 0); 757 else 758 Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend))); 759 } 760 } 761 762 // This is used when '-r' is given. 763 // For REL targets, InputSection::copyRelocations() may store artificial 764 // relocations aimed to update addends. They are handled in relocateAlloc() 765 // for allocatable sections, and this function does the same for 766 // non-allocatable sections, such as sections with debug information. 767 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) { 768 const unsigned Bits = Config->Is64 ? 64 : 32; 769 770 for (const Relocation &Rel : Sec->Relocations) { 771 // InputSection::copyRelocations() adds only R_ABS relocations. 772 assert(Rel.Expr == R_ABS); 773 uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff; 774 uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits); 775 Target->relocateOne(BufLoc, Rel.Type, TargetVA); 776 } 777 } 778 779 template <class ELFT> 780 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) { 781 if (Flags & SHF_EXECINSTR) 782 adjustSplitStackFunctionPrologues<ELFT>(Buf, BufEnd); 783 784 if (Flags & SHF_ALLOC) { 785 relocateAlloc(Buf, BufEnd); 786 return; 787 } 788 789 auto *Sec = cast<InputSection>(this); 790 if (Config->Relocatable) 791 relocateNonAllocForRelocatable(Sec, Buf); 792 else if (Sec->AreRelocsRela) 793 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>()); 794 else 795 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>()); 796 } 797 798 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) { 799 assert(Flags & SHF_ALLOC); 800 const unsigned Bits = Config->Wordsize * 8; 801 802 for (const Relocation &Rel : Relocations) { 803 uint64_t Offset = Rel.Offset; 804 if (auto *Sec = dyn_cast<InputSection>(this)) 805 Offset += Sec->OutSecOff; 806 uint8_t *BufLoc = Buf + Offset; 807 RelType Type = Rel.Type; 808 809 uint64_t AddrLoc = getOutputSection()->Addr + Offset; 810 RelExpr Expr = Rel.Expr; 811 uint64_t TargetVA = SignExtend64( 812 getRelocTargetVA(File, Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), 813 Bits); 814 815 switch (Expr) { 816 case R_RELAX_GOT_PC: 817 case R_RELAX_GOT_PC_NOPIC: 818 Target->relaxGot(BufLoc, TargetVA); 819 break; 820 case R_RELAX_TLS_IE_TO_LE: 821 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA); 822 break; 823 case R_RELAX_TLS_LD_TO_LE: 824 case R_RELAX_TLS_LD_TO_LE_ABS: 825 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA); 826 break; 827 case R_RELAX_TLS_GD_TO_LE: 828 case R_RELAX_TLS_GD_TO_LE_NEG: 829 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA); 830 break; 831 case R_RELAX_TLS_GD_TO_IE: 832 case R_RELAX_TLS_GD_TO_IE_ABS: 833 case R_RELAX_TLS_GD_TO_IE_GOT_OFF: 834 case R_RELAX_TLS_GD_TO_IE_PAGE_PC: 835 case R_RELAX_TLS_GD_TO_IE_END: 836 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA); 837 break; 838 case R_PPC_CALL: 839 // If this is a call to __tls_get_addr, it may be part of a TLS 840 // sequence that has been relaxed and turned into a nop. In this 841 // case, we don't want to handle it as a call. 842 if (read32(BufLoc) == 0x60000000) // nop 843 break; 844 845 // Patch a nop (0x60000000) to a ld. 846 if (Rel.Sym->NeedsTocRestore) { 847 if (BufLoc + 8 > BufEnd || read32(BufLoc + 4) != 0x60000000) { 848 error(getErrorLocation(BufLoc) + "call lacks nop, can't restore toc"); 849 break; 850 } 851 write32(BufLoc + 4, 0xe8410018); // ld %r2, 24(%r1) 852 } 853 Target->relocateOne(BufLoc, Type, TargetVA); 854 break; 855 default: 856 Target->relocateOne(BufLoc, Type, TargetVA); 857 break; 858 } 859 } 860 } 861 862 // For each function-defining prologue, find any calls to __morestack, 863 // and replace them with calls to __morestack_non_split. 864 static void switchMorestackCallsToMorestackNonSplit( 865 DenseSet<Defined *> &Prologues, std::vector<Relocation *> &MorestackCalls) { 866 867 // If the target adjusted a function's prologue, all calls to 868 // __morestack inside that function should be switched to 869 // __morestack_non_split. 870 Symbol *MoreStackNonSplit = Symtab->find("__morestack_non_split"); 871 if (!MoreStackNonSplit) { 872 error("Mixing split-stack objects requires a definition of " 873 "__morestack_non_split"); 874 return; 875 } 876 877 // Sort both collections to compare addresses efficiently. 878 llvm::sort(MorestackCalls.begin(), MorestackCalls.end(), 879 [](const Relocation *L, const Relocation *R) { 880 return L->Offset < R->Offset; 881 }); 882 std::vector<Defined *> Functions(Prologues.begin(), Prologues.end()); 883 llvm::sort( 884 Functions.begin(), Functions.end(), 885 [](const Defined *L, const Defined *R) { return L->Value < R->Value; }); 886 887 auto It = MorestackCalls.begin(); 888 for (Defined *F : Functions) { 889 // Find the first call to __morestack within the function. 890 while (It != MorestackCalls.end() && (*It)->Offset < F->Value) 891 ++It; 892 // Adjust all calls inside the function. 893 while (It != MorestackCalls.end() && (*It)->Offset < F->Value + F->Size) { 894 (*It)->Sym = MoreStackNonSplit; 895 ++It; 896 } 897 } 898 } 899 900 static bool enclosingPrologueAttempted(uint64_t Offset, 901 const DenseSet<Defined *> &Prologues) { 902 for (Defined *F : Prologues) 903 if (F->Value <= Offset && Offset < F->Value + F->Size) 904 return true; 905 return false; 906 } 907 908 // If a function compiled for split stack calls a function not 909 // compiled for split stack, then the caller needs its prologue 910 // adjusted to ensure that the called function will have enough stack 911 // available. Find those functions, and adjust their prologues. 912 template <class ELFT> 913 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *Buf, 914 uint8_t *End) { 915 if (!getFile<ELFT>()->SplitStack) 916 return; 917 DenseSet<Defined *> Prologues; 918 std::vector<Relocation *> MorestackCalls; 919 920 for (Relocation &Rel : Relocations) { 921 // Local symbols can't possibly be cross-calls, and should have been 922 // resolved long before this line. 923 if (Rel.Sym->isLocal()) 924 continue; 925 926 // Ignore calls into the split-stack api. 927 if (Rel.Sym->getName().startswith("__morestack")) { 928 if (Rel.Sym->getName().equals("__morestack")) 929 MorestackCalls.push_back(&Rel); 930 continue; 931 } 932 933 // A relocation to non-function isn't relevant. Sometimes 934 // __morestack is not marked as a function, so this check comes 935 // after the name check. 936 if (Rel.Sym->Type != STT_FUNC) 937 continue; 938 939 // If the callee's-file was compiled with split stack, nothing to do. In 940 // this context, a "Defined" symbol is one "defined by the binary currently 941 // being produced". So an "undefined" symbol might be provided by a shared 942 // library. It is not possible to tell how such symbols were compiled, so be 943 // conservative. 944 if (Defined *D = dyn_cast<Defined>(Rel.Sym)) 945 if (InputSection *IS = cast_or_null<InputSection>(D->Section)) 946 if (!IS || !IS->getFile<ELFT>() || IS->getFile<ELFT>()->SplitStack) 947 continue; 948 949 if (enclosingPrologueAttempted(Rel.Offset, Prologues)) 950 continue; 951 952 if (Defined *F = getEnclosingFunction<ELFT>(Rel.Offset)) { 953 Prologues.insert(F); 954 if (Target->adjustPrologueForCrossSplitStack(Buf + getOffset(F->Value), 955 End)) 956 continue; 957 if (!getFile<ELFT>()->SomeNoSplitStack) 958 error(lld::toString(this) + ": " + F->getName() + 959 " (with -fsplit-stack) calls " + Rel.Sym->getName() + 960 " (without -fsplit-stack), but couldn't adjust its prologue"); 961 } 962 } 963 switchMorestackCallsToMorestackNonSplit(Prologues, MorestackCalls); 964 } 965 966 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) { 967 if (Type == SHT_NOBITS) 968 return; 969 970 if (auto *S = dyn_cast<SyntheticSection>(this)) { 971 S->writeTo(Buf + OutSecOff); 972 return; 973 } 974 975 // If -r or --emit-relocs is given, then an InputSection 976 // may be a relocation section. 977 if (Type == SHT_RELA) { 978 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>()); 979 return; 980 } 981 if (Type == SHT_REL) { 982 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>()); 983 return; 984 } 985 986 // If -r is given, we may have a SHT_GROUP section. 987 if (Type == SHT_GROUP) { 988 copyShtGroup<ELFT>(Buf + OutSecOff); 989 return; 990 } 991 992 // Copy section contents from source object file to output file 993 // and then apply relocations. 994 memcpy(Buf + OutSecOff, Data.data(), Data.size()); 995 uint8_t *BufEnd = Buf + OutSecOff + Data.size(); 996 relocate<ELFT>(Buf, BufEnd); 997 } 998 999 void InputSection::replace(InputSection *Other) { 1000 Alignment = std::max(Alignment, Other->Alignment); 1001 Other->Repl = Repl; 1002 Other->Live = false; 1003 } 1004 1005 template <class ELFT> 1006 EhInputSection::EhInputSection(ObjFile<ELFT> &F, 1007 const typename ELFT::Shdr &Header, 1008 StringRef Name) 1009 : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {} 1010 1011 SyntheticSection *EhInputSection::getParent() const { 1012 return cast_or_null<SyntheticSection>(Parent); 1013 } 1014 1015 // Returns the index of the first relocation that points to a region between 1016 // Begin and Begin+Size. 1017 template <class IntTy, class RelTy> 1018 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels, 1019 unsigned &RelocI) { 1020 // Start search from RelocI for fast access. That works because the 1021 // relocations are sorted in .eh_frame. 1022 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) { 1023 const RelTy &Rel = Rels[RelocI]; 1024 if (Rel.r_offset < Begin) 1025 continue; 1026 1027 if (Rel.r_offset < Begin + Size) 1028 return RelocI; 1029 return -1; 1030 } 1031 return -1; 1032 } 1033 1034 // .eh_frame is a sequence of CIE or FDE records. 1035 // This function splits an input section into records and returns them. 1036 template <class ELFT> void EhInputSection::split() { 1037 if (AreRelocsRela) 1038 split<ELFT>(relas<ELFT>()); 1039 else 1040 split<ELFT>(rels<ELFT>()); 1041 } 1042 1043 template <class ELFT, class RelTy> 1044 void EhInputSection::split(ArrayRef<RelTy> Rels) { 1045 unsigned RelI = 0; 1046 for (size_t Off = 0, End = Data.size(); Off != End;) { 1047 size_t Size = readEhRecordSize(this, Off); 1048 Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI)); 1049 // The empty record is the end marker. 1050 if (Size == 4) 1051 break; 1052 Off += Size; 1053 } 1054 } 1055 1056 static size_t findNull(StringRef S, size_t EntSize) { 1057 // Optimize the common case. 1058 if (EntSize == 1) 1059 return S.find(0); 1060 1061 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) { 1062 const char *B = S.begin() + I; 1063 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; })) 1064 return I; 1065 } 1066 return StringRef::npos; 1067 } 1068 1069 SyntheticSection *MergeInputSection::getParent() const { 1070 return cast_or_null<SyntheticSection>(Parent); 1071 } 1072 1073 // Split SHF_STRINGS section. Such section is a sequence of 1074 // null-terminated strings. 1075 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) { 1076 size_t Off = 0; 1077 bool IsAlloc = Flags & SHF_ALLOC; 1078 StringRef S = toStringRef(Data); 1079 1080 while (!S.empty()) { 1081 size_t End = findNull(S, EntSize); 1082 if (End == StringRef::npos) 1083 fatal(toString(this) + ": string is not null terminated"); 1084 size_t Size = End + EntSize; 1085 1086 Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc); 1087 S = S.substr(Size); 1088 Off += Size; 1089 } 1090 } 1091 1092 // Split non-SHF_STRINGS section. Such section is a sequence of 1093 // fixed size records. 1094 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data, 1095 size_t EntSize) { 1096 size_t Size = Data.size(); 1097 assert((Size % EntSize) == 0); 1098 bool IsAlloc = Flags & SHF_ALLOC; 1099 1100 for (size_t I = 0; I != Size; I += EntSize) 1101 Pieces.emplace_back(I, xxHash64(Data.slice(I, EntSize)), !IsAlloc); 1102 } 1103 1104 template <class ELFT> 1105 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F, 1106 const typename ELFT::Shdr &Header, 1107 StringRef Name) 1108 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {} 1109 1110 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type, 1111 uint64_t Entsize, ArrayRef<uint8_t> Data, 1112 StringRef Name) 1113 : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0, 1114 /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {} 1115 1116 // This function is called after we obtain a complete list of input sections 1117 // that need to be linked. This is responsible to split section contents 1118 // into small chunks for further processing. 1119 // 1120 // Note that this function is called from parallelForEach. This must be 1121 // thread-safe (i.e. no memory allocation from the pools). 1122 void MergeInputSection::splitIntoPieces() { 1123 assert(Pieces.empty()); 1124 1125 if (Flags & SHF_STRINGS) 1126 splitStrings(Data, Entsize); 1127 else 1128 splitNonStrings(Data, Entsize); 1129 1130 OffsetMap.reserve(Pieces.size()); 1131 for (size_t I = 0, E = Pieces.size(); I != E; ++I) 1132 OffsetMap[Pieces[I].InputOff] = I; 1133 } 1134 1135 template <class It, class T, class Compare> 1136 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) { 1137 size_t Size = std::distance(First, Last); 1138 assert(Size != 0); 1139 while (Size != 1) { 1140 size_t H = Size / 2; 1141 const It MI = First + H; 1142 Size -= H; 1143 First = Comp(Value, *MI) ? First : First + H; 1144 } 1145 return Comp(Value, *First) ? First : First + 1; 1146 } 1147 1148 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) { 1149 if (this->Data.size() <= Offset) 1150 fatal(toString(this) + ": offset is outside the section"); 1151 1152 // Find a piece starting at a given offset. 1153 auto It = OffsetMap.find(Offset); 1154 if (It != OffsetMap.end()) 1155 return &Pieces[It->second]; 1156 1157 // If Offset is not at beginning of a section piece, it is not in the map. 1158 // In that case we need to do a binary search of the original section piece vector. 1159 auto I = fastUpperBound( 1160 Pieces.begin(), Pieces.end(), Offset, 1161 [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; }); 1162 --I; 1163 return &*I; 1164 } 1165 1166 // Returns the offset in an output section for a given input offset. 1167 // Because contents of a mergeable section is not contiguous in output, 1168 // it is not just an addition to a base output offset. 1169 uint64_t MergeInputSection::getParentOffset(uint64_t Offset) const { 1170 // If Offset is not at beginning of a section piece, it is not in the map. 1171 // In that case we need to search from the original section piece vector. 1172 const SectionPiece &Piece = 1173 *(const_cast<MergeInputSection *>(this)->getSectionPiece (Offset)); 1174 uint64_t Addend = Offset - Piece.InputOff; 1175 return Piece.OutputOff + Addend; 1176 } 1177 1178 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &, 1179 StringRef); 1180 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &, 1181 StringRef); 1182 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &, 1183 StringRef); 1184 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &, 1185 StringRef); 1186 1187 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t); 1188 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t); 1189 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t); 1190 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t); 1191 1192 template void InputSection::writeTo<ELF32LE>(uint8_t *); 1193 template void InputSection::writeTo<ELF32BE>(uint8_t *); 1194 template void InputSection::writeTo<ELF64LE>(uint8_t *); 1195 template void InputSection::writeTo<ELF64BE>(uint8_t *); 1196 1197 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &, 1198 const ELF32LE::Shdr &, StringRef); 1199 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &, 1200 const ELF32BE::Shdr &, StringRef); 1201 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &, 1202 const ELF64LE::Shdr &, StringRef); 1203 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &, 1204 const ELF64BE::Shdr &, StringRef); 1205 1206 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &, 1207 const ELF32LE::Shdr &, StringRef); 1208 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &, 1209 const ELF32BE::Shdr &, StringRef); 1210 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &, 1211 const ELF64LE::Shdr &, StringRef); 1212 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &, 1213 const ELF64BE::Shdr &, StringRef); 1214 1215 template void EhInputSection::split<ELF32LE>(); 1216 template void EhInputSection::split<ELF32BE>(); 1217 template void EhInputSection::split<ELF64LE>(); 1218 template void EhInputSection::split<ELF64BE>(); 1219