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