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*1fd87a68SDimitry Andric #include "Target.h" 1704eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h" 18480093f4SDimitry Andric #include "lld/Common/DWARF.h" 190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 200b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h" 210b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 220b57cec5SDimitry Andric #include "llvm/IR/Module.h" 230b57cec5SDimitry Andric #include "llvm/LTO/LTO.h" 240b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h" 250b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h" 260b57cec5SDimitry Andric #include "llvm/Support/ARMAttributeParser.h" 270b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h" 280b57cec5SDimitry Andric #include "llvm/Support/Endian.h" 290b57cec5SDimitry Andric #include "llvm/Support/Path.h" 30e8d8bef9SDimitry Andric #include "llvm/Support/RISCVAttributeParser.h" 310b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 320b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 330b57cec5SDimitry Andric 340b57cec5SDimitry Andric using namespace llvm; 350b57cec5SDimitry Andric using namespace llvm::ELF; 360b57cec5SDimitry Andric using namespace llvm::object; 370b57cec5SDimitry Andric using namespace llvm::sys; 380b57cec5SDimitry Andric using namespace llvm::sys::fs; 390b57cec5SDimitry Andric using namespace llvm::support::endian; 405ffd83dbSDimitry Andric using namespace lld; 415ffd83dbSDimitry Andric using namespace lld::elf; 420b57cec5SDimitry Andric 435ffd83dbSDimitry Andric bool InputFile::isInGroup; 445ffd83dbSDimitry Andric uint32_t InputFile::nextGroupId; 455ffd83dbSDimitry Andric 4604eeddc0SDimitry Andric SmallVector<std::unique_ptr<MemoryBuffer>> elf::memoryBuffers; 470eae32dcSDimitry Andric SmallVector<ArchiveFile *, 0> elf::archiveFiles; 480eae32dcSDimitry Andric SmallVector<BinaryFile *, 0> elf::binaryFiles; 490eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::bitcodeFiles; 500eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::lazyBitcodeFiles; 510eae32dcSDimitry Andric SmallVector<ELFFileBase *, 0> elf::objectFiles; 520eae32dcSDimitry Andric SmallVector<SharedFile *, 0> elf::sharedFiles; 535ffd83dbSDimitry Andric 545ffd83dbSDimitry Andric std::unique_ptr<TarWriter> elf::tar; 555ffd83dbSDimitry Andric 5685868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 575ffd83dbSDimitry Andric std::string lld::toString(const InputFile *f) { 5885868e8aSDimitry Andric if (!f) 5985868e8aSDimitry Andric return "<internal>"; 600b57cec5SDimitry Andric 6185868e8aSDimitry Andric if (f->toStringCache.empty()) { 6285868e8aSDimitry Andric if (f->archiveName.empty()) 630eae32dcSDimitry Andric f->toStringCache = f->getName(); 6485868e8aSDimitry Andric else 650eae32dcSDimitry Andric (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache); 6685868e8aSDimitry Andric } 670eae32dcSDimitry Andric return std::string(f->toStringCache); 6885868e8aSDimitry Andric } 6985868e8aSDimitry Andric 700b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) { 710b57cec5SDimitry Andric unsigned char size; 720b57cec5SDimitry Andric unsigned char endian; 730b57cec5SDimitry Andric std::tie(size, endian) = getElfArchType(mb.getBuffer()); 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric auto report = [&](StringRef msg) { 760b57cec5SDimitry Andric StringRef filename = mb.getBufferIdentifier(); 770b57cec5SDimitry Andric if (archiveName.empty()) 780b57cec5SDimitry Andric fatal(filename + ": " + msg); 790b57cec5SDimitry Andric else 800b57cec5SDimitry Andric fatal(archiveName + "(" + filename + "): " + msg); 810b57cec5SDimitry Andric }; 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric if (!mb.getBuffer().startswith(ElfMagic)) 840b57cec5SDimitry Andric report("not an ELF file"); 850b57cec5SDimitry Andric if (endian != ELFDATA2LSB && endian != ELFDATA2MSB) 860b57cec5SDimitry Andric report("corrupted ELF file: invalid data encoding"); 870b57cec5SDimitry Andric if (size != ELFCLASS32 && size != ELFCLASS64) 880b57cec5SDimitry Andric report("corrupted ELF file: invalid file class"); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric size_t bufSize = mb.getBuffer().size(); 910b57cec5SDimitry Andric if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) || 920b57cec5SDimitry Andric (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr))) 930b57cec5SDimitry Andric report("corrupted ELF file: file is too short"); 940b57cec5SDimitry Andric 950b57cec5SDimitry Andric if (size == ELFCLASS32) 960b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 970b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 980b57cec5SDimitry Andric } 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m) 1010b57cec5SDimitry Andric : mb(m), groupId(nextGroupId), fileKind(k) { 1020b57cec5SDimitry Andric // All files within the same --{start,end}-group get the same group ID. 1030b57cec5SDimitry Andric // Otherwise, a new file will get a new group ID. 1040b57cec5SDimitry Andric if (!isInGroup) 1050b57cec5SDimitry Andric ++nextGroupId; 1060b57cec5SDimitry Andric } 1070b57cec5SDimitry Andric 1085ffd83dbSDimitry Andric Optional<MemoryBufferRef> elf::readFile(StringRef path) { 109e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files", path); 110e8d8bef9SDimitry Andric 1110b57cec5SDimitry Andric // The --chroot option changes our virtual root directory. 1120b57cec5SDimitry Andric // This is useful when you are dealing with files created by --reproduce. 1130b57cec5SDimitry Andric if (!config->chroot.empty() && path.startswith("/")) 11404eeddc0SDimitry Andric path = saver().save(config->chroot + path); 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric log(path); 117e8d8bef9SDimitry Andric config->dependencyFiles.insert(llvm::CachedHashString(path)); 1180b57cec5SDimitry Andric 119fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 120fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false); 1210b57cec5SDimitry Andric if (auto ec = mbOrErr.getError()) { 1220b57cec5SDimitry Andric error("cannot open " + path + ": " + ec.message()); 1230b57cec5SDimitry Andric return None; 1240b57cec5SDimitry Andric } 1250b57cec5SDimitry Andric 12604eeddc0SDimitry Andric MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef(); 12704eeddc0SDimitry Andric memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership 1280b57cec5SDimitry Andric 1290b57cec5SDimitry Andric if (tar) 1300b57cec5SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 1310b57cec5SDimitry Andric return mbref; 1320b57cec5SDimitry Andric } 1330b57cec5SDimitry Andric 1340b57cec5SDimitry Andric // All input object files must be for the same architecture 1350b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with 1360b57cec5SDimitry Andric // MIPS object files.) This function checks for that error. 1370b57cec5SDimitry Andric static bool isCompatible(InputFile *file) { 1380b57cec5SDimitry Andric if (!file->isElf() && !isa<BitcodeFile>(file)) 1390b57cec5SDimitry Andric return true; 1400b57cec5SDimitry Andric 1410b57cec5SDimitry Andric if (file->ekind == config->ekind && file->emachine == config->emachine) { 1420b57cec5SDimitry Andric if (config->emachine != EM_MIPS) 1430b57cec5SDimitry Andric return true; 1440b57cec5SDimitry Andric if (isMipsN32Abi(file) == config->mipsN32Abi) 1450b57cec5SDimitry Andric return true; 1460b57cec5SDimitry Andric } 1470b57cec5SDimitry Andric 1485ffd83dbSDimitry Andric StringRef target = 1495ffd83dbSDimitry Andric !config->bfdname.empty() ? config->bfdname : config->emulation; 1505ffd83dbSDimitry Andric if (!target.empty()) { 1515ffd83dbSDimitry Andric error(toString(file) + " is incompatible with " + target); 15285868e8aSDimitry Andric return false; 15385868e8aSDimitry Andric } 15485868e8aSDimitry Andric 1550b57cec5SDimitry Andric InputFile *existing; 1560b57cec5SDimitry Andric if (!objectFiles.empty()) 1570b57cec5SDimitry Andric existing = objectFiles[0]; 1580b57cec5SDimitry Andric else if (!sharedFiles.empty()) 1590b57cec5SDimitry Andric existing = sharedFiles[0]; 1605ffd83dbSDimitry Andric else if (!bitcodeFiles.empty()) 1610b57cec5SDimitry Andric existing = bitcodeFiles[0]; 1625ffd83dbSDimitry Andric else 1635ffd83dbSDimitry Andric llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to " 1645ffd83dbSDimitry Andric "determine target emulation"); 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric error(toString(file) + " is incompatible with " + toString(existing)); 1670b57cec5SDimitry Andric return false; 1680b57cec5SDimitry Andric } 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) { 1710b57cec5SDimitry Andric if (!isCompatible(file)) 1720b57cec5SDimitry Andric return; 1730b57cec5SDimitry Andric 1740b57cec5SDimitry Andric // Binary file 1750b57cec5SDimitry Andric if (auto *f = dyn_cast<BinaryFile>(file)) { 1760b57cec5SDimitry Andric binaryFiles.push_back(f); 1770b57cec5SDimitry Andric f->parse(); 1780b57cec5SDimitry Andric return; 1790b57cec5SDimitry Andric } 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric // .a file 1820b57cec5SDimitry Andric if (auto *f = dyn_cast<ArchiveFile>(file)) { 1835ffd83dbSDimitry Andric archiveFiles.push_back(f); 1840b57cec5SDimitry Andric f->parse(); 1850b57cec5SDimitry Andric return; 1860b57cec5SDimitry Andric } 1870b57cec5SDimitry Andric 1880b57cec5SDimitry Andric // Lazy object file 1890eae32dcSDimitry Andric if (file->lazy) { 1900eae32dcSDimitry Andric if (auto *f = dyn_cast<BitcodeFile>(file)) { 1910eae32dcSDimitry Andric lazyBitcodeFiles.push_back(f); 1920eae32dcSDimitry Andric f->parseLazy(); 1930eae32dcSDimitry Andric } else { 1940eae32dcSDimitry Andric cast<ObjFile<ELFT>>(file)->parseLazy(); 1950eae32dcSDimitry Andric } 1960b57cec5SDimitry Andric return; 1970b57cec5SDimitry Andric } 1980b57cec5SDimitry Andric 1990b57cec5SDimitry Andric if (config->trace) 2000b57cec5SDimitry Andric message(toString(file)); 2010b57cec5SDimitry Andric 2020b57cec5SDimitry Andric // .so file 2030b57cec5SDimitry Andric if (auto *f = dyn_cast<SharedFile>(file)) { 2040b57cec5SDimitry Andric f->parse<ELFT>(); 2050b57cec5SDimitry Andric return; 2060b57cec5SDimitry Andric } 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric // LLVM bitcode file 2090b57cec5SDimitry Andric if (auto *f = dyn_cast<BitcodeFile>(file)) { 2100b57cec5SDimitry Andric bitcodeFiles.push_back(f); 2110b57cec5SDimitry Andric f->parse<ELFT>(); 2120b57cec5SDimitry Andric return; 2130b57cec5SDimitry Andric } 2140b57cec5SDimitry Andric 2150b57cec5SDimitry Andric // Regular object file 2160eae32dcSDimitry Andric objectFiles.push_back(cast<ELFFileBase>(file)); 2170b57cec5SDimitry Andric cast<ObjFile<ELFT>>(file)->parse(); 2180b57cec5SDimitry Andric } 2190b57cec5SDimitry Andric 2200b57cec5SDimitry Andric // Add symbols in File to the symbol table. 221*1fd87a68SDimitry Andric void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); } 2220b57cec5SDimitry Andric 2230b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location. 2240b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) { 2255ffd83dbSDimitry Andric std::string filename = std::string(path::filename(path)); 2260b57cec5SDimitry Andric std::string lineno = ":" + std::to_string(line); 2270b57cec5SDimitry Andric if (filename == path) 2280b57cec5SDimitry Andric return filename + lineno; 2290b57cec5SDimitry Andric return filename + lineno + " (" + path.str() + lineno + ")"; 2300b57cec5SDimitry Andric } 2310b57cec5SDimitry Andric 2320b57cec5SDimitry Andric template <class ELFT> 2330b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym, 2340b57cec5SDimitry Andric InputSectionBase &sec, uint64_t offset) { 2350b57cec5SDimitry Andric // In DWARF, functions and variables are stored to different places. 2360b57cec5SDimitry Andric // First, lookup a function for a given offset. 2370b57cec5SDimitry Andric if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset)) 2380b57cec5SDimitry Andric return createFileLineMsg(info->FileName, info->Line); 2390b57cec5SDimitry Andric 2400b57cec5SDimitry Andric // If it failed, lookup again as a variable. 2410b57cec5SDimitry Andric if (Optional<std::pair<std::string, unsigned>> fileLine = 2420b57cec5SDimitry Andric file.getVariableLoc(sym.getName())) 2430b57cec5SDimitry Andric return createFileLineMsg(fileLine->first, fileLine->second); 2440b57cec5SDimitry Andric 2450b57cec5SDimitry Andric // File.sourceFile contains STT_FILE symbol, and that is a last resort. 2465ffd83dbSDimitry Andric return std::string(file.sourceFile); 2470b57cec5SDimitry Andric } 2480b57cec5SDimitry Andric 2490b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec, 2500b57cec5SDimitry Andric uint64_t offset) { 2510b57cec5SDimitry Andric if (kind() != ObjKind) 2520b57cec5SDimitry Andric return ""; 2530b57cec5SDimitry Andric switch (config->ekind) { 2540b57cec5SDimitry Andric default: 2550b57cec5SDimitry Andric llvm_unreachable("Invalid kind"); 2560b57cec5SDimitry Andric case ELF32LEKind: 2570b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset); 2580b57cec5SDimitry Andric case ELF32BEKind: 2590b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset); 2600b57cec5SDimitry Andric case ELF64LEKind: 2610b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset); 2620b57cec5SDimitry Andric case ELF64BEKind: 2630b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset); 2640b57cec5SDimitry Andric } 2650b57cec5SDimitry Andric } 2660b57cec5SDimitry Andric 267e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const { 268e8d8bef9SDimitry Andric if (archiveName.empty()) 269e8d8bef9SDimitry Andric return getName(); 270e8d8bef9SDimitry Andric 271e8d8bef9SDimitry Andric if (nameForScriptCache.empty()) 272e8d8bef9SDimitry Andric nameForScriptCache = (archiveName + Twine(':') + getName()).str(); 273e8d8bef9SDimitry Andric 274e8d8bef9SDimitry Andric return nameForScriptCache; 275e8d8bef9SDimitry Andric } 276e8d8bef9SDimitry Andric 2775ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() { 2785ffd83dbSDimitry Andric llvm::call_once(initDwarf, [this]() { 2795ffd83dbSDimitry Andric dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 2805ffd83dbSDimitry Andric std::make_unique<LLDDwarfObj<ELFT>>(this), "", 2815ffd83dbSDimitry Andric [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 2825ffd83dbSDimitry Andric [&](Error warning) { 2835ffd83dbSDimitry Andric warn(getName() + ": " + toString(std::move(warning))); 2845ffd83dbSDimitry Andric })); 2855ffd83dbSDimitry Andric }); 2865ffd83dbSDimitry Andric 2875ffd83dbSDimitry Andric return dwarf.get(); 2880b57cec5SDimitry Andric } 2890b57cec5SDimitry Andric 2900b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data 2910b57cec5SDimitry Andric // object (variable, array, etc) definition. 2920b57cec5SDimitry Andric template <class ELFT> 2930b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>> 2940b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) { 2955ffd83dbSDimitry Andric return getDwarf()->getVariableLoc(name); 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric // Returns source line information for a given offset 2990b57cec5SDimitry Andric // using DWARF debug info. 3000b57cec5SDimitry Andric template <class ELFT> 3010b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s, 3020b57cec5SDimitry Andric uint64_t offset) { 3030b57cec5SDimitry Andric // Detect SectionIndex for specified section. 3040b57cec5SDimitry Andric uint64_t sectionIndex = object::SectionedAddress::UndefSection; 3050b57cec5SDimitry Andric ArrayRef<InputSectionBase *> sections = s->file->getSections(); 3060b57cec5SDimitry Andric for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) { 3070b57cec5SDimitry Andric if (s == sections[curIndex]) { 3080b57cec5SDimitry Andric sectionIndex = curIndex; 3090b57cec5SDimitry Andric break; 3100b57cec5SDimitry Andric } 3110b57cec5SDimitry Andric } 3120b57cec5SDimitry Andric 3135ffd83dbSDimitry Andric return getDwarf()->getDILineInfo(offset, sectionIndex); 3140b57cec5SDimitry Andric } 3150b57cec5SDimitry Andric 3160b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) { 3170b57cec5SDimitry Andric ekind = getELFKind(mb, ""); 3180b57cec5SDimitry Andric 3190b57cec5SDimitry Andric switch (ekind) { 3200b57cec5SDimitry Andric case ELF32LEKind: 3210b57cec5SDimitry Andric init<ELF32LE>(); 3220b57cec5SDimitry Andric break; 3230b57cec5SDimitry Andric case ELF32BEKind: 3240b57cec5SDimitry Andric init<ELF32BE>(); 3250b57cec5SDimitry Andric break; 3260b57cec5SDimitry Andric case ELF64LEKind: 3270b57cec5SDimitry Andric init<ELF64LE>(); 3280b57cec5SDimitry Andric break; 3290b57cec5SDimitry Andric case ELF64BEKind: 3300b57cec5SDimitry Andric init<ELF64BE>(); 3310b57cec5SDimitry Andric break; 3320b57cec5SDimitry Andric default: 3330b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 3340b57cec5SDimitry Andric } 3350b57cec5SDimitry Andric } 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric template <typename Elf_Shdr> 3380b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) { 3390b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) 3400b57cec5SDimitry Andric if (sec.sh_type == type) 3410b57cec5SDimitry Andric return &sec; 3420b57cec5SDimitry Andric return nullptr; 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric 3450b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() { 3460b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 3470b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric // Initialize trivial attributes. 3500b57cec5SDimitry Andric const ELFFile<ELFT> &obj = getObj<ELFT>(); 351e8d8bef9SDimitry Andric emachine = obj.getHeader().e_machine; 352e8d8bef9SDimitry Andric osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI]; 353e8d8bef9SDimitry Andric abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION]; 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this); 3560eae32dcSDimitry Andric elfShdrs = sections.data(); 3570eae32dcSDimitry Andric numELFShdrs = sections.size(); 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric // Find a symbol table. 3600b57cec5SDimitry Andric bool isDSO = 3610b57cec5SDimitry Andric (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object); 3620b57cec5SDimitry Andric const Elf_Shdr *symtabSec = 3630b57cec5SDimitry Andric findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB); 3640b57cec5SDimitry Andric 3650b57cec5SDimitry Andric if (!symtabSec) 3660b57cec5SDimitry Andric return; 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric // Initialize members corresponding to a symbol table. 3690b57cec5SDimitry Andric firstGlobal = symtabSec->sh_info; 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this); 3720b57cec5SDimitry Andric if (firstGlobal == 0 || firstGlobal > eSyms.size()) 3730b57cec5SDimitry Andric fatal(toString(this) + ": invalid sh_info in symbol table"); 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric elfSyms = reinterpret_cast<const void *>(eSyms.data()); 3760eae32dcSDimitry Andric numELFSyms = uint32_t(eSyms.size()); 3770b57cec5SDimitry Andric stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this); 3780b57cec5SDimitry Andric } 3790b57cec5SDimitry Andric 3800b57cec5SDimitry Andric template <class ELFT> 3810b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const { 3820b57cec5SDimitry Andric return CHECK( 383e8d8bef9SDimitry Andric this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable), 3840b57cec5SDimitry Andric this); 3850b57cec5SDimitry Andric } 3860b57cec5SDimitry Andric 3870b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) { 388*1fd87a68SDimitry Andric object::ELFFile<ELFT> obj = this->getObj(); 3890b57cec5SDimitry Andric // Read a section table. justSymbols is usually false. 3900b57cec5SDimitry Andric if (this->justSymbols) 3910b57cec5SDimitry Andric initializeJustSymbols(); 3920b57cec5SDimitry Andric else 393*1fd87a68SDimitry Andric initializeSections(ignoreComdats, obj); 3940b57cec5SDimitry Andric 3950b57cec5SDimitry Andric // Read a symbol table. 396*1fd87a68SDimitry Andric initializeSymbols(obj); 3970b57cec5SDimitry Andric } 3980b57cec5SDimitry Andric 3990b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups. 4000b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function 4010b57cec5SDimitry Andric // returns a group name. 4020b57cec5SDimitry Andric template <class ELFT> 4030b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections, 4040b57cec5SDimitry Andric const Elf_Shdr &sec) { 4050b57cec5SDimitry Andric typename ELFT::SymRange symbols = this->getELFSyms<ELFT>(); 4060b57cec5SDimitry Andric if (sec.sh_info >= symbols.size()) 4070b57cec5SDimitry Andric fatal(toString(this) + ": invalid symbol index"); 4080b57cec5SDimitry Andric const typename ELFT::Sym &sym = symbols[sec.sh_info]; 409349cc55cSDimitry Andric return CHECK(sym.getName(this->stringTable), this); 4100b57cec5SDimitry Andric } 4110b57cec5SDimitry Andric 41285868e8aSDimitry Andric template <class ELFT> 41385868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) { 4140b57cec5SDimitry Andric // On a regular link we don't merge sections if -O0 (default is -O1). This 4150b57cec5SDimitry Andric // sometimes makes the linker significantly faster, although the output will 4160b57cec5SDimitry Andric // be bigger. 4170b57cec5SDimitry Andric // 4180b57cec5SDimitry Andric // Doing the same for -r would create a problem as it would combine sections 4190b57cec5SDimitry Andric // with different sh_entsize. One option would be to just copy every SHF_MERGE 4200b57cec5SDimitry Andric // section as is to the output. While this would produce a valid ELF file with 4210b57cec5SDimitry Andric // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when 4220b57cec5SDimitry Andric // they see two .debug_str. We could have separate logic for combining 4230b57cec5SDimitry Andric // SHF_MERGE sections based both on their name and sh_entsize, but that seems 4240b57cec5SDimitry Andric // to be more trouble than it is worth. Instead, we just use the regular (-O1) 4250b57cec5SDimitry Andric // logic for -r. 4260b57cec5SDimitry Andric if (config->optimize == 0 && !config->relocatable) 4270b57cec5SDimitry Andric return false; 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric // A mergeable section with size 0 is useless because they don't have 4300b57cec5SDimitry Andric // any data to merge. A mergeable string section with size 0 can be 4310b57cec5SDimitry Andric // argued as invalid because it doesn't end with a null character. 4320b57cec5SDimitry Andric // We'll avoid a mess by handling them as if they were non-mergeable. 4330b57cec5SDimitry Andric if (sec.sh_size == 0) 4340b57cec5SDimitry Andric return false; 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric // Check for sh_entsize. The ELF spec is not clear about the zero 4370b57cec5SDimitry Andric // sh_entsize. It says that "the member [sh_entsize] contains 0 if 4380b57cec5SDimitry Andric // the section does not hold a table of fixed-size entries". We know 4390b57cec5SDimitry Andric // that Rust 1.13 produces a string mergeable section with a zero 4400b57cec5SDimitry Andric // sh_entsize. Here we just accept it rather than being picky about it. 4410b57cec5SDimitry Andric uint64_t entSize = sec.sh_entsize; 4420b57cec5SDimitry Andric if (entSize == 0) 4430b57cec5SDimitry Andric return false; 4440b57cec5SDimitry Andric if (sec.sh_size % entSize) 44585868e8aSDimitry Andric fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" + 44685868e8aSDimitry Andric Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" + 44785868e8aSDimitry Andric Twine(entSize) + ")"); 4480b57cec5SDimitry Andric 4495ffd83dbSDimitry Andric if (sec.sh_flags & SHF_WRITE) 45085868e8aSDimitry Andric fatal(toString(this) + ":(" + name + 45185868e8aSDimitry Andric "): writable SHF_MERGE section is not supported"); 4520b57cec5SDimitry Andric 4530b57cec5SDimitry Andric return true; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric // This is for --just-symbols. 4570b57cec5SDimitry Andric // 4580b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your 4590b57cec5SDimitry Andric // output against other existing program, so that if you load both your 4600b57cec5SDimitry Andric // program and the other program into memory, your output can refer the 4610b57cec5SDimitry Andric // other program's symbols. 4620b57cec5SDimitry Andric // 4630b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is 4640b57cec5SDimitry Andric // initialized with null pointers. 4650b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() { 4660eae32dcSDimitry Andric sections.resize(numELFShdrs); 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the 4700b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This 4710b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking 4720b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension 4730b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently 4740b57cec5SDimitry Andric // unique to LLVM and lld. 4750b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) { 4760b57cec5SDimitry Andric if (!config->dependentLibraries) 4770b57cec5SDimitry Andric return; 478*1fd87a68SDimitry Andric if (Optional<std::string> s = searchLibraryBaseName(specifier)) 479*1fd87a68SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 4800b57cec5SDimitry Andric else if (Optional<std::string> s = findFromSearchPaths(specifier)) 4810b57cec5SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 482*1fd87a68SDimitry Andric else if (fs::exists(specifier)) 483*1fd87a68SDimitry Andric driver->addFile(specifier, /*withLOption=*/false); 4840b57cec5SDimitry Andric else 4850b57cec5SDimitry Andric error(toString(f) + 4860b57cec5SDimitry Andric ": unable to find library from dependent library specifier: " + 4870b57cec5SDimitry Andric specifier); 4880b57cec5SDimitry Andric } 4890b57cec5SDimitry Andric 490480093f4SDimitry Andric // Record the membership of a section group so that in the garbage collection 491480093f4SDimitry Andric // pass, section group members are kept or discarded as a unit. 492480093f4SDimitry Andric template <class ELFT> 493480093f4SDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections, 494480093f4SDimitry Andric ArrayRef<typename ELFT::Word> entries) { 495480093f4SDimitry Andric bool hasAlloc = false; 496480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 497480093f4SDimitry Andric if (index >= sections.size()) 498480093f4SDimitry Andric return; 499480093f4SDimitry Andric if (InputSectionBase *s = sections[index]) 500480093f4SDimitry Andric if (s != &InputSection::discarded && s->flags & SHF_ALLOC) 501480093f4SDimitry Andric hasAlloc = true; 502480093f4SDimitry Andric } 503480093f4SDimitry Andric 504480093f4SDimitry Andric // If any member has the SHF_ALLOC flag, the whole group is subject to garbage 505480093f4SDimitry Andric // collection. See the comment in markLive(). This rule retains .debug_types 506480093f4SDimitry Andric // and .rela.debug_types. 507480093f4SDimitry Andric if (!hasAlloc) 508480093f4SDimitry Andric return; 509480093f4SDimitry Andric 510480093f4SDimitry Andric // Connect the members in a circular doubly-linked list via 511480093f4SDimitry Andric // nextInSectionGroup. 512480093f4SDimitry Andric InputSectionBase *head; 513480093f4SDimitry Andric InputSectionBase *prev = nullptr; 514480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 515480093f4SDimitry Andric InputSectionBase *s = sections[index]; 516480093f4SDimitry Andric if (!s || s == &InputSection::discarded) 517480093f4SDimitry Andric continue; 518480093f4SDimitry Andric if (prev) 519480093f4SDimitry Andric prev->nextInSectionGroup = s; 520480093f4SDimitry Andric else 521480093f4SDimitry Andric head = s; 522480093f4SDimitry Andric prev = s; 523480093f4SDimitry Andric } 524480093f4SDimitry Andric if (prev) 525480093f4SDimitry Andric prev->nextInSectionGroup = head; 526480093f4SDimitry Andric } 527480093f4SDimitry Andric 5280b57cec5SDimitry Andric template <class ELFT> 529*1fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats, 530*1fd87a68SDimitry Andric const llvm::object::ELFFile<ELFT> &obj) { 5310eae32dcSDimitry Andric ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>(); 532349cc55cSDimitry Andric StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this); 5330b57cec5SDimitry Andric uint64_t size = objSections.size(); 5340b57cec5SDimitry Andric this->sections.resize(size); 5350b57cec5SDimitry Andric 536480093f4SDimitry Andric std::vector<ArrayRef<Elf_Word>> selectedGroups; 537480093f4SDimitry Andric 53804eeddc0SDimitry Andric for (size_t i = 0; i != size; ++i) { 5390b57cec5SDimitry Andric if (this->sections[i] == &InputSection::discarded) 5400b57cec5SDimitry Andric continue; 5410b57cec5SDimitry Andric const Elf_Shdr &sec = objSections[i]; 5420b57cec5SDimitry Andric 5430b57cec5SDimitry Andric // SHF_EXCLUDE'ed sections are discarded by the linker. However, 5440b57cec5SDimitry Andric // if -r is given, we'll let the final link discard such sections. 5450b57cec5SDimitry Andric // This is compatible with GNU. 5460b57cec5SDimitry Andric if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) { 5470eae32dcSDimitry Andric if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE) 5480eae32dcSDimitry Andric cgProfileSectionIndex = i; 5490b57cec5SDimitry Andric if (sec.sh_type == SHT_LLVM_ADDRSIG) { 5500b57cec5SDimitry Andric // We ignore the address-significance table if we know that the object 5510b57cec5SDimitry Andric // file was created by objcopy or ld -r. This is because these tools 5520b57cec5SDimitry Andric // will reorder the symbols in the symbol table, invalidating the data 5530b57cec5SDimitry Andric // in the address-significance table, which refers to symbols by index. 5540b57cec5SDimitry Andric if (sec.sh_link != 0) 5550b57cec5SDimitry Andric this->addrsigSec = &sec; 5560b57cec5SDimitry Andric else if (config->icf == ICFLevel::Safe) 557fe6060f1SDimitry Andric warn(toString(this) + 558fe6060f1SDimitry Andric ": --icf=safe conservatively ignores " 559fe6060f1SDimitry Andric "SHT_LLVM_ADDRSIG [index " + 560fe6060f1SDimitry Andric Twine(i) + 561fe6060f1SDimitry Andric "] with sh_link=0 " 562fe6060f1SDimitry Andric "(likely created using objcopy or ld -r)"); 5630b57cec5SDimitry Andric } 5640b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 5650b57cec5SDimitry Andric continue; 5660b57cec5SDimitry Andric } 5670b57cec5SDimitry Andric 5680b57cec5SDimitry Andric switch (sec.sh_type) { 5690b57cec5SDimitry Andric case SHT_GROUP: { 5700b57cec5SDimitry Andric // De-duplicate section groups by their signatures. 5710b57cec5SDimitry Andric StringRef signature = getShtGroupSignature(objSections, sec); 5720b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 5730b57cec5SDimitry Andric 5740b57cec5SDimitry Andric ArrayRef<Elf_Word> entries = 575e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this); 5760b57cec5SDimitry Andric if (entries.empty()) 5770b57cec5SDimitry Andric fatal(toString(this) + ": empty SHT_GROUP"); 5780b57cec5SDimitry Andric 579fe6060f1SDimitry Andric Elf_Word flag = entries[0]; 580fe6060f1SDimitry Andric if (flag && flag != GRP_COMDAT) 5810b57cec5SDimitry Andric fatal(toString(this) + ": unsupported SHT_GROUP format"); 5820b57cec5SDimitry Andric 583fe6060f1SDimitry Andric bool keepGroup = 584fe6060f1SDimitry Andric (flag & GRP_COMDAT) == 0 || ignoreComdats || 5850b57cec5SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this) 5860b57cec5SDimitry Andric .second; 587fe6060f1SDimitry Andric if (keepGroup) { 5880b57cec5SDimitry Andric if (config->relocatable) 589*1fd87a68SDimitry Andric this->sections[i] = createInputSection( 590*1fd87a68SDimitry Andric i, sec, check(obj.getSectionName(sec, shstrtab))); 591480093f4SDimitry Andric selectedGroups.push_back(entries); 5920b57cec5SDimitry Andric continue; 5930b57cec5SDimitry Andric } 5940b57cec5SDimitry Andric 5950b57cec5SDimitry Andric // Otherwise, discard group members. 5960b57cec5SDimitry Andric for (uint32_t secIndex : entries.slice(1)) { 5970b57cec5SDimitry Andric if (secIndex >= size) 5980b57cec5SDimitry Andric fatal(toString(this) + 5990b57cec5SDimitry Andric ": invalid section index in group: " + Twine(secIndex)); 6000b57cec5SDimitry Andric this->sections[secIndex] = &InputSection::discarded; 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric break; 6030b57cec5SDimitry Andric } 6040b57cec5SDimitry Andric case SHT_SYMTAB_SHNDX: 6050b57cec5SDimitry Andric shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this); 6060b57cec5SDimitry Andric break; 6070b57cec5SDimitry Andric case SHT_SYMTAB: 6080b57cec5SDimitry Andric case SHT_STRTAB: 6095ffd83dbSDimitry Andric case SHT_REL: 6105ffd83dbSDimitry Andric case SHT_RELA: 6110b57cec5SDimitry Andric case SHT_NULL: 6120b57cec5SDimitry Andric break; 6130b57cec5SDimitry Andric default: 614*1fd87a68SDimitry Andric this->sections[i] = 615*1fd87a68SDimitry Andric createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab))); 6160b57cec5SDimitry Andric } 61785868e8aSDimitry Andric } 61885868e8aSDimitry Andric 6195ffd83dbSDimitry Andric // We have a second loop. It is used to: 6205ffd83dbSDimitry Andric // 1) handle SHF_LINK_ORDER sections. 6215ffd83dbSDimitry Andric // 2) create SHT_REL[A] sections. In some cases the section header index of a 6225ffd83dbSDimitry Andric // relocation section may be smaller than that of the relocated section. In 6235ffd83dbSDimitry Andric // such cases, the relocation section would attempt to reference a target 6245ffd83dbSDimitry Andric // section that has not yet been created. For simplicity, delay creation of 6255ffd83dbSDimitry Andric // relocation sections until now. 62604eeddc0SDimitry Andric for (size_t i = 0; i != size; ++i) { 62785868e8aSDimitry Andric if (this->sections[i] == &InputSection::discarded) 62885868e8aSDimitry Andric continue; 62985868e8aSDimitry Andric const Elf_Shdr &sec = objSections[i]; 6305ffd83dbSDimitry Andric 63104eeddc0SDimitry Andric if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) { 63204eeddc0SDimitry Andric // Find a relocation target section and associate this section with that. 63304eeddc0SDimitry Andric // Target may have been discarded if it is in a different section group 63404eeddc0SDimitry Andric // and the group is discarded, even though it's a violation of the spec. 63504eeddc0SDimitry Andric // We handle that situation gracefully by discarding dangling relocation 63604eeddc0SDimitry Andric // sections. 63704eeddc0SDimitry Andric const uint32_t info = sec.sh_info; 63804eeddc0SDimitry Andric InputSectionBase *s = getRelocTarget(i, sec, info); 63904eeddc0SDimitry Andric if (!s) 64004eeddc0SDimitry Andric continue; 64104eeddc0SDimitry Andric 64204eeddc0SDimitry Andric // ELF spec allows mergeable sections with relocations, but they are rare, 64304eeddc0SDimitry Andric // and it is in practice hard to merge such sections by contents, because 64404eeddc0SDimitry Andric // applying relocations at end of linking changes section contents. So, we 64504eeddc0SDimitry Andric // simply handle such sections as non-mergeable ones. Degrading like this 64604eeddc0SDimitry Andric // is acceptable because section merging is optional. 64704eeddc0SDimitry Andric if (auto *ms = dyn_cast<MergeInputSection>(s)) { 64804eeddc0SDimitry Andric s = make<InputSection>(ms->file, ms->flags, ms->type, ms->alignment, 64904eeddc0SDimitry Andric ms->data(), ms->name); 65004eeddc0SDimitry Andric sections[info] = s; 65104eeddc0SDimitry Andric } 65204eeddc0SDimitry Andric 65304eeddc0SDimitry Andric if (s->relSecIdx != 0) 65404eeddc0SDimitry Andric error( 65504eeddc0SDimitry Andric toString(s) + 65604eeddc0SDimitry Andric ": multiple relocation sections to one section are not supported"); 65704eeddc0SDimitry Andric s->relSecIdx = i; 65804eeddc0SDimitry Andric 65904eeddc0SDimitry Andric // Relocation sections are usually removed from the output, so return 66004eeddc0SDimitry Andric // `nullptr` for the normal case. However, if -r or --emit-relocs is 66104eeddc0SDimitry Andric // specified, we need to copy them to the output. (Some post link analysis 66204eeddc0SDimitry Andric // tools specify --emit-relocs to obtain the information.) 66304eeddc0SDimitry Andric if (config->copyRelocs) { 66404eeddc0SDimitry Andric auto *isec = make<InputSection>( 66504eeddc0SDimitry Andric *this, sec, check(obj.getSectionName(sec, shstrtab))); 66604eeddc0SDimitry Andric // If the relocated section is discarded (due to /DISCARD/ or 66704eeddc0SDimitry Andric // --gc-sections), the relocation section should be discarded as well. 66804eeddc0SDimitry Andric s->dependentSections.push_back(isec); 66904eeddc0SDimitry Andric sections[i] = isec; 67004eeddc0SDimitry Andric } 67104eeddc0SDimitry Andric continue; 67204eeddc0SDimitry Andric } 6735ffd83dbSDimitry Andric 674e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have 675e8d8bef9SDimitry Andric // the flag. 67604eeddc0SDimitry Andric if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER)) 67785868e8aSDimitry Andric continue; 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric InputSectionBase *linkSec = nullptr; 68004eeddc0SDimitry Andric if (sec.sh_link < size) 6810b57cec5SDimitry Andric linkSec = this->sections[sec.sh_link]; 6820b57cec5SDimitry Andric if (!linkSec) 68385868e8aSDimitry Andric fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link)); 6840b57cec5SDimitry Andric 685e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section is discarded if its linked-to section is 686e8d8bef9SDimitry Andric // discarded. 6870b57cec5SDimitry Andric InputSection *isec = cast<InputSection>(this->sections[i]); 6880b57cec5SDimitry Andric linkSec->dependentSections.push_back(isec); 6890b57cec5SDimitry Andric if (!isa<InputSection>(linkSec)) 6900b57cec5SDimitry Andric error("a section " + isec->name + 69185868e8aSDimitry Andric " with SHF_LINK_ORDER should not refer a non-regular section: " + 6920b57cec5SDimitry Andric toString(linkSec)); 6930b57cec5SDimitry Andric } 694480093f4SDimitry Andric 695480093f4SDimitry Andric for (ArrayRef<Elf_Word> entries : selectedGroups) 696480093f4SDimitry Andric handleSectionGroup<ELFT>(this->sections, entries); 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric 6990b57cec5SDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD 7000b57cec5SDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how 7010b57cec5SDimitry Andric // the input objects have been compiled. 7020b57cec5SDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes, 7030b57cec5SDimitry Andric const InputFile *f) { 7045ffd83dbSDimitry Andric Optional<unsigned> attr = 7055ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args); 7065ffd83dbSDimitry Andric if (!attr.hasValue()) 7070b57cec5SDimitry Andric // If an ABI tag isn't present then it is implicitly given the value of 0 7080b57cec5SDimitry Andric // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files, 7090b57cec5SDimitry Andric // including some in glibc that don't use FP args (and should have value 3) 7100b57cec5SDimitry Andric // don't have the attribute so we do not consider an implicit value of 0 7110b57cec5SDimitry Andric // as a clash. 7120b57cec5SDimitry Andric return; 7130b57cec5SDimitry Andric 7145ffd83dbSDimitry Andric unsigned vfpArgs = attr.getValue(); 7150b57cec5SDimitry Andric ARMVFPArgKind arg; 7160b57cec5SDimitry Andric switch (vfpArgs) { 7170b57cec5SDimitry Andric case ARMBuildAttrs::BaseAAPCS: 7180b57cec5SDimitry Andric arg = ARMVFPArgKind::Base; 7190b57cec5SDimitry Andric break; 7200b57cec5SDimitry Andric case ARMBuildAttrs::HardFPAAPCS: 7210b57cec5SDimitry Andric arg = ARMVFPArgKind::VFP; 7220b57cec5SDimitry Andric break; 7230b57cec5SDimitry Andric case ARMBuildAttrs::ToolChainFPPCS: 7240b57cec5SDimitry Andric // Tool chain specific convention that conforms to neither AAPCS variant. 7250b57cec5SDimitry Andric arg = ARMVFPArgKind::ToolChain; 7260b57cec5SDimitry Andric break; 7270b57cec5SDimitry Andric case ARMBuildAttrs::CompatibleFPAAPCS: 7280b57cec5SDimitry Andric // Object compatible with all conventions. 7290b57cec5SDimitry Andric return; 7300b57cec5SDimitry Andric default: 7310b57cec5SDimitry Andric error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs)); 7320b57cec5SDimitry Andric return; 7330b57cec5SDimitry Andric } 7340b57cec5SDimitry Andric // Follow ld.bfd and error if there is a mix of calling conventions. 7350b57cec5SDimitry Andric if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default) 7360b57cec5SDimitry Andric error(toString(f) + ": incompatible Tag_ABI_VFP_args"); 7370b57cec5SDimitry Andric else 7380b57cec5SDimitry Andric config->armVFPArgs = arg; 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric // The ARM support in lld makes some use of instructions that are not available 7420b57cec5SDimitry Andric // on all ARM architectures. Namely: 7430b57cec5SDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state. 7440b57cec5SDimitry Andric // - Use of the extended Thumb branch encoding in relocation. 7450b57cec5SDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks. 7460b57cec5SDimitry Andric // The ARM Attributes section contains information about the architecture chosen 7470b57cec5SDimitry Andric // at compile time. We follow the convention that if at least one input object 7480b57cec5SDimitry Andric // is compiled with an architecture that supports these features then lld is 7490b57cec5SDimitry Andric // permitted to use them. 7500b57cec5SDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) { 7515ffd83dbSDimitry Andric Optional<unsigned> attr = 7525ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 7535ffd83dbSDimitry Andric if (!attr.hasValue()) 7540b57cec5SDimitry Andric return; 7555ffd83dbSDimitry Andric auto arch = attr.getValue(); 7560b57cec5SDimitry Andric switch (arch) { 7570b57cec5SDimitry Andric case ARMBuildAttrs::Pre_v4: 7580b57cec5SDimitry Andric case ARMBuildAttrs::v4: 7590b57cec5SDimitry Andric case ARMBuildAttrs::v4T: 7600b57cec5SDimitry Andric // Architectures prior to v5 do not support BLX instruction 7610b57cec5SDimitry Andric break; 7620b57cec5SDimitry Andric case ARMBuildAttrs::v5T: 7630b57cec5SDimitry Andric case ARMBuildAttrs::v5TE: 7640b57cec5SDimitry Andric case ARMBuildAttrs::v5TEJ: 7650b57cec5SDimitry Andric case ARMBuildAttrs::v6: 7660b57cec5SDimitry Andric case ARMBuildAttrs::v6KZ: 7670b57cec5SDimitry Andric case ARMBuildAttrs::v6K: 7680b57cec5SDimitry Andric config->armHasBlx = true; 7690b57cec5SDimitry Andric // Architectures used in pre-Cortex processors do not support 7700b57cec5SDimitry Andric // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 7710b57cec5SDimitry Andric // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 7720b57cec5SDimitry Andric break; 7730b57cec5SDimitry Andric default: 7740b57cec5SDimitry Andric // All other Architectures have BLX and extended branch encoding 7750b57cec5SDimitry Andric config->armHasBlx = true; 7760b57cec5SDimitry Andric config->armJ1J2BranchEncoding = true; 7770b57cec5SDimitry Andric if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M) 7780b57cec5SDimitry Andric // All Architectures used in Cortex processors with the exception 7790b57cec5SDimitry Andric // of v6-M and v6S-M have the MOVT and MOVW instructions. 7800b57cec5SDimitry Andric config->armHasMovtMovw = true; 7810b57cec5SDimitry Andric break; 7820b57cec5SDimitry Andric } 7830b57cec5SDimitry Andric } 7840b57cec5SDimitry Andric 7850b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control 7860b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that 7870b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it. 7880b57cec5SDimitry Andric // 7890b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this 7900b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a 7910b57cec5SDimitry Andric // .note.gnu.property section. 7920b57cec5SDimitry Andric // 7930b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists 7940b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a 7950b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps 7960b57cec5SDimitry Andric // the ABI is unnecessarily complicated. 797e8d8bef9SDimitry Andric template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) { 7980b57cec5SDimitry Andric using Elf_Nhdr = typename ELFT::Nhdr; 7990b57cec5SDimitry Andric using Elf_Note = typename ELFT::Note; 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric uint32_t featuresSet = 0; 802e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = sec.data(); 803e8d8bef9SDimitry Andric auto reportFatal = [&](const uint8_t *place, const char *msg) { 804e8d8bef9SDimitry Andric fatal(toString(sec.file) + ":(" + sec.name + "+0x" + 805e8d8bef9SDimitry Andric Twine::utohexstr(place - sec.data().data()) + "): " + msg); 806e8d8bef9SDimitry Andric }; 8070b57cec5SDimitry Andric while (!data.empty()) { 8080b57cec5SDimitry Andric // Read one NOTE record. 8090b57cec5SDimitry Andric auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data()); 810e8d8bef9SDimitry Andric if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize()) 811e8d8bef9SDimitry Andric reportFatal(data.data(), "data is too short"); 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric Elf_Note note(*nhdr); 8140b57cec5SDimitry Andric if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") { 8150b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8160b57cec5SDimitry Andric continue; 8170b57cec5SDimitry Andric } 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric uint32_t featureAndType = config->emachine == EM_AARCH64 8200b57cec5SDimitry Andric ? GNU_PROPERTY_AARCH64_FEATURE_1_AND 8210b57cec5SDimitry Andric : GNU_PROPERTY_X86_FEATURE_1_AND; 8220b57cec5SDimitry Andric 8230b57cec5SDimitry Andric // Read a body of a NOTE record, which consists of type-length-value fields. 8240b57cec5SDimitry Andric ArrayRef<uint8_t> desc = note.getDesc(); 8250b57cec5SDimitry Andric while (!desc.empty()) { 826e8d8bef9SDimitry Andric const uint8_t *place = desc.data(); 8270b57cec5SDimitry Andric if (desc.size() < 8) 828e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 829e8d8bef9SDimitry Andric uint32_t type = read32<ELFT::TargetEndianness>(desc.data()); 830e8d8bef9SDimitry Andric uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4); 831e8d8bef9SDimitry Andric desc = desc.slice(8); 832e8d8bef9SDimitry Andric if (desc.size() < size) 833e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 8340b57cec5SDimitry Andric 8350b57cec5SDimitry Andric if (type == featureAndType) { 8360b57cec5SDimitry Andric // We found a FEATURE_1_AND field. There may be more than one of these 837480093f4SDimitry Andric // in a .note.gnu.property section, for a relocatable object we 8380b57cec5SDimitry Andric // accumulate the bits set. 839e8d8bef9SDimitry Andric if (size < 4) 840e8d8bef9SDimitry Andric reportFatal(place, "FEATURE_1_AND entry is too short"); 841e8d8bef9SDimitry Andric featuresSet |= read32<ELFT::TargetEndianness>(desc.data()); 8420b57cec5SDimitry Andric } 8430b57cec5SDimitry Andric 844e8d8bef9SDimitry Andric // Padding is present in the note descriptor, if necessary. 845e8d8bef9SDimitry Andric desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size)); 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric // Go to next NOTE record to look for more FEATURE_1_AND descriptions. 8490b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8500b57cec5SDimitry Andric } 8510b57cec5SDimitry Andric 8520b57cec5SDimitry Andric return featuresSet; 8530b57cec5SDimitry Andric } 8540b57cec5SDimitry Andric 8550b57cec5SDimitry Andric template <class ELFT> 85604eeddc0SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, 85704eeddc0SDimitry Andric const Elf_Shdr &sec, 85804eeddc0SDimitry Andric uint32_t info) { 859349cc55cSDimitry Andric if (info < this->sections.size()) { 860349cc55cSDimitry Andric InputSectionBase *target = this->sections[info]; 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric // Strictly speaking, a relocation section must be included in the 8630b57cec5SDimitry Andric // group of the section it relocates. However, LLVM 3.3 and earlier 8640b57cec5SDimitry Andric // would fail to do so, so we gracefully handle that case. 8650b57cec5SDimitry Andric if (target == &InputSection::discarded) 8660b57cec5SDimitry Andric return nullptr; 8670b57cec5SDimitry Andric 868349cc55cSDimitry Andric if (target != nullptr) 8690b57cec5SDimitry Andric return target; 8700b57cec5SDimitry Andric } 8710b57cec5SDimitry Andric 87204eeddc0SDimitry Andric error(toString(this) + Twine(": relocation section (index ") + Twine(idx) + 87304eeddc0SDimitry Andric ") has invalid sh_info (" + Twine(info) + ")"); 874349cc55cSDimitry Andric return nullptr; 875349cc55cSDimitry Andric } 876349cc55cSDimitry Andric 8770b57cec5SDimitry Andric template <class ELFT> 878349cc55cSDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx, 879349cc55cSDimitry Andric const Elf_Shdr &sec, 880*1fd87a68SDimitry Andric StringRef name) { 881*1fd87a68SDimitry Andric if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) { 8820b57cec5SDimitry Andric ARMAttributeParser attributes; 883e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 8845ffd83dbSDimitry Andric if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind 8855ffd83dbSDimitry Andric ? support::little 8865ffd83dbSDimitry Andric : support::big)) { 8875ffd83dbSDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 8885ffd83dbSDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 889e8d8bef9SDimitry Andric } else { 8900b57cec5SDimitry Andric updateSupportedARMFeatures(attributes); 8910b57cec5SDimitry Andric updateARMVFPArgs(attributes, this); 8920b57cec5SDimitry Andric 8930b57cec5SDimitry Andric // FIXME: Retain the first attribute section we see. The eglibc ARM 8940b57cec5SDimitry Andric // dynamic loaders require the presence of an attribute section for dlopen 895e8d8bef9SDimitry Andric // to work. In a full implementation we would merge all attribute 896e8d8bef9SDimitry Andric // sections. 897e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 89804eeddc0SDimitry Andric in.attributes = std::make_unique<InputSection>(*this, sec, name); 89904eeddc0SDimitry Andric return in.attributes.get(); 9000b57cec5SDimitry Andric } 9010b57cec5SDimitry Andric return &InputSection::discarded; 9020b57cec5SDimitry Andric } 903e8d8bef9SDimitry Andric } 904e8d8bef9SDimitry Andric 905*1fd87a68SDimitry Andric if (sec.sh_type == SHT_RISCV_ATTRIBUTES && config->emachine == EM_RISCV) { 906e8d8bef9SDimitry Andric RISCVAttributeParser attributes; 907e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 908e8d8bef9SDimitry Andric if (Error e = attributes.parse(contents, support::little)) { 909e8d8bef9SDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 910e8d8bef9SDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 911e8d8bef9SDimitry Andric } else { 912e8d8bef9SDimitry Andric // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is 913e8d8bef9SDimitry Andric // present. 914e8d8bef9SDimitry Andric 915e8d8bef9SDimitry Andric // FIXME: Retain the first attribute section we see. Tools such as 916e8d8bef9SDimitry Andric // llvm-objdump make use of the attribute section to determine which 917e8d8bef9SDimitry Andric // standard extensions to enable. In a full implementation we would merge 918e8d8bef9SDimitry Andric // all attribute sections. 919e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 92004eeddc0SDimitry Andric in.attributes = std::make_unique<InputSection>(*this, sec, name); 92104eeddc0SDimitry Andric return in.attributes.get(); 922e8d8bef9SDimitry Andric } 923e8d8bef9SDimitry Andric return &InputSection::discarded; 924e8d8bef9SDimitry Andric } 925e8d8bef9SDimitry Andric } 926e8d8bef9SDimitry Andric 92704eeddc0SDimitry Andric if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) { 9280b57cec5SDimitry Andric ArrayRef<char> data = 929e8d8bef9SDimitry Andric CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this); 9300b57cec5SDimitry Andric if (!data.empty() && data.back() != '\0') { 9310b57cec5SDimitry Andric error(toString(this) + 9320b57cec5SDimitry Andric ": corrupted dependent libraries section (unterminated string): " + 9330b57cec5SDimitry Andric name); 9340b57cec5SDimitry Andric return &InputSection::discarded; 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric for (const char *d = data.begin(), *e = data.end(); d < e;) { 9370b57cec5SDimitry Andric StringRef s(d); 9380b57cec5SDimitry Andric addDependentLibrary(s, this); 9390b57cec5SDimitry Andric d += s.size() + 1; 9400b57cec5SDimitry Andric } 9410b57cec5SDimitry Andric return &InputSection::discarded; 9420b57cec5SDimitry Andric } 9430b57cec5SDimitry Andric 9440eae32dcSDimitry Andric if (name.startswith(".n")) { 9450b57cec5SDimitry Andric // The GNU linker uses .note.GNU-stack section as a marker indicating 9460b57cec5SDimitry Andric // that the code in the object file does not expect that the stack is 9470b57cec5SDimitry Andric // executable (in terms of NX bit). If all input files have the marker, 9480b57cec5SDimitry Andric // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 9490b57cec5SDimitry Andric // make the stack non-executable. Most object files have this section as 9500b57cec5SDimitry Andric // of 2017. 9510b57cec5SDimitry Andric // 9520b57cec5SDimitry Andric // But making the stack non-executable is a norm today for security 9530b57cec5SDimitry Andric // reasons. Failure to do so may result in a serious security issue. 9540b57cec5SDimitry Andric // Therefore, we make LLD always add PT_GNU_STACK unless it is 9550b57cec5SDimitry Andric // explicitly told to do otherwise (by -z execstack). Because the stack 9560b57cec5SDimitry Andric // executable-ness is controlled solely by command line options, 9570b57cec5SDimitry Andric // .note.GNU-stack sections are simply ignored. 9580b57cec5SDimitry Andric if (name == ".note.GNU-stack") 9590b57cec5SDimitry Andric return &InputSection::discarded; 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric // Object files that use processor features such as Intel Control-Flow 9620b57cec5SDimitry Andric // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a 9630b57cec5SDimitry Andric // .note.gnu.property section containing a bitfield of feature bits like the 9640b57cec5SDimitry Andric // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag. 9650b57cec5SDimitry Andric // 9660b57cec5SDimitry Andric // Since we merge bitmaps from multiple object files to create a new 9670b57cec5SDimitry Andric // .note.gnu.property containing a single AND'ed bitmap, we discard an input 9680b57cec5SDimitry Andric // file's .note.gnu.property section. 9690b57cec5SDimitry Andric if (name == ".note.gnu.property") { 970e8d8bef9SDimitry Andric this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name)); 9710b57cec5SDimitry Andric return &InputSection::discarded; 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric 9740b57cec5SDimitry Andric // Split stacks is a feature to support a discontiguous stack, 9750b57cec5SDimitry Andric // commonly used in the programming language Go. For the details, 9760b57cec5SDimitry Andric // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled 9770b57cec5SDimitry Andric // for split stack will include a .note.GNU-split-stack section. 9780b57cec5SDimitry Andric if (name == ".note.GNU-split-stack") { 9790b57cec5SDimitry Andric if (config->relocatable) { 9800eae32dcSDimitry Andric error( 9810eae32dcSDimitry Andric "cannot mix split-stack and non-split-stack in a relocatable link"); 9820b57cec5SDimitry Andric return &InputSection::discarded; 9830b57cec5SDimitry Andric } 9840b57cec5SDimitry Andric this->splitStack = true; 9850b57cec5SDimitry Andric return &InputSection::discarded; 9860b57cec5SDimitry Andric } 9870b57cec5SDimitry Andric 9880b57cec5SDimitry Andric // An object file cmpiled for split stack, but where some of the 9890b57cec5SDimitry Andric // functions were compiled with the no_split_stack_attribute will 9900b57cec5SDimitry Andric // include a .note.GNU-no-split-stack section. 9910b57cec5SDimitry Andric if (name == ".note.GNU-no-split-stack") { 9920b57cec5SDimitry Andric this->someNoSplitStack = true; 9930b57cec5SDimitry Andric return &InputSection::discarded; 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric 9960eae32dcSDimitry Andric // Strip existing .note.gnu.build-id sections so that the output won't have 9970eae32dcSDimitry Andric // more than one build-id. This is not usually a problem because input 9980eae32dcSDimitry Andric // object files normally don't have .build-id sections, but you can create 9990eae32dcSDimitry Andric // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard 10000eae32dcSDimitry Andric // against it. 10010eae32dcSDimitry Andric if (name == ".note.gnu.build-id") 10020eae32dcSDimitry Andric return &InputSection::discarded; 10030eae32dcSDimitry Andric } 10040eae32dcSDimitry Andric 10050b57cec5SDimitry Andric // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 10060b57cec5SDimitry Andric // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 10070b57cec5SDimitry Andric // sections. Drop those sections to avoid duplicate symbol errors. 10080b57cec5SDimitry Andric // FIXME: This is glibc PR20543, we should remove this hack once that has been 10090b57cec5SDimitry Andric // fixed for a while. 10100b57cec5SDimitry Andric if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" || 10110b57cec5SDimitry Andric name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx") 10120b57cec5SDimitry Andric return &InputSection::discarded; 10130b57cec5SDimitry Andric 10140b57cec5SDimitry Andric // The linker merges EH (exception handling) frames and creates a 10150b57cec5SDimitry Andric // .eh_frame_hdr section for runtime. So we handle them with a special 10160b57cec5SDimitry Andric // class. For relocatable outputs, they are just passed through. 10170b57cec5SDimitry Andric if (name == ".eh_frame" && !config->relocatable) 10180b57cec5SDimitry Andric return make<EhInputSection>(*this, sec, name); 10190b57cec5SDimitry Andric 10200eae32dcSDimitry Andric if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name)) 10210b57cec5SDimitry Andric return make<MergeInputSection>(*this, sec, name); 10220b57cec5SDimitry Andric return make<InputSection>(*this, sec, name); 10230b57cec5SDimitry Andric } 10240b57cec5SDimitry Andric 10250b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as 10260b57cec5SDimitry Andric // its corresponding ELF symbol table. 1027*1fd87a68SDimitry Andric template <class ELFT> 1028*1fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) { 10290eae32dcSDimitry Andric ArrayRef<InputSectionBase *> sections(this->sections); 10300eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 10310b57cec5SDimitry Andric 10320eae32dcSDimitry Andric ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 10330eae32dcSDimitry Andric symbols.resize(eSyms.size()); 10340eae32dcSDimitry Andric SymbolUnion *locals = 10350eae32dcSDimitry Andric firstGlobal == 0 10360eae32dcSDimitry Andric ? nullptr 10370eae32dcSDimitry Andric : getSpecificAllocSingleton<SymbolUnion>().Allocate(firstGlobal); 10380eae32dcSDimitry Andric 10390eae32dcSDimitry Andric for (size_t i = 0, end = firstGlobal; i != end; ++i) { 10400b57cec5SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 1041*1fd87a68SDimitry Andric uint32_t secIdx = eSym.st_shndx; 1042*1fd87a68SDimitry Andric if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1043*1fd87a68SDimitry Andric secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1044*1fd87a68SDimitry Andric else if (secIdx >= SHN_LORESERVE) 1045*1fd87a68SDimitry Andric secIdx = 0; 10460eae32dcSDimitry Andric if (LLVM_UNLIKELY(secIdx >= sections.size())) 10470b57cec5SDimitry Andric fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 10480eae32dcSDimitry Andric if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL)) 10495ffd83dbSDimitry Andric error(toString(this) + ": non-local symbol (" + Twine(i) + 10500eae32dcSDimitry Andric ") found at index < .symtab's sh_info (" + Twine(end) + ")"); 10515ffd83dbSDimitry Andric 10520eae32dcSDimitry Andric InputSectionBase *sec = sections[secIdx]; 10535ffd83dbSDimitry Andric uint8_t type = eSym.getType(); 10545ffd83dbSDimitry Andric if (type == STT_FILE) 10550eae32dcSDimitry Andric sourceFile = CHECK(eSym.getName(stringTable), this); 10560eae32dcSDimitry Andric if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name)) 10575ffd83dbSDimitry Andric fatal(toString(this) + ": invalid symbol name offset"); 105804eeddc0SDimitry Andric StringRef name(stringTable.data() + eSym.st_name); 10595ffd83dbSDimitry Andric 10600eae32dcSDimitry Andric symbols[i] = reinterpret_cast<Symbol *>(locals + i); 10610eae32dcSDimitry Andric if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded) 10620eae32dcSDimitry Andric new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type, 10635ffd83dbSDimitry Andric /*discardedSecIdx=*/secIdx); 10645ffd83dbSDimitry Andric else 10650eae32dcSDimitry Andric new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type, 10660eae32dcSDimitry Andric eSym.st_value, eSym.st_size, sec); 10675ffd83dbSDimitry Andric } 10685ffd83dbSDimitry Andric 10690eae32dcSDimitry Andric // Some entries have been filled by LazyObjFile. 10700eae32dcSDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 10710eae32dcSDimitry Andric if (!symbols[i]) 10720eae32dcSDimitry Andric symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 10730eae32dcSDimitry Andric 10740eae32dcSDimitry Andric // Perform symbol resolution on non-local symbols. 1075fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 10765ffd83dbSDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 10775ffd83dbSDimitry Andric const Elf_Sym &eSym = eSyms[i]; 10780b57cec5SDimitry Andric uint8_t binding = eSym.getBinding(); 10790eae32dcSDimitry Andric if (LLVM_UNLIKELY(binding == STB_LOCAL)) { 10800eae32dcSDimitry Andric errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) + 10810eae32dcSDimitry Andric ") found at index >= .symtab's sh_info (" + 10820eae32dcSDimitry Andric Twine(firstGlobal) + ")"); 10830eae32dcSDimitry Andric continue; 10840eae32dcSDimitry Andric } 1085*1fd87a68SDimitry Andric uint32_t secIdx = eSym.st_shndx; 1086*1fd87a68SDimitry Andric if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1087*1fd87a68SDimitry Andric secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1088*1fd87a68SDimitry Andric else if (secIdx >= SHN_LORESERVE) 1089*1fd87a68SDimitry Andric secIdx = 0; 10900eae32dcSDimitry Andric if (LLVM_UNLIKELY(secIdx >= sections.size())) 10910eae32dcSDimitry Andric fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 10920eae32dcSDimitry Andric InputSectionBase *sec = sections[secIdx]; 10930b57cec5SDimitry Andric uint8_t stOther = eSym.st_other; 10940b57cec5SDimitry Andric uint8_t type = eSym.getType(); 10950b57cec5SDimitry Andric uint64_t value = eSym.st_value; 10960b57cec5SDimitry Andric uint64_t size = eSym.st_size; 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric if (eSym.st_shndx == SHN_UNDEF) { 1099fe6060f1SDimitry Andric undefineds.push_back(i); 11000b57cec5SDimitry Andric continue; 11010b57cec5SDimitry Andric } 11020b57cec5SDimitry Andric 11030eae32dcSDimitry Andric Symbol *sym = symbols[i]; 11040eae32dcSDimitry Andric const StringRef name = sym->getName(); 11050eae32dcSDimitry Andric if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) { 11060b57cec5SDimitry Andric if (value == 0 || value >= UINT32_MAX) 11070eae32dcSDimitry Andric fatal(toString(this) + ": common symbol '" + name + 11080b57cec5SDimitry Andric "' has invalid alignment: " + Twine(value)); 11090eae32dcSDimitry Andric hasCommonSyms = true; 11100eae32dcSDimitry Andric sym->resolve( 11110b57cec5SDimitry Andric CommonSymbol{this, name, binding, stOther, type, value, size}); 11120b57cec5SDimitry Andric continue; 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric // If a defined symbol is in a discarded section, handle it as if it 11160b57cec5SDimitry Andric // were an undefined symbol. Such symbol doesn't comply with the 11170b57cec5SDimitry Andric // standard, but in practice, a .eh_frame often directly refer 11180b57cec5SDimitry Andric // COMDAT member sections, and if a comdat group is discarded, some 11190b57cec5SDimitry Andric // defined symbol in a .eh_frame becomes dangling symbols. 11200b57cec5SDimitry Andric if (sec == &InputSection::discarded) { 11215ffd83dbSDimitry Andric Undefined und{this, name, binding, stOther, type, secIdx}; 11220eae32dcSDimitry Andric // !ArchiveFile::parsed or !LazyObjFile::lazy means that the file 11235ffd83dbSDimitry Andric // containing this object has not finished processing, i.e. this symbol is 11244824e7fdSDimitry Andric // a result of a lazy symbol extract. We should demote the lazy symbol to 11254824e7fdSDimitry Andric // an Undefined so that any relocations outside of the group to it will 11265ffd83dbSDimitry Andric // trigger a discarded section error. 11275ffd83dbSDimitry Andric if ((sym->symbolKind == Symbol::LazyArchiveKind && 11285ffd83dbSDimitry Andric !cast<ArchiveFile>(sym->file)->parsed) || 11290eae32dcSDimitry Andric (sym->symbolKind == Symbol::LazyObjectKind && !sym->file->lazy)) { 11305ffd83dbSDimitry Andric sym->replace(und); 11314824e7fdSDimitry Andric // Prevent LTO from internalizing the symbol in case there is a 11324824e7fdSDimitry Andric // reference to this symbol from this file. 11334824e7fdSDimitry Andric sym->isUsedInRegularObj = true; 11344824e7fdSDimitry Andric } else 11355ffd83dbSDimitry Andric sym->resolve(und); 11360b57cec5SDimitry Andric continue; 11370b57cec5SDimitry Andric } 11380b57cec5SDimitry Andric 11390b57cec5SDimitry Andric // Handle global defined symbols. 11400b57cec5SDimitry Andric if (binding == STB_GLOBAL || binding == STB_WEAK || 11410b57cec5SDimitry Andric binding == STB_GNU_UNIQUE) { 11420eae32dcSDimitry Andric sym->resolve( 11430b57cec5SDimitry Andric Defined{this, name, binding, stOther, type, value, size, sec}); 11440b57cec5SDimitry Andric continue; 11450b57cec5SDimitry Andric } 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric fatal(toString(this) + ": unexpected binding: " + Twine((int)binding)); 11480b57cec5SDimitry Andric } 1149fe6060f1SDimitry Andric 1150fe6060f1SDimitry Andric // Undefined symbols (excluding those defined relative to non-prevailing 11514824e7fdSDimitry Andric // sections) can trigger recursive extract. Process defined symbols first so 1152fe6060f1SDimitry Andric // that the relative order between a defined symbol and an undefined symbol 1153fe6060f1SDimitry Andric // does not change the symbol resolution behavior. In addition, a set of 1154fe6060f1SDimitry Andric // interconnected symbols will all be resolved to the same file, instead of 1155fe6060f1SDimitry Andric // being resolved to different files. 1156fe6060f1SDimitry Andric for (unsigned i : undefineds) { 1157fe6060f1SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 11580eae32dcSDimitry Andric Symbol *sym = symbols[i]; 11590eae32dcSDimitry Andric sym->resolve(Undefined{this, sym->getName(), eSym.getBinding(), 1160fe6060f1SDimitry Andric eSym.st_other, eSym.getType()}); 11610eae32dcSDimitry Andric sym->referenced = true; 1162fe6060f1SDimitry Andric } 11630b57cec5SDimitry Andric } 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file) 11660b57cec5SDimitry Andric : InputFile(ArchiveKind, file->getMemoryBufferRef()), 11670b57cec5SDimitry Andric file(std::move(file)) {} 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric void ArchiveFile::parse() { 11700eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 11710b57cec5SDimitry Andric for (const Archive::Symbol &sym : file->symbols()) 11720eae32dcSDimitry Andric symtab.addSymbol(LazyArchive{*this, sym}); 11735ffd83dbSDimitry Andric 11745ffd83dbSDimitry Andric // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this 11755ffd83dbSDimitry Andric // archive has been processed. 11765ffd83dbSDimitry Andric parsed = true; 11770b57cec5SDimitry Andric } 11780b57cec5SDimitry Andric 11790b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol. 11804824e7fdSDimitry Andric void ArchiveFile::extract(const Archive::Symbol &sym) { 11810b57cec5SDimitry Andric Archive::Child c = 11820b57cec5SDimitry Andric CHECK(sym.getMember(), toString(this) + 11830b57cec5SDimitry Andric ": could not get the member for symbol " + 11840b57cec5SDimitry Andric toELFString(sym)); 11850b57cec5SDimitry Andric 11860b57cec5SDimitry Andric if (!seen.insert(c.getChildOffset()).second) 11870b57cec5SDimitry Andric return; 11880b57cec5SDimitry Andric 11890b57cec5SDimitry Andric MemoryBufferRef mb = 11900b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 11910b57cec5SDimitry Andric toString(this) + 11920b57cec5SDimitry Andric ": could not get the buffer for the member defining symbol " + 11930b57cec5SDimitry Andric toELFString(sym)); 11940b57cec5SDimitry Andric 11950b57cec5SDimitry Andric if (tar && c.getParent()->isThin()) 11960b57cec5SDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 11970b57cec5SDimitry Andric 11985ffd83dbSDimitry Andric InputFile *file = createObjectFile(mb, getName(), c.getChildOffset()); 11990b57cec5SDimitry Andric file->groupId = groupId; 12000b57cec5SDimitry Andric parseFile(file); 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric 1203e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky. 1204fe6060f1SDimitry Andric // A tentative definition will be promoted to a global definition if there are 1205fe6060f1SDimitry Andric // no non-tentative definitions to dominate it. When we hold a tentative 1206fe6060f1SDimitry Andric // definition to a symbol and are inspecting archive members for inclusion 1207fe6060f1SDimitry Andric // there are 2 ways we can proceed: 1208e8d8bef9SDimitry Andric // 1209e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from 1210e8d8bef9SDimitry Andric // tentative to real definition has already happened) and not inspect 1211e8d8bef9SDimitry Andric // archive members for Global/Weak definitions to replace the tentative 1212e8d8bef9SDimitry Andric // definition. An archive member would only be included if it satisfies some 1213e8d8bef9SDimitry Andric // other undefined symbol. This is the behavior Gold uses. 1214e8d8bef9SDimitry Andric // 1215e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to 1216fe6060f1SDimitry Andric // a real definition happens only after all symbol resolution is done). 1217fe6060f1SDimitry Andric // The linker searches archive members for STB_GLOBAL definitions to 1218e8d8bef9SDimitry Andric // replace the tentative definition with. This is the behavior used by 1219e8d8bef9SDimitry Andric // GNU ld. 1220e8d8bef9SDimitry Andric // 1221e8d8bef9SDimitry Andric // The second behavior is inherited from SysVR4, which based it on the FORTRAN 1222fe6060f1SDimitry Andric // COMMON BLOCK model. This behavior is needed for proper initialization in old 1223e8d8bef9SDimitry Andric // (pre F90) FORTRAN code that is packaged into an archive. 1224e8d8bef9SDimitry Andric // 1225fe6060f1SDimitry Andric // The following functions search archive members for definitions to replace 1226fe6060f1SDimitry Andric // tentative definitions (implementing behavior 2). 1227e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName, 1228e8d8bef9SDimitry Andric StringRef archiveName) { 1229e8d8bef9SDimitry Andric IRSymtabFile symtabFile = check(readIRSymtab(mb)); 1230e8d8bef9SDimitry Andric for (const irsymtab::Reader::SymbolRef &sym : 1231e8d8bef9SDimitry Andric symtabFile.TheReader.symbols()) { 1232e8d8bef9SDimitry Andric if (sym.isGlobal() && sym.getName() == symName) 1233fe6060f1SDimitry Andric return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon(); 1234e8d8bef9SDimitry Andric } 1235e8d8bef9SDimitry Andric return false; 1236e8d8bef9SDimitry Andric } 1237e8d8bef9SDimitry Andric 1238e8d8bef9SDimitry Andric template <class ELFT> 1239e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1240e8d8bef9SDimitry Andric StringRef archiveName) { 1241e8d8bef9SDimitry Andric ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName); 1242e8d8bef9SDimitry Andric StringRef stringtable = obj->getStringTable(); 1243e8d8bef9SDimitry Andric 1244e8d8bef9SDimitry Andric for (auto sym : obj->template getGlobalELFSyms<ELFT>()) { 1245e8d8bef9SDimitry Andric Expected<StringRef> name = sym.getName(stringtable); 1246e8d8bef9SDimitry Andric if (name && name.get() == symName) 1247fe6060f1SDimitry Andric return sym.isDefined() && sym.getBinding() == STB_GLOBAL && 1248fe6060f1SDimitry Andric !sym.isCommon(); 1249e8d8bef9SDimitry Andric } 1250e8d8bef9SDimitry Andric return false; 1251e8d8bef9SDimitry Andric } 1252e8d8bef9SDimitry Andric 1253e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1254e8d8bef9SDimitry Andric StringRef archiveName) { 1255e8d8bef9SDimitry Andric switch (getELFKind(mb, archiveName)) { 1256e8d8bef9SDimitry Andric case ELF32LEKind: 1257e8d8bef9SDimitry Andric return isNonCommonDef<ELF32LE>(mb, symName, archiveName); 1258e8d8bef9SDimitry Andric case ELF32BEKind: 1259e8d8bef9SDimitry Andric return isNonCommonDef<ELF32BE>(mb, symName, archiveName); 1260e8d8bef9SDimitry Andric case ELF64LEKind: 1261e8d8bef9SDimitry Andric return isNonCommonDef<ELF64LE>(mb, symName, archiveName); 1262e8d8bef9SDimitry Andric case ELF64BEKind: 1263e8d8bef9SDimitry Andric return isNonCommonDef<ELF64BE>(mb, symName, archiveName); 1264e8d8bef9SDimitry Andric default: 1265e8d8bef9SDimitry Andric llvm_unreachable("getELFKind"); 1266e8d8bef9SDimitry Andric } 1267e8d8bef9SDimitry Andric } 1268e8d8bef9SDimitry Andric 12694824e7fdSDimitry Andric bool ArchiveFile::shouldExtractForCommon(const Archive::Symbol &sym) { 1270e8d8bef9SDimitry Andric Archive::Child c = 1271e8d8bef9SDimitry Andric CHECK(sym.getMember(), toString(this) + 1272e8d8bef9SDimitry Andric ": could not get the member for symbol " + 1273e8d8bef9SDimitry Andric toELFString(sym)); 1274e8d8bef9SDimitry Andric MemoryBufferRef mb = 1275e8d8bef9SDimitry Andric CHECK(c.getMemoryBufferRef(), 1276e8d8bef9SDimitry Andric toString(this) + 1277e8d8bef9SDimitry Andric ": could not get the buffer for the member defining symbol " + 1278e8d8bef9SDimitry Andric toELFString(sym)); 1279e8d8bef9SDimitry Andric 1280e8d8bef9SDimitry Andric if (isBitcode(mb)) 1281e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, sym.getName(), getName()); 1282e8d8bef9SDimitry Andric 1283e8d8bef9SDimitry Andric return isNonCommonDef(mb, sym.getName(), getName()); 1284e8d8bef9SDimitry Andric } 1285e8d8bef9SDimitry Andric 12865ffd83dbSDimitry Andric size_t ArchiveFile::getMemberCount() const { 12875ffd83dbSDimitry Andric size_t count = 0; 12885ffd83dbSDimitry Andric Error err = Error::success(); 12895ffd83dbSDimitry Andric for (const Archive::Child &c : file->children(err)) { 12905ffd83dbSDimitry Andric (void)c; 12915ffd83dbSDimitry Andric ++count; 12925ffd83dbSDimitry Andric } 12935ffd83dbSDimitry Andric // This function is used by --print-archive-stats=, where an error does not 12945ffd83dbSDimitry Andric // really matter. 12955ffd83dbSDimitry Andric consumeError(std::move(err)); 12965ffd83dbSDimitry Andric return count; 12975ffd83dbSDimitry Andric } 12985ffd83dbSDimitry Andric 12990b57cec5SDimitry Andric unsigned SharedFile::vernauxNum; 13000b57cec5SDimitry Andric 13010b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a 13020b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version 13030b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr. 13040b57cec5SDimitry Andric template <typename ELFT> 13050eae32dcSDimitry Andric static SmallVector<const void *, 0> 13060eae32dcSDimitry Andric parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) { 13070b57cec5SDimitry Andric if (!sec) 13080b57cec5SDimitry Andric return {}; 13090b57cec5SDimitry Andric 13100b57cec5SDimitry Andric // Build the Verdefs array by following the chain of Elf_Verdef objects 13110b57cec5SDimitry Andric // from the start of the .gnu.version_d section. 13120eae32dcSDimitry Andric SmallVector<const void *, 0> verdefs; 13130b57cec5SDimitry Andric const uint8_t *verdef = base + sec->sh_offset; 13140eae32dcSDimitry Andric for (unsigned i = 0, e = sec->sh_info; i != e; ++i) { 13150b57cec5SDimitry Andric auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef); 13160b57cec5SDimitry Andric verdef += curVerdef->vd_next; 13170b57cec5SDimitry Andric unsigned verdefIndex = curVerdef->vd_ndx; 13180eae32dcSDimitry Andric if (verdefIndex >= verdefs.size()) 13190b57cec5SDimitry Andric verdefs.resize(verdefIndex + 1); 13200b57cec5SDimitry Andric verdefs[verdefIndex] = curVerdef; 13210b57cec5SDimitry Andric } 13220b57cec5SDimitry Andric return verdefs; 13230b57cec5SDimitry Andric } 13240b57cec5SDimitry Andric 13255ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined 13265ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not 13275ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value 13285ffd83dbSDimitry Andric // of such diagnostics is low. 13295ffd83dbSDimitry Andric template <typename ELFT> 13305ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj, 13315ffd83dbSDimitry Andric const typename ELFT::Shdr *sec) { 13325ffd83dbSDimitry Andric if (!sec) 13335ffd83dbSDimitry Andric return {}; 13345ffd83dbSDimitry Andric std::vector<uint32_t> verneeds; 1335e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this); 13365ffd83dbSDimitry Andric const uint8_t *verneedBuf = data.begin(); 13375ffd83dbSDimitry Andric for (unsigned i = 0; i != sec->sh_info; ++i) { 13385ffd83dbSDimitry Andric if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) 13395ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Verneed"); 13405ffd83dbSDimitry Andric auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf); 13415ffd83dbSDimitry Andric const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux; 13425ffd83dbSDimitry Andric for (unsigned j = 0; j != vn->vn_cnt; ++j) { 13435ffd83dbSDimitry Andric if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) 13445ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Vernaux"); 13455ffd83dbSDimitry Andric auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf); 13465ffd83dbSDimitry Andric if (aux->vna_name >= this->stringTable.size()) 13475ffd83dbSDimitry Andric fatal(toString(this) + " has a Vernaux with an invalid vna_name"); 13485ffd83dbSDimitry Andric uint16_t version = aux->vna_other & VERSYM_VERSION; 13495ffd83dbSDimitry Andric if (version >= verneeds.size()) 13505ffd83dbSDimitry Andric verneeds.resize(version + 1); 13515ffd83dbSDimitry Andric verneeds[version] = aux->vna_name; 13525ffd83dbSDimitry Andric vernauxBuf += aux->vna_next; 13535ffd83dbSDimitry Andric } 13545ffd83dbSDimitry Andric verneedBuf += vn->vn_next; 13555ffd83dbSDimitry Andric } 13565ffd83dbSDimitry Andric return verneeds; 13575ffd83dbSDimitry Andric } 13585ffd83dbSDimitry Andric 13590b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object 13600b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a 13610b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep 13620b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function. 13630b57cec5SDimitry Andric template <typename ELFT> 13640b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections, 13650b57cec5SDimitry Andric const typename ELFT::Sym &sym) { 13660b57cec5SDimitry Andric uint64_t ret = UINT64_MAX; 13670b57cec5SDimitry Andric if (sym.st_value) 13680b57cec5SDimitry Andric ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value); 13690b57cec5SDimitry Andric if (0 < sym.st_shndx && sym.st_shndx < sections.size()) 13700b57cec5SDimitry Andric ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign); 13710b57cec5SDimitry Andric return (ret > UINT32_MAX) ? 0 : ret; 13720b57cec5SDimitry Andric } 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // Fully parse the shared object file. 13750b57cec5SDimitry Andric // 13760b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information, 13770b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version 13780b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in 13790b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol 13800b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d". 13810b57cec5SDimitry Andric // 13820b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 13830b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in 13840b57cec5SDimitry Andric // ".gnu.version_d". 13850b57cec5SDimitry Andric // 13860b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated 13870b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your 13880b57cec5SDimitry Andric // head around the data structure described above. 13890b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() { 13900b57cec5SDimitry Andric using Elf_Dyn = typename ELFT::Dyn; 13910b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 13920b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 13930b57cec5SDimitry Andric using Elf_Verdef = typename ELFT::Verdef; 13940b57cec5SDimitry Andric using Elf_Versym = typename ELFT::Versym; 13950b57cec5SDimitry Andric 13960b57cec5SDimitry Andric ArrayRef<Elf_Dyn> dynamicTags; 13970b57cec5SDimitry Andric const ELFFile<ELFT> obj = this->getObj<ELFT>(); 13980eae32dcSDimitry Andric ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>(); 13990b57cec5SDimitry Andric 14000b57cec5SDimitry Andric const Elf_Shdr *versymSec = nullptr; 14010b57cec5SDimitry Andric const Elf_Shdr *verdefSec = nullptr; 14025ffd83dbSDimitry Andric const Elf_Shdr *verneedSec = nullptr; 14030b57cec5SDimitry Andric 14040b57cec5SDimitry Andric // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 14050b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) { 14060b57cec5SDimitry Andric switch (sec.sh_type) { 14070b57cec5SDimitry Andric default: 14080b57cec5SDimitry Andric continue; 14090b57cec5SDimitry Andric case SHT_DYNAMIC: 14100b57cec5SDimitry Andric dynamicTags = 1411e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this); 14120b57cec5SDimitry Andric break; 14130b57cec5SDimitry Andric case SHT_GNU_versym: 14140b57cec5SDimitry Andric versymSec = &sec; 14150b57cec5SDimitry Andric break; 14160b57cec5SDimitry Andric case SHT_GNU_verdef: 14170b57cec5SDimitry Andric verdefSec = &sec; 14180b57cec5SDimitry Andric break; 14195ffd83dbSDimitry Andric case SHT_GNU_verneed: 14205ffd83dbSDimitry Andric verneedSec = &sec; 14215ffd83dbSDimitry Andric break; 14220b57cec5SDimitry Andric } 14230b57cec5SDimitry Andric } 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric if (versymSec && numELFSyms == 0) { 14260b57cec5SDimitry Andric error("SHT_GNU_versym should be associated with symbol table"); 14270b57cec5SDimitry Andric return; 14280b57cec5SDimitry Andric } 14290b57cec5SDimitry Andric 14300b57cec5SDimitry Andric // Search for a DT_SONAME tag to initialize this->soName. 14310b57cec5SDimitry Andric for (const Elf_Dyn &dyn : dynamicTags) { 14320b57cec5SDimitry Andric if (dyn.d_tag == DT_NEEDED) { 14330b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14340b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14350b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_NEEDED entry"); 14360b57cec5SDimitry Andric dtNeeded.push_back(this->stringTable.data() + val); 14370b57cec5SDimitry Andric } else if (dyn.d_tag == DT_SONAME) { 14380b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14390b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14400b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_SONAME entry"); 14410b57cec5SDimitry Andric soName = this->stringTable.data() + val; 14420b57cec5SDimitry Andric } 14430b57cec5SDimitry Andric } 14440b57cec5SDimitry Andric 14450b57cec5SDimitry Andric // DSOs are uniquified not by filename but by soname. 144604eeddc0SDimitry Andric DenseMap<CachedHashStringRef, SharedFile *>::iterator it; 14470b57cec5SDimitry Andric bool wasInserted; 144804eeddc0SDimitry Andric std::tie(it, wasInserted) = 144904eeddc0SDimitry Andric symtab->soNames.try_emplace(CachedHashStringRef(soName), this); 14500b57cec5SDimitry Andric 14510b57cec5SDimitry Andric // If a DSO appears more than once on the command line with and without 14520b57cec5SDimitry Andric // --as-needed, --no-as-needed takes precedence over --as-needed because a 14530b57cec5SDimitry Andric // user can add an extra DSO with --no-as-needed to force it to be added to 14540b57cec5SDimitry Andric // the dependency list. 14550b57cec5SDimitry Andric it->second->isNeeded |= isNeeded; 14560b57cec5SDimitry Andric if (!wasInserted) 14570b57cec5SDimitry Andric return; 14580b57cec5SDimitry Andric 14590b57cec5SDimitry Andric sharedFiles.push_back(this); 14600b57cec5SDimitry Andric 14610b57cec5SDimitry Andric verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec); 14625ffd83dbSDimitry Andric std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec); 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric // Parse ".gnu.version" section which is a parallel array for the symbol 14650b57cec5SDimitry Andric // table. If a given file doesn't have a ".gnu.version" section, we use 14660b57cec5SDimitry Andric // VER_NDX_GLOBAL. 14670b57cec5SDimitry Andric size_t size = numELFSyms - firstGlobal; 14685ffd83dbSDimitry Andric std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL); 14690b57cec5SDimitry Andric if (versymSec) { 14700b57cec5SDimitry Andric ArrayRef<Elf_Versym> versym = 1471e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec), 14720b57cec5SDimitry Andric this) 14730b57cec5SDimitry Andric .slice(firstGlobal); 14740b57cec5SDimitry Andric for (size_t i = 0; i < size; ++i) 14750b57cec5SDimitry Andric versyms[i] = versym[i].vs_index; 14760b57cec5SDimitry Andric } 14770b57cec5SDimitry Andric 14780b57cec5SDimitry Andric // System libraries can have a lot of symbols with versions. Using a 14790b57cec5SDimitry Andric // fixed buffer for computing the versions name (foo@ver) can save a 14800b57cec5SDimitry Andric // lot of allocations. 14810b57cec5SDimitry Andric SmallString<0> versionedNameBuffer; 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric // Add symbols to the symbol table. 14840eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 14850b57cec5SDimitry Andric ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>(); 14860eae32dcSDimitry Andric for (size_t i = 0, e = syms.size(); i != e; ++i) { 14870b57cec5SDimitry Andric const Elf_Sym &sym = syms[i]; 14880b57cec5SDimitry Andric 14890b57cec5SDimitry Andric // ELF spec requires that all local symbols precede weak or global 14900b57cec5SDimitry Andric // symbols in each symbol table, and the index of first non-local symbol 14910b57cec5SDimitry Andric // is stored to sh_info. If a local symbol appears after some non-local 14920b57cec5SDimitry Andric // symbol, that's a violation of the spec. 14930eae32dcSDimitry Andric StringRef name = CHECK(sym.getName(stringTable), this); 14940b57cec5SDimitry Andric if (sym.getBinding() == STB_LOCAL) { 14950b57cec5SDimitry Andric warn("found local symbol '" + name + 14960b57cec5SDimitry Andric "' in global part of symbol table in file " + toString(this)); 14970b57cec5SDimitry Andric continue; 14980b57cec5SDimitry Andric } 14990b57cec5SDimitry Andric 15005ffd83dbSDimitry Andric uint16_t idx = versyms[i] & ~VERSYM_HIDDEN; 15010b57cec5SDimitry Andric if (sym.isUndefined()) { 15025ffd83dbSDimitry Andric // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but 15035ffd83dbSDimitry Andric // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL. 15045ffd83dbSDimitry Andric if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) { 15055ffd83dbSDimitry Andric if (idx >= verneeds.size()) { 15065ffd83dbSDimitry Andric error("corrupt input file: version need index " + Twine(idx) + 15075ffd83dbSDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15085ffd83dbSDimitry Andric toString(this)); 15095ffd83dbSDimitry Andric continue; 15105ffd83dbSDimitry Andric } 15110eae32dcSDimitry Andric StringRef verName = stringTable.data() + verneeds[idx]; 15125ffd83dbSDimitry Andric versionedNameBuffer.clear(); 151304eeddc0SDimitry Andric name = saver().save( 151404eeddc0SDimitry Andric (name + "@" + verName).toStringRef(versionedNameBuffer)); 15155ffd83dbSDimitry Andric } 15160eae32dcSDimitry Andric Symbol *s = symtab.addSymbol( 15170b57cec5SDimitry Andric Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()}); 15180b57cec5SDimitry Andric s->exportDynamic = true; 15190eae32dcSDimitry Andric if (s->isUndefined() && sym.getBinding() != STB_WEAK && 1520fe6060f1SDimitry Andric config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) 1521fe6060f1SDimitry Andric requiredSymbols.push_back(s); 15220b57cec5SDimitry Andric continue; 15230b57cec5SDimitry Andric } 15240b57cec5SDimitry Andric 15250b57cec5SDimitry Andric // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 15260b57cec5SDimitry Andric // assigns VER_NDX_LOCAL to this section global symbol. Here is a 15270b57cec5SDimitry Andric // workaround for this bug. 15280b57cec5SDimitry Andric if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL && 15290b57cec5SDimitry Andric name == "_gp_disp") 15300b57cec5SDimitry Andric continue; 15310b57cec5SDimitry Andric 15320b57cec5SDimitry Andric uint32_t alignment = getAlignment<ELFT>(sections, sym); 15330b57cec5SDimitry Andric if (!(versyms[i] & VERSYM_HIDDEN)) { 15340eae32dcSDimitry Andric symtab.addSymbol(SharedSymbol{*this, name, sym.getBinding(), sym.st_other, 15350eae32dcSDimitry Andric sym.getType(), sym.st_value, sym.st_size, 15360eae32dcSDimitry Andric alignment, idx}); 15370b57cec5SDimitry Andric } 15380b57cec5SDimitry Andric 15390b57cec5SDimitry Andric // Also add the symbol with the versioned name to handle undefined symbols 15400b57cec5SDimitry Andric // with explicit versions. 15410b57cec5SDimitry Andric if (idx == VER_NDX_GLOBAL) 15420b57cec5SDimitry Andric continue; 15430b57cec5SDimitry Andric 15440b57cec5SDimitry Andric if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) { 15450b57cec5SDimitry Andric error("corrupt input file: version definition index " + Twine(idx) + 15460b57cec5SDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15470b57cec5SDimitry Andric toString(this)); 15480b57cec5SDimitry Andric continue; 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric StringRef verName = 15520eae32dcSDimitry Andric stringTable.data() + 15530b57cec5SDimitry Andric reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name; 15540b57cec5SDimitry Andric versionedNameBuffer.clear(); 15550b57cec5SDimitry Andric name = (name + "@" + verName).toStringRef(versionedNameBuffer); 155604eeddc0SDimitry Andric symtab.addSymbol(SharedSymbol{*this, saver().save(name), sym.getBinding(), 15570b57cec5SDimitry Andric sym.st_other, sym.getType(), sym.st_value, 15580b57cec5SDimitry Andric sym.st_size, alignment, idx}); 15590b57cec5SDimitry Andric } 15600b57cec5SDimitry Andric } 15610b57cec5SDimitry Andric 15620b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) { 15630b57cec5SDimitry Andric if (t.isLittleEndian()) 15640b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 15650b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 15660b57cec5SDimitry Andric } 15670b57cec5SDimitry Andric 1568e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) { 15690b57cec5SDimitry Andric switch (t.getArch()) { 15700b57cec5SDimitry Andric case Triple::aarch64: 1571fe6060f1SDimitry Andric case Triple::aarch64_be: 15720b57cec5SDimitry Andric return EM_AARCH64; 15730b57cec5SDimitry Andric case Triple::amdgcn: 15740b57cec5SDimitry Andric case Triple::r600: 15750b57cec5SDimitry Andric return EM_AMDGPU; 15760b57cec5SDimitry Andric case Triple::arm: 15770b57cec5SDimitry Andric case Triple::thumb: 15780b57cec5SDimitry Andric return EM_ARM; 15790b57cec5SDimitry Andric case Triple::avr: 15800b57cec5SDimitry Andric return EM_AVR; 1581349cc55cSDimitry Andric case Triple::hexagon: 1582349cc55cSDimitry Andric return EM_HEXAGON; 15830b57cec5SDimitry Andric case Triple::mips: 15840b57cec5SDimitry Andric case Triple::mipsel: 15850b57cec5SDimitry Andric case Triple::mips64: 15860b57cec5SDimitry Andric case Triple::mips64el: 15870b57cec5SDimitry Andric return EM_MIPS; 15880b57cec5SDimitry Andric case Triple::msp430: 15890b57cec5SDimitry Andric return EM_MSP430; 15900b57cec5SDimitry Andric case Triple::ppc: 1591e8d8bef9SDimitry Andric case Triple::ppcle: 15920b57cec5SDimitry Andric return EM_PPC; 15930b57cec5SDimitry Andric case Triple::ppc64: 15940b57cec5SDimitry Andric case Triple::ppc64le: 15950b57cec5SDimitry Andric return EM_PPC64; 15960b57cec5SDimitry Andric case Triple::riscv32: 15970b57cec5SDimitry Andric case Triple::riscv64: 15980b57cec5SDimitry Andric return EM_RISCV; 15990b57cec5SDimitry Andric case Triple::x86: 16000b57cec5SDimitry Andric return t.isOSIAMCU() ? EM_IAMCU : EM_386; 16010b57cec5SDimitry Andric case Triple::x86_64: 16020b57cec5SDimitry Andric return EM_X86_64; 16030b57cec5SDimitry Andric default: 16040b57cec5SDimitry Andric error(path + ": could not infer e_machine from bitcode target triple " + 16050b57cec5SDimitry Andric t.str()); 16060b57cec5SDimitry Andric return EM_NONE; 16070b57cec5SDimitry Andric } 16080b57cec5SDimitry Andric } 16090b57cec5SDimitry Andric 1610e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) { 1611e8d8bef9SDimitry Andric switch (t.getOS()) { 1612e8d8bef9SDimitry Andric case Triple::AMDHSA: 1613e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_HSA; 1614e8d8bef9SDimitry Andric case Triple::AMDPAL: 1615e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_PAL; 1616e8d8bef9SDimitry Andric case Triple::Mesa3D: 1617e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_MESA3D; 1618e8d8bef9SDimitry Andric default: 1619e8d8bef9SDimitry Andric return ELF::ELFOSABI_NONE; 1620e8d8bef9SDimitry Andric } 1621e8d8bef9SDimitry Andric } 1622e8d8bef9SDimitry Andric 16230b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 16240eae32dcSDimitry Andric uint64_t offsetInArchive, bool lazy) 16250b57cec5SDimitry Andric : InputFile(BitcodeKind, mb) { 16260eae32dcSDimitry Andric this->archiveName = archiveName; 16270eae32dcSDimitry Andric this->lazy = lazy; 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 16300b57cec5SDimitry Andric if (config->thinLTOIndexOnly) 16310b57cec5SDimitry Andric path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 16320b57cec5SDimitry Andric 16330b57cec5SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 16340b57cec5SDimitry Andric // name. If two archives define two members with the same name, this 16350b57cec5SDimitry Andric // causes a collision which result in only one of the objects being taken 16360b57cec5SDimitry Andric // into consideration at LTO time (which very likely causes undefined 16370b57cec5SDimitry Andric // symbols later in the link stage). So we append file offset to make 16380b57cec5SDimitry Andric // filename unique. 163904eeddc0SDimitry Andric StringRef name = archiveName.empty() 164004eeddc0SDimitry Andric ? saver().save(path) 164104eeddc0SDimitry Andric : saver().save(archiveName + "(" + path::filename(path) + 164204eeddc0SDimitry Andric " at " + utostr(offsetInArchive) + ")"); 16430b57cec5SDimitry Andric MemoryBufferRef mbref(mb.getBuffer(), name); 16440b57cec5SDimitry Andric 16450b57cec5SDimitry Andric obj = CHECK(lto::InputFile::create(mbref), this); 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric Triple t(obj->getTargetTriple()); 16480b57cec5SDimitry Andric ekind = getBitcodeELFKind(t); 16490b57cec5SDimitry Andric emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t); 1650e8d8bef9SDimitry Andric osabi = getOsAbi(t); 16510b57cec5SDimitry Andric } 16520b57cec5SDimitry Andric 16530b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 16540b57cec5SDimitry Andric switch (gvVisibility) { 16550b57cec5SDimitry Andric case GlobalValue::DefaultVisibility: 16560b57cec5SDimitry Andric return STV_DEFAULT; 16570b57cec5SDimitry Andric case GlobalValue::HiddenVisibility: 16580b57cec5SDimitry Andric return STV_HIDDEN; 16590b57cec5SDimitry Andric case GlobalValue::ProtectedVisibility: 16600b57cec5SDimitry Andric return STV_PROTECTED; 16610b57cec5SDimitry Andric } 16620b57cec5SDimitry Andric llvm_unreachable("unknown visibility"); 16630b57cec5SDimitry Andric } 16640b57cec5SDimitry Andric 16650b57cec5SDimitry Andric template <class ELFT> 166604eeddc0SDimitry Andric static void 166704eeddc0SDimitry Andric createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats, 166804eeddc0SDimitry Andric const lto::InputFile::Symbol &objSym, BitcodeFile &f) { 16690b57cec5SDimitry Andric uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL; 16700b57cec5SDimitry Andric uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE; 16710b57cec5SDimitry Andric uint8_t visibility = mapVisibility(objSym.getVisibility()); 16720b57cec5SDimitry Andric bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable(); 16730b57cec5SDimitry Andric 167404eeddc0SDimitry Andric StringRef name; 167504eeddc0SDimitry Andric if (sym) { 167604eeddc0SDimitry Andric name = sym->getName(); 167704eeddc0SDimitry Andric } else { 167804eeddc0SDimitry Andric name = saver().save(objSym.getName()); 167904eeddc0SDimitry Andric sym = symtab->insert(name); 168004eeddc0SDimitry Andric } 168104eeddc0SDimitry Andric 16820b57cec5SDimitry Andric int c = objSym.getComdatIndex(); 16830b57cec5SDimitry Andric if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) { 168485868e8aSDimitry Andric Undefined newSym(&f, name, binding, visibility, type); 16850b57cec5SDimitry Andric if (canOmitFromDynSym) 168685868e8aSDimitry Andric newSym.exportDynamic = false; 168704eeddc0SDimitry Andric sym->resolve(newSym); 168804eeddc0SDimitry Andric sym->referenced = true; 168904eeddc0SDimitry Andric return; 16900b57cec5SDimitry Andric } 16910b57cec5SDimitry Andric 169204eeddc0SDimitry Andric if (objSym.isCommon()) { 169304eeddc0SDimitry Andric sym->resolve(CommonSymbol{&f, name, binding, visibility, STT_OBJECT, 169404eeddc0SDimitry Andric objSym.getCommonAlignment(), 169504eeddc0SDimitry Andric objSym.getCommonSize()}); 169604eeddc0SDimitry Andric } else { 169785868e8aSDimitry Andric Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr); 16980b57cec5SDimitry Andric if (canOmitFromDynSym) 169985868e8aSDimitry Andric newSym.exportDynamic = false; 170004eeddc0SDimitry Andric sym->resolve(newSym); 170104eeddc0SDimitry Andric } 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() { 17050b57cec5SDimitry Andric std::vector<bool> keptComdats; 1706fe6060f1SDimitry Andric for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) { 17070b57cec5SDimitry Andric keptComdats.push_back( 1708fe6060f1SDimitry Andric s.second == Comdat::NoDeduplicate || 1709fe6060f1SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this) 1710fe6060f1SDimitry Andric .second); 1711fe6060f1SDimitry Andric } 17120b57cec5SDimitry Andric 171304eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 171404eeddc0SDimitry Andric for (auto it : llvm::enumerate(obj->symbols())) { 171504eeddc0SDimitry Andric Symbol *&sym = symbols[it.index()]; 171604eeddc0SDimitry Andric createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this); 171704eeddc0SDimitry Andric } 17180b57cec5SDimitry Andric 17190b57cec5SDimitry Andric for (auto l : obj->getDependentLibraries()) 17200b57cec5SDimitry Andric addDependentLibrary(l, this); 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric 17230eae32dcSDimitry Andric void BitcodeFile::parseLazy() { 17240eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 172504eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 172604eeddc0SDimitry Andric for (auto it : llvm::enumerate(obj->symbols())) 172704eeddc0SDimitry Andric if (!it.value().isUndefined()) 172804eeddc0SDimitry Andric symbols[it.index()] = symtab.addSymbol( 172904eeddc0SDimitry Andric LazyObject{*this, saver().save(it.value().getName())}); 17300eae32dcSDimitry Andric } 17310eae32dcSDimitry Andric 17320b57cec5SDimitry Andric void BinaryFile::parse() { 17330b57cec5SDimitry Andric ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer()); 17340b57cec5SDimitry Andric auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 17350b57cec5SDimitry Andric 8, data, ".data"); 17360b57cec5SDimitry Andric sections.push_back(section); 17370b57cec5SDimitry Andric 17380b57cec5SDimitry Andric // For each input file foo that is embedded to a result as a binary 17390b57cec5SDimitry Andric // blob, we define _binary_foo_{start,end,size} symbols, so that 17400b57cec5SDimitry Andric // user programs can access blobs by name. Non-alphanumeric 17410b57cec5SDimitry Andric // characters in a filename are replaced with underscore. 17420b57cec5SDimitry Andric std::string s = "_binary_" + mb.getBufferIdentifier().str(); 17430b57cec5SDimitry Andric for (size_t i = 0; i < s.size(); ++i) 17440b57cec5SDimitry Andric if (!isAlnum(s[i])) 17450b57cec5SDimitry Andric s[i] = '_'; 17460b57cec5SDimitry Andric 174704eeddc0SDimitry Andric llvm::StringSaver &saver = lld::saver(); 174804eeddc0SDimitry Andric 17490b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL, 17500b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, 0, 0, section}); 17510b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL, 17520b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, section}); 17530b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL, 17540b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr}); 17550b57cec5SDimitry Andric } 17560b57cec5SDimitry Andric 17575ffd83dbSDimitry Andric InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName, 17580b57cec5SDimitry Andric uint64_t offsetInArchive) { 17590b57cec5SDimitry Andric if (isBitcode(mb)) 17600eae32dcSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false); 17610b57cec5SDimitry Andric 17620b57cec5SDimitry Andric switch (getELFKind(mb, archiveName)) { 17630b57cec5SDimitry Andric case ELF32LEKind: 17640b57cec5SDimitry Andric return make<ObjFile<ELF32LE>>(mb, archiveName); 17650b57cec5SDimitry Andric case ELF32BEKind: 17660b57cec5SDimitry Andric return make<ObjFile<ELF32BE>>(mb, archiveName); 17670b57cec5SDimitry Andric case ELF64LEKind: 17680b57cec5SDimitry Andric return make<ObjFile<ELF64LE>>(mb, archiveName); 17690b57cec5SDimitry Andric case ELF64BEKind: 17700b57cec5SDimitry Andric return make<ObjFile<ELF64BE>>(mb, archiveName); 17710b57cec5SDimitry Andric default: 17720b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 17730b57cec5SDimitry Andric } 17740b57cec5SDimitry Andric } 17750b57cec5SDimitry Andric 17760eae32dcSDimitry Andric InputFile *elf::createLazyFile(MemoryBufferRef mb, StringRef archiveName, 17770eae32dcSDimitry Andric uint64_t offsetInArchive) { 17780eae32dcSDimitry Andric if (isBitcode(mb)) 17790eae32dcSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/true); 17800b57cec5SDimitry Andric 17810eae32dcSDimitry Andric auto *file = 17820eae32dcSDimitry Andric cast<ELFFileBase>(createObjectFile(mb, archiveName, offsetInArchive)); 17830eae32dcSDimitry Andric file->lazy = true; 17840eae32dcSDimitry Andric return file; 17850b57cec5SDimitry Andric } 17860b57cec5SDimitry Andric 17870eae32dcSDimitry Andric template <class ELFT> void ObjFile<ELFT>::parseLazy() { 17880eae32dcSDimitry Andric const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>(); 17890eae32dcSDimitry Andric SymbolTable &symtab = *elf::symtab; 17900b57cec5SDimitry Andric 17910eae32dcSDimitry Andric symbols.resize(eSyms.size()); 17920b57cec5SDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 17930b57cec5SDimitry Andric if (eSyms[i].st_shndx != SHN_UNDEF) 17940eae32dcSDimitry Andric symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric // Replace existing symbols with LazyObject symbols. 17970b57cec5SDimitry Andric // 17980eae32dcSDimitry Andric // resolve() may trigger this->extract() if an existing symbol is an undefined 17990eae32dcSDimitry Andric // symbol. If that happens, this function has served its purpose, and we can 18000eae32dcSDimitry Andric // exit from the loop early. 18010eae32dcSDimitry Andric for (Symbol *sym : makeArrayRef(symbols).slice(firstGlobal)) 18020eae32dcSDimitry Andric if (sym) { 18030b57cec5SDimitry Andric sym->resolve(LazyObject{*this, sym->getName()}); 18040eae32dcSDimitry Andric if (!lazy) 18050b57cec5SDimitry Andric return; 18060b57cec5SDimitry Andric } 18070b57cec5SDimitry Andric } 18080b57cec5SDimitry Andric 18090eae32dcSDimitry Andric bool InputFile::shouldExtractForCommon(StringRef name) { 1810e8d8bef9SDimitry Andric if (isBitcode(mb)) 1811e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, name, archiveName); 1812e8d8bef9SDimitry Andric 1813e8d8bef9SDimitry Andric return isNonCommonDef(mb, name, archiveName); 1814e8d8bef9SDimitry Andric } 1815e8d8bef9SDimitry Andric 18165ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) { 18170b57cec5SDimitry Andric StringRef suffix = config->thinLTOObjectSuffixReplace.first; 18180b57cec5SDimitry Andric StringRef repl = config->thinLTOObjectSuffixReplace.second; 18190b57cec5SDimitry Andric 18200b57cec5SDimitry Andric if (path.consume_back(suffix)) 18210b57cec5SDimitry Andric return (path + repl).str(); 18225ffd83dbSDimitry Andric return std::string(path); 18230b57cec5SDimitry Andric } 18240b57cec5SDimitry Andric 18250b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>(); 18260b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>(); 18270b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>(); 18280b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>(); 18290b57cec5SDimitry Andric 18305ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>; 18315ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>; 18325ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>; 18335ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>; 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>(); 18360b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>(); 18370b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>(); 18380b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>(); 1839