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