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