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 403 // Relocation sections processed by the linker are usually removed 404 // from the output, so returning `nullptr` for the normal case. 405 // However, if -emit-relocs is given, we need to leave them in the output. 406 // (Some post link analysis tools need this information.) 407 if (Config->EmitRelocs) 408 return make<InputSection<ELFT>>(this, &Sec, Name); 409 return nullptr; 410 } 411 } 412 413 // .note.GNU-stack is a marker section to control the presence of 414 // PT_GNU_STACK segment in outputs. Since the presence of the segment 415 // is controlled only by the command line option (-z execstack) in LLD, 416 // .note.GNU-stack is ignored. 417 if (Name == ".note.GNU-stack") 418 return &InputSection<ELFT>::Discarded; 419 420 if (Name == ".note.GNU-split-stack") { 421 error("objects using splitstacks are not supported"); 422 return &InputSection<ELFT>::Discarded; 423 } 424 425 if (Config->Strip != StripPolicy::None && Name.startswith(".debug")) 426 return &InputSection<ELFT>::Discarded; 427 428 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 429 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 430 // sections. Drop those sections to avoid duplicate symbol errors. 431 // FIXME: This is glibc PR20543, we should remove this hack once that has been 432 // fixed for a while. 433 if (Name.startswith(".gnu.linkonce.")) 434 return &InputSection<ELFT>::Discarded; 435 436 // The linker merges EH (exception handling) frames and creates a 437 // .eh_frame_hdr section for runtime. So we handle them with a special 438 // class. For relocatable outputs, they are just passed through. 439 if (Name == ".eh_frame" && !Config->Relocatable) 440 return make<EhInputSection<ELFT>>(this, &Sec, Name); 441 442 if (shouldMerge(Sec)) 443 return make<MergeInputSection<ELFT>>(this, &Sec, Name); 444 return make<InputSection<ELFT>>(this, &Sec, Name); 445 } 446 447 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() { 448 SymbolBodies.reserve(this->Symbols.size()); 449 for (const Elf_Sym &Sym : this->Symbols) 450 SymbolBodies.push_back(createSymbolBody(&Sym)); 451 } 452 453 template <class ELFT> 454 InputSectionBase<ELFT> * 455 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const { 456 uint32_t Index = this->getSectionIndex(Sym); 457 if (Index >= Sections.size()) 458 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 459 InputSectionBase<ELFT> *S = Sections[Index]; 460 461 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could 462 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be 463 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections. 464 // In this case it is fine for section to be null here as we do not 465 // allocate sections of these types. 466 if (!S) { 467 if (Index == 0 || Sym.getType() == STT_SECTION || 468 Sym.getType() == STT_NOTYPE) 469 return nullptr; 470 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 471 } 472 473 if (S == &InputSection<ELFT>::Discarded) 474 return S; 475 return S->Repl; 476 } 477 478 template <class ELFT> 479 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) { 480 int Binding = Sym->getBinding(); 481 InputSectionBase<ELFT> *Sec = getSection(*Sym); 482 483 uint8_t StOther = Sym->st_other; 484 uint8_t Type = Sym->getType(); 485 uintX_t Value = Sym->st_value; 486 uintX_t Size = Sym->st_size; 487 488 if (Binding == STB_LOCAL) { 489 if (Sym->getType() == STT_FILE) 490 SourceFile = check(Sym->getName(this->StringTable)); 491 492 if (this->StringTable.size() <= Sym->st_name) 493 fatal(toString(this) + ": invalid symbol name offset"); 494 495 StringRefZ Name = this->StringTable.data() + Sym->st_name; 496 if (Sym->st_shndx == SHN_UNDEF) 497 return new (BAlloc) 498 Undefined(Name, /*IsLocal=*/true, StOther, Type, this); 499 500 return new (BAlloc) DefinedRegular<ELFT>(Name, /*IsLocal=*/true, StOther, 501 Type, Value, Size, Sec, this); 502 } 503 504 StringRef Name = check(Sym->getName(this->StringTable)); 505 506 switch (Sym->st_shndx) { 507 case SHN_UNDEF: 508 return elf::Symtab<ELFT>::X 509 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type, 510 /*CanOmitFromDynSym=*/false, this) 511 ->body(); 512 case SHN_COMMON: 513 if (Value == 0 || Value >= UINT32_MAX) 514 fatal(toString(this) + ": common symbol '" + Name + 515 "' has invalid alignment: " + Twine(Value)); 516 return elf::Symtab<ELFT>::X 517 ->addCommon(Name, Size, Value, Binding, StOther, Type, this) 518 ->body(); 519 } 520 521 switch (Binding) { 522 default: 523 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 524 case STB_GLOBAL: 525 case STB_WEAK: 526 case STB_GNU_UNIQUE: 527 if (Sec == &InputSection<ELFT>::Discarded) 528 return elf::Symtab<ELFT>::X 529 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type, 530 /*CanOmitFromDynSym=*/false, this) 531 ->body(); 532 return elf::Symtab<ELFT>::X 533 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this) 534 ->body(); 535 } 536 } 537 538 template <class ELFT> void ArchiveFile::parse() { 539 File = check(Archive::create(MB), 540 MB.getBufferIdentifier() + ": failed to parse archive"); 541 542 // Read the symbol table to construct Lazy objects. 543 for (const Archive::Symbol &Sym : File->symbols()) 544 Symtab<ELFT>::X->addLazyArchive(this, Sym); 545 } 546 547 // Returns a buffer pointing to a member file containing a given symbol. 548 std::pair<MemoryBufferRef, uint64_t> 549 ArchiveFile::getMember(const Archive::Symbol *Sym) { 550 Archive::Child C = 551 check(Sym->getMember(), 552 "could not get the member for symbol " + Sym->getName()); 553 554 if (!Seen.insert(C.getChildOffset()).second) 555 return {MemoryBufferRef(), 0}; 556 557 MemoryBufferRef Ret = 558 check(C.getMemoryBufferRef(), 559 "could not get the buffer for the member defining symbol " + 560 Sym->getName()); 561 562 if (C.getParent()->isThin() && Tar) 563 Tar->append(relativeToRoot(check(C.getFullName())), Ret.getBuffer()); 564 if (C.getParent()->isThin()) 565 return {Ret, 0}; 566 return {Ret, C.getChildOffset()}; 567 } 568 569 template <class ELFT> 570 SharedFile<ELFT>::SharedFile(MemoryBufferRef M) 571 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {} 572 573 template <class ELFT> 574 const typename ELFT::Shdr * 575 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const { 576 return check( 577 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX)); 578 } 579 580 // Partially parse the shared object file so that we can call 581 // getSoName on this object. 582 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 583 const Elf_Shdr *DynamicSec = nullptr; 584 585 const ELFFile<ELFT> Obj = this->getObj(); 586 ArrayRef<Elf_Shdr> Sections = check(Obj.sections()); 587 for (const Elf_Shdr &Sec : Sections) { 588 switch (Sec.sh_type) { 589 default: 590 continue; 591 case SHT_DYNSYM: 592 this->initSymtab(Sections, &Sec); 593 break; 594 case SHT_DYNAMIC: 595 DynamicSec = &Sec; 596 break; 597 case SHT_SYMTAB_SHNDX: 598 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections)); 599 break; 600 case SHT_GNU_versym: 601 this->VersymSec = &Sec; 602 break; 603 case SHT_GNU_verdef: 604 this->VerdefSec = &Sec; 605 break; 606 } 607 } 608 609 if (this->VersymSec && this->Symbols.empty()) 610 error("SHT_GNU_versym should be associated with symbol table"); 611 612 // DSOs are identified by soname, and they usually contain 613 // DT_SONAME tag in their header. But if they are missing, 614 // filenames are used as default sonames. 615 SoName = sys::path::filename(this->getName()); 616 617 if (!DynamicSec) 618 return; 619 620 ArrayRef<Elf_Dyn> Arr = 621 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 622 toString(this) + ": getSectionContentsAsArray failed"); 623 for (const Elf_Dyn &Dyn : Arr) { 624 if (Dyn.d_tag == DT_SONAME) { 625 uintX_t Val = Dyn.getVal(); 626 if (Val >= this->StringTable.size()) 627 fatal(toString(this) + ": invalid DT_SONAME entry"); 628 SoName = StringRef(this->StringTable.data() + Val); 629 return; 630 } 631 } 632 } 633 634 // Parse the version definitions in the object file if present. Returns a vector 635 // whose nth element contains a pointer to the Elf_Verdef for version identifier 636 // n. Version identifiers that are not definitions map to nullptr. The array 637 // always has at least length 1. 638 template <class ELFT> 639 std::vector<const typename ELFT::Verdef *> 640 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 641 std::vector<const Elf_Verdef *> Verdefs(1); 642 // We only need to process symbol versions for this DSO if it has both a 643 // versym and a verdef section, which indicates that the DSO contains symbol 644 // version definitions. 645 if (!VersymSec || !VerdefSec) 646 return Verdefs; 647 648 // The location of the first global versym entry. 649 const char *Base = this->MB.getBuffer().data(); 650 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 651 this->FirstNonLocal; 652 653 // We cannot determine the largest verdef identifier without inspecting 654 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 655 // sequentially starting from 1, so we predict that the largest identifier 656 // will be VerdefCount. 657 unsigned VerdefCount = VerdefSec->sh_info; 658 Verdefs.resize(VerdefCount + 1); 659 660 // Build the Verdefs array by following the chain of Elf_Verdef objects 661 // from the start of the .gnu.version_d section. 662 const char *Verdef = Base + VerdefSec->sh_offset; 663 for (unsigned I = 0; I != VerdefCount; ++I) { 664 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 665 Verdef += CurVerdef->vd_next; 666 unsigned VerdefIndex = CurVerdef->vd_ndx; 667 if (Verdefs.size() <= VerdefIndex) 668 Verdefs.resize(VerdefIndex + 1); 669 Verdefs[VerdefIndex] = CurVerdef; 670 } 671 672 return Verdefs; 673 } 674 675 // Fully parse the shared object file. This must be called after parseSoName(). 676 template <class ELFT> void SharedFile<ELFT>::parseRest() { 677 // Create mapping from version identifiers to Elf_Verdef entries. 678 const Elf_Versym *Versym = nullptr; 679 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 680 681 Elf_Sym_Range Syms = this->getGlobalSymbols(); 682 for (const Elf_Sym &Sym : Syms) { 683 unsigned VersymIndex = 0; 684 if (Versym) { 685 VersymIndex = Versym->vs_index; 686 ++Versym; 687 } 688 bool Hidden = VersymIndex & VERSYM_HIDDEN; 689 VersymIndex = VersymIndex & ~VERSYM_HIDDEN; 690 691 StringRef Name = check(Sym.getName(this->StringTable)); 692 if (Sym.isUndefined()) { 693 Undefs.push_back(Name); 694 continue; 695 } 696 697 // Ignore local symbols. 698 if (Versym && VersymIndex == VER_NDX_LOCAL) 699 continue; 700 701 const Elf_Verdef *V = 702 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex]; 703 704 if (!Hidden) 705 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 706 707 // Also add the symbol with the versioned name to handle undefined symbols 708 // with explicit versions. 709 if (V) { 710 StringRef VerName = this->StringTable.data() + V->getAux()->vda_name; 711 Name = Saver.save(Twine(Name) + "@" + VerName); 712 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 713 } 714 } 715 } 716 717 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) { 718 Triple T(check(getBitcodeTargetTriple(MB))); 719 if (T.isLittleEndian()) 720 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 721 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 722 } 723 724 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) { 725 Triple T(check(getBitcodeTargetTriple(MB))); 726 switch (T.getArch()) { 727 case Triple::aarch64: 728 return EM_AARCH64; 729 case Triple::arm: 730 return EM_ARM; 731 case Triple::mips: 732 case Triple::mipsel: 733 case Triple::mips64: 734 case Triple::mips64el: 735 return EM_MIPS; 736 case Triple::ppc: 737 return EM_PPC; 738 case Triple::ppc64: 739 return EM_PPC64; 740 case Triple::x86: 741 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 742 case Triple::x86_64: 743 return EM_X86_64; 744 default: 745 fatal(MB.getBufferIdentifier() + 746 ": could not infer e_machine from bitcode target triple " + T.str()); 747 } 748 } 749 750 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) { 751 EKind = getBitcodeELFKind(MB); 752 EMachine = getBitcodeMachineKind(MB); 753 } 754 755 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 756 switch (GvVisibility) { 757 case GlobalValue::DefaultVisibility: 758 return STV_DEFAULT; 759 case GlobalValue::HiddenVisibility: 760 return STV_HIDDEN; 761 case GlobalValue::ProtectedVisibility: 762 return STV_PROTECTED; 763 } 764 llvm_unreachable("unknown visibility"); 765 } 766 767 template <class ELFT> 768 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 769 const lto::InputFile::Symbol &ObjSym, 770 BitcodeFile *F) { 771 StringRef NameRef = Saver.save(ObjSym.getName()); 772 uint32_t Flags = ObjSym.getFlags(); 773 uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL; 774 775 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 776 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 777 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 778 779 int C = check(ObjSym.getComdatIndex()); 780 if (C != -1 && !KeptComdats[C]) 781 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding, 782 Visibility, Type, CanOmitFromDynSym, 783 F); 784 785 if (Flags & BasicSymbolRef::SF_Undefined) 786 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding, 787 Visibility, Type, CanOmitFromDynSym, 788 F); 789 790 if (Flags & BasicSymbolRef::SF_Common) 791 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(), 792 ObjSym.getCommonAlignment(), Binding, 793 Visibility, STT_OBJECT, F); 794 795 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type, 796 CanOmitFromDynSym, F); 797 } 798 799 template <class ELFT> 800 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 801 802 // Here we pass a new MemoryBufferRef which is identified by ArchiveName 803 // (the fully resolved path of the archive) + member name + offset of the 804 // member in the archive. 805 // ThinLTO uses the MemoryBufferRef identifier to access its internal 806 // data structures and if two archives define two members with the same name, 807 // this causes a collision which result in only one of the objects being 808 // taken into consideration at LTO time (which very likely causes undefined 809 // symbols later in the link stage). 810 Obj = check(lto::InputFile::create(MemoryBufferRef( 811 MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() + 812 utostr(OffsetInArchive))))); 813 814 std::vector<bool> KeptComdats; 815 for (StringRef S : Obj->getComdatTable()) { 816 StringRef N = Saver.save(S); 817 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second); 818 } 819 820 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 821 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)); 822 } 823 824 template <template <class> class T> 825 static InputFile *createELFFile(MemoryBufferRef MB) { 826 unsigned char Size; 827 unsigned char Endian; 828 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 829 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 830 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 831 832 size_t BufSize = MB.getBuffer().size(); 833 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 834 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 835 fatal(MB.getBufferIdentifier() + ": file is too short"); 836 837 InputFile *Obj; 838 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB) 839 Obj = make<T<ELF32LE>>(MB); 840 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB) 841 Obj = make<T<ELF32BE>>(MB); 842 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB) 843 Obj = make<T<ELF64LE>>(MB); 844 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB) 845 Obj = make<T<ELF64BE>>(MB); 846 else 847 fatal(MB.getBufferIdentifier() + ": invalid file class"); 848 849 if (!Config->FirstElf) 850 Config->FirstElf = Obj; 851 return Obj; 852 } 853 854 template <class ELFT> void BinaryFile::parse() { 855 StringRef Buf = MB.getBuffer(); 856 ArrayRef<uint8_t> Data = 857 makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size()); 858 859 std::string Filename = MB.getBufferIdentifier(); 860 std::transform(Filename.begin(), Filename.end(), Filename.begin(), 861 [](char C) { return isalnum(C) ? C : '_'; }); 862 Filename = "_binary_" + Filename; 863 StringRef StartName = Saver.save(Twine(Filename) + "_start"); 864 StringRef EndName = Saver.save(Twine(Filename) + "_end"); 865 StringRef SizeName = Saver.save(Twine(Filename) + "_size"); 866 867 auto *Section = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 868 8, Data, ".data"); 869 Sections.push_back(Section); 870 871 elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0, 872 STB_GLOBAL, Section, nullptr); 873 elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT, 874 Data.size(), 0, STB_GLOBAL, Section, 875 nullptr); 876 elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT, 877 Data.size(), 0, STB_GLOBAL, nullptr, 878 nullptr); 879 } 880 881 static bool isBitcode(MemoryBufferRef MB) { 882 using namespace sys::fs; 883 return identify_magic(MB.getBuffer()) == file_magic::bitcode; 884 } 885 886 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 887 uint64_t OffsetInArchive) { 888 InputFile *F = 889 isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB); 890 F->ArchiveName = ArchiveName; 891 F->OffsetInArchive = OffsetInArchive; 892 return F; 893 } 894 895 InputFile *elf::createSharedFile(MemoryBufferRef MB) { 896 return createELFFile<SharedFile>(MB); 897 } 898 899 MemoryBufferRef LazyObjectFile::getBuffer() { 900 if (Seen) 901 return MemoryBufferRef(); 902 Seen = true; 903 return MB; 904 } 905 906 template <class ELFT> void LazyObjectFile::parse() { 907 for (StringRef Sym : getSymbols()) 908 Symtab<ELFT>::X->addLazyObject(Sym, *this); 909 } 910 911 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() { 912 typedef typename ELFT::Shdr Elf_Shdr; 913 typedef typename ELFT::Sym Elf_Sym; 914 typedef typename ELFT::SymRange Elf_Sym_Range; 915 916 const ELFFile<ELFT> Obj(this->MB.getBuffer()); 917 ArrayRef<Elf_Shdr> Sections = check(Obj.sections()); 918 for (const Elf_Shdr &Sec : Sections) { 919 if (Sec.sh_type != SHT_SYMTAB) 920 continue; 921 Elf_Sym_Range Syms = check(Obj.symbols(&Sec)); 922 uint32_t FirstNonLocal = Sec.sh_info; 923 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections)); 924 std::vector<StringRef> V; 925 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal)) 926 if (Sym.st_shndx != SHN_UNDEF) 927 V.push_back(check(Sym.getName(StringTable))); 928 return V; 929 } 930 return {}; 931 } 932 933 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() { 934 std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB)); 935 std::vector<StringRef> V; 936 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 937 if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined)) 938 V.push_back(Saver.save(Sym.getName())); 939 return V; 940 } 941 942 // Returns a vector of globally-visible defined symbol names. 943 std::vector<StringRef> LazyObjectFile::getSymbols() { 944 if (isBitcode(this->MB)) 945 return getBitcodeSymbols(); 946 947 unsigned char Size; 948 unsigned char Endian; 949 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer()); 950 if (Size == ELFCLASS32) { 951 if (Endian == ELFDATA2LSB) 952 return getElfSymbols<ELF32LE>(); 953 return getElfSymbols<ELF32BE>(); 954 } 955 if (Endian == ELFDATA2LSB) 956 return getElfSymbols<ELF64LE>(); 957 return getElfSymbols<ELF64BE>(); 958 } 959 960 template void ArchiveFile::parse<ELF32LE>(); 961 template void ArchiveFile::parse<ELF32BE>(); 962 template void ArchiveFile::parse<ELF64LE>(); 963 template void ArchiveFile::parse<ELF64BE>(); 964 965 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 966 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 967 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 968 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 969 970 template void LazyObjectFile::parse<ELF32LE>(); 971 template void LazyObjectFile::parse<ELF32BE>(); 972 template void LazyObjectFile::parse<ELF64LE>(); 973 template void LazyObjectFile::parse<ELF64BE>(); 974 975 template class elf::ELFFileBase<ELF32LE>; 976 template class elf::ELFFileBase<ELF32BE>; 977 template class elf::ELFFileBase<ELF64LE>; 978 template class elf::ELFFileBase<ELF64BE>; 979 980 template class elf::ObjectFile<ELF32LE>; 981 template class elf::ObjectFile<ELF32BE>; 982 template class elf::ObjectFile<ELF64LE>; 983 template class elf::ObjectFile<ELF64BE>; 984 985 template class elf::SharedFile<ELF32LE>; 986 template class elf::SharedFile<ELF32BE>; 987 template class elf::SharedFile<ELF64LE>; 988 template class elf::SharedFile<ELF64BE>; 989 990 template void BinaryFile::parse<ELF32LE>(); 991 template void BinaryFile::parse<ELF32BE>(); 992 template void BinaryFile::parse<ELF64LE>(); 993 template void BinaryFile::parse<ELF64BE>(); 994