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