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