1 //===- SyntheticSections.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 // This file contains linker-synthesized sections. Currently, 11 // synthetic sections are created either output sections or input sections, 12 // but we are rewriting code so that all synthetic sections are created as 13 // input sections. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "SyntheticSections.h" 18 #include "Config.h" 19 #include "Error.h" 20 #include "InputFiles.h" 21 #include "LinkerScript.h" 22 #include "Memory.h" 23 #include "OutputSections.h" 24 #include "Strings.h" 25 #include "SymbolTable.h" 26 #include "Target.h" 27 #include "Threads.h" 28 #include "Writer.h" 29 #include "lld/Config/Version.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h" 32 #include "llvm/Object/Decompressor.h" 33 #include "llvm/Object/ELFObjectFile.h" 34 #include "llvm/Support/Endian.h" 35 #include "llvm/Support/MD5.h" 36 #include "llvm/Support/RandomNumberGenerator.h" 37 #include "llvm/Support/SHA1.h" 38 #include "llvm/Support/xxhash.h" 39 #include <cstdlib> 40 41 using namespace llvm; 42 using namespace llvm::dwarf; 43 using namespace llvm::ELF; 44 using namespace llvm::object; 45 using namespace llvm::support; 46 using namespace llvm::support::endian; 47 48 using namespace lld; 49 using namespace lld::elf; 50 51 uint64_t SyntheticSection::getVA() const { 52 if (OutputSection *Sec = getParent()) 53 return Sec->Addr + OutSecOff; 54 return 0; 55 } 56 57 template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() { 58 std::vector<DefinedCommon *> V; 59 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) 60 if (auto *B = dyn_cast<DefinedCommon>(S->body())) 61 V.push_back(B); 62 return V; 63 } 64 65 // Find all common symbols and allocate space for them. 66 template <class ELFT> InputSection *elf::createCommonSection() { 67 if (!Config->DefineCommon) 68 return nullptr; 69 70 // Sort the common symbols by alignment as an heuristic to pack them better. 71 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>(); 72 if (Syms.empty()) 73 return nullptr; 74 75 std::stable_sort(Syms.begin(), Syms.end(), 76 [](const DefinedCommon *A, const DefinedCommon *B) { 77 return A->Alignment > B->Alignment; 78 }); 79 80 BssSection *Sec = make<BssSection>("COMMON"); 81 for (DefinedCommon *Sym : Syms) 82 Sym->Offset = Sec->reserveSpace(Sym->Size, Sym->Alignment); 83 return Sec; 84 } 85 86 // Returns an LLD version string. 87 static ArrayRef<uint8_t> getVersion() { 88 // Check LLD_VERSION first for ease of testing. 89 // You can get consitent output by using the environment variable. 90 // This is only for testing. 91 StringRef S = getenv("LLD_VERSION"); 92 if (S.empty()) 93 S = Saver.save(Twine("Linker: ") + getLLDVersion()); 94 95 // +1 to include the terminating '\0'. 96 return {(const uint8_t *)S.data(), S.size() + 1}; 97 } 98 99 // Creates a .comment section containing LLD version info. 100 // With this feature, you can identify LLD-generated binaries easily 101 // by "readelf --string-dump .comment <file>". 102 // The returned object is a mergeable string section. 103 template <class ELFT> MergeInputSection *elf::createCommentSection() { 104 typename ELFT::Shdr Hdr = {}; 105 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS; 106 Hdr.sh_type = SHT_PROGBITS; 107 Hdr.sh_entsize = 1; 108 Hdr.sh_addralign = 1; 109 110 auto *Ret = 111 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment"); 112 Ret->Data = getVersion(); 113 Ret->splitIntoPieces(); 114 return Ret; 115 } 116 117 // .MIPS.abiflags section. 118 template <class ELFT> 119 MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags) 120 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"), 121 Flags(Flags) { 122 this->Entsize = sizeof(Elf_Mips_ABIFlags); 123 } 124 125 template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) { 126 memcpy(Buf, &Flags, sizeof(Flags)); 127 } 128 129 template <class ELFT> 130 MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() { 131 Elf_Mips_ABIFlags Flags = {}; 132 bool Create = false; 133 134 for (InputSectionBase *Sec : InputSections) { 135 if (Sec->Type != SHT_MIPS_ABIFLAGS) 136 continue; 137 Sec->Live = false; 138 Create = true; 139 140 std::string Filename = toString(Sec->getFile<ELFT>()); 141 const size_t Size = Sec->Data.size(); 142 // Older version of BFD (such as the default FreeBSD linker) concatenate 143 // .MIPS.abiflags instead of merging. To allow for this case (or potential 144 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags 145 if (Size < sizeof(Elf_Mips_ABIFlags)) { 146 error(Filename + ": invalid size of .MIPS.abiflags section: got " + 147 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags))); 148 return nullptr; 149 } 150 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data()); 151 if (S->version != 0) { 152 error(Filename + ": unexpected .MIPS.abiflags version " + 153 Twine(S->version)); 154 return nullptr; 155 } 156 157 // LLD checks ISA compatibility in getMipsEFlags(). Here we just 158 // select the highest number of ISA/Rev/Ext. 159 Flags.isa_level = std::max(Flags.isa_level, S->isa_level); 160 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev); 161 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext); 162 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size); 163 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size); 164 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size); 165 Flags.ases |= S->ases; 166 Flags.flags1 |= S->flags1; 167 Flags.flags2 |= S->flags2; 168 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename); 169 }; 170 171 if (Create) 172 return make<MipsAbiFlagsSection<ELFT>>(Flags); 173 return nullptr; 174 } 175 176 // .MIPS.options section. 177 template <class ELFT> 178 MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo) 179 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"), 180 Reginfo(Reginfo) { 181 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo); 182 } 183 184 template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) { 185 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf); 186 Options->kind = ODK_REGINFO; 187 Options->size = getSize(); 188 189 if (!Config->Relocatable) 190 Reginfo.ri_gp_value = InX::MipsGot->getGp(); 191 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo)); 192 } 193 194 template <class ELFT> 195 MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() { 196 // N64 ABI only. 197 if (!ELFT::Is64Bits) 198 return nullptr; 199 200 Elf_Mips_RegInfo Reginfo = {}; 201 bool Create = false; 202 203 for (InputSectionBase *Sec : InputSections) { 204 if (Sec->Type != SHT_MIPS_OPTIONS) 205 continue; 206 Sec->Live = false; 207 Create = true; 208 209 std::string Filename = toString(Sec->getFile<ELFT>()); 210 ArrayRef<uint8_t> D = Sec->Data; 211 212 while (!D.empty()) { 213 if (D.size() < sizeof(Elf_Mips_Options)) { 214 error(Filename + ": invalid size of .MIPS.options section"); 215 break; 216 } 217 218 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data()); 219 if (Opt->kind == ODK_REGINFO) { 220 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value) 221 error(Filename + ": unsupported non-zero ri_gp_value"); 222 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask; 223 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value; 224 break; 225 } 226 227 if (!Opt->size) 228 fatal(Filename + ": zero option descriptor size"); 229 D = D.slice(Opt->size); 230 } 231 }; 232 233 if (Create) 234 return make<MipsOptionsSection<ELFT>>(Reginfo); 235 return nullptr; 236 } 237 238 // MIPS .reginfo section. 239 template <class ELFT> 240 MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo) 241 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"), 242 Reginfo(Reginfo) { 243 this->Entsize = sizeof(Elf_Mips_RegInfo); 244 } 245 246 template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) { 247 if (!Config->Relocatable) 248 Reginfo.ri_gp_value = InX::MipsGot->getGp(); 249 memcpy(Buf, &Reginfo, sizeof(Reginfo)); 250 } 251 252 template <class ELFT> 253 MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() { 254 // Section should be alive for O32 and N32 ABIs only. 255 if (ELFT::Is64Bits) 256 return nullptr; 257 258 Elf_Mips_RegInfo Reginfo = {}; 259 bool Create = false; 260 261 for (InputSectionBase *Sec : InputSections) { 262 if (Sec->Type != SHT_MIPS_REGINFO) 263 continue; 264 Sec->Live = false; 265 Create = true; 266 267 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) { 268 error(toString(Sec->getFile<ELFT>()) + 269 ": invalid size of .reginfo section"); 270 return nullptr; 271 } 272 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data()); 273 if (Config->Relocatable && R->ri_gp_value) 274 error(toString(Sec->getFile<ELFT>()) + 275 ": unsupported non-zero ri_gp_value"); 276 277 Reginfo.ri_gprmask |= R->ri_gprmask; 278 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value; 279 }; 280 281 if (Create) 282 return make<MipsReginfoSection<ELFT>>(Reginfo); 283 return nullptr; 284 } 285 286 InputSection *elf::createInterpSection() { 287 // StringSaver guarantees that the returned string ends with '\0'. 288 StringRef S = Saver.save(Config->DynamicLinker); 289 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1}; 290 291 auto *Sec = 292 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp"); 293 Sec->Live = true; 294 return Sec; 295 } 296 297 SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, 298 uint64_t Size, InputSectionBase *Section) { 299 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type, 300 Value, Size, Section, nullptr); 301 if (InX::SymTab) 302 InX::SymTab->addSymbol(S); 303 return S; 304 } 305 306 static size_t getHashSize() { 307 switch (Config->BuildId) { 308 case BuildIdKind::Fast: 309 return 8; 310 case BuildIdKind::Md5: 311 case BuildIdKind::Uuid: 312 return 16; 313 case BuildIdKind::Sha1: 314 return 20; 315 case BuildIdKind::Hexstring: 316 return Config->BuildIdVector.size(); 317 default: 318 llvm_unreachable("unknown BuildIdKind"); 319 } 320 } 321 322 BuildIdSection::BuildIdSection() 323 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"), 324 HashSize(getHashSize()) {} 325 326 void BuildIdSection::writeTo(uint8_t *Buf) { 327 endianness E = Config->Endianness; 328 write32(Buf, 4, E); // Name size 329 write32(Buf + 4, HashSize, E); // Content size 330 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type 331 memcpy(Buf + 12, "GNU", 4); // Name string 332 HashBuf = Buf + 16; 333 } 334 335 // Split one uint8 array into small pieces of uint8 arrays. 336 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr, 337 size_t ChunkSize) { 338 std::vector<ArrayRef<uint8_t>> Ret; 339 while (Arr.size() > ChunkSize) { 340 Ret.push_back(Arr.take_front(ChunkSize)); 341 Arr = Arr.drop_front(ChunkSize); 342 } 343 if (!Arr.empty()) 344 Ret.push_back(Arr); 345 return Ret; 346 } 347 348 // Computes a hash value of Data using a given hash function. 349 // In order to utilize multiple cores, we first split data into 1MB 350 // chunks, compute a hash for each chunk, and then compute a hash value 351 // of the hash values. 352 void BuildIdSection::computeHash( 353 llvm::ArrayRef<uint8_t> Data, 354 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) { 355 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024); 356 std::vector<uint8_t> Hashes(Chunks.size() * HashSize); 357 358 // Compute hash values. 359 parallelForEachN(0, Chunks.size(), [&](size_t I) { 360 HashFn(Hashes.data() + I * HashSize, Chunks[I]); 361 }); 362 363 // Write to the final output buffer. 364 HashFn(HashBuf, Hashes); 365 } 366 367 BssSection::BssSection(StringRef Name) 368 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {} 369 370 size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) { 371 if (OutputSection *Sec = getParent()) 372 Sec->updateAlignment(Alignment); 373 this->Size = alignTo(this->Size, Alignment) + Size; 374 this->Alignment = std::max(this->Alignment, Alignment); 375 return this->Size - Size; 376 } 377 378 void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) { 379 switch (Config->BuildId) { 380 case BuildIdKind::Fast: 381 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 382 write64le(Dest, xxHash64(toStringRef(Arr))); 383 }); 384 break; 385 case BuildIdKind::Md5: 386 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 387 memcpy(Dest, MD5::hash(Arr).data(), 16); 388 }); 389 break; 390 case BuildIdKind::Sha1: 391 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) { 392 memcpy(Dest, SHA1::hash(Arr).data(), 20); 393 }); 394 break; 395 case BuildIdKind::Uuid: 396 if (getRandomBytes(HashBuf, HashSize)) 397 error("entropy source failure"); 398 break; 399 case BuildIdKind::Hexstring: 400 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size()); 401 break; 402 default: 403 llvm_unreachable("unknown BuildIdKind"); 404 } 405 } 406 407 template <class ELFT> 408 EhFrameSection<ELFT>::EhFrameSection() 409 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {} 410 411 // Search for an existing CIE record or create a new one. 412 // CIE records from input object files are uniquified by their contents 413 // and where their relocations point to. 414 template <class ELFT> 415 template <class RelTy> 416 CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece, 417 ArrayRef<RelTy> Rels) { 418 auto *Sec = cast<EhInputSection>(Piece.ID); 419 const endianness E = ELFT::TargetEndianness; 420 if (read32<E>(Piece.data().data() + 4) != 0) 421 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame"); 422 423 SymbolBody *Personality = nullptr; 424 unsigned FirstRelI = Piece.FirstRelocation; 425 if (FirstRelI != (unsigned)-1) 426 Personality = 427 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]); 428 429 // Search for an existing CIE by CIE contents/relocation target pair. 430 CieRecord *Cie = &CieMap[{Piece.data(), Personality}]; 431 432 // If not found, create a new one. 433 if (Cie->Piece == nullptr) { 434 Cie->Piece = &Piece; 435 Cies.push_back(Cie); 436 } 437 return Cie; 438 } 439 440 // There is one FDE per function. Returns true if a given FDE 441 // points to a live function. 442 template <class ELFT> 443 template <class RelTy> 444 bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece, 445 ArrayRef<RelTy> Rels) { 446 auto *Sec = cast<EhInputSection>(Piece.ID); 447 unsigned FirstRelI = Piece.FirstRelocation; 448 if (FirstRelI == (unsigned)-1) 449 return false; 450 const RelTy &Rel = Rels[FirstRelI]; 451 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel); 452 auto *D = dyn_cast<DefinedRegular>(&B); 453 if (!D || !D->Section) 454 return false; 455 auto *Target = 456 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl); 457 return Target && Target->Live; 458 } 459 460 // .eh_frame is a sequence of CIE or FDE records. In general, there 461 // is one CIE record per input object file which is followed by 462 // a list of FDEs. This function searches an existing CIE or create a new 463 // one and associates FDEs to the CIE. 464 template <class ELFT> 465 template <class RelTy> 466 void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec, 467 ArrayRef<RelTy> Rels) { 468 const endianness E = ELFT::TargetEndianness; 469 470 DenseMap<size_t, CieRecord *> OffsetToCie; 471 for (EhSectionPiece &Piece : Sec->Pieces) { 472 // The empty record is the end marker. 473 if (Piece.size() == 4) 474 return; 475 476 size_t Offset = Piece.InputOff; 477 uint32_t ID = read32<E>(Piece.data().data() + 4); 478 if (ID == 0) { 479 OffsetToCie[Offset] = addCie(Piece, Rels); 480 continue; 481 } 482 483 uint32_t CieOffset = Offset + 4 - ID; 484 CieRecord *Cie = OffsetToCie[CieOffset]; 485 if (!Cie) 486 fatal(toString(Sec) + ": invalid CIE reference"); 487 488 if (!isFdeLive(Piece, Rels)) 489 continue; 490 Cie->FdePieces.push_back(&Piece); 491 NumFdes++; 492 } 493 } 494 495 template <class ELFT> 496 void EhFrameSection<ELFT>::addSection(InputSectionBase *C) { 497 auto *Sec = cast<EhInputSection>(C); 498 Sec->Parent = this; 499 updateAlignment(Sec->Alignment); 500 Sections.push_back(Sec); 501 for (auto *DS : Sec->DependentSections) 502 DependentSections.push_back(DS); 503 504 // .eh_frame is a sequence of CIE or FDE records. This function 505 // splits it into pieces so that we can call 506 // SplitInputSection::getSectionPiece on the section. 507 Sec->split<ELFT>(); 508 if (Sec->Pieces.empty()) 509 return; 510 511 if (Sec->NumRelocations) { 512 if (Sec->AreRelocsRela) 513 addSectionAux(Sec, Sec->template relas<ELFT>()); 514 else 515 addSectionAux(Sec, Sec->template rels<ELFT>()); 516 return; 517 } 518 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr)); 519 } 520 521 template <class ELFT> 522 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) { 523 memcpy(Buf, D.data(), D.size()); 524 525 // Fix the size field. -4 since size does not include the size field itself. 526 const endianness E = ELFT::TargetEndianness; 527 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4); 528 } 529 530 template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() { 531 if (this->Size) 532 return; // Already finalized. 533 534 size_t Off = 0; 535 for (CieRecord *Cie : Cies) { 536 Cie->Piece->OutputOff = Off; 537 Off += alignTo(Cie->Piece->size(), Config->Wordsize); 538 539 for (EhSectionPiece *Fde : Cie->FdePieces) { 540 Fde->OutputOff = Off; 541 Off += alignTo(Fde->size(), Config->Wordsize); 542 } 543 } 544 545 // The LSB standard does not allow a .eh_frame section with zero 546 // Call Frame Information records. Therefore add a CIE record length 547 // 0 as a terminator if this .eh_frame section is empty. 548 if (Off == 0) 549 Off = 4; 550 551 this->Size = Off; 552 } 553 554 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) { 555 const endianness E = ELFT::TargetEndianness; 556 switch (Size) { 557 case DW_EH_PE_udata2: 558 return read16<E>(Buf); 559 case DW_EH_PE_udata4: 560 return read32<E>(Buf); 561 case DW_EH_PE_udata8: 562 return read64<E>(Buf); 563 case DW_EH_PE_absptr: 564 if (ELFT::Is64Bits) 565 return read64<E>(Buf); 566 return read32<E>(Buf); 567 } 568 fatal("unknown FDE size encoding"); 569 } 570 571 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to. 572 // We need it to create .eh_frame_hdr section. 573 template <class ELFT> 574 uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff, 575 uint8_t Enc) { 576 // The starting address to which this FDE applies is 577 // stored at FDE + 8 byte. 578 size_t Off = FdeOff + 8; 579 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7); 580 if ((Enc & 0x70) == DW_EH_PE_absptr) 581 return Addr; 582 if ((Enc & 0x70) == DW_EH_PE_pcrel) 583 return Addr + getParent()->Addr + Off; 584 fatal("unknown FDE size relative encoding"); 585 } 586 587 template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) { 588 const endianness E = ELFT::TargetEndianness; 589 for (CieRecord *Cie : Cies) { 590 size_t CieOffset = Cie->Piece->OutputOff; 591 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data()); 592 593 for (EhSectionPiece *Fde : Cie->FdePieces) { 594 size_t Off = Fde->OutputOff; 595 writeCieFde<ELFT>(Buf + Off, Fde->data()); 596 597 // FDE's second word should have the offset to an associated CIE. 598 // Write it. 599 write32<E>(Buf + Off + 4, Off + 4 - CieOffset); 600 } 601 } 602 603 for (EhInputSection *S : Sections) 604 S->relocateAlloc(Buf, nullptr); 605 606 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table 607 // to get a FDE from an address to which FDE is applied. So here 608 // we obtain two addresses and pass them to EhFrameHdr object. 609 if (In<ELFT>::EhFrameHdr) { 610 for (CieRecord *Cie : Cies) { 611 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece); 612 for (SectionPiece *Fde : Cie->FdePieces) { 613 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc); 614 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff; 615 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA); 616 } 617 } 618 } 619 } 620 621 GotSection::GotSection() 622 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 623 Target->GotEntrySize, ".got") {} 624 625 void GotSection::addEntry(SymbolBody &Sym) { 626 Sym.GotIndex = NumEntries; 627 ++NumEntries; 628 } 629 630 bool GotSection::addDynTlsEntry(SymbolBody &Sym) { 631 if (Sym.GlobalDynIndex != -1U) 632 return false; 633 Sym.GlobalDynIndex = NumEntries; 634 // Global Dynamic TLS entries take two GOT slots. 635 NumEntries += 2; 636 return true; 637 } 638 639 // Reserves TLS entries for a TLS module ID and a TLS block offset. 640 // In total it takes two GOT slots. 641 bool GotSection::addTlsIndex() { 642 if (TlsIndexOff != uint32_t(-1)) 643 return false; 644 TlsIndexOff = NumEntries * Config->Wordsize; 645 NumEntries += 2; 646 return true; 647 } 648 649 uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const { 650 return this->getVA() + B.GlobalDynIndex * Config->Wordsize; 651 } 652 653 uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const { 654 return B.GlobalDynIndex * Config->Wordsize; 655 } 656 657 void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; } 658 659 bool GotSection::empty() const { 660 // If we have a relocation that is relative to GOT (such as GOTOFFREL), 661 // we need to emit a GOT even if it's empty. 662 return NumEntries == 0 && !HasGotOffRel; 663 } 664 665 void GotSection::writeTo(uint8_t *Buf) { relocateAlloc(Buf, Buf + Size); } 666 667 MipsGotSection::MipsGotSection() 668 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16, 669 ".got") {} 670 671 void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) { 672 // For "true" local symbols which can be referenced from the same module 673 // only compiler creates two instructions for address loading: 674 // 675 // lw $8, 0($gp) # R_MIPS_GOT16 676 // addi $8, $8, 0 # R_MIPS_LO16 677 // 678 // The first instruction loads high 16 bits of the symbol address while 679 // the second adds an offset. That allows to reduce number of required 680 // GOT entries because only one global offset table entry is necessary 681 // for every 64 KBytes of local data. So for local symbols we need to 682 // allocate number of GOT entries to hold all required "page" addresses. 683 // 684 // All global symbols (hidden and regular) considered by compiler uniformly. 685 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation 686 // to load address of the symbol. So for each such symbol we need to 687 // allocate dedicated GOT entry to store its address. 688 // 689 // If a symbol is preemptible we need help of dynamic linker to get its 690 // final address. The corresponding GOT entries are allocated in the 691 // "global" part of GOT. Entries for non preemptible global symbol allocated 692 // in the "local" part of GOT. 693 // 694 // See "Global Offset Table" in Chapter 5: 695 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 696 if (Expr == R_MIPS_GOT_LOCAL_PAGE) { 697 // At this point we do not know final symbol value so to reduce number 698 // of allocated GOT entries do the following trick. Save all output 699 // sections referenced by GOT relocations. Then later in the `finalize` 700 // method calculate number of "pages" required to cover all saved output 701 // section and allocate appropriate number of GOT entries. 702 PageIndexMap.insert({Sym.getOutputSection(), 0}); 703 return; 704 } 705 if (Sym.isTls()) { 706 // GOT entries created for MIPS TLS relocations behave like 707 // almost GOT entries from other ABIs. They go to the end 708 // of the global offset table. 709 Sym.GotIndex = TlsEntries.size(); 710 TlsEntries.push_back(&Sym); 711 return; 712 } 713 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) { 714 if (S.isInGot() && !A) 715 return; 716 size_t NewIndex = Items.size(); 717 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second) 718 return; 719 Items.emplace_back(&S, A); 720 if (!A) 721 S.GotIndex = NewIndex; 722 }; 723 if (Sym.isPreemptible()) { 724 // Ignore addends for preemptible symbols. They got single GOT entry anyway. 725 AddEntry(Sym, 0, GlobalEntries); 726 Sym.IsInGlobalMipsGot = true; 727 } else if (Expr == R_MIPS_GOT_OFF32) { 728 AddEntry(Sym, Addend, LocalEntries32); 729 Sym.Is32BitMipsGot = true; 730 } else { 731 // Hold local GOT entries accessed via a 16-bit index separately. 732 // That allows to write them in the beginning of the GOT and keep 733 // their indexes as less as possible to escape relocation's overflow. 734 AddEntry(Sym, Addend, LocalEntries); 735 } 736 } 737 738 bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) { 739 if (Sym.GlobalDynIndex != -1U) 740 return false; 741 Sym.GlobalDynIndex = TlsEntries.size(); 742 // Global Dynamic TLS entries take two GOT slots. 743 TlsEntries.push_back(nullptr); 744 TlsEntries.push_back(&Sym); 745 return true; 746 } 747 748 // Reserves TLS entries for a TLS module ID and a TLS block offset. 749 // In total it takes two GOT slots. 750 bool MipsGotSection::addTlsIndex() { 751 if (TlsIndexOff != uint32_t(-1)) 752 return false; 753 TlsIndexOff = TlsEntries.size() * Config->Wordsize; 754 TlsEntries.push_back(nullptr); 755 TlsEntries.push_back(nullptr); 756 return true; 757 } 758 759 static uint64_t getMipsPageAddr(uint64_t Addr) { 760 return (Addr + 0x8000) & ~0xffff; 761 } 762 763 static uint64_t getMipsPageCount(uint64_t Size) { 764 return (Size + 0xfffe) / 0xffff + 1; 765 } 766 767 uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B, 768 int64_t Addend) const { 769 const OutputSection *OutSec = B.getOutputSection(); 770 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr); 771 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend)); 772 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff; 773 assert(Index < PageEntriesNum); 774 return (HeaderEntriesNum + Index) * Config->Wordsize; 775 } 776 777 uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B, 778 int64_t Addend) const { 779 // Calculate offset of the GOT entries block: TLS, global, local. 780 uint64_t Index = HeaderEntriesNum + PageEntriesNum; 781 if (B.isTls()) 782 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size(); 783 else if (B.IsInGlobalMipsGot) 784 Index += LocalEntries.size() + LocalEntries32.size(); 785 else if (B.Is32BitMipsGot) 786 Index += LocalEntries.size(); 787 // Calculate offset of the GOT entry in the block. 788 if (B.isInGot()) 789 Index += B.GotIndex; 790 else { 791 auto It = EntryIndexMap.find({&B, Addend}); 792 assert(It != EntryIndexMap.end()); 793 Index += It->second; 794 } 795 return Index * Config->Wordsize; 796 } 797 798 uint64_t MipsGotSection::getTlsOffset() const { 799 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize; 800 } 801 802 uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const { 803 return B.GlobalDynIndex * Config->Wordsize; 804 } 805 806 const SymbolBody *MipsGotSection::getFirstGlobalEntry() const { 807 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first; 808 } 809 810 unsigned MipsGotSection::getLocalEntriesNum() const { 811 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() + 812 LocalEntries32.size(); 813 } 814 815 void MipsGotSection::finalizeContents() { 816 updateAllocSize(); 817 } 818 819 void MipsGotSection::updateAllocSize() { 820 PageEntriesNum = 0; 821 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) { 822 // For each output section referenced by GOT page relocations calculate 823 // and save into PageIndexMap an upper bound of MIPS GOT entries required 824 // to store page addresses of local symbols. We assume the worst case - 825 // each 64kb page of the output section has at least one GOT relocation 826 // against it. And take in account the case when the section intersects 827 // page boundaries. 828 P.second = PageEntriesNum; 829 PageEntriesNum += getMipsPageCount(P.first->Size); 830 } 831 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) * 832 Config->Wordsize; 833 } 834 835 bool MipsGotSection::empty() const { 836 // We add the .got section to the result for dynamic MIPS target because 837 // its address and properties are mentioned in the .dynamic section. 838 return Config->Relocatable; 839 } 840 841 uint64_t MipsGotSection::getGp() const { 842 return ElfSym::MipsGp->getVA(0); 843 } 844 845 static uint64_t readUint(uint8_t *Buf) { 846 if (Config->Is64) 847 return read64(Buf, Config->Endianness); 848 return read32(Buf, Config->Endianness); 849 } 850 851 static void writeUint(uint8_t *Buf, uint64_t Val) { 852 if (Config->Is64) 853 write64(Buf, Val, Config->Endianness); 854 else 855 write32(Buf, Val, Config->Endianness); 856 } 857 858 void MipsGotSection::writeTo(uint8_t *Buf) { 859 // Set the MSB of the second GOT slot. This is not required by any 860 // MIPS ABI documentation, though. 861 // 862 // There is a comment in glibc saying that "The MSB of got[1] of a 863 // gnu object is set to identify gnu objects," and in GNU gold it 864 // says "the second entry will be used by some runtime loaders". 865 // But how this field is being used is unclear. 866 // 867 // We are not really willing to mimic other linkers behaviors 868 // without understanding why they do that, but because all files 869 // generated by GNU tools have this special GOT value, and because 870 // we've been doing this for years, it is probably a safe bet to 871 // keep doing this for now. We really need to revisit this to see 872 // if we had to do this. 873 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1)); 874 Buf += HeaderEntriesNum * Config->Wordsize; 875 // Write 'page address' entries to the local part of the GOT. 876 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) { 877 size_t PageCount = getMipsPageCount(L.first->Size); 878 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr); 879 for (size_t PI = 0; PI < PageCount; ++PI) { 880 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize; 881 writeUint(Entry, FirstPageAddr + PI * 0x10000); 882 } 883 } 884 Buf += PageEntriesNum * Config->Wordsize; 885 auto AddEntry = [&](const GotEntry &SA) { 886 uint8_t *Entry = Buf; 887 Buf += Config->Wordsize; 888 const SymbolBody *Body = SA.first; 889 uint64_t VA = Body->getVA(SA.second); 890 writeUint(Entry, VA); 891 }; 892 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry); 893 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry); 894 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry); 895 // Initialize TLS-related GOT entries. If the entry has a corresponding 896 // dynamic relocations, leave it initialized by zero. Write down adjusted 897 // TLS symbol's values otherwise. To calculate the adjustments use offsets 898 // for thread-local storage. 899 // https://www.linux-mips.org/wiki/NPTL 900 if (TlsIndexOff != -1U && !Config->Pic) 901 writeUint(Buf + TlsIndexOff, 1); 902 for (const SymbolBody *B : TlsEntries) { 903 if (!B || B->isPreemptible()) 904 continue; 905 uint64_t VA = B->getVA(); 906 if (B->GotIndex != -1U) { 907 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize; 908 writeUint(Entry, VA - 0x7000); 909 } 910 if (B->GlobalDynIndex != -1U) { 911 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize; 912 writeUint(Entry, 1); 913 Entry += Config->Wordsize; 914 writeUint(Entry, VA - 0x8000); 915 } 916 } 917 } 918 919 GotPltSection::GotPltSection() 920 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 921 Target->GotPltEntrySize, ".got.plt") {} 922 923 void GotPltSection::addEntry(SymbolBody &Sym) { 924 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size(); 925 Entries.push_back(&Sym); 926 } 927 928 size_t GotPltSection::getSize() const { 929 return (Target->GotPltHeaderEntriesNum + Entries.size()) * 930 Target->GotPltEntrySize; 931 } 932 933 void GotPltSection::writeTo(uint8_t *Buf) { 934 Target->writeGotPltHeader(Buf); 935 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize; 936 for (const SymbolBody *B : Entries) { 937 Target->writeGotPlt(Buf, *B); 938 Buf += Config->Wordsize; 939 } 940 } 941 942 // On ARM the IgotPltSection is part of the GotSection, on other Targets it is 943 // part of the .got.plt 944 IgotPltSection::IgotPltSection() 945 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 946 Target->GotPltEntrySize, 947 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {} 948 949 void IgotPltSection::addEntry(SymbolBody &Sym) { 950 Sym.IsInIgot = true; 951 Sym.GotPltIndex = Entries.size(); 952 Entries.push_back(&Sym); 953 } 954 955 size_t IgotPltSection::getSize() const { 956 return Entries.size() * Target->GotPltEntrySize; 957 } 958 959 void IgotPltSection::writeTo(uint8_t *Buf) { 960 for (const SymbolBody *B : Entries) { 961 Target->writeIgotPlt(Buf, *B); 962 Buf += Config->Wordsize; 963 } 964 } 965 966 StringTableSection::StringTableSection(StringRef Name, bool Dynamic) 967 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name), 968 Dynamic(Dynamic) { 969 // ELF string tables start with a NUL byte. 970 addString(""); 971 } 972 973 // Adds a string to the string table. If HashIt is true we hash and check for 974 // duplicates. It is optional because the name of global symbols are already 975 // uniqued and hashing them again has a big cost for a small value: uniquing 976 // them with some other string that happens to be the same. 977 unsigned StringTableSection::addString(StringRef S, bool HashIt) { 978 if (HashIt) { 979 auto R = StringMap.insert(std::make_pair(S, this->Size)); 980 if (!R.second) 981 return R.first->second; 982 } 983 unsigned Ret = this->Size; 984 this->Size = this->Size + S.size() + 1; 985 Strings.push_back(S); 986 return Ret; 987 } 988 989 void StringTableSection::writeTo(uint8_t *Buf) { 990 for (StringRef S : Strings) { 991 memcpy(Buf, S.data(), S.size()); 992 Buf += S.size() + 1; 993 } 994 } 995 996 // Returns the number of version definition entries. Because the first entry 997 // is for the version definition itself, it is the number of versioned symbols 998 // plus one. Note that we don't support multiple versions yet. 999 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; } 1000 1001 template <class ELFT> 1002 DynamicSection<ELFT>::DynamicSection() 1003 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize, 1004 ".dynamic") { 1005 this->Entsize = ELFT::Is64Bits ? 16 : 8; 1006 1007 // .dynamic section is not writable on MIPS and on Fuchsia OS 1008 // which passes -z rodynamic. 1009 // See "Special Section" in Chapter 4 in the following document: 1010 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1011 if (Config->EMachine == EM_MIPS || Config->ZRodynamic) 1012 this->Flags = SHF_ALLOC; 1013 1014 addEntries(); 1015 } 1016 1017 // There are some dynamic entries that don't depend on other sections. 1018 // Such entries can be set early. 1019 template <class ELFT> void DynamicSection<ELFT>::addEntries() { 1020 // Add strings to .dynstr early so that .dynstr's size will be 1021 // fixed early. 1022 for (StringRef S : Config->AuxiliaryList) 1023 add({DT_AUXILIARY, InX::DynStrTab->addString(S)}); 1024 if (!Config->Rpath.empty()) 1025 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, 1026 InX::DynStrTab->addString(Config->Rpath)}); 1027 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles()) 1028 if (F->isNeeded()) 1029 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)}); 1030 if (!Config->SoName.empty()) 1031 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)}); 1032 1033 // Set DT_FLAGS and DT_FLAGS_1. 1034 uint32_t DtFlags = 0; 1035 uint32_t DtFlags1 = 0; 1036 if (Config->Bsymbolic) 1037 DtFlags |= DF_SYMBOLIC; 1038 if (Config->ZNodelete) 1039 DtFlags1 |= DF_1_NODELETE; 1040 if (Config->ZNodlopen) 1041 DtFlags1 |= DF_1_NOOPEN; 1042 if (Config->ZNow) { 1043 DtFlags |= DF_BIND_NOW; 1044 DtFlags1 |= DF_1_NOW; 1045 } 1046 if (Config->ZOrigin) { 1047 DtFlags |= DF_ORIGIN; 1048 DtFlags1 |= DF_1_ORIGIN; 1049 } 1050 1051 if (DtFlags) 1052 add({DT_FLAGS, DtFlags}); 1053 if (DtFlags1) 1054 add({DT_FLAGS_1, DtFlags1}); 1055 1056 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We 1057 // need it for each process, so we don't write it for DSOs. The loader writes 1058 // the pointer into this entry. 1059 // 1060 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some 1061 // systems (currently only Fuchsia OS) provide other means to give the 1062 // debugger this information. Such systems may choose make .dynamic read-only. 1063 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG. 1064 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic) 1065 add({DT_DEBUG, (uint64_t)0}); 1066 } 1067 1068 // Add remaining entries to complete .dynamic contents. 1069 template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { 1070 if (this->Size) 1071 return; // Already finalized. 1072 1073 this->Link = InX::DynStrTab->getParent()->SectionIndex; 1074 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) { 1075 bool IsRela = Config->IsRela; 1076 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn}); 1077 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent(), 1078 Entry::SecSize}); 1079 add({IsRela ? DT_RELAENT : DT_RELENT, 1080 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))}); 1081 1082 // MIPS dynamic loader does not support RELCOUNT tag. 1083 // The problem is in the tight relation between dynamic 1084 // relocations and GOT. So do not emit this tag on MIPS. 1085 if (Config->EMachine != EM_MIPS) { 1086 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount(); 1087 if (Config->ZCombreloc && NumRelativeRels) 1088 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels}); 1089 } 1090 } 1091 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) { 1092 add({DT_JMPREL, In<ELFT>::RelaPlt}); 1093 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent(), Entry::SecSize}); 1094 switch (Config->EMachine) { 1095 case EM_MIPS: 1096 add({DT_MIPS_PLTGOT, In<ELFT>::GotPlt}); 1097 break; 1098 case EM_SPARCV9: 1099 add({DT_PLTGOT, In<ELFT>::Plt}); 1100 break; 1101 default: 1102 add({DT_PLTGOT, In<ELFT>::GotPlt}); 1103 break; 1104 } 1105 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)}); 1106 } 1107 1108 add({DT_SYMTAB, InX::DynSymTab}); 1109 add({DT_SYMENT, sizeof(Elf_Sym)}); 1110 add({DT_STRTAB, InX::DynStrTab}); 1111 add({DT_STRSZ, InX::DynStrTab->getSize()}); 1112 if (!Config->ZText) 1113 add({DT_TEXTREL, (uint64_t)0}); 1114 if (InX::GnuHashTab) 1115 add({DT_GNU_HASH, InX::GnuHashTab}); 1116 if (In<ELFT>::HashTab) 1117 add({DT_HASH, In<ELFT>::HashTab}); 1118 1119 if (Out::PreinitArray) { 1120 add({DT_PREINIT_ARRAY, Out::PreinitArray}); 1121 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize}); 1122 } 1123 if (Out::InitArray) { 1124 add({DT_INIT_ARRAY, Out::InitArray}); 1125 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize}); 1126 } 1127 if (Out::FiniArray) { 1128 add({DT_FINI_ARRAY, Out::FiniArray}); 1129 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize}); 1130 } 1131 1132 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init)) 1133 add({DT_INIT, B}); 1134 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini)) 1135 add({DT_FINI, B}); 1136 1137 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0; 1138 if (HasVerNeed || In<ELFT>::VerDef) 1139 add({DT_VERSYM, In<ELFT>::VerSym}); 1140 if (In<ELFT>::VerDef) { 1141 add({DT_VERDEF, In<ELFT>::VerDef}); 1142 add({DT_VERDEFNUM, getVerDefNum()}); 1143 } 1144 if (HasVerNeed) { 1145 add({DT_VERNEED, In<ELFT>::VerNeed}); 1146 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()}); 1147 } 1148 1149 if (Config->EMachine == EM_MIPS) { 1150 add({DT_MIPS_RLD_VERSION, 1}); 1151 add({DT_MIPS_FLAGS, RHF_NOTPOT}); 1152 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase}); 1153 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()}); 1154 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()}); 1155 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry()) 1156 add({DT_MIPS_GOTSYM, B->DynsymIndex}); 1157 else 1158 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()}); 1159 add({DT_PLTGOT, InX::MipsGot}); 1160 if (InX::MipsRldMap) 1161 add({DT_MIPS_RLD_MAP, InX::MipsRldMap}); 1162 } 1163 1164 getParent()->Link = this->Link; 1165 1166 // +1 for DT_NULL 1167 this->Size = (Entries.size() + 1) * this->Entsize; 1168 } 1169 1170 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) { 1171 auto *P = reinterpret_cast<Elf_Dyn *>(Buf); 1172 1173 for (const Entry &E : Entries) { 1174 P->d_tag = E.Tag; 1175 switch (E.Kind) { 1176 case Entry::SecAddr: 1177 P->d_un.d_ptr = E.OutSec->Addr; 1178 break; 1179 case Entry::InSecAddr: 1180 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff; 1181 break; 1182 case Entry::SecSize: 1183 P->d_un.d_val = E.OutSec->Size; 1184 break; 1185 case Entry::SymAddr: 1186 P->d_un.d_ptr = E.Sym->getVA(); 1187 break; 1188 case Entry::PlainInt: 1189 P->d_un.d_val = E.Val; 1190 break; 1191 } 1192 ++P; 1193 } 1194 } 1195 1196 uint64_t DynamicReloc::getOffset() const { 1197 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec); 1198 } 1199 1200 int64_t DynamicReloc::getAddend() const { 1201 if (UseSymVA) 1202 return Sym->getVA(Addend); 1203 return Addend; 1204 } 1205 1206 uint32_t DynamicReloc::getSymIndex() const { 1207 if (Sym && !UseSymVA) 1208 return Sym->DynsymIndex; 1209 return 0; 1210 } 1211 1212 template <class ELFT> 1213 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort) 1214 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL, 1215 Config->Wordsize, Name), 1216 Sort(Sort) { 1217 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1218 } 1219 1220 template <class ELFT> 1221 void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) { 1222 if (Reloc.Type == Target->RelativeRel) 1223 ++NumRelativeRelocs; 1224 Relocs.push_back(Reloc); 1225 } 1226 1227 template <class ELFT, class RelTy> 1228 static bool compRelocations(const RelTy &A, const RelTy &B) { 1229 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel; 1230 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel; 1231 if (AIsRel != BIsRel) 1232 return AIsRel; 1233 1234 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL); 1235 } 1236 1237 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { 1238 uint8_t *BufBegin = Buf; 1239 for (const DynamicReloc &Rel : Relocs) { 1240 auto *P = reinterpret_cast<Elf_Rela *>(Buf); 1241 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 1242 1243 if (Config->IsRela) 1244 P->r_addend = Rel.getAddend(); 1245 P->r_offset = Rel.getOffset(); 1246 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot) 1247 // Dynamic relocation against MIPS GOT section make deal TLS entries 1248 // allocated in the end of the GOT. We need to adjust the offset to take 1249 // in account 'local' and 'global' GOT entries. 1250 P->r_offset += InX::MipsGot->getTlsOffset(); 1251 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL); 1252 } 1253 1254 if (Sort) { 1255 if (Config->IsRela) 1256 std::stable_sort((Elf_Rela *)BufBegin, 1257 (Elf_Rela *)BufBegin + Relocs.size(), 1258 compRelocations<ELFT, Elf_Rela>); 1259 else 1260 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(), 1261 compRelocations<ELFT, Elf_Rel>); 1262 } 1263 } 1264 1265 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() { 1266 return this->Entsize * Relocs.size(); 1267 } 1268 1269 template <class ELFT> void RelocationSection<ELFT>::finalizeContents() { 1270 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex 1271 : InX::SymTab->getParent()->SectionIndex; 1272 1273 // Set required output section properties. 1274 getParent()->Link = this->Link; 1275 } 1276 1277 SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec) 1278 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0, 1279 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, 1280 Config->Wordsize, 1281 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"), 1282 StrTabSec(StrTabSec) {} 1283 1284 // Orders symbols according to their positions in the GOT, 1285 // in compliance with MIPS ABI rules. 1286 // See "Global Offset Table" in Chapter 5 in the following document 1287 // for detailed description: 1288 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1289 static bool sortMipsSymbols(const SymbolTableEntry &L, 1290 const SymbolTableEntry &R) { 1291 // Sort entries related to non-local preemptible symbols by GOT indexes. 1292 // All other entries go to the first part of GOT in arbitrary order. 1293 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot; 1294 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot; 1295 if (LIsInLocalGot || RIsInLocalGot) 1296 return !RIsInLocalGot; 1297 return L.Symbol->GotIndex < R.Symbol->GotIndex; 1298 } 1299 1300 // Finalize a symbol table. The ELF spec requires that all local 1301 // symbols precede global symbols, so we sort symbol entries in this 1302 // function. (For .dynsym, we don't do that because symbols for 1303 // dynamic linking are inherently all globals.) 1304 void SymbolTableBaseSection::finalizeContents() { 1305 getParent()->Link = StrTabSec.getParent()->SectionIndex; 1306 1307 // If it is a .dynsym, there should be no local symbols, but we need 1308 // to do a few things for the dynamic linker. 1309 if (this->Type == SHT_DYNSYM) { 1310 // Section's Info field has the index of the first non-local symbol. 1311 // Because the first symbol entry is a null entry, 1 is the first. 1312 getParent()->Info = 1; 1313 1314 if (InX::GnuHashTab) { 1315 // NB: It also sorts Symbols to meet the GNU hash table requirements. 1316 InX::GnuHashTab->addSymbols(Symbols); 1317 } else if (Config->EMachine == EM_MIPS) { 1318 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols); 1319 } 1320 1321 size_t I = 0; 1322 for (const SymbolTableEntry &S : Symbols) 1323 S.Symbol->DynsymIndex = ++I; 1324 return; 1325 } 1326 } 1327 1328 void SymbolTableBaseSection::postThunkContents() { 1329 if (this->Type == SHT_DYNSYM) 1330 return; 1331 // move all local symbols before global symbols. 1332 auto It = std::stable_partition( 1333 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) { 1334 return S.Symbol->isLocal() || 1335 S.Symbol->symbol()->computeBinding() == STB_LOCAL; 1336 }); 1337 size_t NumLocals = It - Symbols.begin(); 1338 getParent()->Info = NumLocals + 1; 1339 } 1340 1341 void SymbolTableBaseSection::addSymbol(SymbolBody *B) { 1342 // Adding a local symbol to a .dynsym is a bug. 1343 assert(this->Type != SHT_DYNSYM || !B->isLocal()); 1344 1345 bool HashIt = B->isLocal(); 1346 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)}); 1347 } 1348 1349 size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) { 1350 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) { 1351 if (E.Symbol == Body) 1352 return true; 1353 // This is used for -r, so we have to handle multiple section 1354 // symbols being combined. 1355 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION) 1356 return Body->getOutputSection() == E.Symbol->getOutputSection(); 1357 return false; 1358 }); 1359 if (I == Symbols.end()) 1360 return 0; 1361 return I - Symbols.begin() + 1; 1362 } 1363 1364 template <class ELFT> 1365 SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec) 1366 : SymbolTableBaseSection(StrTabSec) { 1367 this->Entsize = sizeof(Elf_Sym); 1368 } 1369 1370 // Write the internal symbol table contents to the output symbol table. 1371 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { 1372 // The first entry is a null entry as per the ELF spec. 1373 Buf += sizeof(Elf_Sym); 1374 1375 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1376 1377 for (SymbolTableEntry &Ent : Symbols) { 1378 SymbolBody *Body = Ent.Symbol; 1379 1380 // Set st_info and st_other. 1381 if (Body->isLocal()) { 1382 ESym->setBindingAndType(STB_LOCAL, Body->Type); 1383 } else { 1384 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type); 1385 ESym->setVisibility(Body->symbol()->Visibility); 1386 } 1387 1388 ESym->st_name = Ent.StrTabOffset; 1389 1390 // Set a section index. 1391 if (const OutputSection *OutSec = Body->getOutputSection()) 1392 ESym->st_shndx = OutSec->SectionIndex; 1393 else if (isa<DefinedRegular>(Body)) 1394 ESym->st_shndx = SHN_ABS; 1395 else if (isa<DefinedCommon>(Body)) 1396 ESym->st_shndx = SHN_COMMON; 1397 1398 // Copy symbol size if it is a defined symbol. st_size is not significant 1399 // for undefined symbols, so whether copying it or not is up to us if that's 1400 // the case. We'll leave it as zero because by not setting a value, we can 1401 // get the exact same outputs for two sets of input files that differ only 1402 // in undefined symbol size in DSOs. 1403 if (ESym->st_shndx != SHN_UNDEF) 1404 ESym->st_size = Body->getSize<ELFT>(); 1405 1406 // st_value is usually an address of a symbol, but that has a 1407 // special meaining for uninstantiated common symbols (this can 1408 // occur if -r is given). 1409 if (!Config->DefineCommon && isa<DefinedCommon>(Body)) 1410 ESym->st_value = cast<DefinedCommon>(Body)->Alignment; 1411 else 1412 ESym->st_value = Body->getVA(); 1413 1414 ++ESym; 1415 } 1416 1417 // On MIPS we need to mark symbol which has a PLT entry and requires 1418 // pointer equality by STO_MIPS_PLT flag. That is necessary to help 1419 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs. 1420 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt 1421 if (Config->EMachine == EM_MIPS) { 1422 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1423 1424 for (SymbolTableEntry &Ent : Symbols) { 1425 SymbolBody *Body = Ent.Symbol; 1426 if (Body->isInPlt() && Body->NeedsPltAddr) 1427 ESym->st_other |= STO_MIPS_PLT; 1428 1429 if (Config->Relocatable) 1430 if (auto *D = dyn_cast<DefinedRegular>(Body)) 1431 if (D->isMipsPIC<ELFT>()) 1432 ESym->st_other |= STO_MIPS_PIC; 1433 ++ESym; 1434 } 1435 } 1436 } 1437 1438 // .hash and .gnu.hash sections contain on-disk hash tables that map 1439 // symbol names to their dynamic symbol table indices. Their purpose 1440 // is to help the dynamic linker resolve symbols quickly. If ELF files 1441 // don't have them, the dynamic linker has to do linear search on all 1442 // dynamic symbols, which makes programs slower. Therefore, a .hash 1443 // section is added to a DSO by default. A .gnu.hash is added if you 1444 // give the -hash-style=gnu or -hash-style=both option. 1445 // 1446 // The Unix semantics of resolving dynamic symbols is somewhat expensive. 1447 // Each ELF file has a list of DSOs that the ELF file depends on and a 1448 // list of dynamic symbols that need to be resolved from any of the 1449 // DSOs. That means resolving all dynamic symbols takes O(m)*O(n) 1450 // where m is the number of DSOs and n is the number of dynamic 1451 // symbols. For modern large programs, both m and n are large. So 1452 // making each step faster by using hash tables substiantially 1453 // improves time to load programs. 1454 // 1455 // (Note that this is not the only way to design the shared library. 1456 // For instance, the Windows DLL takes a different approach. On 1457 // Windows, each dynamic symbol has a name of DLL from which the symbol 1458 // has to be resolved. That makes the cost of symbol resolution O(n). 1459 // This disables some hacky techniques you can use on Unix such as 1460 // LD_PRELOAD, but this is arguably better semantics than the Unix ones.) 1461 // 1462 // Due to historical reasons, we have two different hash tables, .hash 1463 // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new 1464 // and better version of .hash. .hash is just an on-disk hash table, but 1465 // .gnu.hash has a bloom filter in addition to a hash table to skip 1466 // DSOs very quickly. If you are sure that your dynamic linker knows 1467 // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a 1468 // safe bet is to specify -hash-style=both for backward compatibilty. 1469 GnuHashTableSection::GnuHashTableSection() 1470 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") { 1471 } 1472 1473 void GnuHashTableSection::finalizeContents() { 1474 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 1475 1476 // Computes bloom filter size in word size. We want to allocate 8 1477 // bits for each symbol. It must be a power of two. 1478 if (Symbols.empty()) 1479 MaskWords = 1; 1480 else 1481 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize); 1482 1483 Size = 16; // Header 1484 Size += Config->Wordsize * MaskWords; // Bloom filter 1485 Size += NBuckets * 4; // Hash buckets 1486 Size += Symbols.size() * 4; // Hash values 1487 } 1488 1489 void GnuHashTableSection::writeTo(uint8_t *Buf) { 1490 // Write a header. 1491 write32(Buf, NBuckets, Config->Endianness); 1492 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(), 1493 Config->Endianness); 1494 write32(Buf + 8, MaskWords, Config->Endianness); 1495 write32(Buf + 12, getShift2(), Config->Endianness); 1496 Buf += 16; 1497 1498 // Write a bloom filter and a hash table. 1499 writeBloomFilter(Buf); 1500 Buf += Config->Wordsize * MaskWords; 1501 writeHashTable(Buf); 1502 } 1503 1504 // This function writes a 2-bit bloom filter. This bloom filter alone 1505 // usually filters out 80% or more of all symbol lookups [1]. 1506 // The dynamic linker uses the hash table only when a symbol is not 1507 // filtered out by a bloom filter. 1508 // 1509 // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2), 1510 // p.9, https://www.akkadia.org/drepper/dsohowto.pdf 1511 void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) { 1512 const unsigned C = Config->Wordsize * 8; 1513 for (const Entry &Sym : Symbols) { 1514 size_t I = (Sym.Hash / C) & (MaskWords - 1); 1515 uint64_t Val = readUint(Buf + I * Config->Wordsize); 1516 Val |= uint64_t(1) << (Sym.Hash % C); 1517 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C); 1518 writeUint(Buf + I * Config->Wordsize, Val); 1519 } 1520 } 1521 1522 void GnuHashTableSection::writeHashTable(uint8_t *Buf) { 1523 // Group symbols by hash value. 1524 std::vector<std::vector<Entry>> Syms(NBuckets); 1525 for (const Entry &Ent : Symbols) 1526 Syms[Ent.Hash % NBuckets].push_back(Ent); 1527 1528 // Write hash buckets. Hash buckets contain indices in the following 1529 // hash value table. 1530 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf); 1531 for (size_t I = 0; I < NBuckets; ++I) 1532 if (!Syms[I].empty()) 1533 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness); 1534 1535 // Write a hash value table. It represents a sequence of chains that 1536 // share the same hash modulo value. The last element of each chain 1537 // is terminated by LSB 1. 1538 uint32_t *Values = Buckets + NBuckets; 1539 size_t I = 0; 1540 for (std::vector<Entry> &Vec : Syms) { 1541 if (Vec.empty()) 1542 continue; 1543 for (const Entry &Ent : makeArrayRef(Vec).drop_back()) 1544 write32(Values + I++, Ent.Hash & ~1, Config->Endianness); 1545 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness); 1546 } 1547 } 1548 1549 static uint32_t hashGnu(StringRef Name) { 1550 uint32_t H = 5381; 1551 for (uint8_t C : Name) 1552 H = (H << 5) + H + C; 1553 return H; 1554 } 1555 1556 // Returns a number of hash buckets to accomodate given number of elements. 1557 // We want to choose a moderate number that is not too small (which 1558 // causes too many hash collisions) and not too large (which wastes 1559 // disk space.) 1560 // 1561 // We return a prime number because it (is believed to) achieve good 1562 // hash distribution. 1563 static size_t getBucketSize(size_t NumSymbols) { 1564 // List of largest prime numbers that are not greater than 2^n + 1. 1565 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509, 1566 251, 127, 61, 31, 13, 7, 3, 1}) 1567 if (N <= NumSymbols) 1568 return N; 1569 return 0; 1570 } 1571 1572 // Add symbols to this symbol hash table. Note that this function 1573 // destructively sort a given vector -- which is needed because 1574 // GNU-style hash table places some sorting requirements. 1575 void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) { 1576 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce 1577 // its type correctly. 1578 std::vector<SymbolTableEntry>::iterator Mid = 1579 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) { 1580 return S.Symbol->isUndefined(); 1581 }); 1582 if (Mid == V.end()) 1583 return; 1584 1585 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) { 1586 SymbolBody *B = Ent.Symbol; 1587 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())}); 1588 } 1589 1590 NBuckets = getBucketSize(Symbols.size()); 1591 std::stable_sort(Symbols.begin(), Symbols.end(), 1592 [&](const Entry &L, const Entry &R) { 1593 return L.Hash % NBuckets < R.Hash % NBuckets; 1594 }); 1595 1596 V.erase(Mid, V.end()); 1597 for (const Entry &Ent : Symbols) 1598 V.push_back({Ent.Body, Ent.StrTabOffset}); 1599 } 1600 1601 template <class ELFT> 1602 HashTableSection<ELFT>::HashTableSection() 1603 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") { 1604 this->Entsize = 4; 1605 } 1606 1607 template <class ELFT> void HashTableSection<ELFT>::finalizeContents() { 1608 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 1609 1610 unsigned NumEntries = 2; // nbucket and nchain. 1611 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries. 1612 1613 // Create as many buckets as there are symbols. 1614 // FIXME: This is simplistic. We can try to optimize it, but implementing 1615 // support for SHT_GNU_HASH is probably even more profitable. 1616 NumEntries += InX::DynSymTab->getNumSymbols(); 1617 this->Size = NumEntries * 4; 1618 } 1619 1620 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { 1621 // A 32-bit integer type in the target endianness. 1622 typedef typename ELFT::Word Elf_Word; 1623 1624 unsigned NumSymbols = InX::DynSymTab->getNumSymbols(); 1625 1626 auto *P = reinterpret_cast<Elf_Word *>(Buf); 1627 *P++ = NumSymbols; // nbucket 1628 *P++ = NumSymbols; // nchain 1629 1630 Elf_Word *Buckets = P; 1631 Elf_Word *Chains = P + NumSymbols; 1632 1633 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { 1634 SymbolBody *Body = S.Symbol; 1635 StringRef Name = Body->getName(); 1636 unsigned I = Body->DynsymIndex; 1637 uint32_t Hash = hashSysV(Name) % NumSymbols; 1638 Chains[I] = Buckets[Hash]; 1639 Buckets[Hash] = I; 1640 } 1641 } 1642 1643 PltSection::PltSection(size_t S) 1644 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"), 1645 HeaderSize(S) { 1646 // The PLT needs to be writable on SPARC as the dynamic linker will 1647 // modify the instructions in the PLT entries. 1648 if (Config->EMachine == EM_SPARCV9) 1649 this->Flags |= SHF_WRITE; 1650 } 1651 1652 void PltSection::writeTo(uint8_t *Buf) { 1653 // At beginning of PLT but not the IPLT, we have code to call the dynamic 1654 // linker to resolve dynsyms at runtime. Write such code. 1655 if (HeaderSize != 0) 1656 Target->writePltHeader(Buf); 1657 size_t Off = HeaderSize; 1658 // The IPlt is immediately after the Plt, account for this in RelOff 1659 unsigned PltOff = getPltRelocOff(); 1660 1661 for (auto &I : Entries) { 1662 const SymbolBody *B = I.first; 1663 unsigned RelOff = I.second + PltOff; 1664 uint64_t Got = B->getGotPltVA(); 1665 uint64_t Plt = this->getVA() + Off; 1666 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); 1667 Off += Target->PltEntrySize; 1668 } 1669 } 1670 1671 template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) { 1672 Sym.PltIndex = Entries.size(); 1673 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt; 1674 if (HeaderSize == 0) { 1675 PltRelocSection = In<ELFT>::RelaIplt; 1676 Sym.IsInIplt = true; 1677 } 1678 unsigned RelOff = PltRelocSection->getRelocOffset(); 1679 Entries.push_back(std::make_pair(&Sym, RelOff)); 1680 } 1681 1682 size_t PltSection::getSize() const { 1683 return HeaderSize + Entries.size() * Target->PltEntrySize; 1684 } 1685 1686 // Some architectures such as additional symbols in the PLT section. For 1687 // example ARM uses mapping symbols to aid disassembly 1688 void PltSection::addSymbols() { 1689 // The PLT may have symbols defined for the Header, the IPLT has no header 1690 if (HeaderSize != 0) 1691 Target->addPltHeaderSymbols(this); 1692 size_t Off = HeaderSize; 1693 for (size_t I = 0; I < Entries.size(); ++I) { 1694 Target->addPltSymbols(this, Off); 1695 Off += Target->PltEntrySize; 1696 } 1697 } 1698 1699 unsigned PltSection::getPltRelocOff() const { 1700 return (HeaderSize == 0) ? InX::Plt->getSize() : 0; 1701 } 1702 1703 GdbIndexSection::GdbIndexSection() 1704 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), 1705 StringPool(llvm::StringTableBuilder::ELF) {} 1706 1707 // Iterative hash function for symbol's name is described in .gdb_index format 1708 // specification. Note that we use one for version 5 to 7 here, it is different 1709 // for version 4. 1710 static uint32_t hash(StringRef Str) { 1711 uint32_t R = 0; 1712 for (uint8_t C : Str) 1713 R = R * 67 + tolower(C) - 113; 1714 return R; 1715 } 1716 1717 static std::vector<CompilationUnitEntry> readCuList(DWARFContext &Dwarf, 1718 InputSection *Sec) { 1719 std::vector<CompilationUnitEntry> Ret; 1720 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) 1721 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4}); 1722 return Ret; 1723 } 1724 1725 static std::vector<AddressEntry> readAddressArea(DWARFContext &Dwarf, 1726 InputSection *Sec) { 1727 std::vector<AddressEntry> Ret; 1728 1729 uint32_t CurrentCu = 0; 1730 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) { 1731 DWARFAddressRangesVector Ranges; 1732 CU->collectAddressRanges(Ranges); 1733 1734 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections(); 1735 for (DWARFAddressRange &R : Ranges) { 1736 InputSectionBase *S = Sections[R.SectionIndex]; 1737 if (!S || S == &InputSection::Discarded || !S->Live) 1738 continue; 1739 // Range list with zero size has no effect. 1740 if (R.LowPC == R.HighPC) 1741 continue; 1742 Ret.push_back({cast<InputSection>(S), R.LowPC, R.HighPC, CurrentCu}); 1743 } 1744 ++CurrentCu; 1745 } 1746 return Ret; 1747 } 1748 1749 static std::vector<NameTypeEntry> readPubNamesAndTypes(DWARFContext &Dwarf, 1750 bool IsLE) { 1751 StringRef Data[] = {Dwarf.getGnuPubNamesSection(), 1752 Dwarf.getGnuPubTypesSection()}; 1753 1754 std::vector<NameTypeEntry> Ret; 1755 for (StringRef D : Data) { 1756 DWARFDebugPubTable PubTable(D, IsLE, true); 1757 for (const DWARFDebugPubTable::Set &Set : PubTable.getData()) 1758 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) 1759 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()}); 1760 } 1761 return Ret; 1762 } 1763 1764 static std::vector<InputSection *> getDebugInfoSections() { 1765 std::vector<InputSection *> Ret; 1766 for (InputSectionBase *S : InputSections) 1767 if (InputSection *IS = dyn_cast<InputSection>(S)) 1768 if (IS->getParent() && IS->Name == ".debug_info") 1769 Ret.push_back(IS); 1770 return Ret; 1771 } 1772 1773 void GdbIndexSection::buildIndex() { 1774 std::vector<InputSection *> V = getDebugInfoSections(); 1775 if (V.empty()) 1776 return; 1777 1778 for (InputSection *Sec : V) 1779 Chunks.push_back(readDwarf(Sec)); 1780 1781 uint32_t CuId = 0; 1782 for (GdbIndexChunk &D : Chunks) { 1783 for (AddressEntry &E : D.AddressArea) 1784 E.CuIndex += CuId; 1785 1786 // Populate constant pool area. 1787 for (NameTypeEntry &NameType : D.NamesAndTypes) { 1788 uint32_t Hash = hash(NameType.Name); 1789 size_t Offset = StringPool.add(NameType.Name); 1790 1791 bool IsNew; 1792 GdbSymbol *Sym; 1793 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset); 1794 if (IsNew) { 1795 Sym->CuVectorIndex = CuVectors.size(); 1796 CuVectors.resize(CuVectors.size() + 1); 1797 } 1798 1799 CuVectors[Sym->CuVectorIndex].insert(CuId | (NameType.Type << 24)); 1800 } 1801 1802 CuId += D.CompilationUnits.size(); 1803 } 1804 } 1805 1806 GdbIndexChunk GdbIndexSection::readDwarf(InputSection *Sec) { 1807 Expected<std::unique_ptr<object::ObjectFile>> Obj = 1808 object::ObjectFile::createObjectFile(Sec->File->MB); 1809 if (!Obj) { 1810 error(toString(Sec->File) + ": error creating DWARF context"); 1811 return {}; 1812 } 1813 1814 DWARFContextInMemory Dwarf(*Obj.get(), nullptr, [&](Error E) { 1815 error(toString(Sec->File) + ": error parsing DWARF data:\n>>> " + 1816 toString(std::move(E))); 1817 return ErrorPolicy::Continue; 1818 }); 1819 1820 GdbIndexChunk Ret; 1821 Ret.CompilationUnits = readCuList(Dwarf, Sec); 1822 Ret.AddressArea = readAddressArea(Dwarf, Sec); 1823 Ret.NamesAndTypes = readPubNamesAndTypes(Dwarf, Config->IsLE); 1824 return Ret; 1825 } 1826 1827 static size_t getCuSize(std::vector<GdbIndexChunk> &C) { 1828 size_t Ret = 0; 1829 for (GdbIndexChunk &D : C) 1830 Ret += D.CompilationUnits.size(); 1831 return Ret; 1832 } 1833 1834 static size_t getAddressAreaSize(std::vector<GdbIndexChunk> &C) { 1835 size_t Ret = 0; 1836 for (GdbIndexChunk &D : C) 1837 Ret += D.AddressArea.size(); 1838 return Ret; 1839 } 1840 1841 void GdbIndexSection::finalizeContents() { 1842 if (Finalized) 1843 return; 1844 Finalized = true; 1845 1846 buildIndex(); 1847 1848 SymbolTable.finalizeContents(); 1849 1850 // GdbIndex header consist from version fields 1851 // and 5 more fields with different kinds of offsets. 1852 CuTypesOffset = CuListOffset + getCuSize(Chunks) * CompilationUnitSize; 1853 SymTabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * AddressEntrySize; 1854 1855 ConstantPoolOffset = 1856 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize; 1857 1858 for (std::set<uint32_t> &CuVec : CuVectors) { 1859 CuVectorsOffset.push_back(CuVectorsSize); 1860 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1); 1861 } 1862 StringPoolOffset = ConstantPoolOffset + CuVectorsSize; 1863 1864 StringPool.finalizeInOrder(); 1865 } 1866 1867 size_t GdbIndexSection::getSize() const { 1868 const_cast<GdbIndexSection *>(this)->finalizeContents(); 1869 return StringPoolOffset + StringPool.getSize(); 1870 } 1871 1872 void GdbIndexSection::writeTo(uint8_t *Buf) { 1873 write32le(Buf, 7); // Write version. 1874 write32le(Buf + 4, CuListOffset); // CU list offset. 1875 write32le(Buf + 8, CuTypesOffset); // Types CU list offset. 1876 write32le(Buf + 12, CuTypesOffset); // Address area offset. 1877 write32le(Buf + 16, SymTabOffset); // Symbol table offset. 1878 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset. 1879 Buf += 24; 1880 1881 // Write the CU list. 1882 for (GdbIndexChunk &D : Chunks) { 1883 for (CompilationUnitEntry &Cu : D.CompilationUnits) { 1884 write64le(Buf, Cu.CuOffset); 1885 write64le(Buf + 8, Cu.CuLength); 1886 Buf += 16; 1887 } 1888 } 1889 1890 // Write the address area. 1891 for (GdbIndexChunk &D : Chunks) { 1892 for (AddressEntry &E : D.AddressArea) { 1893 uint64_t BaseAddr = 1894 E.Section->getParent()->Addr + E.Section->getOffset(0); 1895 write64le(Buf, BaseAddr + E.LowAddress); 1896 write64le(Buf + 8, BaseAddr + E.HighAddress); 1897 write32le(Buf + 16, E.CuIndex); 1898 Buf += 20; 1899 } 1900 } 1901 1902 // Write the symbol table. 1903 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) { 1904 GdbSymbol *Sym = SymbolTable.getSymbol(I); 1905 if (Sym) { 1906 size_t NameOffset = 1907 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset; 1908 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex]; 1909 write32le(Buf, NameOffset); 1910 write32le(Buf + 4, CuVectorOffset); 1911 } 1912 Buf += 8; 1913 } 1914 1915 // Write the CU vectors into the constant pool. 1916 for (std::set<uint32_t> &CuVec : CuVectors) { 1917 write32le(Buf, CuVec.size()); 1918 Buf += 4; 1919 for (uint32_t Val : CuVec) { 1920 write32le(Buf, Val); 1921 Buf += 4; 1922 } 1923 } 1924 1925 StringPool.write(Buf); 1926 } 1927 1928 bool GdbIndexSection::empty() const { 1929 return !Out::DebugInfo; 1930 } 1931 1932 template <class ELFT> 1933 EhFrameHeader<ELFT>::EhFrameHeader() 1934 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {} 1935 1936 // .eh_frame_hdr contains a binary search table of pointers to FDEs. 1937 // Each entry of the search table consists of two values, 1938 // the starting PC from where FDEs covers, and the FDE's address. 1939 // It is sorted by PC. 1940 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) { 1941 const endianness E = ELFT::TargetEndianness; 1942 1943 // Sort the FDE list by their PC and uniqueify. Usually there is only 1944 // one FDE for a PC (i.e. function), but if ICF merges two functions 1945 // into one, there can be more than one FDEs pointing to the address. 1946 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; }; 1947 std::stable_sort(Fdes.begin(), Fdes.end(), Less); 1948 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; }; 1949 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end()); 1950 1951 Buf[0] = 1; 1952 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4; 1953 Buf[2] = DW_EH_PE_udata4; 1954 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4; 1955 write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4); 1956 write32<E>(Buf + 8, Fdes.size()); 1957 Buf += 12; 1958 1959 uint64_t VA = this->getVA(); 1960 for (FdeData &Fde : Fdes) { 1961 write32<E>(Buf, Fde.Pc - VA); 1962 write32<E>(Buf + 4, Fde.FdeVA - VA); 1963 Buf += 8; 1964 } 1965 } 1966 1967 template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const { 1968 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs. 1969 return 12 + In<ELFT>::EhFrame->NumFdes * 8; 1970 } 1971 1972 template <class ELFT> 1973 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) { 1974 Fdes.push_back({Pc, FdeVA}); 1975 } 1976 1977 template <class ELFT> bool EhFrameHeader<ELFT>::empty() const { 1978 return In<ELFT>::EhFrame->empty(); 1979 } 1980 1981 template <class ELFT> 1982 VersionDefinitionSection<ELFT>::VersionDefinitionSection() 1983 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t), 1984 ".gnu.version_d") {} 1985 1986 static StringRef getFileDefName() { 1987 if (!Config->SoName.empty()) 1988 return Config->SoName; 1989 return Config->OutputFile; 1990 } 1991 1992 template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() { 1993 FileDefNameOff = InX::DynStrTab->addString(getFileDefName()); 1994 for (VersionDefinition &V : Config->VersionDefinitions) 1995 V.NameOff = InX::DynStrTab->addString(V.Name); 1996 1997 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; 1998 1999 // sh_info should be set to the number of definitions. This fact is missed in 2000 // documentation, but confirmed by binutils community: 2001 // https://sourceware.org/ml/binutils/2014-11/msg00355.html 2002 getParent()->Info = getVerDefNum(); 2003 } 2004 2005 template <class ELFT> 2006 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index, 2007 StringRef Name, size_t NameOff) { 2008 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf); 2009 Verdef->vd_version = 1; 2010 Verdef->vd_cnt = 1; 2011 Verdef->vd_aux = sizeof(Elf_Verdef); 2012 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); 2013 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0); 2014 Verdef->vd_ndx = Index; 2015 Verdef->vd_hash = hashSysV(Name); 2016 2017 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef)); 2018 Verdaux->vda_name = NameOff; 2019 Verdaux->vda_next = 0; 2020 } 2021 2022 template <class ELFT> 2023 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) { 2024 writeOne(Buf, 1, getFileDefName(), FileDefNameOff); 2025 2026 for (VersionDefinition &V : Config->VersionDefinitions) { 2027 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); 2028 writeOne(Buf, V.Id, V.Name, V.NameOff); 2029 } 2030 2031 // Need to terminate the last version definition. 2032 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf); 2033 Verdef->vd_next = 0; 2034 } 2035 2036 template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const { 2037 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum(); 2038 } 2039 2040 template <class ELFT> 2041 VersionTableSection<ELFT>::VersionTableSection() 2042 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t), 2043 ".gnu.version") { 2044 this->Entsize = sizeof(Elf_Versym); 2045 } 2046 2047 template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() { 2048 // At the moment of june 2016 GNU docs does not mention that sh_link field 2049 // should be set, but Sun docs do. Also readelf relies on this field. 2050 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; 2051 } 2052 2053 template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const { 2054 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1); 2055 } 2056 2057 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) { 2058 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1; 2059 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { 2060 OutVersym->vs_index = S.Symbol->symbol()->VersionId; 2061 ++OutVersym; 2062 } 2063 } 2064 2065 template <class ELFT> bool VersionTableSection<ELFT>::empty() const { 2066 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty(); 2067 } 2068 2069 template <class ELFT> 2070 VersionNeedSection<ELFT>::VersionNeedSection() 2071 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t), 2072 ".gnu.version_r") { 2073 // Identifiers in verneed section start at 2 because 0 and 1 are reserved 2074 // for VER_NDX_LOCAL and VER_NDX_GLOBAL. 2075 // First identifiers are reserved by verdef section if it exist. 2076 NextIndex = getVerDefNum() + 1; 2077 } 2078 2079 template <class ELFT> 2080 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) { 2081 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef); 2082 if (!Ver) { 2083 SS->symbol()->VersionId = VER_NDX_GLOBAL; 2084 return; 2085 } 2086 2087 auto *File = cast<SharedFile<ELFT>>(SS->File); 2088 2089 // If we don't already know that we need an Elf_Verneed for this DSO, prepare 2090 // to create one by adding it to our needed list and creating a dynstr entry 2091 // for the soname. 2092 if (File->VerdefMap.empty()) 2093 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)}); 2094 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver]; 2095 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, 2096 // prepare to create one by allocating a version identifier and creating a 2097 // dynstr entry for the version name. 2098 if (NV.Index == 0) { 2099 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() + 2100 Ver->getAux()->vda_name); 2101 NV.Index = NextIndex++; 2102 } 2103 SS->symbol()->VersionId = NV.Index; 2104 } 2105 2106 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { 2107 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. 2108 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf); 2109 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size()); 2110 2111 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) { 2112 // Create an Elf_Verneed for this DSO. 2113 Verneed->vn_version = 1; 2114 Verneed->vn_cnt = P.first->VerdefMap.size(); 2115 Verneed->vn_file = P.second; 2116 Verneed->vn_aux = 2117 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed); 2118 Verneed->vn_next = sizeof(Elf_Verneed); 2119 ++Verneed; 2120 2121 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over 2122 // VerdefMap, which will only contain references to needed version 2123 // definitions. Each Elf_Vernaux is based on the information contained in 2124 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of 2125 // pointers, but is deterministic because the pointers refer to Elf_Verdef 2126 // data structures within a single input file. 2127 for (auto &NV : P.first->VerdefMap) { 2128 Vernaux->vna_hash = NV.first->vd_hash; 2129 Vernaux->vna_flags = 0; 2130 Vernaux->vna_other = NV.second.Index; 2131 Vernaux->vna_name = NV.second.StrTab; 2132 Vernaux->vna_next = sizeof(Elf_Vernaux); 2133 ++Vernaux; 2134 } 2135 2136 Vernaux[-1].vna_next = 0; 2137 } 2138 Verneed[-1].vn_next = 0; 2139 } 2140 2141 template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() { 2142 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; 2143 getParent()->Info = Needed.size(); 2144 } 2145 2146 template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const { 2147 unsigned Size = Needed.size() * sizeof(Elf_Verneed); 2148 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed) 2149 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux); 2150 return Size; 2151 } 2152 2153 template <class ELFT> bool VersionNeedSection<ELFT>::empty() const { 2154 return getNeedNum() == 0; 2155 } 2156 2157 MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type, 2158 uint64_t Flags, uint32_t Alignment) 2159 : SyntheticSection(Flags, Type, Alignment, Name), 2160 Builder(StringTableBuilder::RAW, Alignment) {} 2161 2162 void MergeSyntheticSection::addSection(MergeInputSection *MS) { 2163 MS->Parent = this; 2164 Sections.push_back(MS); 2165 } 2166 2167 void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); } 2168 2169 bool MergeSyntheticSection::shouldTailMerge() const { 2170 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2; 2171 } 2172 2173 void MergeSyntheticSection::finalizeTailMerge() { 2174 // Add all string pieces to the string table builder to create section 2175 // contents. 2176 for (MergeInputSection *Sec : Sections) 2177 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2178 if (Sec->Pieces[I].Live) 2179 Builder.add(Sec->getData(I)); 2180 2181 // Fix the string table content. After this, the contents will never change. 2182 Builder.finalize(); 2183 2184 // finalize() fixed tail-optimized strings, so we can now get 2185 // offsets of strings. Get an offset for each string and save it 2186 // to a corresponding StringPiece for easy access. 2187 for (MergeInputSection *Sec : Sections) 2188 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2189 if (Sec->Pieces[I].Live) 2190 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I)); 2191 } 2192 2193 void MergeSyntheticSection::finalizeNoTailMerge() { 2194 // Add all string pieces to the string table builder to create section 2195 // contents. Because we are not tail-optimizing, offsets of strings are 2196 // fixed when they are added to the builder (string table builder contains 2197 // a hash table from strings to offsets). 2198 for (MergeInputSection *Sec : Sections) 2199 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) 2200 if (Sec->Pieces[I].Live) 2201 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I)); 2202 2203 Builder.finalizeInOrder(); 2204 } 2205 2206 void MergeSyntheticSection::finalizeContents() { 2207 if (shouldTailMerge()) 2208 finalizeTailMerge(); 2209 else 2210 finalizeNoTailMerge(); 2211 } 2212 2213 size_t MergeSyntheticSection::getSize() const { 2214 return Builder.getSize(); 2215 } 2216 2217 // This function decompresses compressed sections and scans over the input 2218 // sections to create mergeable synthetic sections. It removes 2219 // MergeInputSections from the input section array and adds new synthetic 2220 // sections at the location of the first input section that it replaces. It then 2221 // finalizes each synthetic section in order to compute an output offset for 2222 // each piece of each input section. 2223 void elf::decompressAndMergeSections() { 2224 // splitIntoPieces needs to be called on each MergeInputSection before calling 2225 // finalizeContents(). Do that first. 2226 parallelForEach(InputSections.begin(), InputSections.end(), 2227 [](InputSectionBase *S) { 2228 if (!S->Live) 2229 return; 2230 if (Decompressor::isCompressedELFSection(S->Flags, S->Name)) 2231 S->uncompress(); 2232 if (auto *MS = dyn_cast<MergeInputSection>(S)) 2233 MS->splitIntoPieces(); 2234 }); 2235 2236 std::vector<MergeSyntheticSection *> MergeSections; 2237 for (InputSectionBase *&S : InputSections) { 2238 MergeInputSection *MS = dyn_cast<MergeInputSection>(S); 2239 if (!MS) 2240 continue; 2241 2242 // We do not want to handle sections that are not alive, so just remove 2243 // them instead of trying to merge. 2244 if (!MS->Live) 2245 continue; 2246 2247 StringRef OutsecName = getOutputSectionName(MS->Name); 2248 uint64_t Flags = MS->Flags & ~(uint64_t)SHF_GROUP; 2249 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize); 2250 2251 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { 2252 return Sec->Name == OutsecName && Sec->Flags == Flags && 2253 Sec->Alignment == Alignment; 2254 }); 2255 if (I == MergeSections.end()) { 2256 MergeSyntheticSection *Syn = 2257 make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment); 2258 MergeSections.push_back(Syn); 2259 I = std::prev(MergeSections.end()); 2260 S = Syn; 2261 } else { 2262 S = nullptr; 2263 } 2264 (*I)->addSection(MS); 2265 } 2266 for (auto *MS : MergeSections) 2267 MS->finalizeContents(); 2268 2269 std::vector<InputSectionBase *> &V = InputSections; 2270 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); 2271 } 2272 2273 MipsRldMapSection::MipsRldMapSection() 2274 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize, 2275 ".rld_map") {} 2276 2277 ARMExidxSentinelSection::ARMExidxSentinelSection() 2278 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX, 2279 Config->Wordsize, ".ARM.exidx") {} 2280 2281 // Write a terminating sentinel entry to the end of the .ARM.exidx table. 2282 // This section will have been sorted last in the .ARM.exidx table. 2283 // This table entry will have the form: 2284 // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND | 2285 // The sentinel must have the PREL31 value of an address higher than any 2286 // address described by any other table entry. 2287 void ARMExidxSentinelSection::writeTo(uint8_t *Buf) { 2288 // The Sections are sorted in order of ascending PREL31 address with the 2289 // sentinel last. We need to find the InputSection that precedes the 2290 // sentinel. By construction the Sentinel is in the last 2291 // InputSectionDescription as the InputSection that precedes it. 2292 OutputSectionCommand *C = Script->getCmd(getParent()); 2293 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(), 2294 [](const BaseCommand *Base) { 2295 return isa<InputSectionDescription>(Base); 2296 }); 2297 auto L = cast<InputSectionDescription>(*ISD); 2298 InputSection *Highest = L->Sections[L->Sections.size() - 2]; 2299 InputSection *LS = Highest->getLinkOrderDep(); 2300 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize()); 2301 uint64_t P = getVA(); 2302 Target->relocateOne(Buf, R_ARM_PREL31, S - P); 2303 write32le(Buf + 4, 0x1); 2304 } 2305 2306 ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off) 2307 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 2308 Config->Wordsize, ".text.thunk") { 2309 this->Parent = OS; 2310 this->OutSecOff = Off; 2311 } 2312 2313 void ThunkSection::addThunk(Thunk *T) { 2314 uint64_t Off = alignTo(Size, T->alignment); 2315 T->Offset = Off; 2316 Thunks.push_back(T); 2317 T->addSymbols(*this); 2318 Size = Off + T->size(); 2319 } 2320 2321 void ThunkSection::writeTo(uint8_t *Buf) { 2322 for (const Thunk *T : Thunks) 2323 T->writeTo(Buf + T->Offset, *this); 2324 } 2325 2326 InputSection *ThunkSection::getTargetInputSection() const { 2327 const Thunk *T = Thunks.front(); 2328 return T->getTargetInputSection(); 2329 } 2330 2331 InputSection *InX::ARMAttributes; 2332 BssSection *InX::Bss; 2333 BssSection *InX::BssRelRo; 2334 BuildIdSection *InX::BuildId; 2335 InputSection *InX::Common; 2336 SyntheticSection *InX::Dynamic; 2337 StringTableSection *InX::DynStrTab; 2338 SymbolTableBaseSection *InX::DynSymTab; 2339 InputSection *InX::Interp; 2340 GdbIndexSection *InX::GdbIndex; 2341 GotSection *InX::Got; 2342 GotPltSection *InX::GotPlt; 2343 GnuHashTableSection *InX::GnuHashTab; 2344 IgotPltSection *InX::IgotPlt; 2345 MipsGotSection *InX::MipsGot; 2346 MipsRldMapSection *InX::MipsRldMap; 2347 PltSection *InX::Plt; 2348 PltSection *InX::Iplt; 2349 StringTableSection *InX::ShStrTab; 2350 StringTableSection *InX::StrTab; 2351 SymbolTableBaseSection *InX::SymTab; 2352 2353 template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym); 2354 template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym); 2355 template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym); 2356 template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym); 2357 2358 template InputSection *elf::createCommonSection<ELF32LE>(); 2359 template InputSection *elf::createCommonSection<ELF32BE>(); 2360 template InputSection *elf::createCommonSection<ELF64LE>(); 2361 template InputSection *elf::createCommonSection<ELF64BE>(); 2362 2363 template MergeInputSection *elf::createCommentSection<ELF32LE>(); 2364 template MergeInputSection *elf::createCommentSection<ELF32BE>(); 2365 template MergeInputSection *elf::createCommentSection<ELF64LE>(); 2366 template MergeInputSection *elf::createCommentSection<ELF64BE>(); 2367 2368 template class elf::MipsAbiFlagsSection<ELF32LE>; 2369 template class elf::MipsAbiFlagsSection<ELF32BE>; 2370 template class elf::MipsAbiFlagsSection<ELF64LE>; 2371 template class elf::MipsAbiFlagsSection<ELF64BE>; 2372 2373 template class elf::MipsOptionsSection<ELF32LE>; 2374 template class elf::MipsOptionsSection<ELF32BE>; 2375 template class elf::MipsOptionsSection<ELF64LE>; 2376 template class elf::MipsOptionsSection<ELF64BE>; 2377 2378 template class elf::MipsReginfoSection<ELF32LE>; 2379 template class elf::MipsReginfoSection<ELF32BE>; 2380 template class elf::MipsReginfoSection<ELF64LE>; 2381 template class elf::MipsReginfoSection<ELF64BE>; 2382 2383 template class elf::DynamicSection<ELF32LE>; 2384 template class elf::DynamicSection<ELF32BE>; 2385 template class elf::DynamicSection<ELF64LE>; 2386 template class elf::DynamicSection<ELF64BE>; 2387 2388 template class elf::RelocationSection<ELF32LE>; 2389 template class elf::RelocationSection<ELF32BE>; 2390 template class elf::RelocationSection<ELF64LE>; 2391 template class elf::RelocationSection<ELF64BE>; 2392 2393 template class elf::SymbolTableSection<ELF32LE>; 2394 template class elf::SymbolTableSection<ELF32BE>; 2395 template class elf::SymbolTableSection<ELF64LE>; 2396 template class elf::SymbolTableSection<ELF64BE>; 2397 2398 template class elf::HashTableSection<ELF32LE>; 2399 template class elf::HashTableSection<ELF32BE>; 2400 template class elf::HashTableSection<ELF64LE>; 2401 template class elf::HashTableSection<ELF64BE>; 2402 2403 template class elf::EhFrameHeader<ELF32LE>; 2404 template class elf::EhFrameHeader<ELF32BE>; 2405 template class elf::EhFrameHeader<ELF64LE>; 2406 template class elf::EhFrameHeader<ELF64BE>; 2407 2408 template class elf::VersionTableSection<ELF32LE>; 2409 template class elf::VersionTableSection<ELF32BE>; 2410 template class elf::VersionTableSection<ELF64LE>; 2411 template class elf::VersionTableSection<ELF64BE>; 2412 2413 template class elf::VersionNeedSection<ELF32LE>; 2414 template class elf::VersionNeedSection<ELF32BE>; 2415 template class elf::VersionNeedSection<ELF64LE>; 2416 template class elf::VersionNeedSection<ELF64BE>; 2417 2418 template class elf::VersionDefinitionSection<ELF32LE>; 2419 template class elf::VersionDefinitionSection<ELF32BE>; 2420 template class elf::VersionDefinitionSection<ELF64LE>; 2421 template class elf::VersionDefinitionSection<ELF64BE>; 2422 2423 template class elf::EhFrameSection<ELF32LE>; 2424 template class elf::EhFrameSection<ELF32BE>; 2425 template class elf::EhFrameSection<ELF64LE>; 2426 template class elf::EhFrameSection<ELF64BE>; 2427