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<Symbol *> 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 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 541 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 542 // sections. Drop those sections to avoid duplicate symbol errors. 543 // FIXME: This is glibc PR20543, we should remove this hack once that has been 544 // fixed for a while. 545 if (Name.startswith(".gnu.linkonce.")) 546 return &InputSection::Discarded; 547 548 // The linker merges EH (exception handling) frames and creates a 549 // .eh_frame_hdr section for runtime. So we handle them with a special 550 // class. For relocatable outputs, they are just passed through. 551 if (Name == ".eh_frame" && !Config->Relocatable) 552 return make<EhInputSection>(this, &Sec, Name); 553 554 if (shouldMerge(Sec)) 555 return make<MergeInputSection>(this, &Sec, Name); 556 return make<InputSection>(this, &Sec, Name); 557 } 558 559 template <class ELFT> 560 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) { 561 return check(this->getObj().getSectionName(&Sec, SectionStringTable), 562 toString(this)); 563 } 564 565 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 566 this->Symbols.reserve(this->ELFSyms.size()); 567 for (const Elf_Sym &Sym : this->ELFSyms) 568 this->Symbols.push_back(createSymbol(&Sym)); 569 } 570 571 template <class ELFT> 572 InputSectionBase *ObjFile<ELFT>::getSection(uint32_t Index) const { 573 if (Index == 0) 574 return nullptr; 575 if (Index >= this->Sections.size()) 576 fatal(toString(this) + ": invalid section index: " + Twine(Index)); 577 578 if (InputSectionBase *Sec = this->Sections[Index]) 579 return Sec->Repl; 580 return nullptr; 581 } 582 583 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) { 584 int Binding = Sym->getBinding(); 585 InputSectionBase *Sec = getSection(this->getSectionIndex(*Sym)); 586 587 uint8_t StOther = Sym->st_other; 588 uint8_t Type = Sym->getType(); 589 uint64_t Value = Sym->st_value; 590 uint64_t Size = Sym->st_size; 591 592 if (Binding == STB_LOCAL) { 593 if (Sym->getType() == STT_FILE) 594 SourceFile = check(Sym->getName(this->StringTable), toString(this)); 595 596 if (this->StringTable.size() <= Sym->st_name) 597 fatal(toString(this) + ": invalid symbol name offset"); 598 599 StringRefZ Name = this->StringTable.data() + Sym->st_name; 600 if (Sym->st_shndx == SHN_UNDEF) 601 return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type); 602 603 return make<Defined>(Name, /*IsLocal=*/true, StOther, Type, Value, Size, 604 Sec); 605 } 606 607 StringRef Name = check(Sym->getName(this->StringTable), toString(this)); 608 609 switch (Sym->st_shndx) { 610 case SHN_UNDEF: 611 return Symtab->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, 612 Type, 613 /*CanOmitFromDynSym=*/false, this); 614 case SHN_COMMON: 615 if (Value == 0 || Value >= UINT32_MAX) 616 fatal(toString(this) + ": common symbol '" + Name + 617 "' has invalid alignment: " + Twine(Value)); 618 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, this); 619 } 620 621 switch (Binding) { 622 default: 623 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 624 case STB_GLOBAL: 625 case STB_WEAK: 626 case STB_GNU_UNIQUE: 627 if (Sec == &InputSection::Discarded) 628 return Symtab->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, 629 StOther, Type, 630 /*CanOmitFromDynSym=*/false, this); 631 return Symtab->addRegular<ELFT>(Name, StOther, Type, Value, Size, Binding, 632 Sec, this); 633 } 634 } 635 636 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File) 637 : InputFile(ArchiveKind, File->getMemoryBufferRef()), 638 File(std::move(File)) {} 639 640 template <class ELFT> void ArchiveFile::parse() { 641 Symbols.reserve(File->getNumberOfSymbols()); 642 for (const Archive::Symbol &Sym : File->symbols()) 643 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), this, Sym)); 644 } 645 646 // Returns a buffer pointing to a member file containing a given symbol. 647 std::pair<MemoryBufferRef, uint64_t> 648 ArchiveFile::getMember(const Archive::Symbol *Sym) { 649 Archive::Child C = 650 check(Sym->getMember(), toString(this) + 651 ": could not get the member for symbol " + 652 Sym->getName()); 653 654 if (!Seen.insert(C.getChildOffset()).second) 655 return {MemoryBufferRef(), 0}; 656 657 MemoryBufferRef Ret = 658 check(C.getMemoryBufferRef(), 659 toString(this) + 660 ": could not get the buffer for the member defining symbol " + 661 Sym->getName()); 662 663 if (C.getParent()->isThin() && Tar) 664 Tar->append(relativeToRoot(check(C.getFullName(), toString(this))), 665 Ret.getBuffer()); 666 if (C.getParent()->isThin()) 667 return {Ret, 0}; 668 return {Ret, C.getChildOffset()}; 669 } 670 671 template <class ELFT> 672 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName) 673 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName), 674 AsNeeded(Config->AsNeeded) {} 675 676 // Partially parse the shared object file so that we can call 677 // getSoName on this object. 678 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 679 const Elf_Shdr *DynamicSec = nullptr; 680 const ELFFile<ELFT> Obj = this->getObj(); 681 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this)); 682 683 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 684 for (const Elf_Shdr &Sec : Sections) { 685 switch (Sec.sh_type) { 686 default: 687 continue; 688 case SHT_DYNSYM: 689 this->initSymtab(Sections, &Sec); 690 break; 691 case SHT_DYNAMIC: 692 DynamicSec = &Sec; 693 break; 694 case SHT_SYMTAB_SHNDX: 695 this->SymtabSHNDX = 696 check(Obj.getSHNDXTable(Sec, Sections), toString(this)); 697 break; 698 case SHT_GNU_versym: 699 this->VersymSec = &Sec; 700 break; 701 case SHT_GNU_verdef: 702 this->VerdefSec = &Sec; 703 break; 704 } 705 } 706 707 if (this->VersymSec && this->ELFSyms.empty()) 708 error("SHT_GNU_versym should be associated with symbol table"); 709 710 // Search for a DT_SONAME tag to initialize this->SoName. 711 if (!DynamicSec) 712 return; 713 ArrayRef<Elf_Dyn> Arr = 714 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), 715 toString(this)); 716 for (const Elf_Dyn &Dyn : Arr) { 717 if (Dyn.d_tag == DT_SONAME) { 718 uint64_t Val = Dyn.getVal(); 719 if (Val >= this->StringTable.size()) 720 fatal(toString(this) + ": invalid DT_SONAME entry"); 721 SoName = this->StringTable.data() + Val; 722 return; 723 } 724 } 725 } 726 727 // Parse the version definitions in the object file if present. Returns a vector 728 // whose nth element contains a pointer to the Elf_Verdef for version identifier 729 // n. Version identifiers that are not definitions map to nullptr. The array 730 // always has at least length 1. 731 template <class ELFT> 732 std::vector<const typename ELFT::Verdef *> 733 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) { 734 std::vector<const Elf_Verdef *> Verdefs(1); 735 // We only need to process symbol versions for this DSO if it has both a 736 // versym and a verdef section, which indicates that the DSO contains symbol 737 // version definitions. 738 if (!VersymSec || !VerdefSec) 739 return Verdefs; 740 741 // The location of the first global versym entry. 742 const char *Base = this->MB.getBuffer().data(); 743 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 744 this->FirstNonLocal; 745 746 // We cannot determine the largest verdef identifier without inspecting 747 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 748 // sequentially starting from 1, so we predict that the largest identifier 749 // will be VerdefCount. 750 unsigned VerdefCount = VerdefSec->sh_info; 751 Verdefs.resize(VerdefCount + 1); 752 753 // Build the Verdefs array by following the chain of Elf_Verdef objects 754 // from the start of the .gnu.version_d section. 755 const char *Verdef = Base + VerdefSec->sh_offset; 756 for (unsigned I = 0; I != VerdefCount; ++I) { 757 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 758 Verdef += CurVerdef->vd_next; 759 unsigned VerdefIndex = CurVerdef->vd_ndx; 760 if (Verdefs.size() <= VerdefIndex) 761 Verdefs.resize(VerdefIndex + 1); 762 Verdefs[VerdefIndex] = CurVerdef; 763 } 764 765 return Verdefs; 766 } 767 768 // Fully parse the shared object file. This must be called after parseSoName(). 769 template <class ELFT> void SharedFile<ELFT>::parseRest() { 770 // Create mapping from version identifiers to Elf_Verdef entries. 771 const Elf_Versym *Versym = nullptr; 772 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym); 773 774 ArrayRef<Elf_Shdr> Sections = 775 check(this->getObj().sections(), toString(this)); 776 777 // Add symbols to the symbol table. 778 Elf_Sym_Range Syms = this->getGlobalELFSyms(); 779 for (const Elf_Sym &Sym : Syms) { 780 unsigned VersymIndex = 0; 781 if (Versym) { 782 VersymIndex = Versym->vs_index; 783 ++Versym; 784 } 785 bool Hidden = VersymIndex & VERSYM_HIDDEN; 786 VersymIndex = VersymIndex & ~VERSYM_HIDDEN; 787 788 StringRef Name = check(Sym.getName(this->StringTable), toString(this)); 789 if (Sym.isUndefined()) { 790 Undefs.push_back(Name); 791 continue; 792 } 793 794 // Ignore local symbols. 795 if (Versym && VersymIndex == VER_NDX_LOCAL) 796 continue; 797 const Elf_Verdef *Ver = nullptr; 798 if (VersymIndex != VER_NDX_GLOBAL) { 799 if (VersymIndex >= Verdefs.size()) { 800 error("corrupt input file: version definition index " + 801 Twine(VersymIndex) + " for symbol " + Name + 802 " is out of bounds\n>>> defined in " + toString(this)); 803 continue; 804 } 805 Ver = Verdefs[VersymIndex]; 806 } 807 808 // We do not usually care about alignments of data in shared object 809 // files because the loader takes care of it. However, if we promote a 810 // DSO symbol to point to .bss due to copy relocation, we need to keep 811 // the original alignment requirements. We infer it here. 812 uint64_t Alignment = 1; 813 if (Sym.st_value) 814 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value); 815 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) { 816 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign; 817 Alignment = std::min(Alignment, SecAlign); 818 } 819 if (Alignment > UINT32_MAX) 820 error(toString(this) + ": alignment too large: " + Name); 821 822 if (!Hidden) 823 Symtab->addShared(Name, this, Sym, Alignment, Ver); 824 825 // Also add the symbol with the versioned name to handle undefined symbols 826 // with explicit versions. 827 if (Ver) { 828 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name; 829 Name = Saver.save(Name + "@" + VerName); 830 Symtab->addShared(Name, this, Sym, Alignment, Ver); 831 } 832 } 833 } 834 835 static ELFKind getBitcodeELFKind(const Triple &T) { 836 if (T.isLittleEndian()) 837 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 838 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 839 } 840 841 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) { 842 switch (T.getArch()) { 843 case Triple::aarch64: 844 return EM_AARCH64; 845 case Triple::arm: 846 case Triple::thumb: 847 return EM_ARM; 848 case Triple::avr: 849 return EM_AVR; 850 case Triple::mips: 851 case Triple::mipsel: 852 case Triple::mips64: 853 case Triple::mips64el: 854 return EM_MIPS; 855 case Triple::ppc: 856 return EM_PPC; 857 case Triple::ppc64: 858 return EM_PPC64; 859 case Triple::x86: 860 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 861 case Triple::x86_64: 862 return EM_X86_64; 863 default: 864 fatal(Path + ": could not infer e_machine from bitcode target triple " + 865 T.str()); 866 } 867 } 868 869 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName, 870 uint64_t OffsetInArchive) 871 : InputFile(BitcodeKind, MB) { 872 this->ArchiveName = ArchiveName; 873 874 // Here we pass a new MemoryBufferRef which is identified by ArchiveName 875 // (the fully resolved path of the archive) + member name + offset of the 876 // member in the archive. 877 // ThinLTO uses the MemoryBufferRef identifier to access its internal 878 // data structures and if two archives define two members with the same name, 879 // this causes a collision which result in only one of the objects being 880 // taken into consideration at LTO time (which very likely causes undefined 881 // symbols later in the link stage). 882 MemoryBufferRef MBRef(MB.getBuffer(), 883 Saver.save(ArchiveName + MB.getBufferIdentifier() + 884 utostr(OffsetInArchive))); 885 Obj = check(lto::InputFile::create(MBRef), toString(this)); 886 887 Triple T(Obj->getTargetTriple()); 888 EKind = getBitcodeELFKind(T); 889 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T); 890 } 891 892 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 893 switch (GvVisibility) { 894 case GlobalValue::DefaultVisibility: 895 return STV_DEFAULT; 896 case GlobalValue::HiddenVisibility: 897 return STV_HIDDEN; 898 case GlobalValue::ProtectedVisibility: 899 return STV_PROTECTED; 900 } 901 llvm_unreachable("unknown visibility"); 902 } 903 904 template <class ELFT> 905 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 906 const lto::InputFile::Symbol &ObjSym, 907 BitcodeFile *F) { 908 StringRef NameRef = Saver.save(ObjSym.getName()); 909 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL; 910 911 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 912 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 913 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 914 915 int C = ObjSym.getComdatIndex(); 916 if (C != -1 && !KeptComdats[C]) 917 return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding, 918 Visibility, Type, CanOmitFromDynSym, F); 919 920 if (ObjSym.isUndefined()) 921 return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding, 922 Visibility, Type, CanOmitFromDynSym, F); 923 924 if (ObjSym.isCommon()) 925 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(), 926 ObjSym.getCommonAlignment(), Binding, Visibility, 927 STT_OBJECT, F); 928 929 return Symtab->addBitcode(NameRef, Binding, Visibility, Type, 930 CanOmitFromDynSym, F); 931 } 932 933 template <class ELFT> 934 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 935 std::vector<bool> KeptComdats; 936 for (StringRef S : Obj->getComdatTable()) 937 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second); 938 939 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 940 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)); 941 } 942 943 static ELFKind getELFKind(MemoryBufferRef MB) { 944 unsigned char Size; 945 unsigned char Endian; 946 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 947 948 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 949 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 950 if (Size != ELFCLASS32 && Size != ELFCLASS64) 951 fatal(MB.getBufferIdentifier() + ": invalid file class"); 952 953 size_t BufSize = MB.getBuffer().size(); 954 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 955 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 956 fatal(MB.getBufferIdentifier() + ": file is too short"); 957 958 if (Size == ELFCLASS32) 959 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 960 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 961 } 962 963 template <class ELFT> void BinaryFile::parse() { 964 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer()); 965 auto *Section = 966 make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data"); 967 Sections.push_back(Section); 968 969 // For each input file foo that is embedded to a result as a binary 970 // blob, we define _binary_foo_{start,end,size} symbols, so that 971 // user programs can access blobs by name. Non-alphanumeric 972 // characters in a filename are replaced with underscore. 973 std::string S = "_binary_" + MB.getBufferIdentifier().str(); 974 for (size_t I = 0; I < S.size(); ++I) 975 if (!isAlnum(S[I])) 976 S[I] = '_'; 977 978 Symtab->addRegular<ELFT>(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 979 0, 0, STB_GLOBAL, Section, nullptr); 980 Symtab->addRegular<ELFT>(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT, 981 Data.size(), 0, STB_GLOBAL, Section, nullptr); 982 Symtab->addRegular<ELFT>(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT, 983 Data.size(), 0, STB_GLOBAL, nullptr, nullptr); 984 } 985 986 static bool isBitcode(MemoryBufferRef MB) { 987 using namespace sys::fs; 988 return identify_magic(MB.getBuffer()) == file_magic::bitcode; 989 } 990 991 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 992 uint64_t OffsetInArchive) { 993 if (isBitcode(MB)) 994 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive); 995 996 switch (getELFKind(MB)) { 997 case ELF32LEKind: 998 return make<ObjFile<ELF32LE>>(MB, ArchiveName); 999 case ELF32BEKind: 1000 return make<ObjFile<ELF32BE>>(MB, ArchiveName); 1001 case ELF64LEKind: 1002 return make<ObjFile<ELF64LE>>(MB, ArchiveName); 1003 case ELF64BEKind: 1004 return make<ObjFile<ELF64BE>>(MB, ArchiveName); 1005 default: 1006 llvm_unreachable("getELFKind"); 1007 } 1008 } 1009 1010 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) { 1011 switch (getELFKind(MB)) { 1012 case ELF32LEKind: 1013 return make<SharedFile<ELF32LE>>(MB, DefaultSoName); 1014 case ELF32BEKind: 1015 return make<SharedFile<ELF32BE>>(MB, DefaultSoName); 1016 case ELF64LEKind: 1017 return make<SharedFile<ELF64LE>>(MB, DefaultSoName); 1018 case ELF64BEKind: 1019 return make<SharedFile<ELF64BE>>(MB, DefaultSoName); 1020 default: 1021 llvm_unreachable("getELFKind"); 1022 } 1023 } 1024 1025 MemoryBufferRef LazyObjFile::getBuffer() { 1026 if (Seen) 1027 return MemoryBufferRef(); 1028 Seen = true; 1029 return MB; 1030 } 1031 1032 InputFile *LazyObjFile::fetch() { 1033 MemoryBufferRef MBRef = getBuffer(); 1034 if (MBRef.getBuffer().empty()) 1035 return nullptr; 1036 return createObjectFile(MBRef, ArchiveName, OffsetInArchive); 1037 } 1038 1039 template <class ELFT> void LazyObjFile::parse() { 1040 for (StringRef Sym : getSymbolNames()) 1041 Symtab->addLazyObject<ELFT>(Sym, *this); 1042 } 1043 1044 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() { 1045 typedef typename ELFT::Shdr Elf_Shdr; 1046 typedef typename ELFT::Sym Elf_Sym; 1047 typedef typename ELFT::SymRange Elf_Sym_Range; 1048 1049 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer())); 1050 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this)); 1051 for (const Elf_Shdr &Sec : Sections) { 1052 if (Sec.sh_type != SHT_SYMTAB) 1053 continue; 1054 1055 Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this)); 1056 uint32_t FirstNonLocal = Sec.sh_info; 1057 StringRef StringTable = 1058 check(Obj.getStringTableForSymtab(Sec, Sections), toString(this)); 1059 std::vector<StringRef> V; 1060 1061 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal)) 1062 if (Sym.st_shndx != SHN_UNDEF) 1063 V.push_back(check(Sym.getName(StringTable), toString(this))); 1064 return V; 1065 } 1066 return {}; 1067 } 1068 1069 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() { 1070 std::unique_ptr<lto::InputFile> Obj = 1071 check(lto::InputFile::create(this->MB), toString(this)); 1072 std::vector<StringRef> V; 1073 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 1074 if (!Sym.isUndefined()) 1075 V.push_back(Saver.save(Sym.getName())); 1076 return V; 1077 } 1078 1079 // Returns a vector of globally-visible defined symbol names. 1080 std::vector<StringRef> LazyObjFile::getSymbolNames() { 1081 if (isBitcode(this->MB)) 1082 return getBitcodeSymbols(); 1083 1084 switch (getELFKind(this->MB)) { 1085 case ELF32LEKind: 1086 return getElfSymbols<ELF32LE>(); 1087 case ELF32BEKind: 1088 return getElfSymbols<ELF32BE>(); 1089 case ELF64LEKind: 1090 return getElfSymbols<ELF64LE>(); 1091 case ELF64BEKind: 1092 return getElfSymbols<ELF64BE>(); 1093 default: 1094 llvm_unreachable("getELFKind"); 1095 } 1096 } 1097 1098 template void ArchiveFile::parse<ELF32LE>(); 1099 template void ArchiveFile::parse<ELF32BE>(); 1100 template void ArchiveFile::parse<ELF64LE>(); 1101 template void ArchiveFile::parse<ELF64BE>(); 1102 1103 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 1104 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 1105 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 1106 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 1107 1108 template void LazyObjFile::parse<ELF32LE>(); 1109 template void LazyObjFile::parse<ELF32BE>(); 1110 template void LazyObjFile::parse<ELF64LE>(); 1111 template void LazyObjFile::parse<ELF64BE>(); 1112 1113 template class elf::ELFFileBase<ELF32LE>; 1114 template class elf::ELFFileBase<ELF32BE>; 1115 template class elf::ELFFileBase<ELF64LE>; 1116 template class elf::ELFFileBase<ELF64BE>; 1117 1118 template class elf::ObjFile<ELF32LE>; 1119 template class elf::ObjFile<ELF32BE>; 1120 template class elf::ObjFile<ELF64LE>; 1121 template class elf::ObjFile<ELF64BE>; 1122 1123 template class elf::SharedFile<ELF32LE>; 1124 template class elf::SharedFile<ELF32BE>; 1125 template class elf::SharedFile<ELF64LE>; 1126 template class elf::SharedFile<ELF64BE>; 1127 1128 template void BinaryFile::parse<ELF32LE>(); 1129 template void BinaryFile::parse<ELF32BE>(); 1130 template void BinaryFile::parse<ELF64LE>(); 1131 template void BinaryFile::parse<ELF64BE>(); 1132