1 //===- InputFiles.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 "InputFiles.h" 11 #include "Driver.h" 12 #include "ELFCreator.h" 13 #include "Error.h" 14 #include "InputSection.h" 15 #include "LinkerScript.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/Bitcode/ReaderWriter.h" 20 #include "llvm/CodeGen/Analysis.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/LTO/LTO.h" 24 #include "llvm/MC/StringTableBuilder.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/raw_ostream.h" 27 28 using namespace llvm; 29 using namespace llvm::ELF; 30 using namespace llvm::object; 31 using namespace llvm::sys::fs; 32 33 using namespace lld; 34 using namespace lld::elf; 35 36 std::vector<InputFile *> InputFile::Pool; 37 38 // Deletes all InputFile instances created so far. 39 void InputFile::freePool() { 40 // Files are freed in reverse order so that files created 41 // from other files (e.g. object files extracted from archives) 42 // are freed in the proper order. 43 for (int I = Pool.size() - 1; I >= 0; --I) 44 delete Pool[I]; 45 } 46 47 // Returns "(internal)", "foo.a(bar.o)" or "baz.o". 48 std::string elf::getFilename(const InputFile *F) { 49 if (!F) 50 return "(internal)"; 51 if (!F->ArchiveName.empty()) 52 return (F->ArchiveName + "(" + F->getName() + ")").str(); 53 return F->getName(); 54 } 55 56 template <class ELFT> static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) { 57 std::error_code EC; 58 ELFFile<ELFT> F(MB.getBuffer(), EC); 59 if (EC) 60 fatal(EC, "failed to read " + MB.getBufferIdentifier()); 61 return F; 62 } 63 64 template <class ELFT> static ELFKind getELFKind() { 65 if (ELFT::TargetEndianness == support::little) 66 return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind; 67 return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind; 68 } 69 70 template <class ELFT> 71 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) 72 : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) { 73 EKind = getELFKind<ELFT>(); 74 EMachine = ELFObj.getHeader()->e_machine; 75 } 76 77 template <class ELFT> 78 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) { 79 if (!Symtab) 80 return Elf_Sym_Range(nullptr, nullptr); 81 Elf_Sym_Range Syms = ELFObj.symbols(Symtab); 82 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); 83 uint32_t FirstNonLocal = Symtab->sh_info; 84 if (FirstNonLocal == 0 || FirstNonLocal > NumSymbols) 85 fatal(getFilename(this) + ": invalid sh_info in symbol table"); 86 87 if (OnlyGlobals) 88 return makeArrayRef(Syms.begin() + FirstNonLocal, Syms.end()); 89 return makeArrayRef(Syms.begin(), Syms.end()); 90 } 91 92 template <class ELFT> 93 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const { 94 uint32_t I = Sym.st_shndx; 95 if (I == ELF::SHN_XINDEX) 96 return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX); 97 if (I >= ELF::SHN_LORESERVE) 98 return 0; 99 return I; 100 } 101 102 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() { 103 if (!Symtab) 104 return; 105 StringTable = check(ELFObj.getStringTableForSymtab(*Symtab)); 106 } 107 108 template <class ELFT> 109 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M) 110 : ELFFileBase<ELFT>(Base::ObjectKind, M) {} 111 112 template <class ELFT> 113 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() { 114 if (!this->Symtab) 115 return this->SymbolBodies; 116 uint32_t FirstNonLocal = this->Symtab->sh_info; 117 return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal); 118 } 119 120 template <class ELFT> 121 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() { 122 if (!this->Symtab) 123 return this->SymbolBodies; 124 uint32_t FirstNonLocal = this->Symtab->sh_info; 125 return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1); 126 } 127 128 template <class ELFT> 129 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() { 130 if (!this->Symtab) 131 return this->SymbolBodies; 132 return makeArrayRef(this->SymbolBodies).slice(1); 133 } 134 135 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const { 136 if (ELFT::Is64Bits && MipsOptions && MipsOptions->Reginfo) 137 return MipsOptions->Reginfo->ri_gp_value; 138 if (!ELFT::Is64Bits && MipsReginfo && MipsReginfo->Reginfo) 139 return MipsReginfo->Reginfo->ri_gp_value; 140 return 0; 141 } 142 143 template <class ELFT> 144 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) { 145 // Read section and symbol tables. 146 initializeSections(ComdatGroups); 147 initializeSymbols(); 148 } 149 150 // Sections with SHT_GROUP and comdat bits define comdat section groups. 151 // They are identified and deduplicated by group name. This function 152 // returns a group name. 153 template <class ELFT> 154 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) { 155 const ELFFile<ELFT> &Obj = this->ELFObj; 156 const Elf_Shdr *Symtab = check(Obj.getSection(Sec.sh_link)); 157 const Elf_Sym *Sym = Obj.getSymbol(Symtab, Sec.sh_info); 158 StringRef Strtab = check(Obj.getStringTableForSymtab(*Symtab)); 159 return check(Sym->getName(Strtab)); 160 } 161 162 template <class ELFT> 163 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word> 164 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) { 165 const ELFFile<ELFT> &Obj = this->ELFObj; 166 ArrayRef<Elf_Word> Entries = 167 check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec)); 168 if (Entries.empty() || Entries[0] != GRP_COMDAT) 169 fatal(getFilename(this) + ": unsupported SHT_GROUP format"); 170 return Entries.slice(1); 171 } 172 173 template <class ELFT> 174 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) { 175 // We don't merge sections if -O0 (default is -O1). This makes sometimes 176 // the linker significantly faster, although the output will be bigger. 177 if (Config->Optimize == 0) 178 return false; 179 180 // Do not merge sections if generating a relocatable object. It makes 181 // the code simpler because we do not need to update relocation addends 182 // to reflect changes introduced by merging. Instead of that we write 183 // such "merge" sections into separate OutputSections and keep SHF_MERGE 184 // / SHF_STRINGS flags and sh_entsize value to be able to perform merging 185 // later during a final linking. 186 if (Config->Relocatable) 187 return false; 188 189 // A mergeable section with size 0 is useless because they don't have 190 // any data to merge. A mergeable string section with size 0 can be 191 // argued as invalid because it doesn't end with a null character. 192 // We'll avoid a mess by handling them as if they were non-mergeable. 193 if (Sec.sh_size == 0) 194 return false; 195 196 // Check for sh_entsize. The ELF spec is not clear about the zero 197 // sh_entsize. It says that "the member [sh_entsize] contains 0 if 198 // the section does not hold a table of fixed-size entries". We know 199 // that Rust 1.13 produces a string mergeable section with a zero 200 // sh_entsize. Here we just accept it rather than being picky about it. 201 uintX_t EntSize = Sec.sh_entsize; 202 if (EntSize == 0) 203 return false; 204 if (Sec.sh_size % EntSize) 205 fatal(getFilename(this) + 206 ": SHF_MERGE section size must be a multiple of sh_entsize"); 207 208 uintX_t Flags = Sec.sh_flags; 209 if (!(Flags & SHF_MERGE)) 210 return false; 211 if (Flags & SHF_WRITE) 212 fatal(getFilename(this) + ": writable SHF_MERGE section is not supported"); 213 214 // Don't try to merge if the alignment is larger than the sh_entsize and this 215 // is not SHF_STRINGS. 216 // 217 // Since this is not a SHF_STRINGS, we would need to pad after every entity. 218 // It would be equivalent for the producer of the .o to just set a larger 219 // sh_entsize. 220 if (Flags & SHF_STRINGS) 221 return true; 222 223 return Sec.sh_addralign <= EntSize; 224 } 225 226 template <class ELFT> 227 void elf::ObjectFile<ELFT>::initializeSections( 228 DenseSet<StringRef> &ComdatGroups) { 229 uint64_t Size = this->ELFObj.getNumSections(); 230 Sections.resize(Size); 231 unsigned I = -1; 232 const ELFFile<ELFT> &Obj = this->ELFObj; 233 for (const Elf_Shdr &Sec : Obj.sections()) { 234 ++I; 235 if (Sections[I] == &InputSection<ELFT>::Discarded) 236 continue; 237 238 // SHF_EXCLUDE'ed sections are discarded by the linker. However, 239 // if -r is given, we'll let the final link discard such sections. 240 // This is compatible with GNU. 241 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) { 242 Sections[I] = &InputSection<ELFT>::Discarded; 243 continue; 244 } 245 246 switch (Sec.sh_type) { 247 case SHT_GROUP: 248 Sections[I] = &InputSection<ELFT>::Discarded; 249 if (ComdatGroups.insert(getShtGroupSignature(Sec)).second) 250 continue; 251 for (uint32_t SecIndex : getShtGroupEntries(Sec)) { 252 if (SecIndex >= Size) 253 fatal(getFilename(this) + ": invalid section index in group: " + 254 Twine(SecIndex)); 255 Sections[SecIndex] = &InputSection<ELFT>::Discarded; 256 } 257 break; 258 case SHT_SYMTAB: 259 this->Symtab = &Sec; 260 break; 261 case SHT_SYMTAB_SHNDX: 262 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec)); 263 break; 264 case SHT_STRTAB: 265 case SHT_NULL: 266 break; 267 default: 268 Sections[I] = createInputSection(Sec); 269 } 270 } 271 } 272 273 template <class ELFT> 274 InputSectionBase<ELFT> * 275 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) { 276 uint32_t Idx = Sec.sh_info; 277 if (Idx >= Sections.size()) 278 fatal(getFilename(this) + ": invalid relocated section index: " + 279 Twine(Idx)); 280 InputSectionBase<ELFT> *Target = Sections[Idx]; 281 282 // Strictly speaking, a relocation section must be included in the 283 // group of the section it relocates. However, LLVM 3.3 and earlier 284 // would fail to do so, so we gracefully handle that case. 285 if (Target == &InputSection<ELFT>::Discarded) 286 return nullptr; 287 288 if (!Target) 289 fatal(getFilename(this) + ": unsupported relocation reference"); 290 return Target; 291 } 292 293 template <class ELFT> 294 InputSectionBase<ELFT> * 295 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) { 296 StringRef Name = check(this->ELFObj.getSectionName(&Sec)); 297 298 switch (Sec.sh_type) { 299 case SHT_ARM_ATTRIBUTES: 300 // FIXME: ARM meta-data section. At present attributes are ignored, 301 // they can be used to reason about object compatibility. 302 return &InputSection<ELFT>::Discarded; 303 case SHT_MIPS_REGINFO: 304 MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec, Name)); 305 return MipsReginfo.get(); 306 case SHT_MIPS_OPTIONS: 307 MipsOptions.reset(new MipsOptionsInputSection<ELFT>(this, &Sec, Name)); 308 return MipsOptions.get(); 309 case SHT_MIPS_ABIFLAGS: 310 MipsAbiFlags.reset(new MipsAbiFlagsInputSection<ELFT>(this, &Sec, Name)); 311 return MipsAbiFlags.get(); 312 case SHT_RELA: 313 case SHT_REL: { 314 // This section contains relocation information. 315 // If -r is given, we do not interpret or apply relocation 316 // but just copy relocation sections to output. 317 if (Config->Relocatable) 318 return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name); 319 320 // Find the relocation target section and associate this 321 // section with it. 322 InputSectionBase<ELFT> *Target = getRelocTarget(Sec); 323 if (!Target) 324 return nullptr; 325 if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) { 326 S->RelocSections.push_back(&Sec); 327 return nullptr; 328 } 329 if (auto *S = dyn_cast<EhInputSection<ELFT>>(Target)) { 330 if (S->RelocSection) 331 fatal(getFilename(this) + 332 ": multiple relocation sections to .eh_frame are not supported"); 333 S->RelocSection = &Sec; 334 return nullptr; 335 } 336 fatal(getFilename(this) + 337 ": relocations pointing to SHF_MERGE are not supported"); 338 } 339 } 340 341 // .note.GNU-stack is a marker section to control the presence of 342 // PT_GNU_STACK segment in outputs. Since the presence of the segment 343 // is controlled only by the command line option (-z execstack) in LLD, 344 // .note.GNU-stack is ignored. 345 if (Name == ".note.GNU-stack") 346 return &InputSection<ELFT>::Discarded; 347 348 if (Name == ".note.GNU-split-stack") { 349 error("objects using splitstacks are not supported"); 350 return &InputSection<ELFT>::Discarded; 351 } 352 353 if (Config->Strip != StripPolicy::None && Name.startswith(".debug")) 354 return &InputSection<ELFT>::Discarded; 355 356 // The linker merges EH (exception handling) frames and creates a 357 // .eh_frame_hdr section for runtime. So we handle them with a special 358 // class. For relocatable outputs, they are just passed through. 359 if (Name == ".eh_frame" && !Config->Relocatable) 360 return new (EHAlloc.Allocate()) EhInputSection<ELFT>(this, &Sec, Name); 361 362 if (shouldMerge(Sec)) 363 return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec, Name); 364 return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name); 365 } 366 367 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() { 368 this->initStringTable(); 369 Elf_Sym_Range Syms = this->getElfSymbols(false); 370 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); 371 SymbolBodies.reserve(NumSymbols); 372 for (const Elf_Sym &Sym : Syms) 373 SymbolBodies.push_back(createSymbolBody(&Sym)); 374 } 375 376 template <class ELFT> 377 InputSectionBase<ELFT> * 378 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const { 379 uint32_t Index = this->getSectionIndex(Sym); 380 if (Index >= Sections.size()) 381 fatal(getFilename(this) + ": invalid section index: " + Twine(Index)); 382 InputSectionBase<ELFT> *S = Sections[Index]; 383 384 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 385 // could generate broken objects. STT_SECTION symbols can be 386 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections. 387 // In this case it is fine for section to be null here as we 388 // do not allocate sections of these types. 389 if (!S) { 390 if (Index == 0 || Sym.getType() == STT_SECTION) 391 return nullptr; 392 fatal(getFilename(this) + ": invalid section index: " + Twine(Index)); 393 } 394 395 if (S == &InputSectionBase<ELFT>::Discarded) 396 return S; 397 return S->Repl; 398 } 399 400 template <class ELFT> 401 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) { 402 int Binding = Sym->getBinding(); 403 InputSectionBase<ELFT> *Sec = getSection(*Sym); 404 if (Binding == STB_LOCAL) { 405 if (Sym->st_shndx == SHN_UNDEF) 406 return new (this->Alloc) 407 Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this); 408 return new (this->Alloc) DefinedRegular<ELFT>(*Sym, Sec); 409 } 410 411 StringRef Name = check(Sym->getName(this->StringTable)); 412 413 switch (Sym->st_shndx) { 414 case SHN_UNDEF: 415 return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other, 416 Sym->getType(), 417 /*CanOmitFromDynSym*/ false, this) 418 ->body(); 419 case SHN_COMMON: 420 if (Sym->st_value == 0) 421 fatal(getFilename(this) + ": common symbol '" + Name + 422 "' alignment is 0"); 423 return elf::Symtab<ELFT>::X->addCommon(Name, Sym->st_size, Sym->st_value, 424 Binding, Sym->st_other, 425 Sym->getType(), this) 426 ->body(); 427 } 428 429 switch (Binding) { 430 default: 431 fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding)); 432 case STB_GLOBAL: 433 case STB_WEAK: 434 case STB_GNU_UNIQUE: 435 if (Sec == &InputSection<ELFT>::Discarded) 436 return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other, 437 Sym->getType(), 438 /*CanOmitFromDynSym*/ false, 439 this) 440 ->body(); 441 return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body(); 442 } 443 } 444 445 template <class ELFT> void ArchiveFile::parse() { 446 File = check(Archive::create(MB), "failed to parse archive"); 447 448 // Read the symbol table to construct Lazy objects. 449 for (const Archive::Symbol &Sym : File->symbols()) 450 Symtab<ELFT>::X->addLazyArchive(this, Sym); 451 } 452 453 // Returns a buffer pointing to a member file containing a given symbol. 454 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) { 455 Archive::Child C = 456 check(Sym->getMember(), 457 "could not get the member for symbol " + Sym->getName()); 458 459 if (!Seen.insert(C.getChildOffset()).second) 460 return MemoryBufferRef(); 461 462 MemoryBufferRef Ret = 463 check(C.getMemoryBufferRef(), 464 "could not get the buffer for the member defining symbol " + 465 Sym->getName()); 466 467 if (C.getParent()->isThin() && Driver->Cpio) 468 Driver->Cpio->append(relativeToRoot(check(C.getFullName())), 469 Ret.getBuffer()); 470 471 return Ret; 472 } 473 474 template <class ELFT> 475 SharedFile<ELFT>::SharedFile(MemoryBufferRef M) 476 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {} 477 478 template <class ELFT> 479 const typename ELFT::Shdr * 480 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const { 481 uint32_t Index = this->getSectionIndex(Sym); 482 if (Index == 0) 483 return nullptr; 484 return check(this->ELFObj.getSection(Index)); 485 } 486 487 // Partially parse the shared object file so that we can call 488 // getSoName on this object. 489 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 490 typedef typename ELFT::Dyn Elf_Dyn; 491 typedef typename ELFT::uint uintX_t; 492 const Elf_Shdr *DynamicSec = nullptr; 493 494 const ELFFile<ELFT> Obj = this->ELFObj; 495 for (const Elf_Shdr &Sec : Obj.sections()) { 496 switch (Sec.sh_type) { 497 default: 498 continue; 499 case SHT_DYNSYM: 500 this->Symtab = &Sec; 501 break; 502 case SHT_DYNAMIC: 503 DynamicSec = &Sec; 504 break; 505 case SHT_SYMTAB_SHNDX: 506 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec)); 507 break; 508 case SHT_GNU_versym: 509 this->VersymSec = &Sec; 510 break; 511 case SHT_GNU_verdef: 512 this->VerdefSec = &Sec; 513 break; 514 } 515 } 516 517 this->initStringTable(); 518 519 // DSOs are identified by soname, and they usually contain 520 // DT_SONAME tag in their header. But if they are missing, 521 // filenames are used as default sonames. 522 SoName = sys::path::filename(this->getName()); 523 524 if (!DynamicSec) 525 return; 526 527 ArrayRef<Elf_Dyn> Arr = 528 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 529 getFilename(this) + ": getSectionContentsAsArray failed"); 530 for (const Elf_Dyn &Dyn : Arr) { 531 if (Dyn.d_tag == DT_SONAME) { 532 uintX_t Val = Dyn.getVal(); 533 if (Val >= this->StringTable.size()) 534 fatal(getFilename(this) + ": invalid DT_SONAME entry"); 535 SoName = StringRef(this->StringTable.data() + Val); 536 return; 537 } 538 } 539 } 540 541 // Parse the version definitions in the object file if present. Returns a vector 542 // whose nth element contains a pointer to the Elf_Verdef for version identifier 543 // n. Version identifiers that are not definitions map to nullptr. The array 544 // always has at least length 1. 545 template <class ELFT> 546 std::vector<const typename ELFT::Verdef *> 547 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 548 std::vector<const Elf_Verdef *> Verdefs(1); 549 // We only need to process symbol versions for this DSO if it has both a 550 // versym and a verdef section, which indicates that the DSO contains symbol 551 // version definitions. 552 if (!VersymSec || !VerdefSec) 553 return Verdefs; 554 555 // The location of the first global versym entry. 556 Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() + 557 VersymSec->sh_offset) + 558 this->Symtab->sh_info; 559 560 // We cannot determine the largest verdef identifier without inspecting 561 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 562 // sequentially starting from 1, so we predict that the largest identifier 563 // will be VerdefCount. 564 unsigned VerdefCount = VerdefSec->sh_info; 565 Verdefs.resize(VerdefCount + 1); 566 567 // Build the Verdefs array by following the chain of Elf_Verdef objects 568 // from the start of the .gnu.version_d section. 569 const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset; 570 for (unsigned I = 0; I != VerdefCount; ++I) { 571 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 572 Verdef += CurVerdef->vd_next; 573 unsigned VerdefIndex = CurVerdef->vd_ndx; 574 if (Verdefs.size() <= VerdefIndex) 575 Verdefs.resize(VerdefIndex + 1); 576 Verdefs[VerdefIndex] = CurVerdef; 577 } 578 579 return Verdefs; 580 } 581 582 // Fully parse the shared object file. This must be called after parseSoName(). 583 template <class ELFT> void SharedFile<ELFT>::parseRest() { 584 // Create mapping from version identifiers to Elf_Verdef entries. 585 const Elf_Versym *Versym = nullptr; 586 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 587 588 Elf_Sym_Range Syms = this->getElfSymbols(true); 589 for (const Elf_Sym &Sym : Syms) { 590 unsigned VersymIndex = 0; 591 if (Versym) { 592 VersymIndex = Versym->vs_index; 593 ++Versym; 594 } 595 596 StringRef Name = check(Sym.getName(this->StringTable)); 597 if (Sym.isUndefined()) { 598 Undefs.push_back(Name); 599 continue; 600 } 601 602 if (Versym) { 603 // Ignore local symbols and non-default versions. 604 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN)) 605 continue; 606 } 607 608 const Elf_Verdef *V = 609 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex]; 610 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 611 } 612 } 613 614 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) { 615 Triple T(getBitcodeTargetTriple(MB, Driver->Context)); 616 if (T.isLittleEndian()) 617 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 618 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 619 } 620 621 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) { 622 Triple T(getBitcodeTargetTriple(MB, Driver->Context)); 623 switch (T.getArch()) { 624 case Triple::aarch64: 625 return EM_AARCH64; 626 case Triple::arm: 627 return EM_ARM; 628 case Triple::mips: 629 case Triple::mipsel: 630 case Triple::mips64: 631 case Triple::mips64el: 632 return EM_MIPS; 633 case Triple::ppc: 634 return EM_PPC; 635 case Triple::ppc64: 636 return EM_PPC64; 637 case Triple::x86: 638 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 639 case Triple::x86_64: 640 return EM_X86_64; 641 default: 642 fatal(MB.getBufferIdentifier() + 643 ": could not infer e_machine from bitcode target triple " + T.str()); 644 } 645 } 646 647 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) { 648 EKind = getBitcodeELFKind(MB); 649 EMachine = getBitcodeMachineKind(MB); 650 } 651 652 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 653 switch (GvVisibility) { 654 case GlobalValue::DefaultVisibility: 655 return STV_DEFAULT; 656 case GlobalValue::HiddenVisibility: 657 return STV_HIDDEN; 658 case GlobalValue::ProtectedVisibility: 659 return STV_PROTECTED; 660 } 661 llvm_unreachable("unknown visibility"); 662 } 663 664 template <class ELFT> 665 static Symbol *createBitcodeSymbol(const DenseSet<const Comdat *> &KeptComdats, 666 const lto::InputFile::Symbol &ObjSym, 667 StringSaver &Saver, BitcodeFile *F) { 668 StringRef NameRef = Saver.save(ObjSym.getName()); 669 uint32_t Flags = ObjSym.getFlags(); 670 uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL; 671 672 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 673 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 674 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 675 676 if (const Comdat *C = check(ObjSym.getComdat())) 677 if (!KeptComdats.count(C)) 678 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type, 679 CanOmitFromDynSym, F); 680 681 if (Flags & BasicSymbolRef::SF_Undefined) 682 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type, 683 CanOmitFromDynSym, F); 684 685 if (Flags & BasicSymbolRef::SF_Common) 686 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(), 687 ObjSym.getCommonAlignment(), Binding, 688 Visibility, STT_OBJECT, F); 689 690 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type, 691 CanOmitFromDynSym, F); 692 } 693 694 template <class ELFT> 695 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) { 696 Obj = check(lto::InputFile::create(MB)); 697 DenseSet<const Comdat *> KeptComdats; 698 for (const auto &P : Obj->getComdatSymbolTable()) { 699 StringRef N = Saver.save(P.first()); 700 if (ComdatGroups.insert(N).second) 701 KeptComdats.insert(&P.second); 702 } 703 704 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 705 Symbols.push_back( 706 createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, Saver, this)); 707 } 708 709 template <template <class> class T> 710 static InputFile *createELFFile(MemoryBufferRef MB) { 711 unsigned char Size; 712 unsigned char Endian; 713 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 714 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 715 fatal("invalid data encoding: " + MB.getBufferIdentifier()); 716 717 InputFile *Obj; 718 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB) 719 Obj = new T<ELF32LE>(MB); 720 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB) 721 Obj = new T<ELF32BE>(MB); 722 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB) 723 Obj = new T<ELF64LE>(MB); 724 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB) 725 Obj = new T<ELF64BE>(MB); 726 else 727 fatal("invalid file class: " + MB.getBufferIdentifier()); 728 729 if (!Config->FirstElf) 730 Config->FirstElf = Obj; 731 return Obj; 732 } 733 734 // Wraps a binary blob with an ELF header and footer 735 // so that we can link it as a regular ELF file. 736 template <class ELFT> InputFile *BinaryFile::createELF() { 737 // Fill the ELF file header. 738 ELFCreator<ELFT> ELF(ET_REL, Config->EMachine); 739 auto DataSec = ELF.addSection(".data"); 740 DataSec.Header->sh_flags = SHF_ALLOC; 741 DataSec.Header->sh_size = MB.getBufferSize(); 742 DataSec.Header->sh_type = SHT_PROGBITS; 743 DataSec.Header->sh_addralign = 8; 744 745 // Replace non-alphanumeric characters with '_'. 746 std::string Filepath = MB.getBufferIdentifier(); 747 std::transform(Filepath.begin(), Filepath.end(), Filepath.begin(), 748 [](char C) { return isalnum(C) ? C : '_'; }); 749 750 // Add _start, _end and _size symbols. 751 std::string StartSym = "_binary_" + Filepath + "_start"; 752 auto SSym = ELF.addSymbol(StartSym); 753 SSym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT); 754 SSym.Sym->st_shndx = DataSec.Index; 755 756 std::string EndSym = "_binary_" + Filepath + "_end"; 757 auto ESym = ELF.addSymbol(EndSym); 758 ESym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT); 759 ESym.Sym->st_shndx = DataSec.Index; 760 ESym.Sym->st_value = MB.getBufferSize(); 761 762 std::string SizeSym = "_binary_" + Filepath + "_size"; 763 auto SZSym = ELF.addSymbol(SizeSym); 764 SZSym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT); 765 SZSym.Sym->st_shndx = SHN_ABS; 766 SZSym.Sym->st_value = MB.getBufferSize(); 767 768 // Fix the ELF file layout and write it down to ELFData uint8_t vector. 769 std::size_t Size = ELF.layout(); 770 ELFData.resize(Size); 771 ELF.write(ELFData.data()); 772 773 // Fill .data section with actual data. 774 std::copy(MB.getBufferStart(), MB.getBufferEnd(), 775 ELFData.data() + DataSec.Header->sh_offset); 776 777 return createELFFile<ObjectFile>(MemoryBufferRef( 778 StringRef((char *)ELFData.data(), Size), MB.getBufferIdentifier())); 779 } 780 781 static bool isBitcode(MemoryBufferRef MB) { 782 using namespace sys::fs; 783 return identify_magic(MB.getBuffer()) == file_magic::bitcode; 784 } 785 786 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName) { 787 InputFile *F = 788 isBitcode(MB) ? new BitcodeFile(MB) : createELFFile<ObjectFile>(MB); 789 F->ArchiveName = ArchiveName; 790 return F; 791 } 792 793 InputFile *elf::createSharedFile(MemoryBufferRef MB) { 794 return createELFFile<SharedFile>(MB); 795 } 796 797 MemoryBufferRef LazyObjectFile::getBuffer() { 798 if (Seen) 799 return MemoryBufferRef(); 800 Seen = true; 801 return MB; 802 } 803 804 template <class ELFT> void LazyObjectFile::parse() { 805 for (StringRef Sym : getSymbols()) 806 Symtab<ELFT>::X->addLazyObject(Sym, *this); 807 } 808 809 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() { 810 typedef typename ELFT::Shdr Elf_Shdr; 811 typedef typename ELFT::Sym Elf_Sym; 812 typedef typename ELFT::SymRange Elf_Sym_Range; 813 814 const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB); 815 for (const Elf_Shdr &Sec : Obj.sections()) { 816 if (Sec.sh_type != SHT_SYMTAB) 817 continue; 818 Elf_Sym_Range Syms = Obj.symbols(&Sec); 819 uint32_t FirstNonLocal = Sec.sh_info; 820 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec)); 821 std::vector<StringRef> V; 822 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal)) 823 if (Sym.st_shndx != SHN_UNDEF) 824 V.push_back(check(Sym.getName(StringTable))); 825 return V; 826 } 827 return {}; 828 } 829 830 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() { 831 std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB)); 832 std::vector<StringRef> V; 833 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 834 if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined)) 835 V.push_back(Saver.save(Sym.getName())); 836 return V; 837 } 838 839 // Returns a vector of globally-visible defined symbol names. 840 std::vector<StringRef> LazyObjectFile::getSymbols() { 841 if (isBitcode(this->MB)) 842 return getBitcodeSymbols(); 843 844 unsigned char Size; 845 unsigned char Endian; 846 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer()); 847 if (Size == ELFCLASS32) { 848 if (Endian == ELFDATA2LSB) 849 return getElfSymbols<ELF32LE>(); 850 return getElfSymbols<ELF32BE>(); 851 } 852 if (Endian == ELFDATA2LSB) 853 return getElfSymbols<ELF64LE>(); 854 return getElfSymbols<ELF64BE>(); 855 } 856 857 template void ArchiveFile::parse<ELF32LE>(); 858 template void ArchiveFile::parse<ELF32BE>(); 859 template void ArchiveFile::parse<ELF64LE>(); 860 template void ArchiveFile::parse<ELF64BE>(); 861 862 template void BitcodeFile::parse<ELF32LE>(DenseSet<StringRef> &); 863 template void BitcodeFile::parse<ELF32BE>(DenseSet<StringRef> &); 864 template void BitcodeFile::parse<ELF64LE>(DenseSet<StringRef> &); 865 template void BitcodeFile::parse<ELF64BE>(DenseSet<StringRef> &); 866 867 template void LazyObjectFile::parse<ELF32LE>(); 868 template void LazyObjectFile::parse<ELF32BE>(); 869 template void LazyObjectFile::parse<ELF64LE>(); 870 template void LazyObjectFile::parse<ELF64BE>(); 871 872 template class elf::ELFFileBase<ELF32LE>; 873 template class elf::ELFFileBase<ELF32BE>; 874 template class elf::ELFFileBase<ELF64LE>; 875 template class elf::ELFFileBase<ELF64BE>; 876 877 template class elf::ObjectFile<ELF32LE>; 878 template class elf::ObjectFile<ELF32BE>; 879 template class elf::ObjectFile<ELF64LE>; 880 template class elf::ObjectFile<ELF64BE>; 881 882 template class elf::SharedFile<ELF32LE>; 883 template class elf::SharedFile<ELF32BE>; 884 template class elf::SharedFile<ELF64LE>; 885 template class elf::SharedFile<ELF64BE>; 886 887 template InputFile *BinaryFile::createELF<ELF32LE>(); 888 template InputFile *BinaryFile::createELF<ELF32BE>(); 889 template InputFile *BinaryFile::createELF<ELF64LE>(); 890 template InputFile *BinaryFile::createELF<ELF64BE>(); 891