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