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