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