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" 16480093f4SDimitry Andric #include "lld/Common/DWARF.h" 170b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h" 180b57cec5SDimitry Andric #include "lld/Common/Memory.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 465ffd83dbSDimitry Andric std::vector<ArchiveFile *> elf::archiveFiles; 475ffd83dbSDimitry Andric std::vector<BinaryFile *> elf::binaryFiles; 485ffd83dbSDimitry Andric std::vector<BitcodeFile *> elf::bitcodeFiles; 495ffd83dbSDimitry Andric std::vector<LazyObjFile *> elf::lazyObjFiles; 505ffd83dbSDimitry Andric std::vector<InputFile *> elf::objectFiles; 515ffd83dbSDimitry Andric std::vector<SharedFile *> elf::sharedFiles; 525ffd83dbSDimitry Andric 535ffd83dbSDimitry Andric std::unique_ptr<TarWriter> elf::tar; 545ffd83dbSDimitry Andric 5585868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 565ffd83dbSDimitry Andric std::string lld::toString(const InputFile *f) { 5785868e8aSDimitry Andric if (!f) 5885868e8aSDimitry Andric return "<internal>"; 590b57cec5SDimitry Andric 6085868e8aSDimitry Andric if (f->toStringCache.empty()) { 6185868e8aSDimitry Andric if (f->archiveName.empty()) 625ffd83dbSDimitry Andric f->toStringCache = std::string(f->getName()); 6385868e8aSDimitry Andric else 6485868e8aSDimitry Andric f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str(); 6585868e8aSDimitry Andric } 6685868e8aSDimitry Andric return f->toStringCache; 6785868e8aSDimitry Andric } 6885868e8aSDimitry Andric 690b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) { 700b57cec5SDimitry Andric unsigned char size; 710b57cec5SDimitry Andric unsigned char endian; 720b57cec5SDimitry Andric std::tie(size, endian) = getElfArchType(mb.getBuffer()); 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric auto report = [&](StringRef msg) { 750b57cec5SDimitry Andric StringRef filename = mb.getBufferIdentifier(); 760b57cec5SDimitry Andric if (archiveName.empty()) 770b57cec5SDimitry Andric fatal(filename + ": " + msg); 780b57cec5SDimitry Andric else 790b57cec5SDimitry Andric fatal(archiveName + "(" + filename + "): " + msg); 800b57cec5SDimitry Andric }; 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric if (!mb.getBuffer().startswith(ElfMagic)) 830b57cec5SDimitry Andric report("not an ELF file"); 840b57cec5SDimitry Andric if (endian != ELFDATA2LSB && endian != ELFDATA2MSB) 850b57cec5SDimitry Andric report("corrupted ELF file: invalid data encoding"); 860b57cec5SDimitry Andric if (size != ELFCLASS32 && size != ELFCLASS64) 870b57cec5SDimitry Andric report("corrupted ELF file: invalid file class"); 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric size_t bufSize = mb.getBuffer().size(); 900b57cec5SDimitry Andric if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) || 910b57cec5SDimitry Andric (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr))) 920b57cec5SDimitry Andric report("corrupted ELF file: file is too short"); 930b57cec5SDimitry Andric 940b57cec5SDimitry Andric if (size == ELFCLASS32) 950b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 960b57cec5SDimitry Andric return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m) 1000b57cec5SDimitry Andric : mb(m), groupId(nextGroupId), fileKind(k) { 1010b57cec5SDimitry Andric // All files within the same --{start,end}-group get the same group ID. 1020b57cec5SDimitry Andric // Otherwise, a new file will get a new group ID. 1030b57cec5SDimitry Andric if (!isInGroup) 1040b57cec5SDimitry Andric ++nextGroupId; 1050b57cec5SDimitry Andric } 1060b57cec5SDimitry Andric 1075ffd83dbSDimitry Andric Optional<MemoryBufferRef> elf::readFile(StringRef path) { 108e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files", path); 109e8d8bef9SDimitry Andric 1100b57cec5SDimitry Andric // The --chroot option changes our virtual root directory. 1110b57cec5SDimitry Andric // This is useful when you are dealing with files created by --reproduce. 1120b57cec5SDimitry Andric if (!config->chroot.empty() && path.startswith("/")) 1130b57cec5SDimitry Andric path = saver.save(config->chroot + path); 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric log(path); 116e8d8bef9SDimitry Andric config->dependencyFiles.insert(llvm::CachedHashString(path)); 1170b57cec5SDimitry Andric 118*fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 119*fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false); 1200b57cec5SDimitry Andric if (auto ec = mbOrErr.getError()) { 1210b57cec5SDimitry Andric error("cannot open " + path + ": " + ec.message()); 1220b57cec5SDimitry Andric return None; 1230b57cec5SDimitry Andric } 1240b57cec5SDimitry Andric 1250b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 1260b57cec5SDimitry Andric MemoryBufferRef mbref = mb->getMemBufferRef(); 1270b57cec5SDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // 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 1890b57cec5SDimitry Andric if (auto *f = dyn_cast<LazyObjFile>(file)) { 1900b57cec5SDimitry Andric lazyObjFiles.push_back(f); 1910b57cec5SDimitry Andric f->parse<ELFT>(); 1920b57cec5SDimitry Andric return; 1930b57cec5SDimitry Andric } 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric if (config->trace) 1960b57cec5SDimitry Andric message(toString(file)); 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric // .so file 1990b57cec5SDimitry Andric if (auto *f = dyn_cast<SharedFile>(file)) { 2000b57cec5SDimitry Andric f->parse<ELFT>(); 2010b57cec5SDimitry Andric return; 2020b57cec5SDimitry Andric } 2030b57cec5SDimitry Andric 2040b57cec5SDimitry Andric // LLVM bitcode file 2050b57cec5SDimitry Andric if (auto *f = dyn_cast<BitcodeFile>(file)) { 2060b57cec5SDimitry Andric bitcodeFiles.push_back(f); 2070b57cec5SDimitry Andric f->parse<ELFT>(); 2080b57cec5SDimitry Andric return; 2090b57cec5SDimitry Andric } 2100b57cec5SDimitry Andric 2110b57cec5SDimitry Andric // Regular object file 2120b57cec5SDimitry Andric objectFiles.push_back(file); 2130b57cec5SDimitry Andric cast<ObjFile<ELFT>>(file)->parse(); 2140b57cec5SDimitry Andric } 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric // Add symbols in File to the symbol table. 2175ffd83dbSDimitry Andric void elf::parseFile(InputFile *file) { 2180b57cec5SDimitry Andric switch (config->ekind) { 2190b57cec5SDimitry Andric case ELF32LEKind: 2200b57cec5SDimitry Andric doParseFile<ELF32LE>(file); 2210b57cec5SDimitry Andric return; 2220b57cec5SDimitry Andric case ELF32BEKind: 2230b57cec5SDimitry Andric doParseFile<ELF32BE>(file); 2240b57cec5SDimitry Andric return; 2250b57cec5SDimitry Andric case ELF64LEKind: 2260b57cec5SDimitry Andric doParseFile<ELF64LE>(file); 2270b57cec5SDimitry Andric return; 2280b57cec5SDimitry Andric case ELF64BEKind: 2290b57cec5SDimitry Andric doParseFile<ELF64BE>(file); 2300b57cec5SDimitry Andric return; 2310b57cec5SDimitry Andric default: 2320b57cec5SDimitry Andric llvm_unreachable("unknown ELFT"); 2330b57cec5SDimitry Andric } 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location. 2370b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) { 2385ffd83dbSDimitry Andric std::string filename = std::string(path::filename(path)); 2390b57cec5SDimitry Andric std::string lineno = ":" + std::to_string(line); 2400b57cec5SDimitry Andric if (filename == path) 2410b57cec5SDimitry Andric return filename + lineno; 2420b57cec5SDimitry Andric return filename + lineno + " (" + path.str() + lineno + ")"; 2430b57cec5SDimitry Andric } 2440b57cec5SDimitry Andric 2450b57cec5SDimitry Andric template <class ELFT> 2460b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym, 2470b57cec5SDimitry Andric InputSectionBase &sec, uint64_t offset) { 2480b57cec5SDimitry Andric // In DWARF, functions and variables are stored to different places. 2490b57cec5SDimitry Andric // First, lookup a function for a given offset. 2500b57cec5SDimitry Andric if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset)) 2510b57cec5SDimitry Andric return createFileLineMsg(info->FileName, info->Line); 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric // If it failed, lookup again as a variable. 2540b57cec5SDimitry Andric if (Optional<std::pair<std::string, unsigned>> fileLine = 2550b57cec5SDimitry Andric file.getVariableLoc(sym.getName())) 2560b57cec5SDimitry Andric return createFileLineMsg(fileLine->first, fileLine->second); 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric // File.sourceFile contains STT_FILE symbol, and that is a last resort. 2595ffd83dbSDimitry Andric return std::string(file.sourceFile); 2600b57cec5SDimitry Andric } 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec, 2630b57cec5SDimitry Andric uint64_t offset) { 2640b57cec5SDimitry Andric if (kind() != ObjKind) 2650b57cec5SDimitry Andric return ""; 2660b57cec5SDimitry Andric switch (config->ekind) { 2670b57cec5SDimitry Andric default: 2680b57cec5SDimitry Andric llvm_unreachable("Invalid kind"); 2690b57cec5SDimitry Andric case ELF32LEKind: 2700b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset); 2710b57cec5SDimitry Andric case ELF32BEKind: 2720b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset); 2730b57cec5SDimitry Andric case ELF64LEKind: 2740b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset); 2750b57cec5SDimitry Andric case ELF64BEKind: 2760b57cec5SDimitry Andric return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset); 2770b57cec5SDimitry Andric } 2780b57cec5SDimitry Andric } 2790b57cec5SDimitry Andric 280e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const { 281e8d8bef9SDimitry Andric if (archiveName.empty()) 282e8d8bef9SDimitry Andric return getName(); 283e8d8bef9SDimitry Andric 284e8d8bef9SDimitry Andric if (nameForScriptCache.empty()) 285e8d8bef9SDimitry Andric nameForScriptCache = (archiveName + Twine(':') + getName()).str(); 286e8d8bef9SDimitry Andric 287e8d8bef9SDimitry Andric return nameForScriptCache; 288e8d8bef9SDimitry Andric } 289e8d8bef9SDimitry Andric 2905ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() { 2915ffd83dbSDimitry Andric llvm::call_once(initDwarf, [this]() { 2925ffd83dbSDimitry Andric dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 2935ffd83dbSDimitry Andric std::make_unique<LLDDwarfObj<ELFT>>(this), "", 2945ffd83dbSDimitry Andric [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 2955ffd83dbSDimitry Andric [&](Error warning) { 2965ffd83dbSDimitry Andric warn(getName() + ": " + toString(std::move(warning))); 2975ffd83dbSDimitry Andric })); 2985ffd83dbSDimitry Andric }); 2995ffd83dbSDimitry Andric 3005ffd83dbSDimitry Andric return dwarf.get(); 3010b57cec5SDimitry Andric } 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data 3040b57cec5SDimitry Andric // object (variable, array, etc) definition. 3050b57cec5SDimitry Andric template <class ELFT> 3060b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>> 3070b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) { 3085ffd83dbSDimitry Andric return getDwarf()->getVariableLoc(name); 3090b57cec5SDimitry Andric } 3100b57cec5SDimitry Andric 3110b57cec5SDimitry Andric // Returns source line information for a given offset 3120b57cec5SDimitry Andric // using DWARF debug info. 3130b57cec5SDimitry Andric template <class ELFT> 3140b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s, 3150b57cec5SDimitry Andric uint64_t offset) { 3160b57cec5SDimitry Andric // Detect SectionIndex for specified section. 3170b57cec5SDimitry Andric uint64_t sectionIndex = object::SectionedAddress::UndefSection; 3180b57cec5SDimitry Andric ArrayRef<InputSectionBase *> sections = s->file->getSections(); 3190b57cec5SDimitry Andric for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) { 3200b57cec5SDimitry Andric if (s == sections[curIndex]) { 3210b57cec5SDimitry Andric sectionIndex = curIndex; 3220b57cec5SDimitry Andric break; 3230b57cec5SDimitry Andric } 3240b57cec5SDimitry Andric } 3250b57cec5SDimitry Andric 3265ffd83dbSDimitry Andric return getDwarf()->getDILineInfo(offset, sectionIndex); 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric 3290b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) { 3300b57cec5SDimitry Andric ekind = getELFKind(mb, ""); 3310b57cec5SDimitry Andric 3320b57cec5SDimitry Andric switch (ekind) { 3330b57cec5SDimitry Andric case ELF32LEKind: 3340b57cec5SDimitry Andric init<ELF32LE>(); 3350b57cec5SDimitry Andric break; 3360b57cec5SDimitry Andric case ELF32BEKind: 3370b57cec5SDimitry Andric init<ELF32BE>(); 3380b57cec5SDimitry Andric break; 3390b57cec5SDimitry Andric case ELF64LEKind: 3400b57cec5SDimitry Andric init<ELF64LE>(); 3410b57cec5SDimitry Andric break; 3420b57cec5SDimitry Andric case ELF64BEKind: 3430b57cec5SDimitry Andric init<ELF64BE>(); 3440b57cec5SDimitry Andric break; 3450b57cec5SDimitry Andric default: 3460b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 3470b57cec5SDimitry Andric } 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric template <typename Elf_Shdr> 3510b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) { 3520b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) 3530b57cec5SDimitry Andric if (sec.sh_type == type) 3540b57cec5SDimitry Andric return &sec; 3550b57cec5SDimitry Andric return nullptr; 3560b57cec5SDimitry Andric } 3570b57cec5SDimitry Andric 3580b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() { 3590b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 3600b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 3610b57cec5SDimitry Andric 3620b57cec5SDimitry Andric // Initialize trivial attributes. 3630b57cec5SDimitry Andric const ELFFile<ELFT> &obj = getObj<ELFT>(); 364e8d8bef9SDimitry Andric emachine = obj.getHeader().e_machine; 365e8d8bef9SDimitry Andric osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI]; 366e8d8bef9SDimitry Andric abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION]; 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this); 3690b57cec5SDimitry Andric 3700b57cec5SDimitry Andric // Find a symbol table. 3710b57cec5SDimitry Andric bool isDSO = 3720b57cec5SDimitry Andric (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object); 3730b57cec5SDimitry Andric const Elf_Shdr *symtabSec = 3740b57cec5SDimitry Andric findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB); 3750b57cec5SDimitry Andric 3760b57cec5SDimitry Andric if (!symtabSec) 3770b57cec5SDimitry Andric return; 3780b57cec5SDimitry Andric 3790b57cec5SDimitry Andric // Initialize members corresponding to a symbol table. 3800b57cec5SDimitry Andric firstGlobal = symtabSec->sh_info; 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this); 3830b57cec5SDimitry Andric if (firstGlobal == 0 || firstGlobal > eSyms.size()) 3840b57cec5SDimitry Andric fatal(toString(this) + ": invalid sh_info in symbol table"); 3850b57cec5SDimitry Andric 3860b57cec5SDimitry Andric elfSyms = reinterpret_cast<const void *>(eSyms.data()); 3870b57cec5SDimitry Andric numELFSyms = eSyms.size(); 3880b57cec5SDimitry Andric stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this); 3890b57cec5SDimitry Andric } 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric template <class ELFT> 3920b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const { 3930b57cec5SDimitry Andric return CHECK( 394e8d8bef9SDimitry Andric this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable), 3950b57cec5SDimitry Andric this); 3960b57cec5SDimitry Andric } 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() { 3990b57cec5SDimitry Andric if (this->symbols.empty()) 4000b57cec5SDimitry Andric return {}; 4010b57cec5SDimitry Andric return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1); 4020b57cec5SDimitry Andric } 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() { 4050b57cec5SDimitry Andric return makeArrayRef(this->symbols).slice(this->firstGlobal); 4060b57cec5SDimitry Andric } 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) { 4090b57cec5SDimitry Andric // Read a section table. justSymbols is usually false. 4100b57cec5SDimitry Andric if (this->justSymbols) 4110b57cec5SDimitry Andric initializeJustSymbols(); 4120b57cec5SDimitry Andric else 4130b57cec5SDimitry Andric initializeSections(ignoreComdats); 4140b57cec5SDimitry Andric 4150b57cec5SDimitry Andric // Read a symbol table. 4160b57cec5SDimitry Andric initializeSymbols(); 4170b57cec5SDimitry Andric } 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups. 4200b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function 4210b57cec5SDimitry Andric // returns a group name. 4220b57cec5SDimitry Andric template <class ELFT> 4230b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections, 4240b57cec5SDimitry Andric const Elf_Shdr &sec) { 4250b57cec5SDimitry Andric typename ELFT::SymRange symbols = this->getELFSyms<ELFT>(); 4260b57cec5SDimitry Andric if (sec.sh_info >= symbols.size()) 4270b57cec5SDimitry Andric fatal(toString(this) + ": invalid symbol index"); 4280b57cec5SDimitry Andric const typename ELFT::Sym &sym = symbols[sec.sh_info]; 4290b57cec5SDimitry Andric StringRef signature = CHECK(sym.getName(this->stringTable), this); 4300b57cec5SDimitry Andric 4310b57cec5SDimitry Andric // As a special case, if a symbol is a section symbol and has no name, 4320b57cec5SDimitry Andric // we use a section name as a signature. 4330b57cec5SDimitry Andric // 4340b57cec5SDimitry Andric // Such SHT_GROUP sections are invalid from the perspective of the ELF 4350b57cec5SDimitry Andric // standard, but GNU gold 1.14 (the newest version as of July 2017) or 4360b57cec5SDimitry Andric // older produce such sections as outputs for the -r option, so we need 4370b57cec5SDimitry Andric // a bug-compatibility. 4380b57cec5SDimitry Andric if (signature.empty() && sym.getType() == STT_SECTION) 4390b57cec5SDimitry Andric return getSectionName(sec); 4400b57cec5SDimitry Andric return signature; 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric 44385868e8aSDimitry Andric template <class ELFT> 44485868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) { 4455ffd83dbSDimitry Andric if (!(sec.sh_flags & SHF_MERGE)) 4465ffd83dbSDimitry Andric return false; 4475ffd83dbSDimitry Andric 4480b57cec5SDimitry Andric // On a regular link we don't merge sections if -O0 (default is -O1). This 4490b57cec5SDimitry Andric // sometimes makes the linker significantly faster, although the output will 4500b57cec5SDimitry Andric // be bigger. 4510b57cec5SDimitry Andric // 4520b57cec5SDimitry Andric // Doing the same for -r would create a problem as it would combine sections 4530b57cec5SDimitry Andric // with different sh_entsize. One option would be to just copy every SHF_MERGE 4540b57cec5SDimitry Andric // section as is to the output. While this would produce a valid ELF file with 4550b57cec5SDimitry Andric // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when 4560b57cec5SDimitry Andric // they see two .debug_str. We could have separate logic for combining 4570b57cec5SDimitry Andric // SHF_MERGE sections based both on their name and sh_entsize, but that seems 4580b57cec5SDimitry Andric // to be more trouble than it is worth. Instead, we just use the regular (-O1) 4590b57cec5SDimitry Andric // logic for -r. 4600b57cec5SDimitry Andric if (config->optimize == 0 && !config->relocatable) 4610b57cec5SDimitry Andric return false; 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric // A mergeable section with size 0 is useless because they don't have 4640b57cec5SDimitry Andric // any data to merge. A mergeable string section with size 0 can be 4650b57cec5SDimitry Andric // argued as invalid because it doesn't end with a null character. 4660b57cec5SDimitry Andric // We'll avoid a mess by handling them as if they were non-mergeable. 4670b57cec5SDimitry Andric if (sec.sh_size == 0) 4680b57cec5SDimitry Andric return false; 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric // Check for sh_entsize. The ELF spec is not clear about the zero 4710b57cec5SDimitry Andric // sh_entsize. It says that "the member [sh_entsize] contains 0 if 4720b57cec5SDimitry Andric // the section does not hold a table of fixed-size entries". We know 4730b57cec5SDimitry Andric // that Rust 1.13 produces a string mergeable section with a zero 4740b57cec5SDimitry Andric // sh_entsize. Here we just accept it rather than being picky about it. 4750b57cec5SDimitry Andric uint64_t entSize = sec.sh_entsize; 4760b57cec5SDimitry Andric if (entSize == 0) 4770b57cec5SDimitry Andric return false; 4780b57cec5SDimitry Andric if (sec.sh_size % entSize) 47985868e8aSDimitry Andric fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" + 48085868e8aSDimitry Andric Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" + 48185868e8aSDimitry Andric Twine(entSize) + ")"); 4820b57cec5SDimitry Andric 4835ffd83dbSDimitry Andric if (sec.sh_flags & SHF_WRITE) 48485868e8aSDimitry Andric fatal(toString(this) + ":(" + name + 48585868e8aSDimitry Andric "): writable SHF_MERGE section is not supported"); 4860b57cec5SDimitry Andric 4870b57cec5SDimitry Andric return true; 4880b57cec5SDimitry Andric } 4890b57cec5SDimitry Andric 4900b57cec5SDimitry Andric // This is for --just-symbols. 4910b57cec5SDimitry Andric // 4920b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your 4930b57cec5SDimitry Andric // output against other existing program, so that if you load both your 4940b57cec5SDimitry Andric // program and the other program into memory, your output can refer the 4950b57cec5SDimitry Andric // other program's symbols. 4960b57cec5SDimitry Andric // 4970b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is 4980b57cec5SDimitry Andric // initialized with null pointers. 4990b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() { 5000b57cec5SDimitry Andric ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this); 5010b57cec5SDimitry Andric this->sections.resize(sections.size()); 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric 5040b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the 5050b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This 5060b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking 5070b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension 5080b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently 5090b57cec5SDimitry Andric // unique to LLVM and lld. 5100b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) { 5110b57cec5SDimitry Andric if (!config->dependentLibraries) 5120b57cec5SDimitry Andric return; 5130b57cec5SDimitry Andric if (fs::exists(specifier)) 5140b57cec5SDimitry Andric driver->addFile(specifier, /*withLOption=*/false); 5150b57cec5SDimitry Andric else if (Optional<std::string> s = findFromSearchPaths(specifier)) 5160b57cec5SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 5170b57cec5SDimitry Andric else if (Optional<std::string> s = searchLibraryBaseName(specifier)) 5180b57cec5SDimitry Andric driver->addFile(*s, /*withLOption=*/true); 5190b57cec5SDimitry Andric else 5200b57cec5SDimitry Andric error(toString(f) + 5210b57cec5SDimitry Andric ": unable to find library from dependent library specifier: " + 5220b57cec5SDimitry Andric specifier); 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 525480093f4SDimitry Andric // Record the membership of a section group so that in the garbage collection 526480093f4SDimitry Andric // pass, section group members are kept or discarded as a unit. 527480093f4SDimitry Andric template <class ELFT> 528480093f4SDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections, 529480093f4SDimitry Andric ArrayRef<typename ELFT::Word> entries) { 530480093f4SDimitry Andric bool hasAlloc = false; 531480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 532480093f4SDimitry Andric if (index >= sections.size()) 533480093f4SDimitry Andric return; 534480093f4SDimitry Andric if (InputSectionBase *s = sections[index]) 535480093f4SDimitry Andric if (s != &InputSection::discarded && s->flags & SHF_ALLOC) 536480093f4SDimitry Andric hasAlloc = true; 537480093f4SDimitry Andric } 538480093f4SDimitry Andric 539480093f4SDimitry Andric // If any member has the SHF_ALLOC flag, the whole group is subject to garbage 540480093f4SDimitry Andric // collection. See the comment in markLive(). This rule retains .debug_types 541480093f4SDimitry Andric // and .rela.debug_types. 542480093f4SDimitry Andric if (!hasAlloc) 543480093f4SDimitry Andric return; 544480093f4SDimitry Andric 545480093f4SDimitry Andric // Connect the members in a circular doubly-linked list via 546480093f4SDimitry Andric // nextInSectionGroup. 547480093f4SDimitry Andric InputSectionBase *head; 548480093f4SDimitry Andric InputSectionBase *prev = nullptr; 549480093f4SDimitry Andric for (uint32_t index : entries.slice(1)) { 550480093f4SDimitry Andric InputSectionBase *s = sections[index]; 551480093f4SDimitry Andric if (!s || s == &InputSection::discarded) 552480093f4SDimitry Andric continue; 553480093f4SDimitry Andric if (prev) 554480093f4SDimitry Andric prev->nextInSectionGroup = s; 555480093f4SDimitry Andric else 556480093f4SDimitry Andric head = s; 557480093f4SDimitry Andric prev = s; 558480093f4SDimitry Andric } 559480093f4SDimitry Andric if (prev) 560480093f4SDimitry Andric prev->nextInSectionGroup = head; 561480093f4SDimitry Andric } 562480093f4SDimitry Andric 5630b57cec5SDimitry Andric template <class ELFT> 5640b57cec5SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats) { 5650b57cec5SDimitry Andric const ELFFile<ELFT> &obj = this->getObj(); 5660b57cec5SDimitry Andric 5670b57cec5SDimitry Andric ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this); 5680b57cec5SDimitry Andric uint64_t size = objSections.size(); 5690b57cec5SDimitry Andric this->sections.resize(size); 5700b57cec5SDimitry Andric this->sectionStringTable = 5710b57cec5SDimitry Andric CHECK(obj.getSectionStringTable(objSections), this); 5720b57cec5SDimitry Andric 573480093f4SDimitry Andric std::vector<ArrayRef<Elf_Word>> selectedGroups; 574480093f4SDimitry Andric 57585868e8aSDimitry Andric for (size_t i = 0, e = objSections.size(); i < e; ++i) { 5760b57cec5SDimitry Andric if (this->sections[i] == &InputSection::discarded) 5770b57cec5SDimitry Andric continue; 5780b57cec5SDimitry Andric const Elf_Shdr &sec = objSections[i]; 5790b57cec5SDimitry Andric 5800b57cec5SDimitry Andric if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE) 581*fe6060f1SDimitry Andric cgProfileSectionIndex = i; 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric // SHF_EXCLUDE'ed sections are discarded by the linker. However, 5840b57cec5SDimitry Andric // if -r is given, we'll let the final link discard such sections. 5850b57cec5SDimitry Andric // This is compatible with GNU. 5860b57cec5SDimitry Andric if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) { 5870b57cec5SDimitry Andric if (sec.sh_type == SHT_LLVM_ADDRSIG) { 5880b57cec5SDimitry Andric // We ignore the address-significance table if we know that the object 5890b57cec5SDimitry Andric // file was created by objcopy or ld -r. This is because these tools 5900b57cec5SDimitry Andric // will reorder the symbols in the symbol table, invalidating the data 5910b57cec5SDimitry Andric // in the address-significance table, which refers to symbols by index. 5920b57cec5SDimitry Andric if (sec.sh_link != 0) 5930b57cec5SDimitry Andric this->addrsigSec = &sec; 5940b57cec5SDimitry Andric else if (config->icf == ICFLevel::Safe) 595*fe6060f1SDimitry Andric warn(toString(this) + 596*fe6060f1SDimitry Andric ": --icf=safe conservatively ignores " 597*fe6060f1SDimitry Andric "SHT_LLVM_ADDRSIG [index " + 598*fe6060f1SDimitry Andric Twine(i) + 599*fe6060f1SDimitry Andric "] with sh_link=0 " 600*fe6060f1SDimitry Andric "(likely created using objcopy or ld -r)"); 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 6030b57cec5SDimitry Andric continue; 6040b57cec5SDimitry Andric } 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric switch (sec.sh_type) { 6070b57cec5SDimitry Andric case SHT_GROUP: { 6080b57cec5SDimitry Andric // De-duplicate section groups by their signatures. 6090b57cec5SDimitry Andric StringRef signature = getShtGroupSignature(objSections, sec); 6100b57cec5SDimitry Andric this->sections[i] = &InputSection::discarded; 6110b57cec5SDimitry Andric 6120b57cec5SDimitry Andric ArrayRef<Elf_Word> entries = 613e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this); 6140b57cec5SDimitry Andric if (entries.empty()) 6150b57cec5SDimitry Andric fatal(toString(this) + ": empty SHT_GROUP"); 6160b57cec5SDimitry Andric 617*fe6060f1SDimitry Andric Elf_Word flag = entries[0]; 618*fe6060f1SDimitry Andric if (flag && flag != GRP_COMDAT) 6190b57cec5SDimitry Andric fatal(toString(this) + ": unsupported SHT_GROUP format"); 6200b57cec5SDimitry Andric 621*fe6060f1SDimitry Andric bool keepGroup = 622*fe6060f1SDimitry Andric (flag & GRP_COMDAT) == 0 || ignoreComdats || 6230b57cec5SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this) 6240b57cec5SDimitry Andric .second; 625*fe6060f1SDimitry Andric if (keepGroup) { 6260b57cec5SDimitry Andric if (config->relocatable) 6270b57cec5SDimitry Andric this->sections[i] = createInputSection(sec); 628480093f4SDimitry Andric selectedGroups.push_back(entries); 6290b57cec5SDimitry Andric continue; 6300b57cec5SDimitry Andric } 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric // Otherwise, discard group members. 6330b57cec5SDimitry Andric for (uint32_t secIndex : entries.slice(1)) { 6340b57cec5SDimitry Andric if (secIndex >= size) 6350b57cec5SDimitry Andric fatal(toString(this) + 6360b57cec5SDimitry Andric ": invalid section index in group: " + Twine(secIndex)); 6370b57cec5SDimitry Andric this->sections[secIndex] = &InputSection::discarded; 6380b57cec5SDimitry Andric } 6390b57cec5SDimitry Andric break; 6400b57cec5SDimitry Andric } 6410b57cec5SDimitry Andric case SHT_SYMTAB_SHNDX: 6420b57cec5SDimitry Andric shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this); 6430b57cec5SDimitry Andric break; 6440b57cec5SDimitry Andric case SHT_SYMTAB: 6450b57cec5SDimitry Andric case SHT_STRTAB: 6465ffd83dbSDimitry Andric case SHT_REL: 6475ffd83dbSDimitry Andric case SHT_RELA: 6480b57cec5SDimitry Andric case SHT_NULL: 6490b57cec5SDimitry Andric break; 6500b57cec5SDimitry Andric default: 6510b57cec5SDimitry Andric this->sections[i] = createInputSection(sec); 6520b57cec5SDimitry Andric } 65385868e8aSDimitry Andric } 65485868e8aSDimitry Andric 6555ffd83dbSDimitry Andric // We have a second loop. It is used to: 6565ffd83dbSDimitry Andric // 1) handle SHF_LINK_ORDER sections. 6575ffd83dbSDimitry Andric // 2) create SHT_REL[A] sections. In some cases the section header index of a 6585ffd83dbSDimitry Andric // relocation section may be smaller than that of the relocated section. In 6595ffd83dbSDimitry Andric // such cases, the relocation section would attempt to reference a target 6605ffd83dbSDimitry Andric // section that has not yet been created. For simplicity, delay creation of 6615ffd83dbSDimitry Andric // relocation sections until now. 66285868e8aSDimitry Andric for (size_t i = 0, e = objSections.size(); i < e; ++i) { 66385868e8aSDimitry Andric if (this->sections[i] == &InputSection::discarded) 66485868e8aSDimitry Andric continue; 66585868e8aSDimitry Andric const Elf_Shdr &sec = objSections[i]; 6665ffd83dbSDimitry Andric 6675ffd83dbSDimitry Andric if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) 6685ffd83dbSDimitry Andric this->sections[i] = createInputSection(sec); 6695ffd83dbSDimitry Andric 670e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have 671e8d8bef9SDimitry Andric // the flag. 672e8d8bef9SDimitry Andric if (!(sec.sh_flags & SHF_LINK_ORDER) || !sec.sh_link) 67385868e8aSDimitry Andric continue; 6740b57cec5SDimitry Andric 6750b57cec5SDimitry Andric InputSectionBase *linkSec = nullptr; 6760b57cec5SDimitry Andric if (sec.sh_link < this->sections.size()) 6770b57cec5SDimitry Andric linkSec = this->sections[sec.sh_link]; 6780b57cec5SDimitry Andric if (!linkSec) 67985868e8aSDimitry Andric fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link)); 6800b57cec5SDimitry Andric 681e8d8bef9SDimitry Andric // A SHF_LINK_ORDER section is discarded if its linked-to section is 682e8d8bef9SDimitry Andric // discarded. 6830b57cec5SDimitry Andric InputSection *isec = cast<InputSection>(this->sections[i]); 6840b57cec5SDimitry Andric linkSec->dependentSections.push_back(isec); 6850b57cec5SDimitry Andric if (!isa<InputSection>(linkSec)) 6860b57cec5SDimitry Andric error("a section " + isec->name + 68785868e8aSDimitry Andric " with SHF_LINK_ORDER should not refer a non-regular section: " + 6880b57cec5SDimitry Andric toString(linkSec)); 6890b57cec5SDimitry Andric } 690480093f4SDimitry Andric 691480093f4SDimitry Andric for (ArrayRef<Elf_Word> entries : selectedGroups) 692480093f4SDimitry Andric handleSectionGroup<ELFT>(this->sections, entries); 6930b57cec5SDimitry Andric } 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD 6960b57cec5SDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how 6970b57cec5SDimitry Andric // the input objects have been compiled. 6980b57cec5SDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes, 6990b57cec5SDimitry Andric const InputFile *f) { 7005ffd83dbSDimitry Andric Optional<unsigned> attr = 7015ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args); 7025ffd83dbSDimitry Andric if (!attr.hasValue()) 7030b57cec5SDimitry Andric // If an ABI tag isn't present then it is implicitly given the value of 0 7040b57cec5SDimitry Andric // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files, 7050b57cec5SDimitry Andric // including some in glibc that don't use FP args (and should have value 3) 7060b57cec5SDimitry Andric // don't have the attribute so we do not consider an implicit value of 0 7070b57cec5SDimitry Andric // as a clash. 7080b57cec5SDimitry Andric return; 7090b57cec5SDimitry Andric 7105ffd83dbSDimitry Andric unsigned vfpArgs = attr.getValue(); 7110b57cec5SDimitry Andric ARMVFPArgKind arg; 7120b57cec5SDimitry Andric switch (vfpArgs) { 7130b57cec5SDimitry Andric case ARMBuildAttrs::BaseAAPCS: 7140b57cec5SDimitry Andric arg = ARMVFPArgKind::Base; 7150b57cec5SDimitry Andric break; 7160b57cec5SDimitry Andric case ARMBuildAttrs::HardFPAAPCS: 7170b57cec5SDimitry Andric arg = ARMVFPArgKind::VFP; 7180b57cec5SDimitry Andric break; 7190b57cec5SDimitry Andric case ARMBuildAttrs::ToolChainFPPCS: 7200b57cec5SDimitry Andric // Tool chain specific convention that conforms to neither AAPCS variant. 7210b57cec5SDimitry Andric arg = ARMVFPArgKind::ToolChain; 7220b57cec5SDimitry Andric break; 7230b57cec5SDimitry Andric case ARMBuildAttrs::CompatibleFPAAPCS: 7240b57cec5SDimitry Andric // Object compatible with all conventions. 7250b57cec5SDimitry Andric return; 7260b57cec5SDimitry Andric default: 7270b57cec5SDimitry Andric error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs)); 7280b57cec5SDimitry Andric return; 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric // Follow ld.bfd and error if there is a mix of calling conventions. 7310b57cec5SDimitry Andric if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default) 7320b57cec5SDimitry Andric error(toString(f) + ": incompatible Tag_ABI_VFP_args"); 7330b57cec5SDimitry Andric else 7340b57cec5SDimitry Andric config->armVFPArgs = arg; 7350b57cec5SDimitry Andric } 7360b57cec5SDimitry Andric 7370b57cec5SDimitry Andric // The ARM support in lld makes some use of instructions that are not available 7380b57cec5SDimitry Andric // on all ARM architectures. Namely: 7390b57cec5SDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state. 7400b57cec5SDimitry Andric // - Use of the extended Thumb branch encoding in relocation. 7410b57cec5SDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks. 7420b57cec5SDimitry Andric // The ARM Attributes section contains information about the architecture chosen 7430b57cec5SDimitry Andric // at compile time. We follow the convention that if at least one input object 7440b57cec5SDimitry Andric // is compiled with an architecture that supports these features then lld is 7450b57cec5SDimitry Andric // permitted to use them. 7460b57cec5SDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) { 7475ffd83dbSDimitry Andric Optional<unsigned> attr = 7485ffd83dbSDimitry Andric attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 7495ffd83dbSDimitry Andric if (!attr.hasValue()) 7500b57cec5SDimitry Andric return; 7515ffd83dbSDimitry Andric auto arch = attr.getValue(); 7520b57cec5SDimitry Andric switch (arch) { 7530b57cec5SDimitry Andric case ARMBuildAttrs::Pre_v4: 7540b57cec5SDimitry Andric case ARMBuildAttrs::v4: 7550b57cec5SDimitry Andric case ARMBuildAttrs::v4T: 7560b57cec5SDimitry Andric // Architectures prior to v5 do not support BLX instruction 7570b57cec5SDimitry Andric break; 7580b57cec5SDimitry Andric case ARMBuildAttrs::v5T: 7590b57cec5SDimitry Andric case ARMBuildAttrs::v5TE: 7600b57cec5SDimitry Andric case ARMBuildAttrs::v5TEJ: 7610b57cec5SDimitry Andric case ARMBuildAttrs::v6: 7620b57cec5SDimitry Andric case ARMBuildAttrs::v6KZ: 7630b57cec5SDimitry Andric case ARMBuildAttrs::v6K: 7640b57cec5SDimitry Andric config->armHasBlx = true; 7650b57cec5SDimitry Andric // Architectures used in pre-Cortex processors do not support 7660b57cec5SDimitry Andric // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 7670b57cec5SDimitry Andric // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 7680b57cec5SDimitry Andric break; 7690b57cec5SDimitry Andric default: 7700b57cec5SDimitry Andric // All other Architectures have BLX and extended branch encoding 7710b57cec5SDimitry Andric config->armHasBlx = true; 7720b57cec5SDimitry Andric config->armJ1J2BranchEncoding = true; 7730b57cec5SDimitry Andric if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M) 7740b57cec5SDimitry Andric // All Architectures used in Cortex processors with the exception 7750b57cec5SDimitry Andric // of v6-M and v6S-M have the MOVT and MOVW instructions. 7760b57cec5SDimitry Andric config->armHasMovtMovw = true; 7770b57cec5SDimitry Andric break; 7780b57cec5SDimitry Andric } 7790b57cec5SDimitry Andric } 7800b57cec5SDimitry Andric 7810b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control 7820b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that 7830b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it. 7840b57cec5SDimitry Andric // 7850b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this 7860b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a 7870b57cec5SDimitry Andric // .note.gnu.property section. 7880b57cec5SDimitry Andric // 7890b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists 7900b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a 7910b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps 7920b57cec5SDimitry Andric // the ABI is unnecessarily complicated. 793e8d8bef9SDimitry Andric template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) { 7940b57cec5SDimitry Andric using Elf_Nhdr = typename ELFT::Nhdr; 7950b57cec5SDimitry Andric using Elf_Note = typename ELFT::Note; 7960b57cec5SDimitry Andric 7970b57cec5SDimitry Andric uint32_t featuresSet = 0; 798e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = sec.data(); 799e8d8bef9SDimitry Andric auto reportFatal = [&](const uint8_t *place, const char *msg) { 800e8d8bef9SDimitry Andric fatal(toString(sec.file) + ":(" + sec.name + "+0x" + 801e8d8bef9SDimitry Andric Twine::utohexstr(place - sec.data().data()) + "): " + msg); 802e8d8bef9SDimitry Andric }; 8030b57cec5SDimitry Andric while (!data.empty()) { 8040b57cec5SDimitry Andric // Read one NOTE record. 8050b57cec5SDimitry Andric auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data()); 806e8d8bef9SDimitry Andric if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize()) 807e8d8bef9SDimitry Andric reportFatal(data.data(), "data is too short"); 8080b57cec5SDimitry Andric 8090b57cec5SDimitry Andric Elf_Note note(*nhdr); 8100b57cec5SDimitry Andric if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") { 8110b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8120b57cec5SDimitry Andric continue; 8130b57cec5SDimitry Andric } 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric uint32_t featureAndType = config->emachine == EM_AARCH64 8160b57cec5SDimitry Andric ? GNU_PROPERTY_AARCH64_FEATURE_1_AND 8170b57cec5SDimitry Andric : GNU_PROPERTY_X86_FEATURE_1_AND; 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric // Read a body of a NOTE record, which consists of type-length-value fields. 8200b57cec5SDimitry Andric ArrayRef<uint8_t> desc = note.getDesc(); 8210b57cec5SDimitry Andric while (!desc.empty()) { 822e8d8bef9SDimitry Andric const uint8_t *place = desc.data(); 8230b57cec5SDimitry Andric if (desc.size() < 8) 824e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 825e8d8bef9SDimitry Andric uint32_t type = read32<ELFT::TargetEndianness>(desc.data()); 826e8d8bef9SDimitry Andric uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4); 827e8d8bef9SDimitry Andric desc = desc.slice(8); 828e8d8bef9SDimitry Andric if (desc.size() < size) 829e8d8bef9SDimitry Andric reportFatal(place, "program property is too short"); 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric if (type == featureAndType) { 8320b57cec5SDimitry Andric // We found a FEATURE_1_AND field. There may be more than one of these 833480093f4SDimitry Andric // in a .note.gnu.property section, for a relocatable object we 8340b57cec5SDimitry Andric // accumulate the bits set. 835e8d8bef9SDimitry Andric if (size < 4) 836e8d8bef9SDimitry Andric reportFatal(place, "FEATURE_1_AND entry is too short"); 837e8d8bef9SDimitry Andric featuresSet |= read32<ELFT::TargetEndianness>(desc.data()); 8380b57cec5SDimitry Andric } 8390b57cec5SDimitry Andric 840e8d8bef9SDimitry Andric // Padding is present in the note descriptor, if necessary. 841e8d8bef9SDimitry Andric desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size)); 8420b57cec5SDimitry Andric } 8430b57cec5SDimitry Andric 8440b57cec5SDimitry Andric // Go to next NOTE record to look for more FEATURE_1_AND descriptions. 8450b57cec5SDimitry Andric data = data.slice(nhdr->getSize()); 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric return featuresSet; 8490b57cec5SDimitry Andric } 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric template <class ELFT> 8520b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) { 8530b57cec5SDimitry Andric uint32_t idx = sec.sh_info; 8540b57cec5SDimitry Andric if (idx >= this->sections.size()) 8550b57cec5SDimitry Andric fatal(toString(this) + ": invalid relocated section index: " + Twine(idx)); 8560b57cec5SDimitry Andric InputSectionBase *target = this->sections[idx]; 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric // Strictly speaking, a relocation section must be included in the 8590b57cec5SDimitry Andric // group of the section it relocates. However, LLVM 3.3 and earlier 8600b57cec5SDimitry Andric // would fail to do so, so we gracefully handle that case. 8610b57cec5SDimitry Andric if (target == &InputSection::discarded) 8620b57cec5SDimitry Andric return nullptr; 8630b57cec5SDimitry Andric 8640b57cec5SDimitry Andric if (!target) 8650b57cec5SDimitry Andric fatal(toString(this) + ": unsupported relocation reference"); 8660b57cec5SDimitry Andric return target; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric // Create a regular InputSection class that has the same contents 8700b57cec5SDimitry Andric // as a given section. 8710b57cec5SDimitry Andric static InputSection *toRegularSection(MergeInputSection *sec) { 8720b57cec5SDimitry Andric return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment, 8730b57cec5SDimitry Andric sec->data(), sec->name); 8740b57cec5SDimitry Andric } 8750b57cec5SDimitry Andric 8760b57cec5SDimitry Andric template <class ELFT> 8770b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) { 8780b57cec5SDimitry Andric StringRef name = getSectionName(sec); 8790b57cec5SDimitry Andric 880e8d8bef9SDimitry Andric if (config->emachine == EM_ARM && sec.sh_type == SHT_ARM_ATTRIBUTES) { 8810b57cec5SDimitry Andric ARMAttributeParser attributes; 882e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 8835ffd83dbSDimitry Andric if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind 8845ffd83dbSDimitry Andric ? support::little 8855ffd83dbSDimitry Andric : support::big)) { 8865ffd83dbSDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 8875ffd83dbSDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 888e8d8bef9SDimitry Andric } else { 8890b57cec5SDimitry Andric updateSupportedARMFeatures(attributes); 8900b57cec5SDimitry Andric updateARMVFPArgs(attributes, this); 8910b57cec5SDimitry Andric 8920b57cec5SDimitry Andric // FIXME: Retain the first attribute section we see. The eglibc ARM 8930b57cec5SDimitry Andric // dynamic loaders require the presence of an attribute section for dlopen 894e8d8bef9SDimitry Andric // to work. In a full implementation we would merge all attribute 895e8d8bef9SDimitry Andric // sections. 896e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 897e8d8bef9SDimitry Andric in.attributes = make<InputSection>(*this, sec, name); 898e8d8bef9SDimitry Andric return in.attributes; 8990b57cec5SDimitry Andric } 9000b57cec5SDimitry Andric return &InputSection::discarded; 9010b57cec5SDimitry Andric } 902e8d8bef9SDimitry Andric } 903e8d8bef9SDimitry Andric 904e8d8bef9SDimitry Andric if (config->emachine == EM_RISCV && sec.sh_type == SHT_RISCV_ATTRIBUTES) { 905e8d8bef9SDimitry Andric RISCVAttributeParser attributes; 906e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec)); 907e8d8bef9SDimitry Andric if (Error e = attributes.parse(contents, support::little)) { 908e8d8bef9SDimitry Andric auto *isec = make<InputSection>(*this, sec, name); 909e8d8bef9SDimitry Andric warn(toString(isec) + ": " + llvm::toString(std::move(e))); 910e8d8bef9SDimitry Andric } else { 911e8d8bef9SDimitry Andric // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is 912e8d8bef9SDimitry Andric // present. 913e8d8bef9SDimitry Andric 914e8d8bef9SDimitry Andric // FIXME: Retain the first attribute section we see. Tools such as 915e8d8bef9SDimitry Andric // llvm-objdump make use of the attribute section to determine which 916e8d8bef9SDimitry Andric // standard extensions to enable. In a full implementation we would merge 917e8d8bef9SDimitry Andric // all attribute sections. 918e8d8bef9SDimitry Andric if (in.attributes == nullptr) { 919e8d8bef9SDimitry Andric in.attributes = make<InputSection>(*this, sec, name); 920e8d8bef9SDimitry Andric return in.attributes; 921e8d8bef9SDimitry Andric } 922e8d8bef9SDimitry Andric return &InputSection::discarded; 923e8d8bef9SDimitry Andric } 924e8d8bef9SDimitry Andric } 925e8d8bef9SDimitry Andric 926e8d8bef9SDimitry Andric switch (sec.sh_type) { 9270b57cec5SDimitry Andric case SHT_LLVM_DEPENDENT_LIBRARIES: { 9280b57cec5SDimitry Andric if (config->relocatable) 9290b57cec5SDimitry Andric break; 9300b57cec5SDimitry Andric ArrayRef<char> data = 931e8d8bef9SDimitry Andric CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this); 9320b57cec5SDimitry Andric if (!data.empty() && data.back() != '\0') { 9330b57cec5SDimitry Andric error(toString(this) + 9340b57cec5SDimitry Andric ": corrupted dependent libraries section (unterminated string): " + 9350b57cec5SDimitry Andric name); 9360b57cec5SDimitry Andric return &InputSection::discarded; 9370b57cec5SDimitry Andric } 9380b57cec5SDimitry Andric for (const char *d = data.begin(), *e = data.end(); d < e;) { 9390b57cec5SDimitry Andric StringRef s(d); 9400b57cec5SDimitry Andric addDependentLibrary(s, this); 9410b57cec5SDimitry Andric d += s.size() + 1; 9420b57cec5SDimitry Andric } 9430b57cec5SDimitry Andric return &InputSection::discarded; 9440b57cec5SDimitry Andric } 9450b57cec5SDimitry Andric case SHT_RELA: 9460b57cec5SDimitry Andric case SHT_REL: { 9470b57cec5SDimitry Andric // Find a relocation target section and associate this section with that. 9480b57cec5SDimitry Andric // Target may have been discarded if it is in a different section group 9490b57cec5SDimitry Andric // and the group is discarded, even though it's a violation of the 9500b57cec5SDimitry Andric // spec. We handle that situation gracefully by discarding dangling 9510b57cec5SDimitry Andric // relocation sections. 9520b57cec5SDimitry Andric InputSectionBase *target = getRelocTarget(sec); 9530b57cec5SDimitry Andric if (!target) 9540b57cec5SDimitry Andric return nullptr; 9550b57cec5SDimitry Andric 956480093f4SDimitry Andric // ELF spec allows mergeable sections with relocations, but they are 957480093f4SDimitry Andric // rare, and it is in practice hard to merge such sections by contents, 958480093f4SDimitry Andric // because applying relocations at end of linking changes section 959480093f4SDimitry Andric // contents. So, we simply handle such sections as non-mergeable ones. 960480093f4SDimitry Andric // Degrading like this is acceptable because section merging is optional. 961480093f4SDimitry Andric if (auto *ms = dyn_cast<MergeInputSection>(target)) { 962480093f4SDimitry Andric target = toRegularSection(ms); 963480093f4SDimitry Andric this->sections[sec.sh_info] = target; 964480093f4SDimitry Andric } 965480093f4SDimitry Andric 9660b57cec5SDimitry Andric if (target->firstRelocation) 9670b57cec5SDimitry Andric fatal(toString(this) + 9680b57cec5SDimitry Andric ": multiple relocation sections to one section are not supported"); 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric if (sec.sh_type == SHT_RELA) { 971e8d8bef9SDimitry Andric ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(sec), this); 9720b57cec5SDimitry Andric target->firstRelocation = rels.begin(); 9730b57cec5SDimitry Andric target->numRelocations = rels.size(); 9740b57cec5SDimitry Andric target->areRelocsRela = true; 9750b57cec5SDimitry Andric } else { 976e8d8bef9SDimitry Andric ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(sec), this); 9770b57cec5SDimitry Andric target->firstRelocation = rels.begin(); 9780b57cec5SDimitry Andric target->numRelocations = rels.size(); 9790b57cec5SDimitry Andric target->areRelocsRela = false; 9800b57cec5SDimitry Andric } 9810b57cec5SDimitry Andric assert(isUInt<31>(target->numRelocations)); 9820b57cec5SDimitry Andric 983e8d8bef9SDimitry Andric // Relocation sections are usually removed from the output, so return 984e8d8bef9SDimitry Andric // `nullptr` for the normal case. However, if -r or --emit-relocs is 985e8d8bef9SDimitry Andric // specified, we need to copy them to the output. (Some post link analysis 986e8d8bef9SDimitry Andric // tools specify --emit-relocs to obtain the information.) 987e8d8bef9SDimitry Andric if (!config->relocatable && !config->emitRelocs) 988e8d8bef9SDimitry Andric return nullptr; 9890b57cec5SDimitry Andric InputSection *relocSec = make<InputSection>(*this, sec, name); 990e8d8bef9SDimitry Andric // If the relocated section is discarded (due to /DISCARD/ or 991e8d8bef9SDimitry Andric // --gc-sections), the relocation section should be discarded as well. 9920b57cec5SDimitry Andric target->dependentSections.push_back(relocSec); 9930b57cec5SDimitry Andric return relocSec; 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric } 9960b57cec5SDimitry Andric 9970b57cec5SDimitry Andric // The GNU linker uses .note.GNU-stack section as a marker indicating 9980b57cec5SDimitry Andric // that the code in the object file does not expect that the stack is 9990b57cec5SDimitry Andric // executable (in terms of NX bit). If all input files have the marker, 10000b57cec5SDimitry Andric // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 10010b57cec5SDimitry Andric // make the stack non-executable. Most object files have this section as 10020b57cec5SDimitry Andric // of 2017. 10030b57cec5SDimitry Andric // 10040b57cec5SDimitry Andric // But making the stack non-executable is a norm today for security 10050b57cec5SDimitry Andric // reasons. Failure to do so may result in a serious security issue. 10060b57cec5SDimitry Andric // Therefore, we make LLD always add PT_GNU_STACK unless it is 10070b57cec5SDimitry Andric // explicitly told to do otherwise (by -z execstack). Because the stack 10080b57cec5SDimitry Andric // executable-ness is controlled solely by command line options, 10090b57cec5SDimitry Andric // .note.GNU-stack sections are simply ignored. 10100b57cec5SDimitry Andric if (name == ".note.GNU-stack") 10110b57cec5SDimitry Andric return &InputSection::discarded; 10120b57cec5SDimitry Andric 10130b57cec5SDimitry Andric // Object files that use processor features such as Intel Control-Flow 10140b57cec5SDimitry Andric // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a 10150b57cec5SDimitry Andric // .note.gnu.property section containing a bitfield of feature bits like the 10160b57cec5SDimitry Andric // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag. 10170b57cec5SDimitry Andric // 10180b57cec5SDimitry Andric // Since we merge bitmaps from multiple object files to create a new 10190b57cec5SDimitry Andric // .note.gnu.property containing a single AND'ed bitmap, we discard an input 10200b57cec5SDimitry Andric // file's .note.gnu.property section. 10210b57cec5SDimitry Andric if (name == ".note.gnu.property") { 1022e8d8bef9SDimitry Andric this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name)); 10230b57cec5SDimitry Andric return &InputSection::discarded; 10240b57cec5SDimitry Andric } 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric // Split stacks is a feature to support a discontiguous stack, 10270b57cec5SDimitry Andric // commonly used in the programming language Go. For the details, 10280b57cec5SDimitry Andric // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled 10290b57cec5SDimitry Andric // for split stack will include a .note.GNU-split-stack section. 10300b57cec5SDimitry Andric if (name == ".note.GNU-split-stack") { 10310b57cec5SDimitry Andric if (config->relocatable) { 10320b57cec5SDimitry Andric error("cannot mix split-stack and non-split-stack in a relocatable link"); 10330b57cec5SDimitry Andric return &InputSection::discarded; 10340b57cec5SDimitry Andric } 10350b57cec5SDimitry Andric this->splitStack = true; 10360b57cec5SDimitry Andric return &InputSection::discarded; 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric 10390b57cec5SDimitry Andric // An object file cmpiled for split stack, but where some of the 10400b57cec5SDimitry Andric // functions were compiled with the no_split_stack_attribute will 10410b57cec5SDimitry Andric // include a .note.GNU-no-split-stack section. 10420b57cec5SDimitry Andric if (name == ".note.GNU-no-split-stack") { 10430b57cec5SDimitry Andric this->someNoSplitStack = true; 10440b57cec5SDimitry Andric return &InputSection::discarded; 10450b57cec5SDimitry Andric } 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 10480b57cec5SDimitry Andric // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 10490b57cec5SDimitry Andric // sections. Drop those sections to avoid duplicate symbol errors. 10500b57cec5SDimitry Andric // FIXME: This is glibc PR20543, we should remove this hack once that has been 10510b57cec5SDimitry Andric // fixed for a while. 10520b57cec5SDimitry Andric if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" || 10530b57cec5SDimitry Andric name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx") 10540b57cec5SDimitry Andric return &InputSection::discarded; 10550b57cec5SDimitry Andric 10560b57cec5SDimitry Andric // If we are creating a new .build-id section, strip existing .build-id 10570b57cec5SDimitry Andric // sections so that the output won't have more than one .build-id. 10580b57cec5SDimitry Andric // This is not usually a problem because input object files normally don't 10590b57cec5SDimitry Andric // have .build-id sections, but you can create such files by 10600b57cec5SDimitry Andric // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it. 10610b57cec5SDimitry Andric if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None) 10620b57cec5SDimitry Andric return &InputSection::discarded; 10630b57cec5SDimitry Andric 10640b57cec5SDimitry Andric // The linker merges EH (exception handling) frames and creates a 10650b57cec5SDimitry Andric // .eh_frame_hdr section for runtime. So we handle them with a special 10660b57cec5SDimitry Andric // class. For relocatable outputs, they are just passed through. 10670b57cec5SDimitry Andric if (name == ".eh_frame" && !config->relocatable) 10680b57cec5SDimitry Andric return make<EhInputSection>(*this, sec, name); 10690b57cec5SDimitry Andric 107085868e8aSDimitry Andric if (shouldMerge(sec, name)) 10710b57cec5SDimitry Andric return make<MergeInputSection>(*this, sec, name); 10720b57cec5SDimitry Andric return make<InputSection>(*this, sec, name); 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric template <class ELFT> 10760b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) { 1077e8d8bef9SDimitry Andric return CHECK(getObj().getSectionName(sec, sectionStringTable), this); 10780b57cec5SDimitry Andric } 10790b57cec5SDimitry Andric 10800b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as 10810b57cec5SDimitry Andric // its corresponding ELF symbol table. 10820b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 10830b57cec5SDimitry Andric ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 10840b57cec5SDimitry Andric this->symbols.resize(eSyms.size()); 10850b57cec5SDimitry Andric 10865ffd83dbSDimitry Andric // Fill in InputFile::symbols. Some entries have been initialized 10870b57cec5SDimitry Andric // because of LazyObjFile. 10880b57cec5SDimitry Andric for (size_t i = 0, end = eSyms.size(); i != end; ++i) { 10895ffd83dbSDimitry Andric if (this->symbols[i]) 10905ffd83dbSDimitry Andric continue; 10910b57cec5SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 10920b57cec5SDimitry Andric uint32_t secIdx = getSectionIndex(eSym); 10930b57cec5SDimitry Andric if (secIdx >= this->sections.size()) 10940b57cec5SDimitry Andric fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 10955ffd83dbSDimitry Andric if (eSym.getBinding() != STB_LOCAL) { 10965ffd83dbSDimitry Andric if (i < firstGlobal) 10975ffd83dbSDimitry Andric error(toString(this) + ": non-local symbol (" + Twine(i) + 10985ffd83dbSDimitry Andric ") found at index < .symtab's sh_info (" + Twine(firstGlobal) + 10995ffd83dbSDimitry Andric ")"); 11005ffd83dbSDimitry Andric this->symbols[i] = 11015ffd83dbSDimitry Andric symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this)); 11025ffd83dbSDimitry Andric continue; 11035ffd83dbSDimitry Andric } 11045ffd83dbSDimitry Andric 11055ffd83dbSDimitry Andric // Handle local symbols. Local symbols are not added to the symbol 11065ffd83dbSDimitry Andric // table because they are not visible from other object files. We 11075ffd83dbSDimitry Andric // allocate symbol instances and add their pointers to symbols. 11085ffd83dbSDimitry Andric if (i >= firstGlobal) 11095ffd83dbSDimitry Andric errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) + 11105ffd83dbSDimitry Andric ") found at index >= .symtab's sh_info (" + 11115ffd83dbSDimitry Andric Twine(firstGlobal) + ")"); 11120b57cec5SDimitry Andric 11130b57cec5SDimitry Andric InputSectionBase *sec = this->sections[secIdx]; 11145ffd83dbSDimitry Andric uint8_t type = eSym.getType(); 11155ffd83dbSDimitry Andric if (type == STT_FILE) 11165ffd83dbSDimitry Andric sourceFile = CHECK(eSym.getName(this->stringTable), this); 11175ffd83dbSDimitry Andric if (this->stringTable.size() <= eSym.st_name) 11185ffd83dbSDimitry Andric fatal(toString(this) + ": invalid symbol name offset"); 11195ffd83dbSDimitry Andric StringRefZ name = this->stringTable.data() + eSym.st_name; 11205ffd83dbSDimitry Andric 11215ffd83dbSDimitry Andric if (eSym.st_shndx == SHN_UNDEF) 11225ffd83dbSDimitry Andric this->symbols[i] = 11235ffd83dbSDimitry Andric make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type); 11245ffd83dbSDimitry Andric else if (sec == &InputSection::discarded) 11255ffd83dbSDimitry Andric this->symbols[i] = 11265ffd83dbSDimitry Andric make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type, 11275ffd83dbSDimitry Andric /*discardedSecIdx=*/secIdx); 11285ffd83dbSDimitry Andric else 11295ffd83dbSDimitry Andric this->symbols[i] = make<Defined>(this, name, STB_LOCAL, eSym.st_other, 11305ffd83dbSDimitry Andric type, eSym.st_value, eSym.st_size, sec); 11315ffd83dbSDimitry Andric } 11325ffd83dbSDimitry Andric 11335ffd83dbSDimitry Andric // Symbol resolution of non-local symbols. 1134*fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 11355ffd83dbSDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 11365ffd83dbSDimitry Andric const Elf_Sym &eSym = eSyms[i]; 11370b57cec5SDimitry Andric uint8_t binding = eSym.getBinding(); 11385ffd83dbSDimitry Andric if (binding == STB_LOCAL) 11395ffd83dbSDimitry Andric continue; // Errored above. 11405ffd83dbSDimitry Andric 11415ffd83dbSDimitry Andric uint32_t secIdx = getSectionIndex(eSym); 11425ffd83dbSDimitry Andric InputSectionBase *sec = this->sections[secIdx]; 11430b57cec5SDimitry Andric uint8_t stOther = eSym.st_other; 11440b57cec5SDimitry Andric uint8_t type = eSym.getType(); 11450b57cec5SDimitry Andric uint64_t value = eSym.st_value; 11460b57cec5SDimitry Andric uint64_t size = eSym.st_size; 11470b57cec5SDimitry Andric StringRefZ name = this->stringTable.data() + eSym.st_name; 11480b57cec5SDimitry Andric 11490b57cec5SDimitry Andric // Handle global undefined symbols. 11500b57cec5SDimitry Andric if (eSym.st_shndx == SHN_UNDEF) { 1151*fe6060f1SDimitry Andric undefineds.push_back(i); 11520b57cec5SDimitry Andric continue; 11530b57cec5SDimitry Andric } 11540b57cec5SDimitry Andric 11550b57cec5SDimitry Andric // Handle global common symbols. 11560b57cec5SDimitry Andric if (eSym.st_shndx == SHN_COMMON) { 11570b57cec5SDimitry Andric if (value == 0 || value >= UINT32_MAX) 11580b57cec5SDimitry Andric fatal(toString(this) + ": common symbol '" + StringRef(name.data) + 11590b57cec5SDimitry Andric "' has invalid alignment: " + Twine(value)); 11600b57cec5SDimitry Andric this->symbols[i]->resolve( 11610b57cec5SDimitry Andric CommonSymbol{this, name, binding, stOther, type, value, size}); 11620b57cec5SDimitry Andric continue; 11630b57cec5SDimitry Andric } 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric // If a defined symbol is in a discarded section, handle it as if it 11660b57cec5SDimitry Andric // were an undefined symbol. Such symbol doesn't comply with the 11670b57cec5SDimitry Andric // standard, but in practice, a .eh_frame often directly refer 11680b57cec5SDimitry Andric // COMDAT member sections, and if a comdat group is discarded, some 11690b57cec5SDimitry Andric // defined symbol in a .eh_frame becomes dangling symbols. 11700b57cec5SDimitry Andric if (sec == &InputSection::discarded) { 11715ffd83dbSDimitry Andric Undefined und{this, name, binding, stOther, type, secIdx}; 11725ffd83dbSDimitry Andric Symbol *sym = this->symbols[i]; 11735ffd83dbSDimitry Andric // !ArchiveFile::parsed or LazyObjFile::fetched means that the file 11745ffd83dbSDimitry Andric // containing this object has not finished processing, i.e. this symbol is 11755ffd83dbSDimitry Andric // a result of a lazy symbol fetch. We should demote the lazy symbol to an 11765ffd83dbSDimitry Andric // Undefined so that any relocations outside of the group to it will 11775ffd83dbSDimitry Andric // trigger a discarded section error. 11785ffd83dbSDimitry Andric if ((sym->symbolKind == Symbol::LazyArchiveKind && 11795ffd83dbSDimitry Andric !cast<ArchiveFile>(sym->file)->parsed) || 11805ffd83dbSDimitry Andric (sym->symbolKind == Symbol::LazyObjectKind && 11815ffd83dbSDimitry Andric cast<LazyObjFile>(sym->file)->fetched)) 11825ffd83dbSDimitry Andric sym->replace(und); 11835ffd83dbSDimitry Andric else 11845ffd83dbSDimitry Andric sym->resolve(und); 11850b57cec5SDimitry Andric continue; 11860b57cec5SDimitry Andric } 11870b57cec5SDimitry Andric 11880b57cec5SDimitry Andric // Handle global defined symbols. 11890b57cec5SDimitry Andric if (binding == STB_GLOBAL || binding == STB_WEAK || 11900b57cec5SDimitry Andric binding == STB_GNU_UNIQUE) { 11910b57cec5SDimitry Andric this->symbols[i]->resolve( 11920b57cec5SDimitry Andric Defined{this, name, binding, stOther, type, value, size, sec}); 11930b57cec5SDimitry Andric continue; 11940b57cec5SDimitry Andric } 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric fatal(toString(this) + ": unexpected binding: " + Twine((int)binding)); 11970b57cec5SDimitry Andric } 1198*fe6060f1SDimitry Andric 1199*fe6060f1SDimitry Andric // Undefined symbols (excluding those defined relative to non-prevailing 1200*fe6060f1SDimitry Andric // sections) can trigger recursive fetch. Process defined symbols first so 1201*fe6060f1SDimitry Andric // that the relative order between a defined symbol and an undefined symbol 1202*fe6060f1SDimitry Andric // does not change the symbol resolution behavior. In addition, a set of 1203*fe6060f1SDimitry Andric // interconnected symbols will all be resolved to the same file, instead of 1204*fe6060f1SDimitry Andric // being resolved to different files. 1205*fe6060f1SDimitry Andric for (unsigned i : undefineds) { 1206*fe6060f1SDimitry Andric const Elf_Sym &eSym = eSyms[i]; 1207*fe6060f1SDimitry Andric StringRefZ name = this->stringTable.data() + eSym.st_name; 1208*fe6060f1SDimitry Andric this->symbols[i]->resolve(Undefined{this, name, eSym.getBinding(), 1209*fe6060f1SDimitry Andric eSym.st_other, eSym.getType()}); 1210*fe6060f1SDimitry Andric this->symbols[i]->referenced = true; 1211*fe6060f1SDimitry Andric } 12120b57cec5SDimitry Andric } 12130b57cec5SDimitry Andric 12140b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file) 12150b57cec5SDimitry Andric : InputFile(ArchiveKind, file->getMemoryBufferRef()), 12160b57cec5SDimitry Andric file(std::move(file)) {} 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric void ArchiveFile::parse() { 12190b57cec5SDimitry Andric for (const Archive::Symbol &sym : file->symbols()) 12200b57cec5SDimitry Andric symtab->addSymbol(LazyArchive{*this, sym}); 12215ffd83dbSDimitry Andric 12225ffd83dbSDimitry Andric // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this 12235ffd83dbSDimitry Andric // archive has been processed. 12245ffd83dbSDimitry Andric parsed = true; 12250b57cec5SDimitry Andric } 12260b57cec5SDimitry Andric 12270b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol. 12280b57cec5SDimitry Andric void ArchiveFile::fetch(const Archive::Symbol &sym) { 12290b57cec5SDimitry Andric Archive::Child c = 12300b57cec5SDimitry Andric CHECK(sym.getMember(), toString(this) + 12310b57cec5SDimitry Andric ": could not get the member for symbol " + 12320b57cec5SDimitry Andric toELFString(sym)); 12330b57cec5SDimitry Andric 12340b57cec5SDimitry Andric if (!seen.insert(c.getChildOffset()).second) 12350b57cec5SDimitry Andric return; 12360b57cec5SDimitry Andric 12370b57cec5SDimitry Andric MemoryBufferRef mb = 12380b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 12390b57cec5SDimitry Andric toString(this) + 12400b57cec5SDimitry Andric ": could not get the buffer for the member defining symbol " + 12410b57cec5SDimitry Andric toELFString(sym)); 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric if (tar && c.getParent()->isThin()) 12440b57cec5SDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 12450b57cec5SDimitry Andric 12465ffd83dbSDimitry Andric InputFile *file = createObjectFile(mb, getName(), c.getChildOffset()); 12470b57cec5SDimitry Andric file->groupId = groupId; 12480b57cec5SDimitry Andric parseFile(file); 12490b57cec5SDimitry Andric } 12500b57cec5SDimitry Andric 1251e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky. 1252*fe6060f1SDimitry Andric // A tentative definition will be promoted to a global definition if there are 1253*fe6060f1SDimitry Andric // no non-tentative definitions to dominate it. When we hold a tentative 1254*fe6060f1SDimitry Andric // definition to a symbol and are inspecting archive members for inclusion 1255*fe6060f1SDimitry Andric // there are 2 ways we can proceed: 1256e8d8bef9SDimitry Andric // 1257e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from 1258e8d8bef9SDimitry Andric // tentative to real definition has already happened) and not inspect 1259e8d8bef9SDimitry Andric // archive members for Global/Weak definitions to replace the tentative 1260e8d8bef9SDimitry Andric // definition. An archive member would only be included if it satisfies some 1261e8d8bef9SDimitry Andric // other undefined symbol. This is the behavior Gold uses. 1262e8d8bef9SDimitry Andric // 1263e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to 1264*fe6060f1SDimitry Andric // a real definition happens only after all symbol resolution is done). 1265*fe6060f1SDimitry Andric // The linker searches archive members for STB_GLOBAL definitions to 1266e8d8bef9SDimitry Andric // replace the tentative definition with. This is the behavior used by 1267e8d8bef9SDimitry Andric // GNU ld. 1268e8d8bef9SDimitry Andric // 1269e8d8bef9SDimitry Andric // The second behavior is inherited from SysVR4, which based it on the FORTRAN 1270*fe6060f1SDimitry Andric // COMMON BLOCK model. This behavior is needed for proper initialization in old 1271e8d8bef9SDimitry Andric // (pre F90) FORTRAN code that is packaged into an archive. 1272e8d8bef9SDimitry Andric // 1273*fe6060f1SDimitry Andric // The following functions search archive members for definitions to replace 1274*fe6060f1SDimitry Andric // tentative definitions (implementing behavior 2). 1275e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName, 1276e8d8bef9SDimitry Andric StringRef archiveName) { 1277e8d8bef9SDimitry Andric IRSymtabFile symtabFile = check(readIRSymtab(mb)); 1278e8d8bef9SDimitry Andric for (const irsymtab::Reader::SymbolRef &sym : 1279e8d8bef9SDimitry Andric symtabFile.TheReader.symbols()) { 1280e8d8bef9SDimitry Andric if (sym.isGlobal() && sym.getName() == symName) 1281*fe6060f1SDimitry Andric return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon(); 1282e8d8bef9SDimitry Andric } 1283e8d8bef9SDimitry Andric return false; 1284e8d8bef9SDimitry Andric } 1285e8d8bef9SDimitry Andric 1286e8d8bef9SDimitry Andric template <class ELFT> 1287e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1288e8d8bef9SDimitry Andric StringRef archiveName) { 1289e8d8bef9SDimitry Andric ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName); 1290e8d8bef9SDimitry Andric StringRef stringtable = obj->getStringTable(); 1291e8d8bef9SDimitry Andric 1292e8d8bef9SDimitry Andric for (auto sym : obj->template getGlobalELFSyms<ELFT>()) { 1293e8d8bef9SDimitry Andric Expected<StringRef> name = sym.getName(stringtable); 1294e8d8bef9SDimitry Andric if (name && name.get() == symName) 1295*fe6060f1SDimitry Andric return sym.isDefined() && sym.getBinding() == STB_GLOBAL && 1296*fe6060f1SDimitry Andric !sym.isCommon(); 1297e8d8bef9SDimitry Andric } 1298e8d8bef9SDimitry Andric return false; 1299e8d8bef9SDimitry Andric } 1300e8d8bef9SDimitry Andric 1301e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1302e8d8bef9SDimitry Andric StringRef archiveName) { 1303e8d8bef9SDimitry Andric switch (getELFKind(mb, archiveName)) { 1304e8d8bef9SDimitry Andric case ELF32LEKind: 1305e8d8bef9SDimitry Andric return isNonCommonDef<ELF32LE>(mb, symName, archiveName); 1306e8d8bef9SDimitry Andric case ELF32BEKind: 1307e8d8bef9SDimitry Andric return isNonCommonDef<ELF32BE>(mb, symName, archiveName); 1308e8d8bef9SDimitry Andric case ELF64LEKind: 1309e8d8bef9SDimitry Andric return isNonCommonDef<ELF64LE>(mb, symName, archiveName); 1310e8d8bef9SDimitry Andric case ELF64BEKind: 1311e8d8bef9SDimitry Andric return isNonCommonDef<ELF64BE>(mb, symName, archiveName); 1312e8d8bef9SDimitry Andric default: 1313e8d8bef9SDimitry Andric llvm_unreachable("getELFKind"); 1314e8d8bef9SDimitry Andric } 1315e8d8bef9SDimitry Andric } 1316e8d8bef9SDimitry Andric 1317e8d8bef9SDimitry Andric bool ArchiveFile::shouldFetchForCommon(const Archive::Symbol &sym) { 1318e8d8bef9SDimitry Andric Archive::Child c = 1319e8d8bef9SDimitry Andric CHECK(sym.getMember(), toString(this) + 1320e8d8bef9SDimitry Andric ": could not get the member for symbol " + 1321e8d8bef9SDimitry Andric toELFString(sym)); 1322e8d8bef9SDimitry Andric MemoryBufferRef mb = 1323e8d8bef9SDimitry Andric CHECK(c.getMemoryBufferRef(), 1324e8d8bef9SDimitry Andric toString(this) + 1325e8d8bef9SDimitry Andric ": could not get the buffer for the member defining symbol " + 1326e8d8bef9SDimitry Andric toELFString(sym)); 1327e8d8bef9SDimitry Andric 1328e8d8bef9SDimitry Andric if (isBitcode(mb)) 1329e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, sym.getName(), getName()); 1330e8d8bef9SDimitry Andric 1331e8d8bef9SDimitry Andric return isNonCommonDef(mb, sym.getName(), getName()); 1332e8d8bef9SDimitry Andric } 1333e8d8bef9SDimitry Andric 13345ffd83dbSDimitry Andric size_t ArchiveFile::getMemberCount() const { 13355ffd83dbSDimitry Andric size_t count = 0; 13365ffd83dbSDimitry Andric Error err = Error::success(); 13375ffd83dbSDimitry Andric for (const Archive::Child &c : file->children(err)) { 13385ffd83dbSDimitry Andric (void)c; 13395ffd83dbSDimitry Andric ++count; 13405ffd83dbSDimitry Andric } 13415ffd83dbSDimitry Andric // This function is used by --print-archive-stats=, where an error does not 13425ffd83dbSDimitry Andric // really matter. 13435ffd83dbSDimitry Andric consumeError(std::move(err)); 13445ffd83dbSDimitry Andric return count; 13455ffd83dbSDimitry Andric } 13465ffd83dbSDimitry Andric 13470b57cec5SDimitry Andric unsigned SharedFile::vernauxNum; 13480b57cec5SDimitry Andric 13490b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a 13500b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version 13510b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr. 13520b57cec5SDimitry Andric template <typename ELFT> 13530b57cec5SDimitry Andric static std::vector<const void *> parseVerdefs(const uint8_t *base, 13540b57cec5SDimitry Andric const typename ELFT::Shdr *sec) { 13550b57cec5SDimitry Andric if (!sec) 13560b57cec5SDimitry Andric return {}; 13570b57cec5SDimitry Andric 13580b57cec5SDimitry Andric // We cannot determine the largest verdef identifier without inspecting 13590b57cec5SDimitry Andric // every Elf_Verdef, but both bfd and gold assign verdef identifiers 13600b57cec5SDimitry Andric // sequentially starting from 1, so we predict that the largest identifier 13610b57cec5SDimitry Andric // will be verdefCount. 13620b57cec5SDimitry Andric unsigned verdefCount = sec->sh_info; 13630b57cec5SDimitry Andric std::vector<const void *> verdefs(verdefCount + 1); 13640b57cec5SDimitry Andric 13650b57cec5SDimitry Andric // Build the Verdefs array by following the chain of Elf_Verdef objects 13660b57cec5SDimitry Andric // from the start of the .gnu.version_d section. 13670b57cec5SDimitry Andric const uint8_t *verdef = base + sec->sh_offset; 13680b57cec5SDimitry Andric for (unsigned i = 0; i != verdefCount; ++i) { 13690b57cec5SDimitry Andric auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef); 13700b57cec5SDimitry Andric verdef += curVerdef->vd_next; 13710b57cec5SDimitry Andric unsigned verdefIndex = curVerdef->vd_ndx; 13720b57cec5SDimitry Andric verdefs.resize(verdefIndex + 1); 13730b57cec5SDimitry Andric verdefs[verdefIndex] = curVerdef; 13740b57cec5SDimitry Andric } 13750b57cec5SDimitry Andric return verdefs; 13760b57cec5SDimitry Andric } 13770b57cec5SDimitry Andric 13785ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined 13795ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not 13805ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value 13815ffd83dbSDimitry Andric // of such diagnostics is low. 13825ffd83dbSDimitry Andric template <typename ELFT> 13835ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj, 13845ffd83dbSDimitry Andric const typename ELFT::Shdr *sec) { 13855ffd83dbSDimitry Andric if (!sec) 13865ffd83dbSDimitry Andric return {}; 13875ffd83dbSDimitry Andric std::vector<uint32_t> verneeds; 1388e8d8bef9SDimitry Andric ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this); 13895ffd83dbSDimitry Andric const uint8_t *verneedBuf = data.begin(); 13905ffd83dbSDimitry Andric for (unsigned i = 0; i != sec->sh_info; ++i) { 13915ffd83dbSDimitry Andric if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) 13925ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Verneed"); 13935ffd83dbSDimitry Andric auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf); 13945ffd83dbSDimitry Andric const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux; 13955ffd83dbSDimitry Andric for (unsigned j = 0; j != vn->vn_cnt; ++j) { 13965ffd83dbSDimitry Andric if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) 13975ffd83dbSDimitry Andric fatal(toString(this) + " has an invalid Vernaux"); 13985ffd83dbSDimitry Andric auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf); 13995ffd83dbSDimitry Andric if (aux->vna_name >= this->stringTable.size()) 14005ffd83dbSDimitry Andric fatal(toString(this) + " has a Vernaux with an invalid vna_name"); 14015ffd83dbSDimitry Andric uint16_t version = aux->vna_other & VERSYM_VERSION; 14025ffd83dbSDimitry Andric if (version >= verneeds.size()) 14035ffd83dbSDimitry Andric verneeds.resize(version + 1); 14045ffd83dbSDimitry Andric verneeds[version] = aux->vna_name; 14055ffd83dbSDimitry Andric vernauxBuf += aux->vna_next; 14065ffd83dbSDimitry Andric } 14075ffd83dbSDimitry Andric verneedBuf += vn->vn_next; 14085ffd83dbSDimitry Andric } 14095ffd83dbSDimitry Andric return verneeds; 14105ffd83dbSDimitry Andric } 14115ffd83dbSDimitry Andric 14120b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object 14130b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a 14140b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep 14150b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function. 14160b57cec5SDimitry Andric template <typename ELFT> 14170b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections, 14180b57cec5SDimitry Andric const typename ELFT::Sym &sym) { 14190b57cec5SDimitry Andric uint64_t ret = UINT64_MAX; 14200b57cec5SDimitry Andric if (sym.st_value) 14210b57cec5SDimitry Andric ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value); 14220b57cec5SDimitry Andric if (0 < sym.st_shndx && sym.st_shndx < sections.size()) 14230b57cec5SDimitry Andric ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign); 14240b57cec5SDimitry Andric return (ret > UINT32_MAX) ? 0 : ret; 14250b57cec5SDimitry Andric } 14260b57cec5SDimitry Andric 14270b57cec5SDimitry Andric // Fully parse the shared object file. 14280b57cec5SDimitry Andric // 14290b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information, 14300b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version 14310b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in 14320b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol 14330b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d". 14340b57cec5SDimitry Andric // 14350b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 14360b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in 14370b57cec5SDimitry Andric // ".gnu.version_d". 14380b57cec5SDimitry Andric // 14390b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated 14400b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your 14410b57cec5SDimitry Andric // head around the data structure described above. 14420b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() { 14430b57cec5SDimitry Andric using Elf_Dyn = typename ELFT::Dyn; 14440b57cec5SDimitry Andric using Elf_Shdr = typename ELFT::Shdr; 14450b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 14460b57cec5SDimitry Andric using Elf_Verdef = typename ELFT::Verdef; 14470b57cec5SDimitry Andric using Elf_Versym = typename ELFT::Versym; 14480b57cec5SDimitry Andric 14490b57cec5SDimitry Andric ArrayRef<Elf_Dyn> dynamicTags; 14500b57cec5SDimitry Andric const ELFFile<ELFT> obj = this->getObj<ELFT>(); 14510b57cec5SDimitry Andric ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this); 14520b57cec5SDimitry Andric 14530b57cec5SDimitry Andric const Elf_Shdr *versymSec = nullptr; 14540b57cec5SDimitry Andric const Elf_Shdr *verdefSec = nullptr; 14555ffd83dbSDimitry Andric const Elf_Shdr *verneedSec = nullptr; 14560b57cec5SDimitry Andric 14570b57cec5SDimitry Andric // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 14580b57cec5SDimitry Andric for (const Elf_Shdr &sec : sections) { 14590b57cec5SDimitry Andric switch (sec.sh_type) { 14600b57cec5SDimitry Andric default: 14610b57cec5SDimitry Andric continue; 14620b57cec5SDimitry Andric case SHT_DYNAMIC: 14630b57cec5SDimitry Andric dynamicTags = 1464e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this); 14650b57cec5SDimitry Andric break; 14660b57cec5SDimitry Andric case SHT_GNU_versym: 14670b57cec5SDimitry Andric versymSec = &sec; 14680b57cec5SDimitry Andric break; 14690b57cec5SDimitry Andric case SHT_GNU_verdef: 14700b57cec5SDimitry Andric verdefSec = &sec; 14710b57cec5SDimitry Andric break; 14725ffd83dbSDimitry Andric case SHT_GNU_verneed: 14735ffd83dbSDimitry Andric verneedSec = &sec; 14745ffd83dbSDimitry Andric break; 14750b57cec5SDimitry Andric } 14760b57cec5SDimitry Andric } 14770b57cec5SDimitry Andric 14780b57cec5SDimitry Andric if (versymSec && numELFSyms == 0) { 14790b57cec5SDimitry Andric error("SHT_GNU_versym should be associated with symbol table"); 14800b57cec5SDimitry Andric return; 14810b57cec5SDimitry Andric } 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric // Search for a DT_SONAME tag to initialize this->soName. 14840b57cec5SDimitry Andric for (const Elf_Dyn &dyn : dynamicTags) { 14850b57cec5SDimitry Andric if (dyn.d_tag == DT_NEEDED) { 14860b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14870b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14880b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_NEEDED entry"); 14890b57cec5SDimitry Andric dtNeeded.push_back(this->stringTable.data() + val); 14900b57cec5SDimitry Andric } else if (dyn.d_tag == DT_SONAME) { 14910b57cec5SDimitry Andric uint64_t val = dyn.getVal(); 14920b57cec5SDimitry Andric if (val >= this->stringTable.size()) 14930b57cec5SDimitry Andric fatal(toString(this) + ": invalid DT_SONAME entry"); 14940b57cec5SDimitry Andric soName = this->stringTable.data() + val; 14950b57cec5SDimitry Andric } 14960b57cec5SDimitry Andric } 14970b57cec5SDimitry Andric 14980b57cec5SDimitry Andric // DSOs are uniquified not by filename but by soname. 14990b57cec5SDimitry Andric DenseMap<StringRef, SharedFile *>::iterator it; 15000b57cec5SDimitry Andric bool wasInserted; 15010b57cec5SDimitry Andric std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this); 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric // If a DSO appears more than once on the command line with and without 15040b57cec5SDimitry Andric // --as-needed, --no-as-needed takes precedence over --as-needed because a 15050b57cec5SDimitry Andric // user can add an extra DSO with --no-as-needed to force it to be added to 15060b57cec5SDimitry Andric // the dependency list. 15070b57cec5SDimitry Andric it->second->isNeeded |= isNeeded; 15080b57cec5SDimitry Andric if (!wasInserted) 15090b57cec5SDimitry Andric return; 15100b57cec5SDimitry Andric 15110b57cec5SDimitry Andric sharedFiles.push_back(this); 15120b57cec5SDimitry Andric 15130b57cec5SDimitry Andric verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec); 15145ffd83dbSDimitry Andric std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec); 15150b57cec5SDimitry Andric 15160b57cec5SDimitry Andric // Parse ".gnu.version" section which is a parallel array for the symbol 15170b57cec5SDimitry Andric // table. If a given file doesn't have a ".gnu.version" section, we use 15180b57cec5SDimitry Andric // VER_NDX_GLOBAL. 15190b57cec5SDimitry Andric size_t size = numELFSyms - firstGlobal; 15205ffd83dbSDimitry Andric std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL); 15210b57cec5SDimitry Andric if (versymSec) { 15220b57cec5SDimitry Andric ArrayRef<Elf_Versym> versym = 1523e8d8bef9SDimitry Andric CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec), 15240b57cec5SDimitry Andric this) 15250b57cec5SDimitry Andric .slice(firstGlobal); 15260b57cec5SDimitry Andric for (size_t i = 0; i < size; ++i) 15270b57cec5SDimitry Andric versyms[i] = versym[i].vs_index; 15280b57cec5SDimitry Andric } 15290b57cec5SDimitry Andric 15300b57cec5SDimitry Andric // System libraries can have a lot of symbols with versions. Using a 15310b57cec5SDimitry Andric // fixed buffer for computing the versions name (foo@ver) can save a 15320b57cec5SDimitry Andric // lot of allocations. 15330b57cec5SDimitry Andric SmallString<0> versionedNameBuffer; 15340b57cec5SDimitry Andric 15350b57cec5SDimitry Andric // Add symbols to the symbol table. 15360b57cec5SDimitry Andric ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>(); 15370b57cec5SDimitry Andric for (size_t i = 0; i < syms.size(); ++i) { 15380b57cec5SDimitry Andric const Elf_Sym &sym = syms[i]; 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric // ELF spec requires that all local symbols precede weak or global 15410b57cec5SDimitry Andric // symbols in each symbol table, and the index of first non-local symbol 15420b57cec5SDimitry Andric // is stored to sh_info. If a local symbol appears after some non-local 15430b57cec5SDimitry Andric // symbol, that's a violation of the spec. 15440b57cec5SDimitry Andric StringRef name = CHECK(sym.getName(this->stringTable), this); 15450b57cec5SDimitry Andric if (sym.getBinding() == STB_LOCAL) { 15460b57cec5SDimitry Andric warn("found local symbol '" + name + 15470b57cec5SDimitry Andric "' in global part of symbol table in file " + toString(this)); 15480b57cec5SDimitry Andric continue; 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15515ffd83dbSDimitry Andric uint16_t idx = versyms[i] & ~VERSYM_HIDDEN; 15520b57cec5SDimitry Andric if (sym.isUndefined()) { 15535ffd83dbSDimitry Andric // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but 15545ffd83dbSDimitry Andric // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL. 15555ffd83dbSDimitry Andric if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) { 15565ffd83dbSDimitry Andric if (idx >= verneeds.size()) { 15575ffd83dbSDimitry Andric error("corrupt input file: version need index " + Twine(idx) + 15585ffd83dbSDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15595ffd83dbSDimitry Andric toString(this)); 15605ffd83dbSDimitry Andric continue; 15615ffd83dbSDimitry Andric } 15625ffd83dbSDimitry Andric StringRef verName = this->stringTable.data() + verneeds[idx]; 15635ffd83dbSDimitry Andric versionedNameBuffer.clear(); 15645ffd83dbSDimitry Andric name = 15655ffd83dbSDimitry Andric saver.save((name + "@" + verName).toStringRef(versionedNameBuffer)); 15665ffd83dbSDimitry Andric } 15670b57cec5SDimitry Andric Symbol *s = symtab->addSymbol( 15680b57cec5SDimitry Andric Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()}); 15690b57cec5SDimitry Andric s->exportDynamic = true; 1570*fe6060f1SDimitry Andric if (s->isUndefined() && !s->isWeak() && 1571*fe6060f1SDimitry Andric config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) 1572*fe6060f1SDimitry Andric requiredSymbols.push_back(s); 15730b57cec5SDimitry Andric continue; 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 15770b57cec5SDimitry Andric // assigns VER_NDX_LOCAL to this section global symbol. Here is a 15780b57cec5SDimitry Andric // workaround for this bug. 15790b57cec5SDimitry Andric if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL && 15800b57cec5SDimitry Andric name == "_gp_disp") 15810b57cec5SDimitry Andric continue; 15820b57cec5SDimitry Andric 15830b57cec5SDimitry Andric uint32_t alignment = getAlignment<ELFT>(sections, sym); 15840b57cec5SDimitry Andric if (!(versyms[i] & VERSYM_HIDDEN)) { 15850b57cec5SDimitry Andric symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(), 15860b57cec5SDimitry Andric sym.st_other, sym.getType(), sym.st_value, 15870b57cec5SDimitry Andric sym.st_size, alignment, idx}); 15880b57cec5SDimitry Andric } 15890b57cec5SDimitry Andric 15900b57cec5SDimitry Andric // Also add the symbol with the versioned name to handle undefined symbols 15910b57cec5SDimitry Andric // with explicit versions. 15920b57cec5SDimitry Andric if (idx == VER_NDX_GLOBAL) 15930b57cec5SDimitry Andric continue; 15940b57cec5SDimitry Andric 15950b57cec5SDimitry Andric if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) { 15960b57cec5SDimitry Andric error("corrupt input file: version definition index " + Twine(idx) + 15970b57cec5SDimitry Andric " for symbol " + name + " is out of bounds\n>>> defined in " + 15980b57cec5SDimitry Andric toString(this)); 15990b57cec5SDimitry Andric continue; 16000b57cec5SDimitry Andric } 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric StringRef verName = 16030b57cec5SDimitry Andric this->stringTable.data() + 16040b57cec5SDimitry Andric reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name; 16050b57cec5SDimitry Andric versionedNameBuffer.clear(); 16060b57cec5SDimitry Andric name = (name + "@" + verName).toStringRef(versionedNameBuffer); 16070b57cec5SDimitry Andric symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(), 16080b57cec5SDimitry Andric sym.st_other, sym.getType(), sym.st_value, 16090b57cec5SDimitry Andric sym.st_size, alignment, idx}); 16100b57cec5SDimitry Andric } 16110b57cec5SDimitry Andric } 16120b57cec5SDimitry Andric 16130b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) { 16140b57cec5SDimitry Andric if (t.isLittleEndian()) 16150b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 16160b57cec5SDimitry Andric return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 16170b57cec5SDimitry Andric } 16180b57cec5SDimitry Andric 1619e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) { 16200b57cec5SDimitry Andric switch (t.getArch()) { 16210b57cec5SDimitry Andric case Triple::aarch64: 1622*fe6060f1SDimitry Andric case Triple::aarch64_be: 16230b57cec5SDimitry Andric return EM_AARCH64; 16240b57cec5SDimitry Andric case Triple::amdgcn: 16250b57cec5SDimitry Andric case Triple::r600: 16260b57cec5SDimitry Andric return EM_AMDGPU; 16270b57cec5SDimitry Andric case Triple::arm: 16280b57cec5SDimitry Andric case Triple::thumb: 16290b57cec5SDimitry Andric return EM_ARM; 16300b57cec5SDimitry Andric case Triple::avr: 16310b57cec5SDimitry Andric return EM_AVR; 16320b57cec5SDimitry Andric case Triple::mips: 16330b57cec5SDimitry Andric case Triple::mipsel: 16340b57cec5SDimitry Andric case Triple::mips64: 16350b57cec5SDimitry Andric case Triple::mips64el: 16360b57cec5SDimitry Andric return EM_MIPS; 16370b57cec5SDimitry Andric case Triple::msp430: 16380b57cec5SDimitry Andric return EM_MSP430; 16390b57cec5SDimitry Andric case Triple::ppc: 1640e8d8bef9SDimitry Andric case Triple::ppcle: 16410b57cec5SDimitry Andric return EM_PPC; 16420b57cec5SDimitry Andric case Triple::ppc64: 16430b57cec5SDimitry Andric case Triple::ppc64le: 16440b57cec5SDimitry Andric return EM_PPC64; 16450b57cec5SDimitry Andric case Triple::riscv32: 16460b57cec5SDimitry Andric case Triple::riscv64: 16470b57cec5SDimitry Andric return EM_RISCV; 16480b57cec5SDimitry Andric case Triple::x86: 16490b57cec5SDimitry Andric return t.isOSIAMCU() ? EM_IAMCU : EM_386; 16500b57cec5SDimitry Andric case Triple::x86_64: 16510b57cec5SDimitry Andric return EM_X86_64; 16520b57cec5SDimitry Andric default: 16530b57cec5SDimitry Andric error(path + ": could not infer e_machine from bitcode target triple " + 16540b57cec5SDimitry Andric t.str()); 16550b57cec5SDimitry Andric return EM_NONE; 16560b57cec5SDimitry Andric } 16570b57cec5SDimitry Andric } 16580b57cec5SDimitry Andric 1659e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) { 1660e8d8bef9SDimitry Andric switch (t.getOS()) { 1661e8d8bef9SDimitry Andric case Triple::AMDHSA: 1662e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_HSA; 1663e8d8bef9SDimitry Andric case Triple::AMDPAL: 1664e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_PAL; 1665e8d8bef9SDimitry Andric case Triple::Mesa3D: 1666e8d8bef9SDimitry Andric return ELF::ELFOSABI_AMDGPU_MESA3D; 1667e8d8bef9SDimitry Andric default: 1668e8d8bef9SDimitry Andric return ELF::ELFOSABI_NONE; 1669e8d8bef9SDimitry Andric } 1670e8d8bef9SDimitry Andric } 1671e8d8bef9SDimitry Andric 16720b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 16730b57cec5SDimitry Andric uint64_t offsetInArchive) 16740b57cec5SDimitry Andric : InputFile(BitcodeKind, mb) { 16755ffd83dbSDimitry Andric this->archiveName = std::string(archiveName); 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 16780b57cec5SDimitry Andric if (config->thinLTOIndexOnly) 16790b57cec5SDimitry Andric path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 16820b57cec5SDimitry Andric // name. If two archives define two members with the same name, this 16830b57cec5SDimitry Andric // causes a collision which result in only one of the objects being taken 16840b57cec5SDimitry Andric // into consideration at LTO time (which very likely causes undefined 16850b57cec5SDimitry Andric // symbols later in the link stage). So we append file offset to make 16860b57cec5SDimitry Andric // filename unique. 16875ffd83dbSDimitry Andric StringRef name = 16885ffd83dbSDimitry Andric archiveName.empty() 16890b57cec5SDimitry Andric ? saver.save(path) 16905ffd83dbSDimitry Andric : saver.save(archiveName + "(" + path::filename(path) + " at " + 16910b57cec5SDimitry Andric utostr(offsetInArchive) + ")"); 16920b57cec5SDimitry Andric MemoryBufferRef mbref(mb.getBuffer(), name); 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric obj = CHECK(lto::InputFile::create(mbref), this); 16950b57cec5SDimitry Andric 16960b57cec5SDimitry Andric Triple t(obj->getTargetTriple()); 16970b57cec5SDimitry Andric ekind = getBitcodeELFKind(t); 16980b57cec5SDimitry Andric emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t); 1699e8d8bef9SDimitry Andric osabi = getOsAbi(t); 17000b57cec5SDimitry Andric } 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 17030b57cec5SDimitry Andric switch (gvVisibility) { 17040b57cec5SDimitry Andric case GlobalValue::DefaultVisibility: 17050b57cec5SDimitry Andric return STV_DEFAULT; 17060b57cec5SDimitry Andric case GlobalValue::HiddenVisibility: 17070b57cec5SDimitry Andric return STV_HIDDEN; 17080b57cec5SDimitry Andric case GlobalValue::ProtectedVisibility: 17090b57cec5SDimitry Andric return STV_PROTECTED; 17100b57cec5SDimitry Andric } 17110b57cec5SDimitry Andric llvm_unreachable("unknown visibility"); 17120b57cec5SDimitry Andric } 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric template <class ELFT> 17150b57cec5SDimitry Andric static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats, 17160b57cec5SDimitry Andric const lto::InputFile::Symbol &objSym, 17170b57cec5SDimitry Andric BitcodeFile &f) { 17180b57cec5SDimitry Andric StringRef name = saver.save(objSym.getName()); 17190b57cec5SDimitry Andric uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL; 17200b57cec5SDimitry Andric uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE; 17210b57cec5SDimitry Andric uint8_t visibility = mapVisibility(objSym.getVisibility()); 17220b57cec5SDimitry Andric bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable(); 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric int c = objSym.getComdatIndex(); 17250b57cec5SDimitry Andric if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) { 172685868e8aSDimitry Andric Undefined newSym(&f, name, binding, visibility, type); 17270b57cec5SDimitry Andric if (canOmitFromDynSym) 172885868e8aSDimitry Andric newSym.exportDynamic = false; 172985868e8aSDimitry Andric Symbol *ret = symtab->addSymbol(newSym); 173085868e8aSDimitry Andric ret->referenced = true; 173185868e8aSDimitry Andric return ret; 17320b57cec5SDimitry Andric } 17330b57cec5SDimitry Andric 17340b57cec5SDimitry Andric if (objSym.isCommon()) 17350b57cec5SDimitry Andric return symtab->addSymbol( 17360b57cec5SDimitry Andric CommonSymbol{&f, name, binding, visibility, STT_OBJECT, 17370b57cec5SDimitry Andric objSym.getCommonAlignment(), objSym.getCommonSize()}); 17380b57cec5SDimitry Andric 173985868e8aSDimitry Andric Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr); 17400b57cec5SDimitry Andric if (canOmitFromDynSym) 174185868e8aSDimitry Andric newSym.exportDynamic = false; 174285868e8aSDimitry Andric return symtab->addSymbol(newSym); 17430b57cec5SDimitry Andric } 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() { 17460b57cec5SDimitry Andric std::vector<bool> keptComdats; 1747*fe6060f1SDimitry Andric for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) { 17480b57cec5SDimitry Andric keptComdats.push_back( 1749*fe6060f1SDimitry Andric s.second == Comdat::NoDeduplicate || 1750*fe6060f1SDimitry Andric symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this) 1751*fe6060f1SDimitry Andric .second); 1752*fe6060f1SDimitry Andric } 17530b57cec5SDimitry Andric 17540b57cec5SDimitry Andric for (const lto::InputFile::Symbol &objSym : obj->symbols()) 17550b57cec5SDimitry Andric symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this)); 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric for (auto l : obj->getDependentLibraries()) 17580b57cec5SDimitry Andric addDependentLibrary(l, this); 17590b57cec5SDimitry Andric } 17600b57cec5SDimitry Andric 17610b57cec5SDimitry Andric void BinaryFile::parse() { 17620b57cec5SDimitry Andric ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer()); 17630b57cec5SDimitry Andric auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 17640b57cec5SDimitry Andric 8, data, ".data"); 17650b57cec5SDimitry Andric sections.push_back(section); 17660b57cec5SDimitry Andric 17670b57cec5SDimitry Andric // For each input file foo that is embedded to a result as a binary 17680b57cec5SDimitry Andric // blob, we define _binary_foo_{start,end,size} symbols, so that 17690b57cec5SDimitry Andric // user programs can access blobs by name. Non-alphanumeric 17700b57cec5SDimitry Andric // characters in a filename are replaced with underscore. 17710b57cec5SDimitry Andric std::string s = "_binary_" + mb.getBufferIdentifier().str(); 17720b57cec5SDimitry Andric for (size_t i = 0; i < s.size(); ++i) 17730b57cec5SDimitry Andric if (!isAlnum(s[i])) 17740b57cec5SDimitry Andric s[i] = '_'; 17750b57cec5SDimitry Andric 17760b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL, 17770b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, 0, 0, section}); 17780b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL, 17790b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, section}); 17800b57cec5SDimitry Andric symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL, 17810b57cec5SDimitry Andric STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr}); 17820b57cec5SDimitry Andric } 17830b57cec5SDimitry Andric 17845ffd83dbSDimitry Andric InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName, 17850b57cec5SDimitry Andric uint64_t offsetInArchive) { 17860b57cec5SDimitry Andric if (isBitcode(mb)) 17870b57cec5SDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive); 17880b57cec5SDimitry Andric 17890b57cec5SDimitry Andric switch (getELFKind(mb, archiveName)) { 17900b57cec5SDimitry Andric case ELF32LEKind: 17910b57cec5SDimitry Andric return make<ObjFile<ELF32LE>>(mb, archiveName); 17920b57cec5SDimitry Andric case ELF32BEKind: 17930b57cec5SDimitry Andric return make<ObjFile<ELF32BE>>(mb, archiveName); 17940b57cec5SDimitry Andric case ELF64LEKind: 17950b57cec5SDimitry Andric return make<ObjFile<ELF64LE>>(mb, archiveName); 17960b57cec5SDimitry Andric case ELF64BEKind: 17970b57cec5SDimitry Andric return make<ObjFile<ELF64BE>>(mb, archiveName); 17980b57cec5SDimitry Andric default: 17990b57cec5SDimitry Andric llvm_unreachable("getELFKind"); 18000b57cec5SDimitry Andric } 18010b57cec5SDimitry Andric } 18020b57cec5SDimitry Andric 18030b57cec5SDimitry Andric void LazyObjFile::fetch() { 18045ffd83dbSDimitry Andric if (fetched) 18050b57cec5SDimitry Andric return; 18065ffd83dbSDimitry Andric fetched = true; 18070b57cec5SDimitry Andric 18080b57cec5SDimitry Andric InputFile *file = createObjectFile(mb, archiveName, offsetInArchive); 18090b57cec5SDimitry Andric file->groupId = groupId; 18100b57cec5SDimitry Andric 18110b57cec5SDimitry Andric // Copy symbol vector so that the new InputFile doesn't have to 18120b57cec5SDimitry Andric // insert the same defined symbols to the symbol table again. 18130b57cec5SDimitry Andric file->symbols = std::move(symbols); 18140b57cec5SDimitry Andric 18150b57cec5SDimitry Andric parseFile(file); 18160b57cec5SDimitry Andric } 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric template <class ELFT> void LazyObjFile::parse() { 18190b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 18200b57cec5SDimitry Andric 18210b57cec5SDimitry Andric // A lazy object file wraps either a bitcode file or an ELF file. 18220b57cec5SDimitry Andric if (isBitcode(this->mb)) { 18230b57cec5SDimitry Andric std::unique_ptr<lto::InputFile> obj = 18240b57cec5SDimitry Andric CHECK(lto::InputFile::create(this->mb), this); 18250b57cec5SDimitry Andric for (const lto::InputFile::Symbol &sym : obj->symbols()) { 18260b57cec5SDimitry Andric if (sym.isUndefined()) 18270b57cec5SDimitry Andric continue; 18280b57cec5SDimitry Andric symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())}); 18290b57cec5SDimitry Andric } 18300b57cec5SDimitry Andric return; 18310b57cec5SDimitry Andric } 18320b57cec5SDimitry Andric 18330b57cec5SDimitry Andric if (getELFKind(this->mb, archiveName) != config->ekind) { 18340b57cec5SDimitry Andric error("incompatible file: " + this->mb.getBufferIdentifier()); 18350b57cec5SDimitry Andric return; 18360b57cec5SDimitry Andric } 18370b57cec5SDimitry Andric 18380b57cec5SDimitry Andric // Find a symbol table. 18390b57cec5SDimitry Andric ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer())); 18400b57cec5SDimitry Andric ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this); 18410b57cec5SDimitry Andric 18420b57cec5SDimitry Andric for (const typename ELFT::Shdr &sec : sections) { 18430b57cec5SDimitry Andric if (sec.sh_type != SHT_SYMTAB) 18440b57cec5SDimitry Andric continue; 18450b57cec5SDimitry Andric 18460b57cec5SDimitry Andric // A symbol table is found. 18470b57cec5SDimitry Andric ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this); 18480b57cec5SDimitry Andric uint32_t firstGlobal = sec.sh_info; 18490b57cec5SDimitry Andric StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this); 18500b57cec5SDimitry Andric this->symbols.resize(eSyms.size()); 18510b57cec5SDimitry Andric 18520b57cec5SDimitry Andric // Get existing symbols or insert placeholder symbols. 18530b57cec5SDimitry Andric for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 18540b57cec5SDimitry Andric if (eSyms[i].st_shndx != SHN_UNDEF) 18550b57cec5SDimitry Andric this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this)); 18560b57cec5SDimitry Andric 18570b57cec5SDimitry Andric // Replace existing symbols with LazyObject symbols. 18580b57cec5SDimitry Andric // 18590b57cec5SDimitry Andric // resolve() may trigger this->fetch() if an existing symbol is an 18600b57cec5SDimitry Andric // undefined symbol. If that happens, this LazyObjFile has served 18610b57cec5SDimitry Andric // its purpose, and we can exit from the loop early. 18620b57cec5SDimitry Andric for (Symbol *sym : this->symbols) { 18630b57cec5SDimitry Andric if (!sym) 18640b57cec5SDimitry Andric continue; 18650b57cec5SDimitry Andric sym->resolve(LazyObject{*this, sym->getName()}); 18660b57cec5SDimitry Andric 18675ffd83dbSDimitry Andric // If fetched, stop iterating because this->symbols has been transferred 18685ffd83dbSDimitry Andric // to the instantiated ObjFile. 18695ffd83dbSDimitry Andric if (fetched) 18700b57cec5SDimitry Andric return; 18710b57cec5SDimitry Andric } 18720b57cec5SDimitry Andric return; 18730b57cec5SDimitry Andric } 18740b57cec5SDimitry Andric } 18750b57cec5SDimitry Andric 1876e8d8bef9SDimitry Andric bool LazyObjFile::shouldFetchForCommon(const StringRef &name) { 1877e8d8bef9SDimitry Andric if (isBitcode(mb)) 1878e8d8bef9SDimitry Andric return isBitcodeNonCommonDef(mb, name, archiveName); 1879e8d8bef9SDimitry Andric 1880e8d8bef9SDimitry Andric return isNonCommonDef(mb, name, archiveName); 1881e8d8bef9SDimitry Andric } 1882e8d8bef9SDimitry Andric 18835ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) { 18840b57cec5SDimitry Andric StringRef suffix = config->thinLTOObjectSuffixReplace.first; 18850b57cec5SDimitry Andric StringRef repl = config->thinLTOObjectSuffixReplace.second; 18860b57cec5SDimitry Andric 18870b57cec5SDimitry Andric if (path.consume_back(suffix)) 18880b57cec5SDimitry Andric return (path + repl).str(); 18895ffd83dbSDimitry Andric return std::string(path); 18900b57cec5SDimitry Andric } 18910b57cec5SDimitry Andric 18920b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>(); 18930b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>(); 18940b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>(); 18950b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>(); 18960b57cec5SDimitry Andric 18970b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32LE>(); 18980b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32BE>(); 18990b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64LE>(); 19000b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64BE>(); 19010b57cec5SDimitry Andric 19025ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>; 19035ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>; 19045ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>; 19055ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>; 19060b57cec5SDimitry Andric 19070b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>(); 19080b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>(); 19090b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>(); 19100b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>(); 1911