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