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