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