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