1 //===- OutputSections.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 "OutputSections.h" 11 #include "Config.h" 12 #include "LinkerScript.h" 13 #include "SymbolTable.h" 14 #include "Target.h" 15 #include "lld/Core/Parallel.h" 16 #include "llvm/Support/Dwarf.h" 17 #include "llvm/Support/MD5.h" 18 #include "llvm/Support/MathExtras.h" 19 #include "llvm/Support/SHA1.h" 20 #include <map> 21 22 using namespace llvm; 23 using namespace llvm::dwarf; 24 using namespace llvm::object; 25 using namespace llvm::support::endian; 26 using namespace llvm::ELF; 27 28 using namespace lld; 29 using namespace lld::elf; 30 31 static bool isAlpha(char C) { 32 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; 33 } 34 35 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } 36 37 // Returns true if S is valid as a C language identifier. 38 bool elf::isValidCIdentifier(StringRef S) { 39 return !S.empty() && isAlpha(S[0]) && 40 std::all_of(S.begin() + 1, S.end(), isAlnum); 41 } 42 43 template <class ELFT> 44 OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type, 45 uintX_t Flags) 46 : Name(Name) { 47 memset(&Header, 0, sizeof(Elf_Shdr)); 48 Header.sh_type = Type; 49 Header.sh_flags = Flags; 50 } 51 52 template <class ELFT> 53 void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) { 54 *Shdr = Header; 55 } 56 57 template <class ELFT> 58 GotPltSection<ELFT>::GotPltSection() 59 : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) { 60 this->Header.sh_addralign = sizeof(uintX_t); 61 } 62 63 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) { 64 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size(); 65 Entries.push_back(&Sym); 66 } 67 68 template <class ELFT> bool GotPltSection<ELFT>::empty() const { 69 return Entries.empty(); 70 } 71 72 template <class ELFT> void GotPltSection<ELFT>::finalize() { 73 this->Header.sh_size = 74 (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t); 75 } 76 77 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) { 78 Target->writeGotPltHeader(Buf); 79 Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t); 80 for (const SymbolBody *B : Entries) { 81 Target->writeGotPlt(Buf, B->getPltVA<ELFT>()); 82 Buf += sizeof(uintX_t); 83 } 84 } 85 86 template <class ELFT> 87 GotSection<ELFT>::GotSection() 88 : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) { 89 if (Config->EMachine == EM_MIPS) 90 this->Header.sh_flags |= SHF_MIPS_GPREL; 91 this->Header.sh_addralign = sizeof(uintX_t); 92 } 93 94 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) { 95 if (Config->EMachine == EM_MIPS) { 96 // For "true" local symbols which can be referenced from the same module 97 // only compiler creates two instructions for address loading: 98 // 99 // lw $8, 0($gp) # R_MIPS_GOT16 100 // addi $8, $8, 0 # R_MIPS_LO16 101 // 102 // The first instruction loads high 16 bits of the symbol address while 103 // the second adds an offset. That allows to reduce number of required 104 // GOT entries because only one global offset table entry is necessary 105 // for every 64 KBytes of local data. So for local symbols we need to 106 // allocate number of GOT entries to hold all required "page" addresses. 107 // 108 // All global symbols (hidden and regular) considered by compiler uniformly. 109 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation 110 // to load address of the symbol. So for each such symbol we need to 111 // allocate dedicated GOT entry to store its address. 112 // 113 // If a symbol is preemptible we need help of dynamic linker to get its 114 // final address. The corresponding GOT entries are allocated in the 115 // "global" part of GOT. Entries for non preemptible global symbol allocated 116 // in the "local" part of GOT. 117 // 118 // See "Global Offset Table" in Chapter 5: 119 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 120 if (Sym.isLocal()) { 121 // At this point we do not know final symbol value so to reduce number 122 // of allocated GOT entries do the following trick. Save all output 123 // sections referenced by GOT relocations. Then later in the `finalize` 124 // method calculate number of "pages" required to cover all saved output 125 // section and allocate appropriate number of GOT entries. 126 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec; 127 MipsOutSections.insert(OutSec); 128 return; 129 } 130 if (!Sym.isPreemptible()) { 131 // In case of non-local symbols require an entry in the local part 132 // of MIPS GOT, we set GotIndex to 1 just to accent that this symbol 133 // has the GOT entry and escape creation more redundant GOT entries. 134 // FIXME (simon): We can try to store such symbols in the `Entries` 135 // container. But in that case we have to sort out that container 136 // and update GotIndex assigned to symbols. 137 Sym.GotIndex = 1; 138 ++MipsLocalEntries; 139 return; 140 } 141 } 142 Sym.GotIndex = Entries.size(); 143 Entries.push_back(&Sym); 144 } 145 146 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) { 147 if (Sym.hasGlobalDynIndex()) 148 return false; 149 Sym.GlobalDynIndex = Entries.size(); 150 // Global Dynamic TLS entries take two GOT slots. 151 Entries.push_back(&Sym); 152 Entries.push_back(nullptr); 153 return true; 154 } 155 156 // Reserves TLS entries for a TLS module ID and a TLS block offset. 157 // In total it takes two GOT slots. 158 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() { 159 if (TlsIndexOff != uint32_t(-1)) 160 return false; 161 TlsIndexOff = Entries.size() * sizeof(uintX_t); 162 Entries.push_back(nullptr); 163 Entries.push_back(nullptr); 164 return true; 165 } 166 167 template <class ELFT> 168 typename GotSection<ELFT>::uintX_t 169 GotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) { 170 // Initialize the entry by the %hi(EntryValue) expression 171 // but without right-shifting. 172 return getMipsLocalEntryOffset((EntryValue + 0x8000) & ~0xffff); 173 } 174 175 template <class ELFT> 176 typename GotSection<ELFT>::uintX_t 177 GotSection<ELFT>::getMipsLocalEntryOffset(uintX_t EntryValue) { 178 // Take into account MIPS GOT header. 179 // See comment in the GotSection::writeTo. 180 size_t NewIndex = MipsLocalGotPos.size() + 2; 181 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex)); 182 assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries); 183 return P.first->second * sizeof(uintX_t) - MipsGPOffset; 184 } 185 186 template <class ELFT> 187 typename GotSection<ELFT>::uintX_t 188 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const { 189 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t); 190 } 191 192 template <class ELFT> 193 typename GotSection<ELFT>::uintX_t 194 GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const { 195 return B.GlobalDynIndex * sizeof(uintX_t); 196 } 197 198 template <class ELFT> 199 const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const { 200 return Entries.empty() ? nullptr : Entries.front(); 201 } 202 203 template <class ELFT> 204 unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const { 205 return MipsLocalEntries; 206 } 207 208 template <class ELFT> void GotSection<ELFT>::finalize() { 209 if (Config->EMachine == EM_MIPS) 210 // Take into account MIPS GOT header. 211 // See comment in the GotSection::writeTo. 212 MipsLocalEntries += 2; 213 for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) { 214 // Calculate an upper bound of MIPS GOT entries required to store page 215 // addresses of local symbols. We assume the worst case - each 64kb 216 // page of the output section has at least one GOT relocation against it. 217 // Add 0x8000 to the section's size because the page address stored 218 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff. 219 MipsLocalEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff; 220 } 221 this->Header.sh_size = (MipsLocalEntries + Entries.size()) * sizeof(uintX_t); 222 } 223 224 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) { 225 if (Config->EMachine == EM_MIPS) { 226 // Set the MSB of the second GOT slot. This is not required by any 227 // MIPS ABI documentation, though. 228 // 229 // There is a comment in glibc saying that "The MSB of got[1] of a 230 // gnu object is set to identify gnu objects," and in GNU gold it 231 // says "the second entry will be used by some runtime loaders". 232 // But how this field is being used is unclear. 233 // 234 // We are not really willing to mimic other linkers behaviors 235 // without understanding why they do that, but because all files 236 // generated by GNU tools have this special GOT value, and because 237 // we've been doing this for years, it is probably a safe bet to 238 // keep doing this for now. We really need to revisit this to see 239 // if we had to do this. 240 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf); 241 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31); 242 } 243 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) { 244 uint8_t *Entry = Buf + L.second * sizeof(uintX_t); 245 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first); 246 } 247 Buf += MipsLocalEntries * sizeof(uintX_t); 248 for (const SymbolBody *B : Entries) { 249 uint8_t *Entry = Buf; 250 Buf += sizeof(uintX_t); 251 if (!B) 252 continue; 253 // MIPS has special rules to fill up GOT entries. 254 // See "Global Offset Table" in Chapter 5 in the following document 255 // for detailed description: 256 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 257 // As the first approach, we can just store addresses for all symbols. 258 if (Config->EMachine != EM_MIPS && B->isPreemptible()) 259 continue; // The dynamic linker will take care of it. 260 uintX_t VA = B->getVA<ELFT>(); 261 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA); 262 } 263 } 264 265 template <class ELFT> 266 PltSection<ELFT>::PltSection() 267 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) { 268 this->Header.sh_addralign = 16; 269 } 270 271 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) { 272 size_t Off = 0; 273 if (Target->UseLazyBinding) { 274 // At beginning of PLT, we have code to call the dynamic linker 275 // to resolve dynsyms at runtime. Write such code. 276 Target->writePltZero(Buf); 277 Off += Target->PltZeroSize; 278 } 279 for (auto &I : Entries) { 280 const SymbolBody *B = I.first; 281 unsigned RelOff = I.second; 282 uint64_t Got = 283 Target->UseLazyBinding ? B->getGotPltVA<ELFT>() : B->getGotVA<ELFT>(); 284 uint64_t Plt = this->getVA() + Off; 285 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); 286 Off += Target->PltEntrySize; 287 } 288 } 289 290 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) { 291 Sym.PltIndex = Entries.size(); 292 unsigned RelOff = Target->UseLazyBinding 293 ? Out<ELFT>::RelaPlt->getRelocOffset() 294 : Out<ELFT>::RelaDyn->getRelocOffset(); 295 Entries.push_back(std::make_pair(&Sym, RelOff)); 296 } 297 298 template <class ELFT> void PltSection<ELFT>::finalize() { 299 this->Header.sh_size = 300 Target->PltZeroSize + Entries.size() * Target->PltEntrySize; 301 } 302 303 template <class ELFT> 304 RelocationSection<ELFT>::RelocationSection(StringRef Name) 305 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL, 306 SHF_ALLOC) { 307 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 308 this->Header.sh_addralign = sizeof(uintX_t); 309 } 310 311 template <class ELFT> 312 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) { 313 Relocs.push_back(Reloc); 314 } 315 316 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { 317 for (const DynamicReloc<ELFT> &Rel : Relocs) { 318 auto *P = reinterpret_cast<Elf_Rela *>(Buf); 319 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 320 SymbolBody *Sym = Rel.Sym; 321 322 if (Config->Rela) 323 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend; 324 P->r_offset = Rel.OffsetInSec + Rel.OffsetSec->getVA(); 325 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0; 326 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL); 327 } 328 } 329 330 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() { 331 return this->Header.sh_entsize * Relocs.size(); 332 } 333 334 template <class ELFT> void RelocationSection<ELFT>::finalize() { 335 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex 336 : Out<ELFT>::DynSymTab->SectionIndex; 337 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize; 338 } 339 340 template <class ELFT> 341 InterpSection<ELFT>::InterpSection() 342 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) { 343 this->Header.sh_size = Config->DynamicLinker.size() + 1; 344 this->Header.sh_addralign = 1; 345 } 346 347 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) { 348 StringRef S = Config->DynamicLinker; 349 memcpy(Buf, S.data(), S.size()); 350 } 351 352 template <class ELFT> 353 HashTableSection<ELFT>::HashTableSection() 354 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) { 355 this->Header.sh_entsize = sizeof(Elf_Word); 356 this->Header.sh_addralign = sizeof(Elf_Word); 357 } 358 359 static uint32_t hashSysv(StringRef Name) { 360 uint32_t H = 0; 361 for (char C : Name) { 362 H = (H << 4) + C; 363 uint32_t G = H & 0xf0000000; 364 if (G) 365 H ^= G >> 24; 366 H &= ~G; 367 } 368 return H; 369 } 370 371 template <class ELFT> void HashTableSection<ELFT>::finalize() { 372 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex; 373 374 unsigned NumEntries = 2; // nbucket and nchain. 375 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries. 376 377 // Create as many buckets as there are symbols. 378 // FIXME: This is simplistic. We can try to optimize it, but implementing 379 // support for SHT_GNU_HASH is probably even more profitable. 380 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); 381 this->Header.sh_size = NumEntries * sizeof(Elf_Word); 382 } 383 384 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { 385 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols(); 386 auto *P = reinterpret_cast<Elf_Word *>(Buf); 387 *P++ = NumSymbols; // nbucket 388 *P++ = NumSymbols; // nchain 389 390 Elf_Word *Buckets = P; 391 Elf_Word *Chains = P + NumSymbols; 392 393 for (const std::pair<SymbolBody *, unsigned> &P : 394 Out<ELFT>::DynSymTab->getSymbols()) { 395 SymbolBody *Body = P.first; 396 StringRef Name = Body->getName(); 397 unsigned I = Body->DynsymIndex; 398 uint32_t Hash = hashSysv(Name) % NumSymbols; 399 Chains[I] = Buckets[Hash]; 400 Buckets[Hash] = I; 401 } 402 } 403 404 static uint32_t hashGnu(StringRef Name) { 405 uint32_t H = 5381; 406 for (uint8_t C : Name) 407 H = (H << 5) + H + C; 408 return H; 409 } 410 411 template <class ELFT> 412 GnuHashTableSection<ELFT>::GnuHashTableSection() 413 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) { 414 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4; 415 this->Header.sh_addralign = sizeof(uintX_t); 416 } 417 418 template <class ELFT> 419 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) { 420 if (!NumHashed) 421 return 0; 422 423 // These values are prime numbers which are not greater than 2^(N-1) + 1. 424 // In result, for any particular NumHashed we return a prime number 425 // which is not greater than NumHashed. 426 static const unsigned Primes[] = { 427 1, 1, 3, 3, 7, 13, 31, 61, 127, 251, 428 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071}; 429 430 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed), 431 array_lengthof(Primes) - 1)]; 432 } 433 434 // Bloom filter estimation: at least 8 bits for each hashed symbol. 435 // GNU Hash table requirement: it should be a power of 2, 436 // the minimum value is 1, even for an empty table. 437 // Expected results for a 32-bit target: 438 // calcMaskWords(0..4) = 1 439 // calcMaskWords(5..8) = 2 440 // calcMaskWords(9..16) = 4 441 // For a 64-bit target: 442 // calcMaskWords(0..8) = 1 443 // calcMaskWords(9..16) = 2 444 // calcMaskWords(17..32) = 4 445 template <class ELFT> 446 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) { 447 if (!NumHashed) 448 return 1; 449 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off)); 450 } 451 452 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() { 453 unsigned NumHashed = Symbols.size(); 454 NBuckets = calcNBuckets(NumHashed); 455 MaskWords = calcMaskWords(NumHashed); 456 // Second hash shift estimation: just predefined values. 457 Shift2 = ELFT::Is64Bits ? 6 : 5; 458 459 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex; 460 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header 461 + sizeof(Elf_Off) * MaskWords // Bloom Filter 462 + sizeof(Elf_Word) * NBuckets // Hash Buckets 463 + sizeof(Elf_Word) * NumHashed; // Hash Values 464 } 465 466 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) { 467 writeHeader(Buf); 468 if (Symbols.empty()) 469 return; 470 writeBloomFilter(Buf); 471 writeHashTable(Buf); 472 } 473 474 template <class ELFT> 475 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) { 476 auto *P = reinterpret_cast<Elf_Word *>(Buf); 477 *P++ = NBuckets; 478 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size(); 479 *P++ = MaskWords; 480 *P++ = Shift2; 481 Buf = reinterpret_cast<uint8_t *>(P); 482 } 483 484 template <class ELFT> 485 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) { 486 unsigned C = sizeof(Elf_Off) * 8; 487 488 auto *Masks = reinterpret_cast<Elf_Off *>(Buf); 489 for (const SymbolData &Sym : Symbols) { 490 size_t Pos = (Sym.Hash / C) & (MaskWords - 1); 491 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) | 492 (uintX_t(1) << ((Sym.Hash >> Shift2) % C)); 493 Masks[Pos] |= V; 494 } 495 Buf += sizeof(Elf_Off) * MaskWords; 496 } 497 498 template <class ELFT> 499 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) { 500 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf); 501 Elf_Word *Values = Buckets + NBuckets; 502 503 int PrevBucket = -1; 504 int I = 0; 505 for (const SymbolData &Sym : Symbols) { 506 int Bucket = Sym.Hash % NBuckets; 507 assert(PrevBucket <= Bucket); 508 if (Bucket != PrevBucket) { 509 Buckets[Bucket] = Sym.Body->DynsymIndex; 510 PrevBucket = Bucket; 511 if (I > 0) 512 Values[I - 1] |= 1; 513 } 514 Values[I] = Sym.Hash & ~1; 515 ++I; 516 } 517 if (I > 0) 518 Values[I - 1] |= 1; 519 } 520 521 static bool includeInGnuHashTable(SymbolBody *B) { 522 // Assume that includeInDynsym() is already checked. 523 return !B->isUndefined(); 524 } 525 526 // Add symbols to this symbol hash table. Note that this function 527 // destructively sort a given vector -- which is needed because 528 // GNU-style hash table places some sorting requirements. 529 template <class ELFT> 530 void GnuHashTableSection<ELFT>::addSymbols( 531 std::vector<std::pair<SymbolBody *, size_t>> &V) { 532 auto Mid = std::stable_partition(V.begin(), V.end(), 533 [](std::pair<SymbolBody *, size_t> &P) { 534 return !includeInGnuHashTable(P.first); 535 }); 536 if (Mid == V.end()) 537 return; 538 for (auto I = Mid, E = V.end(); I != E; ++I) { 539 SymbolBody *B = I->first; 540 size_t StrOff = I->second; 541 Symbols.push_back({B, StrOff, hashGnu(B->getName())}); 542 } 543 544 unsigned NBuckets = calcNBuckets(Symbols.size()); 545 std::stable_sort(Symbols.begin(), Symbols.end(), 546 [&](const SymbolData &L, const SymbolData &R) { 547 return L.Hash % NBuckets < R.Hash % NBuckets; 548 }); 549 550 V.erase(Mid, V.end()); 551 for (const SymbolData &Sym : Symbols) 552 V.push_back({Sym.Body, Sym.STName}); 553 } 554 555 template <class ELFT> 556 DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab) 557 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE), 558 SymTab(SymTab) { 559 Elf_Shdr &Header = this->Header; 560 Header.sh_addralign = sizeof(uintX_t); 561 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8; 562 563 // .dynamic section is not writable on MIPS. 564 // See "Special Section" in Chapter 4 in the following document: 565 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 566 if (Config->EMachine == EM_MIPS) 567 Header.sh_flags = SHF_ALLOC; 568 } 569 570 template <class ELFT> void DynamicSection<ELFT>::finalize() { 571 if (this->Header.sh_size) 572 return; // Already finalized. 573 574 Elf_Shdr &Header = this->Header; 575 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex; 576 577 auto Add = [=](Entry E) { Entries.push_back(E); }; 578 579 // Add strings. We know that these are the last strings to be added to 580 // DynStrTab and doing this here allows this function to set DT_STRSZ. 581 if (!Config->RPath.empty()) 582 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, 583 Out<ELFT>::DynStrTab->addString(Config->RPath)}); 584 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles()) 585 if (F->isNeeded()) 586 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())}); 587 if (!Config->SoName.empty()) 588 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)}); 589 590 Out<ELFT>::DynStrTab->finalize(); 591 592 if (Out<ELFT>::RelaDyn->hasRelocs()) { 593 bool IsRela = Config->Rela; 594 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn}); 595 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()}); 596 Add({IsRela ? DT_RELAENT : DT_RELENT, 597 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))}); 598 } 599 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) { 600 Add({DT_JMPREL, Out<ELFT>::RelaPlt}); 601 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()}); 602 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT, 603 Out<ELFT>::GotPlt}); 604 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)}); 605 } 606 607 Add({DT_SYMTAB, Out<ELFT>::DynSymTab}); 608 Add({DT_SYMENT, sizeof(Elf_Sym)}); 609 Add({DT_STRTAB, Out<ELFT>::DynStrTab}); 610 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()}); 611 if (Out<ELFT>::GnuHashTab) 612 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab}); 613 if (Out<ELFT>::HashTab) 614 Add({DT_HASH, Out<ELFT>::HashTab}); 615 616 if (PreInitArraySec) { 617 Add({DT_PREINIT_ARRAY, PreInitArraySec}); 618 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()}); 619 } 620 if (InitArraySec) { 621 Add({DT_INIT_ARRAY, InitArraySec}); 622 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()}); 623 } 624 if (FiniArraySec) { 625 Add({DT_FINI_ARRAY, FiniArraySec}); 626 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()}); 627 } 628 629 if (SymbolBody *B = SymTab.find(Config->Init)) 630 Add({DT_INIT, B}); 631 if (SymbolBody *B = SymTab.find(Config->Fini)) 632 Add({DT_FINI, B}); 633 634 uint32_t DtFlags = 0; 635 uint32_t DtFlags1 = 0; 636 if (Config->Bsymbolic) 637 DtFlags |= DF_SYMBOLIC; 638 if (Config->ZNodelete) 639 DtFlags1 |= DF_1_NODELETE; 640 if (Config->ZNow) { 641 DtFlags |= DF_BIND_NOW; 642 DtFlags1 |= DF_1_NOW; 643 } 644 if (Config->ZOrigin) { 645 DtFlags |= DF_ORIGIN; 646 DtFlags1 |= DF_1_ORIGIN; 647 } 648 649 if (DtFlags) 650 Add({DT_FLAGS, DtFlags}); 651 if (DtFlags1) 652 Add({DT_FLAGS_1, DtFlags1}); 653 654 if (!Config->Entry.empty()) 655 Add({DT_DEBUG, (uint64_t)0}); 656 657 if (size_t NeedNum = Out<ELFT>::VerNeed->getNeedNum()) { 658 Add({DT_VERSYM, Out<ELFT>::VerSym}); 659 Add({DT_VERNEED, Out<ELFT>::VerNeed}); 660 Add({DT_VERNEEDNUM, NeedNum}); 661 } 662 663 if (Config->EMachine == EM_MIPS) { 664 Add({DT_MIPS_RLD_VERSION, 1}); 665 Add({DT_MIPS_FLAGS, RHF_NOTPOT}); 666 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()}); 667 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()}); 668 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()}); 669 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry()) 670 Add({DT_MIPS_GOTSYM, B->DynsymIndex}); 671 else 672 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()}); 673 Add({DT_PLTGOT, Out<ELFT>::Got}); 674 if (Out<ELFT>::MipsRldMap) 675 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap}); 676 } 677 678 // +1 for DT_NULL 679 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize; 680 } 681 682 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) { 683 auto *P = reinterpret_cast<Elf_Dyn *>(Buf); 684 685 for (const Entry &E : Entries) { 686 P->d_tag = E.Tag; 687 switch (E.Kind) { 688 case Entry::SecAddr: 689 P->d_un.d_ptr = E.OutSec->getVA(); 690 break; 691 case Entry::SymAddr: 692 P->d_un.d_ptr = E.Sym->template getVA<ELFT>(); 693 break; 694 case Entry::PlainInt: 695 P->d_un.d_val = E.Val; 696 break; 697 } 698 ++P; 699 } 700 } 701 702 template <class ELFT> 703 EhFrameHeader<ELFT>::EhFrameHeader() 704 : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS, 705 SHF_ALLOC) { 706 // It's a 4 bytes of header + pointer to the contents of the .eh_frame section 707 // + the number of FDE pointers in the table. 708 this->Header.sh_size = 12; 709 } 710 711 // We have to get PC values of FDEs. They depend on relocations 712 // which are target specific, so we run this code after performing 713 // all relocations. We read the values from ouput buffer according to the 714 // encoding given for FDEs. Return value is an offset to the initial PC value 715 // for the FDE. 716 template <class ELFT> 717 typename EhFrameHeader<ELFT>::uintX_t 718 EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) { 719 const endianness E = ELFT::TargetEndianness; 720 uint8_t Size = F.Enc & 0x7; 721 if (Size == DW_EH_PE_absptr) 722 Size = sizeof(uintX_t) == 8 ? DW_EH_PE_udata8 : DW_EH_PE_udata4; 723 uint64_t PC; 724 switch (Size) { 725 case DW_EH_PE_udata2: 726 PC = read16<E>(F.PCRel); 727 break; 728 case DW_EH_PE_udata4: 729 PC = read32<E>(F.PCRel); 730 break; 731 case DW_EH_PE_udata8: 732 PC = read64<E>(F.PCRel); 733 break; 734 default: 735 fatal("unknown FDE size encoding"); 736 } 737 switch (F.Enc & 0x70) { 738 case DW_EH_PE_absptr: 739 return PC; 740 case DW_EH_PE_pcrel: 741 return PC + EhVA + F.Off + 8; 742 default: 743 fatal("unknown FDE size relative encoding"); 744 } 745 } 746 747 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) { 748 const endianness E = ELFT::TargetEndianness; 749 750 uintX_t EhVA = Sec->getVA(); 751 uintX_t VA = this->getVA(); 752 753 // InitialPC -> Offset in .eh_frame, sorted by InitialPC, and deduplicate PCs. 754 // FIXME: Deduplication leaves unneeded null bytes at the end of the section. 755 std::map<uintX_t, size_t> PcToOffset; 756 for (const FdeData &F : FdeList) 757 PcToOffset[getFdePc(EhVA, F)] = F.Off; 758 759 const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4, 760 DW_EH_PE_udata4, 761 DW_EH_PE_datarel | DW_EH_PE_sdata4}; 762 memcpy(Buf, Header, sizeof(Header)); 763 764 uintX_t EhOff = EhVA - VA - 4; 765 write32<E>(Buf + 4, EhOff); 766 write32<E>(Buf + 8, PcToOffset.size()); 767 Buf += 12; 768 769 for (auto &I : PcToOffset) { 770 // The first four bytes are an offset to the initial PC value for the FDE. 771 write32<E>(Buf, I.first - VA); 772 // The last four bytes are an offset to the FDE data itself. 773 write32<E>(Buf + 4, EhVA + I.second - VA); 774 Buf += 8; 775 } 776 } 777 778 template <class ELFT> 779 void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) { 780 assert((!this->Sec || this->Sec == Sec) && 781 "multiple .eh_frame sections not supported for .eh_frame_hdr"); 782 Live = Config->EhFrameHdr; 783 this->Sec = Sec; 784 } 785 786 template <class ELFT> 787 void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) { 788 if (Live && (Enc & 0xF0) == DW_EH_PE_datarel) 789 fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr"); 790 FdeList.push_back(FdeData{Enc, Off, PCRel}); 791 } 792 793 template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() { 794 // Each FDE entry is 8 bytes long: 795 // The first four bytes are an offset to the initial PC value for the FDE. The 796 // last four byte are an offset to the FDE data itself. 797 this->Header.sh_size += 8; 798 } 799 800 template <class ELFT> 801 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags) 802 : OutputSectionBase<ELFT>(Name, Type, Flags) { 803 if (Type == SHT_RELA) 804 this->Header.sh_entsize = sizeof(Elf_Rela); 805 else if (Type == SHT_REL) 806 this->Header.sh_entsize = sizeof(Elf_Rel); 807 } 808 809 template <class ELFT> void OutputSection<ELFT>::finalize() { 810 uint32_t Type = this->Header.sh_type; 811 if (Type != SHT_RELA && Type != SHT_REL) 812 return; 813 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex; 814 // sh_info for SHT_REL[A] sections should contain the section header index of 815 // the section to which the relocation applies. 816 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection(); 817 this->Header.sh_info = S->OutSec->SectionIndex; 818 } 819 820 template <class ELFT> 821 void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 822 assert(C->Live); 823 auto *S = cast<InputSection<ELFT>>(C); 824 Sections.push_back(S); 825 S->OutSec = this; 826 this->updateAlign(S->Align); 827 } 828 829 // If an input string is in the form of "foo.N" where N is a number, 830 // return N. Otherwise, returns 65536, which is one greater than the 831 // lowest priority. 832 static int getPriority(StringRef S) { 833 size_t Pos = S.rfind('.'); 834 if (Pos == StringRef::npos) 835 return 65536; 836 int V; 837 if (S.substr(Pos + 1).getAsInteger(10, V)) 838 return 65536; 839 return V; 840 } 841 842 template <class ELFT> 843 void OutputSection<ELFT>::forEachInputSection( 844 std::function<void(InputSectionBase<ELFT> *S)> F) { 845 for (InputSection<ELFT> *S : Sections) 846 F(S); 847 } 848 849 // Sorts input sections by section name suffixes, so that .foo.N comes 850 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 851 // We want to keep the original order if the priorities are the same 852 // because the compiler keeps the original initialization order in a 853 // translation unit and we need to respect that. 854 // For more detail, read the section of the GCC's manual about init_priority. 855 template <class ELFT> void OutputSection<ELFT>::sortInitFini() { 856 // Sort sections by priority. 857 typedef std::pair<int, InputSection<ELFT> *> Pair; 858 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; 859 860 std::vector<Pair> V; 861 for (InputSection<ELFT> *S : Sections) 862 V.push_back({getPriority(S->getSectionName()), S}); 863 std::stable_sort(V.begin(), V.end(), Comp); 864 Sections.clear(); 865 for (Pair &P : V) 866 Sections.push_back(P.second); 867 } 868 869 // Returns true if S matches /Filename.?\.o$/. 870 static bool isCrtBeginEnd(StringRef S, StringRef Filename) { 871 if (!S.endswith(".o")) 872 return false; 873 S = S.drop_back(2); 874 if (S.endswith(Filename)) 875 return true; 876 return !S.empty() && S.drop_back().endswith(Filename); 877 } 878 879 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } 880 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } 881 882 // .ctors and .dtors are sorted by this priority from highest to lowest. 883 // 884 // 1. The section was contained in crtbegin (crtbegin contains 885 // some sentinel value in its .ctors and .dtors so that the runtime 886 // can find the beginning of the sections.) 887 // 888 // 2. The section has an optional priority value in the form of ".ctors.N" 889 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 890 // they are compared as string rather than number. 891 // 892 // 3. The section is just ".ctors" or ".dtors". 893 // 894 // 4. The section was contained in crtend, which contains an end marker. 895 // 896 // In an ideal world, we don't need this function because .init_array and 897 // .ctors are duplicate features (and .init_array is newer.) However, there 898 // are too many real-world use cases of .ctors, so we had no choice to 899 // support that with this rather ad-hoc semantics. 900 template <class ELFT> 901 static bool compCtors(const InputSection<ELFT> *A, 902 const InputSection<ELFT> *B) { 903 bool BeginA = isCrtbegin(A->getFile()->getName()); 904 bool BeginB = isCrtbegin(B->getFile()->getName()); 905 if (BeginA != BeginB) 906 return BeginA; 907 bool EndA = isCrtend(A->getFile()->getName()); 908 bool EndB = isCrtend(B->getFile()->getName()); 909 if (EndA != EndB) 910 return EndB; 911 StringRef X = A->getSectionName(); 912 StringRef Y = B->getSectionName(); 913 assert(X.startswith(".ctors") || X.startswith(".dtors")); 914 assert(Y.startswith(".ctors") || Y.startswith(".dtors")); 915 X = X.substr(6); 916 Y = Y.substr(6); 917 if (X.empty() && Y.empty()) 918 return false; 919 return X < Y; 920 } 921 922 // Sorts input sections by the special rules for .ctors and .dtors. 923 // Unfortunately, the rules are different from the one for .{init,fini}_array. 924 // Read the comment above. 925 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() { 926 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>); 927 } 928 929 static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) { 930 size_t I = 0; 931 for (; I + A.size() < Size; I += A.size()) 932 memcpy(Buf + I, A.data(), A.size()); 933 memcpy(Buf + I, A.data(), Size - I); 934 } 935 936 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) { 937 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name); 938 if (!Filler.empty()) 939 fill(Buf, this->getSize(), Filler); 940 if (Config->Threads) { 941 parallel_for_each(Sections.begin(), Sections.end(), 942 [=](InputSection<ELFT> *C) { C->writeTo(Buf); }); 943 } else { 944 for (InputSection<ELFT> *C : Sections) 945 C->writeTo(Buf); 946 } 947 } 948 949 template <class ELFT> 950 EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type, 951 uintX_t Flags) 952 : OutputSectionBase<ELFT>(Name, Type, Flags) { 953 Out<ELFT>::EhFrameHdr->assignEhFrame(this); 954 } 955 956 template <class ELFT> 957 void EHOutputSection<ELFT>::forEachInputSection( 958 std::function<void(InputSectionBase<ELFT> *)> F) { 959 for (EHInputSection<ELFT> *S : Sections) 960 F(S); 961 } 962 963 template <class ELFT> 964 EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index) 965 : S(S), Index(Index) {} 966 967 template <class ELFT> StringRef EHRegion<ELFT>::data() const { 968 ArrayRef<uint8_t> SecData = S->getSectionData(); 969 ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets; 970 size_t Start = Offsets[Index].first; 971 size_t End = 972 Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first; 973 return StringRef((const char *)SecData.data() + Start, End - Start); 974 } 975 976 template <class ELFT> 977 Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index) 978 : EHRegion<ELFT>(S, Index) {} 979 980 // Read a byte and advance D by one byte. 981 static uint8_t readByte(ArrayRef<uint8_t> &D) { 982 if (D.empty()) 983 fatal("corrupted or unsupported CIE information"); 984 uint8_t B = D.front(); 985 D = D.slice(1); 986 return B; 987 } 988 989 static void skipLeb128(ArrayRef<uint8_t> &D) { 990 while (!D.empty()) { 991 uint8_t Val = D.front(); 992 D = D.slice(1); 993 if ((Val & 0x80) == 0) 994 return; 995 } 996 fatal("corrupted or unsupported CIE information"); 997 } 998 999 template <class ELFT> static size_t getAugPSize(unsigned Enc) { 1000 switch (Enc & 0x0f) { 1001 case DW_EH_PE_absptr: 1002 case DW_EH_PE_signed: 1003 return ELFT::Is64Bits ? 8 : 4; 1004 case DW_EH_PE_udata2: 1005 case DW_EH_PE_sdata2: 1006 return 2; 1007 case DW_EH_PE_udata4: 1008 case DW_EH_PE_sdata4: 1009 return 4; 1010 case DW_EH_PE_udata8: 1011 case DW_EH_PE_sdata8: 1012 return 8; 1013 } 1014 fatal("unknown FDE encoding"); 1015 } 1016 1017 template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) { 1018 uint8_t Enc = readByte(D); 1019 if ((Enc & 0xf0) == DW_EH_PE_aligned) 1020 fatal("DW_EH_PE_aligned encoding is not supported"); 1021 size_t Size = getAugPSize<ELFT>(Enc); 1022 if (Size >= D.size()) 1023 fatal("corrupted CIE"); 1024 D = D.slice(Size); 1025 } 1026 1027 template <class ELFT> 1028 uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) { 1029 if (D.size() < 8) 1030 fatal("CIE too small"); 1031 D = D.slice(8); 1032 1033 uint8_t Version = readByte(D); 1034 if (Version != 1 && Version != 3) 1035 fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version)); 1036 1037 const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0'); 1038 if (AugEnd == D.end()) 1039 fatal("corrupted CIE"); 1040 StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin()); 1041 D = D.slice(Aug.size() + 1); 1042 1043 // Code alignment factor should always be 1 for .eh_frame. 1044 if (readByte(D) != 1) 1045 fatal("CIE code alignment must be 1"); 1046 1047 // Skip data alignment factor. 1048 skipLeb128(D); 1049 1050 // Skip the return address register. In CIE version 1 this is a single 1051 // byte. In CIE version 3 this is an unsigned LEB128. 1052 if (Version == 1) 1053 readByte(D); 1054 else 1055 skipLeb128(D); 1056 1057 // We only care about an 'R' value, but other records may precede an 'R' 1058 // record. Records are not in TLV (type-length-value) format, so we need 1059 // to teach the linker how to skip records for each type. 1060 for (char C : Aug) { 1061 if (C == 'R') 1062 return readByte(D); 1063 if (C == 'z') { 1064 skipLeb128(D); 1065 continue; 1066 } 1067 if (C == 'P') { 1068 skipAugP<ELFT>(D); 1069 continue; 1070 } 1071 if (C == 'L') { 1072 readByte(D); 1073 continue; 1074 } 1075 fatal("unknown .eh_frame augmentation string: " + Aug); 1076 } 1077 return DW_EH_PE_absptr; 1078 } 1079 1080 template <class ELFT> 1081 static typename ELFT::uint readEntryLength(ArrayRef<uint8_t> D) { 1082 const endianness E = ELFT::TargetEndianness; 1083 if (D.size() < 4) 1084 fatal("CIE/FDE too small"); 1085 1086 // First 4 bytes of CIE/FDE is the size of the record. 1087 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead. 1088 uint64_t V = read32<E>(D.data()); 1089 if (V < UINT32_MAX) { 1090 uint64_t Len = V + 4; 1091 if (Len > D.size()) 1092 fatal("CIE/FIE ends past the end of the section"); 1093 return Len; 1094 } 1095 1096 if (D.size() < 12) 1097 fatal("CIE/FDE too small"); 1098 V = read64<E>(D.data() + 4); 1099 uint64_t Len = V + 12; 1100 if (Len < V || D.size() < Len) 1101 fatal("CIE/FIE ends past the end of the section"); 1102 return Len; 1103 } 1104 1105 template <class ELFT> 1106 template <class RelTy> 1107 void EHOutputSection<ELFT>::addSectionAux(EHInputSection<ELFT> *S, 1108 ArrayRef<RelTy> Rels) { 1109 const endianness E = ELFT::TargetEndianness; 1110 1111 S->OutSec = this; 1112 this->updateAlign(S->Align); 1113 Sections.push_back(S); 1114 1115 ArrayRef<uint8_t> SecData = S->getSectionData(); 1116 ArrayRef<uint8_t> D = SecData; 1117 uintX_t Offset = 0; 1118 auto RelI = Rels.begin(); 1119 auto RelE = Rels.end(); 1120 1121 DenseMap<unsigned, unsigned> OffsetToIndex; 1122 while (!D.empty()) { 1123 unsigned Index = S->Offsets.size(); 1124 S->Offsets.push_back(std::make_pair(Offset, -1)); 1125 1126 uintX_t Length = readEntryLength<ELFT>(D); 1127 // If CIE/FDE data length is zero then Length is 4, this 1128 // shall be considered a terminator and processing shall end. 1129 if (Length == 4) 1130 break; 1131 StringRef Entry((const char *)D.data(), Length); 1132 1133 while (RelI != RelE && RelI->r_offset < Offset) 1134 ++RelI; 1135 uintX_t NextOffset = Offset + Length; 1136 bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset; 1137 1138 uint32_t ID = read32<E>(D.data() + 4); 1139 if (ID == 0) { 1140 // CIE 1141 Cie<ELFT> C(S, Index); 1142 if (Config->EhFrameHdr) 1143 C.FdeEncoding = getFdeEncoding(D); 1144 1145 SymbolBody *Personality = nullptr; 1146 if (HasReloc) 1147 Personality = &S->getFile()->getRelocTargetSym(*RelI); 1148 1149 std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality); 1150 auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size())); 1151 if (P.second) { 1152 Cies.push_back(C); 1153 this->Header.sh_size += alignTo(Length, sizeof(uintX_t)); 1154 } 1155 OffsetToIndex[Offset] = P.first->second; 1156 } else { 1157 if (!HasReloc) 1158 fatal("FDE doesn't reference another section"); 1159 SymbolBody &B = S->getFile()->getRelocTargetSym(*RelI); 1160 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B); 1161 if (D && D->Section) { 1162 InputSectionBase<ELFT> *Target = D->Section->Repl; 1163 if (Target && Target->Live) { 1164 uint32_t CieOffset = Offset + 4 - ID; 1165 auto I = OffsetToIndex.find(CieOffset); 1166 if (I == OffsetToIndex.end()) 1167 fatal("invalid CIE reference"); 1168 Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index)); 1169 Out<ELFT>::EhFrameHdr->reserveFde(); 1170 this->Header.sh_size += alignTo(Length, sizeof(uintX_t)); 1171 } 1172 } 1173 } 1174 1175 Offset = NextOffset; 1176 D = D.slice(Length); 1177 } 1178 } 1179 1180 template <class ELFT> 1181 void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1182 auto *S = cast<EHInputSection<ELFT>>(C); 1183 const Elf_Shdr *RelSec = S->RelocSection; 1184 if (!RelSec) { 1185 addSectionAux(S, makeArrayRef<Elf_Rela>(nullptr, nullptr)); 1186 return; 1187 } 1188 ELFFile<ELFT> &Obj = S->getFile()->getObj(); 1189 if (RelSec->sh_type == SHT_RELA) 1190 addSectionAux(S, Obj.relas(RelSec)); 1191 else 1192 addSectionAux(S, Obj.rels(RelSec)); 1193 } 1194 1195 template <class ELFT> 1196 static void writeAlignedCieOrFde(StringRef Data, uint8_t *Buf) { 1197 typedef typename ELFT::uint uintX_t; 1198 const endianness E = ELFT::TargetEndianness; 1199 uint64_t Len = alignTo(Data.size(), sizeof(uintX_t)); 1200 write32<E>(Buf, Len - 4); 1201 memcpy(Buf + 4, Data.data() + 4, Data.size() - 4); 1202 } 1203 1204 template <class ELFT> void EHOutputSection<ELFT>::finalize() { 1205 if (Finalized) 1206 return; 1207 Finalized = true; 1208 1209 size_t Offset = 0; 1210 for (const Cie<ELFT> &C : Cies) { 1211 C.S->Offsets[C.Index].second = Offset; 1212 Offset += alignTo(C.data().size(), sizeof(uintX_t)); 1213 1214 for (const EHRegion<ELFT> &F : C.Fdes) { 1215 F.S->Offsets[F.Index].second = Offset; 1216 Offset += alignTo(F.data().size(), sizeof(uintX_t)); 1217 } 1218 } 1219 } 1220 1221 template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1222 const endianness E = ELFT::TargetEndianness; 1223 for (const Cie<ELFT> &C : Cies) { 1224 size_t CieOffset = C.S->Offsets[C.Index].second; 1225 writeAlignedCieOrFde<ELFT>(C.data(), Buf + CieOffset); 1226 1227 for (const EHRegion<ELFT> &F : C.Fdes) { 1228 size_t Offset = F.S->Offsets[F.Index].second; 1229 writeAlignedCieOrFde<ELFT>(F.data(), Buf + Offset); 1230 write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer 1231 1232 Out<ELFT>::EhFrameHdr->addFde(C.FdeEncoding, Offset, Buf + Offset + 8); 1233 } 1234 } 1235 1236 for (EHInputSection<ELFT> *S : Sections) 1237 S->relocate(Buf, nullptr); 1238 } 1239 1240 template <class ELFT> 1241 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type, 1242 uintX_t Flags, uintX_t Alignment) 1243 : OutputSectionBase<ELFT>(Name, Type, Flags), 1244 Builder(llvm::StringTableBuilder::RAW, Alignment) {} 1245 1246 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1247 if (shouldTailMerge()) { 1248 StringRef Data = Builder.data(); 1249 memcpy(Buf, Data.data(), Data.size()); 1250 return; 1251 } 1252 for (const std::pair<StringRef, size_t> &P : Builder.getMap()) { 1253 StringRef Data = P.first; 1254 memcpy(Buf + P.second, Data.data(), Data.size()); 1255 } 1256 } 1257 1258 template <class ELFT> 1259 void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1260 auto *S = cast<MergeInputSection<ELFT>>(C); 1261 S->OutSec = this; 1262 this->updateAlign(S->Align); 1263 1264 ArrayRef<uint8_t> D = S->getSectionData(); 1265 StringRef Data((const char *)D.data(), D.size()); 1266 uintX_t EntSize = S->getSectionHdr()->sh_entsize; 1267 this->Header.sh_entsize = EntSize; 1268 MutableArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets; 1269 1270 // If this is of type string, the contents are null-terminated strings. 1271 if (this->Header.sh_flags & SHF_STRINGS) { 1272 for (unsigned I = 0, N = Offsets.size(); I != N; ++I) { 1273 auto &P = Offsets[I]; 1274 if (P.second == (uintX_t)-1) 1275 continue; 1276 1277 uintX_t Start = P.first; 1278 uintX_t End = (I == N - 1) ? Data.size() : Offsets[I + 1].first; 1279 StringRef Entry = Data.substr(Start, End - Start); 1280 uintX_t OutputOffset = Builder.add(Entry); 1281 if (shouldTailMerge()) 1282 OutputOffset = -1; 1283 P.second = OutputOffset; 1284 } 1285 return; 1286 } 1287 1288 // If this is not of type string, every entry has the same size. 1289 for (auto &P : Offsets) { 1290 if (P.second == (uintX_t)-1) 1291 continue; 1292 StringRef Entry = Data.substr(P.first, EntSize); 1293 P.second = Builder.add(Entry); 1294 } 1295 } 1296 1297 template <class ELFT> 1298 unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) { 1299 return Builder.getOffset(Val); 1300 } 1301 1302 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const { 1303 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS; 1304 } 1305 1306 template <class ELFT> void MergeOutputSection<ELFT>::finalize() { 1307 if (shouldTailMerge()) 1308 Builder.finalize(); 1309 this->Header.sh_size = Builder.getSize(); 1310 } 1311 1312 template <class ELFT> 1313 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic) 1314 : OutputSectionBase<ELFT>(Name, SHT_STRTAB, 1315 Dynamic ? (uintX_t)SHF_ALLOC : 0), 1316 Dynamic(Dynamic) { 1317 this->Header.sh_addralign = 1; 1318 } 1319 1320 // Adds a string to the string table. If HashIt is true we hash and check for 1321 // duplicates. It is optional because the name of global symbols are already 1322 // uniqued and hashing them again has a big cost for a small value: uniquing 1323 // them with some other string that happens to be the same. 1324 template <class ELFT> 1325 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) { 1326 if (HashIt) { 1327 auto R = StringMap.insert(std::make_pair(S, Size)); 1328 if (!R.second) 1329 return R.first->second; 1330 } 1331 unsigned Ret = Size; 1332 Size += S.size() + 1; 1333 Strings.push_back(S); 1334 return Ret; 1335 } 1336 1337 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) { 1338 // ELF string tables start with NUL byte, so advance the pointer by one. 1339 ++Buf; 1340 for (StringRef S : Strings) { 1341 memcpy(Buf, S.data(), S.size()); 1342 Buf += S.size() + 1; 1343 } 1344 } 1345 1346 template <class ELFT> 1347 SymbolTableSection<ELFT>::SymbolTableSection( 1348 SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec) 1349 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab", 1350 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, 1351 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0), 1352 StrTabSec(StrTabSec), Table(Table) { 1353 this->Header.sh_entsize = sizeof(Elf_Sym); 1354 this->Header.sh_addralign = sizeof(uintX_t); 1355 } 1356 1357 // Orders symbols according to their positions in the GOT, 1358 // in compliance with MIPS ABI rules. 1359 // See "Global Offset Table" in Chapter 5 in the following document 1360 // for detailed description: 1361 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 1362 static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L, 1363 const std::pair<SymbolBody *, unsigned> &R) { 1364 // Sort entries related to non-local preemptible symbols by GOT indexes. 1365 // All other entries go to the first part of GOT in arbitrary order. 1366 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible(); 1367 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible(); 1368 if (LIsInLocalGot || RIsInLocalGot) 1369 return !RIsInLocalGot; 1370 return L.first->GotIndex < R.first->GotIndex; 1371 } 1372 1373 static uint8_t getSymbolBinding(SymbolBody *Body) { 1374 Symbol *S = Body->Backref; 1375 uint8_t Visibility = S->Visibility; 1376 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED) 1377 return STB_LOCAL; 1378 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE) 1379 return STB_GLOBAL; 1380 return S->Binding; 1381 } 1382 1383 template <class ELFT> void SymbolTableSection<ELFT>::finalize() { 1384 if (this->Header.sh_size) 1385 return; // Already finalized. 1386 1387 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym); 1388 this->Header.sh_link = StrTabSec.SectionIndex; 1389 this->Header.sh_info = NumLocals + 1; 1390 1391 if (Config->Relocatable) { 1392 size_t I = NumLocals; 1393 for (const std::pair<SymbolBody *, size_t> &P : Symbols) 1394 P.first->DynsymIndex = ++I; 1395 return; 1396 } 1397 1398 if (!StrTabSec.isDynamic()) { 1399 std::stable_sort(Symbols.begin(), Symbols.end(), 1400 [](const std::pair<SymbolBody *, unsigned> &L, 1401 const std::pair<SymbolBody *, unsigned> &R) { 1402 return getSymbolBinding(L.first) == STB_LOCAL && 1403 getSymbolBinding(R.first) != STB_LOCAL; 1404 }); 1405 return; 1406 } 1407 if (Out<ELFT>::GnuHashTab) 1408 // NB: It also sorts Symbols to meet the GNU hash table requirements. 1409 Out<ELFT>::GnuHashTab->addSymbols(Symbols); 1410 else if (Config->EMachine == EM_MIPS) 1411 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols); 1412 size_t I = 0; 1413 for (const std::pair<SymbolBody *, size_t> &P : Symbols) 1414 P.first->DynsymIndex = ++I; 1415 } 1416 1417 template <class ELFT> 1418 void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) { 1419 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)}); 1420 } 1421 1422 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { 1423 Buf += sizeof(Elf_Sym); 1424 1425 // All symbols with STB_LOCAL binding precede the weak and global symbols. 1426 // .dynsym only contains global symbols. 1427 if (!Config->DiscardAll && !StrTabSec.isDynamic()) 1428 writeLocalSymbols(Buf); 1429 1430 writeGlobalSymbols(Buf); 1431 } 1432 1433 template <class ELFT> 1434 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) { 1435 // Iterate over all input object files to copy their local symbols 1436 // to the output symbol table pointed by Buf. 1437 for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) { 1438 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P : 1439 File->KeptLocalSyms) { 1440 const DefinedRegular<ELFT> &Body = *P.first; 1441 InputSectionBase<ELFT> *Section = Body.Section; 1442 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1443 1444 if (!Section) { 1445 ESym->st_shndx = SHN_ABS; 1446 ESym->st_value = Body.Value; 1447 } else { 1448 const OutputSectionBase<ELFT> *OutSec = Section->OutSec; 1449 ESym->st_shndx = OutSec->SectionIndex; 1450 ESym->st_value = OutSec->getVA() + Section->getOffset(Body); 1451 } 1452 ESym->st_name = P.second; 1453 ESym->st_size = Body.template getSize<ELFT>(); 1454 ESym->setBindingAndType(STB_LOCAL, Body.Type); 1455 Buf += sizeof(*ESym); 1456 } 1457 } 1458 } 1459 1460 template <class ELFT> 1461 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) { 1462 // Write the internal symbol table contents to the output symbol table 1463 // pointed by Buf. 1464 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf); 1465 for (const std::pair<SymbolBody *, size_t> &P : Symbols) { 1466 SymbolBody *Body = P.first; 1467 size_t StrOff = P.second; 1468 1469 uint8_t Type = Body->Type; 1470 uintX_t Size = Body->getSize<ELFT>(); 1471 1472 ESym->setBindingAndType(getSymbolBinding(Body), Type); 1473 ESym->st_size = Size; 1474 ESym->st_name = StrOff; 1475 ESym->setVisibility(Body->Backref->Visibility); 1476 ESym->st_value = Body->getVA<ELFT>(); 1477 1478 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body)) 1479 ESym->st_shndx = OutSec->SectionIndex; 1480 else if (isa<DefinedRegular<ELFT>>(Body)) 1481 ESym->st_shndx = SHN_ABS; 1482 1483 // On MIPS we need to mark symbol which has a PLT entry and requires pointer 1484 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker 1485 // distinguish such symbols and MIPS lazy-binding stubs. 1486 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt 1487 if (Config->EMachine == EM_MIPS && Body->isInPlt() && 1488 Body->NeedsCopyOrPltAddr) 1489 ESym->st_other |= STO_MIPS_PLT; 1490 ++ESym; 1491 } 1492 } 1493 1494 template <class ELFT> 1495 const OutputSectionBase<ELFT> * 1496 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) { 1497 switch (Sym->kind()) { 1498 case SymbolBody::DefinedSyntheticKind: 1499 return &cast<DefinedSynthetic<ELFT>>(Sym)->Section; 1500 case SymbolBody::DefinedRegularKind: { 1501 auto &D = cast<DefinedRegular<ELFT>>(*Sym); 1502 if (D.Section) 1503 return D.Section->OutSec; 1504 break; 1505 } 1506 case SymbolBody::DefinedCommonKind: 1507 return Out<ELFT>::Bss; 1508 case SymbolBody::SharedKind: 1509 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy()) 1510 return Out<ELFT>::Bss; 1511 break; 1512 case SymbolBody::UndefinedKind: 1513 case SymbolBody::LazyArchiveKind: 1514 case SymbolBody::LazyObjectKind: 1515 break; 1516 case SymbolBody::DefinedBitcodeKind: 1517 llvm_unreachable("should have been replaced"); 1518 } 1519 return nullptr; 1520 } 1521 1522 template <class ELFT> 1523 VersionTableSection<ELFT>::VersionTableSection() 1524 : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {} 1525 1526 template <class ELFT> void VersionTableSection<ELFT>::finalize() { 1527 this->Header.sh_size = 1528 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1); 1529 this->Header.sh_entsize = sizeof(Elf_Versym); 1530 } 1531 1532 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) { 1533 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1; 1534 for (const std::pair<SymbolBody *, size_t> &P : 1535 Out<ELFT>::DynSymTab->getSymbols()) { 1536 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(P.first)) 1537 OutVersym->vs_index = SS->VersionId; 1538 else 1539 // The reserved identifier for a non-versioned global symbol. 1540 OutVersym->vs_index = 1; 1541 ++OutVersym; 1542 } 1543 } 1544 1545 template <class ELFT> 1546 VersionNeedSection<ELFT>::VersionNeedSection() 1547 : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {} 1548 1549 template <class ELFT> 1550 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) { 1551 if (!SS->Verdef) { 1552 // The reserved identifier for a non-versioned global symbol. 1553 SS->VersionId = 1; 1554 return; 1555 } 1556 SharedFile<ELFT> *F = SS->File; 1557 // If we don't already know that we need an Elf_Verneed for this DSO, prepare 1558 // to create one by adding it to our needed list and creating a dynstr entry 1559 // for the soname. 1560 if (F->VerdefMap.empty()) 1561 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())}); 1562 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef]; 1563 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, 1564 // prepare to create one by allocating a version identifier and creating a 1565 // dynstr entry for the version name. 1566 if (NV.Index == 0) { 1567 NV.StrTab = Out<ELFT>::DynStrTab->addString( 1568 SS->File->getStringTable().data() + SS->Verdef->getAux()->vda_name); 1569 NV.Index = NextIndex++; 1570 } 1571 SS->VersionId = NV.Index; 1572 } 1573 1574 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { 1575 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. 1576 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf); 1577 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size()); 1578 1579 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) { 1580 // Create an Elf_Verneed for this DSO. 1581 Verneed->vn_version = 1; 1582 Verneed->vn_cnt = P.first->VerdefMap.size(); 1583 Verneed->vn_file = P.second; 1584 Verneed->vn_aux = 1585 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed); 1586 Verneed->vn_next = sizeof(Elf_Verneed); 1587 ++Verneed; 1588 1589 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over 1590 // VerdefMap, which will only contain references to needed version 1591 // definitions. Each Elf_Vernaux is based on the information contained in 1592 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of 1593 // pointers, but is deterministic because the pointers refer to Elf_Verdef 1594 // data structures within a single input file. 1595 for (auto &NV : P.first->VerdefMap) { 1596 Vernaux->vna_hash = NV.first->vd_hash; 1597 Vernaux->vna_flags = 0; 1598 Vernaux->vna_other = NV.second.Index; 1599 Vernaux->vna_name = NV.second.StrTab; 1600 Vernaux->vna_next = sizeof(Elf_Vernaux); 1601 ++Vernaux; 1602 } 1603 1604 Vernaux[-1].vna_next = 0; 1605 } 1606 Verneed[-1].vn_next = 0; 1607 } 1608 1609 template <class ELFT> void VersionNeedSection<ELFT>::finalize() { 1610 this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex; 1611 this->Header.sh_info = Needed.size(); 1612 unsigned Size = Needed.size() * sizeof(Elf_Verneed); 1613 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) 1614 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux); 1615 this->Header.sh_size = Size; 1616 } 1617 1618 template <class ELFT> 1619 BuildIdSection<ELFT>::BuildIdSection(size_t HashSize) 1620 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC), 1621 HashSize(HashSize) { 1622 // 16 bytes for the note section header. 1623 this->Header.sh_size = 16 + HashSize; 1624 } 1625 1626 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) { 1627 const endianness E = ELFT::TargetEndianness; 1628 write32<E>(Buf, 4); // Name size 1629 write32<E>(Buf + 4, HashSize); // Content size 1630 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type 1631 memcpy(Buf + 12, "GNU", 4); // Name string 1632 HashBuf = Buf + 16; 1633 } 1634 1635 template <class ELFT> void BuildIdFnv1<ELFT>::update(ArrayRef<uint8_t> Buf) { 1636 // 64-bit FNV-1 hash 1637 const uint64_t Prime = 0x100000001b3; 1638 for (uint8_t B : Buf) { 1639 Hash *= Prime; 1640 Hash ^= B; 1641 } 1642 } 1643 1644 template <class ELFT> void BuildIdFnv1<ELFT>::writeBuildId() { 1645 const endianness E = ELFT::TargetEndianness; 1646 write64<E>(this->HashBuf, Hash); 1647 } 1648 1649 template <class ELFT> void BuildIdMd5<ELFT>::update(ArrayRef<uint8_t> Buf) { 1650 Hash.update(Buf); 1651 } 1652 1653 template <class ELFT> void BuildIdMd5<ELFT>::writeBuildId() { 1654 MD5::MD5Result Res; 1655 Hash.final(Res); 1656 memcpy(this->HashBuf, Res, 16); 1657 } 1658 1659 template <class ELFT> void BuildIdSha1<ELFT>::update(ArrayRef<uint8_t> Buf) { 1660 Hash.update(Buf); 1661 } 1662 1663 template <class ELFT> void BuildIdSha1<ELFT>::writeBuildId() { 1664 memcpy(this->HashBuf, Hash.final().data(), 20); 1665 } 1666 1667 template <class ELFT> 1668 MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection() 1669 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) { 1670 this->Header.sh_addralign = 4; 1671 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo); 1672 this->Header.sh_size = sizeof(Elf_Mips_RegInfo); 1673 } 1674 1675 template <class ELFT> 1676 void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1677 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf); 1678 R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset; 1679 R->ri_gprmask = GprMask; 1680 } 1681 1682 template <class ELFT> 1683 void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1684 // Copy input object file's .reginfo gprmask to output. 1685 auto *S = cast<MipsReginfoInputSection<ELFT>>(C); 1686 GprMask |= S->Reginfo->ri_gprmask; 1687 } 1688 1689 namespace lld { 1690 namespace elf { 1691 template class OutputSectionBase<ELF32LE>; 1692 template class OutputSectionBase<ELF32BE>; 1693 template class OutputSectionBase<ELF64LE>; 1694 template class OutputSectionBase<ELF64BE>; 1695 1696 template class EhFrameHeader<ELF32LE>; 1697 template class EhFrameHeader<ELF32BE>; 1698 template class EhFrameHeader<ELF64LE>; 1699 template class EhFrameHeader<ELF64BE>; 1700 1701 template class GotPltSection<ELF32LE>; 1702 template class GotPltSection<ELF32BE>; 1703 template class GotPltSection<ELF64LE>; 1704 template class GotPltSection<ELF64BE>; 1705 1706 template class GotSection<ELF32LE>; 1707 template class GotSection<ELF32BE>; 1708 template class GotSection<ELF64LE>; 1709 template class GotSection<ELF64BE>; 1710 1711 template class PltSection<ELF32LE>; 1712 template class PltSection<ELF32BE>; 1713 template class PltSection<ELF64LE>; 1714 template class PltSection<ELF64BE>; 1715 1716 template class RelocationSection<ELF32LE>; 1717 template class RelocationSection<ELF32BE>; 1718 template class RelocationSection<ELF64LE>; 1719 template class RelocationSection<ELF64BE>; 1720 1721 template class InterpSection<ELF32LE>; 1722 template class InterpSection<ELF32BE>; 1723 template class InterpSection<ELF64LE>; 1724 template class InterpSection<ELF64BE>; 1725 1726 template class GnuHashTableSection<ELF32LE>; 1727 template class GnuHashTableSection<ELF32BE>; 1728 template class GnuHashTableSection<ELF64LE>; 1729 template class GnuHashTableSection<ELF64BE>; 1730 1731 template class HashTableSection<ELF32LE>; 1732 template class HashTableSection<ELF32BE>; 1733 template class HashTableSection<ELF64LE>; 1734 template class HashTableSection<ELF64BE>; 1735 1736 template class DynamicSection<ELF32LE>; 1737 template class DynamicSection<ELF32BE>; 1738 template class DynamicSection<ELF64LE>; 1739 template class DynamicSection<ELF64BE>; 1740 1741 template class OutputSection<ELF32LE>; 1742 template class OutputSection<ELF32BE>; 1743 template class OutputSection<ELF64LE>; 1744 template class OutputSection<ELF64BE>; 1745 1746 template class EHOutputSection<ELF32LE>; 1747 template class EHOutputSection<ELF32BE>; 1748 template class EHOutputSection<ELF64LE>; 1749 template class EHOutputSection<ELF64BE>; 1750 1751 template class MipsReginfoOutputSection<ELF32LE>; 1752 template class MipsReginfoOutputSection<ELF32BE>; 1753 template class MipsReginfoOutputSection<ELF64LE>; 1754 template class MipsReginfoOutputSection<ELF64BE>; 1755 1756 template class MergeOutputSection<ELF32LE>; 1757 template class MergeOutputSection<ELF32BE>; 1758 template class MergeOutputSection<ELF64LE>; 1759 template class MergeOutputSection<ELF64BE>; 1760 1761 template class StringTableSection<ELF32LE>; 1762 template class StringTableSection<ELF32BE>; 1763 template class StringTableSection<ELF64LE>; 1764 template class StringTableSection<ELF64BE>; 1765 1766 template class SymbolTableSection<ELF32LE>; 1767 template class SymbolTableSection<ELF32BE>; 1768 template class SymbolTableSection<ELF64LE>; 1769 template class SymbolTableSection<ELF64BE>; 1770 1771 template class VersionTableSection<ELF32LE>; 1772 template class VersionTableSection<ELF32BE>; 1773 template class VersionTableSection<ELF64LE>; 1774 template class VersionTableSection<ELF64BE>; 1775 1776 template class VersionNeedSection<ELF32LE>; 1777 template class VersionNeedSection<ELF32BE>; 1778 template class VersionNeedSection<ELF64LE>; 1779 template class VersionNeedSection<ELF64BE>; 1780 1781 template class BuildIdSection<ELF32LE>; 1782 template class BuildIdSection<ELF32BE>; 1783 template class BuildIdSection<ELF64LE>; 1784 template class BuildIdSection<ELF64BE>; 1785 1786 template class BuildIdFnv1<ELF32LE>; 1787 template class BuildIdFnv1<ELF32BE>; 1788 template class BuildIdFnv1<ELF64LE>; 1789 template class BuildIdFnv1<ELF64BE>; 1790 1791 template class BuildIdMd5<ELF32LE>; 1792 template class BuildIdMd5<ELF32BE>; 1793 template class BuildIdMd5<ELF64LE>; 1794 template class BuildIdMd5<ELF64BE>; 1795 1796 template class BuildIdSha1<ELF32LE>; 1797 template class BuildIdSha1<ELF32BE>; 1798 template class BuildIdSha1<ELF64LE>; 1799 template class BuildIdSha1<ELF64BE>; 1800 } 1801 } 1802