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