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<CachedHashStringRef> &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<CachedHashStringRef> &ComdatGroups) { 284 const ELFFile<ELFT> &Obj = this->getObj(); 285 286 ArrayRef<Elf_Shdr> ObjSections = 287 check(this->getObj().sections(), toString(this)); 288 uint64_t Size = ObjSections.size(); 289 this->Sections.resize(Size); 290 291 StringRef SectionStringTable = 292 check(Obj.getSectionStringTable(ObjSections), toString(this)); 293 294 for (size_t I = 0, E = ObjSections.size(); I < E; I++) { 295 if (this->Sections[I] == &InputSection::Discarded) 296 continue; 297 const Elf_Shdr &Sec = ObjSections[I]; 298 299 // SHF_EXCLUDE'ed sections are discarded by the linker. However, 300 // if -r is given, we'll let the final link discard such sections. 301 // This is compatible with GNU. 302 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) { 303 this->Sections[I] = &InputSection::Discarded; 304 continue; 305 } 306 307 switch (Sec.sh_type) { 308 case SHT_GROUP: { 309 // We discard comdat sections usually. When -r we should not do that. We 310 // still do deduplication in this case to simplify implementation, because 311 // otherwise merging group sections together would requre additional 312 // regeneration of its contents. 313 bool New = ComdatGroups 314 .insert(CachedHashStringRef( 315 getShtGroupSignature(ObjSections, Sec))) 316 .second; 317 if (New && Config->Relocatable) 318 this->Sections[I] = createInputSection(Sec, SectionStringTable); 319 else 320 this->Sections[I] = &InputSection::Discarded; 321 if (New) 322 continue; 323 324 for (uint32_t SecIndex : getShtGroupEntries(Sec)) { 325 if (SecIndex >= Size) 326 fatal(toString(this) + 327 ": invalid section index in group: " + Twine(SecIndex)); 328 this->Sections[SecIndex] = &InputSection::Discarded; 329 } 330 break; 331 } 332 case SHT_SYMTAB: 333 this->initSymtab(ObjSections, &Sec); 334 break; 335 case SHT_SYMTAB_SHNDX: 336 this->SymtabSHNDX = 337 check(Obj.getSHNDXTable(Sec, ObjSections), toString(this)); 338 break; 339 case SHT_STRTAB: 340 case SHT_NULL: 341 break; 342 default: 343 this->Sections[I] = createInputSection(Sec, SectionStringTable); 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 if (Sec.sh_flags & SHF_LINK_ORDER) { 349 if (Sec.sh_link >= this->Sections.size()) 350 fatal(toString(this) + ": invalid sh_link index: " + 351 Twine(Sec.sh_link)); 352 this->Sections[Sec.sh_link]->DependentSections.push_back( 353 this->Sections[I]); 354 } 355 } 356 } 357 358 template <class ELFT> 359 InputSectionBase *elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) { 360 uint32_t Idx = Sec.sh_info; 361 if (Idx >= this->Sections.size()) 362 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx)); 363 InputSectionBase *Target = this->Sections[Idx]; 364 365 // Strictly speaking, a relocation section must be included in the 366 // group of the section it relocates. However, LLVM 3.3 and earlier 367 // would fail to do so, so we gracefully handle that case. 368 if (Target == &InputSection::Discarded) 369 return nullptr; 370 371 if (!Target) 372 fatal(toString(this) + ": unsupported relocation reference"); 373 return Target; 374 } 375 376 // Create a regular InputSection class that has the same contents 377 // as a given section. 378 InputSectionBase *toRegularSection(MergeInputSection *Sec) { 379 auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment, 380 Sec->Data, Sec->Name); 381 Ret->File = Sec->File; 382 return Ret; 383 } 384 385 template <class ELFT> 386 InputSectionBase * 387 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec, 388 StringRef SectionStringTable) { 389 StringRef Name = check( 390 this->getObj().getSectionName(&Sec, SectionStringTable), toString(this)); 391 392 switch (Sec.sh_type) { 393 case SHT_ARM_ATTRIBUTES: 394 // FIXME: ARM meta-data section. Retain the first attribute section 395 // we see. The eglibc ARM dynamic loaders require the presence of an 396 // attribute section for dlopen to work. 397 // In a full implementation we would merge all attribute sections. 398 if (InX::ARMAttributes == nullptr) { 399 InX::ARMAttributes = make<InputSection>(this, &Sec, Name); 400 return InX::ARMAttributes; 401 } 402 return &InputSection::Discarded; 403 case SHT_RELA: 404 case SHT_REL: { 405 // Find the relocation target section and associate this 406 // section with it. Target can be discarded, for example 407 // if it is a duplicated member of SHT_GROUP section, we 408 // do not create or proccess relocatable sections then. 409 InputSectionBase *Target = getRelocTarget(Sec); 410 if (!Target) 411 return nullptr; 412 413 // This section contains relocation information. 414 // If -r is given, we do not interpret or apply relocation 415 // but just copy relocation sections to output. 416 if (Config->Relocatable) 417 return make<InputSection>(this, &Sec, Name); 418 419 if (Target->FirstRelocation) 420 fatal(toString(this) + 421 ": multiple relocation sections to one section are not supported"); 422 423 // Mergeable sections with relocations are tricky because relocations 424 // need to be taken into account when comparing section contents for 425 // merging. It's not worth supporting such mergeable sections because 426 // they are rare and it'd complicates the internal design (we usually 427 // have to determine if two sections are mergeable early in the link 428 // process much before applying relocations). We simply handle mergeable 429 // sections with relocations as non-mergeable. 430 if (auto *MS = dyn_cast<MergeInputSection>(Target)) { 431 Target = toRegularSection(MS); 432 this->Sections[Sec.sh_info] = Target; 433 } 434 435 size_t NumRelocations; 436 if (Sec.sh_type == SHT_RELA) { 437 ArrayRef<Elf_Rela> Rels = 438 check(this->getObj().relas(&Sec), toString(this)); 439 Target->FirstRelocation = Rels.begin(); 440 NumRelocations = Rels.size(); 441 Target->AreRelocsRela = true; 442 } else { 443 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec), toString(this)); 444 Target->FirstRelocation = Rels.begin(); 445 NumRelocations = Rels.size(); 446 Target->AreRelocsRela = false; 447 } 448 assert(isUInt<31>(NumRelocations)); 449 Target->NumRelocations = NumRelocations; 450 451 // Relocation sections processed by the linker are usually removed 452 // from the output, so returning `nullptr` for the normal case. 453 // However, if -emit-relocs is given, we need to leave them in the output. 454 // (Some post link analysis tools need this information.) 455 if (Config->EmitRelocs) { 456 InputSection *RelocSec = make<InputSection>(this, &Sec, Name); 457 // We will not emit relocation section if target was discarded. 458 Target->DependentSections.push_back(RelocSec); 459 return RelocSec; 460 } 461 return nullptr; 462 } 463 } 464 465 // The GNU linker uses .note.GNU-stack section as a marker indicating 466 // that the code in the object file does not expect that the stack is 467 // executable (in terms of NX bit). If all input files have the marker, 468 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 469 // make the stack non-executable. Most object files have this section as 470 // of 2017. 471 // 472 // But making the stack non-executable is a norm today for security 473 // reasons. Failure to do so may result in a serious security issue. 474 // Therefore, we make LLD always add PT_GNU_STACK unless it is 475 // explicitly told to do otherwise (by -z execstack). Because the stack 476 // executable-ness is controlled solely by command line options, 477 // .note.GNU-stack sections are simply ignored. 478 if (Name == ".note.GNU-stack") 479 return &InputSection::Discarded; 480 481 // Split stacks is a feature to support a discontiguous stack. At least 482 // as of 2017, it seems that the feature is not being used widely. 483 // Only GNU gold supports that. We don't. For the details about that, 484 // see https://gcc.gnu.org/wiki/SplitStacks 485 if (Name == ".note.GNU-split-stack") { 486 error(toString(this) + 487 ": object file compiled with -fsplit-stack is not supported"); 488 return &InputSection::Discarded; 489 } 490 491 if (Config->Strip != StripPolicy::None && Name.startswith(".debug")) 492 return &InputSection::Discarded; 493 494 // If -gdb-index is given, LLD creates .gdb_index section, and that 495 // section serves the same purpose as .debug_gnu_pub{names,types} sections. 496 // If that's the case, we want to eliminate .debug_gnu_pub{names,types} 497 // because they are redundant and can waste large amount of disk space 498 // (for example, they are about 400 MiB in total for a clang debug build.) 499 if (Config->GdbIndex && 500 (Name == ".debug_gnu_pubnames" || Name == ".debug_gnu_pubtypes")) 501 return &InputSection::Discarded; 502 503 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 504 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 505 // sections. Drop those sections to avoid duplicate symbol errors. 506 // FIXME: This is glibc PR20543, we should remove this hack once that has been 507 // fixed for a while. 508 if (Name.startswith(".gnu.linkonce.")) 509 return &InputSection::Discarded; 510 511 // The linker merges EH (exception handling) frames and creates a 512 // .eh_frame_hdr section for runtime. So we handle them with a special 513 // class. For relocatable outputs, they are just passed through. 514 if (Name == ".eh_frame" && !Config->Relocatable) 515 return make<EhInputSection>(this, &Sec, Name); 516 517 if (shouldMerge(Sec)) 518 return make<MergeInputSection>(this, &Sec, Name); 519 return make<InputSection>(this, &Sec, Name); 520 } 521 522 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() { 523 SymbolBodies.reserve(this->Symbols.size()); 524 for (const Elf_Sym &Sym : this->Symbols) 525 SymbolBodies.push_back(createSymbolBody(&Sym)); 526 } 527 528 template <class ELFT> 529 InputSectionBase *elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const { 530 uint32_t Index = this->getSectionIndex(Sym); 531 if (Index >= this->Sections.size()) 532 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 533 InputSectionBase *S = this->Sections[Index]; 534 535 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could 536 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be 537 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections. 538 // In this case it is fine for section to be null here as we do not 539 // allocate sections of these types. 540 if (!S) { 541 if (Index == 0 || Sym.getType() == STT_SECTION || 542 Sym.getType() == STT_NOTYPE) 543 return nullptr; 544 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 545 } 546 547 if (S == &InputSection::Discarded) 548 return S; 549 return S->Repl; 550 } 551 552 template <class ELFT> 553 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) { 554 int Binding = Sym->getBinding(); 555 InputSectionBase *Sec = getSection(*Sym); 556 557 uint8_t StOther = Sym->st_other; 558 uint8_t Type = Sym->getType(); 559 uint64_t Value = Sym->st_value; 560 uint64_t Size = Sym->st_size; 561 562 if (Binding == STB_LOCAL) { 563 if (Sym->getType() == STT_FILE) 564 SourceFile = check(Sym->getName(this->StringTable), toString(this)); 565 566 if (this->StringTable.size() <= Sym->st_name) 567 fatal(toString(this) + ": invalid symbol name offset"); 568 569 StringRefZ Name = this->StringTable.data() + Sym->st_name; 570 if (Sym->st_shndx == SHN_UNDEF) 571 return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type, this); 572 573 return make<DefinedRegular>(Name, /*IsLocal=*/true, StOther, Type, Value, 574 Size, Sec, this); 575 } 576 577 StringRef Name = check(Sym->getName(this->StringTable), toString(this)); 578 579 switch (Sym->st_shndx) { 580 case SHN_UNDEF: 581 return elf::Symtab<ELFT>::X 582 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type, 583 /*CanOmitFromDynSym=*/false, this) 584 ->body(); 585 case SHN_COMMON: 586 if (Value == 0 || Value >= UINT32_MAX) 587 fatal(toString(this) + ": common symbol '" + Name + 588 "' has invalid alignment: " + Twine(Value)); 589 return elf::Symtab<ELFT>::X 590 ->addCommon(Name, Size, Value, Binding, StOther, Type, this) 591 ->body(); 592 } 593 594 switch (Binding) { 595 default: 596 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 597 case STB_GLOBAL: 598 case STB_WEAK: 599 case STB_GNU_UNIQUE: 600 if (Sec == &InputSection::Discarded) 601 return elf::Symtab<ELFT>::X 602 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type, 603 /*CanOmitFromDynSym=*/false, this) 604 ->body(); 605 return elf::Symtab<ELFT>::X 606 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this) 607 ->body(); 608 } 609 } 610 611 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File) 612 : InputFile(ArchiveKind, File->getMemoryBufferRef()), 613 File(std::move(File)) {} 614 615 template <class ELFT> void ArchiveFile::parse() { 616 for (const Archive::Symbol &Sym : File->symbols()) 617 Symtab<ELFT>::X->addLazyArchive(this, Sym); 618 } 619 620 // Returns a buffer pointing to a member file containing a given symbol. 621 std::pair<MemoryBufferRef, uint64_t> 622 ArchiveFile::getMember(const Archive::Symbol *Sym) { 623 Archive::Child C = 624 check(Sym->getMember(), toString(this) + 625 ": could not get the member for symbol " + 626 Sym->getName()); 627 628 if (!Seen.insert(C.getChildOffset()).second) 629 return {MemoryBufferRef(), 0}; 630 631 MemoryBufferRef Ret = 632 check(C.getMemoryBufferRef(), 633 toString(this) + 634 ": could not get the buffer for the member defining symbol " + 635 Sym->getName()); 636 637 if (C.getParent()->isThin() && Tar) 638 Tar->append(relativeToRoot(check(C.getFullName(), toString(this))), 639 Ret.getBuffer()); 640 if (C.getParent()->isThin()) 641 return {Ret, 0}; 642 return {Ret, C.getChildOffset()}; 643 } 644 645 template <class ELFT> 646 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName) 647 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName), 648 AsNeeded(Config->AsNeeded) {} 649 650 template <class ELFT> 651 const typename ELFT::Shdr * 652 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const { 653 return check( 654 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX), 655 toString(this)); 656 } 657 658 // Partially parse the shared object file so that we can call 659 // getSoName on this object. 660 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 661 const Elf_Shdr *DynamicSec = nullptr; 662 const ELFFile<ELFT> Obj = this->getObj(); 663 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this)); 664 665 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 666 for (const Elf_Shdr &Sec : Sections) { 667 switch (Sec.sh_type) { 668 default: 669 continue; 670 case SHT_DYNSYM: 671 this->initSymtab(Sections, &Sec); 672 break; 673 case SHT_DYNAMIC: 674 DynamicSec = &Sec; 675 break; 676 case SHT_SYMTAB_SHNDX: 677 this->SymtabSHNDX = 678 check(Obj.getSHNDXTable(Sec, Sections), toString(this)); 679 break; 680 case SHT_GNU_versym: 681 this->VersymSec = &Sec; 682 break; 683 case SHT_GNU_verdef: 684 this->VerdefSec = &Sec; 685 break; 686 } 687 } 688 689 if (this->VersymSec && this->Symbols.empty()) 690 error("SHT_GNU_versym should be associated with symbol table"); 691 692 // Search for a DT_SONAME tag to initialize this->SoName. 693 if (!DynamicSec) 694 return; 695 ArrayRef<Elf_Dyn> Arr = 696 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 697 toString(this)); 698 for (const Elf_Dyn &Dyn : Arr) { 699 if (Dyn.d_tag == DT_SONAME) { 700 uint64_t Val = Dyn.getVal(); 701 if (Val >= this->StringTable.size()) 702 fatal(toString(this) + ": invalid DT_SONAME entry"); 703 SoName = this->StringTable.data() + Val; 704 return; 705 } 706 } 707 } 708 709 // Parse the version definitions in the object file if present. Returns a vector 710 // whose nth element contains a pointer to the Elf_Verdef for version identifier 711 // n. Version identifiers that are not definitions map to nullptr. The array 712 // always has at least length 1. 713 template <class ELFT> 714 std::vector<const typename ELFT::Verdef *> 715 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 716 std::vector<const Elf_Verdef *> Verdefs(1); 717 // We only need to process symbol versions for this DSO if it has both a 718 // versym and a verdef section, which indicates that the DSO contains symbol 719 // version definitions. 720 if (!VersymSec || !VerdefSec) 721 return Verdefs; 722 723 // The location of the first global versym entry. 724 const char *Base = this->MB.getBuffer().data(); 725 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 726 this->FirstNonLocal; 727 728 // We cannot determine the largest verdef identifier without inspecting 729 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 730 // sequentially starting from 1, so we predict that the largest identifier 731 // will be VerdefCount. 732 unsigned VerdefCount = VerdefSec->sh_info; 733 Verdefs.resize(VerdefCount + 1); 734 735 // Build the Verdefs array by following the chain of Elf_Verdef objects 736 // from the start of the .gnu.version_d section. 737 const char *Verdef = Base + VerdefSec->sh_offset; 738 for (unsigned I = 0; I != VerdefCount; ++I) { 739 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 740 Verdef += CurVerdef->vd_next; 741 unsigned VerdefIndex = CurVerdef->vd_ndx; 742 if (Verdefs.size() <= VerdefIndex) 743 Verdefs.resize(VerdefIndex + 1); 744 Verdefs[VerdefIndex] = CurVerdef; 745 } 746 747 return Verdefs; 748 } 749 750 // Fully parse the shared object file. This must be called after parseSoName(). 751 template <class ELFT> void SharedFile<ELFT>::parseRest() { 752 // Create mapping from version identifiers to Elf_Verdef entries. 753 const Elf_Versym *Versym = nullptr; 754 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 755 756 Elf_Sym_Range Syms = this->getGlobalSymbols(); 757 for (const Elf_Sym &Sym : Syms) { 758 unsigned VersymIndex = 0; 759 if (Versym) { 760 VersymIndex = Versym->vs_index; 761 ++Versym; 762 } 763 bool Hidden = VersymIndex & VERSYM_HIDDEN; 764 VersymIndex = VersymIndex & ~VERSYM_HIDDEN; 765 766 StringRef Name = check(Sym.getName(this->StringTable), toString(this)); 767 if (Sym.isUndefined()) { 768 Undefs.push_back(Name); 769 continue; 770 } 771 772 // Ignore local symbols. 773 if (Versym && VersymIndex == VER_NDX_LOCAL) 774 continue; 775 776 const Elf_Verdef *V = 777 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex]; 778 779 if (!Hidden) 780 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 781 782 // Also add the symbol with the versioned name to handle undefined symbols 783 // with explicit versions. 784 if (V) { 785 StringRef VerName = this->StringTable.data() + V->getAux()->vda_name; 786 Name = Saver.save(Name + "@" + VerName); 787 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V); 788 } 789 } 790 } 791 792 static ELFKind getBitcodeELFKind(const Triple &T) { 793 if (T.isLittleEndian()) 794 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 795 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 796 } 797 798 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) { 799 switch (T.getArch()) { 800 case Triple::aarch64: 801 return EM_AARCH64; 802 case Triple::arm: 803 case Triple::thumb: 804 return EM_ARM; 805 case Triple::mips: 806 case Triple::mipsel: 807 case Triple::mips64: 808 case Triple::mips64el: 809 return EM_MIPS; 810 case Triple::ppc: 811 return EM_PPC; 812 case Triple::ppc64: 813 return EM_PPC64; 814 case Triple::x86: 815 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 816 case Triple::x86_64: 817 return EM_X86_64; 818 default: 819 fatal(Path + ": could not infer e_machine from bitcode target triple " + 820 T.str()); 821 } 822 } 823 824 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName, 825 uint64_t OffsetInArchive) 826 : InputFile(BitcodeKind, MB) { 827 this->ArchiveName = ArchiveName; 828 829 // Here we pass a new MemoryBufferRef which is identified by ArchiveName 830 // (the fully resolved path of the archive) + member name + offset of the 831 // member in the archive. 832 // ThinLTO uses the MemoryBufferRef identifier to access its internal 833 // data structures and if two archives define two members with the same name, 834 // this causes a collision which result in only one of the objects being 835 // taken into consideration at LTO time (which very likely causes undefined 836 // symbols later in the link stage). 837 MemoryBufferRef MBRef(MB.getBuffer(), 838 Saver.save(ArchiveName + MB.getBufferIdentifier() + 839 utostr(OffsetInArchive))); 840 Obj = check(lto::InputFile::create(MBRef), toString(this)); 841 842 Triple T(Obj->getTargetTriple()); 843 EKind = getBitcodeELFKind(T); 844 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T); 845 } 846 847 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 848 switch (GvVisibility) { 849 case GlobalValue::DefaultVisibility: 850 return STV_DEFAULT; 851 case GlobalValue::HiddenVisibility: 852 return STV_HIDDEN; 853 case GlobalValue::ProtectedVisibility: 854 return STV_PROTECTED; 855 } 856 llvm_unreachable("unknown visibility"); 857 } 858 859 template <class ELFT> 860 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 861 const lto::InputFile::Symbol &ObjSym, 862 BitcodeFile *F) { 863 StringRef NameRef = Saver.save(ObjSym.getName()); 864 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL; 865 866 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 867 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 868 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 869 870 int C = ObjSym.getComdatIndex(); 871 if (C != -1 && !KeptComdats[C]) 872 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding, 873 Visibility, Type, CanOmitFromDynSym, 874 F); 875 876 if (ObjSym.isUndefined()) 877 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding, 878 Visibility, Type, CanOmitFromDynSym, 879 F); 880 881 if (ObjSym.isCommon()) 882 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(), 883 ObjSym.getCommonAlignment(), Binding, 884 Visibility, STT_OBJECT, F); 885 886 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type, 887 CanOmitFromDynSym, F); 888 } 889 890 template <class ELFT> 891 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 892 std::vector<bool> KeptComdats; 893 for (StringRef S : Obj->getComdatTable()) 894 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second); 895 896 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 897 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)); 898 } 899 900 static ELFKind getELFKind(MemoryBufferRef MB) { 901 unsigned char Size; 902 unsigned char Endian; 903 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 904 905 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 906 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 907 if (Size != ELFCLASS32 && Size != ELFCLASS64) 908 fatal(MB.getBufferIdentifier() + ": invalid file class"); 909 910 size_t BufSize = MB.getBuffer().size(); 911 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 912 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 913 fatal(MB.getBufferIdentifier() + ": file is too short"); 914 915 if (Size == ELFCLASS32) 916 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 917 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 918 } 919 920 template <class ELFT> void BinaryFile::parse() { 921 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer()); 922 auto *Section = 923 make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data"); 924 Sections.push_back(Section); 925 926 // For each input file foo that is embedded to a result as a binary 927 // blob, we define _binary_foo_{start,end,size} symbols, so that 928 // user programs can access blobs by name. Non-alphanumeric 929 // characters in a filename are replaced with underscore. 930 std::string S = "_binary_" + MB.getBufferIdentifier().str(); 931 for (size_t I = 0; I < S.size(); ++I) 932 if (!isalnum(S[I])) 933 S[I] = '_'; 934 935 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_start"), STV_DEFAULT, 936 STT_OBJECT, 0, 0, STB_GLOBAL, Section, 937 nullptr); 938 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_end"), STV_DEFAULT, 939 STT_OBJECT, Data.size(), 0, STB_GLOBAL, 940 Section, nullptr); 941 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_size"), STV_DEFAULT, 942 STT_OBJECT, Data.size(), 0, STB_GLOBAL, 943 nullptr, nullptr); 944 } 945 946 static bool isBitcode(MemoryBufferRef MB) { 947 using namespace sys::fs; 948 return identify_magic(MB.getBuffer()) == file_magic::bitcode; 949 } 950 951 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 952 uint64_t OffsetInArchive) { 953 if (isBitcode(MB)) 954 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive); 955 956 switch (getELFKind(MB)) { 957 case ELF32LEKind: 958 return make<ObjectFile<ELF32LE>>(MB, ArchiveName); 959 case ELF32BEKind: 960 return make<ObjectFile<ELF32BE>>(MB, ArchiveName); 961 case ELF64LEKind: 962 return make<ObjectFile<ELF64LE>>(MB, ArchiveName); 963 case ELF64BEKind: 964 return make<ObjectFile<ELF64BE>>(MB, ArchiveName); 965 default: 966 llvm_unreachable("getELFKind"); 967 } 968 } 969 970 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) { 971 switch (getELFKind(MB)) { 972 case ELF32LEKind: 973 return make<SharedFile<ELF32LE>>(MB, DefaultSoName); 974 case ELF32BEKind: 975 return make<SharedFile<ELF32BE>>(MB, DefaultSoName); 976 case ELF64LEKind: 977 return make<SharedFile<ELF64LE>>(MB, DefaultSoName); 978 case ELF64BEKind: 979 return make<SharedFile<ELF64BE>>(MB, DefaultSoName); 980 default: 981 llvm_unreachable("getELFKind"); 982 } 983 } 984 985 MemoryBufferRef LazyObjectFile::getBuffer() { 986 if (Seen) 987 return MemoryBufferRef(); 988 Seen = true; 989 return MB; 990 } 991 992 InputFile *LazyObjectFile::fetch() { 993 MemoryBufferRef MBRef = getBuffer(); 994 if (MBRef.getBuffer().empty()) 995 return nullptr; 996 return createObjectFile(MBRef, ArchiveName, OffsetInArchive); 997 } 998 999 template <class ELFT> void LazyObjectFile::parse() { 1000 for (StringRef Sym : getSymbols()) 1001 Symtab<ELFT>::X->addLazyObject(Sym, *this); 1002 } 1003 1004 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() { 1005 typedef typename ELFT::Shdr Elf_Shdr; 1006 typedef typename ELFT::Sym Elf_Sym; 1007 typedef typename ELFT::SymRange Elf_Sym_Range; 1008 1009 const ELFFile<ELFT> Obj(this->MB.getBuffer()); 1010 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this)); 1011 for (const Elf_Shdr &Sec : Sections) { 1012 if (Sec.sh_type != SHT_SYMTAB) 1013 continue; 1014 1015 Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this)); 1016 uint32_t FirstNonLocal = Sec.sh_info; 1017 StringRef StringTable = 1018 check(Obj.getStringTableForSymtab(Sec, Sections), toString(this)); 1019 std::vector<StringRef> V; 1020 1021 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal)) 1022 if (Sym.st_shndx != SHN_UNDEF) 1023 V.push_back(check(Sym.getName(StringTable), toString(this))); 1024 return V; 1025 } 1026 return {}; 1027 } 1028 1029 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() { 1030 std::unique_ptr<lto::InputFile> Obj = 1031 check(lto::InputFile::create(this->MB), toString(this)); 1032 std::vector<StringRef> V; 1033 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 1034 if (!Sym.isUndefined()) 1035 V.push_back(Saver.save(Sym.getName())); 1036 return V; 1037 } 1038 1039 // Returns a vector of globally-visible defined symbol names. 1040 std::vector<StringRef> LazyObjectFile::getSymbols() { 1041 if (isBitcode(this->MB)) 1042 return getBitcodeSymbols(); 1043 1044 switch (getELFKind(this->MB)) { 1045 case ELF32LEKind: 1046 return getElfSymbols<ELF32LE>(); 1047 case ELF32BEKind: 1048 return getElfSymbols<ELF32BE>(); 1049 case ELF64LEKind: 1050 return getElfSymbols<ELF64LE>(); 1051 case ELF64BEKind: 1052 return getElfSymbols<ELF64BE>(); 1053 default: 1054 llvm_unreachable("getELFKind"); 1055 } 1056 } 1057 1058 template void ArchiveFile::parse<ELF32LE>(); 1059 template void ArchiveFile::parse<ELF32BE>(); 1060 template void ArchiveFile::parse<ELF64LE>(); 1061 template void ArchiveFile::parse<ELF64BE>(); 1062 1063 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 1064 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 1065 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 1066 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 1067 1068 template void LazyObjectFile::parse<ELF32LE>(); 1069 template void LazyObjectFile::parse<ELF32BE>(); 1070 template void LazyObjectFile::parse<ELF64LE>(); 1071 template void LazyObjectFile::parse<ELF64BE>(); 1072 1073 template class elf::ELFFileBase<ELF32LE>; 1074 template class elf::ELFFileBase<ELF32BE>; 1075 template class elf::ELFFileBase<ELF64LE>; 1076 template class elf::ELFFileBase<ELF64BE>; 1077 1078 template class elf::ObjectFile<ELF32LE>; 1079 template class elf::ObjectFile<ELF32BE>; 1080 template class elf::ObjectFile<ELF64LE>; 1081 template class elf::ObjectFile<ELF64BE>; 1082 1083 template class elf::SharedFile<ELF32LE>; 1084 template class elf::SharedFile<ELF32BE>; 1085 template class elf::SharedFile<ELF64LE>; 1086 template class elf::SharedFile<ELF64BE>; 1087 1088 template void BinaryFile::parse<ELF32LE>(); 1089 template void BinaryFile::parse<ELF32BE>(); 1090 template void BinaryFile::parse<ELF64LE>(); 1091 template void BinaryFile::parse<ELF64BE>(); 1092