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.symbol()->GlobalDynIndex != -1U) 148 return false; 149 Sym.symbol()->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 (uintX_t)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.symbol()->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.symbol()->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 // At beginning of PLT, we have code to call the dynamic linker 273 // to resolve dynsyms at runtime. Write such code. 274 Target->writePltZero(Buf); 275 size_t Off = Target->PltZeroSize; 276 277 for (auto &I : Entries) { 278 const SymbolBody *B = I.first; 279 unsigned RelOff = I.second; 280 uint64_t Got = B->getGotPltVA<ELFT>(); 281 uint64_t Plt = this->getVA() + Off; 282 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); 283 Off += Target->PltEntrySize; 284 } 285 } 286 287 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) { 288 Sym.PltIndex = Entries.size(); 289 unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset(); 290 Entries.push_back(std::make_pair(&Sym, RelOff)); 291 } 292 293 template <class ELFT> void PltSection<ELFT>::finalize() { 294 this->Header.sh_size = 295 Target->PltZeroSize + Entries.size() * Target->PltEntrySize; 296 } 297 298 template <class ELFT> 299 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort) 300 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL, 301 SHF_ALLOC), 302 Sort(Sort) { 303 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 304 this->Header.sh_addralign = sizeof(uintX_t); 305 } 306 307 template <class ELFT> 308 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) { 309 Relocs.push_back(Reloc); 310 } 311 312 template <class ELFT, class RelTy> 313 static bool compRelocations(const RelTy &A, const RelTy &B) { 314 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL); 315 } 316 317 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { 318 uint8_t *BufBegin = Buf; 319 for (const DynamicReloc<ELFT> &Rel : Relocs) { 320 auto *P = reinterpret_cast<Elf_Rela *>(Buf); 321 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); 322 SymbolBody *Sym = Rel.Sym; 323 324 if (Config->Rela) 325 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend; 326 P->r_offset = Rel.OffsetInSec + Rel.OffsetSec->getVA(); 327 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0; 328 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL); 329 } 330 331 if (Sort) { 332 if (Config->Rela) 333 std::stable_sort((Elf_Rela *)BufBegin, 334 (Elf_Rela *)BufBegin + Relocs.size(), 335 compRelocations<ELFT, Elf_Rela>); 336 else 337 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(), 338 compRelocations<ELFT, Elf_Rel>); 339 } 340 } 341 342 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() { 343 return this->Header.sh_entsize * Relocs.size(); 344 } 345 346 template <class ELFT> void RelocationSection<ELFT>::finalize() { 347 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex 348 : Out<ELFT>::DynSymTab->SectionIndex; 349 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize; 350 } 351 352 template <class ELFT> 353 InterpSection<ELFT>::InterpSection() 354 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) { 355 this->Header.sh_size = Config->DynamicLinker.size() + 1; 356 this->Header.sh_addralign = 1; 357 } 358 359 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) { 360 StringRef S = Config->DynamicLinker; 361 memcpy(Buf, S.data(), S.size()); 362 } 363 364 template <class ELFT> 365 HashTableSection<ELFT>::HashTableSection() 366 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) { 367 this->Header.sh_entsize = sizeof(Elf_Word); 368 this->Header.sh_addralign = sizeof(Elf_Word); 369 } 370 371 static uint32_t hashSysv(StringRef Name) { 372 uint32_t H = 0; 373 for (char C : Name) { 374 H = (H << 4) + C; 375 uint32_t G = H & 0xf0000000; 376 if (G) 377 H ^= G >> 24; 378 H &= ~G; 379 } 380 return H; 381 } 382 383 template <class ELFT> void HashTableSection<ELFT>::finalize() { 384 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex; 385 386 unsigned NumEntries = 2; // nbucket and nchain. 387 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries. 388 389 // Create as many buckets as there are symbols. 390 // FIXME: This is simplistic. We can try to optimize it, but implementing 391 // support for SHT_GNU_HASH is probably even more profitable. 392 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); 393 this->Header.sh_size = NumEntries * sizeof(Elf_Word); 394 } 395 396 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { 397 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols(); 398 auto *P = reinterpret_cast<Elf_Word *>(Buf); 399 *P++ = NumSymbols; // nbucket 400 *P++ = NumSymbols; // nchain 401 402 Elf_Word *Buckets = P; 403 Elf_Word *Chains = P + NumSymbols; 404 405 for (const std::pair<SymbolBody *, unsigned> &P : 406 Out<ELFT>::DynSymTab->getSymbols()) { 407 SymbolBody *Body = P.first; 408 StringRef Name = Body->getName(); 409 unsigned I = Body->DynsymIndex; 410 uint32_t Hash = hashSysv(Name) % NumSymbols; 411 Chains[I] = Buckets[Hash]; 412 Buckets[Hash] = I; 413 } 414 } 415 416 static uint32_t hashGnu(StringRef Name) { 417 uint32_t H = 5381; 418 for (uint8_t C : Name) 419 H = (H << 5) + H + C; 420 return H; 421 } 422 423 template <class ELFT> 424 GnuHashTableSection<ELFT>::GnuHashTableSection() 425 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) { 426 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4; 427 this->Header.sh_addralign = sizeof(uintX_t); 428 } 429 430 template <class ELFT> 431 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) { 432 if (!NumHashed) 433 return 0; 434 435 // These values are prime numbers which are not greater than 2^(N-1) + 1. 436 // In result, for any particular NumHashed we return a prime number 437 // which is not greater than NumHashed. 438 static const unsigned Primes[] = { 439 1, 1, 3, 3, 7, 13, 31, 61, 127, 251, 440 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071}; 441 442 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed), 443 array_lengthof(Primes) - 1)]; 444 } 445 446 // Bloom filter estimation: at least 8 bits for each hashed symbol. 447 // GNU Hash table requirement: it should be a power of 2, 448 // the minimum value is 1, even for an empty table. 449 // Expected results for a 32-bit target: 450 // calcMaskWords(0..4) = 1 451 // calcMaskWords(5..8) = 2 452 // calcMaskWords(9..16) = 4 453 // For a 64-bit target: 454 // calcMaskWords(0..8) = 1 455 // calcMaskWords(9..16) = 2 456 // calcMaskWords(17..32) = 4 457 template <class ELFT> 458 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) { 459 if (!NumHashed) 460 return 1; 461 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off)); 462 } 463 464 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() { 465 unsigned NumHashed = Symbols.size(); 466 NBuckets = calcNBuckets(NumHashed); 467 MaskWords = calcMaskWords(NumHashed); 468 // Second hash shift estimation: just predefined values. 469 Shift2 = ELFT::Is64Bits ? 6 : 5; 470 471 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex; 472 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header 473 + sizeof(Elf_Off) * MaskWords // Bloom Filter 474 + sizeof(Elf_Word) * NBuckets // Hash Buckets 475 + sizeof(Elf_Word) * NumHashed; // Hash Values 476 } 477 478 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) { 479 writeHeader(Buf); 480 if (Symbols.empty()) 481 return; 482 writeBloomFilter(Buf); 483 writeHashTable(Buf); 484 } 485 486 template <class ELFT> 487 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) { 488 auto *P = reinterpret_cast<Elf_Word *>(Buf); 489 *P++ = NBuckets; 490 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size(); 491 *P++ = MaskWords; 492 *P++ = Shift2; 493 Buf = reinterpret_cast<uint8_t *>(P); 494 } 495 496 template <class ELFT> 497 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) { 498 unsigned C = sizeof(Elf_Off) * 8; 499 500 auto *Masks = reinterpret_cast<Elf_Off *>(Buf); 501 for (const SymbolData &Sym : Symbols) { 502 size_t Pos = (Sym.Hash / C) & (MaskWords - 1); 503 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) | 504 (uintX_t(1) << ((Sym.Hash >> Shift2) % C)); 505 Masks[Pos] |= V; 506 } 507 Buf += sizeof(Elf_Off) * MaskWords; 508 } 509 510 template <class ELFT> 511 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) { 512 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf); 513 Elf_Word *Values = Buckets + NBuckets; 514 515 int PrevBucket = -1; 516 int I = 0; 517 for (const SymbolData &Sym : Symbols) { 518 int Bucket = Sym.Hash % NBuckets; 519 assert(PrevBucket <= Bucket); 520 if (Bucket != PrevBucket) { 521 Buckets[Bucket] = Sym.Body->DynsymIndex; 522 PrevBucket = Bucket; 523 if (I > 0) 524 Values[I - 1] |= 1; 525 } 526 Values[I] = Sym.Hash & ~1; 527 ++I; 528 } 529 if (I > 0) 530 Values[I - 1] |= 1; 531 } 532 533 static bool includeInGnuHashTable(SymbolBody *B) { 534 // Assume that includeInDynsym() is already checked. 535 return !B->isUndefined(); 536 } 537 538 // Add symbols to this symbol hash table. Note that this function 539 // destructively sort a given vector -- which is needed because 540 // GNU-style hash table places some sorting requirements. 541 template <class ELFT> 542 void GnuHashTableSection<ELFT>::addSymbols( 543 std::vector<std::pair<SymbolBody *, size_t>> &V) { 544 auto Mid = std::stable_partition(V.begin(), V.end(), 545 [](std::pair<SymbolBody *, size_t> &P) { 546 return !includeInGnuHashTable(P.first); 547 }); 548 if (Mid == V.end()) 549 return; 550 for (auto I = Mid, E = V.end(); I != E; ++I) { 551 SymbolBody *B = I->first; 552 size_t StrOff = I->second; 553 Symbols.push_back({B, StrOff, hashGnu(B->getName())}); 554 } 555 556 unsigned NBuckets = calcNBuckets(Symbols.size()); 557 std::stable_sort(Symbols.begin(), Symbols.end(), 558 [&](const SymbolData &L, const SymbolData &R) { 559 return L.Hash % NBuckets < R.Hash % NBuckets; 560 }); 561 562 V.erase(Mid, V.end()); 563 for (const SymbolData &Sym : Symbols) 564 V.push_back({Sym.Body, Sym.STName}); 565 } 566 567 template <class ELFT> 568 DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab) 569 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE), 570 SymTab(SymTab) { 571 Elf_Shdr &Header = this->Header; 572 Header.sh_addralign = sizeof(uintX_t); 573 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8; 574 575 // .dynamic section is not writable on MIPS. 576 // See "Special Section" in Chapter 4 in the following document: 577 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 578 if (Config->EMachine == EM_MIPS) 579 Header.sh_flags = SHF_ALLOC; 580 } 581 582 template <class ELFT> void DynamicSection<ELFT>::finalize() { 583 if (this->Header.sh_size) 584 return; // Already finalized. 585 586 Elf_Shdr &Header = this->Header; 587 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex; 588 589 auto Add = [=](Entry E) { Entries.push_back(E); }; 590 591 // Add strings. We know that these are the last strings to be added to 592 // DynStrTab and doing this here allows this function to set DT_STRSZ. 593 if (!Config->RPath.empty()) 594 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, 595 Out<ELFT>::DynStrTab->addString(Config->RPath)}); 596 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles()) 597 if (F->isNeeded()) 598 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())}); 599 if (!Config->SoName.empty()) 600 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)}); 601 602 Out<ELFT>::DynStrTab->finalize(); 603 604 if (Out<ELFT>::RelaDyn->hasRelocs()) { 605 bool IsRela = Config->Rela; 606 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn}); 607 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()}); 608 Add({IsRela ? DT_RELAENT : DT_RELENT, 609 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))}); 610 } 611 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) { 612 Add({DT_JMPREL, Out<ELFT>::RelaPlt}); 613 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()}); 614 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT, 615 Out<ELFT>::GotPlt}); 616 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)}); 617 } 618 619 Add({DT_SYMTAB, Out<ELFT>::DynSymTab}); 620 Add({DT_SYMENT, sizeof(Elf_Sym)}); 621 Add({DT_STRTAB, Out<ELFT>::DynStrTab}); 622 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()}); 623 if (Out<ELFT>::GnuHashTab) 624 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab}); 625 if (Out<ELFT>::HashTab) 626 Add({DT_HASH, Out<ELFT>::HashTab}); 627 628 if (PreInitArraySec) { 629 Add({DT_PREINIT_ARRAY, PreInitArraySec}); 630 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()}); 631 } 632 if (InitArraySec) { 633 Add({DT_INIT_ARRAY, InitArraySec}); 634 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()}); 635 } 636 if (FiniArraySec) { 637 Add({DT_FINI_ARRAY, FiniArraySec}); 638 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()}); 639 } 640 641 if (SymbolBody *B = SymTab.find(Config->Init)) 642 Add({DT_INIT, B}); 643 if (SymbolBody *B = SymTab.find(Config->Fini)) 644 Add({DT_FINI, B}); 645 646 uint32_t DtFlags = 0; 647 uint32_t DtFlags1 = 0; 648 if (Config->Bsymbolic) 649 DtFlags |= DF_SYMBOLIC; 650 if (Config->ZNodelete) 651 DtFlags1 |= DF_1_NODELETE; 652 if (Config->ZNow) { 653 DtFlags |= DF_BIND_NOW; 654 DtFlags1 |= DF_1_NOW; 655 } 656 if (Config->ZOrigin) { 657 DtFlags |= DF_ORIGIN; 658 DtFlags1 |= DF_1_ORIGIN; 659 } 660 661 if (DtFlags) 662 Add({DT_FLAGS, DtFlags}); 663 if (DtFlags1) 664 Add({DT_FLAGS_1, DtFlags1}); 665 666 if (!Config->Entry.empty()) 667 Add({DT_DEBUG, (uint64_t)0}); 668 669 if (size_t NeedNum = Out<ELFT>::VerNeed->getNeedNum()) { 670 Add({DT_VERSYM, Out<ELFT>::VerSym}); 671 Add({DT_VERNEED, Out<ELFT>::VerNeed}); 672 Add({DT_VERNEEDNUM, NeedNum}); 673 } 674 675 if (Config->EMachine == EM_MIPS) { 676 Add({DT_MIPS_RLD_VERSION, 1}); 677 Add({DT_MIPS_FLAGS, RHF_NOTPOT}); 678 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()}); 679 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()}); 680 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()}); 681 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry()) 682 Add({DT_MIPS_GOTSYM, B->DynsymIndex}); 683 else 684 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()}); 685 Add({DT_PLTGOT, Out<ELFT>::Got}); 686 if (Out<ELFT>::MipsRldMap) 687 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap}); 688 } 689 690 // +1 for DT_NULL 691 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize; 692 } 693 694 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) { 695 auto *P = reinterpret_cast<Elf_Dyn *>(Buf); 696 697 for (const Entry &E : Entries) { 698 P->d_tag = E.Tag; 699 switch (E.Kind) { 700 case Entry::SecAddr: 701 P->d_un.d_ptr = E.OutSec->getVA(); 702 break; 703 case Entry::SymAddr: 704 P->d_un.d_ptr = E.Sym->template getVA<ELFT>(); 705 break; 706 case Entry::PlainInt: 707 P->d_un.d_val = E.Val; 708 break; 709 } 710 ++P; 711 } 712 } 713 714 template <class ELFT> 715 EhFrameHeader<ELFT>::EhFrameHeader() 716 : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS, 717 SHF_ALLOC) { 718 // It's a 4 bytes of header + pointer to the contents of the .eh_frame section 719 // + the number of FDE pointers in the table. 720 this->Header.sh_size = 12; 721 } 722 723 // We have to get PC values of FDEs. They depend on relocations 724 // which are target specific, so we run this code after performing 725 // all relocations. We read the values from ouput buffer according to the 726 // encoding given for FDEs. Return value is an offset to the initial PC value 727 // for the FDE. 728 template <class ELFT> 729 typename EhFrameHeader<ELFT>::uintX_t 730 EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) { 731 const endianness E = ELFT::TargetEndianness; 732 uint8_t Size = F.Enc & 0x7; 733 if (Size == DW_EH_PE_absptr) 734 Size = sizeof(uintX_t) == 8 ? DW_EH_PE_udata8 : DW_EH_PE_udata4; 735 uint64_t PC; 736 switch (Size) { 737 case DW_EH_PE_udata2: 738 PC = read16<E>(F.PCRel); 739 break; 740 case DW_EH_PE_udata4: 741 PC = read32<E>(F.PCRel); 742 break; 743 case DW_EH_PE_udata8: 744 PC = read64<E>(F.PCRel); 745 break; 746 default: 747 fatal("unknown FDE size encoding"); 748 } 749 switch (F.Enc & 0x70) { 750 case DW_EH_PE_absptr: 751 return PC; 752 case DW_EH_PE_pcrel: 753 return PC + EhVA + F.Off + 8; 754 default: 755 fatal("unknown FDE size relative encoding"); 756 } 757 } 758 759 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) { 760 const endianness E = ELFT::TargetEndianness; 761 762 uintX_t EhVA = Sec->getVA(); 763 uintX_t VA = this->getVA(); 764 765 // InitialPC -> Offset in .eh_frame, sorted by InitialPC, and deduplicate PCs. 766 // FIXME: Deduplication leaves unneeded null bytes at the end of the section. 767 std::map<uintX_t, size_t> PcToOffset; 768 for (const FdeData &F : FdeList) 769 PcToOffset[getFdePc(EhVA, F)] = F.Off; 770 771 const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4, 772 DW_EH_PE_udata4, 773 DW_EH_PE_datarel | DW_EH_PE_sdata4}; 774 memcpy(Buf, Header, sizeof(Header)); 775 776 uintX_t EhOff = EhVA - VA - 4; 777 write32<E>(Buf + 4, EhOff); 778 write32<E>(Buf + 8, PcToOffset.size()); 779 Buf += 12; 780 781 for (auto &I : PcToOffset) { 782 // The first four bytes are an offset to the initial PC value for the FDE. 783 write32<E>(Buf, I.first - VA); 784 // The last four bytes are an offset to the FDE data itself. 785 write32<E>(Buf + 4, EhVA + I.second - VA); 786 Buf += 8; 787 } 788 } 789 790 template <class ELFT> 791 void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) { 792 assert((!this->Sec || this->Sec == Sec) && 793 "multiple .eh_frame sections not supported for .eh_frame_hdr"); 794 Live = Config->EhFrameHdr; 795 this->Sec = Sec; 796 } 797 798 template <class ELFT> 799 void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) { 800 if (Live && (Enc & 0xF0) == DW_EH_PE_datarel) 801 fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr"); 802 FdeList.push_back(FdeData{Enc, Off, PCRel}); 803 } 804 805 template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() { 806 // Each FDE entry is 8 bytes long: 807 // The first four bytes are an offset to the initial PC value for the FDE. The 808 // last four byte are an offset to the FDE data itself. 809 this->Header.sh_size += 8; 810 } 811 812 template <class ELFT> 813 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags) 814 : OutputSectionBase<ELFT>(Name, Type, Flags) { 815 if (Type == SHT_RELA) 816 this->Header.sh_entsize = sizeof(Elf_Rela); 817 else if (Type == SHT_REL) 818 this->Header.sh_entsize = sizeof(Elf_Rel); 819 } 820 821 template <class ELFT> void OutputSection<ELFT>::finalize() { 822 uint32_t Type = this->Header.sh_type; 823 if (Type != SHT_RELA && Type != SHT_REL) 824 return; 825 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex; 826 // sh_info for SHT_REL[A] sections should contain the section header index of 827 // the section to which the relocation applies. 828 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection(); 829 this->Header.sh_info = S->OutSec->SectionIndex; 830 } 831 832 template <class ELFT> 833 void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 834 assert(C->Live); 835 auto *S = cast<InputSection<ELFT>>(C); 836 Sections.push_back(S); 837 S->OutSec = this; 838 this->updateAlign(S->Align); 839 } 840 841 // If an input string is in the form of "foo.N" where N is a number, 842 // return N. Otherwise, returns 65536, which is one greater than the 843 // lowest priority. 844 static int getPriority(StringRef S) { 845 size_t Pos = S.rfind('.'); 846 if (Pos == StringRef::npos) 847 return 65536; 848 int V; 849 if (S.substr(Pos + 1).getAsInteger(10, V)) 850 return 65536; 851 return V; 852 } 853 854 template <class ELFT> 855 void OutputSection<ELFT>::forEachInputSection( 856 std::function<void(InputSectionBase<ELFT> *)> F) { 857 for (InputSection<ELFT> *S : Sections) 858 F(S); 859 } 860 861 // Sorts input sections by section name suffixes, so that .foo.N comes 862 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 863 // We want to keep the original order if the priorities are the same 864 // because the compiler keeps the original initialization order in a 865 // translation unit and we need to respect that. 866 // For more detail, read the section of the GCC's manual about init_priority. 867 template <class ELFT> void OutputSection<ELFT>::sortInitFini() { 868 // Sort sections by priority. 869 typedef std::pair<int, InputSection<ELFT> *> Pair; 870 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; 871 872 std::vector<Pair> V; 873 for (InputSection<ELFT> *S : Sections) 874 V.push_back({getPriority(S->getSectionName()), S}); 875 std::stable_sort(V.begin(), V.end(), Comp); 876 Sections.clear(); 877 for (Pair &P : V) 878 Sections.push_back(P.second); 879 } 880 881 // Returns true if S matches /Filename.?\.o$/. 882 static bool isCrtBeginEnd(StringRef S, StringRef Filename) { 883 if (!S.endswith(".o")) 884 return false; 885 S = S.drop_back(2); 886 if (S.endswith(Filename)) 887 return true; 888 return !S.empty() && S.drop_back().endswith(Filename); 889 } 890 891 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } 892 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } 893 894 // .ctors and .dtors are sorted by this priority from highest to lowest. 895 // 896 // 1. The section was contained in crtbegin (crtbegin contains 897 // some sentinel value in its .ctors and .dtors so that the runtime 898 // can find the beginning of the sections.) 899 // 900 // 2. The section has an optional priority value in the form of ".ctors.N" 901 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 902 // they are compared as string rather than number. 903 // 904 // 3. The section is just ".ctors" or ".dtors". 905 // 906 // 4. The section was contained in crtend, which contains an end marker. 907 // 908 // In an ideal world, we don't need this function because .init_array and 909 // .ctors are duplicate features (and .init_array is newer.) However, there 910 // are too many real-world use cases of .ctors, so we had no choice to 911 // support that with this rather ad-hoc semantics. 912 template <class ELFT> 913 static bool compCtors(const InputSection<ELFT> *A, 914 const InputSection<ELFT> *B) { 915 bool BeginA = isCrtbegin(A->getFile()->getName()); 916 bool BeginB = isCrtbegin(B->getFile()->getName()); 917 if (BeginA != BeginB) 918 return BeginA; 919 bool EndA = isCrtend(A->getFile()->getName()); 920 bool EndB = isCrtend(B->getFile()->getName()); 921 if (EndA != EndB) 922 return EndB; 923 StringRef X = A->getSectionName(); 924 StringRef Y = B->getSectionName(); 925 assert(X.startswith(".ctors") || X.startswith(".dtors")); 926 assert(Y.startswith(".ctors") || Y.startswith(".dtors")); 927 X = X.substr(6); 928 Y = Y.substr(6); 929 if (X.empty() && Y.empty()) 930 return false; 931 return X < Y; 932 } 933 934 // Sorts input sections by the special rules for .ctors and .dtors. 935 // Unfortunately, the rules are different from the one for .{init,fini}_array. 936 // Read the comment above. 937 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() { 938 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>); 939 } 940 941 static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) { 942 size_t I = 0; 943 for (; I + A.size() < Size; I += A.size()) 944 memcpy(Buf + I, A.data(), A.size()); 945 memcpy(Buf + I, A.data(), Size - I); 946 } 947 948 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) { 949 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name); 950 if (!Filler.empty()) 951 fill(Buf, this->getSize(), Filler); 952 if (Config->Threads) { 953 parallel_for_each(Sections.begin(), Sections.end(), 954 [=](InputSection<ELFT> *C) { C->writeTo(Buf); }); 955 } else { 956 for (InputSection<ELFT> *C : Sections) 957 C->writeTo(Buf); 958 } 959 } 960 961 template <class ELFT> 962 EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type, 963 uintX_t Flags) 964 : OutputSectionBase<ELFT>(Name, Type, Flags) { 965 Out<ELFT>::EhFrameHdr->assignEhFrame(this); 966 } 967 968 template <class ELFT> 969 void EHOutputSection<ELFT>::forEachInputSection( 970 std::function<void(InputSectionBase<ELFT> *)> F) { 971 for (EHInputSection<ELFT> *S : Sections) 972 F(S); 973 } 974 975 template <class ELFT> 976 EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *Sec, unsigned Index) 977 : Sec(Sec), Index(Index) {} 978 979 template <class ELFT> ArrayRef<uint8_t> EHRegion<ELFT>::data() const { 980 return Sec->Pieces[Index].Data; 981 } 982 983 template <class ELFT> 984 CieRecord<ELFT>::CieRecord(EHInputSection<ELFT> *Sec, unsigned Index) 985 : EHRegion<ELFT>(Sec, Index) {} 986 987 // Read a byte and advance D by one byte. 988 static uint8_t readByte(ArrayRef<uint8_t> &D) { 989 if (D.empty()) 990 fatal("corrupted or unsupported CIE information"); 991 uint8_t B = D.front(); 992 D = D.slice(1); 993 return B; 994 } 995 996 static void skipLeb128(ArrayRef<uint8_t> &D) { 997 while (!D.empty()) { 998 uint8_t Val = D.front(); 999 D = D.slice(1); 1000 if ((Val & 0x80) == 0) 1001 return; 1002 } 1003 fatal("corrupted or unsupported CIE information"); 1004 } 1005 1006 template <class ELFT> static size_t getAugPSize(unsigned Enc) { 1007 switch (Enc & 0x0f) { 1008 case DW_EH_PE_absptr: 1009 case DW_EH_PE_signed: 1010 return ELFT::Is64Bits ? 8 : 4; 1011 case DW_EH_PE_udata2: 1012 case DW_EH_PE_sdata2: 1013 return 2; 1014 case DW_EH_PE_udata4: 1015 case DW_EH_PE_sdata4: 1016 return 4; 1017 case DW_EH_PE_udata8: 1018 case DW_EH_PE_sdata8: 1019 return 8; 1020 } 1021 fatal("unknown FDE encoding"); 1022 } 1023 1024 template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) { 1025 uint8_t Enc = readByte(D); 1026 if ((Enc & 0xf0) == DW_EH_PE_aligned) 1027 fatal("DW_EH_PE_aligned encoding is not supported"); 1028 size_t Size = getAugPSize<ELFT>(Enc); 1029 if (Size >= D.size()) 1030 fatal("corrupted CIE"); 1031 D = D.slice(Size); 1032 } 1033 1034 template <class ELFT> 1035 uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) { 1036 if (D.size() < 8) 1037 fatal("CIE too small"); 1038 D = D.slice(8); 1039 1040 uint8_t Version = readByte(D); 1041 if (Version != 1 && Version != 3) 1042 fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version)); 1043 1044 const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0'); 1045 if (AugEnd == D.end()) 1046 fatal("corrupted CIE"); 1047 StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin()); 1048 D = D.slice(Aug.size() + 1); 1049 1050 // Code alignment factor should always be 1 for .eh_frame. 1051 if (readByte(D) != 1) 1052 fatal("CIE code alignment must be 1"); 1053 1054 // Skip data alignment factor. 1055 skipLeb128(D); 1056 1057 // Skip the return address register. In CIE version 1 this is a single 1058 // byte. In CIE version 3 this is an unsigned LEB128. 1059 if (Version == 1) 1060 readByte(D); 1061 else 1062 skipLeb128(D); 1063 1064 // We only care about an 'R' value, but other records may precede an 'R' 1065 // record. Records are not in TLV (type-length-value) format, so we need 1066 // to teach the linker how to skip records for each type. 1067 for (char C : Aug) { 1068 if (C == 'R') 1069 return readByte(D); 1070 if (C == 'z') { 1071 skipLeb128(D); 1072 continue; 1073 } 1074 if (C == 'P') { 1075 skipAugP<ELFT>(D); 1076 continue; 1077 } 1078 if (C == 'L') { 1079 readByte(D); 1080 continue; 1081 } 1082 fatal("unknown .eh_frame augmentation string: " + Aug); 1083 } 1084 return DW_EH_PE_absptr; 1085 } 1086 1087 template <class ELFT> 1088 static typename ELFT::uint readEntryLength(ArrayRef<uint8_t> D) { 1089 const endianness E = ELFT::TargetEndianness; 1090 if (D.size() < 4) 1091 fatal("CIE/FDE too small"); 1092 1093 // First 4 bytes of CIE/FDE is the size of the record. 1094 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead. 1095 uint64_t V = read32<E>(D.data()); 1096 if (V < UINT32_MAX) { 1097 uint64_t Len = V + 4; 1098 if (Len > D.size()) 1099 fatal("CIE/FIE ends past the end of the section"); 1100 return Len; 1101 } 1102 1103 if (D.size() < 12) 1104 fatal("CIE/FDE too small"); 1105 V = read64<E>(D.data() + 4); 1106 uint64_t Len = V + 12; 1107 if (Len < V || D.size() < Len) 1108 fatal("CIE/FIE ends past the end of the section"); 1109 return Len; 1110 } 1111 1112 // Returns the first relocation that points to a region 1113 // between Begin and Begin+Size. 1114 template <class IntTy, class RelTy> 1115 static const RelTy *getReloc(IntTy Begin, IntTy Size, ArrayRef<RelTy> Rels) { 1116 size_t I = 0; 1117 size_t E = Rels.size(); 1118 while (I != E && Rels[I].r_offset < Begin) 1119 ++I; 1120 if (I == E || Begin + Size <= Rels[I].r_offset) 1121 return nullptr; 1122 return &Rels[I]; 1123 } 1124 1125 template <class ELFT> 1126 template <class RelTy> 1127 void EHOutputSection<ELFT>::addSectionAux(EHInputSection<ELFT> *Sec, 1128 ArrayRef<RelTy> Rels) { 1129 const endianness E = ELFT::TargetEndianness; 1130 1131 Sec->OutSec = this; 1132 this->updateAlign(Sec->Align); 1133 Sections.push_back(Sec); 1134 1135 ArrayRef<uint8_t> D = Sec->getSectionData(); 1136 uintX_t Offset = 0; 1137 1138 DenseMap<uintX_t, uintX_t> OffsetToIndex; 1139 while (!D.empty()) { 1140 uintX_t Length = readEntryLength<ELFT>(D); 1141 // If CIE/FDE data length is zero then Length is 4, this 1142 // shall be considered a terminator and processing shall end. 1143 if (Length == 4) 1144 break; 1145 StringRef Entry((const char *)D.data(), Length); 1146 1147 unsigned Index = Sec->Pieces.size(); 1148 Sec->Pieces.emplace_back(Offset, D.slice(0, Length)); 1149 1150 uint32_t ID = read32<E>(D.data() + 4); 1151 if (ID == 0) { 1152 // CIE 1153 CieRecord<ELFT> Cie(Sec, Index); 1154 if (Config->EhFrameHdr) 1155 Cie.FdeEncoding = getFdeEncoding(D); 1156 1157 SymbolBody *Personality = nullptr; 1158 if (const RelTy *Rel = getReloc(Offset, Length, Rels)) 1159 Personality = &Sec->getFile()->getRelocTargetSym(*Rel); 1160 1161 std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality); 1162 auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size())); 1163 if (P.second) { 1164 Cies.push_back(Cie); 1165 this->Header.sh_size += alignTo(Length, sizeof(uintX_t)); 1166 } 1167 OffsetToIndex[Offset] = P.first->second; 1168 } else { 1169 const RelTy *Rel = getReloc(Offset, Length, Rels); 1170 if (!Rel) 1171 fatal("FDE doesn't reference another section"); 1172 SymbolBody &B = Sec->getFile()->getRelocTargetSym(*Rel); 1173 1174 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B); 1175 if (D && D->Section) { 1176 InputSectionBase<ELFT> *Target = D->Section->Repl; 1177 if (Target && Target->Live) { 1178 uint32_t CieOffset = Offset + 4 - ID; 1179 auto I = OffsetToIndex.find(CieOffset); 1180 if (I == OffsetToIndex.end()) 1181 fatal("invalid CIE reference"); 1182 Cies[I->second].Fdes.push_back(EHRegion<ELFT>(Sec, Index)); 1183 Out<ELFT>::EhFrameHdr->reserveFde(); 1184 this->Header.sh_size += alignTo(Length, sizeof(uintX_t)); 1185 } 1186 } 1187 } 1188 1189 Offset += Length; 1190 D = D.slice(Length); 1191 } 1192 } 1193 1194 template <class ELFT> 1195 void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1196 auto *Sec = cast<EHInputSection<ELFT>>(C); 1197 const Elf_Shdr *RelSec = Sec->RelocSection; 1198 if (!RelSec) { 1199 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr)); 1200 return; 1201 } 1202 ELFFile<ELFT> &Obj = Sec->getFile()->getObj(); 1203 if (RelSec->sh_type == SHT_RELA) 1204 addSectionAux(Sec, Obj.relas(RelSec)); 1205 else 1206 addSectionAux(Sec, Obj.rels(RelSec)); 1207 } 1208 1209 template <class ELFT> 1210 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) { 1211 memcpy(Buf, D.data(), D.size()); 1212 1213 // Fix the size field. -4 since size does not include the size field itself. 1214 const endianness E = ELFT::TargetEndianness; 1215 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4); 1216 } 1217 1218 template <class ELFT> void EHOutputSection<ELFT>::finalize() { 1219 if (Finalized) 1220 return; 1221 Finalized = true; 1222 1223 size_t Offset = 0; 1224 for (const CieRecord<ELFT> &Cie : Cies) { 1225 Cie.Sec->Pieces[Cie.Index].OutputOff = Offset; 1226 Offset += alignTo(Cie.data().size(), sizeof(uintX_t)); 1227 1228 for (const EHRegion<ELFT> &Fde : Cie.Fdes) { 1229 Fde.Sec->Pieces[Fde.Index].OutputOff = Offset; 1230 Offset += alignTo(Fde.data().size(), sizeof(uintX_t)); 1231 } 1232 } 1233 } 1234 1235 template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1236 const endianness E = ELFT::TargetEndianness; 1237 for (const CieRecord<ELFT> &Cie : Cies) { 1238 size_t CieOffset = Cie.Sec->Pieces[Cie.Index].OutputOff; 1239 writeCieFde<ELFT>(Buf + CieOffset, Cie.data()); 1240 1241 for (const EHRegion<ELFT> &Fde : Cie.Fdes) { 1242 size_t Offset = Fde.Sec->Pieces[Fde.Index].OutputOff; 1243 writeCieFde<ELFT>(Buf + Offset, Fde.data()); 1244 write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer 1245 1246 Out<ELFT>::EhFrameHdr->addFde(Cie.FdeEncoding, Offset, Buf + Offset + 8); 1247 } 1248 } 1249 1250 for (EHInputSection<ELFT> *S : Sections) 1251 S->relocate(Buf, nullptr); 1252 } 1253 1254 template <class ELFT> 1255 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type, 1256 uintX_t Flags, uintX_t Alignment) 1257 : OutputSectionBase<ELFT>(Name, Type, Flags), 1258 Builder(llvm::StringTableBuilder::RAW, Alignment) {} 1259 1260 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1261 if (shouldTailMerge()) { 1262 StringRef Data = Builder.data(); 1263 memcpy(Buf, Data.data(), Data.size()); 1264 return; 1265 } 1266 for (const std::pair<CachedHash<StringRef>, size_t> &P : Builder.getMap()) { 1267 StringRef Data = P.first.Val; 1268 memcpy(Buf + P.second, Data.data(), Data.size()); 1269 } 1270 } 1271 1272 static StringRef toStringRef(ArrayRef<uint8_t> A) { 1273 return {(const char *)A.data(), A.size()}; 1274 } 1275 1276 template <class ELFT> 1277 void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1278 auto *Sec = cast<MergeInputSection<ELFT>>(C); 1279 Sec->OutSec = this; 1280 this->updateAlign(Sec->Align); 1281 this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize; 1282 1283 ArrayRef<uint8_t> D = Sec->getSectionData(); 1284 StringRef Data((const char *)D.data(), D.size()); 1285 bool IsString = this->Header.sh_flags & SHF_STRINGS; 1286 1287 for (size_t I = 0, N = Sec->Pieces.size(); I != N; ++I) { 1288 SectionPiece &Piece = Sec->Pieces[I]; 1289 if (!Piece.Live) 1290 continue; 1291 uintX_t OutputOffset = Builder.add(toStringRef(Piece.Data)); 1292 if (!IsString || !shouldTailMerge()) 1293 Piece.OutputOff = OutputOffset; 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->symbol(); 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->symbol()->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 this->Header.sh_addralign = sizeof(uint16_t); 1526 } 1527 1528 template <class ELFT> void VersionTableSection<ELFT>::finalize() { 1529 this->Header.sh_size = 1530 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1); 1531 this->Header.sh_entsize = sizeof(Elf_Versym); 1532 } 1533 1534 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) { 1535 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1; 1536 for (const std::pair<SymbolBody *, size_t> &P : 1537 Out<ELFT>::DynSymTab->getSymbols()) { 1538 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(P.first)) 1539 OutVersym->vs_index = SS->VersionId; 1540 else 1541 // The reserved identifier for a non-versioned global symbol. 1542 OutVersym->vs_index = 1; 1543 ++OutVersym; 1544 } 1545 } 1546 1547 template <class ELFT> 1548 VersionNeedSection<ELFT>::VersionNeedSection() 1549 : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) { 1550 this->Header.sh_addralign = sizeof(uint32_t); 1551 } 1552 1553 template <class ELFT> 1554 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) { 1555 if (!SS->Verdef) { 1556 // The reserved identifier for a non-versioned global symbol. 1557 SS->VersionId = 1; 1558 return; 1559 } 1560 SharedFile<ELFT> *F = SS->File; 1561 // If we don't already know that we need an Elf_Verneed for this DSO, prepare 1562 // to create one by adding it to our needed list and creating a dynstr entry 1563 // for the soname. 1564 if (F->VerdefMap.empty()) 1565 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())}); 1566 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef]; 1567 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, 1568 // prepare to create one by allocating a version identifier and creating a 1569 // dynstr entry for the version name. 1570 if (NV.Index == 0) { 1571 NV.StrTab = Out<ELFT>::DynStrTab->addString( 1572 SS->File->getStringTable().data() + SS->Verdef->getAux()->vda_name); 1573 NV.Index = NextIndex++; 1574 } 1575 SS->VersionId = NV.Index; 1576 } 1577 1578 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { 1579 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. 1580 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf); 1581 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size()); 1582 1583 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) { 1584 // Create an Elf_Verneed for this DSO. 1585 Verneed->vn_version = 1; 1586 Verneed->vn_cnt = P.first->VerdefMap.size(); 1587 Verneed->vn_file = P.second; 1588 Verneed->vn_aux = 1589 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed); 1590 Verneed->vn_next = sizeof(Elf_Verneed); 1591 ++Verneed; 1592 1593 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over 1594 // VerdefMap, which will only contain references to needed version 1595 // definitions. Each Elf_Vernaux is based on the information contained in 1596 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of 1597 // pointers, but is deterministic because the pointers refer to Elf_Verdef 1598 // data structures within a single input file. 1599 for (auto &NV : P.first->VerdefMap) { 1600 Vernaux->vna_hash = NV.first->vd_hash; 1601 Vernaux->vna_flags = 0; 1602 Vernaux->vna_other = NV.second.Index; 1603 Vernaux->vna_name = NV.second.StrTab; 1604 Vernaux->vna_next = sizeof(Elf_Vernaux); 1605 ++Vernaux; 1606 } 1607 1608 Vernaux[-1].vna_next = 0; 1609 } 1610 Verneed[-1].vn_next = 0; 1611 } 1612 1613 template <class ELFT> void VersionNeedSection<ELFT>::finalize() { 1614 this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex; 1615 this->Header.sh_info = Needed.size(); 1616 unsigned Size = Needed.size() * sizeof(Elf_Verneed); 1617 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) 1618 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux); 1619 this->Header.sh_size = Size; 1620 } 1621 1622 template <class ELFT> 1623 BuildIdSection<ELFT>::BuildIdSection(size_t HashSize) 1624 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC), 1625 HashSize(HashSize) { 1626 // 16 bytes for the note section header. 1627 this->Header.sh_size = 16 + HashSize; 1628 } 1629 1630 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) { 1631 const endianness E = ELFT::TargetEndianness; 1632 write32<E>(Buf, 4); // Name size 1633 write32<E>(Buf + 4, HashSize); // Content size 1634 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type 1635 memcpy(Buf + 12, "GNU", 4); // Name string 1636 HashBuf = Buf + 16; 1637 } 1638 1639 template <class ELFT> 1640 void BuildIdFnv1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) { 1641 const endianness E = ELFT::TargetEndianness; 1642 1643 // 64-bit FNV-1 hash 1644 uint64_t Hash = 0xcbf29ce484222325; 1645 for (ArrayRef<uint8_t> Buf : Bufs) { 1646 for (uint8_t B : Buf) { 1647 Hash *= 0x100000001b3; 1648 Hash ^= B; 1649 } 1650 } 1651 write64<E>(this->HashBuf, Hash); 1652 } 1653 1654 template <class ELFT> 1655 void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) { 1656 llvm::MD5 Hash; 1657 for (ArrayRef<uint8_t> Buf : Bufs) 1658 Hash.update(Buf); 1659 MD5::MD5Result Res; 1660 Hash.final(Res); 1661 memcpy(this->HashBuf, Res, 16); 1662 } 1663 1664 template <class ELFT> 1665 void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) { 1666 llvm::SHA1 Hash; 1667 for (ArrayRef<uint8_t> Buf : Bufs) 1668 Hash.update(Buf); 1669 memcpy(this->HashBuf, Hash.final().data(), 20); 1670 } 1671 1672 template <class ELFT> 1673 BuildIdHexstring<ELFT>::BuildIdHexstring() 1674 : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {} 1675 1676 template <class ELFT> 1677 void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) { 1678 memcpy(this->HashBuf, Config->BuildIdVector.data(), 1679 Config->BuildIdVector.size()); 1680 } 1681 1682 template <class ELFT> 1683 MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection() 1684 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) { 1685 this->Header.sh_addralign = 4; 1686 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo); 1687 this->Header.sh_size = sizeof(Elf_Mips_RegInfo); 1688 } 1689 1690 template <class ELFT> 1691 void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1692 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf); 1693 R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset; 1694 R->ri_gprmask = GprMask; 1695 } 1696 1697 template <class ELFT> 1698 void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1699 // Copy input object file's .reginfo gprmask to output. 1700 auto *S = cast<MipsReginfoInputSection<ELFT>>(C); 1701 GprMask |= S->Reginfo->ri_gprmask; 1702 } 1703 1704 template <class ELFT> 1705 MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection() 1706 : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS, 1707 SHF_ALLOC | SHF_MIPS_NOSTRIP) { 1708 this->Header.sh_addralign = 8; 1709 this->Header.sh_entsize = 1; 1710 this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo); 1711 } 1712 1713 template <class ELFT> 1714 void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) { 1715 auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf); 1716 Opt->kind = ODK_REGINFO; 1717 Opt->size = this->Header.sh_size; 1718 Opt->section = 0; 1719 Opt->info = 0; 1720 auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt)); 1721 Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset; 1722 Reg->ri_gprmask = GprMask; 1723 } 1724 1725 template <class ELFT> 1726 void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) { 1727 auto *S = cast<MipsOptionsInputSection<ELFT>>(C); 1728 if (S->Reginfo) 1729 GprMask |= S->Reginfo->ri_gprmask; 1730 } 1731 1732 namespace lld { 1733 namespace elf { 1734 template class OutputSectionBase<ELF32LE>; 1735 template class OutputSectionBase<ELF32BE>; 1736 template class OutputSectionBase<ELF64LE>; 1737 template class OutputSectionBase<ELF64BE>; 1738 1739 template class EhFrameHeader<ELF32LE>; 1740 template class EhFrameHeader<ELF32BE>; 1741 template class EhFrameHeader<ELF64LE>; 1742 template class EhFrameHeader<ELF64BE>; 1743 1744 template class GotPltSection<ELF32LE>; 1745 template class GotPltSection<ELF32BE>; 1746 template class GotPltSection<ELF64LE>; 1747 template class GotPltSection<ELF64BE>; 1748 1749 template class GotSection<ELF32LE>; 1750 template class GotSection<ELF32BE>; 1751 template class GotSection<ELF64LE>; 1752 template class GotSection<ELF64BE>; 1753 1754 template class PltSection<ELF32LE>; 1755 template class PltSection<ELF32BE>; 1756 template class PltSection<ELF64LE>; 1757 template class PltSection<ELF64BE>; 1758 1759 template class RelocationSection<ELF32LE>; 1760 template class RelocationSection<ELF32BE>; 1761 template class RelocationSection<ELF64LE>; 1762 template class RelocationSection<ELF64BE>; 1763 1764 template class InterpSection<ELF32LE>; 1765 template class InterpSection<ELF32BE>; 1766 template class InterpSection<ELF64LE>; 1767 template class InterpSection<ELF64BE>; 1768 1769 template class GnuHashTableSection<ELF32LE>; 1770 template class GnuHashTableSection<ELF32BE>; 1771 template class GnuHashTableSection<ELF64LE>; 1772 template class GnuHashTableSection<ELF64BE>; 1773 1774 template class HashTableSection<ELF32LE>; 1775 template class HashTableSection<ELF32BE>; 1776 template class HashTableSection<ELF64LE>; 1777 template class HashTableSection<ELF64BE>; 1778 1779 template class DynamicSection<ELF32LE>; 1780 template class DynamicSection<ELF32BE>; 1781 template class DynamicSection<ELF64LE>; 1782 template class DynamicSection<ELF64BE>; 1783 1784 template class OutputSection<ELF32LE>; 1785 template class OutputSection<ELF32BE>; 1786 template class OutputSection<ELF64LE>; 1787 template class OutputSection<ELF64BE>; 1788 1789 template class EHOutputSection<ELF32LE>; 1790 template class EHOutputSection<ELF32BE>; 1791 template class EHOutputSection<ELF64LE>; 1792 template class EHOutputSection<ELF64BE>; 1793 1794 template class MipsReginfoOutputSection<ELF32LE>; 1795 template class MipsReginfoOutputSection<ELF32BE>; 1796 template class MipsReginfoOutputSection<ELF64LE>; 1797 template class MipsReginfoOutputSection<ELF64BE>; 1798 1799 template class MipsOptionsOutputSection<ELF32LE>; 1800 template class MipsOptionsOutputSection<ELF32BE>; 1801 template class MipsOptionsOutputSection<ELF64LE>; 1802 template class MipsOptionsOutputSection<ELF64BE>; 1803 1804 template class MergeOutputSection<ELF32LE>; 1805 template class MergeOutputSection<ELF32BE>; 1806 template class MergeOutputSection<ELF64LE>; 1807 template class MergeOutputSection<ELF64BE>; 1808 1809 template class StringTableSection<ELF32LE>; 1810 template class StringTableSection<ELF32BE>; 1811 template class StringTableSection<ELF64LE>; 1812 template class StringTableSection<ELF64BE>; 1813 1814 template class SymbolTableSection<ELF32LE>; 1815 template class SymbolTableSection<ELF32BE>; 1816 template class SymbolTableSection<ELF64LE>; 1817 template class SymbolTableSection<ELF64BE>; 1818 1819 template class VersionTableSection<ELF32LE>; 1820 template class VersionTableSection<ELF32BE>; 1821 template class VersionTableSection<ELF64LE>; 1822 template class VersionTableSection<ELF64BE>; 1823 1824 template class VersionNeedSection<ELF32LE>; 1825 template class VersionNeedSection<ELF32BE>; 1826 template class VersionNeedSection<ELF64LE>; 1827 template class VersionNeedSection<ELF64BE>; 1828 1829 template class BuildIdSection<ELF32LE>; 1830 template class BuildIdSection<ELF32BE>; 1831 template class BuildIdSection<ELF64LE>; 1832 template class BuildIdSection<ELF64BE>; 1833 1834 template class BuildIdFnv1<ELF32LE>; 1835 template class BuildIdFnv1<ELF32BE>; 1836 template class BuildIdFnv1<ELF64LE>; 1837 template class BuildIdFnv1<ELF64BE>; 1838 1839 template class BuildIdMd5<ELF32LE>; 1840 template class BuildIdMd5<ELF32BE>; 1841 template class BuildIdMd5<ELF64LE>; 1842 template class BuildIdMd5<ELF64BE>; 1843 1844 template class BuildIdSha1<ELF32LE>; 1845 template class BuildIdSha1<ELF32BE>; 1846 template class BuildIdSha1<ELF64LE>; 1847 template class BuildIdSha1<ELF64BE>; 1848 1849 template class BuildIdHexstring<ELF32LE>; 1850 template class BuildIdHexstring<ELF32BE>; 1851 template class BuildIdHexstring<ELF64LE>; 1852 template class BuildIdHexstring<ELF64BE>; 1853 } 1854 } 1855