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