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