10b57cec5SDimitry Andric //===- InputFiles.cpp -----------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 90b57cec5SDimitry Andric #include "InputFiles.h" 100b57cec5SDimitry Andric #include "Driver.h" 110b57cec5SDimitry Andric #include "InputSection.h" 120b57cec5SDimitry Andric #include "LinkerScript.h" 130b57cec5SDimitry Andric #include "SymbolTable.h" 140b57cec5SDimitry Andric #include "Symbols.h" 150b57cec5SDimitry Andric #include "SyntheticSections.h" 16*04eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h" 17480093f4SDimitry Andric #include "lld/Common/DWARF.h" 180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 190b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h" 200b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 210b57cec5SDimitry Andric #include "llvm/IR/Module.h" 220b57cec5SDimitry Andric #include "llvm/LTO/LTO.h" 230b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h" 240b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h" 250b57cec5SDimitry Andric #include "llvm/Support/ARMAttributeParser.h" 260b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h" 270b57cec5SDimitry Andric #include "llvm/Support/Endian.h" 280b57cec5SDimitry Andric #include "llvm/Support/Path.h" 29e8d8bef9SDimitry Andric #include "llvm/Support/RISCVAttributeParser.h" 300b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 310b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 320b57cec5SDimitry Andric 330b57cec5SDimitry Andric using namespace llvm; 340b57cec5SDimitry Andric using namespace llvm::ELF; 350b57cec5SDimitry Andric using namespace llvm::object; 360b57cec5SDimitry Andric using namespace llvm::sys; 370b57cec5SDimitry Andric using namespace llvm::sys::fs; 380b57cec5SDimitry Andric using namespace llvm::support::endian; 395ffd83dbSDimitry Andric using namespace lld; 405ffd83dbSDimitry Andric using namespace lld::elf; 410b57cec5SDimitry Andric 425ffd83dbSDimitry Andric bool InputFile::isInGroup; 435ffd83dbSDimitry Andric uint32_t InputFile::nextGroupId; 445ffd83dbSDimitry Andric 45*04eeddc0SDimitry Andric SmallVector<std::unique_ptr<MemoryBuffer>> elf::memoryBuffers; 460eae32dcSDimitry Andric SmallVector<ArchiveFile *, 0> elf::archiveFiles; 470eae32dcSDimitry Andric SmallVector<BinaryFile *, 0> elf::binaryFiles; 480eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::bitcodeFiles; 490eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::lazyBitcodeFiles; 500eae32dcSDimitry Andric SmallVector<ELFFileBase *, 0> elf::objectFiles; 510eae32dcSDimitry Andric SmallVector<SharedFile *, 0> elf::sharedFiles; 525ffd83dbSDimitry Andric 535ffd83dbSDimitry Andric std::unique_ptr<TarWriter> elf::tar; 545ffd83dbSDimitry Andric 5585868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 565ffd83dbSDimitry Andric std::string lld::toString(const InputFile *f) { 5785868e8aSDimitry Andric if (!f) 5885868e8aSDimitry Andric return "<internal>"; 590b57cec5SDimitry Andric 6085868e8aSDimitry Andric if (f->toStringCache.empty()) { 6185868e8aSDimitry Andric if (f->archiveName.empty()) 620eae32dcSDimitry Andric f->toStringCache = f->getName(); 6385868e8aSDimitry Andric else 640eae32dcSDimitry Andric (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache); 6585868e8aSDimitry Andric } 660eae32dcSDimitry Andric return std::string(f->toStringCache); 6785868e8aSDimitry Andric } 6885868e8aSDimitry Andric 690b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) { 700b57cec5SDimitry Andric unsigned char size; 710b57cec5SDimitry Andric unsigned char endian; 720b57cec5SDimitry Andric std::tie(size, endian) = getElfArchType(mb.getBuffer()); 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric auto report = [&](StringRef msg) { 750b57cec5SDimitry Andric StringRef filename = mb.getBufferIdentifier(); 760b57cec5SDimitry Andric if (archiveName.empty()) 770b57cec5SDimitry Andric fatal(filename + ": " + msg); 780b57cec5SDimitry Andric else 790b57cec5SDimitry Andric fatal(archiveName + "(" + filename + "): " + msg); 800b57cec5SDimitry Andric }; 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric if (!mb.getBuffer().startswith(ElfMagic)) 830b57cec5SDimitry Andric report("not an ELF file"); 840b57cec5SDimitry Andric if (endian != ELFDATA2LSB && endian != ELFDATA2MSB) 850b57cec5SDimitry Andric report("corrupted ELF file: invalid data encoding"); 860b57cec5SDimitry Andric if (size != ELFCLASS32 && size != ELFCLASS64) 870b57cec5SDimitry Andric report("corrupted ELF file: invalid file class"); 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric size_t bufSize = mb.getBuffer().size(); 900b57cec5SDimitry Andric if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) || 910b57cec5SDimitry Andric (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr))) 920b57cec5SDimitry Andric report("corrupted ELF file: file is too short"); 930b57cec5SDimitry Andric 940b57cec5SDimitry Andric if (size == ELFCLASS32) 950b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 960b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m) 1000b57cec5SDimitry Andric : mb(m), groupId(nextGroupId), fileKind(k) { 1010b57cec5SDimitry Andric // All files within the same --{start,end}-group get the same group ID. 1020b57cec5SDimitry Andric // Otherwise, a new file will get a new group ID. 1030b57cec5SDimitry Andric if (!isInGroup) 1040b57cec5SDimitry Andric ++nextGroupId; 1050b57cec5SDimitry Andric } 1060b57cec5SDimitry Andric 1075ffd83dbSDimitry Andric Optional<MemoryBufferRef> elf::readFile(StringRef path) { 108e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files", path); 109e8d8bef9SDimitry Andric 1100b57cec5SDimitry Andric // The --chroot option changes our virtual root directory. 1110b57cec5SDimitry Andric // This is useful when you are dealing with files created by --reproduce. 1120b57cec5SDimitry Andric if (!config->chroot.empty() && path.startswith("/")) 113*04eeddc0SDimitry Andric path = saver().save(config->chroot + path); 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric log(path); 116e8d8bef9SDimitry Andric config->dependencyFiles.insert(llvm::CachedHashString(path)); 1170b57cec5SDimitry Andric 118fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 119fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false); 1200b57cec5SDimitry Andric if (auto ec = mbOrErr.getError()) { 1210b57cec5SDimitry Andric error("cannot open " + path + ": " + ec.message()); 1220b57cec5SDimitry Andric return None; 1230b57cec5SDimitry Andric } 1240b57cec5SDimitry Andric 125*04eeddc0SDimitry Andric MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef(); 126*04eeddc0SDimitry Andric memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership 1270b57cec5SDimitry Andric 1280b57cec5SDimitry Andric if (tar) 1290b57cec5SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 1300b57cec5SDimitry Andric return mbref; 1310b57cec5SDimitry Andric } 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric // All input object files must be for the same architecture 1340b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with 1350b57cec5SDimitry Andric // MIPS object files.) This function checks for that error. 1360b57cec5SDimitry Andric static bool isCompatible(InputFile *file) { 1370b57cec5SDimitry Andric if (!file->isElf() && !isa<BitcodeFile>(file)) 1380b57cec5SDimitry Andric return true; 1390b57cec5SDimitry Andric 1400b57cec5SDimitry Andric if (file->ekind == config->ekind && file->emachine == config->emachine) { 1410b57cec5SDimitry Andric if (config->emachine != EM_MIPS) 1420b57cec5SDimitry Andric return true; 1430b57cec5SDimitry Andric if (isMipsN32Abi(file) == config->mipsN32Abi) 1440b57cec5SDimitry Andric return true; 1450b57cec5SDimitry Andric } 1460b57cec5SDimitry Andric 1475ffd83dbSDimitry Andric StringRef target = 1485ffd83dbSDimitry Andric !config->bfdname.empty() ? config->bfdname : config->emulation; 1495ffd83dbSDimitry Andric if (!target.empty()) { 1505ffd83dbSDimitry Andric error(toString(file) + " is incompatible with " + target); 15185868e8aSDimitry Andric return false; 15285868e8aSDimitry Andric } 15385868e8aSDimitry Andric 1540b57cec5SDimitry Andric InputFile *existing; 1550b57cec5SDimitry Andric if (!objectFiles.empty()) 1560b57cec5SDimitry Andric existing = objectFiles[0]; 1570b57cec5SDimitry Andric else if (!sharedFiles.empty()) 1580b57cec5SDimitry Andric existing = sharedFiles[0]; 1595ffd83dbSDimitry Andric else if (!bitcodeFiles.empty()) 1600b57cec5SDimitry Andric existing = bitcodeFiles[0]; 1615ffd83dbSDimitry Andric else 1625ffd83dbSDimitry Andric llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to " 1635ffd83dbSDimitry Andric "determine target emulation"); 1640b57cec5SDimitry Andric 1650b57cec5SDimitry Andric error(toString(file) + " is incompatible with " + toString(existing)); 1660b57cec5SDimitry Andric return false; 1670b57cec5SDimitry Andric } 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) { 1700b57cec5SDimitry Andric if (!isCompatible(file)) 1710b57cec5SDimitry Andric return; 1720b57cec5SDimitry Andric 1730b57cec5SDimitry Andric // Binary file 1740b57cec5SDimitry Andric if (auto *f = dyn_cast<BinaryFile>(file)) { 1750b57cec5SDimitry Andric binaryFiles.push_back(f); 1760b57cec5SDimitry Andric f->parse(); 1770b57cec5SDimitry Andric return; 1780b57cec5SDimitry Andric } 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric // .a file 1810b57cec5SDimitry Andric if (auto *f = dyn_cast<ArchiveFile>(file)) { 1825ffd83dbSDimitry Andric archiveFiles.push_back(f); 1830b57cec5SDimitry Andric f->parse(); 1840b57cec5SDimitry Andric return; 1850b57cec5SDimitry Andric } 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric // Lazy object file 1880eae32dcSDimitry Andric if (file->lazy) { 1890eae32dcSDimitry Andric if (auto *f = dyn_cast<BitcodeFile>(file)) { 1900eae32dcSDimitry Andric lazyBitcodeFiles.push_back(f); 1910eae32dcSDimitry Andric f->parseLazy(); 1920eae32dcSDimitry Andric } else { 1930eae32dcSDimitry Andric cast<ObjFile<ELFT>>(file)->parseLazy(); 1940eae32dcSDimitry Andric } 1950b57cec5SDimitry Andric return; 1960b57cec5SDimitry Andric } 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric if (config->trace) 1990b57cec5SDimitry Andric message(toString(file)); 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric // .so file 2020b57cec5SDimitry Andric if (auto *f = dyn_cast<SharedFile>(file)) { 2030b57cec5SDimitry Andric f->parse<ELFT>(); 2040b57cec5SDimitry Andric return; 2050b57cec5SDimitry Andric } 2060b57cec5SDimitry Andric 2070b57cec5SDimitry Andric // LLVM bitcode file 2080b57cec5SDimitry Andric if (auto *f = dyn_cast<BitcodeFile>(file)) { 2090b57cec5SDimitry Andric bitcodeFiles.push_back(f); 2100b57cec5SDimitry Andric f->parse<ELFT>(); 2110b57cec5SDimitry Andric return; 2120b57cec5SDimitry Andric } 2130b57cec5SDimitry Andric 2140b57cec5SDimitry Andric // Regular object file 2150eae32dcSDimitry Andric objectFiles.push_back(cast<ELFFileBase>(file)); 2160b57cec5SDimitry Andric cast<ObjFile<ELFT>>(file)->parse(); 2170b57cec5SDimitry Andric } 2180b57cec5SDimitry Andric 2190b57cec5SDimitry Andric // Add symbols in File to the symbol table. 2205ffd83dbSDimitry Andric void elf::parseFile(InputFile *file) { 2210b57cec5SDimitry Andric switch (config->ekind) { 2220b57cec5SDimitry Andric case ELF32LEKind: 2230b57cec5SDimitry Andric doParseFile<ELF32LE>(file); 2240b57cec5SDimitry Andric return; 2250b57cec5SDimitry Andric case ELF32BEKind: 2260b57cec5SDimitry Andric doParseFile<ELF32BE>(file); 2270b57cec5SDimitry Andric return; 2280b57cec5SDimitry Andric case ELF64LEKind: 2290b57cec5SDimitry Andric doParseFile<ELF64LE>(file); 2300b57cec5SDimitry Andric return; 2310b57cec5SDimitry Andric case ELF64BEKind: 2320b57cec5SDimitry Andric doParseFile<ELF64BE>(file); 2330b57cec5SDimitry Andric return; 2340b57cec5SDimitry Andric default: 2350b57cec5SDimitry Andric llvm_unreachable("unknown ELFT"); 2360b57cec5SDimitry Andric } 2370b57cec5SDimitry Andric } 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location. 2400b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) { 2415ffd83dbSDimitry Andric std::string filename = std::string(path::filename(path)); 2420b57cec5SDimitry Andric std::string lineno = ":" + std::to_string(line); 2430b57cec5SDimitry Andric if (filename == path) 2440b57cec5SDimitry Andric return filename + lineno; 2450b57cec5SDimitry Andric return filename + lineno + " (" + path.str() + lineno + ")"; 2460b57cec5SDimitry Andric } 2470b57cec5SDimitry Andric 2480b57cec5SDimitry Andric template <class ELFT> 2490b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym, 2500b57cec5SDimitry Andric InputSectionBase &sec, uint64_t offset) { 2510b57cec5SDimitry Andric // In DWARF, functions and variables are stored to different places. 2520b57cec5SDimitry Andric // First, lookup a function for a given offset. 2530b57cec5SDimitry Andric if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset)) 2540b57cec5SDimitry Andric return createFileLineMsg(info->FileName, info->Line); 2550b57cec5SDimitry Andric 2560b57cec5SDimitry Andric // If it failed, lookup again as a variable. 2570b57cec5SDimitry Andric if (Optional<std::pair<std::string, unsigned>> fileLine = 2580b57cec5SDimitry Andric file.getVariableLoc(sym.getName())) 2590b57cec5SDimitry Andric return createFileLineMsg(fileLine->first, fileLine->second); 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric // File.sourceFile contains STT_FILE symbol, and that is a last resort. 2625ffd83dbSDimitry Andric return std::string(file.sourceFile); 2630b57cec5SDimitry Andric } 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec, 2660b57cec5SDimitry Andric uint64_t offset) { 2670b57cec5SDimitry Andric if (kind() != ObjKind) 2680b57cec5SDimitry Andric return ""; 2690b57cec5SDimitry Andric switch (config->ekind) { 2700b57cec5SDimitry Andric default: 2710b57cec5SDimitry Andric llvm_unreachable("Invalid kind"); 2720b57cec5SDimitry Andric case ELF32LEKind: 2730b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset); 2740b57cec5SDimitry Andric case ELF32BEKind: 2750b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset); 2760b57cec5SDimitry Andric case ELF64LEKind: 2770b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset); 2780b57cec5SDimitry Andric case ELF64BEKind: 2790b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset); 2800b57cec5SDimitry Andric } 2810b57cec5SDimitry Andric } 2820b57cec5SDimitry Andric 283e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const { 284e8d8bef9SDimitry Andric if (archiveName.empty()) 285e8d8bef9SDimitry Andric return getName(); 286e8d8bef9SDimitry Andric 287e8d8bef9SDimitry Andric if (nameForScriptCache.empty()) 288e8d8bef9SDimitry Andric nameForScriptCache = (archiveName + Twine(':') + getName()).str(); 289e8d8bef9SDimitry Andric 290e8d8bef9SDimitry Andric return nameForScriptCache; 291e8d8bef9SDimitry Andric } 292e8d8bef9SDimitry Andric 2935ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() { 2945ffd83dbSDimitry Andric llvm::call_once(initDwarf, [this]() { 2955ffd83dbSDimitry Andric dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 2965ffd83dbSDimitry Andric std::make_unique<LLDDwarfObj<ELFT>>(this), "", 2975ffd83dbSDimitry Andric [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 2985ffd83dbSDimitry Andric [&](Error warning) { 2995ffd83dbSDimitry Andric warn(getName() + ": " + toString(std::move(warning))); 3005ffd83dbSDimitry Andric })); 3015ffd83dbSDimitry Andric }); 3025ffd83dbSDimitry Andric 3035ffd83dbSDimitry Andric return dwarf.get(); 3040b57cec5SDimitry Andric } 3050b57cec5SDimitry Andric 3060b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data 3070b57cec5SDimitry Andric // object (variable, array, etc) definition. 3080b57cec5SDimitry Andric template <class ELFT> 3090b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>> 3100b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) { 3115ffd83dbSDimitry Andric return getDwarf()->getVariableLoc(name); 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric // Returns source line information for a given offset 3150b57cec5SDimitry Andric // using DWARF debug info. 3160b57cec5SDimitry Andric template <class ELFT> 3170b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s, 3180b57cec5SDimitry Andric uint64_t offset) { 3190b57cec5SDimitry Andric // Detect SectionIndex for specified section. 3200b57cec5SDimitry Andric uint64_t sectionIndex = object::SectionedAddress::UndefSection; 3210b57cec5SDimitry Andric ArrayRef<InputSectionBase *> sections = s->file->getSections(); 3220b57cec5SDimitry Andric for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) { 3230b57cec5SDimitry Andric if (s == sections[curIndex]) { 3240b57cec5SDimitry Andric sectionIndex = curIndex; 3250b57cec5SDimitry Andric break; 3260b57cec5SDimitry Andric } 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric 3295ffd83dbSDimitry Andric return getDwarf()->getDILineInfo(offset, sectionIndex); 3300b57cec5SDimitry Andric } 3310b57cec5SDimitry Andric 3320b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) { 3330b57cec5SDimitry Andric ekind = getELFKind(mb, ""); 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric switch (ekind) { 3360b57cec5SDimitry Andric case ELF32LEKind: 3370b57cec5SDimitry Andric init<ELF32LE>(); 3380b57cec5SDimitry Andric break; 3390b57cec5SDimitry Andric case ELF32BEKind: 3400b57cec5SDimitry Andric init<ELF32BE>(); 3410b57cec5SDimitry Andric break; 3420b57cec5SDimitry Andric case ELF64LEKind: 3430b57cec5SDimitry Andric init<ELF64LE>(); 3440b57cec5SDimitry Andric break; 3450b57cec5SDimitry Andric case ELF64BEKind: 3460b57cec5SDimitry Andric init<ELF64BE>(); 3470b57cec5SDimitry Andric break; 3480b57cec5SDimitry Andric default: 3490b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 3500b57cec5SDimitry Andric } 3510b57cec5SDimitry Andric } 3520b57cec5SDimitry Andric 3530b57cec5SDimitry Andric template <typename Elf_Shdr> 3540b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) { 3550b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) 3560b57cec5SDimitry Andric if (sec.sh_type == type) 3570b57cec5SDimitry Andric return &sec; 3580b57cec5SDimitry Andric return nullptr; 3590b57cec5SDimitry Andric } 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() { 3620b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 3630b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 3640b57cec5SDimitry Andric 3650b57cec5SDimitry Andric // Initialize trivial attributes. 3660b57cec5SDimitry Andric const ELFFile<ELFT> &obj = getObj<ELFT>(); 367e8d8bef9SDimitry Andric emachine = obj.getHeader().e_machine; 368e8d8bef9SDimitry Andric osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI]; 369e8d8bef9SDimitry Andric abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION]; 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this); 3720eae32dcSDimitry Andric elfShdrs = sections.data(); 3730eae32dcSDimitry Andric numELFShdrs = sections.size(); 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric // Find a symbol table. 3760b57cec5SDimitry Andric bool isDSO = 3770b57cec5SDimitry Andric (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object); 3780b57cec5SDimitry Andric const Elf_Shdr *symtabSec = 3790b57cec5SDimitry Andric findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB); 3800b57cec5SDimitry Andric 3810b57cec5SDimitry Andric if (!symtabSec) 3820b57cec5SDimitry Andric return; 3830b57cec5SDimitry Andric 3840b57cec5SDimitry Andric // Initialize members corresponding to a symbol table. 3850b57cec5SDimitry Andric firstGlobal = symtabSec->sh_info; 3860b57cec5SDimitry Andric 3870b57cec5SDimitry Andric ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this); 3880b57cec5SDimitry Andric if (firstGlobal == 0 || firstGlobal > eSyms.size()) 3890b57cec5SDimitry Andric fatal(toString(this) + ": invalid sh_info in symbol table"); 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric elfSyms = reinterpret_cast<const void *>(eSyms.data()); 3920eae32dcSDimitry Andric numELFSyms = uint32_t(eSyms.size()); 3930b57cec5SDimitry Andric stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this); 3940b57cec5SDimitry Andric } 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric template <class ELFT> 3970b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const { 3980b57cec5SDimitry Andric return CHECK( 399e8d8bef9SDimitry Andric this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable), 4000b57cec5SDimitry Andric this); 4010b57cec5SDimitry Andric } 4020b57cec5SDimitry Andric 4030b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) { 4040b57cec5SDimitry Andric // Read a section table. justSymbols is usually false. 4050b57cec5SDimitry Andric if (this->justSymbols) 4060b57cec5SDimitry Andric initializeJustSymbols(); 4070b57cec5SDimitry Andric else 4080b57cec5SDimitry Andric initializeSections(ignoreComdats); 4090b57cec5SDimitry Andric 4100b57cec5SDimitry Andric // Read a symbol table. 4110b57cec5SDimitry Andric initializeSymbols(); 4120b57cec5SDimitry Andric } 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups. 4150b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function 4160b57cec5SDimitry Andric // returns a group name. 4170b57cec5SDimitry Andric template <class ELFT> 4180b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections, 4190b57cec5SDimitry Andric const Elf_Shdr &sec) { 4200b57cec5SDimitry Andric typename ELFT::SymRange symbols = this->getELFSyms<ELFT>(); 4210b57cec5SDimitry Andric if (sec.sh_info >= symbols.size()) 4220b57cec5SDimitry Andric fatal(toString(this) + ": invalid symbol index"); 4230b57cec5SDimitry Andric const typename ELFT::Sym &sym = symbols[sec.sh_info]; 424349cc55cSDimitry Andric return CHECK(sym.getName(this->stringTable), this); 4250b57cec5SDimitry Andric } 4260b57cec5SDimitry Andric 42785868e8aSDimitry Andric template <class ELFT> 42885868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) { 4290b57cec5SDimitry Andric // On a regular link we don't merge sections if -O0 (default is -O1). This 4300b57cec5SDimitry Andric // sometimes makes the linker significantly faster, although the output will 4310b57cec5SDimitry Andric // be bigger. 4320b57cec5SDimitry Andric // 4330b57cec5SDimitry Andric // Doing the same for -r would create a problem as it would combine sections 4340b57cec5SDimitry Andric // with different sh_entsize. One option would be to just copy every SHF_MERGE 4350b57cec5SDimitry Andric // section as is to the output. While this would produce a valid ELF file with 4360b57cec5SDimitry Andric // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when 4370b57cec5SDimitry Andric // they see two .debug_str. We could have separate logic for combining 4380b57cec5SDimitry Andric // SHF_MERGE sections based both on their name and sh_entsize, but that seems 4390b57cec5SDimitry Andric // to be more trouble than it is worth. Instead, we just use the regular (-O1) 4400b57cec5SDimitry Andric // logic for -r. 4410b57cec5SDimitry Andric if (config->optimize == 0 && !config->relocatable) 4420b57cec5SDimitry Andric return false; 4430b57cec5SDimitry Andric 4440b57cec5SDimitry Andric // A mergeable section with size 0 is useless because they don't have 4450b57cec5SDimitry Andric // any data to merge. A mergeable string section with size 0 can be 4460b57cec5SDimitry Andric // argued as invalid because it doesn't end with a null character. 4470b57cec5SDimitry Andric // We'll avoid a mess by handling them as if they were non-mergeable. 4480b57cec5SDimitry Andric if (sec.sh_size == 0) 4490b57cec5SDimitry Andric return false; 4500b57cec5SDimitry Andric 4510b57cec5SDimitry Andric // Check for sh_entsize. The ELF spec is not clear about the zero 4520b57cec5SDimitry Andric // sh_entsize. It says that "the member [sh_entsize] contains 0 if 4530b57cec5SDimitry Andric // the section does not hold a table of fixed-size entries". We know 4540b57cec5SDimitry Andric // that Rust 1.13 produces a string mergeable section with a zero 4550b57cec5SDimitry Andric // sh_entsize. Here we just accept it rather than being picky about it. 4560b57cec5SDimitry Andric uint64_t entSize = sec.sh_entsize; 4570b57cec5SDimitry Andric if (entSize == 0) 4580b57cec5SDimitry Andric return false; 4590b57cec5SDimitry Andric if (sec.sh_size % entSize) 46085868e8aSDimitry Andric fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" + 46185868e8aSDimitry Andric Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" + 46285868e8aSDimitry Andric Twine(entSize) + ")"); 4630b57cec5SDimitry Andric 4645ffd83dbSDimitry Andric if (sec.sh_flags & SHF_WRITE) 46585868e8aSDimitry Andric fatal(toString(this) + ":(" + name + 46685868e8aSDimitry Andric "): writable SHF_MERGE section is not supported"); 4670b57cec5SDimitry Andric 4680b57cec5SDimitry Andric return true; 4690b57cec5SDimitry Andric } 4700b57cec5SDimitry Andric 4710b57cec5SDimitry Andric // This is for --just-symbols. 4720b57cec5SDimitry Andric // 4730b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your 4740b57cec5SDimitry Andric // output against other existing program, so that if you load both your 4750b57cec5SDimitry Andric // program and the other program into memory, your output can refer the 4760b57cec5SDimitry Andric // other program's symbols. 4770b57cec5SDimitry Andric // 4780b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is 4790b57cec5SDimitry Andric // initialized with null pointers. 4800b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() { 4810eae32dcSDimitry Andric sections.resize(numELFShdrs); 4820b57cec5SDimitry Andric } 4830b57cec5SDimitry Andric 4840b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the 4850b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This 4860b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking 4870b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension 4880b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently 4890b57cec5SDimitry Andric // unique to LLVM and lld. 4900b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) { 4910b57cec5SDimitry Andric if (!config->dependentLibraries) 4920b57cec5SDimitry Andric return; 4930b57cec5SDimitry Andric if (fs::exists(specifier)) 4940b57cec5SDimitry Andric driver->addFile(specifier, /*withLOption=*/false); 4950b57cec5SDimitry Andric else if (Optional<std::string> s = findFromSearchPaths(specifier)) 4960b57cec5SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 4970b57cec5SDimitry Andric else if (Optional<std::string> s = searchLibraryBaseName(specifier)) 4980b57cec5SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 4990b57cec5SDimitry Andric else 5000b57cec5SDimitry Andric error(toString(f) + 5010b57cec5SDimitry Andric ": unable to find library from dependent library specifier: " + 5020b57cec5SDimitry Andric specifier); 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric 505480093f4SDimitry Andric // Record the membership of a section group so that in the garbage collection 506480093f4SDimitry Andric // pass, section group members are kept or discarded as a unit. 507480093f4SDimitry Andric template <class ELFT> 508480093f4SDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections, 509480093f4SDimitry Andric ArrayRef<typename ELFT::Word> entries) { 510480093f4SDimitry Andric bool hasAlloc = false; 511480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 512480093f4SDimitry Andric if (index >= sections.size()) 513480093f4SDimitry Andric return; 514480093f4SDimitry Andric if (InputSectionBase *s = sections[index]) 515480093f4SDimitry Andric if (s != &InputSection::discarded && s->flags & SHF_ALLOC) 516480093f4SDimitry Andric hasAlloc = true; 517480093f4SDimitry Andric } 518480093f4SDimitry Andric 519480093f4SDimitry Andric // If any member has the SHF_ALLOC flag, the whole group is subject to garbage 520480093f4SDimitry Andric // collection. See the comment in markLive(). This rule retains .debug_types 521480093f4SDimitry Andric // and .rela.debug_types. 522480093f4SDimitry Andric if (!hasAlloc) 523480093f4SDimitry Andric return; 524480093f4SDimitry Andric 525480093f4SDimitry Andric // Connect the members in a circular doubly-linked list via 526480093f4SDimitry Andric // nextInSectionGroup. 527480093f4SDimitry Andric InputSectionBase *head; 528480093f4SDimitry Andric InputSectionBase *prev = nullptr; 529480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 530480093f4SDimitry Andric InputSectionBase *s = sections[index]; 531480093f4SDimitry Andric if (!s || s == &InputSection::discarded) 532480093f4SDimitry Andric continue; 533480093f4SDimitry Andric if (prev) 534480093f4SDimitry Andric prev->nextInSectionGroup = s; 535480093f4SDimitry Andric else 536480093f4SDimitry Andric head = s; 537480093f4SDimitry Andric prev = s; 538480093f4SDimitry Andric } 539480093f4SDimitry Andric if (prev) 540480093f4SDimitry Andric prev->nextInSectionGroup = head; 541480093f4SDimitry Andric } 542480093f4SDimitry Andric 5430b57cec5SDimitry Andric template <class ELFT> 5440b57cec5SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats) { 5450b57cec5SDimitry Andric const ELFFile<ELFT> &obj = this->getObj(); 5460b57cec5SDimitry Andric 5470eae32dcSDimitry Andric ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>(); 548349cc55cSDimitry Andric StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this); 5490b57cec5SDimitry Andric uint64_t size = objSections.size(); 5500b57cec5SDimitry Andric this->sections.resize(size); 5510b57cec5SDimitry Andric 552480093f4SDimitry Andric std::vector<ArrayRef<Elf_Word>> selectedGroups; 553480093f4SDimitry Andric 554*04eeddc0SDimitry Andric for (size_t i = 0; i != size; ++i) { 5550b57cec5SDimitry Andric if (this->sections[i] == &InputSection::discarded) 5560b57cec5SDimitry Andric continue; 5570b57cec5SDimitry Andric const Elf_Shdr &sec = objSections[i]; 5580b57cec5SDimitry Andric 5590b57cec5SDimitry Andric // SHF_EXCLUDE'ed sections are discarded by the linker. However, 5600b57cec5SDimitry Andric // if -r is given, we'll let the final link discard such sections. 5610b57cec5SDimitry Andric // This is compatible with GNU. 5620b57cec5SDimitry Andric if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) { 5630eae32dcSDimitry Andric if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE) 5640eae32dcSDimitry Andric cgProfileSectionIndex = i; 5650b57cec5SDimitry Andric if (sec.sh_type == SHT_LLVM_ADDRSIG) { 5660b57cec5SDimitry Andric // We ignore the address-significance table if we know that the object 5670b57cec5SDimitry Andric // file was created by objcopy or ld -r. This is because these tools 5680b57cec5SDimitry Andric // will reorder the symbols in the symbol table, invalidating the data 5690b57cec5SDimitry Andric // in the address-significance table, which refers to symbols by index. 5700b57cec5SDimitry Andric if (sec.sh_link != 0) 5710b57cec5SDimitry Andric this->addrsigSec = &sec; 5720b57cec5SDimitry Andric else if (config->icf == ICFLevel::Safe) 573fe6060f1SDimitry Andric warn(toString(this) + 574fe6060f1SDimitry Andric ": --icf=safe conservatively ignores " 575fe6060f1SDimitry Andric "SHT_LLVM_ADDRSIG [index " + 576fe6060f1SDimitry Andric Twine(i) + 577fe6060f1SDimitry Andric "] with sh_link=0 " 578fe6060f1SDimitry Andric "(likely created using objcopy or ld -r)"); 5790b57cec5SDimitry Andric } 5800b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 5810b57cec5SDimitry Andric continue; 5820b57cec5SDimitry Andric } 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric switch (sec.sh_type) { 5850b57cec5SDimitry Andric case SHT_GROUP: { 5860b57cec5SDimitry Andric // De-duplicate section groups by their signatures. 5870b57cec5SDimitry Andric StringRef signature = getShtGroupSignature(objSections, sec); 5880b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 5890b57cec5SDimitry Andric 5900b57cec5SDimitry Andric ArrayRef<Elf_Word> entries = 591e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this); 5920b57cec5SDimitry Andric if (entries.empty()) 5930b57cec5SDimitry Andric fatal(toString(this) + ": empty SHT_GROUP"); 5940b57cec5SDimitry Andric 595fe6060f1SDimitry Andric Elf_Word flag = entries[0]; 596fe6060f1SDimitry Andric if (flag && flag != GRP_COMDAT) 5970b57cec5SDimitry Andric fatal(toString(this) + ": unsupported SHT_GROUP format"); 5980b57cec5SDimitry Andric 599fe6060f1SDimitry Andric bool keepGroup = 600fe6060f1SDimitry Andric (flag & GRP_COMDAT) == 0 || ignoreComdats || 6010b57cec5SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this) 6020b57cec5SDimitry Andric .second; 603fe6060f1SDimitry Andric if (keepGroup) { 6040b57cec5SDimitry Andric if (config->relocatable) 605349cc55cSDimitry Andric this->sections[i] = createInputSection(i, sec, shstrtab); 606480093f4SDimitry Andric selectedGroups.push_back(entries); 6070b57cec5SDimitry Andric continue; 6080b57cec5SDimitry Andric } 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric // Otherwise, discard group members. 6110b57cec5SDimitry Andric for (uint32_t secIndex : entries.slice(1)) { 6120b57cec5SDimitry Andric if (secIndex >= size) 6130b57cec5SDimitry Andric fatal(toString(this) + 6140b57cec5SDimitry Andric ": invalid section index in group: " + Twine(secIndex)); 6150b57cec5SDimitry Andric this->sections[secIndex] = &InputSection::discarded; 6160b57cec5SDimitry Andric } 6170b57cec5SDimitry Andric break; 6180b57cec5SDimitry Andric } 6190b57cec5SDimitry Andric case SHT_SYMTAB_SHNDX: 6200b57cec5SDimitry Andric shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this); 6210b57cec5SDimitry Andric break; 6220b57cec5SDimitry Andric case SHT_SYMTAB: 6230b57cec5SDimitry Andric case SHT_STRTAB: 6245ffd83dbSDimitry Andric case SHT_REL: 6255ffd83dbSDimitry Andric case SHT_RELA: 6260b57cec5SDimitry Andric case SHT_NULL: 6270b57cec5SDimitry Andric break; 6280b57cec5SDimitry Andric default: 629349cc55cSDimitry Andric this->sections[i] = createInputSection(i, sec, shstrtab); 6300b57cec5SDimitry Andric } 63185868e8aSDimitry Andric } 63285868e8aSDimitry Andric 6335ffd83dbSDimitry Andric // We have a second loop. It is used to: 6345ffd83dbSDimitry Andric // 1) handle SHF_LINK_ORDER sections. 6355ffd83dbSDimitry Andric // 2) create SHT_REL[A] sections. In some cases the section header index of a 6365ffd83dbSDimitry Andric // relocation section may be smaller than that of the relocated section. In 6375ffd83dbSDimitry Andric // such cases, the relocation section would attempt to reference a target 6385ffd83dbSDimitry Andric // section that has not yet been created. For simplicity, delay creation of 6395ffd83dbSDimitry Andric // relocation sections until now. 640*04eeddc0SDimitry Andric for (size_t i = 0; i != size; ++i) { 64185868e8aSDimitry Andric if (this->sections[i] == &InputSection::discarded) 64285868e8aSDimitry Andric continue; 64385868e8aSDimitry Andric const Elf_Shdr &sec = objSections[i]; 6445ffd83dbSDimitry Andric 645*04eeddc0SDimitry Andric if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) { 646*04eeddc0SDimitry Andric // Find a relocation target section and associate this section with that. 647*04eeddc0SDimitry Andric // Target may have been discarded if it is in a different section group 648*04eeddc0SDimitry Andric // and the group is discarded, even though it's a violation of the spec. 649*04eeddc0SDimitry Andric // We handle that situation gracefully by discarding dangling relocation 650*04eeddc0SDimitry Andric // sections. 651*04eeddc0SDimitry Andric const uint32_t info = sec.sh_info; 652*04eeddc0SDimitry Andric InputSectionBase *s = getRelocTarget(i, sec, info); 653*04eeddc0SDimitry Andric if (!s) 654*04eeddc0SDimitry Andric continue; 655*04eeddc0SDimitry Andric 656*04eeddc0SDimitry Andric // ELF spec allows mergeable sections with relocations, but they are rare, 657*04eeddc0SDimitry Andric // and it is in practice hard to merge such sections by contents, because 658*04eeddc0SDimitry Andric // applying relocations at end of linking changes section contents. So, we 659*04eeddc0SDimitry Andric // simply handle such sections as non-mergeable ones. Degrading like this 660*04eeddc0SDimitry Andric // is acceptable because section merging is optional. 661*04eeddc0SDimitry Andric if (auto *ms = dyn_cast<MergeInputSection>(s)) { 662*04eeddc0SDimitry Andric s = make<InputSection>(ms->file, ms->flags, ms->type, ms->alignment, 663*04eeddc0SDimitry Andric ms->data(), ms->name); 664*04eeddc0SDimitry Andric sections[info] = s; 665*04eeddc0SDimitry Andric } 666*04eeddc0SDimitry Andric 667*04eeddc0SDimitry Andric if (s->relSecIdx != 0) 668*04eeddc0SDimitry Andric error( 669*04eeddc0SDimitry Andric toString(s) + 670*04eeddc0SDimitry Andric ": multiple relocation sections to one section are not supported"); 671*04eeddc0SDimitry Andric s->relSecIdx = i; 672*04eeddc0SDimitry Andric 673*04eeddc0SDimitry Andric // Relocation sections are usually removed from the output, so return 674*04eeddc0SDimitry Andric // `nullptr` for the normal case. However, if -r or --emit-relocs is 675*04eeddc0SDimitry Andric // specified, we need to copy them to the output. (Some post link analysis 676*04eeddc0SDimitry Andric // tools specify --emit-relocs to obtain the information.) 677*04eeddc0SDimitry Andric if (config->copyRelocs) { 678*04eeddc0SDimitry Andric auto *isec = make<InputSection>( 679*04eeddc0SDimitry Andric *this, sec, check(obj.getSectionName(sec, shstrtab))); 680*04eeddc0SDimitry Andric // If the relocated section is discarded (due to /DISCARD/ or 681*04eeddc0SDimitry Andric // --gc-sections), the relocation section should be discarded as well. 682*04eeddc0SDimitry Andric s->dependentSections.push_back(isec); 683*04eeddc0SDimitry Andric sections[i] = isec; 684*04eeddc0SDimitry Andric } 685*04eeddc0SDimitry Andric continue; 686*04eeddc0SDimitry Andric } 6875ffd83dbSDimitry Andric 688e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have 689e8d8bef9SDimitry Andric // the flag. 690*04eeddc0SDimitry Andric if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER)) 69185868e8aSDimitry Andric continue; 6920b57cec5SDimitry Andric 6930b57cec5SDimitry Andric InputSectionBase *linkSec = nullptr; 694*04eeddc0SDimitry Andric if (sec.sh_link < size) 6950b57cec5SDimitry Andric linkSec = this->sections[sec.sh_link]; 6960b57cec5SDimitry Andric if (!linkSec) 69785868e8aSDimitry Andric fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link)); 6980b57cec5SDimitry Andric 699e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section is discarded if its linked-to section is 700e8d8bef9SDimitry Andric // discarded. 7010b57cec5SDimitry Andric InputSection *isec = cast<InputSection>(this->sections[i]); 7020b57cec5SDimitry Andric linkSec->dependentSections.push_back(isec); 7030b57cec5SDimitry Andric if (!isa<InputSection>(linkSec)) 7040b57cec5SDimitry Andric error("a section " + isec->name + 70585868e8aSDimitry Andric " with SHF_LINK_ORDER should not refer a non-regular section: " + 7060b57cec5SDimitry Andric toString(linkSec)); 7070b57cec5SDimitry Andric } 708480093f4SDimitry Andric 709480093f4SDimitry Andric for (ArrayRef<Elf_Word> entries : selectedGroups) 710480093f4SDimitry Andric handleSectionGroup<ELFT>(this->sections, entries); 7110b57cec5SDimitry Andric } 7120b57cec5SDimitry Andric 7130b57cec5SDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD 7140b57cec5SDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how 7150b57cec5SDimitry Andric // the input objects have been compiled. 7160b57cec5SDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes, 7170b57cec5SDimitry Andric const InputFile *f) { 7185ffd83dbSDimitry Andric Optional<unsigned> attr = 7195ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args); 7205ffd83dbSDimitry Andric if (!attr.hasValue()) 7210b57cec5SDimitry Andric // If an ABI tag isn't present then it is implicitly given the value of 0 7220b57cec5SDimitry Andric // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files, 7230b57cec5SDimitry Andric // including some in glibc that don't use FP args (and should have value 3) 7240b57cec5SDimitry Andric // don't have the attribute so we do not consider an implicit value of 0 7250b57cec5SDimitry Andric // as a clash. 7260b57cec5SDimitry Andric return; 7270b57cec5SDimitry Andric 7285ffd83dbSDimitry Andric unsigned vfpArgs = attr.getValue(); 7290b57cec5SDimitry Andric ARMVFPArgKind arg; 7300b57cec5SDimitry Andric switch (vfpArgs) { 7310b57cec5SDimitry Andric case ARMBuildAttrs::BaseAAPCS: 7320b57cec5SDimitry Andric arg = ARMVFPArgKind::Base; 7330b57cec5SDimitry Andric break; 7340b57cec5SDimitry Andric case ARMBuildAttrs::HardFPAAPCS: 7350b57cec5SDimitry Andric arg = ARMVFPArgKind::VFP; 7360b57cec5SDimitry Andric break; 7370b57cec5SDimitry Andric case ARMBuildAttrs::ToolChainFPPCS: 7380b57cec5SDimitry Andric // Tool chain specific convention that conforms to neither AAPCS variant. 7390b57cec5SDimitry Andric arg = ARMVFPArgKind::ToolChain; 7400b57cec5SDimitry Andric break; 7410b57cec5SDimitry Andric case ARMBuildAttrs::CompatibleFPAAPCS: 7420b57cec5SDimitry Andric // Object compatible with all conventions. 7430b57cec5SDimitry Andric return; 7440b57cec5SDimitry Andric default: 7450b57cec5SDimitry Andric error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs)); 7460b57cec5SDimitry Andric return; 7470b57cec5SDimitry Andric } 7480b57cec5SDimitry Andric // Follow ld.bfd and error if there is a mix of calling conventions. 7490b57cec5SDimitry Andric if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default) 7500b57cec5SDimitry Andric error(toString(f) + ": incompatible Tag_ABI_VFP_args"); 7510b57cec5SDimitry Andric else 7520b57cec5SDimitry Andric config->armVFPArgs = arg; 7530b57cec5SDimitry Andric } 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric // The ARM support in lld makes some use of instructions that are not available 7560b57cec5SDimitry Andric // on all ARM architectures. Namely: 7570b57cec5SDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state. 7580b57cec5SDimitry Andric // - Use of the extended Thumb branch encoding in relocation. 7590b57cec5SDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks. 7600b57cec5SDimitry Andric // The ARM Attributes section contains information about the architecture chosen 7610b57cec5SDimitry Andric // at compile time. We follow the convention that if at least one input object 7620b57cec5SDimitry Andric // is compiled with an architecture that supports these features then lld is 7630b57cec5SDimitry Andric // permitted to use them. 7640b57cec5SDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) { 7655ffd83dbSDimitry Andric Optional<unsigned> attr = 7665ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 7675ffd83dbSDimitry Andric if (!attr.hasValue()) 7680b57cec5SDimitry Andric return; 7695ffd83dbSDimitry Andric auto arch = attr.getValue(); 7700b57cec5SDimitry Andric switch (arch) { 7710b57cec5SDimitry Andric case ARMBuildAttrs::Pre_v4: 7720b57cec5SDimitry Andric case ARMBuildAttrs::v4: 7730b57cec5SDimitry Andric case ARMBuildAttrs::v4T: 7740b57cec5SDimitry Andric // Architectures prior to v5 do not support BLX instruction 7750b57cec5SDimitry Andric break; 7760b57cec5SDimitry Andric case ARMBuildAttrs::v5T: 7770b57cec5SDimitry Andric case ARMBuildAttrs::v5TE: 7780b57cec5SDimitry Andric case ARMBuildAttrs::v5TEJ: 7790b57cec5SDimitry Andric case ARMBuildAttrs::v6: 7800b57cec5SDimitry Andric case ARMBuildAttrs::v6KZ: 7810b57cec5SDimitry Andric case ARMBuildAttrs::v6K: 7820b57cec5SDimitry Andric config->armHasBlx = true; 7830b57cec5SDimitry Andric // Architectures used in pre-Cortex processors do not support 7840b57cec5SDimitry Andric // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 7850b57cec5SDimitry Andric // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 7860b57cec5SDimitry Andric break; 7870b57cec5SDimitry Andric default: 7880b57cec5SDimitry Andric // All other Architectures have BLX and extended branch encoding 7890b57cec5SDimitry Andric config->armHasBlx = true; 7900b57cec5SDimitry Andric config->armJ1J2BranchEncoding = true; 7910b57cec5SDimitry Andric if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M) 7920b57cec5SDimitry Andric // All Architectures used in Cortex processors with the exception 7930b57cec5SDimitry Andric // of v6-M and v6S-M have the MOVT and MOVW instructions. 7940b57cec5SDimitry Andric config->armHasMovtMovw = true; 7950b57cec5SDimitry Andric break; 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric } 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control 8000b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that 8010b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it. 8020b57cec5SDimitry Andric // 8030b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this 8040b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a 8050b57cec5SDimitry Andric // .note.gnu.property section. 8060b57cec5SDimitry Andric // 8070b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists 8080b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a 8090b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps 8100b57cec5SDimitry Andric // the ABI is unnecessarily complicated. 811e8d8bef9SDimitry Andric template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) { 8120b57cec5SDimitry Andric using Elf_Nhdr = typename ELFT::Nhdr; 8130b57cec5SDimitry Andric using Elf_Note = typename ELFT::Note; 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric uint32_t featuresSet = 0; 816e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = sec.data(); 817e8d8bef9SDimitry Andric auto reportFatal = [&](const uint8_t *place, const char *msg) { 818e8d8bef9SDimitry Andric fatal(toString(sec.file) + ":(" + sec.name + "+0x" + 819e8d8bef9SDimitry Andric Twine::utohexstr(place - sec.data().data()) + "): " + msg); 820e8d8bef9SDimitry Andric }; 8210b57cec5SDimitry Andric while (!data.empty()) { 8220b57cec5SDimitry Andric // Read one NOTE record. 8230b57cec5SDimitry Andric auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data()); 824e8d8bef9SDimitry Andric if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize()) 825e8d8bef9SDimitry Andric reportFatal(data.data(), "data is too short"); 8260b57cec5SDimitry Andric 8270b57cec5SDimitry Andric Elf_Note note(*nhdr); 8280b57cec5SDimitry Andric if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") { 8290b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8300b57cec5SDimitry Andric continue; 8310b57cec5SDimitry Andric } 8320b57cec5SDimitry Andric 8330b57cec5SDimitry Andric uint32_t featureAndType = config->emachine == EM_AARCH64 8340b57cec5SDimitry Andric ? GNU_PROPERTY_AARCH64_FEATURE_1_AND 8350b57cec5SDimitry Andric : GNU_PROPERTY_X86_FEATURE_1_AND; 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric // Read a body of a NOTE record, which consists of type-length-value fields. 8380b57cec5SDimitry Andric ArrayRef<uint8_t> desc = note.getDesc(); 8390b57cec5SDimitry Andric while (!desc.empty()) { 840e8d8bef9SDimitry Andric const uint8_t *place = desc.data(); 8410b57cec5SDimitry Andric if (desc.size() < 8) 842e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 843e8d8bef9SDimitry Andric uint32_t type = read32<ELFT::TargetEndianness>(desc.data()); 844e8d8bef9SDimitry Andric uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4); 845e8d8bef9SDimitry Andric desc = desc.slice(8); 846e8d8bef9SDimitry Andric if (desc.size() < size) 847e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 8480b57cec5SDimitry Andric 8490b57cec5SDimitry Andric if (type == featureAndType) { 8500b57cec5SDimitry Andric // We found a FEATURE_1_AND field. There may be more than one of these 851480093f4SDimitry Andric // in a .note.gnu.property section, for a relocatable object we 8520b57cec5SDimitry Andric // accumulate the bits set. 853e8d8bef9SDimitry Andric if (size < 4) 854e8d8bef9SDimitry Andric reportFatal(place, "FEATURE_1_AND entry is too short"); 855e8d8bef9SDimitry Andric featuresSet |= read32<ELFT::TargetEndianness>(desc.data()); 8560b57cec5SDimitry Andric } 8570b57cec5SDimitry Andric 858e8d8bef9SDimitry Andric // Padding is present in the note descriptor, if necessary. 859e8d8bef9SDimitry Andric desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size)); 8600b57cec5SDimitry Andric } 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric // Go to next NOTE record to look for more FEATURE_1_AND descriptions. 8630b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8640b57cec5SDimitry Andric } 8650b57cec5SDimitry Andric 8660b57cec5SDimitry Andric return featuresSet; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric template <class ELFT> 870*04eeddc0SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, 871*04eeddc0SDimitry Andric const Elf_Shdr &sec, 872*04eeddc0SDimitry Andric uint32_t info) { 873349cc55cSDimitry Andric if (info < this->sections.size()) { 874349cc55cSDimitry Andric InputSectionBase *target = this->sections[info]; 8750b57cec5SDimitry Andric 8760b57cec5SDimitry Andric // Strictly speaking, a relocation section must be included in the 8770b57cec5SDimitry Andric // group of the section it relocates. However, LLVM 3.3 and earlier 8780b57cec5SDimitry Andric // would fail to do so, so we gracefully handle that case. 8790b57cec5SDimitry Andric if (target == &InputSection::discarded) 8800b57cec5SDimitry Andric return nullptr; 8810b57cec5SDimitry Andric 882349cc55cSDimitry Andric if (target != nullptr) 8830b57cec5SDimitry Andric return target; 8840b57cec5SDimitry Andric } 8850b57cec5SDimitry Andric 886*04eeddc0SDimitry Andric error(toString(this) + Twine(": relocation section (index ") + Twine(idx) + 887*04eeddc0SDimitry Andric ") has invalid sh_info (" + Twine(info) + ")"); 888349cc55cSDimitry Andric return nullptr; 889349cc55cSDimitry Andric } 890349cc55cSDimitry Andric 8910b57cec5SDimitry Andric template <class ELFT> 892349cc55cSDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx, 893349cc55cSDimitry Andric const Elf_Shdr &sec, 894349cc55cSDimitry Andric StringRef shstrtab) { 895349cc55cSDimitry Andric StringRef name = CHECK(getObj().getSectionName(sec, shstrtab), this); 8960b57cec5SDimitry Andric 897e8d8bef9SDimitry Andric if (config->emachine == EM_ARM && sec.sh_type == SHT_ARM_ATTRIBUTES) { 8980b57cec5SDimitry Andric ARMAttributeParser attributes; 899e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 9005ffd83dbSDimitry Andric if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind 9015ffd83dbSDimitry Andric ? support::little 9025ffd83dbSDimitry Andric : support::big)) { 9035ffd83dbSDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 9045ffd83dbSDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 905e8d8bef9SDimitry Andric } else { 9060b57cec5SDimitry Andric updateSupportedARMFeatures(attributes); 9070b57cec5SDimitry Andric updateARMVFPArgs(attributes, this); 9080b57cec5SDimitry Andric 9090b57cec5SDimitry Andric // FIXME: Retain the first attribute section we see. The eglibc ARM 9100b57cec5SDimitry Andric // dynamic loaders require the presence of an attribute section for dlopen 911e8d8bef9SDimitry Andric // to work. In a full implementation we would merge all attribute 912e8d8bef9SDimitry Andric // sections. 913e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 914*04eeddc0SDimitry Andric in.attributes = std::make_unique<InputSection>(*this, sec, name); 915*04eeddc0SDimitry Andric return in.attributes.get(); 9160b57cec5SDimitry Andric } 9170b57cec5SDimitry Andric return &InputSection::discarded; 9180b57cec5SDimitry Andric } 919e8d8bef9SDimitry Andric } 920e8d8bef9SDimitry Andric 921e8d8bef9SDimitry Andric if (config->emachine == EM_RISCV && sec.sh_type == SHT_RISCV_ATTRIBUTES) { 922e8d8bef9SDimitry Andric RISCVAttributeParser attributes; 923e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 924e8d8bef9SDimitry Andric if (Error e = attributes.parse(contents, support::little)) { 925e8d8bef9SDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 926e8d8bef9SDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 927e8d8bef9SDimitry Andric } else { 928e8d8bef9SDimitry Andric // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is 929e8d8bef9SDimitry Andric // present. 930e8d8bef9SDimitry Andric 931e8d8bef9SDimitry Andric // FIXME: Retain the first attribute section we see. Tools such as 932e8d8bef9SDimitry Andric // llvm-objdump make use of the attribute section to determine which 933e8d8bef9SDimitry Andric // standard extensions to enable. In a full implementation we would merge 934e8d8bef9SDimitry Andric // all attribute sections. 935e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 936*04eeddc0SDimitry Andric in.attributes = std::make_unique<InputSection>(*this, sec, name); 937*04eeddc0SDimitry Andric return in.attributes.get(); 938e8d8bef9SDimitry Andric } 939e8d8bef9SDimitry Andric return &InputSection::discarded; 940e8d8bef9SDimitry Andric } 941e8d8bef9SDimitry Andric } 942e8d8bef9SDimitry Andric 943*04eeddc0SDimitry Andric if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) { 9440b57cec5SDimitry Andric ArrayRef<char> data = 945e8d8bef9SDimitry Andric CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this); 9460b57cec5SDimitry Andric if (!data.empty() && data.back() != '\0') { 9470b57cec5SDimitry Andric error(toString(this) + 9480b57cec5SDimitry Andric ": corrupted dependent libraries section (unterminated string): " + 9490b57cec5SDimitry Andric name); 9500b57cec5SDimitry Andric return &InputSection::discarded; 9510b57cec5SDimitry Andric } 9520b57cec5SDimitry Andric for (const char *d = data.begin(), *e = data.end(); d < e;) { 9530b57cec5SDimitry Andric StringRef s(d); 9540b57cec5SDimitry Andric addDependentLibrary(s, this); 9550b57cec5SDimitry Andric d += s.size() + 1; 9560b57cec5SDimitry Andric } 9570b57cec5SDimitry Andric return &InputSection::discarded; 9580b57cec5SDimitry Andric } 9590b57cec5SDimitry Andric 9600eae32dcSDimitry Andric if (name.startswith(".n")) { 9610b57cec5SDimitry Andric // The GNU linker uses .note.GNU-stack section as a marker indicating 9620b57cec5SDimitry Andric // that the code in the object file does not expect that the stack is 9630b57cec5SDimitry Andric // executable (in terms of NX bit). If all input files have the marker, 9640b57cec5SDimitry Andric // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 9650b57cec5SDimitry Andric // make the stack non-executable. Most object files have this section as 9660b57cec5SDimitry Andric // of 2017. 9670b57cec5SDimitry Andric // 9680b57cec5SDimitry Andric // But making the stack non-executable is a norm today for security 9690b57cec5SDimitry Andric // reasons. Failure to do so may result in a serious security issue. 9700b57cec5SDimitry Andric // Therefore, we make LLD always add PT_GNU_STACK unless it is 9710b57cec5SDimitry Andric // explicitly told to do otherwise (by -z execstack). Because the stack 9720b57cec5SDimitry Andric // executable-ness is controlled solely by command line options, 9730b57cec5SDimitry Andric // .note.GNU-stack sections are simply ignored. 9740b57cec5SDimitry Andric if (name == ".note.GNU-stack") 9750b57cec5SDimitry Andric return &InputSection::discarded; 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric // Object files that use processor features such as Intel Control-Flow 9780b57cec5SDimitry Andric // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a 9790b57cec5SDimitry Andric // .note.gnu.property section containing a bitfield of feature bits like the 9800b57cec5SDimitry Andric // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag. 9810b57cec5SDimitry Andric // 9820b57cec5SDimitry Andric // Since we merge bitmaps from multiple object files to create a new 9830b57cec5SDimitry Andric // .note.gnu.property containing a single AND'ed bitmap, we discard an input 9840b57cec5SDimitry Andric // file's .note.gnu.property section. 9850b57cec5SDimitry Andric if (name == ".note.gnu.property") { 986e8d8bef9SDimitry Andric this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name)); 9870b57cec5SDimitry Andric return &InputSection::discarded; 9880b57cec5SDimitry Andric } 9890b57cec5SDimitry Andric 9900b57cec5SDimitry Andric // Split stacks is a feature to support a discontiguous stack, 9910b57cec5SDimitry Andric // commonly used in the programming language Go. For the details, 9920b57cec5SDimitry Andric // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled 9930b57cec5SDimitry Andric // for split stack will include a .note.GNU-split-stack section. 9940b57cec5SDimitry Andric if (name == ".note.GNU-split-stack") { 9950b57cec5SDimitry Andric if (config->relocatable) { 9960eae32dcSDimitry Andric error( 9970eae32dcSDimitry Andric "cannot mix split-stack and non-split-stack in a relocatable link"); 9980b57cec5SDimitry Andric return &InputSection::discarded; 9990b57cec5SDimitry Andric } 10000b57cec5SDimitry Andric this->splitStack = true; 10010b57cec5SDimitry Andric return &InputSection::discarded; 10020b57cec5SDimitry Andric } 10030b57cec5SDimitry Andric 10040b57cec5SDimitry Andric // An object file cmpiled for split stack, but where some of the 10050b57cec5SDimitry Andric // functions were compiled with the no_split_stack_attribute will 10060b57cec5SDimitry Andric // include a .note.GNU-no-split-stack section. 10070b57cec5SDimitry Andric if (name == ".note.GNU-no-split-stack") { 10080b57cec5SDimitry Andric this->someNoSplitStack = true; 10090b57cec5SDimitry Andric return &InputSection::discarded; 10100b57cec5SDimitry Andric } 10110b57cec5SDimitry Andric 10120eae32dcSDimitry Andric // Strip existing .note.gnu.build-id sections so that the output won't have 10130eae32dcSDimitry Andric // more than one build-id. This is not usually a problem because input 10140eae32dcSDimitry Andric // object files normally don't have .build-id sections, but you can create 10150eae32dcSDimitry Andric // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard 10160eae32dcSDimitry Andric // against it. 10170eae32dcSDimitry Andric if (name == ".note.gnu.build-id") 10180eae32dcSDimitry Andric return &InputSection::discarded; 10190eae32dcSDimitry Andric } 10200eae32dcSDimitry Andric 10210b57cec5SDimitry Andric // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 10220b57cec5SDimitry Andric // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 10230b57cec5SDimitry Andric // sections. Drop those sections to avoid duplicate symbol errors. 10240b57cec5SDimitry Andric // FIXME: This is glibc PR20543, we should remove this hack once that has been 10250b57cec5SDimitry Andric // fixed for a while. 10260b57cec5SDimitry Andric if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" || 10270b57cec5SDimitry Andric name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx") 10280b57cec5SDimitry Andric return &InputSection::discarded; 10290b57cec5SDimitry Andric 10300b57cec5SDimitry Andric // The linker merges EH (exception handling) frames and creates a 10310b57cec5SDimitry Andric // .eh_frame_hdr section for runtime. So we handle them with a special 10320b57cec5SDimitry Andric // class. For relocatable outputs, they are just passed through. 10330b57cec5SDimitry Andric if (name == ".eh_frame" && !config->relocatable) 10340b57cec5SDimitry Andric return make<EhInputSection>(*this, sec, name); 10350b57cec5SDimitry Andric 10360eae32dcSDimitry Andric if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name)) 10370b57cec5SDimitry Andric return make<MergeInputSection>(*this, sec, name); 10380b57cec5SDimitry Andric return make<InputSection>(*this, sec, name); 10390b57cec5SDimitry Andric } 10400b57cec5SDimitry Andric 10410b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as 10420b57cec5SDimitry Andric // its corresponding ELF symbol table. 10430b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 10440eae32dcSDimitry Andric ArrayRef<InputSectionBase *> sections(this->sections); 10450eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 10460b57cec5SDimitry Andric 10470eae32dcSDimitry Andric ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 10480eae32dcSDimitry Andric symbols.resize(eSyms.size()); 10490eae32dcSDimitry Andric SymbolUnion *locals = 10500eae32dcSDimitry Andric firstGlobal == 0 10510eae32dcSDimitry Andric ? nullptr 10520eae32dcSDimitry Andric : getSpecificAllocSingleton<SymbolUnion>().Allocate(firstGlobal); 10530eae32dcSDimitry Andric 10540eae32dcSDimitry Andric for (size_t i = 0, end = firstGlobal; i != end; ++i) { 10550b57cec5SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 10560b57cec5SDimitry Andric uint32_t secIdx = getSectionIndex(eSym); 10570eae32dcSDimitry Andric if (LLVM_UNLIKELY(secIdx >= sections.size())) 10580b57cec5SDimitry Andric fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 10590eae32dcSDimitry Andric if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL)) 10605ffd83dbSDimitry Andric error(toString(this) + ": non-local symbol (" + Twine(i) + 10610eae32dcSDimitry Andric ") found at index < .symtab's sh_info (" + Twine(end) + ")"); 10625ffd83dbSDimitry Andric 10630eae32dcSDimitry Andric InputSectionBase *sec = sections[secIdx]; 10645ffd83dbSDimitry Andric uint8_t type = eSym.getType(); 10655ffd83dbSDimitry Andric if (type == STT_FILE) 10660eae32dcSDimitry Andric sourceFile = CHECK(eSym.getName(stringTable), this); 10670eae32dcSDimitry Andric if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name)) 10685ffd83dbSDimitry Andric fatal(toString(this) + ": invalid symbol name offset"); 1069*04eeddc0SDimitry Andric StringRef name(stringTable.data() + eSym.st_name); 10705ffd83dbSDimitry Andric 10710eae32dcSDimitry Andric symbols[i] = reinterpret_cast<Symbol *>(locals + i); 10720eae32dcSDimitry Andric if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded) 10730eae32dcSDimitry Andric new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type, 10745ffd83dbSDimitry Andric /*discardedSecIdx=*/secIdx); 10755ffd83dbSDimitry Andric else 10760eae32dcSDimitry Andric new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type, 10770eae32dcSDimitry Andric eSym.st_value, eSym.st_size, sec); 10785ffd83dbSDimitry Andric } 10795ffd83dbSDimitry Andric 10800eae32dcSDimitry Andric // Some entries have been filled by LazyObjFile. 10810eae32dcSDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 10820eae32dcSDimitry Andric if (!symbols[i]) 10830eae32dcSDimitry Andric symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 10840eae32dcSDimitry Andric 10850eae32dcSDimitry Andric // Perform symbol resolution on non-local symbols. 1086fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 10875ffd83dbSDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 10885ffd83dbSDimitry Andric const Elf_Sym &eSym = eSyms[i]; 10890b57cec5SDimitry Andric uint8_t binding = eSym.getBinding(); 10900eae32dcSDimitry Andric if (LLVM_UNLIKELY(binding == STB_LOCAL)) { 10910eae32dcSDimitry Andric errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) + 10920eae32dcSDimitry Andric ") found at index >= .symtab's sh_info (" + 10930eae32dcSDimitry Andric Twine(firstGlobal) + ")"); 10940eae32dcSDimitry Andric continue; 10950eae32dcSDimitry Andric } 10965ffd83dbSDimitry Andric uint32_t secIdx = getSectionIndex(eSym); 10970eae32dcSDimitry Andric if (LLVM_UNLIKELY(secIdx >= sections.size())) 10980eae32dcSDimitry Andric fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 10990eae32dcSDimitry Andric InputSectionBase *sec = sections[secIdx]; 11000b57cec5SDimitry Andric uint8_t stOther = eSym.st_other; 11010b57cec5SDimitry Andric uint8_t type = eSym.getType(); 11020b57cec5SDimitry Andric uint64_t value = eSym.st_value; 11030b57cec5SDimitry Andric uint64_t size = eSym.st_size; 11040b57cec5SDimitry Andric 11050b57cec5SDimitry Andric if (eSym.st_shndx == SHN_UNDEF) { 1106fe6060f1SDimitry Andric undefineds.push_back(i); 11070b57cec5SDimitry Andric continue; 11080b57cec5SDimitry Andric } 11090b57cec5SDimitry Andric 11100eae32dcSDimitry Andric Symbol *sym = symbols[i]; 11110eae32dcSDimitry Andric const StringRef name = sym->getName(); 11120eae32dcSDimitry Andric if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) { 11130b57cec5SDimitry Andric if (value == 0 || value >= UINT32_MAX) 11140eae32dcSDimitry Andric fatal(toString(this) + ": common symbol '" + name + 11150b57cec5SDimitry Andric "' has invalid alignment: " + Twine(value)); 11160eae32dcSDimitry Andric hasCommonSyms = true; 11170eae32dcSDimitry Andric sym->resolve( 11180b57cec5SDimitry Andric CommonSymbol{this, name, binding, stOther, type, value, size}); 11190b57cec5SDimitry Andric continue; 11200b57cec5SDimitry Andric } 11210b57cec5SDimitry Andric 11220b57cec5SDimitry Andric // If a defined symbol is in a discarded section, handle it as if it 11230b57cec5SDimitry Andric // were an undefined symbol. Such symbol doesn't comply with the 11240b57cec5SDimitry Andric // standard, but in practice, a .eh_frame often directly refer 11250b57cec5SDimitry Andric // COMDAT member sections, and if a comdat group is discarded, some 11260b57cec5SDimitry Andric // defined symbol in a .eh_frame becomes dangling symbols. 11270b57cec5SDimitry Andric if (sec == &InputSection::discarded) { 11285ffd83dbSDimitry Andric Undefined und{this, name, binding, stOther, type, secIdx}; 11290eae32dcSDimitry Andric // !ArchiveFile::parsed or !LazyObjFile::lazy means that the file 11305ffd83dbSDimitry Andric // containing this object has not finished processing, i.e. this symbol is 11314824e7fdSDimitry Andric // a result of a lazy symbol extract. We should demote the lazy symbol to 11324824e7fdSDimitry Andric // an Undefined so that any relocations outside of the group to it will 11335ffd83dbSDimitry Andric // trigger a discarded section error. 11345ffd83dbSDimitry Andric if ((sym->symbolKind == Symbol::LazyArchiveKind && 11355ffd83dbSDimitry Andric !cast<ArchiveFile>(sym->file)->parsed) || 11360eae32dcSDimitry Andric (sym->symbolKind == Symbol::LazyObjectKind && !sym->file->lazy)) { 11375ffd83dbSDimitry Andric sym->replace(und); 11384824e7fdSDimitry Andric // Prevent LTO from internalizing the symbol in case there is a 11394824e7fdSDimitry Andric // reference to this symbol from this file. 11404824e7fdSDimitry Andric sym->isUsedInRegularObj = true; 11414824e7fdSDimitry Andric } else 11425ffd83dbSDimitry Andric sym->resolve(und); 11430b57cec5SDimitry Andric continue; 11440b57cec5SDimitry Andric } 11450b57cec5SDimitry Andric 11460b57cec5SDimitry Andric // Handle global defined symbols. 11470b57cec5SDimitry Andric if (binding == STB_GLOBAL || binding == STB_WEAK || 11480b57cec5SDimitry Andric binding == STB_GNU_UNIQUE) { 11490eae32dcSDimitry Andric sym->resolve( 11500b57cec5SDimitry Andric Defined{this, name, binding, stOther, type, value, size, sec}); 11510b57cec5SDimitry Andric continue; 11520b57cec5SDimitry Andric } 11530b57cec5SDimitry Andric 11540b57cec5SDimitry Andric fatal(toString(this) + ": unexpected binding: " + Twine((int)binding)); 11550b57cec5SDimitry Andric } 1156fe6060f1SDimitry Andric 1157fe6060f1SDimitry Andric // Undefined symbols (excluding those defined relative to non-prevailing 11584824e7fdSDimitry Andric // sections) can trigger recursive extract. Process defined symbols first so 1159fe6060f1SDimitry Andric // that the relative order between a defined symbol and an undefined symbol 1160fe6060f1SDimitry Andric // does not change the symbol resolution behavior. In addition, a set of 1161fe6060f1SDimitry Andric // interconnected symbols will all be resolved to the same file, instead of 1162fe6060f1SDimitry Andric // being resolved to different files. 1163fe6060f1SDimitry Andric for (unsigned i : undefineds) { 1164fe6060f1SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 11650eae32dcSDimitry Andric Symbol *sym = symbols[i]; 11660eae32dcSDimitry Andric sym->resolve(Undefined{this, sym->getName(), eSym.getBinding(), 1167fe6060f1SDimitry Andric eSym.st_other, eSym.getType()}); 11680eae32dcSDimitry Andric sym->referenced = true; 1169fe6060f1SDimitry Andric } 11700b57cec5SDimitry Andric } 11710b57cec5SDimitry Andric 11720b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file) 11730b57cec5SDimitry Andric : InputFile(ArchiveKind, file->getMemoryBufferRef()), 11740b57cec5SDimitry Andric file(std::move(file)) {} 11750b57cec5SDimitry Andric 11760b57cec5SDimitry Andric void ArchiveFile::parse() { 11770eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 11780b57cec5SDimitry Andric for (const Archive::Symbol &sym : file->symbols()) 11790eae32dcSDimitry Andric symtab.addSymbol(LazyArchive{*this, sym}); 11805ffd83dbSDimitry Andric 11815ffd83dbSDimitry Andric // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this 11825ffd83dbSDimitry Andric // archive has been processed. 11835ffd83dbSDimitry Andric parsed = true; 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric 11860b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol. 11874824e7fdSDimitry Andric void ArchiveFile::extract(const Archive::Symbol &sym) { 11880b57cec5SDimitry Andric Archive::Child c = 11890b57cec5SDimitry Andric CHECK(sym.getMember(), toString(this) + 11900b57cec5SDimitry Andric ": could not get the member for symbol " + 11910b57cec5SDimitry Andric toELFString(sym)); 11920b57cec5SDimitry Andric 11930b57cec5SDimitry Andric if (!seen.insert(c.getChildOffset()).second) 11940b57cec5SDimitry Andric return; 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric MemoryBufferRef mb = 11970b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 11980b57cec5SDimitry Andric toString(this) + 11990b57cec5SDimitry Andric ": could not get the buffer for the member defining symbol " + 12000b57cec5SDimitry Andric toELFString(sym)); 12010b57cec5SDimitry Andric 12020b57cec5SDimitry Andric if (tar && c.getParent()->isThin()) 12030b57cec5SDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 12040b57cec5SDimitry Andric 12055ffd83dbSDimitry Andric InputFile *file = createObjectFile(mb, getName(), c.getChildOffset()); 12060b57cec5SDimitry Andric file->groupId = groupId; 12070b57cec5SDimitry Andric parseFile(file); 12080b57cec5SDimitry Andric } 12090b57cec5SDimitry Andric 1210e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky. 1211fe6060f1SDimitry Andric // A tentative definition will be promoted to a global definition if there are 1212fe6060f1SDimitry Andric // no non-tentative definitions to dominate it. When we hold a tentative 1213fe6060f1SDimitry Andric // definition to a symbol and are inspecting archive members for inclusion 1214fe6060f1SDimitry Andric // there are 2 ways we can proceed: 1215e8d8bef9SDimitry Andric // 1216e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from 1217e8d8bef9SDimitry Andric // tentative to real definition has already happened) and not inspect 1218e8d8bef9SDimitry Andric // archive members for Global/Weak definitions to replace the tentative 1219e8d8bef9SDimitry Andric // definition. An archive member would only be included if it satisfies some 1220e8d8bef9SDimitry Andric // other undefined symbol. This is the behavior Gold uses. 1221e8d8bef9SDimitry Andric // 1222e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to 1223fe6060f1SDimitry Andric // a real definition happens only after all symbol resolution is done). 1224fe6060f1SDimitry Andric // The linker searches archive members for STB_GLOBAL definitions to 1225e8d8bef9SDimitry Andric // replace the tentative definition with. This is the behavior used by 1226e8d8bef9SDimitry Andric // GNU ld. 1227e8d8bef9SDimitry Andric // 1228e8d8bef9SDimitry Andric // The second behavior is inherited from SysVR4, which based it on the FORTRAN 1229fe6060f1SDimitry Andric // COMMON BLOCK model. This behavior is needed for proper initialization in old 1230e8d8bef9SDimitry Andric // (pre F90) FORTRAN code that is packaged into an archive. 1231e8d8bef9SDimitry Andric // 1232fe6060f1SDimitry Andric // The following functions search archive members for definitions to replace 1233fe6060f1SDimitry Andric // tentative definitions (implementing behavior 2). 1234e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName, 1235e8d8bef9SDimitry Andric StringRef archiveName) { 1236e8d8bef9SDimitry Andric IRSymtabFile symtabFile = check(readIRSymtab(mb)); 1237e8d8bef9SDimitry Andric for (const irsymtab::Reader::SymbolRef &sym : 1238e8d8bef9SDimitry Andric symtabFile.TheReader.symbols()) { 1239e8d8bef9SDimitry Andric if (sym.isGlobal() && sym.getName() == symName) 1240fe6060f1SDimitry Andric return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon(); 1241e8d8bef9SDimitry Andric } 1242e8d8bef9SDimitry Andric return false; 1243e8d8bef9SDimitry Andric } 1244e8d8bef9SDimitry Andric 1245e8d8bef9SDimitry Andric template <class ELFT> 1246e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1247e8d8bef9SDimitry Andric StringRef archiveName) { 1248e8d8bef9SDimitry Andric ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName); 1249e8d8bef9SDimitry Andric StringRef stringtable = obj->getStringTable(); 1250e8d8bef9SDimitry Andric 1251e8d8bef9SDimitry Andric for (auto sym : obj->template getGlobalELFSyms<ELFT>()) { 1252e8d8bef9SDimitry Andric Expected<StringRef> name = sym.getName(stringtable); 1253e8d8bef9SDimitry Andric if (name && name.get() == symName) 1254fe6060f1SDimitry Andric return sym.isDefined() && sym.getBinding() == STB_GLOBAL && 1255fe6060f1SDimitry Andric !sym.isCommon(); 1256e8d8bef9SDimitry Andric } 1257e8d8bef9SDimitry Andric return false; 1258e8d8bef9SDimitry Andric } 1259e8d8bef9SDimitry Andric 1260e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1261e8d8bef9SDimitry Andric StringRef archiveName) { 1262e8d8bef9SDimitry Andric switch (getELFKind(mb, archiveName)) { 1263e8d8bef9SDimitry Andric case ELF32LEKind: 1264e8d8bef9SDimitry Andric return isNonCommonDef<ELF32LE>(mb, symName, archiveName); 1265e8d8bef9SDimitry Andric case ELF32BEKind: 1266e8d8bef9SDimitry Andric return isNonCommonDef<ELF32BE>(mb, symName, archiveName); 1267e8d8bef9SDimitry Andric case ELF64LEKind: 1268e8d8bef9SDimitry Andric return isNonCommonDef<ELF64LE>(mb, symName, archiveName); 1269e8d8bef9SDimitry Andric case ELF64BEKind: 1270e8d8bef9SDimitry Andric return isNonCommonDef<ELF64BE>(mb, symName, archiveName); 1271e8d8bef9SDimitry Andric default: 1272e8d8bef9SDimitry Andric llvm_unreachable("getELFKind"); 1273e8d8bef9SDimitry Andric } 1274e8d8bef9SDimitry Andric } 1275e8d8bef9SDimitry Andric 12764824e7fdSDimitry Andric bool ArchiveFile::shouldExtractForCommon(const Archive::Symbol &sym) { 1277e8d8bef9SDimitry Andric Archive::Child c = 1278e8d8bef9SDimitry Andric CHECK(sym.getMember(), toString(this) + 1279e8d8bef9SDimitry Andric ": could not get the member for symbol " + 1280e8d8bef9SDimitry Andric toELFString(sym)); 1281e8d8bef9SDimitry Andric MemoryBufferRef mb = 1282e8d8bef9SDimitry Andric CHECK(c.getMemoryBufferRef(), 1283e8d8bef9SDimitry Andric toString(this) + 1284e8d8bef9SDimitry Andric ": could not get the buffer for the member defining symbol " + 1285e8d8bef9SDimitry Andric toELFString(sym)); 1286e8d8bef9SDimitry Andric 1287e8d8bef9SDimitry Andric if (isBitcode(mb)) 1288e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, sym.getName(), getName()); 1289e8d8bef9SDimitry Andric 1290e8d8bef9SDimitry Andric return isNonCommonDef(mb, sym.getName(), getName()); 1291e8d8bef9SDimitry Andric } 1292e8d8bef9SDimitry Andric 12935ffd83dbSDimitry Andric size_t ArchiveFile::getMemberCount() const { 12945ffd83dbSDimitry Andric size_t count = 0; 12955ffd83dbSDimitry Andric Error err = Error::success(); 12965ffd83dbSDimitry Andric for (const Archive::Child &c : file->children(err)) { 12975ffd83dbSDimitry Andric (void)c; 12985ffd83dbSDimitry Andric ++count; 12995ffd83dbSDimitry Andric } 13005ffd83dbSDimitry Andric // This function is used by --print-archive-stats=, where an error does not 13015ffd83dbSDimitry Andric // really matter. 13025ffd83dbSDimitry Andric consumeError(std::move(err)); 13035ffd83dbSDimitry Andric return count; 13045ffd83dbSDimitry Andric } 13055ffd83dbSDimitry Andric 13060b57cec5SDimitry Andric unsigned SharedFile::vernauxNum; 13070b57cec5SDimitry Andric 13080b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a 13090b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version 13100b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr. 13110b57cec5SDimitry Andric template <typename ELFT> 13120eae32dcSDimitry Andric static SmallVector<const void *, 0> 13130eae32dcSDimitry Andric parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) { 13140b57cec5SDimitry Andric if (!sec) 13150b57cec5SDimitry Andric return {}; 13160b57cec5SDimitry Andric 13170b57cec5SDimitry Andric // Build the Verdefs array by following the chain of Elf_Verdef objects 13180b57cec5SDimitry Andric // from the start of the .gnu.version_d section. 13190eae32dcSDimitry Andric SmallVector<const void *, 0> verdefs; 13200b57cec5SDimitry Andric const uint8_t *verdef = base + sec->sh_offset; 13210eae32dcSDimitry Andric for (unsigned i = 0, e = sec->sh_info; i != e; ++i) { 13220b57cec5SDimitry Andric auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef); 13230b57cec5SDimitry Andric verdef += curVerdef->vd_next; 13240b57cec5SDimitry Andric unsigned verdefIndex = curVerdef->vd_ndx; 13250eae32dcSDimitry Andric if (verdefIndex >= verdefs.size()) 13260b57cec5SDimitry Andric verdefs.resize(verdefIndex + 1); 13270b57cec5SDimitry Andric verdefs[verdefIndex] = curVerdef; 13280b57cec5SDimitry Andric } 13290b57cec5SDimitry Andric return verdefs; 13300b57cec5SDimitry Andric } 13310b57cec5SDimitry Andric 13325ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined 13335ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not 13345ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value 13355ffd83dbSDimitry Andric // of such diagnostics is low. 13365ffd83dbSDimitry Andric template <typename ELFT> 13375ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj, 13385ffd83dbSDimitry Andric const typename ELFT::Shdr *sec) { 13395ffd83dbSDimitry Andric if (!sec) 13405ffd83dbSDimitry Andric return {}; 13415ffd83dbSDimitry Andric std::vector<uint32_t> verneeds; 1342e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this); 13435ffd83dbSDimitry Andric const uint8_t *verneedBuf = data.begin(); 13445ffd83dbSDimitry Andric for (unsigned i = 0; i != sec->sh_info; ++i) { 13455ffd83dbSDimitry Andric if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) 13465ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Verneed"); 13475ffd83dbSDimitry Andric auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf); 13485ffd83dbSDimitry Andric const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux; 13495ffd83dbSDimitry Andric for (unsigned j = 0; j != vn->vn_cnt; ++j) { 13505ffd83dbSDimitry Andric if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) 13515ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Vernaux"); 13525ffd83dbSDimitry Andric auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf); 13535ffd83dbSDimitry Andric if (aux->vna_name >= this->stringTable.size()) 13545ffd83dbSDimitry Andric fatal(toString(this) + " has a Vernaux with an invalid vna_name"); 13555ffd83dbSDimitry Andric uint16_t version = aux->vna_other & VERSYM_VERSION; 13565ffd83dbSDimitry Andric if (version >= verneeds.size()) 13575ffd83dbSDimitry Andric verneeds.resize(version + 1); 13585ffd83dbSDimitry Andric verneeds[version] = aux->vna_name; 13595ffd83dbSDimitry Andric vernauxBuf += aux->vna_next; 13605ffd83dbSDimitry Andric } 13615ffd83dbSDimitry Andric verneedBuf += vn->vn_next; 13625ffd83dbSDimitry Andric } 13635ffd83dbSDimitry Andric return verneeds; 13645ffd83dbSDimitry Andric } 13655ffd83dbSDimitry Andric 13660b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object 13670b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a 13680b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep 13690b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function. 13700b57cec5SDimitry Andric template <typename ELFT> 13710b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections, 13720b57cec5SDimitry Andric const typename ELFT::Sym &sym) { 13730b57cec5SDimitry Andric uint64_t ret = UINT64_MAX; 13740b57cec5SDimitry Andric if (sym.st_value) 13750b57cec5SDimitry Andric ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value); 13760b57cec5SDimitry Andric if (0 < sym.st_shndx && sym.st_shndx < sections.size()) 13770b57cec5SDimitry Andric ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign); 13780b57cec5SDimitry Andric return (ret > UINT32_MAX) ? 0 : ret; 13790b57cec5SDimitry Andric } 13800b57cec5SDimitry Andric 13810b57cec5SDimitry Andric // Fully parse the shared object file. 13820b57cec5SDimitry Andric // 13830b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information, 13840b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version 13850b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in 13860b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol 13870b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d". 13880b57cec5SDimitry Andric // 13890b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 13900b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in 13910b57cec5SDimitry Andric // ".gnu.version_d". 13920b57cec5SDimitry Andric // 13930b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated 13940b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your 13950b57cec5SDimitry Andric // head around the data structure described above. 13960b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() { 13970b57cec5SDimitry Andric using Elf_Dyn = typename ELFT::Dyn; 13980b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 13990b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 14000b57cec5SDimitry Andric using Elf_Verdef = typename ELFT::Verdef; 14010b57cec5SDimitry Andric using Elf_Versym = typename ELFT::Versym; 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric ArrayRef<Elf_Dyn> dynamicTags; 14040b57cec5SDimitry Andric const ELFFile<ELFT> obj = this->getObj<ELFT>(); 14050eae32dcSDimitry Andric ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>(); 14060b57cec5SDimitry Andric 14070b57cec5SDimitry Andric const Elf_Shdr *versymSec = nullptr; 14080b57cec5SDimitry Andric const Elf_Shdr *verdefSec = nullptr; 14095ffd83dbSDimitry Andric const Elf_Shdr *verneedSec = nullptr; 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 14120b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) { 14130b57cec5SDimitry Andric switch (sec.sh_type) { 14140b57cec5SDimitry Andric default: 14150b57cec5SDimitry Andric continue; 14160b57cec5SDimitry Andric case SHT_DYNAMIC: 14170b57cec5SDimitry Andric dynamicTags = 1418e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this); 14190b57cec5SDimitry Andric break; 14200b57cec5SDimitry Andric case SHT_GNU_versym: 14210b57cec5SDimitry Andric versymSec = &sec; 14220b57cec5SDimitry Andric break; 14230b57cec5SDimitry Andric case SHT_GNU_verdef: 14240b57cec5SDimitry Andric verdefSec = &sec; 14250b57cec5SDimitry Andric break; 14265ffd83dbSDimitry Andric case SHT_GNU_verneed: 14275ffd83dbSDimitry Andric verneedSec = &sec; 14285ffd83dbSDimitry Andric break; 14290b57cec5SDimitry Andric } 14300b57cec5SDimitry Andric } 14310b57cec5SDimitry Andric 14320b57cec5SDimitry Andric if (versymSec && numELFSyms == 0) { 14330b57cec5SDimitry Andric error("SHT_GNU_versym should be associated with symbol table"); 14340b57cec5SDimitry Andric return; 14350b57cec5SDimitry Andric } 14360b57cec5SDimitry Andric 14370b57cec5SDimitry Andric // Search for a DT_SONAME tag to initialize this->soName. 14380b57cec5SDimitry Andric for (const Elf_Dyn &dyn : dynamicTags) { 14390b57cec5SDimitry Andric if (dyn.d_tag == DT_NEEDED) { 14400b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14410b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14420b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_NEEDED entry"); 14430b57cec5SDimitry Andric dtNeeded.push_back(this->stringTable.data() + val); 14440b57cec5SDimitry Andric } else if (dyn.d_tag == DT_SONAME) { 14450b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14460b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14470b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_SONAME entry"); 14480b57cec5SDimitry Andric soName = this->stringTable.data() + val; 14490b57cec5SDimitry Andric } 14500b57cec5SDimitry Andric } 14510b57cec5SDimitry Andric 14520b57cec5SDimitry Andric // DSOs are uniquified not by filename but by soname. 1453*04eeddc0SDimitry Andric DenseMap<CachedHashStringRef, SharedFile *>::iterator it; 14540b57cec5SDimitry Andric bool wasInserted; 1455*04eeddc0SDimitry Andric std::tie(it, wasInserted) = 1456*04eeddc0SDimitry Andric symtab->soNames.try_emplace(CachedHashStringRef(soName), this); 14570b57cec5SDimitry Andric 14580b57cec5SDimitry Andric // If a DSO appears more than once on the command line with and without 14590b57cec5SDimitry Andric // --as-needed, --no-as-needed takes precedence over --as-needed because a 14600b57cec5SDimitry Andric // user can add an extra DSO with --no-as-needed to force it to be added to 14610b57cec5SDimitry Andric // the dependency list. 14620b57cec5SDimitry Andric it->second->isNeeded |= isNeeded; 14630b57cec5SDimitry Andric if (!wasInserted) 14640b57cec5SDimitry Andric return; 14650b57cec5SDimitry Andric 14660b57cec5SDimitry Andric sharedFiles.push_back(this); 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec); 14695ffd83dbSDimitry Andric std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec); 14700b57cec5SDimitry Andric 14710b57cec5SDimitry Andric // Parse ".gnu.version" section which is a parallel array for the symbol 14720b57cec5SDimitry Andric // table. If a given file doesn't have a ".gnu.version" section, we use 14730b57cec5SDimitry Andric // VER_NDX_GLOBAL. 14740b57cec5SDimitry Andric size_t size = numELFSyms - firstGlobal; 14755ffd83dbSDimitry Andric std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL); 14760b57cec5SDimitry Andric if (versymSec) { 14770b57cec5SDimitry Andric ArrayRef<Elf_Versym> versym = 1478e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec), 14790b57cec5SDimitry Andric this) 14800b57cec5SDimitry Andric .slice(firstGlobal); 14810b57cec5SDimitry Andric for (size_t i = 0; i < size; ++i) 14820b57cec5SDimitry Andric versyms[i] = versym[i].vs_index; 14830b57cec5SDimitry Andric } 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // System libraries can have a lot of symbols with versions. Using a 14860b57cec5SDimitry Andric // fixed buffer for computing the versions name (foo@ver) can save a 14870b57cec5SDimitry Andric // lot of allocations. 14880b57cec5SDimitry Andric SmallString<0> versionedNameBuffer; 14890b57cec5SDimitry Andric 14900b57cec5SDimitry Andric // Add symbols to the symbol table. 14910eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 14920b57cec5SDimitry Andric ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>(); 14930eae32dcSDimitry Andric for (size_t i = 0, e = syms.size(); i != e; ++i) { 14940b57cec5SDimitry Andric const Elf_Sym &sym = syms[i]; 14950b57cec5SDimitry Andric 14960b57cec5SDimitry Andric // ELF spec requires that all local symbols precede weak or global 14970b57cec5SDimitry Andric // symbols in each symbol table, and the index of first non-local symbol 14980b57cec5SDimitry Andric // is stored to sh_info. If a local symbol appears after some non-local 14990b57cec5SDimitry Andric // symbol, that's a violation of the spec. 15000eae32dcSDimitry Andric StringRef name = CHECK(sym.getName(stringTable), this); 15010b57cec5SDimitry Andric if (sym.getBinding() == STB_LOCAL) { 15020b57cec5SDimitry Andric warn("found local symbol '" + name + 15030b57cec5SDimitry Andric "' in global part of symbol table in file " + toString(this)); 15040b57cec5SDimitry Andric continue; 15050b57cec5SDimitry Andric } 15060b57cec5SDimitry Andric 15075ffd83dbSDimitry Andric uint16_t idx = versyms[i] & ~VERSYM_HIDDEN; 15080b57cec5SDimitry Andric if (sym.isUndefined()) { 15095ffd83dbSDimitry Andric // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but 15105ffd83dbSDimitry Andric // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL. 15115ffd83dbSDimitry Andric if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) { 15125ffd83dbSDimitry Andric if (idx >= verneeds.size()) { 15135ffd83dbSDimitry Andric error("corrupt input file: version need index " + Twine(idx) + 15145ffd83dbSDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15155ffd83dbSDimitry Andric toString(this)); 15165ffd83dbSDimitry Andric continue; 15175ffd83dbSDimitry Andric } 15180eae32dcSDimitry Andric StringRef verName = stringTable.data() + verneeds[idx]; 15195ffd83dbSDimitry Andric versionedNameBuffer.clear(); 1520*04eeddc0SDimitry Andric name = saver().save( 1521*04eeddc0SDimitry Andric (name + "@" + verName).toStringRef(versionedNameBuffer)); 15225ffd83dbSDimitry Andric } 15230eae32dcSDimitry Andric Symbol *s = symtab.addSymbol( 15240b57cec5SDimitry Andric Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()}); 15250b57cec5SDimitry Andric s->exportDynamic = true; 15260eae32dcSDimitry Andric if (s->isUndefined() && sym.getBinding() != STB_WEAK && 1527fe6060f1SDimitry Andric config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) 1528fe6060f1SDimitry Andric requiredSymbols.push_back(s); 15290b57cec5SDimitry Andric continue; 15300b57cec5SDimitry Andric } 15310b57cec5SDimitry Andric 15320b57cec5SDimitry Andric // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 15330b57cec5SDimitry Andric // assigns VER_NDX_LOCAL to this section global symbol. Here is a 15340b57cec5SDimitry Andric // workaround for this bug. 15350b57cec5SDimitry Andric if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL && 15360b57cec5SDimitry Andric name == "_gp_disp") 15370b57cec5SDimitry Andric continue; 15380b57cec5SDimitry Andric 15390b57cec5SDimitry Andric uint32_t alignment = getAlignment<ELFT>(sections, sym); 15400b57cec5SDimitry Andric if (!(versyms[i] & VERSYM_HIDDEN)) { 15410eae32dcSDimitry Andric symtab.addSymbol(SharedSymbol{*this, name, sym.getBinding(), sym.st_other, 15420eae32dcSDimitry Andric sym.getType(), sym.st_value, sym.st_size, 15430eae32dcSDimitry Andric alignment, idx}); 15440b57cec5SDimitry Andric } 15450b57cec5SDimitry Andric 15460b57cec5SDimitry Andric // Also add the symbol with the versioned name to handle undefined symbols 15470b57cec5SDimitry Andric // with explicit versions. 15480b57cec5SDimitry Andric if (idx == VER_NDX_GLOBAL) 15490b57cec5SDimitry Andric continue; 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) { 15520b57cec5SDimitry Andric error("corrupt input file: version definition index " + Twine(idx) + 15530b57cec5SDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15540b57cec5SDimitry Andric toString(this)); 15550b57cec5SDimitry Andric continue; 15560b57cec5SDimitry Andric } 15570b57cec5SDimitry Andric 15580b57cec5SDimitry Andric StringRef verName = 15590eae32dcSDimitry Andric stringTable.data() + 15600b57cec5SDimitry Andric reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name; 15610b57cec5SDimitry Andric versionedNameBuffer.clear(); 15620b57cec5SDimitry Andric name = (name + "@" + verName).toStringRef(versionedNameBuffer); 1563*04eeddc0SDimitry Andric symtab.addSymbol(SharedSymbol{*this, saver().save(name), sym.getBinding(), 15640b57cec5SDimitry Andric sym.st_other, sym.getType(), sym.st_value, 15650b57cec5SDimitry Andric sym.st_size, alignment, idx}); 15660b57cec5SDimitry Andric } 15670b57cec5SDimitry Andric } 15680b57cec5SDimitry Andric 15690b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) { 15700b57cec5SDimitry Andric if (t.isLittleEndian()) 15710b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 15720b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 15730b57cec5SDimitry Andric } 15740b57cec5SDimitry Andric 1575e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) { 15760b57cec5SDimitry Andric switch (t.getArch()) { 15770b57cec5SDimitry Andric case Triple::aarch64: 1578fe6060f1SDimitry Andric case Triple::aarch64_be: 15790b57cec5SDimitry Andric return EM_AARCH64; 15800b57cec5SDimitry Andric case Triple::amdgcn: 15810b57cec5SDimitry Andric case Triple::r600: 15820b57cec5SDimitry Andric return EM_AMDGPU; 15830b57cec5SDimitry Andric case Triple::arm: 15840b57cec5SDimitry Andric case Triple::thumb: 15850b57cec5SDimitry Andric return EM_ARM; 15860b57cec5SDimitry Andric case Triple::avr: 15870b57cec5SDimitry Andric return EM_AVR; 1588349cc55cSDimitry Andric case Triple::hexagon: 1589349cc55cSDimitry Andric return EM_HEXAGON; 15900b57cec5SDimitry Andric case Triple::mips: 15910b57cec5SDimitry Andric case Triple::mipsel: 15920b57cec5SDimitry Andric case Triple::mips64: 15930b57cec5SDimitry Andric case Triple::mips64el: 15940b57cec5SDimitry Andric return EM_MIPS; 15950b57cec5SDimitry Andric case Triple::msp430: 15960b57cec5SDimitry Andric return EM_MSP430; 15970b57cec5SDimitry Andric case Triple::ppc: 1598e8d8bef9SDimitry Andric case Triple::ppcle: 15990b57cec5SDimitry Andric return EM_PPC; 16000b57cec5SDimitry Andric case Triple::ppc64: 16010b57cec5SDimitry Andric case Triple::ppc64le: 16020b57cec5SDimitry Andric return EM_PPC64; 16030b57cec5SDimitry Andric case Triple::riscv32: 16040b57cec5SDimitry Andric case Triple::riscv64: 16050b57cec5SDimitry Andric return EM_RISCV; 16060b57cec5SDimitry Andric case Triple::x86: 16070b57cec5SDimitry Andric return t.isOSIAMCU() ? EM_IAMCU : EM_386; 16080b57cec5SDimitry Andric case Triple::x86_64: 16090b57cec5SDimitry Andric return EM_X86_64; 16100b57cec5SDimitry Andric default: 16110b57cec5SDimitry Andric error(path + ": could not infer e_machine from bitcode target triple " + 16120b57cec5SDimitry Andric t.str()); 16130b57cec5SDimitry Andric return EM_NONE; 16140b57cec5SDimitry Andric } 16150b57cec5SDimitry Andric } 16160b57cec5SDimitry Andric 1617e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) { 1618e8d8bef9SDimitry Andric switch (t.getOS()) { 1619e8d8bef9SDimitry Andric case Triple::AMDHSA: 1620e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_HSA; 1621e8d8bef9SDimitry Andric case Triple::AMDPAL: 1622e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_PAL; 1623e8d8bef9SDimitry Andric case Triple::Mesa3D: 1624e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_MESA3D; 1625e8d8bef9SDimitry Andric default: 1626e8d8bef9SDimitry Andric return ELF::ELFOSABI_NONE; 1627e8d8bef9SDimitry Andric } 1628e8d8bef9SDimitry Andric } 1629e8d8bef9SDimitry Andric 16300b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 16310eae32dcSDimitry Andric uint64_t offsetInArchive, bool lazy) 16320b57cec5SDimitry Andric : InputFile(BitcodeKind, mb) { 16330eae32dcSDimitry Andric this->archiveName = archiveName; 16340eae32dcSDimitry Andric this->lazy = lazy; 16350b57cec5SDimitry Andric 16360b57cec5SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 16370b57cec5SDimitry Andric if (config->thinLTOIndexOnly) 16380b57cec5SDimitry Andric path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 16390b57cec5SDimitry Andric 16400b57cec5SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 16410b57cec5SDimitry Andric // name. If two archives define two members with the same name, this 16420b57cec5SDimitry Andric // causes a collision which result in only one of the objects being taken 16430b57cec5SDimitry Andric // into consideration at LTO time (which very likely causes undefined 16440b57cec5SDimitry Andric // symbols later in the link stage). So we append file offset to make 16450b57cec5SDimitry Andric // filename unique. 1646*04eeddc0SDimitry Andric StringRef name = archiveName.empty() 1647*04eeddc0SDimitry Andric ? saver().save(path) 1648*04eeddc0SDimitry Andric : saver().save(archiveName + "(" + path::filename(path) + 1649*04eeddc0SDimitry Andric " at " + utostr(offsetInArchive) + ")"); 16500b57cec5SDimitry Andric MemoryBufferRef mbref(mb.getBuffer(), name); 16510b57cec5SDimitry Andric 16520b57cec5SDimitry Andric obj = CHECK(lto::InputFile::create(mbref), this); 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric Triple t(obj->getTargetTriple()); 16550b57cec5SDimitry Andric ekind = getBitcodeELFKind(t); 16560b57cec5SDimitry Andric emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t); 1657e8d8bef9SDimitry Andric osabi = getOsAbi(t); 16580b57cec5SDimitry Andric } 16590b57cec5SDimitry Andric 16600b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 16610b57cec5SDimitry Andric switch (gvVisibility) { 16620b57cec5SDimitry Andric case GlobalValue::DefaultVisibility: 16630b57cec5SDimitry Andric return STV_DEFAULT; 16640b57cec5SDimitry Andric case GlobalValue::HiddenVisibility: 16650b57cec5SDimitry Andric return STV_HIDDEN; 16660b57cec5SDimitry Andric case GlobalValue::ProtectedVisibility: 16670b57cec5SDimitry Andric return STV_PROTECTED; 16680b57cec5SDimitry Andric } 16690b57cec5SDimitry Andric llvm_unreachable("unknown visibility"); 16700b57cec5SDimitry Andric } 16710b57cec5SDimitry Andric 16720b57cec5SDimitry Andric template <class ELFT> 1673*04eeddc0SDimitry Andric static void 1674*04eeddc0SDimitry Andric createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats, 1675*04eeddc0SDimitry Andric const lto::InputFile::Symbol &objSym, BitcodeFile &f) { 16760b57cec5SDimitry Andric uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL; 16770b57cec5SDimitry Andric uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE; 16780b57cec5SDimitry Andric uint8_t visibility = mapVisibility(objSym.getVisibility()); 16790b57cec5SDimitry Andric bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable(); 16800b57cec5SDimitry Andric 1681*04eeddc0SDimitry Andric StringRef name; 1682*04eeddc0SDimitry Andric if (sym) { 1683*04eeddc0SDimitry Andric name = sym->getName(); 1684*04eeddc0SDimitry Andric } else { 1685*04eeddc0SDimitry Andric name = saver().save(objSym.getName()); 1686*04eeddc0SDimitry Andric sym = symtab->insert(name); 1687*04eeddc0SDimitry Andric } 1688*04eeddc0SDimitry Andric 16890b57cec5SDimitry Andric int c = objSym.getComdatIndex(); 16900b57cec5SDimitry Andric if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) { 169185868e8aSDimitry Andric Undefined newSym(&f, name, binding, visibility, type); 16920b57cec5SDimitry Andric if (canOmitFromDynSym) 169385868e8aSDimitry Andric newSym.exportDynamic = false; 1694*04eeddc0SDimitry Andric sym->resolve(newSym); 1695*04eeddc0SDimitry Andric sym->referenced = true; 1696*04eeddc0SDimitry Andric return; 16970b57cec5SDimitry Andric } 16980b57cec5SDimitry Andric 1699*04eeddc0SDimitry Andric if (objSym.isCommon()) { 1700*04eeddc0SDimitry Andric sym->resolve(CommonSymbol{&f, name, binding, visibility, STT_OBJECT, 1701*04eeddc0SDimitry Andric objSym.getCommonAlignment(), 1702*04eeddc0SDimitry Andric objSym.getCommonSize()}); 1703*04eeddc0SDimitry Andric } else { 170485868e8aSDimitry Andric Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr); 17050b57cec5SDimitry Andric if (canOmitFromDynSym) 170685868e8aSDimitry Andric newSym.exportDynamic = false; 1707*04eeddc0SDimitry Andric sym->resolve(newSym); 1708*04eeddc0SDimitry Andric } 17090b57cec5SDimitry Andric } 17100b57cec5SDimitry Andric 17110b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() { 17120b57cec5SDimitry Andric std::vector<bool> keptComdats; 1713fe6060f1SDimitry Andric for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) { 17140b57cec5SDimitry Andric keptComdats.push_back( 1715fe6060f1SDimitry Andric s.second == Comdat::NoDeduplicate || 1716fe6060f1SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this) 1717fe6060f1SDimitry Andric .second); 1718fe6060f1SDimitry Andric } 17190b57cec5SDimitry Andric 1720*04eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 1721*04eeddc0SDimitry Andric for (auto it : llvm::enumerate(obj->symbols())) { 1722*04eeddc0SDimitry Andric Symbol *&sym = symbols[it.index()]; 1723*04eeddc0SDimitry Andric createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this); 1724*04eeddc0SDimitry Andric } 17250b57cec5SDimitry Andric 17260b57cec5SDimitry Andric for (auto l : obj->getDependentLibraries()) 17270b57cec5SDimitry Andric addDependentLibrary(l, this); 17280b57cec5SDimitry Andric } 17290b57cec5SDimitry Andric 17300eae32dcSDimitry Andric void BitcodeFile::parseLazy() { 17310eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 1732*04eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 1733*04eeddc0SDimitry Andric for (auto it : llvm::enumerate(obj->symbols())) 1734*04eeddc0SDimitry Andric if (!it.value().isUndefined()) 1735*04eeddc0SDimitry Andric symbols[it.index()] = symtab.addSymbol( 1736*04eeddc0SDimitry Andric LazyObject{*this, saver().save(it.value().getName())}); 17370eae32dcSDimitry Andric } 17380eae32dcSDimitry Andric 17390b57cec5SDimitry Andric void BinaryFile::parse() { 17400b57cec5SDimitry Andric ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer()); 17410b57cec5SDimitry Andric auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 17420b57cec5SDimitry Andric 8, data, ".data"); 17430b57cec5SDimitry Andric sections.push_back(section); 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric // For each input file foo that is embedded to a result as a binary 17460b57cec5SDimitry Andric // blob, we define _binary_foo_{start,end,size} symbols, so that 17470b57cec5SDimitry Andric // user programs can access blobs by name. Non-alphanumeric 17480b57cec5SDimitry Andric // characters in a filename are replaced with underscore. 17490b57cec5SDimitry Andric std::string s = "_binary_" + mb.getBufferIdentifier().str(); 17500b57cec5SDimitry Andric for (size_t i = 0; i < s.size(); ++i) 17510b57cec5SDimitry Andric if (!isAlnum(s[i])) 17520b57cec5SDimitry Andric s[i] = '_'; 17530b57cec5SDimitry Andric 1754*04eeddc0SDimitry Andric llvm::StringSaver &saver = lld::saver(); 1755*04eeddc0SDimitry Andric 17560b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL, 17570b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, 0, 0, section}); 17580b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL, 17590b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, section}); 17600b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL, 17610b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr}); 17620b57cec5SDimitry Andric } 17630b57cec5SDimitry Andric 17645ffd83dbSDimitry Andric InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName, 17650b57cec5SDimitry Andric uint64_t offsetInArchive) { 17660b57cec5SDimitry Andric if (isBitcode(mb)) 17670eae32dcSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false); 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric switch (getELFKind(mb, archiveName)) { 17700b57cec5SDimitry Andric case ELF32LEKind: 17710b57cec5SDimitry Andric return make<ObjFile<ELF32LE>>(mb, archiveName); 17720b57cec5SDimitry Andric case ELF32BEKind: 17730b57cec5SDimitry Andric return make<ObjFile<ELF32BE>>(mb, archiveName); 17740b57cec5SDimitry Andric case ELF64LEKind: 17750b57cec5SDimitry Andric return make<ObjFile<ELF64LE>>(mb, archiveName); 17760b57cec5SDimitry Andric case ELF64BEKind: 17770b57cec5SDimitry Andric return make<ObjFile<ELF64BE>>(mb, archiveName); 17780b57cec5SDimitry Andric default: 17790b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 17800b57cec5SDimitry Andric } 17810b57cec5SDimitry Andric } 17820b57cec5SDimitry Andric 17830eae32dcSDimitry Andric InputFile *elf::createLazyFile(MemoryBufferRef mb, StringRef archiveName, 17840eae32dcSDimitry Andric uint64_t offsetInArchive) { 17850eae32dcSDimitry Andric if (isBitcode(mb)) 17860eae32dcSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/true); 17870b57cec5SDimitry Andric 17880eae32dcSDimitry Andric auto *file = 17890eae32dcSDimitry Andric cast<ELFFileBase>(createObjectFile(mb, archiveName, offsetInArchive)); 17900eae32dcSDimitry Andric file->lazy = true; 17910eae32dcSDimitry Andric return file; 17920b57cec5SDimitry Andric } 17930b57cec5SDimitry Andric 17940eae32dcSDimitry Andric template <class ELFT> void ObjFile<ELFT>::parseLazy() { 17950eae32dcSDimitry Andric const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>(); 17960eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 17970b57cec5SDimitry Andric 17980eae32dcSDimitry Andric symbols.resize(eSyms.size()); 17990b57cec5SDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 18000b57cec5SDimitry Andric if (eSyms[i].st_shndx != SHN_UNDEF) 18010eae32dcSDimitry Andric symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 18020b57cec5SDimitry Andric 18030b57cec5SDimitry Andric // Replace existing symbols with LazyObject symbols. 18040b57cec5SDimitry Andric // 18050eae32dcSDimitry Andric // resolve() may trigger this->extract() if an existing symbol is an undefined 18060eae32dcSDimitry Andric // symbol. If that happens, this function has served its purpose, and we can 18070eae32dcSDimitry Andric // exit from the loop early. 18080eae32dcSDimitry Andric for (Symbol *sym : makeArrayRef(symbols).slice(firstGlobal)) 18090eae32dcSDimitry Andric if (sym) { 18100b57cec5SDimitry Andric sym->resolve(LazyObject{*this, sym->getName()}); 18110eae32dcSDimitry Andric if (!lazy) 18120b57cec5SDimitry Andric return; 18130b57cec5SDimitry Andric } 18140b57cec5SDimitry Andric } 18150b57cec5SDimitry Andric 18160eae32dcSDimitry Andric bool InputFile::shouldExtractForCommon(StringRef name) { 1817e8d8bef9SDimitry Andric if (isBitcode(mb)) 1818e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, name, archiveName); 1819e8d8bef9SDimitry Andric 1820e8d8bef9SDimitry Andric return isNonCommonDef(mb, name, archiveName); 1821e8d8bef9SDimitry Andric } 1822e8d8bef9SDimitry Andric 18235ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) { 18240b57cec5SDimitry Andric StringRef suffix = config->thinLTOObjectSuffixReplace.first; 18250b57cec5SDimitry Andric StringRef repl = config->thinLTOObjectSuffixReplace.second; 18260b57cec5SDimitry Andric 18270b57cec5SDimitry Andric if (path.consume_back(suffix)) 18280b57cec5SDimitry Andric return (path + repl).str(); 18295ffd83dbSDimitry Andric return std::string(path); 18300b57cec5SDimitry Andric } 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>(); 18330b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>(); 18340b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>(); 18350b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>(); 18360b57cec5SDimitry Andric 18375ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>; 18385ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>; 18395ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>; 18405ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>; 18410b57cec5SDimitry Andric 18420b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>(); 18430b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>(); 18440b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>(); 18450b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>(); 1846