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 // FIXME: Provide the associated DWARFUnit if there is one. DWARF v5 81 // needs it in order to find indirect strings. 82 const DWARFDebugLine::LineTable *LT = 83 DwarfLine->getOrParseLineTable(LineData, 0, nullptr); 84 85 // Return if there is no debug information about CU available. 86 if (!Dwarf.getNumCompileUnits()) 87 return; 88 89 // Loop over variable records and insert them to VariableLoc. 90 DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0); 91 for (const auto &Entry : CU->dies()) { 92 DWARFDie Die(CU, &Entry); 93 // Skip all tags that are not variables. 94 if (Die.getTag() != dwarf::DW_TAG_variable) 95 continue; 96 97 // Skip if a local variable because we don't need them for generating error 98 // messages. In general, only non-local symbols can fail to be linked. 99 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0)) 100 continue; 101 102 // Get the source filename index for the variable. 103 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0); 104 if (!LT->hasFileAtIndex(File)) 105 continue; 106 107 // Get the line number on which the variable is declared. 108 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0); 109 110 // Get the name of the variable and add the collected information to 111 // VariableLoc. Usually Name is non-empty, but it can be empty if the input 112 // object file lacks some debug info. 113 StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), ""); 114 if (!Name.empty()) 115 VariableLoc.insert({Name, {File, Line}}); 116 } 117 } 118 119 // Returns the pair of file name and line number describing location of data 120 // object (variable, array, etc) definition. 121 template <class ELFT> 122 Optional<std::pair<std::string, unsigned>> 123 ObjFile<ELFT>::getVariableLoc(StringRef Name) { 124 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); }); 125 126 // There is always only one CU so it's offset is 0. 127 const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0); 128 if (!LT) 129 return None; 130 131 // Return if we have no debug information about data object. 132 auto It = VariableLoc.find(Name); 133 if (It == VariableLoc.end()) 134 return None; 135 136 // Take file name string from line table. 137 std::string FileName; 138 if (!LT->getFileNameByIndex( 139 It->second.first /* File */, nullptr, 140 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName)) 141 return None; 142 143 return std::make_pair(FileName, It->second.second /*Line*/); 144 } 145 146 // Returns source line information for a given offset 147 // using DWARF debug info. 148 template <class ELFT> 149 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S, 150 uint64_t Offset) { 151 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); }); 152 153 // The offset to CU is 0. 154 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0); 155 if (!Tbl) 156 return None; 157 158 // Use fake address calcuated by adding section file offset and offset in 159 // section. See comments for ObjectInfo class. 160 DILineInfo Info; 161 Tbl->getFileLineInfoForAddress( 162 S->getOffsetInFile() + Offset, nullptr, 163 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info); 164 if (Info.Line == 0) 165 return None; 166 return Info; 167 } 168 169 // Returns source line information for a given offset 170 // using DWARF debug info. 171 template <class ELFT> 172 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) { 173 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset)) 174 return Info->FileName + ":" + std::to_string(Info->Line); 175 return ""; 176 } 177 178 // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 179 std::string lld::toString(const InputFile *F) { 180 if (!F) 181 return "<internal>"; 182 183 if (F->ToStringCache.empty()) { 184 if (F->ArchiveName.empty()) 185 F->ToStringCache = F->getName(); 186 else 187 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str(); 188 } 189 return F->ToStringCache; 190 } 191 192 template <class ELFT> 193 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) { 194 if (ELFT::TargetEndianness == support::little) 195 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind; 196 else 197 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind; 198 199 EMachine = getObj().getHeader()->e_machine; 200 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI]; 201 } 202 203 template <class ELFT> 204 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() { 205 return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end()); 206 } 207 208 template <class ELFT> 209 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const { 210 return check(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), 211 toString(this)); 212 } 213 214 template <class ELFT> 215 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections, 216 const Elf_Shdr *Symtab) { 217 FirstNonLocal = Symtab->sh_info; 218 ELFSyms = check(getObj().symbols(Symtab), toString(this)); 219 if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size()) 220 fatal(toString(this) + ": invalid sh_info in symbol table"); 221 222 StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections), 223 toString(this)); 224 } 225 226 template <class ELFT> 227 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName) 228 : ELFFileBase<ELFT>(Base::ObjKind, M) { 229 this->ArchiveName = ArchiveName; 230 } 231 232 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() { 233 if (this->Symbols.empty()) 234 return {}; 235 return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1); 236 } 237 238 template <class ELFT> 239 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 240 // Read section and symbol tables. 241 initializeSections(ComdatGroups); 242 initializeSymbols(); 243 } 244 245 // Sections with SHT_GROUP and comdat bits define comdat section groups. 246 // They are identified and deduplicated by group name. This function 247 // returns a group name. 248 template <class ELFT> 249 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections, 250 const Elf_Shdr &Sec) { 251 // Group signatures are stored as symbol names in object files. 252 // sh_info contains a symbol index, so we fetch a symbol and read its name. 253 if (this->ELFSyms.empty()) 254 this->initSymtab( 255 Sections, 256 check(object::getSection<ELFT>(Sections, Sec.sh_link), toString(this))); 257 258 const Elf_Sym *Sym = check( 259 object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), toString(this)); 260 StringRef Signature = check(Sym->getName(this->StringTable), toString(this)); 261 262 // As a special case, if a symbol is a section symbol and has no name, 263 // we use a section name as a signature. 264 // 265 // Such SHT_GROUP sections are invalid from the perspective of the ELF 266 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or 267 // older produce such sections as outputs for the -r option, so we need 268 // a bug-compatibility. 269 if (Signature.empty() && Sym->getType() == STT_SECTION) 270 return getSectionName(Sec); 271 return Signature; 272 } 273 274 template <class ELFT> 275 ArrayRef<typename ObjFile<ELFT>::Elf_Word> 276 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) { 277 const ELFFile<ELFT> &Obj = this->getObj(); 278 ArrayRef<Elf_Word> Entries = check( 279 Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), toString(this)); 280 if (Entries.empty() || Entries[0] != GRP_COMDAT) 281 fatal(toString(this) + ": unsupported SHT_GROUP format"); 282 return Entries.slice(1); 283 } 284 285 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) { 286 // We don't merge sections if -O0 (default is -O1). This makes sometimes 287 // the linker significantly faster, although the output will be bigger. 288 if (Config->Optimize == 0) 289 return false; 290 291 // Do not merge sections if generating a relocatable object. It makes 292 // the code simpler because we do not need to update relocation addends 293 // to reflect changes introduced by merging. 294 if (Config->Relocatable) 295 return false; 296 297 // A mergeable section with size 0 is useless because they don't have 298 // any data to merge. A mergeable string section with size 0 can be 299 // argued as invalid because it doesn't end with a null character. 300 // We'll avoid a mess by handling them as if they were non-mergeable. 301 if (Sec.sh_size == 0) 302 return false; 303 304 // Check for sh_entsize. The ELF spec is not clear about the zero 305 // sh_entsize. It says that "the member [sh_entsize] contains 0 if 306 // the section does not hold a table of fixed-size entries". We know 307 // that Rust 1.13 produces a string mergeable section with a zero 308 // sh_entsize. Here we just accept it rather than being picky about it. 309 uint64_t EntSize = Sec.sh_entsize; 310 if (EntSize == 0) 311 return false; 312 if (Sec.sh_size % EntSize) 313 fatal(toString(this) + 314 ": SHF_MERGE section size must be a multiple of sh_entsize"); 315 316 uint64_t Flags = Sec.sh_flags; 317 if (!(Flags & SHF_MERGE)) 318 return false; 319 if (Flags & SHF_WRITE) 320 fatal(toString(this) + ": writable SHF_MERGE section is not supported"); 321 322 // Don't try to merge if the alignment is larger than the sh_entsize and this 323 // is not SHF_STRINGS. 324 // 325 // Since this is not a SHF_STRINGS, we would need to pad after every entity. 326 // It would be equivalent for the producer of the .o to just set a larger 327 // sh_entsize. 328 if (Flags & SHF_STRINGS) 329 return true; 330 331 return Sec.sh_addralign <= EntSize; 332 } 333 334 template <class ELFT> 335 void ObjFile<ELFT>::initializeSections( 336 DenseSet<CachedHashStringRef> &ComdatGroups) { 337 const ELFFile<ELFT> &Obj = this->getObj(); 338 339 ArrayRef<Elf_Shdr> ObjSections = 340 check(this->getObj().sections(), toString(this)); 341 uint64_t Size = ObjSections.size(); 342 this->Sections.resize(Size); 343 this->SectionStringTable = 344 check(Obj.getSectionStringTable(ObjSections), toString(this)); 345 346 for (size_t I = 0, E = ObjSections.size(); I < E; I++) { 347 if (this->Sections[I] == &InputSection::Discarded) 348 continue; 349 const Elf_Shdr &Sec = ObjSections[I]; 350 351 // SHF_EXCLUDE'ed sections are discarded by the linker. However, 352 // if -r is given, we'll let the final link discard such sections. 353 // This is compatible with GNU. 354 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) { 355 this->Sections[I] = &InputSection::Discarded; 356 continue; 357 } 358 359 switch (Sec.sh_type) { 360 case SHT_GROUP: { 361 // De-duplicate section groups by their signatures. 362 StringRef Signature = getShtGroupSignature(ObjSections, Sec); 363 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second; 364 this->Sections[I] = &InputSection::Discarded; 365 366 // If it is a new section group, we want to keep group members. 367 // Group leader sections, which contain indices of group members, are 368 // discarded because they are useless beyond this point. The only 369 // exception is the -r option because in order to produce re-linkable 370 // object files, we want to pass through basically everything. 371 if (IsNew) { 372 if (Config->Relocatable) 373 this->Sections[I] = createInputSection(Sec); 374 continue; 375 } 376 377 // Otherwise, discard group members. 378 for (uint32_t SecIndex : getShtGroupEntries(Sec)) { 379 if (SecIndex >= Size) 380 fatal(toString(this) + 381 ": invalid section index in group: " + Twine(SecIndex)); 382 this->Sections[SecIndex] = &InputSection::Discarded; 383 } 384 break; 385 } 386 case SHT_SYMTAB: 387 this->initSymtab(ObjSections, &Sec); 388 break; 389 case SHT_SYMTAB_SHNDX: 390 this->SymtabSHNDX = 391 check(Obj.getSHNDXTable(Sec, ObjSections), toString(this)); 392 break; 393 case SHT_STRTAB: 394 case SHT_NULL: 395 break; 396 default: 397 this->Sections[I] = createInputSection(Sec); 398 } 399 400 // .ARM.exidx sections have a reverse dependency on the InputSection they 401 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link. 402 if (Sec.sh_flags & SHF_LINK_ORDER) { 403 if (Sec.sh_link >= this->Sections.size()) 404 fatal(toString(this) + ": invalid sh_link index: " + 405 Twine(Sec.sh_link)); 406 this->Sections[Sec.sh_link]->DependentSections.push_back( 407 cast<InputSection>(this->Sections[I])); 408 } 409 } 410 } 411 412 template <class ELFT> 413 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) { 414 uint32_t Idx = Sec.sh_info; 415 if (Idx >= this->Sections.size()) 416 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx)); 417 InputSectionBase *Target = this->Sections[Idx]; 418 419 // Strictly speaking, a relocation section must be included in the 420 // group of the section it relocates. However, LLVM 3.3 and earlier 421 // would fail to do so, so we gracefully handle that case. 422 if (Target == &InputSection::Discarded) 423 return nullptr; 424 425 if (!Target) 426 fatal(toString(this) + ": unsupported relocation reference"); 427 return Target; 428 } 429 430 // Create a regular InputSection class that has the same contents 431 // as a given section. 432 InputSectionBase *toRegularSection(MergeInputSection *Sec) { 433 auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment, 434 Sec->Data, Sec->Name); 435 Ret->File = Sec->File; 436 return Ret; 437 } 438 439 template <class ELFT> 440 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) { 441 StringRef Name = getSectionName(Sec); 442 443 switch (Sec.sh_type) { 444 case SHT_ARM_ATTRIBUTES: 445 // FIXME: ARM meta-data section. Retain the first attribute section 446 // we see. The eglibc ARM dynamic loaders require the presence of an 447 // attribute section for dlopen to work. 448 // In a full implementation we would merge all attribute sections. 449 if (InX::ARMAttributes == nullptr) { 450 InX::ARMAttributes = make<InputSection>(this, &Sec, Name); 451 return InX::ARMAttributes; 452 } 453 return &InputSection::Discarded; 454 case SHT_RELA: 455 case SHT_REL: { 456 // Find the relocation target section and associate this 457 // section with it. Target can be discarded, for example 458 // if it is a duplicated member of SHT_GROUP section, we 459 // do not create or proccess relocatable sections then. 460 InputSectionBase *Target = getRelocTarget(Sec); 461 if (!Target) 462 return nullptr; 463 464 // This section contains relocation information. 465 // If -r is given, we do not interpret or apply relocation 466 // but just copy relocation sections to output. 467 if (Config->Relocatable) 468 return make<InputSection>(this, &Sec, Name); 469 470 if (Target->FirstRelocation) 471 fatal(toString(this) + 472 ": multiple relocation sections to one section are not supported"); 473 474 // Mergeable sections with relocations are tricky because relocations 475 // need to be taken into account when comparing section contents for 476 // merging. It's not worth supporting such mergeable sections because 477 // they are rare and it'd complicates the internal design (we usually 478 // have to determine if two sections are mergeable early in the link 479 // process much before applying relocations). We simply handle mergeable 480 // sections with relocations as non-mergeable. 481 if (auto *MS = dyn_cast<MergeInputSection>(Target)) { 482 Target = toRegularSection(MS); 483 this->Sections[Sec.sh_info] = Target; 484 } 485 486 size_t NumRelocations; 487 if (Sec.sh_type == SHT_RELA) { 488 ArrayRef<Elf_Rela> Rels = 489 check(this->getObj().relas(&Sec), toString(this)); 490 Target->FirstRelocation = Rels.begin(); 491 NumRelocations = Rels.size(); 492 Target->AreRelocsRela = true; 493 } else { 494 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec), toString(this)); 495 Target->FirstRelocation = Rels.begin(); 496 NumRelocations = Rels.size(); 497 Target->AreRelocsRela = false; 498 } 499 assert(isUInt<31>(NumRelocations)); 500 Target->NumRelocations = NumRelocations; 501 502 // Relocation sections processed by the linker are usually removed 503 // from the output, so returning `nullptr` for the normal case. 504 // However, if -emit-relocs is given, we need to leave them in the output. 505 // (Some post link analysis tools need this information.) 506 if (Config->EmitRelocs) { 507 InputSection *RelocSec = make<InputSection>(this, &Sec, Name); 508 // We will not emit relocation section if target was discarded. 509 Target->DependentSections.push_back(RelocSec); 510 return RelocSec; 511 } 512 return nullptr; 513 } 514 } 515 516 // The GNU linker uses .note.GNU-stack section as a marker indicating 517 // that the code in the object file does not expect that the stack is 518 // executable (in terms of NX bit). If all input files have the marker, 519 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 520 // make the stack non-executable. Most object files have this section as 521 // of 2017. 522 // 523 // But making the stack non-executable is a norm today for security 524 // reasons. Failure to do so may result in a serious security issue. 525 // Therefore, we make LLD always add PT_GNU_STACK unless it is 526 // explicitly told to do otherwise (by -z execstack). Because the stack 527 // executable-ness is controlled solely by command line options, 528 // .note.GNU-stack sections are simply ignored. 529 if (Name == ".note.GNU-stack") 530 return &InputSection::Discarded; 531 532 // Split stacks is a feature to support a discontiguous stack. At least 533 // as of 2017, it seems that the feature is not being used widely. 534 // Only GNU gold supports that. We don't. For the details about that, 535 // see https://gcc.gnu.org/wiki/SplitStacks 536 if (Name == ".note.GNU-split-stack") { 537 error(toString(this) + 538 ": object file compiled with -fsplit-stack is not supported"); 539 return &InputSection::Discarded; 540 } 541 542 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 543 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 544 // sections. Drop those sections to avoid duplicate symbol errors. 545 // FIXME: This is glibc PR20543, we should remove this hack once that has been 546 // fixed for a while. 547 if (Name.startswith(".gnu.linkonce.")) 548 return &InputSection::Discarded; 549 550 // The linker merges EH (exception handling) frames and creates a 551 // .eh_frame_hdr section for runtime. So we handle them with a special 552 // class. For relocatable outputs, they are just passed through. 553 if (Name == ".eh_frame" && !Config->Relocatable) 554 return make<EhInputSection>(this, &Sec, Name); 555 556 if (shouldMerge(Sec)) 557 return make<MergeInputSection>(this, &Sec, Name); 558 return make<InputSection>(this, &Sec, Name); 559 } 560 561 template <class ELFT> 562 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) { 563 return check(this->getObj().getSectionName(&Sec, SectionStringTable), 564 toString(this)); 565 } 566 567 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 568 this->Symbols.reserve(this->ELFSyms.size()); 569 for (const Elf_Sym &Sym : this->ELFSyms) 570 this->Symbols.push_back(createSymbol(&Sym)); 571 } 572 573 template <class ELFT> 574 InputSectionBase *ObjFile<ELFT>::getSection(uint32_t Index) const { 575 if (Index == 0) 576 return nullptr; 577 if (Index >= this->Sections.size()) 578 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 579 580 if (InputSectionBase *Sec = this->Sections[Index]) 581 return Sec->Repl; 582 return nullptr; 583 } 584 585 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) { 586 int Binding = Sym->getBinding(); 587 InputSectionBase *Sec = getSection(this->getSectionIndex(*Sym)); 588 589 uint8_t StOther = Sym->st_other; 590 uint8_t Type = Sym->getType(); 591 uint64_t Value = Sym->st_value; 592 uint64_t Size = Sym->st_size; 593 594 if (Binding == STB_LOCAL) { 595 if (Sym->getType() == STT_FILE) 596 SourceFile = check(Sym->getName(this->StringTable), toString(this)); 597 598 if (this->StringTable.size() <= Sym->st_name) 599 fatal(toString(this) + ": invalid symbol name offset"); 600 601 StringRefZ Name = this->StringTable.data() + Sym->st_name; 602 if (Sym->st_shndx == SHN_UNDEF) 603 return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type); 604 605 return make<Defined>(Name, /*IsLocal=*/true, StOther, Type, Value, Size, 606 Sec); 607 } 608 609 StringRef Name = check(Sym->getName(this->StringTable), toString(this)); 610 611 switch (Sym->st_shndx) { 612 case SHN_UNDEF: 613 return Symtab->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, 614 Type, 615 /*CanOmitFromDynSym=*/false, this); 616 case SHN_COMMON: 617 if (Value == 0 || Value >= UINT32_MAX) 618 fatal(toString(this) + ": common symbol '" + Name + 619 "' has invalid alignment: " + Twine(Value)); 620 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, this); 621 } 622 623 switch (Binding) { 624 default: 625 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 626 case STB_GLOBAL: 627 case STB_WEAK: 628 case STB_GNU_UNIQUE: 629 if (Sec == &InputSection::Discarded) 630 return Symtab->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, 631 StOther, Type, 632 /*CanOmitFromDynSym=*/false, this); 633 return Symtab->addRegular<ELFT>(Name, StOther, Type, Value, Size, Binding, 634 Sec, this); 635 } 636 } 637 638 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File) 639 : InputFile(ArchiveKind, File->getMemoryBufferRef()), 640 File(std::move(File)) {} 641 642 template <class ELFT> void ArchiveFile::parse() { 643 Symbols.reserve(File->getNumberOfSymbols()); 644 for (const Archive::Symbol &Sym : File->symbols()) 645 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), this, Sym)); 646 } 647 648 // Returns a buffer pointing to a member file containing a given symbol. 649 std::pair<MemoryBufferRef, uint64_t> 650 ArchiveFile::getMember(const Archive::Symbol *Sym) { 651 Archive::Child C = 652 check(Sym->getMember(), toString(this) + 653 ": could not get the member for symbol " + 654 Sym->getName()); 655 656 if (!Seen.insert(C.getChildOffset()).second) 657 return {MemoryBufferRef(), 0}; 658 659 MemoryBufferRef Ret = 660 check(C.getMemoryBufferRef(), 661 toString(this) + 662 ": could not get the buffer for the member defining symbol " + 663 Sym->getName()); 664 665 if (C.getParent()->isThin() && Tar) 666 Tar->append(relativeToRoot(check(C.getFullName(), toString(this))), 667 Ret.getBuffer()); 668 if (C.getParent()->isThin()) 669 return {Ret, 0}; 670 return {Ret, C.getChildOffset()}; 671 } 672 673 template <class ELFT> 674 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName) 675 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName), 676 AsNeeded(Config->AsNeeded) {} 677 678 // Partially parse the shared object file so that we can call 679 // getSoName on this object. 680 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 681 const Elf_Shdr *DynamicSec = nullptr; 682 const ELFFile<ELFT> Obj = this->getObj(); 683 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this)); 684 685 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 686 for (const Elf_Shdr &Sec : Sections) { 687 switch (Sec.sh_type) { 688 default: 689 continue; 690 case SHT_DYNSYM: 691 this->initSymtab(Sections, &Sec); 692 break; 693 case SHT_DYNAMIC: 694 DynamicSec = &Sec; 695 break; 696 case SHT_SYMTAB_SHNDX: 697 this->SymtabSHNDX = 698 check(Obj.getSHNDXTable(Sec, Sections), toString(this)); 699 break; 700 case SHT_GNU_versym: 701 this->VersymSec = &Sec; 702 break; 703 case SHT_GNU_verdef: 704 this->VerdefSec = &Sec; 705 break; 706 } 707 } 708 709 if (this->VersymSec && this->ELFSyms.empty()) 710 error("SHT_GNU_versym should be associated with symbol table"); 711 712 // Search for a DT_SONAME tag to initialize this->SoName. 713 if (!DynamicSec) 714 return; 715 ArrayRef<Elf_Dyn> Arr = 716 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 717 toString(this)); 718 for (const Elf_Dyn &Dyn : Arr) { 719 if (Dyn.d_tag == DT_SONAME) { 720 uint64_t Val = Dyn.getVal(); 721 if (Val >= this->StringTable.size()) 722 fatal(toString(this) + ": invalid DT_SONAME entry"); 723 SoName = this->StringTable.data() + Val; 724 return; 725 } 726 } 727 } 728 729 // Parse the version definitions in the object file if present. Returns a vector 730 // whose nth element contains a pointer to the Elf_Verdef for version identifier 731 // n. Version identifiers that are not definitions map to nullptr. The array 732 // always has at least length 1. 733 template <class ELFT> 734 std::vector<const typename ELFT::Verdef *> 735 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 736 std::vector<const Elf_Verdef *> Verdefs(1); 737 // We only need to process symbol versions for this DSO if it has both a 738 // versym and a verdef section, which indicates that the DSO contains symbol 739 // version definitions. 740 if (!VersymSec || !VerdefSec) 741 return Verdefs; 742 743 // The location of the first global versym entry. 744 const char *Base = this->MB.getBuffer().data(); 745 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 746 this->FirstNonLocal; 747 748 // We cannot determine the largest verdef identifier without inspecting 749 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 750 // sequentially starting from 1, so we predict that the largest identifier 751 // will be VerdefCount. 752 unsigned VerdefCount = VerdefSec->sh_info; 753 Verdefs.resize(VerdefCount + 1); 754 755 // Build the Verdefs array by following the chain of Elf_Verdef objects 756 // from the start of the .gnu.version_d section. 757 const char *Verdef = Base + VerdefSec->sh_offset; 758 for (unsigned I = 0; I != VerdefCount; ++I) { 759 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 760 Verdef += CurVerdef->vd_next; 761 unsigned VerdefIndex = CurVerdef->vd_ndx; 762 if (Verdefs.size() <= VerdefIndex) 763 Verdefs.resize(VerdefIndex + 1); 764 Verdefs[VerdefIndex] = CurVerdef; 765 } 766 767 return Verdefs; 768 } 769 770 // Fully parse the shared object file. This must be called after parseSoName(). 771 template <class ELFT> void SharedFile<ELFT>::parseRest() { 772 // Create mapping from version identifiers to Elf_Verdef entries. 773 const Elf_Versym *Versym = nullptr; 774 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 775 776 ArrayRef<Elf_Shdr> Sections = 777 check(this->getObj().sections(), toString(this)); 778 779 // Add symbols to the symbol table. 780 Elf_Sym_Range Syms = this->getGlobalELFSyms(); 781 for (const Elf_Sym &Sym : Syms) { 782 unsigned VersymIndex = 0; 783 if (Versym) { 784 VersymIndex = Versym->vs_index; 785 ++Versym; 786 } 787 bool Hidden = VersymIndex & VERSYM_HIDDEN; 788 VersymIndex = VersymIndex & ~VERSYM_HIDDEN; 789 790 StringRef Name = check(Sym.getName(this->StringTable), toString(this)); 791 if (Sym.isUndefined()) { 792 Undefs.push_back(Name); 793 continue; 794 } 795 796 // Ignore local symbols. 797 if (Versym && VersymIndex == VER_NDX_LOCAL) 798 continue; 799 const Elf_Verdef *Ver = nullptr; 800 if (VersymIndex != VER_NDX_GLOBAL) { 801 if (VersymIndex >= Verdefs.size()) { 802 error("corrupt input file: version definition index " + 803 Twine(VersymIndex) + " for symbol " + Name + 804 " is out of bounds\n>>> defined in " + toString(this)); 805 continue; 806 } 807 Ver = Verdefs[VersymIndex]; 808 } 809 810 // We do not usually care about alignments of data in shared object 811 // files because the loader takes care of it. However, if we promote a 812 // DSO symbol to point to .bss due to copy relocation, we need to keep 813 // the original alignment requirements. We infer it here. 814 uint64_t Alignment = 1; 815 if (Sym.st_value) 816 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value); 817 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) { 818 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign; 819 Alignment = std::min(Alignment, SecAlign); 820 } 821 if (Alignment > UINT32_MAX) 822 error(toString(this) + ": alignment too large: " + Name); 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 Symbol *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