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 const Elf_Shdr *DynamicSec = nullptr; 539 540 const ELFFile<ELFT> Obj = this->getObj(); 541 ArrayRef<Elf_Shdr> Sections = check(Obj.sections()); 542 for (const Elf_Shdr &Sec : Sections) { 543 switch (Sec.sh_type) { 544 default: 545 continue; 546 case SHT_DYNSYM: 547 this->initSymtab(Sections, &Sec); 548 break; 549 case SHT_DYNAMIC: 550 DynamicSec = &Sec; 551 break; 552 case SHT_SYMTAB_SHNDX: 553 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections)); 554 break; 555 case SHT_GNU_versym: 556 this->VersymSec = &Sec; 557 break; 558 case SHT_GNU_verdef: 559 this->VerdefSec = &Sec; 560 break; 561 } 562 } 563 564 if (this->VersymSec && this->Symbols.empty()) 565 error("SHT_GNU_versym should be associated with symbol table"); 566 567 // DSOs are identified by soname, and they usually contain 568 // DT_SONAME tag in their header. But if they are missing, 569 // filenames are used as default sonames. 570 SoName = sys::path::filename(this->getName()); 571 572 if (!DynamicSec) 573 return; 574 575 ArrayRef<Elf_Dyn> Arr = 576 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 577 toString(this) + ": getSectionContentsAsArray failed"); 578 for (const Elf_Dyn &Dyn : Arr) { 579 if (Dyn.d_tag == DT_SONAME) { 580 uintX_t Val = Dyn.getVal(); 581 if (Val >= this->StringTable.size()) 582 fatal(toString(this) + ": invalid DT_SONAME entry"); 583 SoName = StringRef(this->StringTable.data() + Val); 584 return; 585 } 586 } 587 } 588 589 // Parse the version definitions in the object file if present. Returns a vector 590 // whose nth element contains a pointer to the Elf_Verdef for version identifier 591 // n. Version identifiers that are not definitions map to nullptr. The array 592 // always has at least length 1. 593 template <class ELFT> 594 std::vector<const typename ELFT::Verdef *> 595 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 596 std::vector<const Elf_Verdef *> Verdefs(1); 597 // We only need to process symbol versions for this DSO if it has both a 598 // versym and a verdef section, which indicates that the DSO contains symbol 599 // version definitions. 600 if (!VersymSec || !VerdefSec) 601 return Verdefs; 602 603 // The location of the first global versym entry. 604 const char *Base = this->MB.getBuffer().data(); 605 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 606 this->FirstNonLocal; 607 608 // We cannot determine the largest verdef identifier without inspecting 609 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 610 // sequentially starting from 1, so we predict that the largest identifier 611 // will be VerdefCount. 612 unsigned VerdefCount = VerdefSec->sh_info; 613 Verdefs.resize(VerdefCount + 1); 614 615 // Build the Verdefs array by following the chain of Elf_Verdef objects 616 // from the start of the .gnu.version_d section. 617 const char *Verdef = Base + VerdefSec->sh_offset; 618 for (unsigned I = 0; I != VerdefCount; ++I) { 619 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 620 Verdef += CurVerdef->vd_next; 621 unsigned VerdefIndex = CurVerdef->vd_ndx; 622 if (Verdefs.size() <= VerdefIndex) 623 Verdefs.resize(VerdefIndex + 1); 624 Verdefs[VerdefIndex] = CurVerdef; 625 } 626 627 return Verdefs; 628 } 629 630 // Fully parse the shared object file. This must be called after parseSoName(). 631 template <class ELFT> void SharedFile<ELFT>::parseRest() { 632 // Create mapping from version identifiers to Elf_Verdef entries. 633 const Elf_Versym *Versym = nullptr; 634 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 635 636 Elf_Sym_Range Syms = this->getGlobalSymbols(); 637 for (const Elf_Sym &Sym : Syms) { 638 unsigned VersymIndex = 0; 639 if (Versym) { 640 VersymIndex = Versym->vs_index; 641 ++Versym; 642 } 643 644 StringRef Name = check(Sym.getName(this->StringTable)); 645 if (Sym.isUndefined()) { 646 Undefs.push_back(Name); 647 continue; 648 } 649 650 if (Versym) { 651 // Ignore local symbols and non-default versions. 652 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN)) 653 continue; 654 } 655 656 const Elf_Verdef *V = 657 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex]; 658 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 659 } 660 } 661 662 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) { 663 Triple T(check(getBitcodeTargetTriple(MB))); 664 if (T.isLittleEndian()) 665 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 666 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 667 } 668 669 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) { 670 Triple T(check(getBitcodeTargetTriple(MB))); 671 switch (T.getArch()) { 672 case Triple::aarch64: 673 return EM_AARCH64; 674 case Triple::arm: 675 return EM_ARM; 676 case Triple::mips: 677 case Triple::mipsel: 678 case Triple::mips64: 679 case Triple::mips64el: 680 return EM_MIPS; 681 case Triple::ppc: 682 return EM_PPC; 683 case Triple::ppc64: 684 return EM_PPC64; 685 case Triple::x86: 686 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 687 case Triple::x86_64: 688 return EM_X86_64; 689 default: 690 fatal(MB.getBufferIdentifier() + 691 ": could not infer e_machine from bitcode target triple " + T.str()); 692 } 693 } 694 695 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) { 696 EKind = getBitcodeELFKind(MB); 697 EMachine = getBitcodeMachineKind(MB); 698 } 699 700 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 701 switch (GvVisibility) { 702 case GlobalValue::DefaultVisibility: 703 return STV_DEFAULT; 704 case GlobalValue::HiddenVisibility: 705 return STV_HIDDEN; 706 case GlobalValue::ProtectedVisibility: 707 return STV_PROTECTED; 708 } 709 llvm_unreachable("unknown visibility"); 710 } 711 712 template <class ELFT> 713 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 714 const lto::InputFile::Symbol &ObjSym, 715 BitcodeFile *F) { 716 StringRef NameRef = Saver.save(ObjSym.getName()); 717 uint32_t Flags = ObjSym.getFlags(); 718 uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL; 719 720 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 721 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 722 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 723 724 int C = check(ObjSym.getComdatIndex()); 725 if (C != -1 && !KeptComdats[C]) 726 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type, 727 CanOmitFromDynSym, F); 728 729 if (Flags & BasicSymbolRef::SF_Undefined) 730 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type, 731 CanOmitFromDynSym, F); 732 733 if (Flags & BasicSymbolRef::SF_Common) 734 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(), 735 ObjSym.getCommonAlignment(), Binding, 736 Visibility, STT_OBJECT, F); 737 738 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type, 739 CanOmitFromDynSym, F); 740 } 741 742 template <class ELFT> 743 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 744 745 // Here we pass a new MemoryBufferRef which is identified by ArchiveName 746 // (the fully resolved path of the archive) + member name + offset of the 747 // member in the archive. 748 // ThinLTO uses the MemoryBufferRef identifier to access its internal 749 // data structures and if two archives define two members with the same name, 750 // this causes a collision which result in only one of the objects being 751 // taken into consideration at LTO time (which very likely causes undefined 752 // symbols later in the link stage). 753 Obj = check(lto::InputFile::create(MemoryBufferRef( 754 MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() + 755 utostr(OffsetInArchive))))); 756 757 std::vector<bool> KeptComdats; 758 for (StringRef S : Obj->getComdatTable()) { 759 StringRef N = Saver.save(S); 760 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second); 761 } 762 763 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 764 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)); 765 } 766 767 template <template <class> class T> 768 static InputFile *createELFFile(MemoryBufferRef MB) { 769 unsigned char Size; 770 unsigned char Endian; 771 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 772 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 773 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 774 775 size_t BufSize = MB.getBuffer().size(); 776 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 777 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 778 fatal(MB.getBufferIdentifier() + ": file is too short"); 779 780 InputFile *Obj; 781 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB) 782 Obj = make<T<ELF32LE>>(MB); 783 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB) 784 Obj = make<T<ELF32BE>>(MB); 785 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB) 786 Obj = make<T<ELF64LE>>(MB); 787 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB) 788 Obj = make<T<ELF64BE>>(MB); 789 else 790 fatal(MB.getBufferIdentifier() + ": invalid file class"); 791 792 if (!Config->FirstElf) 793 Config->FirstElf = Obj; 794 return Obj; 795 } 796 797 template <class ELFT> void BinaryFile::parse() { 798 StringRef Buf = MB.getBuffer(); 799 ArrayRef<uint8_t> Data = 800 makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size()); 801 802 std::string Filename = MB.getBufferIdentifier(); 803 std::transform(Filename.begin(), Filename.end(), Filename.begin(), 804 [](char C) { return isalnum(C) ? C : '_'; }); 805 Filename = "_binary_" + Filename; 806 StringRef StartName = Saver.save(Twine(Filename) + "_start"); 807 StringRef EndName = Saver.save(Twine(Filename) + "_end"); 808 StringRef SizeName = Saver.save(Twine(Filename) + "_size"); 809 810 auto *Section = 811 make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 8, Data, ".data"); 812 Sections.push_back(Section); 813 814 elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0, 815 STB_GLOBAL, Section, nullptr); 816 elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT, 817 Data.size(), 0, STB_GLOBAL, Section, 818 nullptr); 819 elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT, 820 Data.size(), 0, STB_GLOBAL, nullptr, 821 nullptr); 822 } 823 824 static bool isBitcode(MemoryBufferRef MB) { 825 using namespace sys::fs; 826 return identify_magic(MB.getBuffer()) == file_magic::bitcode; 827 } 828 829 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 830 uint64_t OffsetInArchive) { 831 InputFile *F = 832 isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB); 833 F->ArchiveName = ArchiveName; 834 F->OffsetInArchive = OffsetInArchive; 835 return F; 836 } 837 838 InputFile *elf::createSharedFile(MemoryBufferRef MB) { 839 return createELFFile<SharedFile>(MB); 840 } 841 842 MemoryBufferRef LazyObjectFile::getBuffer() { 843 if (Seen) 844 return MemoryBufferRef(); 845 Seen = true; 846 return MB; 847 } 848 849 template <class ELFT> void LazyObjectFile::parse() { 850 for (StringRef Sym : getSymbols()) 851 Symtab<ELFT>::X->addLazyObject(Sym, *this); 852 } 853 854 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() { 855 typedef typename ELFT::Shdr Elf_Shdr; 856 typedef typename ELFT::Sym Elf_Sym; 857 typedef typename ELFT::SymRange Elf_Sym_Range; 858 859 const ELFFile<ELFT> Obj(this->MB.getBuffer()); 860 ArrayRef<Elf_Shdr> Sections = check(Obj.sections()); 861 for (const Elf_Shdr &Sec : Sections) { 862 if (Sec.sh_type != SHT_SYMTAB) 863 continue; 864 Elf_Sym_Range Syms = check(Obj.symbols(&Sec)); 865 uint32_t FirstNonLocal = Sec.sh_info; 866 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections)); 867 std::vector<StringRef> V; 868 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal)) 869 if (Sym.st_shndx != SHN_UNDEF) 870 V.push_back(check(Sym.getName(StringTable))); 871 return V; 872 } 873 return {}; 874 } 875 876 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() { 877 std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB)); 878 std::vector<StringRef> V; 879 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 880 if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined)) 881 V.push_back(Saver.save(Sym.getName())); 882 return V; 883 } 884 885 // Returns a vector of globally-visible defined symbol names. 886 std::vector<StringRef> LazyObjectFile::getSymbols() { 887 if (isBitcode(this->MB)) 888 return getBitcodeSymbols(); 889 890 unsigned char Size; 891 unsigned char Endian; 892 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer()); 893 if (Size == ELFCLASS32) { 894 if (Endian == ELFDATA2LSB) 895 return getElfSymbols<ELF32LE>(); 896 return getElfSymbols<ELF32BE>(); 897 } 898 if (Endian == ELFDATA2LSB) 899 return getElfSymbols<ELF64LE>(); 900 return getElfSymbols<ELF64BE>(); 901 } 902 903 template void ArchiveFile::parse<ELF32LE>(); 904 template void ArchiveFile::parse<ELF32BE>(); 905 template void ArchiveFile::parse<ELF64LE>(); 906 template void ArchiveFile::parse<ELF64BE>(); 907 908 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 909 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 910 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 911 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 912 913 template void LazyObjectFile::parse<ELF32LE>(); 914 template void LazyObjectFile::parse<ELF32BE>(); 915 template void LazyObjectFile::parse<ELF64LE>(); 916 template void LazyObjectFile::parse<ELF64BE>(); 917 918 template class elf::ELFFileBase<ELF32LE>; 919 template class elf::ELFFileBase<ELF32BE>; 920 template class elf::ELFFileBase<ELF64LE>; 921 template class elf::ELFFileBase<ELF64BE>; 922 923 template class elf::ObjectFile<ELF32LE>; 924 template class elf::ObjectFile<ELF32BE>; 925 template class elf::ObjectFile<ELF64LE>; 926 template class elf::ObjectFile<ELF64BE>; 927 928 template class elf::SharedFile<ELF32LE>; 929 template class elf::SharedFile<ELF32BE>; 930 template class elf::SharedFile<ELF64LE>; 931 template class elf::SharedFile<ELF64BE>; 932 933 template void BinaryFile::parse<ELF32LE>(); 934 template void BinaryFile::parse<ELF32BE>(); 935 template void BinaryFile::parse<ELF64LE>(); 936 template void BinaryFile::parse<ELF64BE>(); 937